Skip to content

Commit

Permalink
fix(rtrim): remove regex to prevent ReDOS attack
Browse files Browse the repository at this point in the history
  • Loading branch information
tux-tn committed Sep 27, 2021
1 parent c899b31 commit b21879c
Showing 1 changed file with 12 additions and 3 deletions.
15 changes: 12 additions & 3 deletions src/lib/rtrim.js
Original file line number Diff line number Diff line change
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 b21879c

Please sign in to comment.