index.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. const analyzer = require('./lib/analyzer');
  2. const analyzerFamily = require('./lib/analyzer-family');
  3. const DEFAULT_SAFE_REP_LIMIT = 25;
  4. const RET_IS_SAFE = true;
  5. const RET_IS_VULNERABLE = false;
  6. class Args {
  7. constructor(regExp, analyzerOptions) {
  8. this.regExp = regExp;
  9. this.analyzerOptions = analyzerOptions;
  10. }
  11. }
  12. function safeRegex(re, opts) {
  13. try {
  14. const args = buildArgs(re, opts);
  15. const analyzerResponses = askAnalyzersIfVulnerable(args);
  16. // Did any analyzer say true?
  17. if (analyzerResponses.find((isVulnerable) => isVulnerable)) {
  18. return RET_IS_VULNERABLE;
  19. } else {
  20. return RET_IS_SAFE;
  21. }
  22. } catch (err) {
  23. // Invalid or unparseable input
  24. return false;
  25. }
  26. }
  27. function buildArgs(re, opts) {
  28. // Build AnalyzerOptions
  29. if (!opts) opts = {};
  30. const heuristic_replimit = opts.limit === undefined ? DEFAULT_SAFE_REP_LIMIT : opts.limit;
  31. const analyzerOptions = new analyzer.AnalyzerOptions(heuristic_replimit);
  32. // Build RegExp
  33. let regExp = null;
  34. // Construct a RegExp object
  35. if (re instanceof RegExp) {
  36. regExp = re;
  37. } else if (typeof re === 'string') {
  38. regExp = new RegExp(re);
  39. } else {
  40. regExp = new RegExp(String(re));
  41. }
  42. return new Args(regExp, analyzerOptions);
  43. }
  44. function askAnalyzersIfVulnerable(args) {
  45. let analyzerSaysVulnerable = [];
  46. // Query the Analyzers
  47. let Analyzer;
  48. for (Analyzer of analyzerFamily) {
  49. try {
  50. const analyzer = new Analyzer(args.analyzerOptions);
  51. analyzerSaysVulnerable.push(analyzer.isVulnerable(args.regExp));
  52. } catch (err) {
  53. /* istanbul ignore next */ // No need to worry about code coverage here.
  54. analyzerSaysVulnerable.push(false);
  55. }
  56. }
  57. return analyzerSaysVulnerable;
  58. }
  59. // Export
  60. module.exports = safeRegex;