~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): escape innerHTML injections across analytics pages (#3095)
LearningCircuitdf539f6e2835
diff --git a/.github/workflows/docker-tests.yml b/.github/workflows/docker-tests.ymlindex 8cee4d2b02..97a90105db 100644--- a/.github/workflows/docker-tests.yml+++ b/.github/workflows/docker-tests.yml@@ -540,7 +540,7 @@ jobs:# Run UI tests with Puppeteer#- # Runs as a 14-way matrix (one cell per shard). Each cell spins up its own+ # Runs as a 17-way matrix (one cell per shard). Each cell spins up its own# docker container and runs only the tests tagged with its shard in# tests/ui_tests/run_all_tests.js. Fresh per-cell DB bounds state leakage# across tests (see #5165 flake analysis).@@ -582,6 +582,7 @@ jobs:- accessibility- chat-core- chat-lifecycle+ - link-analyticsfail-fast: falsepermissions:contents: read@@ -623,7 +624,7 @@ jobs:# to GitHub's "Re-run failed jobs" but skipping the docker artifact# re-download (the tarball is bit-identical between attempts).#- # 3 attempts because 14 independent shards each at ~98% success only+ # 3 attempts because 17 independent shards each at ~98% success only# gives ~75% gate pass; 2 retries brings per-shard fail to ~0.0001%.# More than 3 starts hiding genuine bugs (a test that fails 3/3 is a# regression, not a flake).diff --git a/changelog.d/+analytics-rank-and-cost-research-id-escape.security.md b/changelog.d/+analytics-rank-and-cost-research-id-escape.security.mdnew file mode 100644index 0000000000..57ff5083cc--- /dev/null+++ b/changelog.d/+analytics-rank-and-cost-research-id-escape.security.md@@ -0,0 +1 @@+Completed the analytics-page innerHTML hardening pass: coerced the `frequency_rank` value (`#N` domain rank badge) in `link_analytics.html` with `Number()` — the one numeric sibling left un-coerced next to `usageCount`/`usagePercentage`/`researchDiversity` — and escaped `research_id` in `cost_analytics.html`'s "most expensive research" list (`encodeURIComponent()` in the `href`, `window.escapeHtml()` in the link text, mirroring `star_reviews.html`). Both are defense-in-depth on raw `${...}` interpolation into `innerHTML` with no DOMPurify barrier; neither is currently exploitable (rank is a server-side int, `research_id` is a `uuid4` and the cost-analytics render path is presently disabled), but together they make the PR's "across analytics pages" scope complete.diff --git a/changelog.d/+link-analytics-research-diversity-number-coerce.security.md b/changelog.d/+link-analytics-research-diversity-number-coerce.security.mdnew file mode 100644index 0000000000..9513988061--- /dev/null+++ b/changelog.d/+link-analytics-research-diversity-number-coerce.security.md@@ -0,0 +1 @@+Wrapped the `research_diversity` interpolation in the link-analytics "Recent Researches (N total)" header in `Number()`, matching the same coercion already applied to the sibling `🔍 N researches` badge in the same template. Closes a defense-in-depth gap (raw `${researchDiversity}` into `innerHTML` with no DOMPurify) left inconsistent by PR #3095. Not currently exploitable — the value is a Python `len(...)` int server-side — but aligns with the PR's stated scope of coercing numeric fields used in template-literal text positions.diff --git a/changelog.d/+link-analytics-tests.security.md b/changelog.d/+link-analytics-tests.security.mdnew file mode 100644index 0000000000..ceda039db5--- /dev/null+++ b/changelog.d/+link-analytics-tests.security.md@@ -0,0 +1 @@+Extracted `updateEnhancedDomainList` from the `link_analytics.html` inline script into `static/js/pages/link_analytics_render.js` (surgical extraction mirroring PR #4584) so it can be tested in isolation. Added 7 Vitest XSS regression tests at `tests/js/pages/link-analytics-xss.test.js` covering the escape sites fixed in #3095 (Number()-coercion of `research_diversity`/`usage_count`/`usage_percentage`, `escapeHtml` of research-link queries and classification fields, `encodeURI`/`encodeURIComponent` of domain names and research IDs, and the inline-script wrapper pattern at `link_analytics.html:797-802`). These tests run in PR CI via the existing Vitest job. Added a new `link-analytics` Puppeteer shard for full-page verification of `/metrics/links` in the release pipeline (strict-mode only), with runtime assertions that no `<script>` element is injected and that the "Recent Researches (N total)" header shows a numeric `N`.diff --git a/src/local_deep_research/web/static/js/pages/link_analytics_render.js b/src/local_deep_research/web/static/js/pages/link_analytics_render.jsnew file mode 100644index 0000000000..0dff517a70--- /dev/null+++ b/src/local_deep_research/web/static/js/pages/link_analytics_render.js@@ -0,0 +1,108 @@+/**+ * Link Analytics render helpers — extracted from link_analytics.html inline+ * script (PR #3095 follow-up). Surgical extraction mirroring PR #4584.+ *+ * This module exposes updateEnhancedDomainList on window for the inline+ * script's wrapper (lines 856-861 of link_analytics.html) to reassign,+ * and as a CommonJS export for Vitest regression tests.+ *+ * Security note: every untrusted string interpolation in this function is+ * either wrapped in Number()/Math.round() (numeric coercion) or passed+ * through window.escapeHtml / encodeURIComponent / encodeURI. External+ * hrefs are additionally screened by URLValidator.isSafeUrl to reject+ * javascript:/data: schemes, with a console.warn on rejection for+ * debuggability. Tests at tests/js/pages/link-analytics-xss.test.js+ * pin these escape sites.+ */+(function() {+ 'use strict';++ /**+ * Build a safe `https://<domain>` href, rejecting anything URLValidator+ * flags as an unsafe scheme. Domains here come from the link_analytics+ * DB (the user's own research browsing history), but we still screen+ * at render time as defense-in-depth.+ */+ function safeExternalHref(domain) {+ const url = 'https://' + domain;+ const validator = (typeof window !== 'undefined' && window.URLValidator) || null;+ if (validator && !validator.isSafeUrl(url)) {+ window.SafeLogger.warn('link_analytics: rejected unsafe external href for domain', domain);+ return '#';+ }+ return 'https://' + encodeURI(domain);+ }++ function updateEnhancedDomainList(domains, domainMetrics) {+ const container = document.getElementById('domain-list');+ container.innerHTML = '';++ if (domains.length === 0) {+ container.innerHTML = '<div style="text-align: center; color: var(--text-secondary); padding: 1rem;">No domain data available</div>';+ return;+ }++ domains.forEach(domain => {+ const metrics = domainMetrics[domain.domain] || {};+ const usageCount = metrics.usage_count || domain.count || 0;+ const usagePercentage = metrics.usage_percentage || domain.percentage || 0;+ const researchDiversity = metrics.research_diversity || domain.research_count || 0;+ const rank = Number(metrics.frequency_rank) || 0;++ const item = document.createElement('div');+ item.className = 'ldr-domain-item-expanded';++ let researchLinksHtml = '';+ if (domain.recent_researches && domain.recent_researches.length > 0) {+ researchLinksHtml = `+ <div class="ldr-research-links">+ <div class="ldr-research-links-title">Recent Researches (${Number(researchDiversity) || 0} total)</div>+ ${domain.recent_researches.map(r => `+ <a href="/research/${encodeURIComponent(r.id)}" class="ldr-research-link" title="${window.escapeHtml(r.query)}">+ ${window.escapeHtml(r.query.length > 30 ? r.query.substring(0, 30) + '...' : r.query)}+ </a>+ `).join('')}+ </div>+ `;+ }++ // Add classification if available+ let classificationHtml = '';+ if (domain.classification) {+ classificationHtml = `+ <span class="ldr-classified-badge" title="${window.escapeHtml(domain.classification.subcategory)} (${Math.round(Number(domain.classification.confidence) * 100)}% confidence)">+ ${window.escapeHtml(domain.classification.category)}+ </span>+ `;+ }++ // bearer:disable javascript_lang_dangerous_insert_html+ // eslint-disable-next-line no-unsanitized/property -- audited: every interpolation uses Number()/Math.round(), escapeHtml, encodeURIComponent, encodeURI, or safeExternalHref (URLValidator-screened).+ item.innerHTML = `+ <div class="ldr-domain-header">+ <span class="ldr-domain-name" style="font-size: 1rem; font-weight: 600;">+ ${rank ? `#${rank}` : ''} <a href="${safeExternalHref(domain.domain)}" target="_blank" rel="noopener noreferrer" style="color: var(--accent-primary); text-decoration: none; border-bottom: 1px dotted var(--accent-primary); transition: all 0.2s ease;" onmouseover="this.style.borderBottom='2px solid var(--accent-primary)'" onmouseout="this.style.borderBottom='1px dotted var(--accent-primary)'">${window.escapeHtml(domain.domain)}</a>+ ${classificationHtml}+ </span>+ <div class="ldr-domain-stats">+ <span class="ldr-metric-badge ldr-frequency">+ 📊 ${Number(usageCount) || 0} uses (${Number(usagePercentage) || 0}%)+ </span>+ <span class="ldr-metric-badge ldr-diversity">+ 🔍 ${Number(researchDiversity) || 0} researches+ </span>+ </div>+ </div>+ ${researchLinksHtml}+ `;+ container.appendChild(item);+ });+ }++ if (typeof window !== 'undefined') {+ window.updateEnhancedDomainList = updateEnhancedDomainList;+ }+ if (typeof module !== 'undefined' && module.exports) {+ module.exports = { updateEnhancedDomainList };+ }+})();diff --git a/src/local_deep_research/web/static/js/pages/news.js b/src/local_deep_research/web/static/js/pages/news.jsindex e2230a7003..5ec3bddb00 100644--- a/src/local_deep_research/web/static/js/pages/news.js+++ b/src/local_deep_research/web/static/js/pages/news.js@@ -1042,11 +1042,11 @@ function renderNewsItems(searchQuery = null) {<span class="ldr-impact-indicator">Impact:<div class="ldr-impact-bar">- <div class="ldr-impact-fill" style="width: ${item.impact_score * 10}%"></div>+ <div class="ldr-impact-fill" style="width: ${(Number(item.impact_score) || 0) * 10}%"></div></div>- ${item.impact_score}/10+ ${Number(item.impact_score) || 0}/10</span>- <span><i class="fas fa-calendar"></i> ${formatNewsDate(item.created_at) || item.time_ago || 'Recently'}</span>+ <span><i class="fas fa-calendar"></i> ${escapeHtml(formatNewsDate(item.created_at) || item.time_ago || 'Recently')}</span></div>${findingsHtml}${topicsHtml}@@ -1054,10 +1054,10 @@ function renderNewsItems(searchQuery = null) {<div class="ldr-news-actions"><div class="ldr-vote-buttons"><button class="ldr-vote-btn" onclick="vote('${escapeAttr(item.id)}', 'up')">- <i class="fas fa-thumbs-up"></i> ${item.upvotes || 0}+ <i class="fas fa-thumbs-up"></i> ${Number(item.upvotes) || 0}</button><button class="ldr-vote-btn" onclick="vote('${escapeAttr(item.id)}', 'down')">- <i class="fas fa-thumbs-down"></i> ${item.downvotes || 0}+ <i class="fas fa-thumbs-down"></i> ${Number(item.downvotes) || 0}</button></div><div class="ldr-action-buttons">@@ -1131,7 +1131,7 @@ function populateNewsTable() {<td>${escapeHtml(analysis || 'Analysis in progress...')}</td><td><span class="ldr-impact-badge ${impactClass}">- ${item.impact_score}/10+ ${Number(item.impact_score) || 0}/10</span></td></tr>@@ -3862,3 +3862,7 @@ window.selectSubscription = selectSubscription;window.showCreateSubscriptionModal = showCreateSubscriptionModal;window.createSubscription = createSubscription;window.createSubscriptionFromItem = createSubscriptionFromItem;+// Exposed for test harness: lets XSS-regression tests drive a single render+// cycle with a controlled newsItems payload without going through the full+// DOMContentLoaded -> initializeNewsPage chain.+window.loadNewsFeed = loadNewsFeed;diff --git a/src/local_deep_research/web/templates/pages/cost_analytics.html b/src/local_deep_research/web/templates/pages/cost_analytics.htmlindex 4d1e058f98..1d14e0ac37 100644--- a/src/local_deep_research/web/templates/pages/cost_analytics.html+++ b/src/local_deep_research/web/templates/pages/cost_analytics.html@@ -651,8 +651,8 @@div.innerHTML = `<div class="ldr-cost-item-info"><div class="ldr-cost-item-name">- <a href="/results/${item.research_id}" class="ldr-research-link">- Research Session #${item.research_id}+ <a href="/results/${encodeURIComponent(item.research_id)}" class="ldr-research-link">+ Research Session #${window.escapeHtml(item.research_id)}</a></div><div class="ldr-cost-item-details">Rank #${index + 1} most expensive</div>diff --git a/src/local_deep_research/web/templates/pages/link_analytics.html b/src/local_deep_research/web/templates/pages/link_analytics.htmlindex c4d931378a..a2100f2133 100644--- a/src/local_deep_research/web/templates/pages/link_analytics.html+++ b/src/local_deep_research/web/templates/pages/link_analytics.html@@ -191,6 +191,7 @@</div></div>+<script src="/static/js/pages/link_analytics_render.js"></script><script>let topDomainsChart = null;let domainDistributionChart = null;@@ -264,8 +265,8 @@ function generateCategoryGrid(domainCategories) {const cardHtml = `<div class="ldr-category-card" style="border-left: 4px solid ${cardColor};"><div class="ldr-category-name">${window.escapeHtml(categoryName)}</div>- <div class="ldr-category-count">${count}</div>- <div class="ldr-category-percentage">${percentage}%</div>+ <div class="ldr-category-count">${Number(count) || 0}</div>+ <div class="ldr-category-percentage">${Number(percentage) || 0}%</div></div>`;@@ -522,69 +523,9 @@ function updateTemporalTrendChart(trendData) {});}-function updateEnhancedDomainList(domains, domainMetrics) {- const container = document.getElementById('domain-list');- container.innerHTML = '';-- if (domains.length === 0) {- container.innerHTML = '<div style="text-align: center; color: var(--text-secondary); padding: 1rem;">No domain data available</div>';- return;- }-- domains.forEach(domain => {- const metrics = domainMetrics[domain.domain] || {};- const usageCount = metrics.usage_count || domain.count || 0;- const usagePercentage = metrics.usage_percentage || domain.percentage || 0;- const researchDiversity = metrics.research_diversity || domain.research_count || 0;- const rank = metrics.frequency_rank || 0;-- const item = document.createElement('div');- item.className = 'ldr-domain-item-expanded';-- let researchLinksHtml = '';- if (domain.recent_researches && domain.recent_researches.length > 0) {- researchLinksHtml = `- <div class="ldr-research-links">- <div class="ldr-research-links-title">Recent Researches (${researchDiversity} total)</div>- ${domain.recent_researches.map(r => `- <a href="/research/${encodeURIComponent(r.id)}" class="ldr-research-link" title="${window.escapeHtml(r.query)}">- ${window.escapeHtml(r.query.length > 30 ? r.query.substring(0, 30) + '...' : r.query)}- </a>- `).join('')}- </div>- `;- }-- // Add classification if available- let classificationHtml = '';- if (domain.classification) {- classificationHtml = `- <span class="ldr-classified-badge" title="${window.escapeHtml(domain.classification.subcategory)} (${Math.round(domain.classification.confidence * 100)}% confidence)">- ${window.escapeHtml(domain.classification.category)}- </span>- `;- }-- item.innerHTML = `- <div class="ldr-domain-header">- <span class="ldr-domain-name" style="font-size: 1rem; font-weight: 600;">- ${rank ? `#${rank}` : ''} <a href="https://${encodeURI(domain.domain)}" target="_blank" rel="noopener noreferrer" style="color: var(--accent-primary); text-decoration: none; border-bottom: 1px dotted var(--accent-primary); transition: all 0.2s ease;" onmouseover="this.style.borderBottom='2px solid var(--accent-primary)'" onmouseout="this.style.borderBottom='1px dotted var(--accent-primary)'">${window.escapeHtml(domain.domain)}</a>- ${classificationHtml}- </span>- <div class="ldr-domain-stats">- <span class="ldr-metric-badge ldr-frequency">- 📊 ${usageCount} uses (${usagePercentage}%)- </span>- <span class="ldr-metric-badge ldr-diversity">- 🔍 ${researchDiversity} researches- </span>- </div>- </div>- ${researchLinksHtml}- `;- container.appendChild(item);- });-}+// updateEnhancedDomainList lives in /static/js/pages/link_analytics_render.js+// and is exposed on window. The wrapper below (end of this script) reassigns+// it to also call loadClassificationsAndUpdateDisplay.// Event listener for period selectordocument.getElementById('period-select').addEventListener('change', (e) => {@@ -840,7 +781,7 @@ async function loadClassificationsAndUpdateDisplay() {const badge = document.createElement('span');badge.className = 'ldr-classified-badge';badge.textContent = classification.category;- badge.title = `${classification.subcategory} (${Math.round(classification.confidence * 100)}% confidence)`;+ badge.title = `${window.escapeHtml(classification.subcategory)} (${Math.round(Number(classification.confidence) * 100)}% confidence)`;domainName.appendChild(badge);}}diff --git a/tests/js/pages/link-analytics-xss.test.js b/tests/js/pages/link-analytics-xss.test.jsnew file mode 100644index 0000000000..bd929a7e01--- /dev/null+++ b/tests/js/pages/link-analytics-xss.test.js@@ -0,0 +1,261 @@+/**+ * Regression tests for the XSS hardening in link_analytics.html (PR #3095)+ * and the follow-up consistency fix at commit 12a1b11b0+ * (`researchDiversity` wrapped in `Number()` at the "Recent Researches+ * (N total)" header — link_analytics_render.js).+ *+ * Unlike pages/news.js, link_analytics writes the rendered HTML directly+ * to #domain-list via innerHTML — no DOMPurify barrier. Every untrusted+ * string interpolation must therefore be wrapped in Number() (numeric+ * coercion), escapeHtml() (entity encoding), encodeURIComponent()+ * (path segment), or encodeURI() (host). These tests pin each escape+ * site by injecting a `<script>` payload and asserting:+ * (a) no `<script>` element is created in the DOM, and+ * (b) the specific escape ran (e.g. `<script>` or `NaN` present).+ *+ * The function under test was extracted to+ * src/local_deep_research/web/static/js/pages/link_analytics_render.js+ * (surgical extraction mirroring PR #4584). The inline wrapper at+ * link_analytics.html:797-802 still reassigns it on window; the last+ * test verifies that wrapper pattern still works against the extracted+ * module.+ */++const PAYLOAD = '<script>alert(1)</script>';++beforeAll(async () => {+ // xss-protection.js provides window.escapeHtml, which the render+ // function relies on as a global. In production it's loaded by+ // base.html before the link_analytics inline script runs.+ await import('@js/security/xss-protection.js');++ // link_analytics_render.js is an IIFE that exposes+ // window.updateEnhancedDomainList on load.+ await import('@js/pages/link_analytics_render.js');+});++beforeEach(() => {+ // The render function only references #domain-list. Reset it between+ // tests so payload leakage from one test cannot satisfy another.+ document.body.innerHTML = '<div id="domain-list"></div>';+});++describe('pages/link_analytics_render.js — XSS regression for PR #3095', () => {+ it('Number()-coerces researchDiversity header + usage badges (commit 12a1b11b0)', () => {+ // Regression for the consistency fix: ${researchDiversity} in the+ // "Recent Researches (N total)" header was the only sibling field+ // not wrapped in Number(). Injecting a payload must produce 0+ // (NaN is falsy, so `Number(x) || 0` falls through) — never the+ // raw payload. Matches the `|| 0` UX pattern from news.js.+ const domains = [{+ domain: 'safe.example.com',+ count: 0,+ percentage: 0,+ research_count: 0,+ recent_researches: [{ id: 'r1', query: 'safe query' }],+ }];+ const metrics = {+ 'safe.example.com': {+ usage_count: PAYLOAD,+ usage_percentage: PAYLOAD,+ research_diversity: PAYLOAD,+ frequency_rank: PAYLOAD,+ },+ };++ window.updateEnhancedDomainList(domains, metrics);++ const html = document.getElementById('domain-list').innerHTML;++ // No script element created.+ expect(document.querySelectorAll('#domain-list script').length).toBe(0);+ // No raw payload substring anywhere.+ expect(html).not.toContain(PAYLOAD);+ // Header ran through Number() || 0 — payload can't leak; NaN+ // falls through to 0 per the established news.js pattern.+ expect(html).toContain('Recent Researches (0 total)');+ // Frequency badge: both usage_count and usage_percentage hit Number() || 0.+ expect(html).toContain('📊 0 uses (0%)');+ // Diversity badge: research_diversity hit Number() || 0.+ expect(html).toContain('🔍 0 researches');+ // Frequency rank ran through Number() — payload can't leak via the+ // `#${rank}` interpolation. The broader guards above catch this+ // if Number() coercion is ever dropped (the payload would render+ // raw as `#<script>...`).+ });++ it('escapeHtml-encodes research link query in title attr and text', () => {+ // Payload includes a quote so the title-attribute assertion can+ // distinguish "escapeHtml ran" from "browser just didn't parse <+ // as a tag inside a quoted attr". If escapeHtml did NOT run, the+ // quote would break out of the title attribute and spawn a+ // rogue onmouseover attribute on the <a>.+ const ATTR_BREAKOUT = `" onmouseover="alert(1)`;+ const domains = [{+ domain: 'safe.example.com',+ count: 1,+ recent_researches: [+ { id: 'r1', query: PAYLOAD },+ { id: 'r2', query: 'short ' + PAYLOAD },+ { id: 'r3', query: ATTR_BREAKOUT },+ ],+ }];++ window.updateEnhancedDomainList(domains, {});++ const links = document.querySelectorAll('#domain-list .ldr-research-link');+ expect(links.length).toBe(3);+ expect(document.querySelectorAll('#domain-list script').length).toBe(0);++ // First two links: text node is entity-encoded. innerHTML carries+ // the escaped form for text content (the text is inside an <a>+ // element, not an attribute, so the entities are preserved).+ const html = document.getElementById('domain-list').innerHTML;+ expect(html).toContain('<script>');+ expect(html).not.toContain('>' + PAYLOAD); // no raw payload in any text node++ // Third link: breakout payload must be contained inside the title+ // attribute, not parsed as a new attribute.+ const breakoutLink = links[2];+ expect(breakoutLink.getAttribute('onmouseover')).toBeNull();+ expect(breakoutLink.getAttribute('title')).toBe(ATTR_BREAKOUT);+ });++ it('escapes domain name in link text via escapeHtml and in href via encodeURI', () => {+ const domains = [{+ domain: PAYLOAD,+ count: 1,+ recent_researches: [],+ }];++ window.updateEnhancedDomainList(domains, {});++ const html = document.getElementById('domain-list').innerHTML;+ const link = document.querySelector('#domain-list .ldr-domain-name a');++ expect(link).not.toBeNull();+ expect(document.querySelectorAll('#domain-list script').length).toBe(0);+ // Link text is entity-encoded.+ expect(html).toContain('<script>alert(1)</script>');+ // The href is percent-encoded via encodeURI (< > " all escape to+ // %3C %3E %22), so the payload cannot break out of the href+ // attribute or be replayed as an executable URL.+ const href = link.getAttribute('href');+ expect(href).toContain('%3Cscript%3E');+ expect(href.toLowerCase()).not.toContain('javascript:');+ });++ it('escapeHtml-encodes classification category/subcategory and Number()-coerces confidence', () => {+ // Quote in subcategory tests attribute containment on the badge title.+ const ATTR_BREAKOUT = `" tiles="evil`;+ const domains = [{+ domain: 'classified.example.com',+ count: 1,+ recent_researches: [],+ classification: {+ category: PAYLOAD,+ subcategory: PAYLOAD + ATTR_BREAKOUT,+ confidence: PAYLOAD,+ },+ }];++ window.updateEnhancedDomainList(domains, {});++ const badge = document.querySelector('#domain-list .ldr-classified-badge');+ expect(badge).not.toBeNull();+ expect(document.querySelectorAll('#domain-list script').length).toBe(0);++ // Category text node entity-encoded (whitespace from template+ // literal indentation surrounds the value).+ expect(badge.textContent.trim()).toBe(PAYLOAD);++ // Subcategory ran through escapeHtml: the breakout quote must be+ // contained inside the title attribute, not parsed as a new+ // attribute. The badge must not gain a `tiles` attribute.+ expect(badge.getAttribute('tiles')).toBeNull();+ expect(badge.getAttribute('title')).toContain(PAYLOAD);+ expect(badge.getAttribute('title')).toContain(ATTR_BREAKOUT);++ // Confidence ran through Math.round(Number(...)) — produces NaN,+ // never the raw payload.+ expect(badge.getAttribute('title')).toContain('(NaN% confidence)');+ });++ it('renders the full set of expected selectors on a valid payload', () => {+ const domains = [{+ domain: 'example.com',+ count: 5,+ percentage: 12.5,+ research_count: 3,+ frequency_rank: 1,+ recent_researches: [{ id: 'r1', query: 'a safe query' }],+ classification: { category: 'Tech', subcategory: 'AI', confidence: 0.9 },+ }];+ const metrics = {+ 'example.com': {+ usage_count: 5,+ usage_percentage: 12.5,+ research_diversity: 3,+ frequency_rank: 1,+ },+ };++ expect(() => window.updateEnhancedDomainList(domains, metrics)).not.toThrow();++ const list = document.getElementById('domain-list');+ expect(list.querySelector('.ldr-domain-item-expanded')).not.toBeNull();+ expect(list.querySelector('.ldr-domain-header')).not.toBeNull();+ expect(list.querySelector('.ldr-domain-name')).not.toBeNull();+ expect(list.querySelector('.ldr-domain-stats')).not.toBeNull();+ expect(list.querySelector('.ldr-frequency')).not.toBeNull();+ expect(list.querySelector('.ldr-diversity')).not.toBeNull();+ expect(list.querySelector('.ldr-research-links')).not.toBeNull();+ expect(list.querySelector('.ldr-research-links-title')).not.toBeNull();+ expect(list.querySelector('.ldr-research-link')).not.toBeNull();+ expect(list.querySelector('.ldr-classified-badge')).not.toBeNull();++ // Numeric rendering is intact on the happy path.+ const html = list.innerHTML;+ expect(html).toContain('Recent Researches (3 total)');+ expect(html).toContain('📊 5 uses (12.5%)');+ expect(html).toContain('🔍 3 researches');+ expect(html).toContain('(90% confidence)');+ });++ it('renders the empty-list fallback when domains is []', () => {+ window.updateEnhancedDomainList([], {});++ const html = document.getElementById('domain-list').innerHTML;+ expect(html).toContain('No domain data available');+ expect(document.querySelectorAll('#domain-list script').length).toBe(0);+ });++ it('supports the inline-script wrapper pattern (read + reassign + call)', () => {+ // link_analytics.html:797-802 captures the original+ // window.updateEnhancedDomainList and reassigns it to a wrapper+ // that also calls loadClassificationsAndUpdateDisplay(). The+ // surgical extraction must preserve this pattern: window must+ // hold a reassignable function reference, not a frozen export.+ const original = window.updateEnhancedDomainList;+ expect(typeof original).toBe('function');++ let sideEffectRan = false;+ window.updateEnhancedDomainList = function(domains, metrics) {+ original.call(this, domains, metrics);+ sideEffectRan = true;+ };++ try {+ window.updateEnhancedDomainList(+ [{ domain: 'wrapper.example.com', count: 1, recent_researches: [] }],+ {}+ );+ expect(sideEffectRan).toBe(true);+ // Original behavior still ran — domain was rendered.+ expect(document.querySelector('#domain-list .ldr-domain-item-expanded')).not.toBeNull();+ } finally {+ // Restore so subsequent tests get the un-wrapped function.+ window.updateEnhancedDomainList = original;+ }+ });+});diff --git a/tests/js/pages/news-xss.test.js b/tests/js/pages/news-xss.test.jsnew file mode 100644index 0000000000..3af955feab--- /dev/null+++ b/tests/js/pages/news-xss.test.js@@ -0,0 +1,167 @@+/**+ * Regression tests for the XSS hardening in pages/news.js (PR #3095).+ *+ * The render path runs every template literal through safeRenderHTML ->+ * window.DOMPurify.sanitize, so DOMPurify is the runtime XSS barrier.+ * The Number()/escapeHtml() wrappers added in PR #3095 are defense-in-depth:+ * they stop a payload from reaching DOMPurify in an executable shape —+ * notably inside `style="width: ..."` (where escapeHtml would not help) and+ * inside text nodes that DOMPurify would technically allow through if the+ * surrounding markup looked valid.+ *+ * To assert the *source-level* escaping rather than DOMPurify's output, we+ * spy on DOMPurify.sanitize and inspect the pre-sanitized htmlString that+ * the template produced. If the literal `<script>` substring shows up there,+ * a future edit has dropped one of the Number()/escapeHtml() wrappers.+ *+ * Scope: the fields touched by PR #3095 — impact_score (style attribute and+ * text node), upvotes/downvotes (text node), and time_ago (text node wrapped+ * by escapeHtml that previously only covered one branch of a || chain).+ */++let sanitizeSpy;+let feedResponse;++const PAYLOAD = '<script>alert(1)</script>';++function makeItem(overrides = {}) {+ return {+ id: 'xss-item',+ headline: 'Safe headline',+ category: 'General',+ impact_score: 5,+ upvotes: 0,+ downvotes: 0,+ created_at: new Date().toISOString(),+ time_ago: 'just now',+ topics: [],+ links: [],+ ...overrides,+ };+}++beforeAll(async () => {+ // xss-protection.js provides window.escapeHtml, which news.js relies on+ // as a global. In production it's loaded by base.html before pages/news.js.+ await import('@js/security/xss-protection.js');++ // Stub DOMPurify.sanitize with a spy that returns a real DocumentFragment+ // (safeRenderHTML appends it to the container). The incoming htmlString+ // is captured on mock.calls so assertions can inspect the pre-sanitized+ // template output.+ 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 are explicitly capturing for assertions; this code runs only under Vitest, never in production.+ template.innerHTML = htmlString;+ return template.content;+ });+ window.DOMPurify = { sanitize: sanitizeSpy };++ // feedResponse is swapped per-test to control the payload. The default+ // routes mean only /news/api/feed sees the payload; other endpoints+ // initializeNewsPage touches get an empty object so they no-op.+ feedResponse = { news_items: [] };+ globalThis.fetch = vi.fn((url) => {+ const urlStr = String(url);+ const body = urlStr.includes('/news/api/feed') ? feedResponse : {};+ 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>+ `;++ await import('@js/pages/news.js');+});++async function renderWith(items) {+ // Drive a single loadNewsFeed() round-trip with `items` as the response.+ // Each call appends to sanitizeSpy.mock.calls; callers search for their+ // headline to find the matching htmlString.+ sanitizeSpy.mockClear();+ feedResponse = { news_items: items };+ await window.loadNewsFeed();+ // loadVotesForNewsItems is fired unconditionally after render; let it+ // settle so it doesn't pollute the next test's spy captures.+ await new Promise(resolve => setTimeout(resolve, 10));+}++function renderedHtmlForHeadline(headline) {+ for (const [htmlString] of sanitizeSpy.mock.calls) {+ if (typeof htmlString === 'string' && htmlString.includes(headline)) {+ return htmlString;+ }+ }+ return '';+}++describe('pages/news.js — XSS regression for PR #3095', () => {+ it('does not leak raw <script> from impact_score into the style attribute', async () => {+ const html = await renderWith([makeItem({+ id: 'impact-payload',+ headline: 'IMPACT_CANARY',+ impact_score: PAYLOAD,+ })]).then(() => renderedHtmlForHeadline('IMPACT_CANARY'));++ expect(html).not.toBe('');+ // Style-attribute injection: a payload inside style="width:..."+ // would let an attacker inject e.g. `1;background:url(javascript:...)`.+ // Number() coerces the payload to NaN, so the literal <script>+ // substring must never appear in the produced HTML.+ expect(html).not.toContain(PAYLOAD);+ // The "/10" text node is interpolated from the same field and must+ // also be free of the payload.+ expect(html).not.toMatch(new RegExp(PAYLOAD.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '\\s*/10'));+ });++ it('does not leak raw <script> from upvotes/downvotes into vote buttons', async () => {+ const html = await renderWith([makeItem({+ id: 'vote-payload',+ headline: 'VOTE_CANARY',+ upvotes: PAYLOAD,+ downvotes: PAYLOAD,+ })]).then(() => renderedHtmlForHeadline('VOTE_CANARY'));++ expect(html).not.toBe('');+ expect(html).not.toContain(PAYLOAD);+ });++ it('does not leak raw <script> from time_ago into the date span', async () => {+ // time_ago only interpolates when formatNewsDate(item.created_at) is+ // falsy. Send no created_at so the right side of the || chain fires+ // — that's the branch PR #3095 wrapped in escapeHtml().+ const html = await renderWith([makeItem({+ id: 'time-payload',+ headline: 'TIME_CANARY',+ created_at: null,+ time_ago: PAYLOAD,+ })]).then(() => renderedHtmlForHeadline('TIME_CANARY'));++ expect(html).not.toBe('');+ // escapeHtml turns <script> into <script>. The literal payload+ // substring must not survive.+ expect(html).not.toContain(PAYLOAD);+ expect(html).toContain('<script>');+ });+});diff --git a/tests/ui_tests/run_all_tests.js b/tests/ui_tests/run_all_tests.jsindex 6098e490fd..c232092ff1 100644--- a/tests/ui_tests/run_all_tests.js+++ b/tests/ui_tests/run_all_tests.js@@ -13,13 +13,13 @@* Valid shards: auth-login, auth-register, auth-pages, research-workflow,* research-form, research-metrics, settings-core, settings-pages,* library, history-news, mobile, api-crud, error-benchmark, accessibility,- * chat-core, chat-lifecycle+ * chat-core, chat-lifecycle, link-analytics*/// Keep in sync with `strategy.matrix.shard` in .github/workflows/docker-tests.yml.// A mismatch would cause silent test misrouting.//-// Shard design (16 shards, ~4 tests each):+// Shard design (17 shards, ~4 tests each):// Each shard runs in its own Docker container with a dedicated server.// Keeping shards small prevents cascade failures when one test stresses// the server (e.g., encrypted DB creation in auth-register).@@ -40,6 +40,7 @@ const VALID_SHARDS = ['accessibility', // keyboard navigation & ARIA'chat-core', // chat-mode v2 input + a11y + chips + nav'chat-lifecycle', // chat-mode v2 session lifecycle + export + persistence+ 'link-analytics', // /metrics/links full-page render + XSS runtime check];const { spawn } = require('child_process');@@ -211,6 +212,16 @@ const tests = [description: 'Tests progress page and real-time elements'},+ // =====================================================================+ // Shard: link-analytics (1 test — release-pipeline only)+ // =====================================================================+ {+ name: 'Link Analytics Full Page Test',+ file: 'test_link_analytics_full.js',+ shard: 'link-analytics',+ description: 'Verifies /metrics/links renders, Recent Researches header shows numeric total, no console errors, no script element leaks'+ },+// =====================================================================// Shard: settings-core (4 tests)// =====================================================================diff --git a/tests/ui_tests/test_link_analytics_full.js b/tests/ui_tests/test_link_analytics_full.jsnew file mode 100644index 0000000000..b537db8eae--- /dev/null+++ b/tests/ui_tests/test_link_analytics_full.js@@ -0,0 +1,243 @@+#!/usr/bin/env node+/**+ * Link Analytics Full Page UI Test (shard: link-analytics)+ *+ * Verifies the rendered /metrics/links page:+ * - page loads without console errors or uncaught exceptions+ * - the domain list renders with the expected CSS selectors+ * - the inline-script wrapper (link_analytics.html:797-802) preserved+ * after the surgical extraction of updateEnhancedDomainList to+ * /static/js/pages/link_analytics_render.js — i.e. the function+ * is callable and the rendered number in the "Recent Researches+ * (N total)" header matches the API response (catches the exact+ * bug class of commit 12a1b11b0 on valid data).+ *+ * Existing LinkAnalyticsTests in test_metrics_dashboard_ci.js:474-552+ * is smoke-only (never expands a domain, never sees the header). This+ * shard is the deeper coverage complement.+ *+ * Run: node test_link_analytics_full.js+ */++const { setupTest, teardownTest, TestResults, log, navigateTo, withTimeout } = require('./test_lib');++const LinkAnalyticsFullTests = {+ /**+ * Render check: #domain-list must populate with at least one+ * .ldr-domain-item-expanded, plus the frequency and diversity badges.+ * The page must render clean — the inline-script wrapper depends on+ * updateEnhancedDomainList being on window, and any throw would+ * break the render path silently. Console/pageerror capture is+ * handled centrally by the `run` wrapper in main(), not here.+ */+ async pageLoadsCleanAndRendersList(page, baseUrl) {+ await navigateTo(page, `${baseUrl}/metrics/links`);++ // #domain-list is populated by updateEnhancedDomainList (now in+ // link_analytics_render.js). Wait for at least one rendered item.+ await page.waitForSelector('#domain-list .ldr-domain-item-expanded', {+ timeout: 15000,+ });++ const result = await page.evaluate(() => {+ const list = document.getElementById('domain-list');+ const items = list?.querySelectorAll('.ldr-domain-item-expanded') ?? [];+ const firstHeader = list?.querySelector('.ldr-domain-header') ?? null;+ return {+ itemCount: items.length,+ hasFrequencyBadge: !!list?.querySelector('.ldr-frequency'),+ hasDiversityBadge: !!list?.querySelector('.ldr-diversity'),+ firstDomainText: firstHeader?.querySelector('.ldr-domain-name')?.textContent?.trim() ?? null,+ };+ });++ return {+ passed: result.itemCount > 0 && result.hasFrequencyBadge && result.hasDiversityBadge,+ message: `${result.itemCount} domain(s) rendered, first="${result.firstDomainText}"`,+ };+ },++ /**+ * Expand the first domain and verify the "Recent Researches (N total)"+ * header is present. The (N total) value must be a number — if the+ * Number() coercion from commit 12a1b11b0 regressed on valid data,+ * N would be `NaN` and this assertion catches it.+ */+ async recentResearchesHeaderShowsNumericTotal(page, baseUrl) {+ await navigateTo(page, `${baseUrl}/metrics/links`);++ await page.waitForSelector('#domain-list .ldr-domain-item-expanded', {+ timeout: 15000,+ });++ // Domains always render expanded in this layout (.ldr-domain-item-expanded+ // is the row class), so the research-links block is already in the DOM+ // if the domain has any recent researches. Find one with links present.+ const result = await page.evaluate(() => {+ const titles = Array.from(document.querySelectorAll('.ldr-research-links-title'));+ const match = titles.find(t => /Recent Researches\s*\(/.test(t.textContent || ''));+ if (!match) return { found: false };+ const text = match.textContent.trim();+ // Header looks like "Recent Researches (N total)". Capture N.+ // Restrict N to digits to avoid super-linear backtracking.+ const m = text.match(/Recent Researches\s*\((\d+)\s+total\)/);+ return {+ found: true,+ rawText: text,+ totalToken: m ? m[1] : null,+ };+ });++ if (!result.found) {+ return { passed: null, skipped: true, message: 'No "Recent Researches" header present (no domains had recent researches in test data)' };+ }++ // totalToken must be a valid base-10 number — proves Number() coercion+ // succeeded on a valid input (the inverse of the XSS test which proves+ // it produces NaN on a bad input).+ const isNumeric = /^\d+$/.test(result.totalToken || '');+ return {+ passed: isNumeric,+ message: `header raw="${result.rawText}", totalToken="${result.totalToken}", numeric=${isNumeric}`,+ };+ },++ /**+ * Verify the frequency badge text is well-formed: "📊 N uses (N%)" with+ * numeric N. Catches the same Number()-coercion bug class as the header+ * test, on a separate field path.+ */+ async frequencyBadgeWellFormed(page, baseUrl) {+ await navigateTo(page, `${baseUrl}/metrics/links`);+ await page.waitForSelector('.ldr-frequency', { timeout: 15000 });++ const result = await page.evaluate(() => {+ const badges = Array.from(document.querySelectorAll('.ldr-frequency'));+ const sample = badges.slice(0, 3).map(b => b.textContent.trim());+ const allMatch = badges.every(b => /📊\s+\d+\s+uses\s+\(\d+(?:\.\d+)?%\)/.test(b.textContent || ''));+ return { sample, allMatch, count: badges.length };+ });++ return {+ passed: result.allMatch && result.count > 0,+ message: `${result.count} frequency badges, allMatch=${result.allMatch}, sample=${JSON.stringify(result.sample)}`,+ };+ },++ /**+ * Verify no <script> element was injected into the rendered list —+ * the runtime mirror of the Vitest XSS regression. If a payload ever+ * survives the Number()/escapeHtml() barrier, this catches it in a+ * real browser against live API data.+ */+ async noScriptElementLeakedIntoList(page, baseUrl) {+ await navigateTo(page, `${baseUrl}/metrics/links`);+ await page.waitForSelector('#domain-list .ldr-domain-item-expanded', { timeout: 15000 });++ const result = await page.evaluate(() => {+ const list = document.getElementById('domain-list');+ return {+ scriptCount: list?.querySelectorAll('script').length ?? 0,+ eventHandlers: Array.from(list?.querySelectorAll('*') ?? [])+ .filter(el => Array.from(el.attributes).some(a => a.name.startsWith('on') && a.name !== 'onmouseover' && a.name !== 'onmouseout'))+ .map(el => ({ tag: el.tagName, attrs: Array.from(el.attributes).filter(a => a.name.startsWith('on')).map(a => a.name) })),+ };+ });++ return {+ passed: result.scriptCount === 0 && result.eventHandlers.length === 0,+ message: `script elements in #domain-list: ${result.scriptCount}; unexpected event handlers: ${JSON.stringify(result.eventHandlers)}`,+ };+ },+};++// ============================================================================+// Main Test Runner+// ============================================================================+async function main() {+ log.section('Link Analytics Full Page Tests');++ const ctx = await setupTest({ authenticate: true });+ const results = new TestResults('Link Analytics Full Page Tests');+ const { page } = ctx;+ const { baseUrl } = ctx.config;++ // Capture browser-side errors across the entire test run. Each test+ // receives this array; the verdict for any test that observed the+ // navigation lifecycle is "fail" if errors is non-empty.+ const browserErrors = [];+ page.on('console', (msg) => {+ if (msg.type() === 'error') {+ browserErrors.push(`console.error: ${msg.text()}`);+ }+ });+ page.on('pageerror', (err) => {+ browserErrors.push(`pageerror: ${err.message}`);+ });++ const subTestTimeout = ctx.config.isCI ? 60000 : 30000;+ async function run(category, name, testFn) {+ // Snapshot browser errors before the test starts. After testFn+ // resolves, the delta is attributed to THIS test — not shared+ // across tests, not stale. If the delta is non-empty, the test+ // fails regardless of its own verdict, because a console error+ // or pageerror during render signals the inline-script wrapper+ // or extracted module is broken in the real browser.+ const before = browserErrors.length;+ let result;+ try {+ result = await withTimeout(+ testFn(page, baseUrl),+ subTestTimeout,+ `${category}/${name}`+ );+ } catch (error) {+ results.add(category, name, false, `Error: ${error.message}`);+ return;+ }++ const newErrors = browserErrors.slice(before);+ if (result.skipped) {+ results.skip(category, name, result.message);+ return;+ }+ if (newErrors.length > 0) {+ results.add(+ category,+ name,+ false,+ `${result.message} | ${newErrors.length} browser error(s): ${newErrors.join('; ')}`+ );+ return;+ }+ results.add(category, name, result.passed, result.message);+ }++ try {+ await run('Render', 'Page Loads Clean And Renders List',+ (p, u) => LinkAnalyticsFullTests.pageLoadsCleanAndRendersList(p, u));+ await run('Render', 'Recent Researches Header Shows Numeric Total',+ (p, u) => LinkAnalyticsFullTests.recentResearchesHeaderShowsNumericTotal(p, u));+ await run('Render', 'Frequency Badge Well Formed',+ (p, u) => LinkAnalyticsFullTests.frequencyBadgeWellFormed(p, u));+ await run('Security', 'No Script Element Leaked Into List',+ (p, u) => LinkAnalyticsFullTests.noScriptElementLeakedIntoList(p, u));+ } catch (error) {+ log.error(`Fatal error: ${error.message}`);+ console.error(error.stack);+ } finally {+ results.print();+ results.save();+ await teardownTest(ctx);+ process.exit(results.exitCode());+ }+}++if (require.main === module) {+ main().catch(error => {+ console.error('Test runner failed:', error);+ process.exit(1);+ });+}++module.exports = { LinkAnalyticsFullTests };