no-danger.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. /**
  2. * @fileoverview Prevent usage of dangerous JSX props
  3. * @author Scott Andrews
  4. */
  5. 'use strict';
  6. const has = require('object.hasown/polyfill')();
  7. const fromEntries = require('object.fromentries/polyfill')();
  8. const docsUrl = require('../util/docsUrl');
  9. const jsxUtil = require('../util/jsx');
  10. const report = require('../util/report');
  11. // ------------------------------------------------------------------------------
  12. // Constants
  13. // ------------------------------------------------------------------------------
  14. const DANGEROUS_PROPERTY_NAMES = [
  15. 'dangerouslySetInnerHTML',
  16. ];
  17. const DANGEROUS_PROPERTIES = fromEntries(DANGEROUS_PROPERTY_NAMES.map((prop) => [prop, prop]));
  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 dangerous.
  25. */
  26. function isDangerous(name) {
  27. return has(DANGEROUS_PROPERTIES, name);
  28. }
  29. // ------------------------------------------------------------------------------
  30. // Rule Definition
  31. // ------------------------------------------------------------------------------
  32. const messages = {
  33. dangerousProp: 'Dangerous property \'{{name}}\' found',
  34. };
  35. module.exports = {
  36. meta: {
  37. docs: {
  38. description: 'Disallow usage of dangerous JSX properties',
  39. category: 'Best Practices',
  40. recommended: false,
  41. url: docsUrl('no-danger'),
  42. },
  43. messages,
  44. schema: [],
  45. },
  46. create(context) {
  47. return {
  48. JSXAttribute(node) {
  49. if (jsxUtil.isDOMComponent(node.parent) && isDangerous(node.name.name)) {
  50. report(context, messages.dangerousProp, 'dangerousProp', {
  51. node,
  52. data: {
  53. name: node.name.name,
  54. },
  55. });
  56. }
  57. },
  58. };
  59. },
  60. };