Skip to content

fix: escape adjacent fallback raw-content text nodes as one run - #41

Open
SkyZeroZx wants to merge 1 commit into
angular:mainfrom
SkyZeroZx:fix/escape-text-nodes
Open

SkyZeroZx wants to merge 1 commit into
angular:mainfrom
SkyZeroZx:fix/escape-text-nodes

Conversation

@SkyZeroZx

@SkyZeroZx SkyZeroZx commented Aug 28, 2026 •

Copy link
Copy Markdown

Serialize adjacent Text and CDATA children of fallback raw-content elements (<noscript>, <iframe>, <noembed>, <noframes>) as one run. Closing tags and comment delimiters split across nodes are then escaped where the parser sees them. A run of Text and CDATA nodes is the largest span that can rebuild these tokens, because every other serialized node starts with <.

Escape an unterminated <!-- in fallback raw text too. Otherwise the comment stays open past the element's closing tag until a later -->, such as one in the JSON of the TransferState <script>, and that raw text becomes live HTML. This includes a comment opener split across text nodes, such as ['<!', '--'].

How it works:

  • serializeChildren() passes Text and CDATA nodes to an outlined serializeText() helper.
  • The helper checks the parent once, the same check serializeOne() used to make. It coalesces only inside fallback raw-content elements, and serializeChildren() carries on after the run.
  • serializeOne() still serializes one node.
  • The walk over the ancestors runs only when the text contains <!--.

test/html5lib-tests.json updates only the 16 cases with an unterminated <!-- in fallback raw text. Running update-html5lib-tests.js on the whole file would also rewrite 15 unrelated entries that are already stale on main.

Instructions per serialization, measured with perf stat. An A/A copy of main stays within ±0.8%.

vs main
WPT corpus, HTML only (259 docs) -2.1%
WPT corpus, SVG/MathML (34 docs) -0.3%
2,000 single-child <noscript> -28%
<noscript> with a 5,000-node @for run -78%
2,000 spans with three adjacent text nodes each -0.7%

Fixes angular/angular#70462

@SkyZeroZx
SkyZeroZx force-pushed the fix/escape-text-nodes branch 2 times, most recently from fd09099 to 6652148 Compare September 10, 2026 15:48
@SkyZeroZx

Copy link
Copy Markdown
Author

@alan-agius4 , Sorry to bother you , I think this is ready to merge

@alan-agius4

Copy link
Copy Markdown

Thanks for putting this together — the fix is clean, well-scoped, and performs well (0% overhead on normal HTML and actually ~4.5× faster with ~45% less memory than main on long adjacent text-node runs).

Just one security issue to address before merging, plus a small perf/architecture suggestion and a few minor nits:

1. Escape unterminated <!-- in escapeFallbackRawText() (blocking)

Coalescing adjacent text nodes fixes </tag synthesis across siblings, but introduces a subtle regression for split comment openers like [Text('<!'), Text('--')]. On main those were escaped to &lt;!--, whereas coalescing turns them into '<!--', hits commentEnd === -1 in escapeFallbackRawText(), and emits a raw unterminated <!--.

