From 30648cef1d17267c238c36b10e034ea24c7852e5 Mon Sep 17 00:00:00 2001 From: Hans Ott Date: Tue, 26 Oct 2021 11:36:19 +0200 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20Use=20AST=20to=20verify=20whether?= =?UTF-8?q?=20regexes=20are=20safe?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- package.json | 2 ++ test/test.js | 21 +++++++++++++++------ 2 files changed, 17 insertions(+), 6 deletions(-) diff --git a/package.json b/package.json index 9faf964fb..8e9b59c73 100644 --- a/package.json +++ b/package.json @@ -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", diff --git a/test/test.js b/test/test.js index ad54ef43e..71d1f46e1 100644 --- a/test/test.js +++ b/test/test.js @@ -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'); @@ -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 () { @@ -156,4 +165,4 @@ describe('Testing regexes', function () { }); }); }); -}) \ No newline at end of file +});