Skip to content

Commit

Permalink
fix: remediate ReDOS further
Browse files Browse the repository at this point in the history
  • Loading branch information
Trott committed Sep 23, 2021
1 parent 8cd3f73 commit e3e7fa6
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 2 deletions.
14 changes: 12 additions & 2 deletions index.js
@@ -1,7 +1,17 @@
'use strict';

var regex = /^(?:\r|\n)+|(?:\r|\n)+$/g;
var regex = /[^\r\n]/g;

module.exports = function (str) {
return str.replace(regex, '');
var result = regex.exec(str);
if (!result) {
return '';
}
var firstIndex = result.index;
var lastIndex;
while (result) {
lastIndex = result.index + 1;
result = regex.exec(str);
}
return str.substring(firstIndex, lastIndex);
};
13 changes: 13 additions & 0 deletions test.js
Expand Up @@ -23,6 +23,19 @@ it('should trim off \\r\\n', function () {
it('should not be susceptible to exponential backtracking', function () {
var start = Date.now();
trimOffNewlines('a' + '\r\n'.repeat(1000) + 'a');
trimOffNewlines(`a${'\r\n'.repeat(1000)}a`.repeat(1000));
var end = Date.now();
assert.ok(end - start < 1000, 'took too long, probably susceptible to ReDOS');
});

it('should leave newlines in the middle of a string alone', function () {
assert.strictEqual(trimOffNewlines('Come on,\nFhqwhgads.'), 'Come on,\nFhqwhgads.');
});

it('should leave spaces at start and end alone', function () {
assert.strictEqual(trimOffNewlines(' fhqwhgads '), ' fhqwhgads ');
});

it('should return an empty string if there are only \\r and \\n', function () {
assert.strictEqual(trimOffNewlines('\r\n\r\r\n\n'), '');
});

0 comments on commit e3e7fa6

Please sign in to comment.