Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

fix(security): sanitize search snippets after highlighting, not before (#6231)

LearningCircuit6d80630c49d3
diff --git a/changelog.d/+semantic-snippet-highlight-order.security.md b/changelog.d/+semantic-snippet-highlight-order.security.md
new file mode 100644
index 0000000000..f6eda88ff0
--- /dev/null
+++ b/changelog.d/+semantic-snippet-highlight-order.security.md
@@ -0,0 +1 @@
+Fixed an XSS in search-result snippets on the history, library-search, news and collection-details (`GET /collections/{id}`) pages: query-term highlighting ran *after* DOMPurify, so a crafted snippet could reopen an attribute the sanitizer had closed and revive markup it had already neutralized. Highlighting now runs before the sanitize pass, leaving DOMPurify as the last step; normal highlighting is unchanged.
diff --git a/src/local_deep_research/web/static/js/components/history.js b/src/local_deep_research/web/static/js/components/history.js
index 0f96f2d571..e11afdd31b 100644
--- a/src/local_deep_research/web/static/js/components/history.js
+++ b/src/local_deep_research/web/static/js/components/history.js
@@ -589,8 +589,14 @@
${semanticMatch.snippet ? `<div class="ldr-history-item-snippet">${renderSnippet(semanticMatch.snippet, searchInput ? searchInput.value.trim() : '')}</div>` : ''}
` : '';
+ // Re-audited 2026-09-04: every interpolation below is esc()'d or
+ // numeric EXCEPT the snippet, which is DOMPurify output from
+ // SemanticSearch.renderSnippet(). That helper now sanitizes as its
+ // LAST step -- it previously highlighted afterwards, which could
+ // reopen a closed attribute -- so the value assigned here is
+ // sanitizer output that nothing has modified since.
// bearer:disable javascript_lang_dangerous_insert_html
- // eslint-disable-next-line no-unsanitized/property -- audited 2026-03-28: variable built from escaped/numeric values above
+ // eslint-disable-next-line no-unsanitized/property -- re-audited 2026-09-04: esc()'d/numeric, plus sanitizer-last renderSnippet output (see above)
itemEl.innerHTML = `
<div class="ldr-history-item-header">
<div class="ldr-history-item-title">${esc(displayTitle)}</div>
@@ -730,8 +736,14 @@
}
}
+ // Re-audited 2026-09-04: every interpolation below is esc()'d,
+ // numeric, or a hardcoded string EXCEPT the snippet, which is
+ // DOMPurify output from SemanticSearch.renderSnippet(). That helper
+ // now sanitizes as its LAST step -- it previously highlighted
+ // afterwards, which could reopen a closed attribute -- so the value
+ // assigned here is sanitizer output that nothing has modified since.
// bearer:disable javascript_lang_dangerous_insert_html
- // eslint-disable-next-line no-unsanitized/property -- audited 2026-03-28: all interpolations use escapeHtml/esc, numeric coercion, or hardcoded strings
+ // eslint-disable-next-line no-unsanitized/property -- re-audited 2026-09-04: esc()'d/numeric/literal, plus sanitizer-last renderSnippet output (see above)
itemEl.innerHTML = `
<div class="ldr-history-item-header">
<div class="ldr-history-item-title">${esc(displayTitle)}</div>
diff --git a/src/local_deep_research/web/static/js/components/library_search_ui.js b/src/local_deep_research/web/static/js/components/library_search_ui.js
index f200bb40e9..fded9f26c8 100644
--- a/src/local_deep_research/web/static/js/components/library_search_ui.js
+++ b/src/local_deep_research/web/static/js/components/library_search_ui.js
@@ -321,8 +321,15 @@ function renderMergedLibraryResults(tiered, query) {
if (existing) existing.remove();
const snippetDiv = document.createElement('div');
snippetDiv.className = 'ldr-library-snippet';
+ // Re-audited 2026-09-04: every interpolation here is a
+ // hardcoded string EXCEPT the snippet, which is DOMPurify
+ // output from SemanticSearch.renderSnippet(). That helper
+ // now sanitizes as its LAST step -- it previously
+ // highlighted afterwards, which could reopen a closed
+ // attribute -- so the value assigned here is sanitizer
+ // output that nothing has modified since.
// bearer:disable javascript_lang_dangerous_insert_html
- // eslint-disable-next-line no-unsanitized/property -- audited 2026-03-28: all interpolations use escapeHtml/esc, numeric coercion, or hardcoded strings
+ // eslint-disable-next-line no-unsanitized/property -- re-audited 2026-09-04: literals, plus sanitizer-last renderSnippet output (see above)
snippetDiv.innerHTML = '<small class="text-muted"><i class="fas fa-brain" aria-hidden="true"></i> Matched content:</small>' +
'<div>' + renderSnippet(entry.semanticMatch.snippet, query) + '</div>';
const body = card.querySelector('.card-body');
diff --git a/src/local_deep_research/web/static/js/components/semantic_search.js b/src/local_deep_research/web/static/js/components/semantic_search.js
index a145bf9d89..a8a90081c1 100644
--- a/src/local_deep_research/web/static/js/components/semantic_search.js
+++ b/src/local_deep_research/web/static/js/components/semantic_search.js
@@ -25,29 +25,55 @@ function renderSnippet(md, query) {
let html;
if (window.marked && window.DOMPurify) {
html = window.marked.parseInline(String(md));
+ // ORDER IS LOAD-BEARING: highlight BEFORE sanitizing, never after.
+ //
+ // highlightTerms() splits HTML with the regex /(<[^>]*>)|([^<]+)/,
+ // which treats the first ">" as ending a tag. HTML attribute values
+ // are NOT ">"-escaped when serialized, so a value containing ">"
+ // (e.g. a title="...") makes the regex see a tag boundary that the
+ // real parser does not, and the <mark> it then injects supplies the
+ // quote that closes the attribute for real. Running that surgery on
+ // sanitizer OUTPUT therefore reintroduces markup DOMPurify had
+ // already decided was safe, turning inert attribute text into live
+ // elements. Sanitizing last means any boundary the highlighter
+ // breaks is repaired (or dropped) before the string reaches a
+ // caller's innerHTML.
+ //
+ // "mark" and "class" are in the allowlists below, so the highlight
+ // itself survives the pass.
+ if (query) {
+ html = highlightTerms(html, query);
+ }
html = window.DOMPurify.sanitize(html, {
ALLOWED_TAGS: ['b', 'i', 'em', 'strong', 'span', 'a', 'code', 'br', 'p', 'ul', 'ol', 'li', 'mark'],
ALLOWED_ATTR: ['href', 'title', 'class'],
ALLOW_DATA_ATTR: false,
});
- } else {
- html = esc(md);
- // Skip highlightTerms in fallback path: injecting <mark> into
- // esc'd text would produce garbled entities like &lt;<mark>b</mark>&gt;
return html;
}
- if (query) {
- html = highlightTerms(html, query);
- }
- return html;
+ // Fallback path: no sanitizer available, so the snippet is escaped
+ // wholesale and highlightTerms is skipped -- injecting <mark> into
+ // esc'd text would produce garbled entities like &lt;<mark>b</mark>&gt;,
+ // and there would be no sanitizer pass afterwards to repair a broken
+ // boundary.
+ return esc(md);
}
/**
* Highlight query terms in an HTML string by wrapping matches in <mark> tags.
- * Only operates on text between HTML tags to avoid breaking markup.
- * @param {string} html - HTML string
+ *
+ * SECURITY: never call this on the OUTPUT of a sanitizer. The tag-splitting
+ * regex below treats the first ">" as ending a tag, but HTML serialization
+ * does not escape ">" inside attribute values -- so an attribute containing
+ * ">" desynchronizes this function's view of the markup from the real
+ * parser's, and the <mark> injected at that point can close the attribute
+ * and introduce live elements. Callers must sanitize AFTER highlighting, so
+ * that any boundary broken here is repaired before the string is assigned to
+ * innerHTML. See renderSnippet(), which is the only intended caller.
+ *
+ * @param {string} html - HTML string, NOT yet sanitized
* @param {string} query - search query (split into words, each highlighted)
- * @returns {string} HTML with <mark> wrapped terms
+ * @returns {string} HTML with <mark> wrapped terms; must still be sanitized
*/
function highlightTerms(html, query) {
if (!html || !query) return html;
@@ -217,8 +243,22 @@ function createSemanticResultCard(result, config, query) {
}
}
+ // Re-audited 2026-09-04: every interpolation below is esc()'d or a
+ // hardcoded string EXCEPT the snippet, which is DOMPurify output from
+ // renderSnippet() above. That helper now sanitizes as its LAST step --
+ // it previously highlighted afterwards, which could reopen a closed
+ // attribute -- so the value assigned here is sanitizer output that
+ // nothing has modified since. Six callers append this card verbatim,
+ // with no re-sanitize of their own: the library tier-3 list
+ // (library_search_ui.js), both news search paths and its own tier-3
+ // list (news.js), collection-details search results
+ // (collection_details.js), library search (library_search.js), and
+ // history search (history_search.js). A third tier-3 list, in
+ // history.js, does not call this function at all -- it builds its own
+ // card via createSemanticOnlyElement(), audited separately there. So
+ // this assignment is the last sanitizing step for those six callers.
// bearer:disable javascript_lang_dangerous_insert_html
- // eslint-disable-next-line no-unsanitized/property -- audited 2026-03-28: all interpolations use escapeHtml/esc, numeric coercion, or hardcoded strings
+ // eslint-disable-next-line no-unsanitized/property -- re-audited 2026-09-04: esc()'d/literal, plus sanitizer-last renderSnippet output (see above)
card.innerHTML = `
<div class="ldr-semantic-result-header">
<div>
@@ -272,7 +312,6 @@ function isSafeExternalUrl(url) {
// Expose shared API
window.SemanticSearch = {
renderSnippet,
- highlightTerms,
buildTieredResults,
flattenTieredResults,
createSemanticResultCard,
diff --git a/tests/js/security/snippet-highlight-order.test.js b/tests/js/security/snippet-highlight-order.test.js
new file mode 100644
index 0000000000..5443882aa9
--- /dev/null
+++ b/tests/js/security/snippet-highlight-order.test.js
@@ -0,0 +1,155 @@
+/**
+ * Regression tests for SemanticSearch.renderSnippet's sanitize ordering.
+ *
+ * renderSnippet() highlights query terms by injecting <mark> into an HTML
+ * string with a tag-splitting regex. That surgery MUST happen before the
+ * DOMPurify pass, never after: HTML serialization does not escape ">" inside
+ * attribute values, so an attribute containing ">" desynchronizes the
+ * highlighter's view of the markup from the real parser's, and the <mark> it
+ * injects at that point supplies the quote that closes the attribute for real.
+ *
+ * Running the highlighter on sanitizer OUTPUT therefore reintroduces markup
+ * DOMPurify had already neutralized. Four sinks assign renderSnippet output
+ * straight to innerHTML: components/history.js (twice),
+ * components/library_search_ui.js, and createSemanticResultCard() in
+ * components/semantic_search.js itself — whose cards are appended verbatim,
+ * with no re-sanitize of their own, by six callers: the library tier-3 list
+ * and library search (components/library_search_ui.js,
+ * components/library_search.js), both news search paths and its own tier-3
+ * list (pages/news.js), collection-details search results
+ * (collection_details.js), and history search (components/history_search.js).
+ * A third tier-3 list, in components/history.js, does not call
+ * createSemanticResultCard() at all — it builds its own card, which is one
+ * of the two components/history.js sinks counted above. The only re-sanitize
+ * on the news page happens in renderNewsItems() (its safeRenderHTML() sink),
+ * which is reached from many call sites, not from a single "load" path.
+ *
+ * WHY THE PAYLOAD LOOKS INERT: marked escapes ">" to "&gt;" when it builds the
+ * title attribute, so the string handed to the sanitizer contains no raw ">".
+ * The round trip THROUGH DOMPurify is what creates one: parsing "&gt;" yields a
+ * ">" character in the attribute VALUE, and HTML serialization does not escape
+ * "<" or ">" inside attribute values (only "&", U+00A0 and the quote). Verified
+ * directly:
+ *
+ * in : <span title="A&gt;budget&lt;img src=x onerror=BOOM()&gt;B">hi</span>
+ * out : <span title="A>budget<img src=x onerror=BOOM()>B">hi</span>
+ *
+ * So the exposure exists only when highlighting runs AFTER sanitizing, which is
+ * exactly what these tests pin. Do not "simplify" the payload to a literal raw
+ * ">" — marked would escape it and the test would pass vacuously.
+ *
+ * WHY THE PAYLOAD STARTS WITH "**x** ": that leading <strong> is a sacrificial
+ * node, the same workaround tests/js/services/ui.test.js uses (see its
+ * "renders math alongside other markdown" case). DOMPurify >=3.4.8 reads
+ * element names through the cached Node.prototype.nodeName getter, and
+ * happy-dom's getter returns "" when invoked that way, so the FIRST top-level
+ * node of a sanitized fragment is treated as an unknown tag and unwrapped —
+ * tags dropped, text kept. Upstream: capricorn86/happy-dom#2182. Without the
+ * prefix the payload's <a> is the lone top-level node, gets unwrapped, and BOTH
+ * orderings collapse to "hi" — the tests would pass on vulnerable code. Real
+ * browsers are unaffected; this is a test-env artifact only. Do not remove it.
+ *
+ * WHAT THIS ENVIRONMENT CAN AND CANNOT SEE: the same happy-dom defect means
+ * DOMPurify's tag/attribute allow-lists are NOT enforced on the remaining
+ * top-level nodes here — only the first one is inspected. So nothing below can
+ * observe ALLOWED_TAGS/ALLOWED_ATTR; those are pinned from source instead, in
+ * tests/security/test_client_side_xss_sinks.py. What these tests DO observe is
+ * the property the fix actually turns on: DOMPurify re-parses and re-serializes
+ * the string, so a tag boundary the highlighter broke is repaired before the
+ * value reaches a caller — and running the highlighter afterwards instead
+ * breaks it again, unrepaired.
+ *
+ * ALSO NOTE: on correct code the literal text "onerror" DOES appear in the
+ * output, inert, inside the title attribute value. Assertions here are made at
+ * the DOM level (re-parse, then look for event-handler attributes and
+ * elements), never with a substring match on the serialized string.
+ *
+ * Each test below names the revert it catches.
+ */
+
+import DOMPurify from 'dompurify';
+import { marked } from 'marked';
+import '@js/components/semantic_search.js';
+
+const SS = window.SemanticSearch;
+
+/**
+ * A title attribute whose value contains ">" and a would-be element, behind a
+ * sacrificial leading node (see the happy-dom note in the file header).
+ */
+const ATTR_BOUNDARY_MD =
+ '**x** [hi](https://example.com "A>budget<img src=x onerror=BOOM()>B")';
+
+beforeAll(() => {
+ window.DOMPurify = DOMPurify;
+ window.marked = marked;
+});
+
+/** Re-parse an HTML string and return the host element. */
+function parse(html) {
+ const host = document.createElement('div');
+ // eslint-disable-next-line no-unsanitized/property -- test code
+ host.innerHTML = html;
+ return host;
+}
+
+/** Every event-handler attribute that survived a re-parse, as "TAG@attr". */
+function eventHandlers(html) {
+ return Array.from(parse(html).querySelectorAll('*')).flatMap((el) =>
+ Array.from(el.attributes)
+ .filter((a) => /^on/i.test(a.name))
+ .map((a) => `${el.tagName}@${a.name}`),
+ );
+}
+
+describe('renderSnippet sanitizes after highlighting', () => {
+ // CATCHES: moving the highlightTerms() call back after the
+ // DOMPurify.sanitize() call in renderSnippet(). Under the old order this
+ // output re-parses to <a title="A><mark ...>budget</mark><img src=x
+ // onerror=BOOM()>B"> — a live IMG@onerror.
+ it('does not let a ">" inside an attribute value smuggle an event handler', () => {
+ const out = SS.renderSnippet(ATTR_BOUNDARY_MD, 'budget');
+
+ // DOM-level, not a substring match: "onerror" legitimately appears as
+ // inert text inside the title attribute value on correct code.
+ expect(eventHandlers(out)).toEqual([]);
+ });
+
+ // CATCHES: the same revert, via the element rather than the attribute.
+ it('never emits an <img> from attribute-boundary confusion', () => {
+ const out = SS.renderSnippet(ATTR_BOUNDARY_MD, 'budget');
+ expect(parse(out).querySelector('img')).toBeNull();
+ });
+
+ // CATCHES: dropping the highlightTerms() call, or gating it off. It does
+ // NOT catch the ordering revert — on an ordinary snippet both orders
+ // produce the same <mark>; the two payload tests above are what pin order.
+ it('still highlights matching terms in ordinary snippets', () => {
+ const out = SS.renderSnippet('the budget report', 'budget');
+ expect(out).toMatch(/<mark[^>]*>budget<\/mark>/i);
+ });
+
+ // CATCHES: changing or dropping the highlight class that
+ // css/components/semantic-search.css styles. It does NOT catch removing
+ // 'mark'/'class' from the sanitizer allow-lists — see the note in the file
+ // header on why this environment cannot observe them; that revert is
+ // caught from source in tests/security/test_client_side_xss_sinks.py.
+ it('emits the highlight class the stylesheet keys off', () => {
+ const out = SS.renderSnippet('the budget report', 'budget');
+ expect(out).toMatch(/<mark class="ldr-search-highlight">/);
+ });
+
+ // CATCHES: reintroducing highlightTerms in the no-sanitizer fallback,
+ // where there is no pass afterwards to repair a broken boundary.
+ it('escapes wholesale and does not highlight when DOMPurify is absent', () => {
+ const saved = window.DOMPurify;
+ window.DOMPurify = undefined;
+ try {
+ const out = SS.renderSnippet('<b>budget</b>', 'budget');
+ expect(out).not.toMatch(/<mark/i);
+ expect(out).not.toMatch(/<b>/i);
+ } finally {
+ window.DOMPurify = saved;
+ }
+ });
+});
diff --git a/tests/security/test_client_side_xss_sinks.py b/tests/security/test_client_side_xss_sinks.py
index 17415571fb..78c4e42703 100644
--- a/tests/security/test_client_side_xss_sinks.py
+++ b/tests/security/test_client_side_xss_sinks.py
@@ -648,16 +648,56 @@ def test_fallback_markdown_renderer_emits_no_markup_from_input():
#: Rewriting a DOMPurify result with a regex re-opens what the sanitiser
-#: closed. The reviewed set is deliberately tiny; adding to it needs an
-#: argument, not a suppression comment.
-REVIEWED_POST_SANITISE_REWRITERS = {"components/semantic_search.js"}
+#: closed. The set is empty and must stay empty: ``renderSnippet`` used to
+#: be in it, and highlighting now runs *before* the sanitise pass. Adding
+#: to it needs an argument, not a suppression comment.
+REVIEWED_POST_SANITISE_REWRITERS: set[str] = set()
+
+# NOTE: this is a textual scanner, not a parser — see the caveats on each
+# piece below. It is defence-in-depth, not a hard guarantee; the vitest
+# suite in tests/js/security/snippet-highlight-order.test.js, which
+# exercises renderSnippet() and asserts on the DOM it produces, is the
+# actual behavioural gate and cannot be fooled by the evasions noted here.
+_HIGHLIGHT_REWRITE_RE = re.compile(r"html\s*=\s*highlightTerms\(html")
+# .search() takes the FIRST textual occurrence of "DOMPurify.sanitize(" as
+# *the* sanitise call. An aliased call (e.g. ``const purify =
+# window.DOMPurify; ... purify.sanitize(html)``) is invisible to this
+# regex, and a later, never-executed "DOMPurify.sanitize(" decoy (even
+# inside a comment) would then be taken as the real call — masking a
+# revert that keeps the actual (aliased) sanitise call ahead of the
+# highlight call.
+_SANITIZE_CALL_RE = re.compile(r"DOMPurify\.sanitize\(")
def find_post_sanitise_rewrites(text: str) -> bool:
- """Does a sanitised value get regex-rewritten before it is returned?"""
- if "DOMPurify.sanitize" not in text:
+ """Does a sanitised value get regex-rewritten *after* it is sanitised?
+
+ Order-aware on purpose. Both halves — a ``DOMPurify.sanitize`` call
+ and a ``html = highlightTerms(html…)`` rewrite — are present in the
+ fixed code too; what makes them safe is that the rewrite runs first.
+ A scanner that only asked "are both present?" would keep reporting
+ the file after the fix and could never tell the two orders apart.
+ """
+ sanitize = _SANITIZE_CALL_RE.search(text)
+ if not sanitize:
return False
- return bool(re.search(r"html\s*=\s*highlightTerms\(html", text))
+ return any(
+ m.start() > sanitize.start()
+ for m in _HIGHLIGHT_REWRITE_RE.finditer(text)
+ )
+
+
+def _render_snippet_body(text: str) -> str:
+ """The body of ``renderSnippet``, up to its column-0 closing brace.
+
+ Naive on purpose, and naive in a specific way: it stops at the FIRST
+ ``\\n}`` at column 0 after the function keyword, so a top-level ``}``
+ inside e.g. a column-0 template literal would truncate the body early.
+ No such literal exists in this function today.
+ """
+ start = text.index("function renderSnippet(")
+ end = text.index("\n}", start)
+ return text[start:end]
def test_post_sanitise_rewrite_scanner_flags_a_synthetic_case():
@@ -673,19 +713,41 @@ def test_post_sanitise_rewrite_scanner_is_quiet_on_a_plain_sanitise():
assert find_post_sanitise_rewrites(safe) is False
+def test_post_sanitise_rewrite_scanner_is_quiet_on_the_safe_order():
+ """The discriminating case: same two lines, swapped."""
+ safe = (
+ "html = highlightTerms(html, query);\n"
+ "html = window.DOMPurify.sanitize(x);\n"
+ )
+ assert find_post_sanitise_rewrites(safe) is False
+
+
def test_post_sanitise_rewriters_are_exactly_the_reviewed_set():
- """Library/notes search snippets are re-marked after sanitisation.
+ """Search snippets are highlighted *before* they are sanitised.
- ``renderSnippet`` sanitises a document snippet with DOMPurify and
- then hands the *serialised* result to ``highlightTerms``, which
- splits tags with ``/(<[^>]*>)|([^<]+)/`` and inserts
+ ``renderSnippet`` marks up query terms with ``highlightTerms``,
+ which splits tags with ``/(<[^>]*>)|([^<]+)/`` and inserts
``<mark class="...">`` into what it takes for text. That tag regex
stops at the first ``>``, including one inside a quoted attribute
value — and the HTML serialiser does not entity-encode ``>`` in
- attribute values, so a snippet can produce one. Where the two
- disagree, the inserted markup's own double quotes land inside an
- attribute value and terminate it. Snippets are indexed document
+ attribute values, so a *sanitised* snippet can contain one. Where
+ the two disagree, the inserted markup's own double quotes land
+ inside an attribute value and terminate it, reviving markup the
+ sanitiser had already neutralised. Snippets are indexed document
text, i.e. attacker-influenceable.
+
+ So the highlighter must run first and DOMPurify must be the last
+ thing to touch the string. Both halves of the hazard still exist in
+ the file; this test pins the ordering that defuses them.
+
+ This textual scanner is defence-in-depth with known evasions, not a
+ hard guarantee: it catches a plain revert (moving the sanitise call
+ back in front of the highlight call), but not an aliased sanitise
+ call paired with a trailing decoy — see the caveats on
+ ``_SANITIZE_CALL_RE`` and the tail-guard below. The vitest suite in
+ tests/js/security/snippet-highlight-order.test.js is the actual
+ behavioural gate: it exercises renderSnippet() and asserts on the DOM
+ it produces, so it cannot be fooled by aliasing or decoys.
"""
found = {
rel for rel, text in _js_sources() if find_post_sanitise_rewrites(text)
@@ -695,9 +757,37 @@ def test_post_sanitise_rewriters_are_exactly_the_reviewed_set():
text = (STATIC_JS / "components" / "semantic_search.js").read_text(
encoding="utf-8"
)
- # The two halves of the hazard, pinned so a fix is visible here.
+ # Floor: an empty census must mean "no post-sanitise rewriter left",
+ # not "the walk reached nothing". Both halves of the hazard are still
+ # here, so the scanner had something real to decide about.
assert "/(<[^>]*>)|([^<]+)/g" in text
assert '<mark class="ldr-search-highlight">' in text
+ assert _HIGHLIGHT_REWRITE_RE.search(text)
+ assert _SANITIZE_CALL_RE.search(text)
+
+ # The ordering itself, inside renderSnippet.
+ body = _render_snippet_body(text)
+ highlight = _HIGHLIGHT_REWRITE_RE.search(body)
+ sanitize = _SANITIZE_CALL_RE.search(body)
+ assert highlight and sanitize, body
+ assert highlight.start() < sanitize.start(), (
+ "renderSnippet highlights AFTER sanitising again"
+ )
+ # ...and nothing rewrites the sanitised string afterwards. Matches
+ # both a plain reassignment (``html = ...``, excluding the ``==``
+ # comparison operator) and a compound one (``html += ...``), which a
+ # bare ``=[^=]`` pattern would miss.
+ tail = body[sanitize.end() :]
+ assert not re.search(r"\bhtml\s*(?:\+=|=[^=])", tail), tail
+
+ # With the sanitise pass last, the allow-lists are what keep the
+ # highlight alive. Pinned here rather than in the vitest suite: under
+ # happy-dom, DOMPurify only inspects the first top-level node, so the
+ # browser-side tests cannot observe an allow-list change at all.
+ tags = re.search(r"ALLOWED_TAGS:\s*\[([^]]*)]", text)
+ assert tags and "'mark'" in tags.group(1), tags
+ attrs = re.search(r"ALLOWED_ATTR:\s*\[([^]]*)]", text)
+ assert attrs and "'class'" in attrs.group(1), attrs
def test_snippet_sanitiser_allows_no_event_handler_attributes():