Skip to content

Commit 5c37d98

Browse files
committed
fix: remediate ReDOS further
1 parent 76ca93c commit 5c37d98

File tree

2 files changed

+39
-3
lines changed

2 files changed

+39
-3
lines changed

index.js

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,17 @@
11
'use strict';
22

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

55
module.exports = function (str) {
6-
return str.replace(regex, '');
6+
var result = regex.exec(str);
7+
if (!result) {
8+
return '';
9+
}
10+
var firstIndex = result.index;
11+
var lastIndex;
12+
while (result) {
13+
lastIndex = result.index + 1;
14+
result = regex.exec(str);
15+
}
16+
return str.substring(firstIndex, lastIndex);
717
};

test.js

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,8 +21,34 @@ it('should trim off \\r\\n', function () {
2121
});
2222

2323
it('should not be susceptible to exponential backtracking', function () {
24+
var redosString = 'a';
25+
var count = 1000;
26+
while (count) {
27+
redosString += '\r\n';
28+
count--;
29+
}
30+
redosString += 'a';
31+
var LongerRedosString = redosString;
32+
var count = 1000;
33+
while (count) {
34+
LongerRedosString += redosString;
35+
count--;
36+
}
2437
var start = Date.now();
25-
trimOffNewlines('a' + '\r\n'.repeat(1000) + 'a');
38+
trimOffNewlines(redosString);
39+
trimOffNewlines(LongerRedosString);
2640
var end = Date.now();
2741
assert.ok(end - start < 1000, 'took too long, probably susceptible to ReDOS');
2842
});
43+
44+
it('should leave newlines in the middle of a string alone', function () {
45+
assert.strictEqual(trimOffNewlines('Come on,\nFhqwhgads.'), 'Come on,\nFhqwhgads.');
46+
});
47+
48+
it('should leave spaces at start and end alone', function () {
49+
assert.strictEqual(trimOffNewlines(' fhqwhgads '), ' fhqwhgads ');
50+
});
51+
52+
it('should return an empty string if there are only \\r and \\n', function () {
53+
assert.strictEqual(trimOffNewlines('\r\n\r\r\n\n'), '');
54+
});

0 commit comments

Comments
 (0)