That leaks HTML comment state past </noscript> until a later --> (for example inside Angular's <script id="ng-state" type="application/json"> TransferState or a <style> block) closes it and turns inert raw text into live HTML — e.g.:

  • <svg><noscript>[Text('<!'), Text('--')]</noscript></svg><script type="application/json">{"x":"--><img src=x onerror=alert(1)>"}</script> (triggers even with JS enabled in Chrome)
  • <noscript>[Text('<!'), Text('--')]</noscript><script id="ng-state" type="application/json">{"a":"--></noscript><img src=x onerror=alert(1)>"}</script> (triggers on JS-disabled / DOMParser / SSR round-trip)

Escaping unterminated <!-- directly in escapeFallbackRawText() closes all of these while keeping complete comments (including split ['<!-- fall', 'back comment -->']) intact:

 const commentEnd = findCommentEnd(rawText, commentStart + 4);
 if (commentEnd === -1) {
-  result += escapeMatchingClosingTags(rawText.slice(commentStart), parentTag, ancestorTags);
+  result += escape(rawText.slice(commentStart));
   break;
 }

(This will just need syncing the 4 unterminated-<!-- entries in test/tools/update-html5lib-tests.js / test/html5lib-tests.json, and testing both terminated <!--</noscript ...--> and unterminated ['<!', '--'] cases in test/xss.js.)

2. Performance & serializeOne() contract

Since this PR was branched before a0d9c35 moved serializeChildren() into lib/NodeUtils.js, coalescing currently lives inside serializeOne(). That breaks single-node semantics for direct serializeOne(secondTextNode, noscript) calls (returns ''), re-enters serializeOne() N - 1 extra times for an N-node run, and adds ~5–6% overhead on single-child <noscript> elements from the extra previousSibling / nextSibling getter lookups.

Two clean options here:

  • Preferred: Keep serializeOne() single-node and handle adjacent fallback text runs via a separate outlined helper called from serializeChildren() (advancing kid past the coalesced run — just be careful not to inline the coalescing loop into serializeChildren() or add fields to stack frames so V8 doesn't regress normal HTML). That keeps 0% overhead on pure HTML, beats main on single-child <noscript>, and is ~4× faster than the current PR on large @for runs.
  • Minimal alternative: If keeping coalescing in serializeOne(), add a kid._nextSibling === kid single-child fast-path (Domino's circular sibling list invariant) to avoid the getter lookups on single-child fallback elements.

Also, as a small bonus perf win: fallbackRawContentTags(parent.parentNode) can be computed lazily inside escapeFallbackRawText() only when rawText.includes('<!--'), skipping the ancestor walk on plain text runs.

3. Minor nits

  • Naming: isCharacterDataNode / coalesceCharacterData is a bit misleading since Comment and ProcessingInstruction also inherit from CharacterData in Domino (lib/CharacterData.js). isTextOrCDataNode / coalesceTextData would be clearer.
  • test/xss.js cleanup:
    • Group all 6 new tests together at the end of test/xss.js (currently the first 3 are inserted in the middle of the escapableRawText* tests).
    • Remove the unused async on fallbackRawTextEscapesAncestorClosingTagSplitAcrossTextNodes and the vacuous content.should.not.containEql('</' + tag) check (tag !== ancestorTag).
    • You can trim the cut loops in the exhaustive tests to 0..('<!--</' + tag).length (plus payload.length) and hoist the constant domino.createDocument reparse out of the inner loop.
    • Worth adding fast unit cases (no extra Puppeteer pages needed) for <textarea>/<title> ancestors with split closing tags, <noscript><template><iframe>, split abrupt closes (<!--+>, <!--+->) / --!>, and an empty Text('') node between split pieces.

Serialize adjacent Text and CDATA children of fallback raw-content elements as one run, so closing tags and comment delimiters split across nodes are escaped where the parser sees them. A run of Text and CDATA nodes is the largest span that can reconstruct these tokens, because every other serialized node starts with `<`.

Escape an unterminated `<!--` in fallback raw text as well. It would keep the comment open past the closing tag of the element until a later `-->`, such as one in the JSON of the TransferState script, and turn that raw text into live HTML.
@SkyZeroZx
SkyZeroZx force-pushed the fix/escape-text-nodes branch from 6652148 to b4622d1 Compare November 27, 2026 14:41
@SkyZeroZx

Copy link
Copy Markdown
Author

Thanks for the review. Everything is addressed in b4622d1, which is rebased on main so the coalescing can live in serializeChildren().

1. Unterminated <!--. It is now escape()d, as you suggested. I synced update-html5lib-tests.js and html5lib-tests.json: 16 cases across noscript, noframes, iframe and noembed, and only those, because 15 other entries are already stale on main. test/xss.js now covers:

  • the terminated split <!--</nosc + ript -->;
  • the unterminated openers ['<!', '--'], ['<', '!--'] and ['<!-', '-'];
  • both of your examples.

The <svg><noscript> one does fire alert in Chrome on the previous head. It is inert now.

2. Perf / serializeOne(). I took the preferred option, with one change. Any check in the serializeChildren() loop that reads parent or kid.nextSibling for every text node cost +8% to +11% instructions on the WPT corpus, almost all of it in LoadIC_Megamorphic. That held even with the check order tuned, and with the fallback test moved to the push. So the loop now passes Text and CDATA nodes to an outlined serializeText(kid, parent, coalesce):

  • It makes the same single parent check that serializeOne() made.
  • It coalesces only in the fallback branch.
  • serializeChildren() continues after the run.

serializeOne() calls it with coalesce = false, so it is single-node again. The ancestor walk only runs when the text contains <!--.

Instructions per serialization, measured with perf stat. An A/A copy of main stays within ±0.8%:

  • WPT HTML: -2.1%
  • WPT SVG/MathML: -0.3%
  • single-child <noscript>: -28%
  • 5,000-node @for run in a <noscript>: -78%, about 1.5× fewer instructions than the previous head
  • adjacent text nodes in ordinary elements: -0.7%

3. Nits. All done:

  • renamed to isTextOrCDataNode / coalesceTextData;
  • the new tests are grouped at the end;
  • removed the async and the vacuous check;
  • trimmed the cuts and hoisted the reparse;
  • added fast cases for <textarea>/<title> ancestors, <noscript><template><iframe>, split <!--+>, <!--+-> and --!>, and an empty Text('') inside a run.

One observation: with (1) in place, escaping one node at a time is already safe. A fuzz over 200k random fallback trees found no closing tag of the element or its ancestors and no comment left open. What coalescing adds is that a comment split across nodes stays a comment, and it is faster.

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.

Angular SSR can reconstruct fallback RAWTEXT closing tags across Text nodes

2 participants