~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(news): clamp impact_score width to [0, 100]% (#4705)
LearningCircuit3c71f766b2fb
diff --git a/src/local_deep_research/web/static/js/pages/news.js b/src/local_deep_research/web/static/js/pages/news.jsindex 58e2db4c92..2bf5043c1d 100644--- a/src/local_deep_research/web/static/js/pages/news.js+++ b/src/local_deep_research/web/static/js/pages/news.js@@ -1042,7 +1042,7 @@ function renderNewsItems(searchQuery = null) {<span class="ldr-impact-indicator">Impact:<div class="ldr-impact-bar">- <div class="ldr-impact-fill" style="width: ${(Number(item.impact_score) || 0) * 10}%"></div>+ <div class="ldr-impact-fill" style="width: ${Math.max(0, Math.min(100, (Number(item.impact_score) || 0) * 10))}%"></div></div>${Number(item.impact_score) || 0}/10</span>diff --git a/tests/js/pages/helpers/news-render-harness.js b/tests/js/pages/helpers/news-render-harness.jsnew file mode 100644index 0000000000..734b9b3f88--- /dev/null+++ b/tests/js/pages/helpers/news-render-harness.js@@ -0,0 +1,122 @@+/**+ * Shared test harness for pages/news.js render-path specs.+ *+ * Both news-xss.test.js and news-impact-clamp.test.js drive the same render+ * cycle (loadNewsFeed -> safeRenderHTML -> window.DOMPurify.sanitize) and+ * assert on the *pre-sanitized* htmlString the template produced. This module+ * owns the scaffold they previously cloned: the item factory, the DOMPurify+ * spy + fetch stub + DOM fixture installer, and the render/capture helpers.+ *+ * Vitest isolates modules per test file, so each spec that calls+ * installNewsRenderHarness() in beforeAll gets its own fresh news.js import+ * and spy — no cross-file state leaks.+ */++import { vi } from 'vitest';++// Minimal DOM the news page wires up in initializeNewsPage(); without these+// ids/classes the render path throws before producing any sanitize() call.+const NEWS_FIXTURE_HTML = `+ <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>+`;++/** A well-formed news item; pass overrides to control the field under test. */+export function makeNewsItem(overrides = {}) {+ return {+ id: 'news-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,+ };+}++/**+ * Install the news render harness. Call once from a spec's beforeAll.+ *+ * Stubs window.DOMPurify.sanitize with a spy that returns a real+ * DocumentFragment (so safeRenderHTML can append it) while capturing the+ * incoming pre-sanitized htmlString, stubs fetch so only /news/api/feed sees+ * the per-render payload, installs the DOM fixture, and imports news.js.+ *+ * Returns:+ * - renderWith(items): drive one loadNewsFeed() round-trip with `items`.+ * - capturedHtmlFor(substring): the pre-sanitized htmlString containing+ * `substring` (typically a unique headline), or null.+ * - sanitizeSpy: the underlying vi.fn for assertions that need raw calls.+ */+export async function installNewsRenderHarness() {+ // xss-protection.js provides window.escapeHtml, which news.js relies on as+ // a global (loaded by base.html before pages/news.js in production).+ await import('@js/security/xss-protection.js');++ const 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 = { sanitize: sanitizeSpy };++ // Swapped per render to control the payload; only /news/api/feed returns+ // it so the other endpoints initializeNewsPage touches no-op.+ let feedResponse = { news_items: [] };+ globalThis.fetch = vi.fn((url) => {+ const body = String(url).includes('/news/api/feed') ? feedResponse : {};+ return Promise.resolve({+ ok: true,+ status: 200,+ json: () => Promise.resolve(body),+ text: () => Promise.resolve(''),+ });+ });++ // eslint-disable-next-line no-unsanitized/property -- test-only: NEWS_FIXTURE_HTML is a static fixture constant defined in this file, not user input; runs only under Vitest.+ document.body.innerHTML = NEWS_FIXTURE_HTML;+ await import('@js/pages/news.js');++ async function renderWith(items) {+ sanitizeSpy.mockClear();+ feedResponse = { news_items: items };+ await window.loadNewsFeed();+ // loadVotesForNewsItems fires unconditionally after render; let it+ // settle so it doesn't pollute the next render's spy captures.+ await new Promise((resolve) => setTimeout(resolve, 10));+ }++ function capturedHtmlFor(substring) {+ for (const [htmlString] of sanitizeSpy.mock.calls) {+ if (+ typeof htmlString === 'string' &&+ htmlString.includes(substring)+ ) {+ return htmlString;+ }+ }+ return null;+ }++ return { sanitizeSpy, renderWith, capturedHtmlFor };+}diff --git a/tests/js/pages/news-impact-clamp.test.js b/tests/js/pages/news-impact-clamp.test.jsnew file mode 100644index 0000000000..7180748758--- /dev/null+++ b/tests/js/pages/news-impact-clamp.test.js@@ -0,0 +1,65 @@+/**+ * Regression tests for the impact_score width clamp in pages/news.js.+ *+ * impact_score is documented as 0-10. The width style interpolates the+ * value * 10 to get a percentage, so an out-of-range API response+ * (e.g. 15 or -1) would produce width: 150% or width: -10%. CSS clamps+ * both silently at render time, but the inspected DOM would still show+ * the broken value, and any future code path that read the style back+ * would see the unclamped number.+ *+ * These tests lock in Math.max(0, Math.min(100, ...)) around the width+ * interpolation. They do NOT exercise DOMPurify because the clamp is+ * orthogonal to XSS hardening (covered by news-xss.test.js). The shared+ * render scaffold lives in helpers/news-render-harness.js.+ */++import {+ installNewsRenderHarness,+ makeNewsItem as makeItem,+} from './helpers/news-render-harness.js';++let harness;++beforeAll(async () => {+ harness = await installNewsRenderHarness();+});++function widthForHeadline(headline) {+ const html = harness.capturedHtmlFor(headline);+ if (!html) {+ return null;+ }+ const match = html.match(/width:\s*(\S+)%/);+ return match ? match[1] : null;+}++describe('pages/news.js — impact_score width clamp', () => {+ it('produces width: 50% for a normal impact_score of 5', async () => {+ await harness.renderWith([makeItem({ id: 'a', headline: 'NORMAL_FIVE', impact_score: 5 })]);+ expect(widthForHeadline('NORMAL_FIVE')).toBe('50');+ });++ it('clamps an out-of-range high impact_score to 100% width', async () => {+ // API contract says 0-10, but defend in depth: a buggy response of+ // 15 must not produce width: 150%.+ await harness.renderWith([makeItem({ id: 'b', headline: 'OVER_TEN', impact_score: 15 })]);+ expect(widthForHeadline('OVER_TEN')).toBe('100');+ });++ it('clamps a negative impact_score to 0% width', async () => {+ await harness.renderWith([makeItem({ id: 'c', headline: 'NEGATIVE', impact_score: -3 })]);+ expect(widthForHeadline('NEGATIVE')).toBe('0');+ });++ it('does not affect the impact_score text node (which still shows the raw value)', async () => {+ // The clamp is width-only; the /10 text node shows the real value+ // so the user sees "15/10" and can spot the API bug visually.+ await harness.renderWith([makeItem({+ id: 'd', headline: 'TEXT_UNCLAMPED', impact_score: 15,+ })]);+ const html = harness.capturedHtmlFor('TEXT_UNCLAMPED') || '';+ expect(html).toContain('15/10');+ expect(html).not.toContain('10/10');+ });+});diff --git a/tests/js/pages/news-xss.test.js b/tests/js/pages/news-xss.test.jsindex 3af955feab..aa9845e7ad 100644--- a/tests/js/pages/news-xss.test.js+++ b/tests/js/pages/news-xss.test.js@@ -17,103 +17,29 @@* 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).+ *+ * The shared render scaffold lives in helpers/news-render-harness.js.*/-let sanitizeSpy;-let feedResponse;+import {+ installNewsRenderHarness,+ makeNewsItem as makeItem,+} from './helpers/news-render-harness.js';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,- };-}+let harness;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');+ harness = await installNewsRenderHarness();});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));+ return harness.renderWith(items);}function renderedHtmlForHeadline(headline) {- for (const [htmlString] of sanitizeSpy.mock.calls) {- if (typeof htmlString === 'string' && htmlString.includes(headline)) {- return htmlString;- }- }- return '';+ return harness.capturedHtmlFor(headline) || '';}describe('pages/news.js — XSS regression for PR #3095', () => {