Skip to content

Commit

Permalink
fix(rtrim): remove regex to prevent ReDOS attack (#1738)
Browse files Browse the repository at this point in the history
  • Loading branch information
tux-tn committed Nov 1, 2021
1 parent 45901ec commit 496fc8b
Showing 1 changed file with 12 additions and 3 deletions.
15 changes: 12 additions & 3 deletions src/lib/rtrim.js
Expand Up @@ -2,7 +2,16 @@ import assertString from './util/assertString';

export default function rtrim(str, chars) {
assertString(str);
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#Escaping
const pattern = chars ? new RegExp(`[${chars.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}]+$`, 'g') : /(\s)+$/g;
return str.replace(pattern, '');
if (chars) {
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#Escaping
const pattern = new RegExp(`[${chars.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}]+$`, 'g');
return str.replace(pattern, '');
}
// Use a faster and more safe than regex trim method https://blog.stevenlevithan.com/archives/faster-trim-javascript
let strIndex = str.length - 1;
while (/\s/.test(str.charAt(strIndex))) {
strIndex -= 1;
}

return str.slice(0, strIndex + 1);
}

0 comments on commit 496fc8b

Please sign in to comment.