Skip to content

Fix ReDoS and edge cases in CSS url regexp - #93

Draft
aivus wants to merge 7 commits into
masterfrom
fix/regexp-redos-and-edge-cases
Draft

aivus wants to merge 7 commits into
masterfrom
fix/regexp-redos-and-edge-cases

Conversation

@aivus

@aivus aivus commented Dec 2, 2026 •

Copy link
Copy Markdown
Member

Summary

ReDoS (most important)

The url() branch url\s*\(\s*(...|(.*?))\s*\) allowed \s*, the lazy (.*?), and the trailing \s* to all consume the same whitespace, so unterminated input backtracked cubically. This package parses untrusted CSS from scraped sites:

Input Before After
url( + 2,000 spaces 1.1 s <5 ms
url( + 8,000 spaces 71 s <5 ms
100,000 distinct url(N.png) entries ~7.3 s ~25 ms

The regexp is now built from mutually exclusive character classes (unquoted content can't start/end with whitespace), so matching is linear. Deduplication uses a lookup map instead of indexOf, so many distinct URLs are linear too.

Long tokens

Loops in the regexp are unrolled ([^"\\]*(?:\\.[^"\\]*)* 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 would throw RangeError: Maximum call stack size exceeded on a single token longer than ~8M characters (e.g. an embedded font in url(data:...)). This is not a bug of the released version, only a constraint on how the new regexp is written; 10M-character tokens are covered by a test.

Correctness fixes

Input Before After
@import "a.css" (end of input) [] a.css
@import"a.css"; [] a.css
@import "a.css"screen; "a.css"screen a.css
my-url(evil.png) evil.png []
url(a\).png) a\ a\).png
url("a.png) (unclosed) "a.png —
url("x/*y*/z.png") xz.png x/*y*/z.png
url(x/*y*/z.png) (unquoted) xz.png x/*y*/z.png
content:"/*" … url(keep.png) … /* */ [] keep.png
url(DATA:image/png;...) returned ignored
url(a.png) /* url(b.png) (unterminated comment) a.png, b.png a.png (comment runs to end of input, per CSS spec)
content:"see url(foo.png)" foo.png []
[data-x="url(q.png)"] q.png []
url(a'b.png) (quote in unquoted url) a'b.png []
@namespace url(http://www.w3.org/1999/xhtml); returned []
@document url(http://example.com/) { .a{background:url(a.png)} } both a.png

Behaviour changes to be aware of

  • url(...) and @import text inside ordinary strings and attribute selectors is no longer returned.
  • An unquoted url() containing a quote (url(a'b.png), url(it's.png)) is invalid per the CSS spec and is now skipped as a whole, up to its closing parenthesis, instead of returning the raw body.
  • url(...) in @namespace and in the prelude of @document / @-moz-document is no longer returned: it is not a resource to load. Urls in the rules inside @document { ... } are still returned.
  • Non-string input still throws TypeError (now explicitly; before it came from text.replace).
  • Invalid CSS is treated as invalid: the result for it follows the CSS spec where practical, but recall on malformed input is not a goal.

Notes

  • The text is scanned in a single pass by one regexp that works as a tokenizer. At each position it matches either a token with a URL (url(...), @import ...) or a token to skip as a whole: a comment, a string, or an identifier (including backslash escapes). There is no separate comment-stripping pass, so /* inside strings and inside the value of url() is not treated as a comment, and escaped quotes in selectors (e.g. .content-\[\'\'\]) do not start a string.
  • Comments around the value inside url(...) are skipped: url("a.png" /* c */), url(/* c */ "a.png"), url( /* c */ a.png ). For an unquoted value the comment has to be separated from it by whitespace; /* glued to the value is a part of it, so url(http://example.com/*/a.png) and url(x/*y*/z.png) are returned as is.
  • An unterminated string ends at a newline (\n, \r or \f) or end of input, and an unterminated comment at end of input (as in the CSS spec). An escaped \r\n is a single line continuation, so CRLF stylesheets do not desynchronise the tokenizer.
  • my-url( is skipped because the identifier token consumes the whole name. No regexp lookbehind is used, so the supported runtimes do not change.
  • Comments between @import and its URL are allowed (@import/**/url(a.css), @import /* c */ "b.css"), as is whitespace before the parenthesis (@import url ("a.css")).
  • The unquoted @import path form does not allow @ in the path, so a path cannot run across following @import rules and be rescanned from each of them (this was quadratic: ~1.9 s for a 190 KB input, now ~3 ms). @import foo@2x.css; (unquoted, not valid CSS) therefore no longer matches; the quoted form is unaffected.
  • Escapes are respected while matching, but returned URLs are not unescaped. This keeps them identical to the source text, so consumers (e.g. website-scraper) that search for and replace them in the CSS keep working.

Test plan

  • All 23 original tests pass (only lint formatting changed in them)
  • 36 new regression tests (59 in total, 100% coverage)
  • Timing test with 47 adversarial inputs: each is parsed at two sizes and the 4x bigger one must not take more than ~8x longer, so the test does not depend on the speed of the machine (it fails on the earlier quadratic versions of the regexp)
  • Test with 10M-character tokens (regexp stack overflow)
  • npm run eslint clean; it now lints test as well as lib and index.js
  • Test files get a mocha ESLint override (env: mocha, func-names: off)

🤖 Generated with Claude Code

aivus and others added 2 commits December 2, 2026 22:45
- 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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
Comment thread lib/css-parser.js Fixed
aivus and others added 5 commits December 2, 2026 22:49
- 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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
- 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 <noreply@anthropic.com>
- 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 <noreply@anthropic.com>
@aivus
aivus marked this pull request as draft December 3, 2026 08:30
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants