Skip to content

[lexical][lexical-extension][lexical-markdown][lexical-playground][lexical-yjs] Bug Fix: Linear-time regexes, prototype-pollution guards, and faster CSS parsing - #8593

Merged
etrepum merged 4 commits into
meta:mainfrom
etrepum:claude/friendly-ramanujan-3CtZv
May 30, 2026

Conversation

@etrepum

@etrepum etrepum commented May 30, 2026 •

Copy link
Copy Markdown
Collaborator

Description

This PR audits the library for two classes of issue — polynomial-time (ReDoS) regular expressions and prototype pollution — fixes them, de-duplicates a parser, and speeds up CSS parsing. All regex work stays within Safari 15+ syntax (no atomic groups, possessive quantifiers, or lookbehind), and every change preserves existing behavior, verified by differential testing against the originals.

Polynomial-time regexes → linear

Each offender was confirmed empirically (clean O(n²) scaling on adversarial input) and rewritten to run in linear time.

Regex Location Worst case before → after Fix
IMPORTANT_REG_EXP /\s*!important\s*$/i lexical (setDOMStyle, runs on every applied style value) ~1.3s → <1ms @32k chars trimEnd + slice, no regex
EMAIL_REGEX lexical-playground AutoLink ~1.45s → ~12ms @16k chars bounded quantifiers (RFC-generous)
urlRegExp (Stack Overflow URL regex) lexical-playground validateUrl ~0.47s → ~28ms @16k chars bounded quantifiers
TABLE_ROW_DIVIDER_REG_EXP /^(| ?:?-*:? ?)+|\s?$/ lexical-markdown + playground linear in V8, but -* nested in (...)+ can backtrack under Safari/JavaScriptCore guaranteed-O(n) manual scan isTableRowDivider

The LINK import/export regexes, CODE_SINGLE_LINE_REGEX, and the AutoLink URL_REGEX were also benchmarked and confirmed linear, so they are left unchanged.

Prototype pollution

  • deepThemeMergeInPlace (@lexical/extension): a __proto__ key from JSON.parse leaked into Object.prototype globally; the recursive merge now skips __proto__/constructor/prototype and only copies own keys.
  • LexicalNodeState (core) and SyncV2 (collab-v2): unknown-state deserialization wrote keys straight from serialized JSON, so a crafted {"$":{"__proto__":{…}}} re-parented the record. Because getValue resolves keys with the in operator (which walks the prototype chain), this allowed state injection — $getState returned the attacker's value instead of the default. Both write sites now skip the dangerous keys, and the Yjs importer applies the same guard to remote property attributes (its state attributes already route through the guarded NodeState path).
  • Other dynamic-key writes were reviewed and are safe: object spread never fires the __proto__ setter; Map/YMap.set/setAttribute/setData/setProperty take string arguments; style writes only ever store strings; and the remaining computed keys are dev-controlled (node types, transformer tags, createState keys).

Refactor

isTableRowDivider is now exported from @lexical/markdown and reused by the playground instead of being duplicated.

Performance: getStyleObjectFromCSS

The parser built the current property/value by appending one character at a time; it now accumulates contiguous runs with slice, flushing only at dropped characters (comments) and delimiters (:/;). Throughput improves ~33% on typical inline styles and ~3.3× on very long values (~372ms → ~102ms for a 200k-char value), with byte-identical output.

Test plan

Before

  • IMPORTANT_REG_EXP on whitespace-only input scaled quadratically (21ms → 83ms → 329ms → 1303ms as N doubled 4k → 8k → 16k → 32k); EMAIL_REGEX and urlRegExp showed the same O(n²) curve on adversarial input.
  • deepThemeMergeInPlace(target, JSON.parse('{"__proto__":{"polluted":"YES"}}')) set ({}).polluted === 'YES' (global pollution), and importing {"$":{"__proto__":{"injectedKey":"evil"}}} made $getState(node, injectedKeyState) return 'evil' instead of the default.
  • getStyleObjectFromCSS built values via per-character concatenation (~372ms for a single 200k-char value).

