From de3684408d74204367178e952b652e8d006efafc Mon Sep 17 00:00:00 2001 From: Jahed Ahmed Date: Tue, 11 May 2021 12:43:46 +0100 Subject: [PATCH] fix: ignore unsafe regex in namespace Fixes #737 --- package.json | 3 ++- src/common.js | 16 ++++++++++++++-- test.js | 26 ++++++++++++++++++++++++++ 3 files changed, 42 insertions(+), 3 deletions(-) diff --git a/package.json b/package.json index b7d70acb..059307d2 100644 --- a/package.json +++ b/package.json @@ -31,7 +31,8 @@ "test:coverage": "cat ./coverage/lcov.info | coveralls" }, "dependencies": { - "ms": "2.1.2" + "ms": "2.1.2", + "safe-regex": "^2.1.1" }, "devDependencies": { "brfs": "^2.0.1", diff --git a/src/common.js b/src/common.js index 50ce2925..ceae1a72 100644 --- a/src/common.js +++ b/src/common.js @@ -4,6 +4,8 @@ * implementations of `debug()`. */ +const safeRegex = require('safe-regex'); + function setup(env) { createDebug.debug = createDebug; createDebug.default = createDebug; @@ -179,9 +181,19 @@ function setup(env) { namespaces = split[i].replace(/\*/g, '.*?'); if (namespaces[0] === '-') { - createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); + const regex = new RegExp('^' + namespaces.substr(1) + '$'); + if (safeRegex(regex)) { + createDebug.skips.push(regex); + } else { + createDebug.log(`ignoring unsafe skipped namespace regex: "${regex}"`); + } } else { - createDebug.names.push(new RegExp('^' + namespaces + '$')); + const regex = new RegExp('^' + namespaces + '$'); + if (safeRegex(regex)) { + createDebug.names.push(regex); + } else { + createDebug.log(`ignoring unsafe enabled namespace regex: "${regex}"`); + } } } } diff --git a/test.js b/test.js index a1d6f633..0c181c07 100644 --- a/test.js +++ b/test.js @@ -137,4 +137,30 @@ describe('debug', () => { assert.deepStrictEqual(messages, ['test2', 'test3']); }); }); + + describe('ignores unsafe regex', () => { + it('in enabled namespace', () => { + const messages = []; + debug.log = (...args) => messages.push(args); + + debug.enable('(x+x+)+y'); + + assert.deepStrictEqual(messages.length, 1); + assert.deepStrictEqual(messages, [[ + 'ignoring unsafe enabled namespace regex: "/^(x+x+)+y$/"' + ]]); + }); + + it('in skipped namespace', () => { + const messages = []; + debug.log = (...args) => messages.push(args); + + debug.enable('-(x+x+)+y'); + + assert.deepStrictEqual(messages.length, 1); + assert.deepStrictEqual(messages, [[ + 'ignoring unsafe skipped namespace regex: "/^(x+x+)+y$/"' + ]]); + }); + }); });