From 815b0a3ab58630dc5a2d6457857d4644a019cf23 Mon Sep 17 00:00:00 2001 From: Illia Antypenko Date: Wed, 2 Dec 2026 22:45:03 +0100 Subject: [PATCH 1/7] Fix ReDoS and edge cases in CSS url regexp - Rewrite url() regexp so whitespace and content groups can't overlap; worst-case matching is now linear instead of cubic (url( + 8000 spaces took ~71s before, a few ms now) - Support @import "x" at end of input and @import"x" without space - Don't include trailing characters after quoted @import - Ignore functions whose name only ends with "url" (e.g. my-url()) - Respect backslash escapes so escaped quotes/parens don't end the url - Don't strip comment-like sequences inside strings - Make data URI detection case-insensitive Co-Authored-By: Claude Opus 5.5 --- lib/css-parser.js | 44 +++++++++++++++++++++---- test/css-parser-test.js | 73 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 111 insertions(+), 6 deletions(-) diff --git a/lib/css-parser.js b/lib/css-parser.js index fe06bc4..ce85c5f 100644 --- a/lib/css-parser.js +++ b/lib/css-parser.js @@ -1,20 +1,52 @@ -var embeddedRegexp = /^data:(.*?),(.*?)/; -var commentRegexp = /\/\*([\s\S]*?)\*\//g; -var urlsRegexp = /(?:@import\s+)?url\s*\(\s*(("(.*?)")|('(.*?)')|(.*?))\s*\)|(?:@import\s+)(("(.*?)")|('(.*?)')|(.*?))[\s;]/ig; +var embeddedRegexp = /^data:/i; + +// Matches either a string (kept as is) or a comment (removed), so comment-like sequences inside strings are preserved +var commentRegexp = /("(?:\\[\s\S]|[^"\\\n])*"|'(?:\\[\s\S]|[^'\\\n])*')|\/\*[\s\S]*?\*\//g; + +// Character classes below are mutually exclusive so the regexp cannot backtrack catastrophically (ReDoS) +var doubleQuoted = '"((?:\\\\[\\s\\S]|[^"\\\\\\n])*)"'; +var singleQuoted = '\'((?:\\\\[\\s\\S]|[^\'\\\\\\n])*)\''; +var unquotedChar = '(?:\\\\[\\s\\S]|[^"\'()\\\\\\s])'; +var unquoted = '(' + unquotedChar + '+(?:\\s+' + unquotedChar + '+)*)'; + +var urlsRegexp = new RegExp([ + // url("path"), url('path'), url(path) + 'url\\s*\\(\\s*(?:(?:' + doubleQuoted + '|' + singleQuoted + '|' + unquoted + ')\\s*)?\\)', + // @import "path", @import 'path' + '@import\\s*(?:' + doubleQuoted + '|' + singleQuoted + ')', + // @import path + '@import\\s+([^\\s;"\'()]+)(?=[\\s;]|$)' +].join('|'), 'ig'); + +var identifierCharRegexp = /[\w-]/; function isEmbedded (src) { return embeddedRegexp.test(src.trim()); } +function keepStrings (match, str) { + return str || ''; +} + +function isPartOfIdentifier (text, index) { + return index > 0 && identifierCharRegexp.test(text[index - 1]); +} + function getUrls (text) { var urls = []; var urlMatch, url; - text = text.replace(commentRegexp, ''); + text = text.replace(commentRegexp, keepStrings); + urlsRegexp.lastIndex = 0; while ((urlMatch = urlsRegexp.exec(text))) { - // Match 3, 5, 6 group if '[@import] url(path)', match 9, 11, 12 group if '@import path' - url = urlMatch[3] || urlMatch[5] || urlMatch[6] || urlMatch[9] || urlMatch[11] || urlMatch[12]; + // Skip functions which only end with "url", e.g. my-url(...) + if (urlMatch[0].charAt(0) !== '@' && isPartOfIdentifier(text, urlMatch.index)) { + continue; + } + + // Groups 1-3 for url(...), 4-5 for @import "...", 6 for @import path + url = urlMatch[1] || urlMatch[2] || urlMatch[3] || urlMatch[4] || urlMatch[5] || urlMatch[6]; if (url && !isEmbedded(url) && urls.indexOf(url) === -1) { urls.push(url); diff --git a/test/css-parser-test.js b/test/css-parser-test.js index 2599f72..fddda1b 100644 --- a/test/css-parser-test.js +++ b/test/css-parser-test.js @@ -243,4 +243,77 @@ describe('Parse css urls', function(){ urls.should.have.length(0); }) }); + + describe('@import edge cases', function() { + it('should find quoted import at the end of input', function() { + parseCssUrls('@import "a.css"').should.eql(['a.css']); + parseCssUrls('@import \'b.css\'').should.eql(['b.css']); + }); + + it('should find unquoted import at the end of input', function() { + parseCssUrls('@import a.css').should.eql(['a.css']); + }); + + it('should find quoted import without whitespace after @import', function() { + parseCssUrls('@import"a.css";').should.eql(['a.css']); + }); + + it('should not include trailing characters after quoted import', function() { + parseCssUrls('@import "a.css"screen;').should.eql(['a.css']); + }); + }); + + describe('url() edge cases', function() { + it('should ignore functions whose name only ends with url', function() { + parseCssUrls('.x { mask: my-url(a.png); b: myurl(b.png); }').should.eql([]); + }); + + it('should keep escaped parentheses in unquoted url', function() { + parseCssUrls('.x { background: url(a\\).png); }').should.eql(['a\\).png']); + }); + + it('should keep escaped quotes in quoted url', function() { + parseCssUrls('.x { background: url("a\\"b.png"); }').should.eql(['a\\"b.png']); + }); + + it('should not return url with unclosed quote', function() { + parseCssUrls('.a { background: url("a.png); } .b { background: url(b.png); }').should.eql(['b.png']); + }); + + it('should find multiple urls on one line', function() { + parseCssUrls('.x { background: url(a.png), url("b.png"); }').should.eql(['a.png', 'b.png']); + }); + }); + + describe('comment-like sequences in strings', function() { + it('should not treat /* */ inside url string as comment', function() { + parseCssUrls('.x { background: url("x/*y*/z.png"); }').should.eql(['x/*y*/z.png']); + }); + + it('should not start comment from /* inside string', function() { + var text = '.a { content: "/*"; } .b { background: url(keep.png); } /* c */'; + parseCssUrls(text).should.eql(['keep.png']); + }); + }); + + it('should ignore data uri regardless of case', function() { + parseCssUrls('.x { background: url(DATA:image/png;base64,AAA); }').should.eql([]); + }); + + describe('performance', function() { + it('should not backtrack catastrophically on malicious input', function() { + var n = 100000; + var inputs = [ + 'url(' + ' '.repeat(n), + 'url('.repeat(n), + 'url("' + 'a'.repeat(n), + 'url(' + 'a '.repeat(n), + '@import ' + ' '.repeat(n), + '/*' + ' '.repeat(n) + ]; + var start = Date.now(); + inputs.forEach(function(input) { parseCssUrls(input); }); + (Date.now() - start).should.be.below(1000); + }); + }); }); From 04b1597355fa40928ba9d442249582124d315359 Mon Sep 17 00:00:00 2001 From: Illia Antypenko Date: Wed, 2 Dec 2026 22:45:34 +0100 Subject: [PATCH 2/7] Use lookbehind to skip functions ending with url Bump ESLint ecmaVersion to 2018 to allow regexp lookbehind (supported by all Node.js versions in the CI matrix). Co-Authored-By: Claude Opus 5.5 --- .eslintrc.yml | 2 +- lib/css-parser.js | 15 ++------------- 2 files changed, 3 insertions(+), 14 deletions(-) diff --git a/.eslintrc.yml b/.eslintrc.yml index 136cae3..3a38cdc 100644 --- a/.eslintrc.yml +++ b/.eslintrc.yml @@ -1,6 +1,6 @@ extends: "eslint:recommended" parserOptions: - ecmaVersion: 6 + ecmaVersion: 2018 env: node: true es6: true diff --git a/lib/css-parser.js b/lib/css-parser.js index ce85c5f..d0258f8 100644 --- a/lib/css-parser.js +++ b/lib/css-parser.js @@ -10,16 +10,14 @@ var unquotedChar = '(?:\\\\[\\s\\S]|[^"\'()\\\\\\s])'; var unquoted = '(' + unquotedChar + '+(?:\\s+' + unquotedChar + '+)*)'; var urlsRegexp = new RegExp([ - // url("path"), url('path'), url(path) - 'url\\s*\\(\\s*(?:(?:' + doubleQuoted + '|' + singleQuoted + '|' + unquoted + ')\\s*)?\\)', + // url("path"), url('path'), url(path); lookbehind skips functions which only end with "url", e.g. my-url(...) + '(? 0 && identifierCharRegexp.test(text[index - 1]); -} - function getUrls (text) { var urls = []; var urlMatch, url; @@ -40,11 +34,6 @@ function getUrls (text) { urlsRegexp.lastIndex = 0; while ((urlMatch = urlsRegexp.exec(text))) { - // Skip functions which only end with "url", e.g. my-url(...) - if (urlMatch[0].charAt(0) !== '@' && isPartOfIdentifier(text, urlMatch.index)) { - continue; - } - // Groups 1-3 for url(...), 4-5 for @import "...", 6 for @import path url = urlMatch[1] || urlMatch[2] || urlMatch[3] || urlMatch[4] || urlMatch[5] || urlMatch[6]; From f6a40ab3c8eeb087467291b52f41183d05ca1f3e Mon Sep 17 00:00:00 2001 From: Illia Antypenko Date: Wed, 2 Dec 2026 22:49:33 +0100 Subject: [PATCH 3/7] Fix polynomial backtracking in comment regexp, fix lint issues in tests - Unterminated strings now end at newline/end of input and unterminated comments at end of input (as in CSS spec), so every match attempt succeeds and no text is rescanned. Fixes CodeQL js/polynomial-redos - Add regression tests for unterminated strings/comments and CodeQL inputs - Enable mocha env and disable func-names for tests in ESLint config Co-Authored-By: Claude Opus 5.5 --- .eslintrc.yml | 8 ++++++- lib/css-parser.js | 6 +++-- test/css-parser-test.js | 53 +++++++++++++++++++++++++---------------- 3 files changed, 44 insertions(+), 23 deletions(-) diff --git a/.eslintrc.yml b/.eslintrc.yml index 3a38cdc..fee5d9f 100644 --- a/.eslintrc.yml +++ b/.eslintrc.yml @@ -32,4 +32,10 @@ rules: no-spaced-func: "warn" keyword-spacing: "error" space-before-blocks: "error" - no-console: "error" \ No newline at end of file + no-console: "error" +overrides: + - files: ["test/**/*.js"] + env: + mocha: true + rules: + func-names: "off" diff --git a/lib/css-parser.js b/lib/css-parser.js index d0258f8..8f433ed 100644 --- a/lib/css-parser.js +++ b/lib/css-parser.js @@ -1,7 +1,9 @@ var embeddedRegexp = /^data:/i; -// Matches either a string (kept as is) or a comment (removed), so comment-like sequences inside strings are preserved -var commentRegexp = /("(?:\\[\s\S]|[^"\\\n])*"|'(?:\\[\s\S]|[^'\\\n])*')|\/\*[\s\S]*?\*\//g; +// Matches either a string (kept as is) or a comment (removed), so comment-like sequences inside strings are preserved. +// As in CSS spec, unterminated string ends at newline or end of input and unterminated comment ends at end of input. +// Every match attempt starting with a quote or /* always succeeds, so the regexp never rescans text (no ReDoS) +var commentRegexp = /("(?:\\[\s\S]|[^"\\\n])*\\?(?:"|\n|$)|'(?:\\[\s\S]|[^'\\\n])*\\?(?:'|\n|$))|\/\*[\s\S]*?(?:\*\/|$)/g; // Character classes below are mutually exclusive so the regexp cannot backtrack catastrophically (ReDoS) var doubleQuoted = '"((?:\\\\[\\s\\S]|[^"\\\\\\n])*)"'; diff --git a/test/css-parser-test.js b/test/css-parser-test.js index fddda1b..a45b263 100644 --- a/test/css-parser-test.js +++ b/test/css-parser-test.js @@ -1,7 +1,7 @@ var parseCssUrls = require('../index'); var should = require('should'); -describe('Parse css urls', function(){ +describe('Parse css urls', function () { it('should return array of entries from url(...), @import url(...) and @import ...', function(){ var text = '\ @import url("a.css"); \ @@ -244,64 +244,72 @@ describe('Parse css urls', function(){ }) }); - describe('@import edge cases', function() { - it('should find quoted import at the end of input', function() { + describe('@import edge cases', function () { + it('should find quoted import at the end of input', function () { parseCssUrls('@import "a.css"').should.eql(['a.css']); parseCssUrls('@import \'b.css\'').should.eql(['b.css']); }); - it('should find unquoted import at the end of input', function() { + it('should find unquoted import at the end of input', function () { parseCssUrls('@import a.css').should.eql(['a.css']); }); - it('should find quoted import without whitespace after @import', function() { + it('should find quoted import without whitespace after @import', function () { parseCssUrls('@import"a.css";').should.eql(['a.css']); }); - it('should not include trailing characters after quoted import', function() { + it('should not include trailing characters after quoted import', function () { parseCssUrls('@import "a.css"screen;').should.eql(['a.css']); }); }); - describe('url() edge cases', function() { - it('should ignore functions whose name only ends with url', function() { + describe('url() edge cases', function () { + it('should ignore functions whose name only ends with url', function () { parseCssUrls('.x { mask: my-url(a.png); b: myurl(b.png); }').should.eql([]); }); - it('should keep escaped parentheses in unquoted url', function() { + it('should keep escaped parentheses in unquoted url', function () { parseCssUrls('.x { background: url(a\\).png); }').should.eql(['a\\).png']); }); - it('should keep escaped quotes in quoted url', function() { + it('should keep escaped quotes in quoted url', function () { parseCssUrls('.x { background: url("a\\"b.png"); }').should.eql(['a\\"b.png']); }); - it('should not return url with unclosed quote', function() { + it('should not return url with unclosed quote', function () { parseCssUrls('.a { background: url("a.png); } .b { background: url(b.png); }').should.eql(['b.png']); }); - it('should find multiple urls on one line', function() { + it('should find multiple urls on one line', function () { parseCssUrls('.x { background: url(a.png), url("b.png"); }').should.eql(['a.png', 'b.png']); }); }); - describe('comment-like sequences in strings', function() { - it('should not treat /* */ inside url string as comment', function() { + describe('comment-like sequences in strings', function () { + it('should not treat /* */ inside url string as comment', function () { parseCssUrls('.x { background: url("x/*y*/z.png"); }').should.eql(['x/*y*/z.png']); }); - it('should not start comment from /* inside string', function() { + it('should not start comment from /* inside string', function () { var text = '.a { content: "/*"; } .b { background: url(keep.png); } /* c */'; parseCssUrls(text).should.eql(['keep.png']); }); + + it('should treat unterminated comment as comment till the end of input', function () { + parseCssUrls('.a { background: url(a.png); } /* .b { background: url(b.png); }').should.eql(['a.png']); + }); + + it('should end unterminated string at newline', function () { + parseCssUrls('.a { content: "/*\n} .b { background: url(b.png); } /* c */').should.eql(['b.png']); + }); }); - it('should ignore data uri regardless of case', function() { + it('should ignore data uri regardless of case', function () { parseCssUrls('.x { background: url(DATA:image/png;base64,AAA); }').should.eql([]); }); - describe('performance', function() { - it('should not backtrack catastrophically on malicious input', function() { + describe('performance', function () { + it('should not backtrack catastrophically on malicious input', function () { var n = 100000; var inputs = [ 'url(' + ' '.repeat(n), @@ -309,10 +317,15 @@ describe('Parse css urls', function(){ 'url("' + 'a'.repeat(n), 'url(' + 'a '.repeat(n), '@import ' + ' '.repeat(n), - '/*' + ' '.repeat(n) + '/*' + ' '.repeat(n), + '"' + '\\"'.repeat(n), + '/*' + 'a/*'.repeat(n), + '"\\'.repeat(n), + 'url("'.repeat(n), + '@import "'.repeat(n) ]; var start = Date.now(); - inputs.forEach(function(input) { parseCssUrls(input); }); + inputs.forEach(function (input) { parseCssUrls(input); }); (Date.now() - start).should.be.below(1000); }); }); From ecd436e3990170fe7a133d0eef679f92fd159231 Mon Sep 17 00:00:00 2001 From: Illia Antypenko Date: Wed, 2 Dec 2026 22:59:41 +0100 Subject: [PATCH 4/7] Parse CSS urls in a single tokenizer pass, fix review findings Replace the separate comment-stripping pass with one regexp which skips comments, strings and identifiers as whole tokens: - find @import url (...) with whitespace before the parenthesis - do not start strings from escaped quotes outside of strings - do not treat /* inside unquoted url() as a comment - find urls right after a comment - skip invalid unquoted url() with quotes inside as a whole - ignore url() inside strings and attribute selectors - drop regexp lookbehind to keep old runtimes working - deduplicate urls in linear time - lint tests with npm run eslint and fix lint errors in them Co-Authored-By: Claude Fable 5.2 --- lib/css-parser.js | 54 ++++++++++++------- package.json | 2 +- test/css-parser-test.js | 114 +++++++++++++++++++++++++++++----------- 3 files changed, 119 insertions(+), 51 deletions(-) diff --git a/lib/css-parser.js b/lib/css-parser.js index 8f433ed..7a23a10 100644 --- a/lib/css-parser.js +++ b/lib/css-parser.js @@ -1,45 +1,59 @@ var embeddedRegexp = /^data:/i; -// Matches either a string (kept as is) or a comment (removed), so comment-like sequences inside strings are preserved. -// As in CSS spec, unterminated string ends at newline or end of input and unterminated comment ends at end of input. -// Every match attempt starting with a quote or /* always succeeds, so the regexp never rescans text (no ReDoS) -var commentRegexp = /("(?:\\[\s\S]|[^"\\\n])*\\?(?:"|\n|$)|'(?:\\[\s\S]|[^'\\\n])*\\?(?:'|\n|$))|\/\*[\s\S]*?(?:\*\/|$)/g; - -// Character classes below are mutually exclusive so the regexp cannot backtrack catastrophically (ReDoS) -var doubleQuoted = '"((?:\\\\[\\s\\S]|[^"\\\\\\n])*)"'; -var singleQuoted = '\'((?:\\\\[\\s\\S]|[^\'\\\\\\n])*)\''; -var unquotedChar = '(?:\\\\[\\s\\S]|[^"\'()\\\\\\s])'; +// The text is scanned in a single pass by one regexp which works as a tokenizer: at every position it matches either +// a token with url (url(...), @import ...) or a token which has to be skipped as a whole (comment, string, identifier). +// Every character class in a repetition excludes the characters which can follow it, so the regexp cannot backtrack +// catastrophically (ReDoS) + +// As in CSS spec, unterminated comment ends at the end of input +var comment = /\/\*[\s\S]*?(?:\*\/|$)/.source; +// Terminated comment without lazy quantifier, safe to use inside repetition +var closedComment = /\/\*[^*]*\*+(?:[^/*][^*]*\*+)*\//.source; +var whitespace = '(?:\\s|' + closedComment + ')'; + +var doubleQuoted = /"((?:\\[\s\S]|[^"\\\n])*)"/.source; +var singleQuoted = /'((?:\\[\s\S]|[^'\\\n])*)'/.source; +var unquotedChar = /(?:\\[\s\S]|[^"'()\\\s])/.source; var unquoted = '(' + unquotedChar + '+(?:\\s+' + unquotedChar + '+)*)'; +var closedString = /"(?:\\[\s\S]|[^"\\\n])*"|'(?:\\[\s\S]|[^'\\\n])*'/.source; +// As in CSS spec, unterminated string ends at newline or end of input +var skippedString = /"(?:\\[\s\S]|[^"\\\n])*\\?(?:"|\n|$)|'(?:\\[\s\S]|[^'\\\n])*\\?(?:'|\n|$)/.source; +// Identifier with escapes, so url is found only at the start of a name (not in my-url(...)) and escaped quotes +// do not start a string +var skippedIdentifier = /(?:[\w-]|[\u0080-\uFFFF]|\\[\s\S])+/.source; + var urlsRegexp = new RegExp([ - // url("path"), url('path'), url(path); lookbehind skips functions which only end with "url", e.g. my-url(...) - '(?"); \ }'; @@ -234,14 +234,14 @@ describe('Parse css urls', function () { urls.should.have.length(0); }); - it('should ignore minimal data uri ("data:,")', function() { + it('should ignore minimal data uri ("data:,")', function () { var text = 'img.grayscale { \ filter: url("data:,"); \ }'; var urls = parseCssUrls(text); urls.should.be.instanceof(Array); urls.should.have.length(0); - }) + }); }); describe('@import edge cases', function () { @@ -261,6 +261,21 @@ describe('Parse css urls', function () { it('should not include trailing characters after quoted import', function () { parseCssUrls('@import "a.css"screen;').should.eql(['a.css']); }); + + it('should find import with whitespace between url and parenthesis', function () { + parseCssUrls('@import url ("a.css");').should.eql(['a.css']); + parseCssUrls('@import URL (b.css);').should.eql(['b.css']); + }); + + it('should find import separated by comments', function () { + parseCssUrls('@import/**/url(a.css);').should.eql(['a.css']); + parseCssUrls('@import /* c */ "b.css";').should.eql(['b.css']); + parseCssUrls('@import /* c *//**/ c.css;').should.eql(['c.css']); + }); + + it('should not treat unterminated comment as import', function () { + parseCssUrls('@import /* a.css;').should.eql([]); + }); }); describe('url() edge cases', function () { @@ -280,6 +295,29 @@ describe('Parse css urls', function () { parseCssUrls('.a { background: url("a.png); } .b { background: url(b.png); }').should.eql(['b.png']); }); + it('should find url right after comment', function () { + parseCssUrls('.a{background:#fff/**/url(a.png)}').should.eql(['a.png']); + }); + + it('should not treat /* inside unquoted url as comment', function () { + parseCssUrls('.a{background:url(//cdn.com/img/*.png)} .b{background:url(b.png)}') + .should.eql(['//cdn.com/img/*.png', 'b.png']); + parseCssUrls('.a{background:url(x/*y*/z.png)}').should.eql(['x/*y*/z.png']); + }); + + it('should skip unquoted url with quotes inside as a whole', function () { + var text = '.a{background:url(data:image/svg+xml;utf8,' + + ')} .b{background:url(b.png)}'; + parseCssUrls(text).should.eql(['b.png']); + parseCssUrls('.a{background:url(it\'s.png)} /* url(x.png) */').should.eql([]); + }); + + it('should ignore url inside strings and attribute selectors', function () { + parseCssUrls('.a{content:"see url(foo.png)"}').should.eql([]); + parseCssUrls('.sel[data-x=\'url(q.png)\']{color:red}').should.eql([]); + parseCssUrls('.a{content:"@import \\"a.css\\""}').should.eql([]); + }); + it('should find multiple urls on one line', function () { parseCssUrls('.x { background: url(a.png), url("b.png"); }').should.eql(['a.png', 'b.png']); }); @@ -299,6 +337,12 @@ describe('Parse css urls', function () { parseCssUrls('.a { background: url(a.png); } /* .b { background: url(b.png); }').should.eql(['a.png']); }); + it('should not start string from escaped quote outside of string', function () { + var text = '.a\\\'b{color:red}/* url(x.png) */ .c{background:url(c.png)}'; + parseCssUrls(text).should.eql(['c.png']); + parseCssUrls('.content-\\[\\\'\\\'\\]{}/* url(x.png) */.d{background:url(d.png)}').should.eql(['d.png']); + }); + it('should end unterminated string at newline', function () { parseCssUrls('.a { content: "/*\n} .b { background: url(b.png); } /* c */').should.eql(['b.png']); }); @@ -322,7 +366,17 @@ describe('Parse css urls', function () { '/*' + 'a/*'.repeat(n), '"\\'.repeat(n), 'url("'.repeat(n), - '@import "'.repeat(n) + '@import "'.repeat(n), + '@import' + '/**/'.repeat(n), + '@import/*' + '*a'.repeat(n), + '@import ' + '/* */ '.repeat(n) + '(', + 'url' + ' '.repeat(n), + 'url(a' + ' a'.repeat(n) + '"', + '-'.repeat(n) + '\\', + '\''.repeat(n), + 'url(' + '"\''.repeat(n), + 'url(")'.repeat(n) + 'url(\')'.repeat(n), + Array.from({length: n}, function (_, i) { return 'url(' + i + '.png)'; }).join(' ') ]; var start = Date.now(); inputs.forEach(function (input) { parseCssUrls(input); }); From ae115d94abce4e2a927c6ad6abd1b0f5a7fe3751 Mon Sep 17 00:00:00 2001 From: Illia Antypenko Date: Wed, 2 Dec 2026 23:13:29 +0100 Subject: [PATCH 5/7] Fix quadratic backtracking in unquoted @import path The path could run over following @import rules separated only by comments and was rescanned from each of them. Exclude @ from the path characters. Co-Authored-By: Claude Fable 5.2 --- lib/css-parser.js | 4 ++-- test/css-parser-test.js | 3 +++ 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/lib/css-parser.js b/lib/css-parser.js index 7a23a10..e66759d 100644 --- a/lib/css-parser.js +++ b/lib/css-parser.js @@ -32,8 +32,8 @@ var urlsRegexp = new RegExp([ 'url\\s*\\((?:' + closedString + '|\\\\[\\s\\S]|[^)\\\\])*\\)?', // @import "path", @import 'path' '@import' + whitespace + '*(?:' + doubleQuoted + '|' + singleQuoted + ')', - // @import path - '@import' + whitespace + '+(?!url\\s*\\(|\\/\\*)([^\\s;"\'()]+)(?=[\\s;]|$)', + // @import path; @ is excluded so the path cannot run over following @import rules and be rescanned from each of them + '@import' + whitespace + '+(?!url\\s*\\(|\\/\\*)([^\\s;@"\'()]+)(?=[\\s;]|$)', skippedString, skippedIdentifier ].join('|'), 'ig'); diff --git a/test/css-parser-test.js b/test/css-parser-test.js index 43dd93f..fab68f2 100644 --- a/test/css-parser-test.js +++ b/test/css-parser-test.js @@ -376,6 +376,9 @@ describe('Parse css urls', function () { '\''.repeat(n), 'url(' + '"\''.repeat(n), 'url(")'.repeat(n) + 'url(\')'.repeat(n), + '@import/**/@import*'.repeat(n) + ')', + '\\"' + '/**/@import'.repeat(n) + '@import)', + '*/' + '@import/*/**/url\u00e9'.repeat(n) + 'url(', Array.from({length: n}, function (_, i) { return 'url(' + i + '.png)'; }).join(' ') ]; var start = Date.now(); From 9eb822247b2d2b218e0a31e5daefe3f304af339c Mon Sep 17 00:00:00 2001 From: Illia Antypenko Date: Wed, 2 Dec 2026 23:26:29 +0100 Subject: [PATCH 6/7] Unroll regexp loops, handle comments in url() and CR/FF newlines - Unroll alternations inside loops: they cost a backtrack frame per character and overflowed the regexp stack on tokens longer than ~8M characters (e.g. embedded fonts) - Skip comments around the value inside url(...). For unquoted value comments have to be separated from it by whitespace - Treat \r and \f as newlines which end a string and escaped \r\n as a single line continuation, so CRLF stylesheets do not desynchronise the tokenizer Co-Authored-By: Claude Fable 5.2 --- lib/css-parser.js | 49 +++++++++++++++++++-------- test/css-parser-test.js | 75 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 110 insertions(+), 14 deletions(-) diff --git a/lib/css-parser.js b/lib/css-parser.js index e66759d..7d18084 100644 --- a/lib/css-parser.js +++ b/lib/css-parser.js @@ -3,37 +3,58 @@ var embeddedRegexp = /^data:/i; // The text is scanned in a single pass by one regexp which works as a tokenizer: at every position it matches either // a token with url (url(...), @import ...) or a token which has to be skipped as a whole (comment, string, identifier). // Every character class in a repetition excludes the characters which can follow it, so the regexp cannot backtrack -// catastrophically (ReDoS) +// catastrophically (ReDoS). +// Loops are unrolled, e.g. [^"\\]*(?:\\.[^"\\]*)* instead of (?:\\.|[^"\\])*, so a long run of plain characters is +// consumed by a single character class: an alternation inside a loop costs a backtrack frame per character and +// overflows the regexp stack on tokens of several megabytes (e.g. embedded fonts). +// Unrolled parts must never match an empty string and must not nest a quantified class in a quantified group // As in CSS spec, unterminated comment ends at the end of input var comment = /\/\*[\s\S]*?(?:\*\/|$)/.source; // Terminated comment without lazy quantifier, safe to use inside repetition var closedComment = /\/\*[^*]*\*+(?:[^/*][^*]*\*+)*\//.source; -var whitespace = '(?:\\s|' + closedComment + ')'; +// Optional and required whitespace with comments +var whitespaceOpt = '\\s*(?:' + closedComment + '\\s*)*'; +var whitespaceReq = '(?:\\s+(?:' + closedComment + '\\s*)*|(?:' + closedComment + '\\s*)+)'; +// Whitespace with comments inside url(...). Comment with closing parenthesis is not matched here, so a scan for the end +// of comment never leaves url(...) which is skipped as invalid when the comment is unterminated; otherwise the rest +// of the text would be rescanned from every url(/* +var urlComment = /\/\*[^*)]*\*+(?:[^/*)][^*)]*\*+)*\//.source; +var urlWhitespaceOpt = '\\s*(?:' + urlComment + '\\s*)*'; -var doubleQuoted = /"((?:\\[\s\S]|[^"\\\n])*)"/.source; -var singleQuoted = /'((?:\\[\s\S]|[^'\\\n])*)'/.source; -var unquotedChar = /(?:\\[\s\S]|[^"'()\\\s])/.source; -var unquoted = '(' + unquotedChar + '+(?:\\s+' + unquotedChar + '+)*)'; +// Escaped character; \r\n is a single newline (line continuation in a string). Alternatives are mutually exclusive, +// so \ followed by \r\n can be matched in one way only +var escaped = /\\(?:\r\n|[^\r]|\r(?!\n))/.source; +// As in CSS spec, string cannot contain unescaped newline (\n, \r or \f) +var doubleQuotedBody = '[^"\\\\\\n\\r\\f]*(?:' + escaped + '[^"\\\\\\n\\r\\f]*)*'; +var singleQuotedBody = '[^\'\\\\\\n\\r\\f]*(?:' + escaped + '[^\'\\\\\\n\\r\\f]*)*'; +var doubleQuoted = '"(' + doubleQuotedBody + ')"'; +var singleQuoted = '\'(' + singleQuotedBody + ')\''; +// One or more characters or escapes without whitespace +var unquotedChunk = '(?:[^"\'()\\\\\\s]+(?:' + escaped + '[^"\'()\\\\\\s]*)*|(?:' + escaped + '[^"\'()\\\\\\s]*)+)'; +// Neither the value nor its part after whitespace starts with a comment, and the value ends only at whitespace or +// closing parenthesis: comments around the value are matched as whitespace only and have to be separated from it +// by whitespace (/* glued to the value is a part of it). Otherwise comments could be matched in two ways and rescanned +var unquoted = '((?!\\/\\*)' + unquotedChunk + '(?:\\s+(?!\\/\\*)' + unquotedChunk + ')*)(?=[\\s)])'; -var closedString = /"(?:\\[\s\S]|[^"\\\n])*"|'(?:\\[\s\S]|[^'\\\n])*'/.source; +var closedString = '"' + doubleQuotedBody + '"|\'' + singleQuotedBody + '\''; // As in CSS spec, unterminated string ends at newline or end of input -var skippedString = /"(?:\\[\s\S]|[^"\\\n])*\\?(?:"|\n|$)|'(?:\\[\s\S]|[^'\\\n])*\\?(?:'|\n|$)/.source; +var skippedString = '"' + doubleQuotedBody + '\\\\?(?:"|[\\n\\r\\f]|$)|\'' + singleQuotedBody + '\\\\?(?:\'|[\\n\\r\\f]|$)'; // Identifier with escapes, so url is found only at the start of a name (not in my-url(...)) and escaped quotes // do not start a string -var skippedIdentifier = /(?:[\w-]|[\u0080-\uFFFF]|\\[\s\S])+/.source; +var skippedIdentifier = '(?:[\\w\\u0080-\\uFFFF-]+(?:' + escaped + '[\\w\\u0080-\\uFFFF-]*)*|(?:' + escaped + '[\\w\\u0080-\\uFFFF-]*)+)'; var urlsRegexp = new RegExp([ comment, - // url("path"), url('path'), url(path) - 'url\\s*\\(\\s*(?:(?:' + doubleQuoted + '|' + singleQuoted + '|' + unquoted + ')\\s*)?\\)', + // url("path"), url('path'), url(path), with optional comments around the path + 'url\\s*\\(' + urlWhitespaceOpt + '(?:(?:' + doubleQuoted + '|' + singleQuoted + '|' + unquoted + ')' + urlWhitespaceOpt + ')?\\)', // Invalid url(...), e.g. unquoted with quotes inside: skipped till the closing parenthesis as in CSS spec. // Parentheses inside closed strings do not end it - 'url\\s*\\((?:' + closedString + '|\\\\[\\s\\S]|[^)\\\\])*\\)?', + 'url\\s*\\([^)\\\\"\']*(?:(?:' + closedString + '|' + escaped + '|["\'])[^)\\\\"\']*)*\\)?', // @import "path", @import 'path' - '@import' + whitespace + '*(?:' + doubleQuoted + '|' + singleQuoted + ')', + '@import' + whitespaceOpt + '(?:' + doubleQuoted + '|' + singleQuoted + ')', // @import path; @ is excluded so the path cannot run over following @import rules and be rescanned from each of them - '@import' + whitespace + '+(?!url\\s*\\(|\\/\\*)([^\\s;@"\'()]+)(?=[\\s;]|$)', + '@import' + whitespaceReq + '(?!url\\s*\\(|\\/\\*)([^\\s;@"\'()]+)(?=[\\s;]|$)', skippedString, skippedIdentifier ].join('|'), 'ig'); diff --git a/test/css-parser-test.js b/test/css-parser-test.js index fab68f2..188c389 100644 --- a/test/css-parser-test.js +++ b/test/css-parser-test.js @@ -352,6 +352,47 @@ describe('Parse css urls', function () { parseCssUrls('.x { background: url(DATA:image/png;base64,AAA); }').should.eql([]); }); + describe('comments inside url()', function () { + it('should skip comments around quoted url', function () { + parseCssUrls('.a{background:url("a.png" /* c */)}').should.be.eql(['a.png']); + parseCssUrls('.a{background:url(/* c */ \'a.png\')}').should.be.eql(['a.png']); + parseCssUrls('.a{background:url(/* c *//* d */"a.png"/* e */ /* f */)}').should.be.eql(['a.png']); + }); + + it('should skip comments separated by whitespace from unquoted url', function () { + parseCssUrls('.a{background:url( /* c */ a.png)}').should.be.eql(['a.png']); + parseCssUrls('.a{background:url(/* c */a.png /* d */)}').should.be.eql(['a.png']); + parseCssUrls('.a{background:url(a.png\n/* d */\n)}').should.be.eql(['a.png']); + }); + + it('should keep /* inside unquoted url', function () { + parseCssUrls('.a{background:url(http://example.com/*/a.png)}').should.be.eql(['http://example.com/*/a.png']); + }); + + it('should not find url in url() with comment only', function () { + parseCssUrls('.a{background:url(/* a.png */)} .b{background:url(b.png)}').should.be.eql(['b.png']); + }); + }); + + describe('newlines', function () { + it('should handle escaped CRLF as line continuation in string', function () { + parseCssUrls('.a{content:"x\\\r\ny";background:url(a.png)}\r\n.b{background:url(b.png)}') + .should.be.eql(['a.png', 'b.png']); + parseCssUrls('.a{content:"foo\\\r\nbar url(x.png)"} .b{background:url(b.png)}').should.be.eql(['b.png']); + parseCssUrls('.a{content:\'foo\\\r\nbar url(x.png)\'} .b{background:url(b.png)}').should.be.eql(['b.png']); + }); + + it('should end unterminated string at \\r and \\f', function () { + parseCssUrls('.a{content:"unterminated\r.b{background:url(b.png)}').should.be.eql(['b.png']); + parseCssUrls('.a{content:\'unterminated\f.b{background:url(b.png)}').should.be.eql(['b.png']); + parseCssUrls('.a{content:"unterminated\r\n.b{background:url(b.png)}').should.be.eql(['b.png']); + }); + + it('should not find quoted url with unescaped newline', function () { + parseCssUrls('.a{background:url("a\r.png")} .b{background:url(b.png)}').should.be.eql(['b.png']); + }); + }); + describe('performance', function () { it('should not backtrack catastrophically on malicious input', function () { var n = 100000; @@ -379,11 +420,45 @@ describe('Parse css urls', function () { '@import/**/@import*'.repeat(n) + ')', '\\"' + '/**/@import'.repeat(n) + '@import)', '*/' + '@import/*/**/url\u00e9'.repeat(n) + 'url(', + 'url(' + '/**/'.repeat(n) + '"', + 'url(' + '/**/ '.repeat(n) + '"', + 'url(a ' + '/**/ '.repeat(n) + '"', + 'url("a"' + '/**/'.repeat(n) + '"', + 'url(/*)'.repeat(n), + 'url(a /*)'.repeat(n), + 'url("a"/*)'.repeat(n), + 'url( /*\\)'.repeat(n), + 'url(a .' + '/**/'.repeat(n) + '"', + 'url( ' + '\\"/*'.repeat(n) + '\r\n', + 'url(a \\\r' + '/*url@import'.repeat(n) + '\\\r\nurl(a ', + 'url( ' + 'x.css/*\\\r\n'.repeat(n) + '\'', + 'url(' + 'a\\\r\n'.repeat(n) + '"', + 'url("' + '\\\r\n'.repeat(n), + '"' + '\\\r'.repeat(n) + '\n', Array.from({length: n}, function (_, i) { return 'url(' + i + '.png)'; }).join(' ') ]; var start = Date.now(); inputs.forEach(function (input) { parseCssUrls(input); }); (Date.now() - start).should.be.below(1000); }); + + it('should not overflow regexp stack on very long tokens', function () { + var long = 'A'.repeat(10000000); + var rest = ' .b{background:url(b.png)}'; + var inputs = [ + '.a{src:url(data:font/woff2;base64,' + long + ')}', + '.a{src:url("data:font/woff2;base64,' + long + '")}', + '.a{src:url(\'data:font/woff2;base64,' + long + '\')}', + '.a{content:"' + long + '"}', + '.a{content:"' + long + '\n', + long, + '@import' + ' '.repeat(10000000) + '"b.png";', + '@import' + ' '.repeat(10000000) + 'b.png;', + '.a{src:url(a"' + long + ')}' + ]; + inputs.forEach(function (input) { + parseCssUrls(input + rest).should.be.eql(['b.png']); + }); + }); }); }); From f574c1468cfaadcc81feac1f5509eceed3ff1888 Mon Sep 17 00:00:00 2001 From: Illia Antypenko Date: Thu, 3 Dec 2026 09:27:16 +0100 Subject: [PATCH 7/7] Skip @namespace and @document urls, reject non-string input - Do not return url(...) from @namespace and from @document prelude: these are not resources to load - Skip comments with closing parenthesis inside url(...); invalid url(...) now skips comments as a whole - Throw TypeError for non-string input as before instead of coercing it - Performance test compares time for two input sizes instead of a fixed wall-clock limit Co-Authored-By: Claude Fable 5.2 --- lib/css-parser.js | 22 +++++++----- test/css-parser-test.js | 75 +++++++++++++++++++++++++++++++++++++---- 2 files changed, 83 insertions(+), 14 deletions(-) diff --git a/lib/css-parser.js b/lib/css-parser.js index 7d18084..d28cbcc 100644 --- a/lib/css-parser.js +++ b/lib/css-parser.js @@ -16,11 +16,6 @@ var closedComment = /\/\*[^*]*\*+(?:[^/*][^*]*\*+)*\//.source; // Optional and required whitespace with comments var whitespaceOpt = '\\s*(?:' + closedComment + '\\s*)*'; var whitespaceReq = '(?:\\s+(?:' + closedComment + '\\s*)*|(?:' + closedComment + '\\s*)+)'; -// Whitespace with comments inside url(...). Comment with closing parenthesis is not matched here, so a scan for the end -// of comment never leaves url(...) which is skipped as invalid when the comment is unterminated; otherwise the rest -// of the text would be rescanned from every url(/* -var urlComment = /\/\*[^*)]*\*+(?:[^/*)][^*)]*\*+)*\//.source; -var urlWhitespaceOpt = '\\s*(?:' + urlComment + '\\s*)*'; // Escaped character; \r\n is a single newline (line continuation in a string). Alternatives are mutually exclusive, // so \ followed by \r\n can be matched in one way only @@ -44,13 +39,20 @@ var skippedString = '"' + doubleQuotedBody + '\\\\?(?:"|[\\n\\r\\f]|$)|\'' + sin // do not start a string var skippedIdentifier = '(?:[\\w\\u0080-\\uFFFF-]+(?:' + escaped + '[\\w\\u0080-\\uFFFF-]*)*|(?:' + escaped + '[\\w\\u0080-\\uFFFF-]*)+)'; +// Prelude of at-rule where url(...) is not a resource to load: @namespace url(...), @document url(...). +// Skipped till ; or { which are not inside closed strings. Escapes are skipped as a whole, so escaped quote +// does not start a string +var skippedAtRule = '@(?:namespace|(?:-moz-)?document)(?![\\w-])[^;{"\'\\\\]*(?:(?:' + closedString + '|' + escaped + '|["\'])[^;{"\'\\\\]*)*'; + var urlsRegexp = new RegExp([ comment, + skippedAtRule, // url("path"), url('path'), url(path), with optional comments around the path - 'url\\s*\\(' + urlWhitespaceOpt + '(?:(?:' + doubleQuoted + '|' + singleQuoted + '|' + unquoted + ')' + urlWhitespaceOpt + ')?\\)', + 'url\\s*\\(' + whitespaceOpt + '(?:(?:' + doubleQuoted + '|' + singleQuoted + '|' + unquoted + ')' + whitespaceOpt + ')?\\)', // Invalid url(...), e.g. unquoted with quotes inside: skipped till the closing parenthesis as in CSS spec. - // Parentheses inside closed strings do not end it - 'url\\s*\\([^)\\\\"\']*(?:(?:' + closedString + '|' + escaped + '|["\'])[^)\\\\"\']*)*\\)?', + // Parentheses inside closed strings and comments do not end it. Unterminated comment is skipped till the end of + // input here as well, otherwise the rest of the text would be rescanned for the end of comment from every url(/* + 'url\\s*\\([^)\\\\"\'/]*(?:(?:' + closedString + '|' + escaped + '|' + comment + '|["\'/])[^)\\\\"\'/]*)*\\)?', // @import "path", @import 'path' '@import' + whitespaceOpt + '(?:' + doubleQuoted + '|' + singleQuoted + ')', // @import path; @ is excluded so the path cannot run over following @import rules and be rescanned from each of them @@ -68,6 +70,10 @@ function getUrls (text) { var found = Object.create(null); var urlMatch, url; + if (typeof text !== 'string') { + throw new TypeError('css text must be a string, got ' + typeof text); + } + urlsRegexp.lastIndex = 0; while ((urlMatch = urlsRegexp.exec(text))) { // Groups 1-3 for url(...), 4-5 for @import "...", 6 for @import path diff --git a/test/css-parser-test.js b/test/css-parser-test.js index 188c389..87094a9 100644 --- a/test/css-parser-test.js +++ b/test/css-parser-test.js @@ -369,6 +369,11 @@ describe('Parse css urls', function () { parseCssUrls('.a{background:url(http://example.com/*/a.png)}').should.be.eql(['http://example.com/*/a.png']); }); + it('should skip comments with closing parenthesis', function () { + parseCssUrls('.a{background:url("a.png" /* ) */)}').should.be.eql(['a.png']); + parseCssUrls('.a{background:url(/* (c) */ "a.png")}').should.be.eql(['a.png']); + }); + it('should not find url in url() with comment only', function () { parseCssUrls('.a{background:url(/* a.png */)} .b{background:url(b.png)}').should.be.eql(['b.png']); }); @@ -393,10 +398,36 @@ describe('Parse css urls', function () { }); }); + describe('at-rules with url() which is not a resource', function () { + it('should not find url in @namespace', function () { + parseCssUrls('@namespace url(http://www.w3.org/1999/xhtml);').should.be.eql([]); + parseCssUrls('@NAMESPACE svg url("http://www.w3.org/2000/svg"); .a{background:url(a.png)}').should.be.eql(['a.png']); + parseCssUrls('@namespace "http://www.w3.org/1999/xhtml;url(x.png)"; .a{background:url(a.png)}').should.be.eql(['a.png']); + }); + + it('should not find url in @document prelude, but find urls in its rules', function () { + parseCssUrls('@document url(http://example.com/), url-prefix("http://example.com/a") { .a{background:url(a.png)} }') + .should.be.eql(['a.png']); + parseCssUrls('@-moz-document url(http://example.com/) { .a{background:url(a.png)} }').should.be.eql(['a.png']); + }); + + it('should find urls in at-rules with similar names', function () { + parseCssUrls('@namespaces url(a.png);').should.be.eql(['a.png']); + }); + }); + + describe('input type', function () { + it('should throw TypeError if text is not a string', function () { + [undefined, null, 42, {}, Buffer.from('url(a.png)')].forEach(function (text) { + (function () { parseCssUrls(text); }).should.throw(TypeError); + }); + }); + }); + describe('performance', function () { - it('should not backtrack catastrophically on malicious input', function () { - var n = 100000; - var inputs = [ + // Inputs which made some version of the regexp polynomial, built from n repetitions + function buildInputs (n) { + return [ 'url(' + ' '.repeat(n), 'url('.repeat(n), 'url("' + 'a'.repeat(n), @@ -435,11 +466,43 @@ describe('Parse css urls', function () { 'url(' + 'a\\\r\n'.repeat(n) + '"', 'url("' + '\\\r\n'.repeat(n), '"' + '\\\r'.repeat(n) + '\n', + 'url(/* ) */'.repeat(n), + 'url("a"/*)'.repeat(n) + '*', + '@namespace"'.repeat(n), + '@document ' + '\\"'.repeat(n), + '@document \'\\"a'.repeat(n) + '\'', + '\\"@namespace\\\r\n@'.repeat(n) + '/', + '@namespace\';@document"{'.repeat(n), + '@namespace ' + '"a" '.repeat(n) + '\'', Array.from({length: n}, function (_, i) { return 'url(' + i + '.png)'; }).join(' ') ]; - var start = Date.now(); - inputs.forEach(function (input) { parseCssUrls(input); }); - (Date.now() - start).should.be.below(1000); + } + + // Best of several runs, in milliseconds + function measure (input) { + var best = Infinity; + var i, start; + for (i = 0; i < 3; i++) { + start = process.hrtime.bigint(); + parseCssUrls(input); + best = Math.min(best, Number(process.hrtime.bigint() - start) / 1e6); + } + return best; + } + + it('should not backtrack catastrophically on malicious input', function () { + // Time is compared between two sizes instead of a fixed limit, so the result does not depend on the speed + // of the machine: for 4 times bigger input linear scan takes 4 times longer, quadratic one - 16 times + this.timeout(60000); + // Sizes are small enough for a quadratic scan to finish and fail the assertion instead of hanging + var small = buildInputs(5000); + var big = buildInputs(20000); + + small.forEach(function (input, i) { + var smallTime = measure(input); + var bigTime = measure(big[i]); + bigTime.should.be.below(smallTime * 8 + 10, 'input #' + i + ' ' + JSON.stringify(input.slice(0, 40))); + }); }); it('should not overflow regexp stack on very long tokens', function () {