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 76ca93c commit 5c37d98
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 3 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);
};
28 changes: 27 additions & 1 deletion test.js
Expand Up @@ -21,8 +21,34 @@ it('should trim off \\r\\n', function () {
});

it('should not be susceptible to exponential backtracking', function () {
var redosString = 'a';
var count = 1000;
while (count) {
redosString += '\r\n';
count--;
}
redosString += 'a';
var LongerRedosString = redosString;
var count = 1000;
while (count) {
LongerRedosString += redosString;
count--;
}
var start = Date.now();
trimOffNewlines('a' + '\r\n'.repeat(1000) + 'a');
trimOffNewlines(redosString);
trimOffNewlines(LongerRedosString);
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 5c37d98

Please sign in to comment.