detect-unsafe-regex.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. var safe = require('safe-regex');
  2. /**
  3. * Check if the regex is evil or not using the safe-regex module
  4. * @author Adam Baldwin
  5. */
  6. //------------------------------------------------------------------------------
  7. // Rule Definition
  8. //------------------------------------------------------------------------------
  9. module.exports = function(context) {
  10. "use strict";
  11. return {
  12. "Literal": function(node) {
  13. var token = context.getTokens(node)[0],
  14. nodeType = token.type,
  15. nodeValue = token.value;
  16. if (nodeType === "RegularExpression") {
  17. if (!safe(nodeValue)) {
  18. context.report(node, "Unsafe Regular Expression");
  19. }
  20. }
  21. },
  22. "NewExpression": function(node) {
  23. if (node.callee.name == "RegExp" && node.arguments && node.arguments.length > 0 && node.arguments[0].type == "Literal") {
  24. if (!safe(node.arguments[0].value)) {
  25. context.report(node, "Unsafe Regular Expression (new RegExp)");
  26. }
  27. }
  28. }
  29. };
  30. };