Skip to content

Commit

Permalink
Fix ReDoS for data URLs
Browse files Browse the repository at this point in the history
  • Loading branch information
sindresorhus committed May 21, 2021
1 parent b98fe7e commit b1fdb51
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 1 deletion.
2 changes: 1 addition & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ const testParameter = (name, filters) => {
};

const normalizeDataURL = (urlString, {stripHash}) => {
const match = /^data:(?<type>.*?),(?<data>.*?)(?:#(?<hash>.*))?$/.exec(urlString);
const match = /^data:(?<type>[^,]*?),(?<data>[^#]*?)(?:#(?<hash>.*))?$/.exec(urlString);

if (!match) {
throw new Error(`Invalid URL: ${urlString}`);
Expand Down
14 changes: 14 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -344,3 +344,17 @@ test('view-source URL', t => {
normalizeUrl('view-source:https://www.sindresorhus.com');
}, '`view-source:` is not supported as it is a non-standard protocol');
});

test('does not have exponential performance for data URLs', t => {
for (let index = 0; index < 1000; index += 50) {
const url = 'data:' + Array.from({length: index}).fill(',#').join('') + '\ra';
const start = Date.now();

try {
normalizeUrl(url);
} catch {}

const difference = Date.now() - start;
t.true(difference < 100, `Execution time: ${difference}`);
}
});

0 comments on commit b1fdb51

Please sign in to comment.