no-danger.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. /**
  2. * @fileoverview Prevent usage of dangerous JSX props
  3. * @author Scott Andrews
  4. */
  5. 'use strict';
  6. const docsUrl = require('../util/docsUrl');
  7. const jsxUtil = require('../util/jsx');
  8. // ------------------------------------------------------------------------------
  9. // Constants
  10. // ------------------------------------------------------------------------------
  11. const DANGEROUS_PROPERTY_NAMES = [
  12. 'dangerouslySetInnerHTML'
  13. ];
  14. const DANGEROUS_PROPERTIES = DANGEROUS_PROPERTY_NAMES.reduce((props, prop) => {
  15. props[prop] = prop;
  16. return props;
  17. }, Object.create(null));
  18. // ------------------------------------------------------------------------------
  19. // Helpers
  20. // ------------------------------------------------------------------------------
  21. /**
  22. * Checks if a JSX attribute is dangerous.
  23. * @param {String} name - Name of the attribute to check.
  24. * @returns {boolean} Whether or not the attribute is dnagerous.
  25. */
  26. function isDangerous(name) {
  27. return name in DANGEROUS_PROPERTIES;
  28. }
  29. // ------------------------------------------------------------------------------
  30. // Rule Definition
  31. // ------------------------------------------------------------------------------
  32. module.exports = {
  33. meta: {
  34. docs: {
  35. description: 'Prevent usage of dangerous JSX props',
  36. category: 'Best Practices',
  37. recommended: false,
  38. url: docsUrl('no-danger')
  39. },
  40. messages: {
  41. dangerousProp: 'Dangerous property \'{{name}}\' found'
  42. },
  43. schema: []
  44. },
  45. create(context) {
  46. return {
  47. JSXAttribute(node) {
  48. if (jsxUtil.isDOMComponent(node.parent) && isDangerous(node.name.name)) {
  49. context.report({
  50. node,
  51. messageId: 'dangerousProp',
  52. data: {
  53. name: node.name.name
  54. }
  55. });
  56. }
  57. }
  58. };
  59. }
  60. };