Skip to content

Commit

Permalink
Add backtrack protection to 3.x release (#321)
Browse files Browse the repository at this point in the history
  • Loading branch information
blakeembrey authored Sep 10, 2024
1 parent 6d2e8db commit d31670a
Show file tree
Hide file tree
Showing 3 changed files with 2,358 additions and 1,564 deletions.
13 changes: 12 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@ function parse (str, options) {
var optional = modifier === '?' || modifier === '*'
var pattern = capture || group
var delimiter = prev || defaultDelimiter
var prevText = prev || (typeof tokens[tokens.length - 1] === 'string' ? tokens[tokens.length - 1] : '')

tokens.push({
name: name || key++,
Expand All @@ -99,7 +100,7 @@ function parse (str, options) {
repeat: repeat,
pattern: pattern
? escapeGroup(pattern)
: '[^' + escapeString(delimiter === defaultDelimiter ? delimiter : (delimiter + defaultDelimiter)) + ']+?'
: restrictBacktrack(delimiter, defaultDelimiter, prevText)
})
}

Expand All @@ -111,6 +112,16 @@ function parse (str, options) {
return tokens
}

function restrictBacktrack (delimiter, defaultDelimiter, prevText) {
var charGroup = '[^' + escapeString(delimiter === defaultDelimiter ? delimiter : (delimiter + defaultDelimiter)) + ']'

if (!prevText || prevText.indexOf(delimiter) > -1 || prevText.indexOf(defaultDelimiter) > -1) {
return charGroup + '+?'
}

return escapeString(prevText) + '|(?:(?!' + escapeString(prevText) + ')' + charGroup + ')+?'
}

/**
* Compile a string to a template function for the path.
*
Expand Down
Loading

0 comments on commit d31670a

Please sign in to comment.