Skip to content

Commit

Permalink
Fix ReDoS vulnerability
Browse files Browse the repository at this point in the history
  • Loading branch information
sindresorhus committed Sep 11, 2021
1 parent 80cd2f2 commit 11c6624
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 3 deletions.
2 changes: 1 addition & 1 deletion index.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
export default function semverRegex() {
return /(?<=^v?|\sv?)(?:(?:0|[1-9]\d*)\.){2}(?:0|[1-9]\d*)(?:-(?:0|[1-9]\d*|[\da-z-]*[a-z-][\da-z-]*)(?:\.(?:0|[1-9]\d*|[\da-z-]*[a-z-][\da-z-]*))*)?(?:\+[\da-z-]+(?:\.[\da-z-]+)*)?\b/gi;
return /(?:(?<=^v?|\sv?)(?:(?:0|[1-9]\d{0,9})\.){2}(?:0|[1-9]\d{0,9})(?:-(?:0|[1-9]\d*?|[\da-z-]*?[a-z-][\da-z-]*?){0,100}(?:\.(?:0|[1-9]\d*?|[\da-z-]*?[a-z-][\da-z-]*?))*?){0,100}(?:\+[\da-z-]+?(?:\.[\da-z-]+?)*?){0,100}\b){1,200}/gi;
}
2 changes: 1 addition & 1 deletion readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ semverRegex().exec('unicorn 1.0.0 rainbow')[0];
//=> ['1.0.0', '2.1.3']
```

**Note:** For versions coming from user-input, it's up to you to truncate the string to a sensible length to prevent abuse. For example, 100 length.
**Note:** For versions coming from user-input, you are recommended to truncate the string to a sensible length to prevent abuse. For example, 100 length.

## Related

Expand Down
11 changes: 10 additions & 1 deletion test.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ const fixtures = [
'2.7.2-foo+bar',
'1.2.3-alpha.10.beta',
'1.2.3-alpha.10.beta+build.unicorn.rainbow',
'foo 0.0.0 bar 0.0.0'
'foo 0.0.0 bar 0.0.0',
'99999.99999.99999'
];

test('matches semver versions on test', t => {
Expand Down Expand Up @@ -110,4 +111,12 @@ test('invalid version does not cause catatrophic backtracking', t => {
`v1.1.3-0aa${postfix}$`,
semverRegex()
);

for (let index = 1; index <= 50000; index++) {
const start = Date.now();
const fixture = `0.0.0-0${'.-------'.repeat(index)}@`;
semverRegex().test(fixture);
const difference = Date.now() - start;
t.true(difference < 10, `Execution time: ${difference}`);
}
});

0 comments on commit 11c6624

Please sign in to comment.