After

  • All four regexes scale linearly; the replacements were re-benchmarked (e.g. IMPORTANT ~1303ms → <0.1ms @32k, CSS long-value ~372ms → ~102ms).
  • Behavior is proven identical by differential testing against the originals: 2.2M exhaustive table-divider cases plus 60k–200k random/adversarial inputs each for the !important strip, email/url regexes, and CSS parser — 0 mismatches; the email/URL corpora include every address/URL the e2e suite asserts.
  • New regression unit tests: prototype-pollution guards for deepThemeMergeInPlace and NodeState (the latter fails without the fix), and CSS-parser edge cases (comments mid-value, escaped quotes, and :/; inside parentheses).
  • pnpm tsc passes monorepo-wide; ESLint and Prettier are clean; existing unit suites for the touched packages pass (setDOMStyle, MarkdownTransformers, LexicalMarkdown, LexicalNodeState, LinkExtension, HTMLCopyAndPaste, deepThemeMergeInPlace, LexicalBuilder).

…rf/Security: Remove polynomial-time regexes and guard against prototype pollution

Audited the library for ReDoS-prone (polynomial-time) regular expressions
and confirmed the offenders empirically (clean O(n^2) scaling on adversarial
input). Refactored each one to run in linear time; behavior is preserved and
verified by differential testing (2.5M+ inputs, incl. an exhaustive sweep for
the table-divider). Constrained to Safari 15+ syntax (no atomic groups,
possessive quantifiers, or lookbehind).

- lexical (setDOMStyle): `/\s*!important\s*$/i` was O(n^2) on whitespace-heavy
  style values (it runs on every applied style). Replaced with trimEnd + slice.
- lexical-markdown / lexical-playground (markdown table divider): replaced
  `/^(\| ?:?-*:? ?)+\|\s?$/` (a `-*` nested inside `(...)+`, which JSC may run
  super-linearly) with a guaranteed-O(n) manual scan, `isTableRowDivider`.
- lexical-playground (AutoLink email matcher, url validator): the unbounded
  `+`/`*` quantifiers backtracked in O(n^2) under RegExp.exec; bounded them to
  RFC-generous limits so every realistic address/URL still matches.

Also fixed a prototype-pollution sink in deepThemeMergeInPlace: a malicious
`__proto__` key (e.g. from JSON.parse) leaked into Object.prototype. The merge
now skips `__proto__`/`constructor`/`prototype` and only copies own keys, with
regression tests.

https://claude.ai/code/session_019a6JqhMNpfJ1o2UgtidAXg
@vercel

vercel Bot commented May 30, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
lexical Ready Ready Preview, Comment May 30, 2026 6:33am
lexical-playground Ready Ready Preview, Comment May 30, 2026 6:33am

Request Review

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed. label May 30, 2026
claude added 3 commits May 30, 2026 06:24
…oto__ in serialized node state

Editor-state deserialization wrote unknown-state keys straight from
serialized (potentially untrusted) JSON into a plain object:
`this.unknownState[k] = v`. A crafted `{"$":{"__proto__":{...}}}` —
`__proto__` is an own enumerable key once it comes through JSON.parse —
re-parented the record. Because NodeState.getValue resolves keys with the
`in` operator (which walks the prototype chain), an attacker could inject
arbitrary state values: importing `{"__proto__":{"someKey":"evil"}}` made
`$getState(node, someKeyState)` return "evil" instead of the default.

NodeState now skips `__proto__`/`constructor`/`prototype` (never valid
createState keys) at both write sites (updateFromUnknown and
parseAndPruneNextUnknownState). The collab-v2 Yjs importer (SyncV2) applies
the same guard to remote property attributes; its state attributes already
route through the guarded NodeState path. Added a regression test that
fails without the guard.

https://claude.ai/code/session_019a6JqhMNpfJ1o2UgtidAXg
…bleRowDivider parser

The Markdown table-delimiter scan was duplicated in lexical-markdown and the
playground's custom transformer set. Export `isTableRowDivider` from
`@lexical/markdown` and reuse it in the playground instead of keeping a second
copy.

https://claude.ai/code/session_019a6JqhMNpfJ1o2UgtidAXg
The CSS parser built the current property/value by appending one character at
a time (`currentValue += char`), which is slow for long values. Accumulate
contiguous runs with `slice` instead, flushing only at dropped characters
(comments) and delimiters (`:`/`;`). Behavior is unchanged (verified identical
across 200k+ random and edge-case inputs); throughput improves ~33% on typical
inline styles and ~3.3x on very long values. Added regression tests covering
comments mid-value, escaped quotes, and ':'/';' inside parentheses.

