~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.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
fix(ui): preserve sanitized rendering and scanner coverage (#7739)
LearningCircuit83648f8675a1
diff --git a/.github/workflows/bearer.yml b/.github/workflows/bearer.ymlindex 1517a38dca..0647288352 100644--- a/.github/workflows/bearer.yml+++ b/.github/workflows/bearer.yml@@ -5,6 +5,8 @@ on:paths:- "src/local_deep_research/database/sqlcipher_compat.py"- "src/local_deep_research/settings/manager.py"+ - "src/local_deep_research/web/static/js/services/ui.js"+ - "src/local_deep_research/web/static/js/services/pdf.js"- "tests/settings/test_settings_exception_privacy.py"- "bearer.yml"- ".github/workflows/bearer.yml"diff --git a/changelog.d/+xss-ui-service-sinks.security.md b/changelog.d/+xss-ui-service-sinks.security.mdnew file mode 100644index 0000000000..166c9a0357--- /dev/null+++ b/changelog.d/+xss-ui-service-sinks.security.md@@ -0,0 +1 @@+Clear the four Bearer `javascript_lang_dangerous_insert_html` alerts in the web UI service (code-scanning alerts 9654-9657). `hardenSanitizedMarkdown()` and `processSpecialMarkdown()` now parse their already-DOMPurify-sanitized markup into an inert `DOMParser` document instead of assigning it to a `template.innerHTML` fragment (alerts 9655 and 9656), and the generated-image directive rewrite swaps the paragraph for its wrapper with `Node.replaceChild` — a scanner-sink consistency change; neither API parses HTML strings — instead of `Node.replaceWith` (alert 9657). The `safeSetHTML()` assignment (alert 9654) is the intentional sanitization boundary (`window.sanitizeHtml` reparse-fixpoint under the restrictive allowlist, failing closed to `textContent` without DOMPurify) and carries a documented inline `bearer:disable` suppression. Rendered output is unchanged. Bearer scans now run on pull requests changing either the UI or PDF service.diff --git a/src/local_deep_research/web/static/js/services/ui.js b/src/local_deep_research/web/static/js/services/ui.jsindex 6cd5138bc8..b22c33a020 100644--- a/src/local_deep_research/web/static/js/services/ui.js+++ b/src/local_deep_research/web/static/js/services/ui.js@@ -54,6 +54,14 @@ function safeSetHTML(element, html) {typeof window.sanitizeHtml === 'function') {// no-unsanitized needs no suppression here: window.sanitizeHtml is// an allowlisted escape method in eslint.config.js.+ // This assignment is the sanitization boundary safeSetHTML exists to+ // provide: html passes through window.sanitizeHtml -- the+ // sanitizeStable() reparse-fixpoint under the SANITIZE_CONFIG+ // allowlist documented above -- and the no-sanitizer branch fails+ // closed to textContent. Bearer's sanitizer detection only matches+ // third-party library calls, not this wrapper, so the intentional+ // sanitization sink is suppressed inline.+ // bearer:disable javascript_lang_dangerous_insert_htmlelement.innerHTML = window.sanitizeHtml(html, { SAFE_FOR_TEMPLATES: false });return;}@@ -466,9 +474,9 @@ const MARKDOWN_PROHIBITED_NAMED_PROPS = new Set([* including custom properties, network-bearing image functions and* overlay positioning.*- * Implemented on top of a detached <template> so the sanitized string is- * parsed once into a DocumentFragment, mutated, then serialized back.- * No regex HTML parsing, no main-document side effects.+ * Implemented on top of a detached DOMParser document so the sanitized+ * string is parsed into its body, mutated, then serialized back.+ * The final sanitizeStable() pass precedes insertion into the live document.*/const ALLOWED_INPUT_TYPES = new Set(['checkbox']); // every other type is stripped in the hardening passconst ALLOWED_CHECKBOX_ATTRS = new Set([@@ -787,10 +795,14 @@ function hardenSanitizedMarkdown(html) {if (!html) {return html;}- const template = document.createElement('template');- // eslint-disable-next-line no-unsanitized/property -- hardened by definition: hardenSanitizedMarkdown runs on the OUTPUT of DOMPurify.sanitize, which has already passed the explicit allowlist config.- template.innerHTML = html;- const root = template.content;+ // html has passed sanitizeStable() under the explicit allowlist.+ // Parse it into a detached document before applying the value filters.+ // Scripts are inert here; the sanitizer and final sanitizeStable()+ // pass, rather than DOMParser itself, establish the HTML boundary.+ // Raw author HTML is escaped upstream, and marked emits complete GFM+ // tables; regression tests cover those shapes and the supported+ // KaTeX markup through this document-parse path.+ const root = new window.DOMParser().parseFromString(html, 'text/html').body;// Interactive controls: keep only display-only checkboxes. Everything// else (password/text/button/form/etc.) is dropped wholesale, and any// surviving checkbox is forced into a non-interactive state carrying@@ -859,7 +871,7 @@ function hardenSanitizedMarkdown(html) {}}}- return template.innerHTML;+ return root.innerHTML;}@@ -966,7 +978,7 @@ function renderMarkdown(markdown) {// Value-layer hardening of interactive controls and inline styles.// DOMPurify's tag/attr allowlist cannot express the value-level// restrictions (input type filter, style token filter) we want,- // so a detached template mutation handles them. Runs BEFORE+ // so a detached inert-document mutation handles them. Runs BEFORE// processSpecialMarkdown for the same reason as DOMPurify above.const hardened = hardenSanitizedMarkdown(sanitized);@@ -1012,11 +1024,13 @@ function processSpecialMarkdown(html) {// could turn harmless attribute text into executable markup after the// final browser parse.const GENERATED_IMAGE_DIRECTIVE = /^\s*!\[ref:(image-[\w-]+)\]\s*$/;- const template = document.createElement('template');- // eslint-disable-next-line no-unsanitized/property -- html is the output of sanitizeStable() and hardenSanitizedMarkdown(); new markup below is created exclusively with DOM APIs.- template.innerHTML = html;+ // html has passed sanitizeStable() and the value hardening above.+ // Parse it into a detached document; build generated-image markup+ // with DOM APIs, then sanitize the serialized result once more in+ // renderMarkdown() before any caller inserts it into the live document.+ const root = new window.DOMParser().parseFromString(html, 'text/html').body;- for (const paragraph of [...template.content.querySelectorAll('p')]) {+ for (const paragraph of [...root.querySelectorAll('p')]) {if (paragraph.childNodes.length !== 1 ||paragraph.firstChild.nodeType !== Node.TEXT_NODE) {continue;@@ -1049,10 +1063,16 @@ function processSpecialMarkdown(html) {wrapper.appendChild(image);wrapper.appendChild(caption);- paragraph.replaceWith(wrapper);+ // A pure node swap on wrapper, which was built above exclusively+ // with DOM APIs. Spelled replaceChild rather than the shorter+ // Node.replaceWith for scanner-sink consistency (alert 9657):+ // neither API parses HTML -- replaceWith stringifies a non-node+ // argument into a Text node -- so this is hygiene, not an+ // escaping fix.+ paragraph.parentNode.replaceChild(wrapper, paragraph);}- return template.innerHTML;+ return root.innerHTML;}/**diff --git a/tests/js/security/markdown-render-xss.test.js b/tests/js/security/markdown-render-xss.test.jsindex 52ee1fda29..7f834cc05a 100644--- a/tests/js/security/markdown-render-xss.test.js+++ b/tests/js/security/markdown-render-xss.test.js@@ -296,6 +296,19 @@ describe('renderMarkdown() XSS surface', () => {expect(root.querySelectorAll('.ldr-markdown-content > p')).toHaveLength(0);});+ it('replaces generated-image directive paragraphs in place among siblings', () => {+ // Pins the directive swap in processSpecialMarkdown(): the wrapper+ // takes the directive paragraph's exact position (a pure node+ // swap), so surrounding content keeps its source order around it.+ const root = renderContainer('before\n\n![ref:image-x]\n\nafter');+ const children = [...root.querySelector('.ldr-markdown-content').children];++ expect(children.map((child) => child.tagName)).toEqual(['P', 'DIV', 'P']);+ expect(children[0].textContent).toBe('before');+ expect(children[1].className).toBe('ldr-generated-image');+ expect(children[2].textContent).toBe('after');+ });+it('does not re-enable user-supplied images in the final image-aware pass', () => {const root = renderContainer(['![ref:image-safe]',@@ -397,6 +410,23 @@ describe('renderMarkdown() XSS surface', () => {expect(boxes[1].hasAttribute('checked')).toBe(false);});+ it('preserves GFM table structure through the hardening pipeline', () => {+ // Pins only the rendered shape: the complete <table> subtree+ // marked emits (raw HTML is escaped before sanitization, so this+ // is the only table the pipeline sees) must survive+ // hardenSanitizedMarkdown() and processSpecialMarkdown() with its+ // cells in source order. It does NOT discriminate the inert+ // DOMParser parse from the former template-fragment parse -- this+ // harness handles this input identically under both -- and a bare+ // table fragment would only separate them under a real browser+ // parse. The parse-path change itself is pinned statically in+ // tests/security/test_client_side_xss_sinks.py.+ const root = renderContainer('| a | b |\n| --- | --- |\n| 1 | 2 |');++ const cells = [...root.querySelectorAll('th, td')].map((cell) => cell.textContent);+ expect(cells).toEqual(['a', 'b', '1', '2']);+ });+it('preserves KaTeX HTML and MathML through the allowlist', () => {const root = renderContainer('$x^2 + y_i$');diff --git a/tests/security/test_client_side_xss_sinks.py b/tests/security/test_client_side_xss_sinks.pyindex 53bc40f5f6..4b53aff154 100644--- a/tests/security/test_client_side_xss_sinks.py+++ b/tests/security/test_client_side_xss_sinks.py@@ -725,6 +725,210 @@ def test_fallback_markdown_renderer_emits_no_markup_from_input():assert "marked" not in body+# ---------------------------------------------------------------------+# Markdown hardening parse boundary (Bearer alerts 9655-9657)+#+# The three security-graded hunks pinned here are behaviour-neutral by+# design (the old-vs-new render matrix is byte-identical), so no+# behavioural test can separate the fixed source from the reverted one:+# the vitest cases in tests/js/security/markdown-render-xss.test.js pass+# under both parse paths. The pin therefore has to be structural, on the+# shape of the source. Following the mutation-rejection precedent of+# tests/theme_tests/test_accent_ink_contrast.py's+# test_authored_math_style_exception_rejects_unreviewed_writes: each+# pin runs over the shipped source AND over a copy of the shipped+# source with the exact Bearer revert spliced back in, which the pin+# must reject.+# ---------------------------------------------------------------------++_DOM_PARSE_CALL = "DOMParser().parseFromString("+_TEMPLATE_WRITE_RE = re.compile(r"template\w*\.innerHTML\s*\+?=")+_REPLACEWITH_CALL_RE = re.compile(r"\.replaceWith\s*\(")+#: One ``innerHTML`` WRITE per source line: reads (``return x.innerHTML``)+#: and ``==`` comparisons do not match; ``+=`` does.+_INNERHTML_WRITE_RE = re.compile(r"^[^\n]*\.innerHTML\s*\+?=[^=][^\n]*$", re.M)+_BLANK_WRITE_RE = re.compile(r"\.innerHTML\s*=\s*''\s*;")+++def _function_body(text: str, name: str) -> str:+ """The body of top-level ``function name(``, up to its column-0 ``}``.++ Naive in the same way as ``_render_snippet_body`` below: it stops at+ the FIRST ``\\n}`` at column 0 after the function keyword. That is+ correct for the functions pinned here -- none holds a column-0 ``}``+ inside a template literal.+ """+ start = text.index(f"function {name}(")+ end = text.index("\n}", start)+ return text[start:end]+++def markdown_parse_boundary_violations(text: str) -> list[str]:+ """Sink shapes the DOMParser/replaceChild rewrite removed.++ Empty on the shipped ui.js. Alerts 9655/9656 had the two markdown+ helpers writing their already-sanitized markup into a+ ``template.innerHTML`` fragment; alert 9657 had the generated-image+ directive swap spelled ``Node.replaceWith``. A violation name is+ phrased as the failure it reports so a red assertion is readable.+ """+ ui = _strip_js_comments(text)+ problems = []+ if _TEMPLATE_WRITE_RE.search(ui):+ problems.append("template.innerHTML assignment returned")+ for name in ("hardenSanitizedMarkdown", "processSpecialMarkdown"):+ if _DOM_PARSE_CALL not in _function_body(ui, name):+ problems.append(f"{name} no longer parses via DOMParser")+ swap = _function_body(ui, "processSpecialMarkdown")+ if "parentNode.replaceChild(" not in swap:+ problems.append(+ "generated-image swap is no longer parentNode.replaceChild"+ )+ if _REPLACEWITH_CALL_RE.search(swap):+ problems.append("generated-image swap calls Node.replaceWith")+ return problems+++def test_markdown_helpers_never_write_a_template_innerhtml_fragment():+ """Alerts 9655/9656: parsing goes through the inert DOMParser+ document, never a ``template.innerHTML = html`` fragment write.++ Reverting either fix hunk turns this red (and so does the mutation+ case below, which splices the exact revert back in). The write, not+ the parse, is what is pinned: the DOMParser spelling in+ test_markdown_helpers_parse_their_markup_with_domparser is its+ positive half, so a revert cannot pass by renaming the template.+ """+ problems = markdown_parse_boundary_violations(_ui_js())+ assert not [p for p in problems if "template.innerHTML" in p], problems+++def test_markdown_helpers_parse_their_markup_with_domparser():+ """Both hardened helpers parse via ``DOMParser().parseFromString(``.++ One parse per helper, so dropping the parse from either+ ``hardenSanitizedMarkdown`` (alert 9655) or ``processSpecialMarkdown``+ (alert 9656) turns this red even if the removed write is spelled+ without ``template`` in the name.+ """+ problems = markdown_parse_boundary_violations(_ui_js())+ assert not [p for p in problems if "DOMParser" in p], problems+++def test_generated_image_swap_is_a_pure_node_operation():+ """Alert 9657: the directive paragraph is swapped with+ ``parentNode.replaceChild(wrapper, paragraph)`` and ``Node.replaceWith``+ does not reappear in the function.++ (``replaceChild`` is scanner-sink consistency, not an escaping fix --+ ``replaceWith`` stringifies a non-node argument to a Text node and+ never parses HTML either -- but the sink removal is what the alert+ grades, so the removal is what is pinned.)+ """+ problems = markdown_parse_boundary_violations(_ui_js())+ assert not [p for p in problems if "generated-image" in p], problems+++#: The exact pre-fix shapes behind alerts 9655-9657 (from the fix+#: commit), spliced back into a copy of the shipped source by+#: test_parse_boundary_pins_reject_each_exact_bearer_revert below. Each+#: ``old`` text must occur exactly once in ui.js -- if the shipped+#: spelling moves, the splice site check fails instead of the pin+#: silently losing its target.+_BEARER_REVERTS = {+ "harden-parse": (+ " const root = new window.DOMParser().parseFromString(html, "+ "'text/html').body;\n // Interactive controls:",+ " const template = document.createElement('template');\n"+ " template.innerHTML = html;\n"+ " const root = template.content;\n"+ " // Interactive controls:",+ ),+ "process-parse": (+ " const root = new window.DOMParser().parseFromString(html, "+ "'text/html').body;\n\n"+ " for (const paragraph of [...root.querySelectorAll('p')]) {",+ " const template = document.createElement('template');\n"+ " template.innerHTML = html;\n"+ " const root = template.content;\n\n"+ " for (const paragraph of [...root.querySelectorAll('p')]) {",+ ),+ "image-swap": (+ " paragraph.parentNode.replaceChild(wrapper, paragraph);",+ " paragraph.replaceWith(wrapper);",+ ),+}++_BEARER_REVERT_FINDINGS = {+ "harden-parse": [+ "template.innerHTML assignment returned",+ "hardenSanitizedMarkdown no longer parses via DOMParser",+ ],+ "process-parse": [+ "template.innerHTML assignment returned",+ "processSpecialMarkdown no longer parses via DOMParser",+ ],+ "image-swap": [+ "generated-image swap is no longer parentNode.replaceChild",+ "generated-image swap calls Node.replaceWith",+ ],+}++[email protected]("change", sorted(_BEARER_REVERTS))+def test_parse_boundary_pins_reject_each_exact_bearer_revert(change):+ """Mutation rejection: the pins above are not vacuous.++ Splice the exact revert of each fix hunk back into a copy of the+ shipped source and the pins must report exactly the finding that+ hunk's removal stands in for. A pin that stays green here would stay+ green on a real revert too -- which is how the pre-fix sinks shipped.+ """+ old, new = _BEARER_REVERTS[change]+ text = _ui_js()+ assert text.count(old) == 1, f"{change}: splice site moved"+ reverted = text.replace(old, new, 1)+ assert reverted != text+ assert (+ markdown_parse_boundary_violations(reverted)+ == _BEARER_REVERT_FINDINGS[change]+ )+++def test_ui_js_innerhtml_writes_are_only_the_safe_set_html_boundary():+ """The untrusted-string-to-sink sweep, frozen: only safeSetHTML+ writes markup into an element -- sanitized and failing closed to+ text, pinned by test_safe_set_html_fails_closed_without_dompurify --+ and every other ``innerHTML`` assignment in ui.js blanks its element+ to ``''``.++ A new direct write -- e.g. the ``template.innerHTML = html``+ fragment writes removed for alerts 9655/9656 -- shows up here as an+ unexpected write even if it is spelled in a function no other pin+ looks at, so this is the file-wide half of the two pins above.+ """+ ui = _strip_js_comments(_ui_js())+ writes = [+ " ".join(m.group(0).split()) for m in _INNERHTML_WRITE_RE.finditer(ui)+ ]+ assert len(writes) >= 3, (+ f"expected the known innerHTML writes, found {writes} — "+ "the scan is not reaching the file"+ )+ safe_body = " ".join(_function_body(ui, "safeSetHTML").split())+ unexpected = [+ w+ for w in writes+ if not _BLANK_WRITE_RE.search(w) and w not in safe_body+ ]+ assert unexpected == [], unexpected+ non_blank = [w for w in writes if not _BLANK_WRITE_RE.search(w)]+ assert len(non_blank) == 1, (+ "safeSetHTML's sanitized write is no longer the only non-blank "+ f"innerHTML write in ui.js: {writes}"+ )++#: Rewriting a DOMPurify result with a regex re-opens what the sanitiser#: closed. The set is empty and must stay empty: ``renderSnippet`` used to#: be in it, and highlighting now runs *before* the sanitise pass. Addingdiff --git a/tests/theme_tests/test_accent_ink_contrast.py b/tests/theme_tests/test_accent_ink_contrast.pyindex bd67e577fb..6b762131ec 100644--- a/tests/theme_tests/test_accent_ink_contrast.py+++ b/tests/theme_tests/test_accent_ink_contrast.py@@ -838,7 +838,7 @@ def _style_variants(name, decls, allowlist):# real-browser reparse suite. Do not pretend these arbitrary author colors# are finite theme variants. Only this exact guarded source block is outside# the application-palette sweep; new or changed whole-style writes still fail.-_AUTHORED_MATH_STYLE_SITE = ("static/js/services/ui.js", 838)+_AUTHORED_MATH_STYLE_SITE = ("static/js/services/ui.js", 850)_AUTHORED_MATH_STYLE_CONTEXT = ("const safeStyle = getSafeKatexInlineStyle(el);","if (!safeStyle) {",