From f01c26a013b1889f0c217c643964513acf17f6a4 Mon Sep 17 00:00:00 2001 From: Blake Embrey Date: Thu, 5 Dec 2024 14:05:02 -0800 Subject: [PATCH] Merge commit from fork * Fix backtracking protection * Add test --- index.js | 12 +++++++++--- test.js | 4 ++++ 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/index.js b/index.js index 750c2bf..95d2f4b 100644 --- a/index.js +++ b/index.js @@ -72,20 +72,26 @@ function pathToRegexp(path, keys, options) { path = path.replace( /\\.|(\/)?(\.)?:(\w+)(\(.*?\))?(\*)?(\?)?|[.*]|\/\(/g, function (match, slash, format, key, capture, star, optional, offset) { - pos = offset + match.length; - if (match[0] === '\\') { backtrack += match; + pos += 2; return match; } if (match === '.') { backtrack += '\\.'; extraOffset += 1; + pos += 1; return '\\.'; } - backtrack = slash || format ? '' : path.slice(pos, offset); + if (slash || format) { + backtrack = ''; + } else { + backtrack += path.slice(pos, offset); + } + + pos = offset + match.length; if (match === '*') { extraOffset += 3; diff --git a/test.js b/test.js index d239195..537160e 100644 --- a/test.js +++ b/test.js @@ -8,6 +8,10 @@ describe('path-to-regexp', function () { }, /path must be a string, array of strings, or regular expression/); }); + it('should generate a regex without backtracking', function () { + assert.deepEqual(pathToRegExp('/:a-:b'), /^(?:\/([^/]+?))-(?:((?:(?!\/|-).)+?))\/?$/i); + }); + describe('strings', function () { it('should match simple paths', function () { var params = [];