~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): keep server IDs out of inline event handlers (#7055)
LearningCircuit6f6d5893d9b6
diff --git a/changelog.d/+collection-document-actions.security.md b/changelog.d/+collection-document-actions.security.mdnew file mode 100644index 0000000000..88747078a2--- /dev/null+++ b/changelog.d/+collection-document-actions.security.md@@ -0,0 +1 @@+Document, research and subscription action controls no longer embed IDs in inline JavaScript event handlers. Each control now carries its ID as inert data that a page script reads in an event listener. The browser decodes an attribute's HTML escaping before it compiles an inline `onclick` handler, so escaping alone did not stop an ID containing a quote from closing the handler's string and running as script when a user clicked. This covers: the collection details page's document remove-from-collection and delete buttons; the library page's document cards (clicking a card to open it, and the remove-PDF and delete buttons); the download manager's per-research View Research, PDFs, Text Only and View Downloaded buttons; the subscriptions page's cards (clicking a card opens its history) and their Run now, Pause/Resume, View history and Delete buttons; and the collection upload page's Cancel button, whose collection ID the route already restricts to a well-formed UUID.diff --git a/src/local_deep_research/web/routers/rag.py b/src/local_deep_research/web/routers/rag.pyindex 7d8e12a10f..47443b86b3 100644--- a/src/local_deep_research/web/routers/rag.py+++ b/src/local_deep_research/web/routers/rag.py@@ -611,14 +611,15 @@ def _validated_collection_id(collection_id: str) -> str:String(36), assigned from `str(uuid.uuid4())`), so anything else is eithera typo or an injection attempt and cannot match a real row.- This is the fix for a stored-reflection XSS: the page templates interpolate- this value into an inline `onclick` handler, and HTML-escaping is NOT- sufficient there -- the browser entity-decodes attribute content before- treating it as JS, so an escaped quote reopens the string. Validating the- shape at the boundary means no template can receive a value capable of- breaking out, regardless of the context it is interpolated into. That is- strictly more robust than fixing the one template, because it also covers- collection_details.html and anything added later.+ This was the first fix for a stored-reflection XSS: collection_upload.html+ interpolated this value into an inline `onclick` handler, and+ HTML-escaping is NOT sufficient there -- the browser entity-decodes+ attribute content before treating it as JS, so an escaped quote reopens+ the string. That template now passes the ID as a data attribute read by a+ script listener instead. This check stays as the second layer: validating+ the shape at the boundary means no template can receive a value capable of+ breaking out, regardless of the context it is interpolated into, which+ also covers collection_details.html and anything added later.(`/collections/create` is a separate static route registered ahead of theparameterised ones, so it never reaches this.)diff --git a/src/local_deep_research/web/static/js/collection_details.js b/src/local_deep_research/web/static/js/collection_details.jsindex 2ac5956bc4..6c9dfffed6 100644--- a/src/local_deep_research/web/static/js/collection_details.js+++ b/src/local_deep_research/web/static/js/collection_details.js@@ -43,6 +43,25 @@ document.addEventListener('DOMContentLoaded', function() {agentToggle.addEventListener('change', () => updateCollectionAgentEnabled(agentToggle.checked));}+ const documentList = document.getElementById('documents-list');+ if (documentList) {+ documentList.addEventListener('click', (event) => {+ const actionButton = event.target.closest('button[data-doc-action]');+ if (!actionButton || !documentList.contains(actionButton)) return;+ const row = actionButton.closest('.ldr-document-item');+ const documentId = row?.dataset.documentId;+ if (!documentId) return;++ event.preventDefault();+ event.stopPropagation();+ if (actionButton.dataset.docAction === 'remove') {+ removeDocumentFromCollection(documentId);+ } else if (actionButton.dataset.docAction === 'delete') {+ deleteDocumentCompletely(documentId);+ }+ });+ }+// Check if there's an active indexing taskcheckAndResumeIndexing();});@@ -409,7 +428,7 @@ function renderDocuments() {// eslint-disable-next-line no-unsanitized/property -- audited 2026-03-28: all interpolations use escapeHtml/esc, numeric coercion, or hardcoded stringscontainer.innerHTML = filteredDocs.map(doc => `- <div class="ldr-document-item ${doc.indexed ? 'ldr-indexed' : 'ldr-unindexed'}">+ <div class="ldr-document-item ${doc.indexed ? 'ldr-indexed' : 'ldr-unindexed'}" data-document-id="${escapeHtml(doc.id)}"><a href="/library/document/${encodeURIComponent(doc.id)}" class="ldr-document-link" style="text-decoration: none; color: inherit; display: block; flex: 1;"><div class="ldr-document-info"><div class="ldr-document-title">@@ -430,11 +449,11 @@ function renderDocuments() {</div></a><div class="ldr-document-actions">- <button class="ldr-btn-remove-from-collection" onclick="event.stopPropagation(); removeDocumentFromCollection('${escapeHtml(doc.id)}')"+ <button class="ldr-btn-remove-from-collection" data-doc-action="remove"title="Remove from collection. ${doc.in_other_collections ? 'Document exists in other collections.' : 'Document will be deleted (not in other collections).'}"><i class="fas fa-unlink"></i></button>- <button class="ldr-btn-delete-doc" onclick="event.stopPropagation(); deleteDocumentCompletely('${escapeHtml(doc.id)}')"+ <button class="ldr-btn-delete-doc" data-doc-action="delete"title="Permanently delete this document, including PDF and text content. This cannot be undone."><i class="fas fa-trash"></i></button>diff --git a/src/local_deep_research/web/static/js/collection_upload.js b/src/local_deep_research/web/static/js/collection_upload.jsindex 7c094634d5..cf6a0f7e1f 100644--- a/src/local_deep_research/web/static/js/collection_upload.js+++ b/src/local_deep_research/web/static/js/collection_upload.js@@ -93,6 +93,18 @@ document.addEventListener('DOMContentLoaded', function() {// Setup file input change handlerdocument.getElementById('files-input').addEventListener('change', handleFileSelect);+ // Cancel returns to the collection. The button carries the collection ID+ // as inert data, so the ID is never compiled as JavaScript, as it would+ // be inside an inline on* handler.+ const cancelButton = document.querySelector('[data-upload-action="cancel"]');+ if (cancelButton) {+ cancelButton.addEventListener('click', () => {+ const collectionId = cancelButton.dataset.collectionId;+ if (!collectionId) return;+ window.location.href = `/library/collections/${encodeURIComponent(collectionId)}`;+ });+ }+// Setup drag and dropconst dropZone = document.getElementById('drop-zone');const fileInput = document.getElementById('files-input');diff --git a/src/local_deep_research/web/static/js/pages/subscriptions.js b/src/local_deep_research/web/static/js/pages/subscriptions.jsindex ddc8e03c25..3d9d63c174 100644--- a/src/local_deep_research/web/static/js/pages/subscriptions.js+++ b/src/local_deep_research/web/static/js/pages/subscriptions.js@@ -61,6 +61,13 @@ document.addEventListener('DOMContentLoaded', function() {// Setup event listenersfunction setupEventListeners() {+ // Card actions. Each card carries its subscription ID as inert data, and+ // the card and its buttons name their action in data-subscription-action.+ // This one delegated listener joins the two, so an ID is never compiled+ // as JavaScript, as it would be inside an inline on* handler.+ document.getElementById('subscriptions-grid')+ ?.addEventListener('click', handleSubscriptionCardAction);+// Search boxdocument.getElementById('subscription-search').addEventListener('input', (e) => {currentFilter.search = e.target.value;@@ -98,6 +105,37 @@ function setupEventListeners() {});}+// Dispatch a click on a subscription card or on one of its action buttons+function handleSubscriptionCardAction(event) {+ const grid = event.currentTarget;+ const actionElement = event.target.closest('[data-subscription-action]');+ if (!actionElement || !grid.contains(actionElement)) return;+ const card = actionElement.closest('.ldr-subscription-card');+ const subscriptionId = card?.dataset.subscriptionId;+ if (!subscriptionId) return;++ // A button click stays inside the card, as it did when each button+ // stopped propagation itself.+ if (actionElement !== card) event.stopPropagation();++ switch (actionElement.dataset.subscriptionAction) {+ case 'run':+ runSubscriptionNow(subscriptionId);+ break;+ case 'toggle':+ toggleSubscription(subscriptionId);+ break;+ case 'history':+ viewSubscriptionHistory(subscriptionId);+ break;+ case 'delete':+ deleteSubscriptionDirect(subscriptionId);+ break;+ default:+ break;+ }+}+// Load subscriptions from APIasync function loadSubscriptions() {const loadRequestId = ++subscriptionsLoadRequestId;@@ -227,23 +265,23 @@ function createSubscriptionCard(subscription) {const safeQuery = escapeHtml(subscription.query);return `- <div class="ldr-subscription-card" data-subscription-id="${escapeHtml(subscription.id)}" onclick="viewSubscriptionHistory('${escapeHtml(subscription.id)}')" style="cursor: pointer;">+ <div class="ldr-subscription-card" data-subscription-id="${escapeHtml(subscription.id)}" data-subscription-action="history" style="cursor: pointer;"><div class="ldr-card-header"><h4 title="${safeDisplayName}">${safeTruncatedName}</h4><div class="ldr-card-actions">- <button class="btn btn-sm ldr-btn-icon" onclick="event.stopPropagation(); runSubscriptionNow('${escapeHtml(subscription.id)}')" title="Run now">+ <button class="btn btn-sm ldr-btn-icon" data-subscription-action="run" title="Run now"><i class="bi bi-arrow-clockwise"></i></button>- <button class="btn btn-sm ldr-btn-icon" onclick="event.stopPropagation(); toggleSubscription('${escapeHtml(subscription.id)}')" title="${statusClass === 'active' ? 'Pause' : 'Resume'}">+ <button class="btn btn-sm ldr-btn-icon" data-subscription-action="toggle" title="${statusClass === 'active' ? 'Pause' : 'Resume'}"><i class="bi ${statusIcon}"></i></button>- <button class="btn btn-sm ldr-btn-icon" onclick="event.stopPropagation(); viewSubscriptionHistory('${escapeHtml(subscription.id)}')" title="View history">+ <button class="btn btn-sm ldr-btn-icon" data-subscription-action="history" title="View history"><i class="bi bi-clock-history"></i></button><a href="/news/subscriptions/${encodeURIComponent(subscription.id)}/edit" class="btn btn-sm ldr-btn-icon" onclick="event.stopPropagation();" title="Edit"><i class="bi bi-pencil"></i></a>- <button class="btn btn-sm ldr-btn-icon btn-danger" onclick="event.stopPropagation(); deleteSubscriptionDirect('${escapeHtml(subscription.id)}')" title="Delete">+ <button class="btn btn-sm ldr-btn-icon btn-danger" data-subscription-action="delete" title="Delete"><i class="bi bi-trash"></i></button></div>@@ -793,9 +831,11 @@ function showSchedulerInfo() {`, 'info');}-// Inline card actions are resolved through window in the browser. Assign-// them explicitly so that contract remains intact if this file is later-// loaded as a module (and so tests can drive the real page runtime).+// The card actions are dispatched by handleSubscriptionCardAction. The+// scheduler notice's constant inline "Learn more" handler still resolves+// showSchedulerInfo through window. Assign them all explicitly so that+// contract remains intact if this file is later loaded as a module (and so+// tests can drive the real page runtime).window.runSubscriptionNow = runSubscriptionNow;window.toggleSubscription = toggleSubscription;window.viewSubscriptionHistory = viewSubscriptionHistory;diff --git a/src/local_deep_research/web/templates/pages/collection_upload.html b/src/local_deep_research/web/templates/pages/collection_upload.htmlindex 9aa139725d..e5c60bb777 100644--- a/src/local_deep_research/web/templates/pages/collection_upload.html+++ b/src/local_deep_research/web/templates/pages/collection_upload.html@@ -200,7 +200,7 @@<div id="upload-results" class="ldr-upload-results" style="display: none;"></div><div class="ldr-form-actions">- <button type="button" class="ldr-btn-collections ldr-btn-collections-secondary" onclick="window.location.href='/library/collections/{{ collection_id }}'">+ <button type="button" class="ldr-btn-collections ldr-btn-collections-secondary" data-upload-action="cancel" data-collection-id="{{ collection_id }}"><i aria-hidden="true" class="fas fa-times"></i> Cancel</button><button type="submit" class="ldr-btn-collections ldr-btn-collections-primary" style="font-size: 1.2rem; padding: 1rem 2rem; min-width: 200px;">diff --git a/src/local_deep_research/web/templates/pages/download_manager.html b/src/local_deep_research/web/templates/pages/download_manager.htmlindex 783fc127a6..d7d5225841 100644--- a/src/local_deep_research/web/templates/pages/download_manager.html+++ b/src/local_deep_research/web/templates/pages/download_manager.html@@ -301,11 +301,11 @@<!-- Action Buttons --><div class="ldr-research-actions">- <button class="btn btn-sm" onclick="viewResearch('{{ research.id }}')">+ <button class="btn btn-sm" data-research-action="view"><i aria-hidden="true" class="fas fa-eye"></i> View Research</button><button class="btn btn-sm btn-success"- onclick="downloadResearch('{{ research.id }}', 'pdf')"+ data-research-action="download-pdf"{% if not enable_pdf_storage %}disabledtitle="PDF downloads are disabled. Enable PDF storage in Settings"@@ -315,12 +315,12 @@<i aria-hidden="true" class="fas fa-file-pdf"></i> PDFs</button><button class="btn btn-sm btn-info"- onclick="downloadResearch('{{ research.id }}', 'text_only')"+ data-research-action="download-text"title="Extract text from this research without saving PDF files"><i aria-hidden="true" class="fas fa-file-alt"></i> Text Only</button>{% if research.downloaded_count > 0 %}- <button class="btn btn-sm" onclick="viewDownloaded('{{ research.id }}')">+ <button class="btn btn-sm" data-research-action="view-downloaded"><i aria-hidden="true" class="fas fa-folder-open"></i> View Downloaded</button>{% endif %}@@ -727,6 +727,45 @@ function viewDownloaded(researchId) {window.location.href = `/library?research=${researchId}`;}+// Research row actions. Each row carries its research ID as inert data+// (data-id), and each button names its action in data-research-action. This+// one delegated listener joins the two, so an ID is never compiled as+// JavaScript, as it would be inside an inline on* handler.+function handleResearchItemAction(event) {+ const container = event.currentTarget;+ const actionButton = event.target.closest('button[data-research-action]');+ if (!actionButton || !container.contains(actionButton)) return;+ // The PDF button is disabled when PDF storage is off. Keep it inert even+ // when the browser delivers the click to the icon inside it.+ if (actionButton.disabled) return;+ const researchId = actionButton.closest('.ldr-research-item')?.dataset.id;+ if (!researchId) return;++ switch (actionButton.dataset.researchAction) {+ case 'view':+ viewResearch(researchId);+ break;+ case 'download-pdf':+ downloadResearch(researchId, 'pdf');+ break;+ case 'download-text':+ downloadResearch(researchId, 'text_only');+ break;+ case 'view-downloaded':+ viewDownloaded(researchId);+ break;+ default:+ break;+ }+}++function bindResearchItemActions() {+ const list = document.querySelector('.ldr-research-list');+ if (list) list.addEventListener('click', handleResearchItemAction);+}++bindResearchItemActions();+// Filtersdocument.getElementById('filter-mode').addEventListener('change', filterResearch);document.getElementById('filter-rating').addEventListener('change', filterResearch);diff --git a/src/local_deep_research/web/templates/pages/library.html b/src/local_deep_research/web/templates/pages/library.htmlindex 26798b4805..6c524eed60 100644--- a/src/local_deep_research/web/templates/pages/library.html+++ b/src/local_deep_research/web/templates/pages/library.html@@ -221,7 +221,7 @@</div><!-- Card Body -->- <div class="card-body" onclick="window.location.href='/library/document/{{ doc.id }}'">+ <div class="card-body" data-doc-action="open"><!-- Large action buttons --><div class="ldr-action-buttons" onclick="event.stopPropagation()">{% if doc.has_pdf %}@@ -288,14 +288,14 @@{% endif %}<span class="ldr-tag">{{ doc.domain|truncate(20) }}</span></div>- <div class="ldr-doc-actions" onclick="event.stopPropagation()">+ <div class="ldr-doc-actions">{% if doc.has_pdf %}- <button class="ldr-btn-delete-blob" onclick="DeleteManager.deleteDocumentBlob('{{ doc.id }}', {onSuccess: () => location.reload()})"+ <button class="ldr-btn-delete-blob" data-doc-action="delete-blob"title="Remove PDF only (keep text). Text content will be preserved for searching."><i class="fas fa-file-pdf"></i><i class="fas fa-times" style="font-size: 0.6em; margin-left: -2px;"></i></button>{% endif %}- <button class="ldr-btn-delete-doc" onclick="DeleteManager.deleteDocument('{{ doc.id }}', {onSuccess: () => location.reload()})"+ <button class="ldr-btn-delete-doc" data-doc-action="delete"title="Permanently delete this document, including PDF and text content. This cannot be undone."><i class="fas fa-trash"></i></button>@@ -1260,6 +1260,44 @@ document.querySelectorAll('.ldr-view-toggle button').forEach(btn => {}});});++// Document card actions. Each card carries its document ID as inert data+// (data-doc-id), and the card body and delete buttons name their action in+// data-doc-action. This one delegated listener joins the two, so an ID is+// never compiled as JavaScript. An inline on* handler would compile it: the+// browser entity-decodes attribute text first, which undoes Jinja's escaping+// of a quote.+function handleDocumentCardAction(event) {+ const container = event.currentTarget;+ const actionElement = event.target.closest('[data-doc-action]');+ if (!actionElement || !container.contains(actionElement)) return;+ const docId = actionElement.closest('.ldr-document-card')?.dataset.docId;+ if (!docId) return;++ const reloadLibrary = () => location.reload();+ switch (actionElement.dataset.docAction) {+ case 'open':+ window.location.href = `/library/document/${encodeURIComponent(docId)}`;+ break;+ case 'delete-blob':+ event.stopPropagation();+ DeleteManager.deleteDocumentBlob(docId, { onSuccess: reloadLibrary });+ break;+ case 'delete':+ event.stopPropagation();+ DeleteManager.deleteDocument(docId, { onSuccess: reloadLibrary });+ break;+ default:+ break;+ }+}++function bindDocumentCardActions() {+ const container = document.getElementById('documents-container');+ if (container) container.addEventListener('click', handleDocumentCardAction);+}++bindDocumentCardActions();</script><!-- Delete Confirmation Modal -->diff --git a/tests/js/collection-details-direct-runtime.test.js b/tests/js/collection-details-direct-runtime.test.jsindex cb9c8cf559..7527d5c8c5 100644--- a/tests/js/collection-details-direct-runtime.test.js+++ b/tests/js/collection-details-direct-runtime.test.js@@ -1035,3 +1035,40 @@ it('delegates both document deletion choices and refreshes after success', async)).toHaveLength(3);});});++it('keeps document IDs out of inline handlers and delegates both action clicks', async () => {+ const hostileId = "doc');window.__collectionActionXss=true;//";+ const payload = collectionPayload();+ payload.documents[0].id = hostileId;+ const safeFetch = vi.fn(async url => {+ if (url === COLLECTION_DOCUMENTS_URL) return response(payload);+ if (url === INDEX_STATUS_URL) return response({ status: 'idle' });+ throw new Error(`Unexpected URL: ${url}`);+ });+ window.DeleteManager = {+ removeFromCollection: vi.fn(),+ deleteDocument: vi.fn(),+ };++ await loadCollectionPage(safeFetch);+ await vi.waitFor(() => {+ expect(document.querySelector('.ldr-document-item')).not.toBeNull();+ });++ const row = document.querySelector('.ldr-document-item');+ expect(row.dataset.documentId).toBe(hostileId);+ const removeButton = row.querySelector('.ldr-btn-remove-from-collection');+ const deleteButton = row.querySelector('.ldr-btn-delete-doc');+ expect(removeButton.hasAttribute('onclick')).toBe(false);+ expect(deleteButton.hasAttribute('onclick')).toBe(false);++ removeButton.querySelector('i').click();+ expect(window.DeleteManager.removeFromCollection).toHaveBeenCalledWith(+ hostileId, COLLECTION_ID, expect.objectContaining({ onSuccess: expect.any(Function) }),+ );+ deleteButton.querySelector('i').click();+ expect(window.DeleteManager.deleteDocument).toHaveBeenCalledWith(+ hostileId, expect.objectContaining({ onSuccess: expect.any(Function) }),+ );+ expect(window.__collectionActionXss).toBeUndefined();+});diff --git a/tests/js/collection-upload-direct-runtime.test.js b/tests/js/collection-upload-direct-runtime.test.jsindex 23828f2b8b..c3c98987c5 100644--- a/tests/js/collection-upload-direct-runtime.test.js+++ b/tests/js/collection-upload-direct-runtime.test.js@@ -371,3 +371,35 @@ it('renders a non-OK upload response as inert error text and recovers', async ()expect(document.querySelector('button[type="submit"]').disabled).toBe(false);});++it('returns to the collection from Cancel through a listener, not an inline handler', async () => {+ renderCheckedInUploadPage();+ const cancelButton = [...document.querySelectorAll('.ldr-form-actions button')]+ .find(button => button.textContent.trim() === 'Cancel');+ expect(cancelButton).toBeDefined();+ expect(cancelButton.hasAttribute('onclick')).toBe(false);+ // The template renders the route's collection ID into this attribute. The+ // test value goes in through the DOM API, never through markup.+ cancelButton.setAttribute('data-collection-id', "collection\"&<');//?#");++ const ownLocation = Object.getOwnPropertyDescriptor(window, 'location');+ Object.defineProperty(window, 'location', {+ configurable: true,+ writable: true,+ value: { href: '/library/collections/collection-direct-3299/upload' },+ });+ try {+ await loadUploadPage();+ cancelButton.querySelector('i').click();++ expect(window.location.href).toBe(+ "/library/collections/collection%22%26%3C')%3B%2F%2F%3F%23",+ );+ } finally {+ if (ownLocation) {+ Object.defineProperty(window, 'location', ownLocation);+ } else {+ delete window.location;+ }+ }+});diff --git a/tests/js/pages/download-manager-inline-runtime.test.js b/tests/js/pages/download-manager-inline-runtime.test.jsindex dc2f253985..3cef9dd9e3 100644--- a/tests/js/pages/download-manager-inline-runtime.test.js+++ b/tests/js/pages/download-manager-inline-runtime.test.js@@ -1,14 +1,17 @@/**- * Runtime contracts for the download manager's inline bulk-download client.+ * Runtime contracts for the download manager's inline bulk-download client+ * and its per-research row actions.** The functions are executed from the checked-in Jinja template so route,- * payload, CSRF, streaming, status aggregation, and abort behavior cannot- * silently drift during the FastAPI migration.+ * payload, CSRF, streaming, status aggregation, abort behavior and row action+ * dispatch cannot silently drift during the FastAPI migration.*/import { readFileSync } from 'node:fs';import { resolve } from 'node:path';+import { compileTemplateHarness } from '../helpers/template-harness.js';+const TEMPLATE_PATH = resolve(__dirname,'../../../src/local_deep_research/web/templates/pages/download_manager.html',@@ -482,3 +485,70 @@ it('turns an aborted stream into a visible cancellation entry', async () => {expect(entry).not.toBeNull();expect(entry.textContent).toContain('Download cancelled by user');});++const HOSTILE_RESEARCH_ID = "research\"&<');window.__researchActionXss=true;//";++function renderResearchRows() {+ document.body.innerHTML = `+ <div class="ldr-research-list">+ <div class="ldr-research-item">+ <div class="ldr-research-header"><h3>Delegated research</h3></div>+ <div class="ldr-research-actions">+ <button class="btn btn-sm" data-research-action="view"><i></i> View Research</button>+ <button class="btn btn-sm btn-success" data-research-action="download-pdf"><i></i> PDFs</button>+ <button class="btn btn-sm btn-info" data-research-action="download-text"><i></i> Text Only</button>+ <button class="btn btn-sm" data-research-action="view-downloaded"><i></i> View Downloaded</button>+ </div>+ </div>+ <div class="ldr-research-item" data-id="pdf-storage-off">+ <div class="ldr-research-actions">+ <button class="btn btn-sm btn-success" data-research-action="download-pdf" disabled><i></i> PDFs</button>+ </div>+ </div>+ </div>+ `;+ // The ID goes in through the DOM API, never through markup interpolation.+ document.querySelector('.ldr-research-item')+ .setAttribute('data-id', HOSTILE_RESEARCH_ID);+}++it('keeps research IDs out of the row markup inline handlers', () => {+ const template = readFileSync(TEMPLATE_PATH, 'utf8');++ expect(template).not.toMatch(/\bon[a-z]+="[^"]*\{\{\s*research\.id\b/);+});++it('delegates every row action through the research list', () => {+ renderResearchRows();+ const actions = {+ viewResearch: vi.fn(),+ downloadResearch: vi.fn(),+ viewDownloaded: vi.fn(),+ };+ const bindResearchItemActions = compileTemplateHarness({+ templatePath: TEMPLATE_PATH,+ functionNames: ['handleResearchItemAction', 'bindResearchItemActions'],+ dependencies: actions,+ returnExpression: 'bindResearchItemActions',+ });+ bindResearchItemActions();++ const row = document.querySelector('.ldr-research-item');+ expect(row.dataset.id).toBe(HOSTILE_RESEARCH_ID);+ for (const action of ['view', 'download-pdf', 'download-text', 'view-downloaded']) {+ row.querySelector(`[data-research-action="${action}"] i`).click();+ }+ row.querySelector('h3').click();++ expect(actions.viewResearch.mock.calls).toEqual([[HOSTILE_RESEARCH_ID]]);+ expect(actions.downloadResearch.mock.calls).toEqual([+ [HOSTILE_RESEARCH_ID, 'pdf'],+ [HOSTILE_RESEARCH_ID, 'text_only'],+ ]);+ expect(actions.viewDownloaded.mock.calls).toEqual([[HOSTILE_RESEARCH_ID]]);++ // With PDF storage off the template disables the PDF button. A click that+ // lands on its icon must not start a download.+ document.querySelector('[data-id="pdf-storage-off"] i').click();+ expect(actions.downloadResearch).toHaveBeenCalledTimes(2);+});diff --git a/tests/js/pages/library-inline-runtime.test.js b/tests/js/pages/library-inline-runtime.test.jsindex 84132035f8..585f001963 100644--- a/tests/js/pages/library-inline-runtime.test.js+++ b/tests/js/pages/library-inline-runtime.test.js@@ -1,5 +1,6 @@/**- * Runtime contracts for the library page's inline content viewer and sync.+ * Runtime contracts for the library page's inline content viewer, sync and+ * document card actions.** These execute the checked-in template functions, covering browser-visible* FastAPI request paths and modal/error state rather than duplicating them in@@ -9,6 +10,8 @@import { readFileSync } from 'node:fs';import { resolve } from 'node:path';+import { compileTemplateHarness } from '../helpers/template-harness.js';+const TEMPLATE_PATH = resolve(__dirname,'../../../src/local_deep_research/web/templates/pages/library.html',@@ -848,3 +851,97 @@ it('suppresses a delayed completion after a newer extraction becomes current', a'Text extraction complete! Extracted 7 documents to encrypted database.',);});++const HOSTILE_DOCUMENT_ID = "doc\"&<');window.__libraryCardActionXss=true;//";++function renderDocumentCards() {+ // The wrapping action outside the container checks the listener ignores+ // matches that lie beyond the documents container.+ document.body.innerHTML = `+ <section data-doc-action="delete">+ <div id="documents-container">+ <div class="ldr-document-card">+ <div class="card-body" data-doc-action="open">+ <h3 class="ldr-doc-title">Delegated card</h3>+ </div>+ <div class="card-footer">+ <div class="ldr-doc-tags"><span class="ldr-tag">example.org</span></div>+ <div class="ldr-doc-actions">+ <button class="ldr-btn-delete-blob" data-doc-action="delete-blob"><i class="fas fa-file-pdf"></i></button>+ <button class="ldr-btn-delete-doc" data-doc-action="delete"><i class="fas fa-trash"></i></button>+ </div>+ </div>+ </div>+ <div class="ldr-semantic-result"><h4>Content-only match</h4></div>+ </div>+ </section>+ `;+ // The ID goes in through the DOM API, never through markup interpolation.+ document.querySelector('.ldr-document-card')+ .setAttribute('data-doc-id', HOSTILE_DOCUMENT_ID);+}++it('keeps document IDs out of the card markup inline handlers', () => {+ const template = readFileSync(TEMPLATE_PATH, 'utf8');++ expect(template).not.toMatch(/\bon[a-z]+="[^"]*\{\{\s*doc\.id\b/);+});++it('delegates opening and both deletions through the documents container', () => {+ renderDocumentCards();+ const deleteManager = {+ deleteDocument: vi.fn(),+ deleteDocumentBlob: vi.fn(),+ };+ const fakeLocation = { reload: vi.fn() };+ const fakeWindow = { location: { href: '/library/' } };+ const bindDocumentCardActions = compileTemplateHarness({+ templatePath: TEMPLATE_PATH,+ functionNames: ['handleDocumentCardAction', 'bindDocumentCardActions'],+ dependencies: {+ DeleteManager: deleteManager,+ location: fakeLocation,+ window: fakeWindow,+ },+ returnExpression: 'bindDocumentCardActions',+ });+ const reachedDocument = vi.fn();+ document.addEventListener('click', reachedDocument);+ try {+ bindDocumentCardActions();+ const card = document.querySelector('.ldr-document-card');+ expect(card.dataset.docId).toBe(HOSTILE_DOCUMENT_ID);++ card.querySelector('.ldr-btn-delete-doc i').click();+ expect(deleteManager.deleteDocument).toHaveBeenCalledOnce();+ expect(deleteManager.deleteDocument).toHaveBeenCalledWith(+ HOSTILE_DOCUMENT_ID, { onSuccess: expect.any(Function) },+ );+ deleteManager.deleteDocument.mock.calls[0][1].onSuccess();+ expect(fakeLocation.reload).toHaveBeenCalledOnce();++ card.querySelector('.ldr-btn-delete-blob i').click();+ expect(deleteManager.deleteDocumentBlob).toHaveBeenCalledOnce();+ expect(deleteManager.deleteDocumentBlob).toHaveBeenCalledWith(+ HOSTILE_DOCUMENT_ID, { onSuccess: expect.any(Function) },+ );+ // Deletions stay inside the card and never open the document.+ expect(reachedDocument).not.toHaveBeenCalled();+ expect(fakeWindow.location.href).toBe('/library/');++ card.querySelector('.ldr-doc-title').click();+ expect(fakeWindow.location.href).toBe(+ "/library/document/doc%22%26%3C')%3Bwindow.__libraryCardActionXss%3Dtrue%3B%2F%2F",+ );+ expect(reachedDocument).toHaveBeenCalledOnce();++ fakeWindow.location.href = '/library/';+ document.querySelector('.ldr-doc-tags').click();+ document.querySelector('.ldr-semantic-result h4').click();+ expect(fakeWindow.location.href).toBe('/library/');+ expect(deleteManager.deleteDocument).toHaveBeenCalledOnce();+ expect(deleteManager.deleteDocumentBlob).toHaveBeenCalledOnce();+ } finally {+ document.removeEventListener('click', reachedDocument);+ }+});diff --git a/tests/js/pages/subscriptions-card-actions-runtime.test.js b/tests/js/pages/subscriptions-card-actions-runtime.test.jsnew file mode 100644index 0000000000..bf1cb5945e--- /dev/null+++ b/tests/js/pages/subscriptions-card-actions-runtime.test.js@@ -0,0 +1,175 @@+/**+ * Subscription card actions dispatch through one delegated grid listener.+ *+ * Each card carries its subscription ID as inert data (data-subscription-id),+ * and the card and its buttons name their action in data-subscription-action.+ * The buttons used to embed the ID in inline onclick JavaScript, where the+ * browser decodes escapeHtml's ' back into a quote before compiling it.+ * These tests boot the real page script with an ID built to break out of such+ * a string, then follow it from each click to the request it produces.+ */++const HOSTILE_ID = "sub\"&<');window.__subscriptionCardActionXss=true;//";+const ACTION_URL = `/news/api/subscriptions/${HOSTILE_ID}`;++function jsonResponse(payload, status = 200) {+ return {+ ok: status >= 200 && status < 300,+ status,+ statusText: status === 200 ? 'OK' : 'Request failed',+ json: vi.fn().mockResolvedValue(payload),+ };+}++function installDom() {+ document.body.innerHTML = `+ <header class="ldr-page-header"><h1>Subscriptions</h1></header>+ <span id="total-subscriptions">0</span>+ <span id="active-subscriptions">0</span>+ <span id="paused-subscriptions">0</span>+ <span id="updates-today">0</span>+ <span id="status-indicator"></span>+ <span id="status-text"></span>+ <span id="scheduler-details"></span>+ <div class="ldr-folder-list">+ <div class="ldr-folder-item active" data-folder="all">+ All <span class="ldr-folder-count">0</span>+ </div>+ </div>+ <button id="add-folder-btn"></button>+ <button id="create-subscription-btn"></button>+ <input id="subscription-search">+ <select id="status-filter"><option value="all">All</option></select>+ <select id="frequency-filter"><option value="all">All</option></select>+ <main id="subscriptions-grid"></main>+ `;+}++let fetchMock;+let registeredDocumentListeners;++beforeEach(async () => {+ vi.resetModules();+ vi.useFakeTimers();+ registeredDocumentListeners = [];+ installDom();+ await import('@js/security/xss-protection.js');+ await import('@js/utils/alert-helpers.js');+ window.api = { getCsrfToken: vi.fn(() => 'csrf-card-actions') };+ window.RESEARCH_STATUS = { QUEUED: 'queued' };++ fetchMock = vi.fn(async input => {+ const url = String(input);+ if (url === '/news/api/subscriptions/current') {+ return jsonResponse({+ subscriptions: [{+ id: HOSTILE_ID,+ name: 'Hostile ID watch',+ query: 'hostile id query',+ is_active: true,+ folder_id: null,+ refresh_minutes: 60,+ created_at: '2026-10-01T10:00:00.000Z',+ total_runs: 0,+ }],+ });+ }+ if (url === '/news/api/subscription/folders') {+ return jsonResponse({ folders: [] });+ }+ if (url === '/news/api/scheduler/status') {+ return jsonResponse({ scheduler_available: false });+ }+ // Every card action gets a failure. These tests only follow the ID+ // from the click to the request it produces.+ return jsonResponse({}, 503);+ });+ vi.stubGlobal('fetch', fetchMock);+ vi.stubGlobal('confirm', vi.fn(() => true));++ const originalDocumentAdd = document.addEventListener.bind(document);+ const documentAddSpy = vi.spyOn(document, 'addEventListener')+ .mockImplementation((type, listener, options) => {+ registeredDocumentListeners.push([type, listener, options]);+ originalDocumentAdd(type, listener, options);+ });+ try {+ await import('@js/pages/subscriptions.js');+ document.dispatchEvent(new Event('DOMContentLoaded'));+ await vi.waitFor(() => {+ expect(document.querySelectorAll('.ldr-subscription-card'))+ .toHaveLength(1);+ });+ } finally {+ documentAddSpy.mockRestore();+ }+});++afterEach(() => {+ registeredDocumentListeners.forEach(([type, listener, options]) => {+ document.removeEventListener(type, listener, options);+ });+ vi.clearAllTimers();+ vi.useRealTimers();+ vi.restoreAllMocks();+ vi.unstubAllGlobals();+ localStorage.clear();+ document.body.replaceChildren();+ delete window.api;+ delete window.RESEARCH_STATUS;+ delete window.runSubscriptionNow;+ delete window.toggleSubscription;+ delete window.viewSubscriptionHistory;+ delete window.deleteSubscriptionDirect;+ delete window.showSchedulerInfo;+ delete window.formatNextUpdate;+});++function subscriptionCard() {+ return document.querySelector('.ldr-subscription-card');+}++function cardButtonIcon(action) {+ return subscriptionCard()+ .querySelector(`button[data-subscription-action="${action}"] i`);+}++it('keeps the subscription ID out of every inline handler on the card', () => {+ const card = subscriptionCard();+ expect(card.dataset.subscriptionId).toBe(HOSTILE_ID);++ const inlineHandlers = [card, ...card.querySelectorAll('*')]+ .flatMap(element => [...element.attributes]+ .filter(attribute => attribute.name.startsWith('on'))+ .map(attribute => [element.tagName, attribute.name, attribute.value]));+ // Only the Edit link keeps a constant handler, and it carries no ID.+ expect(inlineHandlers).toEqual([['A', 'onclick', 'event.stopPropagation();']]);+});++it('dispatches each card action with the exact subscription ID', async () => {+ cardButtonIcon('run').click();+ cardButtonIcon('toggle').click();+ cardButtonIcon('history').click();+ subscriptionCard().querySelector('.ldr-query-text').click();+ cardButtonIcon('delete').click();++ const actionRequests = () => fetchMock.mock.calls+ .map(([url, options = {}]) => [String(url), options.method || 'GET'])+ .filter(([url]) => (+ url === '/api/start_research' || url.startsWith(ACTION_URL)+ ));+ await vi.waitFor(() => {+ expect(actionRequests()).toEqual([+ ['/api/start_research', 'POST'],+ [ACTION_URL, 'PUT'],+ [`${ACTION_URL}/history`, 'GET'],+ [`${ACTION_URL}/history`, 'GET'],+ [ACTION_URL, 'DELETE'],+ ]);+ });+ const [, runOptions] = fetchMock.mock.calls+ .find(([url]) => url === '/api/start_research');+ expect(JSON.parse(runOptions.body).metadata.subscription_id)+ .toBe(HOSTILE_ID);+ expect(confirm).toHaveBeenCalledOnce();+});diff --git a/tests/security/test_collection_id_xss.py b/tests/security/test_collection_id_xss.pyindex 80c281dc6b..9cf8c87272 100644--- a/tests/security/test_collection_id_xss.py+++ b/tests/security/test_collection_id_xss.py@@ -1,6 +1,7 @@"""A collection id must be a real UUID before it reaches a template.-`collection_upload.html` interpolates `collection_id` into an inline handler:+`collection_upload.html` used to interpolate `collection_id` into an inline+handler:onclick="window.location.href='/library/collections/{{ collection_id }}'"@@ -15,14 +16,16 @@ exploit:rendered `...href='/library/collections/1';alert(document.cookie);varx=''`, which the browser decodes into executable JS. CSP does not stop it:`script-src` includes `'unsafe-inline'`. The route is behind `require_auth`, so-it needs an authenticated victim to follow a crafted link and click Cancel --+it needed an authenticated victim to follow a crafted link and click Cancel --which is one of only two buttons on the page.-The fix validates the SHAPE at the route boundary rather than patching the one-template. Collection ids are server-generated UUID4 strings, so anything else-cannot match a real row anyway; validating there means no template can receive-a value capable of breaking out of any context, including-`collection_details.html` and any page added later.+The first fix validated the SHAPE at the route boundary rather than patching+the one template. Collection ids are server-generated UUID4 strings, so+anything else cannot match a real row anyway; validating there means no+template can receive a value capable of breaking out of any context, including+`collection_details.html` and any page added later. The Cancel button has+since dropped the inline handler and carries the ID as a data attribute read+by collection_upload.js; these tests pin the boundary layer, which stays."""import uuiddiff --git a/tests/security/test_inline_handler_ids.py b/tests/security/test_inline_handler_ids.pynew file mode 100644index 0000000000..00961bb57e--- /dev/null+++ b/tests/security/test_inline_handler_ids.py@@ -0,0 +1,294 @@+"""Server IDs rendered into page markup must never reach an inline handler.++Jinja autoescape turns ``'`` into ``'``. That is enough for an ordinary+attribute value, but not inside an ``on*`` event handler: the browser+entity-decodes attribute text BEFORE it compiles the handler, so the escaping+is undone and a quote in the ID closes the handler's string literal. CSP does+not stop it either, because ``script-src`` includes ``'unsafe-inline'``.++Each test renders a real template through its route handler with an ID built+to break out of a quoted JavaScript string (and to test the attribute+escaping with ``"``, ``&`` and ``<``). It then reads the attributes the way+the browser does (BeautifulSoup decodes entities like the HTML parser) and+checks two things:++* no ``on*`` attribute anywhere on the page contains the ID, and+* the ID survives intact as data on the element the page script reads,+ beside the ``data-*-action`` names that script dispatches on.++The click path through those listeners is exercised by vitest:+tests/js/pages/library-inline-runtime.test.js,+tests/js/pages/download-manager-inline-runtime.test.js and+tests/js/collection-upload-direct-runtime.test.js.+"""++import uuid+from contextlib import contextmanager+from unittest.mock import Mock, patch++from bs4 import BeautifulSoup+from starlette.requests import Request++from local_deep_research.web.routers import library as library_module+from local_deep_research.web.routers.library import (+ download_manager_page,+ library_page,+)+from local_deep_research.web.routers.rag import collection_upload_page++#: Distinctive text that only appears in the ID, so a match in any handler+#: means the ID reached it.+MARKER = "__inlineHandlerIdXss"+#: Closes a single-quoted JS string, runs the marker, comments out the rest.+#: The leading ``"&<`` exercise the attribute escaping of the data attribute.+HOSTILE_ID = f"id\"&<');window.{MARKER}=true;//"+++def _request(app, path):+ request = Request(+ {+ "type": "http",+ "method": "GET",+ "path": path,+ "headers": [],+ "query_string": b"",+ "session": {},+ }+ )+ request.scope.update(+ {+ "app": app,+ "router": app.router,+ "scheme": "http",+ "server": ("testserver", 80),+ "root_path": "",+ }+ )+ return request+++@contextmanager+def _fake_db_session(*args, **kwargs):+ yield Mock()+++def _settings_manager(values):+ manager = Mock()+ manager.get_setting.side_effect = lambda key, default=None: values.get(+ key, default+ )+ return manager+++def _soup(response):+ assert response.status_code == 200+ return BeautifulSoup(response.body.decode("utf-8"), "html.parser")+++def _handlers_containing(soup, needle):+ """Every ``on*`` attribute on the page whose decoded value has needle."""+ return [+ (tag.name, name, value)+ for tag in soup.find_all(True)+ for name, value in tag.attrs.items()+ if name.lower().startswith("on") and needle in str(value)+ ]+++def _inline_handlers(tag):+ return [name for name in tag.attrs if name.lower().startswith("on")]+++def _library_service(document):+ service = Mock()+ service.get_library_stats.return_value = {+ "total_pdfs": 1,+ "total_size_mb": 0.0,+ "storage_path": "/tmp/library",+ }+ service.count_documents.return_value = 1+ service.get_documents.return_value = [document]+ service.get_unique_domains.return_value = []+ service.get_research_list_for_dropdown.return_value = []+ service.get_all_collections.return_value = []+ return service+++def _library_document(document_id):+ return {+ "id": document_id,+ "research_id": "research-1",+ "document_title": "Inline handler fixture",+ "authors": ["A. Author"],+ "doi": None,+ "file_name": "fixture.pdf",+ "file_size": 2048,+ "file_type": "pdf",+ "domain": "example.org",+ "domain_category": None,+ "downloaded_at": "2026-10-01T12:00:00",+ "research_title": "Fixture research",+ "is_arxiv": False,+ "is_pubmed": False,+ "has_pdf": True,+ "has_text_db": True,+ "has_rag_indexed": False,+ "rag_chunk_count": 0,+ }+++def _render_library(app, document):+ with (+ patch.object(+ library_module,+ "get_user_db_session",+ side_effect=_fake_db_session,+ ),+ patch.object(+ library_module,+ "get_settings_manager",+ return_value=_settings_manager(+ {+ "research_library.pdf_storage_mode": "database",+ "research_library.shared_library": False,+ }+ ),+ ),+ patch.object(+ library_module,+ "LibraryService",+ return_value=_library_service(document),+ ),+ patch(+ "local_deep_research.database.library_init.get_default_library_id",+ return_value="col-default",+ ),+ ):+ return library_page(_request(app, "/library/"), username="alice")+++def test_library_cards_keep_document_ids_out_of_inline_handlers(app):+ soup = _soup(_render_library(app, _library_document(HOSTILE_ID)))++ assert _handlers_containing(soup, MARKER) == []++ card = soup.select_one(".ldr-document-card")+ assert card is not None, "the fixture document did not render a card"+ assert card["data-doc-id"] == HOSTILE_ID++ body = card.select_one(".card-body")+ delete_blob = card.select_one(".ldr-btn-delete-blob")+ delete_doc = card.select_one(".ldr-btn-delete-doc")+ actions = [+ (body, "open"),+ (delete_blob, "delete-blob"),+ (delete_doc, "delete"),+ ]+ for element, action in actions:+ assert element is not None, f"no element for the {action!r} action"+ assert element.get("data-doc-action") == action+ assert _inline_handlers(element) == [], (action, element.attrs)+++def _research_row(research_id):+ return {+ "id": research_id,+ "title": "Inline handler fixture research",+ "query": "inline handler fixture",+ "mode": "quick",+ "status": "completed",+ "created_at": "2026-10-01T12:00:00",+ "duration_seconds": 12,+ "total_resources": 3,+ "downloaded_count": 1,+ "downloadable_count": 2,+ "rating": None,+ "top_domains": [],+ }+++def _render_download_manager(app, research):+ service = Mock()+ service.get_download_manager_summary_stats.return_value = {+ "total_researches": 1,+ "total_resources": 3,+ "already_downloaded": 1,+ "available_to_download": 1,+ }+ service.get_research_list_with_stats.return_value = [research]+ service.get_pdf_previews_batch.return_value = {}+ with (+ patch.object(+ library_module,+ "get_user_db_session",+ side_effect=_fake_db_session,+ ),+ patch.object(+ library_module,+ "get_settings_manager",+ return_value=_settings_manager(+ {+ "research_library.pdf_storage_mode": "database",+ "research_library.shared_library": False,+ }+ ),+ ),+ patch.object(library_module, "LibraryService", return_value=service),+ ):+ return download_manager_page(+ _request(app, "/library/download-manager"), username="alice"+ )+++def test_download_manager_rows_keep_research_ids_out_of_inline_handlers(app):+ soup = _soup(_render_download_manager(app, _research_row(HOSTILE_ID)))++ assert _handlers_containing(soup, MARKER) == []++ row = soup.select_one(".ldr-research-item")+ assert row is not None, "the fixture research did not render a row"+ assert row["data-id"] == HOSTILE_ID++ buttons = row.select(".ldr-research-actions button")+ assert [button.get("data-research-action") for button in buttons] == [+ "view",+ "download-pdf",+ "download-text",+ "view-downloaded",+ ]+ for button in buttons:+ assert _inline_handlers(button) == [], button.attrs+++def test_collection_upload_cancel_keeps_the_collection_id_out_of_inline_handlers(+ app,+):+ # The route only admits a well-formed UUID (tests/security/+ # test_collection_id_xss.py), so this page is checked with a real one.+ collection_id = str(uuid.uuid4())+ with (+ patch(+ "local_deep_research.database.session_context.get_user_db_session",+ side_effect=_fake_db_session,+ ),+ patch(+ "local_deep_research.utilities.db_utils.get_settings_manager",+ return_value=_settings_manager(+ {"research_library.upload_pdf_storage": "none"}+ ),+ ),+ ):+ response = collection_upload_page(+ _request(app, f"/library/collections/{collection_id}/upload"),+ collection_id=collection_id,+ username="alice",+ )+ soup = _soup(response)++ assert _handlers_containing(soup, collection_id) == []++ cancel = soup.select_one('[data-upload-action="cancel"]')+ assert cancel is not None, "the Cancel button lost its action name"+ assert cancel.get_text(" ", strip=True) == "Cancel"+ assert cancel["data-collection-id"] == collection_id+ assert _inline_handlers(cancel) == []diff --git a/tests/theme_tests/test_accent_ink_contrast.py b/tests/theme_tests/test_accent_ink_contrast.pyindex 45ff1f1e6a..1c9f252038 100644--- a/tests/theme_tests/test_accent_ink_contrast.py+++ b/tests/theme_tests/test_accent_ink_contrast.py@@ -1333,8 +1333,8 @@ NON_TEXT_ACCENT_FILLS = {("star_reviews.css", ".ldr-rating-fill"): _BAR,("styles.css", ".ldr-progress-fill"): _BAR,("styles.css", ".ldr-detail-progress-fill"): _BAR,- ("static/js/collection_upload.js", "style@L576"): _BAR,- ("static/js/collection_upload.js", "style@L646"): _BAR,+ ("static/js/collection_upload.js", "style@L588"): _BAR,+ ("static/js/collection_upload.js", "style@L658"): _BAR,# _stateColor(): success, error, accent or the track colour.("templates/pages/journal_quality.html", "style@L831"): _BAR,("collection_details.css", ".ldr-stat-card::before"): _STRIPE,