~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): fail closed when DOMPurify is unavailable in renderMarkdown (#6591)
LearningCircuita247fa2482c0
diff --git a/changelog.d/6591.security.md b/changelog.d/6591.security.mdnew file mode 100644index 0000000000..38a37a2103--- /dev/null+++ b/changelog.d/6591.security.md@@ -0,0 +1 @@+Client-side HTML rendering now fails closed when the DOMPurify sanitizer fails to load or reports itself unsupported. Report and note markdown (`renderMarkdown`) previously returned the parsed, unsanitized markdown HTML when DOMPurify was missing, letting raw HTML embedded in hostile report content render as live markup. In addition, `renderMarkdown`, `safeSetHTML` (used by the shared spinner, error and alert UI), the `XSSProtection` helpers (`sanitizeHtml`, `safeSetInnerHTML`, `safeCreateElement`), semantic-search snippet rendering, the news page's HTML renderer and PDF export all treated any loaded DOMPurify as usable, but DOMPurify's `isSupported` flag can be `false`, `null` or `undefined` in a broken DOM environment, and `sanitize()` then returns its input unchanged. Each of these now uses DOMPurify only when `DOMPurify.isSupported` is exactly `true`, and otherwise takes its existing no-sanitizer fallback: escaped plaintext, `textContent`, or refusing to proceed (`safeCreateElement`, PDF export). `safeSetHTML`'s own fallback was fail-open too: when DOMPurify was missing it assigned its input to `innerHTML` unsanitized. It now sets `textContent` instead.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.jsindex a8a90081c1..8812213cd6 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@@ -23,7 +23,9 @@ const esc = window.escapeHtml || (s => String(s || '').replace(/[&<>"']/g, m =>function renderSnippet(md, query) {if (!md) return '';let html;- if (window.marked && window.DOMPurify) {+ // isSupported must be exactly true: an unsupported DOMPurify returns+ // its input unchanged from sanitize(), so treat it as missing.+ if (window.marked && window.DOMPurify?.isSupported === true) {html = window.marked.parseInline(String(md));// ORDER IS LOAD-BEARING: highlight BEFORE sanitizing, never after.//diff --git a/src/local_deep_research/web/static/js/pages/news.js b/src/local_deep_research/web/static/js/pages/news.jsindex 9acf1f7fd1..6dcea97bf3 100644--- a/src/local_deep_research/web/static/js/pages/news.js+++ b/src/local_deep_research/web/static/js/pages/news.js@@ -14,8 +14,10 @@ function safeRenderHTML(container, htmlString) {// Non-async module scripts and defer classic scripts execute in document// order, so it is normally bound before this script runs; if the bundle// failed to load or was reordered, fall back to textContent (which is- // always XSS-safe) instead of assigning unsanitized HTML.- if (!window.DOMPurify) {+ // always XSS-safe) instead of assigning unsanitized HTML. An unsupported+ // DOMPurify (isSupported not exactly true) returns its input unchanged+ // from sanitize(), so it gets the same fallback.+ if (window.DOMPurify?.isSupported !== true) {SafeLogger.warn('DOMPurify not yet loaded — rendering as plain text (safe fallback)');while (container.firstChild) {container.removeChild(container.firstChild);diff --git a/src/local_deep_research/web/static/js/security/xss-protection.js b/src/local_deep_research/web/static/js/security/xss-protection.jsindex b47f43a40c..ddc6705b01 100644--- a/src/local_deep_research/web/static/js/security/xss-protection.js+++ b/src/local_deep_research/web/static/js/security/xss-protection.js@@ -36,8 +36,13 @@// Check if DOMPurify is available dynamically (bound by app.js/Vite module).// Evaluated per call rather than once, so no helper depends on the// relative load order of this script and the module that binds it.+ // Usable only when isSupported is exactly true: DOMPurify computes+ // isSupported from an && chain that can yield null/undefined as well+ // as false, and sanitize() returns its input unchanged whenever it is+ // falsy -- treating such an instance as present would fail open.function hasDOMPurify() {- return typeof DOMPurify !== 'undefined';+ return typeof DOMPurify !== 'undefined' && DOMPurify !== null &&+ DOMPurify.isSupported === true;}// Browsing-context keywords that never open a new browsing context.diff --git a/src/local_deep_research/web/static/js/services/pdf.js b/src/local_deep_research/web/static/js/services/pdf.jsindex 5f7f35d680..3478f6a560 100644--- a/src/local_deep_research/web/static/js/services/pdf.js+++ b/src/local_deep_research/web/static/js/services/pdf.js@@ -186,7 +186,11 @@ async function generatePdf(title, content, _metadata = {}) {if (pdfBodyDiv) {if (window.marked && typeof window.marked.parse === 'function') {const rawHtml = window.marked.parse(content);- if (!window.DOMPurify) {+ // isSupported must be exactly true: an unsupported DOMPurify+ // (isSupported false/null/undefined) returns its input+ // unchanged from sanitize(), which would put raw markup into+ // this live-document element.+ if (window.DOMPurify?.isSupported !== true) {document.body.removeChild(tempContainer);throw new Error('DOMPurify not loaded. Cannot generate PDF safely.');}diff --git a/src/local_deep_research/web/static/js/services/ui.js b/src/local_deep_research/web/static/js/services/ui.jsindex f3800ea165..e53a11d844 100644--- a/src/local_deep_research/web/static/js/services/ui.js+++ b/src/local_deep_research/web/static/js/services/ui.js@@ -12,19 +12,20 @@ const UI_CONFIG = {// Note: sanitizer functions are available via Vite bundle or we use safe fallbacks/**- * Safe HTML setter - uses DOMPurify if available, otherwise sets innerHTML directly- * for controlled/trusted content only+ * Safe HTML setter - sanitizes with DOMPurify when a supported instance is+ * bound; otherwise fails closed and renders the string as plain text.*/function safeSetHTML(element, html) {if (!element) return;- // If DOMPurify is available globally (from Vite bundle), use it- if (typeof DOMPurify !== 'undefined') {+ // Trust DOMPurify only when isSupported is exactly true: in a broken DOM+ // environment it can be false, null or undefined, and sanitize() then+ // returns its input unchanged.+ if (typeof DOMPurify !== 'undefined' && DOMPurify?.isSupported === true) {element.innerHTML = DOMPurify.sanitize(html);} else {- // For controlled content (UI elements we generate), direct assignment is acceptable- // bearer:disable javascript_lang_dangerous_insert_html- // eslint-disable-next-line no-unsanitized/property -- audited 2026-03-28: DOMPurify fallback path — callers use safeSetHTML which documents sanitization requirement- element.innerHTML = html;+ // Fail closed: without a usable sanitizer the markup is shown as text,+ // never parsed as HTML.+ element.textContent = html;}}@@ -260,6 +261,25 @@ function showMessage(message, type = 'success', duration = UI_CONFIG.NOTIFICATIO}, duration);}+/**+ * Fail-closed markdown rendering: escape everything, show as text.+ * Shared by the marked-missing and DOMPurify-missing branches --+ * neither missing library may ever yield raw parsed markup.+ */+function _escapedPlaintextFallback(markdown) {+ const escaped = typeof window.escapeHtml === 'function'+ ? window.escapeHtml(markdown)+ // bearer:disable javascript_lang_manual_html_sanitization+ : String(markdown).replace(/[&<>"']/g, (m) => ({'&':'&','<':'<','>':'>','"':'"',"'":'''})[m]);++ return `<div class="markdown-content">+ <div class="alert alert-warning" style="margin-bottom: 1rem;">+ <i class="fas fa-exclamation-triangle"></i> Markdown rendering unavailable. Displaying as plaintext.+ </div>+ <pre style="white-space: pre-wrap; word-wrap: break-word; font-family: inherit;">${escaped}</pre>+ </div>`;+}+/*** Format and render Markdown content* @param {string} markdown - The markdown content@@ -304,18 +324,30 @@ function renderMarkdown(markdown) {// Process any special elements like image referencesconst processedHtml = processSpecialMarkdown(html);- // Sanitize to prevent XSS from markdown content+ // Sanitize to prevent XSS from markdown content. DOMPurify+ // missing is NOT a pass-through condition: marked passes raw+ // HTML in markdown through by default, so unsanitized output+ // would render hostile report content raw. Fail closed to the+ // same escaped-plaintext path as the marked-missing branch.+ // Anything but an explicitly supported sanitizer+ // (DOMPurify.isSupported !== true) is treated the same:+ // DOMPurify computes isSupported from an && chain that can+ // yield null/undefined as well as false, and sanitize()+ // returns its input unchanged whenever it is falsy, which+ // would also fail open.+ if (typeof DOMPurify === 'undefined' || DOMPurify?.isSupported !== true) {+ SafeLogger.warn('DOMPurify not available. Displaying as plaintext for security.');+ return _escapedPlaintextFallback(markdown);+ }// Raw <a target="_blank"> HTML embedded in markdown bypasses// the marked renderer's rel hook; ensure the shared tabnabbing// hook is registered before sanitizing (idempotent, and a// no-op when XSSProtection has not loaded).window.XSSProtection?.ensureTabnabbingHook?.();- const sanitized = typeof DOMPurify !== 'undefined'- ? DOMPurify.sanitize(processedHtml, {- ADD_TAGS: ['semantics', 'annotation'],- ADD_ATTR: ['target', 'rel']- })- : processedHtml;+ const sanitized = DOMPurify.sanitize(processedHtml, {+ ADD_TAGS: ['semantics', 'annotation'],+ ADD_ATTR: ['target', 'rel']+ });return `<div class="ldr-markdown-content">${sanitized}</div>`;}@@ -323,17 +355,7 @@ function renderMarkdown(markdown) {// Using regex-based partial markdown is fragile and a security risk,// so we escape all HTML and display as preformatted text with a warningSafeLogger.warn('Marked library not available. Displaying as plaintext for security.');- const escaped = typeof window.escapeHtml === 'function'- ? window.escapeHtml(markdown)- // bearer:disable javascript_lang_manual_html_sanitization- : markdown.replace(/[&<>"']/g, (m) => ({'&':'&','<':'<','>':'>','"':'"',"'":'''})[m]);-- return `<div class="markdown-content">- <div class="alert alert-warning" style="margin-bottom: 1rem;">- <i class="fas fa-exclamation-triangle"></i> Markdown rendering unavailable. Displaying as plaintext.- </div>- <pre style="white-space: pre-wrap; word-wrap: break-word; font-family: inherit;">${escaped}</pre>- </div>`;+ return _escapedPlaintextFallback(markdown);} catch (error) {SafeLogger.error('Error rendering markdown:', error);const escapedMessage = typeof window.escapeHtml === 'function'diff --git a/tests/infrastructure_tests/test_xss_protection.test.js b/tests/infrastructure_tests/test_xss_protection.test.jsindex bdb4f9ea03..33ab42be29 100644--- a/tests/infrastructure_tests/test_xss_protection.test.js+++ b/tests/infrastructure_tests/test_xss_protection.test.js@@ -8,6 +8,7 @@// Mock DOMPurify for testingconst mockDOMPurify = {+ isSupported: true,sanitize: jest.fn((content) => {// Simple mock that allows span tags with class attribute// but removes script tagsdiff --git a/tests/js/components/semantic-search.test.js b/tests/js/components/semantic-search.test.jsindex 6939a80d9f..f1fec2b451 100644--- a/tests/js/components/semantic-search.test.js+++ b/tests/js/components/semantic-search.test.js@@ -177,6 +177,7 @@ describe('SemanticSearch rendering helpers', () => {)),};window.DOMPurify = {+ isSupported: true,sanitize: vi.fn(html => html),};diff --git a/tests/js/pages/helpers/news-render-harness.js b/tests/js/pages/helpers/news-render-harness.jsindex 734b9b3f88..3252d055d6 100644--- a/tests/js/pages/helpers/news-render-harness.js+++ b/tests/js/pages/helpers/news-render-harness.js@@ -78,7 +78,7 @@ export async function installNewsRenderHarness() {template.innerHTML = htmlString;return template.content;});- window.DOMPurify = { sanitize: sanitizeSpy };+ window.DOMPurify = { isSupported: true, sanitize: sanitizeSpy };// Swapped per render to control the payload; only /news/api/feed returns// it so the other endpoints initializeNewsPage touches no-op.diff --git a/tests/js/pages/news-actions-direct-runtime.test.js b/tests/js/pages/news-actions-direct-runtime.test.jsindex bf7d68a0f1..35e5c473ca 100644--- a/tests/js/pages/news-actions-direct-runtime.test.js+++ b/tests/js/pages/news-actions-direct-runtime.test.js@@ -167,6 +167,7 @@ beforeAll(async () => {// mirrors the production policy relevant to the page: event attributes// and unsafe URLs are removed, while declarative data attributes survive.const purify = {+ isSupported: true,addHook: vi.fn(),sanitize: vi.fn(dirty => {const template = document.createElement('template');diff --git a/tests/js/pages/news-lifecycle-runtime.test.js b/tests/js/pages/news-lifecycle-runtime.test.jsindex 6a4dd67812..b751c35480 100644--- a/tests/js/pages/news-lifecycle-runtime.test.js+++ b/tests/js/pages/news-lifecycle-runtime.test.js@@ -51,6 +51,7 @@ beforeAll(async () => {installDom();const purify = {+ isSupported: true,addHook: vi.fn(),sanitize: vi.fn(dirty => {const template = document.createElement('template');diff --git a/tests/js/pages/news-search-history-xss.test.js b/tests/js/pages/news-search-history-xss.test.jsindex e329583b23..6a097f47b7 100644--- a/tests/js/pages/news-search-history-xss.test.js+++ b/tests/js/pages/news-search-history-xss.test.js@@ -36,7 +36,7 @@ beforeAll(async () => {template.innerHTML = htmlString;return template.content;});- window.DOMPurify = { sanitize: sanitizeSpy };+ window.DOMPurify = { isSupported: true, sanitize: sanitizeSpy };// fetchResponses is keyed by URL substring so individual tests can swap// in payloads for /news/api/search-history without affecting otherdiff --git a/tests/js/pages/subscriptions-direct-runtime.test.js b/tests/js/pages/subscriptions-direct-runtime.test.jsindex 9e0b0cf9c1..de8582ff15 100644--- a/tests/js/pages/subscriptions-direct-runtime.test.js+++ b/tests/js/pages/subscriptions-direct-runtime.test.js@@ -63,6 +63,7 @@ beforeEach(async () => {installDom();const purify = {+ isSupported: true,addHook: vi.fn(),sanitize: vi.fn(dirty => {const template = document.createElement('template');diff --git a/tests/js/pages/subscriptions-folder-race-runtime.test.js b/tests/js/pages/subscriptions-folder-race-runtime.test.jsindex a5acb3fd03..f4d9367ff6 100644--- a/tests/js/pages/subscriptions-folder-race-runtime.test.js+++ b/tests/js/pages/subscriptions-folder-race-runtime.test.js@@ -55,6 +55,7 @@ beforeEach(async () => {installDom();const purify = {+ isSupported: true,addHook: vi.fn(),sanitize: vi.fn(dirty => String(dirty)),};diff --git a/tests/js/security/dompurify-unsupported-fail-closed.test.js b/tests/js/security/dompurify-unsupported-fail-closed.test.jsnew file mode 100644index 0000000000..36a0b7c506--- /dev/null+++ b/tests/js/security/dompurify-unsupported-fail-closed.test.js@@ -0,0 +1,157 @@+/**+ * Fail-closed contracts for an unsupported DOMPurify at every direct+ * sanitizer call site outside renderMarkdown.+ *+ * DOMPurify computes ``isSupported`` from an ``&&`` chain that can yield+ * ``null``/``undefined`` as well as ``false`` (e.g. a broken DOM+ * environment), and ``sanitize()`` returns its input UNCHANGED whenever+ * it is falsy. A presence check (``typeof DOMPurify !== 'undefined'`` or+ * ``!window.DOMPurify``) therefore treats such an instance as a working+ * sanitizer and fails open. Each site must instead take its existing+ * no-sanitizer fallback unless ``isSupported === true``:+ *+ * - xss-protection.js sanitizeHtml -> escaped text+ * - xss-protection.js safeSetInnerHTML -> textContent+ * - xss-protection.js safeCreateElement -> throws+ * - semantic_search.js renderSnippet -> escaped text+ * - news.js safeRenderHTML -> textContent+ * - pdf.js generatePdf -> throws, temp DOM removed+ *+ * The stand-in below behaves like an unsupported DOMPurify: sanitize()+ * hands its input back untouched, so any site that still calls it would+ * emit raw markup.+ */++import '@js/security/xss-protection.js';+import '@js/components/semantic_search.js';+import '@js/services/pdf.js';+import { installNewsRenderHarness, makeNewsItem } from '../pages/helpers/news-render-harness.js';++const RAW = '<img src=x onerror="window.__ldrPwned=1">';+const UNSUPPORTED = [false, null, undefined];++function unsupportedPurifier(isSupported) {+ return {+ isSupported,+ addHook: vi.fn(),+ // Real DOMPurify with a falsy isSupported returns its input as-is.+ sanitize: vi.fn((dirty) => dirty),+ };+}++function bindPurifier(purifier) {+ globalThis.DOMPurify = purifier;+ window.DOMPurify = purifier;+}++let newsHarness;+let savedPurifier;++beforeAll(async () => {+ newsHarness = await installNewsRenderHarness();+ savedPurifier = window.DOMPurify;+});++afterEach(() => {+ bindPurifier(savedPurifier);+ delete window.marked;+ delete globalThis.jsPDF;+ delete globalThis.html2canvas;+ delete window.__ldrPwned;+ vi.restoreAllMocks();+});++describe('xss-protection.js with an unsupported DOMPurify', () => {+ it.each(UNSUPPORTED)('sanitizeHtml escapes instead of passing through (isSupported=%s)', (flag) => {+ const purifier = unsupportedPurifier(flag);+ bindPurifier(purifier);++ const out = window.sanitizeHtml(RAW);++ expect(purifier.sanitize).not.toHaveBeenCalled();+ expect(out).not.toContain('<img');+ expect(out).toContain('<img');+ });++ it.each(UNSUPPORTED)('safeSetInnerHTML falls back to text (isSupported=%s)', (flag) => {+ const purifier = unsupportedPurifier(flag);+ bindPurifier(purifier);+ const el = document.createElement('div');++ window.safeSetInnerHTML(el, RAW, true);++ expect(purifier.sanitize).not.toHaveBeenCalled();+ expect(el.querySelector('img')).toBeNull();+ expect(el.textContent).toBe(RAW);+ });++ it.each(UNSUPPORTED)('safeCreateElement refuses (isSupported=%s)', (flag) => {+ const purifier = unsupportedPurifier(flag);+ bindPurifier(purifier);++ expect(() => window.safeCreateElement('a', 'x', { onclick: 'window.__ldrPwned=1' }))+ .toThrow('safeCreateElement requires DOMPurify to be loaded');+ expect(purifier.sanitize).not.toHaveBeenCalled();+ });++ it('still sanitizes when isSupported is exactly true', () => {+ const purifier = unsupportedPurifier(true);+ purifier.sanitize = vi.fn(() => '<b>clean</b>');+ bindPurifier(purifier);++ expect(window.sanitizeHtml(RAW)).toBe('<b>clean</b>');+ expect(purifier.sanitize).toHaveBeenCalledTimes(1);+ });+});++describe('semantic_search.js renderSnippet with an unsupported DOMPurify', () => {+ it.each(UNSUPPORTED)('escapes the snippet (isSupported=%s)', (flag) => {+ const purifier = unsupportedPurifier(flag);+ bindPurifier(purifier);+ window.marked = { parseInline: vi.fn((md) => String(md)) };++ const out = window.SemanticSearch.renderSnippet(RAW, 'img');++ expect(purifier.sanitize).not.toHaveBeenCalled();+ expect(window.marked.parseInline).not.toHaveBeenCalled();+ expect(out).not.toContain('<img');+ expect(out).toContain('<img');+ });+});++describe('news.js safeRenderHTML with an unsupported DOMPurify', () => {+ it.each(UNSUPPORTED)('renders the feed as text (isSupported=%s)', async (flag) => {+ const purifier = unsupportedPurifier(flag);+ bindPurifier(purifier);+ vi.spyOn(SafeLogger, 'warn').mockImplementation(() => {});++ await newsHarness.renderWith([makeNewsItem({ headline: 'UNSUPPORTED_CANARY' })]);++ // Every safeRenderHTML call in the cycle (loading placeholder,+ // feed or error message) must take the textContent fallback.+ const container = document.getElementById('news-feed-content');+ expect(purifier.sanitize).not.toHaveBeenCalled();+ expect(container.children).toHaveLength(0);+ // The template markup shows up as inert text, not elements.+ expect(container.textContent).toContain('<p');+ });+});++describe('pdf.js generatePdf with an unsupported DOMPurify', () => {+ it.each(UNSUPPORTED)('refuses and removes its temporary DOM (isSupported=%s)', async (flag) => {+ const purifier = unsupportedPurifier(flag);+ bindPurifier(purifier);+ globalThis.jsPDF = vi.fn();+ globalThis.html2canvas = vi.fn();+ window.marked = { parse: vi.fn(() => RAW) };+ vi.spyOn(SafeLogger, 'error').mockImplementation(() => {});++ await expect(window.pdfService.generatePdf('Title', 'Report')).rejects.toThrow(+ 'DOMPurify not loaded. Cannot generate PDF safely.',+ );+ expect(purifier.sanitize).not.toHaveBeenCalled();+ expect(document.querySelector('.ldr-pdf-content')).toBeNull();+ expect(document.querySelector('img[onerror]')).toBeNull();+ expect(window.__ldrPwned).toBeUndefined();+ });+});diff --git a/tests/js/security/render-markdown-fail-closed.test.js b/tests/js/security/render-markdown-fail-closed.test.jsnew file mode 100644index 0000000000..be2b08833a--- /dev/null+++ b/tests/js/security/render-markdown-fail-closed.test.js@@ -0,0 +1,199 @@+/**+ * Fail-closed contracts for renderMarkdown's sanitizer availability.+ *+ * ``services/ui.js`` renderMarkdown parses report markdown through+ * ``marked`` — which passes raw HTML in markdown through by default —+ * and then sanitizes with DOMPurify. The marked-missing branch fails+ * closed to escaped plaintext, but the DOMPurify-missing branch+ * returned the parsed HTML **unsanitized**: on a page where the+ * sanitizer failed to load, hostile report/note content (web-influenced+ * through research results) rendered raw — a fail-open stored-XSS path.+ *+ * These contracts pin: payloads never survive when DOMPurify is+ * unavailable (escaped plaintext instead), and the sanitizing path is+ * actually taken when it is available.+ */++import '@js/services/ui.js';++const HOSTILE_MARKDOWN = '# Title\n\n<img src=x onerror="window.__pwnedA=1">';+// What a pass-through marked would produce for hostile markdown+// (raw HTML survives marked by default).+const HOSTILE_PARSED_HTML = [+ '<h1>Title</h1><p>body</p>',+ '<img src=x onerror="window.__pwnedA=1">',+ '<script>window.__pwnedB=1</script>',+ '<a href="javascript:window.__pwnedC=1">click</a>',+].join('');++class _StubRenderer {+ link() {+ return '<a href="#">x</a>';+ }+}++function _stubMarked(html = HOSTILE_PARSED_HTML) {+ globalThis.marked = {+ Renderer: _StubRenderer,+ setOptions() {},+ parse: () => html,+ };+}++const BENIGN_MARKDOWN = '# H with <b>bold</b>';+const BENIGN_PARSED_HTML = '<h1>H with <b>bold</b></h1>';++describe('renderMarkdown fails closed when DOMPurify is unavailable', () => {+ let _savedPurify;+ let _savedMarked;++ beforeEach(() => {+ _savedPurify = globalThis.DOMPurify;+ _savedMarked = globalThis.marked;+ });++ afterEach(() => {+ globalThis.DOMPurify = _savedPurify;+ globalThis.marked = _savedMarked;+ delete globalThis.__pwnedA;+ });++ it('never returns raw payload HTML without the sanitizer', () => {+ _stubMarked();+ globalThis.DOMPurify = undefined;++ const out = window.ui.renderMarkdown(HOSTILE_MARKDOWN);++ // No raw markup survives: only escaped text inside <pre>.+ // (Attribute substrings like "onerror" may appear ESCAPED —+ // that is the safe rendering; raw tags must not exist.)+ expect(out).toMatch(/<pre/);+ expect(out).not.toContain('<img');+ expect(out).not.toContain('<script');+ expect(out).not.toContain('href="javascript:');+ });++ it('renders escaped plaintext on the closed path', () => {+ _stubMarked();+ globalThis.DOMPurify = undefined;++ const out = window.ui.renderMarkdown(HOSTILE_MARKDOWN);++ // Same contract as the marked-missing branch: the markdown's+ // own markup is visible only as escaped text.+ expect(out).toMatch(/<pre/);+ expect(out).toContain('<img');+ expect(out).toContain('onerror="'); // escaped attr form+ });++ it('fails closed when DOMPurify is present but unsupported', () => {+ _stubMarked();+ let sanitizeCalled = false;+ // An unsupported DOMPurify returns its input unchanged from+ // sanitize() -- that must not be treated as sanitized output.+ globalThis.DOMPurify = {+ isSupported: false,+ sanitize: (html) => {+ sanitizeCalled = true;+ return html;+ },+ };++ const out = window.ui.renderMarkdown(HOSTILE_MARKDOWN);++ expect(sanitizeCalled).toBe(false);+ expect(out).toMatch(/<pre/);+ expect(out).not.toContain('<img');+ expect(out).not.toContain('<script');+ expect(out).toContain('<img');+ });++ // DOMPurify computes isSupported as an && chain (typeof entries ===+ // 'function' && ... && implementation && implementation.createHTMLDocument+ // !== undefined), so a broken environment can yield null or undefined+ // rather than false -- and sanitize() passes input through on any falsy+ // value. Only isSupported === true may take the sanitize path.+ it.each([+ ['null', null],+ ['undefined', undefined],+ ['missing', '__omit__'],+ ])('fails closed when DOMPurify.isSupported is %s', (_label, value) => {+ _stubMarked();+ let sanitizeCalled = false;+ const purifier = {+ sanitize: (html) => {+ sanitizeCalled = true;+ return html;+ },+ };+ if (value !== '__omit__') {+ purifier.isSupported = value;+ }+ globalThis.DOMPurify = purifier;++ const out = window.ui.renderMarkdown(HOSTILE_MARKDOWN);++ expect(sanitizeCalled).toBe(false);+ expect(out).toMatch(/<pre/);+ expect(out).not.toContain('<img');+ expect(out).not.toContain('<script');+ expect(out).toContain('<img');+ });++ it('sanitizes through DOMPurify when it is available', () => {+ _stubMarked();+ let sanitizedInput = null;+ globalThis.DOMPurify = {+ isSupported: true,+ sanitize: (html) => {+ sanitizedInput = html;+ return '<p>clean</p>';+ },+ };++ const out = window.ui.renderMarkdown(HOSTILE_MARKDOWN);++ expect(sanitizedInput).toBe(HOSTILE_PARSED_HTML);+ expect(out).toContain('<p>clean</p>');+ });++ it('survives benign markdown when marked is unavailable', () => {+ globalThis.marked = undefined;+ globalThis.DOMPurify = undefined;++ const out = window.ui.renderMarkdown(BENIGN_MARKDOWN);++ // Escaped observable: the raw markup is visible only escaped.+ expect(out).toContain('<b>');+ expect(out).not.toContain('<b>');+ expect(out).not.toContain('<h1');+ });++ it('survives benign markdown when marked is available but DOMPurify is not', () => {+ _stubMarked(BENIGN_PARSED_HTML);+ globalThis.DOMPurify = undefined;++ const out = window.ui.renderMarkdown(BENIGN_MARKDOWN);++ // Same fail-closed contract as the marked-missing branch: escaped+ // plaintext, never the parsed markup, even though the input is benign.+ expect(out).toMatch(/<pre/);+ expect(out).toContain('<b>');+ expect(out).not.toContain('<b>bold</b>');+ });++ it('passes benign markdown through the sanitize path when both are available', () => {+ _stubMarked(BENIGN_PARSED_HTML);+ globalThis.DOMPurify = {+ isSupported: true,+ sanitize: (html) => html,+ };++ const out = window.ui.renderMarkdown(BENIGN_MARKDOWN);++ // The sanitize path is taken (not the plaintext fallback), and+ // safe markup like <b> survives it untouched.+ expect(out).not.toMatch(/<pre/);+ expect(out).toContain('<b>bold</b>');+ });+});diff --git a/tests/js/security/render-markdown-tabnabbing.test.js b/tests/js/security/render-markdown-tabnabbing.test.jsindex 39dfa75031..fb01738cbb 100644--- a/tests/js/security/render-markdown-tabnabbing.test.js+++ b/tests/js/security/render-markdown-tabnabbing.test.js@@ -68,6 +68,8 @@ describe('renderMarkdown ensures the tabnabbing hook', () => {registeredHooks = {};shadowedCount = 0;purifier = {+ // renderMarkdown trusts only an explicitly supported sanitizer.+ isSupported: true,addHook: (name, cb) => {registeredHooks[name] ||= [];registeredHooks[name].push(cb);diff --git a/tests/js/security/xss-protection-dompurify-runtime.test.js b/tests/js/security/xss-protection-dompurify-runtime.test.jsindex 4937950179..89fe62f2c3 100644--- a/tests/js/security/xss-protection-dompurify-runtime.test.js+++ b/tests/js/security/xss-protection-dompurify-runtime.test.js@@ -21,6 +21,7 @@ let afterSanitizeAttributes;beforeAll(async () => {realDOMPurify = createDOMPurify(window);purifierBoundary = {+ isSupported: true,addHook: vi.fn((name, callback) => {if (name === 'afterSanitizeAttributes') {afterSanitizeAttributes = callback;diff --git a/tests/js/security/xss-protection-late-dompurify.test.js b/tests/js/security/xss-protection-late-dompurify.test.jsindex b76515683a..da11c5e25f 100644--- a/tests/js/security/xss-protection-late-dompurify.test.js+++ b/tests/js/security/xss-protection-late-dompurify.test.js@@ -89,6 +89,7 @@ const makePurifier = () => {const stats = { shadowedCount: 0 };const lower = (list) => (list || []).map((x) => String(x).toLowerCase());const purifier = {+ isSupported: true,addHook: (name, cb) => {hooks[name] ||= [];hooks[name].push(cb);@@ -254,7 +255,7 @@ describe('tabnabbing hook under late-bound DOMPurify', () => {await import('@js/security/xss-protection.js');const warn = vi.spyOn(globalThis.SafeLogger, 'warn');try {- globalThis.DOMPurify = { sanitize: (dirty) => String(dirty) };+ globalThis.DOMPurify = { isSupported: true, sanitize: (dirty) => String(dirty) };expect(() => window.sanitizeHtml('<p>x</p>')).not.toThrow();window.sanitizeHtml('<p>y</p>');@@ -276,7 +277,7 @@ describe('tabnabbing hook under late-bound DOMPurify', () => {const savedLogger = globalThis.SafeLogger;try {globalThis.SafeLogger = {};- globalThis.DOMPurify = { sanitize: (dirty) => String(dirty) };+ globalThis.DOMPurify = { isSupported: true, sanitize: (dirty) => String(dirty) };expect(() => window.sanitizeHtml('<p>x</p>')).not.toThrow();} finally {globalThis.SafeLogger = savedLogger;diff --git a/tests/js/services/pdf-runtime.test.js b/tests/js/services/pdf-runtime.test.jsindex 0321bead21..00f68e78d6 100644--- a/tests/js/services/pdf-runtime.test.js+++ b/tests/js/services/pdf-runtime.test.js@@ -58,7 +58,7 @@ beforeEach(() => {globalThis.jsPDF = FakePdf;globalThis.html2canvas = vi.fn().mockResolvedValue(canvas());window.marked = { parse: vi.fn((markdown) => String(markdown)) };- window.DOMPurify = { sanitize: vi.fn((html) => html) };+ window.DOMPurify = { isSupported: true, sanitize: vi.fn((html) => html) };globalThis.URLValidator = {safeAssign: vi.fn((element, property, value) => {element[property] = value;diff --git a/tests/js/services/ui.test.js b/tests/js/services/ui.test.jsindex 7cd2011fcb..a1b6739860 100644--- a/tests/js/services/ui.test.js+++ b/tests/js/services/ui.test.js@@ -5,11 +5,31 @@* inline errors, escapeHtmlFallback, and notification system.*/+import RealDOMPurify from 'dompurify';import '@js/security/xss-protection.js';import '@js/services/ui.js';const ui = window.ui;+// showSpinner, showError and showAlert render through safeSetHTML, which+// only parses markup when a supported DOMPurify is bound (as on every page+// that loads the Vite bundle). Bind the real one for the blocks that assert+// rendered structure; the fail-closed fallback is covered separately below.+function bindRealDOMPurify() {+ let saved;+ beforeEach(() => {+ saved = globalThis.DOMPurify;+ globalThis.DOMPurify = RealDOMPurify;+ });+ afterEach(() => {+ if (saved === undefined) {+ delete globalThis.DOMPurify;+ } else {+ globalThis.DOMPurify = saved;+ }+ });+}+describe('ui service', () => {describe('updateProgressBar', () => {let fill, pct;@@ -73,6 +93,7 @@ describe('ui service', () => {});describe('showSpinner / hideSpinner', () => {+ bindRealDOMPurify();let container;beforeEach(() => {@@ -120,6 +141,7 @@ describe('ui service', () => {});describe('showError', () => {+ bindRealDOMPurify();let container;beforeEach(() => {@@ -509,6 +531,7 @@ describe('favicon status ownership', () => {});describe('page alerts', () => {+ bindRealDOMPurify();beforeEach(() => {window.LdrAlertHelpers = {mapAlertType: vi.fn(type => (@@ -561,3 +584,70 @@ describe('page alerts', () => {.toHaveLength(0);});});++describe('safeSetHTML fails closed without a supported DOMPurify', () => {+ // DOMPurify.isSupported can be false, null or undefined in a broken DOM+ // environment, and sanitize() then returns its input unchanged. Only an+ // instance reporting exactly true may be trusted; anything else (and a+ // missing DOMPurify) must render the markup as text, never as HTML.+ const PAYLOAD = '<img src=x onerror="window.__uiPwned=1">';+ let container;+ let saved;++ beforeEach(() => {+ saved = globalThis.DOMPurify;+ container = document.createElement('div');+ document.body.appendChild(container);+ });++ afterEach(() => {+ container.remove();+ if (saved === undefined) {+ delete globalThis.DOMPurify;+ } else {+ globalThis.DOMPurify = saved;+ }+ delete window.__uiPwned;+ });++ function expectPlainText(sanitize) {+ ui.showError(container, PAYLOAD);+ expect(container.children).toHaveLength(0);+ expect(container.querySelector('img')).toBeNull();+ expect(container.textContent).toContain('<div class="ldr-error-message">');+ expect(window.__uiPwned).toBeUndefined();+ if (sanitize) {+ expect(sanitize).not.toHaveBeenCalled();+ }++ ui.showSpinner(container, 'Loading');+ expect(container.children).toHaveLength(0);+ expect(container.textContent).toContain('ldr-loading-spinner');+ }++ it('renders text when DOMPurify is absent', () => {+ delete globalThis.DOMPurify;+ expectPlainText(null);+ });++ it.each([+ ['false', { isSupported: false }],+ ['null', { isSupported: null }],+ ['undefined', { isSupported: undefined }],+ ['missing', {}],+ ])('renders text when isSupported is %s', (_label, extra) => {+ // A passthrough sanitize, as DOMPurify's own is when unsupported.+ const sanitize = vi.fn(html => html);+ globalThis.DOMPurify = { ...extra, sanitize };+ expectPlainText(sanitize);+ });++ it('sanitizes through a supported DOMPurify', () => {+ const sanitize = vi.fn(() => '<div class="ldr-error-message">ok</div>');+ globalThis.DOMPurify = { isSupported: true, sanitize };+ ui.showError(container, 'boom');+ expect(sanitize).toHaveBeenCalledTimes(1);+ expect(sanitize.mock.calls[0][0]).toContain('boom');+ expect(container.querySelector('.ldr-error-message')).not.toBeNull();+ });+});diff --git a/tests/security/test_client_side_xss_sinks.py b/tests/security/test_client_side_xss_sinks.pyindex 838922001e..d6d2338939 100644--- a/tests/security/test_client_side_xss_sinks.py+++ b/tests/security/test_client_side_xss_sinks.py@@ -573,20 +573,32 @@ def test_report_markdown_is_dompurify_sanitised_before_display():assert "${sanitized}" in body-def test_report_markdown_sanitisation_is_conditional_on_dompurify():- """Pin the conditional, then pin what makes it safe.-- ``renderMarkdown`` sanitises only ``typeof DOMPurify !== 'undefined'``- and otherwise returns ``processedHtml`` — raw ``marked`` output. The- eleven suppressions that read "renderMarkdown() sanitizes internally- via DOMPurify" therefore hold only while ``marked`` and ``DOMPurify``- ship together. They do: one bundle entry point imports both and- assigns both to ``window`` in the same module body. Break that- pairing and the sanitiser disappears with no lint error.+def test_report_markdown_sanitisation_fails_closed_without_dompurify():+ """Pin the fail-closed shape, then pin what makes it reachable.++ ``renderMarkdown`` checks ``typeof DOMPurify === 'undefined'`` and,+ when true, returns early through the shared escaped-plaintext+ fallback — the unsanitized passthrough (``: processedHtml`` /+ ``return processedHtml``) must never come back. Both pins are scoped+ to renderMarkdown's own body: a file-wide check would also be+ satisfied by ``safeSetHTML``'s unrelated ``typeof DOMPurify !==+ 'undefined'`` branch (and by ``_escapedPlaintextFallback``'s own+ declaration), so it could keep passing even if renderMarkdown's+ fail-closed branch regressed entirely."""- body = _ui_js()- assert "typeof DOMPurify !== 'undefined'" in body- assert ": processedHtml" in body+ body = _ui_js().split("function renderMarkdown(markdown) {")[1]+ body = body.split("\nfunction ")[0]++ assert "typeof DOMPurify === 'undefined'" in body+ # Only an explicitly supported sanitizer is trusted: DOMPurify's+ # isSupported can be null/undefined as well as false, and sanitize()+ # passes input through unchanged whenever it is falsy.+ assert "DOMPurify?.isSupported !== true" in body+ # The fail-open passthrough must never come back.+ assert ": processedHtml" not in body+ assert "return processedHtml" not in body+ # The missing-sanitizer branch returns through the shared fallback.+ assert "return _escapedPlaintextFallback(markdown)" in bodyapp_js = (STATIC_JS / "app.js").read_text(encoding="utf-8")for line in (@@ -802,16 +814,25 @@ def test_snippet_sanitiser_allows_no_event_handler_attributes():assert "ALLOW_DATA_ATTR: false" in text-def test_safe_set_html_fallback_is_only_reached_without_dompurify():- """``safeSetHTML``'s suppression is circular; pin what it relies on."""+def test_safe_set_html_fails_closed_without_a_supported_dompurify():+ """``safeSetHTML`` trusts DOMPurify only when it is supported.++ DOMPurify's ``isSupported`` can be ``false``, ``null`` or+ ``undefined`` in a broken DOM environment, and ``sanitize()`` then+ returns its input unchanged; a missing DOMPurify must not fall back+ to raw ``innerHTML`` either. The only ``innerHTML`` write is the+ sanitized one, and the fallback assigns ``textContent``. Comments are+ stripped first so a commented-out guard cannot satisfy the pin.+ Behaviour is pinned by tests/js/services/ui.test.js.+ """body = _ui_js().split("function safeSetHTML(element, html) {")[1]- body = body.split("\n/**")[0]- assert "if (typeof DOMPurify !== 'undefined') {" in body+ body = _strip_js_comments(body.split("\n/**")[0])+ assert "DOMPurify?.isSupported === true" in bodyassert "element.innerHTML = DOMPurify.sanitize(html);" in body- # The unsanitised branch exists; it is reachable only before the- # module bundle has run, which is the same window that makes- # renderMarkdown fall back to plaintext.- assert body.count("element.innerHTML") == 2+ # No raw-innerHTML fallback: the sanitized write is the only one.+ assert body.count("innerHTML") == 1+ assert "element.textContent = html;" in body+ assert not re.search(r"innerHTML\s*=\s*html\b", body)# ---------------------------------------------------------------------diff --git a/tests/web/test_js_fetch_parity.py b/tests/web/test_js_fetch_parity.pyindex 976e05e508..2ca3ad2d2b 100644--- a/tests/web/test_js_fetch_parity.py+++ b/tests/web/test_js_fetch_parity.py@@ -973,7 +973,7 @@ LIVE_CASES = (# That is a separate defect (unguarded lookup) and out of scope here;# what matters for *this* test is that 500 means the body passed# validation and the handler ran.- js_ref="pages/news.js:1426",+ js_ref="pages/news.js:1428",method="POST",url=f"/news/api/feedback/{NOPE_UUID}",good={"vote": "up"},