no-script-url.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /**
  2. * @fileoverview Rule to disallow `javascript:` URLs
  3. * @author Ilya Volodin
  4. */
  5. /* eslint no-script-url: 0 -- Code is checking to report such URLs */
  6. "use strict";
  7. const astUtils = require("./utils/ast-utils");
  8. //------------------------------------------------------------------------------
  9. // Rule Definition
  10. //------------------------------------------------------------------------------
  11. /** @type {import('../types').Rule.RuleModule} */
  12. module.exports = {
  13. meta: {
  14. type: "suggestion",
  15. docs: {
  16. description: "Disallow `javascript:` URLs",
  17. recommended: false,
  18. url: "https://eslint.org/docs/latest/rules/no-script-url",
  19. },
  20. schema: [],
  21. messages: {
  22. unexpectedScriptURL: "Script URL is a form of eval.",
  23. },
  24. },
  25. create(context) {
  26. /**
  27. * Check whether a node's static value starts with `javascript:` or not.
  28. * And report an error for unexpected script URL.
  29. * @param {ASTNode} node node to check
  30. * @returns {void}
  31. */
  32. function check(node) {
  33. const value = astUtils.getStaticStringValue(node);
  34. if (
  35. typeof value === "string" &&
  36. value.toLowerCase().indexOf("javascript:") === 0
  37. ) {
  38. context.report({ node, messageId: "unexpectedScriptURL" });
  39. }
  40. }
  41. return {
  42. Literal(node) {
  43. if (node.value && typeof node.value === "string") {
  44. check(node);
  45. }
  46. },
  47. TemplateLiteral(node) {
  48. if (
  49. !(
  50. node.parent &&
  51. node.parent.type === "TaggedTemplateExpression"
  52. )
  53. ) {
  54. check(node);
  55. }
  56. },
  57. };
  58. },
  59. };