https://claude.ai/code/session_019a6JqhMNpfJ1o2UgtidAXg
@etrepum etrepum changed the title [lexical][lexical-markdown][lexical-playground][lexical-extension] Perf/Security: Remove polynomial-time regexes and guard against prototype pollution [lexical][lexical-extension][lexical-markdown][lexical-playground][lexical-yjs] Bug Fix: Linear-time regexes, prototype-pollution guards, and faster CSS parsing May 30, 2026
@etrepum etrepum added the extended-tests Run extended e2e tests on a PR label May 30, 2026
@etrepum
etrepum marked this pull request as ready for review May 30, 2026 07:24
@potatowagon

Copy link
Copy Markdown
Contributor

Review: Linear-Time Regexes, Prototype-Pollution Guards, and Faster CSS Parsing

Reviewed by: Navi (AI review assistant for @potatowagon)

Summary

A security and performance hardening PR that addresses three categories of issues:

  1. ReDoS mitigation — Replaces regex patterns with nested quantifiers ((-*)+, ([^...]+)*) that could backtrack in O(n²) or worse with linear-time alternatives:

    • TABLE_ROW_DIVIDER_REG_EXP → manual isTableRowDivider() scan (guaranteed O(n))
    • EMAIL_REGEX → bounded quantifiers ({1,64}, {0,63}, {1,127}) matching RFC 5321 limits
    • urlRegExp → capped runs at 256 characters
  2. Prototype pollution guards — Prevents __proto__, constructor, prototype keys from being merged/assigned in:

    • deepThemeMergeInPlace (theme merging from potentially untrusted JSON)
    • LexicalNodeState (updateFromUnknown, parseAndPruneNextUnknownState)
    • SyncV2.ts (Yjs collaborative editing — remote attrs from untrusted peers)
  3. CSS parser optimization — getStyleObjectFromCSS rewritten to accumulate slices via chunkStart index instead of per-character string concatenation, reducing from O(n²) to O(n). Also replaces regex-based !important detection with simple string suffix check.

What I Verified

  • isTableRowDivider correctness: The manual scan correctly mirrors the original regex semantics — requires leading |, parses ?:?-*:? ?| cells, requires ≥1 cell, allows optional trailing whitespace. The function is exported and reused in the playground's MarkdownTransformers.
  • Prototype pollution guards: UNSAFE_KEYS set approach is correct and comprehensive. The Yjs SyncV2.ts guard uses inline check rather than Set (fine for 3 keys). Tests cover JSON.parse-produced __proto__ (which creates an own enumerable property, unlike object literals).
  • CSS parser refactor: The chunkStart slice-flushing pattern is a well-known optimization. Flush points (comments, delimiters) are correctly handled. No behavioral change to output.
  • Email regex bounds: {1,64} local part, {1,63} DNS labels, {1,127} subdomains — all comfortably exceed RFC 5321 maximums while preventing catastrophic backtracking.
  • Test coverage: New tests for prototype pollution in deepThemeMergeInPlace, LexicalNodeState, and setDOMStyle (CSS parser).
  • CI: ALL checks green (30+ jobs including all e2e suites across Chrome, Firefox, WebKit on Linux, macOS, Windows). No regressions.

Recommendation

Approve ✅ — This is a well-crafted security/performance hardening PR from a maintainer. All changes are correctness-preserving, well-tested, and CI is fully green. The prototype pollution guards are particularly important for collaborative editing scenarios where remote peers could inject malicious payloads.


— via Navi on behalf of @potatowagon

@etrepum
etrepum added this pull request to the merge queue May 30, 2026
Merged via the queue into meta:main with commit 495ce82 May 30, 2026
63 of 64 checks passed
etrepum pushed a commit to etrepum/lexical that referenced this pull request May 30, 2026
Picks up meta#8593 (linear-time regexes / prototype-pollution guards /
faster CSS parsing) and meta#8598 (TabNode.setTextContent Safari IME
fix) — both touch lexical/extension/markdown/playground/yjs and
don't intersect with the release tooling on this branch, so the
merge is clean.

https://claude.ai/code/session_01UEAeW4ZkfApZnrJTGc6Xm9
@etrepum etrepum mentioned this pull request Jun 25, 2026

This branch was successfully deployed

2 active deployments
Preview – lexical — 70ccb8f5 Deployed May 30, 2026 by vercel[bot]
Preview – lexical-playground — 70ccb8f5 Deployed May 30, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed. extended-tests Run extended e2e tests on a PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants