Skip to content

Commit

Permalink
Merge pull request #546 from hansott/master
Browse files Browse the repository at this point in the history
✨ Use AST to verify whether regexes are safe
  • Loading branch information
faisalman authored Oct 26, 2021
2 parents 157af1e + 30648ce commit b86860e
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 6 deletions.
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,8 @@
]
},
"devDependencies": {
"@babel/parser": "7.15.8",
"@babel/traverse": "7.15.4",
"jshint": "~2.12.0",
"mocha": "~8.2.0",
"requirejs": "^2.3.2",
Expand Down
21 changes: 15 additions & 6 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ var fs = require('fs');
var safe = require('safe-regex');
var assert = require('assert');
var requirejs = require('requirejs');
var parseJS = require('@babel/parser').parse;
var traverse = require('@babel/traverse').default;
var UAParser = require('./../src/ua-parser');
var browsers = require('./browser-test.json');
var cpus = require('./cpu-test.json');
Expand Down Expand Up @@ -137,12 +139,19 @@ describe('Testing regexes', function () {

var regexes;

// todo: use AST-based instead of grep
before('Read main js file', function (done) {
fs.readFile('src/ua-parser.js', 'utf8', function (err, data) {
regexes = data.match(/(\/.+\/[ig]+)(?=[,\s\n])/g);
done();
before('Read main js file', function () {
var code = fs.readFileSync('src/ua-parser.js', 'utf8').toString();
var ast = parseJS(code, { sourceType: "script" });
regexes = [];
traverse(ast, {
RegExpLiteral: (path) => {
regexes.push(path.node.pattern);
}
});

if (regexes.length === 0) {
throw new Error("Regexes cannot be empty!");
}
});

describe('Begin testing', function () {
Expand All @@ -156,4 +165,4 @@ describe('Testing regexes', function () {
});
});
});
})
});

0 comments on commit b86860e

Please sign in to comment.