~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(security): harden frontend rendering and preserve Markdown behavior (#5632)
LearningCircuit6ce858250ecc
diff --git a/changelog.d/+7365-pdf-export-hardened-sanitizer.security.md b/changelog.d/+7365-pdf-export-hardened-sanitizer.security.mdnew file mode 100644index 0000000000..e37b7852ca--- /dev/null+++ b/changelog.d/+7365-pdf-export-hardened-sanitizer.security.md@@ -0,0 +1 @@+PDF export now renders the report body through the same hardened pipeline as the on-screen report view (`ui.renderMarkdown`): raw author-supplied HTML is escaped to literal text and the output is sanitized to a reparse fixpoint under the restrictive allowlist, instead of a single pass of DOMPurify's default profile. PDF export fails closed if the sanitizer is unavailable. Fixes #7365.diff --git a/changelog.d/+frontend-xss-hardening.security.md b/changelog.d/+frontend-xss-hardening.security.mdnew file mode 100644index 0000000000..54e577285b--- /dev/null+++ b/changelog.d/+frontend-xss-hardening.security.md@@ -0,0 +1,86 @@+Hardened how the web frontend renders HTML and Markdown.++- Markdown (research reports, chat, notes and news findings) no longer+ renders raw HTML written in the Markdown source; it is shown as literal+ text. Content that deliberately embedded HTML, such as a `<details>`+ block, now displays the tags as text. The app's own report text no+ longer uses raw HTML: the error report for a failed research shows its+ partial results under a plain Markdown heading instead of a `<details>`+ block, and the HTML comment a detailed report places before its Sources+ list is removed when the report is saved, assembled for viewing or+ export, or used as news findings. It used to stay in reports saved with+ the "no hyperlinks" citation format or after a citation formatting+ error, and reports already saved that way are cleaned the same way when+ they are assembled or used as news findings.+- Markdown output is sanitized against an explicit allowlist (Markdown and+ GFM elements, tables, task-list checkboxes, links, images, and KaTeX's+ HTML, MathML and SVG output) instead of DOMPurify's default allowlist,+ and `data-*` attributes from the Markdown are dropped. A second pass then+ removes any `<input>` other than a checkbox and makes checkboxes+ display-only; rebuilds each inline `style` from the declarations the+ browser parsed, keeping only a fixed list of KaTeX layout and color+ properties whose values validate, so any other declaration (a `url(...)`+ value or `position: fixed`, for example) is dropped; keeps only class+ names on a renderer allowlist (KaTeX, syntax-highlighting tokens, GFM+ task lists and `language-*` code-block classes); and prefixes an `id` or+ `name` that matches an application global. That last step is defence in+ depth: no author-controlled `id` or `name` reaches it today.+- Markdown `` images keep only `src`, `alt` and `title`. The+ source must be http(s), ftp(s), a relative URL, or a PNG, JPEG, GIF, WebP+ or BMP `data:` URL; an SVG or any other `data:` type removes the image.+ Remote images were already blocked by the Content-Security-Policy+ (`img-src 'self' data:`) and still are, so the images that display are+ same-origin ones and those raster `data:` images.+- Generated-image references (`![ref:image-*]`) expand only when one stands+ alone as a paragraph; a reference inside a sentence, a link title or code+ is left as written. The image markup is built with DOM APIs, and the+ result is sanitized again before display.+- Markdown rendering falls back to escaped plain text when+ `XSSProtection.sanitizeStable` is unavailable, as it already did without+ marked or a supported DOMPurify.+- `sanitizeHtml()`, `safeSetInnerHTML()`, `services/ui.js`'s+ `safeSetHTML()` and `renderMarkdown()` now sanitize to a fixpoint:+ DOMPurify runs again until its output stops changing+ (`sanitize(s) === s`), so the tree the browser builds from the emitted+ string is one DOMPurify has already cleared under the same configuration.+ Markup still changing after five passes is shown as escaped text. Other+ direct DOMPurify call sites, such as PDF export (#7365) and semantic-search+ snippets, still sanitize once.+- `safeSetHTML()` (loading spinners, error banners and alerts) now+ sanitizes with the shared restrictive allowlist instead of DOMPurify's+ default profile, and shows text when `window.sanitizeHtml` is unavailable.+- Research results and the research-details panels no longer blank out+ parts of text that look like template syntax (`}}`, `${...}`, `%>`), such+ as nested JSON in an error message or a `${VAR}` shell example in a+ report.+- News feed card actions (the card menu, votes, save, subscribe and "View+ Full Report") now run only from the controls the feed rendered in each+ card's own menu and footer. A lookalike control inside a card's findings,+ or one added after rendering, triggers no card action, and each vote+ button's direction is fixed when the card is rendered.+- The shared DOMPurify link hook also rewrites a named link `target` (any+ value except `_self`, `_parent` and `_top`) to `_blank` and gives it+ `rel="noopener noreferrer"`, so a sanitized link cannot select another+ open window by name. `xss-protection.js` installs this hook when it+ loads, and the bundle installs it after publishing DOMPurify if+ `xss-protection.js` already ran; installing it twice does nothing. Pages+ built on the base template run the bundle first, so there+ `xss-protection.js` installs it. Either way, call sites that use+ DOMPurify directly after both scripts have run get the hook.+- `safeCreateElement()` now sets only allowlisted attributes (plus `aria-*`+ and `data-*`), accepts an `href` only if it is http(s), mailto, tel or+ relative (protocol-relative `//host` and backslash forms are rejected),+ and adds `rel="noopener noreferrer"` to links that open a new window. It+ has no call sites today, so this protects future callers only.+- The context-overflow panel coerces truncation rates and average response+ times to numbers before rendering, and the collection upload page+ URI-encodes the collection id in its "View Collection" link.+- New Vitest security suites cover these render paths, including an mXSS+ reparse suite. It runs in happy-dom, which has no MathML foreign-content+ support, so its MathML namespace-confusion cases are regression coverage+ only; see the suite header. The Python client-side sink checks were+ extended; a new check parses every template and fails unless each call+ of the `help_tip` macro, which renders its text with `|safe`, passes+ string literals, whether the macro is called by name, through an import+ alias or through a namespace import; and the real-browser mXSS suite+ from #6338 now checks that author-supplied MathML stays literal text.diff --git a/src/local_deep_research/error_handling/report_generator.py b/src/local_deep_research/error_handling/report_generator.pyindex 5d86371301..e2273b968f 100644--- a/src/local_deep_research/error_handling/report_generator.py+++ b/src/local_deep_research/error_handling/report_generator.py@@ -104,12 +104,15 @@ class ErrorReportGenerator:"- 💭 **Join discussions:** [Reddit r/LocalDeepResearch](https://www.reddit.com/r/LocalDeepResearch/) *(checked less frequently)*")- # Show partial results if available (in expandable section)+ # Show partial results if available, as a plain Markdown+ # section. The report is shown through renderMarkdown()+ # (services/ui.js), which displays raw HTML in Markdown as+ # literal text, so a <details> wrapper would show its tags.if error_analysis.get("has_partial_results"):partial_content = self._format_partial_results(partial_results)if partial_content:report_parts.append(- f"\n<details>\n<summary>📊 Partial Results Available</summary>\n\n{partial_content}\n</details>"+ f"\n## 📊 Partial Results Available\n\n{partial_content}")return "\n".join(report_parts)diff --git a/src/local_deep_research/news/api.py b/src/local_deep_research/news/api.pyindex 67c805d462..502e90d4e1 100644--- a/src/local_deep_research/news/api.py+++ b/src/local_deep_research/news/api.py@@ -137,6 +137,9 @@ def get_news_feed(# Import database functionsfrom ..database.session_context import get_user_db_sessionfrom ..database.models import ResearchHistory+ from ..text_optimization.citation_formatter import (+ strip_appended_sources_sentinel,+ )news_items: list[dict[str, Any]] = []remaining_limit = limit@@ -308,8 +311,15 @@ def get_news_feed("report_content") # Get database content- # Use database content- content = report_content_db+ # Use database content. A detailed report saved+ # in NO_HYPERLINKS mode, or after the citation+ # formatter raised, before the save site removed+ # it still carries the report generator's+ # appended-sources sentinel, an HTML comment the+ # card's renderMarkdown() would show as text.+ content = strip_appended_sources_sentinel(+ report_content_db+ )if content:logger.debug(f"Using database content for research {row['id']}"diff --git a/src/local_deep_research/text_optimization/citation_formatter.py b/src/local_deep_research/text_optimization/citation_formatter.pyindex 2853840c49..667b8dd30d 100644--- a/src/local_deep_research/text_optimization/citation_formatter.py+++ b/src/local_deep_research/text_optimization/citation_formatter.py@@ -226,8 +226,11 @@ def _safe_link_destination(url: str) -> str:# report. Looked up by ``find_sources_section`` so the splitter can locate# the appended sources section unambiguously, even when the LLM has# emitted its own ``## Sources`` (or ``References:`` etc.) header earlier-# in the prose. The sentinel is a markdown HTML comment so it round-trips-# through markdown renderers without affecting the displayed output.+# in the prose. The sentinel is an HTML comment, and renderMarkdown()+# (services/ui.js) shows raw HTML in Markdown as literal text, so it must+# not reach displayed report text: ``strip_appended_sources_sentinel``+# removes it when a detailed report is saved, when a saved report is+# assembled for display or export, and from news-feed findings.LDR_APPENDED_SOURCES_SENTINEL = "<!-- LDR_APPENDED_SOURCES_START -->"_SOURCES_SECTION_PATTERNS = [@@ -291,6 +294,36 @@ def find_sources_section(return -1, False+def strip_appended_sources_sentinel(content: str) -> str:+ """Remove the report generator's appended-sources sentinel from *content*.++ Only the occurrence ``find_sources_section`` trusts is removed: the last+ one that stands on its own line, which is the one+ ``IntegratedReportGenerator`` emitted. The line breaks around it are kept.+ A copy quoted inside a line, or an earlier one, is report text and is+ left as written.++ The sentinel is an HTML comment. renderMarkdown() (services/ui.js) shows+ raw HTML in Markdown as literal text, so a sentinel left in report text+ would appear on the page. The detailed-mode save site keeps the whole+ report, Sources block and sentinel included, in+ ``CitationMode.NO_HYPERLINKS`` mode and when the citation formatter+ raises; it now removes the sentinel before saving, and reports saved+ that way earlier still contain it.++ Anything that is not a non-empty string is returned unchanged.+ """+ if not isinstance(content, str) or not content:+ return content+ sentinel_start, on_sentinel = find_sources_section(content)+ if not on_sentinel:+ return content+ return (+ content[:sentinel_start]+ + content[sentinel_start + len(LDR_APPENDED_SOURCES_SENTINEL) :]+ )++_BIB_SOURCES_PATTERN = re.compile(r"^\[(\d+(?:,\s*\d+)*)\]\s*(.+?)(?:\n\s*URL:\s*(.+?))?$",re.MULTILINE,diff --git a/src/local_deep_research/web/services/report_assembly_service.py b/src/local_deep_research/web/services/report_assembly_service.pyindex df4bcb86fc..c94a3e7827 100644--- a/src/local_deep_research/web/services/report_assembly_service.py+++ b/src/local_deep_research/web/services/report_assembly_service.py@@ -30,6 +30,9 @@ from loguru import loggerfrom sqlalchemy.orm import Sessionfrom ...database.models.research import ResearchHistory, ResearchResource+from ...text_optimization.citation_formatter import (+ strip_appended_sources_sentinel,+)from ...utilities.search_utilities import (UNCITED_SOURCES_MODE_KEY,UNCITED_SOURCES_MODES,@@ -146,7 +149,12 @@ def assemble_full_report(if research is None:return None- body = research.report_content or ""+ # Detailed reports saved in NO_HYPERLINKS mode, or after the citation+ # formatter raised, before the save site removed it, still carry the+ # report generator's appended-sources sentinel. It is an HTML comment,+ # which renderMarkdown() shows as literal text, so it is removed before+ # the body is displayed or exported.+ body = strip_appended_sources_sentinel(research.report_content or "")# Legacy-row guard: older rows already contain inline# `## Sources` / `## Research Metrics` blocks in report_content. Ifdiff --git a/src/local_deep_research/web/services/research_service.py b/src/local_deep_research/web/services/research_service.pyindex 17d846c4cb..5aa987074d 100644--- a/src/local_deep_research/web/services/research_service.py+++ b/src/local_deep_research/web/services/research_service.py@@ -36,6 +36,9 @@ from ...utilities.thread_context import set_search_contextfrom ...report_generator import IntegratedReportGeneratorfrom ...search_system import AdvancedSearchSystemfrom ...text_optimization import CitationFormatter, CitationMode+from ...text_optimization.citation_formatter import (+ strip_appended_sources_sentinel,+)from ...utilities.log_utils import log_for_researchfrom ...utilities.search_utilities import extract_links_from_search_resultsfrom ...utilities.type_utils import overlay_runtime_settings@@ -2693,7 +2696,13 @@ def run_research_process(research_id, query, mode, **kwargs):research_id,)answer_with_links = final_report["content"]- formatted_content = answer_with_links+ # The answer keeps the generator's appended-sources sentinel+ # whenever the split above kept the Sources block with it+ # (NO_HYPERLINKS mode, or the formatter raised). It is an HTML+ # comment, which renderMarkdown() shows as literal text.+ formatted_content = strip_appended_sources_sentinel(+ answer_with_links+ )# Save report FIRST, sources after.# See quick-summary path for rationale.diff --git a/src/local_deep_research/web/static/js/app.js b/src/local_deep_research/web/static/js/app.jsindex 02a0f59676..ae0ca803bd 100644--- a/src/local_deep_research/web/static/js/app.js+++ b/src/local_deep_research/web/static/js/app.js@@ -41,6 +41,14 @@ window.html2canvas = html2canvas;window.bootstrap = bootstrap;window.Chart = Chart;window.DOMPurify = DOMPurify;+// Non-async module scripts and defer classic scripts run in document order.+// base.html loads this bundle in <head>, before its deferred+// xss-protection.js, so on those pages the call below finds no XSSProtection+// and does nothing: xss-protection.js sees window.DOMPurify and installs the+// same idempotent hook during its own load. The call covers a page that runs+// xss-protection.js before this bundle, where that load-time install found+// no DOMPurify yet.+window.XSSProtection?.ensureDOMPurifyHooks?.();// Configure markedmarked.setOptions({diff --git a/src/local_deep_research/web/static/js/collection_upload.js b/src/local_deep_research/web/static/js/collection_upload.jsindex cf6a0f7e1f..4b350da848 100644--- a/src/local_deep_research/web/static/js/collection_upload.js+++ b/src/local_deep_research/web/static/js/collection_upload.js@@ -868,7 +868,7 @@ function showUploadResults(data) {// Action buttonshtml += '<div style="margin-top: 1.5rem; display: flex; gap: 1rem; flex-wrap: wrap;">';- html += `<a href="/library/collections/${COLLECTION_ID}" class="ldr-btn-collections ldr-btn-collections-primary">+ html += `<a href="/library/collections/${encodeURIComponent(COLLECTION_ID)}" class="ldr-btn-collections ldr-btn-collections-primary"><i class="fas fa-folder-open"></i> View Collection</a>`;html += `<button onclick="location.reload()" class="ldr-btn-collections ldr-btn-collections-secondary">diff --git a/src/local_deep_research/web/static/js/components/context-overflow.js b/src/local_deep_research/web/static/js/components/context-overflow.jsindex 1dc2e0667d..b71c6cc3de 100644--- a/src/local_deep_research/web/static/js/components/context-overflow.js+++ b/src/local_deep_research/web/static/js/components/context-overflow.js@@ -53,6 +53,10 @@return div.innerHTML.replace(/"/g, '"').replace(/'/g, ''');}+ function escapeHtmlAttribute(text) {+ return escapeHtml(text).replace(/"/g, '"').replace(/'/g, ''');+ }+// Helper function to format model names for better displayfunction formatModelName(model) {if (!model) return 'N/A';@@ -456,7 +460,7 @@<tr><td style="white-space: nowrap;">${timestamp}</td><td>${researchLink}</td>- <td title="${escapeHtml(req.model)}">${escapeHtml(formatModelName(req.model))}</td>+ <td title="${escapeHtmlAttribute(req.model)}">${escapeHtml(formatModelName(req.model))}</td><td>${escapeHtml(formatProviderName(req.provider))}</td><td>${escapeHtml(req.research_phase || 'N/A')}</td><td style="text-align: right;">${formatNumber(req.prompt_tokens)}</td>@@ -465,7 +469,7 @@<td style="text-align: right;">${contextLimit}</td><td style="text-align: center;">${truncatedBadge}</td><td style="text-align: right;" class="${truncationClass}">${formatNumber(tokensLost)}</td>- <td style="max-width: 200px; overflow: hidden; text-overflow: ellipsis;" title="${escapeHtml(req.research_query)}">${escapeHtml(req.research_query || 'N/A')}</td>+ <td style="max-width: 200px; overflow: hidden; text-overflow: ellipsis;" title="${escapeHtmlAttribute(req.research_query)}">${escapeHtml(req.research_query || 'N/A')}</td></tr>`;});@@ -508,7 +512,8 @@});modelStats.forEach(stat => {- const truncationPercent = stat.truncation_rate;+ const truncationRate = Number(stat.truncation_rate);+ const truncationPercent = Number.isFinite(truncationRate) ? truncationRate : 0;const card = document.createElement('div');card.className = 'ldr-model-card';@@ -518,13 +523,16 @@const hasUtil = stat.avg_context_limit && tokenStats.avg_prompt;const utilPct = hasUtil ? Math.round((tokenStats.avg_prompt / stat.avg_context_limit) * 100) : 0;const utilColor = utilPct > 80 ? 'var(--error-color)' : utilPct > 50 ? 'var(--warning-color)' : 'var(--success-color)';+ const responseTime = Number(tokenStats.avg_response_time_ms);+ const responseTimeMs = Number.isFinite(responseTime) ? responseTime : 0;+ const responseDuration = responseTimeMs >= 1000 ? `${(responseTimeMs / 1000).toFixed(1)}s` : `${responseTimeMs}ms`;// bearer:disable javascript_lang_dangerous_insert_html// eslint-disable-next-line no-unsanitized/property -- `truncationRateClass` is hardcoded to one of three string literals; model/provider go through escapeHtml; numeric stats go through formatNumber; utilColor is hardcoded to one of three CSS variablescard.innerHTML = `<div class="ldr-model-header"><div>- <div class="ldr-model-name" title="${escapeHtml(stat.model)}">${escapeHtml(formatModelName(stat.model))}</div>+ <div class="ldr-model-name" title="${escapeHtmlAttribute(stat.model)}">${escapeHtml(formatModelName(stat.model))}</div><div class="ldr-model-provider">${escapeHtml(formatProviderName(stat.provider))}</div></div><div style="text-align: right;">@@ -584,7 +592,7 @@${tokenStats.avg_response_time_ms ? `<div style="margin-top: 0.5rem; font-size: 0.75rem;" class="ldr-text-secondary">- <span><i aria-hidden="true" class="fas fa-clock" style="margin-right: 0.25rem;"></i>Avg ${tokenStats.avg_response_time_ms >= 1000 ? (tokenStats.avg_response_time_ms / 1000).toFixed(1) + 's' : tokenStats.avg_response_time_ms + 'ms'}</span>+ <span><i aria-hidden="true" class="fas fa-clock" style="margin-right: 0.25rem;"></i>Avg ${responseDuration}</span></div>` : ''}`;diff --git a/src/local_deep_research/web/static/js/components/details.js b/src/local_deep_research/web/static/js/components/details.jsindex e9cb6b4b89..44680a9404 100644--- a/src/local_deep_research/web/static/js/components/details.js+++ b/src/local_deep_research/web/static/js/components/details.js@@ -125,7 +125,7 @@`).join('');if (window.sanitizeHtml) {// bearer:disable javascript_lang_dangerous_insert_html- domainList.innerHTML = window.sanitizeHtml(domainHtml);+ domainList.innerHTML = window.sanitizeHtml(domainHtml, { SAFE_FOR_TEMPLATES: false });} else {// bearer:disable javascript_lang_dangerous_insert_html// eslint-disable-next-line no-unsanitized/property -- all dynamic fields use the always-available local escapeHtml helper@@ -169,7 +169,7 @@}).join('');if (window.sanitizeHtml) {// bearer:disable javascript_lang_dangerous_insert_html- resourceSample.innerHTML = window.sanitizeHtml(resourceHtml);+ resourceSample.innerHTML = window.sanitizeHtml(resourceHtml, { SAFE_FOR_TEMPLATES: false });} else {// 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 stringsdiff --git a/src/local_deep_research/web/static/js/components/research.js b/src/local_deep_research/web/static/js/components/research.jsindex 5dc6ab297d..e13badc8f2 100644--- a/src/local_deep_research/web/static/js/components/research.js+++ b/src/local_deep_research/web/static/js/components/research.js@@ -256,9 +256,14 @@}// Set mode via the visible label element so both the radio and- // the visual highlight update correctly+ // the visual highlight update correctly. Match the stored mode+ // against the rendered options by attribute comparison instead of+ // building a selector from the stored value; unknown or hostile+ // values match no option and leave the default mode selected.if (config.mode) {- const modeOption = document.querySelector(`.ldr-mode-option[data-mode="${CSS.escape(config.mode)}"]`);+ const modeOption = Array.from(modeOptions).find(+ option => option.getAttribute('data-mode') === config.mode+ );if (modeOption) {selectMode(modeOption);}diff --git a/src/local_deep_research/web/static/js/components/results.js b/src/local_deep_research/web/static/js/components/results.jsindex 66d5b8ffe3..0eed59c35d 100644--- a/src/local_deep_research/web/static/js/components/results.js+++ b/src/local_deep_research/web/static/js/components/results.js@@ -601,8 +601,17 @@} else if (data.html) {// HTML content - sanitize for securityif (window.sanitizeHtml) {+ // SAFE_FOR_TEMPLATES: false -- this is a research report+ // body, which can legitimately contain plain-text prose+ // matching mustache/ERB/template-literal syntax (nested+ // JSON ending in `}}`, `${VAR}` shell-variable mentions,+ // `%>`) -- not markup, since SANITIZE_CONFIG's+ // ALLOWED_TAGS has no `pre`/`code`/`table`, so a fenced+ // code block never survives as one anyway. The default+ // would silently blank that text; this page renders it,+ // not a client-side template.// bearer:disable javascript_lang_dangerous_insert_html- resultsContainer.innerHTML = window.sanitizeHtml(data.html);+ resultsContainer.innerHTML = window.sanitizeHtml(data.html, { SAFE_FOR_TEMPLATES: false });} else if (window.escapeHtml) {// Fallback to HTML escaping if DOMPurify not available// bearer:disable javascript_lang_dangerous_insert_htmldiff --git a/src/local_deep_research/web/static/js/components/settings.js b/src/local_deep_research/web/static/js/components/settings.jsindex bfc81fdb3b..37d6cd78b7 100644--- a/src/local_deep_research/web/static/js/components/settings.js+++ b/src/local_deep_research/web/static/js/components/settings.js@@ -248,6 +248,7 @@// Use global escapeHtml from xss-protection.js with fallbackconst escapeHtml = window.escapeHtml || escapeHtmlFallback;+ const escapeHtmlAttribute = window.escapeHtmlAttribute || escapeHtmlFallback;// Preserve existing IDs for registered keys. Encode all code units of// custom metadata so quotes cannot break attributes and dot/dash pairs@@ -294,11 +295,11 @@* @returns {string} HTML string for the custom dropdown input part*/function renderCustomDropdownHTML(params) {- const dropdownId = escapeHtml(params.dropdown_id);- const inputId = escapeHtml(params.input_id);- const settingKey = escapeHtml(params.data_setting_key || params.input_id);- const placeholder = escapeHtml(params.placeholder || '');- const labelId = params.label_id ? escapeHtml(params.label_id) : '';+ const dropdownId = escapeHtmlAttribute(params.dropdown_id);+ const inputId = escapeHtmlAttribute(params.input_id);+ const settingKey = escapeHtmlAttribute(params.data_setting_key || params.input_id);+ const placeholder = escapeHtmlAttribute(params.placeholder || '');+ const labelId = params.label_id ? escapeHtmlAttribute(params.label_id) : '';// Basic structure with input and list containerlet dropdownHTML = `<div class="ldr-custom-dropdown" id="${dropdownId}">@@ -326,7 +327,7 @@<button type="button"class="ldr-custom-dropdown-refresh-btn"id="${inputId}-refresh"- aria-label="${escapeHtml(params.refresh_aria_label || 'Refresh options')}">+ aria-label="${escapeHtmlAttribute(params.refresh_aria_label || 'Refresh options')}"><i class="fas fa-sync-alt" aria-hidden="true"></i></button>` : '';@@ -1832,25 +1833,25 @@);// Create a mapping of types- const typeMap = {+ const typeMap = Object.assign(Object.create(null), {'app': 'Application','llm': 'Language Models','search': 'Search Engines','report': 'Reports'- };+ });// Map auxiliary key prefixes onto the tab that should render// them. egress-policy keys live under their own prefixes// (policy.*, embeddings.*) but conceptually belong to existing// tabs — without this remap the settings dashboard silently// hides them since no 'policy' / 'embeddings' tab exists.- const prefixToTab = {+ const prefixToTab = Object.assign(Object.create(null), {'policy': 'search','embeddings': 'search'- };+ });// Define settings that should only appear in specific tabs- const tabSpecificSettings = {+ const tabSpecificSettings = Object.assign(Object.create(null), {'llm': ['provider','model',@@ -1898,15 +1899,15 @@'warnings','allow_registrations']- };+ });// Priority settings that should appear at the top of each tab- const prioritySettings = {+ const prioritySettings = Object.assign(Object.create(null), {'app': ['enable_web', 'enable_notifications', 'web_interface', 'theme', 'default_theme', 'dark_mode', 'debug', 'host', 'port', 'warnings'],'llm': ['provider', 'model', 'temperature', 'max_tokens', 'api_key', 'openai_endpoint_url', 'lmstudio_url', 'llamacpp_url'],'search': ['tool', 'iterations', 'questions_per_iteration', 'max_results', 'region', 'search_engine'],'report': ['knowledge_accumulation']- };+ });// Group by prefix and categoryconst grouped = Object.create(null);@@ -2877,7 +2878,7 @@SafeLogger.log('Processing Setting:', setting.key, 'UI Element:', setting.ui_element);const settingId = settingIdFor(setting.key);- const settingKeyAttribute = escapeHtml(setting.key);+ const settingKeyAttribute = escapeHtmlAttribute(setting.key);let inputElement;// Generate the appropriate input element based on UI element type@@ -3069,16 +3070,16 @@case 'slider':case 'range': {- const min = setting.min_value !== null ? setting.min_value : 0;- const max = setting.max_value !== null ? setting.max_value : 100;- const step = setting.step !== null ? setting.step : 1;+ const min = setting.min_value ?? 0;+ const max = setting.max_value ?? 100;+ const step = setting.step ?? 1;inputElement = `<div class="ldr-settings-range-container"><input type="range" id="${settingId}" name="${settingKeyAttribute}"class="ldr-settings-range ldr-form-control"value="${escapeHtml(String(setting.value !== null ? setting.value : min))}"- min="${escapeHtml(String(min))}" max="${escapeHtml(String(max))}" step="${escapeHtml(String(step))}"+ min="${escapeHtmlAttribute(String(min))}" max="${escapeHtmlAttribute(String(max))}" step="${escapeHtmlAttribute(String(step))}"${!setting.editable ? 'disabled' : ''}><span class="ldr-settings-range-value">${escapeHtml(String(setting.value !== null ? setting.value : min))}</span>@@ -3088,15 +3089,15 @@}case 'number': {- const numMin = setting.min_value !== null ? setting.min_value : '';- const numMax = setting.max_value !== null ? setting.max_value : '';- const numStep = setting.step !== null ? setting.step : 1;+ const numMin = setting.min_value ?? '';+ const numMax = setting.max_value ?? '';+ const numStep = setting.step ?? 1;inputElement = `<input type="number" id="${settingId}" name="${settingKeyAttribute}"class="ldr-settings-input ldr-form-control"value="${escapeHtml(String(setting.value !== null ? setting.value : ''))}"- min="${escapeHtml(String(numMin))}" max="${escapeHtml(String(numMax))}" step="${escapeHtml(String(numStep))}"+ min="${escapeHtmlAttribute(String(numMin))}" max="${escapeHtmlAttribute(String(numMax))}" step="${escapeHtmlAttribute(String(numStep))}"${!setting.editable ? 'disabled' : ''}>`;@@ -3207,7 +3208,7 @@* @returns {string} - The HTML for the expanded JSON controls*/function renderExpandedJsonControls(setting, settingId, jsonObj) {- const settingKeyAttribute = escapeHtml(setting.key);+ const settingKeyAttribute = escapeHtmlAttribute(setting.key);let html = `<div class="ldr-settings-item form-group" data-key="${settingKeyAttribute}"><div class="ldr-settings-item-header">@@ -3216,7 +3217,7 @@</label></div><div class="ldr-json-expanded-controls">- <input type="hidden" id="${settingId}_original" name="${escapeHtml(`${setting.key}_original`)}"+ <input type="hidden" id="${settingId}_original" name="${escapeHtmlAttribute(`${setting.key}_original`)}"value="${escapeHtml(JSON.stringify(jsonObj))}"><div class="ldr-json-property-controls">@@ -3226,8 +3227,8 @@for (const key of Object.keys(jsonObj)) {const value = jsonObj[key];const controlId = jsonPropertyIdFor(settingId, key);- const propertyKeyAttribute = escapeHtml(key);- const compoundNameAttribute = escapeHtml(`${setting.key}_${key}`);+ const propertyKeyAttribute = escapeHtmlAttribute(key);+ const compoundNameAttribute = escapeHtmlAttribute(`${setting.key}_${key}`);const formattedName = formatPropertyName(key);let controlHtml;@@ -5030,6 +5031,8 @@// Initialize JSON handlinginitJsonFormatting();+ initCheckboxWrappers();+// Load settings from API if on settings dashboardif (settingsContent) {// Load settings immediately (doesn't depend on providers/engines)diff --git a/src/local_deep_research/web/static/js/pages/news.js b/src/local_deep_research/web/static/js/pages/news.jsindex 8e1b401385..14fda13251 100644--- a/src/local_deep_research/web/static/js/pages/news.js+++ b/src/local_deep_research/web/static/js/pages/news.js@@ -26,6 +26,16 @@ function safeRenderHTML(container, htmlString) {return;}+ // Single-pass, not the sanitizeStable() reparse-fixpoint loop used+ // elsewhere in this hardening pass -- but RETURN_DOM_FRAGMENT makes a+ // second pass unnecessary here specifically: DOMPurify hands back the+ // DOM nodes it just built and validated, and those nodes are appended+ // directly below with no round trip through HTML serialization/+ // reparsing in between. The mXSS class sanitizeStable guards against+ // exists precisely because a sanitizer inspects one tree but ships a+ // serialization that the browser re-parses into a different one; that+ // gap does not open here, so this is genuinely reparse-immune despite+ // being single-pass.const fragment = window.DOMPurify.sanitize(htmlString, { RETURN_DOM_FRAGMENT: true });// Clear the container safely@@ -106,6 +116,33 @@ let newsResearchRestoreId = 0;let activeNewsSubscriptionSubmit = null;const activeAdvancedNewsSearches = new Map();+// News-card actions are delegated only from the two application-rendered+// action regions below. The Markdown sanitizer also strips data-* attributes,+// but matching an attribute is deliberately not treated as a trust boundary:+// exact controls and regions must have been registered during app rendering.+const NEWS_ACTION_REGION = Object.freeze({+ MENU: 'menu',+ FOOTER: 'footer'+});+const NEWS_ACTIONS_BY_REGION = Object.freeze({+ [NEWS_ACTION_REGION.MENU]: new Set([+ 'toggle-read',+ 'share',+ 'copy-link',+ 'export-markdown',+ 'hide'+ ]),+ [NEWS_ACTION_REGION.FOOTER]: new Set([+ 'vote',+ 'mark-read-on-click',+ 'toggle-save',+ 'create-subscription'+ ])+});+const trustedNewsActionRegions = new WeakMap();+const trustedNewsActionControls = new WeakMap();+const newsActionDelegationRoots = new WeakSet();+// Semantic search stateconst NEWS_SM = { HYBRID: 'hybrid', TEXT: 'text', SEMANTIC: 'semantic' };let newsSearchMode = NEWS_SM.HYBRID;@@ -426,58 +463,6 @@ function setupEventListeners() {}});- // DOMPurify deliberately removes inline event handlers from the rendered- // feed. Keep card actions declarative and dispatch them from this stable- // listener so re-rendered cards remain interactive after sanitization.- document.addEventListener('click', (e) => {- const actionControl = e.target.closest('[data-news-action]');- const newsItem = actionControl?.closest('.ldr-news-item');- if (!actionControl || !newsItem) return;-- const newsId = newsItem.dataset.newsId;- if (!newsId) return;-- const action = actionControl.dataset.newsAction;- // Only the report link should retain its normal navigation. The menu- // actions use href="#" and the remaining controls are buttons.- if (action !== 'mark-read') e.preventDefault();-- switch (action) {- case 'toggle-read':- toggleReadStatus(newsId);- break;- case 'share':- shareNews(newsId);- break;- case 'copy-link':- copyNewsLink(newsId);- break;- case 'export-markdown':- exportToMarkdown(newsId);- break;- case 'hide':- hideNewsItem(newsId);- break;- case 'vote':- if (actionControl.dataset.voteType === 'up' ||- actionControl.dataset.voteType === 'down') {- vote(newsId, actionControl.dataset.voteType);- }- break;- case 'mark-read':- markAsReadOnClick(newsId);- break;- case 'toggle-save':- toggleSaveItem(newsId);- break;- case 'subscribe':- createSubscriptionFromItem(newsId);- break;- default:- break;- }- });-// Event delegation for news card clicksdocument.addEventListener('click', (e) => {// Find the closest news-item parent@@ -899,51 +884,11 @@ async function loadSubscriptions() {}}-// Render subscriptions - REMOVED: Subscription list moved to dedicated page-/* function renderSubscriptions() {- const container = document.getElementById('sidebar-subscriptions-list');-- // Add "All" option- let html = `- <div class="ldr-subscription-item ${activeSubscription === 'all' ? 'active' : ''}"- onclick="selectSubscription('all')">- <div class="ldr-subscription-type">ALL FEEDS</div>- <div class="ldr-subscription-query">Combined News Feed</div>- <div class="ldr-subscription-meta">All your subscriptions</div>- </div>- <div class="ldr-subscription-item ${activeSubscription === 'saved' ? 'active' : ''}"- onclick="selectSubscription('saved')">- <div class="ldr-subscription-type">SAVED</div>- <div class="ldr-subscription-query">Bookmarked Items</div>- <div class="ldr-subscription-meta">${savedNewsIds.size} saved items</div>- </div>- `;-- // Add user subscriptions- subscriptions.forEach(sub => {- const typeLabel = sub.type === 'search' ? 'SEARCH' : 'TOPIC';- const query = sub.query || sub.topic || 'Unknown';- const nextRefresh = sub.next_refresh ? new Date(sub.next_refresh).toLocaleString() : 'Soon';-- html += `- <div class="ldr-subscription-item ${activeSubscription === sub.id ? 'active' : ''}"- onclick="selectSubscription('${sub.id}')">- <div class="ldr-subscription-header">- <div>- <div class="ldr-subscription-type">${typeLabel}</div>- <div class="ldr-subscription-query">${query}</div>- <div class="ldr-subscription-meta">Next: ${nextRefresh}</div>- </div>- <button class="btn btn-sm ldr-btn-ghost" onclick="showSubscriptionHistory('${sub.id}'); event.stopPropagation();" title="View history">- <i class="bi bi-clock-history"></i>- </button>- </div>- </div>- `;- });-- safeRenderHTML(container, html);-} */+// Subscription sidebar list REMOVED: moved to the dedicated+// /news/subscriptions page (pages/subscriptions.js). The old commented-out+// renderSubscriptions() template was deleted rather than kept as dead code —+// it interpolated `sub.id` into inline onclick handlers with NO escaping at+// all, so reviving it would have reintroduced a script-injection sink.// Select subscriptionfunction selectSubscription(subId) {@@ -1046,6 +991,114 @@ async function loadNewsFeed(focus = null, explicitView = false) {}}+function directChildWithClass(parent, className) {+ if (!parent) return null;+ return Array.from(parent.children).find(child => child.classList.contains(className)) || null;+}++// Mark only regions at the exact structure produced by renderNewsItems().+// A lookalike region nested in Markdown is never entered into this WeakMap,+// even if it copies every class and data attribute used by a real control.+function registerTrustedNewsActionRegions(root) {+ for (const card of root.children) {+ if (!card.classList.contains('ldr-news-item')) continue;++ const header = directChildWithClass(card, 'ldr-news-item-header');+ const menu = directChildWithClass(header, 'ldr-news-actions-menu');+ const footer = directChildWithClass(card, 'ldr-news-actions');++ if (menu) {+ trustedNewsActionRegions.set(menu, {+ card,+ region: NEWS_ACTION_REGION.MENU+ });+ registerTrustedNewsActionControls(menu, card, NEWS_ACTION_REGION.MENU);+ }+ if (footer) {+ trustedNewsActionRegions.set(footer, {+ card,+ region: NEWS_ACTION_REGION.FOOTER+ });+ registerTrustedNewsActionControls(footer, card, NEWS_ACTION_REGION.FOOTER);+ }+ }+}++function registerTrustedNewsActionControls(actionRegion, card, region) {+ for (const control of actionRegion.querySelectorAll('[data-news-action]')) {+ const action = control.dataset.newsAction;+ if (!NEWS_ACTIONS_BY_REGION[region].has(action)) continue;++ trustedNewsActionControls.set(control, {+ action,+ actionRegion,+ card,+ region,+ voteType: action === 'vote' ? control.dataset.vote : null+ });+ }+}++function dispatchTrustedNewsAction(event, root) {+ if (!(event.target instanceof Element)) return;++ const actionTarget = event.target.closest('[data-news-action]');+ if (!actionTarget || !root.contains(actionTarget)) return;++ const trustedControl = trustedNewsActionControls.get(actionTarget);+ if (!trustedControl) return;++ const actionRegion = actionTarget.closest('.ldr-news-actions-menu, .ldr-news-actions');+ const trustedRegion = actionRegion && trustedNewsActionRegions.get(actionRegion);+ if (!trustedRegion) return;++ const { card: actionCard, region } = trustedControl;+ if (+ trustedRegion.card !== actionCard ||+ trustedRegion.region !== region ||+ trustedControl.actionRegion !== actionRegion+ ) return;+ if (actionCard.parentElement !== root || actionTarget.closest('.ldr-news-item') !== actionCard) return;++ const action = actionTarget.dataset.newsAction;+ if (action !== trustedControl.action || !NEWS_ACTIONS_BY_REGION[region].has(action)) return;++ const newsId = actionCard.dataset.newsId;++ // Dropdown entries are <a href="#"> — their old inline handlers ended+ // in `return false`, so keep suppressing the fragment navigation, but+ // only after the element has passed the trusted-region checks above.+ if (actionTarget.tagName === 'A' && actionTarget.getAttribute('href') === '#') {+ event.preventDefault();+ }++ switch (action) {+ case 'toggle-read': toggleReadStatus(newsId); break;+ case 'share': shareNews(newsId); break;+ case 'copy-link': copyNewsLink(newsId); break;+ case 'export-markdown': exportToMarkdown(newsId); break;+ case 'hide': hideNewsItem(newsId); break;+ case 'vote': {+ const voteType = actionTarget.dataset.vote;+ if (+ voteType === trustedControl.voteType &&+ (voteType === 'up' || voteType === 'down')+ ) vote(newsId, voteType);+ break;+ }+ case 'mark-read-on-click': markAsReadOnClick(newsId); break;+ case 'toggle-save': toggleSaveItem(newsId); break;+ case 'create-subscription': createSubscriptionFromItem(newsId); break;+ default: break;+ }+}++function setupNewsActionDelegation(root) {+ if (newsActionDelegationRoots.has(root)) return;+ root.addEventListener('click', event => dispatchTrustedNewsAction(event, root));+ newsActionDelegationRoots.add(root);+}+// Render news itemsfunction renderNewsItems(searchQuery = null) {const container = document.getElementById('news-feed-content');@@ -1241,21 +1294,21 @@ function renderNewsItems(searchQuery = null) {${renderSourceLinks(item.links)}<div class="ldr-news-actions"><div class="ldr-vote-buttons">- <button class="ldr-vote-btn" data-news-action="vote" data-vote-type="up">+ <button class="ldr-vote-btn" data-news-action="vote" data-vote="up"><i class="fas fa-thumbs-up"></i> ${Number(item.upvotes) || 0}</button>- <button class="ldr-vote-btn" data-news-action="vote" data-vote-type="down">+ <button class="ldr-vote-btn" data-news-action="vote" data-vote="down"><i class="fas fa-thumbs-down"></i> ${Number(item.downvotes) || 0}</button></div><div class="ldr-action-buttons">- <a href="${safeHref(item.source_url || `/results/${item.research_id}`)}" class="btn btn-primary btn-sm" data-news-action="mark-read">+ <a href="${safeHref(item.source_url || `/results/${item.research_id}`)}" class="btn btn-primary btn-sm" data-news-action="mark-read-on-click"><i class="fas fa-file-alt"></i> View Full Report</a><button class="btn btn-secondary btn-sm ldr-save-btn" data-news-action="toggle-save" title="${savedNewsIds.has(item.id) ? 'Remove from saved' : 'Save for later'}"><i class="${savedNewsIds.has(item.id) ? 'bi bi-bookmark-fill' : 'bi bi-bookmark'}"></i></button>- ${item.query ? `<button class="btn btn-outline-primary btn-sm" data-news-action="subscribe" title="Create subscription from this search">+ ${item.query ? `<button class="btn btn-outline-primary btn-sm" data-news-action="create-subscription" title="Create subscription from this search"><i class="bi bi-bell-plus"></i> Subscribe</button>` : ''}</div>@@ -1266,6 +1319,8 @@ function renderNewsItems(searchQuery = null) {// Use safe renderingsafeRenderHTML(container, fullHtml);+ registerTrustedNewsActionRegions(container);+ setupNewsActionDelegation(container);// Update table view if activeconst tableToggle = document.getElementById('table-view-toggle');diff --git a/src/local_deep_research/web/static/js/security/url-validator.js b/src/local_deep_research/web/static/js/security/url-validator.jsindex 0a03ced735..5203770262 100644--- a/src/local_deep_research/web/static/js/security/url-validator.js+++ b/src/local_deep_research/web/static/js/security/url-validator.js@@ -7,6 +7,42 @@ const URLValidator = {UNSAFE_SCHEMES: ['javascript', 'data', 'vbscript', 'about', 'blob', 'file'],SAFE_SCHEMES: ['http', 'https', 'ftp', 'ftps'],EMAIL_SCHEME: 'mailto',+ // Raster MIME types a Markdown image may use as a `data:` source. Read+ // only by services/ui.js's isSafeMarkdownImageSrc. safeAssign's data:+ // carve-out below does NOT read this list; see the note there.+ SAFE_DATA_MIME_TYPES: [+ 'image/png',+ 'image/jpeg',+ 'image/jpg',+ 'image/gif',+ 'image/webp',+ 'image/bmp'+ ],++ /**+ * Strip what a browser could ignore in a URL before scheme/MIME+ * detection: leading/trailing whitespace, then every C0 control+ * character (and space, and DEL) anywhere in the string. Browsers strip+ * only leading/trailing C0 controls and spaces plus every tab, LF and+ * CR, so this removes a superset of what they ignore, and a check run+ * on the result cannot be dodged by a character the browser would+ * discard (e.g. a tab between "data:" and the MIME type).+ *+ * Its only caller is services/ui.js's isSafeMarkdownImageSrc.+ * safeAssign does not use it: its data: carve-out matches a raw-string+ * regex against `url.trim()`, so a control character inside the+ * `data:<mime>;base64,` prefix makes that match fail and the value is+ * blocked rather than normalized.+ * @param {string} url - The value to normalize.+ * @returns {string} - The normalized value, or '' for non-strings.+ */+ normalizeUrlForSchemeCheck(url) {+ if (typeof url !== 'string') {+ return '';+ }+ // eslint-disable-next-line no-control-regex -- intentional: browsers ignore control characters inside URLs, so they must be stripped before scheme/MIME detection+ return url.trim().replace(/[\x00-\x20\x7F]/g, '');+ },isUnsafeScheme(url) {if (!url) return false;@@ -170,6 +206,16 @@ const URLValidator = {// raster image assigned to an <img> or favicon <link>, so keep that// narrow target/MIME contract instead of bypassing isUnsafeScheme for// every data URL.+ //+ // This is a separate policy from the Markdown image check+ // (services/ui.js isSafeMarkdownImageSrc), and the two differ: this+ // regex also admits avif and x-icon, which SAFE_DATA_MIME_TYPES+ // excludes; it requires `;base64,`, which the Markdown check does+ // not; and it runs on `url.trim()` instead of+ // normalizeUrlForSchemeCheck(). Each difference only makes one side+ // stricter than the other, and neither side admits SVG or any+ // non-image type. tests/js/security/markdown-render-xss.test.js pins+ // the MIME and base64 differences.if (/^data:/i.test(normalizedUrl)) {const tagName = String(element?.tagName || '').toUpperCase();const isImageTarget = property === 'src' && tagName === 'IMG';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 ddc6705b01..95a3b42185 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@@ -109,6 +109,36 @@return kept.join(' ');}+ function hardenLinkTarget(node) {+ // Enforce rel noopener noreferrer on every link or form that+ // can open a new browsing context, so the opened page cannot+ // reach window.opener (tabnabbing) or receive the Referer.+ // Every read and write goes through the prototype accessors+ // above, never through a property looked up on the node.+ const api = _getElementApi();+ if (!api || !(node instanceof api.ElementCtor)) {+ return;+ }+ const tag = String(api.getTagName.call(node)).toUpperCase();+ if (!NEW_CONTEXT_TAGS.has(tag)) {+ return;+ }+ const target = api.getAttr.call(node, 'target');+ if (target === null) {+ return;+ }+ // Only exact keywords are exempt (ASCII case-insensitive).+ // DOMPurify trims attribute values before invoking this hook.+ const normalized = String(target).toLowerCase();+ if (tag === 'A' && normalized !== '') {+ // Named links must not select another existing browsing context.+ api.setAttr.call(node, 'target', SAME_CONTEXT_TARGETS.has(normalized) ? normalized : '_blank');+ }+ if (normalized !== '' && !SAME_CONTEXT_TARGETS.has(normalized)) {+ api.setAttr.call(node, 'rel', _mergeRel(api.getAttr.call(node, 'rel')));+ }+ }+// Configure DOMPurify hooks to prevent tabnabbing attacks.// Registration is lazy and idempotent per DOMPurify instance. The// load-time call below registers when DOMPurify is already bound, but@@ -138,35 +168,7 @@}return;}- purifier.addHook('afterSanitizeAttributes', function(node) {- // Enforce rel noopener noreferrer on every link or form that- // can open a new browsing context, so the opened page cannot- // reach window.opener (tabnabbing) or receive the Referer.- // Every read and write goes through the prototype accessors- // above, never through a property looked up on the node.- const api = _getElementApi();- if (!api || !(node instanceof api.ElementCtor)) {- return;- }- const tag = String(api.getTagName.call(node)).toUpperCase();- if (!NEW_CONTEXT_TAGS.has(tag)) {- return;- }- const target = api.getAttr.call(node, 'target');- if (target === null) {- return;- }- // Only the exact keywords are exempt (ASCII case-insensitive,- // not trimmed here): anything else gets the forced rel, and an- // extra rel on a same-context navigation is harmless. DOMPurify- // trims attribute values before this hook runs, so a padded- // " _top " arrives as "_top"; the no-trim rule only matters for- // callers that hand the hook untrimmed values.- const normalized = String(target).toLowerCase();- if (normalized !== '' && !SAME_CONTEXT_TARGETS.has(normalized)) {- api.setAttr.call(node, 'rel', _mergeRel(api.getAttr.call(node, 'rel')));- }- });+ purifier.addHook('afterSanitizeAttributes', hardenLinkTarget);_hookedPurifiers.add(purifier);}_ensureTabnabbingHook();@@ -191,7 +193,26 @@ALLOWED_ATTR: ['class', 'id', 'href', 'title', 'alt', 'target', 'rel'],ALLOW_DATA_ATTR: false,FORBID_TAGS: ['script', 'iframe', 'object', 'embed', 'form', 'input', 'button', 'style', 'meta', 'link'],- FORBID_ATTR: ['onerror', 'onload', 'onclick', 'onmouseover', 'onfocus', 'onblur', 'onchange', 'onsubmit', 'on*'],+ // The real guard against event handlers is ALLOWED_ATTR above,+ // which does not list any on* name. Note the precise reason: it is+ // NOT that DOMPurify only ever keeps an attribute named in+ // ALLOWED_ATTR -- _isValidAttribute returns true for any `data-*`+ // name when ALLOW_DATA_ATTR is on, and for any `aria-*` name when+ // ALLOW_ARIA_ATTR is on, both of them *before* the allowlist is+ // consulted (dompurify/dist/purify.js, the ALLOW_DATA_ATTR /+ // ALLOW_ARIA_ATTR early returns). ALLOW_ARIA_ATTR defaults to true+ // and is deliberately left at its default here. Those two escape+ // hatches are name-shaped, though: they match only /^data-[...]/ and+ // /^aria-[\-\w]+$/, and no on* handler has either prefix. So every+ // on* attribute does fall through to the allowlist, finds no entry,+ // and is dropped -- the conclusion holds, just not for the blanket+ // reason the earlier wording gave.+ //+ // FORBID_ATTR itself takes literal attribute names, not a glob:+ // 'on*' matches nothing DOMPurify would otherwise keep, so it was+ // never doing anything -- listed here only as documentation of+ // intent, not as an active control.+ FORBID_ATTR: ['onerror', 'onload', 'onclick', 'onmouseover', 'onfocus', 'onblur', 'onchange', 'onsubmit'],KEEP_CONTENT: true,SANITIZE_DOM: true,SANITIZE_NAMED_PROPS: true,@@ -207,6 +228,72 @@}};+ /**+ * Maximum sanitize passes before sanitizeStable gives up and falls back+ * to escaped text. Benign markup reaches a fixpoint on the second pass+ * (pass 1 sanitizes, pass 2 observes no change); anything still mutating+ * after this many passes is treated as hostile.+ */+ const MAX_SANITIZE_PASSES = 5;++ /**+ * Sanitize to a reparse fixpoint to prevent mXSS.+ *+ * The mXSS class exists because sanitizers inspect a parse tree but ship a+ * SERIALIZATION of it, and the browser re-parses that serialization into a+ * DIFFERENT tree. Inspecting the result once does not close the gap: the+ * inspected tree is still not the tree the user gets.+ *+ * This applies DOMPurify repeatedly until `sanitize(s) === s`. At that+ * point the string is a fixpoint of parse -> sanitize -> serialize, so the+ * tree the browser builds from it is one DOMPurify has already declared+ * clean under `config` -- a mutation that only materialises on reparse is+ * caught by the following pass instead of shipping unseen.+ *+ * If the string never stabilises it is escaped rather than emitted: the+ * content is still shown (as text), but no markup derived from it reaches+ * the DOM. This is deliberately fail-closed, matching safeSetInnerHTML's+ * DOMPurify-missing branch.+ *+ * Note this is a pure string operation -- it never touches the DOM+ * directly, so it behaves identically in every environment DOMPurify+ * itself works in.+ *+ * @param {string} dirty - The potentially dirty HTML string+ * @param {Object} config - DOMPurify configuration+ * @returns {string} - Sanitized HTML that is stable across reparsing+ */+ function sanitizeStable(dirty, config) {+ if (!hasDOMPurify()) {+ return escapeHtml(dirty);+ }+ _ensureTabnabbingHook();+ let current = String(dirty);++ for (let pass = 0; pass < MAX_SANITIZE_PASSES; pass++) {+ const next = DOMPurify.sanitize(current, config);++ // RETURN_DOM/RETURN_DOM_FRAGMENT configurations (and test doubles+ // that mimic them) return nodes, not strings. String stability is+ // meaningless there, so hand the node back untouched.+ if (typeof next !== 'string') {+ return next;+ }++ if (next === current) {+ return next;+ }++ current = next;+ }++ SafeLogger.warn(+ 'sanitizeStable: markup did not reach a sanitization fixpoint after '+ + MAX_SANITIZE_PASSES + ' passes; rendering as escaped text'+ );+ return escapeHtml(current);+ }+/*** Escape HTML entities in a string to prevent XSS* @param {string} text - The text to escape@@ -263,10 +350,9 @@ function safeSetInnerHTML(element, content, allowHtmlTags = false) {if (allowHtmlTags && hasDOMPurify()) {// Use DOMPurify for secure HTML sanitization- _ensureTabnabbingHook();- const sanitized = DOMPurify.sanitize(contentString, SANITIZE_CONFIG);+ const sanitized = sanitizeStable(contentString, SANITIZE_CONFIG);// bearer:disable javascript_lang_dangerous_insert_html- // eslint-disable-next-line no-unsanitized/property -- audited 2026-03-28: content already sanitized by DOMPurify.sanitize() above+ // eslint-disable-next-line no-unsanitized/property -- audited 2026-03-28: content already sanitized by sanitizeStable() aboveelement.innerHTML = sanitized;} else if (allowHtmlTags) {// DOMPurify not available but HTML requested - escape all HTML for safety@@ -297,13 +383,41 @@ function safeCreateElement(tagName, text = '', attributes = {}, classNames = [])'table', 'thead', 'tbody', 'tr', 'th', 'td','select', 'option', 'optgroup', 'canvas']);+ // Attribute allowlist: only these names (plus aria-*/data-* prefixes)+ // are ever set. Everything else -- including all on* event handlers --+ // is dropped silently.+ const SAFE_ATTRS = new Set([+ 'class', 'id', 'title', 'role', 'tabindex',+ 'href', 'target', 'rel',+ 'type', 'value', 'disabled', 'name', 'alt',+ 'for', 'colspan', 'rowspan', 'scope'+ ]);++ // href only permits http/https/mailto/tel schemes plus relative+ // references (#, /path, ./path, query-only). javascript:, data:,+ // vbscript:, file:, about: and protocol-relative //host values are+ // rejected. Control characters and whitespace are stripped before+ // scheme detection because browsers ignore them inside URLs.+ function isSafeHref(raw) {+ // eslint-disable-next-line no-control-regex -- intentional: browsers ignore control characters inside URL schemes, so they must be stripped before scheme validation+ const normalized = String(raw).replace(/[\x00-\x20\x7F]/g, '');+ // Backslashes are normalized to forward slashes for protocol-relative detection only -- browsers accept /\ and \\ as scheme-relative URLs (e.g. /\evil.com == //evil.com). The assigned value itself is never rewritten, so a href like /\path\foo survives verbatim when safe.+ if (normalized.replace(/\\/g, '/').startsWith('//')) {+ return false;+ }+ const schemeMatch = /^[a-z][a-z0-9+.-]*:/i.exec(normalized);+ if (schemeMatch) {+ const scheme = schemeMatch[0].slice(0, -1).toLowerCase();+ return scheme === 'http' || scheme === 'https' ||+ scheme === 'mailto' || scheme === 'tel';+ }+ return true;+ }+const normalizedTag = String(tagName).toLowerCase();if (!SAFE_TAGS.has(normalizedTag)) {throw new Error('safeCreateElement: disallowed tag "' + tagName + '"');}- if (!hasDOMPurify()) {- throw new Error('safeCreateElement requires DOMPurify to be loaded');- }// normalizedTag is validated against the SAFE_TAGS whitelist above (throws// otherwise) and createElement does not parse HTML -- Bearer false positive.@@ -315,23 +429,30 @@ function safeCreateElement(tagName, text = '', attributes = {}, classNames = [])}Object.entries(attributes).forEach(([key, value]) => {- if (key && value !== null && value !== undefined) {- element.setAttribute(String(key), String(value));+ if (!key || value === null || value === undefined) {+ return;+ }+ const name = String(key).toLowerCase();+ const allowed = SAFE_ATTRS.has(name) ||+ name.startsWith('aria-') || name.startsWith('data-');+ if (!allowed) {+ return;+ }+ if (name === 'href' && !isSafeHref(value)) {+ return;}+ element.setAttribute(name, String(value));});+ _ensureTabnabbingHook();+ // Mirror the DOMPurify hook for programmatically created links.+ hardenLinkTarget(element);+if (classNames.length > 0) {element.className = classNames.join(' ');}- // Let DOMPurify sanitize attributes (on*, javascript:/data: URIs, etc.)- _ensureTabnabbingHook();- const clean = DOMPurify.sanitize(element.outerHTML, {- ALLOWED_TAGS: [normalizedTag],- RETURN_DOM_FRAGMENT: true,- });-- return clean.firstChild || element;+ return element;}/**@@ -410,8 +531,7 @@ function sanitizeHtml(dirty, config = {}) {if (hasDOMPurify()) {const finalConfig = { ...SANITIZE_CONFIG, ...config };- _ensureTabnabbingHook();- return DOMPurify.sanitize(String(dirty), finalConfig);+ return sanitizeStable(dirty, finalConfig);}// Fallback: escape all HTML if DOMPurify is not availableSafeLogger.warn('DOMPurify not available, falling back to HTML escaping');@@ -470,7 +590,12 @@ function sanitizeUserInput(input, options = {}) {safeSetTextContent,createSafeAlertElement,sanitizeUserInput,- sanitizeHtml+ sanitizeHtml,+ sanitizeStable,+ // app.js calls this after publishing its deferred DOMPurify import.+ // Exposing the idempotent installer also covers direct DOMPurify+ // consumers that do not route through sanitizeStable().+ ensureDOMPurifyHooks: _ensureTabnabbingHook};/**diff --git a/src/local_deep_research/web/static/js/services/pdf.js b/src/local_deep_research/web/static/js/services/pdf.jsindex 3478f6a560..b7991e3df5 100644--- a/src/local_deep_research/web/static/js/services/pdf.js+++ b/src/local_deep_research/web/static/js/services/pdf.js@@ -3,6 +3,11 @@* Handles generation of PDFs from research results*/+// Prefix of the wrapper ui.renderMarkdown() puts around successfully+// sanitized output. Its absence means renderMarkdown() fell back to an+// escaped-plaintext or error banner, which is not a valid PDF body.+const RENDERED_MARKDOWN_PREFIX = '<div class="ldr-markdown-content">';+/*** Replace KaTeX-rendered math elements with their raw LaTeX source.*@@ -42,6 +47,27 @@ function replaceKatexWithLatex(container) {});}+/**+ * Wrap top-level text nodes in <p> elements.+ *+ * renderMarkdown() escapes block-level raw HTML at marked's renderer.html+ * hook, which emits it as bare text with no <p> wrapper. The PDF walker+ * iterates contentDiv.children (Elements only), so without this the text+ * that the on-screen view shows would silently vanish from the PDF.+ *+ * @param {Element} container - The PDF body container+ */+function wrapTopLevelText(container) {+ for (const node of [...container.childNodes]) {+ if (node.nodeType !== Node.TEXT_NODE || !node.textContent.trim()) {+ continue;+ }+ const p = document.createElement('p');+ p.textContent = node.textContent.trim();+ node.replaceWith(p);+ }+}+/*** Generate a PDF from the research content* @param {string|any} title - The research title/query@@ -185,7 +211,6 @@ async function generatePdf(title, content, _metadata = {}) {const pdfBodyDiv = tempContainer.querySelector('#pdf-body-content');if (pdfBodyDiv) {if (window.marked && typeof window.marked.parse === 'function') {- const rawHtml = window.marked.parse(content);// isSupported must be exactly true: an unsupported DOMPurify// (isSupported false/null/undefined) returns its input// unchanged from sanitize(), which would put raw markup into@@ -194,9 +219,37 @@ async function generatePdf(title, content, _metadata = {}) {document.body.removeChild(tempContainer);throw new Error('DOMPurify not loaded. Cannot generate PDF safely.');}- pdfBodyDiv.innerHTML = window.DOMPurify.sanitize(rawHtml, {- ADD_TAGS: ['semantics', 'annotation'],- });+ // Render through the same hardened pipeline as the on-screen+ // report view (services/ui.js renderMarkdown): raw author HTML+ // is escaped at marked's renderer.html hook, then the output is+ // sanitized to a reparse fixpoint under the restrictive+ // allowlist and value-hardened. Unlike the screen path, a+ // missing pipeline must fail CLOSED: renderMarkdown() degrades+ // to an escaped-plaintext or error-banner string, which would+ // silently produce a wrong PDF.+ if (typeof window.ui?.renderMarkdown !== 'function'+ || typeof window.XSSProtection?.sanitizeStable !== 'function') {+ document.body.removeChild(tempContainer);+ throw new Error('Markdown sanitizer not loaded. Cannot generate PDF safely.');+ }+ const renderedHtml = window.ui.renderMarkdown(content);+ if (typeof renderedHtml !== 'string'+ || !renderedHtml.startsWith(RENDERED_MARKDOWN_PREFIX)) {+ document.body.removeChild(tempContainer);+ throw new Error('Markdown rendering failed. Cannot generate PDF safely.');+ }+ // Parse the already-sanitized string in an inert <template>+ // (no script execution, no resource loading) and move its nodes+ // into the live container, so no HTML string is ever assigned+ // to a live-document element's innerHTML.+ const template = document.createElement('template');+ // eslint-disable-next-line no-unsanitized/property -- renderedHtml is the output of ui.renderMarkdown(): escaped at renderer.html, then sanitizeStable() under the restrictive allowlist; parsed here only into an inert template.+ template.innerHTML = renderedHtml;+ // The PDF walker iterates contentDiv.children, so unwrap the+ // .ldr-markdown-content wrapper renderMarkdown() adds.+ const wrapper = template.content.firstElementChild;+ pdfBodyDiv.replaceChildren(...wrapper.childNodes);+ wrapTopLevelText(pdfBodyDiv);replaceKatexWithLatex(pdfBodyDiv);} else {// marked.js not available - this is a critical error for PDF generationdiff --git a/src/local_deep_research/web/static/js/services/ui.js b/src/local_deep_research/web/static/js/services/ui.jsindex 7b5e2708fd..6cd5138bc8 100644--- a/src/local_deep_research/web/static/js/services/ui.js+++ b/src/local_deep_research/web/static/js/services/ui.js@@ -12,21 +12,53 @@ const UI_CONFIG = {// Note: sanitizer functions are available via Vite bundle or we use safe fallbacks/**- * Safe HTML setter - sanitizes with DOMPurify when a supported instance is- * bound; otherwise fails closed and renders the string as plain text.+ * Safe HTML setter.+ *+ * Fails CLOSED when a supported DOMPurify or window.sanitizeHtml is+ * missing: the value is rendered as text rather than assigned raw, the+ * same textContent fallback its near-namesake safeSetInnerHTML+ * (security/xss-protection.js) uses.+ *+ * Sanitizes through window.sanitizeHtml (security/xss-protection.js): the+ * sanitizeStable() reparse-fixpoint loop under the restrictive+ * SANITIZE_CONFIG allowlist that safeSetInnerHTML also uses, plus this+ * function's SAFE_FOR_TEMPLATES override described below. Other sanitize+ * sites differ: renderMarkdown() also runs sanitizeStable(), but with its+ * own MARKDOWN_SANITIZE_CONFIG and GENERATED_IMAGE_SANITIZE_CONFIG+ * allowlists, and news.js safeRenderHTML() runs DOMPurify once, with its+ * default allowlist, and appends the DOM fragment it returns. A single+ * DOMPurify.sanitize(html) call with no config, as this used to do, runs+ * under DOMPurify's permissive default profile -- which allows SVG/MathML+ * foreign-content parsing no caller of this function needs -- and inspects+ * only one parse, not the reparsed tree the browser actually builds from the+ * serialized result. window.sanitizeHtml is populated by+ * security/xss-protection.js, a sibling <script defer>; by the time any+ * caller invokes safeSetHTML the page has finished loading and both scripts+ * have executed.+ *+ * Passes { SAFE_FOR_TEMPLATES: false } to override SANITIZE_CONFIG's+ * default of true. SAFE_FOR_TEMPLATES makes DOMPurify blank out any text+ * node matching mustache (}}), template-literal (${...}), or ERB (%>)+ * syntax -- a guard against re-interpolating sanitizer+ * output through a client-side template engine. Nothing rendered via this+ * function is a client-side template; every caller here is plain UI markup+ * (spinners, error banners, alerts) that regularly wraps server error text+ * (error.message, data.error, etc.), and nested-JSON error text ending in+ * `}}`, a shell-style `${VAR}` example, or anything with `%>` in it is+ * ordinary content, not a template expression. With the default left on,+ * that content was silently blanked instead of shown.*/function safeSetHTML(element, html) {if (!element) return;- // 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 {- // Fail closed: without a usable sanitizer the markup is shown as text,- // never parsed as HTML.- element.textContent = html;+ if (typeof DOMPurify !== 'undefined' && DOMPurify?.isSupported === true &&+ typeof window.sanitizeHtml === 'function') {+ // no-unsanitized needs no suppression here: window.sanitizeHtml is+ // an allowlisted escape method in eslint.config.js.+ element.innerHTML = window.sanitizeHtml(html, { SAFE_FOR_TEMPLATES: false });+ return;}+ SafeLogger.warn('DOMPurify not available — rendering as text instead of HTML');+ element.textContent = html === null || html === undefined ? '' : String(html);}/**@@ -96,7 +128,7 @@ function showSpinner(container, message = 'Loading...') {`;// Safe: spinner HTML is controlled/static, message is escaped above- safeSetHTML(containerEl, spinnerHTML, 'ui');+ safeSetHTML(containerEl, spinnerHTML);}}@@ -134,7 +166,7 @@ function showError(container, message) {`;// Safe: error HTML is controlled/static, message is escaped above- safeSetHTML(containerEl, errorHTML, 'ui');+ safeSetHTML(containerEl, errorHTML);}}@@ -261,6 +293,576 @@ function showMessage(message, type = 'success', duration = UI_CONFIG.NOTIFICATIO}, duration);}+// Explicit DOMPurify allowlist for renderer-generated Markdown output. Raw+// author-supplied HTML is escaped at Marked's renderer.html hook below; this+// second boundary constrains HTML produced by Markdown/GFM, syntax highlighting,+// and KaTeX. Executable/embedded-content tags remain excluded, event-handler+// attributes are excluded, and URL attributes keep DOMPurify's built-in scheme+// filter so javascript:/data:/vbscript: hrefs are dropped.+const MARKDOWN_ALLOWED_TAGS = [+ // Standard markdown / GFM output+ 'p', 'br', 'hr', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'blockquote', 'ul',+ 'ol', 'li', 'strong', 'em', 'b', 'i', 'u', 'del', 's', 'strike', 'sub',+ 'sup', 'a', 'code', 'pre', 'span', 'div', 'table', 'thead', 'tbody',+ 'tfoot', 'tr', 'th', 'td',+ 'input', // GFM task-list checkboxes+ // `` images. DOMPurify's own tag/attr allowlist below cannot+ // express the src MIME/scheme sub-policy a safe <img> needs, so+ // hardenSanitizedMarkdown() removes any img whose src fails+ // isSafeMarkdownImageSrc (a Markdown-only policy built from URLValidator+ // helpers, security/url-validator.js) and strips every attribute but+ // src/alt/title from the ones that remain.+ 'img',+ // KaTeX MathML output (katex-mathml block)+ 'math', 'semantics', 'annotation', 'annotation-xml', 'mrow', 'mi', 'mn',+ 'mo', 'ms', 'mtext', 'mfrac', 'msqrt', 'mroot', 'msub', 'msup', 'msubsup',+ 'munder', 'mover', 'munderover', 'mmultiscripts', 'mprescripts', 'none',+ 'mtable', 'mtr', 'mlabeledtr', 'mtd', 'mspace', 'mpadded', 'mphantom',+ 'mstyle', 'merror', 'maligngroup', 'malignmark', 'maction', 'menclose',+ 'mfenced', 'mglyph', 'mlongdiv', 'msline', 'mscarries', 'msgroup',+ 'msrow', 'mstack',+ // Inline SVG generated by KaTeX for radicals, stretchy arrows/braces,+ // wide accents, delimiters, and cancellation lines. Raw Markdown HTML+ // is escaped by the renderer below, so these tags cannot originate in+ // user-authored HTML.+ 'svg', 'path', 'line',+];++const MARKDOWN_ALLOWED_ATTR = [+ 'href', 'title', 'target', 'rel', // links (scheme-filtered)+ 'src', 'alt', // images (src is policy-checked below)+ 'class', 'id', 'style', 'role', // layout, Prism tokens, KaTeX styling+ 'align', 'colspan', 'rowspan', // tables+ 'type', 'checked', 'disabled', // GFM task-list inputs+ 'start', // ordered lists+ // KaTeX SVG geometry. Attribute names are lowercase because DOMPurify+ // normalizes the HTML-string input before applying this allowlist.+ 'xmlns', 'width', 'height', 'viewbox', 'preserveaspectratio', 'd',+ 'x1', 'y1', 'x2', 'y2', 'stroke-width',+ // KaTeX's accessibility tree carries mathematical meaning in attributes,+ // including upright/double-struck identifiers and the TeX annotation.+ // Raw author HTML is escaped before this renderer-only allowlist runs.+ 'accent', 'accentunder', 'columnalign', 'columnlines', 'columnspacing',+ 'depth', 'display', 'displaystyle', 'encoding', 'fence', 'largeop',+ 'linebreak', 'linethickness', 'lspace', 'mathbackground', 'mathcolor',+ 'mathsize', 'mathvariant', 'maxsize', 'minsize', 'notation', 'rowlines',+ 'rowspacing', 'rspace', 'scriptlevel', 'separator', 'stretchy', 'valign',+ 'voffset',+];++const MARKDOWN_SANITIZE_CONFIG = {+ ALLOWED_TAGS: MARKDOWN_ALLOWED_TAGS,+ ALLOWED_ATTR: MARKDOWN_ALLOWED_ATTR,+ // KaTeX uses aria-hidden="true", but with trust:false (the application+ // default) it emits no data-* attributes. Renderer output must not be+ // able to manufacture Bootstrap/news dispatcher controls through data-*.+ ALLOW_ARIA_ATTR: true,+ ALLOW_DATA_ATTR: false,+};++// Applied only after processSpecialMarkdown() has constructed a validated+// local generated-image reference with DOM APIs. `img`/`src`/`alt` are+// already in the base config (author-supplied `` images survive+// the strict pass too, subject to hardenSanitizedMarkdown's src policy);+// this restores the sanitizer boundary after serialization while adding+// only the extra attributes a generated image's own markup requires.+const GENERATED_IMAGE_SANITIZE_CONFIG = {+ ...MARKDOWN_SANITIZE_CONFIG,+ ALLOWED_ATTR: [+ ...MARKDOWN_ALLOWED_ATTR,+ 'loading',+ // Added by processSpecialMarkdown() only after the strict pass has+ // removed every author-supplied data-* attribute.+ 'data-image-id',+ ],+};++// DOMPurify's default SANITIZE_DOM protects browser-provided properties, but+// app-defined window globals need an explicit namespace boundary.+//+// WHAT THIS LAYER ACTUALLY COVERS: nothing reachable through the current+// Markdown pipeline. `name` is not in MARKDOWN_ALLOWED_ATTR, so DOMPurify+// strips it before hardenSanitizedMarkdown ever runs; `id` is allowed, but+// the only ways an `id` could carry an author-chosen value are raw HTML in+// the Markdown source -- which renderMarkdown's `renderer.html` hook escapes+// to literal text before marked emits it -- and heading anchors, which+// marked 18 no longer generates (`headerIds` was removed upstream). Deleting+// the `[id], [name]` namespacing loop below therefore fails no test today.+// It is kept purely as defence-in-depth, so that a future change to the+// allowlist, the renderer hook or the Markdown extensions cannot silently+// re-open a DOM-clobbering path. This is the same situation the+// ALLOWED_INPUT_TYPES pass is in; see the note on+// "keeps only renderer-generated GFM checkboxes ..." in+// tests/js/security/markdown-render-xss.test.js.+//+// Consequently there is NO automated check that keeps this list in step with+// the app's real window globals -- the clobbering tests in+// tests/js/security/clobbering-prototype-pollution.test.js derive their own+// global list from source, but they exercise the Markdown path, where the+// values never arrive, so a name missing from here does not turn them red.+// Treat the list as a best-effort snapshot; it was last reconciled against+// the `window.<name> =` assignments in static/js on 2026-09-04.+const MARKDOWN_PROHIBITED_NAMED_PROPS = new Set([+ // Sensitive Window/Document properties.+ 'close', 'document', 'frames', 'location', 'name', 'opener', 'top',+ // Application globals.+ '__annotationSurfaceTest', '__documentNotesTest', '__LDR_MOBILE_BREAKPOINT_PX',+ '__noteDetailTest', '__notesTest', '__researchNotesTest', '__unifiedSearchTest',+ '_logAutoExpandTimer', '_socketAddLogEntry', 'addConsoleLog', 'api',+ 'applyCustomTemplate', 'audio', 'bindReindexButtons', 'bootstrap', 'Chart',+ 'chatComponent', 'checkAndDisplayWarnings', 'checkboxHandler', 'clearAllFilters',+ 'clearAllWarnings', 'clearTopicFilter', 'collapseAll', 'collectionApiUrl',+ 'contextOverflowController', 'contextOverflowShared', 'copyNewsLink',+ 'copyQueryTemplate', 'createSafeAlertElement', 'createSafeLoadingOverlay',+ 'createSubscription', 'createSubscriptionFromItem', 'createTag',+ 'createTopicSubscription', 'debounce', 'DeleteConfirmation', 'DeleteManager',+ 'displayCollectionEmbeddingSettings', 'displayWarnings', 'DOMPurify',+ 'escapeHtml', 'escapeHtmlAttribute', 'expandAll',+ 'exportToMarkdown', 'filterBySubscription', 'filterByTopic', 'filterLogsByType',+ 'followUpResearch', 'FollowUpResearch', 'formatBytes', 'formatNextUpdate',+ 'formatSettingsSnapshot', 'formatSettingValue', 'formatTimeAgo', 'formatting',+ 'FormValidator', 'formValidators', 'getProviderLabel', 'HelpService', 'hideModal',+ 'hideNewsItem', 'hideProgressUI', 'hideQueryTemplate', 'HistorySearch', 'hljs',+ 'html2canvas', 'HTTPError', 'indexStatusMarkup', 'io', 'jsPDF', 'KeyboardService',+ 'LDR_CONSTANTS', 'LdrAlertHelpers', 'LDRAnnotationSurface', 'LdrLogHelpers',+ 'LdrProviderOptions', 'LdrValueHelpers', 'LibrarySearch',+ 'loadBackgroundSweepSetting', 'loadNewsFeed', 'loadNewsTableQuery',+ 'loadSearchHistory', 'logPanel', 'markAllAsRead', 'markAsReadOnClick', 'marked',+ 'mobileNav', 'MobileNavigation', 'modelDropdownsInitialized',+ 'modelProvidersRequestInProgress', 'NewsUtils', 'NotesShared', 'onerror',+ 'pdfService', 'pdfUploadHandler', 'pollIntervals', 'pollResearchStatus',+ 'progressComponent', 'refetchSettingsAndUpdateWarnings', 'refreshFeed',+ 'renderCollections', 'renderIndexingFailure', 'rerunSearch', 'ResearchStates',+ 'safeCreateElement', 'safeFetch', 'safeFetchJson', 'safeFetchWithAuth', 'safeLog',+ 'safeLogDebug', 'safeLogError', 'SafeLogger', 'safeLogInfo', 'safeLogWarn',+ 'safeSetInnerHTML', 'safeSetStyles', 'safeSetTextContent', 'safeUpdateButton',+ 'sanitizeHtml', 'sanitizeUserInput', 'saveBackgroundSweepSetting', 'saveItem',+ 'saveProviderSetting', 'searchEngineDropdownInitialized',+ 'searchEnginesRequestInProgress', 'selectSubscription', 'SemanticSearch',+ 'setCollectionDataForTesting',+ 'setupCustomDropdown', 'setupSettingsDropdowns', 'shareNews',+ 'showCreateSubscriptionModal', 'showEmptyState', 'showErrorState',+ 'showLoadingState', 'showModal', 'showNotification', 'showSafeAlert', 'socket',+ 'showUploadResults', 'startPolling', 'subscriptionManager', 'themeService', 'toggleExpanded',+ 'toggleReadStatus', 'toggleSaveItem', 'triggerReindex', 'ui',+ 'updateDropdownOptions', 'updateEnhancedDomainList', 'URLBuilder', 'URLS',+ 'URLValidator', 'useNewsTemplate', 'useQueryTemplate', 'validatePasswordViaAPI',+ 'vote', 'XSSProtection', 'yamlEscape',+]);++/**+ * Post-sanitize hardening for the value layer of controls and styles.+ *+ * The explicit ALLOWED_TAGS allowlist intentionally keeps <input> (so GFM+ * task-list checkboxes survive) and the style attribute (so KaTeX inline+ * layout works), but DOMPurify's config cannot express the value-level+ * restrictions we also want:+ *+ * * interactive controls other than GFM checkboxes are stripped, and+ * every surviving checkbox is forced into a display-only state — it+ * can no longer receive focus, submit, or carry form-association data;+ * * inline styles are parsed by the browser and rebuilt from a narrow+ * KaTeX property/value allowlist. Anything else is dropped wholesale,+ * 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.+ */+const ALLOWED_INPUT_TYPES = new Set(['checkbox']); // every other type is stripped in the hardening pass+const ALLOWED_CHECKBOX_ATTRS = new Set([+ 'type', 'checked', 'disabled', 'class',+]);++// Attributes a surviving <img> keeps. Pinned to this exact set (rather than+// letting MARKDOWN_ALLOWED_ATTR's general 'class'/'id'/'style' reach img+// too) so a future addition to that shared list cannot silently widen this+// element's surface; srcset/onerror/onload are never in MARKDOWN_ALLOWED_ATTR+// to begin with, so DOMPurify already strips them, but this keeps the+// invariant explicit and independent of that list.+const SAFE_MARKDOWN_IMG_ATTRS = new Set(['src', 'alt', 'title']);++/**+ * Decide whether an `<img src>` produced by sanitized Markdown may be kept.+ *+ * A Markdown-only policy assembled from URLValidator helpers+ * (security/url-validator.js). It is not shared with any other URL check:+ * `isSafeHref` (security/xss-protection.js) is a separate private helper of+ * safeCreateElement, Markdown link hrefs rely on DOMPurify's built-in URI+ * filter, and URLValidator.safeAssign's `data:` carve-out has its own+ * rules (the note above its data: branch lists the differences). The rules:+ *+ * * `javascript:`/`vbscript:` and the rest of URLValidator.UNSAFE_SCHEMES+ * are rejected outright (belt-and-braces: DOMPurify's own URI filter+ * already drops these schemes on a `src` attribute).+ * * `data:` URIs are restricted to URLValidator.SAFE_DATA_MIME_TYPES, a+ * raster-only allowlist (png/jpeg/gif/webp/bmp) that deliberately+ * excludes `image/svg+xml`. The MIME type is read from the+ * normalizeUrlForSchemeCheck() form, and `;base64,` is not required.+ *+ * To be precise about WHY SVG is excluded, because the obvious reason+ * is wrong: an SVG referenced from `<img src>` is loaded in the image+ * "secure static mode" -- scripting, external references and+ * interactivity are all disabled -- so `data:image/svg+xml` in *this*+ * position does not run `<script>` or event handlers. The exclusion is+ * a conservative default, not an execution fix. This predicate is the+ * only MIME gate in the pipeline: DOMPurify's `data:` allowance for+ * `<img>` (DATA_URI_TAGS) is scheme-only, not MIME-aware, so without+ * the check here ANY `data:` payload -- `data:text/html`,+ * `data:image/svg+xml`, anything -- reaches the DOM on a `src`+ * attribute untouched. Keeping that one gate raster-only matches+ * safeAssign's separate data: check, which admits no SVG either.+ * * Anything else must pass URLValidator.isSafeUrl: http, https, ftp or+ * ftps, or a relative path resolved against the page. Unlike+ * isSafeHref, a `//host/path` protocol-relative source is NOT rejected+ * here: isSafeHref's rejection is about the auxiliary-browsing-context/+ * phishing risk of *navigating* somewhere unexpected, which does not+ * apply to an <img> loading pixels, and `//host/x.png` carries no more+ * risk than `https://host/x.png`.+ *+ * Remote sources pass this predicate, but the shipped Content-Security-+ * Policy (`img-src 'self' data:`, web/fastapi_app.py) blocks them in the+ * browser, so the images that actually display today are same-origin ones+ * and the raster `data:` images allowed above.+ *+ * @param {string|null} src - The img element's `src` attribute value.+ * @returns {boolean} - True if the image may be kept.+ */+function isSafeMarkdownImageSrc(src) {+ if (typeof src !== 'string' || !src) {+ return false;+ }+ if (typeof URLValidator === 'undefined') {+ // Fail closed if URLValidator (security/url-validator.js) did not load.+ return false;+ }++ // Detect the scheme and MIME type on the normalized form, so a control+ // character the browser would ignore cannot dodge either check.+ // safeAssign's data: carve-out does not share this step (see+ // URLValidator.normalizeUrlForSchemeCheck).+ const normalized = URLValidator.normalizeUrlForSchemeCheck(src);+ if (!normalized) {+ return false;+ }++ if (/^data:/i.test(normalized)) {+ const mime = /^data:([^;,]*)/i.exec(normalized);+ return !!(mime && URLValidator.SAFE_DATA_MIME_TYPES.includes(mime[1].toLowerCase()));+ }++ if (URLValidator.isUnsafeScheme(normalized)) {+ return false;+ }++ return URLValidator.isSafeUrl(normalized, { allowFragments: false });+}++// KaTeX emits a small, stable set of inline metrics. Keep the maximum generous+// enough for large equations while bounding anomalous renderer output as a+// defense in depth; author-supplied raw styles never reach this pass.+const MAX_KATEX_INLINE_LENGTH_EM = 50;++function isSafeKatexLength(value, allowNegative = false) {+ const normalized = value.trim().toLowerCase();+ // CSSOM serializes a unitless zero as 0px in some implementations.+ if (/^-?0(?:\.0+)?(?:em|px)?$/.test(normalized)) {+ return true;+ }+ const match = /^(-?(?:\d+(?:\.\d*)?|\.\d+))em$/.exec(normalized);+ if (!match) {+ return false;+ }+ const number = Number(match[1]);+ return Number.isFinite(number)+ && (allowNegative || number >= 0)+ && Math.abs(number) <= MAX_KATEX_INLINE_LENGTH_EM;+}++function isSafeKatexMargin(value) {+ const parts = value.trim().split(/\s+/);+ return parts.length >= 1 && parts.length <= 4+ && parts.every((part) => isSafeKatexLength(part, true));+}++// Matches a single rgb()/rgba() numeric or percentage component: an+// integer/decimal, optionally followed by `%`. No calc(), no var(), no+// exponents -- just the plain numeric grammar getPropertyValue() emits.+const RGB_COMPONENT = String.raw`-?(?:\d+(?:\.\d+)?|\.\d+)%?`;+// The optional alpha group starts with its own comma (not a leading `\s*`)+// so it never sits directly adjacent to another `\s*` -- two `\s*` quantifiers+// that can both match the same whitespace is a superlinear-backtracking+// shape (regexp/no-super-linear-backtracking), not just a style nit.+const RGB_COLOR_RE = new RegExp(+ `^rgba?\\(\\s*(${RGB_COMPONENT})\\s*,\\s*(${RGB_COMPONENT})\\s*,\\s*(${RGB_COMPONENT})`+ + `(?:\\s*,\\s*(${RGB_COMPONENT}))?\\s*\\)$`,+ 'i',+);++function isSafeRgbColorComponent(component, max) {+ if (component.endsWith('%')) {+ const percent = Number(component.slice(0, -1));+ return Number.isFinite(percent) && percent >= 0 && percent <= 100;+ }+ const number = Number(component);+ return Number.isFinite(number) && number >= 0 && number <= max;+}++function isSafeKatexColor(value) {+ const normalized = value.trim();++ // This matches KaTeX's color-token grammar plus currentColor, which the+ // application uses for theme-aware parse errors.+ if (/^(?:#[a-f0-9]{3,4}|#[a-f0-9]{6}|#[a-f0-9]{8}|[a-z]+)$/i.test(normalized)) {+ return true;+ }++ // KaTeX only ever authors hex colors, but CSSOM never echoes a hex (or+ // keyword) color back verbatim: reading a `color:#df0030` declaration+ // through element.style.getPropertyValue() returns the browser's+ // SERIALIZED form, which every current engine renders as `rgb(r, g, b)`+ // / `rgba(r, g, b, a)` -- never the original hex text. Without accepting+ // that serialized shape, every KaTeX color declaration fails validation+ // on real browsers (happy-dom does not perform this normalization,+ // which is why no existing vitest suite caught this). Parse strictly:+ // exactly three/four numeric-or-percentage components in range, nothing+ // else -- this cannot match url(), var(), calc(), or any other+ // function-valued or custom-property-referencing form.+ const rgbMatch = RGB_COLOR_RE.exec(normalized);+ if (rgbMatch) {+ const [, r, g, b, a] = rgbMatch;+ if (![r, g, b].every((component) => isSafeRgbColorComponent(component, 255))) {+ return false;+ }+ return a === undefined || isSafeRgbColorComponent(a, 1);+ }++ // color()/oklch()/lab()/lch() etc: deliberately rejected, not merely+ // unhandled. KaTeX's only color inputs are the hex/keyword literals+ // matched above, and every engine serializes those (and their rgb()+ // equivalents) through the sRGB rgb()/rgba() form matched above --+ // never through a wide-gamut color function -- so a real KaTeX render+ // can never legitimately produce one. Accepting them would widen the+ // parser surface (nested legacy color notation, `none` angle/percent+ // components, `var()`-only-inside-color() variants) for a shape this+ // pipeline never needs to pass, so they stay outside the boundary.+ return false;+}++const SAFE_KATEX_STYLE_VALIDATORS = new Map([+ ['background-color', isSafeKatexColor],+ ['border-bottom-color', isSafeKatexColor],+ // `border-style` is the shorthand KaTeX authors (e.g. \fcolorbox's+ // border, katex.js sets `borderStyle = "solid"`); no browser's CSSOM+ // enumerates a shorthand parsed from an inline style attribute -- it+ // is always expanded into the four border-*-style longhands, same as+ // border-color/border-width below. Without all four, three sides+ // silently fall back to their default style and the box renders with+ // only one visible edge.+ ['border-bottom-style', (value) => /^(?:solid|dashed)$/i.test(value.trim())],+ ['border-bottom-width', isSafeKatexLength],+ // `border-color` is the shorthand KaTeX authors (e.g. \fcolorbox's+ // border), but no browser's CSSOM enumerates a shorthand parsed from an+ // inline style attribute -- it is always expanded into the four+ // border-*-color longhands below. The shorthand entry is kept too+ // (harmless, and a safety net for any engine that behaves otherwise),+ // but without the longhands a real browser silently drops the color+ // and \fcolorbox's border falls back to currentColor.+ ['border-color', isSafeKatexColor],+ ['border-left-color', isSafeKatexColor],+ ['border-left-style', (value) => /^(?:solid|dashed)$/i.test(value.trim())],+ ['border-left-width', isSafeKatexLength],+ ['border-right-color', isSafeKatexColor],+ ['border-right-style', (value) => /^(?:solid|dashed)$/i.test(value.trim())],+ ['border-right-width', isSafeKatexLength],+ ['border-style', (value) => /^solid$/i.test(value.trim())],+ ['border-top-color', isSafeKatexColor],+ ['border-top-style', (value) => /^(?:solid|dashed)$/i.test(value.trim())],+ ['border-top-width', isSafeKatexLength],+ ['border-width', isSafeKatexLength],+ ['bottom', (value) => isSafeKatexLength(value, true)],+ ['color', isSafeKatexColor],+ ['height', isSafeKatexLength],+ ['left', (value) => isSafeKatexLength(value, true)],+ // Browsers differ on whether CSSOM exposes KaTeX's `margin` shorthand or+ // its four expanded longhands, so safely accept both representations.+ ['margin', isSafeKatexMargin],+ ['margin-bottom', (value) => isSafeKatexLength(value, true)],+ ['margin-left', (value) => isSafeKatexLength(value, true)],+ ['margin-right', (value) => isSafeKatexLength(value, true)],+ ['margin-top', (value) => isSafeKatexLength(value, true)],+ ['min-width', isSafeKatexLength],+ ['padding-left', isSafeKatexLength],+ ['position', (value) => /^relative$/i.test(value.trim())],+ ['text-shadow', (value) => value.trim().replace(/\s+/g, ' ')+ === '0.02em 0.01em 0.04px'],+ ['top', (value) => isSafeKatexLength(value, true)],+ ['vertical-align', (value) => isSafeKatexLength(value, true)],+ ['width', isSafeKatexLength],+]);++// `class` is needed for KaTeX and code highlighting. Preserve only classes+// generated by the renderers this pipeline supports, so a future renderer or+// extension cannot accidentally invoke unrelated globally-loaded utilities.+const SAFE_MARKDOWN_CLASS_NAMES = new Set([+ // GFM task lists.+ 'contains-task-list', 'task-list-item', 'task-list-item-checkbox',+ // Prism token classes. Language identifiers use the safe prefix below.+ 'token', 'atrule', 'attr-name', 'attr-value', 'bold', 'boolean', 'builtin',+ 'cdata', 'char', 'class-name', 'comment', 'constant', 'decorator', 'deleted',+ 'doctype', 'entity', 'function', 'function-variable', 'hashbang', 'important',+ 'inserted', 'interpolation', 'interpolation-punctuation', 'italic', 'keyword',+ 'known-class-name', 'literal-property', 'namespace', 'number', 'operator',+ 'parameter', 'prolog', 'property', 'punctuation', 'regex', 'selector', 'string',+ 'symbol', 'tag', 'template-punctuation', 'template-string', 'triple-quoted-string',+ 'url', 'variable',+ // KaTeX renderer classes (HTML and MathML wrappers). KaTeX 0.18+ // prefixes several layout classes; keep those alongside legacy names.+ 'katex-accent', 'katex-base', 'katex-fix', 'katex-hdashline', 'katex-hline',+ 'katex-inner', 'katex-newline', 'katex-overlay', 'katex-overline',+ 'katex-root', 'katex-rule', 'katex-sizing', 'katex-smash', 'katex-sout',+ 'katex-stretchy', 'katex-strut', 'katex-tag', 'katex-thinbox',+ 'katex-underline', 'katex-vbox',+ 'accent', 'accent-body', 'accent-full', 'amsrm', 'angl', 'anglpad',+ 'arraycolsep', 'base', 'boldsymbol', 'boxpad', 'brace-center', 'brace-left',+ 'brace-right', 'cancel-lap', 'cancel-pad', 'cd-arrow-pad', 'cd-label-left',+ 'cd-label-right', 'cd-vert-arrow', 'clap', 'col-align-c', 'col-align-l',+ 'col-align-r', 'colorbox', 'delim-size1', 'delim-size4', 'delimcenter',+ 'delimsizing', 'eqn-num', 'fbox', 'fcolorbox', 'fix', 'fleqn',+ 'fontsize-ensurer', 'frac-line', 'halfarrow-left', 'halfarrow-right', 'hbox',+ 'hdashline', 'hide-tail', 'hline', 'inner', 'katex', 'katex-display',+ 'katex-error', 'katex-html', 'katex-mathml', 'katex-version', 'large-op',+ 'leqno', 'llap',+ 'mainrm', 'mathbb', 'mathbf', 'mathboldfrak', 'mathboldsf', 'mathcal',+ 'mathfrak', 'mathit', 'mathitsf', 'mathnormal', 'mathrm', 'mathscr', 'mathsf',+ 'mathsfit', 'mathtt', 'mbin', 'mclose', 'mfrac', 'minner', 'mml-eqn-num',+ 'mop', 'mopen', 'mord', 'mover', 'mpunct', 'mrel', 'mspace', 'msupsub',+ 'mtable', 'mtight', 'mtr-glue', 'mult', 'munder', 'newline', 'nulldelimiter',+ 'op-limits', 'op-symbol', 'overlay', 'overline', 'overline-line', 'pstrut',+ 'reset-size1', 'reset-size2', 'reset-size3', 'reset-size4', 'reset-size5',+ 'reset-size6', 'reset-size7', 'reset-size8', 'reset-size9', 'reset-size10',+ 'reset-size11', 'rlap', 'root', 'rule', 'size1', 'size2', 'size3', 'size4',+ 'size5', 'size6', 'size7', 'size8', 'size9', 'size10', 'size11', 'sizing',+ 'small-op', 'smash', 'sout', 'sqrt', 'stretchy', 'strut', 'svg-align', 'tag',+ 'text', 'textbb', 'textbf', 'textboldfrak', 'textboldsf', 'textfrak', 'textit',+ 'textitsf', 'textrm', 'textscr', 'textsf', 'texttt', 'thinbox', 'ttf',+ 'underline', 'underline-line', 'vbox', 'vertical-separator', 'vlist', 'vlist-r',+ 'vlist-s', 'vlist-t', 'vlist-t2', 'x-arrow', 'x-arrow-pad',+]);++function isSafeMarkdownClassName(className) {+ return SAFE_MARKDOWN_CLASS_NAMES.has(className)+ // Marked places the requested lexer name on fenced code blocks;+ // highlight.js prefixes every generated token class with `hljs-`.+ || /^language-[\w-]+$/i.test(className)+ || /^hljs(?:-[\w-]+)?$/i.test(className);+}++function getSafeKatexInlineStyle(element) {+ // Filter, don't fail-all: an unrecognized/invalid declaration is+ // dropped on its own, never taken as license to drop every declaration+ // on the element. KaTeX packs geometry (height/vertical-align/top/+ // margin) onto the same span as color, so a fail-all policy lets one+ // rejected color property (see isSafeKatexColor above) silently strip+ // the positioning that makes the math render correctly -- a rendering+ // regression, not a safety win: the security property this function+ // exists for is that no unsafe VALUE survives, and per-property+ // filtering keeps that while shrinking the blast radius of a rejection+ // from "the whole style" to "that one property".+ const declarations = [];+ for (let i = 0; i < element.style.length; i++) {+ const property = element.style.item(i).toLowerCase();+ const value = element.style.getPropertyValue(property).trim();+ const validator = SAFE_KATEX_STYLE_VALIDATORS.get(property);+ if (!validator || element.style.getPropertyPriority(property) || !validator(value)) {+ continue;+ }+ declarations.push(`${property}: ${value}`);+ }+ return declarations.length > 0 ? `${declarations.join('; ')};` : null;+}++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;+ // 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+ // only display-relevant attrs (type/checked/disabled/class/aria-*).+ for (const input of [...root.querySelectorAll('input')]) {+ const type = (input.getAttribute('type') || '').toLowerCase();+ if (!ALLOWED_INPUT_TYPES.has(type)) {+ input.remove();+ continue;+ }+ input.setAttribute('disabled', '');+ for (const name of input.getAttributeNames()) {+ if (ALLOWED_CHECKBOX_ATTRS.has(name) || name.startsWith('aria-')) {+ continue;+ }+ input.removeAttribute(name);+ }+ }+ // Images: DOMPurify's tag/attr allowlist gets `<img>` and its+ // attribute NAMES this far, but not the src-value policy (MIME/scheme)+ // a safe image needs -- see isSafeMarkdownImageSrc(). Drop any image+ // whose src does not clear that policy, and pin every surviving one+ // down to exactly src/alt/title so it cannot carry a class/id/style+ // value the generic loops below would otherwise have to re-validate.+ for (const img of [...root.querySelectorAll('img')]) {+ if (!isSafeMarkdownImageSrc(img.getAttribute('src'))) {+ img.remove();+ continue;+ }+ for (const name of img.getAttributeNames()) {+ if (!SAFE_MARKDOWN_IMG_ATTRS.has(name)) {+ img.removeAttribute(name);+ }+ }+ }+ // Inline styles: rebuild the browser-parsed declaration list from a+ // positive KaTeX allowlist. Re-serialization is important: unsupported+ // or malformed syntax cannot hitch a ride beside declarations CSSOM did+ // understand, and CSS escapes/custom properties never reach the output.+ for (const el of root.querySelectorAll('[style]')) {+ const safeStyle = getSafeKatexInlineStyle(el);+ if (!safeStyle) {+ el.removeAttribute('style');+ } else {+ el.setAttribute('style', safeStyle);+ }+ }+ // Class values are another CSS execution surface. Filter individual+ // tokens so a valid KaTeX/Prism class can survive without carrying a+ // Bootstrap utility class alongside it.+ for (const el of root.querySelectorAll('[class]')) {+ const safeClasses = [...el.classList].filter(isSafeMarkdownClassName);+ if (safeClasses.length === 0) {+ el.removeAttribute('class');+ } else {+ el.setAttribute('class', safeClasses.join(' '));+ }+ }+ // Namespace only dangerous id/name values. Unlike DOMPurify's strict+ // SANITIZE_NAMED_PROPS mode, this leaves benign heading anchors unchanged.+ for (const el of root.querySelectorAll('[id], [name]')) {+ for (const attributeName of ['id', 'name']) {+ const value = el.getAttribute(attributeName);+ if (MARKDOWN_PROHIBITED_NAMED_PROPS.has(value)) {+ el.setAttribute(attributeName, `user-content-${value}`);+ }+ }+ }+ return template.innerHTML;+}++/*** Fail-closed markdown rendering: escape everything, show as text.* Shared by the marked-missing and DOMPurify-missing branches --@@ -290,15 +892,48 @@ function renderMarkdown(markdown) {return '<div class="alert alert-warning">No content available</div>';}+ // security/xss-protection.js publishes window.XSSProtection. base.html+ // loads it on every page, and renderMarkdown only ever runs from event+ // handlers and render callbacks — long after every deferred script has+ // executed — so this resolves in production. It is read defensively+ // anyway: an unguarded `window.XSSProtection.sanitizeStable(...)` would+ // throw when that file is missing (404, CSP, a page that stops extending+ // base.html) and the catch below would turn a missing sanitizer into an+ // "Error rendering content" banner. Treat it like marked/DOMPurify+ // instead, so a missing sanitizer degrades to the escaped-plaintext+ // fallback that already exists for exactly this case.+ const sanitizeStable = window.XSSProtection && window.XSSProtection.sanitizeStable;+try {- // Use marked library if available- if (typeof marked !== 'undefined') {+ // Use marked library if available. DOMPurify is required too: this+ // branch produces HTML from untrusted markdown, and without a+ // sanitizer there is nothing between marked's output and innerHTML.+ // It previously fell through with `sanitized = html` (raw) — a+ // fail-OPEN, and inconsistent with the marked-missing branch below,+ // which correctly escapes.+ if (typeof marked !== 'undefined' && typeof DOMPurify !== 'undefined' && DOMPurify?.isSupported === true+ && typeof sanitizeStable === 'function') {// Configure marked options and custom renderer for links and special elementsconst renderer = new marked.Renderer();const _origLink = renderer.link.bind(renderer);renderer.link = function(token) {return _origLink(token).replace(/^<a /, '<a target="_blank" rel="noopener noreferrer" '); // DevSkim: ignore DS610000};+ // Raw HTML has no trustworthy provenance: if it reaches the+ // final sanitizer as active markup, it can impersonate the+ // KaTeX/Prism classes and inline metrics that generated output+ // legitimately needs. Escaping at Marked's raw-HTML hook keeps+ // ordinary Markdown, GFM, highlighted code, and KaTeX rendering+ // intact while making author-supplied tags visible as text.+ // Renderer extensions such as marked-katex-extension bypass+ // this hook, so their generated markup still reaches the tight+ // tag/attribute/value allowlists below.+ renderer.html = function(token) {+ const rawHtml = typeof token === 'string'+ ? token+ : token?.raw ?? token?.text ?? '';+ return escapeHtmlFallback(rawHtml);+ };marked.setOptions({breaks: true,gfm: true,@@ -321,40 +956,38 @@ function renderMarkdown(markdown) {// Parse markdown and return HTMLconst html = marked.parse(markdown, { renderer });- // Process any special elements like image references- const processedHtml = processSpecialMarkdown(html);-- // 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 = DOMPurify.sanitize(processedHtml, {- ADD_TAGS: ['semantics', 'annotation'],- ADD_ATTR: ['target', 'rel']- });+ // Sanitize to prevent XSS from markdown content. This runs+ // BEFORE processSpecialMarkdown so the strictly-validated+ // generated-image markup it constructs (fixed attribute set,+ // GENERATED_IMAGE_DIRECTIVE-guarded) still produces its <img>+ // while all markdown-derived HTML is forced through the+ // allowlist first.+ const sanitized = sanitizeStable(html, MARKDOWN_SANITIZE_CONFIG);+ // 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+ // processSpecialMarkdown for the same reason as DOMPurify above.+ const hardened = hardenSanitizedMarkdown(sanitized);- return `<div class="ldr-markdown-content">${sanitized}</div>`;+ // Process any special elements like image references+ const processedHtml = processSpecialMarkdown(hardened);++ // processSpecialMarkdown serializes trusted nodes back to a+ // string, so sanitize to a fixpoint once more before callers+ // assign the result to innerHTML. Ordinary Markdown images have+ // already passed the URL and attribute checks above.+ const finalHtml = sanitizeStable(+ processedHtml,+ GENERATED_IMAGE_SANITIZE_CONFIG,+ );++ return `<div class="ldr-markdown-content">${finalHtml}</div>`;}// Fallback if marked is not available - display as plaintext for security// Using regex-based partial markdown is fragile and a security risk,// so we escape all HTML and display as preformatted text with a warning- SafeLogger.warn('Marked library not available. Displaying as plaintext for security.');+ SafeLogger.warn('marked, supported DOMPurify and/or XSSProtection.sanitizeStable not available. Displaying as plaintext for security.');return _escapedPlaintextFallback(markdown);} catch (error) {SafeLogger.error('Error rendering markdown:', error);@@ -372,23 +1005,54 @@ function renderMarkdown(markdown) {* @returns {string} - Processed HTML*/function processSpecialMarkdown(html) {- // Process image references. `ref` is user-influenced content from the- // markdown body; tighten the allowed shape so HTML-attribute injection- // (a `"` would break out of the data-image-id attribute and confuse- // DOMPurify's parser) and src-path traversal (`../`) are impossible.- const SAFE_IMAGE_REF = /^image-[\w-]+$/;- return html.replace(/!\[ref:([^\]]+)\]/g, (match, ref) => {- if (!SAFE_IMAGE_REF.test(ref)) {- return match; // Leave unmatched refs as literal markdown.+ // Generated-image references are block directives. Only a marker that is+ // the sole text child of a paragraph produced by marked is eligible. This+ // deliberately excludes attributes, links, code, KaTeX, and inline prose.+ // Searching the serialized HTML with a regex would lose that context and+ // 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;++ for (const paragraph of [...template.content.querySelectorAll('p')]) {+ if (paragraph.childNodes.length !== 1 ||+ paragraph.firstChild.nodeType !== Node.TEXT_NODE) {+ continue;}- return `<div class="ldr-generated-image" data-image-id="${ref}">- <img src="/static/img/generated/${ref}.png"- alt="Generated image ${ref}"- class="img-fluid"- loading="lazy" />- <div class="ldr-image-caption">Generated image (${ref})</div>- </div>`;- });++ const match = GENERATED_IMAGE_DIRECTIVE.exec(paragraph.textContent);+ if (!match) {+ continue;+ }++ const ref = match[1];+ const wrapper = document.createElement('div');+ wrapper.className = 'ldr-generated-image';+ wrapper.setAttribute('data-image-id', ref);++ const image = document.createElement('img');+ // Keep the path component explicitly encoded even though the+ // directive regex already limits it to image-[\w-]+. Besides making+ // the URL boundary self-contained, this lets static taint analysis+ // verify that DOM text cannot become an executable URL.+ const encodedRef = encodeURIComponent(ref);+ image.setAttribute('src', `/static/img/generated/${encodedRef}.png`);+ image.setAttribute('alt', `Generated image ${ref}`);+ image.className = 'img-fluid';+ image.setAttribute('loading', 'lazy');++ const caption = document.createElement('div');+ caption.className = 'ldr-image-caption';+ caption.textContent = `Generated image (${ref})`;++ wrapper.appendChild(image);+ wrapper.appendChild(caption);+ paragraph.replaceWith(wrapper);+ }++ return template.innerHTML;}/**@@ -542,7 +1206,7 @@ function showAlert(message, type = 'info', skipIfToastShown = true) {const alert = document.createElement('div');const alertType = window.LdrAlertHelpers.mapAlertType(type);alert.className = `alert alert-${alertType}`;- safeSetHTML(alert, `<i class="fas ${type === 'success' ? 'fa-check-circle' : 'fa-exclamation-circle'}"></i> ${escapedMessage}`, 'ui');+ safeSetHTML(alert, `<i class="fas ${type === 'success' ? 'fa-check-circle' : 'fa-exclamation-circle'}"></i> ${escapedMessage}`);// Add a close buttonconst closeBtn = document.createElement('button');@@ -733,5 +1397,16 @@ window.ui = {updateFavicon,showAlert,showInlineError,- clearInlineError+ clearInlineError,+ // Exposed for testing and debugging (see window.progressComponent for+ // the same pattern in components/progress.js): the KaTeX inline-style+ // hardening pass has no other reachable entry point from outside this+ // file (it runs as a private step inside renderMarkdown), and its+ // rgb()/rgba() color handling is specifically the shape happy-dom+ // cannot exercise on its own -- a real browser serializes a hex color+ // read back from CSSOM as rgb()/rgba(), happy-dom does not, so tests+ // must be able to call these directly with an explicitly-constructed+ // rgb() value.+ isSafeKatexColor,+ getSafeKatexInlineStyle};diff --git a/tests/error_handling/test_report_generator.py b/tests/error_handling/test_report_generator.pyindex 532a9d16ba..18a9aa340b 100644--- a/tests/error_handling/test_report_generator.py+++ b/tests/error_handling/test_report_generator.py@@ -1,5 +1,6 @@"""Tests for report_generator module."""+import refrom unittest.mock import MagicMockimport pytest@@ -108,6 +109,68 @@ class TestGenerateErrorReport:assert "Error report generation failed" in result+# Where CommonMark raw HTML can begin: an open or closing tag, a comment, a+# declaration or a processing instruction always starts with "<" followed by+# a letter, "/", "!" or "?". Text inside an inline code span is literal, so+# a placeholder such as `ollama pull <model-name>` is not raw HTML.+_RAW_HTML_START = re.compile(r"<[A-Za-z/!?]")+_CODE_SPAN = re.compile(r"`[^`\n]*`")+++def _raw_html_outside_code(report):+ """The first place raw HTML could begin outside an inline code span."""+ return _RAW_HTML_START.search(_CODE_SPAN.sub("", report))+++class TestErrorReportIsPlainMarkdown:+ """The saved report is shown through renderMarkdown() (services/ui.js),+ which displays raw HTML in Markdown as literal text. The report's own+ structure must therefore be plain Markdown: with inputs that contain no+ HTML, the report contains none either."""++ def test_partial_results_are_a_markdown_section(+ self, error_report_generator, sample_partial_results+ ):+ """Regression: the partial results used to be wrapped in+ <details><summary>, which renders as escaped tags."""+ report = error_report_generator.generate_error_report(+ "Connection refused",+ "test query",+ partial_results=sample_partial_results,+ )++ assert "\n## 📊 Partial Results Available\n" in report+ assert "### Search Results Found" in report+ assert _raw_html_outside_code(report) is None, report++ @pytest.mark.parametrize(+ "error_message",+ [+ "Connection refused",+ "Model gemma2:9b not found in Ollama",+ "zzqx unexpected failure",+ ],+ )+ def test_report_without_partial_results_has_no_raw_html(+ self, error_report_generator, error_message+ ):+ report = error_report_generator.generate_error_report(+ error_message, "test query", partial_results=None+ )++ assert _raw_html_outside_code(report) is None, report++ def test_fallback_report_has_no_raw_html(self, error_report_generator):+ error_report_generator.error_reporter.analyze_error = MagicMock(+ side_effect=Exception("test error")+ )++ report = error_report_generator.generate_error_report("Error", "query")++ assert "Error report generation failed" in report+ assert _raw_html_outside_code(report) is None, report++class TestFormatPartialResults:"""Tests for _format_partial_results method."""diff --git a/tests/infrastructure_tests/test_xss_protection.test.js b/tests/infrastructure_tests/test_xss_protection.test.jsindex 33ab42be29..4d7b18c050 100644--- a/tests/infrastructure_tests/test_xss_protection.test.js+++ b/tests/infrastructure_tests/test_xss_protection.test.js@@ -44,7 +44,17 @@ global.document = {removeChild: jest.fn(),addEventListener: jest.fn(),querySelectorAll: jest.fn(() => []),- firstChild: null+ firstChild: null,+ // <template> elements expose their parsed children through .content+ // (a DocumentFragment). Production code that parses a sanitizer+ // result into a template walks template.content, so the fake must+ // model it -- omitting it made this suite pass on code that would+ // throw in every real browser.+ content: {+ querySelectorAll: jest.fn(() => []),+ childNodes: [],+ firstChild: null+ }}))};diff --git a/tests/js/components/results-display-runtime.test.js b/tests/js/components/results-display-runtime.test.jsindex fc5fd136ee..88f1864445 100644--- a/tests/js/components/results-display-runtime.test.js+++ b/tests/js/components/results-display-runtime.test.js@@ -253,7 +253,7 @@ it('sanitizes an HTML report even when its metadata omits a mode', async () => {expect(document.getElementById('results-content').textContent).toBe('Sanitized report');});- expect(window.sanitizeHtml).toHaveBeenCalledWith(unsafeHtml);+ expect(window.sanitizeHtml).toHaveBeenCalledWith(unsafeHtml, { SAFE_FOR_TEMPLATES: false });expect(document.querySelector('#results-content img')).toBeNull();expect(document.getElementById('result-query').textContent).toBe('Stored HTML report');diff --git a/tests/js/components/settings-accordion.test.js b/tests/js/components/settings-accordion.test.jsindex 251df201c2..b37c8240a2 100644--- a/tests/js/components/settings-accordion.test.js+++ b/tests/js/components/settings-accordion.test.js@@ -184,7 +184,7 @@ describe('settings.js source: accordion markup carries aria wiring', () => {// Regex (not a plain string) so eslint's no-template-curly-in-string// rule doesn't mistake this literal-source-text assertion for an// accidentally unwrapped template literal.- expect(tag).toMatch(/aria-controls="\$\{sectionId\}"/);+ expect(tag).toMatch(/aria-controls="\$\{sectionId(?:Attribute)?\}"/);});});});diff --git a/tests/js/components/settings-dashboard-runtime.test.js b/tests/js/components/settings-dashboard-runtime.test.jsindex d3201dc52a..d76a1fa5d3 100644--- a/tests/js/components/settings-dashboard-runtime.test.js+++ b/tests/js/components/settings-dashboard-runtime.test.js@@ -355,7 +355,7 @@ it('renders aliased policy settings, clears a redacted secret, and recovers from);expect(saveBodies).toContainEqual({ 'llm.provider': 'openai' });- const reportEnabled = document.getElementById('setting-report-options_enabled');+ const reportEnabled = document.querySelector('.ldr-json-property-control[data-parent-key="report.options"][data-property="enabled"]');const saveCountBeforeWrapperClick = saveBodies.length;reportEnabled.closest('.ldr-boolean-property').click();await flushPromises();@@ -384,7 +384,7 @@ it('renders aliased policy settings, clears a redacted secret, and recovers fromexpect(settings['report.options'].value.enabled).toBe(true);expect(reportEnabled.checked).toBe(true);- const reportLimit = document.getElementById('setting-report-options_limit');+ const reportLimit = document.querySelector('.ldr-json-property-control[data-parent-key="report.options"][data-property="limit"]');reportLimit.value = '5';reportLimit.dispatchEvent(new Event('input', { bubbles: true }));reportLimit.dispatchEvent(new Event('blur', { bubbles: true }));diff --git a/tests/js/happy-dom-dompurify-shim.js b/tests/js/happy-dom-dompurify-shim.jsnew file mode 100644index 0000000000..fe272320e5--- /dev/null+++ b/tests/js/happy-dom-dompurify-shim.js@@ -0,0 +1,111 @@+/**+ * happy-dom repairs required for DOMPurify to behave like a browser.+ *+ * happy-dom has two defects that DOMPurify trips over (first seen on+ * 20.11.12; both still reproduce on the pinned 20.14.5):+ *+ * 1. `document.createNodeIterator` truncates traversal as soon as the+ * current node is removed from the tree. DOMPurify removes nodes while+ * iterating, so only the nodes up to the first removal are ever+ * inspected.+ * 2. The BASE `Node.prototype` `nodeName` getter returns "". DOMPurify+ * caches that getter at import time (anti-clobbering hardening added in+ * 3.4.8) and reads every node's name through it, so the first node it+ * looks at is seen as an unknown tag: elements are unwrapped (tags+ * dropped, text kept) and text nodes are dropped outright.+ *+ * Together these make `DOMPurify.sanitize` destroy exactly one node per call+ * and, crucially, NOT be idempotent -- `sanitize(sanitize(x)) !== sanitize(x)`+ * for any markup with more than one node. That breaks+ * `XSSProtection.sanitizeStable`, whose whole contract is to iterate to a+ * fixpoint: instead of converging it erodes the document one node per pass+ * and then falls closed to escaped text. In a real browser DOMPurify is+ * idempotent and `sanitizeStable` returns on its second pass.+ *+ * WHAT THE createNodeIterator REPAIR ITSELF DIVERGES ON. The replacement is+ * not a NodeIterator: it walks the tree once, up front, and then replays that+ * snapshot. A real NodeIterator is live -- it tracks the tree as it changes,+ * so a node DOMPurify has already removed is never handed back, and nodes+ * inserted during traversal are seen. Here the opposite holds: every node+ * present at creation time is yielded, including ones removed mid-pass, and+ * nodes added mid-pass are never yielded. For DOMPurify that is safe in the+ * direction that matters -- it means the sanitizer inspects MORE nodes than a+ * browser would, never fewer, so nothing hostile is skipped -- but a test+ * that asserts on *how many* nodes were visited, or that relies on a removal+ * cutting traversal short, is measuring this shim rather than the browser.+ *+ * Neither repair changes what `Element.prototype.namespaceURI` reports:+ * happy-dom's own HTML parser already assigns SVG namespace correctly by+ * tree position (see `NamespaceURI.svg` handling in+ * html-parser/HTMLParser.ts), and this file does not touch that. It also+ * does NOT fabricate a MathML namespace from tag name -- happy-dom has no+ * MathML foreign-content support at all (no tokenizer/tree-construction+ * branch for it), so no getter override can make `<math>` subtrees behave+ * like a real browser's; a getter that returned MathML for any element whose+ * tagName happens to be in the MathML tag list, regardless of where that+ * element actually sits in the tree, would fabricate a namespace-confusion+ * invariant no test could ever fail. Suites that need parsed `<math>`+ * content to survive DOMPurify for a LEGITIMATE reason (asserting on KaTeX's+ * accessibility subtree, not testing namespace-confusion security) opt into+ * that approximation explicitly and locally via+ * `tests/js/happy-dom-mathml-namespace-approximation.js` -- see that file's+ * header for what it does and does not model. Suites asserting a namespace-+ * confusion / mXSS invariant (tests/js/security/mxss-reparse-invariant.test.js)+ * must NOT install it.+ *+ * This runs as a Vitest setup file, BEFORE any test module (and therefore+ * before any `import 'dompurify'`), because DOMPurify captures these+ * primitives at import time. Several suites under tests/js/security/ install+ * their own copy of the same two repairs (plus their own local MathML+ * namespace approximation) in module scope; re-installing is harmless (every+ * descriptor is `configurable` and this file's repairs do not touch+ * namespaceURI at all).+ *+ * Upstream: https://github.com/capricorn86/happy-dom/issues/2182+ */++export function installDomPurifyHappyDomShims() {+ document.createNodeIterator = function(root, whatToShow) {+ const mask = whatToShow === undefined || whatToShow === null+ ? 0xffffffff+ : whatToShow;+ const nodes = [];+ (function collect(node) {+ if (mask & (1 << (node.nodeType - 1))) {+ nodes.push(node);+ }+ for (let i = 0; i < node.childNodes.length; i++) {+ collect(node.childNodes[i]);+ }+ })(root);+ let index = 0;+ return {+ nextNode() {+ return index < nodes.length ? nodes[index++] : null;+ },+ previousNode() {+ return index > 0 ? nodes[--index] : null;+ },+ };+ };++ Object.defineProperty(window.Node.prototype, 'nodeName', {+ configurable: true,+ get() {+ switch (this.nodeType) {+ case 1: return this.tagName;+ case 2: return this.name;+ case 3: return '#text';+ case 4: return '#cdata-section';+ case 7: return this.target;+ case 8: return '#comment';+ case 9: return '#document';+ case 10: return '#document-type';+ case 11: return '#document-fragment';+ default: return '';+ }+ },+ });+}++installDomPurifyHappyDomShims();diff --git a/tests/js/happy-dom-mathml-namespace-approximation.js b/tests/js/happy-dom-mathml-namespace-approximation.jsnew file mode 100644index 0000000000..a85ea1b234--- /dev/null+++ b/tests/js/happy-dom-mathml-namespace-approximation.js@@ -0,0 +1,68 @@+/**+ * OPT-IN, tag-name-based MathML namespace approximation for happy-dom.+ *+ * happy-dom does not parse `<math>` subtrees into the MathML namespace at+ * all (no tokenizer/tree-construction support for MathML foreign content),+ * so `Element.prototype.namespaceURI` reports the HTML namespace for every+ * MathML tag regardless of where it sits in the tree. DOMPurify treats that+ * as a namespace mismatch and strips KaTeX's accessibility subtree+ * (`annotation`, `semantics`, `mrow`, ...) even though it survives untouched+ * in a real browser.+ *+ * This function patches `namespaceURI` to return the MathML namespace for+ * any element whose tagName is a known MathML tag name -- WITHOUT regard to+ * tree position. That is a coarse approximation good enough to let+ * legitimately-rendered KaTeX markup survive DOMPurify in assertions that+ * check the accessibility subtree exists (e.g. `querySelector('math+ * annotation')`). It is NOT a model of namespace inheritance or of the+ * parser's foreign-content / integration-point rules+ * (`annotation-xml[encoding="text/html"]`, `mglyph`, `mtext` reverting to+ * HTML parsing inside a table or form), which is exactly the axis+ * mXSS namespace-confusion payloads exploit.+ *+ * DO NOT install this in a suite that asserts a namespace-confusion / mXSS+ * invariant (checking that no HTML-namespaced element has a foreign-+ * namespaced parent, or similar): because this getter answers purely from+ * tag name, such a check can never observe real namespace confusion -- it+ * would report "confused" or "not confused" consistently with the input's+ * tag names, never with where a real parser would actually have put those+ * tags. tests/js/security/mxss-reparse-invariant.test.js deliberately does+ * NOT install this for that reason; see its header for what it uses instead+ * (happy-dom's real, tree-position-based SVG namespace tracking, and an+ * explicit acknowledgment that MathML foreign-content confusion is not+ * modeled by this test harness at all).+ *+ * Suites that only need KaTeX's rendered MathML markup to survive+ * sanitization for a non-adversarial rendering assertion (tests/js/services/+ * ui.test.js's "renderMarkdown with KaTeX math" suite, and the render-XSS+ * suites under tests/js/security/ that assert benign KaTeX output alongside+ * hostile payloads) should call this explicitly in their own `beforeAll`,+ * before importing 'dompurify'.+ */+export function installMathMlNamespaceApproximation() {+ const mathMlTags = new Set([+ 'math', 'semantics', 'annotation', 'annotation-xml', 'maction',+ 'maligngroup', 'malignmark', 'menclose', 'merror', 'mfenced',+ 'mfrac', 'mglyph', 'mi', 'mlabeledtr', 'mlongdiv', 'mmultiscripts',+ 'mn', 'mo', 'mover', 'mpadded', 'mphantom', 'mprescripts', 'mroot',+ 'mrow', 'ms', 'mscarries', 'msgroup', 'msline', 'mspace', 'msqrt',+ 'msrow', 'mstack', 'mstyle', 'msub', 'msubsup', 'msup', 'mtable',+ 'mtd', 'mtext', 'mtr', 'munder', 'munderover', 'none',+ ]);+ const originalNamespace = Object.getOwnPropertyDescriptor(+ window.Element.prototype,+ 'namespaceURI',+ );+ Object.defineProperty(window.Element.prototype, 'namespaceURI', {+ configurable: true,+ get() {+ if (typeof this.tagName === 'string'+ && mathMlTags.has(this.tagName.toLowerCase())) {+ return 'http://www.w3.org/1998/Math/MathML';+ }+ return originalNamespace?.get+ ? originalNamespace.get.call(this)+ : undefined;+ },+ });+}diff --git a/tests/js/pages/news-action-delegation.test.js b/tests/js/pages/news-action-delegation.test.jsnew file mode 100644index 0000000000..fbf5c7ed42--- /dev/null+++ b/tests/js/pages/news-action-delegation.test.js@@ -0,0 +1,170 @@+/**+ * Trust-boundary regressions for pages/news.js action delegation.+ *+ * Findings and semantic snippets contain renderer-produced markup. The main+ * Markdown policy strips data-* attributes, but action delegation remains an+ * independent trust boundary for alternate renderers and later DOM mutation:+ * matching attributes alone must never invoke an authenticated action. Only+ * controls registered in application-owned menu/footer regions are trusted.+ */++import {+ installNewsRenderHarness,+ makeNewsItem,+} from './helpers/news-render-harness.js';++const EXPECTED_MENU_ACTIONS = [+ 'copy-link',+ 'export-markdown',+ 'hide',+ 'share',+ 'toggle-read',+];+const EXPECTED_FOOTER_ACTIONS = [+ 'create-subscription',+ 'mark-read-on-click',+ 'toggle-save',+ 'vote',+ 'vote',+];++let harness;+let originalUi;++function flushAsyncAction() {+ return new Promise(resolve => setTimeout(resolve, 0));+}++function voteRequestsFor(newsId) {+ return globalThis.fetch.mock.calls.filter(([url, options]) =>+ String(url) === `/news/api/feedback/${newsId}` && options?.method === 'POST'+ );+}++beforeAll(async () => {+ originalUi = window.ui;+ harness = await installNewsRenderHarness();++ // The shared render harness only needs pre-sanitized template output;+ // these tests inspect the live DOM, so include the post-render target used+ // by extractTrendingTopics() as well.+ const trendingTopics = document.createElement('div');+ trendingTopics.id = 'trending-topics';+ document.body.appendChild(trendingTopics);+});++afterAll(() => {+ window.ui = originalUi;+});++beforeEach(() => {+ localStorage.clear();+ window.ui = {+ renderMarkdown: vi.fn(() => '<p>Safe findings</p>'),+ };+});++describe('pages/news.js — trusted news action delegation', () => {+ it('ignores forged actions in findings and nested semantic-style content', async () => {+ window.ui.renderMarkdown.mockReturnValue(`+ <div class="ldr-news-actions-menu">+ <button id="forged-read" data-news-action="toggle-read">+ <span class="forged-read-icon">Mark read</span>+ </button>+ </div>+ <div class="ldr-semantic-snippet">+ <div class="ldr-news-item" data-news-id="forged-card">+ <div class="ldr-news-actions">+ <button id="forged-vote" data-news-action="vote" data-vote="up">+ <span class="forged-vote-icon">Vote</span>+ </button>+ </div>+ </div>+ </div>+ `);++ await harness.renderWith([makeNewsItem({+ id: 'real-card',+ headline: 'FORGED_ACTION_CANARY',+ findings: 'attacker-controlled Markdown',+ })]);++ const findings = document.querySelector('.ldr-news-findings');+ expect(findings).not.toBeNull();+ expect(findings.querySelectorAll('[data-news-action]')).toHaveLength(2);++ // Click nested descendants, matching normal icon/text clicks rather+ // than dispatching directly on the forged controls.+ findings.querySelector('.forged-read-icon').click();+ findings.querySelector('.forged-vote-icon').click();+ await flushAsyncAction();++ expect(localStorage.getItem('news_read_ids')).toBeNull();+ expect(voteRequestsFor('real-card')).toHaveLength(0);+ expect(voteRequestsFor('forged-card')).toHaveLength(0);+ });++ it('keeps every generated action in its intended region and dispatches trusted controls', async () => {+ await harness.renderWith([makeNewsItem({+ id: 'trusted-card',+ headline: 'TRUSTED_ACTION_CANARY',+ findings: 'safe',+ query: 'trusted query',+ })]);++ const card = document.querySelector('#news-feed-content > .ldr-news-item');+ const menu = Array.from(card.children)+ .find(child => child.classList.contains('ldr-news-item-header'))+ .querySelector('.ldr-news-actions-menu');+ const footer = Array.from(card.children)+ .find(child => child.classList.contains('ldr-news-actions'));++ const menuActions = [...menu.querySelectorAll('[data-news-action]')]+ .map(control => control.dataset.newsAction)+ .sort();+ const footerActions = [...footer.querySelectorAll('[data-news-action]')]+ .map(control => control.dataset.newsAction)+ .sort();++ expect(menuActions).toEqual(EXPECTED_MENU_ACTIONS);+ expect(footerActions).toEqual(EXPECTED_FOOTER_ACTIONS);++ // Exercise one control from each trusted region through a nested icon.+ menu.querySelector('[data-news-action="toggle-read"] i').click();+ expect(JSON.parse(localStorage.getItem('news_read_ids'))).toContain('trusted-card');++ globalThis.fetch.mockResolvedValueOnce({+ ok: true,+ json: async () => ({ upvotes: 1, downvotes: 0 }),+ });+ footer.querySelector('[data-news-action="vote"][data-vote="up"] i').click();+ await flushAsyncAction();++ const voteRequests = voteRequestsFor('trusted-card');+ expect(voteRequests).toHaveLength(1);+ expect(JSON.parse(voteRequests[0][1].body)).toEqual({ vote: 'up' });+ });++ it('does not trust a control added to a trusted region after rendering', async () => {+ await harness.renderWith([makeNewsItem({+ id: 'late-control-card',+ headline: 'LATE_CONTROL_CANARY',+ })]);++ const footer = document.querySelector(+ '#news-feed-content > .ldr-news-item > .ldr-news-actions'+ );+ const forgedControl = document.createElement('button');+ forgedControl.dataset.newsAction = 'vote';+ forgedControl.dataset.vote = 'up';+ const forgedLabel = document.createElement('span');+ forgedLabel.textContent = 'Late forged vote';+ forgedControl.appendChild(forgedLabel);+ footer.appendChild(forgedControl);++ forgedLabel.click();+ await flushAsyncAction();++ expect(voteRequestsFor('late-control-card')).toHaveLength(0);+ });+});diff --git a/tests/js/pages/news-actions-direct-runtime.test.js b/tests/js/pages/news-actions-direct-runtime.test.jsindex 4a509e7300..b2551a93f8 100644--- a/tests/js/pages/news-actions-direct-runtime.test.js+++ b/tests/js/pages/news-actions-direct-runtime.test.js@@ -432,7 +432,7 @@ it('uses action attributes accepted by the installed DOMPurify defaults', () =>'button', 'data-news-page-action', 'clear-search',)).toBe(true);expect(DOMPurify.isValidAttribute(- 'button', 'data-vote-type', 'up',+ 'button', 'data-vote', 'up',)).toBe(true);expect(DOMPurify.isValidAttribute('button', 'onclick', "vote('news-one', 'up')",@@ -638,7 +638,7 @@ it('keeps every rendered card action clickable through the page sanitizer contra'hide','vote','vote',- 'mark-read',+ 'mark-read-on-click','toggle-save',]);expect(card.querySelector('[onclick]')).toBeNull();@@ -658,7 +658,7 @@ it('keeps every rendered card action clickable through the page sanitizer contraconst downvoteCallsBefore = fetchMock.mock.calls.filter(([url, options = {}]) => (url === '/news/api/feedback/news-one' && options.method === 'POST')).length;- card.querySelector('[data-news-action="vote"][data-vote-type="down"] i')+ card.querySelector('[data-news-action="vote"][data-vote="down"] i').dispatchEvent(new MouseEvent('click', { bubbles: true }));await vi.waitFor(() => {expect(fetchMock.mock.calls.filter(([url, options = {}]) => (@@ -704,7 +704,7 @@ it('keeps every rendered card action clickable through the page sanitizer contraURL.createObjectURL.mockClear();setReadState('news-one', false);- card.querySelector('[data-news-action="mark-read"] i')+ card.querySelector('[data-news-action="mark-read-on-click"] i').dispatchEvent(new MouseEvent('click', { bubbles: true }));expect(JSON.parse(localStorage.getItem('news_read_ids'))).toContain('news-one');@@ -720,7 +720,7 @@ it('opens the subscription form from its sanitized rendered card control', asynctry {await window.selectSubscription('all');const subscribeControl = document.querySelector(- '[data-news-id="news-one"] [data-news-action="subscribe"]',+ '[data-news-id="news-one"] [data-news-action="create-subscription"]',);expect(subscribeControl).not.toBeNull();expect(subscribeControl.getAttribute('onclick')).toBeNull();diff --git a/tests/js/pages/news-localstorage-xss.test.js b/tests/js/pages/news-localstorage-xss.test.jsnew file mode 100644index 0000000000..0479d58078--- /dev/null+++ b/tests/js/pages/news-localstorage-xss.test.js@@ -0,0 +1,392 @@+/**+ * Security regression tests for the localStorage re-hydration XSS surface of+ * pages/news.js — the paths that survive a page reload and are attacker-+ * writable via any earlier XSS or direct store poisoning.+ *+ * Traced paths (src/local_deep_research/web/static/js/pages/news.js):+ *+ * saved_news_items:+ * loadSavedNewsFeed (news.js:1383) reads + JSON.parse's the key (:1384,+ * UNGUARDED) -> newsItems -> renderNewsItems (:864) builds the card+ * template (:944-1079: headline escapeHtml :1011, summary escapeHtml :993,+ * id escapeHtml :1007, source_url via safeHref :1066, links via+ * renderSourceLinks :1801 -> safeHref/escapeHtml :1821-1823) ->+ * safeRenderHTML (:5) -> window.DOMPurify.sanitize (:26).+ * Entry: loadNewsFeed (:783) saved branch (:798-799), reached via+ * window.selectSubscription('saved') (:775).+ *+ * active_news_research:+ * checkActiveNewsResearch (news.js:2568) reads + JSON.parse's the key+ * (:2571, :2574 — inside try/catch) -> on in-progress status calls+ * monitorResearch(researchId, query) (:2594) -> progress card via DIRECT+ * newCard.innerHTML assignment (:2468-2485). DOMPurify is NOT on this+ * path — escapeHtml is the only barrier: query :2472+ * (escapeHtml(query.substring(0, 60))), researchId :2476, status message+ * :2483, progress coerced via Number() :2480-2481.+ * Entry: DOMContentLoaded (:141) -> initializeNewsPage (:146) ->+ * await checkActiveNewsResearch() (:191).+ *+ * saved_news_ids / expanded_news_ids:+ * loadSavedItems (:1301) / loadExpandedState (:1317) read + parse inside+ * try/catch (malformed -> empty Set). The stored strings never reach+ * innerHTML directly — they only feed `Set.has(item.id)` boolean checks+ * (:1004, :1069-1070). Hydrated via initializeNewsPage (:159, :162).+ *+ * Unlike news-xss.test.js / news-search-history-xss.test.js (server-response+ * data), these tests poison localStorage directly, then drive the REAL+ * re-hydration triggers: window.loadNewsFeed() for the saved feed and a+ * re-dispatched DOMContentLoaded for the page-load paths.+ */++// Backend-injected constants (base.html injects these in production; stub+// before importing config/constants.js, which freezes window.ResearchStates+// around them — same approach as tests/js/config/constants.test.js).+window.RESEARCH_STATUS = {+ IN_PROGRESS: 'in_progress',+ COMPLETED: 'completed',+ FAILED: 'failed',+ SUSPENDED: 'suspended',+ CANCELLED: 'cancelled',+ QUEUED: 'queued',+ PENDING: 'pending',+ ERROR: 'error',+};+window.RESEARCH_TERMINAL_STATES = new Set([+ 'completed', 'suspended', 'failed', 'error', 'cancelled',+]);++const IMG_ONERROR = '<img src=x onerror=alert(1)>';+const QUOTE_BREAK = '"><a href="javascript:alert(1)">click</a>';+const SCRIPT_PAYLOAD = '<script>alert(1)</script>';+// Attribute-context breakout aimed at item.id, the ONLY field that reached+// the card's inline handlers. escapeAttr backslash-escaped the quote, which+// the HTML parser discards, leaving onmouseover as a genuine handler.+const ATTR_BREAK = '" onmouseover="alert(1)';++let sanitizeSpy;+// fetchResponses is keyed by URL substring (search-history harness pattern);+// '/news/api/feed' and '/api/research/' (URLBuilder.researchStatus shape:+// '/api/research/{id}/status') are the endpoints the re-hydration paths hit.+let fetchResponses;+let statusFetches = 0;++function feedContainer() {+ return document.getElementById('news-feed-content');+}++function flush(ms) {+ return new Promise((resolve) => setTimeout(resolve, ms));+}++/** Names of any inline event-handler attributes (on*) anywhere under root. */+function onHandlerAttributes(root) {+ const found = [];+ for (const el of root.querySelectorAll('*')) {+ for (const name of el.getAttributeNames()) {+ if (/^on/i.test(name)) found.push(`${el.tagName}[${name}]`);+ }+ }+ return found;+}++/** on* attributes whose value carries the attacker payload marker.+ *+ * This used to carry a note declaring the card template's static onclick+ * handlers legitimate. They were not: they interpolated item.id through+ * escapeAttr (a JavaScript-string escaper) into an HTML attribute, so a+ * quote in the id closed onclick and the remainder tokenized as real+ * attributes. The card template now ships NO inline handlers at all --+ * ids ride in data-* attributes and are read back by delegation -- so any+ * on* attribute under a rendered card is a finding. */+function payloadHandlerAttributes(root) {+ const found = [];+ for (const el of root.querySelectorAll('*')) {+ for (const name of el.getAttributeNames()) {+ if (/^on/i.test(name) && (el.getAttribute(name) || '').includes('alert(')) {+ found.push(`${el.tagName}[${name}]`);+ }+ }+ }+ return found;+}++/** Any anchor whose href uses the javascript: scheme. */+function javascriptHrefs(root) {+ return [...root.querySelectorAll('a[href]')]+ .map((a) => (a.getAttribute('href') || '').trim())+ .filter((href) => href.toLowerCase().startsWith('javascript:'));+}++function inertContainerAssertions(root) {+ expect(root.querySelector('script')).toBeNull();+ expect(payloadHandlerAttributes(root)).toEqual([]);+ expect(javascriptHrefs(root)).toEqual([]);+}++beforeAll(async () => {+ // Real escaper first — window.escapeHtml from security/xss-protection.js+ // is the production barrier on the innerHTML sink at news.js:2468.+ await import('@js/security/xss-protection.js');+ // window.ResearchStates + window.URLBuilder/URLS, mirroring the base.html+ // script order news.js depends on as bare globals.+ await import('@js/config/constants.js');+ await import('@js/config/urls.js');++ sanitizeSpy = vi.fn((htmlString) => {+ const template = document.createElement('template');+ // eslint-disable-next-line no-unsanitized/property -- test-only spy: htmlString is the pre-sanitized template output we explicitly capture for assertions; runs only under Vitest, never in production.+ template.innerHTML = htmlString;+ return template.content;+ });+ window.DOMPurify = { isSupported: true, sanitize: sanitizeSpy };++ fetchResponses = {+ default: {},+ '/news/api/feed': { news_items: [] },+ '/api/research/': { status: 'in_progress', progress: 45, message: 'Analyzing' },+ };+ globalThis.fetch = vi.fn((url) => {+ const urlStr = String(url);+ let body = fetchResponses.default;+ for (const [key, value] of Object.entries(fetchResponses)) {+ if (key !== 'default' && urlStr.includes(key)) {+ body = value;+ if (key === '/api/research/') statusFetches += 1;+ break;+ }+ }+ return Promise.resolve({+ ok: true,+ status: 200,+ json: () => Promise.resolve(body),+ text: () => Promise.resolve(''),+ });+ });++ document.body.innerHTML = `+ <div id="news-feed-content"></div>+ <input id="table-view-toggle" type="checkbox">+ <tbody id="news-table-body"></tbody>+ <input id="news-search" type="text">+ <button id="search-btn"></button>+ <button id="create-subscription-btn"></button>+ <button id="run-template-btn"></button>+ <input id="impact-filter" type="range" min="0" max="10" value="0">+ <span class="ldr-impact-value"></span>+ <div id="sidebar-subscriptions-list"></div>+ <div id="news-semantic-results"></div>+ <div id="news-query"></div>+ <div id="newsSubscriptionModal"></div>+ <div id="news-subscription-query"></div>+ <div class="ldr-time-filter-group"><button class="ldr-filter-btn"></button></div>+ <input id="auto-refresh" type="checkbox">+ <button id="refresh-feed-btn"></button>+ <div id="recent-searches"></div>+ <div id="trending-topics"></div>+ `;++ localStorage.clear();+ await import('@js/pages/news.js');++ // Pin the module to the saved view — loadNewsFeed's saved branch+ // (news.js:798-799) is the only reader of saved_news_items.+ window.selectSubscription('saved');+});++beforeEach(() => {+ localStorage.clear();+ sanitizeSpy.mockClear();+ statusFetches = 0;+ fetchResponses['/news/api/feed'] = { news_items: [] };+ fetchResponses['/api/research/'] = { status: 'in_progress', progress: 45, message: 'Analyzing' };+ feedContainer().innerHTML = '';+});++/** The pre-sanitized htmlString (news.js:1082 -> safeRenderHTML) containing+ * `substring`, or null — same capture approach as news-render-harness.js. */+function capturedHtmlFor(substring) {+ for (const [htmlString] of sanitizeSpy.mock.calls) {+ if (typeof htmlString === 'string' && htmlString.includes(substring)) {+ return htmlString;+ }+ }+ return null;+}++describe('pages/news.js — saved_news_items localStorage re-hydration XSS', () => {+ it('renders a hostile saved article as inert text (no on* handlers, no <script>, no javascript: hrefs)', async () => {+ localStorage.setItem('saved_news_items', JSON.stringify({+ 'xss-saved-1': {+ // item.id is the field that reached the card's action+ // buttons. The corpus used to poison headline/source_url/links+ // but never this one, routing around the detector below.+ id: `xss-saved-1${ATTR_BREAK}`,+ headline: `${IMG_ONERROR}${QUOTE_BREAK}${SCRIPT_PAYLOAD}`,+ summary: `${QUOTE_BREAK} ${IMG_ONERROR}`,+ source_url: 'javascript:alert(1)',+ links: [{ url: 'javascript:alert(1)', title: SCRIPT_PAYLOAD }],+ topics: [IMG_ONERROR],+ impact_score: 5,+ created_at: new Date().toISOString(),+ savedAt: new Date().toISOString(),+ },+ }));++ // Real trigger: saved branch of loadNewsFeed -> loadSavedNewsFeed+ // (news.js:1383) reads the poisoned key and renders it.+ await window.loadNewsFeed();+ await flush(10); // let post-render vote fetches settle++ const container = feedContainer();+ expect(container.textContent).toContain('alert(1)'); // something rendered++ // Pre-sanitized template output: payloads must arrive escaped.+ const html = capturedHtmlFor('xss-saved-1');+ expect(html).not.toBeNull();+ expect(html).not.toContain('<img src=x');+ expect(html).not.toContain('<script');+ expect(html).not.toContain('href="javascript:');+ expect(html).toContain('<img src=x onerror=alert(1)>');++ // The hostile id must not have produced an attribute breakout. A+ // string check is not enough here -- the id is escapeHtml'd into a+ // data-* attribute, so the literal text " onmouseover=" survives+ // inside the attribute VALUE while being completely inert. Only the+ // parsed DOM can tell the two apart, and the card template now ships+ // no inline handlers of its own, so any on* attribute under a card is+ // a finding.+ //+ // Scoped to the cards, NOT the whole feed container: renderNewsItems+ // also calls updateBulkActionsBar (news.js:1652), which prepends a+ // sibling .ldr-bulk-actions-bar into #news-feed-content carrying three+ // static onclick="markAllAsRead()" / "expandAll()" / "collapseAll()"+ // buttons. That template interpolates only ${unreadCount} and+ // ${totalCount} -- both Array#filter/#length results, never strings --+ // so no attacker-controlled byte can reach those attributes. Every+ // attacker-controlled field in this fixture lands inside a+ // .ldr-news-item, which is exactly what is asserted on here.+ const cards = [...container.querySelectorAll('.ldr-news-item')];+ expect(cards.length).toBeGreaterThan(0);+ for (const cardEl of cards) {+ expect(onHandlerAttributes(cardEl)).toEqual([]);+ }++ // Pin the non-card remainder too, by VALUE rather than by count: the+ // only on* attributes outside the cards must be the bulk bar's three+ // fixed, argument-less verbs. Any new handler, or any handler that+ // grows an interpolated argument list, fails this.+ const nonCardHandlerValues = [];+ for (const el of container.querySelectorAll('*')) {+ if (el.closest('.ldr-news-item')) continue;+ for (const name of el.getAttributeNames()) {+ if (/^on/i.test(name)) nonCardHandlerValues.push(el.getAttribute(name));+ }+ }+ expect(nonCardHandlerValues.sort()).toEqual([+ 'collapseAll()', 'expandAll()', 'markAllAsRead()',+ ]);++ // Post-parse DOM: nothing executable, payload visible as text.+ inertContainerAssertions(container);+ expect(container.textContent).toContain(IMG_ONERROR);+ expect(container.textContent).toContain('javascript:alert(1)');+ });+});++describe('pages/news.js — active_news_research localStorage re-hydration XSS', () => {+ it('renders a hostile query/status through checkActiveNewsResearch -> monitorResearch as inert text', async () => {+ localStorage.setItem('active_news_research', JSON.stringify({+ researchId: 'research-xss-canary',+ query: `${IMG_ONERROR}${QUOTE_BREAK}${SCRIPT_PAYLOAD}`,+ startTime: new Date().toISOString(),+ }));+ // Server-side fields rendered on the same card (escapeHtml :2483,+ // Number() :2480-2481) — poisoned to prove the card sinks hold.+ fetchResponses['/api/research/'] = {+ status: 'in_progress',+ progress: SCRIPT_PAYLOAD,+ message: IMG_ONERROR,+ };++ // Real trigger: page-load re-hydration.+ document.dispatchEvent(new Event('DOMContentLoaded'));+ await vi.waitFor(() => {+ if (!document.querySelector('.ldr-active-research-card')) {+ throw new Error('progress card has not rendered yet');+ }+ });++ // NOTE: this card is a DIRECT newCard.innerHTML assignment+ // (news.js:2468) — DOMPurify is not on this path, escapeHtml is the+ // only barrier, so assert on the parsed DOM itself.+ const card = document.querySelector('.ldr-active-research-card');+ inertContainerAssertions(card);+ // The progress-card template (news.js:2468-2485) ships no static+ // handlers of its own, so ANY on* attribute here would be payload.+ expect(onHandlerAttributes(card)).toEqual([]);+ // Payload survived as inert text (query is truncated at 60 chars,+ // which still covers the full <img ...> payload).+ expect(card.textContent).toContain(IMG_ONERROR);+ expect(card.innerHTML).toContain('<img src=x onerror=alert(1)>');+ });++ it('does not crash or leak when the stored researchId itself is hostile', async () => {+ localStorage.setItem('active_news_research', JSON.stringify({+ researchId: `${QUOTE_BREAK}${IMG_ONERROR}`,+ query: 'benign query',+ startTime: new Date().toISOString(),+ }));++ document.dispatchEvent(new Event('DOMContentLoaded'));+ // The current renderer compares dataset values directly, so a+ // quote-bearing ID remains data and still gets a progress card.+ await vi.waitFor(() => expect(statusFetches).toBeGreaterThanOrEqual(2));+ await flush(50);++ const card = document.querySelector('.ldr-active-research-card');+ expect(card).not.toBeNull();+ expect(card.dataset.researchId).toBe(`${QUOTE_BREAK}${IMG_ONERROR}`);+ expect(onHandlerAttributes(card)).toEqual([]);+ inertContainerAssertions(feedContainer());+ });+});++describe('pages/news.js — malformed localStorage JSON on re-hydration', () => {+ it('saved_news_items: unguarded JSON.parse rejects the load (documented actual behavior)', async () => {+ // news.js:1384 parses this key with NO try/catch. loadNewsFeed is+ // async, so the SyntaxError surfaces as a rejection. On a real page+ // reload initializeNewsPage awaits this call (news.js:173) with no+ // surrounding catch, leaving an unhandled rejection and the feed stuck+ // on the loading spinner — a robustness gap, but NOT an XSS: nothing+ // from the malformed value reaches a sink. Assert the actual behavior+ // rather than guessing a cleanup that does not exist.+ localStorage.setItem('saved_news_items', '{not-valid-json');+ await expect(window.loadNewsFeed()).rejects.toThrow(SyntaxError);+ });++ it('saved_news_ids / expanded_news_ids: malformed JSON is caught and the feed still renders', async () => {+ localStorage.setItem('saved_news_ids', 'not-json-at-all');+ localStorage.setItem('expanded_news_ids', '[[[');++ document.dispatchEvent(new Event('DOMContentLoaded'));+ // loadSavedItems (:1307) and loadExpandedState (:1323) swallow the+ // SyntaxError and reset to empty Sets, so initializeNewsPage completes+ // and renders the (empty) saved feed.+ await vi.waitFor(() => {+ expect(feedContainer().textContent).toContain('No saved items');+ });+ inertContainerAssertions(feedContainer());+ });++ it('active_news_research: malformed JSON is caught and the poisoned key is cleared', async () => {+ localStorage.setItem('active_news_research', '{broken');++ document.dispatchEvent(new Event('DOMContentLoaded'));+ // checkActiveNewsResearch's catch (news.js:2606-2609) removes the key.+ await vi.waitFor(() => {+ expect(localStorage.getItem('active_news_research')).toBeNull();+ });+ expect(document.querySelector('.ldr-active-research-card')).toBeNull();+ inertContainerAssertions(feedContainer());+ });+});diff --git a/tests/js/pages/news-xss.test.js b/tests/js/pages/news-xss.test.jsindex aa9845e7ad..64e49e02ff 100644--- a/tests/js/pages/news-xss.test.js+++ b/tests/js/pages/news-xss.test.js@@ -91,3 +91,68 @@ describe('pages/news.js — XSS regression for PR #3095', () => {expect(html).toContain('<script>');});});++describe('pages/news.js — safeHref open redirect (frontend-security-xss-hardening gate defect (4))', () => {+ // safeHref() used to short-circuit on `startsWith('/')`, so+ // `//evil.com` and `/\evil.com` reached the "View Full Report" href+ // unchanged -- browsers resolve both as protocol-relative, i.e. an+ // open redirect off the current origin. isSafeHref+ // (security/xss-protection.js) rejects this form outright; safeHref+ // now does too, via an explicit check rather than relying on+ // URLValidator.isSafeUrl (which accepts a bare "//evil.com" absent a+ // trustedDomains restriction). This is narrower than an open redirect+ // to any host: safeHref, like isSafeUrl, still accepts a plain+ // "https://evil.com" source_url -- only the disguised "//"/"/\"+ // spelling that used to be misclassified as an internal path is now+ // rejected.+ //+ // Parse the captured pre-sanitized markup and read the href back off the+ // anchor, rather than regexing the raw attribute text. safeHref returns+ // escapeHtml(trimmed) for an accepted internal path, so the raw attribute+ // reads "/results/42"; getAttribute() gives the decoded value+ // the browser would navigate to, which is what these cases are about.+ // That keeps the assertions stable if the escaping (or the attribute+ // order in the template) ever changes.+ function viewFullReportHref(html) {+ const holder = document.createElement('template');+ // eslint-disable-next-line no-unsanitized/property -- test-only: `html` is the pre-sanitized template output captured from the DOMPurify spy, parsed here purely to read the href back; runs only under Vitest, never in production.+ holder.innerHTML = html;+ const link = holder.content.querySelector(+ 'a[data-news-action="mark-read-on-click"]',+ );+ return link ? link.getAttribute('href') : null;+ }++ it.each([+ ['protocol-relative', '//evil.com'],+ ['slash-backslash', '/\\evil.com'],+ // A control character (tab) between the two slashes: browsers+ // strip C0 controls before parsing a URL, so "/\t/evil.com"+ // resolves exactly like "//evil.com". safeHref's `probe` strips+ // control characters before the protocol-relative check for+ // exactly this reason -- this exercises that stripping, not just+ // the already-normalized forms above.+ ['control-character', '/\t/evil.com'],+ ])('rejects a %s source_url on the View Full Report link', async (_label, sourceUrl) => {+ const html = await renderWith([makeItem({+ id: 'redirect-payload',+ headline: 'REDIRECT_CANARY',+ source_url: sourceUrl,+ })]).then(() => renderedHtmlForHeadline('REDIRECT_CANARY'));++ expect(html).not.toBe('');+ const href = viewFullReportHref(html);+ expect(href).toBe('#');+ });++ it('still allows a normal internal path source_url through', async () => {+ const html = await renderWith([makeItem({+ id: 'benign-link',+ headline: 'BENIGN_LINK_CANARY',+ source_url: '/results/42',+ })]).then(() => renderedHtmlForHeadline('BENIGN_LINK_CANARY'));++ expect(html).not.toBe('');+ expect(viewFullReportHref(html)).toBe('/results/42');+ });+});diff --git a/tests/js/pages/unified-search-xss.test.js b/tests/js/pages/unified-search-xss.test.jsnew file mode 100644index 0000000000..988c9d96e2--- /dev/null+++ b/tests/js/pages/unified-search-xss.test.js@@ -0,0 +1,124 @@+let hook;++beforeAll(async () => {+ window.__VITEST_TEST__ = true;+ globalThis.escapeHtml = (value) => String(value ?? '')+ .replace(/&/g, '&')+ .replace(/</g, '<')+ .replace(/>/g, '>')+ .replace(/"/g, '"');+ globalThis.safeFetch = vi.fn();+ globalThis.safeFetchWithAuth = (...args) => globalThis.safeFetch(...args);+ await import('@js/pages/unified_search.js');+ hook = window.__unifiedSearchTest;+});++afterAll(() => {+ delete window.__VITEST_TEST__;+});++function makeDom() {+ const input = document.createElement('input');+ const results = document.createElement('div');+ const empty = document.createElement('div');+ const notice = document.createElement('div');+ const modeBtn = document.createElement('button');+ const modeMenu = document.createElement('ul');+ const modeLabel = document.createElement('span');+ document.body.append(input, results, empty, notice, modeBtn, modeMenu, modeLabel);+ return { input, results, empty, notice, modeBtn, modeMenu, modeLabel };+}++function expectNoActiveMarkup(container) {+ expect(container.querySelectorAll('script').length).toBe(0);+ const eventAttributes = [...container.querySelectorAll('*')]+ .flatMap((element) => [...element.attributes])+ .filter((attribute) => attribute.name.toLowerCase().startsWith('on'));+ expect(eventAttributes).toHaveLength(0);+ expect(container.querySelectorAll('a[href^="javascript:"]').length).toBe(0);+}++beforeEach(() => {+ document.body.innerHTML = '';+});++describe('unified search result rendering XSS surface', () => {+ it('keeps hostile titles, snippets, and source types inert and visible', () => {+ const dom = makeDom();+ hook.setDomRefs(dom);+ const hostileTitle = '<img src=x onerror=alert(1)>';+ const quoteTitle = '"><a href="javascript:alert(1)">x</a>';+ const scriptTitle = '<script>alert(1)</script>';+ const hostileSnippet = '<svg onload=alert(1)>summary</svg>';++ hook.renderUnifiedSearchResults([+ { title: hostileTitle, content_preview: hostileSnippet, url: '/notes/1', source_type: '<img onerror=alert(1)>' },+ { title: quoteTitle, content_preview: hostileSnippet, url: '/notes/2', source_type: '"><b onmouseover=alert(1)>' },+ { title: scriptTitle, content_preview: hostileSnippet, url: '/notes/3', source_type: '<script>alert(1)</script>' },+ ]);++ expectNoActiveMarkup(dom.results);+ expect(dom.results.textContent).toContain(hostileTitle);+ expect(dom.results.textContent).toContain(quoteTitle);+ expect(dom.results.textContent).toContain(scriptTitle);+ expect(dom.results.textContent).toContain(hostileSnippet);+ });++ it('constrains hostile URLs while preserving inert quote-containing paths', () => {+ const dom = makeDom();+ hook.setDomRefs(dom);+ hook.renderUnifiedSearchResults([+ { title: 'JavaScript', content_preview: '', url: 'javascript:alert(1)', source_type: 'note' },+ { title: 'Data', content_preview: '', url: 'data:text/html,<script>alert(1)</script>', source_type: 'note' },+ { title: 'Quote', content_preview: '', url: '/notes/1" onmouseover="alert(1)', source_type: 'note' },+ ]);++ const links = [...dom.results.querySelectorAll('a.ldr-unified-result-card')];+ expect(links[0].getAttribute('href')).toBe('#');+ expect(links[1].getAttribute('href')).toBe('#');+ expect(links[2].getAttribute('href')).toBe('/notes/1" onmouseover="alert(1)');+ expectNoActiveMarkup(dom.results);+ });++ it('does not echo a hostile query into the empty state', async () => {+ const dom = makeDom();+ hook.setDomRefs(dom);+ hook.setUnifiedSearchMode('text');+ dom.input.value = '<script>alert(1)</script>';+ globalThis.safeFetch = vi.fn(() => Promise.resolve({+ json: () => Promise.resolve({ success: true, results: [] }),+ }));++ await hook.runUnifiedSearch();++ expectNoActiveMarkup(dom.empty);+ expect(dom.empty.textContent).not.toContain(dom.input.value);+ expect(dom.empty.textContent).toContain('No matches found');+ });++ it('renders benign results as clickable links without over-escaping', () => {+ const dom = makeDom();+ hook.setDomRefs(dom);+ hook.renderUnifiedSearchResults([+ {+ title: 'A & useful note',+ content_preview: 'Read this summary',+ url: '/notes/benign-1?tab=summary',+ source_type: 'note',+ },+ {+ title: 'Research report',+ content_preview: 'Report preview',+ url: '/results/report-2',+ source_type: 'research_report',+ },+ ]);++ const links = [...dom.results.querySelectorAll('a.ldr-unified-result-card')];+ expect(links).toHaveLength(2);+ expect(links[0].getAttribute('href')).toBe('/notes/benign-1?tab=summary');+ expect(links[1].getAttribute('href')).toBe('/results/report-2');+ expect(links[0].textContent).toContain('A & useful note');+ expect(links[0].textContent).toContain('Read this summary');+ });+});diff --git a/tests/js/security/chat-headers-delete-xss.test.js b/tests/js/security/chat-headers-delete-xss.test.jsnew file mode 100644index 0000000000..d49318650c--- /dev/null+++ b/tests/js/security/chat-headers-delete-xss.test.js@@ -0,0 +1,550 @@+/**+ * XSS regression coverage for:+ *+ * - components/chat.js step-accordion header sinks:+ * :1315 ensureLiveAccordion() header.innerHTML (static literals only)+ * :1447 wrapStepsInAccordion() header.innerHTML (static literals + integer .length)+ * Step row content itself flows through createStepElement -> textContent+ * (:1287), and the live count through label.textContent (:1344).+ * - the DOM-API builders flagged as structurally safe:+ * :1216 _appendResearchLink() (setAttribute('href', encodeURIComponent))+ * :2155 _setBtnLabel() (replaceChildren + createTextNode)+ * - chat session metadata title path (updateTitle -> chatTitle.textContent).+ * The renderMarkdown innerHTML path (:1005) is covered by+ * markdown-render-xss.test.js and is intentionally not re-tested here.+ * - deletion/delete_manager.js's single innerHTML sink (:554,+ * showNotification bootstrap toast) whose `message` argument can carry+ * server-echoed error text (`result.error` -> error.message).+ *+ * Every hostile-payload test drives a real production path (socket progress+ * events, session reload, delete API responses) and asserts inertness:+ * zero script/img/svg/iframe descendants, zero on* attributes, and the+ * payload surviving as visible text.+ */+import fs from 'node:fs';+import path from 'node:path';+import { fileURLToPath } from 'node:url';+import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';++const SESSION_ID = 'sess-1';+const RESEARCH_ID = 'research-1';++/** Hostile payloads covering element injection and attribute quote-breakout. */+const IMG_PAYLOAD = '<img src=x onerror=alert(1)>';+const SVG_QUOTE_PAYLOAD = '"><svg onload=alert(2)>';++function buildChatDom() {+ // Static literal (no interpolation) so no-unsanitized/property is+ // satisfied; SESSION_ID must match this meta content.+ document.head.innerHTML = `+ <meta name="chat-session-id" content="sess-1">+ `;+ document.body.innerHTML = `+ <div id="chat-welcome"></div>+ <textarea id="chat-input"></textarea>+ <button id="send-btn"></button>+ <div id="chat-title"></div>+ <div id="chat-messages" role="log"></div>+ <template id="thinking-template">+ <div class="ldr-chat-message ldr-chat-message-assistant ldr-chat-message-thinking" role="status">+ <div class="ldr-chat-message-avatar"><i class="fas fa-robot"></i></div>+ <div class="ldr-chat-message-content">+ <div class="ldr-chat-thinking-text" hidden></div>+ <div class="ldr-chat-thinking-dots"><span></span><span></span><span></span></div>+ </div>+ </div>+ </template>+ <template id="message-template">+ <div class="ldr-chat-message">+ <div class="ldr-chat-message-avatar"><i class="fas fa-user"></i></div>+ <div class="ldr-chat-message-content">+ <div class="ldr-chat-message-text"></div>+ <div class="ldr-chat-message-meta"><span class="ldr-chat-message-time"></span></div>+ </div>+ </div>+ </template>+ `;+}++const json = (payload) => ({+ ok: true,+ status: 200,+ json: async () => payload,+});++const flush = async (n = 10) => {+ for (let i = 0; i < n; i++) await Promise.resolve();+};++/** Install the window stubs chat.js needs; returns the captured progress cb. */+function stubChatGlobals({ inProgressResearchId }) {+ let progressCb = null;+ window.api = { getCsrfToken: () => '' };+ // Mirrors production's DOMPurify-backed renderer only for BENIGN content+ // in these tests; hostile payloads never travel the renderMarkdown path+ // here (that sink is covered by markdown-render-xss.test.js).+ window.ui = { renderMarkdown: (t) => t };+ window.socket = {+ subscribeToResearch: vi.fn((id, cb) => {+ progressCb = cb;+ }),+ unsubscribeFromResearch: vi.fn(),+ getSocketInstance: vi.fn(() => ({+ on: vi.fn(),+ off: vi.fn(),+ })),+ };+ return { getProgressCb: () => progressCb, inProgressResearchId };+}++/** Standard session-restore fetch mock; messages override via arguments. */+function stubChatFetch({ messages, session }) {+ globalThis.fetch = vi.fn(async (url) => {+ const u = String(url);+ if (u.includes(`/api/chat/sessions/${SESSION_ID}/messages`)) {+ return json({+ success: true,+ messages,+ has_more: false,+ in_progress_research_id: null,+ });+ }+ if (u.includes(`/api/chat/sessions/${SESSION_ID}`)) {+ return json({ success: true, session });+ }+ return json({ success: true, sessions: [] });+ });+}++/** Shared inertness assertion: no active content, no event-handler attrs. */+function expectInert(root) {+ expect(root).not.toBeNull();+ expect(root.querySelectorAll('img, script, svg, iframe, object, embed').length).toBe(0);+ for (const element of root.querySelectorAll('*')) {+ expect(+ [...element.attributes].some(({ name }) => name.toLowerCase().startsWith('on')),+ ).toBe(false);+ }+}++async function loadChatModule() {+ await import('@js/components/chat.js');+ await flush();+}++// =============================================================================+// chat.js — live accordion header sink (ensureLiveAccordion :1315)+// =============================================================================++describe('chat.js live steps header (ensureLiveAccordion :1315)', () => {+ let getProgressCb;++ beforeEach(async () => {+ vi.resetModules();+ buildChatDom();+ const stubs = stubChatGlobals({ inProgressResearchId: RESEARCH_ID });+ getProgressCb = stubs.getProgressCb;+ stubChatFetch({+ messages: [+ {+ id: 'm1',+ role: 'user',+ message_type: 'chat',+ content: 'hello',+ created_at: '2026-07-11T00:00:00Z',+ },+ ],+ session: { id: SESSION_ID, title: 'Test session' },+ });+ // Rewire the in-progress research id the harness reports.+ globalThis.fetch = vi.fn(async (url) => {+ const u = String(url);+ if (u.includes(`/api/chat/sessions/${SESSION_ID}/messages`)) {+ return json({+ success: true,+ messages: [+ {+ id: 'm1',+ role: 'user',+ message_type: 'chat',+ content: 'hello',+ created_at: '2026-07-11T00:00:00Z',+ },+ ],+ has_more: false,+ in_progress_research_id: RESEARCH_ID,+ });+ }+ if (u.includes(`/api/chat/sessions/${SESSION_ID}`)) {+ return json({+ success: true,+ session: { id: SESSION_ID, title: 'Test session' },+ });+ }+ return json({ success: true, sessions: [] });+ });++ await loadChatModule();+ expect(getProgressCb()).toBeTypeOf('function');+ });++ afterEach(() => {+ delete globalThis.fetch;+ });++ it('renders hostile live step message/content inertly and keeps the header static', () => {+ getProgressCb()({+ research_id: RESEARCH_ID,+ phase: 'observation',+ message: `From the web (SearXNG): ${IMG_PAYLOAD}`,+ content: SVG_QUOTE_PAYLOAD,+ progress: 42,+ });++ const group = document.querySelector('.ldr-chat-steps-group[data-live="true"]');+ expectInert(group);++ // Header markup is the static template: chevron + flask icons and a+ // label span — nothing derived from the step text.+ const header = group.querySelector('.ldr-chat-steps-header');+ expect(header.querySelectorAll(':scope > *').length).toBe(3);+ expect(header.querySelector('.ldr-chat-steps-chevron')).not.toBeNull();+ // Live count is maintained via textContent (:1344), not innerHTML.+ expect(header.querySelector('.ldr-chat-steps-label').textContent)+ .toBe('Research Steps (1)');++ // Hostile payloads survive as visible text in the step row.+ const stepText = group.querySelector('.ldr-chat-message-step .ldr-chat-message-text');+ expect(stepText.textContent).toContain(IMG_PAYLOAD);+ expect(stepText.textContent).toContain(SVG_QUOTE_PAYLOAD);+ });++ it('renders a benign live step with its text and count', () => {+ getProgressCb()({+ research_id: RESEARCH_ID,+ phase: 'search',+ message: 'Searching arXiv for "quantum computing"',+ progress: 10,+ });++ const group = document.querySelector('.ldr-chat-steps-group[data-live="true"]');+ const stepText = group.querySelector('.ldr-chat-message-step .ldr-chat-message-text');+ expect(stepText.textContent).toContain('Searching arXiv for "quantum computing"');+ expect(+ group.querySelector('.ldr-chat-steps-label').textContent,+ ).toBe('Research Steps (1)');+ });+});++// =============================================================================+// chat.js — reloaded steps header sink (wrapStepsInAccordion :1447)+// =============================================================================++describe('chat.js reloaded steps header (wrapStepsInAccordion :1447)', () => {+ beforeEach(async () => {+ vi.resetModules();+ buildChatDom();+ stubChatGlobals({ inProgressResearchId: null });+ stubChatFetch({+ messages: [+ {+ id: 'm1',+ role: 'user',+ message_type: 'chat',+ content: 'hello',+ created_at: '2026-07-11T00:00:00Z',+ },+ {+ id: 'step-1',+ role: 'assistant',+ message_type: 'step',+ phase: 'observation',+ content: `From PubMed: ${IMG_PAYLOAD}`,+ created_at: '2026-07-11T00:00:01Z',+ },+ {+ id: 'step-2',+ role: 'assistant',+ message_type: 'step',+ phase: 'search',+ content: SVG_QUOTE_PAYLOAD,+ created_at: '2026-07-11T00:00:02Z',+ },+ ],+ session: { id: SESSION_ID, title: 'Test session' },+ });+ await loadChatModule();+ });++ afterEach(() => {+ delete globalThis.fetch;+ });++ it('wraps hostile persisted steps in an accordion whose header only carries the integer count', () => {+ const groups = document.querySelectorAll(+ '#chat-messages > .ldr-chat-steps-group',+ );+ expect(groups.length).toBe(1);+ const group = groups[0];++ expectInert(group);++ // The :1447 sink's only dynamic operand is stepElements.length —+ // rendered as the integer 2, never step content.+ const label = group.querySelector('.ldr-chat-steps-label');+ expect(label.textContent).toBe('Research Steps (2)');++ const header = group.querySelector('.ldr-chat-steps-header');+ expect(header.querySelectorAll(':scope > *').length).toBe(3);++ // Persisted hostile step content stays text.+ const stepTexts = [+ ...group.querySelectorAll('.ldr-chat-message-step .ldr-chat-message-text'),+ ];+ expect(stepTexts.length).toBe(2);+ expect(stepTexts[0].textContent).toContain(IMG_PAYLOAD);+ expect(stepTexts[1].textContent).toContain(SVG_QUOTE_PAYLOAD);+ });+});++// =============================================================================+// chat.js — session metadata (title) and research link (:1216)+// =============================================================================++describe('chat.js session metadata and research link', () => {+ beforeEach(async () => {+ vi.resetModules();+ buildChatDom();+ stubChatGlobals({ inProgressResearchId: null });+ });++ afterEach(() => {+ delete globalThis.fetch;+ });++ it('renders a hostile session title as text in #chat-title', async () => {+ const hostileTitle = `Session ${IMG_PAYLOAD}`;+ stubChatFetch({+ messages: [],+ session: { id: SESSION_ID, title: hostileTitle },+ });+ await loadChatModule();++ const chatTitle = document.getElementById('chat-title');+ expect(chatTitle.textContent).toBe(hostileTitle);+ expect(chatTitle.children.length).toBe(0);+ expect(document.querySelectorAll('#chat-title img, #chat-title svg').length).toBe(0);+ });++ it('encodes a hostile research_id into the view-research link href (:1216)', async () => {+ const hostileResearchId = `"><svg onload=alert(1)>`;+ stubChatFetch({+ messages: [+ {+ id: 'a1',+ role: 'user',+ message_type: 'chat',+ content: 'query',+ created_at: '2026-07-11T00:00:00Z',+ },+ {+ id: 'a2',+ role: 'assistant',+ message_type: 'chat',+ content: 'Done',+ research_id: hostileResearchId,+ created_at: '2026-07-11T00:00:01Z',+ },+ ],+ session: { id: SESSION_ID, title: 'T' },+ });+ await loadChatModule();++ const anchor = document.querySelector('.ldr-chat-research-link-btn');+ expect(anchor).not.toBeNull();+ // URLBuilder is absent in tests, so the encoded fallback path runs.+ expect(anchor.getAttribute('href')).toBe(+ `/results/${encodeURIComponent(hostileResearchId)}`,+ );+ expectInert(anchor.closest('.ldr-chat-research-link'));+ // Built via DOM APIs: exactly one icon element plus a text node —+ // no injected children from the id.+ expect(anchor.children.length).toBe(1);+ expect(anchor.textContent).toBe(' View full research');+ });++ it('renders the research link normally for a benign research_id', async () => {+ stubChatFetch({+ messages: [+ {+ id: 'a2',+ role: 'assistant',+ message_type: 'chat',+ content: 'Done',+ research_id: 'res-123',+ created_at: '2026-07-11T00:00:01Z',+ },+ ],+ session: { id: SESSION_ID, title: 'T' },+ });+ await loadChatModule();++ const anchor = document.querySelector('.ldr-chat-research-link-btn');+ expect(anchor).not.toBeNull();+ expect(anchor.getAttribute('href')).toBe('/results/res-123');+ expect(anchor.textContent).toBe(' View full research');+ });+});++// =============================================================================+// chat.js — structural lock on the sinks (source-level)+// =============================================================================++describe('chat.js sink structure (source-level lock)', () => {+ const chatSource = fs.readFileSync(+ path.resolve(+ path.dirname(fileURLToPath(import.meta.url)),+ '../../../src/local_deep_research/web/static/js/components/chat.js',+ ),+ 'utf8',+ );++ it('keeps both header.innerHTML templates free of string interpolation', () => {+ const sinks = [];+ const sinkRe = /header\.innerHTML\s*=/g;+ for (let m = sinkRe.exec(chatSource); m !== null; m = sinkRe.exec(chatSource)) {+ const end = chatSource.indexOf(';', m.index + m[0].length);+ sinks.push(chatSource.slice(m.index + m[0].length, end));+ }+ // :1315 (ensureLiveAccordion) and :1447 (wrapStepsInAccordion).+ expect(sinks).toHaveLength(2);+ for (const body of sinks) {+ expect(body.includes('${')).toBe(false);+ }+ // Strip string literals: whatever remains is the dynamic part.+ const strip = (body) => body.replace(/'[^']*'/g, '').replace(/[\s+]/g, '');+ expect(strip(sinks[0])).toBe('');+ expect(strip(sinks[1])).toBe('stepElements.length');+ });++ it('builds the research link and stop-button label without innerHTML', () => {+ const nextFunction = (from) => chatSource.indexOf('\n function ', from);+ const linkStart = chatSource.indexOf('function _appendResearchLink');+ expect(linkStart).toBeGreaterThan(-1);+ const linkBody = chatSource.slice(linkStart, nextFunction(linkStart));+ expect(/\.innerHTML\s*=/.test(linkBody)).toBe(false);+ expect(linkBody.includes("setAttribute('href'")).toBe(true);+ expect(linkBody.includes('encodeURIComponent')).toBe(true);++ const labelStart = chatSource.indexOf('const _setBtnLabel');+ expect(labelStart).toBeGreaterThan(-1);+ const labelEnd = chatSource.indexOf('\n };', labelStart);+ const labelBody = chatSource.slice(labelStart, labelEnd);+ expect(/\.innerHTML\s*=/.test(labelBody)).toBe(false);+ expect(labelBody.includes('createTextNode')).toBe(true);+ });+});++// =============================================================================+// delete_manager.js — showNotification toast innerHTML sink (:554)+// =============================================================================++describe('delete_manager.js showNotification toast (:554)', () => {+ let DM;++ beforeAll(async () => {+ // Production globals: the real escaper and alert-type mapper.+ await import('@js/security/xss-protection.js');+ await import('@js/utils/alert-helpers.js');+ window.api = { fetchWithErrorHandling: vi.fn(), getCsrfToken: () => 'test-token' };+ // Toast branch requires bootstrap.Toast; show() is a no-op stub.+ globalThis.bootstrap = {+ Toast: class {+ show() {}+ },+ };+ window.DeleteConfirmation = { confirmAndRun: vi.fn() };+ await import('@js/deletion/delete_manager.js');+ DM = window.DeleteManager;+ });++ beforeEach(() => {+ window.api.fetchWithErrorHandling.mockReset();+ window.DeleteConfirmation.confirmAndRun.mockReset();+ document.querySelectorAll('.ldr-toast-container').forEach((c) => c.remove());+ });++ const flushPromises = () => new Promise((resolve) => setTimeout(resolve, 0));++ function renderedToasts() {+ return document.querySelectorAll('.ldr-toast-container .toast');+ }++ it('renders a server-echoed hostile error message inertly via the real delete path', async () => {+ const onError = vi.fn();+ window.api.fetchWithErrorHandling.mockResolvedValueOnce({+ success: false,+ error: IMG_PAYLOAD,+ });++ await DM.deleteDocument('doc-1', { skipConfirm: true, onError });+ await flushPromises();++ // Non-vacuity: the error path actually ran and produced a toast.+ expect(onError).toHaveBeenCalled();+ expect(onError.mock.calls[0][0].message).toContain(IMG_PAYLOAD);+ const toasts = renderedToasts();+ expect(toasts.length).toBe(1);++ expectInert(toasts[0]);+ const body = toasts[0].querySelector('.toast-body');+ expect(body.textContent).toContain(IMG_PAYLOAD);+ expect(body.innerHTML).not.toContain('<img');+ expect(body.innerHTML).toContain('<img');+ });++ it('keeps quote-breakout payloads inert in the toast body', () => {+ DM.showNotification('error', `Failed to remove PDFs: ${SVG_QUOTE_PAYLOAD}`);++ const toasts = renderedToasts();+ expect(toasts.length).toBe(1);+ expectInert(toasts[0]);+ const body = toasts[0].querySelector('.toast-body');+ expect(body.textContent).toContain(SVG_QUOTE_PAYLOAD);+ expect(body.innerHTML).not.toContain('<svg');+ expect(body.innerHTML).toContain('<svg');+ });++ it('renders a benign success toast', () => {+ DM.showNotification('success', 'Document deleted successfully');++ const toasts = renderedToasts();+ expect(toasts.length).toBe(1);+ const body = toasts[0].querySelector('.toast-body');+ expect(body.textContent).toBe('Document deleted successfully');+ expect(toasts[0].className).toContain('toast');+ });++ it('passes hostile preview titles to DeleteConfirmation as plain data, not markup', async () => {+ window.DeleteConfirmation.confirmAndRun.mockImplementation(async () => {});+ window.api.fetchWithErrorHandling+ .mockResolvedValueOnce({+ success: true,+ title: `Report ${IMG_PAYLOAD}`,+ has_blob: false,+ has_text: true,+ chunks_count: 3,+ collections_count: 0,+ })+ .mockResolvedValueOnce({ success: true });++ await DM.deleteDocument('doc-2');++ expect(window.DeleteConfirmation.confirmAndRun).toHaveBeenCalledTimes(1);+ const opts = window.DeleteConfirmation.confirmAndRun.mock.calls[0][0];+ expect(opts.title).toBe(`Delete "Report ${IMG_PAYLOAD}"?`);+ // delete_manager itself must not render anything from the title.+ expect(renderedToasts().length).toBe(0);+ expect(document.querySelectorAll('img, svg, script').length).toBe(0);+ });+});diff --git a/tests/js/security/clobbering-prototype-pollution.test.js b/tests/js/security/clobbering-prototype-pollution.test.jsnew file mode 100644index 0000000000..baf327e091--- /dev/null+++ b/tests/js/security/clobbering-prototype-pollution.test.js@@ -0,0 +1,519 @@+/**+ * OWASP DOM Clobbering Prevention Cheat Sheet and WSTG-INV-22 regression+ * coverage for the browser code.+ *+ * Vitest's happy-dom 20.11.2 realm does not expose connected `id` or `name`+ * elements as Window named properties. The harness test records that limitation;+ * the sanitizer/config tests are therefore authoritative for browser behavior.+ * The NodeIterator/nodeName repairs below are installed before dompurify is+ * imported, matching the misc-surface/markdown security harnesses.+ *+ * Source recon performed for prototype-pollution sinks:+ * - grep for recursive merge/clone/path-assignment helper declarations in the+ * static JS source found none. The only `merge(...)` aliases are array/result+ * aggregation through SemanticSearch.buildTieredResults in notes.js and+ * unified_search.js, not recursive object mutation.+ * - settings.js dynamic JSON writes/merges are exercised through its real+ * load -> render -> blur/autosave -> POST path below.+ *+ * The markdown hardening pass preserves benign named attributes while+ * namespacing collisions with sensitive built-ins and app globals.+ */+import { readFileSync, readdirSync } from 'node:fs';+import { join, relative, resolve } from 'node:path';++import {+ afterAll,+ afterEach,+ beforeAll,+ beforeEach,+ describe,+ expect,+ it,+ test,+ vi,+} from 'vitest';++const STATIC_JS_ROOT = resolve(+ __dirname,+ '../../../src/local_deep_research/web/static/js',+);+const XSS_PROTECTION_PATH = join(STATIC_JS_ROOT, 'security/xss-protection.js');+const SETTINGS_KEY = 'app.prototype_pollution_probe';+const SENSITIVE_NAMED_PROPS = new Set([+ 'location', 'document', 'name', 'opener', 'top', 'close', 'frames',+]);+const STANDARD_CLOBBERING_CORPUS = [+ '<a id="api" name="api">api probe</a>',+ '<img name="socket" src="x">',+ '<div id="URLBuilder">URL builder probe</div>',+ ...[...SENSITIVE_NAMED_PROPS].map(+ (propertyName) => `<a id="${propertyName}" name="${propertyName}">${propertyName}</a>`,+ ),+];++function collectJavaScriptFiles(directoryPath) {+ return readdirSync(directoryPath, { withFileTypes: true }).flatMap((directoryEntry) => {+ const entryPath = join(directoryPath, directoryEntry.name);+ if (directoryEntry.isDirectory()) {+ return collectJavaScriptFiles(entryPath);+ }+ return directoryEntry.isFile() && directoryEntry.name.endsWith('.js')+ ? [entryPath]+ : [];+ });+}++const SOURCE_RECORDS = collectJavaScriptFiles(STATIC_JS_ROOT).map((filePath) => ({+ filePath,+ relativePath: relative(STATIC_JS_ROOT, filePath),+ contents: readFileSync(filePath, 'utf8'),+}));++function extractAppGlobals() {+ const names = new Set();+ const assignmentPattern = /\bwindow\.([A-Za-z_$][\w$]*)\s*=(?!=)/g;+ for (const sourceRecord of SOURCE_RECORDS) {+ for (const assignmentMatch of sourceRecord.contents.matchAll(assignmentPattern)) {+ names.add(assignmentMatch[1]);+ }+ }+ return names;+}++const APP_GLOBALS = extractAppGlobals();+const ORIGINAL_CREATE_NODE_ITERATOR = document.createNodeIterator;+const ORIGINAL_NODE_NAME = Object.getOwnPropertyDescriptor(window.Node.prototype, 'nodeName');+const WINDOW_KEYS = [+ 'api', 'socket', 'URLBuilder', 'URLS', 'ui', 'DOMPurify', 'marked',+ 'XSSProtection', 'escapeHtml', 'sanitizeHtml', 'LdrAlertHelpers',+ 'LdrProviderOptions', 'LdrValueHelpers', 'setupSettingsDropdowns',+];+const ORIGINAL_WINDOW_STATE = new Map(WINDOW_KEYS.map((propertyName) => [propertyName, {+ owned: Object.hasOwn(window, propertyName),+ value: window[propertyName],+}]));+const ORIGINAL_GLOBAL_MARKED = {+ owned: Object.hasOwn(globalThis, 'marked'),+ value: globalThis.marked,+};+const ORIGINAL_GLOBAL_DOMPURIFY = {+ owned: Object.hasOwn(globalThis, 'DOMPurify'),+ value: globalThis.DOMPurify,+};++let baselineWindowState;+let productionDOMPurify;+let productionMarked;+let productionLogHelpers;++function installDOMPurifyHappyDomShims() {+ document.createNodeIterator = function createNodeIterator(root, whatToShow) {+ const mask = whatToShow === undefined || whatToShow === null+ ? 0xffffffff+ : whatToShow;+ const nodes = [];+ (function collect(node) {+ if (mask & (1 << (node.nodeType - 1))) {+ nodes.push(node);+ }+ for (let index = 0; index < node.childNodes.length; index++) {+ collect(node.childNodes[index]);+ }+ })(root);+ let iteratorIndex = 0;+ return {+ nextNode() {+ return iteratorIndex < nodes.length ? nodes[iteratorIndex++] : null;+ },+ previousNode() {+ return iteratorIndex > 0 ? nodes[--iteratorIndex] : null;+ },+ };+ };++ Object.defineProperty(window.Node.prototype, 'nodeName', {+ configurable: true,+ get() {+ switch (this.nodeType) {+ case 1: return this.tagName;+ case 2: return this.name;+ case 3: return '#text';+ case 4: return '#cdata-section';+ case 7: return this.target;+ case 8: return '#comment';+ case 9: return '#document';+ case 10: return '#document-type';+ case 11: return '#document-fragment';+ default: return '';+ }+ },+ });+}++function restoreProperty(target, propertyName, savedState) {+ if (savedState.owned) {+ target[propertyName] = savedState.value;+ } else {+ delete target[propertyName];+ }+}++function parseMarkup(markup) {+ const container = document.createElement('div');+ // eslint-disable-next-line no-unsanitized/property -- test-only: parsing sanitizer output is the assertion surface.+ container.innerHTML = markup;+ return container;+}++function renderThenReparse(markdown) {+ const firstParse = parseMarkup(window.ui.renderMarkdown(markdown));+ return parseMarkup(firstParse.innerHTML);+}++function namedValues(root) {+ return [...root.querySelectorAll('[id], [name]')].flatMap((element) =>+ ['id', 'name']+ .map((attributeName) => element.getAttribute(attributeName))+ .filter(Boolean),+ );+}++function collidingNamedValues(root, collisionNames) {+ return [...new Set(namedValues(root).filter((value) => collisionNames.has(value)))].sort();+}++function assertPrototypeClean() {+ expect(({}).polluted).toBeUndefined();+ expect(Object.prototype.polluted).toBeUndefined();+}++function deliberatelyUnsafeRecursiveMerge(target, source) {+ for (const [propertyName, propertyValue] of Object.entries(source)) {+ if (propertyValue && typeof propertyValue === 'object') {+ if (!target[propertyName]) {+ target[propertyName] = {};+ }+ deliberatelyUnsafeRecursiveMerge(target[propertyName], propertyValue);+ } else {+ target[propertyName] = propertyValue;+ }+ }+ return target;+}++beforeAll(async () => {+ installDOMPurifyHappyDomShims();+ const { Marked } = await import('marked');+ productionMarked = new Marked();+ productionDOMPurify = (await import('dompurify')).default;+ globalThis.marked = productionMarked;+ window.marked = productionMarked;+ globalThis.DOMPurify = productionDOMPurify;+ window.DOMPurify = productionDOMPurify;++ await import('@js/config/urls.js');+ await import('@js/services/api.js');+ await import('@js/services/socket.js');+ await import('@js/security/xss-protection.js');+ await import('@js/services/ui.js');+ await import('@js/utils/log-helpers.js');+ productionLogHelpers = window.LdrLogHelpers;+ baselineWindowState = new Map(WINDOW_KEYS.map((propertyName) => [propertyName, {+ owned: Object.hasOwn(window, propertyName),+ value: window[propertyName],+ }]));+});++afterEach(() => {+ vi.restoreAllMocks();+ vi.unstubAllGlobals();+ vi.useRealTimers();+ document.body.replaceChildren();+ baselineWindowState.forEach((savedState, propertyName) => {+ restoreProperty(window, propertyName, savedState);+ });+ globalThis.marked = productionMarked;+ globalThis.DOMPurify = productionDOMPurify;+});++afterAll(() => {+ document.createNodeIterator = ORIGINAL_CREATE_NODE_ITERATOR;+ if (ORIGINAL_NODE_NAME) {+ Object.defineProperty(window.Node.prototype, 'nodeName', ORIGINAL_NODE_NAME);+ }+ ORIGINAL_WINDOW_STATE.forEach((savedState, propertyName) => {+ restoreProperty(window, propertyName, savedState);+ });+ restoreProperty(globalThis, 'marked', ORIGINAL_GLOBAL_MARKED);+ restoreProperty(globalThis, 'DOMPurify', ORIGINAL_GLOBAL_DOMPURIFY);+});++describe('DOM clobbering (OWASP DOM Clobbering Prevention Cheat Sheet)', () => {+ it('documents the named-property behavior available in the happy-dom realm', () => {+ const idProbe = document.createElement('a');+ idProbe.id = '__owaspIdNamedAccessProbe';+ const nameProbe = document.createElement('img');+ nameProbe.name = '__owaspNameNamedAccessProbe';+ document.body.append(idProbe, nameProbe);++ expect(Object.hasOwn(window, '__owaspIdNamedAccessProbe')).toBe(false);+ expect(Object.hasOwn(window, '__owaspNameNamedAccessProbe')).toBe(false);+ });++ it('renders benign markdown through the production pipeline (non-vacuity)', () => {+ const root = renderThenReparse('## Safe heading\n\n**benign content**');++ expect(root.querySelector('h2')?.textContent).toBe('Safe heading');+ expect(root.querySelector('strong')?.textContent).toBe('benign content');+ });++ it('keeps real globals stable when hostile named elements are connected', () => {+ const expectedGlobals = new Map([+ ['api', window.api],+ ['socket', window.socket],+ ['URLBuilder', window.URLBuilder],+ ]);+ const host = parseMarkup(window.ui.renderMarkdown([+ '<a id="api">api</a>',+ '<img name="socket" src="x">',+ '<div id="URLBuilder">builder</div>',+ ].join('\n')));+ document.body.appendChild(host);++ expect(host.textContent).toContain('api');+ for (const [globalName, expectedValue] of expectedGlobals) {+ expect(typeof window[globalName]).toBe(typeof expectedValue);+ expect(window[globalName]).toBe(expectedValue);+ }+ });++ it('locks the shared sanitizer DOM-clobbering configuration', () => {+ const source = readFileSync(XSS_PROTECTION_PATH, 'utf8');+ const configStart = source.indexOf('const SANITIZE_CONFIG = {');+ const configEnd = source.indexOf('\n };', configStart);+ const configSource = source.slice(configStart, configEnd);++ expect(configStart).toBeGreaterThan(-1);+ expect(configEnd).toBeGreaterThan(configStart);+ expect(configSource).toMatch(/\bSANITIZE_DOM:\s*true\b/);+ expect(configSource).toMatch(/\bSANITIZE_NAMED_PROPS:\s*true\b/);+ });++ it('sanitizeHtml inert-izes collisions with sensitive Window/Document built-ins', () => {+ const dirty = [...SENSITIVE_NAMED_PROPS]+ .map((propertyName) => `<a id="${propertyName}" name="${propertyName}">${propertyName}</a>`)+ .join('');+ const root = parseMarkup(window.XSSProtection.sanitizeHtml(dirty));++ expect(root.querySelectorAll('a')).toHaveLength(SENSITIVE_NAMED_PROPS.size);+ expect(root.textContent).toContain('location');+ expect(collidingNamedValues(root, SENSITIVE_NAMED_PROPS)).toEqual([]);+ });++ // App-defined globals need filtering beyond DOMPurify's built-in collision protection.+ //+ // NOTE ON WHAT THIS DOES AND DOES NOT COVER: this asserts the *outcome*+ // -- no element reaching the DOM carries an app-global id/name -- not the+ // MARKDOWN_PROHIBITED_NAMED_PROPS namespacing loop in ui.js. Markdown+ // never delivers an author-chosen id/name that far: renderMarkdown's+ // `renderer.html` hook escapes raw author HTML to text, and `name` is not+ // in MARKDOWN_ALLOWED_ATTR, so the payload below arrives as literal text+ // and the loop sees nothing. Deleting that loop would NOT fail this test.+ // See the comment above MARKDOWN_PROHIBITED_NAMED_PROPS in+ // services/ui.js: it is defence-in-depth with no revert-fails test, and+ // the registry is a best-effort snapshot rather than a checked invariant.+ test('markdown named attributes cannot collide with the source-derived app-global registry', () => {+ expect(APP_GLOBALS.size).toBeGreaterThan(50);+ for (const expectedGlobal of [+ 'api', 'socket', 'ui', 'URLBuilder', 'URLValidator', 'SafeLogger',+ ]) {+ expect(APP_GLOBALS.has(expectedGlobal)).toBe(true);+ }+ const payload = [...APP_GLOBALS]+ .map((globalName) => `<div id="${globalName}" name="${globalName}">${globalName}</div>`)+ .join('\n');+ const root = renderThenReparse(payload);++ expect(collidingNamedValues(root, APP_GLOBALS)).toEqual([]);+ });++ // The collision boundary must survive the production serialize/reparse path.+ test('rendered-then-reparsed hostile corpus has no app-global or sensitive built-in names', () => {+ const collisionNames = new Set([...APP_GLOBALS, ...SENSITIVE_NAMED_PROPS]);+ const root = renderThenReparse(STANDARD_CLOBBERING_CORPUS.join('\n'));++ expect(root.textContent).toContain('api probe');+ expect(collidingNamedValues(root, collisionNames)).toEqual([]);+ });+});++async function exerciseSettingsJsonSave(jsonBody) {+ document.body.innerHTML = `+ <form id="settings-form">+ <input id="settings-search">+ <button type="button" class="ldr-settings-tab active" data-tab="all">All</button>+ <div id="settings-alert"></div>+ <div id="settings-content"></div>+ <div id="raw-config" style="display: none">+ <textarea id="raw_config_editor"></textarea>+ </div>+ </form>`;+ vi.useFakeTimers();+ vi.resetModules();+ await import('@js/config/urls.js');+ await import('@js/services/api.js');+ await import('@js/utils/alert-helpers.js');+ await import('@js/utils/provider-options.js');+ await import('@js/utils/value-helpers.js');+ await import('@js/security/xss-protection.js');++ const settingDescriptor = {+ name: 'Prototype pollution probe',+ description: 'JSON editor security probe',+ value: [],+ ui_element: 'json',+ editable: true,+ visible: true,+ category: 'app_parameters',+ };+ const apiRequests = vi.fn(async (requestUrl, requestOptions = {}) => {+ if (requestUrl === window.URLS.SETTINGS_API.SAVE_ALL_SETTINGS) {+ const savedSettings = JSON.parse(requestOptions.body);+ return {+ status: 'success',+ settings: {+ [SETTINGS_KEY]: {+ ...settingDescriptor,+ value: savedSettings[SETTINGS_KEY],+ },+ },+ };+ }+ if (requestUrl === window.URLS.SETTINGS_API.BASE) {+ return {+ status: 'success',+ settings: { [SETTINGS_KEY]: { ...settingDescriptor } },+ };+ }+ if (requestUrl === '/settings/api/data-location') {+ return { data_directory: '/tmp/ldr-test', security_notice: { encrypted: true } };+ }+ if (requestUrl === window.URLS.SETTINGS_API.BACKUP_STATUS) {+ return { enabled: false, count: 0, backups: [] };+ }+ return { status: 'success' };+ });+ window.api.fetchWithErrorHandling = apiRequests;+ vi.stubGlobal('fetch', vi.fn(async () => new Response(JSON.stringify({+ providers: {},+ provider_options: [],+ engine_options: [],+ }), { status: 200 })));++ await import('@js/components/settings.js');+ if (!apiRequests.mock.calls.some(([requestUrl]) =>+ requestUrl === window.URLS.SETTINGS_API.BASE)) {+ document.dispatchEvent(new Event('DOMContentLoaded'));+ }+ await vi.advanceTimersByTimeAsync(400);++ const editor = document.getElementById('setting-app-prototype_pollution_probe');+ expect(editor).not.toBeNull();+ expect(editor.classList.contains('ldr-json-content')).toBe(true);+ editor.value = jsonBody;+ editor.dispatchEvent(new Event('input', { bubbles: true }));+ editor.dispatchEvent(new Event('blur', { bubbles: true }));+ await vi.advanceTimersByTimeAsync(1);+ await Promise.resolve();++ const saveCall = apiRequests.mock.calls.find(([requestUrl]) =>+ requestUrl === window.URLS.SETTINGS_API.SAVE_ALL_SETTINGS);+ expect(saveCall).toBeDefined();+ return JSON.parse(saveCall[1].body)[SETTINGS_KEY];+}++describe('client-side prototype pollution (OWASP WSTG-INV-22)', () => {+ let pollutedDescriptor;++ beforeEach(() => {+ pollutedDescriptor = Object.getOwnPropertyDescriptor(Object.prototype, 'polluted');+ delete Object.prototype.polluted;+ });++ afterEach(() => {+ delete Object.prototype.polluted;+ if (pollutedDescriptor) {+ Reflect.defineProperty(Object.getPrototypeOf({}), 'polluted', pollutedDescriptor);+ }+ });++ it('keeps hostile category keys inert through LdrLogHelpers.bumpCount', () => {+ const counts = productionLogHelpers.emptyCounts();+ for (const hostileKey of ['__proto__', 'constructor.prototype', '__proto__[x]']) {+ productionLogHelpers.bumpCount(counts, hostileKey, 1);+ }++ expect(counts).toEqual({ info: 0, milestone: 0, warning: 0, error: 0 });+ expect(Object.getPrototypeOf(counts)).toBe(Object.prototype);+ assertPrototypeClean();+ });++ it.each([+ ['__proto__', '{"__proto__":{"polluted":"yes"}}'],+ ['constructor.prototype', '{"constructor":{"prototype":{"polluted":"yes"}}}'],+ ])('keeps %s inert through the real settings JSON load/save flow', async (hostileKey, jsonBody) => {+ const postedValue = await exerciseSettingsJsonSave(jsonBody);++ if (hostileKey === '__proto__') {+ expect(Object.hasOwn(postedValue, '__proto__')).toBe(true);+ const ownProtoValue = Object.getOwnPropertyDescriptor(postedValue, '__proto__').value;+ expect(ownProtoValue.polluted).toBe('yes');+ } else {+ expect(postedValue.constructor.prototype.polluted).toBe('yes');+ }+ assertPrototypeClean();+ });++ it('round-trips benign settings JSON through the same save path (non-vacuity)', async () => {+ const benign = { theme: 'dark', nested: { enabled: true } };+ const postedValue = await exerciseSettingsJsonSave(JSON.stringify(benign));++ expect(postedValue).toEqual(benign);+ assertPrototypeClean();+ });++ it('proves the prototype-clean detector trips on a deliberately unsafe merge', () => {+ const syntheticPayload = JSON.parse('{"__proto__":{"polluted":"yes"}}');+ try {+ expect(() => {+ deliberatelyUnsafeRecursiveMerge({}, syntheticPayload);+ assertPrototypeClean();+ }).toThrow();+ } finally {+ delete Object.prototype.polluted;+ }+ assertPrototypeClean();+ });++ it('records no hand-rolled recursive merge/clone/path helper at JSON boundaries', () => {+ const jsonBoundaryPattern = /\bJSON\.parse\(|(?:local|session)Storage\.getItem\(|fetchWithErrorHandling\(/;+ const helperName = '(?:merge|clone|deepMerge|recursiveMerge|mergeObjects?|deepClone|recursiveClone|cloneObjects?|setByPath|setNestedValue|assignPath|assignNestedValue)';+ const helperDefinitionPattern = new RegExp(+ `\\b(?:function\\s+${helperName}\\s*\\(|(?:const|let|var)\\s+${helperName}\\s*=\\s*(?:async\\s*)?(?:function\\b|\\([^)]*\\)\\s*=>|[a-z_$][\\w$]*\\s*=>))`,+ 'i',+ );+ const boundarySources = SOURCE_RECORDS.filter((sourceRecord) =>+ jsonBoundaryPattern.test(sourceRecord.contents));+ const candidates = SOURCE_RECORDS.flatMap((sourceRecord) =>+ sourceRecord.contents.split('\n').flatMap((sourceLine, lineIndex) => (+ helperDefinitionPattern.test(sourceLine)+ ? [`${sourceRecord.relativePath}:${lineIndex + 1}: ${sourceLine.trim()}`]+ : []+ )));++ expect(SOURCE_RECORDS.length).toBeGreaterThan(50);+ expect(boundarySources.length).toBeGreaterThan(10);+ expect(candidates).toEqual([]);+ });+});diff --git a/tests/js/security/collections-forms-xss.test.js b/tests/js/security/collections-forms-xss.test.jsnew file mode 100644index 0000000000..dcac89d9d6--- /dev/null+++ b/tests/js/security/collections-forms-xss.test.js@@ -0,0 +1,222 @@+/**+ * Security regression tests for collection_upload.js and collection_create.js.+ *+ * Interpolation map:+ * collection_upload.js+ * :267 file.name — escapeHtml; :517/:520/:529/:533 and :587/:590/:603 —+ * file/batch/byte totals derived from numeric file metadata; :612 file.name+ * — escapeHtml; :613 file size — numeric; :643/:648 — progress arguments+ * supplied by numeric XHR progress; :673 — uploaded/errors array lengths;+ * :714/:721/:728/:739/:750/:761/:772 — array lengths; :742/:753/:764+ * uploaded filenames — escapeHtml; :775 failed filename/error — escapeHtml;+ * :782 COLLECTION_ID — encodeURIComponent in href (regression test below).+ * collection_create.js+ * :108 collection.id — raw same-origin redirect path; :139 collection.id —+ * escapeHtml; :141/:144 collection.id — encodeURIComponent in href; :156+ * static onclick only; :179 error message — escapeHtml. collection.name is+ * not interpolated by this module.+ */++const HOSTILE_FILE_NAMES = [+ '<img src=x onerror=alert(1)>.pdf',+ '"><svg onload=alert(2)>.txt',+];+const HOSTILE_ERROR = '<script>alert(3)</script><img src=x onerror=alert(4)>';++let createResponse;+let uploadResponse;++class MockXMLHttpRequest {+ constructor() {+ this.upload = {};+ this.status = 0;+ this.responseText = '';+ }++ open() {}++ setRequestHeader() {}++ send() {+ Promise.resolve().then(() => {+ this.upload.onprogress?.({ lengthComputable: true, loaded: 1, total: 1 });+ this.status = uploadResponse.status;+ this.responseText = uploadResponse.body;+ this.onload();+ });+ }+}++beforeAll(async () => {+ window.URLS = {+ LIBRARY_API: {+ SUPPORTED_FORMATS: '/library/api/supported-formats',+ COLLECTION_UPLOAD: '/library/api/collections/upload',+ COLLECTION_CREATE: '/library/api/collections/create',+ },+ };+ window.URLBuilder = { build: (base, id) => `${base}/${id}` };+ window.URLValidator = {};+ window.api = { getCsrfToken: () => 'test-csrf' };+ globalThis.COLLECTION_ID = 'collection-safe';+ globalThis.XMLHttpRequest = MockXMLHttpRequest;++ await import('@js/security/xss-protection.js');+ await import('@js/collection_upload.js');+ await import('@js/collection_create.js');+});++beforeEach(() => {+ createResponse = { success: true, collection: { id: 'collection-safe', name: 'Safe collection' } };+ uploadResponse = { status: 200, body: JSON.stringify({ success: true, uploaded: [], errors: [] }) };+ globalThis.COLLECTION_ID = 'collection-safe';+ globalThis.safeFetchWithAuth = vi.fn((url) => {+ if (url === window.URLS.LIBRARY_API.SUPPORTED_FORMATS) {+ return Promise.resolve({ ok: true, json: () => Promise.resolve({ count: 1, extensions: ['.txt'], accept_string: '.txt' }) });+ }+ if (url === window.URLS.LIBRARY_API.COLLECTION_CREATE) {+ return Promise.resolve({ ok: true, json: () => Promise.resolve(createResponse) });+ }+ return Promise.reject(new Error(`Unexpected request: ${url}`));+ });+ document.body.innerHTML = `+ <form id="upload-files-form"><input id="files-input" type="file" multiple><button type="submit">Upload</button></form>+ <div id="drop-zone"></div><div id="selected-files" style="display: none"><ul id="file-list"></ul></div>+ <div id="upload-progress" style="display: none"></div><div id="upload-results" style="display: none"></div>+ <span id="format-details"></span><span id="full-format-list"></span>+ <form id="create-collection-form"><input id="collection-name" name="name"><textarea name="description"></textarea><button id="create-collection-btn" type="submit">Create</button></form>+ <input id="collection-is-public" type="checkbox"><input id="collection-agent-enabled" type="checkbox"><span id="name-counter"></span>+ <div id="create-results" style="display: none"></div>+ `;+ document.dispatchEvent(new Event('DOMContentLoaded'));+});++function selectFiles(files) {+ const input = document.getElementById('files-input');+ Object.defineProperty(input, 'files', { configurable: true, value: files });+ input.dispatchEvent(new Event('change'));+}++function submitUpload() {+ document.getElementById('upload-files-form').dispatchEvent(new Event('submit', { cancelable: true }));+}++function submitCreate(name = 'Safe collection') {+ document.getElementById('collection-name').value = name;+ document.getElementById('create-collection-form').dispatchEvent(new Event('submit', { cancelable: true }));+}++function expectNoInjectedMarkup(root) {+ expect(root.querySelectorAll('img, script, svg, iframe')).toHaveLength(0);+ expect(root.querySelectorAll('[onerror], [onload], [onmouseover]')).toHaveLength(0);+}++describe('collection upload XSS surface', () => {+ it('renders hostile File names inert in selected-file and real upload-progress/result paths', async () => {+ const files = HOSTILE_FILE_NAMES.map((name) => new File(['content'], name, { type: 'text/plain' }));+ uploadResponse.body = JSON.stringify({+ success: true,+ uploaded: [+ { filename: HOSTILE_FILE_NAMES[0], status: 'uploaded' },+ { filename: HOSTILE_FILE_NAMES[1], status: '<svg onload=alert(5)>' },+ ],+ errors: [{ filename: HOSTILE_FILE_NAMES[1], error: HOSTILE_ERROR }],+ });++ selectFiles(files);+ const preview = document.getElementById('selected-files');+ expect(preview.querySelectorAll('li')).toHaveLength(2);+ expect(preview.textContent).toContain(HOSTILE_FILE_NAMES[0]);+ expect(preview.textContent).toContain(HOSTILE_FILE_NAMES[1]);+ expectNoInjectedMarkup(preview);++ submitUpload();+ const progress = document.getElementById('upload-progress');+ await vi.waitFor(() => expect(progress.querySelector('#file-progress-list')).not.toBeNull());+ expect(progress.textContent).toContain(HOSTILE_FILE_NAMES[0]);+ expectNoInjectedMarkup(progress);++ const results = document.getElementById('upload-results');+ await vi.waitFor(() => expect(results.style.display).toBe('block'));+ expect(results.textContent).toContain(HOSTILE_FILE_NAMES[0]);+ expect(results.textContent).toContain(HOSTILE_FILE_NAMES[1]);+ expect(results.textContent).toContain(HOSTILE_ERROR);+ expectNoInjectedMarkup(results);+ });++ it('renders a hostile server error message inert through the real XHR failure path', async () => {+ selectFiles([new File(['content'], 'safe.txt', { type: 'text/plain' })]);+ uploadResponse = { status: 500, body: HOSTILE_ERROR };++ submitUpload();+ const results = document.getElementById('upload-results');+ await vi.waitFor(() => expect(results.style.display).toBe('block'));+ expect(results.querySelector('.ldr-alert-danger')).not.toBeNull();+ expect(results.textContent).toContain(HOSTILE_ERROR);+ expectNoInjectedMarkup(results);+ });++ // Regression: collection_upload.js:782 must URI-encode COLLECTION_ID in the View Collection href.+ test('does not parse a hostile collection id as markup in the View Collection href', async () => {+ globalThis.COLLECTION_ID = '"><svg onload=alert(6)>';+ selectFiles([new File(['content'], 'safe.txt', { type: 'text/plain' })]);+ uploadResponse.body = JSON.stringify({+ success: true,+ uploaded: [{ filename: 'safe.txt', status: 'uploaded' }],+ errors: [],+ });++ submitUpload();+ const results = document.getElementById('upload-results');+ await vi.waitFor(() => expect(results.style.display).toBe('block'));+ expectNoInjectedMarkup(results);+ });+});++describe('collection create XSS surface', () => {+ it('renders hostile API collection id/name inert and URI-encodes both result links', async () => {+ const id = '"><svg onload=alert(7)>';+ createResponse = { success: true, collection: { id, name: '<img src=x onerror=alert(8)>' } };++ submitCreate('<script>alert(9)</script>');+ const results = document.getElementById('create-results');+ await vi.waitFor(() => expect(results.style.display).toBe('block'));+ expect(results.textContent).toContain(id);+ expect(results.textContent).not.toContain(createResponse.collection.name);+ const links = results.querySelectorAll('a');+ expect(links).toHaveLength(2);+ expect(links[0].getAttribute('href')).toBe(`/library/collections/${encodeURIComponent(id)}`);+ expect(links[1].getAttribute('href')).toBe(`/library/collections/${encodeURIComponent(id)}/upload`);+ expectNoInjectedMarkup(results);+ });++ it('renders hostile API error messages inert through the actual create submit handler', async () => {+ createResponse = { success: false, error: HOSTILE_ERROR };++ submitCreate('Safe collection');+ const results = document.getElementById('create-results');+ await vi.waitFor(() => expect(results.style.display).toBe('block'));+ expect(results.querySelector('.ldr-alert-danger')).not.toBeNull();+ expect(results.textContent).toContain(HOSTILE_ERROR);+ expectNoInjectedMarkup(results);+ });++ it('keeps benign file preview and successful View/Upload controls working', async () => {+ const fileName = 'meeting-notes.txt';+ selectFiles([new File(['notes'], fileName, { type: 'text/plain' })]);+ const preview = document.getElementById('selected-files');+ expect(preview.querySelectorAll('li')).toHaveLength(1);+ expect(preview.textContent).toContain(fileName);++ createResponse = { success: true, collection: { id: 'collection-42', name: 'Research notes' } };+ submitCreate('Research notes');+ const results = document.getElementById('create-results');+ await vi.waitFor(() => expect(results.style.display).toBe('block'));+ const links = results.querySelectorAll('a');+ expect(links).toHaveLength(2);+ expect(links[0].textContent).toContain('View Collection');+ expect(links[0].getAttribute('href')).toBe('/library/collections/collection-42');+ expect(links[1].textContent).toContain('Upload Files');+ expect(links[1].getAttribute('href')).toBe('/library/collections/collection-42/upload');+ });+});diff --git a/tests/js/security/collections-render-xss.test.js b/tests/js/security/collections-render-xss.test.jsnew file mode 100644index 0000000000..c4ded9b665--- /dev/null+++ b/tests/js/security/collections-render-xss.test.js@@ -0,0 +1,177 @@+/**+ * Security regression tests for renderCollections() in collections_manager.js+ * — the frontend half of the collection XSS incident (8d11eed08; the+ * Python-side coverage lives in tests/security/test_collection_id_xss.py).+ *+ * WHICH escapeHtml is in scope: collections_manager.js defines NO local+ * fallback. Every interpolation calls the bare global `escapeHtml`, i.e.+ * window.escapeHtml installed by security/xss-protection.js (loaded first via+ * base.html). That variant escapes & < > " ' / — so quotes are safe even in+ * attribute context. Unlike collections-manager.test.js (which stubs an+ * identity escaper), these tests install the REAL xss-protection.js escaper+ * so the assertions exercise production escaping end-to-end.+ *+ * renderCollections() reads the module-private `collections` array, so each+ * test drives it through loadCollections(): mock safeFetchWithAuth to return+ * the payload, re-dispatch DOMContentLoaded, and wait for the grid to render.+ */++// --- Global stubs the module reaches for at call time ----------------------+window.URLS = {+ LIBRARY_API: {+ COLLECTIONS: '/library/api/collections',+ },+};+window.api = { getCsrfToken: () => 'test-csrf' };+globalThis.alert = () => {};++// Benign default so the import-time DOMContentLoaded handler (if happy-dom+// fires one) doesn't explode; each test overrides this with its payload.+globalThis.safeFetchWithAuth = vi.fn(() =>+ Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve({ success: true, collections: [] }) })+);++let container;++beforeAll(async () => {+ // Load the REAL escaper first so window.escapeHtml is the production+ // xss-protection.js implementation (the module resolves it as a global+ // at call time, so this must be in place before any render happens).+ await import('@js/security/xss-protection.js');+ await import('@js/collections_manager.js');+});++beforeEach(() => {+ globalThis.safeFetchWithAuth.mockReset();+ globalThis.safeFetchWithAuth.mockImplementation(() =>+ Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve({ success: true, collections: [] }) })+ );+ document.body.innerHTML = '';+ container = document.createElement('div');+ container.id = 'collections-container';+ const noMsg = document.createElement('div');+ noMsg.id = 'no-collections-message';+ document.body.append(container, noMsg);+});++/** Feed `list` through loadCollections() and wait for renderCollections(). */+async function renderCollectionsFrom(collections) {+ globalThis.safeFetchWithAuth.mockImplementation(() =>+ Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve({ success: true, collections }) })+ );+ // The module registered loadCollections() on DOMContentLoaded at import;+ // re-dispatch it to drive fetch -> collections = payload -> render.+ document.dispatchEvent(new window.Event('DOMContentLoaded'));+ await vi.waitFor(() => {+ if (container.children.length === 0) {+ throw new Error('renderCollections() has not rendered yet');+ }+ });+ return container;+}++/** Names of any inline event-handler attributes (on*) anywhere under root. */+function eventHandlerAttributes(root) {+ const found = [];+ for (const el of root.querySelectorAll('*')) {+ for (const name of el.getAttributeNames()) {+ if (/^on/i.test(name)) found.push(`${el.tagName}[${name}]`);+ }+ }+ return found;+}++describe('renderCollections() XSS surface', () => {+ it('has the attribute-safe escapeHtml from security/xss-protection.js in scope', () => {+ // Documents WHICH escaper renderCollections() resolves: window.escapeHtml+ // set by security/xss-protection.js. It must escape & < > " ' / — the+ // quote and slash escaping is what keeps attribute contexts safe.+ expect(window.escapeHtml('<img src=x onerror=alert(1)>')).toBe('<img src=x onerror=alert(1)>');+ expect(window.escapeHtml('x" onmouseover="alert(1)')).toBe('x" onmouseover="alert(1)');+ expect(window.escapeHtml("'")).toBe(''');+ expect(window.escapeHtml('/')).toBe('/');+ });++ it('renders hostile name/description/id as visible text, never as markup', async () => {+ await renderCollectionsFrom([+ {+ id: '"><svg onload=alert(1)>',+ name: '<img src=x onerror=alert(1)>',+ description: '<script>alert(1)</script>',+ document_count: 3,+ created_at: '2026-01-02T03:04:05Z',+ embedding: { provider: 'openai', model: 'text-embedding-3-small' },+ },+ ]);++ // No injected elements...+ expect(container.querySelectorAll('script')).toHaveLength(0);+ expect(container.querySelectorAll('img')).toHaveLength(0);+ expect(container.querySelectorAll('svg')).toHaveLength(0);+ // ...and no inline event-handler attribute anywhere in the grid.+ expect(eventHandlerAttributes(container)).toEqual([]);++ // The payloads survive as VISIBLE TEXT (decoded)...+ expect(container.textContent).toContain('<img src=x onerror=alert(1)>');+ expect(container.textContent).toContain('<script>alert(1)</script>');+ // ...and the serialized markup shows them entity-encoded.+ expect(container.innerHTML).toContain('<img');+ expect(container.innerHTML).toContain('<script');++ // The quote-breakout id stays a single attribute VALUE (data-id).+ const wrapper = container.querySelector('.ldr-collection-card-wrapper');+ expect(wrapper.getAttribute('data-id')).toBe('"><svg onload=alert(1)>');+ });++ it('contains embedding provider/model payloads inside the title attribute (no quote-breakout)', async () => {+ const providerPayload = 'x" onmouseover="alert(1)';+ const modelPayload = 'y" onmouseover="alert(2)';+ await renderCollectionsFrom([+ {+ id: 'coll-attr',+ name: 'attr xss',+ description: '',+ document_count: 1,+ embedding: { provider: providerPayload, model: modelPayload },+ },+ ]);++ // Quote-breakout would create a real onmouseover attribute — none exists.+ expect(container.querySelector('[onmouseover]')).toBeNull();+ expect(eventHandlerAttributes(container)).toEqual([]);++ // Both payloads are contained INSIDE the title value, decoded verbatim:+ // "Embedding: <provider>/<model>" with the quotes inert.+ const span = container.querySelector('.ldr-embedding-info span[title]');+ expect(span).not.toBeNull();+ expect(span.getAttribute('title')).toBe(`Embedding: ${providerPayload}/${modelPayload}`);+ // The visible label is the model string as text, not markup.+ expect(span.textContent).toBe(modelPayload);+ });++ it('never lets a javascript: collection id reach a rendered href', async () => {+ await renderCollectionsFrom([{ id: 'javascript:alert(1)//', name: 'js-uri', document_count: 0 }]);++ const card = container.querySelector('a.ldr-collection-card');+ const view = container.querySelector('a.ldr-collection-view-link');+ // encodeURIComponent() neutralizes the scheme: ':' -> %3A, '/' -> %2F.+ const expected = '/library/collections/javascript%3Aalert(1)%2F%2F';+ expect(card.getAttribute('href')).toBe(expected);+ expect(view.getAttribute('href')).toBe(expected);+ expect(card.getAttribute('href').toLowerCase()).not.toMatch(/^javascript:/);+ });++ it('coerces a hostile document_count to 0 documents with no markup leak', async () => {+ await renderCollectionsFrom([+ { id: 'coll-count', name: 'count xss', description: '', document_count: '<img onerror=x>' },+ ]);++ // Number('<img onerror=x>') is NaN -> || 0 -> "0 documents"; the raw+ // string never reaches the HTML at all.+ const icon = container.querySelector('.ldr-stat-item i.fa-file');+ expect(icon).not.toBeNull();+ expect(icon.nextElementSibling.textContent).toBe('0 documents');+ expect(container.querySelectorAll('img')).toHaveLength(0);+ expect(container.innerHTML).not.toContain('<img');+ });+});diff --git a/tests/js/security/context-overflow-xss.test.js b/tests/js/security/context-overflow-xss.test.jsnew file mode 100644index 0000000000..60ee70657b--- /dev/null+++ b/tests/js/security/context-overflow-xss.test.js@@ -0,0 +1,408 @@+/**+ * Security regression coverage for components/context-overflow.js.+ *+ * The component is an IIFE, so these tests use its real public path:+ * contextOverflowController.loadContextData() -> fetch -> displayContextData().+ * Chart.js is stubbed because its output is canvas-only; every DOM renderer in+ * context-overflow.js still runs unchanged.+ *+ * innerHTML occurrence/interpolation map (current source lines):+ * :49 escapeHtml serializer read after textContent assignment; not a write sink.+ * :154 static empty string.+ * :210 static empty string.+ * :216 static page scaffold; no data interpolation.+ * :412 searchTerm selects one of two hardcoded empty-table messages.+ * :457 request rows assembled at :437-452:+ * :439 timestamp -> Date(...).toLocaleString() (derived text)+ * :440 research_id -> encodeURIComponent in href, escapeHtml in text+ * :441 model -> escapeHtmlAttribute in title, escapeHtml in text+ * :442 provider -> escapeHtml+ * :443 research_phase -> escapeHtml+ * :444-447 token counts/context limit -> formatNumber (numeric coercion)+ * :448 truncation badge -> hardcoded branch+ * :449 class -> hardcoded branch; tokens lost -> formatNumber+ * :450 research_query -> escapeHtmlAttribute in title, escapeHtml in text+ * :476 static no-model message.+ * :485 static empty string.+ * :506 model card assembled at :506-571:+ * :509 model -> escapeHtmlAttribute in title, escapeHtml in text+ * :510 provider -> escapeHtml+ * :513 class -> one of three hardcoded classes+ * :514 truncation_rate -> finite numeric coercion+ * :524/:528/:532 request counts/context limit -> formatNumber/static+ * :536/:550 max_prompt only selects a template; min/avg/max at+ * :540/:544/:548 -> formatNumber+ * :552/:561 hasUtil only selects a template; :556/:559 utilPct is+ * arithmetic-derived and utilColor is a hardcoded CSS variable+ * :564 truncation progress width -> Math.min numeric coercion+ * :567/:570 response-time presence only selects a template+ * :569 avg_response_time_ms -> finite numeric coercion and formatting+ * :582 static no-truncated-requests message.+ * :592 static empty string.+ * :597 recent-truncation table assembled at :597-628:+ * :610/:626 map/join only; :612 timestamp -> Date locale string+ * :614 query and :616 model -> escapeHtml+ * :617-619 token metrics -> formatNumber+ * :621 research_id -> encodeURIComponent in href+ * :895 static no-phase-data message.+ * :930 static no-phase-data message.+ * :1089 phase summary assembled at :1089-1110:+ * :1100/:1107 map/join only; :1102 phase -> escapeHtml;+ * :1103-1105 counts/tokens -> formatNumber.+ * :1265 static load-error message.+ *+ * There are 16 innerHTML tokens in the file: 15 assignments plus the escaped+ * serializer read at :49. There are no insertAdjacentHTML calls.+ */++import { afterAll, afterEach, beforeAll, describe, expect, test, vi } from 'vitest';++const IMG_PAYLOAD = '<img src=x onerror=alert(1)>';+const MODEL_PAYLOAD = '<script>';+const SCRIPT_PAYLOAD = '<script>alert(2)</script>';+const SVG_PAYLOAD = '"><svg onload=alert(3)>';+const ATTR_PAYLOAD = 'x" onmouseover="alert(1)';+const JAVASCRIPT_URL = 'javascript:alert(1)';++beforeAll(async () => {+ window.__VITEST_TEST__ = true;+ globalThis.Chart = class Chart {+ destroy() {}+ };+ globalThis.URLValidator = { safeAssign: vi.fn() };+ await import('@js/components/context-overflow.js');+});++afterEach(() => {+ vi.restoreAllMocks();+});++afterAll(() => {+ delete window.__VITEST_TEST__;+ delete globalThis.Chart;+ delete globalThis.URLValidator;+ delete globalThis.fetch;+});++function buildPayload() {+ const timestamp = '2026-08-20T12:00:00Z';+ return {+ status: 'success',+ overview: {+ truncation_rate: 25,+ truncated_requests: 1,+ requests_with_context_data: 2,+ total_requests: 2,+ avg_tokens_truncated: 256,+ },+ token_summary: { total_requests: 2 },+ model_stats: [{+ model: 'gpt-4',+ provider: 'openai',+ total_requests: 2,+ truncated_count: 1,+ truncation_rate: 25,+ avg_context_limit: 8192,+ }],+ model_token_stats: [{+ model: 'gpt-4',+ provider: 'openai',+ min_prompt: 512,+ avg_prompt: 4096,+ max_prompt: 7000,+ avg_response_time_ms: 1200,+ }],+ recent_truncated: [{+ timestamp,+ research_query: 'Benign truncated query',+ model: 'gpt-4',+ prompt_tokens: 8000,+ context_limit: 8192,+ tokens_truncated: 256,+ research_id: 'research-1',+ }],+ chart_data: [{+ timestamp,+ original_prompt_tokens: 4096,+ prompt_tokens: 4096,+ context_limit: 8192,+ research_phase: 'search',+ research_id: 'research-1',+ model: 'gpt-4',+ provider: 'openai',+ tokens_truncated: 0,+ response_time_ms: 1200,+ truncated: false,+ }],+ context_limits: [8192],+ phase_breakdown: [{+ phase: 'search',+ count: 2,+ total_tokens: 8192,+ avg_tokens: 4096,+ }],+ current_context_window: 4096,+ all_requests: [{+ timestamp,+ research_id: 'research-1',+ model: 'gpt-4',+ provider: 'openai',+ research_phase: 'search',+ prompt_tokens: 4096,+ completion_tokens: 512,+ total_tokens: 4608,+ context_limit: 8192,+ context_truncated: false,+ tokens_truncated: 0,+ research_query: 'Benign request query',+ }],+ pagination: { page: 1, total_pages: 1 },+ };+}++function installPageDom() {+ document.body.innerHTML = `+ <div id="loading"></div>+ <div id="content"></div>+ <div id="empty-no-data"></div>+ <div id="empty-no-truncation"></div>+ <div id="empty-no-context-data"></div>+ <div id="warning-banner"></div>+ <span id="warning-rate"></span>+ <div id="context-overflow-section"></div>+ <table><tbody id="requests-tbody"></tbody></table>+ <span id="pagination-info"></span>+ <button id="pagination-prev"></button>+ <button id="pagination-next"></button>+ `;+}++async function renderPayload(payload) {+ installPageDom();+ globalThis.fetch = vi.fn(async () => ({+ ok: true,+ json: async () => payload,+ }));++ await window.contextOverflowController.loadContextData('30d');+ expect(globalThis.fetch).toHaveBeenCalledTimes(1);+ return document.getElementById('context-overflow-section');+}++function eventHandlerAttributes(root) {+ const found = [];+ for (const element of root.querySelectorAll('*')) {+ for (const name of element.getAttributeNames()) {+ if (/^on/i.test(name)) found.push(`${element.tagName}[${name}]`);+ }+ }+ return found;+}++function expectNoLiveMarkup(root = document.body) {+ expect(root.querySelectorAll('script, img, svg')).toHaveLength(0);+ expect(eventHandlerAttributes(root)).toEqual([]);+}++describe('context-overflow text and attribute contexts', () => {+ test('renders model, provider, query, phase, and overview percentage payloads as inert text', async () => {+ const payload = buildPayload();+ payload.overview.truncation_rate = SCRIPT_PAYLOAD;++ payload.model_stats[0].model = MODEL_PAYLOAD;+ payload.model_stats[0].provider = IMG_PAYLOAD;+ payload.model_token_stats[0].model = MODEL_PAYLOAD;+ payload.model_token_stats[0].provider = IMG_PAYLOAD;++ payload.recent_truncated[0].model = MODEL_PAYLOAD;+ payload.recent_truncated[0].research_query = IMG_PAYLOAD;++ payload.chart_data[0].model = MODEL_PAYLOAD;+ payload.chart_data[0].provider = IMG_PAYLOAD;+ payload.chart_data[0].research_phase = SVG_PAYLOAD;+ payload.phase_breakdown[0].phase = SVG_PAYLOAD;++ payload.all_requests[0].model = MODEL_PAYLOAD;+ payload.all_requests[0].provider = IMG_PAYLOAD;+ payload.all_requests[0].research_phase = SVG_PAYLOAD;+ payload.all_requests[0].research_query = IMG_PAYLOAD;++ const section = await renderPayload(payload);+ const modelCard = section.querySelector('.ldr-model-card');+ const requestRow = document.querySelector('#requests-tbody tr');+ const phaseRow = document.querySelector('#phase-summary-table tbody tr');++ expect(modelCard).not.toBeNull();+ expect(requestRow).not.toBeNull();+ expect(phaseRow).not.toBeNull();+ expect(modelCard.querySelector('.ldr-model-name').textContent).toBe(MODEL_PAYLOAD);+ expect(modelCard.querySelector('.ldr-model-provider').textContent).toBe(IMG_PAYLOAD);+ expect(requestRow.children[2].textContent).toBe(MODEL_PAYLOAD);+ expect(requestRow.children[3].textContent).toBe(IMG_PAYLOAD);+ expect(requestRow.children[4].textContent).toBe(SVG_PAYLOAD);+ expect(requestRow.children[11].textContent).toBe(IMG_PAYLOAD);+ expect(document.getElementById('truncated-list').textContent).toContain(IMG_PAYLOAD);+ expect(phaseRow.children[0].textContent).toBe(SVG_PAYLOAD);+ expect(document.getElementById('truncation-rate').textContent)+ .toBe(`${SCRIPT_PAYLOAD}%`);+ expectNoLiveMarkup();+ });++ test('encodes javascript-like research IDs as inert detail-path segments', async () => {+ const payload = buildPayload();+ payload.recent_truncated[0].research_id = JAVASCRIPT_URL;+ payload.all_requests[0].research_id = JAVASCRIPT_URL;++ const section = await renderPayload(payload);+ const detailLinks = document.querySelectorAll(+ '#truncated-list a[href], #requests-tbody a[href]'+ );++ expect(section.querySelector('.ldr-model-card')).not.toBeNull();+ expect(detailLinks).toHaveLength(2);+ for (const link of detailLinks) {+ expect(link.getAttribute('href')).toBe('/details/javascript%3Aalert(1)');+ expect(link.getAttribute('href')).not.toMatch(/^javascript:/i);+ }+ expectNoLiveMarkup();+ });++ // Regression: all_requests[].model titles must keep quotes inside the attribute value.+ test('prevents quote breakouts in request-model title attributes', async () => {+ const payload = buildPayload();+ payload.all_requests[0].model = ATTR_PAYLOAD;++ await renderPayload(payload);+ const modelCell = document.querySelector('#requests-tbody tr').children[2];++ expect(modelCell).not.toBeNull();+ expect(modelCell.hasAttribute('onmouseover')).toBe(false);+ expect(modelCell.getAttribute('title')).toBe(ATTR_PAYLOAD);+ });++ // Regression: all_requests[].research_query titles must keep quotes inside the attribute value.+ test('prevents quote breakouts in request-query title attributes', async () => {+ const payload = buildPayload();+ payload.all_requests[0].research_query = ATTR_PAYLOAD;++ await renderPayload(payload);+ const queryCell = document.querySelector('#requests-tbody tr').children[11];++ expect(queryCell).not.toBeNull();+ expect(queryCell.hasAttribute('onmouseover')).toBe(false);+ expect(queryCell.getAttribute('title')).toBe(ATTR_PAYLOAD);+ });++ // Regression: model_stats[].model titles must keep quotes inside the attribute value.+ test('prevents quote breakouts in model-card title attributes', async () => {+ const payload = buildPayload();+ payload.model_stats[0].model = ATTR_PAYLOAD;+ payload.model_token_stats[0].model = ATTR_PAYLOAD;++ const section = await renderPayload(payload);+ const modelName = section.querySelector('.ldr-model-name');++ expect(modelName).not.toBeNull();+ expect(modelName.hasAttribute('onmouseover')).toBe(false);+ expect(modelName.getAttribute('title')).toBe(ATTR_PAYLOAD);+ });+});++describe('context-overflow numeric interpolation', () => {+ test('coerces hostile count and token metrics to zero instead of markup', async () => {+ const payload = buildPayload();+ payload.overview.truncated_requests = IMG_PAYLOAD;+ payload.overview.avg_tokens_truncated = IMG_PAYLOAD;+ payload.overview.total_requests = IMG_PAYLOAD;++ payload.model_stats[0].total_requests = IMG_PAYLOAD;+ payload.model_stats[0].truncated_count = IMG_PAYLOAD;+ payload.model_stats[0].avg_context_limit = 0;+ payload.model_token_stats[0].min_prompt = IMG_PAYLOAD;+ payload.model_token_stats[0].avg_prompt = IMG_PAYLOAD;+ payload.model_token_stats[0].max_prompt = IMG_PAYLOAD;++ payload.recent_truncated[0].prompt_tokens = IMG_PAYLOAD;+ payload.recent_truncated[0].context_limit = IMG_PAYLOAD;+ payload.recent_truncated[0].tokens_truncated = IMG_PAYLOAD;++ payload.phase_breakdown[0].count = IMG_PAYLOAD;+ payload.phase_breakdown[0].total_tokens = IMG_PAYLOAD;+ payload.phase_breakdown[0].avg_tokens = IMG_PAYLOAD;++ payload.all_requests[0].prompt_tokens = IMG_PAYLOAD;+ payload.all_requests[0].completion_tokens = IMG_PAYLOAD;+ payload.all_requests[0].total_tokens = IMG_PAYLOAD;+ payload.all_requests[0].context_limit = IMG_PAYLOAD;+ payload.all_requests[0].tokens_truncated = IMG_PAYLOAD;++ const section = await renderPayload(payload);+ const recentCells = document.querySelector('#truncated-list tbody tr').children;+ const requestCells = document.querySelector('#requests-tbody tr').children;+ const phaseCells = document.querySelector('#phase-summary-table tbody tr').children;++ expect(section.querySelector('.ldr-model-card')).not.toBeNull();+ expect(document.getElementById('truncated-count').textContent).toBe('0');+ expect(document.getElementById('avg-tokens-lost').textContent).toBe('0');+ expect([recentCells[3].textContent, recentCells[4].textContent, recentCells[5].textContent])+ .toEqual(['0', '0', '0']);+ expect([+ requestCells[5].textContent,+ requestCells[6].textContent,+ requestCells[7].textContent,+ requestCells[8].textContent,+ requestCells[10].textContent,+ ]).toEqual(['0', '0', '0', '0', '0']);+ expect([phaseCells[1].textContent, phaseCells[2].textContent, phaseCells[3].textContent])+ .toEqual(['0', '0', '0']);+ expect(document.body.textContent).not.toContain(IMG_PAYLOAD);+ expect(document.body.textContent).not.toContain('NaN');+ expectNoLiveMarkup();+ });++ // Regression: model_stats[].truncation_rate must be numerically coerced before interpolation.+ test('rejects markup supplied as a model truncation percentage', async () => {+ const payload = buildPayload();+ payload.model_stats[0].truncation_rate = IMG_PAYLOAD;++ const section = await renderPayload(payload);+ const modelCard = section.querySelector('.ldr-model-card');++ expect(modelCard).not.toBeNull();+ expect(modelCard.querySelector('img')).toBeNull();+ expect(eventHandlerAttributes(modelCard)).toEqual([]);+ });++ // Regression: model_token_stats[].avg_response_time_ms must be numerically coerced.+ test('rejects markup supplied as average response time', async () => {+ const payload = buildPayload();+ payload.model_token_stats[0].avg_response_time_ms = SCRIPT_PAYLOAD;++ const section = await renderPayload(payload);+ const modelCard = section.querySelector('.ldr-model-card');++ expect(modelCard).not.toBeNull();+ expect(modelCard.querySelector('.fa-clock')).not.toBeNull();+ expect(modelCard.querySelector('script')).toBeNull();+ });+});++test('benign control renders all four data-bearing HTML surfaces intact', async () => {+ const section = await renderPayload(buildPayload());+ const modelCard = section.querySelector('.ldr-model-card');+ const recentRow = document.querySelector('#truncated-list tbody tr');+ const requestRow = document.querySelector('#requests-tbody tr');+ const phaseRow = document.querySelector('#phase-summary-table tbody tr');++ expect(modelCard).not.toBeNull();+ expect(recentRow).not.toBeNull();+ expect(requestRow).not.toBeNull();+ expect(phaseRow).not.toBeNull();+ expect(modelCard.textContent).toContain('gpt-4');+ expect(modelCard.textContent).toContain('OpenAI');+ expect(recentRow.textContent).toContain('Benign truncated query');+ expect(requestRow.textContent).toContain('Benign request query');+ expect(phaseRow.textContent).toContain('search');+ expect(document.querySelectorAll('a[href="/details/research-1"]')).toHaveLength(2);+ expectNoLiveMarkup();+});diff --git a/tests/js/security/dompurify-unsupported-fail-closed.test.js b/tests/js/security/dompurify-unsupported-fail-closed.test.jsindex 36a0b7c506..a88f90d30d 100644--- a/tests/js/security/dompurify-unsupported-fail-closed.test.js+++ b/tests/js/security/dompurify-unsupported-fail-closed.test.js@@ -12,7 +12,7 @@** - xss-protection.js sanitizeHtml -> escaped text* - xss-protection.js safeSetInnerHTML -> textContent- * - xss-protection.js safeCreateElement -> throws+ * - xss-protection.js safeCreateElement -> allowlisted DOM creation* - semantic_search.js renderSnippet -> escaped text* - news.js safeRenderHTML -> textContent* - pdf.js generatePdf -> throws, temp DOM removed@@ -85,22 +85,36 @@ describe('xss-protection.js with an unsupported DOMPurify', () => {expect(el.textContent).toBe(RAW);});- it.each(UNSUPPORTED)('safeCreateElement refuses (isSupported=%s)', (flag) => {+ it.each(UNSUPPORTED)('safeCreateElement strips unsafe attributes without a sanitizer (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');+ const element = window.safeCreateElement('a', 'x', {+ onclick: 'window.__ldrPwned=1', href: 'javascript:alert(1)', title: 'safe',+ });+ expect(element.textContent).toBe('x');+ expect(element.hasAttribute('onclick')).toBe(false);+ expect(element.hasAttribute('href')).toBe(false);+ expect(element.getAttribute('title')).toBe('safe');expect(purifier.sanitize).not.toHaveBeenCalled();});+ it.each(UNSUPPORTED)('sanitizeStable escapes when unsupported (isSupported=%s)', flag => {+ const purifier = unsupportedPurifier(flag);+ bindPurifier(purifier);+ const out = window.XSSProtection.sanitizeStable(RAW, {});+ expect(purifier.sanitize).not.toHaveBeenCalled();+ expect(out).not.toContain('<img');+ expect(out).toContain('<img');+ });+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);+ expect(purifier.sanitize).toHaveBeenCalled();});});diff --git a/tests/js/security/library-search-xss.test.js b/tests/js/security/library-search-xss.test.jsnew file mode 100644index 0000000000..0bff2f97e2--- /dev/null+++ b/tests/js/security/library-search-xss.test.js@@ -0,0 +1,920 @@+/**+ * XSS regression coverage for the library/search/history render surfaces.+ *+ * Interpolation map (source lines at the revision under test):+ * library_search.js:38-52,161-184 — result ids/titles/file types/dates/domains+ * are passed to SemanticSearch; ids become dataset values, display fields are+ * escaped, and the unencoded id is anchored below /library/document/.+ * library_search_ui.js:313-327 — similarity uses dataset + escapeHtml and+ * snippets use SemanticSearch.renderSnippet; :394-398 receives only static+ * or array-length-derived notices from :225/:230/:267.+ * semantic_search.js:23-42 — marked output is DOMPurify-sanitized (or escaped);+ * :210 dataset id is a DOM-API sink; :216/:226/:228/:231/:233 escape text and+ * attributes; :234 sanitizes snippets; :235-241 scheme-guards external URLs.+ * history.js:549,578-602,630-666,701-733 — ids use dataset/escaped data attrs,+ * titles/status/date/mode/counts use escapeHtml, queries are URI-encoded,+ * and semantic snippets use renderSnippet.+ * history_search.js:390-412 — delegates result rendering to SemanticSearch;+ * progress/status API strings elsewhere use textContent.+ * custom_dropdown.js:31,60,145-200,404-478 — group/reason/no-result text uses+ * textContent or safeSetTextContent, values use setAttribute, and highlighted+ * labels pass through safeSetInnerHTML/DOMPurify.+ * save_to_collection.js:118-146,214-226 — collection ids/names use dataset and+ * names/descriptions/counts use textContent-created DOM nodes.+ * collection_details.js:113-174 — textContent; :187-240 escaped settings;+ * :306-338 escaped document fields, numeric formatBytes, encoded href id;+ * :375-395 escaped note fields + encoded href id; :578-669 textContent;+ * :899-923 delegates cards or escapes the API error.+ */++import {+ afterAll,+ afterEach,+ beforeAll,+ beforeEach,+ describe,+ expect,+ test,+ vi,+} from 'vitest';++const IMG_PAYLOAD = '<img src=x onerror=alert(1)>';+const SVG_PAYLOAD = '"><svg onload=alert(2)>';+const ATTR_PAYLOAD = 'x" onmouseover="alert(3)';+const JS_URL = 'javascript:alert(4)';++const originalGlobals = {+ api: window.api,+ bootstrap: globalThis.bootstrap,+ collectionId: globalThis.COLLECTION_ID,+ domPurify: globalThis.DOMPurify,+ fetch: globalThis.fetch,+ historySearch: window.HistorySearch,+ marked: window.marked,+ researchStates: window.ResearchStates,+ safeFetch: globalThis.safeFetch,+ safeFetchWithAuth: globalThis.safeFetchWithAuth,+};++let realLibrarySearch;+let pageListeners;+let pageListenerSpy;++function setFixture(html) {+ // eslint-disable-next-line no-unsanitized/property -- test-only helper; every caller passes a static fixture literal defined in this file.+ document.body.innerHTML = html;+}++function eventHandlerAttributes(root) {+ const found = [];+ for (const element of [root, ...root.querySelectorAll('*')]) {+ for (const name of element.getAttributeNames()) {+ if (/^on/i.test(name)) found.push(name.toLowerCase());+ }+ }+ return found;+}++function expectInert(root) {+ expect(root.querySelectorAll('img, script, svg, iframe, object, embed')).toHaveLength(0);+ // No exemption list here: an inline onclick (or any other `on*`)+ // attribute anywhere under root must fail this check. An exemption+ // parameter on this assertion is exactly the shape that let a reverted+ // inline-onclick regression pass round 1 (see the comment at the+ // click-driven regression test below).+ expect(eventHandlerAttributes(root)).toEqual([]);+}++function expectSafeHrefs(root) {+ const anchors = root.querySelectorAll('a[href]');+ for (const anchor of anchors) {+ expect(anchor.getAttribute('href')).not.toMatch(/^\s*(?:javascript|data|vbscript):/i);+ }+}++function researchStatesStub() {+ return {+ formatStatus: (status) => String(status || ''),+ isTerminal: (status) => ['completed', 'failed', 'cancelled', 'error'].includes(status),+ isCompleted: (status) => status === 'completed',+ isFailed: (status) => status === 'failed',+ isCancelled: (status) => status === 'cancelled',+ };+}++function installDomPurifyHappyDomShims() {+ document.createNodeIterator = function(root, whatToShow) {+ const mask = whatToShow === undefined || whatToShow === null+ ? 0xffffffff+ : whatToShow;+ const nodes = [];+ (function collect(node) {+ if (mask & (1 << (node.nodeType - 1))) nodes.push(node);+ for (const child of node.childNodes) collect(child);+ })(root);+ let index = 0;+ return {+ nextNode() {+ return index < nodes.length ? nodes[index++] : null;+ },+ previousNode() {+ return index > 0 ? nodes[--index] : null;+ },+ };+ };++ Object.defineProperty(window.Node.prototype, 'nodeName', {+ configurable: true,+ get() {+ switch (this.nodeType) {+ case 1: return this.tagName;+ case 2: return this.name;+ case 3: return '#text';+ case 4: return '#cdata-section';+ case 7: return this.target;+ case 8: return '#comment';+ case 9: return '#document';+ case 10: return '#document-type';+ case 11: return '#document-fragment';+ default: return '';+ }+ },+ });++ const mathMlTags = new Set([+ 'math', 'semantics', 'annotation', 'annotation-xml', 'maction',+ 'maligngroup', 'malignmark', 'menclose', 'merror', 'mfenced',+ 'mfrac', 'mglyph', 'mi', 'mlabeledtr', 'mlongdiv', 'mmultiscripts',+ 'mn', 'mo', 'mover', 'mpadded', 'mphantom', 'mprescripts', 'mroot',+ 'mrow', 'ms', 'mscarries', 'msgroup', 'msline', 'mspace', 'msqrt',+ 'msrow', 'mstack', 'mstyle', 'msub', 'msubsup', 'msup', 'mtable',+ 'mtd', 'mtext', 'mtr', 'munder', 'munderover', 'none',+ ]);+ const originalNamespace = Object.getOwnPropertyDescriptor(+ window.Element.prototype,+ 'namespaceURI'+ );+ Object.defineProperty(window.Element.prototype, 'namespaceURI', {+ configurable: true,+ get() {+ if (typeof this.tagName === 'string'+ && mathMlTags.has(this.tagName.toLowerCase())) {+ return 'http://www.w3.org/1998/Math/MathML';+ }+ return originalNamespace?.get+ ? originalNamespace.get.call(this)+ : undefined;+ },+ });+}++beforeAll(async () => {+ // DOMPurify captures these DOM primitives at import time; happy-dom's+ // defaults do not expose enough node metadata for removal-based sanitizing.+ installDomPurifyHappyDomShims();+ const DOMPurify = (await import('dompurify')).default;+ const { marked } = await import('marked');+ globalThis.DOMPurify = DOMPurify;+ window.DOMPurify = DOMPurify;+ window.marked = marked;++ await import('@js/security/xss-protection.js');+ await import('@js/config/urls.js');+ await import('@js/components/library_search.js');+ await import('@js/components/custom_dropdown.js');+ realLibrarySearch = window.LibrarySearch;+});++beforeEach(() => {+ // Each scenario loads a different page into this shared document. Retire+ // its initializer before another page dispatches DOMContentLoaded.+ vi.resetModules();+ pageListeners = [];+ const addEventListener = document.addEventListener.bind(document);+ pageListenerSpy = vi.spyOn(document, 'addEventListener').mockImplementation(+ (type, listener, options) => {+ pageListeners.push([type, listener, options]);+ addEventListener(type, listener, options);+ }+ );+});++afterEach(() => {+ for (const [type, listener, options] of pageListeners) {+ document.removeEventListener(type, listener, options);+ }+ pageListenerSpy.mockRestore();+ vi.useRealTimers();+ window.LibrarySearch = realLibrarySearch;+ window.HistorySearch = originalGlobals.historySearch;+ window.api = originalGlobals.api;+ window.ResearchStates = originalGlobals.researchStates;+ globalThis.fetch = originalGlobals.fetch;+ globalThis.safeFetch = originalGlobals.safeFetch;+ globalThis.safeFetchWithAuth = originalGlobals.safeFetchWithAuth;+ globalThis.bootstrap = originalGlobals.bootstrap;+ window.bootstrap = originalGlobals.bootstrap;+ document.body.replaceChildren();+});++afterAll(() => {+ globalThis.COLLECTION_ID = originalGlobals.collectionId;+ window.COLLECTION_ID = originalGlobals.collectionId;+ globalThis.DOMPurify = originalGlobals.domPurify;+ window.DOMPurify = originalGlobals.domPurify;+ window.marked = originalGlobals.marked;+});++describe('semantic_search.js', () => {+ test('renders hostile card fields and URLs inert while preserving a benign card', () => {+ const root = document.createElement('div');+ const hostile = window.SemanticSearch.createSemanticResultCard({+ research_id: SVG_PAYLOAD,+ research_title: IMG_PAYLOAD,+ similarity: ATTR_PAYLOAD,+ snippet: `Hostile snippet ${IMG_PAYLOAD} [bad link](${JS_URL})`,+ url: JS_URL,+ type: 'source',+ research_created_at: '2026-01-02T03:04:05Z',+ }, null, 'Hostile');+ const benign = window.SemanticSearch.createSemanticResultCard({+ research_id: 'research-benign',+ research_title: 'Benign semantic result',+ similarity: 87,+ snippet: '**Benign snippet**',+ url: 'https://example.com/source',+ type: 'source',+ research_created_at: '2026-01-02T03:04:05Z',+ }, null, 'Benign');+ root.append(hostile, benign);++ const cards = root.querySelectorAll('.ldr-semantic-result');+ expect(cards).toHaveLength(2);+ expect(hostile.dataset.id).toBe(SVG_PAYLOAD);+ expect(hostile.querySelector('.ldr-semantic-result-title').textContent.trim()).toBe(IMG_PAYLOAD);+ expect(hostile.textContent).toContain(ATTR_PAYLOAD);+ expect(hostile.querySelector('.ldr-semantic-result-source')).toBeNull();+ expect(benign.textContent).toContain('Benign semantic result');+ expect(benign.querySelector('.ldr-semantic-result-source a').getAttribute('href'))+ .toBe('https://example.com/source');+ expectInert(root);+ expectSafeHrefs(root);+ });+});++describe('library_search.js', () => {+ test('drives renderSemanticResults with hostile document fields and a benign control', () => {+ const container = document.createElement('div');+ window.LibrarySearch.renderSemanticResults([+ {+ document_id: SVG_PAYLOAD,+ title: IMG_PAYLOAD,+ similarity: ATTR_PAYLOAD,+ snippet: `Matched ${IMG_PAYLOAD}`,+ file_type: ATTR_PAYLOAD,+ domain: SVG_PAYLOAD,+ url: JS_URL,+ created_at: '2026-01-02T03:04:05Z',+ },+ {+ document_id: 'doc-benign',+ title: 'Benign library document',+ similarity: 91,+ snippet: 'Benign matched passage',+ file_type: 'pdf',+ domain: 'example.com',+ created_at: '2026-01-02T03:04:05Z',+ },+ ], container, 'Matched');++ const cards = container.querySelectorAll('.ldr-semantic-result');+ expect(cards).toHaveLength(2);+ expect(cards[0].dataset.id).toBe(SVG_PAYLOAD);+ expect(cards[0].querySelector('.ldr-semantic-result-title').textContent.trim()).toBe(IMG_PAYLOAD);+ expect(cards[0].querySelector('.ldr-semantic-result-title a').getAttribute('href'))+ .toBe(`/library/document/${SVG_PAYLOAD}`);+ expect(cards[1].textContent).toContain('Benign library document');+ expect(cards[1].querySelector('.ldr-semantic-result-title a').getAttribute('href'))+ .toBe('/library/document/doc-benign');+ expectInert(container);+ expectSafeHrefs(container);+ });+});++describe('library_search_ui.js', () => {+ test('keeps hybrid similarity and snippet payloads inert on an existing benign card', async () => {+ setFixture(`+ <div id="documents-container">+ <div class="ldr-document-card" data-doc-id="doc-ui" data-domain="" data-research="">+ <div class="card-header"><span>Benign existing document</span></div>+ <div class="card-body"></div>+ </div>+ </div>+ <div id="semantic-results-container"></div>+ <div id="library-search-notice"></div>+ <select id="filter-collection"><option value="collection-ui" selected>Collection</option></select>+ <select id="filter-domain"><option value="" selected>All</option></select>+ <select id="filter-research"><option value="" selected>All</option></select>+ <select id="filter-date"><option value="" selected>All</option></select>+ <input id="search-documents">+ `);++ vi.useFakeTimers();+ window.LibrarySearch = {+ performSemanticSearch: vi.fn().mockResolvedValue({+ success: true,+ results: [{+ document_id: 'doc-ui',+ similarity: ATTR_PAYLOAD,+ snippet: `Benign matched text ${IMG_PAYLOAD}`,+ }],+ }),+ getIndexedCollectionIds: () => ['collection-ui'],+ getLibraryCardConfig: () => realLibrarySearch.getLibraryCardConfig(),+ };++ await import('@js/components/library_search_ui.js');+ const input = document.getElementById('search-documents');+ input.value = 'Benign';+ input.dispatchEvent(new Event('input', { bubbles: true }));+ await vi.advanceTimersByTimeAsync(750);++ const container = document.getElementById('documents-container');+ const snippet = container.querySelector('.ldr-library-snippet');+ const badge = container.querySelector('[data-similarity]');+ expect(snippet).not.toBeNull();+ expect(badge).not.toBeNull();+ expect(badge.dataset.similarity).toBe(ATTR_PAYLOAD);+ expect(badge.textContent).toContain(ATTR_PAYLOAD);+ expect(snippet.textContent).toContain('Benign matched text');+ expect(container.textContent).toContain('Benign existing document');+ expectInert(container);+ });+});++describe('history.js', () => {+ test('loads and renders hostile history metadata inert beside a benign item', async () => {+ setFixture(`+ <div id="history-items"></div>+ <input id="history-search">+ <button id="clear-history-btn"></button>+ <div id="history-empty-message"></div>+ `);+ const states = researchStatesStub();+ window.ResearchStates = states;+ globalThis.ResearchStates = states;+ window.api = {+ getCsrfToken: () => 'csrf',+ getResearchHistory: vi.fn().mockResolvedValue({+ items: [+ {+ id: SVG_PAYLOAD,+ title: IMG_PAYLOAD,+ query: ATTR_PAYLOAD,+ mode: SVG_PAYLOAD,+ status: 'completed',+ document_count: 1,+ created_at: '2026-01-02T03:04:05Z',+ metadata: { is_news_search: true },+ },+ {+ id: 'history-benign',+ title: 'Benign history item',+ query: 'benign query',+ mode: 'quick',+ status: 'completed',+ document_count: 2,+ created_at: '2026-01-01T03:04:05Z',+ metadata: {},+ },+ ],+ }),+ };+ globalThis.fetch = vi.fn().mockResolvedValue({+ ok: true,+ json: () => Promise.resolve({ success: true, sessions: [] }),+ });+ window.HistorySearch = {+ getSemanticCollectionId: () => 'history-collection',+ semanticSearchHistory: vi.fn().mockResolvedValue([+ {+ research_id: 'history-benign',+ similarity: ATTR_PAYLOAD,+ snippet: `Tier one snippet ${IMG_PAYLOAD}`,+ },+ {+ research_id: 'semantic-only-hostile',+ research_title: SVG_PAYLOAD,+ similarity: ATTR_PAYLOAD,+ snippet: `Tier three snippet ${IMG_PAYLOAD}`,+ },+ ]),+ };++ await import('@js/components/history.js');+ document.dispatchEvent(new Event('DOMContentLoaded'));+ const container = document.getElementById('history-items');+ await vi.waitFor(() => {+ expect(container.querySelectorAll('.ldr-history-item')).toHaveLength(2);+ });++ const hostile = Array.from(container.querySelectorAll('.ldr-history-item'))+ .find((item) => item.dataset.id === SVG_PAYLOAD);+ const subscribe = hostile.querySelector('.ldr-subscribe-btn');+ expect(hostile.dataset.id).toBe(SVG_PAYLOAD);+ expect(hostile.querySelector('.ldr-history-item-title').textContent).toBe(IMG_PAYLOAD);+ expect(subscribe).not.toBeNull();+ expect(subscribe.dataset.researchId).toBe(SVG_PAYLOAD);+ expect(subscribe.dataset.query).toBe(encodeURIComponent(ATTR_PAYLOAD));+ expect(container.textContent).toContain('Benign history item');+ expect(container.textContent).toContain('Library (2)');+ expectInert(container);++ vi.useFakeTimers();+ const search = document.getElementById('history-search');+ search.value = 'Benign';+ search.dispatchEvent(new Event('input', { bubbles: true }));+ await vi.advanceTimersByTimeAsync(750);++ const snippets = container.querySelectorAll('.ldr-history-item-snippet');+ const badges = container.querySelectorAll('.ldr-ai-match-badge');+ expect(snippets).toHaveLength(2);+ expect(badges).toHaveLength(2);+ expect(container.textContent).toContain('Tier one snippet');+ expect(container.textContent).toContain('Tier three snippet');+ expect(container.textContent).toContain(SVG_PAYLOAD);+ expect(container.textContent).toContain('Benign history item');+ expectInert(container);+ });+});++describe('history_search.js', () => {+ test('renders hostile API results through the real shared card path with a benign control', async () => {+ const states = researchStatesStub();+ window.ResearchStates = states;+ globalThis.ResearchStates = states;+ window.api = { getCsrfToken: () => 'csrf' };+ globalThis.fetch = vi.fn((url) => Promise.resolve({+ ok: true,+ json: () => Promise.resolve(String(url).includes('research-history/collection')+ ? {+ success: true,+ collection_id: 'history-collection',+ indexed_documents: 1,+ total_documents: 1,+ }+ : { status: 'idle' }),+ }));++ await import('@js/components/history_search.js');+ document.dispatchEvent(new Event('DOMContentLoaded'));+ await new Promise((resolve) => setTimeout(resolve, 0));+ setFixture('<div id="history-items"></div>');++ window.HistorySearch.renderSemanticResults([+ {+ research_id: SVG_PAYLOAD,+ research_title: IMG_PAYLOAD,+ similarity: ATTR_PAYLOAD,+ snippet: `History snippet ${IMG_PAYLOAD}`,+ url: JS_URL,+ },+ {+ research_id: 'history-semantic-benign',+ research_title: 'Benign history semantic result',+ similarity: 75,+ snippet: 'Benign history snippet',+ url: 'https://example.com/history',+ },+ ], 'History');++ const container = document.getElementById('history-items');+ expect(container.querySelectorAll('.ldr-semantic-result')).toHaveLength(2);+ expect(container.textContent).toContain(IMG_PAYLOAD);+ expect(container.textContent).toContain('Benign history semantic result');+ expectInert(container);+ expectSafeHrefs(container);+ });+});++describe('custom_dropdown.js', () => {+ function mountDropdown() {+ setFixture(`+ <div id="dropdown-wrapper">+ <input id="security-dropdown">+ <input id="security-dropdown_hidden" type="hidden">+ <div id="security-dropdown-list"></div>+ </div>+ `);+ return {+ input: document.getElementById('security-dropdown'),+ list: document.getElementById('security-dropdown-list'),+ };+ }++ test('sanitizes hostile option labels while keeping values and benign labels intact', () => {+ const { input, list } = mountDropdown();+ const options = [+ {+ value: ATTR_PAYLOAD,+ label: `Hostile ${IMG_PAYLOAD} option`,+ group_label: SVG_PAYLOAD,+ disabled: true,+ disabled_reason: IMG_PAYLOAD,+ is_favorite: true,+ },+ { value: 'benign', label: 'Benign option', group_label: 'Safe group' },+ ];+ const dropdown = window.setupCustomDropdown(+ input,+ list,+ () => options,+ vi.fn(),+ false,+ 'No results',+ vi.fn()+ );+ input.click();++ const items = list.querySelectorAll('.ldr-custom-dropdown-item');+ const labels = list.querySelectorAll('.ldr-dropdown-item-label');+ expect(items).toHaveLength(2);+ expect(items[0].getAttribute('data-value')).toBe(ATTR_PAYLOAD);+ expect(labels[0].textContent).toContain('Hostile');+ expect(labels[0].textContent).toContain('option');+ expect(labels[1].textContent).toBe('Benign option');+ expect(list.querySelector('.ldr-custom-dropdown-group-header').textContent).toBe(SVG_PAYLOAD);+ expect(list.querySelector('.ldr-dropdown-item-disabled-reason').textContent).toBe(IMG_PAYLOAD);+ expectInert(list);+ dropdown.destroy();+ });++ test('keeps updateDropdownOptions labels inert on the open-list render path', () => {+ const { input, list } = mountDropdown();+ const dropdown = window.setupCustomDropdown(+ input,+ list,+ () => [{ value: 'initial', label: 'Initial benign option' }],+ vi.fn()+ );+ input.click();+ window.updateDropdownOptions(input, [+ { value: JS_URL, label: IMG_PAYLOAD, group_label: SVG_PAYLOAD },+ { value: 'benign-updated', label: 'Benign updated option', group_label: 'Safe group' },+ ]);++ const items = list.querySelectorAll('.ldr-custom-dropdown-item');+ expect(items).toHaveLength(2);+ expect(items[0].getAttribute('data-value')).toBe(JS_URL);+ expect(items[0].querySelector('.ldr-dropdown-item-label').textContent).toBe(IMG_PAYLOAD);+ expect(items[1].textContent).toContain('Benign updated option');+ expectInert(list);+ dropdown.destroy();+ });+});++describe('save_to_collection.js', () => {+ test('keeps hostile collection names/descriptions inert through DOM-API construction', async () => {+ setFixture(`+ <button id="save-to-collection-btn"></button>+ <div id="saveToCollectionModal"></div>+ <div id="collection-list-loading"></div>+ <div id="collection-list"></div>+ <div id="collection-error"></div>+ <div id="collection-success"></div>+ <div id="collection-items"></div>+ `);+ const originalUrl = window.location.href;+ window.history.pushState({}, '', '/results/research-save');+ const show = vi.fn();+ const bootstrapStub = {+ Modal: { getOrCreateInstance: vi.fn(() => ({ show })) },+ };+ globalThis.bootstrap = bootstrapStub;+ window.bootstrap = bootstrapStub;+ globalThis.fetch = vi.fn().mockResolvedValue({+ ok: true,+ json: () => Promise.resolve({+ success: true,+ collections: [+ { id: ATTR_PAYLOAD, name: IMG_PAYLOAD, description: SVG_PAYLOAD },+ { id: 'collection-benign', name: 'Benign collection', description: 'Benign description' },+ ],+ }),+ });++ try {+ await import('@js/components/save_to_collection.js');+ document.dispatchEvent(new Event('DOMContentLoaded'));+ document.getElementById('save-to-collection-btn').click();+ const items = document.getElementById('collection-items');+ await vi.waitFor(() => {+ expect(items.querySelectorAll('button')).toHaveLength(2);+ });++ const buttons = items.querySelectorAll('button');+ expect(show).toHaveBeenCalledTimes(1);+ expect(buttons[0].dataset.collectionId).toBe(ATTR_PAYLOAD);+ expect(buttons[0].dataset.collectionName).toBe(IMG_PAYLOAD);+ expect(buttons[0].querySelector('strong').textContent).toBe(IMG_PAYLOAD);+ expect(buttons[0].querySelector('small').textContent).toBe(SVG_PAYLOAD);+ expect(buttons[1].textContent).toContain('Benign collection');+ expect(buttons[1].textContent).toContain('Benign description');+ expectInert(items);+ } finally {+ window.history.pushState({}, '', originalUrl);+ }+ });+});++describe('collection_details.js', () => {+ test('renders hostile collection/document/note metadata inert and encodes link ids', async () => {+ setFixture(`+ <button id="index-collection-btn"></button>+ <button id="reindex-collection-btn"></button>+ <button id="delete-collection-btn"></button>+ <button id="cancel-indexing-btn"></button>+ <input id="collection-is-public" type="checkbox">+ <input id="collection-agent-enabled" type="checkbox">+ <h1 id="collection-name"></h1>+ <p id="collection-description"></p>+ <span id="stat-total-docs"></span>+ <span id="stat-indexed-docs"></span>+ <span id="stat-unindexed-docs"></span>+ <span id="stat-total-chunks"></span>+ <div id="collection-embedding-info"></div>+ <div id="documents-list"></div>+ <div id="no-documents-message"></div>+ <section id="notes-section"><div id="notes-list"></div></section>+ <section id="collection-search-section" style="display:none">+ <input id="collection-search-input">+ <button id="collection-search-btn"></button>+ <div id="collection-search-results"></div>+ </section>+ <div id="indexing-progress"></div>+ <div id="progress-fill"></div>+ <div id="progress-text"></div>+ <div id="progress-log"></div>+ <div id="indexing-spinner"></div>+ `);++ const states = researchStatesStub();+ window.ResearchStates = states;+ globalThis.ResearchStates = states;+ globalThis.COLLECTION_ID = 'collection-security';+ window.COLLECTION_ID = 'collection-security';+ window.api = { getCsrfToken: () => 'csrf' };++ const payload = {+ success: true,+ collection: {+ name: IMG_PAYLOAD,+ description: SVG_PAYLOAD,+ embedding_model_type: IMG_PAYLOAD,+ embedding_model: ATTR_PAYLOAD,+ chunk_size: IMG_PAYLOAD,+ chunk_overlap: ATTR_PAYLOAD,+ embedding_dimension: SVG_PAYLOAD,+ splitter_type: IMG_PAYLOAD,+ distance_metric: ATTR_PAYLOAD,+ index_type: SVG_PAYLOAD,+ normalize_vectors: true,+ index_file_size: IMG_PAYLOAD,+ is_public: true,+ agent_enabled: true,+ is_protected: false,+ },+ documents: [+ {+ id: SVG_PAYLOAD,+ filename: IMG_PAYLOAD,+ indexed: true,+ chunk_count: IMG_PAYLOAD,+ file_size: IMG_PAYLOAD,+ source_type: ATTR_PAYLOAD,+ in_other_collections: true,+ other_collections_count: ATTR_PAYLOAD,+ last_indexed_at: SVG_PAYLOAD,+ has_pdf: false,+ has_text_db: false,+ },+ {+ id: 'doc-benign',+ filename: 'Benign document.pdf',+ indexed: true,+ chunk_count: 4,+ file_size: 1024,+ source_type: 'pdf',+ in_other_collections: false,+ last_indexed_at: '2026-01-02T03:04:05Z',+ has_pdf: true,+ has_text_db: true,+ },+ ],+ notes: [+ {+ id: JS_URL,+ title: SVG_PAYLOAD,+ indexed: true,+ chunk_count: IMG_PAYLOAD,+ updated_at: '2026-01-02T03:04:05Z',+ pinned: true,+ },+ {+ id: 'note-benign',+ title: 'Benign note',+ indexed: true,+ chunk_count: 2,+ updated_at: '2026-01-02T03:04:05Z',+ pinned: false,+ },+ ],+ };+ const safeFetchMock = vi.fn((url) => Promise.resolve({+ ok: true,+ json: () => Promise.resolve(String(url).endsWith('/documents')+ ? payload+ : { status: 'idle' }),+ }));+ globalThis.safeFetch = safeFetchMock;+ globalThis.safeFetchWithAuth = safeFetchMock;++ await import('@js/collection_details.js');+ document.dispatchEvent(new Event('DOMContentLoaded'));+ await vi.waitFor(() => {+ expect(document.querySelectorAll('#documents-list .ldr-document-item')).toHaveLength(2);+ expect(document.querySelectorAll('#notes-list .ldr-document-item')).toHaveLength(2);+ });++ const documents = document.getElementById('documents-list');+ const notes = document.getElementById('notes-list');+ const embedding = document.getElementById('collection-embedding-info');+ expect(document.getElementById('collection-name').textContent).toBe(IMG_PAYLOAD);+ expect(document.getElementById('collection-description').textContent).toBe(SVG_PAYLOAD);+ expect(document.getElementById('stat-total-docs').textContent).toBe('4');+ expect(embedding.textContent).toContain(ATTR_PAYLOAD);+ expect(documents.textContent).toContain(IMG_PAYLOAD);+ expect(documents.textContent).toContain('Benign document.pdf');+ expect(notes.textContent).toContain(SVG_PAYLOAD);+ expect(notes.textContent).toContain('Benign note');++ const documentLinks = documents.querySelectorAll('a.ldr-document-link');+ const noteLinks = notes.querySelectorAll('a.ldr-document-link');+ expect(documentLinks[0].getAttribute('href'))+ .toBe(`/library/document/${encodeURIComponent(SVG_PAYLOAD)}`);+ expect(documentLinks[1].getAttribute('href')).toBe('/library/document/doc-benign');+ expect(noteLinks[0].getAttribute('href')).toBe(`/notes/${encodeURIComponent(JS_URL)}`);+ expect(noteLinks[1].getAttribute('href')).toBe('/notes/note-benign');+ // No `['onclick']` exemption here: an inline onclick attribute+ // anywhere under body must fail this check. (See the dedicated+ // click-driven regression below for why an exemption list on this+ // assertion is not sufficient on its own.)+ expectInert(document.body);+ expectSafeHrefs(document.body);+ });++ // FIX (defect (2) in the frontend-security-xss-hardening gate report):+ // the test above used to assert expectInert(document.body, ['onclick'])+ // -- an EXEMPTION list. Reverting renderDocuments() to the pre-fix+ // `onclick="…removeDocumentFromCollection('${escapeHtml(doc.id)}')"`+ // form still PASSES that assertion, because the exemption tells+ // expectInert to ignore onclick attributes rather than to require their+ // absence -- it was never exercising the fix. This test drops the+ // exemption (see above) and adds a click-driven regression modeled on+ // tests/js/pages/subscriptions-xss.test.js:191-208 ("blocks hostile IDs+ // from executing through card action handlers"): a hostile id whose+ // escapeHtml() output (') the HTML parser decodes back to a bare+ // quote BEFORE a reverted inline onclick string is compiled as+ // JavaScript, closing the string early and letting the injected+ // statement run on click. happy-dom actually compiles and executes+ // inline event-handler attributes (ElementEventAttributeUtility), so+ // this genuinely fails against that revert -- caught here by asserting+ // no onclick attribute exists AND that clicking the action button never+ // sets the sentinel. Against the current data-doc-action delegation,+ // the id is only ever read back via `.dataset.documentId` as a plain+ // string, never compiled as JS, so the sentinel stays unset.+ test('blocks a hostile document id from executing through the remove/delete action buttons', async () => {+ globalThis.confirm = vi.fn(() => false);+ window.confirm = globalThis.confirm;++ setFixture(`+ <button id="index-collection-btn"></button>+ <button id="reindex-collection-btn"></button>+ <button id="delete-collection-btn"></button>+ <button id="cancel-indexing-btn"></button>+ <input id="collection-is-public" type="checkbox">+ <input id="collection-agent-enabled" type="checkbox">+ <h1 id="collection-name"></h1>+ <p id="collection-description"></p>+ <span id="stat-total-docs"></span>+ <span id="stat-indexed-docs"></span>+ <span id="stat-unindexed-docs"></span>+ <span id="stat-total-chunks"></span>+ <div id="collection-embedding-info"></div>+ <div id="documents-list"></div>+ <div id="no-documents-message"></div>+ <section id="notes-section"><div id="notes-list"></div></section>+ <section id="collection-search-section" style="display:none">+ <input id="collection-search-input">+ <button id="collection-search-btn"></button>+ <div id="collection-search-results"></div>+ </section>+ <div id="indexing-progress"></div>+ <div id="progress-fill"></div>+ <div id="progress-text"></div>+ <div id="progress-log"></div>+ <div id="indexing-spinner"></div>+ `);++ const states = researchStatesStub();+ window.ResearchStates = states;+ globalThis.ResearchStates = states;+ globalThis.COLLECTION_ID = 'collection-security';+ window.COLLECTION_ID = 'collection-security';+ window.api = { getCsrfToken: () => 'csrf' };++ const hostileId = "doc-');window.__doc_action_onclick_xss=1;//";+ // Reset the sentinel before any `await` in this test (assigning to+ // it afterward trips eslint's require-atomic-updates) -- it only+ // needs a known baseline before removeBtn.click() below, which is+ // still well after this point.+ window.__doc_action_onclick_xss = 0;+ const payload = {+ success: true,+ collection: {+ name: 'benign collection',+ description: '',+ is_public: false,+ agent_enabled: false,+ is_protected: false,+ },+ documents: [+ {+ id: hostileId,+ filename: 'evil.pdf',+ indexed: false,+ chunk_count: 0,+ file_size: 10,+ source_type: 'pdf',+ in_other_collections: false,+ last_indexed_at: null,+ has_pdf: true,+ has_text_db: false,+ },+ ],+ notes: [],+ };+ const safeFetchMock = vi.fn((url) => Promise.resolve({+ ok: true,+ json: () => Promise.resolve(String(url).endsWith('/documents')+ ? payload+ : { status: 'idle' }),+ }));+ globalThis.safeFetch = safeFetchMock;+ globalThis.safeFetchWithAuth = safeFetchMock;++ await import('@js/collection_details.js');+ document.dispatchEvent(new Event('DOMContentLoaded'));+ await vi.waitFor(() => {+ expect(document.querySelectorAll('#documents-list .ldr-document-item')).toHaveLength(1);+ });++ const item = document.querySelector('#documents-list .ldr-document-item');+ expect(item.dataset.documentId).toBe(hostileId);++ const removeBtn = document.querySelector('#documents-list [data-doc-action="remove"]');+ expect(removeBtn).not.toBeNull();+ // No onclick attribute exists anywhere in the rendered list.+ expect(document.querySelectorAll('#documents-list [onclick]')).toHaveLength(0);++ removeBtn.click();++ // The reverted inline-onclick form would set this synchronously,+ // during attribute compilation, before confirm()/fetch ever run.+ expect(window.__doc_action_onclick_xss).toBe(0);+ });++ test('keeps hostile indexing failure strings in textContent beside a benign error', async () => {+ await import('@js/collection_details.js');+ setFixture('<div id="progress-log"></div><div id="progress-text"></div>');+ window.renderIndexingFailure({+ error_message: `${IMG_PAYLOAD}.`,+ result: {+ errors: [+ { title: SVG_PAYLOAD, error: ATTR_PAYLOAD },+ { title: 'Benign document', error: 'Benign disk error' },+ ],+ },+ });++ const log = document.getElementById('progress-log');+ const text = document.getElementById('progress-text');+ expect(log.querySelectorAll('.ldr-log-entry')).toHaveLength(3);+ expect(log.textContent).toContain(IMG_PAYLOAD);+ expect(log.textContent).toContain(SVG_PAYLOAD);+ expect(log.textContent).toContain(ATTR_PAYLOAD);+ expect(log.textContent).toContain('Benign document: Benign disk error');+ expect(text.textContent).toBe(IMG_PAYLOAD);+ expectInert(document.body);+ });+});diff --git a/tests/js/security/logpanel-events-xss.test.js b/tests/js/security/logpanel-events-xss.test.jsnew file mode 100644index 0000000000..88bb3036ed--- /dev/null+++ b/tests/js/security/logpanel-events-xss.test.js@@ -0,0 +1,329 @@+/**+ * Security tests for components/logpanel.js — research-log -> DOM surface.+ *+ * logpanel.js is the REAL log-panel renderer used by progress.js and+ * results.js. Its inputs are indirectly untrusted: research-progress log+ * messages originate from web-search result content and LLM output, and+ * they reach this module both live (socket.js -> window.addConsoleLog /+ * window._socketAddLogEntry, registered at logpanel.js:491/:497) and via+ * the persisted API (loadLogsForResearch -> /api/research/<id>/logs).+ * tests/js/security/socket-events-xss.test.js covered only socket.js's+ * internal fallback sink; this file covers logpanel.js's own sinks.+ *+ * Interpolation map (verified against logpanel.js source):+ * - :1228-1230 template path — .textContent sinks for timeStr /+ * badge / message (structurally inert)+ * - :1249-1253 no-template fallback — element.innerHTML with+ * escapeHtml(timeStr) / escapeHtml(badge) / escapeHtml(message)+ * - :1108 loadLogsForResearch error path — innerHTML with+ * escapeHtml(error.message)+ * - :183/:300/:783/:999 static placeholder innerHTML — constant+ * strings, no interpolation+ * - :1203-1224 / :1235-1245 dataset.logType / logId / logMessage /+ * engine writes — property assignment, not markup+ *+ * window.escapeHtml is deliberately left UNDEFINED before import so the+ * module exercises its own quote-safe fallback (logpanel.js:9-10) — the+ * weakest escaper any real page can run it with. (base.html normally+ * provides an equivalent global.)+ *+ * Non-XSS observation: logEntry.id / logEntry.time are interpolated into+ * a querySelector attribute selector at :1316. A hostile server payload+ * with embedded double quotes can throw there (selector injection /+ * DoS), but it cannot execute markup — hostile fields used in these+ * tests are therefore kept quote-free to isolate the XSS surface.+ */++let logPanel;+let emptyCounts;++beforeAll(async () => {+ // logpanel.js destructures window.LdrLogHelpers at IIFE-time.+ await import('@js/utils/log-helpers.js');+ emptyCounts = window.LdrLogHelpers.emptyCounts;++ // Stubs the IIFE expects to find on window. window.escapeHtml is+ // intentionally NOT defined — see the file header.+ window.URLBuilder = {+ researchLogs: (id, limit) =>+ `/api/research/${id}/logs${limit ? `?limit=${limit}` : ''}`,+ historyLogCount: (id) => `/api/research/${id}/log_count`,+ researchLogsExport: (id) => `/api/research/${id}/logs/export`,+ };++ Object.defineProperty(window, 'location', {+ configurable: true,+ value: { ...window.location, pathname: '/', search: '', hash: '' },+ });++ await import('@js/components/logpanel.js');+ logPanel = window.logPanel;+});++/**+ * Build the panel DOM. `withTemplate` mirrors production pages (which ship+ * #console-log-entry-template, so createLogEntryElement takes the+ * textContent path); without it the fallback innerHTML path (:1249) runs —+ * exactly the escapeHtml-dependent sink.+ */+function setupDom({ withTemplate = true } = {}) {+ const template = withTemplate+ ? `+ <template id="console-log-entry-template">+ <div class="ldr-console-log-entry">+ <span class="ldr-log-timestamp"></span>+ <span class="ldr-log-badge"></span>+ <span class="ldr-log-message"></span>+ </div>+ </template>`+ : '';+ // eslint-disable-next-line no-unsanitized/property -- test fixture: hardcoded static template with no interpolated values.+ document.body.innerHTML = `+ <div class="ldr-collapsible-log-panel">+ <div class="ldr-log-panel-header" id="log-panel-toggle">+ <i class="fas fa-chevron-right ldr-toggle-icon"></i>+ </div>+ <div class="ldr-log-panel-content collapsed" id="log-panel-content">+ <div class="ldr-console-log" id="console-log-container"></div>+ </div>+ </div>+ ${template}+ `;+}++beforeEach(() => {+ setupDom({ withTemplate: true });++ // Reset shared state between tests (mirrors logpanel.test.js).+ if (window._logPanelState) {+ window._logPanelState.queuedLogs = [];+ window._logPanelState.expanded = true; // route addLog straight to the panel+ window._logPanelState.logCount = 0;+ window._logPanelState.counts = emptyCounts();+ window._logPanelState.currentFilter = 'all';+ window._logPanelState.autoscroll = true;+ window._logPanelState.renderedIds = new Set();+ window._logPanelState.initialized = false;+ window._logPanelState.connectedResearchId = null;+ window._logPanelState.totalLogs = null;+ window._logPanelState.fetchedLogs = null;+ window._logPanelState.renderedLimit = null;+ }+});++afterEach(() => {+ delete globalThis.fetch;+});++const IMG_ONERROR = '<img src=x onerror=alert(1)>';+const QUOTE_SCRIPT = '"><script>alert(1)</script>';+const SPAN_BREAKOUT = '</span><img src=x onerror=alert(1)><span>';+const HOSTILE_TYPE = '<img/src=x/onerror=alert(1)>'; // no whitespace: classList token stays valid++/** Assert no live markup materialized under `root` (or under it). */+function expectTreeInert(root) {+ expect(root.querySelectorAll('img')).toHaveLength(0);+ expect(root.querySelectorAll('script')).toHaveLength(0);+ expect(root.querySelectorAll('[onerror]')).toHaveLength(0);+ for (const el of Array.from(root.querySelectorAll('*'))) {+ for (const attr of Array.from(el.attributes)) {+ expect(attr.name.toLowerCase().startsWith('on')).toBe(false);+ }+ }+}++/** Mock the /logs API (loadLogs fetches log_count first, then logs). */+function mockLogsResponse(entries) {+ globalThis.fetch = vi.fn(() =>+ Promise.resolve({ json: () => Promise.resolve(entries) })+ );+}++describe('logpanel inertness detector sanity', () => {+ it('is not vacuous: an unescaped payload would create a real img element', () => {+ const scratch = document.createElement('div');+ // eslint-disable-next-line no-unsanitized/property -- test-only: detached scratch node proving the detector is not vacuous.+ scratch.innerHTML = IMG_ONERROR;+ expect(scratch.querySelectorAll('img')).toHaveLength(1);+ expect(scratch.querySelectorAll('[onerror]')).toHaveLength(1);+ });+});++describe('addConsoleLog message — template path (textContent sinks :1228-1230)', () => {+ it('img/onerror message lands inert and visible as text', () => {+ logPanel.addLog(IMG_ONERROR, 'info');++ const container = document.getElementById('console-log-container');+ const entries = container.querySelectorAll('.ldr-console-log-entry');+ expect(entries).toHaveLength(1); // sink actually ran++ expectTreeInert(document.body);+ const message = entries[0].querySelector('.ldr-log-message');+ expect(message).not.toBeNull();+ expect(message.textContent).toBe(IMG_ONERROR); // payload arrived...+ expect(message.innerHTML).toContain('<img'); // ...and stored escaped+ expect(message.innerHTML).not.toMatch(/<(img|script)\b/i);+ });++ it('quote-breakout + script payload lands inert', () => {+ logPanel.addLog(QUOTE_SCRIPT, 'info');++ const container = document.getElementById('console-log-container');+ const entries = container.querySelectorAll('.ldr-console-log-entry');+ expect(entries).toHaveLength(1);++ expectTreeInert(document.body);+ const message = entries[0].querySelector('.ldr-log-message');+ expect(message.textContent).toBe(QUOTE_SCRIPT);+ expect(message.innerHTML).toContain('<script>');+ // dataset.logMessage (:1224) stores the raw payload as a data-*+ // attribute value; serialization keeps it inside the quoted value,+ // so no live script element can exist (asserted structurally).+ expect(document.querySelectorAll('script')).toHaveLength(0);+ });++ it('benign control entry renders the expected structure', () => {+ logPanel.addLog('research started', 'info');++ const entry = document.querySelector('.ldr-console-log-entry');+ expect(entry).not.toBeNull(); // non-vacuity: renderer produced output+ expect(entry.dataset.logType).toBe('info');+ expect(entry.querySelector('.ldr-log-timestamp').textContent).not.toBe('');+ expect(entry.querySelector('.ldr-log-badge').textContent).toBe('Info');+ expect(entry.querySelector('.ldr-log-message').textContent).toBe('research started');+ expectTreeInert(document.body);+ });+});++describe('hostile entry metadata — via loadLogs batch render (template path)', () => {+ it('hostile type / timestamp / metadata.engine render inert', async () => {+ // id is quote-free and hostile fields avoid double quotes so the+ // :1316 attribute-selector lookup stays parseable (see header note).+ mockLogsResponse([+ {+ id: 'xss-meta-1',+ timestamp: IMG_ONERROR, // hostile time (flows into new Date())+ message: `meta hostile ${IMG_ONERROR}`,+ log_type: HOSTILE_TYPE, // hostile severity+ metadata: {+ phase: 'engine_selected',+ engine: `${QUOTE_SCRIPT}<img src=x onerror=alert(1)>`,+ },+ },+ ]);++ await logPanel.loadLogs('xss-meta-rid');++ const container = document.getElementById('console-log-container');+ const entries = container.querySelectorAll('.ldr-console-log-entry');+ expect(entries).toHaveLength(1); // sink actually ran++ expectTreeInert(document.body);+ const entry = entries[0];+ // Hostile type: rendered as badge text, never markup.+ const badge = entry.querySelector('.ldr-log-badge');+ expect(badge.textContent).toBe(HOSTILE_TYPE);+ expect(badge.innerHTML).not.toMatch(/<(img|script)\b/i);+ // Hostile message still inert next to the hostile metadata.+ expect(entry.querySelector('.ldr-log-message').textContent)+ .toBe(`meta hostile ${IMG_ONERROR}`);+ // metadata.engine -> dataset property write (:1217): present as a+ // data-* attribute value, never as an on* handler or live element.+ expect(entry.dataset.engine).toContain('<img src=x onerror=alert(1)>');+ expect(entry.getAttribute('data-engine')).toContain(QUOTE_SCRIPT);+ // Hostile timestamp: destroyed by Date parsing (renders "Invalid+ // Date"), and the raw string never reaches markup.+ expect(entry.querySelector('.ldr-log-timestamp').textContent)+ .not.toContain('<img');+ });+});++describe('addConsoleLog message — no-template fallback (innerHTML :1249-1253)', () => {+ beforeEach(() => {+ setupDom({ withTemplate: false });+ });++ it('img/onerror message is escaped into innerHTML and visible as text', () => {+ logPanel.addLog(IMG_ONERROR, 'error');++ const entries = document.querySelectorAll('.ldr-console-log-entry');+ expect(entries).toHaveLength(1); // sink actually ran++ expectTreeInert(document.body);+ const message = entries[0].querySelector('.ldr-log-message');+ expect(message).not.toBeNull();+ expect(message.innerHTML).toContain('<img src=x onerror=alert(1)>');+ expect(message.innerHTML).not.toMatch(/<(img|script)\b/i);+ expect(message.textContent).toBe(IMG_ONERROR);+ });++ it('span-closing payload cannot break out of the message span', () => {+ logPanel.addLog(SPAN_BREAKOUT, 'info');++ const entries = document.querySelectorAll('.ldr-console-log-entry');+ expect(entries).toHaveLength(1);++ expectTreeInert(document.body);+ const entry = entries[0];+ const message = entry.querySelector('.ldr-log-message');+ expect(message.textContent).toBe(SPAN_BREAKOUT);+ // The closing tag was neutralized, so the message node still holds+ // the full payload and the entry gained no extra element children.+ expect(entry.querySelectorAll('.ldr-log-message')).toHaveLength(1);+ expect(message.innerHTML).toContain('</span>');+ });++ it('hostile type renders an escaped badge', () => {+ logPanel.addLog('fallback hostile type', HOSTILE_TYPE);++ const entries = document.querySelectorAll('.ldr-console-log-entry');+ expect(entries).toHaveLength(1);++ expectTreeInert(document.body);+ const badge = entries[0].querySelector('.ldr-log-badge');+ expect(badge).not.toBeNull();+ expect(badge.textContent).toBe(HOSTILE_TYPE);+ expect(badge.innerHTML).toContain('<img');+ expect(badge.innerHTML).not.toMatch(/<(img|script)\b/i);+ });+});++describe('loadLogsForResearch error path (:1108)', () => {+ it('hostile error.message lands escaped and inert', async () => {+ globalThis.fetch = vi.fn(() =>+ Promise.reject(new Error(IMG_ONERROR))+ );++ await logPanel.loadLogs('xss-error-rid');++ const container = document.getElementById('console-log-container');+ const err = container.querySelector('.ldr-error-message');+ expect(err).not.toBeNull(); // sink actually ran++ expectTreeInert(document.body);+ expect(err.innerHTML).toContain('<img src=x onerror=alert(1)>');+ expect(err.innerHTML).not.toMatch(/<(img|script)\b/i);+ expect(err.textContent).toBe(`Error loading logs: ${IMG_ONERROR}`);+ });++ it('quote-breakout error.message lands escaped and inert', async () => {+ globalThis.fetch = vi.fn(() =>+ Promise.reject(new Error(QUOTE_SCRIPT))+ );++ await logPanel.loadLogs('xss-error-rid-2');++ const container = document.getElementById('console-log-container');+ const err = container.querySelector('.ldr-error-message');+ expect(err).not.toBeNull();++ expectTreeInert(document.body);+ expectTreeInert(document.body);+ // innerHTML read-back re-serializes the parsed text node, so the+ // escaped " becomes a bare quote character again; assert on the+ // inert, fully tag-escaped serialization instead.+ expect(err.innerHTML).toContain('><script>');+ expect(err.innerHTML).not.toMatch(/<(img|script)\b/i);+ expect(err.textContent).toBe(`Error loading logs: ${QUOTE_SCRIPT}`);+ });+});diff --git a/tests/js/security/markdown-render-xss.test.js b/tests/js/security/markdown-render-xss.test.jsnew file mode 100644index 0000000000..52ee1fda29--- /dev/null+++ b/tests/js/security/markdown-render-xss.test.js@@ -0,0 +1,829 @@+import '@js/security/url-validator.js';+import '@js/security/xss-protection.js';+import '@js/services/ui.js';++const ui = window.ui;++beforeAll(async () => {+ // happy-dom's NodeIterator stops yielding nodes as soon as the current+ // node is removed from the tree. DOMPurify removes disallowed elements+ // WHILE iterating, so under happy-dom its traversal silently truncates+ // after the first removal and hostile markup after it survives+ // sanitization (DOMPurify's README explicitly lists happy-dom as an+ // unsupported DOM). Install a snapshot-based iterator with the spec+ // behavior DOMPurify requires — removals never truncate the traversal —+ // BEFORE importing dompurify, which captures document.createNodeIterator+ // at module-evaluation time.+ document.createNodeIterator = function(root, whatToShow) {+ const mask = whatToShow === undefined || whatToShow === null+ ? 0xffffffff+ : whatToShow;+ const nodes = [];+ (function collect(node) {+ if (mask & (1 << (node.nodeType - 1))) {+ nodes.push(node);+ }+ for (let i = 0; i < node.childNodes.length; i++) {+ collect(node.childNodes[i]);+ }+ })(root);+ let index = 0;+ return {+ nextNode() {+ return index < nodes.length ? nodes[index++] : null;+ },+ previousNode() {+ return index > 0 ? nodes[--index] : null;+ },+ };+ };++ // happy-dom's Node.prototype#nodeName base getter returns "" (the+ // correct values come from subclass getters on property access, but+ // DOMPurify caches the BASE getter at module-evaluation time and uses+ // it for every node, so every tag resolves to "" and falls into the+ // forbidden-element branch). Install a spec-correct getter before+ // dompurify captures it.+ Object.defineProperty(window.Node.prototype, 'nodeName', {+ configurable: true,+ get() {+ switch (this.nodeType) {+ case 1: return this.tagName;+ case 2: return this.name;+ case 3: return '#text';+ case 4: return '#cdata-section';+ case 7: return this.target;+ case 8: return '#comment';+ case 9: return '#document';+ case 10: return '#document-type';+ case 11: return '#document-fragment';+ default: return '';+ }+ },+ });++ // happy-dom's HTML parser never assigns foreign-content namespaces:+ // a parsed <math> subtree reports the XHTML namespace, and DOMPurify's+ // namespace-confusion defense (mXSS) removes every MathML-namespaced+ // tag found in the HTML namespace. Real browsers give parsed <math>+ // subtrees the MathML namespace. Map MathML-specific tag names onto+ // the MathML namespace so KaTeX output survives like it does in a+ // browser; SVG tag names are deliberately NOT mapped, so hostile+ // <svg> markup keeps failing the namespace check and is removed.+ const MATHML_TAG_NAMES = new Set([+ 'math', 'semantics', 'annotation', 'annotation-xml', 'maction',+ 'maligngroup', 'malignmark', 'menclose', 'merror', 'mfenced',+ 'mfrac', 'mglyph', 'mi', 'mlabeledtr', 'mlongdiv', 'mmultiscripts',+ 'mn', 'mo', 'mover', 'mpadded', 'mphantom', 'mprescripts', 'mroot',+ 'mrow', 'ms', 'mscarries', 'msgroup', 'msline', 'mspace', 'msqrt',+ 'msrow', 'mstack', 'mstyle', 'msub', 'msubsup', 'msup', 'mtable',+ 'mtd', 'mtext', 'mtr', 'munder', 'munderover', 'none',+ ]);+ const MATHML_NAMESPACE_URI = 'http://www.w3.org/1998/Math/MathML';+ const originalNamespaceURI = Object.getOwnPropertyDescriptor(+ window.Element.prototype, 'namespaceURI',+ );+ Object.defineProperty(window.Element.prototype, 'namespaceURI', {+ configurable: true,+ get() {+ if (typeof this.tagName === 'string'+ && MATHML_TAG_NAMES.has(this.tagName.toLowerCase())) {+ return MATHML_NAMESPACE_URI;+ }+ return originalNamespaceURI && originalNamespaceURI.get+ ? originalNamespaceURI.get.call(this)+ : undefined;+ },+ });++ const { Marked } = await import('marked');+ const markedKatex = (await import('marked-katex-extension')).default;+ const DOMPurify = (await import('dompurify')).default;+ const markedInstance = new Marked();++ markedInstance.use(markedKatex({+ throwOnError: false,+ errorColor: 'currentColor',+ }));+ globalThis.marked = markedInstance;+ globalThis.DOMPurify = DOMPurify;+});++afterAll(() => {+ delete globalThis.marked;+ delete globalThis.DOMPurify;+});++function renderContainer(markdown) {+ const container = document.createElement('div');+ // eslint-disable-next-line no-unsanitized/property -- test-only: renderMarkdown() sanitizes through the DOMPurify allowlist under test; parsing its output is how these tests assert on the sanitized DOM.+ container.innerHTML = ui.renderMarkdown(markdown);+ return container;+}++function eventHandlerAttributes(root) {+ return [...root.querySelectorAll('*')].flatMap((element) =>+ element.getAttributeNames()+ .filter((name) => /^on/i.test(name))+ .map((name) => `${element.tagName}[${name}]`),+ );+}++function hrefs(root) {+ return [...root.querySelectorAll('[href]')].map((element) =>+ element.getAttribute('href'),+ );+}++describe('renderMarkdown() XSS surface', () => {+ test('removes raw script, image, iframe, and SVG HTML', () => {+ // Regression: iframe/SVG nodes must not survive the sanitizer pipeline.+ const root = renderContainer([+ '<script>alert(1)</script>',+ '<img src="x" onerror="alert(1)">',+ '<iframe src="javascript:alert(1)"></iframe>',+ '<svg onload="alert(1)"><circle /></svg>',+ ].join('\n'));++ expect(root.querySelectorAll('script, iframe, svg')).toHaveLength(0);+ expect(root.querySelectorAll('img')).toHaveLength(0);+ expect(eventHandlerAttributes(root)).toEqual([]);+ });++ test('removes dangerous javascript, data, and vbscript markdown links', () => {+ // Regression: marked links must not retain dangerous URL schemes after sanitization.+ const root = renderContainer([+ '[javascript](javascript:alert(1))',+ '[data](data:text/html,<script>alert(1)</script>)',+ '[vbscript](vbscript:alert(1))',+ ].join('\n'));++ expect(hrefs(root).every((href) =>+ !/^(?:javascript|data|vbscript):/i.test(href),+ )).toBe(true);+ });++ test('does not create dangerous anchors from hostile autolinks', () => {+ // Regression: marked autolinks must not retain dangerous URL schemes after sanitization.+ const root = renderContainer([+ '<javascript:alert(1)>',+ '<data:text/html,alert(1)>',+ '<vbscript:alert(1)>',+ ].join('\n'));++ expect(hrefs(root).every((href) =>+ !/^(?:javascript|data|vbscript):/i.test(href),+ )).toBe(true);+ expect(eventHandlerAttributes(root)).toEqual([]);+ });++ it('sanitizes KaTeX-generated links and event attributes', () => {+ const root = renderContainer([+ '$\\href{javascript:alert(1)}{click}$',+ '$\\htmlClass{onmouseover=alert(1)}{text}$',+ ].join('\n'));++ expect(root.querySelectorAll('script, iframe, svg')).toHaveLength(0);+ expect(eventHandlerAttributes(root)).toEqual([]);+ expect(hrefs(root).every((href) =>+ !/^(?:javascript|data|vbscript):/i.test(href),+ )).toBe(true);+ });++ test('neutralizes entity-encoded dangerous URLs and event attributes', () => {+ // Regression: entity-encoded raw HTML must not retain an inline event handler.+ const root = renderContainer(+ '<a href="javascript:alert(1)" onmouseover="alert(1)">click</a>',+ );++ expect(eventHandlerAttributes(root)).toEqual([]);+ expect(hrefs(root).every((href) =>+ !/^(?:javascript|data|vbscript):/i.test(href),+ )).toBe(true);+ });++ it('does not preserve event attributes on benign markdown anchors', () => {+ const root = renderContainer(+ '[safe link](https://example.com "Example")',+ );+ const link = root.querySelector('a');++ expect(link).not.toBeNull();+ expect(link.getAttribute('href')).toBe('https://example.com');+ expect(link.getAttribute('target')).toBe('_blank');+ expect(link.getAttribute('rel')).toContain('noopener');+ expect(eventHandlerAttributes(root)).toEqual([]);+ });++ it('preserves benign markdown markup as a non-vacuity control', () => {+ const root = renderContainer('Intro.\n\n## Safe heading\n\n**bold** and `code`');++ expect(root.querySelector('h2')?.textContent).toBe('Safe heading');+ expect(root.querySelector('strong')?.textContent).toBe('bold');+ expect(root.querySelector('code')?.textContent).toBe('code');+ });++ it('still renders safe generated-image refs after sanitization', () => {+ const root = renderContainer('![ref:image-abc-123]');++ const wrap = root.querySelector('.ldr-generated-image');+ expect(wrap).not.toBeNull();+ expect(wrap.getAttribute('data-image-id')).toBe('image-abc-123');+ expect(wrap.parentElement.className).toBe('ldr-markdown-content');+ expect(wrap.getAttributeNames().sort()).toEqual([+ 'class', 'data-image-id',+ ]);+ const img = wrap.querySelector('img');+ expect(img).not.toBeNull();+ expect(img.getAttribute('src')).toBe('/static/img/generated/image-abc-123.png');+ expect(img.getAttributeNames().sort()).toEqual([+ 'alt', 'class', 'loading', 'src',+ ]);+ expect([...wrap.children].map((child) => child.tagName)).toEqual([+ 'IMG', 'DIV',+ ]);+ expect(eventHandlerAttributes(root)).toEqual([]);+ });++ it('never expands generated-image markers from HTML attribute values', () => {+ // Regression: a post-sanitize string replacement used to search this+ // serialized attribute text, inject generated markup into it, and+ // materialize a live IMG[onerror] on the browser's final parse. Raw+ // HTML is now escaped before sanitization, and image directives are+ // expanded only from standalone paragraph text nodes.+ const root = renderContainer(+ '<a href="https://example.test/" '+ + 'title="![ref:image-a]<img src=x onerror=alert(1)>" '+ + 'data-note="![ref:image-data]">safe</a>',+ );++ expect(root.querySelector('a')).toBeNull();+ expect(root.querySelectorAll('.ldr-generated-image, img')).toHaveLength(0);+ expect(root.textContent).toContain('![ref:image-a]');+ expect(root.textContent).toContain('![ref:image-data]');+ expect(eventHandlerAttributes(root)).toEqual([]);+ });++ it('treats generated-image refs as standalone block directives', () => {+ const root = renderContainer([+ 'before ![ref:image-inline] after',+ '',+ '`![ref:image-inline-code]`',+ '',+ '```text',+ '![ref:image-fenced-code]',+ '```',+ ].join('\n'));++ expect(root.querySelectorAll('.ldr-generated-image, img')).toHaveLength(0);+ expect(root.textContent).toContain('![ref:image-inline]');+ expect(root.textContent).toContain('![ref:image-inline-code]');+ expect(root.textContent).toContain('![ref:image-fenced-code]');+ });++ it('renders multiple standalone generated-image refs in source order', () => {+ const root = renderContainer(+ '![ref:image-one]\n\n![ref:image-two]',+ );+ const wraps = [...root.querySelectorAll('.ldr-generated-image')];++ expect(wraps.map((wrap) => wrap.dataset.imageId)).toEqual([+ 'image-one', 'image-two',+ ]);+ expect(wraps.every((wrap) =>+ wrap.parentElement.className === 'ldr-markdown-content'+ )).toBe(true);+ expect(root.querySelectorAll('.ldr-markdown-content > p')).toHaveLength(0);+ });++ it('does not re-enable user-supplied images in the final image-aware pass', () => {+ const root = renderContainer([+ '![ref:image-safe]',+ '',+ '<img src="x" onerror="alert(1)">',+ ].join('\n'));+ const images = root.querySelectorAll('img');++ expect(images).toHaveLength(1);+ expect(images[0].getAttribute('src')).toBe(+ '/static/img/generated/image-safe.png',+ );+ expect(eventHandlerAttributes(root)).toEqual([]);+ });++ // FIX (defect (3) in the frontend-security-xss-hardening gate report):+ // the changelog claims `img` was re-admitted "with a value-level src+ // policy" that "closes that gap explicitly" for data:image/svg+xml and+ // javascript: sources, but nothing here rendered a real Markdown+ // `` image before this test was added -- deleting the entire+ // `for (const img of …)` block in hardenSanitizedMarkdown() (the code+ // that calls isSafeMarkdownImageSrc) failed nothing. These four cases+ // exercise that block through the real renderMarkdown() pipeline, not+ // isSafeMarkdownImageSrc() in isolation, so they fail if the block --+ // or its call to isSafeMarkdownImageSrc -- is removed or bypassed.+ it('drops a javascript: markdown image source', () => {+ const root = renderContainer(')');++ expect(root.querySelectorAll('img')).toHaveLength(0);+ expect(eventHandlerAttributes(root)).toEqual([]);+ });++ it('drops a data:image/svg+xml markdown image source', () => {+ const root = renderContainer(+ '',+ );++ // Defence-in-depth: an <img> with an SVG data: source is+ // script-inert in browsers even if kept. The test asserts the+ // claimed control actually runs, not that a revert is exploitable.+ expect(root.querySelectorAll('img')).toHaveLength(0);+ });++ it('keeps a permitted data:image/png markdown image source', () => {+ const pngSrc = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=';+ const root = renderContainer(``);+ const images = root.querySelectorAll('img');++ expect(images).toHaveLength(1);+ expect(images[0].getAttribute('src')).toBe(pngSrc);+ });++ it('keeps a normal https: markdown image source', () => {+ const root = renderContainer('');+ const images = root.querySelectorAll('img');++ expect(images).toHaveLength(1);+ expect(images[0].getAttribute('src')).toBe('https://example.com/a.png');+ });++ // isSafeMarkdownImageSrc and URLValidator.safeAssign's data: carve-out+ // are separate policies, and the comments on both (services/ui.js and+ // security/url-validator.js) list how they differ. This table pins the+ // documented MIME and `;base64,` differences: changing how either policy+ // treats one of these rows fails here until those comments are updated+ // with it. A MIME type with no row (image/tiff, say) is not pinned, so+ // adding one to either list needs a row here too. Neither side may+ // accept SVG or a non-image type.+ it.each([+ // [data: URL, kept as a Markdown image, accepted by safeAssign on <img src>]+ ['data:image/png;base64,iVBORw0KGgo=', true, true],+ ['data:image/png,raw', true, false], // safeAssign requires ;base64,+ ['data:image/avif;base64,AAAA', false, true], // not in SAFE_DATA_MIME_TYPES+ ['data:image/x-icon;base64,AAAA', false, true], // not in SAFE_DATA_MIME_TYPES+ ['data:image/svg+xml;base64,PHN2Zy8+', false, false],+ ['data:text/html;base64,PHNjcmlwdD4=', false, false],+ ])('data: image policies stay as documented for %s', (src, markdownKeeps, safeAssignAccepts) => {+ const root = renderContainer(``);+ expect(root.querySelectorAll('img')).toHaveLength(markdownKeeps ? 1 : 0);++ const img = document.createElement('img');+ expect(window.URLValidator.safeAssign(img, 'src', src)).toBe(safeAssignAccepts);+ });++ it('leaves malformed generated-image refs as literal text', () => {+ const root = renderContainer('![ref:image-" onerror="alert(1)]');++ expect(root.querySelectorAll('img, .ldr-generated-image')).toHaveLength(0);+ expect(root.textContent).toContain('![ref:');+ });++ it('preserves GFM task-list checkboxes', () => {+ const root = renderContainer('- [x] done\n- [ ] pending');++ const boxes = root.querySelectorAll('input[type="checkbox"]');+ expect(boxes).toHaveLength(2);+ expect(boxes[0].hasAttribute('checked')).toBe(true);+ expect(boxes[0].hasAttribute('disabled')).toBe(true);+ expect(boxes[1].hasAttribute('checked')).toBe(false);+ });++ it('preserves KaTeX HTML and MathML through the allowlist', () => {+ const root = renderContainer('$x^2 + y_i$');++ expect(root.querySelector('span.katex')).not.toBeNull();+ expect(root.querySelector('span.katex-html')).not.toBeNull();+ const math = root.querySelector('math');+ expect(math).not.toBeNull();+ expect(root.querySelector('math annotation')).not.toBeNull();+ expect(math.textContent).toContain('x');+ });++ it('renders raw interactive controls as inert source text', () => {+ const root = renderContainer([+ '<input type="password" value="secret">',+ '<input type="text" value="x">',+ '<input type="submit" value="go">',+ '<input autofocus>',+ '<input type="checkbox">',+ '<button>click</button>',+ '<form action="https://evil"><input type="text"></form>',+ ].join('\n'));++ expect(root.querySelectorAll('input')).toHaveLength(0);+ expect(root.querySelectorAll('button')).toHaveLength(0);+ expect(root.querySelectorAll('form')).toHaveLength(0);+ expect(root.textContent).toContain('<input type="password"');+ expect(root.textContent).toContain('<button>click</button>');+ });++ it('renders an error report as sections and keeps model-supplied HTML literal', () => {+ // ErrorReportGenerator.generate_error_report()+ // (error_handling/report_generator.py) output for a failed research+ // with partial results. The generator used to wrap the partial+ // results in <details><summary>; this renderer escapes raw HTML, so+ // those tags showed as text. It now writes a plain Markdown section,+ // and tests/error_handling/test_report_generator.py checks that it+ // emits no raw HTML. HTML inside the model's own findings text+ // stays literal.+ const root = renderContainer([+ '# ⚠️ Research Failed',+ '',+ '**Error Type:** Unexpected Error',+ '',+ '## 💬 Get Help',+ "We're here to help you get this working:",+ '- 📖 **Documentation & guides:** [Wiki](https://github.com/LearningCircuit/local-deep-research/wiki)',+ '',+ '## 📊 Partial Results Available',+ '',+ '### Research Summary',+ '',+ 'Solar output rose in 2025, according to the sources collected before the failure.',+ '',+ '### Research Findings',+ '',+ '**Initial search:**',+ '<details><summary>Model notes</summary>hidden</details> Panels got cheaper.',+ '',+ '*Note: The above results were successfully collected before the error occurred.*',+ ].join('\n'));++ expect([...root.querySelectorAll('h1, h2, h3')].map(+ (heading) => `${heading.tagName}:${heading.textContent.trim()}`,+ )).toEqual([+ 'H1:⚠️ Research Failed',+ 'H2:💬 Get Help',+ 'H2:📊 Partial Results Available',+ 'H3:Research Summary',+ 'H3:Research Findings',+ ]);+ expect(hrefs(root)).toContain('https://github.com/LearningCircuit/local-deep-research/wiki');+ expect(root.querySelector('strong')).not.toBeNull();+ // The only tag text on the page is the model's own <details>.+ expect(root.querySelectorAll('details, summary')).toHaveLength(0);+ expect(root.textContent.split('<details>')).toHaveLength(2);+ expect(root.textContent).toContain(+ '<details><summary>Model notes</summary>hidden</details> Panels got cheaper.',+ );+ });++ it('shows a raw HTML comment, such as the report sources sentinel, as literal text', () => {+ // The report generator's appended-sources sentinel+ // (text_optimization/citation_formatter.py) is an HTML comment, and+ // this renderer escapes it like any other raw HTML. That is why the+ // server removes it (strip_appended_sources_sentinel) before a+ // report is saved, assembled for display, or used as news findings.+ const root = renderContainer(+ 'Answer.\n\n<!-- LDR_APPENDED_SOURCES_START -->\n\n## Sources',+ );++ expect(root.textContent).toContain('<!-- LDR_APPENDED_SOURCES_START -->');+ expect(root.querySelector('h2').textContent).toBe('Sources');+ });++ it('keeps only renderer-generated GFM checkboxes in a display-only state (outer layer only)', () => {+ // NOTE ON WHAT THIS DOES AND DOES NOT COVER: marked's renderer.html+ // hook (see the module header above) escapes ALL raw author-supplied+ // HTML in Markdown source to literal text BEFORE it ever reaches+ // DOMPurify or hardenSanitizedMarkdown's ALLOWED_INPUT_TYPES pass+ // (ui.js's `for (const input of ...)` block). That means+ // `rawCheckbox` below is never parsed into a real <input> element by+ // this pipeline -- it stays text, as the `root.textContent` assertion+ // shows -- so the single checkbox this test finds and inspects is+ // always the ONE marked's own GFM task-list renderer generates,+ // which marked already emits as `checked=""`/`disabled=""` with no+ // other attributes. The attribute assertions below therefore pin+ // marked's own output, not the ALLOWED_INPUT_TYPES/attribute-strip+ // defense-in-depth layer in hardenSanitizedMarkdown: deleting that+ // layer entirely would NOT fail this test, because no attacker+ // attribute-bearing <input> ever reaches it through Markdown source+ // once raw HTML is escaped upstream. That inner layer has no+ // revert-fails test of its own -- it is unreachable in the current+ // pipeline and kept only as defence-in-depth.+ const rawCheckbox = '<input type="checkbox" checked="" autofocus="autofocus" '+ + 'form="f" name="x" value="v" onfocus="alert(1)">';+ const root = renderContainer(`${rawCheckbox}\n\n- [x] generated task`);++ const boxes = root.querySelectorAll('input[type="checkbox"]');+ expect(boxes).toHaveLength(1);+ const box = boxes[0];+ expect(box.hasAttribute('checked')).toBe(true);+ expect(box.hasAttribute('disabled')).toBe(true);+ // Every other attribute — form-association, identity, value,+ // focus-grabbing, event handlers — must be stripped (or, per the+ // note above, never present in marked's own generated markup).+ for (const name of box.getAttributeNames()) {+ expect([+ 'type', 'checked', 'disabled', 'class',+ ]).toContain(name);+ }+ expect(box.hasAttribute('autofocus')).toBe(false);+ expect(box.hasAttribute('form')).toBe(false);+ expect(box.hasAttribute('name')).toBe(false);+ expect(box.hasAttribute('value')).toBe(false);+ expect(box.hasAttribute('onfocus')).toBe(false);+ expect(root.textContent).toContain(rawCheckbox);+ });++ it('escapes raw inline styles that exfiltrate via network-bearing values', () => {+ const root = renderContainer([+ '<span style="background-image: url(http://evil.example/x.png); color: red">a</span>',+ '<span style="background-image: image-set(\'https://evil.example/a.png\' 1x)">a2</span>',+ '<span style="cursor: image-set(\'https://evil.example/cursor.png\' 1x), auto">a3</span>',+ '<span style="@import url(http://evil.example/x.css);">b</span>',+ '<span style="width: expression(alert(1));">c</span>',+ '<span style="background: javascript:alert(1);">d</span>',+ '<span style="background: data:image/svg+xml,<svg/>">e</span>',+ ].join('\n'));++ expect(root.querySelectorAll('span, [style]')).toHaveLength(0);+ expect(root.textContent).toContain('evil.example');+ });++ it('escapes raw inline styles that could create full-page overlays', () => {+ const root = renderContainer([+ '<span style="position: fixed; top: 0; left: 0">a</span>',+ '<span style="position:sticky">b</span>',+ '<span style="position:absolute;inset:0;z-index:2147483647">c</span>',+ '<span style="--overlay-position:fixed;position:var(--overlay-position);inset:0">d</span>',+ '<span style="height:100vh;width:100vw;opacity:0.01">e</span>',+ '<span style="-moz-binding: url(http://evil);">f</span>',+ '<span style="behavior: url(#x);">g</span>',+ ].join('\n'));++ expect(root.querySelectorAll('span, [style]')).toHaveLength(0);+ expect(root.textContent).toContain('position: fixed');+ });++ it('escapes raw styles that hide prohibited tokens behind CSS escapes', () => {+ // The positive policy validates parsed property/value pairs, so CSS+ // escapes cannot smuggle an unapproved declaration into the output.+ const root = renderContainer([+ String.raw`<span style="background-image: u\72 l(http://evil/x.png)">a</span>`,+ String.raw`<span style="p\6f sition: fix\65 d; top: 0">b</span>`,+ String.raw`<span style="behavi\6fr: url(#x)">c</span>`,+ ].join('\n'));++ expect(root.querySelectorAll('span, [style]')).toHaveLength(0);+ expect(root.textContent).toContain('background-image');+ });++ it('escapes raw styles that split overlay declarations with CSS comments', () => {+ // Regression for the PR review finding: CSS accepts a comment between+ // a property name and its colon, while a raw-token denylist does not+ // recognize the resulting position:fixed declaration.+ const root = renderContainer([+ '<span style="position/**/:fixed;top:0;left:0">fixed overlay</span>',+ '<span style="position/* separator */:sticky;top:0">sticky overlay</span>',+ ].join('\n'));++ expect(root.querySelectorAll('span, [style]')).toHaveLength(0);+ expect(root.textContent).toContain('position/**/:fixed');+ expect(root.textContent).toContain('position/* separator */:sticky');+ });++ it('removes indirect overlay and network styles from parsed and computed output', () => {+ const root = renderContainer([+ '<span style="--p:fixed;position:var(--p);inset:0;z-index:2147483647">a</span>',+ '<span style="position:absolute;top:0;right:0;bottom:0;left:0">b</span>',+ '<span style="background-image:image-set(\'https://evil.example/pixel\' 1x)">c</span>',+ ].join('\n'));+ document.body.append(root);+ try {+ expect(root.querySelectorAll('span, [style]')).toHaveLength(0);+ expect(root.textContent).toContain('image-set');+ } finally {+ root.remove();+ }+ });++ it('drops mixed declarations instead of retaining an allowed fragment', () => {+ const root = renderContainer(+ '<span style="color:red;position:absolute;inset:0">mixed</span>',+ );++ expect(root.querySelector('span')).toBeNull();+ expect(root.textContent).toContain('<span style=');+ });++ it('escapes raw HTML before it can compose trusted classes, styles, or actions', () => {+ // Model the utility classes loaded by app.js. The test does not need+ // to import all of Bootstrap to prove that the dangerous class token+ // is gone before the rendered fragment reaches the document.+ const bootstrapUtilities = document.createElement('style');+ bootstrapUtilities.textContent = [+ '.position-fixed{position:fixed!important}',+ '.top-0{top:0!important}',+ '.start-0{left:0!important}',+ '.w-100{width:100%!important}',+ '.h-100{height:100%!important}',+ '.z-3{z-index:3!important}',+ ].join('');+ document.head.append(bootstrapUtilities);++ const root = renderContainer([+ '<a id="relative-overlay" href="https://attacker.invalid/phish">',+ ' <div style="position:relative;top:-5em;left:0;width:50em;'+ + 'height:50em;background-color:white">Session expired — sign in</div>',+ '</a>',+ '<div class="katex-display"><span class="katex"><span class="katex-html">',+ ' <a id="forged-katex-overlay" class="tag" '+ + 'href="https://attacker.invalid/phish" '+ + 'style="top:-5em;left:0;width:50em;height:50em;background-color:#0000">'+ + 'Continue</a>',+ '</span></span></div>',+ '<a href="https://example.com" '+ + 'class="katex position-fixed top-0 start-0 w-100 h-100 z-3" '+ + 'data-bs-toggle="modal" data-bs-target="#login" '+ + 'data-news-action="vote" data-vote="up">overlay</a>',+ ].join('\n'));+ document.body.append(root);+ try {+ expect(root.querySelectorAll('a, [style], [data-news-action]')).toHaveLength(0);+ expect(root.querySelector('#relative-overlay')).toBeNull();+ expect(root.querySelector('#forged-katex-overlay')).toBeNull();+ expect(root.querySelector('.katex-display')).toBeNull();+ expect(root.textContent).toContain('Session expired — sign in');+ expect(root.textContent).toContain('forged-katex-overlay');+ } finally {+ root.remove();+ bootstrapUtilities.remove();+ }+ });++ it('preserves generated fenced-code language classes', () => {+ const root = renderContainer('```javascript\nconst answer = 42;\n```');++ const code = root.querySelector('pre code');+ expect(code).not.toBeNull();+ expect(code.classList.contains('language-javascript')).toBe(true);+ });++ it('preserves benign KaTeX inline styles through the hardening pass', () => {+ // \href without trust mode renders as a KaTeX error span with+ // the configured errorColor carried via inline style. That+ // style must survive because KaTeX's visual error indicator+ // depends on it, and the existing KaTeX tests assert that the+ // katex spans are still present in the output.+ const root = renderContainer('$\\href{javascript:alert(1)}{x}$');+ const styled = [...root.querySelectorAll('[style]')];+ expect(styled.length).toBeGreaterThan(0);+ for (const el of styled) {+ for (let i = 0; i < el.style.length; i++) {+ expect([+ 'background-color', 'border-bottom-width', 'border-color',+ 'border-right-style', 'border-right-width', 'border-style',+ 'border-top-width', 'border-width', 'bottom', 'color', 'height',+ 'left', 'margin', 'margin-bottom', 'margin-left', 'margin-right',+ 'margin-top', 'min-width', 'padding-left', 'position',+ 'text-shadow', 'top', 'vertical-align', 'width',+ ]).toContain(el.style.item(i));+ }+ }+ // Spot-check: at least one KaTeX error-marker span keeps a+ // benign color style.+ const errorSpan = root.querySelector('span[style*="color"]');+ expect(errorSpan).not.toBeNull();+ });++ it('accepts the rgb()/rgba() forms a real browser serializes a KaTeX hex color into', () => {+ // KaTeX only ever AUTHORS hex colors (e.g. `style="color:#df0030"`),+ // but no real browser echoes that hex text back through+ // element.style.getPropertyValue(): the CSS <hex-color> token has no+ // reciprocal CSSOM serialization, so every current engine reads it+ // back as `rgb(r, g, b)` (or `rgba(r, g, b, a)` when translucent).+ // happy-dom does NOT perform this normalization -- reading back a+ // style it parsed from `color:#df0030` returns the literal hex text+ // -- so this suite cannot observe the bug by rendering real KaTeX+ // output under happy-dom; the rgb()/rgba() value has to be supplied+ // explicitly, as if it came from a real browser's CSSOM.+ expect(ui.isSafeKatexColor('rgb(223, 0, 48)')).toBe(true);+ expect(ui.isSafeKatexColor('rgb(223,0,48)')).toBe(true);+ expect(ui.isSafeKatexColor('rgba(223, 0, 48, 0.5)')).toBe(true);+ expect(ui.isSafeKatexColor('RGBA(223, 0, 48, 1)')).toBe(true);+ // Still hex/keyword too -- this is additive, not a replacement.+ expect(ui.isSafeKatexColor('#df0030')).toBe(true);+ expect(ui.isSafeKatexColor('currentcolor')).toBe(true);+ // Out-of-range channels, and anything not a plain numeric triple,+ // stay rejected -- no url()/var()/calc() composition, no+ // wide-gamut color()/oklch()/lab() functions, no CSS comments or+ // escapes riding along inside the parens.+ expect(ui.isSafeKatexColor('rgb(300, 0, 0)')).toBe(false);+ expect(ui.isSafeKatexColor('rgba(0, 0, 0, 2)')).toBe(false);+ expect(ui.isSafeKatexColor('rgb(1, 2, 3) url(evil)')).toBe(false);+ expect(ui.isSafeKatexColor('rgb(1, 2, var(--x))')).toBe(false);+ expect(ui.isSafeKatexColor('color(srgb 1 0 0)')).toBe(false);+ expect(ui.isSafeKatexColor('oklch(0.5 0.2 30)')).toBe(false);+ });++ it('drops only the invalid declaration from a mixed KaTeX style, not the whole style', () => {+ // Regression test for the rendering bug: getSafeKatexInlineStyle+ // used to return null (dropping EVERY declaration on the element)+ // as soon as ANY single declaration failed validation. Since a+ // real browser serializes KaTeX's `color:#df0030` as `rgb(223, 0,+ // 48)` (see the test above) and the pre-fix isSafeKatexColor+ // rejected that form, every KaTeX span carrying both a color and+ // geometry (height/vertical-align/margin/...) lost its geometry+ // too -- the math rendered with broken layout. Build that exact+ // element shape directly (style set explicitly, since happy-dom+ // would not reproduce the rgb() serialization on its own) and+ // confirm geometry now survives regardless of the color's fate.+ const el = document.createElement('span');+ el.setAttribute(+ 'style',+ 'color: rgb(223, 0, 48); height: 0.68em; vertical-align: -0.19em; '+ + 'margin-right: 0.05em; position: absolute',+ );+ // `position: absolute` is not in SAFE_KATEX_STYLE_VALIDATORS+ // (only `relative` is), so it must be the one property dropped.+ const result = ui.getSafeKatexInlineStyle(el);+ expect(result).not.toBeNull();+ expect(result).toContain('color: rgb(223, 0, 48)');+ expect(result).toContain('height: 0.68em');+ expect(result).toContain('vertical-align: -0.19em');+ expect(result).toContain('margin-right: 0.05em');+ expect(result).not.toContain('position');+ });++ // RECORDABLE fix (frontend-security-xss-hardening gate report): the+ // `border-color` shorthand SAFE_KATEX_STYLE_VALIDATORS listed is never+ // enumerated by a browser's CSSOM when parsed from an inline style+ // attribute -- it is always expanded into the four border-*-color+ // longhands. happy-dom does not perform that expansion (like the hex+ // color the test above), so this constructs the element with the+ // longhand names directly, as a real browser's CSSOM would present+ // them, and asserts getSafeKatexInlineStyle now keeps them instead of+ // silently dropping the \fcolorbox border color to currentColor.+ it('preserves the border-*-color longhands a real browser expands border-color into', () => {+ const el = document.createElement('span');+ el.setAttribute(+ 'style',+ 'border-top-color: rgb(223, 0, 48); border-right-color: rgb(223, 0, 48); '+ + 'border-bottom-color: rgb(223, 0, 48); border-left-color: rgb(223, 0, 48); '+ + 'border-left-width: 0.05em; border-style: solid',+ );+ const result = ui.getSafeKatexInlineStyle(el);+ expect(result).not.toBeNull();+ expect(result).toContain('border-top-color: rgb(223, 0, 48)');+ expect(result).toContain('border-right-color: rgb(223, 0, 48)');+ expect(result).toContain('border-bottom-color: rgb(223, 0, 48)');+ expect(result).toContain('border-left-color: rgb(223, 0, 48)');+ expect(result).toContain('border-left-width: 0.05em');+ });++ it('preserves the generated katex-error class for themed parse failures', () => {+ const root = renderContainer('$\\frac$');+ const error = root.querySelector('.katex-error');++ expect(error).not.toBeNull();+ expect(error.style.color).toBe('currentcolor');+ expect(error.textContent).toContain('\\frac');+ });++ it.each([+ ['radical', '$\\sqrt{x}$', 'path'],+ ['stretchy brace', '$\\overbrace{x+y}$', 'path'],+ ['stretchy arrow', '$\\xrightarrow{abc}$', 'path'],+ ['wide accent', '$\\widehat{xyz}$', 'path'],+ ['cancellation line', '$\\cancel{x}$', 'line'],+ ])('preserves KaTeX-generated SVG for a %s', (_label, markdown, childTag) => {+ const root = renderContainer(markdown);+ const svg = root.querySelector('span.katex svg');+ const geometry = svg?.querySelector(childTag);++ expect(svg).not.toBeNull();+ expect(geometry).not.toBeNull();+ expect(svg.getAttribute('width')).not.toBeNull();+ expect(svg.getAttribute('height')).not.toBeNull();+ if (childTag === 'path') {+ expect(geometry.getAttribute('d')).not.toBeNull();+ expect(svg.getAttribute('viewBox')).not.toBeNull();+ expect(svg.getAttribute('preserveAspectRatio')).not.toBeNull();+ } else {+ expect(geometry.getAttribute('stroke-width')).toBe('0.046em');+ }+ });++ it('preserves the metrics used by complex real KaTeX output', () => {+ const root = renderContainer(+ '$\\pmb{x}+\\frac{a}{b}+\\begin{array}{c|c}a&b\\\\c&d\\end{array}$',+ );++ expect(root.querySelector('span.katex')).not.toBeNull();+ expect(root.querySelector('[style*="height"]')).not.toBeNull();+ expect(root.querySelector('[style*="text-shadow"]')).not.toBeNull();+ expect(root.querySelector('[style*="border-right"]')).not.toBeNull();+ expect(root.querySelectorAll('[style]').length).toBeGreaterThan(5);+ });++});diff --git a/tests/js/security/messaging-storage-guards.test.js b/tests/js/security/messaging-storage-guards.test.jsnew file mode 100644index 0000000000..4b087c8ff1--- /dev/null+++ b/tests/js/security/messaging-storage-guards.test.js@@ -0,0 +1,407 @@+import { readdirSync, readFileSync } from 'node:fs';+import { relative, resolve } from 'node:path';++import { describe, expect, it, vi } from 'vitest';++const STATIC_JS_ROOT = resolve(+ __dirname,+ '../../../src/local_deep_research/web/static/js'+);+const VETTED_MESSAGING_SITES = new Set();+const MESSAGING_PATTERNS = [+ ['postMessage', /\bpostMessage\s*\(/g],+ ['message listener', /\baddEventListener\s*\(\s*['"]message['"]/g],+ ['onmessage', /\bonmessage\b/g],+];++const KNOWN_BENIGN_KEYS = new Set([+ 'active_news_research',+ 'advancedMenuOpen',+ 'expanded_news_ids',+ 'lastUsedProvider',+ 'mobileNavState',+ 'news_last_visit',+ 'news_read_ids',+ 'news_seen_ids',+ 'rerunConfig',+ 'saved_news_ids',+ 'saved_news_items',+]);+const SECRET_VALUE_SHAPES = [+ ['csrf-token', /\b(?:x[-_])?csrf[-_]?token\b/i],+ ['sk-prefix', /sk-/i],+ ['bearer-token', /Bearer\s+/i],+ ['api-key', /api[_-]?key/i],+ ['password-field', /["']?password["']?\s*[:=]/i],+ ['long-base62-token', /[a-z0-9]{41,}/i],+];++function scrubJsComments(source) {+ const scrubbed = [...source];+ let quote = null;++ for (let index = 0; index < source.length; index += 1) {+ const char = source[index];+ const next = source[index + 1];++ if (quote !== null) {+ if (char === '\\') {+ index += 1;+ } else if (char === quote) {+ quote = null;+ }+ continue;+ }+ if (char === "'" || char === '"' || char === '`') {+ quote = char;+ continue;+ }+ if (char === '/' && next === '/') {+ while (index < source.length && !['\n', '\r'].includes(source[index])) {+ scrubbed[index] = ' ';+ index += 1;+ }+ index -= 1;+ } else if (char === '/' && next === '*') {+ while (index < source.length) {+ if (!['\n', '\r'].includes(source[index])) scrubbed[index] = ' ';+ if (source[index] === '*' && source[index + 1] === '/') {+ scrubbed[index + 1] = ' ';+ index += 1;+ break;+ }+ index += 1;+ }+ }+ }+ return scrubbed.join('');+}++function scanMessagingSource(source, file = 'synthetic.js') {+ const scrubbed = scrubJsComments(source);+ return MESSAGING_PATTERNS.flatMap(([kind, pattern]) =>+ [...scrubbed.matchAll(pattern)].map(match => ({+ file,+ line: scrubbed.slice(0, match.index).split('\n').length,+ kind,+ }))+ );+}++function listJsFiles(directory) {+ return readdirSync(directory, { withFileTypes: true }).flatMap(entry => {+ const path = resolve(directory, entry.name);+ if (entry.isDirectory()) return listJsFiles(path);+ return entry.isFile() && entry.name.endsWith('.js') ? [path] : [];+ });+}++function isKnownBenignKey(key) {+ return KNOWN_BENIGN_KEYS.has(key) || key.startsWith('ldr_panel_collapsed_');+}++function storageViolations(writes) {+ return writes.flatMap(({ area, key: rawKey, value: rawValue }) => {+ const key = String(rawKey);+ const value = String(rawValue);+ const normalizedKey = key.toLowerCase().replace(/[^a-z0-9]/g, '');+ const shapes = [];++ if (['token', 'secret', 'password', 'apikey'].some(part => normalizedKey.includes(part))) {+ shapes.push('secret-bearing-key');+ }+ if (!isKnownBenignKey(key)) shapes.push('unapproved-key');+ for (const [shape, pattern] of SECRET_VALUE_SHAPES) {+ if (pattern.test(value)) shapes.push(shape);+ }+ return shapes.map(shape => ({ area, key, shape }));+ });+}++function formatStorageViolations(violations) {+ return violations+ .map(({ area, key, shape }) => ` ${area}:${key} -> value shape: ${shape}`)+ .join('\n');+}++function installFlowDom() {+ document.body.innerHTML = `+ <div class="ldr-page-header"></div>+ <input id="subscription-search"><select id="status-filter"></select>+ <select id="frequency-filter"></select><button id="add-folder-btn"></button>+ <button id="create-subscription-btn"></button><div id="subscriptions-grid"></div>+ <span id="total-subscriptions"></span><span id="active-subscriptions"></span>+ <span id="paused-subscriptions"></span><span id="updates-today"></span>+ <span id="status-indicator"></span><span id="status-text"></span>+ <div id="scheduler-details"></div>+ <nav class="ldr-folder-list">+ <div class="ldr-folder-item" data-folder="all"><span class="ldr-folder-count"></span></div>+ <div class="ldr-folder-item" data-folder="uncategorized"><span class="ldr-folder-count"></span></div>+ </nav>++ <div class="ldr-feed-header"><h2></h2></div><div id="news-feed-content"></div>+ <input id="table-view-toggle" type="checkbox"><tbody id="news-table-body"></tbody>+ <input id="news-search"><button id="search-btn"></button><button id="run-template-btn"></button>+ <input id="impact-filter" type="range" value="0"><span class="ldr-impact-value"></span>+ <div id="sidebar-subscriptions-list"></div><div id="news-semantic-results"></div>+ <div id="news-query"></div><div id="newsSubscriptionModal"></div>+ <input id="news-subscription-query"><div class="ldr-time-filter-group"></div>+ <input id="auto-refresh" type="checkbox"><button id="refresh-feed-btn"></button>+ <div id="recent-searches"></div><div id="trending-topics"></div>+ <div id="priority-status"><span id="priority-message"></span></div>++ <form id="research-form">+ <div id="research-alert"></div><div id="research-error-alert"></div>+ <textarea id="query"></textarea>+ <div class="ldr-privacy-panel" data-scope="adaptive">+ <i id="ldr-privacy-panel-icon"></i>+ <select id="policy_egress_scope"><option value="adaptive">Adaptive</option></select>+ <input id="llm_require_local_endpoint" type="checkbox">+ <input id="embeddings_require_local" type="checkbox">+ </div>+ <label class="ldr-mode-option"><input name="research_mode" value="quick" type="radio" checked></label>+ <button class="ldr-advanced-options-toggle ldr-open" type="button" aria-expanded="true"></button>+ <div class="ldr-advanced-options-panel ldr-expanded" id="advanced-options-panel">+ <select id="model_provider"><option value="OLLAMA">Ollama</option></select>+ <div id="model-dropdown"><input id="model"><div id="model-dropdown-list"></div></div>+ <input id="model_hidden" type="hidden"><button id="model-refresh" type="button"></button>+ <div id="search-engine-dropdown"><input id="search_engine"><div id="search-engine-dropdown-list"></div></div>+ <input id="search_engine_hidden" type="hidden" value="searxng">+ <button id="search_engine-refresh" type="button"></button>+ <select id="strategy"><option value="source-based">Source based</option></select>+ <input id="iterations" value="2"><input id="questions_per_iteration" value="3">+ </div>+ <button id="start-research-btn" type="submit"><span>Start</span></button>+ </form>++ <form id="settings-form">+ <input id="settings-search"><button class="ldr-settings-tab active" data-tab="all" type="button">All</button>+ <div id="settings-alert"></div><div id="settings-content"></div>+ </form>+ `;+}++function jsonResponse(body) {+ return Promise.resolve({+ ok: true,+ status: 200,+ statusText: 'OK',+ json: () => Promise.resolve(body),+ text: () => Promise.resolve(JSON.stringify(body)),+ });+}++describe('WSTG-CLNT-11 Web Messaging lock', () => {+ it('finds no unvetted messaging sites in source JavaScript', () => {+ const findings = listJsFiles(STATIC_JS_ROOT).flatMap(path => {+ const file = relative(STATIC_JS_ROOT, path);+ return scanMessagingSource(readFileSync(path, 'utf8'), file);+ });+ const unvetted = findings.filter(({ file, line }) =>+ !VETTED_MESSAGING_SITES.has(`${file}:${line}`)+ );+ const report = unvetted.map(({ file, line, kind }) => ` ${file}:${line} -> ${kind}`).join('\n');++ expect(unvetted, `New Web Messaging sites require origin-check review:\n${report}`).toEqual([]);+ });++ it('detects synthetic messaging APIs while ignoring comments and clean code', () => {+ const active = scanMessagingSource([+ "window.addEventListener('message', receiveMessage);",+ "window.postMessage('payload', 'https://example.test');",+ 'worker.onmessage = receiveMessage;',+ ].join('\n'));+ const clean = scanMessagingSource(`+ // window.postMessage('commented', '*');+ /* window.addEventListener("message", commentedHandler);+ worker.onmessage = commentedHandler; */+ const eventName = 'storage';+ `);++ expect(active.map(({ kind }) => kind)).toEqual([+ 'postMessage',+ 'message listener',+ 'onmessage',+ ]);+ expect(clean).toEqual([]);+ });+});++describe('WSTG-CLNT-12 Browser Storage secret-leak guard', () => {+ it('rejects synthetic forbidden keys and every protected value shape', () => {+ const violations = storageViolations([+ { area: 'localStorage', key: 'access_token', value: 'ordinary' },+ { area: 'localStorage', key: 'news_seen_ids', value: 'csrf_token=abcdefgh' },+ { area: 'localStorage', key: 'saved_news_ids', value: 'sk-example' },+ { area: 'sessionStorage', key: 'rerunConfig', value: 'Bearer credential' },+ { area: 'localStorage', key: 'saved_news_items', value: 'api_key=example' },+ { area: 'localStorage', key: 'active_news_research', value: '{"password":"example"}' },+ { area: 'localStorage', key: 'news_read_ids', value: 'Ab3'.repeat(14) },+ ]);+ const benign = storageViolations([+ { area: 'localStorage', key: 'news_seen_ids', value: '["news-1"]' },+ { area: 'localStorage', key: 'ldr_panel_collapsed_help', value: 'true' },+ { area: 'sessionStorage', key: 'rerunConfig', value: '{"query":"safe"}' },+ ]);++ expect(violations.map(({ shape }) => shape)).toEqual(expect.arrayContaining([+ 'secret-bearing-key',+ 'unapproved-key',+ 'csrf-token',+ 'sk-prefix',+ 'bearer-token',+ 'api-key',+ 'password-field',+ 'long-base62-token',+ ]));+ expect(benign).toEqual([]);+ });++ it('allows only non-secret writes while real subscription, news, research, and settings flows run', async () => {+ localStorage.clear();+ sessionStorage.clear();+ installFlowDom();++ const storageSetItem = vi.spyOn(window.Storage.prototype, 'setItem');+ const localSetItem = vi.spyOn(localStorage, 'setItem');+ const sessionSetItem = vi.spyOn(sessionStorage, 'setItem');+ const subscription = {+ id: 'subscription-1',+ name: 'Benign subscription',+ query: 'benign query',+ is_active: true,+ refresh_minutes: 60,+ total_runs: 1,+ folder_id: null,+ };+ const settingsPayload = {+ status: 'success',+ settings: {+ 'app.guard_setting': {+ key: 'app.guard_setting',+ name: 'Guard Setting',+ description: 'Benign settings-load control',+ value: 'enabled',+ ui_element: 'text',+ editable: true,+ visible: true,+ category: 'app_parameters',+ },+ },+ };+ const fetchMock = vi.fn((url, options = {}) => {+ const requestUrl = String(url);+ if (requestUrl === '/news/api/subscriptions/current') {+ return jsonResponse({ subscriptions: [subscription] });+ }+ if (requestUrl === '/news/api/subscription/folders') return jsonResponse([]);+ if (requestUrl === '/news/api/scheduler/status') {+ return jsonResponse({ scheduler_available: false });+ }+ if (requestUrl.startsWith('/news/api/feed?')) return jsonResponse({ news_items: [] });+ if (requestUrl === '/history/api') return jsonResponse({ items: [] });+ if (requestUrl === '/library/api/research-history/collection') {+ return jsonResponse({ success: false });+ }+ if (requestUrl.startsWith('/settings/api/available-models')) {+ return jsonResponse({ providers: {}, provider_options: [], models: [] });+ }+ if (requestUrl.startsWith('/settings/api/available-search-engines')) {+ return jsonResponse({ engine_options: [], engines: [] });+ }+ if (requestUrl === '/settings/api') return jsonResponse(settingsPayload);+ if (requestUrl === '/news/api/subscriptions/subscription-1' &&+ ['PUT', 'DELETE'].includes(options.method)) {+ return jsonResponse({ success: true });+ }+ return Promise.reject(new Error(`Unexpected fetch: ${requestUrl}`));+ });++ vi.stubGlobal('fetch', fetchMock);+ vi.stubGlobal('confirm', vi.fn(() => true));+ vi.stubGlobal('bootstrap', { Modal: vi.fn() });+ window.RESEARCH_STATUS = { QUEUED: 'queued', IN_PROGRESS: 'in_progress' };+ window.RESEARCH_TERMINAL_STATES = new Set(['completed', 'failed', 'cancelled']);+ window.ui = { showAlert: vi.fn() };+ window.DOMPurify = {+ addHook: vi.fn(),+ sanitize: html => {+ const template = document.createElement('template');+ // eslint-disable-next-line no-unsanitized/property -- fixed benign API fixtures pass through this test-only DOMPurify stand-in.+ template.innerHTML = html;+ return template.content;+ },+ };++ try {+ await import('@js/config/constants.js');+ await import('@js/config/urls.js');+ await import('@js/utils/alert-helpers.js');+ await import('@js/security/xss-protection.js');+ await import('@js/utils/form-validation.js');+ await import('@js/components/custom_dropdown.js');+ await import('@js/utils/provider-options.js');+ await import('@js/utils/value-helpers.js');+ await import('@js/services/api.js');+ Object.assign(window.api, {+ fetchWithErrorHandling: vi.fn(() => Promise.resolve(settingsPayload)),+ getCsrfToken: () => 'test-csrf',+ });++ await import('@js/pages/subscriptions.js');+ await import('@js/pages/news.js');+ await import('@js/components/research.js');+ await import('@js/components/settings.js');+ document.dispatchEvent(new Event('DOMContentLoaded'));++ await vi.waitFor(() => {+ expect(document.querySelectorAll('.ldr-subscription-card')).toHaveLength(1);+ expect(document.getElementById('settings-content').textContent).toContain('Guard Setting');+ expect(fetchMock.mock.calls.some(([url]) => String(url).startsWith('/news/api/feed?'))).toBe(true);+ expect(fetchMock.mock.calls.some(([url]) => url === '/history/api')).toBe(true);+ });++ document.querySelector('#subscriptions-grid [data-subscription-action="toggle"]').click();+ await vi.waitFor(() => expect(fetchMock.mock.calls.some(([url, options]) =>+ url === '/news/api/subscriptions/subscription-1' && options.method === 'PUT'+ )).toBe(true));+ document.querySelector('#subscriptions-grid [data-subscription-action="delete"]').click();+ await vi.waitFor(() => expect(fetchMock.mock.calls.some(([url, options]) =>+ url === '/news/api/subscriptions/subscription-1' && options.method === 'DELETE'+ )).toBe(true));++ document.querySelector('.ldr-advanced-options-toggle').click();+ window.dispatchEvent(new Event('beforeunload'));+ await new Promise(resolvePromise => setTimeout(resolvePromise, 350));++ const writes = [+ ...localSetItem.mock.calls.map(([key, value]) => ({ area: 'localStorage', key, value })),+ ...sessionSetItem.mock.calls.map(([key, value]) => ({ area: 'sessionStorage', key, value })),+ ];+ const violations = storageViolations(writes);+ const observedKeys = writes.map(({ key }) => String(key));++ expect(storageSetItem).toHaveBeenCalled();+ expect(observedKeys).toEqual(expect.arrayContaining([+ 'advancedMenuOpen',+ 'news_last_visit',+ 'news_read_ids',+ 'news_seen_ids',+ ]));+ expect(+ violations,+ `Browser storage secret leak(s):\n${formatStorageViolations(violations)}`+ ).toEqual([]);+ } finally {+ window.dispatchEvent(new Event('pagehide'));+ sessionSetItem.mockRestore();+ localSetItem.mockRestore();+ storageSetItem.mockRestore();+ vi.unstubAllGlobals();+ delete window.DOMPurify;+ delete window.RESEARCH_STATUS;+ delete window.RESEARCH_TERMINAL_STATES;+ document.body.replaceChildren();+ }+ });+});diff --git a/tests/js/security/misc-surface-xss.test.js b/tests/js/security/misc-surface-xss.test.jsnew file mode 100644index 0000000000..9fddc04399--- /dev/null+++ b/tests/js/security/misc-surface-xss.test.js@@ -0,0 +1,368 @@+/**+ * Output-encoding regression coverage for small, otherwise isolated render+ * surfaces. Every production module below is reachable from a page template:+ * fallback/ui.js (results.html), embedding_settings.js (embedding_settings.html),+ * confirmation_modal.js (library.html and collection_details.html),+ * mobile-navigation.js and services/theme.js (base.html), and services/pdf.js+ * (results.html).+ *+ * Interpolation map (file:line -> value -> status):+ * - components/fallback/ui.js:36 -> escapedMessage -> escaped by its local+ * escapeHtmlFallback/window.escapeHtml; :74, :121 -> escapedMessage -> escaped.+ * This fallback has no DOMPurify configuration: unlike services/ui.js, it uses+ * a self-contained five-character HTML escaper before its three HTML sinks.+ * - embedding_settings.js:205,209,213,217,221,225,229 -> saved setting fields ->+ * escapeHtml (numeric fields are String-coerced first); :645 -> provider label+ * -> escapeHtml; :796-797,826,831 -> numeric counts / escaped provider label;+ * :896-900,909,920,941,964,987 -> escaped values. Other innerHTML writes are+ * static templates or clearing assignments.+ * - deletion/confirmation_modal.js:142 -> details item -> escapeHtml.+ * - mobile-navigation.js:122-133 -> fixed tab/URLS constants; :150-229 -> fixed+ * URLS constants plus getUsername(), which strips non [\\w\\[email protected]] characters.+ * - services/theme.js:281 -> metadata icon (raw class interpolation); theme names+ * and labels themselves use DOM APIs/textContent at :204-211 and setAttribute+ * at :286-287. This suite locks the server-provided theme-name display path.+ * - services/pdf.js -> ui.renderMarkdown output (escaped raw HTML + sanitizeStable+ * under the restrictive allowlist); the remaining writes are static CSS/detached+ * text extraction/static loading markup respectively.+ */+import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';++const IMG_PAYLOAD = '<img src=x onerror=alert(1)>';+const SVG_PAYLOAD = '"><svg onload=alert(1)>';+const ATTRIBUTE_PAYLOAD = 'x" onmouseover="alert(1)';+const JAVASCRIPT_PAYLOAD = 'javascript:alert(1)';+let productionEscapeHtml;+let productionDOMPurify;++// Sync helper: assigning globalThis/window properties in a non-async scope+// keeps eslint's require-atomic-updates aliasing analysis out of the way.+function installDOMPurifyGlobal(instance) {+ globalThis.DOMPurify = instance;+ window.DOMPurify = instance;+}++function expectInert(root) {+ expect(root).not.toBeNull();+ expect(root.querySelectorAll('script, img, svg, iframe, object, embed').length).toBe(0);+ for (const element of root.querySelectorAll('*')) {+ expect(element.getAttributeNames().some(name => /^on/i.test(name))).toBe(false);+ }+ for (const anchor of root.querySelectorAll('[href]')) {+ expect(anchor.getAttribute('href')).not.toMatch(/^javascript:/i);+ }+}++function response(payload) {+ return { ok: true, json: async () => payload };+}++function resetBody() {+ document.head.replaceChildren();+ document.body.replaceChildren();+}++beforeAll(async () => {+ // happy-dom's NodeIterator stops yielding nodes as soon as the current+ // node is removed, and its Node.prototype#nodeName base getter returns+ // "" for every node. DOMPurify (which lists happy-dom as unsupported)+ // captures both at module-evaluation time: without repair its traversal+ // silently truncates after the first removal and every tag name+ // mis-resolves, so event handlers and javascript: URLs sail through+ // sanitize(). Install the same spec-correct shims as+ // tests/js/security/markdown-render-xss.test.js BEFORE the first+ // dompurify import so every suite below exercises real sanitizer+ // behavior instead of a broken harness path.+ document.createNodeIterator = function(root, whatToShow) {+ const mask = whatToShow === undefined || whatToShow === null+ ? 0xffffffff+ : whatToShow;+ const nodes = [];+ (function collect(node) {+ if (mask & (1 << (node.nodeType - 1))) {+ nodes.push(node);+ }+ for (let i = 0; i < node.childNodes.length; i++) {+ collect(node.childNodes[i]);+ }+ })(root);+ let index = 0;+ return {+ nextNode() {+ return index < nodes.length ? nodes[index++] : null;+ },+ previousNode() {+ return index > 0 ? nodes[--index] : null;+ },+ };+ };+ Object.defineProperty(window.Node.prototype, 'nodeName', {+ configurable: true,+ get() {+ switch (this.nodeType) {+ case 1: return this.tagName;+ case 2: return this.name;+ case 3: return '#text';+ case 4: return '#cdata-section';+ case 7: return this.target;+ case 8: return '#comment';+ case 9: return '#document';+ case 10: return '#document-type';+ case 11: return '#document-fragment';+ default: return '';+ }+ },+ });++ const DOMPurify = (await import('dompurify')).default;+ installDOMPurifyGlobal(DOMPurify);+ productionDOMPurify = DOMPurify;+ await import('@js/security/xss-protection.js');+ productionEscapeHtml = window.escapeHtml;+});++afterEach(() => {+ vi.restoreAllMocks();+ vi.unstubAllGlobals();+ window.escapeHtml = productionEscapeHtml;+ resetBody();+ delete window.ui;+ delete window.DeleteConfirmation;+ delete window.MobileNavigation;+ delete window.mobileNav;+ delete window.themeService;+ delete window.LDR_THEME_METADATA;+ delete window.URLS;+ delete window.URLValidator;+ delete window.pdfService;+});++describe('components/fallback/ui.js output encoding', () => {+ beforeEach(async () => {+ vi.resetModules();+ delete window.ui;+ await import('@js/components/fallback/ui.js');+ });++ it('uses its own local escaper to render spinner, error, and success messages as text', () => {+ window.escapeHtml = undefined;+ const notifications = document.createElement('div');+ notifications.className = 'ldr-notifications-container';+ const spinnerTarget = document.createElement('div');+ document.body.append(notifications, spinnerTarget);++ window.ui.showSpinner(spinnerTarget, IMG_PAYLOAD);+ window.ui.showError(SVG_PAYLOAD);+ window.ui.showMessage(ATTRIBUTE_PAYLOAD);++ expect(spinnerTarget.querySelector('.spinner-message').textContent).toBe(IMG_PAYLOAD);+ expect(notifications.querySelectorAll('.ldr-notification')).toHaveLength(2);+ expect(notifications.textContent).toContain(SVG_PAYLOAD);+ expect(notifications.textContent).toContain(ATTRIBUTE_PAYLOAD);+ expectInert(document.body);+ });++ it('renders a benign fallback message (non-vacuity)', () => {+ const notifications = document.createElement('div');+ notifications.className = 'ldr-notifications-container';+ document.body.appendChild(notifications);++ window.ui.showMessage('Saved successfully');++ expect(notifications.querySelector('.ldr-notification').textContent).toContain('Saved successfully');+ });+});++describe('embedding_settings.js output encoding', () => {+ function buildDom() {+ document.body.innerHTML = `+ <select id="embedding-provider"></select><select id="embedding-model"></select>+ <input id="chunk-size"><input id="chunk-overlap"><select id="splitter-type"></select>+ <select id="distance-metric"></select><select id="index-type"></select>+ <input id="normalize-vectors" type="checkbox"><textarea id="text-separators"></textarea>+ <input id="ollama-url"><input id="ollama-num-ctx"><input id="openai-embedding-batch-size">+ <div id="openai-embedding-batch-size-error"></div><div id="openai-embedding-batch-size-group"></div>+ <div id="ollama-url-group"></div><div id="ollama-num-ctx-group"></div>+ <div id="saved-default-settings"></div><div id="provider-info"></div>+ <span id="model-description"></span><button id="test-config-btn"></button><div id="test-result"></div>+ <div class="ldr-library-container"></div>`;+ }++ it('escapes server-provided saved defaults and provider labels through the real load path', async () => {+ vi.resetModules();+ buildDom();+ globalThis.safeFetchWithAuth = vi.fn((url) => {+ if (url === '/library/api/rag/models') {+ return Promise.resolve(response({+ success: true,+ provider_options: [{ value: 'hostile', label: IMG_PAYLOAD, available: true }],+ providers: { hostile: [{ value: SVG_PAYLOAD, label: ATTRIBUTE_PAYLOAD, is_embedding: true }] },+ }));+ }+ if (url === '/library/api/rag/settings') {+ return Promise.resolve(response({+ success: true,+ settings: {+ embedding_provider: 'hostile', embedding_model: SVG_PAYLOAD,+ chunk_size: ATTRIBUTE_PAYLOAD, chunk_overlap: IMG_PAYLOAD,+ splitter_type: SVG_PAYLOAD, distance_metric: ATTRIBUTE_PAYLOAD,+ index_type: IMG_PAYLOAD,+ },+ }));+ }+ return Promise.resolve(response({ value: null }));+ });+ window.api = { getCsrfToken: () => '' };++ await import('@js/embedding_settings.js');+ document.dispatchEvent(new Event('DOMContentLoaded'));+ await new Promise(resolve => setTimeout(resolve, 0));+ await new Promise(resolve => setTimeout(resolve, 0));++ const defaults = document.getElementById('saved-default-settings');+ const providerInfo = document.getElementById('provider-info');+ expect(defaults.textContent).toContain(SVG_PAYLOAD);+ expect(defaults.textContent).toContain(ATTRIBUTE_PAYLOAD);+ expect(defaults.textContent).toContain(IMG_PAYLOAD);+ expect(providerInfo.textContent).toContain(IMG_PAYLOAD);+ expect(providerInfo.querySelector('.ldr-stat-card')).not.toBeNull();+ expectInert(defaults);+ expectInert(providerInfo);+ });+});++describe('deletion/confirmation_modal.js output encoding', () => {+ beforeEach(async () => {+ vi.resetModules();+ document.body.innerHTML = `+ <div id="deleteConfirmModal"><h2 id="deleteModalTitle"></h2><p id="deleteModalMessage"></p>+ <div id="deleteModalDetails"><ul id="deleteDetailsList"></ul></div>+ <div id="deleteModalWarning"><span id="deleteWarningText"></span></div>+ <button id="deleteConfirmBtn"><span id="deleteConfirmBtnText"></span></button></div>`;+ globalThis.bootstrap = { Modal: class { show() {} static getInstance() { return { hide() {} }; } } };+ await import('@js/deletion/confirmation_modal.js');+ });++ it('renders hostile confirmation details as literal list text', () => {+ window.DeleteConfirmation.show({+ action: 'deleteDocument', details: [IMG_PAYLOAD, SVG_PAYLOAD, ATTRIBUTE_PAYLOAD],+ });++ const modal = document.getElementById('deleteConfirmModal');+ expect(modal.querySelectorAll('#deleteDetailsList li')).toHaveLength(3);+ expect(modal.textContent).toContain(IMG_PAYLOAD);+ expect(modal.textContent).toContain(SVG_PAYLOAD);+ expect(modal.textContent).toContain(ATTRIBUTE_PAYLOAD);+ expectInert(modal);+ });++ it('renders benign confirmation details (non-vacuity)', () => {+ window.DeleteConfirmation.show({ action: 'deleteDocument', details: ['Quarterly report'] });+ expect(document.querySelector('#deleteDetailsList li').textContent).toBe('Quarterly report');+ });+});++describe('mobile-navigation.js output encoding', () => {+ beforeEach(async () => {+ vi.resetModules();+ window.URLS = { PAGES: {+ HOME: '/', HISTORY: '/history', LIBRARY: '/library', NEWS: '/news', NEWS_SUBSCRIPTIONS: '/news/subscriptions',+ COLLECTIONS: '/collections', METRICS: '/metrics', BENCHMARK: '/benchmark', BENCHMARK_RESULTS: '/benchmark-results',+ EMBEDDING_SETTINGS: '/embedding-settings', SETTINGS: '/settings',+ } };+ window.URLValidator = { safeAssign: vi.fn() };+ Object.defineProperty(window, 'innerWidth', { configurable: true, value: 1024 });+ await import('@js/mobile-navigation.js');+ });++ it('keeps special characters from the displayed username inert in the sheet menu', () => {+ const payload = `User ${SVG_PAYLOAD}`;+ const userInfo = document.createElement('div');+ userInfo.className = 'ldr-user-info';+ userInfo.textContent = payload;+ document.body.appendChild(userInfo);+ const nav = new window.MobileNavigation({ persistState: false });+ nav.createSheetMenu();++ const sheet = nav.elements.sheet;+ const usernameLabel = [...sheet.querySelectorAll('.ldr-mobile-sheet-label')]+ .find(label => label.textContent.includes('User'));+ expect(usernameLabel.textContent).toBe('User svg onloadalert1');+ expectInert(sheet);+ });+});++describe('services/theme.js output encoding', () => {+ it('renders server-provided special-character theme names as option text, not markup', async () => {+ vi.resetModules();+ const hostileName = `Theme ${IMG_PAYLOAD}`;+ window.LDR_THEME_METADATA = {+ hostile: { label: hostileName, icon: 'fa-palette', group: 'core' },+ system: { label: 'System', icon: 'fa-desktop', group: 'system' },+ };+ globalThis.fetch = vi.fn(() => Promise.resolve({ ok: false, status: 404 }));+ window.api = { getCsrfToken: () => '' };+ await import('@js/services/theme.js');++ const select = document.createElement('select');+ window.themeService.populateThemeDropdown(select);++ const hostileOption = [...select.options].find(option => option.value === 'hostile');+ expect(hostileOption).toBeDefined();+ expect(hostileOption.textContent).toBe(hostileName);+ expectInert(select);+ expect(select.options.length).toBe(2);+ });+});++describe('services/pdf.js DOM-facing output', () => {+ // pdf.js renders the report body through ui.renderMarkdown -- the same+ // hardened pipeline as the on-screen report view: raw author HTML is+ // escaped at marked's renderer.html hook, then sanitizeStable() applies+ // the restrictive allowlist. (It previously ran marked output through+ // DOMPurify's default profile, which kept defanged <img>/<svg>; see+ // tests/js/services/pdf-sanitization.test.js for the screen/PDF parity+ // checks.) Hostile markup must therefore be inert AND absent: the+ // payloads below reach the preview DOM only as literal text.+ it('sanitizes hostile markdown before it reaches the temporary preview DOM', async () => {+ vi.resetModules();+ const previewContainers = [];+ const appendChild = document.body.appendChild.bind(document.body);+ vi.spyOn(document.body, 'appendChild').mockImplementation((node) => {+ if (node.classList?.contains('ldr-pdf-content')) previewContainers.push(node);+ return appendChild(node);+ });+ const { Marked } = await import('marked');+ globalThis.marked = new Marked();+ globalThis.DOMPurify = productionDOMPurify;+ window.DOMPurify = productionDOMPurify;+ await import('@js/security/url-validator.js');+ await import('@js/security/xss-protection.js');+ await import('@js/services/ui.js');+ const pdf = {+ internal: { pageSize: { getWidth: () => 612, getHeight: () => 792 } }, output: () => new Blob(),+ setFontSize() {}, setTextColor() {}, text() {}, splitTextToSize: text => [text], setFont() {},+ setFillColor() {}, rect() {}, addPage() {}, setDrawColor() {}, setLineWidth() {}, line() {},+ };+ globalThis.jsPDF = class { constructor() { return pdf; } };+ globalThis.html2canvas = vi.fn();+ await import('@js/services/pdf.js');++ const markdown = `${IMG_PAYLOAD}${SVG_PAYLOAD}\n\n[bad](${JAVASCRIPT_PAYLOAD})`;+ await window.pdfService.generatePdf('Report', markdown);++ expect(previewContainers).toHaveLength(1);+ const preview = previewContainers[0].querySelector('#pdf-body-content');+ expect(preview.textContent).toContain('bad');+ // Raw HTML is escaped, so none of it may exist as an element.+ expect(preview.querySelectorAll('script, img, svg, iframe, object, embed')).toHaveLength(0);+ for (const element of preview.querySelectorAll('*')) {+ expect(element.getAttributeNames().some(name => /^on/i.test(name))).toBe(false);+ }+ for (const anchor of preview.querySelectorAll('[href]')) {+ expect(anchor.getAttribute('href')).not.toMatch(/^javascript:/i);+ }+ // ...and it is visible as text, exactly as on the screen path.+ expect(preview.textContent).toContain('<img src=x onerror=alert(1)>');+ });+});diff --git a/tests/js/security/mxss-reparse-invariant.test.js b/tests/js/security/mxss-reparse-invariant.test.jsnew file mode 100644index 0000000000..5584cf8708--- /dev/null+++ b/tests/js/security/mxss-reparse-invariant.test.js@@ -0,0 +1,291 @@+/**+ * mXSS reparse invariant coverage for every sanitizer that returns markup for+ * an innerHTML sink. The contract is sanitize -> parse -> serialize -> reparse:+ * reparsing must not create executable nodes, attributes, unsafe URLs, or a+ * foreign-content transition back into executable HTML.+ *+ * ============================================================================+ * WHAT THIS SUITE DOES AND DOES NOT ESTABLISH — READ BEFORE TRUSTING IT+ * ============================================================================+ *+ * This suite runs under happy-dom (Vitest's simulated DOM), not a real+ * browser engine. It asserts sanitizer behaviour under that SIMULATED DOM. It+ * does NOT, by itself, establish a browser mXSS invariant, for one concrete+ * reason: happy-dom 20.11.12 has no MathML foreign-content support at all —+ * no tokenizer or tree-construction branch for `<math>` (see+ * html-parser/HTMLParser.ts: there is no reference to `mathml` in it+ * anywhere). Elements under a `<math>` subtree get created in the plain HTML+ * namespace, indistinguishable from any other unrecognized HTML tag, and+ * that cannot be repaired by patching `Element.prototype.namespaceURI`+ * afterwards — the tree was already built wrong by the time any getter runs.+ * A getter that fabricated MathML namespace purely from tag name (which an+ * earlier version of this suite, and this repo's shared vitest setup file,+ * both did) does not fix that: it hides it, by making every MathML-tag-named+ * element report the same namespace regardless of where it actually sits in+ * the tree — precisely the axis mXSS namespace-confusion payloads exploit.+ * Under that fabrication the MathML vectors below could never fail no matter+ * what the application did. This file therefore does NOT install any+ * namespace approximation (see tests/js/happy-dom-mathml-namespace-+ * approximation.js for where that lives now and why it must not be used+ * here), and relies only on happy-dom's real, unmodified behaviour:+ *+ * - SVG: happy-dom's own HTML parser DOES track SVG namespace by tree+ * position (NamespaceURI.svg is assigned during parsing, inherited down+ * the tree it actually builds). The SVG half of the "foreign-content+ * confusion" vector, and DOMPurify's own `_checkSvgNamespace` validity+ * check that runs against it, are exercising real (if not fully+ * browser-faithful — see the parser-algorithm gaps below) namespace+ * tracking, not a fabrication. That part of the invariant is meaningful.+ * - MathML: happy-dom reports plain HTML namespace for every MathML tag,+ * always. DOMPurify's OWN namespace-validity check (`_checkHtmlNamespace`+ * in dompurify/dist/purify.cjs.js) force-removes any element whose tag+ * name is MathML-only but whose reported namespace is HTML — a real+ * mXSS defense, not a test artifact — so these vectors' MathML content+ * is stripped wholesale regardless of whether it was legitimately nested+ * under `<math>` or maliciously placed. The assertions below can still+ * pass, but that tells you DOMPurify fails closed when happy-dom cannot+ * grant real MathML namespace; it tells you NOTHING about whether a+ * REAL browser's foreign-content parser would ever hand DOMPurify a tree+ * where MathML namespace confusion actually occurred. This suite cannot+ * exercise that question at all, with or without a namespace shim.+ *+ * Independently of namespace tracking, happy-dom also does not implement the+ * HTML5 "in foreign content" insertion-mode algorithm: no HTML-integration-+ * point / MathML-text-integration-point reparenting, no rawtext/RCDATA-state+ * divergence inside foreign content, no foster parenting, no breakout on a+ * reparenting-list tag (e.g. `<p>`) encountered inside `<svg>`/`<math>`. Its+ * parser applies the same tokenization rules everywhere (see+ * parseRawTextElementContent in html-parser/HTMLParser.ts, which keys+ * purely off tag name, not namespace/foreign-content state). Direct probes+ * of these vectors serialize identically on the first and second parse in+ * this harness. None of that can be patched from test code without+ * reimplementing the tokenizer's foreign-content branches — well beyond what+ * a test shim should do.+ *+ * Keep the vectors: this suite still guards the application's required+ * sanitize -> serialize -> reparse round trip against regressions in this+ * simulated DOM, and the sentinel/script/on*-attribute/href-scheme checks+ * (unlike the namespace check) do not depend on foreign-content parsing+ * being modeled at all. But treat it as regression coverage for the+ * sanitizer's string-level behaviour, not as proof of a browser mXSS+ * invariant.+ *+ * Real browser coverage lives in+ * tests/ui_tests/playwright/tests/security-mxss-reparse.spec.js. It loads the+ * production sanitizers and locked rendering dependencies in Chromium,+ * Firefox and WebKit, drives these vectors through all four render paths,+ * and checks each reparsed tree for executable surface. Its positive TeX+ * control also verifies that real KaTeX-generated MathML survives. This+ * simulated-DOM suite complements that coverage; it does not replace it.+ * ============================================================================+ */+import { afterAll, afterEach, beforeAll, describe, expect, test, vi } from 'vitest';++const HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml';+const FOREIGN_NAMESPACES = new Set([+ 'http://www.w3.org/2000/svg',+ 'http://www.w3.org/1998/Math/MathML',+]);++const VECTORS = [+ {+ family: 'foreign-content confusion',+ sentinel: 'foreign-sentinel',+ payload: '<p>foreign-sentinel</p><svg><p><style><!--</style><img src=x onerror=alert(1)>'+ + '<math><mtext><table><mglyph><style><!--</style><img src=x onerror=alert(1)>'+ + '</table></mtext></math>',+ },+ {+ family: 'rawtext/RCDATA breakout',+ sentinel: 'rawtext-sentinel',+ payload: '<p>rawtext-sentinel</p><style><a title="</style><img src=x onerror=alert(1)">'+ + '<noscript><p title="</noscript><a href="vbscript:alert(1)" onclick="alert(1)">bad</a>">'+ + '<textarea><a title="</textarea><a href="data:text/html,%3Cscript%3Ealert(1)%3C/script%3E" '+ + 'onfocus="alert(1)">bad</a>">',+ },+ {+ family: 'foster-parenting/table repair',+ sentinel: 'foster-sentinel',+ payload: '<p>foster-sentinel</p><table><caption><svg><foreignObject><table><tr><td>'+ + '<img src=x onerror=alert(1)></td></tr></table></foreignObject></svg></caption></table>'+ + '<form><table><form><tr><td onmouseover=alert(1)>'+ + '<a href=javascript:alert(1)>bad</a></td></tr></form></table></form>',+ },+ {+ family: 'deep-nesting flattening',+ sentinel: 'deep-sentinel',+ payload: '<p>deep-sentinel</p>' + '<div><svg>'.repeat(100)+ + '<a href="javascript:alert(1)"><img src=x onerror=alert(1)></a>'+ + '</svg></div>'.repeat(100),+ },+ {+ family: 'serialization instability',+ sentinel: 'serialization-sentinel',+ payload: '<p>serialization-sentinel</p><div title="prefix<!--suffix">'+ + '<a title="<script src=x>" href="javascript:alert(1)">bad</a></div><!--',+ },+];++let productionDOMPurify;+let productionMarked;++// No local namespace-approximation shim here, deliberately: this suite must+// see happy-dom's real (unfabricated) namespaceURI behaviour for its+// FOREIGN_NAMESPACES check to mean anything. See the file header. The+// createNodeIterator/nodeName repairs DOMPurify still needs are installed+// globally by tests/js/happy-dom-dompurify-shim.js (a Vitest setupFile,+// so they run before the dynamic `import('dompurify')` in beforeAll below).++function reparse(html) {+ const first = document.createElement('div');+ // eslint-disable-next-line no-unsanitized/property -- test-only: this deliberately parses a sanitizer result to assert the mXSS reparse invariant.+ first.innerHTML = html;+ const serialized = first.innerHTML;+ const second = document.createElement('div');+ // eslint-disable-next-line no-unsanitized/property -- test-only: this is the required serialize -> reparse hop under test.+ second.innerHTML = serialized;+ return second;+}++function expectReparseInvariant(html, sentinel) {+ expect(html).not.toBe('');+ const root = reparse(html);+ expect(root.innerHTML).not.toBe('');+ expect(root.textContent).toContain(sentinel);+ expect(root.querySelectorAll('script, iframe, object, embed')).toHaveLength(0);++ for (const element of root.querySelectorAll('*')) {+ expect(element.getAttributeNames().some((name) => /^on/i.test(name))).toBe(false);+ }+ for (const element of root.querySelectorAll('[href]')) {+ // The previous pattern was /^(?:javascript|vbscript|data:text\/html):/i,+ // which required a literal ':' AFTER 'data:text/html' -- so no real+ // 'data:text/html,<payload>' href could ever match it, and three of+ // the five vectors carry exactly that payload. Alternate on complete+ // prefixes instead, and strip the control characters and whitespace+ // browsers ignore inside a scheme before matching.+ // eslint-disable-next-line no-control-regex -- intentional: browsers ignore control characters inside URL schemes+ const href = (element.getAttribute('href') || '').replace(/[\x00-\x20\x7F]/g, '');+ expect(href).not.toMatch(/^(?:javascript:|vbscript:|data:text\/html)/i);+ }+ for (const element of root.querySelectorAll('*')) {+ if (element.namespaceURI !== HTML_NAMESPACE) {+ continue;+ }+ expect(FOREIGN_NAMESPACES.has(element.parentElement?.namespaceURI)).toBe(false);+ }+}++function pdfStub() {+ return {+ internal: { pageSize: { getWidth: () => 612, getHeight: () => 792 } },+ output: () => new Blob(),+ addImage() {}, addPage() {}, getTextWidth: () => 1, line() {}, rect() {},+ setDrawColor() {}, setFillColor() {}, setFont() {}, setFontSize() {},+ setLineWidth() {}, setTextColor() {}, splitTextToSize: (text) => [text],+ text() {}, textWithLink() {},+ };+}++async function sanitizeForPdf(rawHtml) {+ const previews = [];+ const appendChild = document.body.appendChild.bind(document.body);+ vi.spyOn(document.body, 'appendChild').mockImplementation((node) => {+ if (node.classList?.contains('ldr-pdf-content')) {+ previews.push(node);+ }+ return appendChild(node);+ });+ // Feed hostile HTML as if marked itself had emitted it (bypassing the+ // renderer.html escape, like a renderer extension would): the PDF body+ // must still come out of renderMarkdown's sanitizeStable() allowlist.+ vi.spyOn(productionMarked, 'parse').mockReturnValue(rawHtml);+ globalThis.marked = productionMarked;+ globalThis.DOMPurify = productionDOMPurify;+ window.DOMPurify = productionDOMPurify;+ globalThis.jsPDF = class { constructor() { return pdfStub(); } };+ globalThis.html2canvas = vi.fn();+ vi.resetModules();+ await import('@js/services/pdf.js');+ await window.pdfService.generatePdf('mXSS', 'ignored');+ expect(previews).toHaveLength(1);+ return previews[0].querySelector('#pdf-body-content').innerHTML;+}++beforeAll(async () => {+ const { Marked } = await import('marked');+ const markedKatex = (await import('marked-katex-extension')).default;+ productionDOMPurify = (await import('dompurify')).default;+ const marked = new Marked();+ marked.use(markedKatex({ throwOnError: false, errorColor: 'currentColor' }));+ productionMarked = marked;+ globalThis.marked = marked;+ globalThis.DOMPurify = productionDOMPurify;+ window.DOMPurify = productionDOMPurify;+ await import('@js/security/xss-protection.js');+ await import('@js/services/ui.js');+});++afterEach(() => {+ vi.restoreAllMocks();+ globalThis.marked = productionMarked;+ delete window.pdfService;+ document.body.replaceChildren();+});++afterAll(() => {+ delete globalThis.DOMPurify;+ delete globalThis.marked;+ delete globalThis.jsPDF;+ delete globalThis.html2canvas;+});++describe('mXSS sanitize -> serialize -> reparse invariant', () => {+ for (const vector of VECTORS) {+ // Regression: markdown output must remain safe after table repair reparsing.+ test(`renderMarkdown resists ${vector.family}`, () => {+ expectReparseInvariant(window.ui.renderMarkdown(vector.payload), vector.sentinel);+ });++ // Regression: returned sanitizer strings must remain safe after table repair reparsing.+ test(`sanitizeHtml resists ${vector.family}`, () => {+ expectReparseInvariant(+ window.XSSProtection.sanitizeHtml(vector.payload),+ vector.sentinel,+ );+ });++ // Regression: assigned sanitizer strings must remain safe after table repair reparsing.+ test(`safeSetInnerHTML output resists ${vector.family}`, () => {+ const target = document.createElement('div');+ window.XSSProtection.safeSetInnerHTML(target, vector.payload, true);+ expectReparseInvariant(target.innerHTML, vector.sentinel);+ });+ }++ test.each(VECTORS)('PDF preview markup resists $family', async ({ payload, sentinel }) => {+ expectReparseInvariant(await sanitizeForPdf(payload), sentinel);+ });++ test('renderMarkdown keeps benign headings and links', () => {+ const html = window.ui.renderMarkdown('## Safe heading\n\n[Safe link](https://example.com)');+ const root = reparse(html);+ expect(root.innerHTML).not.toBe('');+ expect(root.querySelector('h2')?.textContent).toBe('Safe heading');+ expect(root.querySelector('a')?.getAttribute('href')).toBe('https://example.com');+ });++ test('sanitizeHtml keeps allowed tags', () => {+ const root = reparse(window.XSSProtection.sanitizeHtml('<p><strong>safe</strong> <a href="https://example.com">link</a></p>'));+ expect(root.innerHTML).not.toBe('');+ expect(root.querySelector('strong')?.textContent).toBe('safe');+ expect(root.querySelector('a')?.getAttribute('href')).toBe('https://example.com');+ });++ test('PDF preview keeps benign markdown markup', async () => {+ const root = reparse(await sanitizeForPdf('<h2>Safe heading</h2><p><a href="https://example.com">Safe link</a></p>'));+ expect(root.innerHTML).not.toBe('');+ expect(root.querySelector('h2')?.textContent).toBe('Safe heading');+ expect(root.querySelector('a')?.getAttribute('href')).toBe('https://example.com');+ });+});diff --git a/tests/js/security/notes-news-components-xss.test.js b/tests/js/security/notes-news-components-xss.test.jsnew file mode 100644index 0000000000..b75396d04c--- /dev/null+++ b/tests/js/security/notes-news-components-xss.test.js@@ -0,0 +1,540 @@+/**+ * Defensive output-encoding coverage for the notes/news component scripts.+ *+ * Interpolation map (line numbers in the sources under test):+ *+ * notes_shared.js+ * :67-83 no innerHTML/insertAdjacentHTML sink. note.id is passed through+ * encodeURIComponent before href assignment; title and stripped+ * content_preview are assigned with textContent.+ *+ * research_notes.js+ * :91-96 no parser sink. API note rows are rendered by+ * NotesShared.renderNoteRow (the safe path above).+ *+ * annotation_surface.js+ * no innerHTML/insertAdjacentHTML sink. Dynamic display values use DOM APIs:+ * :189 note_id -> dataset (raw property assignment)+ * :432 selected quote -> textContent+ * :490-491 comment_preview/note_title -> textContent+ * :497 note_id -> encodeURIComponent -> href property+ *+ * news.js+ * :58-64 icon -> esc() in class=""; message -> esc() in text+ * :70-75 message -> esc() in text+ * :81-87 message -> esc() in text+ *+ * subscription-manager.js+ * :129-134 folder.name -> escapeHtml in data-folder and text; folder.icon ->+ * escapeHtml in text; item_count -> finite integer coercion+ * :166-171 static empty-state markup only+ * :177 joins renderSubscriptionCard output into innerHTML+ * :188 subscription.id -> escapeHtml in data-subscription-id+ * :191 query_or_topic -> escapeHtml in text+ * :193 refresh_interval_minutes -> finite integer coercion+ * :194 timeUntil -> locally derived numeric duration string+ * :195 folder -> escapeHtml in text+ * :197 notes -> escapeHtml in text+ * :201/:205/:209 subscription.id -> escapeHtml in data attributes+ * :205-206 status -> strict-comparison-selected static title/icon literals+ * :241-246 refresh interval -> strict-comparison-selected static "selected"+ * :253-256 folder name -> escapeHtml in option value/text; selected is static+ * :279 insertAdjacentHTML receives the modal assembled from those values;+ * notes are assigned afterward through textarea.value (:281)+ * :410-416 static loading markup only+ */++import {+ afterAll,+ beforeAll,+ beforeEach,+ describe,+ expect,+ it,+ test,+ vi,+} from 'vitest';++const IMAGE_PAYLOAD = '<img src=x onerror=alert(1)>';+const SCRIPT_PAYLOAD = '<script>alert(1)</script>';+const SVG_PAYLOAD = '"><svg onload=alert(1)>';+const ATTRIBUTE_PAYLOAD = 'x" onmouseover="alert(1)';+const JAVASCRIPT_URL = 'javascript:alert(1)';++const SUBSCRIPTION_FIXTURE = `+ <ul id="folderTabs">+ <li><button class="nav-link" data-folder="all" type="button">All</button></li>+ <li><button class="nav-link" data-folder="Unfiled" type="button">Unfiled</button></li>+ <li><button id="create-folder-btn" type="button">Create</button></li>+ </ul>+ <div id="subscriptions-list"></div>+`;++let researchNotesHook;+let subscriptionManager;+let modalShow;++function installSubscriptionFixture() {+ // eslint-disable-next-line no-unsanitized/property -- hardcoded test scaffold; no runtime values are interpolated.+ document.body.innerHTML = SUBSCRIPTION_FIXTURE;+}++function jsonResponse(data) {+ return Promise.resolve({+ ok: true,+ status: 200,+ json: () => Promise.resolve(data),+ });+}++function allElements(root) {+ const elements = [...root.querySelectorAll('*')];+ if (root instanceof Element) elements.unshift(root);+ return elements;+}++function eventHandlerAttributes(root) {+ const found = [];+ for (const element of allElements(root)) {+ for (const name of element.getAttributeNames()) {+ if (/^on/i.test(name)) found.push(`${element.tagName}[${name}]`);+ }+ }+ return found;+}++function javascriptHrefs(root) {+ return allElements(root)+ .filter((element) => element.hasAttribute('href'))+ .map((element) => element.getAttribute('href'))+ .filter((href) => /^\s*javascript:/i.test(href || ''));+}++function expectNoActiveMarkup(root) {+ expect(root.querySelectorAll('script, img, svg')).toHaveLength(0);+ expect(eventHandlerAttributes(root)).toEqual([]);+ expect(javascriptHrefs(root)).toEqual([]);+}++function expectInertText(root, payloads) {+ expect(root).not.toBeNull();+ expect(root.textContent).not.toBe('');+ expectNoActiveMarkup(root);+ for (const payload of payloads) {+ expect(root.textContent).toContain(payload);+ }+}++function makeSubscription(overrides = {}) {+ return {+ id: 'subscription-1',+ query_or_topic: 'Quantum updates',+ refresh_interval_minutes: 60,+ next_refresh: new Date(Date.now() + 60 * 60 * 1000).toISOString(),+ folder: 'Reading',+ notes: 'Review weekly',+ status: 'active',+ ...overrides,+ };+}++function renderSubscriptionCards(subscriptions) {+ installSubscriptionFixture();+ subscriptionManager.currentFolder = 'all';+ subscriptionManager.subscriptions = { Reading: subscriptions };+ subscriptionManager.renderSubscriptions();+ return document.getElementById('subscriptions-list');+}++async function renderResearchNotes(notes) {+ const list = document.createElement('div');+ list.id = 'research-notes-list';+ const empty = document.createElement('div');+ empty.id = 'research-notes-empty';+ document.body.replaceChildren(list, empty);++ researchNotesHook.setResearchId('research-1');+ globalThis.safeFetch.mockImplementation(() => jsonResponse({ success: true, notes }));+ await researchNotesHook.loadResearchNotes();+ return list;+}++async function renderAnnotation(annotation, reportText) {+ const container = document.createElement('div');+ container.id = 'annotation-xss-report';+ container.textContent = reportText;+ document.body.replaceChildren(container);++ globalThis.safeFetch.mockImplementation(() => jsonResponse({+ success: true,+ annotations: [annotation],+ }));+ window.LDRAnnotationSurface.init({+ containerId: container.id,+ endpoints: {+ list: '/notes/api/annotations',+ create: '/notes/api/annotations',+ deleteFor: (noteId) => `/notes/api/annotations/${encodeURIComponent(noteId)}`,+ },+ });++ await vi.waitFor(() => {+ expect(container.querySelectorAll('mark.ldr-research-annotation').length)+ .toBeGreaterThan(0);+ });+ const mark = container.querySelector('mark.ldr-research-annotation');+ mark.click();+ const popover = document.querySelector('.ldr-annotation-popover');+ expect(popover).not.toBeNull();+ return { container, mark, popover };+}++beforeAll(async () => {+ window.__VITEST_TEST__ = true;+ globalThis.safeFetch = vi.fn(() => jsonResponse({ success: true, annotations: [] }));++ await import('@js/security/xss-protection.js');+ await import('@js/components/annotation_surface.js');++ document.body.replaceChildren();+ await import('@js/components/research_notes.js');+ researchNotesHook = window.__researchNotesTest;++ await import('@js/components/news.js');++ installSubscriptionFixture();+ await import('@js/components/subscription-manager.js');+ if (!window.subscriptionManager) {+ document.dispatchEvent(new Event('DOMContentLoaded'));+ }+ subscriptionManager = window.subscriptionManager;+});++afterAll(() => {+ delete window.__VITEST_TEST__;+});++beforeEach(() => {+ document.body.replaceChildren();+ globalThis.safeFetch.mockReset();+ globalThis.safeFetch.mockImplementation(() => jsonResponse({ success: true, annotations: [] }));+ modalShow = vi.fn();+ globalThis.bootstrap = {+ Modal: vi.fn(function() {+ this.show = modalShow;+ this.hide = vi.fn();+ }),+ };+ subscriptionManager.folders = [];+ subscriptionManager.subscriptions = {};+ subscriptionManager.currentFolder = 'all';+});++describe('notes_shared.js output encoding', () => {+ it('renders a benign linked-note row through the production helper', () => {+ const row = window.NotesShared.renderNoteRow({+ id: 'note one',+ title: 'Benign title',+ content_preview: '**Benign preview**',+ });+ document.body.appendChild(row);++ expect(row.classList.contains('ldr-research-note-row')).toBe(true);+ expect(row.getAttribute('href')).toBe('/notes/note%20one');+ expect(row.querySelector('.ldr-research-note-title').textContent).toBe('Benign title');+ expect(row.querySelector('.ldr-research-note-preview').textContent).toBe('Benign preview');+ expectNoActiveMarkup(row);+ });++ it('keeps hostile note titles/previews as text and encodes href IDs', () => {+ const title = `${IMAGE_PAYLOAD} ${ATTRIBUTE_PAYLOAD}`;+ const preview = `${SCRIPT_PAYLOAD} ${SVG_PAYLOAD}`;+ const row = window.NotesShared.renderNoteRow({+ id: JAVASCRIPT_URL,+ title,+ content_preview: preview,+ });+ document.body.appendChild(row);++ expect(row.querySelector('.ldr-research-note-title')).not.toBeNull();+ expect(row.querySelector('.ldr-research-note-preview')).not.toBeNull();+ expect(row.getAttribute('href')).toBe(`/notes/${encodeURIComponent(JAVASCRIPT_URL)}`);+ expectInertText(row, [title, preview]);+ });+});++describe('research_notes.js output encoding', () => {+ it('renders a benign API note through the real load path', async () => {+ const list = await renderResearchNotes([{+ id: 'research-note-1',+ title: 'Linked research note',+ content_preview: 'A safe preview',+ }]);++ const row = list.querySelector('.ldr-research-note-row');+ expect(list.children).toHaveLength(1);+ expect(row.getAttribute('href')).toBe('/notes/research-note-1');+ expect(row.textContent).toContain('Linked research note');+ expect(row.textContent).toContain('A safe preview');+ expectNoActiveMarkup(list);+ });++ it('keeps every hostile API note display field inert through loadResearchNotes', async () => {+ const title = `${IMAGE_PAYLOAD} ${SVG_PAYLOAD}`;+ const preview = `${SCRIPT_PAYLOAD} ${ATTRIBUTE_PAYLOAD}`;+ const list = await renderResearchNotes([{+ id: JAVASCRIPT_URL,+ title,+ content_preview: preview,+ }]);++ const row = list.querySelector('.ldr-research-note-row');+ expect(list.children).toHaveLength(1);+ expect(row).not.toBeNull();+ expect(row.getAttribute('href')).toBe(`/notes/${encodeURIComponent(JAVASCRIPT_URL)}`);+ expectInertText(list, [title, preview]);+ });+});++describe('annotation_surface.js output encoding', () => {+ it('renders a benign annotation highlight and popover through init/reload', async () => {+ const { container, mark, popover } = await renderAnnotation({+ note_id: 'note-1',+ quote: 'benign highlighted quote',+ prefix: '',+ suffix: '',+ comment_preview: 'Benign comment',+ }, 'Report with a benign highlighted quote for review.');++ expect(mark.textContent).toBe('benign highlighted quote');+ expect(popover.querySelector('.ldr-annotation-popover-comment').textContent)+ .toBe('Benign comment');+ expect(popover.querySelector('a').getAttribute('href')).toBe('/notes/note-1');+ expectNoActiveMarkup(container);+ expectNoActiveMarkup(popover);+ });++ it('keeps hostile quotes/comments inert and percent-encodes note hrefs', async () => {+ const quote = `${IMAGE_PAYLOAD} ${SCRIPT_PAYLOAD} ${SVG_PAYLOAD}`;+ const comment = `${ATTRIBUTE_PAYLOAD} ${SCRIPT_PAYLOAD}`;+ const { container, mark, popover } = await renderAnnotation({+ note_id: JAVASCRIPT_URL,+ quote,+ prefix: '',+ suffix: '',+ comment_preview: comment,+ }, `Report prefix ${quote} report suffix.`);++ expect(mark.dataset.noteId).toBe(JAVASCRIPT_URL);+ expect(container.textContent).toContain(quote);+ expect(popover.querySelector('.ldr-annotation-popover-comment')).not.toBeNull();+ expect(popover.querySelector('a').getAttribute('href'))+ .toBe(`/notes/${encodeURIComponent(JAVASCRIPT_URL)}`);+ expectInertText(popover, [comment]);+ expectNoActiveMarkup(container);+ });++ it('keeps a hostile note_title fallback as visible popover text', async () => {+ const noteTitle = `${SCRIPT_PAYLOAD} ${SVG_PAYLOAD} ${ATTRIBUTE_PAYLOAD}`;+ const { popover } = await renderAnnotation({+ note_id: ATTRIBUTE_PAYLOAD,+ quote: 'title fallback target',+ prefix: '',+ suffix: '',+ comment_preview: '',+ note_title: noteTitle,+ }, 'A title fallback target is present in this report.');++ const body = popover.querySelector('.ldr-annotation-popover-comment');+ expect(body).not.toBeNull();+ expect(popover.querySelector('a').getAttribute('href'))+ .toBe(`/notes/${encodeURIComponent(ATTRIBUTE_PAYLOAD)}`);+ expectInertText(popover, [noteTitle]);+ });+});++describe('components/news.js output encoding', () => {+ it('renders benign empty/loading/error states and tags intact', () => {+ const empty = document.createElement('div');+ const loading = document.createElement('div');+ const error = document.createElement('div');+ const tag = window.createTag('Benign tag', 'ldr-safe-tag');+ document.body.append(empty, loading, error, tag);++ window.showEmptyState(empty, 'Nothing here', 'fas fa-box-open');+ window.showLoadingState(loading, 'Loading feed');+ window.showErrorState(error, 'Could not load feed');++ expect(empty.querySelector('.ldr-empty-state')).not.toBeNull();+ expect(empty.querySelector('p').textContent).toBe('Nothing here');+ expect(loading.querySelector('p').textContent).toBe('Loading feed');+ expect(error.querySelector('p').textContent).toBe('Could not load feed');+ expect(tag.textContent).toBe('Benign tag');+ expect(tag.className).toBe('ldr-safe-tag');+ expectNoActiveMarkup(document.body);+ });++ it('escapes state messages and contains an icon quote-breakout in class', () => {+ const empty = document.createElement('div');+ const loading = document.createElement('div');+ const error = document.createElement('div');+ document.body.append(empty, loading, error);++ window.showEmptyState(empty, IMAGE_PAYLOAD, ATTRIBUTE_PAYLOAD);+ window.showLoadingState(loading, SCRIPT_PAYLOAD);+ window.showErrorState(error, SVG_PAYLOAD);++ expect(empty.querySelector('.ldr-empty-state')).not.toBeNull();+ expect(loading.querySelector('.ldr-loading-placeholder')).not.toBeNull();+ expect(error.querySelector('.ldr-error-state')).not.toBeNull();+ expect(empty.querySelector('i').getAttribute('class')).toBe(ATTRIBUTE_PAYLOAD);+ expectInertText(empty, [IMAGE_PAYLOAD]);+ expectInertText(loading, [SCRIPT_PAYLOAD]);+ expectInertText(error, [SVG_PAYLOAD]);+ });++ it('uses DOM properties for hostile tag text and class values', () => {+ const text = `${IMAGE_PAYLOAD} ${SCRIPT_PAYLOAD} ${SVG_PAYLOAD}`;+ const tag = window.createTag(text, ATTRIBUTE_PAYLOAD);+ document.body.appendChild(tag);++ expect(tag.tagName).toBe('SPAN');+ expect(tag.getAttribute('class')).toBe(ATTRIBUTE_PAYLOAD);+ expectInertText(tag, [text]);+ });+});++describe('subscription-manager.js output encoding', () => {+ it('renders benign folder tabs and subscription cards intact', () => {+ installSubscriptionFixture();+ subscriptionManager.folders = [{+ name: 'Reading',+ icon: 'folder',+ item_count: 2,+ }];+ subscriptionManager.renderFolderTabs();++ subscriptionManager.subscriptions = { Reading: [makeSubscription()] };+ subscriptionManager.renderSubscriptions();++ const tab = [...document.querySelectorAll('#folderTabs .nav-link')]+ .find((element) => element.dataset.folder === 'Reading');+ const card = document.querySelector('.ldr-subscription-card');+ expect(tab).not.toBeUndefined();+ expect(tab.textContent).toContain('Reading');+ expect(tab.textContent).toContain('2');+ expect(card).not.toBeNull();+ expect(card.dataset.subscriptionId).toBe('subscription-1');+ expect(card.textContent).toContain('Quantum updates');+ expect(card.textContent).toContain('Every 60 min');+ expect(card.textContent).toContain('Review weekly');+ expect(card.querySelectorAll('.ldr-subscription-actions button')).toHaveLength(3);+ expectNoActiveMarkup(document.body);+ });++ it('escapes hostile folder names/icons in text and data attributes', () => {+ installSubscriptionFixture();+ const folderName = `${IMAGE_PAYLOAD} ${ATTRIBUTE_PAYLOAD}`;+ const folderIcon = `${SCRIPT_PAYLOAD} ${SVG_PAYLOAD}`;+ subscriptionManager.folders = [{+ name: folderName,+ icon: folderIcon,+ item_count: 7,+ }];+ subscriptionManager.renderFolderTabs();++ const tab = [...document.querySelectorAll('#folderTabs .nav-link')]+ .find((element) => element.dataset.folder === folderName);+ expect(tab).not.toBeUndefined();+ expect(tab.getAttribute('data-folder')).toBe(folderName);+ expectInertText(tab, [folderIcon, folderName]);+ });++ // Regression coverage: folder.item_count is coerced to a finite integer.+ test('does not materialize markup from a hostile folder item_count', () => {+ installSubscriptionFixture();+ subscriptionManager.folders = [{+ name: 'Count canary',+ icon: 'folder',+ item_count: IMAGE_PAYLOAD,+ }];+ subscriptionManager.renderFolderTabs();++ const tab = [...document.querySelectorAll('#folderTabs .nav-link')]+ .find((element) => element.dataset.folder === 'Count canary');+ expect(tab).not.toBeUndefined();+ expect(tab.textContent).toContain('Count canary');+ expectNoActiveMarkup(document.getElementById('folderTabs'));+ });++ it('escapes hostile subscription text/IDs and safely derives status/time output', () => {+ const cardId = ATTRIBUTE_PAYLOAD;+ const query = IMAGE_PAYLOAD;+ const folder = SCRIPT_PAYLOAD;+ const notes = SVG_PAYLOAD;+ const container = renderSubscriptionCards([makeSubscription({+ id: cardId,+ query_or_topic: query,+ folder,+ notes,+ next_refresh: IMAGE_PAYLOAD,+ status: ATTRIBUTE_PAYLOAD,+ })]);++ const card = container.querySelector('.ldr-subscription-card');+ expect(container.children).toHaveLength(1);+ expect(card).not.toBeNull();+ expect(card.dataset.subscriptionId).toBe(cardId);+ const actions = card.querySelectorAll('.ldr-subscription-actions button');+ expect(actions).toHaveLength(3);+ for (const action of actions) {+ expect(action.dataset.subscriptionId).toBe(cardId);+ }+ expect(card.querySelector('.pause-subscription-btn').title).toBe('Resume');+ expect(card.textContent).toContain('Next: NaNm');+ expectInertText(card, [query, folder, notes]);+ });++ // Regression coverage: refresh_interval_minutes is coerced to a finite integer.+ test('does not materialize markup from a hostile refresh interval', () => {+ const container = renderSubscriptionCards([makeSubscription({+ query_or_topic: 'Interval canary',+ refresh_interval_minutes: SCRIPT_PAYLOAD,+ })]);++ const card = container.querySelector('.ldr-subscription-card');+ expect(container.children).toHaveLength(1);+ expect(card).not.toBeNull();+ expect(card.textContent).toContain('Interval canary');+ expectNoActiveMarkup(container);+ });++ it('keeps hostile edit-modal folder text and textarea notes inert', async () => {+ installSubscriptionFixture();+ const folderName = `${ATTRIBUTE_PAYLOAD} ${SVG_PAYLOAD}`;+ const notes = `${IMAGE_PAYLOAD} ${SCRIPT_PAYLOAD}`;+ const subscription = makeSubscription({+ id: 'edit-subscription',+ refresh_interval_minutes: ATTRIBUTE_PAYLOAD,+ folder: folderName,+ notes,+ });+ subscriptionManager.folders = [{ name: folderName }];+ subscriptionManager.subscriptions = { Reading: [subscription] };++ await subscriptionManager.editSubscription(subscription.id);++ const modal = document.getElementById('editSubscriptionModal');+ expect(modal).not.toBeNull();+ expect(modal.querySelectorAll('#edit-folder option').length).toBeGreaterThan(1);+ const option = [...modal.querySelectorAll('#edit-folder option')]+ .find((element) => element.value === folderName);+ expect(option).not.toBeUndefined();+ expect(option.textContent).toBe(folderName);+ expect(option.value).toBe(folderName);+ expect(document.getElementById('edit-notes').value).toBe(notes);+ expect(globalThis.bootstrap.Modal).toHaveBeenCalledWith(modal);+ expect(modalShow).toHaveBeenCalledTimes(1);+ expectInertText(modal, [folderName]);+ });+});diff --git a/tests/js/security/progress-agent-thinking-xss.test.js b/tests/js/security/progress-agent-thinking-xss.test.jsnew file mode 100644index 0000000000..cd79d9037d--- /dev/null+++ b/tests/js/security/progress-agent-thinking-xss.test.js@@ -0,0 +1,127 @@+/**+ * XSS regression coverage for components/progress.js updateAgentThinking().+ *+ * Live progress data can contain user queries, search-derived web content,+ * and LLM output. The renderer's innerHTML sink must keep all of that in text+ * context.+ */+import fs from 'node:fs';+import path from 'node:path';+import { fileURLToPath } from 'node:url';++let progressComponent;++beforeAll(async () => {+ await import('@js/components/progress.js');+ progressComponent = window.progressComponent;+});++beforeEach(() => {+ document.body.innerHTML = `+ <div id="agent-thinking-panel" style="display: none;">+ <div id="agent-thinking-content"></div>+ </div>+ `;+});++function renderStep(data) {+ progressComponent.updateAgentThinking(data);+ return document+ .getElementById('agent-thinking-content')+ .querySelector('.ldr-agent-step:last-child');+}++function expectInertStep(step, visiblePayload) {+ expect(step).not.toBeNull();+ expect(step.querySelectorAll('img, script, svg, iframe, object, embed').length).toBe(0);+ for (const element of step.querySelectorAll('*')) {+ expect([...element.attributes].some(({ name }) => name.toLowerCase().startsWith('on'))).toBe(false);+ }+ expect(step.textContent).toContain(visiblePayload);+}++describe('updateAgentThinking XSS surfaces', () => {+ it('keeps hostile thought output as inert visible text', () => {+ const payload = '<img src=x onerror=alert(1)><script>alert(1)</script>';+ const step = renderStep({ phase: 'thought', thought: payload });++ expectInertStep(step, payload);+ });++ it('keeps hostile tool-call message and tool name inert', () => {+ const message = '<img src=x onerror=alert(1)> Searching <svg onload=alert(2)>';+ const step = renderStep({+ phase: 'tool_call',+ tool: '<svg onload=alert(3)>',+ message,+ });++ expectInertStep(step, message);+ });++ it('keeps hostile fallback tool name and query inert', () => {+ const tool = '<svg onload=alert(1)>';+ const query = '"><svg onload=alert(2)>';+ const step = renderStep({+ phase: 'tool_call',+ tool,+ arguments: { query },+ });++ expectInertStep(step, `Using ${tool}\nQuery: "${query}"`);+ });++ it('keeps hostile observation web content inert', () => {+ const content = '<script>alert(1)</script><img src=x onerror=alert(1)>';+ const step = renderStep({+ phase: 'observation',+ message: 'Search result',+ content,+ });++ expectInertStep(step, `Search result\n${content}`);+ });++ it('keeps hostile errors inert', () => {+ const error = '<img src=x onerror=alert(1)><script>alert(1)</script>';+ const step = renderStep({ phase: 'error', error });++ expectInertStep(step, error);+ });++ it('documents quote-unsafe escapeHtml output and guards sink interpolations', () => {+ const step = renderStep({ phase: 'thought', thought: 'x" y' });+ const renderedContent = step.querySelector('.ldr-agent-step-content');++ // The local escapeHtml() leaves quotes unchanged. This is safe here+ // only because the interpolation is text context, never an attribute.+ expect(renderedContent.innerHTML).toContain('x" y');+ expect(renderedContent.innerHTML).not.toContain('"');++ const progressPath = path.resolve(+ path.dirname(fileURLToPath(import.meta.url)),+ '../../../src/local_deep_research/web/static/js/components/progress.js',+ );+ const source = fs.readFileSync(progressPath, 'utf8');+ const template = source.match(/step\.innerHTML\s*=\s*`([^`]*)`/);+ expect(template).not.toBeNull();++ const interpolations = template[1].match(/\$\{[^}]*\}/g) || [];+ expect(interpolations).toHaveLength(2);+ const dollar = '$';+ expect(interpolations).toEqual([+ `${dollar}{escapeHtml(label)}`,+ `${dollar}{escapeHtml(stepContent)}`,+ ]);+ });++ it('escapes content that crosses the 800-character truncation boundary', () => {+ const content = `${'A'.repeat(795)}<img src=x onerror=alert(1)>`;+ const step = renderStep({ phase: 'observation', message: 'M\n', content });+ const renderedContent = step.querySelector('.ldr-agent-step-content');++ expect(step.querySelectorAll('img, script, svg').length).toBe(0);+ expect(renderedContent.textContent).toContain(`${'A'.repeat(795)}<i...`);+ expect(renderedContent.innerHTML).toContain('<i...');+ });+});diff --git a/tests/js/security/progress-stats-xss.test.js b/tests/js/security/progress-stats-xss.test.jsnew file mode 100644index 0000000000..413d5ff49b--- /dev/null+++ b/tests/js/security/progress-stats-xss.test.js@@ -0,0 +1,242 @@+/**+ * XSS regression coverage for the context-overflow stats tables.+ *+ * The requested symbols are implemented in components/context-overflow.js,+ * not components/progress.js. The production path is+ * loadContextData() -> displayContextData() -> renderRequestsTable() /+ * displayModelStats() / displayTruncatedRequests().+ *+ * Interpolation map (context-overflow.js):+ * renderRequestsTable :439 timestamp is Date output; :434 research_id is+ * URL-encoded + escaped; :441 model and :450 query use attribute-context+ * escaping for titles and text-context escaping for display; :442 provider,+ * :443 phase are escaped; :444-449 number cells use the local+ * Number()/isFinite-coercing formatNumber; badges/classes are literals.+ * displayModelStats :509 model title/display and :510 provider are escaped;+ * :524/:528/:532/:540/:544/:548 are formatNumber-coerced; :514 truncation+ * rate and :569 response time are finite-number-coerced. Computed widths/colors+ * are numeric/hardcoded.+ * displayTruncatedRequests :612 timestamp is Date output; :614 query and+ * :616 model are escaped; :617-619 are formatNumber-coerced; :621 is URL-+ * encoded. displayContextData's dynamic-section values are textContent or+ * number-derived. This component has no cost/formatCurrency interpolation.+ */+import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';++const MARKUP = `+ <div id="loading"></div>+ <div id="content"></div>+ <div id="empty-no-data"></div>+ <div id="empty-no-truncation"></div>+ <div id="empty-no-context-data"></div>+ <div id="warning-banner"></div>+ <span id="warning-rate"></span>+ <div id="context-overflow-section"></div>+ <table><tbody id="requests-tbody"></tbody></table>+ <span id="pagination-info"></span>+ <button id="pagination-prev"></button>+ <button id="pagination-next"></button>+`;++const MARKUP_PAYLOAD = '<img src=x onerror=alert(1)>';+const SVG_PAYLOAD = '<svg onload=alert(2)>';+const ATTRIBUTE_PAYLOAD = 'x" onmouseover="alert(3)';++beforeAll(async () => {+ window.__VITEST_TEST__ = true;+ globalThis.Chart = class { destroy() {} };+ globalThis.URLValidator = { safeAssign: vi.fn() };+ window.HTMLCanvasElement.prototype.getContext = () => null;+ await import('@js/components/context-overflow.js');+});++beforeEach(() => {+ // eslint-disable-next-line no-unsanitized/property -- hardcoded fixture markup.+ document.body.innerHTML = MARKUP;+});++function payload({ allRequests = [], modelStats = [], modelTokenStats = [], truncated = [] } = {}) {+ return {+ status: 'success',+ overview: {+ truncation_rate: 5,+ truncated_requests: 1,+ requests_with_context_data: 1,+ total_requests: 1,+ avg_tokens_truncated: 20,+ },+ token_summary: { total_requests: 1 },+ model_stats: modelStats,+ model_token_stats: modelTokenStats,+ recent_truncated: truncated,+ chart_data: [],+ context_limits: [],+ phase_breakdown: [],+ current_context_window: 8192,+ all_requests: allRequests,+ pagination: { page: 1, total_pages: 1 },+ };+}++async function render(data) {+ globalThis.fetch = vi.fn(() => Promise.resolve({+ ok: true,+ json: () => Promise.resolve(data),+ }));+ await window.contextOverflowController.loadContextData('30d');+}++function expectNoLiveMarkup() {+ expect(document.querySelectorAll('img, script, svg, iframe, object, embed')).toHaveLength(0);+ for (const element of document.querySelectorAll('*')) {+ expect([...element.attributes].some(({ name }) => /^on/i.test(name))).toBe(false);+ }+}++describe('context-overflow stats table XSS surfaces', () => {+ it('renders hostile request strings inertly and coerces every request numeric cell', async () => {+ await render(payload({+ allRequests: [{+ timestamp: '2026-01-02T03:04:05Z',+ research_id: 'id?<svg>',+ model: SVG_PAYLOAD,+ provider: MARKUP_PAYLOAD,+ research_phase: SVG_PAYLOAD,+ research_query: MARKUP_PAYLOAD,+ prompt_tokens: MARKUP_PAYLOAD,+ completion_tokens: MARKUP_PAYLOAD,+ total_tokens: MARKUP_PAYLOAD,+ context_limit: MARKUP_PAYLOAD,+ tokens_truncated: MARKUP_PAYLOAD,+ context_truncated: true,+ }],+ }));++ const row = document.querySelector('#requests-tbody tr');+ expect(row).not.toBeNull();+ expect(row.textContent).toContain(SVG_PAYLOAD);+ expect(row.textContent).toContain(MARKUP_PAYLOAD);+ expect(row.textContent).toContain('0');+ expectNoLiveMarkup();+ });++ it('renders hostile truncated-request text inertly and coerces its numeric cells', async () => {+ await render(payload({+ truncated: [{+ timestamp: '2026-01-02T03:04:05Z',+ research_id: `id/${MARKUP_PAYLOAD}`,+ research_query: MARKUP_PAYLOAD,+ model: SVG_PAYLOAD,+ prompt_tokens: MARKUP_PAYLOAD,+ context_limit: MARKUP_PAYLOAD,+ tokens_truncated: MARKUP_PAYLOAD,+ }],+ }));++ const table = document.querySelector('#truncated-list table');+ expect(table).not.toBeNull();+ expect(table.textContent).toContain(MARKUP_PAYLOAD);+ expect(table.textContent).toContain(SVG_PAYLOAD);+ expect(table.textContent).toContain('0');+ expectNoLiveMarkup();+ });++ it('keeps model-card names/providers and formatNumber-fed values inert', async () => {+ await render(payload({+ modelStats: [{+ model: SVG_PAYLOAD,+ provider: MARKUP_PAYLOAD,+ total_requests: MARKUP_PAYLOAD,+ truncated_count: MARKUP_PAYLOAD,+ truncation_rate: 5,+ avg_context_limit: MARKUP_PAYLOAD,+ }],+ modelTokenStats: [{+ model: SVG_PAYLOAD,+ provider: MARKUP_PAYLOAD,+ min_prompt: MARKUP_PAYLOAD,+ avg_prompt: MARKUP_PAYLOAD,+ max_prompt: MARKUP_PAYLOAD,+ }],+ }));++ const card = document.querySelector('#model-stats .ldr-model-card');+ expect(card).not.toBeNull();+ expect(card.textContent).toContain(SVG_PAYLOAD);+ expect(card.textContent).toContain(MARKUP_PAYLOAD);+ expect(card.textContent).toContain('0');+ expectNoLiveMarkup();+ });++ // Regression: renderRequestsTable model titles must not allow quote breakouts.+ it('prevents quote breakout in renderRequestsTable model title', async () => {+ await render(payload({+ allRequests: [{+ timestamp: '2026-01-02T03:04:05Z', model: ATTRIBUTE_PAYLOAD,+ provider: 'openai', prompt_tokens: 1, completion_tokens: 2,+ total_tokens: 3, context_limit: 4, tokens_truncated: 0,+ }],+ }));++ expectNoLiveMarkup();+ });++ // Regression: model-card truncation rates must be numerically coerced.+ it('rejects raw model-card truncation-rate interpolation', async () => {+ await render(payload({+ modelStats: [{+ model: 'safe-model', provider: 'openai', total_requests: 1,+ truncated_count: 0, truncation_rate: MARKUP_PAYLOAD,+ }],+ }));++ expectNoLiveMarkup();+ });++ // Regression: model-card response durations must be numerically coerced.+ it('rejects raw model-card response-duration interpolation', async () => {+ await render(payload({+ modelStats: [{+ model: 'safe-model', provider: 'openai', total_requests: 1,+ truncated_count: 0, truncation_rate: 5,+ }],+ modelTokenStats: [{+ model: 'safe-model', provider: 'openai', avg_response_time_ms: MARKUP_PAYLOAD,+ }],+ }));++ expectNoLiveMarkup();+ });++ it('renders a benign end-to-end stats table with real numbers', async () => {+ await render(payload({+ allRequests: [{+ timestamp: '2026-01-02T03:04:05Z', research_id: 'research-123',+ model: 'gpt-4', provider: 'openai', research_phase: 'analysis',+ research_query: 'quantum computing', prompt_tokens: 1234,+ completion_tokens: 567, total_tokens: 1801, context_limit: 8192,+ tokens_truncated: 42, context_truncated: true,+ }],+ modelStats: [{+ model: 'gpt-4', provider: 'openai', total_requests: 12,+ truncated_count: 2, truncation_rate: 16, avg_context_limit: 8192,+ }],+ modelTokenStats: [{+ model: 'gpt-4', provider: 'openai', min_prompt: 100,+ avg_prompt: 1200, max_prompt: 2000, avg_response_time_ms: 250,+ }],+ truncated: [{+ timestamp: '2026-01-02T03:04:05Z', research_id: 'research-123',+ research_query: 'quantum computing', model: 'gpt-4',+ prompt_tokens: 1234, context_limit: 8192, tokens_truncated: 42,+ }],+ }));++ expect(document.querySelectorAll('#requests-tbody tr')).toHaveLength(1);+ expect(document.querySelector('#requests-tbody').textContent).toContain('1,234');+ expect(document.querySelector('#requests-tbody').textContent).toContain('1,801');+ expect(document.querySelector('#model-stats').textContent).toContain('1,200');+ expect(document.querySelector('#truncated-list').textContent).toContain('8,192');+ expectNoLiveMarkup();+ });+});diff --git a/tests/js/security/render-markdown-fail-closed.test.js b/tests/js/security/render-markdown-fail-closed.test.jsindex be2b08833a..c7cb27f4a7 100644--- a/tests/js/security/render-markdown-fail-closed.test.js+++ b/tests/js/security/render-markdown-fail-closed.test.js@@ -14,6 +14,7 @@* actually taken when it is available.*/+import '@js/security/xss-protection.js';import '@js/services/ui.js';const HOSTILE_MARKDOWN = '# Title\n\n<img src=x onerror="window.__pwnedA=1">';@@ -142,18 +143,18 @@ describe('renderMarkdown fails closed when DOMPurify is unavailable', () => {it('sanitizes through DOMPurify when it is available', () => {_stubMarked();- let sanitizedInput = null;+ const sanitizedInputs = [];globalThis.DOMPurify = {isSupported: true,sanitize: (html) => {- sanitizedInput = html;+ sanitizedInputs.push(html);return '<p>clean</p>';},};const out = window.ui.renderMarkdown(HOSTILE_MARKDOWN);- expect(sanitizedInput).toBe(HOSTILE_PARSED_HTML);+ expect(sanitizedInputs[0]).toBe(HOSTILE_PARSED_HTML);expect(out).toContain('<p>clean</p>');});diff --git a/tests/js/security/render-markdown-tabnabbing.test.js b/tests/js/security/render-markdown-tabnabbing.test.jsindex fb01738cbb..5e0af36433 100644--- a/tests/js/security/render-markdown-tabnabbing.test.js+++ b/tests/js/security/render-markdown-tabnabbing.test.js@@ -1,138 +1,26 @@-/**- * Tabnabbing contracts for raw-HTML anchors inside rendered markdown.- *- * ``renderMarkdown``'s marked renderer adds ``rel="noopener- * noreferrer"`` to **markdown-syntax** links, but raw ``<a- * target="_blank">`` HTML embedded in markdown passes through marked's- * HTML passthrough untouched by that renderer hook. Those anchors get- * their rel from xss-protection.js's ``afterSanitizeAttributes`` hook,- * so ``renderMarkdown`` ensures that hook is registered before it- * sanitizes (``XSSProtection.ensureTabnabbingHook``).- *- * These contracts pin, under the adverse order where DOMPurify binds- * after both scripts loaded: a raw-HTML ``target="_blank"`` anchor,- * ``<area>`` or ``<form>`` in markdown keeps its target through- * renderMarkdown's ``ADD_ATTR`` and gains the rel through the hook,- * registration stays single across renders, and the marked-missing- * fallback escapes raw anchors into inert text. Every test reloads both- * modules and late-binds a fresh DOMPurify, so each test's first render- * is the first sanitize that instance sees: moving the ensure after the- * sanitize call fails every rel assertion, not only the first test's.- */+/** Late-bound sanitizer coverage through the real Markdown rendering path. */+import createDOMPurify from 'dompurify';+import { Marked } from 'marked';-// Browsers expose a <form>'s controls as named properties that shadow-// same-named built-ins on the form instance ([LegacyOverrideBuiltIns]);-// happy-dom does not, so the stand-in emulates it while the hooks run.-const FORM_SHADOWABLE = ['tagName', 'getAttribute', 'setAttribute'];-const FORM_CONTROLS = 'input,button,select,textarea,fieldset,output,object';--const withFormNamedProps = (el, fn) => {- const shadowed = [];- if (el.localName === 'form') {- const controls = Array.from(el.querySelectorAll(FORM_CONTROLS));- FORM_SHADOWABLE.forEach((prop) => {- const control = controls.find((c) =>- c.getAttribute('name') === prop || c.getAttribute('id') === prop- );- if (control) {- Object.defineProperty(el, prop, {- configurable: true,- get: () => control,- });- shadowed.push(prop);- }- });- }- try {- fn();- } finally {- shadowed.forEach((prop) => delete el[prop]);- }- return shadowed.length;-};--describe('renderMarkdown ensures the tabnabbing hook', () => {- let registeredHooks;- let purifier;- let shadowedCount;-- // Subset of DOMPurify's default ALLOWED_ATTR; like the real list it- // has no `target`, so `target` only survives through the caller's- // ADD_ATTR (renderMarkdown passes ['target', 'rel']).- const DEFAULT_ALLOWED_ATTR = [- 'href', 'title', 'class', 'id', 'rel', 'action', 'method', 'name',- 'alt', 'shape', 'coords',- ];-- const lateBind = () => {- registeredHooks = {};- shadowedCount = 0;- purifier = {- // renderMarkdown trusts only an explicitly supported sanitizer.- isSupported: true,- addHook: (name, cb) => {- registeredHooks[name] ||= [];- registeredHooks[name].push(cb);- },- sanitize: (dirty, config = {}) => {- const template = document.createElement('template');- // eslint-disable-next-line no-unsanitized/property -- test harness stand-in: fixture is this file's own input- template.innerHTML = String(dirty);- const allowedAttr = new Set([- ...(config.ALLOWED_ATTR || DEFAULT_ALLOWED_ATTR),- ...(config.ADD_ATTR || []),- ].map((x) => String(x).toLowerCase()));- // Like DOMPurify: filter each element's attributes, then run- // the afterSanitizeAttributes hooks on it.- template.content.querySelectorAll('*').forEach((el) => {- Array.from(el.attributes).forEach((attr) => {- if (!allowedAttr.has(attr.name.toLowerCase())) {- el.removeAttribute(attr.name);- }- });- shadowedCount += withFormNamedProps(el, () => {- (registeredHooks.afterSanitizeAttributes || []).forEach(- (cb) => cb(el)- );- });- });- return template.innerHTML;- },- };- globalThis.DOMPurify = purifier;- };-- const parseOut = (out) => {- const template = document.createElement('template');- // eslint-disable-next-line no-unsanitized/property -- test harness: output under test- template.innerHTML = out;- return template.content;- };+describe('renderMarkdown with late-bound DOMPurify', () => {+ let addHook;beforeEach(async () => {- // Adverse order, per test: neither marked, nor DOMPurify, nor- // (therefore) the hook exist when the modules load.delete globalThis.DOMPurify;- globalThis.marked = undefined;+ delete globalThis.marked;vi.resetModules();await import('@js/security/xss-protection.js');await import('@js/services/ui.js');-- // ...then the real-world stack binds afterwards.- // eslint-disable-next-line require-atomic-updates -- deliberate late binding of the deferred-module global- globalThis.marked = {- Renderer: class {- link() {- return '<a href="#">x</a>';- }- },- setOptions() {},- parse: (md) => String(md),- };- lateBind();+ const purifier = createDOMPurify(window);+ addHook = vi.spyOn(purifier, 'addHook');+ // eslint-disable-next-line require-atomic-updates -- deliberate late binding after both application modules have loaded.+ globalThis.DOMPurify = purifier;+ // eslint-disable-next-line require-atomic-updates -- deliberate late binding after both application modules have loaded.+ globalThis.marked = new Marked();});afterEach(() => {+ vi.restoreAllMocks();delete globalThis.DOMPurify;delete globalThis.marked;delete window.XSSProtection;@@ -141,94 +29,61 @@ describe('renderMarkdown ensures the tabnabbing hook', () => {'safeCreateElement', 'safeSetTextContent', 'createSafeAlertElement','sanitizeUserInput', 'sanitizeHtml', 'safeUpdateButton','createSafeLoadingOverlay', 'safeSetStyles', 'showSafeAlert'- ].forEach((name) => delete window[name]);+ ].forEach(name => delete window[name]);});- it('a raw-HTML target=_blank anchor in markdown gains rel', () => {- const out = window.ui.renderMarkdown(- 'text <a href="https://example.test" target="_blank">raw link</a> more'- );+ function parse(markdown) {const template = document.createElement('template');- // eslint-disable-next-line no-unsanitized/property -- test harness: output under test- template.innerHTML = out;- const anchor = template.content.querySelector('a[target="_blank"]');- expect(anchor).not.toBeNull();- expect(anchor.getAttribute('rel')).toBe('noopener noreferrer');- });+ // eslint-disable-next-line no-unsanitized/property -- test-only: inspect the actual renderer output.+ template.innerHTML = window.ui.renderMarkdown(markdown);+ return template.content;+ }- it('target survives the ADD_ATTR config that DOMPurify defaults would strip', () => {- const out = window.ui.renderMarkdown(- '<a href="https://example.test" target="popup">named</a>'+ it('isolates a Markdown link on the first render after late binding', () => {+ const root = parse('[source](https://example.test/paper)');+ const anchor = root.querySelector('a');+ expect(anchor.getAttribute('href')).toBe('https://example.test/paper');+ expect(anchor.getAttribute('target')).toBe('_blank');+ expect(anchor.getAttribute('rel').split(/\s+/)).toEqual(+ expect.arrayContaining(['noopener', 'noreferrer']));- const anchor = parseOut(out).querySelector('a');- expect(anchor.getAttribute('target')).toBe('popup');- expect(anchor.getAttribute('rel')).toBe('noopener noreferrer');+ expect(addHook).toHaveBeenCalledTimes(1);});it.each([- ['area', '<map name="m"><area href="https://example.test" target="_blank"></map>'],- ['form', '<form action="https://example.test" target="_blank"></form>'],- ])('a raw-HTML <%s target=_blank> in markdown gains rel', (tag, markdown) => {- const el = parseOut(window.ui.renderMarkdown(markdown)).querySelector(tag);- expect(el).not.toBeNull();- expect(el.getAttribute('target')).toBe('_blank');- expect(el.getAttribute('rel')).toBe('noopener noreferrer');+ '<a href="https://example.test" target="_blank">raw link</a>',+ '<a href="https://example.test" target="popup" rel="opener">named</a>',+ '<map name="m"><area href="https://example.test" target="_blank"></map>',+ '<form action="https://example.test" target="_blank"></form>',+ ])('shows author-supplied HTML as text: %s', markup => {+ const root = parse(markup);+ expect(root.querySelector('a, area, form, input')).toBeNull();+ expect(root.textContent).toContain(markup);});it.each([['name', 'tagName'], ['id', 'tagName'],['name', 'getAttribute'], ['id', 'getAttribute'],['name', 'setAttribute'], ['id', 'setAttribute'],- ])('a raw-HTML <form> whose control %s=%j shadows the built-in still gains rel', (attr, prop) => {- const form = document.createElement('form');- form.setAttribute('action', 'https://evil.test');- form.setAttribute('target', 'popup');- const control = document.createElement('input');- control.setAttribute(attr, prop);- const button = document.createElement('button');- button.textContent = 'go';- form.append(control, button);-- const el = parseOut(window.ui.renderMarkdown(form.outerHTML))- .querySelector('form');-- // The emulated override was live while the hook ran...- expect(shadowedCount).toBe(1);- // ...and the hook still set rel through Element.prototype.- expect(el).not.toBeNull();- expect(el.getAttribute('target')).toBe('popup');- expect(el.getAttribute('rel')).toBe('noopener noreferrer');+ ])('does not create a form with a control %s=%s', (attr, prop) => {+ const markup = `<form action="https://example.test" target="popup"><input ${attr}="${prop}"><button>go</button></form>`;+ const root = parse(markup);+ expect(root.querySelector('form, input, button')).toBeNull();+ expect(root.textContent).toContain(markup);});- it('an existing rel is merged: other tokens kept, opener dropped', () => {- const anchor = parseOut(window.ui.renderMarkdown(- '<a href="https://example.test" target="_blank" rel="nofollow ugc opener">r</a>'- )).querySelector('a');- const tokens = anchor.getAttribute('rel').split(/\s+/);- expect(tokens).toEqual(- expect.arrayContaining(['nofollow', 'ugc', 'noopener', 'noreferrer'])- );- expect(tokens).toHaveLength(4);- expect(tokens).not.toContain('opener');- });-- it('registration stays single across repeated renders', () => {+ it('registers the hook once across repeated renders', () => {for (let i = 0; i < 3; i++) {- window.ui.renderMarkdown('# heading\n\n[a](https://x.test)');+ expect(parse('[source](https://example.test)').querySelector('a')).not.toBeNull();}- expect(- (registeredHooks.afterSanitizeAttributes || []).length- ).toBe(1);+ expect(addHook).toHaveBeenCalledTimes(1);});- it('the marked-missing fallback escapes raw anchors into inert text', () => {- globalThis.marked = undefined;- const markdown =- 'x <a href="https://example.test" target="_blank">raw</a>';- const out = window.ui.renderMarkdown(markdown);- const doc = new window.DOMParser().parseFromString(out, 'text/html');- // No live anchor survives: the raw HTML is shown verbatim as text.- expect(doc.querySelector('a')).toBeNull();- expect(doc.querySelector('pre').textContent).toBe(markdown);+ it('escapes raw anchors when marked is unavailable', () => {+ delete globalThis.marked;+ const markup = 'x <a href="https://example.test" target="_blank">raw</a>';+ const root = parse(markup);+ expect(root.querySelector('a')).toBeNull();+ expect(root.querySelector('pre').textContent).toBe(markup);});});diff --git a/tests/js/security/research-flow-xss.test.js b/tests/js/security/research-flow-xss.test.jsnew file mode 100644index 0000000000..19f1daabcd--- /dev/null+++ b/tests/js/security/research-flow-xss.test.js@@ -0,0 +1,488 @@+/**+ * Defensive output-encoding coverage for the new-research/follow-up flow.+ *+ * innerHTML / insertAdjacentHTML interpolation map (current source lines):+ *+ * components/research.js+ * :259 static rerun-notice markup; no interpolated values.+ * :463 static empty string (model dropdown clear).+ * :535 static empty string (search-engine dropdown clear).+ * :1176 static empty string (provider select clear). Provider value/label are+ * subsequently assigned through option.value / option.textContent at+ * :1181-1182, so neither is an HTML interpolation.+ *+ * research_form.js+ * :272 static empty string (warning clear).+ * :338 warningsHtml assembled at :279-334:+ * :291 actionUrl -> escapeHtml in a double-quoted href attribute.+ * :292 actionLabel -> escapeHtml (text context).+ * :301 dismissKey -> escapeHtml in a data attribute; a delegated click+ * listener reads the decoded value without executable markup.+ * :313 alertClass -> hardcoded; warning.type -> escapeHtml in class.+ * :321 warning.icon -> escapeHtml (text context).+ * :324 warning.title -> escapeHtml (text context).+ * :327 warning.message -> escapeHtml (text context).+ * :329/:331 actionHtml/dismissHtml -> derived fragments above.+ * No numeric values are interpolated.+ *+ * followup.js+ * :91 modalHtml -> raw, trusted same-origin static template response.+ * :201 static CSS literal; no interpolated values.+ * API-displayed parent_summary / available_sources use textContent at+ * :265-266 rather than either HTML sink.+ */++import '@js/config/urls.js';+import '@js/utils/alert-helpers.js';+import '@js/security/xss-protection.js';+import '@js/utils/form-validation.js';+import '@js/components/custom_dropdown.js';+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test, vi } from 'vitest';++const IMG_PAYLOAD = '<img src=x onerror=alert(1)>';+const SCRIPT_PAYLOAD = '<script>alert(1)</script>';+const SVG_PAYLOAD = '"><svg onload=alert(1)>';+const ATTR_PAYLOAD = 'x" onmouseover="alert(1)';+const JAVASCRIPT_URL = 'javascript:alert(1)';+const SPECIAL_VALUES = [+ IMG_PAYLOAD,+ SCRIPT_PAYLOAD,+ SVG_PAYLOAD,+ ATTR_PAYLOAD,+ JAVASCRIPT_URL,+];+const BENIGN_PROVIDER_LABEL = 'Ollama (benign control)';+const START_RESEARCH_URL = '/api/start_research';++const providerOptions = [+ ...SPECIAL_VALUES.map((label, index) => ({+ value: `TEST_PROVIDER_${index}`,+ label,+ is_cloud: false,+ })),+ {+ value: 'OLLAMA',+ label: BENIGN_PROVIDER_LABEL,+ is_cloud: false,+ },+];++const defaultApiBody = {+ status: 'error',+ message: 'stubbed response',+ settings: {},+ providers: {},+ provider_options: providerOptions,+ engine_options: [],+ engines: {},+};++let fetchMock;+let FollowUpResearch;++function jsonResponse(responseBody) {+ return Promise.resolve({+ ok: true,+ status: 200,+ json: () => Promise.resolve(responseBody),+ text: () => Promise.resolve(''),+ });+}++function installResearchPage() {+ document.body.innerHTML = `+ <form id="research-form">+ <div id="research-alert" role="alert" style="display:none"></div>+ <div id="research-error-alert" style="display:none"></div>+ <textarea id="query" name="query"></textarea>+ <div class="ldr-privacy-panel" data-scope="adaptive">+ <i id="ldr-privacy-panel-icon"></i>+ <select id="policy_egress_scope" name="policy_egress_scope">+ <option value="adaptive" selected>Adaptive</option>+ </select>+ <input type="checkbox" id="llm_require_local_endpoint">+ <input type="checkbox" id="embeddings_require_local">+ </div>+ <label class="ldr-mode-option" data-mode="quick">+ <input type="radio" name="research_mode" value="quick" checked>+ </label>+ <button type="button" class="ldr-advanced-options-toggle ldr-open" aria-expanded="true">+ <i class="fas fa-chevron-up"></i><span class="sr-only"></span>+ </button>+ <div class="ldr-advanced-options-panel ldr-expanded" id="advanced-options-panel">+ <select id="model_provider" data-initial-value="OLLAMA">+ <option value="OLLAMA" selected>Ollama</option>+ </select>+ <div class="form-group">+ <div id="model-dropdown">+ <input type="text" id="model">+ <div id="model-dropdown-list"></div>+ </div>+ </div>+ <input type="hidden" id="model_hidden" value="safe-model">+ <button type="button" id="model-refresh"></button>+ <div id="search-engine-dropdown">+ <input type="text" id="search_engine">+ <div id="search-engine-dropdown-list"></div>+ </div>+ <input type="hidden" id="search_engine_hidden" value="searxng">+ <button type="button" id="search_engine-refresh"></button>+ <select id="strategy"><option value="source-based">Source based</option></select>+ <input id="iterations" value="2">+ <input id="questions_per_iteration" value="3">+ </div>+ <button type="submit" id="start-research-btn"><span>Start Research</span></button>+ </form>+ `;+}++function installWarningContainer() {+ document.body.innerHTML = '<div id="research-alert" style="display:none"></div>';+}++function installParentContext() {+ document.body.innerHTML = `+ <section id="parentContext" style="display:none">+ <div id="parentSummary"></div>+ <div id="parentSources"></div>+ </section>+ `;+}++function eventHandlerAttributes(root) {+ const found = [];+ for (const element of root.querySelectorAll('*')) {+ for (const name of element.getAttributeNames()) {+ if (/^on/i.test(name)) found.push(`${element.tagName}[${name}]`);+ }+ }+ return found;+}++function expectNoLiveMarkup(root) {+ expect(root.querySelectorAll('script, img, svg')).toHaveLength(0);+ expect(eventHandlerAttributes(root)).toEqual([]);+ for (const link of root.querySelectorAll('a[href]')) {+ expect(link.getAttribute('href') ?? '').not.toMatch(/^\s*javascript:/i);+ }+}++function expectNonEmpty(container) {+ expect(container).not.toBeNull();+ expect(container.textContent.trim().length).toBeGreaterThan(0);+}++async function renderResearchStatus(message) {+ const query = document.getElementById('query');+ const model = document.getElementById('model_hidden');+ const button = document.getElementById('start-research-btn');+ const topAlert = document.getElementById('research-alert');+ const anchoredAlert = document.getElementById('research-error-alert');++ query.value = 'Benign research query';+ model.value = 'safe-model';+ button.disabled = false;+ topAlert.replaceChildren();+ anchoredAlert.replaceChildren();+ topAlert.style.display = 'none';+ anchoredAlert.style.display = 'none';+ document.querySelectorAll('.ldr-loading-overlay').forEach((overlay) => overlay.remove());++ fetchMock.mockImplementation((requestUrl) => {+ if (requestUrl === START_RESEARCH_URL) {+ return jsonResponse({ status: 'error', message });+ }+ return jsonResponse(defaultApiBody);+ });++ document.getElementById('research-form').dispatchEvent(+ new Event('submit', { bubbles: true, cancelable: true })+ );++ await vi.waitFor(() => expect(topAlert.textContent).toContain(message));+ return { topAlert, anchoredAlert };+}++async function renderParentContext(summary, sources) {+ installParentContext();+ const followUp = new FollowUpResearch();+ followUp.parentResearchId = 'parent-research-1';+ fetchMock.mockImplementation(() => jsonResponse({+ success: true,+ parent_summary: summary,+ available_sources: sources,+ }));++ await followUp.loadParentContext();+ return document.getElementById('parentContext');+}++beforeAll(async () => {+ fetchMock = vi.fn(() => jsonResponse(defaultApiBody));+ globalThis.fetch = fetchMock;+ window.api = { getCsrfToken: () => 'test-csrf' };+ window.RESEARCH_STATUS = { QUEUED: 'queued', IN_PROGRESS: 'in_progress' };++ await import('@js/research_form.js');+ await import('@js/followup.js');+ FollowUpResearch = window.FollowUpResearch;+});++afterAll(() => {+ sessionStorage.clear();+ document.head.querySelector('#followup-modal-styles')?.remove();+ delete window.api;+ delete window.RESEARCH_STATUS;+ delete globalThis.fetch;+});++describe('components/research.js rendering', () => {+ let pageListeners;++ beforeEach(async () => {+ installResearchPage();+ fetchMock.mockImplementation(() => jsonResponse(defaultApiBody));+ sessionStorage.setItem('rerunConfig', JSON.stringify({ query: IMG_PAYLOAD }));+ vi.resetModules();+ pageListeners = [];+ const initializers = [];+ const addEventListener = document.addEventListener.bind(document);+ const listenerSpy = vi.spyOn(document, 'addEventListener').mockImplementation(+ (type, listener, options) => {+ if (type === 'DOMContentLoaded') {+ initializers.push(listener);+ return;+ }+ pageListeners.push([type, listener, options]);+ addEventListener(type, listener, options);+ }+ );+ try {+ // Reload the page's closure as a navigation would. Only run its+ // initializer; the other page modules have separate fixtures.+ await import('@js/components/research.js');+ expect(initializers.length).toBeGreaterThan(0);+ for (const initialize of initializers) {+ initialize.call(document, new Event('DOMContentLoaded'));+ }+ await vi.waitFor(() => {+ expect(document.querySelectorAll('#model_provider option')).toHaveLength(+ providerOptions.length+ );+ expect(document.getElementById('research-alert').textContent)+ .toContain('Re-running previous research');+ });+ } finally {+ listenerSpy.mockRestore();+ }+ });++ afterEach(() => {+ for (const [type, listener, options] of pageListeners) {+ document.removeEventListener(type, listener, options);+ }+ });++ test('keeps rerun metadata out of its static innerHTML notice', () => {+ const alertContainer = document.getElementById('research-alert');++ expectNonEmpty(alertContainer);+ expect(alertContainer.textContent).toContain('Re-running previous research');+ expect(document.getElementById('query').value).toBe(IMG_PAYLOAD);+ expect(alertContainer.textContent).not.toContain(IMG_PAYLOAD);+ expectNoLiveMarkup(document.body);+ });++ test('renders special-character provider labels through textContent', () => {+ const providerSelect = document.getElementById('model_provider');++ expectNonEmpty(providerSelect);+ for (const specialValue of SPECIAL_VALUES) {+ expect(providerSelect.textContent).toContain(specialValue);+ }+ expect(providerSelect.textContent).toContain(BENIGN_PROVIDER_LABEL);+ expectNoLiveMarkup(document.body);+ });++ test.each(SPECIAL_VALUES)(+ 'renders a server status value as inert visible text: %s',+ async (specialValue) => {+ const { topAlert, anchoredAlert } = await renderResearchStatus(specialValue);++ expectNonEmpty(topAlert);+ expectNonEmpty(anchoredAlert);+ expect(topAlert.textContent).toContain(specialValue);+ expect(anchoredAlert.textContent).toContain(specialValue);+ expectNoLiveMarkup(document.body);+ }+ );++ test('preserves a benign server status message', async () => {+ const benignMessage = 'Research could not start; choose another engine.';+ const { topAlert, anchoredAlert } = await renderResearchStatus(benignMessage);++ expectNonEmpty(topAlert);+ expectNonEmpty(anchoredAlert);+ expect(topAlert.textContent).toContain(benignMessage);+ expect(anchoredAlert.textContent).toContain(benignMessage);+ expectNoLiveMarkup(document.body);+ });+});++describe('research_form.js warning rendering', () => {+ beforeEach(() => {+ installWarningContainer();+ });++ test('renders warning text and an internal quote-bearing href without live markup', () => {+ const internalUrl = `/${ATTR_PAYLOAD}`;+ window.displayWarnings([{+ type: 'configuration_warning',+ icon: IMG_PAYLOAD,+ title: SCRIPT_PAYLOAD,+ message: SVG_PAYLOAD,+ actionUrl: internalUrl,+ actionLabel: ATTR_PAYLOAD,+ dismissKey: null,+ }]);++ const alertContainer = document.getElementById('research-alert');+ const action = alertContainer.querySelector('a.ldr-alert-action');+ expectNonEmpty(alertContainer);+ expect(alertContainer.textContent).toContain(IMG_PAYLOAD);+ expect(alertContainer.textContent).toContain(SCRIPT_PAYLOAD);+ expect(alertContainer.textContent).toContain(SVG_PAYLOAD);+ expect(alertContainer.textContent).toContain(ATTR_PAYLOAD);+ expect(action.getAttribute('href')).toBe(internalUrl);+ expectNoLiveMarkup(alertContainer);+ });++ test('keeps a quote-bearing warning type inside the class attribute', () => {+ window.displayWarnings([{+ type: ATTR_PAYLOAD,+ icon: '!',+ title: 'Attribute boundary control',+ message: ATTR_PAYLOAD,+ dismissKey: null,+ }]);++ const alertContainer = document.getElementById('research-alert');+ const banner = alertContainer.querySelector('.warning-banner');+ expectNonEmpty(alertContainer);+ expect(alertContainer.textContent).toContain(ATTR_PAYLOAD);+ expect(banner.getAttribute('class')).toContain(`warning-${ATTR_PAYLOAD}`);+ expect(banner.hasAttribute('onmouseover')).toBe(false);+ expectNoLiveMarkup(alertContainer);+ });++ test('rejects javascript action URLs while retaining visible warning text', () => {+ window.displayWarnings([{+ type: 'configuration_warning',+ icon: '!',+ title: 'Unsafe destination rejected',+ message: JAVASCRIPT_URL,+ actionUrl: JAVASCRIPT_URL,+ actionLabel: 'Open destination',+ dismissKey: null,+ }]);++ const alertContainer = document.getElementById('research-alert');+ expectNonEmpty(alertContainer);+ expect(alertContainer.textContent).toContain(JAVASCRIPT_URL);+ expect(alertContainer.querySelector('a')).toBeNull();+ expectNoLiveMarkup(alertContainer);+ });++ // Regression coverage: dismissKey stays in a data attribute and is handled+ // by a delegated click listener instead of executable inline JavaScript.+ test('does not create event-handler attributes for a hostile dismiss key', () => {+ window.displayWarnings([{+ type: 'configuration_warning',+ icon: '!',+ title: 'Dismissible warning',+ message: ATTR_PAYLOAD,+ dismissKey: ATTR_PAYLOAD,+ }]);++ const alertContainer = document.getElementById('research-alert');+ const dismissButton = alertContainer.querySelector('button');+ expectNonEmpty(alertContainer);+ expect(alertContainer.textContent).toContain(ATTR_PAYLOAD);+ expect(dismissButton).not.toBeNull();+ expectNoLiveMarkup(alertContainer);+ });++ test('preserves a benign warning and internal action', () => {+ window.displayWarnings([{+ type: 'searxng_recommendation',+ icon: 'i',+ title: 'Use a local search engine',+ message: 'SearXNG is available for private searches.',+ actionUrl: '/settings',+ actionLabel: 'Open settings',+ dismissKey: null,+ }]);++ const alertContainer = document.getElementById('research-alert');+ const action = alertContainer.querySelector('a.ldr-alert-action');+ expectNonEmpty(alertContainer);+ expect(alertContainer.textContent).toContain('Use a local search engine');+ expect(action.textContent).toContain('Open settings');+ expect(action.getAttribute('href')).toBe('/settings');+ expectNoLiveMarkup(alertContainer);+ });+});++describe('followup.js displayed parent context', () => {+ test.each(SPECIAL_VALUES)(+ 'renders parent summary and source values as inert visible text: %s',+ async (specialValue) => {+ const parentContext = await renderParentContext(specialValue, specialValue);+ const summary = document.getElementById('parentSummary');+ const sources = document.getElementById('parentSources');++ expectNonEmpty(parentContext);+ expect(summary.textContent).toBe(specialValue);+ expect(sources.textContent).toBe(specialValue);+ expect(parentContext.style.display).toBe('block');+ expectNoLiveMarkup(parentContext);+ }+ );++ test('preserves benign parent context values', async () => {+ const parentContext = await renderParentContext(+ 'A benign parent summary.',+ '12 sources'+ );++ expectNonEmpty(parentContext);+ expect(document.getElementById('parentSummary').textContent)+ .toBe('A benign parent summary.');+ expect(document.getElementById('parentSources').textContent).toBe('12 sources');+ expectNoLiveMarkup(parentContext);+ });++ test('loads the trusted static modal template and hardcoded styles normally', async () => {+ document.body.replaceChildren();+ document.head.querySelector('#followup-modal-styles')?.remove();+ fetchMock.mockImplementation(() => Promise.resolve({+ ok: true,+ status: 200,+ text: () => Promise.resolve(`+ <div id="followUpModal">+ <p>Benign follow-up form</p>+ <button id="startFollowUpBtn" type="button">Start follow-up</button>+ </div>+ `),+ }));+ const followUp = new FollowUpResearch();++ await followUp.createModal();++ const modal = document.getElementById('followUpModal');+ expectNonEmpty(modal);+ expect(modal.textContent).toContain('Benign follow-up form');+ expect(document.getElementById('followup-modal-styles')).not.toBeNull();+ expectNoLiveMarkup(document.body);+ });+});diff --git a/tests/js/security/results-render-xss.test.js b/tests/js/security/results-render-xss.test.jsnew file mode 100644index 0000000000..eb28c62187--- /dev/null+++ b/tests/js/security/results-render-xss.test.js@@ -0,0 +1,491 @@+/**+ * Security regression tests for the XSS surface of components/results.js —+ * the results page's primary render surface for LLM/web-derived report+ * content, metadata and error strings.+ *+ * Interpolation map (results.js @ commit under test):+ * :148 loading spinner innerHTML — static string, no interpolation+ * :598 data.html via window.sanitizeHtml — DOMPurify SANITIZE_CONFIG+ * (xss-protection.js:329)+ * :602 data.html via window.escapeHtml — escaped (& < > " ' /)+ * :606 data.html via textContent — inert by construction+ * :632 content via window.ui.renderMarkdown — delegated to services/ui.js+ * (marked -> DOMPurify allowlist ->+ * hardening; covered end-to-end+ * here with the real pipeline)+ * :637/:644 fallback `<pre>${escaped}</pre>` — (window.escapeHtml ||+ * escapeHtmlFallback @ :21)+ * :665/:670 showError alert innerHTML — escaped message, hardcoded+ * href="/" @ :673+ * :216-:292, :373-:572 query/date/mode — textContent only (inert)+ * :248-:259 duration — parseInt + isNaN guard (numeric)+ * :857/:891/:909 pdf button innerHTML — static strings+ * No data-driven raw innerHTML interpolation exists; URL writes all go+ * through URLValidator.safeAssign with URLBuilder-built paths.+ *+ * Driving the real paths: results.js is an IIFE with no exports that calls+ * initializeResults() at import time (happy-dom reports readyState+ * 'complete'), so each mount installs fresh DOM + fetch mocks, resets the+ * module registry, and dynamically imports the component. The REAL+ * xss-protection.js escaper and the REAL services/ui.js renderMarkdown+ * pipeline (marked + katex + DOMPurify) are installed so assertions exercise+ * production escaping end-to-end, mirroring+ * tests/js/security/markdown-render-xss.test.js.+ */++import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest';++const RESEARCH_ID = 'research-123';++const RESULTS_MARKUP = `+ <h1 id="result-query"></h1>+ <p id="result-date"></p>+ <p id="result-mode"></p>+ <div id="results-content"></div>+ <button id="export-markdown-btn" disabled></button>+ <button id="download-pdf-btn" disabled></button>+ <button id="view-metrics-btn"></button>+`;++const TEXT_PAYLOADS = [+ '<img src=x onerror=alert(1)>',+ '<script>alert(2)</script>',+ '"><svg onload=alert(3)>',+];+const ATTR_PAYLOAD = 'x" onmouseover="alert(1)';++let realUi;+let realEscapeHtml;+let realSanitizeHtml;++beforeAll(async () => {+ // --- happy-dom shims required by DOMPurify -------------------------------+ // Copied from tests/js/security/markdown-render-xss.test.js: happy-dom's+ // NodeIterator truncates on removal, its Node.prototype#nodeName base+ // getter returns "" for every tag, and parsed <math> never gets the+ // MathML namespace. All three are captured by dompurify at module-eval+ // time, so the shims must be installed BEFORE the dynamic import below.++ document.createNodeIterator = function(root, whatToShow) {+ const mask = whatToShow === undefined || whatToShow === null+ ? 0xffffffff+ : whatToShow;+ const nodes = [];+ (function collect(node) {+ if (mask & (1 << (node.nodeType - 1))) {+ nodes.push(node);+ }+ for (let i = 0; i < node.childNodes.length; i++) {+ collect(node.childNodes[i]);+ }+ })(root);+ let index = 0;+ return {+ nextNode() {+ return index < nodes.length ? nodes[index++] : null;+ },+ previousNode() {+ return index > 0 ? nodes[--index] : null;+ },+ };+ };++ Object.defineProperty(window.Node.prototype, 'nodeName', {+ configurable: true,+ get() {+ switch (this.nodeType) {+ case 1: return this.tagName;+ case 2: return this.name;+ case 3: return '#text';+ case 4: return '#cdata-section';+ case 7: return this.target;+ case 8: return '#comment';+ case 9: return '#document';+ case 10: return '#document-type';+ case 11: return '#document-fragment';+ default: return '';+ }+ },+ });++ const MATHML_TAG_NAMES = new Set([+ 'math', 'semantics', 'annotation', 'annotation-xml', 'maction',+ 'maligngroup', 'malignmark', 'menclose', 'merror', 'mfenced',+ 'mfrac', 'mglyph', 'mi', 'mlabeledtr', 'mlongdiv', 'mmultiscripts',+ 'mn', 'mo', 'mover', 'mpadded', 'mphantom', 'mprescripts', 'mroot',+ 'mrow', 'ms', 'mscarries', 'msgroup', 'msline', 'mspace', 'msqrt',+ 'msrow', 'mstack', 'mstyle', 'msub', 'msubsup', 'msup', 'mtable',+ 'mtd', 'mtext', 'mtr', 'munder', 'munderover', 'none',+ ]);+ const MATHML_NAMESPACE_URI = 'http://www.w3.org/1998/Math/MathML';+ const originalNamespaceURI = Object.getOwnPropertyDescriptor(+ window.Element.prototype, 'namespaceURI',+ );+ Object.defineProperty(window.Element.prototype, 'namespaceURI', {+ configurable: true,+ get() {+ if (typeof this.tagName === 'string'+ && MATHML_TAG_NAMES.has(this.tagName.toLowerCase())) {+ return MATHML_NAMESPACE_URI;+ }+ return originalNamespaceURI && originalNamespaceURI.get+ ? originalNamespaceURI.get.call(this)+ : undefined;+ },+ });++ // Stubs for the URL globals results.js reaches at init/click time,+ // assigned before any await (require-atomic-updates).+ window.URLBuilder = {+ extractResearchIdFromPattern: () => RESEARCH_ID,+ detailsPage: (id) => `/research/details/${id}`,+ };+ window.URLValidator = {+ safeAssign: (obj, prop, value) => { obj[prop] = value; },+ };+ window.URLS = { PAGES: { HISTORY: '/history' } };++ // --- production globals --------------------------------------------------+ // Real escaper/sanitizer (window.escapeHtml, window.sanitizeHtml) and the+ // real renderMarkdown pipeline (window.ui), as loaded by base.html.+ await import('@js/security/xss-protection.js');++ const { Marked } = await import('marked');+ const markedKatex = (await import('marked-katex-extension')).default;+ const DOMPurify = (await import('dompurify')).default;+ const markedInstance = new Marked();+ markedInstance.use(markedKatex({+ throwOnError: false,+ errorColor: 'currentColor',+ }));+ globalThis.marked = markedInstance;+ globalThis.DOMPurify = DOMPurify;++ await import('@js/services/ui.js');+++ realUi = window.ui;+ realEscapeHtml = window.escapeHtml;+ realSanitizeHtml = window.sanitizeHtml;+});++afterAll(() => {+ delete globalThis.marked;+ delete globalThis.DOMPurify;+});++afterEach(() => {+ // Tests delete/undefine these to isolate fallback paths; restore the+ // production globals for the next test.+ window.ui = realUi;+ window.escapeHtml = realEscapeHtml;+ window.sanitizeHtml = realSanitizeHtml;+});++function okResponse(data) {+ return { ok: true, json: () => Promise.resolve(data) };+}++/**+ * Mount the real results component against a fresh DOM and a fetch mock that+ * serves `payload` from /api/report/:id (or rejects with `error`), then wait+ * for the loading spinner to be replaced by rendered output.+ */+async function mountResults({ payload, error } = {}) {+ // eslint-disable-next-line no-unsanitized/property -- test fixture: hardcoded static template with no interpolated values.+ document.body.innerHTML = RESULTS_MARKUP;+ globalThis.fetch = vi.fn((url) => {+ if (url === `/api/report/${RESEARCH_ID}`) {+ return error ? Promise.reject(error) : Promise.resolve(okResponse(payload));+ }+ if (url === `/metrics/api/research/${RESEARCH_ID}/context-overflow`) {+ return Promise.resolve({ ok: false, status: 404 });+ }+ return Promise.reject(new Error(`Unexpected fetch: ${url}`));+ });++ // happy-dom reports readyState 'complete', so the IIFE runs+ // initializeResults() synchronously at import: reset the registry and+ // re-import so each mount captures this test's DOM and fetch mock.+ vi.resetModules();+ await import('@js/components/results.js');++ const container = document.getElementById('results-content');+ await vi.waitFor(() => {+ expect(container.innerHTML).not.toContain('fa-spinner');+ });+ return container;+}++/** Names of any inline event-handler attributes (on*) anywhere under root. */+function eventHandlerAttributes(root) {+ const found = [];+ for (const el of root.querySelectorAll('*')) {+ for (const name of el.getAttributeNames()) {+ if (/^on/i.test(name)) found.push(`${el.tagName}[${name}]`);+ }+ }+ return found;+}++/** Non-vacuity guard: the container must actually contain rendered output. */+function expectRendered(container) {+ expect(container.textContent.trim().length).toBeGreaterThan(0);+}++describe('results.js renderResults() — fallback plaintext path (renderMarkdown unavailable)', () => {+ it('escapes text-context payloads in report content as visible text', async () => {+ window.ui = undefined;+ for (const payload of TEXT_PAYLOADS) {+ const container = await mountResults({ payload: { content: `Report intro.\n\n${payload}` } });++ expect(container.querySelectorAll('img, script, svg, iframe')).toHaveLength(0);+ expect(eventHandlerAttributes(container)).toEqual([]);+ expect(container.querySelector('pre')).not.toBeNull();+ expect(container.textContent).toContain(payload);+ expect(container.innerHTML).toContain('<');+ expectRendered(container);+ }+ });++ it('escapes hostile payloads arriving through every findAndRenderContent() field', async () => {+ window.ui = undefined;+ const p = TEXT_PAYLOADS[0];+ const shapes = [+ { markdown: p }, // renderResults(data.markdown)+ { text: p }, // renderResults(data.text)+ { summary: p }, // renderResults(data.summary)+ { report: p }, // findAndRenderContent: data.report+ { results: [p, 'second'] }, // renderResults: array join+ { results: p }, // renderResults: string results+ { research: { content: p } }, // nested research.content+ { results: { content: p } }, // results.content+ { output: p }, // contentProps fallback loop+ { unknown_field: p }, // last resort: JSON.stringify(data)+ p, // plain-string API response+ ];+ for (const payload of shapes) {+ const container = await mountResults({ payload });++ expect(container.querySelectorAll('img, script, svg, iframe')).toHaveLength(0);+ expect(eventHandlerAttributes(container)).toEqual([]);+ expect(container.textContent).toContain(p);+ expectRendered(container);+ }+ });++ it('stays safe when only the local escapeHtmlFallback is available (xss-protection.js failed to load)', async () => {+ window.ui = undefined;+ delete window.escapeHtml;+ delete window.sanitizeHtml;++ const container = await mountResults({+ payload: { content: `Notes: ${ATTR_PAYLOAD} and <img src=x onerror=alert(1)>` },+ });++ // results.js:637 resolves escapeHtmlFallback (results.js:21), which+ // escapes & < > " ' — the quote escaping keeps the payload inert.+ expect(container.querySelectorAll('img, script, svg, iframe')).toHaveLength(0);+ expect(eventHandlerAttributes(container)).toEqual([]);+ expect(container.textContent).toContain('<img src=x onerror=alert(1)>');+ expect(container.textContent).toContain(ATTR_PAYLOAD);+ expectRendered(container);+ });++ it('keeps attribute-breakout payloads inert (results.js renders no title/tooltip/aria interpolations)', async () => {+ window.ui = undefined;+ const container = await mountResults({ payload: { content: `Research notes: ${ATTR_PAYLOAD}` } });++ expect(container.querySelector('[onmouseover]')).toBeNull();+ expect(eventHandlerAttributes(container)).toEqual([]);+ expect(container.textContent).toContain(ATTR_PAYLOAD);+ expectRendered(container);+ });++ it('escapes hostile error messages in showError() on the fetch-rejection path', async () => {+ window.ui = undefined;+ const container = await mountResults({+ error: new Error('HTTP error <img src=x onerror=alert(1)><script>alert(2)</script>'),+ });++ expect(container.querySelector('.alert-danger')).not.toBeNull();+ expect(container.querySelectorAll('img, script, svg')).toHaveLength(0);+ expect(eventHandlerAttributes(container)).toEqual([]);+ expect(container.textContent).toContain('<img src=x onerror=alert(1)>');+ // The only link in the error state is the hardcoded safe one.+ const back = container.querySelector('a');+ expect(back.getAttribute('href')).toBe('/');+ expectRendered(container);+ });+});++describe('results.js renderResults() — data.html branches', () => {+ it('sanitizes data.html through the real window.sanitizeHtml (DOMPurify allowlist)', async () => {+ const container = await mountResults({+ payload: {+ html: '<p>keep this</p><img src=x onerror=alert(1)><script>alert(2)</script>'+ + '<a href="javascript:alert(1)" onmouseover="alert(1)">link</a>',+ },+ });++ expect(container.querySelectorAll('img, script, svg, iframe')).toHaveLength(0);+ expect(eventHandlerAttributes(container)).toEqual([]);+ for (const a of container.querySelectorAll('a')) {+ // A stripped href (null) is the safe outcome — coerce before matching.+ expect(a.getAttribute('href') ?? '').not.toMatch(/^(javascript|data|vbscript):/i);+ }+ expect(container.textContent).toContain('keep this');+ expectRendered(container);+ });++ it('keeps template-literal-shaped text intact instead of blanking it (SAFE_FOR_TEMPLATES: false)', async () => {+ // Regression test: SANITIZE_CONFIG's shared default is+ // SAFE_FOR_TEMPLATES: true, which makes DOMPurify blank out any+ // text node matching mustache/ERB/template-literal syntax+ // (`}}`, `${...}`, `%>`). results.js's call site overrides that+ // with { SAFE_FOR_TEMPLATES: false } (services/ui.js's safeSetHTML+ // does too) specifically so report content quoting JSON or a shell+ // `${VAR}` example survives. Reverting that override to the shared+ // default's SAFE_FOR_TEMPLATES: true would blank the payload below+ // but pass every other test in this describe block, since none of+ // them assert on `}}`-shaped text.+ const container = await mountResults({+ payload: { html: '<p>see the {{ config }} block</p>' },+ });++ expect(container.textContent).toContain('{{ config }}');+ expectRendered(container);+ });++ it('escapes data.html as text when only window.escapeHtml is available', async () => {+ delete window.sanitizeHtml;+ const container = await mountResults({+ payload: { html: '<img src=x onerror=alert(1)><b>bold</b>' },+ });++ expect(container.querySelectorAll('img, b')).toHaveLength(0);+ expect(container.innerHTML).toContain('<img');+ expect(container.textContent).toContain('<img src=x onerror=alert(1)>');+ expectRendered(container);+ });++ it('renders data.html via textContent when no sanitizer is available at all', async () => {+ delete window.sanitizeHtml;+ delete window.escapeHtml;+ const container = await mountResults({ payload: { html: TEXT_PAYLOADS[0] } });++ expect(container.querySelectorAll('img, script, svg')).toHaveLength(0);+ expect(container.children).toHaveLength(0); // pure text node, no elements+ expect(container.textContent).toBe(TEXT_PAYLOADS[0]);+ });+});++describe('results.js renderResults() — markdown path (real marked + DOMPurify pipeline)', () => {+ it('sanitizes raw hostile HTML embedded in markdown content', async () => {+ const container = await mountResults({+ payload: {+ content: '# Heading ok\n\n<img src=x onerror=alert(1)>\n\n<script>alert(2)</script>'+ + '\n\n"><svg onload=alert(3)>\n\nBody text.',+ },+ });++ expect(container.querySelectorAll('img, script, svg, iframe')).toHaveLength(0);+ expect(eventHandlerAttributes(container)).toEqual([]);+ expect(container.querySelector('.ldr-markdown-content h1').textContent).toBe('Heading ok');+ expectRendered(container);+ });++ it('never renders javascript:/data:/vbscript: hrefs from markdown content', async () => {+ const container = await mountResults({+ payload: {+ content: [+ '[js](javascript:alert(1))',+ '[data](data:text/html,<script>alert(1)</script>)',+ '[vb](vbscript:alert(1))',+ '<a href="javascript:alert(1)">raw</a>',+ '[ok](https://example.com/safe)',+ ].join('\n'),+ },+ });++ const anchors = container.querySelectorAll('a[href]');+ expect(anchors.length).toBeGreaterThan(0);+ for (const a of anchors) {+ expect(a.getAttribute('href')).not.toMatch(/^(javascript|data|vbscript):/i);+ }+ expect(container.querySelector('a[href="https://example.com/safe"]')).not.toBeNull();+ expectRendered(container);+ });++ it('renders a benign report intact with clickable safe links and populated metadata', async () => {+ const container = await mountResults({+ payload: {+ content: '# Quarterly AI Report\n\n**Key finding**: models improved.'+ + '\n\n[Read the source](https://example.com/paper).',+ metadata: {+ query: 'Latest AI advances',+ mode: 'quick',+ created_at: '2026-01-02T03:04:05Z',+ },+ },+ });++ expect(container.querySelector('.ldr-markdown-content h1').textContent).toBe('Quarterly AI Report');+ const link = container.querySelector('a[href="https://example.com/paper"]');+ expect(link).not.toBeNull();+ expect(link.getAttribute('target')).toBe('_blank');+ expect(link.getAttribute('rel')).toContain('noopener');+ expect(document.getElementById('result-query').textContent).toBe('Latest AI advances');+ expect(document.getElementById('result-mode').textContent).toBe('Quick Summary');+ expect(document.getElementById('result-date').textContent).not.toBe('');+ // Real load path completed: export buttons were re-enabled.+ expect(document.getElementById('export-markdown-btn').disabled).toBe(false);+ expectRendered(container);+ });+});++describe('results.js metadata population — textContent-only surface', () => {+ it('renders hostile API metadata (query/mode/title/duration) as inert text', async () => {+ window.ui = undefined;+ const container = await mountResults({+ payload: {+ content: 'benign report body',+ metadata: {+ query: TEXT_PAYLOADS[0],+ title: '<script>alert(2)</script>',+ mode: '"><svg onload=alert(3)>',+ created_at: '<img src=x onerror=alert(4)>',+ duration: '<script>alert(5)</script>',+ },+ },+ });++ const query = document.getElementById('result-query');+ expect(query.textContent).toBe(TEXT_PAYLOADS[0]);+ expect(query.children).toHaveLength(0);++ const mode = document.getElementById('result-mode');+ expect(mode.children).toHaveLength(0);+ expect(mode.textContent).toContain('<svg onload=alert(3)>');++ const date = document.getElementById('result-date');+ expect(date.children).toHaveLength(0);+ expect(date.textContent).not.toContain('<img');+ // Hostile duration fails parseInt -> NaN -> no suffix is appended.++ expect(document.querySelectorAll('#result-query img, #result-query script, #result-mode svg, #result-date img')).toHaveLength(0);+ expectRendered(container);+ });++ it('keeps the query extracted from a hostile content heading inert (populateMetadata fallback)', async () => {+ window.ui = undefined;+ const container = await mountResults({+ payload: { content: `# ${TEXT_PAYLOADS[0]}\n\nbody text` },+ });++ const query = document.getElementById('result-query');+ expect(query.textContent).toBe(TEXT_PAYLOADS[0]);+ expect(query.children).toHaveLength(0);+ expectRendered(container);+ });+});diff --git a/tests/js/security/settings-render-xss.test.js b/tests/js/security/settings-render-xss.test.jsindex a1b149ca8b..274f5a7c61 100644--- a/tests/js/security/settings-render-xss.test.js+++ b/tests/js/security/settings-render-xss.test.js@@ -24,6 +24,9 @@ const SPECIAL_JSON_PROPERTY = '__proto__';const REDACTED_KEY = 'app.x"onfocus="alert(5).api_key';const COLLIDING_DOTTED_KEY = 'app.collision.probe';const COLLIDING_DASHED_KEY = 'app.collision-probe';+const TOP_LEVEL_SETTING_KEY = 'local_search_chunk_size';+const OPTION_LABEL = '<img src=x onerror=alert(7)>';+const RAW_SECRET = 'sk-test-LEAKED-SECRET-DO-NOT-RENDER-9d8f7a';function setting(name, value, uiElement = 'text', extra = {}) {return {@@ -46,6 +49,7 @@ function payload() {[REDACTED_KEY]: setting('Redacted Key', '[REDACTED]'),[JSON_SETTING_KEY]: setting('JSON Key', JSON.stringify({[JSON_PROPERTY]: 'old value',+ "x') ;alert(1)//": 'iteration','<img src=x onerror=alert(6)>': true,}), 'json'),[SPECIAL_JSON_SETTING_KEY]: setting('Special JSON Key', JSON.stringify({@@ -54,6 +58,19 @@ function payload() {}), 'json'),[COLLIDING_DOTTED_KEY]: setting('Dotted Key', 'dotted'),[COLLIDING_DASHED_KEY]: setting('Dashed Key', 'dashed'),+ [TOP_LEVEL_SETTING_KEY]: setting('Top-level key', 512, 'number'),+ 'app.choose_engine': setting('Hostile Engine Label', CATEGORY, 'select', {+ options: [+ { value: CATEGORY, label: OPTION_LABEL },+ { value: 'searxng', label: 'SearXNG (control)' },+ ],+ }),+ 'llm.api_key_redacted': setting('API Key (masked)', '[REDACTED]', 'password', {+ category: 'llm_parameters',+ }),+ 'llm.api_key_raw': setting('API Key (raw)', RAW_SECRET, 'password', {+ category: 'llm_parameters',+ }),'constructor.alpha': setting('Prototype Prefix A', 'a', 'text', {category: 'general',}),@@ -153,6 +170,7 @@ it('round-trips hostile keys as data with distinct selector-safe IDs', async ()const dotted = inputs.find(input => input.name === COLLIDING_DOTTED_KEY);const dashed = inputs.find(input => input.name === COLLIDING_DASHED_KEY);const benign = document.getElementById('setting-app-benign_control');+ const topLevel = inputs.find(input => input.name === TOP_LEVEL_SETTING_KEY);expect(hostile).toBeDefined();expect(hostile.closest('.ldr-settings-item').dataset.key).toBe(SETTING_KEY);for (const attribute of ['min', 'max', 'step']) {@@ -162,6 +180,7 @@ it('round-trips hostile keys as data with distinct selector-safe IDs', async ()expect(redacted?.dataset.redacted).toBe('true');expect(dotted?.id).not.toBe(dashed?.id);expect(benign?.value).toBe('benign');+ expect(topLevel?.id).toBe(`setting-${TOP_LEVEL_SETTING_KEY}`);for (const input of [hostile, redacted, dotted, dashed]) {expect(input.id).toMatch(/^[a-z][\w-]*$/i);}@@ -248,3 +267,32 @@ it('treats prototype-like legacy prefixes as setting metadata', async () => {.querySelector('.ldr-settings-section-title').textContent.trim()).toBe('Constructor General');});+++it('renders hostile select option labels and values as inert text', async () => {+ const content = await renderSettings();+ const select = document.getElementById('setting-app-choose_engine');+ expect(select?.tagName).toBe('SELECT');+ const options = Array.from(select.options);+ expect(options.map(option => [option.value, option.textContent])).toEqual([+ [CATEGORY, OPTION_LABEL],+ ['searxng', 'SearXNG (control)'],+ ]);+ expect(select.querySelector('img, svg, script')).toBeNull();+ expect(onAttributes(content)).toEqual([]);+});++it('renders password inputs empty for both redacted and raw stored values', async () => {+ await renderSettings();+ for (const id of ['setting-llm-api_key_redacted', 'setting-llm-api_key_raw']) {+ const input = document.getElementById(id);+ expect(input).not.toBeNull();+ expect(input.type).toBe('password');+ expect(input.value).toBe('');+ expect(input.getAttribute('value')).toBe('');+ expect(input.getAttribute('placeholder')).toBe('(saved — type to change)');+ expect(input.getAttribute('autocomplete')).toBe('new-password');+ expect(input.outerHTML).not.toContain('[REDACTED]');+ }+ expect(document.body.innerHTML).not.toContain(RAW_SECRET);+});diff --git a/tests/js/security/socket-events-xss.test.js b/tests/js/security/socket-events-xss.test.jsnew file mode 100644index 0000000000..002086e7ab--- /dev/null+++ b/tests/js/security/socket-events-xss.test.js@@ -0,0 +1,236 @@+/**+ * Security tests for services/socket.js — socket-event -> DOM surface.+ *+ * socket.js registers handlers for server-pushed Socket.IO events whose+ * payloads are indirectly untrusted (engine names and progress/log messages+ * originate from web-search results and LLM output). This file fires each+ * handler with hostile payloads and asserts inertness at the real sink.+ *+ * Sink map (verified against socket.js source):+ * - 'search_engine_selected' (:116) -> window.addConsoleLog (:127)+ * - 'research_progress_<id>' (:203) -> handleProgressUpdate ->+ * window.addConsoleLog at :302 (engine path), :372 (progress_log+ * items), :425 (log_entry), :451 (message/status path)+ * - 'connect_error' (:100), 'error' (:156), 'disconnect' (:138),+ * 'reconnect' (:147), 'reconnect_attempt' (:152) -> SafeLogger only;+ * no DOM writes (asserted below as payload-received + untouched DOM).+ *+ * In production window.addConsoleLog is logpanel.js's function. This suite+ * isolates socket.js's standalone DOM fallback by clearing its routing+ * connector. With the socket's own connector still installed, current main+ * deliberately drops entries instead of recursing. Clearing it here lets the+ * real fallback sink run so its output encoding can be checked directly.+ */++// Static import is safe: module scope only schedules a 100ms auto-init that+// no-ops off research pages. Globals below are installed before anything+// fires. Mirrors the import style of tests/js/services/api.test.js.+import '@js/services/socket.js';++// Registered socket event handlers, captured by the fake socket.io client.+const registeredHandlers = new Map();+let fakeSocket;++// window.escapeHtml — identical implementation to escapeHtmlFallback in+// services/ui.js (:75 there), which production pages provide globally.+const escapeHtml =+ (str) => String(str).replace(/[&<>"']/g, (m) => ({'&':'&','<':'<','>':'>','"':'"',"'":'''})[m]);++const originalLocation = window.location;++/** Fire a captured socket handler with a payload. */+function emit(event, payload) {+ const handler = registeredHandlers.get(event);+ if (typeof handler !== 'function') {+ throw new Error(`no handler registered for '${event}'`);+ }+ handler(payload);+}++/**+ * Assert the last log entry landed inert: no img/script elements anywhere,+ * and the message text present as escaped, non-parsed content.+ */+function expectInertLogEntry(rawPayloadSubstring) {+ const entries = document.querySelectorAll('.ldr-console-log-entry');+ expect(entries.length).toBeGreaterThan(0); // sink actually ran++ expect(document.querySelectorAll('img')).toHaveLength(0);+ expect(document.querySelectorAll('script')).toHaveLength(0);+ expect(document.querySelectorAll('[onerror]')).toHaveLength(0);++ const message = entries[entries.length - 1].querySelector('.ldr-log-message');+ expect(message).not.toBeNull();+ // Raw payload visible as inert text...+ expect(message.textContent).toContain(rawPayloadSubstring);+ // ...and stored escaped, never as live markup.+ expect(message.innerHTML).not.toMatch(/<(img|script)\b/i);+ expect(message.innerHTML).toContain('<');+}++beforeAll(() => {+ vi.spyOn(SafeLogger, 'log');+ vi.spyOn(SafeLogger, 'warn');+ vi.spyOn(SafeLogger, 'error');++ window.escapeHtml = escapeHtml;+ // Bare globals socket.js resolves at call time.+ globalThis.ResearchStates = { logLevel: () => 'info', isTerminal: () => false };++ // Fake socket.io-client: records .on(event, cb) registrations.+ fakeSocket = {+ connected: true,+ on: vi.fn((event, cb) => registeredHandlers.set(event, cb)),+ off: vi.fn(),+ emit: vi.fn(),+ disconnect: vi.fn(),+ };+ globalThis.io = vi.fn(() => fakeSocket);++ // Reach the standalone DOM sink rather than the missing-logpanel guard.+ delete window._socketAddLogEntry;++ // Research page so initializeSocket() actually creates the socket.+ delete window.location;+ window.location = {+ href: 'http://localhost:5000/progress/xss-test',+ protocol: 'http:',+ host: 'localhost:5000',+ pathname: '/progress/xss-test',+ };++ window.socket.init();+ window.socket.subscribeToResearch('r-xss');+ expect(registeredHandlers.get('search_engine_selected')).toBeTypeOf('function');+ expect(registeredHandlers.get('research_progress_r-xss')).toBeTypeOf('function');+});++afterAll(() => {+ window.socket.disconnect();+ window.location = originalLocation;+});++beforeEach(() => {+ // A prior error/disconnect case may already own the polling fallback.+ // Begin each scenario with the real connected-state reset.+ emit('connect');+ vi.clearAllMocks();+ window._processedSocketMessages = new Map();+ window.pollResearchStatus = vi.fn();+ // Log-panel markup WITHOUT the entry template and WITHOUT logpanel.js:+ // this is exactly the configuration socket.js's fallback DOM sink serves.+ document.body.innerHTML =+ '<div id="console-log-container"></div><span id="log-indicator">0</span>';+});++describe('socket events -> DOM XSS surface', () => {+ it('sanity: the inertness detector is not vacuous (unescaped payload does create an img)', () => {+ // Detached node: setting innerHTML never fires load/error events,+ // this only proves querySelectorAll('img') would find a real leak.+ const scratch = document.createElement('div');+ scratch.innerHTML = '<img src=x onerror=alert(1)>';+ expect(scratch.querySelectorAll('img')).toHaveLength(1);+ });++ it('search_engine_selected: engine name with <img onerror> markup lands inert', () => {+ emit('search_engine_selected', {+ engine: '<img src=x onerror=alert(1)>',+ result_count: 3,+ });++ expectInertLogEntry('Search engine selected: <img src=x onerror=alert(1)> (found 3 results)');+ // Sink really executed: the indicator counted the entry.+ expect(document.getElementById('log-indicator').textContent).toBe('1');+ });++ it('search_engine_selected: script-injection engine name lands inert', () => {+ emit('search_engine_selected', {+ engine: '"><script>alert(1)</script>',+ result_count: 0,+ });++ expectInertLogEntry('"><script>alert(1)</script>');+ expect(document.querySelectorAll('script')).toHaveLength(0);+ expect(document.body.innerHTML).not.toContain('<script>');+ });++ it('research_progress_<id>: hostile message string lands inert at the addConsoleLog sink', () => {+ emit('research_progress_r-xss', {+ status: 'in_progress',+ message: '<img src=x onerror=alert(1)>',+ });++ expectInertLogEntry('<img src=x onerror=alert(1)>');+ // status only feeds ResearchStates.logLevel in socket.js — it must+ // never appear in the DOM by itself.+ expect(document.body.textContent).not.toContain('in_progress<script>');+ });++ it('research_progress_<id>: hostile log_entry.message lands inert', () => {+ emit('research_progress_r-xss', {+ log_entry: {+ time: '2026-01-01T00:00:00Z',+ type: 'error',+ message: '<img src=x onerror=alert(1)>',+ },+ });++ expectInertLogEntry('<img src=x onerror=alert(1)>');+ expect(document.querySelectorAll('.ldr-log-error')).toHaveLength(1);+ });++ it('research_progress_<id>: hostile messages inside progress_log JSON land inert', () => {+ emit('research_progress_r-xss', {+ progress_log: JSON.stringify([+ { time: 't-xss-1', message: '"><script>alert(1)</script>' },+ { time: 't-xss-2', message: '<img src=x onerror=alert(1)>' },+ ]),+ });++ expect(document.querySelectorAll('.ldr-console-log-entry')).toHaveLength(2);+ expect(document.querySelectorAll('img')).toHaveLength(0);+ expect(document.querySelectorAll('script')).toHaveLength(0);+ const messages = [...document.querySelectorAll('.ldr-log-message')];+ expect(messages[0].textContent).toContain('"><script>alert(1)</script>');+ expect(messages[1].textContent).toContain('<img src=x onerror=alert(1)>');+ expect(messages.every((m) => m.innerHTML.includes('<'))).toBe(true);+ });++ it('connect_error: hostile error is logged to SafeLogger only — no DOM writes', () => {+ // Handler (:100) has no DOM sink: SafeLogger.warn + attempt counting.+ emit('connect_error', { message: '<img src=x onerror=alert(1)>' });++ expect(SafeLogger.warn).toHaveBeenCalled();+ const warnArg = SafeLogger.warn.mock.calls.find(+ (call) => call[0] === 'Socket connection error:'+ )[1];+ expect(warnArg.message).toBe('<img src=x onerror=alert(1)>');+ // Lock in "no DOM sink": nothing materialized.+ expect(document.getElementById('console-log-container').children).toHaveLength(0);+ expect(document.querySelectorAll('img, script')).toHaveLength(0);+ });++ it('error: hostile error is logged and polling fallback invoked — no DOM writes', () => {+ emit('error', { message: '"><script>alert(1)</script>' });++ const errorArg = SafeLogger.error.mock.calls.find(+ (call) => call[0] === 'Socket error:'+ )[1];+ expect(errorArg.message).toBe('"><script>alert(1)</script>');+ expect(window.pollResearchStatus).toHaveBeenCalledWith('r-xss');+ expect(document.getElementById('console-log-container').children).toHaveLength(0);+ expect(document.querySelectorAll('img, script')).toHaveLength(0);+ });++ it('disconnect/reconnect/reconnect_attempt: hostile payloads stay in SafeLogger, DOM untouched', () => {+ emit('disconnect', '<img src=x onerror=alert(1)>');+ emit('reconnect', '"><script>');+ emit('reconnect_attempt', '<img src=x onerror=alert(1)>');++ expect(SafeLogger.log).toHaveBeenCalledWith('Socket disconnected:', '<img src=x onerror=alert(1)>');+ expect(SafeLogger.log).toHaveBeenCalledWith('Socket reconnected after', '"><script>', 'attempts');+ expect(SafeLogger.log).toHaveBeenCalledWith('Socket reconnection attempt:', '<img src=x onerror=alert(1)>');+ expect(document.getElementById('console-log-container').children).toHaveLength(0);+ expect(document.querySelectorAll('img, script')).toHaveLength(0);+ });+});diff --git a/tests/js/security/url-source-flows-xss.test.js b/tests/js/security/url-source-flows-xss.test.jsnew file mode 100644index 0000000000..54caa1f9f5--- /dev/null+++ b/tests/js/security/url-source-flows-xss.test.js@@ -0,0 +1,773 @@+/**+ * Defensive output-encoding coverage for browser URL/storage sources.+ *+ * Source -> sink map (verified 2026-08-20):+ *+ * location.search+ * - followup.js:52-55 reads `research_id`; the value becomes+ * `parentResearchId`, then JSON data in the constant-URL fetches at+ * :248-258 and :300-311. It is never rendered or persisted.+ * - services/api.js:67 reads the whole search string (with pathname/hash),+ * encodeURIComponent encodes it, and :72 assigns the result to the+ * hardcoded `/auth/login?next=` navigation target.+ * - components/library_search_ui.js:67/:90/:107/:124 preserves existing+ * query parameters with URLSearchParams, then :74/:97/:114/:131 assigns+ * the serialized result back to location.search. No DOM/fetch/storage sink.+ * - components/chat.js:281-288 reads `q`, removes the query string with+ * history.replaceState, assigns the decoded value to the chat input, then+ * handleSend renders it through textContent (:1114) and sends it as JSON+ * request data (:684-687). It never enters a fetch URL.+ * - components/logpanel.js:481 only checks for the literal `debug=logs`;+ * matching controls a delayed toggle click and does not render the URL.+ *+ * location.hash+ * - services/api.js:67 follows the encoded login-return flow above.+ * - components/logpanel.js:473/:481 compares `#logs` or checks for `debug`;+ * matching controls a delayed toggle click and does not render the hash.+ *+ * rerunConfig+ * - Recon correction: this is sessionStorage, not localStorage.+ * - components/history.js:821-829 writes `{query, mode}` and navigates to `/`.+ * - components/research.js:195-241 parses/removes it, assigns query through+ * input.value, selects mode through CSS.escape, and shows static notice HTML.+ * A later submit sends the query as JSON data at :3248-3283; the stored mode+ * is not submitted unless it matches an existing mode option.+ * - research_form.js has no rerunConfig read or write.+ *+ * Coverage note: grep of the complete static/js tree found no document.referrer or+ * window.name reader. It did find the location.hash readers above, so they are+ * exercised here rather than recorded as absent.+ */++import '@js/config/urls.js';+import '@js/utils/alert-helpers.js';+import '@js/security/xss-protection.js';+import '@js/utils/form-validation.js';+import '@js/components/custom_dropdown.js';+import '@js/services/api.js';+import { afterAll, afterEach, describe, expect, test, vi } from 'vitest';++const IMG_PAYLOAD = '<img src=x onerror=alert(1)>';+const SVG_PAYLOAD = '"><svg onload=alert(1)>';+const ATTR_PAYLOAD = 'x" onmouseover="alert(1)';+const JAVASCRIPT_URL = 'javascript:alert(1)';+const SPECIAL_VALUES = [+ IMG_PAYLOAD,+ SVG_PAYLOAD,+ ATTR_PAYLOAD,+ JAVASCRIPT_URL,+];+const BENIGN_CONTROL = 'Benign control value';+const START_RESEARCH_URL = '/api/start_research';+const DEFAULT_RESEARCH_PAYLOAD = {+ status: 'error',+ message: 'Benign stubbed response',+ settings: {},+ providers: {},+ provider_options: [{+ value: 'OLLAMA',+ label: 'Benign Ollama provider',+ is_cloud: false,+ }],+ engine_options: [],+ engines: {},+};+const nativeLocation = window.location;+const originalFetch = globalThis.fetch;+const originalApi = window.api;+const originalUrlBuilder = window.URLBuilder;+const originalUrlValidator = window.URLValidator;++function jsonResponse(payload) {+ return Promise.resolve({+ ok: true,+ status: 200,+ statusText: 'OK',+ json: () => Promise.resolve(payload),+ text: () => Promise.resolve(''),+ });+}++function installMockLocation(overrides = {}) {+ const location = {+ href: 'http://localhost/',+ protocol: 'http:',+ host: 'localhost',+ pathname: '/',+ search: '',+ hash: '',+ ...overrides,+ };+ Object.defineProperty(window, 'location', {+ configurable: true,+ writable: true,+ value: location,+ });+ return location;+}++function restoreNativeLocation() {+ Object.defineProperty(window, 'location', {+ configurable: true,+ writable: true,+ value: nativeLocation,+ });+}++function eventHandlerAttributes(root) {+ const found = [];+ for (const element of root.querySelectorAll('*')) {+ for (const name of element.getAttributeNames()) {+ if (/^on/i.test(name)) found.push(`${element.tagName}[${name}]`);+ }+ }+ return found;+}++function expectInert(root) {+ expect(root.querySelectorAll('script, img, svg')).toHaveLength(0);+ expect(eventHandlerAttributes(root)).toEqual([]);+ for (const link of root.querySelectorAll('a[href]')) {+ expect(link.getAttribute('href') ?? '').not.toMatch(/^\s*javascript:/i);+ }+}++function installHistoryPage() {+ document.body.innerHTML = `+ <p id="benign-control">Benign history item</p>+ <div id="history-items"></div>+ <input id="history-search">+ <button id="clear-history-btn" type="button">Clear</button>+ <div id="history-empty-message"></div>+ `;+}++function installResearchPage() {+ document.body.innerHTML = `+ <p id="benign-control">Benign research form</p>+ <form id="research-form">+ <div id="research-alert" role="alert" style="display:none"></div>+ <div id="research-error-alert" style="display:none"></div>+ <textarea id="query" name="query"></textarea>+ <div class="ldr-privacy-panel" data-scope="adaptive">+ <i id="ldr-privacy-panel-icon"></i>+ <select id="policy_egress_scope" name="policy_egress_scope">+ <option value="adaptive" selected>Adaptive</option>+ </select>+ <input type="checkbox" id="llm_require_local_endpoint">+ <input type="checkbox" id="embeddings_require_local">+ </div>+ <label class="ldr-mode-option active" data-mode="quick">+ <input id="mode-quick" type="radio" name="research_mode" value="quick" checked>+ Quick+ </label>+ <button type="button" class="ldr-advanced-options-toggle ldr-open" aria-expanded="true">+ <i class="fas fa-chevron-up"></i><span class="sr-only"></span>+ </button>+ <div class="ldr-advanced-options-panel ldr-expanded" id="advanced-options-panel">+ <select id="model_provider" data-initial-value="OLLAMA">+ <option value="OLLAMA" selected>Benign Ollama provider</option>+ </select>+ <div class="form-group">+ <div id="model-dropdown">+ <input type="text" id="model">+ <div id="model-dropdown-list"></div>+ </div>+ </div>+ <input type="hidden" id="model_hidden" value="safe-model">+ <button type="button" id="model-refresh"></button>+ <div id="search-engine-dropdown">+ <input type="text" id="search_engine">+ <div id="search-engine-dropdown-list"></div>+ </div>+ <input type="hidden" id="search_engine_hidden" value="searxng">+ <button type="button" id="search_engine-refresh"></button>+ <select id="strategy"><option value="source-based">Source based</option></select>+ <input id="iterations" value="2">+ <input id="questions_per_iteration" value="3">+ </div>+ <button type="submit" id="start-research-btn"><span>Start Research</span></button>+ </form>+ `;+}++function installChatPage() {+ document.head.innerHTML = '<meta name="chat-session-id" content="source-session">';+ document.body.innerHTML = `+ <div id="chat-welcome"></div>+ <textarea id="chat-input"></textarea>+ <button id="send-btn" type="button">Send</button>+ <div id="chat-title"></div>+ <div id="chat-messages" role="log"></div>+ <template id="thinking-template">+ <div class="ldr-chat-message ldr-chat-message-assistant ldr-chat-message-thinking" role="status">+ <div class="ldr-chat-message-content">+ <div class="ldr-chat-thinking-text" hidden></div>+ <div class="ldr-chat-thinking-dots"><span></span></div>+ </div>+ </div>+ </template>+ <template id="message-template">+ <div class="ldr-chat-message">+ <div class="ldr-chat-message-avatar"><i class="fas fa-user"></i></div>+ <div class="ldr-chat-message-content">+ <div class="ldr-chat-message-text"></div>+ <div class="ldr-chat-message-meta"><span class="ldr-chat-message-time"></span></div>+ </div>+ </div>+ </template>+ `;+}++function installLibraryPage() {+ document.body.innerHTML = `+ <p id="benign-control">Benign library document</p>+ <div id="search-mode-menu">+ <button class="dropdown-item" data-mode="text" type="button">Text Only</button>+ </div>+ <button id="search-mode-btn" type="button">AI Hybrid</button>+ <div id="documents-container">+ <div class="ldr-document-card" data-doc-id="benign-doc" data-domain="" data-research="">+ <div class="card-header">Benign library document</div>+ <div class="card-body"></div>+ </div>+ </div>+ <div id="semantic-results-container"></div>+ <div id="library-search-notice"></div>+ <select id="filter-collection"></select>+ <select id="filter-domain"></select>+ <select id="filter-research"></select>+ <select id="filter-date"></select>+ <input id="search-documents">+ `;+}++function installLogPanel() {+ document.body.innerHTML = `+ <p id="benign-control">Benign log panel</p>+ <div class="ldr-collapsible-log-panel">+ <div class="ldr-log-panel-header" id="log-panel-toggle">+ <i class="fas fa-chevron-right ldr-toggle-icon"></i>+ </div>+ <div class="ldr-log-panel-content collapsed" id="log-panel-content">+ <div class="ldr-log-controls">+ <div class="ldr-log-filter">+ <button class="ldr-small-btn ldr-selected" data-filter-type="all" type="button">All</button>+ <button class="ldr-small-btn" data-filter-type="info" type="button">Info</button>+ </div>+ <button id="log-autoscroll-button" class="ldr-selected" type="button"></button>+ <button id="log-download-button" type="button"></button>+ </div>+ <div class="ldr-console-log" id="console-log-container"></div>+ </div>+ </div>+ <template id="console-log-entry-template">+ <div class="ldr-console-log-entry">+ <span class="ldr-log-timestamp"></span>+ <span class="ldr-log-badge"></span>+ <span class="ldr-log-message"></span>+ </div>+ </template>+ `;+}++afterEach(() => {+ vi.useRealTimers();+ vi.restoreAllMocks();+ sessionStorage.clear();+ localStorage.clear();+ document.body.replaceChildren();+ document.head.querySelector('meta[name="chat-session-id"]')?.remove();+ restoreNativeLocation();+ window.history.replaceState({}, '', '/');+ globalThis.fetch = originalFetch;+ window.api = originalApi;+ window.URLBuilder = originalUrlBuilder;+ globalThis.URLBuilder = originalUrlBuilder;+ window.URLValidator = originalUrlValidator;+ globalThis.URLValidator = originalUrlValidator;+ delete window.LibrarySearch;+ delete window.socket;+ delete window.ui;+ delete window.RESEARCH_STATUS;+ delete window.currentResearchId;+ delete globalThis.ResearchStates;+});++afterAll(() => {+ restoreNativeLocation();+ globalThis.fetch = originalFetch;+});++describe('rerunConfig sessionStorage -> form -> request', { concurrent: false }, () => {+ test('keeps poisoned history data inert through the real writer and reader flow', async () => {+ const storedQuery = SPECIAL_VALUES.join(' | ');+ const storedMode = 'quick';+ const safeAssign = vi.fn();+ const validator = { safeAssign };+ const states = {+ formatStatus: () => 'Completed',+ isCompleted: () => true,+ isTerminal: () => true,+ };++ installHistoryPage();+ window.URLValidator = validator;+ globalThis.URLValidator = validator;+ window.ResearchStates = states;+ globalThis.ResearchStates = states;+ window.api = {+ getCsrfToken: () => 'test-csrf',+ getResearchHistory: vi.fn().mockResolvedValue({+ items: [+ {+ id: 'hostile-history-item',+ query: storedQuery,+ title: storedQuery,+ mode: storedMode,+ status: 'completed',+ document_count: 0,+ created_at: '2026-08-20T10:00:00Z',+ },+ {+ id: 'benign-history-item',+ query: BENIGN_CONTROL,+ title: BENIGN_CONTROL,+ mode: 'quick',+ status: 'completed',+ document_count: 0,+ created_at: '2026-08-20T09:00:00Z',+ },+ ],+ }),+ };+ globalThis.fetch = vi.fn(() => jsonResponse({ success: true, sessions: [] }));++ await import('@js/components/history.js');+ await vi.waitFor(() => {+ expect(document.querySelectorAll('.ldr-history-item')).toHaveLength(2);+ });++ const hostileItem = document.querySelector('[data-id="hostile-history-item"]');+ expect(hostileItem).not.toBeNull();+ expect(hostileItem.textContent).toContain(storedQuery);+ expect(hostileItem.textContent).toContain('Quick Summary');+ expect(document.getElementById('history-items').textContent).toContain(BENIGN_CONTROL);+ expectInert(document.body);++ hostileItem.querySelector('.ldr-rerun-btn').click();++ expect(JSON.parse(sessionStorage.getItem('rerunConfig'))).toEqual({+ query: storedQuery,+ mode: storedMode,+ });+ expect(localStorage.getItem('rerunConfig')).toBeNull();+ expect(safeAssign).toHaveBeenCalledWith(window.location, 'href', '/');++ installResearchPage();+ window.api = { getCsrfToken: () => 'test-csrf' };+ window.RESEARCH_STATUS = { QUEUED: 'queued', IN_PROGRESS: 'in_progress' };+ const researchFetch = vi.fn((url, options) => {+ if (url === START_RESEARCH_URL && options?.method === 'POST') {+ return jsonResponse({ status: 'error', message: 'Benign API rejection' });+ }+ return jsonResponse(DEFAULT_RESEARCH_PAYLOAD);+ });+ globalThis.fetch = researchFetch;++ await import('@js/components/research.js');+ document.dispatchEvent(new Event('DOMContentLoaded'));++ await vi.waitFor(() => {+ expect(document.getElementById('query').value).toBe(storedQuery);+ expect(document.getElementById('research-alert').textContent)+ .toContain('Re-running previous research');+ });++ expect(sessionStorage.getItem('rerunConfig')).toBeNull();+ expect(document.getElementById('mode-quick').checked).toBe(true);+ expect(document.getElementById('research-alert').textContent).not.toContain(storedQuery);+ expect(document.body.textContent).toContain('Benign research form');+ expect(document.body.textContent).not.toContain(storedQuery);+ expectInert(document.body);++ document.getElementById('research-form').dispatchEvent(+ new Event('submit', { bubbles: true, cancelable: true })+ );++ await vi.waitFor(() => {+ expect(researchFetch.mock.calls.some(+ ([url, options]) => url === START_RESEARCH_URL && options?.method === 'POST'+ )).toBe(true);+ });+ const startCall = researchFetch.mock.calls.find(+ ([url, options]) => url === START_RESEARCH_URL && options?.method === 'POST'+ );+ const submitted = JSON.parse(startCall[1].body);+ expect(startCall[0]).toBe(START_RESEARCH_URL);+ expect(startCall[0]).not.toContain(storedQuery);+ expect(startCall[1].body).toBe(JSON.stringify(submitted));+ expect(submitted.query).toBe(storedQuery);+ expect(submitted.mode).toBe('quick');+ await vi.waitFor(() => {+ expect(document.getElementById('research-alert').textContent)+ .toContain('Benign API rejection');+ });+ expectInert(document.body);+ });++ // Resolved: research.js matches the stored mode against the rendered options by attribute comparison, so no selector is built from the stored value.+ test('handles a quote-bearing stored mode without aborting rerun application', async () => {+ installResearchPage();+ sessionStorage.setItem('rerunConfig', JSON.stringify({+ query: BENIGN_CONTROL,+ mode: SVG_PAYLOAD,+ }));+ window.api = { getCsrfToken: () => 'test-csrf' };+ window.RESEARCH_STATUS = { QUEUED: 'queued', IN_PROGRESS: 'in_progress' };+ globalThis.fetch = vi.fn(() => jsonResponse(DEFAULT_RESEARCH_PAYLOAD));++ const realQuerySelector = document.querySelector.bind(document);+ const rejectedModeSelectors = [];+ vi.spyOn(document, 'querySelector').mockImplementation((selector) => {+ try {+ return realQuerySelector(selector);+ } catch (error) {+ if (String(selector).startsWith('.ldr-mode-option[data-mode=')) {+ rejectedModeSelectors.push({ selector, error });+ return null;+ }+ throw error;+ }+ });++ await import('@js/components/research.js');+ document.dispatchEvent(new Event('DOMContentLoaded'));+ await vi.waitFor(() => {+ expect(document.getElementById('query').value).toBe(BENIGN_CONTROL);+ expect(document.getElementById('research-alert').textContent)+ .toContain('Re-running previous research');+ });++ expect(sessionStorage.getItem('rerunConfig')).toBeNull();+ expect(document.body.textContent).toContain('Benign research form');+ expectInert(document.body);+ expect(rejectedModeSelectors).toEqual([]);+ });+});++describe('components/chat.js location.search q flow', { concurrent: false }, () => {+ test.each(SPECIAL_VALUES)(+ 'renders and submits q as inert data, never as URL structure: %s',+ async (payload) => {+ vi.resetModules();+ installChatPage();+ window.history.replaceState(+ {},+ '',+ `/chat/source-session?${new URLSearchParams({ q: payload, control: 'benign' })}`+ );++ const socketInstance = { on: vi.fn(), off: vi.fn() };+ window.api = { getCsrfToken: () => 'test-csrf' };+ window.ui = { renderMarkdown: (text) => text };+ window.socket = {+ getSocketInstance: () => socketInstance,+ subscribeToResearch: vi.fn(),+ unsubscribeFromResearch: vi.fn(),+ };+ const chatFetch = vi.fn((url, options = {}) => {+ if (url === '/api/chat/sessions/source-session/messages' && options.method === 'POST') {+ return jsonResponse({ success: true });+ }+ if (url === '/api/chat/sessions/source-session/messages') {+ return jsonResponse({+ success: true,+ messages: [{+ id: 'benign-existing-message',+ role: 'user',+ message_type: 'chat',+ content: 'Benign existing chat message',+ created_at: '2026-08-20T10:00:00Z',+ }],+ has_more: false,+ in_progress_research_id: null,+ });+ }+ if (url === '/api/chat/sessions/source-session') {+ return jsonResponse({+ success: true,+ session: { id: 'source-session', title: 'Benign chat session' },+ });+ }+ throw new Error(`Unexpected chat request: ${url}`);+ });+ globalThis.fetch = chatFetch;++ await import('@js/components/chat.js');+ await vi.waitFor(() => {+ expect(document.getElementById('chat-input').dataset.initComplete).toBe('true');+ expect(chatFetch.mock.calls.some(+ ([url, options]) => url === '/api/chat/sessions/source-session/messages'+ && options?.method === 'POST'+ )).toBe(true);+ });++ const userMessages = document.querySelectorAll('.ldr-chat-message-user .ldr-chat-message-text');+ const renderedPayload = userMessages[userMessages.length - 1];+ const sendCall = chatFetch.mock.calls.find(+ ([url, options]) => url === '/api/chat/sessions/source-session/messages'+ && options?.method === 'POST'+ );+ expect(userMessages.length).toBeGreaterThanOrEqual(2);+ expect(renderedPayload.textContent).toBe(payload);+ expect(document.getElementById('chat-messages').textContent)+ .toContain('Benign existing chat message');+ expect(document.getElementById('chat-title').textContent).toBe('Benign chat session');+ expect(sendCall[0]).toBe('/api/chat/sessions/source-session/messages');+ expect(sendCall[0]).not.toContain(payload);+ expect(sendCall[1].body).toBe(JSON.stringify({+ content: payload,+ trigger_research: true,+ }));+ expect(window.location.search).toBe('');+ expectInert(document.body);+ }+ );+});++describe('services/api.js location.search/hash return target', { concurrent: false }, () => {+ test.each(SPECIAL_VALUES)(+ 'percent-encodes the full URL state under the fixed login target: %s',+ (payload) => {+ document.body.innerHTML = '<p id="benign-control">Benign current page</p>';+ const search = `?${new URLSearchParams({ payload, control: 'benign-control' })}`;+ const hash = `#${new URLSearchParams({ fragment: payload })}`;+ const location = installMockLocation({+ href: `http://localhost/results/benign${search}${hash}`,+ pathname: '/results/benign',+ search,+ hash,+ });+ const sourceValue = location.pathname + location.search + location.hash;++ originalApi.redirectToLogin();++ expect(location.href).toBe(`/auth/login?next=${encodeURIComponent(sourceValue)}`);+ expect(new URL(location.href, 'http://localhost').searchParams.get('next'))+ .toBe(sourceValue);+ expect(location.href).toContain('benign-control');+ expect(location.href).not.toMatch(/^\s*javascript:/i);+ expect(document.getElementById('benign-control').textContent).toBe('Benign current page');+ expect(document.body.textContent).not.toContain(payload);+ expectInert(document.body);+ }+ );+});++describe('components/library_search_ui.js URL serialization', { concurrent: false }, () => {+ test('preserves every existing special-character value with URLSearchParams across all four filters', async () => {+ installLibraryPage();+ const location = installMockLocation({ pathname: '/library' });+ const fetchMock = vi.fn();+ globalThis.fetch = fetchMock;+ window.LibrarySearch = null;++ await import('@js/components/library_search_ui.js');+ document.querySelector('[data-mode="text"]').click();++ const filterCases = [+ ['filter-collection', 'collection'],+ ['filter-domain', 'domain'],+ ['filter-research', 'research'],+ ['filter-date', 'date'],+ ];+ for (const payload of SPECIAL_VALUES) {+ for (const [elementId, parameter] of filterCases) {+ const selection = `benign-${parameter}`;+ const select = document.getElementById(elementId);+ const option = document.createElement('option');+ option.value = selection;+ option.textContent = `Benign ${parameter}`;+ select.replaceChildren(option);+ select.value = selection;++ const sourceParams = new URLSearchParams({+ source: payload,+ control: 'benign-control',+ page: '9',+ });+ location.search = `?${sourceParams.toString()}`;+ select.dispatchEvent(new Event('change', { bubbles: true }));++ const expected = new URLSearchParams(sourceParams);+ expected.set(parameter, selection);+ expected.delete('page');+ expect(location.search).toBe(expected.toString());+ const serialized = new URLSearchParams(location.search);+ expect(serialized.get('source')).toBe(payload);+ expect(serialized.get('control')).toBe('benign-control');+ expect(serialized.get(parameter)).toBe(selection);+ expect(serialized.has('page')).toBe(false);+ expect(document.body.textContent).toContain('Benign library document');+ expectInert(document.body);+ }+ }+ expect(fetchMock).not.toHaveBeenCalled();+ });+});++let followUpResearchPromise;++function getFollowUpResearch() {+ if (!followUpResearchPromise) {+ followUpResearchPromise = import('@js/followup.js')+ .then(() => window.FollowUpResearch);+ }+ return followUpResearchPromise;+}++describe('followup.js location.search research_id flow', { concurrent: false }, () => {+ test.each(SPECIAL_VALUES)(+ 'keeps research_id out of DOM and fetch URLs while preserving JSON data: %s',+ async (payload) => {+ const search = `?${new URLSearchParams({+ research_id: payload,+ control: 'benign-control',+ })}`;+ installMockLocation({+ href: `http://localhost/followup${search}`,+ pathname: '/followup',+ search,+ });+ document.body.innerHTML = `+ <p id="benign-control">Benign follow-up page</p>+ <button id="ask-followup-btn" type="button">Ask</button>+ <div id="followUpModal"></div>+ <section id="parentContext" style="display:none">+ <div id="parentSummary"></div>+ <div id="parentSources"></div>+ </section>+ <textarea id="followUpQuestion">Benign follow-up question</textarea>+ <div id="followup-error-container"></div>+ `;+ window.api = { getCsrfToken: () => 'test-csrf' };+ window.ui = {+ clearInlineError: vi.fn(),+ showInlineError: vi.fn(),+ };+ const followupFetch = vi.fn((url) => {+ if (url === '/api/followup/prepare') {+ return jsonResponse({+ success: true,+ parent_summary: 'Benign parent summary',+ available_sources: '7 benign sources',+ });+ }+ if (url === '/api/followup/start') {+ return jsonResponse({ success: false, error: 'Benign rejected start' });+ }+ throw new Error(`Unexpected follow-up request: ${url}`);+ });+ globalThis.fetch = followupFetch;+ const FollowUpClass = await getFollowUpResearch();+ const followUp = new FollowUpClass();++ followUp.init();+ expect(followUp.parentResearchId).toBe(payload);+ expect(document.getElementById('ask-followup-btn').onclick).toBeTypeOf('function');+ await followUp.loadParentContext();+ await followUp.submitFollowUp();++ const prepareCall = followupFetch.mock.calls.find(+ ([url]) => url === '/api/followup/prepare'+ );+ const startCall = followupFetch.mock.calls.find(+ ([url]) => url === '/api/followup/start'+ );+ expect(prepareCall).toBeDefined();+ expect(startCall).toBeDefined();+ expect(prepareCall[0]).toBe('/api/followup/prepare');+ expect(startCall[0]).toBe('/api/followup/start');+ expect(prepareCall[0]).not.toContain(payload);+ expect(startCall[0]).not.toContain(payload);+ expect(prepareCall[1].body).toBe(JSON.stringify({+ parent_research_id: payload,+ question: 'test',+ }));+ expect(startCall[1].body).toBe(JSON.stringify({+ parent_research_id: payload,+ question: 'Benign follow-up question',+ }));+ expect(document.getElementById('parentSummary').textContent)+ .toBe('Benign parent summary');+ expect(document.getElementById('parentSources').textContent)+ .toBe('7 benign sources');+ expect(document.getElementById('parentContext').style.display).toBe('block');+ expect(document.body.textContent).toContain('Benign follow-up page');+ expect(document.body.textContent).not.toContain(payload);+ expectInert(document.body);+ }+ );+});++describe('components/logpanel.js location.search/hash control flow', { concurrent: false }, () => {+ test('uses benign and hostile URL state only as toggle conditions', async () => {+ vi.useFakeTimers();+ const location = installMockLocation({ pathname: '/not-a-research-page' });+ await import('@js/utils/log-helpers.js');+ window.URLBuilder = {+ researchLogs: (id, limit) => `/api/research/${id}/logs${limit ? `?limit=${limit}` : ''}`,+ historyLogCount: (id) => `/api/research/${id}/log_count`,+ researchLogsExport: (id) => `/api/research/${id}/logs/export`,+ };+ globalThis.URLBuilder = window.URLBuilder;+ globalThis.fetch = vi.fn((url) => {+ if (String(url).includes('log_count')) {+ return jsonResponse({ total_logs: 0 });+ }+ return jsonResponse([]);+ });+ await import('@js/components/logpanel.js');++ let sequence = 0;+ const exerciseToggle = async ({ search = '', hash = '', payload = null }) => {+ installLogPanel();+ location.pathname = '/results/url-source-test';+ location.search = search;+ location.hash = hash;+ const state = window._logPanelState;+ state.initialized = false;+ state.connectedResearchId = null;+ state.expanded = false;+ state.renderedIds = new Set();+ state.counts = window.LdrLogHelpers.emptyCounts();+ const toggle = document.getElementById('log-panel-toggle');+ const clickSpy = vi.spyOn(toggle, 'click');++ window.logPanel.initialize(`url-source-${sequence++}`);+ await vi.advanceTimersByTimeAsync(900);++ expect(clickSpy).toHaveBeenCalled();+ expect(document.body.textContent).toContain('Benign log panel');+ if (payload !== null) expect(document.body.textContent).not.toContain(payload);+ expectInert(document.body);+ };++ await exerciseToggle({ hash: '#logs' });+ for (const payload of SPECIAL_VALUES) {+ await exerciseToggle({+ hash: `#debug-${encodeURIComponent(payload)}`,+ payload,+ });+ await exerciseToggle({+ search: `?${new URLSearchParams({+ debug: 'logs',+ payload,+ control: 'benign-control',+ })}`,+ payload,+ });+ }+ });+});diff --git a/tests/js/security/url-validator-adversarial.test.js b/tests/js/security/url-validator-adversarial.test.jsnew file mode 100644index 0000000000..f2e092d8a6--- /dev/null+++ b/tests/js/security/url-validator-adversarial.test.js@@ -0,0 +1,217 @@+import '@js/security/url-validator.js';++const { URLValidator } = window;+const baseUrl = window.location.href;++describe('URLValidator adversarial inputs', () => {+ describe('scheme smuggling', () => {+ it.each([+ 'java\tscript:alert(1)',+ 'java\nscript:alert(1)',+ 'java\rscript:alert(1)',+ ' \tjavascript:alert(1)',+ ])('rejects tab/newline-smuggled JavaScript schemes: %j', (url) => {+ expect(URLValidator.isSafeUrl(url)).toBe(false);+ });++ it.each(['java\x01script:alert(1)', 'java\x0Bscript:alert(1)'])(+ 'treats non-stripped C0 lookalikes as same-origin relative paths: %j',+ (url) => {+ const parsed = new URL(url, baseUrl);++ expect(parsed.protocol).toBe('http:');+ expect(URLValidator.isSafeUrl(url)).toBe(true);+ }+ );+ });++ describe('entity, fullwidth, and NUL lookalikes', () => {+ it.each([+ 'javascript:alert(1)',+ 'javascript:alert(1)',+ 'java\x00script:alert(1)',+ '%6Aavascript:alert(1)',+ ])('resolves %j as a relative path rather than decoding a JavaScript scheme', (url) => {+ const parsed = new URL(url, baseUrl);++ expect(parsed.protocol).toBe('http:');+ expect(parsed.hostname).toBe('localhost');+ expect(URLValidator.isSafeUrl(url)).toBe(true);+ });+ });++ describe('direct unsafe schemes', () => {+ it.each([+ 'data:text/html,<script>alert(1)</script>',+ 'vbscript:msgbox(1)',+ 'file:///etc/passwd',+ 'about:blank',+ 'blob:https://example.com/uuid',+ 'DATA:text/html,<script>alert(1)</script>',+ 'VBScript:msgbox(1)',+ 'File:///etc/passwd',+ 'About:blank',+ ])('rejects %j', (url) => {+ expect(URLValidator.isSafeUrl(url)).toBe(false);+ });+ });++ describe('protocol-relative and backslash URLs', () => {+ it('recognizes protocol-relative URLs as allowed HTTP URLs without a trusted-domain policy', () => {+ expect(new URL('//evil.com', baseUrl).href).toBe('http://evil.com/');+ expect(URLValidator.isSafeUrl('//evil.com')).toBe(true);+ });++ it('normalizes double-backslash URLs to protocol-relative HTTP URLs', () => {+ expect(new URL('\\\\evil.com', baseUrl).href).toBe('http://evil.com/');+ expect(URLValidator.isSafeUrl('\\\\evil.com')).toBe(true);+ });++ it('normalizes slash-backslash URLs to protocol-relative HTTP URLs', () => {+ expect(new URL('/\\evil.com', baseUrl).href).toBe('http://evil.com/');+ expect(URLValidator.isSafeUrl('/\\evil.com')).toBe(true);+ });+ });++ describe('trusted-domain matching', () => {+ const options = { trustedDomains: ['example.com'] };+ const cyrillicHomoglyph = 'https://еxample.com';++ it('rejects an IDN homoglyph rather than treating it as a trusted domain', () => {+ expect(new URL(cyrillicHomoglyph).hostname).toBe('xn--xample-2of.com');+ expect(URLValidator.isSafeUrl(cyrillicHomoglyph, options)).toBe(false);+ });++ it.each([+ 'https://example.com。attacker.com',+ 'https://[email protected]',+ 'https://evil.com#@example.com',+ 'https://example.com.evil.com',+ 'https://notexample.com',+ ])('rejects trusted-domain confusion URL %j', (url) => {+ expect(URLValidator.isSafeUrl(url, options)).toBe(false);+ });++ it('allows the trusted apex and a real subdomain', () => {+ expect(URLValidator.isSafeUrl('https://example.com', options)).toBe(true);+ expect(URLValidator.isSafeUrl('https://sub.example.com/path', options)).toBe(true);+ });+ });++ describe('benign URLs', () => {+ it.each([+ 'settings/general',+ '/news/subscriptions',+ 'http://example.com/path',+ 'https://example.com/path?q=1',+ 'ftp://files.example.com/pub',+ 'ftps://files.example.com/pub',+ ])('allows %j', (url) => {+ expect(URLValidator.isSafeUrl(url)).toBe(true);+ });++ it('rejects tab-smuggled JavaScript while sanitizing', () => {+ expect(URLValidator.sanitizeUrl('java\tscript:alert(1)')).toBeNull();+ });+ });++ describe('safeAssign carve-outs', () => {+ it.each([+ ' data:text/html,<script>alert(1)</script>',+ 'DATA:text/html,<script>alert(1)</script>',+ 'da\tta:text/html,<script>alert(1)</script>',+ ])('rejects a non-exact data: prefix: %j', (url) => {+ const element = {};++ expect(URLValidator.safeAssign(element, 'href', url)).toBe(false);+ expect(element.href).toBeUndefined();+ });++ it('applies trusted-domain validation to double-backslash URLs that miss the internal-path carve-out', () => {+ const element = {};++ expect(URLValidator.safeAssign(element, 'href', '\\\\evil.com', {+ trustedDomains: ['example.com'],+ })).toBe(false);+ expect(element.href).toBeUndefined();+ });++ it('blocks data:text/html assignment', () => {+ const element = {};+ const payload = 'data:text/html,<script>alert(1)</script>';++ expect(URLValidator.safeAssign(element, 'href', payload)).toBe(false);+ expect(element.href).toBeUndefined();+ });++ // An SVG data: document can carry <script>/event-handler content, so+ // safeAssign's data: carve-out must refuse it even for an <img src>,+ // the target where a raster data: image IS accepted. That carve-out+ // checks the MIME type with its own regex, not SAFE_DATA_MIME_TYPES+ // (see the note above its data: branch in url-validator.js). The+ // target is a real <img> so only the MIME check can reject the+ // value: a plain object fails the target check first and would+ // reject even an allowed PNG.+ it('blocks data:image/svg+xml assignment to an img src', () => {+ const element = document.createElement('img');+ const payload = 'data:image/svg+xml;base64,PHN2ZyBvbmxvYWQ9ImFsZXJ0KDEpIi8+';++ expect(URLValidator.safeAssign(element, 'src', payload)).toBe(false);+ expect(element.getAttribute('src')).toBeNull();+ });++ it('does not allow protocol-relative URLs to bypass trustedDomains', () => {+ const element = {};++ expect(URLValidator.safeAssign(element, 'href', '//evil.com', {+ trustedDomains: ['example.com'],+ })).toBe(false);+ expect(element.href).toBeUndefined();+ });++ it('does not allow slash-backslash URLs to bypass trustedDomains', () => {+ const element = {};++ expect(URLValidator.safeAssign(element, 'href', '/\\evil.com', {+ trustedDomains: ['example.com'],+ })).toBe(false);+ expect(element.href).toBeUndefined();+ });++ // Regression: the internal-path carve-out used to compare the RAW+ // string, so a C0 control character at index 1 kept `url[1]` from+ // being '/' while the browser still stripped it and parsed the value+ // as protocol-relative. Every one of these resolved to+ // https://evil.com/ without ever reaching isSafeUrl.+ it.each([+ ['tab', '/\t/evil.com'],+ ['line feed', '/\n/evil.com'],+ ['carriage return', '/\r/evil.com'],+ ['tab before a backslash', '/\t\\evil.com'],+ ])('does not let a %s-smuggled protocol-relative URL skip validation', (_label, url) => {+ const element = {};++ expect(URLValidator.safeAssign(element, 'href', url, {+ trustedDomains: ['example.com'],+ })).toBe(false);+ expect(element.href).toBeUndefined();+ });++ it('still allows trusted carve-outs after the tightening', () => {+ const blobElement = document.createElement('a');+ expect(URLValidator.safeAssign(+ blobElement, 'href', 'blob:https://example.com/uuid'+ )).toBe(true);+ expect(blobElement.href).toBe('blob:https://example.com/uuid');++ const dataElement = document.createElement('img');+ const dataUrl = 'data:image/png;base64,iVBORw0KGgo=';+ expect(URLValidator.safeAssign(dataElement, 'src', dataUrl)).toBe(true);+ expect(dataElement.src).toBe(dataUrl);++ const internalElement = {};+ expect(URLValidator.safeAssign(internalElement, 'href', '/settings/general')).toBe(true);+ expect(internalElement.href).toBe('/settings/general');+ });+ });+});diff --git a/tests/js/security/xss-protection-dompurify-runtime.test.js b/tests/js/security/xss-protection-dompurify-runtime.test.jsindex 89fe62f2c3..683a349913 100644--- a/tests/js/security/xss-protection-dompurify-runtime.test.js+++ b/tests/js/security/xss-protection-dompurify-runtime.test.js@@ -113,7 +113,7 @@ it('safeSetInnerHTML inserts only the sanitizer result with the strict config',expect.objectContaining({ALLOWED_TAGS: expect.arrayContaining(['strong', 'a']),FORBID_TAGS: expect.arrayContaining(['script', 'iframe', 'form']),- FORBID_ATTR: expect.arrayContaining(['onerror', 'onclick', 'on*']),+ FORBID_ATTR: expect.arrayContaining(['onerror', 'onclick']),ALLOW_DATA_ATTR: false,SAFE_FOR_TEMPLATES: true,}),diff --git a/tests/js/security/xss-protection-late-dompurify.test.js b/tests/js/security/xss-protection-late-dompurify.test.jsindex da11c5e25f..ceb85b0de3 100644--- a/tests/js/security/xss-protection-late-dompurify.test.js+++ b/tests/js/security/xss-protection-late-dompurify.test.js@@ -359,7 +359,7 @@ describe('tabnabbing hook under late-bound DOMPurify', () => {});// The emulated override was live while the hook ran...- expect(stats.shadowedCount).toBe(1);+ expect(stats.shadowedCount).toBeGreaterThanOrEqual(1);// ...and the hook read and wrote through Element.prototype anyway.const el = firstElement(out, 'form');expect(el).not.toBeNull();diff --git a/tests/js/security/xss-protection-primitives.test.js b/tests/js/security/xss-protection-primitives.test.jsnew file mode 100644index 0000000000..a5f54dd0a4--- /dev/null+++ b/tests/js/security/xss-protection-primitives.test.js@@ -0,0 +1,466 @@+import DOMPurify from 'dompurify';++globalThis.DOMPurify = DOMPurify;+window.DOMPurify = DOMPurify;++await import('@js/security/xss-protection.js');++const {+ safeSetInnerHTML,+ safeCreateElement,+ sanitizeHtml,+ sanitizeStable,+} = window.XSSProtection;++const removeDOMPurify = () => {+ delete globalThis.DOMPurify;+ delete window.DOMPurify;+};++const restoreDOMPurify = () => {+ globalThis.DOMPurify = DOMPurify;+ window.DOMPurify = DOMPurify;+};++describe('safeSetInnerHTML DOMPurify branches', () => {+ afterEach(() => {+ restoreDOMPurify();+ });++ it('sanitizes hostile HTML while preserving allowed markup', () => {+ const element = document.createElement('div');++ safeSetInnerHTML(element, 'Intro <p>Safe <strong>content</strong></p>', true);++ expect(element.querySelector('p strong')?.textContent).toBe('content');++ for (const payload of [+ '<script>alert(1)</script>',+ '<iframe src="javascript:alert(2)"></iframe>',+ '<img src=x onerror="alert(3)">',+ '<a href="javascript:alert(4)" onclick="alert(5)">link</a>',+ ]) {+ safeSetInnerHTML(element, payload, true);+ expect(element.querySelectorAll('script, iframe, img').length).toBe(0);+ expect(element.querySelectorAll('[onerror], [onclick], [onload]').length).toBe(0);+ // DOMPurify strips the unsafe href but KEEPS the anchor, so this is+ // null when an <a> survives and undefined when the payload produced+ // none. Both mean "no href reached the DOM"; normalise to null so the+ // assertion does not depend on which of the two happened.+ expect(element.querySelector('a')?.getAttribute('href') ?? null).toBeNull();+ }+ });++ it('falls back to text content and warns when DOMPurify is unavailable', () => {+ const element = document.createElement('div');+ const warning = vi.spyOn(SafeLogger, 'warn');+ removeDOMPurify();++ safeSetInnerHTML(element, '<strong>not markup</strong>', true);++ expect(element.textContent).toBe('<strong>not markup</strong>');+ expect(element.children.length).toBe(0);+ expect(warning).toHaveBeenCalledWith(+ 'DOMPurify not available, escaping HTML instead of sanitizing'+ );+ warning.mockRestore();+ });++ it('stringifies non-string content in the sanitizing branch', () => {+ const element = document.createElement('div');++ safeSetInnerHTML(element, 42, true);++ expect(element.children.length).toBe(0);+ });+});++describe('safeCreateElement', () => {+ it('rejects tags outside the safe whitelist', () => {+ expect(() => safeCreateElement('script')).toThrow(/disallowed tag/);+ expect(() => safeCreateElement('img')).toThrow(/disallowed tag/);+ expect(() => safeCreateElement('form')).toThrow(/disallowed tag/);+ });++ it('normalizes uppercase tags and preserves text, benign attributes, and classes', () => {+ const element = safeCreateElement(+ 'BUTTON',+ '',+ { type: 'button', title: 'Run action', 'data-count': 7 },+ ['primary', 'wide']+ );++ expect(element.tagName).toBe('BUTTON');+ expect(element.textContent).toBe('');+ expect(element.children.length).toBe(0);+ expect(element.getAttribute('type')).toBe('button');+ expect(element.getAttribute('title')).toBe('Run action');+ expect(element.getAttribute('data-count')).toBe('7');+ expect(element.className).toBe('primary wide');+ });++ it('neutralizes hostile attributes while preserving safe link content', () => {+ const textElement = safeCreateElement('a', '<b>literal text</b>');+ const element = safeCreateElement(+ 'a',+ '',+ { onclick: 'alert(1)', href: 'javascript:alert(2)', title: 'Safe title' },+ []+ );++ expect(textElement.textContent).toBe('<b>literal text</b>');+ expect(element.getAttribute('onclick')).toBeNull();+ expect(element.getAttribute('href')).toBeNull();+ expect(element.getAttribute('title')).toBe('Safe title');+ });++ it('accepts empty attributes and handles edge inputs', () => {+ const empty = safeCreateElement('div', undefined, {}, []);+ const numeric = safeCreateElement('div', 0, { tabindex: 2 }, []);++ expect(empty.textContent).toBe('');+ expect(numeric.textContent).toBe('');+ expect(numeric.getAttribute('tabindex')).toBe('2');+ expect(() => safeCreateElement(null)).toThrow(/disallowed tag/);+ });++ it('rejects protocol-relative and backslash hrefs', () => {+ for (const href of [+ '//evil.com',+ '/\\evil.com',+ '\\\\evil.com',+ '/\\\\evil.com',+ ]) {+ const element = safeCreateElement('a', 'link', { href }, []);+ expect(element.getAttribute('href')).toBeNull();+ }+ });++ it('rejects control-character-smuggled dangerous schemes', () => {+ for (const href of [+ 'java\tscript:alert(1)',+ 'ja\nvascript:alert(1)',+ 'data:text/html,<img src=x>',+ '\tvbscript:alert(1)',+ 'file:///etc/passwd',+ 'about:blank',+ ]) {+ const element = safeCreateElement('a', 'link', { href }, []);+ expect(element.getAttribute('href')).toBeNull();+ }+ });++ it('allows benign href values', () => {+ for (const href of [+ 'https://example.com/page',+ 'http://example.com',+ 'mailto:[email protected]',+ 'tel:+15551234567',+ '#section-anchor',+ '/reports/latest',+ 'details.html',+ './relative/path',+ '?query=1',+ ]) {+ const element = safeCreateElement('a', 'link', { href }, []);+ expect(element.getAttribute('href')).toBe(href);+ }+ });++ it('forces noopener and noreferrer on target="_blank" while preserving safe rel tokens', () => {+ const blank = safeCreateElement(+ 'a',+ '',+ { href: 'https://example.com', target: '_blank' },+ []+ );+ const blankTokens = (blank.getAttribute('rel') || '').split(/\s+/).filter(Boolean);+ expect(blankTokens).toContain('noopener');+ expect(blankTokens).toContain('noreferrer');++ const preserved = safeCreateElement(+ 'a',+ '',+ {+ href: 'https://example.com',+ target: '_blank',+ rel: 'external nofollow',+ },+ []+ );+ const preservedTokens = (preserved.getAttribute('rel') || '').split(/\s+/).filter(Boolean);+ expect(preservedTokens).toContain('external');+ expect(preservedTokens).toContain('nofollow');+ expect(preservedTokens).toContain('noopener');+ expect(preservedTokens).toContain('noreferrer');++ const selfTarget = safeCreateElement(+ 'a',+ '',+ { href: 'https://example.com', rel: 'nofollow' },+ []+ );+ expect(selfTarget.getAttribute('rel')).toBe('nofollow');++ const mixedCase = safeCreateElement(+ 'a',+ '',+ {+ href: 'https://example.com',+ target: ' _BLANK ',+ rel: 'External NoOpEnEr OPENER noReFeRrEr external',+ },+ []+ );+ const mixedCaseTokens = (mixedCase.getAttribute('rel') || '')+ .split(/\s+/).filter(Boolean).map(token => token.toLowerCase());+ expect(mixedCase.getAttribute('target')).toBe('_blank');+ expect(mixedCaseTokens.filter(token => token === 'noopener')).toHaveLength(1);+ expect(mixedCaseTokens.filter(token => token === 'noreferrer')).toHaveLength(1);+ expect(mixedCaseTokens.filter(token => token === 'external')).toHaveLength(1);+ expect(mixedCaseTokens).not.toContain('opener');++ const namedTarget = safeCreateElement(+ 'a',+ '',+ { href: 'https://example.com', target: 'report-preview', rel: 'opener' },+ []+ );+ expect(namedTarget.getAttribute('target')).toBe('_blank');+ expect((namedTarget.getAttribute('rel') || '').toLowerCase()).toBe('noopener noreferrer');++ const topTarget = safeCreateElement(+ 'a',+ '',+ { href: '/settings', target: '_TOP', rel: 'nofollow' },+ []+ );+ expect(topTarget.getAttribute('target')).toBe('_top');+ expect(topTarget.getAttribute('rel')).toBe('nofollow');+ });+});++describe('sanitizeHtml DOMPurify branches', () => {+ afterEach(() => {+ restoreDOMPurify();+ });++ it('uses the default SANITIZE_CONFIG and preserves only allowed markup', () => {+ const result = sanitizeHtml(+ 'Intro <div id="kept" class="note"><b>bold</b><span>span</span></div>'+ );+ const container = document.createElement('div');+ container.innerHTML = result;++ // SANITIZE_NAMED_PROPS is on, so DOMPurify rewrites id/name to a+ // `user-content-` prefix. That is anti-DOM-clobbering hardening, not+ // an accident: without it, `id="kept"` would become+ // `document.kept` and could shadow a real property. Assert the+ // prefixed form, and pin the rewrite itself below so that turning+ // SANITIZE_NAMED_PROPS off is a test failure rather than a silent+ // loss of protection.+ expect(container.querySelector('div#user-content-kept.note b')?.textContent).toBe('bold');+ expect(container.querySelector('div#kept')).toBeNull();+ expect(container.querySelector('span')?.textContent).toBe('span');+ for (const payload of [+ '<script>alert(1)</script>',+ '<img src=x onerror="alert(2)">',+ '<a href="javascript:alert(3)" onclick="alert(4)">link</a>',+ ]) {+ container.innerHTML = sanitizeHtml(payload);+ expect(container.querySelectorAll('script, img').length).toBe(0);+ expect(container.querySelectorAll('[onclick], [onerror]').length).toBe(0);+ // See the note in the safeSetInnerHTML suite: the anchor survives+ // without its href, so getAttribute returns null rather than undefined.+ expect(container.querySelector('a')?.getAttribute('href') ?? null).toBeNull();+ }+ });++ it('isolates mixed-case blank and auxiliary named targets without retaining rel=opener', () => {+ const result = sanitizeHtml(+ '<a href="https://example.com/one" target="_BLANK" rel="External OPENER NoOpEnEr">one</a>' ++ '<a href="https://example.com/two" target="report-preview" rel="opener noReFeRrEr">two</a>'+ );+ const container = document.createElement('div');+ container.innerHTML = result;+ const links = container.querySelectorAll('a');++ expect(links).toHaveLength(2);+ links.forEach(link => {+ const relTokens = (link.getAttribute('rel') || '')+ .split(/\s+/).filter(Boolean).map(token => token.toLowerCase());+ expect(link.getAttribute('target')).toBe('_blank');+ expect(relTokens.filter(token => token === 'noopener')).toHaveLength(1);+ expect(relTokens.filter(token => token === 'noreferrer')).toHaveLength(1);+ expect(relTokens).not.toContain('opener');+ });+ expect((links[0].getAttribute('rel') || '').toLowerCase()).toContain('external');+ });++ it('exposes a lazy hook installer for direct DOMPurify consumers', async () => {+ const originalXSSProtection = window.XSSProtection;+ removeDOMPurify();+ vi.resetModules();+ await import('@js/security/xss-protection.js');+ const lateLoadedXSSProtection = window.XSSProtection;+ const addHook = vi.spyOn(DOMPurify, 'addHook');+ restoreDOMPurify();+ let installedHook;++ try {+ // Mirrors app.js publishing its deferred module import after the+ // classic security script has already executed.+ lateLoadedXSSProtection.ensureDOMPurifyHooks();+ const result = DOMPurify.sanitize(+ '<a href="https://example.com" target="named-window" rel="opener">link</a>',+ {+ ALLOWED_TAGS: ['a'],+ ALLOWED_ATTR: ['href', 'target', 'rel'],+ }+ );+ installedHook = addHook.mock.calls.find(+ ([entryPoint]) => entryPoint === 'afterSanitizeAttributes'+ )?.[1];+ const container = document.createElement('div');+ // eslint-disable-next-line no-unsanitized/property -- test-only: result is the output of the lazily hooked real sanitizer under assertion.+ container.innerHTML = result;+ const link = container.querySelector('a');+ const relTokens = (link.getAttribute('rel') || '')+ .split(/\s+/).filter(Boolean).map(token => token.toLowerCase());++ expect(addHook).toHaveBeenCalledWith(+ 'afterSanitizeAttributes',+ expect.any(Function)+ );+ expect(link.getAttribute('target')).toBe('_blank');+ expect(relTokens).toContain('noopener');+ expect(relTokens).toContain('noreferrer');+ expect(relTokens).not.toContain('opener');+ } finally {+ if (installedHook) {+ DOMPurify.removeHook('afterSanitizeAttributes', installedHook);+ }+ addHook.mockRestore();+ window.XSSProtection = originalXSSProtection;+ }+ });++ it('applies custom config overrides', () => {+ const result = sanitizeHtml(+ 'Intro <em data-note="kept">emphasis</em>',+ { ALLOWED_TAGS: ['em'], ALLOWED_ATTR: ['data-note'], ALLOW_DATA_ATTR: true }+ );++ expect(result).toContain('<em data-note="kept">emphasis</em>');+ expect(result).toContain('data-note="kept"');+ });++ it('returns an empty string for empty, null, and undefined input', () => {+ expect(sanitizeHtml('')).toBe('');+ expect(sanitizeHtml(null)).toBe('');+ expect(sanitizeHtml(undefined)).toBe('');+ });++ it('stringifies non-string input', () => {+ // 42 is truthy, so it does NOT take the `if (!dirty) return ''` early+ // exit above: it reaches sanitizeStable, which String()s it. The+ // default config sets KEEP_CONTENT, so DOMPurify allows '#text' and+ // the number survives as its own text node.+ expect(sanitizeHtml(42)).toBe('42');+ });++ it('falls back to escapeHtml and warns when DOMPurify is unavailable', () => {+ const warning = vi.spyOn(SafeLogger, 'warn');+ removeDOMPurify();++ expect(sanitizeHtml('<script>alert(1)</script>')).toBe(+ '<script>alert(1)</script>'+ );+ expect(warning).toHaveBeenCalledWith(+ 'DOMPurify not available, falling back to HTML escaping'+ );+ warning.mockRestore();+ });+});+++// sanitizeStable is the primitive both public entry points route through, and+// it had no direct coverage at all: `grep -rn sanitizeStable tests/js/`+// returned nothing. The property that makes the mXSS claim true is a+// FIXPOINT -- sanitize(sanitize(x)) === sanitize(x) -- because the sanitizer+// inspects a parse tree but ships a serialization of it, and the browser+// re-parses that serialization into a possibly different tree. Only when the+// string stops changing is the tree the browser builds one DOMPurify has+// already cleared.+describe('sanitizeStable reaches a sanitization fixpoint', () => {+ const CONFIG = { ALLOWED_TAGS: ['b', 'i', 'em', 'strong', 'span', 'p', 'div', 'a'], ALLOWED_ATTR: ['class', 'href', 'title'] };++ const PAYLOADS = [+ '<p>plain</p>',+ '<p>benign <strong>markup</strong> with <a href="https://example.com" title="ok">a link</a></p>',+ '<script>alert(1)</script>',+ '<img src=x onerror=alert(1)>',+ '<a href="javascript:alert(1)">click</a>',+ '<div><svg><p><style><!--</style><img src=x onerror=alert(1)></svg></div>',+ '<table><caption><svg><foreignObject><table><tr><td><img src=x onerror=alert(1)>'+ + '</td></tr></table></foreignObject></svg></caption></table>',+ '<noscript><p title="</noscript><img src=x onerror=alert(1)>">',+ '<form><table><form><tr><td onmouseover=alert(1)><a href=javascript:alert(1)>x</a></td></tr></form></table></form>',+ '<div title="prefix<!--suffix"><a title="<script src=x>" href="javascript:alert(1)">bad</a></div><!--',+ ];++ it.each(PAYLOADS)('is idempotent for %j', (payload) => {+ const once = sanitizeStable(payload, CONFIG);+ expect(typeof once).toBe('string');+ // The defining property: applying the sanitizer again changes nothing.+ expect(sanitizeStable(once, CONFIG)).toBe(once);+ // And the same must hold for the public entry point.+ const viaPublic = sanitizeHtml(payload);+ expect(sanitizeHtml(viaPublic)).toBe(viaPublic);+ });++ it.each(PAYLOADS)('output survives a serialize -> reparse round trip unchanged for %j', (payload) => {+ const sanitized = sanitizeStable(payload, CONFIG);+ const host = document.createElement('div');+ // eslint-disable-next-line no-unsanitized/property -- test-only: this is the serialize -> reparse hop the fixpoint has to survive.+ host.innerHTML = sanitized;+ // Reparsing must not resurrect executable nodes or handlers.+ expect(host.querySelectorAll('script, iframe, object, embed').length).toBe(0);+ for (const element of host.querySelectorAll('*')) {+ expect(element.getAttributeNames().some((name) => /^on/i.test(name))).toBe(false);+ }+ for (const anchor of host.querySelectorAll('[href]')) {+ expect((anchor.getAttribute('href') || '').toLowerCase())+ .not.toMatch(/^(?:javascript:|vbscript:|data:text\/html)/);+ }+ });++ it('keeps allowed markup intact instead of over-stripping', () => {+ const result = sanitizeStable('<p>hello <strong>world</strong></p>', CONFIG);+ expect(result).toContain('<strong>world</strong>');+ });++ it('falls closed to escaped text when the markup never stabilises', () => {+ const warning = vi.spyOn(SafeLogger, 'warn');+ // A sanitizer that never converges: each pass appends a marker, so no+ // two consecutive outputs are ever equal.+ let pass = 0;+ const original = globalThis.DOMPurify;+ globalThis.DOMPurify = { isSupported: true, sanitize: () => `<b>${++pass}</b>` };+ window.DOMPurify = globalThis.DOMPurify;++ try {+ const result = sanitizeStable('<b>x</b>', CONFIG);+ // No markup may be emitted -- the value is escaped, not shipped.+ expect(result).not.toContain('<b>');+ expect(result).toContain('<b>');+ expect(warning).toHaveBeenCalledWith(+ expect.stringContaining('did not reach a sanitization fixpoint')+ );+ } finally {+ globalThis.DOMPurify = original;+ window.DOMPurify = original;+ warning.mockRestore();+ }+ });+});diff --git a/tests/js/services/pdf-runtime.test.js b/tests/js/services/pdf-runtime.test.jsindex 00f68e78d6..80105579d0 100644--- a/tests/js/services/pdf-runtime.test.js+++ b/tests/js/services/pdf-runtime.test.js@@ -57,8 +57,17 @@ beforeEach(() => {pageHeight = 792;globalThis.jsPDF = FakePdf;globalThis.html2canvas = vi.fn().mockResolvedValue(canvas());+ // marked/DOMPurify are only presence checks here: the body is rendered+ // by ui.renderMarkdown (the hardened pipeline, covered end to end in+ // pdf-sanitization.test.js), which is a boundary fake in this file.window.marked = { parse: vi.fn((markdown) => String(markdown)) };window.DOMPurify = { isSupported: true, sanitize: vi.fn((html) => html) };+ window.XSSProtection = { sanitizeStable: vi.fn((html) => html) };+ window.ui = {+ renderMarkdown: vi.fn(+ (markdown) => `<div class="ldr-markdown-content">${markdown}</div>`,+ ),+ };globalThis.URLValidator = {safeAssign: vi.fn((element, property, value) => {element[property] = value;@@ -84,9 +93,17 @@ afterEach(() => {delete globalThis.URLValidator;delete window.marked;delete window.DOMPurify;+ delete window.XSSProtection;+ delete window.ui;delete window.alert;});+function renderReturns(html) {+ window.ui.renderMarkdown.mockReturnValue(+ `<div class="ldr-markdown-content">${html}</div>`,+ );+}+it('fails before rendering when jsPDF is unavailable', async () => {delete globalThis.jsPDF;await expect(generatePdf('Title', 'Report')).rejects.toThrow(@@ -113,7 +130,7 @@ it('requires the markdown parser and cleans its temporary DOM', async () => {});it('requires the sanitizer and cleans its temporary DOM', async () => {- window.marked.parse.mockReturnValue('<p>Report</p>');+ renderReturns('<p>Report</p>');delete window.DOMPurify;await expect(generatePdf('Title', '# Report')).rejects.toThrow('DOMPurify not loaded. Cannot generate PDF safely.',@@ -121,6 +138,29 @@ it('requires the sanitizer and cleans its temporary DOM', async () => {expect(document.querySelector('.ldr-pdf-content')).toBeNull();});+it.each([+ ['ui.renderMarkdown', () => { delete window.ui; }],+ ['XSSProtection.sanitizeStable', () => { delete window.XSSProtection; }],+])('fails closed when %s is unavailable', async (_name, remove) => {+ remove();+ await expect(generatePdf('Title', '# Report')).rejects.toThrow(+ 'Markdown sanitizer not loaded. Cannot generate PDF safely.',+ );+ expect(document.querySelector('.ldr-pdf-content')).toBeNull();+ expect(pdfInstances).toHaveLength(0);+});++it('fails closed when renderMarkdown degrades to its fallback output', async () => {+ window.ui.renderMarkdown.mockReturnValue(+ '<div class="alert alert-danger">Error rendering content: boom</div>',+ );+ await expect(generatePdf('Title', '# Report')).rejects.toThrow(+ 'Markdown rendering failed. Cannot generate PDF safely.',+ );+ expect(document.querySelector('.ldr-pdf-content')).toBeNull();+ expect(pdfInstances).toHaveLength(0);+});+it('sanitizes and walks structured report content into selectable PDF operations', async () => {const html = `<h1>Migration report</h1>@@ -139,14 +179,12 @@ it('sanitizes and walks structured report content into selectable PDF operations<section>Fallback text remains selectable</section><section><svg></svg></section>`;- window.marked.parse.mockReturnValue(html);+ renderReturns(html);const result = await generatePdf('Migration', '# ignored');expect(result).toBe(createdBlob);- expect(window.DOMPurify.sanitize).toHaveBeenCalledWith(html, {- ADD_TAGS: ['semantics', 'annotation'],- });+ expect(window.ui.renderMarkdown).toHaveBeenCalledWith('# ignored');expect(document.querySelector('.ldr-pdf-content')).toBeNull();expect(pdfInstances).toHaveLength(1);const pdf = pdfInstances[0];@@ -184,7 +222,7 @@ it('sanitizes and walks structured report content into selectable PDF operations});it('contains one malformed element and keeps producing the remaining PDF', async () => {- window.marked.parse.mockReturnValue('<p>Broken</p><p>Still rendered</p>');+ renderReturns('<p>Broken</p><p>Still rendered</p>');class PartiallyFailingPdf extends FakePdf {constructor() {super();@@ -217,7 +255,7 @@ it('contains one malformed element and keeps producing the remaining PDF', asyncit('paginates long structured reports and redraws table ownership headers', async () => {pageHeight = 115;- window.marked.parse.mockReturnValue(`+ renderReturns(`<h1>Long migration report</h1><h2>Next section</h2><p>Paragraph crossing the remaining page</p>@@ -247,7 +285,7 @@ it('paginates long structured reports and redraws table ownership headers', asynit('wraps long links and citations across pages without losing their targets', async () => {pageWidth = 140;pageHeight = 90;- window.marked.parse.mockReturnValue(`+ renderReturns(`<p>alpha beta gamma <a href="https://example.test/report-source">report source</a> omega psi</p><p>alpha beta [[99]](https://example.test/citation) omega psi</p><ul>@@ -281,7 +319,7 @@ it('wraps long links and citations across pages without losing their targets', a});it('falls back to a readable placeholder when an image URL is rejected', async () => {- window.marked.parse.mockReturnValue(+ renderReturns('<img src="https://untrusted.example/image.jpg">',);globalThis.URLValidator.safeAssign.mockImplementation(() => {@@ -302,7 +340,7 @@ it('falls back to a readable placeholder when an image URL is rejected', async (});it('contains an html2canvas failure to the unsupported element', async () => {- window.marked.parse.mockReturnValue('<section><svg></svg></section>');+ renderReturns('<section><svg></svg></section>');globalThis.html2canvas.mockRejectedValue(new Error('canvas tainted'));await expect(generatePdf('Report', 'ignored')).resolves.toBe(createdBlob);@@ -316,7 +354,7 @@ it('contains an html2canvas failure to the unsupported element', async () => {});it('keeps the loading state until rendering completes and revokes the download URL', async () => {- window.marked.parse.mockReturnValue('<section><svg></svg></section>');+ renderReturns('<section><svg></svg></section>');let finishCanvas;globalThis.html2canvas.mockImplementation(() => new Promise((resolve) => {finishCanvas = resolve;@@ -361,7 +399,7 @@ it('safely reduces legacy HTML research data to text before PDF rendering', asyncreated_at: '2026-09-01T10:00:00Z',}, 'research-3299');- const markdownInput = window.marked.parse.mock.calls[0][0];+ const markdownInput = window.ui.renderMarkdown.mock.calls[0][0];expect(markdownInput).toContain('# Hello');expect(markdownInput).toContain('Safe & sound');expect(markdownInput).not.toContain('<img');diff --git a/tests/js/services/pdf-sanitization.test.js b/tests/js/services/pdf-sanitization.test.jsnew file mode 100644index 0000000000..6b244399ef--- /dev/null+++ b/tests/js/services/pdf-sanitization.test.js@@ -0,0 +1,172 @@+/**+ * PDF export must render report content under the SAME hardened policy as+ * the on-screen report view (services/ui.js renderMarkdown): raw+ * author-supplied HTML is escaped to literal text, and the output is+ * sanitized to a reparse fixpoint under the restrictive allowlist. These+ * tests run the REAL marked + DOMPurify + XSSProtection + ui.renderMarkdown+ * pipeline; only jsPDF / html2canvas are boundary fakes, and the text handed+ * to jsPDF is what the PDF would actually contain.+ */++import createDOMPurify from 'dompurify';++import { installDomPurifyHappyDomShims } from '../happy-dom-dompurify-shim.js';+import { installMathMlNamespaceApproximation } from '../happy-dom-mathml-namespace-approximation.js';++import '@js/security/url-validator.js';+import '@js/security/xss-protection.js';+import '@js/services/ui.js';+import '@js/services/pdf.js';++const { generatePdf } = window.pdfService;++let pdf;++class FakePdf {+ constructor() {+ this.internal = {+ pageSize: { getWidth: () => 612, getHeight: () => 792 },+ };+ for (const name of [+ 'setFontSize', 'setTextColor', 'text', 'setFont', 'addPage',+ 'setFillColor', 'rect', 'textWithLink', 'setDrawColor',+ 'setLineWidth', 'line', 'addImage',+ ]) {+ this[name] = vi.fn();+ }+ this.splitTextToSize = vi.fn((text) => String(text).split('\n'));+ this.getTextWidth = vi.fn((text) => String(text).length * 5);+ this.output = vi.fn(() => new Blob(['pdf']));+ pdf = this;+ }+}++beforeAll(async () => {+ installDomPurifyHappyDomShims();+ installMathMlNamespaceApproximation();+ const { Marked } = await import('marked');+ const markedKatex = (await import('marked-katex-extension')).default;+ const instance = new Marked();+ instance.use(markedKatex({ throwOnError: false, errorColor: 'currentColor' }));+ globalThis.marked = instance;+ // Capture the opted-in namespace accessor in this instance. The default+ // instance was created by the static import before the shim was installed.+ globalThis.DOMPurify = createDOMPurify(window);+});++afterAll(() => {+ delete globalThis.marked;+ delete globalThis.DOMPurify;+});++beforeEach(() => {+ document.body.replaceChildren();+ pdf = undefined;+ globalThis.jsPDF = FakePdf;+ globalThis.html2canvas = vi.fn().mockResolvedValue({+ width: 10,+ height: 10,+ toDataURL: () => 'data:image/png;base64,x',+ });+ globalThis.URLValidator = {+ ...(globalThis.URLValidator || {}),+ safeAssign: vi.fn((el, prop, value) => { el[prop] = value; }),+ };+ window.pwned = undefined;+});++afterEach(() => {+ vi.restoreAllMocks();+ delete globalThis.jsPDF;+ delete globalThis.html2canvas;+});++function pdfText() {+ return [...pdf.text.mock.calls, ...pdf.textWithLink.mock.calls]+ .map((call) => String(call[0]))+ .join('\n');+}++describe('generatePdf() uses the hardened rendering pipeline', () => {+ test('shows raw author HTML as literal text, matching the screen view', async () => {+ const markdown = '# Report\n\n<img src=x onerror="window.pwned=true">\n\n'+ + '<script>window.pwned = true</script>\n\nPlain paragraph';++ // What the screen path displays for the same content.+ const screen = document.createElement('div');+ // eslint-disable-next-line no-unsanitized/property -- test-only: parsing renderMarkdown()'s sanitized output to compare with the PDF body.+ screen.innerHTML = window.ui.renderMarkdown(markdown);+ expect(screen.querySelector('img, script')).toBeNull();+ const screenText = screen.textContent;+ expect(screenText).toContain('<img src=x onerror=');+ expect(screenText).toContain('<script>');++ await generatePdf('Title', markdown);++ const text = pdfText();+ expect(text).toContain('Plain paragraph');+ // Raw HTML is interpreted as markup on neither surface: it reaches+ // the PDF as visible text rather than being dropped or executed.+ expect(text).toContain('<img src=x onerror=');+ expect(text).toContain('<script>');+ expect(window.pwned).toBeUndefined();+ expect(document.querySelector('.ldr-pdf-content')).toBeNull();+ });++ test('never lets default-profile SVG/MathML foreign content through', async () => {+ const markdown = '<svg><animate onbegin="window.pwned=true" attributeName="x" dur="1s"></svg>\n\n'+ + '<math><mtext><table><mglyph><style><img src=x onerror="window.pwned=true"></style></mglyph></table></mtext></math>\n\n'+ + 'After';++ await generatePdf('Title', markdown);++ expect(window.pwned).toBeUndefined();+ expect(pdfText()).toContain('After');+ expect(document.querySelector('svg, math')).toBeNull();+ });++ test('does not call DOMPurify directly with the permissive default profile', async () => {+ const sanitize = vi.spyOn(globalThis.DOMPurify, 'sanitize');++ await generatePdf('Title', 'Some *text*');++ // Every call must carry an explicit config (the restrictive+ // allowlist); a bare sanitize(html) or an ADD_TAGS-only call is the+ // default profile this change removes.+ expect(sanitize).toHaveBeenCalled();+ for (const call of sanitize.mock.calls) {+ expect(call[1]).toBeDefined();+ expect(call[1].ALLOWED_TAGS).toBeDefined();+ expect(call[1].ADD_TAGS).toBeUndefined();+ }+ });++ test('keeps KaTeX math readable as LaTeX in the PDF', async () => {+ await generatePdf('Title', 'Inline $x^2$ here\n\n$$\ny = mx + b\n$$\n');++ const text = pdfText();+ expect(text).toContain('$x^2$');+ expect(text).toContain('$$y = mx + b$$');+ });++ test('keeps ordinary markdown structure and safe links', async () => {+ await generatePdf(+ 'Title',+ '# Heading\n\n- item one\n- item two\n\n[the source](https://example.test/source)\n\n'+ + '[bad](javascript:window.pwned=true)',+ );++ const text = pdfText();+ expect(text).toContain('Heading');+ expect(text).toContain('item one');+ expect(pdf.textWithLink).toHaveBeenCalledWith(+ expect.stringContaining('the source'),+ expect.any(Number),+ expect.any(Number),+ { url: 'https://example.test/source' },+ );+ const urls = pdf.textWithLink.mock.calls.map((call) => call[3]?.url);+ expect(urls.every((url) => !String(url).startsWith('javascript:'))).toBe(true);+ expect(window.pwned).toBeUndefined();+ });+});diff --git a/tests/js/services/ui.test.js b/tests/js/services/ui.test.jsindex a1b6739860..2de8f22624 100644--- a/tests/js/services/ui.test.js+++ b/tests/js/services/ui.test.js@@ -5,10 +5,28 @@* inline errors, escapeHtmlFallback, and notification system.*/-import RealDOMPurify from 'dompurify';+import DOMPurify from 'dompurify';++import { installMathMlNamespaceApproximation } from '../happy-dom-mathml-namespace-approximation.js';++const RealDOMPurify = DOMPurify;import '@js/security/xss-protection.js';import '@js/services/ui.js';+// services/ui.js's safeSetHTML now fails CLOSED: with no DOMPurify on the page+// it assigns the markup to textContent instead of innerHTML, so showSpinner /+// showError / showMessage produce no elements at all and every+// `querySelector(...)` below returns null. Production always has the sanitizer+// (base.html loads security/xss-protection.js on every page and the Vite+// bundle publishes window.DOMPurify), so install it here to mirror that rather+// than exercise the sanitizer-missing degradation.+//+// This runs after the imports above (ES module evaluation order), which is why+// xss-protection.js's load-time `afterSanitizeAttributes` tabnabbing hook is+// not registered for this suite -- nothing here asserts on rel="noopener".+globalThis.DOMPurify = DOMPurify;+window.DOMPurify = DOMPurify;+const ui = window.ui;// showSpinner, showError and showAlert render through safeSetHTML, which@@ -355,25 +373,62 @@ describe('renderMarkdown with KaTeX math', () => {// The setup mirrors app.js so renderMarkdown takes the marked-rendering// branch instead of falling through to the plaintext-escape fallback.beforeAll(async () => {+ // happy-dom does not parse <math> into the MathML namespace on its+ // own (no foreign-content support at all), so without this,+ // DOMPurify's own namespace-validity check (a real mXSS defense: a+ // MathML-only tag name observed in the HTML namespace is force-+ // removed) strips the MathML accessibility subtree (annotation,+ // semantics, mrow, ...) even though those elements survive in real+ // browsers. installMathMlNamespaceApproximation() is a coarse,+ // tag-name-based approximation good enough for that -- see its+ // header for exactly what it does and does not model, and why it+ // must never be installed in a suite (like+ // tests/js/security/mxss-reparse-invariant.test.js) that asserts a+ // namespace-confusion invariant.+ installMathMlNamespaceApproximation();const { Marked } = await import('marked');const markedKatex = (await import('marked-katex-extension')).default;- const DOMPurify = (await import('dompurify')).default;const m = new Marked();// Mirror app.js so the test exercises the production config.m.use(markedKatex({ throwOnError: false, errorColor: 'currentColor' }));globalThis.marked = m;- globalThis.DOMPurify = DOMPurify;+ // DOMPurify captures native accessors when an instance is created.+ // Create this benign-rendering instance AFTER the namespace shim;+ // the module's default instance captured happy-dom's HTML getter.+ const createDOMPurify = DOMPurify;+ globalThis.DOMPurify = createDOMPurify(window);});afterAll(() => {delete globalThis.marked;- delete globalThis.DOMPurify;+ // Restore, don't delete: this file installs DOMPurify as a global at+ // module scope for safeSetHTML's fail-closed branch, so deleting it+ // here would leave any later describe block without a sanitizer.+ globalThis.DOMPurify = DOMPurify;});- // happy-dom does not parse <math> into the MathML namespace, so DOMPurify- // strips the MathML accessibility subtree (annotation, semantics, mrow, ...)- // even though those elements survive in real browsers. We assert on the- // KaTeX HTML rendering branch instead — that is the visible math layer- // and the proof that the extension actually ran.+ // We still assert on the KaTeX HTML rendering branch — that is the+ // visible math layer and the proof that the extension actually ran, and+ // it is what a browser shows.++ it('preserves mathematical semantics in the accessible MathML tree', () => {+ const template = document.createElement('template');+ // eslint-disable-next-line no-unsanitized/property -- test-only: inspect actual renderer output.+ template.innerHTML = ui.renderMarkdown('$\\mathbb{R}+\\mathrm{x}$');+ const math = template.content.querySelector('math');+ expect(math.querySelector('mi[mathvariant="double-struck"]').textContent).toBe('R');+ expect(math.querySelector('mi[mathvariant="normal"]').textContent).toBe('x');+ expect(math.querySelector('annotation').getAttribute('encoding')).toBe('application/x-tex');+ expect(math.querySelector('annotation').textContent).toBe('\\mathbb{R}+\\mathrm{x}');+ });++ it('preserves current KaTeX layout classes for fractions and stretchy braces', () => {+ const template = document.createElement('template');+ // eslint-disable-next-line no-unsanitized/property -- test-only: inspect actual renderer output.+ template.innerHTML = ui.renderMarkdown('$\\overbrace{\\frac{1}{2}}^{n}$');+ for (const name of ['katex-base', 'katex-strut', 'katex-sizing', 'katex-stretchy']) {+ expect(template.content.querySelector(`.${name}`)).not.toBeNull();+ }+ });it('renders inline math as KaTeX HTML', () => {const result = ui.renderMarkdown('The equation $E=mc^2$ is famous');@@ -389,17 +444,18 @@ describe('renderMarkdown with KaTeX math', () => {});it('renders math alongside other markdown', () => {- // The leading "Intro." paragraph is a deliberate sacrificial node.+ // The leading "Intro." paragraph was a deliberate sacrificial node.// DOMPurify >=3.4.8 reads element names through the cached// Node.prototype.nodeName getter (anti-clobbering hardening). happy-dom's- // getter returns "" when invoked that way, so the first top-level node of- // the sanitized fragment is treated as an unknown tag and unwrapped — its- // tags dropped, text kept (a leading `<h1>Title</h1>` collapses to- // `Title`). Real browsers return the correct tag name and are unaffected,- // so this is a test-env-only artifact, tracked upstream at- // https://github.com/capricorn86/happy-dom/issues/2182. Prefixing a- // throwaway paragraph keeps the heading off the first slot so we can still- // assert on its `<h1>` rendering here. See also the MathML note above.+ // BASE getter returns "" when invoked that way, so the first top-level+ // node of the sanitized fragment was treated as an unknown tag and+ // unwrapped — its tags dropped, text kept (a leading `<h1>Title</h1>`+ // collapsed to `Title`). Real browsers return the correct tag name and+ // are unaffected, so it was a test-env-only artifact, tracked upstream at+ // https://github.com/capricorn86/happy-dom/issues/2182.+ // tests/js/happy-dom-dompurify-shim.js repairs it globally now, so the+ // prefix is no longer load-bearing — it is kept only so the assertions+ // below stay comparable with the older recorded output.const result = ui.renderMarkdown('Intro.\n\n# Title\n\nSome text $x^2$ more text\n\n- list item');expect(result).toContain('<h1');expect(result).toContain('<li>');@@ -646,7 +702,7 @@ describe('safeSetHTML fails closed without 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).toHaveBeenCalled();expect(sanitize.mock.calls[0][0]).toContain('boom');expect(container.querySelector('.ldr-error-message')).not.toBeNull();});diff --git a/tests/news/test_news_api_contract.py b/tests/news/test_news_api_contract.pyindex 8e524ea44f..95a66ff142 100644--- a/tests/news/test_news_api_contract.py+++ b/tests/news/test_news_api_contract.py@@ -38,8 +38,13 @@ N_SOURCES = 4 # > the feed's top-N (3): links must be capped, not unbounded.@pytest.fixture-def seeded_news_db(tmp_path):- """Real temp-file SQLite seeded with one completed news-style research."""+def seeded_news_db(tmp_path, request):+ """Real temp-file SQLite seeded with one completed news-style research.++ Its ``report_content`` is ``ANSWER_ONLY`` unless a test passes another+ body through indirect parametrization.+ """+ report_content = getattr(request, "param", ANSWER_ONLY)engine = create_engine(f"sqlite:///{tmp_path / 'news_contract.db'}")Base.metadata.create_all(engine)SessionLocal = sessionmaker(bind=engine)@@ -54,7 +59,7 @@ def seeded_news_db(tmp_path):status="completed",created_at="2026-04-25T12:00:00+00:00",completed_at="2026-04-25T12:05:00+00:00",- report_content=ANSWER_ONLY,+ report_content=report_content,research_meta={"is_news_search": True},))@@ -116,6 +121,28 @@ def test_news_feed_findings_is_answer_only(seeded_news_db):assert "## Sources" not in findings+# A detailed report saved in NO_HYPERLINKS mode before the save site removed+# the generator's appended-sources sentinel: the answer, the sentinel, and+# the Sources block the split kept with the answer.+LEGACY_SENTINEL_BODY = (+ ANSWER_ONLY+ + "\n\n<!-- LDR_APPENDED_SOURCES_START -->\n\n"+ + "## Sources\n\n[1] Quantum Source 1\n URL: https://q1.example\n"+)+++ "seeded_news_db", [LEGACY_SENTINEL_BODY], indirect=True, ids=["legacy"]+)+def test_news_feed_findings_drop_the_sources_sentinel(seeded_news_db):+ """The sentinel is an HTML comment, which the card's renderMarkdown()+ shows as literal text, so it must not reach the findings."""+ findings = _feed_item(seeded_news_db)["findings"]+ assert "LDR_APPENDED_SOURCES_START" not in findings+ assert findings.startswith(ANSWER_ONLY)+ assert "URL: https://q1.example" in findings++def test_news_feed_links_array_populated_from_research_resources(seeded_news_db,):diff --git a/tests/security/test_client_side_xss_sinks.py b/tests/security/test_client_side_xss_sinks.pyindex 1a7245ed50..53bc40f5f6 100644--- a/tests/security/test_client_side_xss_sinks.py+++ b/tests/security/test_client_side_xss_sinks.py@@ -252,6 +252,15 @@ def classify_escaper(text: str, line_index: int) -> str:# a module-level one; both must map ``"`` to the entity.if QUOT_ENTITY in body or QUOT_ENTITY in text:return ENTITY+ if re.search(+ r"replace\(\s*/\"/g\s*,\s*['\"]" + re.escape(QUOT_ENTITY), body+ ) and re.search(r"replace\(\s*/'/g\s*,\s*['\"]'", body):+ # A chained quote-to-entity replace after a base call, e.g.+ # ``escapeHtml(text).replace(/"/g, '"').replace(/'/g,+ # ''')``. Still an entity escaper (assuming the base call+ # handles ``& < >``) -- just spelled without one bracketed+ # character class, which the check above looks for.+ return ENTITYif re.search(r"=\s*\w+(?:\.\w+)*\s*\|\|\s*[A-Za-z_$][\w$]*\s*;", head):return ALIASreturn NO_OP@@ -291,11 +300,26 @@ _SYNTHETIC_TEXT_NODE = (_SYNTHETIC_NO_OP = "const esc = window.escapeHtml || (s => String(s || ''));\n"+_SYNTHETIC_CHAINED_ENTITY = _SYNTHETIC_TEXT_NODE + (+ "function escapeHtmlAttribute(text) {\n"+ " return escapeHtml(text).replace(/\"/g, '"').replace(/'/g, ''');\n"+ "}\n"+)++def test_escaper_classifier_recognises_an_entity_escaper():found = escaper_definitions(_SYNTHETIC_ENTITY)assert found == [(1, "esc", ENTITY)], found+def test_escaper_classifier_recognises_a_chained_quote_replace_as_entity():+ """An entity escaper spelled as two ``.replace()`` calls, not one+ bracketed character class -- the shape ``escapeHtmlAttribute`` takes+ in components/context-overflow.js."""+ found = escaper_definitions(_SYNTHETIC_CHAINED_ENTITY)+ assert (6, "escapeHtmlAttribute", ENTITY) in found, found++def test_escaper_classifier_flags_a_text_node_only_escaper():found = escaper_definitions(_SYNTHETIC_TEXT_NODE)assert found == [(1, "escapeHtml", TEXT_NODE_ONLY)], found@@ -318,6 +342,12 @@ REVIEWED_NON_ENTITY_ESCAPERS = {# NOT safe inside a quoted attribute (see the attribute census)."components/context-overflow.js::escapeHtml": TEXT_NODE_ONLY,"components/progress.js::escapeHtml": TEXT_NODE_ONLY,+ # Fixed: pages/news.js::escapeAttr (a JavaScript-string escaper used+ # inside HTML attributes -- see the misuse census below) was removed+ # entirely; ids/queries now travel in data-* attributes read back+ # through event delegation. See+ # test_news_no_longer_has_a_javascript_string_attribute_escaper.+ ## Identity fallback: when ``window.escapeHtml`` is absent this# escapes nothing at all, and ESLint accepts it because it is# spelled ``esc``.@@ -457,21 +487,19 @@ def test_misuse_scanner_is_quiet_when_the_same_escaper_is_text_context():#: Attribute-context substitutions escaped by something that does not#: neutralise ``"``, frozen after review. Each entry is a real defect;#: the fence exists so no *new* one is introduced silently.-KNOWN_ATTRIBUTE_ESCAPER_MISUSES = {- # DEFECT. ``escapeHtml`` here is the module-local text-node encoder- # (context-overflow.js:45). ``req.research_query`` reaches- # ``<td ... title="${escapeHtml(req.research_query)}">`` and the- # rows land on ``tbody.innerHTML`` with no DOMPurify in the path,- # so a query containing a double quote injects attributes. The- # suppression above that sink claims "all user-supplied strings- # ... are run through escapeHtml"; the claim is true and the- # protection is still absent.- "components/context-overflow.js": [- "escapeHtml(req.model)",- "escapeHtml(req.research_query)",- "escapeHtml(stat.model)",- ],-}+#:+#: Both previously-pinned defects are fixed:+#:+#: * components/context-overflow.js's title attributes used the+#: module-local text-node ``escapeHtml`` (``escapeHtml(req.model)`` etc);+#: they now go through ``escapeHtmlAttribute`` (an entity escaper, see+#: the census above), a distinct call the misuse scanner's+#: ``_ESCAPER_CALL`` regex does not even match -- so it correctly finds+#: nothing to flag at these sites any more.+#: * pages/news.js's ``escapeAttr`` (a JS-string escaper misused in HTML+#: attributes) was removed entirely; see+#: test_news_no_longer_has_a_javascript_string_attribute_escaper.+KNOWN_ATTRIBUTE_ESCAPER_MISUSES = {}def test_attribute_escaper_misuses_are_exactly_the_reviewed_set():@@ -513,8 +541,9 @@ def test_news_action_values_do_not_enter_inline_javascript_handlers():"data-search-type=\"${escapeHtml(item.type || 'quick')}\""in recent_body)- assert "e.target.closest('[data-news-action]')" in text- assert "newsItem.dataset.newsId" in text+ assert "event.target.closest('[data-news-action]')" in text+ assert "trustedNewsActionControls.get(actionTarget)" in text+ assert "actionCard.dataset.newsId" in textassert "e.target.closest('[data-news-page-action]')" in text@@ -523,11 +552,21 @@ def test_news_html_is_rendered_through_dompurify_not_raw_innerhtml():text = (STATIC_JS / "pages" / "news.js").read_text(encoding="utf-8")helper = text.split("function safeRenderHTML(container, htmlString) {")assert len(helper) == 2, "safeRenderHTML was renamed or removed"- body = helper[1][:1500]+ body = helper[1].split("\nfunction ")[0]assert "window.DOMPurify.sanitize(" in bodyassert "RETURN_DOM_FRAGMENT: true" in body# The no-DOMPurify branch must degrade to text, never to markup.assert "container.textContent = htmlString;" in body+ # Negative half. Without this the test is all positive assertions: a+ # second, unguarded `container.innerHTML = htmlString;` added anywhere+ # in the function would leave every assertion above still true. This+ # also makes the exact end of the body window irrelevant -- a slice+ # that ends too early can only ever *hide* an innerHTML write, and a+ # slice that runs long cannot invent one, since the count is zero.+ assert body.count("container.innerHTML") == 0, (+ "safeRenderHTML writes innerHTML directly; the DOMPurify fragment "+ "path is no longer the only way markup reaches the container"+ )def test_context_overflow_rows_reach_innerhtml_without_sanitisation():@@ -565,40 +604,63 @@ def _ui_js() -> str:def test_report_markdown_is_dompurify_sanitised_before_display():+ """Pin the render path, then pin that sanitisation cannot be skipped.++ Fixed from a prior fail-OPEN (see the test below): the marked-based+ render path used to fall back to raw, unsanitized ``processedHtml``+ whenever DOMPurify was undefined. It now requires ``marked``,+ ``DOMPurify`` AND ``sanitizeStable`` to all be present before running+ at all -- any one missing falls through to the escaped-plaintext+ fallback, never to raw ``marked`` output.+ """body = _ui_js().split("function renderMarkdown(markdown) {")[1]body = body.split("\nfunction ")[0]assert "marked.parse(markdown, { renderer })" in body- assert "DOMPurify.sanitize(processedHtml" in body- # The sanitised value, not the parsed one, is what is returned.- assert "${sanitized}" in body+ assert (+ "typeof marked !== 'undefined' && typeof DOMPurify !== 'undefined'"+ in body+ )+ assert "&& typeof sanitizeStable === 'function') {" in body+ assert "sanitizeStable(html, MARKDOWN_SANITIZE_CONFIG)" in body+ # The sanitised/hardened/reprocessed value, not the raw parsed one, is+ # what is returned.+ assert "${finalHtml}" in body+++def test_markdown_sanitize_stable_is_a_dompurify_reparse_fixpoint():+ """``sanitizeStable`` (security/xss-protection.js) is the DOMPurify+ boundary ``renderMarkdown`` relies on above -- proves the claim is not+ just a name. It reparses to a fixpoint (mXSS hardening) but the+ sanitiser underneath every pass is still real ``DOMPurify.sanitize``.+ """+ text = (STATIC_JS / "security" / "xss-protection.js").read_text(+ encoding="utf-8"+ )+ body = text.split("function sanitizeStable(dirty, config) {")[1]+ body = body.split("\n function ")[0]+ assert "DOMPurify.sanitize(current, config)" in bodydef 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.+ ``renderMarkdown``'s marked-based render path (with it, the only path+ that produces ``sanitizeStable``-derived HTML) requires ``marked``,+ ``DOMPurify`` and ``sanitizeStable`` together; 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 -- but (unlike before) the+ render path disappears with it, rather than silently going raw."""- 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.+ body = _render_markdown_body(_strip_js_comments(_ui_js()))+ assert "typeof DOMPurify !== 'undefined'" in body+ assert "typeof sanitizeStable === 'function'" in body+ assert "DOMPurify?.isSupported === true" in body+ assert "return _escapedPlaintextFallback(markdown)" in bodyassert ": processedHtml" not in bodyassert "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 (@@ -623,9 +685,13 @@ def test_rendered_report_links_carry_noopener():body = _ui_js()assert 'rel="noopener noreferrer" ' in bodyassert "renderer.link = function(token)" in body- # ...and DOMPurify must be told to keep the attributes it just added,- # or the wrapper would be undone by the sanitiser.- assert "ADD_ATTR: ['target', 'rel']" in body+ # ...and the sanitizer's explicit attribute allowlist must include the+ # attributes the wrapper just added, or they would be stripped by the+ # sanitiser that immediately follows (sanitizeStable(html,+ # MARKDOWN_SANITIZE_CONFIG) above).+ body_attr = body.split("const MARKDOWN_ALLOWED_ATTR = [")[1]+ body_attr = body_attr.split("];")[0]+ assert "'target', 'rel'" in body_attrdef test_note_markdown_renderer_escapes_before_building_markup():@@ -814,25 +880,83 @@ def test_snippet_sanitiser_allows_no_event_handler_attributes():assert "ALLOW_DATA_ATTR: false" in text-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.+def test_safe_set_html_fails_closed_without_dompurify():+ """``safeSetHTML`` must fail CLOSED when no sanitizer is available.++ The no-DOMPurify branch used to assign ``element.innerHTML = html``+ directly (unsanitised) on the theory that callers only pass+ controlled content -- making the safety of every call site, present+ and future, depend on a comment.++ A prior version of this test pinned that fix to the exact source line+ it landed as (``if (typeof DOMPurify !== 'undefined') {`` /+ ``element.innerHTML = DOMPurify.sanitize(html);``). A later,+ behaviour-preserving refactor routed the same guarded write through+ ``window.sanitizeHtml`` (security/xss-protection.js) instead of a+ bare ``DOMPurify.sanitize`` call -- so it runs the same+ ``sanitizeStable()`` fixpoint loop under ``SANITIZE_CONFIG`` as+ ``safeSetInnerHTML`` -- and that exact-line assertion started failing+ on code that was, if anything, more correct than before. That+ brittleness is exactly the bug: pinning an incidental spelling+ instead of the invariant that spelling was standing in for.++ This asserts the invariant directly instead: there is exactly one+ ``innerHTML`` write in the function, it only executes inside a+ guard that checks some sanitizer function is actually available, the+ value assigned there is that same sanitizer's OWN output (never raw+ ``html``), and a non-HTML (``textContent``) fallback exists for when+ the guard is false."""body = _ui_js().split("function safeSetHTML(element, html) {")[1]- body = _strip_js_comments(body.split("\n/**")[0])+ body = _strip_js_comments(body.split("\nfunction ")[0])assert "DOMPurify?.isSupported === true" in body- assert "element.innerHTML = DOMPurify.sanitize(html);" in body- # 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)++ # No second, unguarded write -- the guarded one below is the only path+ # from `html` to `innerHTML`.+ assert body.count("element.innerHTML") == 1++ guard = re.search(+ r"if\s*\([^{}]*?typeof\s+([\w.]*sanitize\w*)\s*===\s*'function'\s*\)\s*\{"+ r"(?P<block>.*?)\n \}",+ body,+ re.IGNORECASE | re.DOTALL,+ )+ assert guard, "safeSetHTML has no sanitizer-availability guard"+ sanitizer_name = guard.group(1)+ block = guard["block"]++ # The guarded write sanitizes through the checked function itself,+ # not through some other name and not through raw `html`. An optional+ # trailing options object (e.g. `{ SAFE_FOR_TEMPLATES: false }`) is+ # permitted -- the invariant is that `html` is the sanitizer's first+ # and only *value* argument, not that no options are ever passed. A+ # bare `element.innerHTML = html` (no call at all) still fails this,+ # as does routing through any other name.+ #+ # Two loopholes the permissive options clause used to leave open, now+ # closed. (1) The statement is anchored on a trailing `;`, so+ # `sanitize(html, {...}) + html` -- sanitized output concatenated with+ # the raw value -- no longer satisfies it. (2) The options object may+ # not re-admit what the sanitizer exists to strip: `ADD_TAGS` /+ # `ADD_ATTR` turn the call back into a pass-through for exactly the+ # `<script>`/`on*` shapes this file is about, so an options object+ # mentioning either is rejected rather than waved through as "just+ # config".+ assert re.search(+ r"element\.innerHTML\s*=\s*"+ + re.escape(sanitizer_name)+ + r"\(html(?:\s*,\s*\{(?![^{}]*\bADD_(?:TAGS|ATTR)\b)[^{}]*\})?\)"+ r"\s*;",+ block,+ ), (+ f"guarded innerHTML write does not sanitize through {sanitizer_name}(html)"+ )++ # Outside the guard -- i.e. when the sanitizer is unavailable -- the+ # function falls back to text, never to raw HTML.+ after_guard = body[guard.end() :]+ assert "element.innerHTML" not in after_guard+ assert "element.textContent" in after_guard# ---------------------------------------------------------------------@@ -897,79 +1021,44 @@ def test_no_cross_origin_blank_anchor_ships_without_noopener():def test_dompurify_tabnabbing_hook_registration_is_lazy_and_idempotent():- """Static shape of the tabnabbing hook registration in xss-protection.js.-- The hook must not be registered only inside a one-shot load-time- ``if (hasDOMPurify()) { DOMPurify.addHook(...) }`` guard: a DOMPurify- bound after the script loads would then never get it. Instead a- lazy ensure, idempotent per DOMPurify instance, runs at load time and- before each of the module's own sanitize calls, and is exported for- other sanitizing callers (renderMarkdown in services/ui.js). Every- sanitize path whose config lets ``target`` through (SANITIZE_CONFIG in- xss-protection.js, renderMarkdown's ``ADD_ATTR``) ensures the hook- first, so correctness does not depend on the load-time call or on- script order. The remaining direct ``DOMPurify.sanitize`` callers- (safeSetHTML in ui.js, news.js, pdf.js, semantic_search.js) keep- DOMPurify's default attribute list or an explicit one, neither of which- contains ``target``, so no link they emit can open a new browsing- context and they need no hook. Behaviour is pinned by- tests/js/security/xss-protection-late-dompurify.test.js and- render-markdown-tabnabbing.test.js; this only guards the static shape,- including that the hook reads and writes the node only through the- captured Element.prototype accessors (a <form> control can shadow the- instance's own) and that renderMarkdown calls the ensure before it- sanitizes with ``target`` in ``ADD_ATTR``. Comments are stripped first- so a commented-out call cannot satisfy it.- """+ """Every string sanitizer reaches the shared, clobber-safe lazy hook."""text = _strip_js_comments((STATIC_JS / "security" / "xss-protection.js").read_text(encoding="utf-8"))- # No load-order-bound registration, however it is formatted.- assert not re.search(- r"if\s*\(\s*hasDOMPurify\s*\(\s*\)\s*\)\s*\{\s*DOMPurify\s*\.\s*addHook\s*\(",- text,- )- # A lazy ensure exists, is called at load time and before sanitizing,- # and is exported for other callers.- assert re.search(r"function\s+_ensureTabnabbingHook\s*\(", text)- assert len(re.findall(r"\b_ensureTabnabbingHook\s*\(\s*\)\s*;", text)) >= 4- assert re.search(- r"ensureTabnabbingHook\s*:\s*_ensureTabnabbingHook\b", text+ assert "const _hookedPurifiers = new WeakSet()" in text+ assert "_hookedPurifiers.has(purifier)" in text+ assert "_hookedPurifiers.add(purifier)" in text+ assert (+ "purifier.addHook('afterSanitizeAttributes', hardenLinkTarget)" in text)- # The hook never trusts a property looked up on the node: a <form>- # control named or id'd like a built-in shadows it on the instance.- hook_start = text.index("addHook('afterSanitizeAttributes'")- hook = text[hook_start : text.index("_hookedPurifiers.add(", hook_start)]+ assert "ensureTabnabbingHook: _ensureTabnabbingHook" in text+ assert "ensureDOMPurifyHooks: _ensureTabnabbingHook" in text++ hook = text.split("function hardenLinkTarget(node) {", 1)[1]+ hook = hook.split("\n function ", 1)[0]assert not re.search(r"\bnode\s*(\.|\[)", hook), hook- assert re.search(- r"\.setAttr\.call\(\s*node\s*,\s*['\"]rel['\"]\s*,\s*_mergeRel\(",- hook,- )- assert re.search(r"\.getTagName\.call\(\s*node\s*\)", hook)- assert re.search(- r"\.getAttr\.call\(\s*node\s*,\s*['\"]target['\"]\s*\)", hook- )- ui = _strip_js_comments(- (STATIC_JS / "services" / "ui.js").read_text(encoding="utf-8")+ for accessor in ("getTagName", "getAttr", "setAttr"):+ assert f"api.{accessor}.call(node" in hook++ stable = text.split("function sanitizeStable(dirty, config) {", 1)[1]+ stable = stable.split("\n function ", 1)[0]+ assert stable.index("_ensureTabnabbingHook();") < stable.index(+ "DOMPurify.sanitize(")+ assert "if (!hasDOMPurify())" in stable+ assert "return escapeHtml(dirty);" in stable+ assert "sanitizeStable(contentString, SANITIZE_CONFIG)" in text+ assert "return sanitizeStable(dirty, finalConfig);" in text++ ui = _strip_js_comments(_ui_js())body = _render_markdown_body(ui)- # renderMarkdown's config is the only one outside xss-protection.js- # that keeps ``target``. Removing ``target`` from it is a deliberate- # change that must update this test, so it fails rather than skips.- sanitize = re.search(r"DOMPurify\.sanitize\s*\(", body)- assert sanitize, "renderMarkdown no longer calls DOMPurify.sanitize"- add_attr = re.search(r"ADD_ATTR\s*:\s*\[([^\]]*)\]", body[sanitize.end() :])- assert add_attr, "renderMarkdown's sanitize config lost its ADD_ATTR"- assert re.search(r"['\"]target['\"]", add_attr.group(1))- # The ensure is an actual call, in renderMarkdown, before that sanitize.- ensure = re.search(- r"window\.XSSProtection\s*\?\.\s*ensureTabnabbingHook\s*\?\.\s*\(\s*\)\s*;",- body,- )- assert ensure, "renderMarkdown does not call ensureTabnabbingHook"- assert ensure.end() <= sanitize.start()+ assert "sanitizeStable(html, MARKDOWN_SANITIZE_CONFIG)" in body+ allowed = ui.split("const MARKDOWN_ALLOWED_ATTR = [", 1)[1].split("];", 1)[+ 0+ ]+ assert "'target', 'rel'" in alloweddef _strip_js_comments(text: str) -> str:diff --git a/tests/security/test_help_tip_safe_boundary.py b/tests/security/test_help_tip_safe_boundary.pynew file mode 100644index 0000000000..e4e417c1eb--- /dev/null+++ b/tests/security/test_help_tip_safe_boundary.py@@ -0,0 +1,517 @@+"""Security boundary tests for the `|safe` usage in help_macros.html.++``help_tip(text, variant='info')`` (components/help_macros.html) renders+``{{ text|safe }}`` which DISABLES Jinja autoescaping for its ``text``+argument. The only reason this is acceptable is that every current call site+passes a static developer-written string literal (e.g. pages/benchmark.html,+pages/collection_details.html, pages/collections.html). If a call site ever+passes a runtime/user-derived variable, it becomes a stored/reflected XSS+hole.++These tests lock that boundary from both sides:++1. Static call-site guard: parse every ``*.html`` under the web templates dir+ with the production Jinja environment and walk the syntax tree, so Jinja+ comments, ``{% raw %}`` text and the HTML around the tags are never+ mistaken for calls. Every call of the macro must pass ``text`` (first+ positional argument, or the ``text=`` keyword) as quoted string literals,+ optionally joined with ``~``. That holds whatever name the macro is called+ by:++ * the bare name ``help_tip``;+ * an alias, ``{% from "components/help_macros.html" import help_tip as+ tip %}`` then ``tip(...)``;+ * a namespace, ``{% import "components/help_macros.html" as hm %}`` then+ ``hm.help_tip(...)`` or ``hm["help_tip"](...)``.++ Aliases and namespaces are collected from every template, because an+ included template sees the names its includer imported. An import whose+ template name is computed at runtime counts as an import of+ help_macros.html. Calls inside another macro's body are checked like any+ other call; only the ``{% macro help_tip %}`` definition itself is not a+ call. Any other use of the macro or of such a namespace, such as+ ``{% set t = help_tip %}``, passing it to another macro, or+ ``hm|attr("help_tip")``, is reported too, because the call it leads to+ cannot be checked. So is a call that passes ``*args`` or ``**kwargs``.+2. Render-behavior sanity: through the real Jinja2 environment used at+ runtime (``local_deep_research.web.template_config.templates.env`` —+ same ``FileSystemLoader`` and ``autoescape`` configuration the+ production templates use), prove that a literal keeps its trusted+ HTML, that a sibling macro (``tooltip``) autoescapes a variable+ carrying ``<script>``, and that ``help_tip`` would NOT escape such a+ variable — which is exactly why the static guard above is the real+ defense.++Out of scope but noted: base.html lines 16/18 use+``{{ get_themes_json()|safe }}`` / ``{{ get_theme_metadata()|safe }}`` —+server-controlled JSON helpers, not user-derived input.+"""++from functools import lru_cache+from pathlib import Path+from typing import NamedTuple++import pytest+from jinja2 import nodes+from jinja2.exceptions import TemplateNotFound+from jinja2.loaders import split_template_path++from tests.test_utils import add_src_to_path++add_src_to_path()++REPO_ROOT = Path(__file__).resolve().parents[2]+TEMPLATES_DIR = REPO_ROOT / "src" / "local_deep_research" / "web" / "templates"++MACRO_NAME = "help_tip"+MACRO_FILE = "components/help_macros.html"+# The macro parameter rendered with |safe.+TEXT_PARAMETER = "text"+++class HelpTipSite(NamedTuple):+ """One place a template defines, calls or otherwise uses ``help_tip``."""++ path: Path+ line: int+ is_definition: bool+ is_safe: bool+ detail: str+++@lru_cache(maxsize=1)+def _jinja_env():+ """The production environment, so the guard parses what the app parses."""+ from local_deep_research.web.template_config import templates++ return templates.env+++def _parse(path, templates_dir):+ source = path.read_text(encoding="utf-8")+ name = path.relative_to(templates_dir).as_posix()+ return _jinja_env().parse(source, name=name, filename=str(path)), source+++def _may_name_macro_file(template):+ """True if an import's template expression can resolve to MACRO_FILE.++ A constant name is compared after the loader's own normalization+ (``split_template_path``), so ``./components/help_macros.html`` matches.+ A name computed at runtime might be MACRO_FILE, so it counts as one.+ """+ if not isinstance(template, nodes.Const):+ return True+ if not isinstance(template.value, str):+ return False+ try:+ return "/".join(split_template_path(template.value)) == MACRO_FILE+ except TemplateNotFound:+ # A `..` segment, which the loader refuses to load.+ return False+++def _collect_bindings(trees):+ """Names bound to the macro, and to MACRO_FILE namespaces, in any tree."""+ aliases = {MACRO_NAME}+ namespaces = set()+ for tree in trees:+ for node in tree.find_all((nodes.Import, nodes.FromImport)):+ if not _may_name_macro_file(node.template):+ continue+ if isinstance(node, nodes.Import):+ namespaces.add(node.target)+ continue+ for name in node.names:+ imported, alias = (+ name if isinstance(name, tuple) else (name, name)+ )+ if imported == MACRO_NAME:+ aliases.add(alias)+ return aliases, namespaces+++def _namespace_member(node, namespaces):+ """For ``ns.x`` or ``ns["x"]`` on a tracked namespace: ``x``.++ Returns ``""`` for a subscript whose key is not a constant string (the+ member cannot be known) and ``None`` when ``node`` is no such lookup.+ """+ if not isinstance(node, (nodes.Getattr, nodes.Getitem)):+ return None+ if not (+ isinstance(node.node, nodes.Name)+ and node.node.ctx == "load"+ and node.node.name in namespaces+ ):+ return None+ if isinstance(node, nodes.Getattr):+ return node.attr+ if isinstance(node.arg, nodes.Const) and isinstance(node.arg.value, str):+ return node.arg.value+ return ""+++def _refers_to_macro(node, aliases, namespaces):+ """True if evaluating ``node`` yields the help_tip macro (or may)."""+ if isinstance(node, nodes.Name):+ return node.ctx == "load" and node.name in aliases+ return _namespace_member(node, namespaces) in (MACRO_NAME, "")+++def _text_argument(call):+ """The node passed as ``text``, or None when it cannot be determined."""+ if call.dyn_args is not None or call.dyn_kwargs is not None:+ return None+ if call.args:+ return call.args[0]+ for keyword in call.kwargs:+ if keyword.key == TEXT_PARAMETER:+ return keyword.value+ return None+++def _is_string_literal(node):+ """True iff ``node`` is quoted string literals joined only by ``~``.++ Jinja's parser turns adjacent literals into one ``Const`` and ``~`` into+ ``Concat``. Variables, attribute lookups, calls, filters, tests,+ conditionals, arithmetic and non-string constants are all other node+ types, so a value spliced between two literals is rejected too.+ """+ if isinstance(node, nodes.Const):+ return isinstance(node.value, str)+ if isinstance(node, nodes.Concat):+ return all(_is_string_literal(part) for part in node.nodes)+ return False+++def _walk(node, parent=None):+ """Yield ``(node, parent)`` for ``node`` and every node below it."""+ yield node, parent+ for child in node.iter_child_nodes():+ yield from _walk(child, node)+++def _sites_in_tree(tree, source, rel_path, aliases, namespaces):+ lines = source.splitlines()++ def _site(node, is_definition, is_safe, what):+ text = (+ lines[node.lineno - 1].strip() if node.lineno <= len(lines) else ""+ )+ return HelpTipSite(+ rel_path,+ node.lineno,+ is_definition,+ is_safe,+ f"{what}: {text[:100]}",+ )++ for node, parent in _walk(tree):+ if isinstance(node, nodes.Macro) and node.name == MACRO_NAME:+ yield _site(node, True, True, "definition")+ elif isinstance(node, nodes.Call) and _refers_to_macro(+ node.node, aliases, namespaces+ ):+ argument = _text_argument(node)+ is_safe = argument is not None and _is_string_literal(argument)+ yield _site(node, False, is_safe, "call")+ elif _refers_to_macro(node, aliases, namespaces) and not (+ isinstance(parent, nodes.Call) and parent.node is node+ ):+ yield _site(node, False, False, "macro used without a call")+ elif (+ isinstance(node, nodes.Name)+ and node.ctx == "load"+ and node.name in namespaces+ and _namespace_member(parent, namespaces) is None+ ):+ yield _site(node, False, False, "namespace used without a lookup")+++def _scan_help_tip_calls(templates_dir):+ """Yield a ``HelpTipSite`` for every definition, call and other use of+ the macro in the ``*.html`` templates under ``templates_dir``."""+ parsed = [+ (path, *_parse(path, templates_dir))+ for path in sorted(templates_dir.rglob("*.html"))+ ]+ aliases, namespaces = _collect_bindings(tree for _, tree, _ in parsed)+ for path, tree, source in parsed:+ yield from _sites_in_tree(+ tree, source, path.relative_to(templates_dir), aliases, namespaces+ )+++def _find_violations(templates_dir):+ """file:line strings for every use whose ``text`` is not a literal."""+ return [+ f" {site.path}:{site.line} -> {site.detail}"+ for site in _scan_help_tip_calls(templates_dir)+ if not site.is_definition and not site.is_safe+ ]+++class TestHelpTipCallSitesAreStaticLiterals:+ """The static trust-boundary guard for `help_tip(...|safe)`."""++ def test_all_call_sites_pass_string_literals(self):+ """Every help_tip() call must pass a quoted literal as `text`."""+ violations = _find_violations(TEMPLATES_DIR)+ assert not violations, (+ "help_tip() renders its `text` argument via {{ text|safe }} "+ "(Jinja autoescape DISABLED). Every call site must pass a static "+ "developer-written string literal; passing a runtime or "+ "user-derived variable is a stored/reflected XSS. "+ "Violations:\n" + "\n".join(violations)+ )++ def test_scan_actually_finds_call_sites(self):+ """Guard against a silently broken scanner passing vacuously."""+ sites = list(_scan_help_tip_calls(TEMPLATES_DIR))+ call_sites = [s for s in sites if not s.is_definition]+ definitions = [s for s in sites if s.is_definition]+ assert len(call_sites) >= 5, (+ f"Expected at least 5 help_tip() call sites under "+ f"{TEMPLATES_DIR}, found {len(call_sites)} — scanner broken?"+ )+ # The single allowed definition lives in the macro file itself.+ assert len(definitions) == 1+ assert definitions[0].path.as_posix() == MACRO_FILE++ def test_scanner_detects_synthetic_violations(self, tmp_path):+ """Self-test: the scanner must accept literals (including tricky+ ones) and reject every variable-derived or untraceable form."""+ cases = [+ # (template body, is_violation)+ ('{{ help_tip("<strong>Tip:</strong> static text") }}', False),+ ("{{ help_tip('single quoted') }}", False),+ # Parens, % and commas inside the literal must not end the arg.+ (+ '{{ help_tip("<strong>A</strong> (<50%, see foo) ok") }}',+ False,+ ),+ # Multi-line literal-only concatenation is harmless.+ (+ '{{ help_tip("<strong>Long</strong> text"\n ~ " more") }}',+ False,+ ),+ # `text` passed by keyword is checked, not the first argument.+ ("{{ help_tip(variant='warning', text='literal') }}", False),+ ("{{ help_tip(variant='warning', text=user_text) }}", True),+ # Variable call sites — live XSS if ever shipped.+ ("{{ help_tip(user_text) }}", True),+ ("{{ help_tip(user_text|safe) }}", True),+ ("{{ help_tip(user_text|truncate(50)) }}", True),+ ('{{ help_tip("<b>" ~ user_text) }}', True),+ ("{{ help_tip(prefix ~ user_text) }}", True),+ ("{% if x %}{{ help_tip(query_result) }}{% endif %}", True),+ # Regression (parent review): a variable sandwiched between+ # literals defeats any first/last-quote heuristic — only a full+ # literal-only `~` concatenation parse catches it.+ (+ '{{ help_tip("<b>" ~ user_text ~ "</b>") }}',+ True,+ ),+ ('{{ help_tip("prefix" ~ user.name ~ "suffix") }}', True),+ ("{{ help_tip(trusted_fn()) }}", True),+ ('{{ help_tip("count: " ~ 42) }}', True),+ ('{{ help_tip("a" ~ user_text|safe) }}', True),+ ("{{ help_tip(*parts) }}", True),+ ("{{ help_tip(**options) }}", True),+ ("{% call help_tip(user_text) %}{% endcall %}", True),+ # Escaped quotes inside literals keep concatenation literal-only.+ (+ '{{ help_tip("she said \\"hi\\"" ~ " ok") }}',+ False,+ ),+ # Regression (gate review): a namespace import and an import+ # alias call the same |safe macro under another name.+ (+ '{% import "' + MACRO_FILE + '" as hm %}'+ "{{ hm.help_tip(user_text) }}",+ True,+ ),+ (+ '{% from "' + MACRO_FILE + '" import help_tip as ht %}'+ "{{ ht(user_text) }}",+ True,+ ),+ (+ '{% import "' + MACRO_FILE + '" as hm %}'+ "{{ hm['help_tip'](user_text) }}",+ True,+ ),+ (+ '{% from "./' + MACRO_FILE + '" import help_tip as ht %}'+ "{{ ht(user_text) }}",+ True,+ ),+ (+ '{% import "' + MACRO_FILE + '" as hm with context %}'+ "{{ hm.help_tip(user_text) }}",+ True,+ ),+ # The same forms with literals, and other macros reached through+ # the namespace, stay clean.+ (+ '{% import "' + MACRO_FILE + '" as hm %}'+ '{{ hm.help_tip("literal") }}{{ hm.tooltip(label, tip) }}',+ False,+ ),+ (+ '{% from "' + MACRO_FILE + '" import help_tip as ht %}'+ "{{ ht('literal') }}",+ False,+ ),+ # The macro or its namespace escaping into something the scan+ # cannot follow is reported, whatever is eventually passed.+ (+ '{% from "' + MACRO_FILE + '" import help_tip %}'+ "{% set t = help_tip %}{{ t(user_text) }}",+ True,+ ),+ (+ '{% import "' + MACRO_FILE + '" as hm %}'+ "{% set t = hm.help_tip %}{{ t(user_text) }}",+ True,+ ),+ (+ '{% import "' + MACRO_FILE + '" as hm %}'+ "{% set ns2 = hm %}{{ ns2.help_tip(user_text) }}",+ True,+ ),+ (+ '{% import "' + MACRO_FILE + '" as hm %}'+ "{{ (hm|attr('help_tip'))(user_text) }}",+ True,+ ),+ ("{{ render_with(help_tip, user_text) }}", True),+ (+ '{% import "' + MACRO_FILE + '" as hm %}'+ "{{ hm[member](user_text) }}",+ True,+ ),+ # An import whose template name is computed at runtime may be+ # the macro file.+ (+ "{% import macro_file as hm %}{{ hm.help_tip(user_text) }}",+ True,+ ),+ (+ "{% from macro_file import help_tip as ht %}{{ ht(user_text) }}",+ True,+ ),+ # A call inside another macro's body is a call like any other.+ (+ "{% macro wrap(x) %}{{ help_tip(x) }}{% endmacro %}",+ True,+ ),+ (+ "{% macro wrap() %}{{ help_tip('literal') }}{% endmacro %}",+ False,+ ),+ # Raw blocks and comments are template text, not calls.+ ("{% raw %}{{ help_tip(user_text) }}{% endraw %}", False),+ ("{# {{ help_tip(user_text) }} #}", False),+ ]+ for body, expect_violation in cases:+ page = tmp_path / "pages" / "synthetic.html"+ page.parent.mkdir(parents=True, exist_ok=True)+ page.write_text(body, encoding="utf-8")+ violations = _find_violations(tmp_path)+ assert bool(violations) is expect_violation, (+ f"Scanner misclassified:\n{body}\nviolations: {violations}"+ )++ def test_scanner_follows_aliases_into_included_templates(self, tmp_path):+ """An included template sees its includer's imports, so an alias+ bound in one template is tracked in every template."""+ pages = tmp_path / "pages"+ pages.mkdir(parents=True, exist_ok=True)+ (pages / "outer.html").write_text(+ '{% from "' + MACRO_FILE + '" import help_tip as ht %}'+ '{% include "pages/inner.html" %}',+ encoding="utf-8",+ )+ (pages / "inner.html").write_text(+ "{{ ht(user_text) }}", encoding="utf-8"+ )+ violations = _find_violations(tmp_path)+ assert len(violations) == 1+ assert "inner.html:1" in violations[0]++ def test_scanner_exempts_definition_and_comments(self, tmp_path):+ """The macro definition and Jinja-commented calls are exempt."""+ macros = tmp_path / MACRO_FILE+ macros.parent.mkdir(parents=True, exist_ok=True)+ macros.write_text(+ "{% macro help_tip(text, variant='info') %}"+ "<span>{{ text|safe }}</span>"+ "{%- endmacro %}\n",+ encoding="utf-8",+ )+ page = tmp_path / "pages" / "uses.html"+ page.parent.mkdir(parents=True, exist_ok=True)+ page.write_text(+ "{# {{ help_tip(commented_out_var) }} #}\n"+ "{% macro other_macro() %}{% endmacro %}\n",+ encoding="utf-8",+ )+ sites = list(_scan_help_tip_calls(tmp_path))+ assert [s.is_definition for s in sites] == [True]+ assert _find_violations(tmp_path) == []+++class TestHelpTipRenderBoundary:+ """Render-behavior proof through the real Jinja2 environment and+ template loader the app uses in production (mirrors+ tests/security/test_xss_prevention.py).++ Post-FastAPI-migration (#3299), templates are rendered through+ ``local_deep_research.web.template_config.templates`` — a+ ``fastapi.templating.Jinja2Templates`` instance whose ``.env`` is a+ real ``jinja2.Environment`` backed by a ``FileSystemLoader`` pointed+ at the same template directory used at runtime, with the same+ ``autoescape`` policy (``jinja2.select_autoescape()``). Rendering+ through ``templates.env`` exercises that exact loader/autoescape+ configuration directly, without booting the FastAPI app or a test+ client.+ """++ @pytest.fixture(scope="module")+ def jinja_env(self):+ from local_deep_research.web.template_config import templates++ return templates.env++ def test_literal_keeps_trusted_html(self, jinja_env):+ """help_tip with a developer literal keeps its trusted markup."""+ template = jinja_env.from_string(+ '{% from "' + MACRO_FILE + '" import ' + MACRO_NAME + " %}"+ "{{ " + MACRO_NAME + '("<strong>Tip:</strong> trusted text") }}'+ )+ rendered = template.render()+ assert "<strong>Tip:</strong>" in rendered++ def test_sibling_macro_autoescapes_variable(self, jinja_env):+ """Control: `tooltip` (no |safe) escapes a variable carrying markup."""+ template = jinja_env.from_string(+ '{% from "' + MACRO_FILE + '" import tooltip %}'+ "{{ tooltip(payload, payload) }}"+ )+ rendered = template.render(payload="<script>alert('XSS')</script>")+ assert "<script>" not in rendered+ assert "<script>" in rendered++ def test_help_tip_would_not_escape_untrusted_input(self, jinja_env):+ """Documents WHY the static call-site guard is the real defense:+ autoescape is active in this environment, and |safe still lets a+ runtime variable through untouched."""+ template = jinja_env.from_string(+ '{% from "' + MACRO_FILE + '" import ' + MACRO_NAME + " %}"+ "{{ " + MACRO_NAME + "(payload) }}"+ )+ rendered = template.render(payload="<script>alert('XSS')</script>")+ assert "<script>alert('XSS')</script>" in rendereddiff --git a/tests/text_optimization/test_citation_formatter_behavior.py b/tests/text_optimization/test_citation_formatter_behavior.pyindex e19d3929bb..fa50dedc2e 100644--- a/tests/text_optimization/test_citation_formatter_behavior.py+++ b/tests/text_optimization/test_citation_formatter_behavior.py@@ -370,6 +370,69 @@ class TestCitationFormatterFindSourcesSection:assert on_sentinel is True+class TestStripAppendedSourcesSentinel:+ """strip_appended_sources_sentinel removes only the generator's marker.++ The sentinel is an HTML comment and renderMarkdown() (services/ui.js)+ shows raw HTML as literal text, so the copy IntegratedReportGenerator+ appended must not reach displayed report text. Copies an LLM wrote are+ report text and stay.+ """++ def test_removes_the_appended_sentinel_and_keeps_the_report(self):+ from local_deep_research.text_optimization.citation_formatter import (+ LDR_APPENDED_SOURCES_SENTINEL,+ strip_appended_sources_sentinel,+ )++ answer = "The answer [1]."+ sources = "## Sources\n\n[1] Source\n URL: https://s.example\n"+ content = f"{answer}\n\n{LDR_APPENDED_SOURCES_SENTINEL}\n\n{sources}"++ assert (+ strip_appended_sources_sentinel(content)+ == f"{answer}\n\n\n\n{sources}"+ )++ def test_keeps_copies_that_are_not_the_trusted_sentinel(self):+ """An inline copy, and a standalone copy before the trusted last+ one, are text find_sources_section does not trust either."""+ from local_deep_research.text_optimization.citation_formatter import (+ LDR_APPENDED_SOURCES_SENTINEL,+ strip_appended_sources_sentinel,+ )++ quoted = f"The marker is {LDR_APPENDED_SOURCES_SENTINEL} here."+ content = (+ f"{quoted}\n\n{LDR_APPENDED_SOURCES_SENTINEL}\n\nMore."+ f"\n\n{LDR_APPENDED_SOURCES_SENTINEL}\n\n## Sources\n"+ )++ stripped = strip_appended_sources_sentinel(content)++ assert stripped == (+ f"{quoted}\n\n{LDR_APPENDED_SOURCES_SENTINEL}\n\nMore."+ "\n\n\n\n## Sources\n"+ )+ assert strip_appended_sources_sentinel(quoted) == quoted++ @pytest.mark.parametrize(+ "content",+ [+ "",+ None,+ "No sources here.",+ "Answer.\n\n## Sources\n\n[1] S\n URL: https://s.example",+ ],+ )+ def test_leaves_text_without_the_sentinel_unchanged(self, content):+ from local_deep_research.text_optimization.citation_formatter import (+ strip_appended_sources_sentinel,+ )++ assert strip_appended_sources_sentinel(content) == content++class TestCitationFormatterParseSources:"""Tests for _parse_sources method."""diff --git a/tests/theme_tests/test_accent_ink_contrast.py b/tests/theme_tests/test_accent_ink_contrast.pyindex 15e7996bb3..bd67e577fb 100644--- a/tests/theme_tests/test_accent_ink_contrast.py+++ b/tests/theme_tests/test_accent_ink_contrast.py@@ -520,8 +520,8 @@ def _stylesheets():# reviewer, replace the expression: one pseudo-rule ``style@L<line>#<n>``# per combination, checked like any other rule. A style the scanner# cannot read as ``property: value`` declarations fails with no-# allowlist: an attribute that is itself an expression (``style=${st}``,-# ``style="${st}"``); an expression or tag in a property name or in a part+# allowlist for application UI: an attribute that is itself an expression+# (``style=${st}``, ``style="${st}"``); an expression or tag in a property name or in a part# with no ``:``; a quote, backtick, backslash or brace left in a value# once its expressions, a ``font-family`` list of plain quoted names# (``'Courier New'``) and plain ``url()``s are set aside, so a string@@ -532,7 +532,8 @@ def _stylesheets():# one property at a time (``el.style.color = ...``,# ``style.setProperty(...)``, ``Object.assign(el.style, ...)``),# ``el['style']``, an attribute name built by script, and ``<style>`` text-# built in script.+# built in script. The one sanitized document-authored KaTeX write is+# classified separately below, with its exact guarded source pinned._MAX_VARIANTS = 64# A server-side template tag, which renders before the browser parses the# attribute.@@ -831,6 +832,33 @@ def _style_variants(name, decls, allowlist):return variants+# This write preserves document-authored KaTeX colors, not application+# palette choices. Its CSSOM declarations pass the positive property/value+# policy tested in tests/js/security/markdown-render-xss.test.js and the+# 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_CONTEXT = (+ "const safeStyle = getSafeKatexInlineStyle(el);",+ "if (!safeStyle) {",+ "el.removeAttribute('style');",+ "} else {",+ "el.setAttribute('style', safeStyle);",+ "}",+)+++def _is_authored_math_style(text, name, line):+ if (name, line) != _AUTHORED_MATH_STYLE_SITE:+ return False+ end = line + 1 # the closing brace directly after the reviewed write+ context = text.splitlines()[end - len(_AUTHORED_MATH_STYLE_CONTEXT) : end]+ return (+ tuple(part.strip() for part in context) == _AUTHORED_MATH_STYLE_CONTEXT+ )++def _scan_styles(text, name, allowlist=None):"""``(rules, unread, found)`` for the inline styles in one file's``text``: the pseudo-rules (``style@L<line>``, or ``style@L<line>#<n>``@@ -840,7 +868,10 @@ def _scan_styles(text, name, allowlist=None):allowlist = DYNAMIC_INLINE_STYLES if allowlist is None else allowlistrules, unread, found = [], {}, {}for offset, read in _style_sites(text):- label = f"style@L{text.count(chr(10), 0, offset) + 1}"+ line = text.count(chr(10), 0, offset) + 1+ label = f"style@L{line}"+ if read is None and _is_authored_math_style(text, name, line):+ continuedecls = read and _style_declarations(text, *read)if decls is None:unread[label] = "cannot be read as literal declarations"@@ -941,26 +972,25 @@ DYNAMIC_INLINE_STYLES = {("inline", "none"),None,),- # context-overflow.js L520: ``const utilColor = utilPct > 80 ?- # 'var(--error-color)' : utilPct > 50 ? 'var(--warning-color)' :- # 'var(--success-color)'``, assigned once. L519 makes utilPct a number- # (``Math.round(...)`` or 0); L582's truncationPercent is a number too.- ("static/js/components/context-overflow.js", 574, "color"): (+ # utilColor selects one of three fixed CSS variables. utilPct uses+ # Math.round(...) or 0, and truncationPercent is a finite number before+ # either value is interpolated into these styles.+ ("static/js/components/context-overflow.js", 582, "color"): ("utilColor",("var(--error-color)", "var(--warning-color)", "var(--success-color)"),None,),- ("static/js/components/context-overflow.js", 577, "background"): (+ ("static/js/components/context-overflow.js", 585, "background"): ("utilColor",("var(--error-color)", "var(--warning-color)", "var(--success-color)"),None,),- ("static/js/components/context-overflow.js", 577, "width"): (+ ("static/js/components/context-overflow.js", 585, "width"): ("Math.min(utilPct, 100)",(NUMBER,),None,),- ("static/js/components/context-overflow.js", 582, "width"): (+ ("static/js/components/context-overflow.js", 590, "width"): ("Math.min(truncationPercent, 100)",(NUMBER,),None,@@ -1035,12 +1065,12 @@ DYNAMIC_INLINE_STYLES = {),# news.js: ``Math.max(0, Math.min(100, ...))`` and ``Number(...) ||# 10`` are numbers.- ("static/js/pages/news.js", 1233, "width"): (+ ("static/js/pages/news.js", 1286, "width"): ("Math.max(0, Math.min(100, (Number(item.impact_score) || 0) * 10))",(NUMBER,),None,),- ("static/js/pages/news.js", 2894, "width"): (+ ("static/js/pages/news.js", 2949, "width"): ("Number(statusData.progress) || 10",(NUMBER,),None,@@ -1134,6 +1164,41 @@ def test_dynamic_inline_style_values_are_literals():assert not problems, problems+def test_authored_math_style_write_matches_reviewed_source():+ name, line = _AUTHORED_MATH_STYLE_SITE+ source = _markup_text(name)+ assert _is_authored_math_style(source, name, line)+ assert any(+ source.count("\n", 0, offset) + 1 == line and read is None+ for offset, read in _style_sites(source)+ )+ assert f"style@L{line}" not in _scan_styles(source, name)[1]+++ "change", ["validator", "value", "second-write", "file"]+)+def test_authored_math_style_exception_rejects_unreviewed_writes(change):+ name, line = _AUTHORED_MATH_STYLE_SITE+ source = _markup_text(name)+ if change == "validator":+ source = source.replace(+ "const safeStyle = getSafeKatexInlineStyle(el);",+ "const safeStyle = el.getAttribute('style');",+ )+ elif change == "value":+ source = source.replace(+ "el.setAttribute('style', safeStyle);",+ "el.setAttribute('style', unfilteredStyle);",+ )+ elif change == "second-write":+ source += "\nel.setAttribute('style', safeStyle);\n"+ line = len(source.splitlines())+ else:+ name = "static/js/services/other.js"+ assert f"style@L{line}" in _scan_styles(source, name)[1]++def test_inline_style_scanner_over_reports():"""Every shape the scanner does not model fails rather than being readas a style without a fill, and every expression is reported for the@@ -1281,7 +1346,7 @@ def test_inline_style_scan_finds_the_known_expressions():assert {("templates/pages/journal_quality.html", 723, "background"),("templates/pages/journal_quality.html", 831, "background"),- ("static/js/components/context-overflow.js", 577, "background"),+ ("static/js/components/context-overflow.js", 585, "background"),("static/js/components/details.js", 712, "color"),("templates/pages/metrics.html", 989, "color"),} <= set(found), sorted(found)@@ -1294,7 +1359,7 @@ def test_inline_style_scan_finds_the_known_expressions():assert {("templates/pages/journal_quality.html", "style@L723"),("templates/pages/journal_quality.html", "style@L831"),- ("static/js/components/context-overflow.js", "style@L577"),+ ("static/js/components/context-overflow.js", "style@L585"),} <= expanded, sorted(expanded)@@ -1596,7 +1661,7 @@ NON_TEXT_STATUS_FILLS = {("templates/auth/register.html", ".ldr-strength-medium"): _STRENGTH,("templates/auth/register.html", ".ldr-strength-strong"): _STRENGTH,# The utilColor and _stateColor() bars; their figures sit beside them.- ("static/js/components/context-overflow.js", "style@L577"): _BAR,+ ("static/js/components/context-overflow.js", "style@L585"): _BAR,("templates/pages/journal_quality.html", "style@L831"): _BAR,}@@ -1688,7 +1753,7 @@ def test_fill_inks_read_on_swapped_fills():("styles.css", ".ldr-console-log-entry.ldr-log-error .ldr-log-badge"),("styles.css", ".ldr-badge-danger"),("templates/pages/journal_quality.html", ".ldr-quality-dangerous"),- ("static/js/components/context-overflow.js", "style@L253"),+ ("static/js/components/context-overflow.js", "style@L257"),} <= foundassert len(pairs) >= 80, "too few fill/ink pairs were found"palettes = _palettes()diff --git a/tests/ui_tests/playwright/tests/security-mxss-reparse.spec.js b/tests/ui_tests/playwright/tests/security-mxss-reparse.spec.jsindex b8a9b1a1b3..22854f8dd5 100644--- a/tests/ui_tests/playwright/tests/security-mxss-reparse.spec.js+++ b/tests/ui_tests/playwright/tests/security-mxss-reparse.spec.js@@ -25,10 +25,10 @@* → re-walk for executable surfaces** Also runs the closures the production app actually uses for "I trust this- * Markdown": `renderMarkdown` (which feeds DOMPurify a richer config than the- * strict one used by safeSetInnerHTML — it adds `semantics` and `annotation`,+ * Markdown": `renderMarkdown` (which uses an explicit generated-markup allow-list richer than the+ * strict one used by safeSetInnerHTML — it keeps `semantics` and `annotation`,* which is what enables MathML/KaTeX in the production render path) and- * `sanitizeHtml` (the underlying DOMPurify.sanitize wrapper).+ * `sanitizeHtml` (the shared sanitizer wrapper).** Scope (per the issue's acceptance criteria)* -------------------------------------------@@ -38,8 +38,8 @@* 2. Four production code paths exercised with every payload:* a. `window.safeSetInnerHTML` — strict `SANITIZE_CONFIG` allow-list;* b. `window.safeSetHTML` — services/ui.js wrapper (prefers DOMPurify);- * c. `window.ui.renderMarkdown` — Markdown → DOMPurify *permissive* config- * (default allow-list plus `semantics`/`annotation`), the path the+ * c. `window.ui.renderMarkdown` — Markdown → DOMPurify generated-markup+ * allow-list (including `semantics`/`annotation`), the path the* application uses to keep tables and KaTeX-emitted MathML alive;* d. `window.sanitizeHtml` — the DOMPurify wrapper the other setters* delegate to, driven with the same payloads so its config is a tested@@ -62,8 +62,8 @@* reparse with no executable surface alongside. Because the math is TeX,* this can catch a failure to *generate* math, which pre-built MathML* cannot.- * b. An additional control supplies pre-built MathML as markup and asserts- * it survives the renderer and the reparse.+ * b. An additional control supplies pre-built MathML as author markup and+ * asserts it remains literal text through the renderer and reparse.* c. A strict audit asserts `safeSetInnerHTML` and `sanitizeHtml` strip* table/svg/math, the opposite of what `renderMarkdown` preserves. Both* directions are pinned so "correctly rejected" and "never produced"@@ -343,7 +343,8 @@ async function loadFixture(page) {await page.addScriptTag({ path: KATEX_PATH });await page.addScriptTag({ path: MARKED_KATEX_PATH });await page.evaluate(() => {- // Mirrors src/local_deep_research/web/static/js/app.js:62.+ // Mirrors the marked.use(markedKatex(...)) call in+ // src/local_deep_research/web/static/js/app.js.marked.use(window.markedKatex({ throwOnError: false, errorColor: 'currentColor' }));});@@ -622,7 +623,7 @@ test('benign renderer control: GFM table and real TeX render through renderMarkd// could not catch a failure to generate math at all.//// This is the positive half of the foreign-content story: `renderMarkdown`- // runs the permissive DOMPurify configuration (default allow-list plus+ // runs the explicit generated-markup allow-list (including// `semantics`/`annotation`), which is what keeps real Markdown — including// the MathML KaTeX emits — alive. The strict `SANITIZE_CONFIG` used by// `safeSetInnerHTML` and `sanitizeHtml` strips the same tags; that strip is@@ -706,11 +707,10 @@ test('benign renderer control: GFM table and real TeX render through renderMarkd).toEqual([]);});-test('benign renderer control (additional): pre-built MathML supplied as markup survives', async ({ page }) => {+test('author-supplied MathML remains literal text through rendering and reparsing', async ({ page }) => {// Additional coverage kept alongside the TeX control above. This asserts the- // narrower property that MathML written directly into the source survives- // the renderer and the reparse — useful when the KaTeX pipeline changes,- // but on its own it cannot show that math is generated.+ // raw author HTML cannot impersonate generated KaTeX markup. The real TeX+ // control above independently verifies that generated math still renders.await loadFixture(page);const markdown = [@@ -731,15 +731,16 @@ test('benign renderer control (additional): pre-built MathML supplied as markup// eslint-disable-next-line no-unsanitized/property -- serialize → reparse hop under test.reparseHost.innerHTML = target.outerHTML;return {- reparsed: reparseHost.innerHTML,+ firstText: target.textContent,+ reparsedText: reparseHost.textContent,+ mathCount: reparseHost.querySelectorAll('math, semantics, msqrt, annotation').length,reparseSurface: window.__mxssScan(reparseHost),};}, markdown);- expect(result.reparsed, 'supplied MathML <math> must survive').toMatch(/<math[\s>]/i);- expect(result.reparsed, 'supplied <semantics> must survive').toMatch(/<semantics[\s>]/i);- expect(result.reparsed, 'supplied <msqrt> must survive').toMatch(/<msqrt[\s>]/i);- expect(result.reparsed, 'supplied <annotation> must survive').toMatch(/<annotation[\s>]/i);+ expect(result.firstText.trim()).toBe(markdown.trim());+ expect(result.reparsedText.trim()).toBe(markdown.trim());+ expect(result.mathCount, 'raw author MathML must not become active markup').toBe(0);expect(result.reparseSurface.badElements,'reparsed tree must not contain executable elements'@@ -751,8 +752,8 @@ test('benign renderer control (additional): pre-built MathML supplied as markuptest('strict allow-list audit: safeSetInnerHTML and sanitizeHtml both strip table/svg/math', async ({ page }) => {// The strict `SANITIZE_CONFIG` is allowed to strip table/svg/math, and it// must keep doing so — these two entry points are the ones that receive- // untrusted HTML, as opposed to `renderMarkdown`, whose permissive config- // is asserted to PRESERVE the same tags in the benign renderer control+ // untrusted HTML, as opposed to `renderMarkdown`, whose generated-markup+ // allow-list preserves the same tags in the benign renderer control// above. Pinning both directions is what makes either claim meaningful:// a strip-only suite cannot tell "correctly rejected" from "never// produced", and a preserve-only suite cannot tell "correctly kept" fromdiff --git a/tests/web/services/test_report_assembly_service.py b/tests/web/services/test_report_assembly_service.pyindex 327b6cd0a2..8c271bb5f9 100644--- a/tests/web/services/test_report_assembly_service.py+++ b/tests/web/services/test_report_assembly_service.py@@ -209,6 +209,32 @@ class TestAssembleFullReport:assert "https://old.com" in outassert "https://new.com" not in out+ def test_legacy_row_drops_the_appended_sources_sentinel(self, db_session):+ """A detailed report saved in NO_HYPERLINKS mode (or after the+ citation formatter raised) before the save site removed it carries+ the generator's sentinel, an HTML comment that renderMarkdown()+ shows as literal text. The assembled report must not include it."""+ from local_deep_research.text_optimization.citation_formatter import (+ LDR_APPENDED_SOURCES_SENTINEL,+ )++ legacy_body = (+ "The answer body.\n\n"+ f"{LDR_APPENDED_SOURCES_SENTINEL}\n\n"+ "## Sources\n\n"+ "[1] Old Source (source nr: 1)\n"+ " URL: https://old.com\n"+ )+ research = _mk_research(db_session, report_content=legacy_body)++ out = assemble_full_report(research, db_session)++ assert LDR_APPENDED_SOURCES_SENTINEL not in out+ assert out.startswith("The answer body.\n\n")+ # Still recognised as a legacy row: one Sources block, the saved one.+ assert out.count("## Sources") == 1+ assert "https://old.com" in out+def test_legacy_row_with_repeated_source_not_double_rendered(self, db_session):diff --git a/tests/web/services/test_research_service_citation_sentinel.py b/tests/web/services/test_research_service_citation_sentinel.pyindex fa1946a91c..6b626f10f7 100644--- a/tests/web/services/test_research_service_citation_sentinel.py+++ b/tests/web/services/test_research_service_citation_sentinel.py@@ -364,3 +364,111 @@ class TestRunResearchProcessQuickModeSentinel:mock_formatter.format_document_split.assert_called_once_with("# Results", trust_sentinel=False)+++def _run_detailed_and_capture_saved_content(formatter, report_content):+ """Run detailed mode with ``formatter`` and return what was saved."""+ mock_system = MagicMock()+ mock_system.all_links_of_system = [+ {"url": "https://s.example", "title": "S", "index": 1}+ ]+ mock_system.analyze_topic.return_value = {+ "findings": [{"content": "data"}],+ "formatted_findings": "# Report",+ "iterations": 5,+ "search_system": mock_system,+ }+ mock_report_gen = MagicMock()+ mock_report_gen.generate_report.return_value = {+ "content": report_content,+ "metadata": {"sections": 3},+ }+ mock_storage = MagicMock()+ mock_storage.save_report.return_value = True+ mock_sources_service = MagicMock()+ mock_sources_service.save_research_sources.return_value = 1++ with ExitStack() as stack:+ for cm in _base_patches(mock_system, formatter):+ stack.enter_context(cm)+ stack.enter_context(+ patch(+ f"{RS}.IntegratedReportGenerator",+ return_value=mock_report_gen,+ )+ )+ stack.enter_context(+ patch(+ "local_deep_research.storage.get_report_storage",+ return_value=mock_storage,+ )+ )+ stack.enter_context(+ patch(+ "local_deep_research.web.services.research_sources_service.ResearchSourcesService",+ return_value=mock_sources_service,+ )+ )+ from local_deep_research.web.services.research_service import (+ run_research_process,+ )++ run_research_process(+ research_id=1,+ query="query",+ mode="detailed",+ username="alice",+ settings_snapshot={"search.tool": "searxng"},+ model="m",+ search_engine="s",+ )++ mock_storage.save_report.assert_called_once()+ return mock_storage.save_report.call_args.kwargs["content"]+++class TestRunResearchProcessDetailedModeSavesNoSentinel:+ """The appended-sources sentinel is an HTML comment, and+ renderMarkdown() shows raw HTML in Markdown as literal text. When the+ split keeps the Sources block in the saved answer, the sentinel must not+ be saved with it."""++ ANSWER = "The answer [1]."+ SOURCES = "## Sources\n\n[1] S\n URL: https://s.example\n"++ def _content(self):+ from local_deep_research.text_optimization.citation_formatter import (+ LDR_APPENDED_SOURCES_SENTINEL,+ )++ return f"{self.ANSWER}\n\n{LDR_APPENDED_SOURCES_SENTINEL}\n\n{self.SOURCES}"++ def test_no_hyperlinks_mode_saves_the_report_without_the_sentinel(self):+ """NO_HYPERLINKS keeps the whole report as the answer, Sources block+ and all, so the sentinel used to be saved and shown on the page."""+ from local_deep_research.text_optimization.citation_formatter import (+ CitationFormatter,+ CitationMode,+ )++ saved = _run_detailed_and_capture_saved_content(+ CitationFormatter(mode=CitationMode.NO_HYPERLINKS), self._content()+ )++ assert "LDR_APPENDED_SOURCES_START" not in saved+ assert saved.startswith(self.ANSWER)+ assert saved.endswith(self.SOURCES)++ def test_formatter_failure_saves_the_raw_report_without_the_sentinel(+ self,+ ):+ formatter = MagicMock()+ formatter.format_document_split.side_effect = RuntimeError("boom")++ saved = _run_detailed_and_capture_saved_content(+ formatter, self._content()+ )++ assert "LDR_APPENDED_SOURCES_START" not in saved+ assert saved.startswith(self.ANSWER)+ assert saved.endswith(self.SOURCES)diff --git a/tests/web/test_js_fetch_parity.py b/tests/web/test_js_fetch_parity.pyindex 901371930e..b9a2d81848 100644--- a/tests/web/test_js_fetch_parity.py+++ b/tests/web/test_js_fetch_parity.py@@ -990,7 +990,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:1452",+ js_ref="pages/news.js:1507",method="POST",url=f"/news/api/feedback/{NOPE_UUID}",good={"vote": "up"},diff --git a/vite.config.js b/vite.config.jsindex 55a5e9c63a..dc4a8c77b5 100644--- a/vite.config.js+++ b/vite.config.js@@ -77,6 +77,13 @@ export default defineConfig({clearMocks: false,root: resolve(__dirname),include: ['tests/js/**/*.test.js'],- setupFiles: ['tests/js/setup.js'],+ // The DOMPurify/happy-dom repairs MUST run before any test module, and+ // therefore before any `import 'dompurify'` -- DOMPurify captures+ // document.createNodeIterator and the Node.prototype nodeName getter at+ // import time. See tests/js/happy-dom-dompurify-shim.js.+ setupFiles: [+ 'tests/js/happy-dom-dompurify-shim.js',+ 'tests/js/setup.js',+ ],}});