~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
web: require response nonces for template scripts and styles (#8230)
LearningCircuit7f035a27c2ee
diff --git a/changelog.d/8230.security.md b/changelog.d/8230.security.mdnew file mode 100644index 0000000000..d17dea95eb--- /dev/null+++ b/changelog.d/8230.security.md@@ -0,0 +1 @@+Page controls and PDF exports support per-page authorization of scripts and styles.diff --git a/eslint.config.js b/eslint.config.jsindex 0ec9e0734e..bc6f31e030 100644--- a/eslint.config.js+++ b/eslint.config.js@@ -22,6 +22,8 @@ const escapeConfig = {"window.escapeHtml","window.sanitizeHtml","window.XSSProtection.escapeHtml",+ // Only validated names, per-response tokens and URI-encoded JSON data.+ "window.LDRTemplateEvents.attributes",],},};diff --git a/src/local_deep_research/web/fastapi_app.py b/src/local_deep_research/web/fastapi_app.pyindex 1bc3aff9da..fc255a3ee7 100644--- a/src/local_deep_research/web/fastapi_app.py+++ b/src/local_deep_research/web/fastapi_app.py@@ -690,12 +690,15 @@ class SecurityHeadersMiddleware:Ports Flask's SecurityHeaders + ServerHeaderMiddleware to ASGI."""- # Pre-compute static header values+ # Style attributes support math rendering and browser-driven layout.+ # Inline script and style elements require a per-response nonce.CSP = ("default-src 'self'; ""connect-src 'self'; "- "script-src 'self' 'unsafe-inline'; "- "style-src 'self' 'unsafe-inline'; "+ "script-src 'self'; "+ "script-src-attr 'none'; "+ "style-src 'self'; "+ "style-src-attr 'unsafe-inline'; ""font-src 'self' data:; ""img-src 'self' data:; ""media-src 'self'; "@@ -715,7 +718,7 @@ class SecurityHeadersMiddleware:)@classmethod- def unconditional_headers(cls) -> list[tuple[bytes, bytes]]:+ def unconditional_headers(cls, scope=None) -> list[tuple[bytes, bytes]]:"""The security headers stamped on every HTTP response.Exposed separately because this middleware cannot cover every@@ -732,8 +735,16 @@ class SecurityHeadersMiddleware:Excludes the two conditional headers (HSTS, which needs a securescheme, and cache-control, which is skipped for static asset routes)."""+ policy = cls.CSP+ if scope is not None:+ from .utils.csp import template_security_context++ nonce = template_security_context(scope).nonce+ policy = policy.replace(+ "script-src 'self'", f"script-src 'self' 'nonce-{nonce}'"+ ).replace("style-src 'self'", f"style-src 'self' 'nonce-{nonce}'")return [- (b"content-security-policy", cls.CSP.encode()),+ (b"content-security-policy", policy.encode()),(b"x-frame-options", b"SAMEORIGIN"),(b"x-content-type-options", b"nosniff"),(b"cross-origin-opener-policy", b"same-origin"),@@ -772,10 +783,10 @@ class SecurityHeadersMiddleware:@classmethoddef response_headers(- cls, *, path: str, scheme: str, status: int+ cls, *, path: str, scheme: str, status: int, scope=None) -> list[tuple[bytes, bytes]]:"""Apply the same header policy inside and outside the middleware."""- headers = cls.unconditional_headers()+ headers = cls.unconditional_headers(scope)if scheme == "https":headers.append((@@ -797,6 +808,11 @@ class SecurityHeadersMiddleware:await self.app(scope, receive, send)return+ from .utils.csp import template_security_context++ # Error rendering and other inner adapters may copy the scope.+ # Share its immutable authorization before those copies are made.+ template_security_context(scope)path = scope.get("path", "")async def send_wrapper(message):@@ -805,6 +821,7 @@ class SecurityHeadersMiddleware:path=path,scheme=scope.get("scheme", "http"),status=message["status"],+ scope=scope,)# Keep the route's streaming directive while replacing its# caching policy. SSE must remain untransformed by proxies,@@ -1649,6 +1666,7 @@ def _register_exception_handlers(app: FastAPI) -> None:path=request.url.path,scheme=request.url.scheme,status=500,+ scope=request.scope,)},)@@ -2425,6 +2443,7 @@ def _setup_rate_limiting(app: FastAPI) -> None:path=request.url.path,scheme=request.url.scheme,status=429,+ scope=request.scope,)},)diff --git a/src/local_deep_research/web/static/js/collection_create.js b/src/local_deep_research/web/static/js/collection_create.jsindex 997720c8ac..276e8f2947 100644--- a/src/local_deep_research/web/static/js/collection_create.js+++ b/src/local_deep_research/web/static/js/collection_create.js@@ -153,7 +153,7 @@ function showCreateResults(data) {html += '<a href="/library/collections" class="ldr-btn-collections ldr-btn-collections-primary">';html += '<i class="fas fa-folder-open"></i> View All Collections';html += '</a>';- html += '<button onclick="window.location.href=\'/library/collections/create\'" class="ldr-btn-collections ldr-btn-collections-secondary" style="margin-left: 1rem;">';+ html += `<button ${window.LDRTemplateEvents.attributes('ldr-4d106764b648')} class="ldr-btn-collections ldr-btn-collections-secondary" style="margin-left: 1rem;">`;html += '<i class="fas fa-plus"></i> Create Another Collection';html += '</button>';html += '</div>';diff --git a/src/local_deep_research/web/static/js/collection_upload.js b/src/local_deep_research/web/static/js/collection_upload.jsindex 4b350da848..406180a43c 100644--- a/src/local_deep_research/web/static/js/collection_upload.js+++ b/src/local_deep_research/web/static/js/collection_upload.js@@ -871,7 +871,7 @@ function showUploadResults(data) {html += `<a href="/library/collections/${encodeURIComponent(COLLECTION_ID)}" class="ldr-btn-collections ldr-btn-collections-primary"><i class="fas fa-folder-open"></i> View Collection</a>`;- html += `<button onclick="location.reload()" class="ldr-btn-collections ldr-btn-collections-secondary">+ html += `<button ${window.LDRTemplateEvents.attributes("ldr-e768766cc8a7", [])} class="ldr-btn-collections ldr-btn-collections-secondary"><i class="fas fa-plus"></i> Upload More Files</button>`;html += '</div>';diff --git a/src/local_deep_research/web/static/js/components/settings.js b/src/local_deep_research/web/static/js/components/settings.jsindex fb4be91f10..f655b2c2d0 100644--- a/src/local_deep_research/web/static/js/components/settings.js+++ b/src/local_deep_research/web/static/js/components/settings.js@@ -2284,6 +2284,7 @@// Add styles for the data location sectionif (!document.getElementById('data-location-styles')) {const style = document.createElement('style');+ style.nonce = window.LDRTemplateEvents?.styleNonce || '';style.id = 'data-location-styles';style.textContent = `.ldr-data-location-section {@@ -2642,6 +2643,7 @@// Add stylesif (!document.getElementById('ldr-backup-status-styles')) {const style = document.createElement('style');+ style.nonce = window.LDRTemplateEvents?.styleNonce || '';style.id = 'ldr-backup-status-styles';style.textContent = `.ldr-backup-status-section {@@ -5044,6 +5046,7 @@let styleEl = document.getElementById('settings-dynamic-styles');if (!styleEl) {styleEl = document.createElement('style');+ styleEl.nonce = window.LDRTemplateEvents?.styleNonce || '';styleEl.id = 'settings-dynamic-styles';document.head.appendChild(styleEl);}diff --git a/src/local_deep_research/web/static/js/followup.js b/src/local_deep_research/web/static/js/followup.jsindex 5b175fe551..5a667ac7de 100644--- a/src/local_deep_research/web/static/js/followup.js+++ b/src/local_deep_research/web/static/js/followup.js@@ -128,9 +128,8 @@ class FollowUpResearch {*/attachModalEventHandlers() {const startBtn = this.getStartButton();- // The checked-in modal currently has an inline compatibility handler;- // don't register a second click callback when that handler is present.- if (startBtn && !startBtn.hasAttribute('onclick')) {+ // The fetched modal uses the page's registered script, not an attribute.+ if (startBtn) {startBtn.addEventListener('click', () => this.submitFollowUp());}@@ -153,8 +152,10 @@ class FollowUpResearch {addModalStyles() {// Add custom CSS if neededif (!document.getElementById('followup-modal-styles')) {- const styles = `- <style id="followup-modal-styles">+ const styles = document.createElement('style');+ styles.id = 'followup-modal-styles';+ styles.nonce = window.LDRTemplateEvents?.styleNonce || '';+ styles.textContent = `.modal-backdrop {position: fixed;top: 0;@@ -259,10 +260,8 @@ class FollowUpResearch {border-color: rgba(var(--accent-tertiary-rgb), 0.3);color: var(--accent-tertiary);}- </style>`;- // eslint-disable-next-line no-unsanitized/method -- audited 2026-03-28: pure hardcoded CSS string literal with no interpolations- document.head.insertAdjacentHTML('beforeend', styles);+ document.head.appendChild(styles);}}@@ -454,9 +453,5 @@ function toggleAdvancedOptions(event) {// Exposed on window so vitest can exercise getResearchIdFromPage// (and other future helpers) without spinning up the full followup modal.window.FollowUpResearch = FollowUpResearch;-// The singleton instance must also be on window because templates use it in-// inline onclick handlers (e.g. results.html: `window.followUpResearch ? ...`).-// A top-level `const` does NOT become a window property in classic scripts,-// so without this assignment those handlers always fall through to the-// "feature loading..." alert branch and the modal never opens.+// Keep the singleton available to page integrations as well as its listeners.window.followUpResearch = followUpResearch;diff --git a/src/local_deep_research/web/static/js/news-enhancements.js b/src/local_deep_research/web/static/js/news-enhancements.jsindex b9f33a24ab..fada593466 100644--- a/src/local_deep_research/web/static/js/news-enhancements.js+++ b/src/local_deep_research/web/static/js/news-enhancements.js@@ -125,6 +125,7 @@ document.addEventListener('DOMContentLoaded', function() {// CSS for ripple effectconst style = document.createElement('style');+style.nonce = window.LDRTemplateEvents?.styleNonce || '';style.textContent = `.ldr-ripple {position: absolute;diff --git a/src/local_deep_research/web/static/js/pages/news.js b/src/local_deep_research/web/static/js/pages/news.jsindex bd94baa127..3086213a47 100644--- a/src/local_deep_research/web/static/js/pages/news.js+++ b/src/local_deep_research/web/static/js/pages/news.js@@ -1154,7 +1154,7 @@ function renderNewsItems(searchQuery = null) {<h3>No news items${filterText}</h3><p>${hasFilters ? 'Try adjusting your filters or' : 'Start by searching for topics or creating subscriptions'}</p>${hasFilters ? `- <button class="btn btn-sm btn-outline-secondary mt-2" onclick="clearAllFilters()">+ <button class="btn btn-sm btn-outline-secondary mt-2" ${window.LDRTemplateEvents.attributes("ldr-579596525a9b", [])}><i class="bi bi-x-circle"></i> Clear all filters</button>` : ''}@@ -1930,7 +1930,7 @@ function updateActiveTopicUI() {<div class="ldr-filter-info"><i class="bi bi-funnel-fill"></i>Filtering by topic: <strong>${escapeHtml(activeTopicFilter)}</strong>- <button class="btn btn-sm btn-link" onclick="clearTopicFilter()">+ <button class="btn btn-sm btn-link" ${window.LDRTemplateEvents.attributes("ldr-e0804aecb652", [])}><i class="bi bi-x-circle"></i> Clear filter</button></div>@@ -1982,13 +1982,13 @@ function updateBulkActionsBar() {</span></div><div class="ldr-bulk-actions">- <button class="btn btn-sm btn-outline-secondary" onclick="markAllAsRead()">+ <button class="btn btn-sm btn-outline-secondary" ${window.LDRTemplateEvents.attributes("ldr-bd0633e0397b", [])}><i class="bi bi-check-all"></i> Mark all as read</button>- <button class="btn btn-sm btn-outline-secondary" onclick="expandAll()">+ <button class="btn btn-sm btn-outline-secondary" ${window.LDRTemplateEvents.attributes("ldr-3b4cb39bbbaa", [])}><i class="bi bi-arrows-expand"></i> Expand all</button>- <button class="btn btn-sm btn-outline-secondary" onclick="collapseAll()">+ <button class="btn btn-sm btn-outline-secondary" ${window.LDRTemplateEvents.attributes("ldr-f41390edb83d", [])}><i class="bi bi-arrows-collapse"></i> Collapse all</button></div>@@ -2038,7 +2038,7 @@ function updateFilterStatusBar() {let filterHtml = '<div class="ldr-active-filters"><span>Active filters:</span>';filterHtml += filterBadges.join('');- filterHtml += `<button class="btn btn-sm btn-link" onclick="clearAllFilters()">+ filterHtml += `<button class="btn btn-sm btn-link" ${window.LDRTemplateEvents.attributes("ldr-579596525a9b", [])}><i class="bi bi-x-circle"></i> Clear all</button></div>`;@@ -2297,7 +2297,7 @@ function showCreateSubscriptionModal() {</div><div class="modal-footer"><button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>- <button type="button" class="btn btn-primary" onclick="createSubscription()">Create Subscription</button>+ <button type="button" class="btn btn-primary" ${window.LDRTemplateEvents.attributes("ldr-bc47cdbe2fcf", [])}>Create Subscription</button></div></div></div>@@ -2711,7 +2711,7 @@ function updateRefreshIndicator() {const seconds = timeSinceRefresh % 60;// Update refresh button text if it exists- const refreshBtn = document.querySelector('button[onclick="refreshFeed()"] i');+ const refreshBtn = document.querySelector('#refresh-feed-btn i');if (refreshBtn) {const timeText = minutes > 0 ? `${minutes}m ago` : `${seconds}s ago`;refreshBtn.setAttribute('title', `Last refresh: ${timeText}`);@@ -4404,7 +4404,7 @@ function showCustomTemplateModal() {</div><div class="modal-footer"><button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>- <button type="button" class="btn btn-primary" onclick="applyCustomTemplate()">Use Template</button>+ <button type="button" class="btn btn-primary" ${window.LDRTemplateEvents.attributes("ldr-e7f65423115b", [])}>Use Template</button></div></div></div>diff --git a/src/local_deep_research/web/static/js/pages/subscriptions.js b/src/local_deep_research/web/static/js/pages/subscriptions.jsindex 4ae6428e8d..4382bacc7c 100644--- a/src/local_deep_research/web/static/js/pages/subscriptions.js+++ b/src/local_deep_research/web/static/js/pages/subscriptions.js@@ -828,7 +828,7 @@ async function checkSchedulerStatus() {} else {statusIndicator.className = 'ldr-status-indicator ldr-inactive';statusText.textContent = 'Not Tracking Your Session';- schedulerDetails.innerHTML = 'Log out and log back in to activate automatic scheduling. <a href="#" onclick="showSchedulerInfo(); return false;">Learn more</a>';+ schedulerDetails.innerHTML = `Log out and log back in to activate automatic scheduling. <a href="#" ${window.LDRTemplateEvents.attributes('ldr-8b7c364b086d')}>Learn more</a>`;}} else {statusIndicator.className = 'ldr-status-indicator ldr-inactive';diff --git a/src/local_deep_research/web/static/js/security/template-events.js b/src/local_deep_research/web/static/js/security/template-events.jsnew file mode 100644index 0000000000..5b8befae37--- /dev/null+++ b/src/local_deep_research/web/static/js/security/template-events.js@@ -0,0 +1,175 @@+/* global HelpService, applyCustomTemplate, cancelAndDeleteBenchmarkRun, cancelDownloads, clearAllFilters, clearSearchHistory, clearTopicFilter, closePDFModal, closeProgressModal, closeStorageModeModal, closeSyncModal, closeTextModal, collapseAll, confirmStorageModeChange, copyTextContent, createSubscription, deleteBenchmarkRun, downloadAllAsText, downloadAllNew, downloadBenchmarkYAML, downloadCurrentPDF, downloadJournalData, downloadTextContent, expandAll, filterDocuments, goToDownloadManager, goToPage, handleNewsSubscriptionSubmit, markAllAsRead, onThresholdChange, onThresholdInput, openPDFInNewTab, performSync, selectAll, selectFiltered, selectNone, showSchedulerInfo, showStorageModeModal, showSyncModal, switchTab, testConfiguration, toggleCostDetails, toggleRunDetails, toggleText, toggleTokenDetails, useNewsTemplate */+/* Page actions are compiled trusted code; attribute values are data only. */+(function () {+ 'use strict';+ if (typeof window.LDRTemplateEvents?.register === 'function') return;+ const script = document.currentScript;+ const suppliedToken = script?.getAttribute('data-template-token') || '';+ const token = /^[\w-]{43}$/.test(suppliedToken) ? suppliedToken : '';+ const suppliedNonce = script?.nonce || '';+ const nonce = /^[\w-]{43}$/.test(suppliedNonce) ? suppliedNonce : '';+ const actions = new Map();+ const bound = new WeakMap();+ const events = ['click', 'change', 'input', 'submit', 'keydown'];+ const selector = events.map(type => `[data-ldr-on${type}]`).join(',');++ function bindElement(element) {+ if (!token || element.getAttribute('data-ldr-template-token') !== token) return;+ for (const type of events) {+ const attribute = `data-ldr-on${type}`;+ const id = element.getAttribute(attribute);+ const action = actions.get(id);+ if (!action || action.type !== type) continue;+ let existing = bound.get(element);+ if (!existing) {+ existing = new Set();+ bound.set(element, existing);+ }+ const key = `${type}:${id}`;+ if (existing.has(key)) continue;+ existing.add(key);+ element.addEventListener(type, function (event) {+ if (element.getAttribute(attribute) !== id ||+ element.getAttribute('data-ldr-template-token') !== token) return;+ let args = [];+ const encoded = element.getAttribute(`${attribute}-args`);+ if (encoded) {+ try {+ args = JSON.parse(decodeURIComponent(encoded));+ } catch (_error) {+ // Malformed data cannot select or execute another action.+ return;+ }+ if (!Array.isArray(args)) return;+ }+ if (action.handle.call(element, event, args) === false) {+ event.preventDefault();+ }+ });+ }+ }++ function bindRoot(root) {+ if (root.nodeType === 1) bindElement(root);+ root.querySelectorAll?.(selector).forEach(bindElement);+ }++ function register(id, type, handle) {+ if (!/^ldr-[0-9a-f]{12}$/.test(id) || !events.includes(type) ||+ typeof handle !== 'function' || actions.has(id)) {+ throw new TypeError('Invalid or duplicate template action');+ }+ actions.set(id, {type, handle});+ if (document.readyState !== 'loading') bindRoot(document);+ }++ function attributes(id, args = []) {+ const action = actions.get(id);+ if (!action || !Array.isArray(args)) {+ throw new TypeError('Invalid template action arguments');+ }+ const encoded = encodeURIComponent(JSON.stringify(args));+ return `data-ldr-on${action.type}="${id}" data-ldr-template-token="${token}" ` ++ `data-ldr-on${action.type}-args="${encoded}"`;+ }++ Object.defineProperty(window, 'LDRTemplateEvents', {+ value: Object.freeze({register, attributes, styleNonce: nonce}),+ writable: false,+ configurable: false,+ });++ register("ldr-07597121e78c", "click", function () { clearSearchHistory(); });+ register("ldr-1196e5e97014", "click", function () { window.filterLogsByType('info'); });+ register("ldr-154c55d5fa77", "click", function () { toggleTokenDetails(); });+ register("ldr-19b1027885b7", "keydown", function (event) { if(event.key==='Enter'||event.key===' '){event.preventDefault();this.click();} });+ register("ldr-1acd607f63be", "click", function () { switchTab('how-it-works'); });+ register("ldr-1e59759d716e", "click", function () { toggleCostDetails(); });+ register("ldr-20a43efc0120", "click", function () { this.parentElement.parentElement.style.display='none'; });+ register("ldr-25bdba94481d", "click", function () { window.filterLogsByType('error'); });+ register("ldr-2879f1d6b0ec", "click", function () { selectFiltered(); });+ register("ldr-28da1ff332dc", "click", function () { window.filterLogsByType('all'); });+ register("ldr-2a2a04119f28", "click", function (_event, args) { HelpService.togglePanel((String(args[0]))); });+ register("ldr-3b4cb39bbbaa", "click", function () { expandAll(); });+ register("ldr-4194a142f077", "click", function () { useNewsTemplate('custom'); });+ register("ldr-438d24fdd13e", "click", function () { filterDocuments('all'); });+ register("ldr-477281533c5c", "click", function () { window.filterLogsByType('warning'); });+ register("ldr-4a0c076b7987", "input", function () { onThresholdInput(this.value); });+ register("ldr-4b7d0f3a810f", "click", function () { window.location.href='/library/download-manager'; });+ register("ldr-4c2b17647c07", "click", function () { testConfiguration(); });+ register("ldr-4d106764b648", "click", function () { window.location.href='/library/collections/create'; });+ register("ldr-4ebaf419a72f", "click", function () { closeProgressModal(); });+ register("ldr-561feb93281e", "click", function () { useNewsTemplate('market-analysis'); });+ register("ldr-579596525a9b", "click", function () { clearAllFilters(); });+ register("ldr-5e849f3930dc", "click", function (event) { event.stopPropagation(); });+ register("ldr-6251dc7d9ff9", "click", function () { cancelDownloads(); });+ register("ldr-66604a98bfa8", "click", function () { useNewsTemplate('product-prices'); });+ register("ldr-732c097d3bd6", "input", function () { onThresholdInput(this.value, 'top'); });+ register("ldr-76c5cfca3bf9", "keydown", function (event, args) { if(event.key==='Enter'||event.key===' '){event.preventDefault();HelpService.togglePanel((String(args[0])));} });+ register("ldr-77470237e7f1", "click", function () { downloadAllAsText(); });+ register("ldr-7943169f7695", "click", function (event, args) { event.stopPropagation(); deleteBenchmarkRun(args[0]); });+ register("ldr-7f84802b842e", "click", function () { filterDocuments('unindexed'); });+ register("ldr-8629590b5f36", "click", function (_event, args) { toggleText((String(args[0]))); return false; });+ register("ldr-866fc15ec52d", "click", function (event, args) { event.preventDefault(); event.stopPropagation(); downloadBenchmarkYAML(args[0], true, document.getElementById(("include-settings-" + String(args[0]))).checked); });+ register("ldr-8b7c364b086d", "click", function () { showSchedulerInfo(); return false; });+ register("ldr-90d21284bbec", "click", function (event, args) { event.preventDefault(); event.stopPropagation(); downloadBenchmarkYAML(args[0], false, document.getElementById(("include-settings-" + String(args[0]))).checked); });+ register("ldr-93611303c0ce", "click", function () { copyTextContent(); });+ register("ldr-9c5e3fe6429b", "click", function () { downloadAllNew(); });+ register("ldr-a016548a6d9d", "click", function () { useNewsTemplate('tech-updates'); });+ register("ldr-a3bb8d0e0519", "submit", function (event) { handleNewsSubscriptionSubmit(event); });+ register("ldr-a501e656c944", "change", function () { onThresholdChange(this.value, 'top'); });+ register("ldr-a77923e9b953", "click", function () { closePDFModal(); });+ register("ldr-a88460f4b0fb", "click", function (_event, args) { goToPage(args[0]); });+ register("ldr-b05f0d5805ca", "change", function (_event, args) { HelpService.dismissPanel((String(args[0]))); });+ register("ldr-b08cdb8752cf", "click", function () { downloadJournalData(); });+ register("ldr-b1788a1b608c", "click", function () { switchTab('global-db'); });+ register("ldr-b656cf065727", "click", function () { switchTab('how-it-works'); return false; });+ register("ldr-ba74d1613374", "click", function () { useNewsTemplate('topic-news'); });+ register("ldr-bc47cdbe2fcf", "click", function () { createSubscription(); });+ register("ldr-bc4f4ba2110f", "click", function () { window.filterLogsByType('milestone'); });+ register("ldr-bd0633e0397b", "click", function () { markAllAsRead(); });+ register("ldr-be08ba18b565", "click", function () { window.location.href='/library/collections'; });+ register("ldr-be0b89850bf1", "click", function () { confirmStorageModeChange(); });+ register("ldr-bebfdb3bdf5e", "click", function () { useNewsTemplate('local-news'); });+ register("ldr-c1570cca83a9", "click", function () { window.location.href='/settings#research-library'; });+ register("ldr-c3f334819492", "click", function () { closeSyncModal(); });+ register("ldr-c5accacbff2a", "click", function () { downloadTextContent(); });+ register("ldr-c83d68f22951", "click", function () { selectNone(); });+ register("ldr-cd3cd8f3ee26", "click", function (_event, args) { toggleRunDetails(args[0]); });+ register("ldr-cdb29c0672c4", "click", function () { switchTab('your-research'); });+ register("ldr-d0086f8b30e2", "click", function () { this.parentElement.parentElement.remove(); });+ register("ldr-d7e9771cf24b", "click", function () { this.parentElement.style.display='none'; });+ register("ldr-d870f0b6fe62", "click", function () { closeTextModal(); });+ register("ldr-dbaa13cb7350", "click", function (event, args) { event.stopPropagation(); cancelAndDeleteBenchmarkRun(args[0]); });+ register("ldr-dbe8377a6a28", "click", function () { showSyncModal(); });+ register("ldr-dd13800ca405", "click", function () { filterDocuments('indexed'); });+ register("ldr-dfa4c91ebf6a", "click", function () { goToDownloadManager(); });+ register("ldr-e0804aecb652", "click", function () { clearTopicFilter(); });+ register("ldr-e590c2cc6eea", "change", function () { onThresholdChange(this.value); });+ register("ldr-e70e663ac02c", "click", function () { performSync(); });+ register("ldr-e768766cc8a7", "click", function () { location.reload(); });+ register("ldr-e7f65423115b", "click", function () { applyCustomTemplate(); });+ register("ldr-ecc80a8a9227", "click", function () { useNewsTemplate('breaking-news'); });+ register("ldr-f41390edb83d", "click", function () { collapseAll(); });+ register("ldr-f610ed2f650a", "click", function () { showStorageModeModal(); });+ register("ldr-f7667769f204", "click", function () { closeStorageModeModal(); });+ register("ldr-f9d9c5429c68", "click", function () { selectAll(); });+ register("ldr-fa738477c7c3", "click", function () { downloadCurrentPDF(); });+ register("ldr-fdae34cefb54", "click", function () { openPDFInNewTab(); });++ const observer = new MutationObserver(records => {+ for (const record of records) {+ if (record.type === 'attributes') bindElement(record.target);+ else for (const node of record.addedNodes) bindRoot(node);+ }+ });+ observer.observe(document, {+ childList: true,+ subtree: true,+ attributes: true,+ attributeFilter: ['data-ldr-template-token', ...events.map(type => `data-ldr-on${type}`)],+ });+ if (document.readyState === 'loading') {+ document.addEventListener('DOMContentLoaded', () => bindRoot(document), {once: true});+ } else bindRoot(document);+})();diff --git a/src/local_deep_research/web/static/js/services/pdf.js b/src/local_deep_research/web/static/js/services/pdf.jsindex 281e98fbc9..de33d8b1a9 100644--- a/src/local_deep_research/web/static/js/services/pdf.js+++ b/src/local_deep_research/web/static/js/services/pdf.js@@ -69,6 +69,53 @@ function wrapTopLevelText(container) {}}+/**+ * Preserve style authorization during html2canvas's synchronous clone phase.+ * Only fresh renderer styles and copies of already authorized styles qualify.+ * Restore DOM methods before the renderer's promise can resume other work.+ */+function renderPDFCanvas(renderer, element, options) {+ const nonce = window.LDRTemplateEvents?.styleNonce;+ if (typeof nonce !== 'string' || !/^[\w-]{43}$/.test(nonce)) {+ return renderer(element, options);+ }+ const owner = element.ownerDocument;+ const restores = [];+ function replaceMethod(target, name, replacement) {+ const descriptor = Object.getOwnPropertyDescriptor(target, name);+ Object.defineProperty(target, name, {+ configurable: true, writable: true, value: replacement,+ });+ restores.push(() => {+ if (descriptor) Object.defineProperty(target, name, descriptor);+ else delete target[name];+ });+ }+ try {+ const createElement = owner.createElement;+ replaceMethod(owner, 'createElement', function (...args) {+ const created = Reflect.apply(createElement, this, args);+ if (this === owner && created.localName === 'style') created.nonce = nonce;+ return created;+ });+ for (const style of owner.querySelectorAll('style')) {+ if (style.nonce !== nonce) continue;+ const cloneNode = style.cloneNode;+ replaceMethod(style, 'cloneNode', function (...args) {+ const clone = Reflect.apply(cloneNode, this, args);+ if (this === style && style.nonce === nonce && clone.localName === 'style') {+ clone.nonce = nonce;+ }+ return clone;+ });+ }+ return renderer(element, options);+ } finally {+ // The document-wide factory is restored first, including on failures.+ for (const restore of restores) restore();+ }+}+/*** Generate a PDF from the research content* @param {string|any} title - The research title/query@@ -102,8 +149,9 @@ async function generatePdf(title, content, _metadata = {}) {tempContainer.className = 'ldr-pdf-content';// Add PDF-specific styles- tempContainer.innerHTML = `- <style>+ const pdfStyle = document.createElement('style');+ pdfStyle.nonce = window.LDRTemplateEvents?.styleNonce || '';+ pdfStyle.textContent = `.ldr-pdf-content {font-family: Arial, sans-serif;color: #333;@@ -199,11 +247,11 @@ async function generatePdf(title, content, _metadata = {}) {color: #0066cc;text-decoration: underline;}- </style>- <div class="ldr-pdf-body" id="pdf-body-content">- <!-- Content will be added after marked parsing -->- </div>`;+ const pdfBody = document.createElement('div');+ pdfBody.className = 'ldr-pdf-body';+ pdfBody.id = 'pdf-body-content';+ tempContainer.append(pdfStyle, pdfBody);// Add to the document body temporarilydocument.body.appendChild(tempContainer);@@ -916,7 +964,7 @@ async function generatePdf(title, content, _metadata = {}) {} else {// Only use html2canvas as a last resort for elements with no text contenttry {- const canvas = await html2canvasLib(element, {+ const canvas = await renderPDFCanvas(html2canvasLib, element, {scale: 2,useCORS: true,logging: false,diff --git a/src/local_deep_research/web/static/js/services/ui.js b/src/local_deep_research/web/static/js/services/ui.jsindex acd7a76378..8f0efa373e 100644--- a/src/local_deep_research/web/static/js/services/ui.js+++ b/src/local_deep_research/web/static/js/services/ui.js@@ -1312,6 +1312,7 @@ function addAlertStyles() {if (document.getElementById('alert-styles')) return;const styleEl = document.createElement('style');+ styleEl.nonce = window.LDRTemplateEvents?.styleNonce || '';styleEl.id = 'alert-styles';styleEl.textContent = `.alert {diff --git a/src/local_deep_research/web/static/templates/followup_modal.html b/src/local_deep_research/web/static/templates/followup_modal.htmlindex 9c5c559a53..988a37edfe 100644--- a/src/local_deep_research/web/static/templates/followup_modal.html+++ b/src/local_deep_research/web/static/templates/followup_modal.html@@ -40,7 +40,7 @@</div><div class="modal-footer"><button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>- <button type="button" class="btn btn-primary" onclick="followUpResearch.submitFollowUp()">+ <button type="button" class="btn btn-primary"><i class="fas fa-search"></i> Start Follow-up Research</button></div>diff --git a/src/local_deep_research/web/template_config.py b/src/local_deep_research/web/template_config.pyindex e07f562f5b..bc603b73dd 100644--- a/src/local_deep_research/web/template_config.py+++ b/src/local_deep_research/web/template_config.py@@ -55,7 +55,16 @@ class _LDRTemplates(Jinja2Templates):)kwargs[key] = valueargs = args[len(_TEMPLATE_RESPONSE_ARGS) :]- context = kwargs.get("context") or {}+ elif args and isinstance(args[0], str):+ legacy_keys = _TEMPLATE_RESPONSE_ARGS[1:]+ for key, value in zip(legacy_keys, args):+ if key in kwargs:+ raise TypeError(+ f"TemplateResponse() got multiple values for argument {key!r}"+ )+ kwargs[key] = value+ args = args[len(legacy_keys) :]+ context = dict(kwargs.get("context") or {})request = kwargs.get("request") or context.get("request")if request is None and args:@@ -63,6 +72,15 @@ class _LDRTemplates(Jinja2Templates):if isinstance(args[0], Request):request = args[0]+ if request is not None:+ from .utils.csp import template_security_context++ security = template_security_context(request.scope)+ context["csp_nonce"] = security.nonce+ context["template_event_token"] = security.event_token+ kwargs["request"] = request+ kwargs["context"] = context+session = getattr(request, "session", None) if request else None# Session is a Starlette mapping (dict-like); guard conservatively# — the old check `session.__class__.get` crashed when session wasdiff --git a/src/local_deep_research/web/templates/auth/change_password.html b/src/local_deep_research/web/templates/auth/change_password.htmlindex b741da0e77..7ddce11b5f 100644--- a/src/local_deep_research/web/templates/auth/change_password.html+++ b/src/local_deep_research/web/templates/auth/change_password.html@@ -1,6 +1,7 @@<!DOCTYPE html><html lang="en"><head>+ <script nonce="{{ csp_nonce }}" data-template-token="{{ template_event_token }}" src="/static/js/security/template-events.js"></script><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Change Password - Local Deep Research</title>@@ -15,7 +16,7 @@{{ vite_asset('js/app.js') }}<link rel="stylesheet" href="/static/css/themes.css"><link rel="stylesheet" href="/static/css/styles.css">- <style>+ <style nonce="{{ csp_nonce }}">body {background-color: var(--bg-primary);display: flex;@@ -200,7 +201,7 @@</div></div>- <script>+ <script nonce="{{ csp_nonce }}">const csrfToken = document.querySelector('input[name="csrf_token"]').value;const strengthBar = document.getElementById('password-strength');diff --git a/src/local_deep_research/web/templates/auth/login.html b/src/local_deep_research/web/templates/auth/login.htmlindex d3101b2aad..7c1a167c25 100644--- a/src/local_deep_research/web/templates/auth/login.html+++ b/src/local_deep_research/web/templates/auth/login.html@@ -1,6 +1,7 @@<!DOCTYPE html><html lang="en"><head>+ <script nonce="{{ csp_nonce }}" data-template-token="{{ template_event_token }}" src="/static/js/security/template-events.js"></script><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Login - Local Deep Research</title>@@ -15,7 +16,7 @@<!-- Keep local styles --><link rel="stylesheet" href="/static/css/styles.css">- <style>+ <style nonce="{{ csp_nonce }}">/* Override main layout for auth pages */body {min-height: 100vh;@@ -349,7 +350,7 @@<div class="alert alert-warning alert-dismissible">{% endif %}{{ message }}- <button type="button" class="btn-close" onclick="this.parentElement.style.display='none'">×</button>+ <button type="button" class="btn-close" data-ldr-onclick="ldr-d7e9771cf24b" data-ldr-template-token="{{ template_event_token }}">×</button></div>{% endfor %}{% endif %}@@ -411,14 +412,14 @@</div>- <!-- Clear theme localStorage on logout to prevent cross-user theme bleeding -->- <script>+ {# Clear theme localStorage on logout to prevent cross-user theme bleeding #}+ <script nonce="{{ csp_nonce }}">(function() {- // Check if user was just logged out (via flash message or URL parameter)+var wasLoggedOut = {{ 'true' if session.get('just_logged_out') else 'false' }};var urlParams = new URLSearchParams(window.location.search);if (wasLoggedOut || urlParams.has('logged_out')) {- // Clear all theme keys from localStorage+var keysToRemove = [];for (var i = 0; i < localStorage.length; i++) {var key = localStorage.key(i);diff --git a/src/local_deep_research/web/templates/auth/register.html b/src/local_deep_research/web/templates/auth/register.htmlindex 9b0d4e01d4..b67f069691 100644--- a/src/local_deep_research/web/templates/auth/register.html+++ b/src/local_deep_research/web/templates/auth/register.html@@ -1,6 +1,7 @@<!DOCTYPE html><html lang="en"><head>+ <script nonce="{{ csp_nonce }}" data-template-token="{{ template_event_token }}" src="/static/js/security/template-events.js"></script><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Register - Local Deep Research</title>@@ -16,7 +17,7 @@<!-- Keep local styles --><link rel="stylesheet" href="/static/css/styles.css">- <style>+ <style nonce="{{ csp_nonce }}">/* Override main layout for auth pages */body {display: flex;@@ -417,7 +418,7 @@{% for category, message in messages %}<div class="alert alert-dismissible">{{ message }}- <button type="button" class="btn-close" onclick="this.parentElement.style.display='none'">×</button>+ <button type="button" class="btn-close" data-ldr-onclick="ldr-d7e9771cf24b" data-ldr-template-token="{{ template_event_token }}">×</button></div>{% endfor %}{% endif %}@@ -515,7 +516,7 @@</div></div></div>- <script>+ <script nonce="{{ csp_nonce }}">// Validation helpersfunction setFieldValid(input, errorEl) {input.classList.remove('is-invalid');@@ -540,7 +541,7 @@errorEl.textContent = '';}- // Username validation+const usernameInput = document.getElementById('username');const usernameError = document.getElementById('username-error');const usernamePattern = /^[a-zA-Z0-9_\-]+$/;@@ -666,7 +667,7 @@e.preventDefault();let hasError = false;- // Validate username+const username = usernameInput.value.trim();if (username.length === 0) {setFieldInvalid(usernameInput, usernameError, 'Username is required');diff --git a/src/local_deep_research/web/templates/base.html b/src/local_deep_research/web/templates/base.htmlindex 1d0948ee71..383234c203 100644--- a/src/local_deep_research/web/templates/base.html+++ b/src/local_deep_research/web/templates/base.html@@ -2,6 +2,7 @@{# Hashed is the registered dark palette, preferred while light themes need refinement. #}<html lang="en" data-theme="{{ default_theme }}"><head>+ <script nonce="{{ csp_nonce }}" data-template-token="{{ template_event_token }}" src="/static/js/security/template-events.js"></script><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta name="csrf-token" content="{{ csrf_token() }}">@@ -12,7 +13,7 @@<!-- FOUC Prevention: Apply theme before any rendering --><!-- Theme list is auto-detected from themes.css by ThemeHelper -->- <script>+ <script nonce="{{ csp_nonce }}">(function() {// Auto-detected from CSS - no need to manually update this listvar validThemes = {{ get_themes_json() }};@@ -86,7 +87,7 @@warning. The egress banners do the actual nag. Red intentionallyavoided on the card itself.-->- <style>+ <style nonce="{{ csp_nonce }}">.ldr-card.ldr-research-card,#chat-page,.ldr-chat-container {@@ -137,7 +138,7 @@</style><!-- Force hide sidebar on mobile with inline CSS for highest priority -->- <style>+ <style nonce="{{ csp_nonce }}">@media (max-width: 767px) {/* Absolutely hide the desktop sidebar on mobile */.ldr-sidebar:not(.active),@@ -235,7 +236,7 @@<!-- Injected by: src/local_deep_research/web/template_config.py (_LDRTemplates.TemplateResponse) --><!-- Consumed by: src/local_deep_research/web/static/js/config/constants.js (ResearchStates helpers) --><!-- Must remain a bare <script> (no defer) so window.* is set before defer-ed scripts run. -->- <script>+ <script nonce="{{ csp_nonce }}">window.RESEARCH_STATUS = Object.freeze({{ research_status_enum | tojson }}); // nosemgrep: generic.html-templates.security.var-in-script-tag.var-in-script-tag, reason: Jinja tojson escapes HTML delimiterswindow.RESEARCH_TERMINAL_STATES = Object.freeze(new Set({{ research_terminal_states | tojson }})); // nosemgrep: generic.html-templates.security.var-in-script-tag.var-in-script-tag, reason: Jinja tojson escapes HTML delimiterswindow.LDR_LOG_LIMITS = Object.freeze({{ log_limits | tojson }}); // nosemgrep: generic.html-templates.security.var-in-script-tag.var-in-script-tag, reason: Jinja tojson escapes HTML delimiters@@ -247,7 +248,7 @@<script defer src="/static/js/config/urls.js"></script><!-- Logo click handler -->- <script>+ <script nonce="{{ csp_nonce }}">document.addEventListener('DOMContentLoaded', function() {const logoLink = document.getElementById('logo-link');if (logoLink) {@@ -310,7 +311,7 @@<!-- Page-specific JS -->{% block page_scripts %}{% endblock %}- <script>+ <script nonce="{{ csp_nonce }}">// Configure marked to not use evalif (typeof marked !== 'undefined') {marked.setOptions({diff --git a/src/local_deep_research/web/templates/components/delete_confirmation_modal.html b/src/local_deep_research/web/templates/components/delete_confirmation_modal.htmlindex e593d1b6e9..4746ce7559 100644--- a/src/local_deep_research/web/templates/components/delete_confirmation_modal.html+++ b/src/local_deep_research/web/templates/components/delete_confirmation_modal.html@@ -36,7 +36,7 @@</div></div>-<style>+<style nonce="{{ csp_nonce }}">/* Delete confirmation modal specific styles */#deleteConfirmModal .modal-header.bg-danger {background: var(--error-color) !important;diff --git a/src/local_deep_research/web/templates/components/help_macros.html b/src/local_deep_research/web/templates/components/help_macros.htmlindex 5b56ed45a0..0c4a2f14a4 100644--- a/src/local_deep_research/web/templates/components/help_macros.html+++ b/src/local_deep_research/web/templates/components/help_macros.html@@ -59,8 +59,8 @@tabindex="0"aria-expanded="{{ 'false' if collapsed else 'true' }}"aria-controls="help-panel-content-{{ panel_id }}"- onclick="HelpService.togglePanel('{{ panel_id }}')"- onkeydown="if(event.key==='Enter'||event.key===' '){event.preventDefault();HelpService.togglePanel('{{ panel_id }}');}">+ data-ldr-onclick="ldr-2a2a04119f28" data-ldr-template-token="{{ template_event_token }}" data-ldr-onclick-args="{{ [panel_id]|tojson|urlencode }}"+ data-ldr-onkeydown="ldr-76c5cfca3bf9" data-ldr-onkeydown-args="{{ [panel_id]|tojson|urlencode }}"><div class="ldr-help-panel-title"><i class="{{ 'fas fa-' ~ icon }}" aria-hidden="true"></i><span>{{ title }}</span>@@ -73,7 +73,7 @@<div class="ldr-help-panel-dismiss"><label><input type="checkbox"- onchange="HelpService.dismissPanel('{{ panel_id }}')"+ data-ldr-onchange="ldr-b05f0d5805ca" data-ldr-template-token="{{ template_event_token }}" data-ldr-onchange-args="{{ [panel_id]|tojson|urlencode }}"aria-label="Don't show this help panel again"><span>Don't show this again</span></label>diff --git a/src/local_deep_research/web/templates/components/log_panel.html b/src/local_deep_research/web/templates/components/log_panel.htmlindex fe6f1a6b0a..e4e409515c 100644--- a/src/local_deep_research/web/templates/components/log_panel.html+++ b/src/local_deep_research/web/templates/components/log_panel.html@@ -8,19 +8,19 @@<div class="ldr-log-controls"><div class="ldr-log-filter"><div class="ldr-filter-buttons">- <button class="ldr-small-btn ldr-selected" data-filter-type="all" onclick="window.filterLogsByType('all')">+ <button class="ldr-small-btn ldr-selected" data-filter-type="all" data-ldr-onclick="ldr-28da1ff332dc" data-ldr-template-token="{{ template_event_token }}">All <span class="ldr-filter-count" data-filter-count="all">0</span></button>- <button class="ldr-small-btn" data-filter-type="milestone" onclick="window.filterLogsByType('milestone')">+ <button class="ldr-small-btn" data-filter-type="milestone" data-ldr-onclick="ldr-bc4f4ba2110f" data-ldr-template-token="{{ template_event_token }}">Milestones <span class="ldr-filter-count" data-filter-count="milestone">0</span></button>- <button class="ldr-small-btn" data-filter-type="info" onclick="window.filterLogsByType('info')">+ <button class="ldr-small-btn" data-filter-type="info" data-ldr-onclick="ldr-1196e5e97014" data-ldr-template-token="{{ template_event_token }}">Info <span class="ldr-filter-count" data-filter-count="info">0</span></button>- <button class="ldr-small-btn" data-filter-type="warning" onclick="window.filterLogsByType('warning')">+ <button class="ldr-small-btn" data-filter-type="warning" data-ldr-onclick="ldr-477281533c5c" data-ldr-template-token="{{ template_event_token }}">Warning <span class="ldr-filter-count" data-filter-count="warning">0</span></button>- <button class="ldr-small-btn" data-filter-type="error" onclick="window.filterLogsByType('error')">+ <button class="ldr-small-btn" data-filter-type="error" data-ldr-onclick="ldr-25bdba94481d" data-ldr-template-token="{{ template_event_token }}">Errors <span class="ldr-filter-count" data-filter-count="error">0</span></button></div>diff --git a/src/local_deep_research/web/templates/components/storage_mode_modal.html b/src/local_deep_research/web/templates/components/storage_mode_modal.htmlindex 70a35c8487..feb076400b 100644--- a/src/local_deep_research/web/templates/components/storage_mode_modal.html+++ b/src/local_deep_research/web/templates/components/storage_mode_modal.html@@ -3,7 +3,7 @@<div class="modal-content" style="max-width: 650px;"><div class="modal-header"><h2><i aria-hidden="true" class="fas fa-database"></i> PDF Storage Mode</h2>- <button class="ldr-close" onclick="closeStorageModeModal()">×</button>+ <button class="ldr-close" data-ldr-onclick="ldr-f7667769f204" data-ldr-template-token="{{ template_event_token }}">×</button></div><div class="modal-body"><p style="margin-bottom: 20px;">Choose where to store downloaded PDFs:</p>@@ -50,15 +50,15 @@</div></div><div class="modal-footer">- <button id="storage-mode-confirm-btn" class="btn btn-primary" onclick="confirmStorageModeChange()">+ <button id="storage-mode-confirm-btn" class="btn btn-primary" data-ldr-onclick="ldr-be0b89850bf1" data-ldr-template-token="{{ template_event_token }}"><i aria-hidden="true" class="fas fa-check"></i> Save</button>- <button class="btn btn-secondary" onclick="closeStorageModeModal()">Cancel</button>+ <button class="btn btn-secondary" data-ldr-onclick="ldr-f7667769f204" data-ldr-template-token="{{ template_event_token }}">Cancel</button></div></div></div>-<style>+<style nonce="{{ csp_nonce }}">/* Storage Mode Modal */#storage-mode-modal .modal-content {color: var(--text-primary);@@ -202,7 +202,7 @@ button.ldr-storage-mode-btn.ldr-warning-message {}</style>-<script>+<script nonce="{{ csp_nonce }}">// Storage Mode Modal Functionsfunction showStorageModeModal() {document.getElementById('storage-mode-modal').style.display = 'flex';diff --git a/src/local_deep_research/web/templates/pages/benchmark.html b/src/local_deep_research/web/templates/pages/benchmark.htmlindex 55e1b0342c..b68e1e86ea 100644--- a/src/local_deep_research/web/templates/pages/benchmark.html+++ b/src/local_deep_research/web/templates/pages/benchmark.html@@ -1,6 +1,6 @@{% extends "base.html" %}{% from "components/custom_dropdown.html" import render_dropdown %}-{% from "components/help_macros.html" import tooltip, help_panel, help_step, help_tip %}+{% from "components/help_macros.html" import tooltip, help_panel, help_step, help_tip with context %}{% set active_page = 'benchmark' %}@@ -444,7 +444,7 @@</div></div>-<script>+<script nonce="{{ csp_nonce }}">// Get CSRF tokenconst csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || '';@@ -1103,7 +1103,7 @@ function showAlert(message, type) {alertContainer.innerHTML = `<div class="ldr-settings-alert alert-${window.escapeHtml(type === 'error' ? 'danger' : type)}"><span>${window.escapeHtml(message)}</span>- <button type="button" class="ldr-close-alert" onclick="this.parentElement.parentElement.style.display='none'">+ <button type="button" class="ldr-close-alert" data-ldr-onclick="ldr-20a43efc0120" data-ldr-template-token="{{ template_event_token }}"><i aria-hidden="true" class="fas fa-times"></i></button></div>@@ -1429,7 +1429,7 @@ function displayRecentResults(results) {return `<span id="truncated-${id}" style="display: ${isExpanded ? 'none' : 'inline'};">${window.escapeHtml(truncated)}</span><span id="full-${id}" style="display: ${isExpanded ? 'inline' : 'none'};">${window.escapeHtml(text)}</span>- <a href="#" onclick="toggleText('${id}'); return false;" id="toggle-${id}" class="ldr-link">${isExpanded ? 'Show less' : 'Show more'}</a>+ <a href="#" ${window.LDRTemplateEvents.attributes("ldr-8629590b5f36", [id])} id="toggle-${id}" class="ldr-link">${isExpanded ? 'Show less' : 'Show more'}</a>`;};diff --git a/src/local_deep_research/web/templates/pages/benchmark_results.html b/src/local_deep_research/web/templates/pages/benchmark_results.htmlindex f02cfa220f..2f625c3263 100644--- a/src/local_deep_research/web/templates/pages/benchmark_results.html+++ b/src/local_deep_research/web/templates/pages/benchmark_results.html@@ -80,7 +80,7 @@formatSettingsSnapshot) — extracted so the export escaping is unit-tested.Must load before the inline script below, which calls them as globals. --><script src="/static/js/utils/yaml_export.js"></script>-<script>+<script nonce="{{ csp_nonce }}">let benchmarkRuns = [];let filteredRuns = [];let currentPage = 1;@@ -224,7 +224,7 @@ function createRunCard(run) {const formattedStatus = status.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase());return `- <div class="ldr-run-card" onclick="toggleRunDetails(${run.id})">+ <div class="ldr-run-card" ${window.LDRTemplateEvents.attributes("ldr-cd3cd8f3ee26", [run.id])}><div class="ldr-run-header"><div class="ldr-run-title">${escapeHtml(run.run_name)}</div><div class="ldr-run-date">${date} ${time}</div>@@ -270,31 +270,31 @@ function createRunCard(run) {<div class="ldr-summary-item"><div style="display: flex; gap: 8px; flex-wrap: wrap; justify-content: center;">${status === 'completed' ?- `<div class="dropdown d-inline-block" onclick="event.stopPropagation()">+ `<div class="dropdown d-inline-block" data-ldr-onclick="ldr-5e849f3930dc" data-ldr-template-token="{{ template_event_token }}"><button class="btn ldr-btn-outline btn-sm ldr-download-btn dropdown-toggle" type="button" id="export-dropdown-${run.id}" data-bs-toggle="dropdown" aria-expanded="false" title="Export benchmark YAML"><i aria-hidden="true" class="fas fa-download"></i> Export</button><ul class="dropdown-menu" aria-labelledby="export-dropdown-${run.id}">- <li><a class="dropdown-item" href="#" onclick="event.preventDefault(); event.stopPropagation(); downloadBenchmarkYAML(${run.id}, false, document.getElementById('include-settings-${run.id}').checked)">+ <li><a class="dropdown-item" href="#" ${window.LDRTemplateEvents.attributes("ldr-90d21284bbec", [run.id])}><i aria-hidden="true" class="fas fa-download"></i> Download YAML (summary)</a></li>- <li><a class="dropdown-item" href="#" onclick="event.preventDefault(); event.stopPropagation(); downloadBenchmarkYAML(${run.id}, true, document.getElementById('include-settings-${run.id}').checked)">+ <li><a class="dropdown-item" href="#" ${window.LDRTemplateEvents.attributes("ldr-866fc15ec52d", [run.id])}><i aria-hidden="true" class="fas fa-download"></i> Download YAML + examples</a></li><li><hr class="dropdown-divider"></li>- <li class="dropdown-item" onclick="event.stopPropagation()">+ <li class="dropdown-item" data-ldr-onclick="ldr-5e849f3930dc" data-ldr-template-token="{{ template_event_token }}"><label style="display:flex; align-items:center; gap:6px; margin:0; cursor:pointer;">- <input type="checkbox" id="include-settings-${run.id}" onclick="event.stopPropagation()"> Include settings snapshot+ <input type="checkbox" id="include-settings-${run.id}" data-ldr-onclick="ldr-5e849f3930dc" data-ldr-template-token="{{ template_event_token }}"> Include settings snapshot</label></li></ul></div>` : ''}${status === 'in_progress' ?- `<button class="btn ldr-btn-outline btn-sm ldr-delete-btn" onclick="event.stopPropagation(); cancelAndDeleteBenchmarkRun(${run.id})">+ `<button class="btn ldr-btn-outline btn-sm ldr-delete-btn" ${window.LDRTemplateEvents.attributes("ldr-dbaa13cb7350", [run.id])}><i aria-hidden="true" class="fas fa-stop"></i> Cancel & Delete</button>` :- `<button class="btn ldr-btn-outline btn-sm ldr-delete-btn" onclick="event.stopPropagation(); deleteBenchmarkRun(${run.id})">+ `<button class="btn ldr-btn-outline btn-sm ldr-delete-btn" ${window.LDRTemplateEvents.attributes("ldr-7943169f7695", [run.id])}><i aria-hidden="true" class="fas fa-trash"></i> Delete</button>`}@@ -832,7 +832,7 @@ function showAlert(message, type) {alertDiv.innerHTML = `<div style="display: flex; align-items: center; justify-content: space-between;"><span>${escapeHtml(message)}</span>- <button onclick="this.parentElement.parentElement.remove()" style="background: none; border: none; color: white; font-size: 1.2rem; cursor: pointer; margin-left: 10px;">×</button>+ <button data-ldr-onclick="ldr-d0086f8b30e2" data-ldr-template-token="{{ template_event_token }}" style="background: none; border: none; color: white; font-size: 1.2rem; cursor: pointer; margin-left: 10px;">×</button></div>`;diff --git a/src/local_deep_research/web/templates/pages/benchmark_simple.html b/src/local_deep_research/web/templates/pages/benchmark_simple.htmlindex 9a286cde75..d54b26d1e9 100644--- a/src/local_deep_research/web/templates/pages/benchmark_simple.html+++ b/src/local_deep_research/web/templates/pages/benchmark_simple.html@@ -6,7 +6,7 @@{% block extra_head %}<meta name="csrf-token" content="{{ csrf_token() }}">-<style>+<style nonce="{{ csp_nonce }}">.ldr-benchmark-card {max-width: 700px;margin: 0 auto;@@ -211,7 +211,7 @@</div></div>-<script>+<script nonce="{{ csp_nonce }}">let currentBenchmarkId = null;let progressInterval = null;let progressRunGeneration = 0;@@ -519,7 +519,7 @@ function showAlert(message, type) {alertContainer.innerHTML = `<div class="ldr-settings-alert alert-${escapeHtml(type === 'error' ? 'danger' : type)}"><span>${escapeHtml(message)}</span>- <button type="button" class="ldr-close-alert" onclick="this.parentElement.parentElement.style.display='none'">+ <button type="button" class="ldr-close-alert" data-ldr-onclick="ldr-20a43efc0120" data-ldr-template-token="{{ template_event_token }}"><i aria-hidden="true" class="fas fa-times"></i></button></div>diff --git a/src/local_deep_research/web/templates/pages/collection_create.html b/src/local_deep_research/web/templates/pages/collection_create.htmlindex 52f4f2a400..45033b474c 100644--- a/src/local_deep_research/web/templates/pages/collection_create.html+++ b/src/local_deep_research/web/templates/pages/collection_create.html@@ -75,7 +75,7 @@</div><div class="ldr-form-actions">- <button type="button" class="ldr-btn-collections ldr-btn-collections-secondary" onclick="window.location.href='/library/collections'">+ <button type="button" class="ldr-btn-collections ldr-btn-collections-secondary" data-ldr-onclick="ldr-be08ba18b565" data-ldr-template-token="{{ template_event_token }}"><i aria-hidden="true" class="fas fa-times"></i> Cancel</button><button type="submit" class="ldr-btn-collections ldr-btn-collections-primary ldr-btn-lg ldr-btn-featured" id="create-collection-btn">@@ -125,7 +125,7 @@</div><!-- Pass collection_id placeholder (not used) to JavaScript -->-<script>+<script nonce="{{ csp_nonce }}">const COLLECTION_ID = null; // Not needed for create page</script><script defer src="/static/js/collection_create.js"></script>diff --git a/src/local_deep_research/web/templates/pages/collection_details.html b/src/local_deep_research/web/templates/pages/collection_details.htmlindex 0e96353c84..7a02dc2b02 100644--- a/src/local_deep_research/web/templates/pages/collection_details.html+++ b/src/local_deep_research/web/templates/pages/collection_details.html@@ -1,5 +1,5 @@{% extends "base.html" %}-{% from "components/help_macros.html" import tooltip, help_panel, help_step, help_tip %}+{% from "components/help_macros.html" import tooltip, help_panel, help_step, help_tip with context %}{% block title %}Collection Details{% endblock %}@@ -188,9 +188,9 @@<div class="ldr-section-header"><h2><i aria-hidden="true" class="fas fa-file"></i> Documents</h2><div class="ldr-filter-controls">- <button class="ldr-btn-collections ldr-btn-outline-primary ldr-active" onclick="filterDocuments('all')">All</button>- <button class="ldr-btn-collections ldr-btn-outline-success" onclick="filterDocuments('indexed')">Indexed</button>- <button class="ldr-btn-collections ldr-btn-outline-warning" onclick="filterDocuments('unindexed')">Not Indexed</button>+ <button class="ldr-btn-collections ldr-btn-outline-primary ldr-active" data-ldr-onclick="ldr-438d24fdd13e" data-ldr-template-token="{{ template_event_token }}">All</button>+ <button class="ldr-btn-collections ldr-btn-outline-success" data-ldr-onclick="ldr-dd13800ca405" data-ldr-template-token="{{ template_event_token }}">Indexed</button>+ <button class="ldr-btn-collections ldr-btn-outline-warning" data-ldr-onclick="ldr-7f84802b842e" data-ldr-template-token="{{ template_event_token }}">Not Indexed</button></div></div>@@ -220,7 +220,7 @@{% include "components/delete_confirmation_modal.html" %}<!-- Pass collection_id to JavaScript -->-<script>+<script nonce="{{ csp_nonce }}">const COLLECTION_ID = "{{ collection_id }}";</script><script defer src="/static/js/deletion/confirmation_modal.js"></script>diff --git a/src/local_deep_research/web/templates/pages/collection_upload.html b/src/local_deep_research/web/templates/pages/collection_upload.htmlindex e5c60bb777..755054445a 100644--- a/src/local_deep_research/web/templates/pages/collection_upload.html+++ b/src/local_deep_research/web/templates/pages/collection_upload.html@@ -4,7 +4,7 @@{% block extra_head %}<link rel="stylesheet" href="/static/css/collection_details.css">-<style>+<style nonce="{{ csp_nonce }}">/* Storage Mode Options - reused from storage_mode_modal.html */.ldr-storage-mode-options {display: flex;@@ -236,7 +236,7 @@<!-- All JavaScript dependencies are already loaded in base template --><!-- Pass collection_id to JavaScript -->-<script>+<script nonce="{{ csp_nonce }}">const COLLECTION_ID = "{{ collection_id }}";</script><script defer src="/static/js/collection_upload.js"></script>diff --git a/src/local_deep_research/web/templates/pages/collections.html b/src/local_deep_research/web/templates/pages/collections.htmlindex 7df0f9838c..2420099930 100644--- a/src/local_deep_research/web/templates/pages/collections.html+++ b/src/local_deep_research/web/templates/pages/collections.html@@ -1,5 +1,5 @@{% extends "base.html" %}-{% from "components/help_macros.html" import tooltip, help_panel, help_step, help_tip %}+{% from "components/help_macros.html" import tooltip, help_panel, help_step, help_tip with context %}{% block title %}Document Collections - Deep Research System{% endblock %}diff --git a/src/local_deep_research/web/templates/pages/context_overflow.html b/src/local_deep_research/web/templates/pages/context_overflow.htmlindex b165280159..25e00d3d9a 100644--- a/src/local_deep_research/web/templates/pages/context_overflow.html+++ b/src/local_deep_research/web/templates/pages/context_overflow.html@@ -1,5 +1,5 @@{% extends "base.html" %}-{% from "components/help_macros.html" import tooltip, help_panel, help_step, help_tip %}+{% from "components/help_macros.html" import tooltip, help_panel, help_step, help_tip with context %}{% set active_page = 'metrics' %}diff --git a/src/local_deep_research/web/templates/pages/cost_analytics.html b/src/local_deep_research/web/templates/pages/cost_analytics.htmlindex 2c6467e3a3..ced775712d 100644--- a/src/local_deep_research/web/templates/pages/cost_analytics.html+++ b/src/local_deep_research/web/templates/pages/cost_analytics.html@@ -1,5 +1,5 @@{% extends "base.html" %}-{% from "components/help_macros.html" import tooltip, help_panel, help_step, help_tip, privacy_note %}+{% from "components/help_macros.html" import tooltip, help_panel, help_step, help_tip, privacy_note with context %}{% set active_page = 'metrics' %}@@ -320,7 +320,7 @@</div></div>-<script>+<script nonce="{{ csp_nonce }}">// Cost Analytics JavaScript(function() {let currentPeriod = '7d';diff --git a/src/local_deep_research/web/templates/pages/download_manager.html b/src/local_deep_research/web/templates/pages/download_manager.htmlindex 4fd6ae2f33..149324dc50 100644--- a/src/local_deep_research/web/templates/pages/download_manager.html+++ b/src/local_deep_research/web/templates/pages/download_manager.html@@ -1,5 +1,5 @@{% extends "base.html" %}-{% from "components/help_macros.html" import tooltip, help_panel, help_step, help_tip %}+{% from "components/help_macros.html" import tooltip, help_panel, help_step, help_tip with context %}{% set active_page = 'download-manager' %}{% block title %}Download Manager{% endblock %}@@ -15,7 +15,7 @@<h1>Download Manager</h1><div class="ldr-header-actions"><div class="ldr-btn-group" style="margin-right: 15px;">- <button class="btn btn-success" onclick="downloadAllNew()"+ <button class="btn btn-success" data-ldr-onclick="ldr-9c5e3fe6429b" data-ldr-template-token="{{ template_event_token }}"{% if not enable_pdf_storage %}disabledtitle="PDF storage is disabled. Click the storage mode button to enable."@@ -24,7 +24,7 @@{% endif %}><i aria-hidden="true" class="fas fa-file-pdf"></i> Get All Research PDFs</button>- <button class="btn btn-info" onclick="downloadAllAsText()"+ <button class="btn btn-info" data-ldr-onclick="ldr-77470237e7f1" data-ldr-template-token="{{ template_event_token }}"title="Extract text from all research sources without saving PDF files"><i aria-hidden="true" class="fas fa-file-alt"></i> Text Only (from PDFs)</button>@@ -74,19 +74,19 @@<div class="ldr-info-content"><h4>Library Storage Settings</h4>{% if pdf_storage_mode == 'database' %}- <button class="ldr-storage-mode-btn ldr-info-message" onclick="showStorageModeModal()" title="Click to change storage mode">+ <button class="ldr-storage-mode-btn ldr-info-message" data-ldr-onclick="ldr-f610ed2f650a" data-ldr-template-token="{{ template_event_token }}" title="Click to change storage mode"><i aria-hidden="true" class="fas fa-database"></i><strong>PDF Storage: Encrypted Database</strong> - PDFs encrypted in your personal database. Portable, isolated per-user.<i aria-hidden="true" class="fas fa-pen" style="margin-left: 8px; opacity: 0.6; font-size: 0.85em;"></i></button>{% elif pdf_storage_mode == 'filesystem' %}- <button class="ldr-storage-mode-btn ldr-warning-message" onclick="showStorageModeModal()" title="Click to change storage mode">+ <button class="ldr-storage-mode-btn ldr-warning-message" data-ldr-onclick="ldr-f610ed2f650a" data-ldr-template-token="{{ template_event_token }}" title="Click to change storage mode"><i aria-hidden="true" class="fas fa-hdd"></i><strong>PDF Storage: Filesystem</strong> - PDFs saved unencrypted to disk. Faster for large files.<i aria-hidden="true" class="fas fa-pen" style="margin-left: 8px; opacity: 0.6; font-size: 0.85em;"></i></button>{% else %}- <button class="ldr-storage-mode-btn ldr-warning-message" onclick="showStorageModeModal()" title="Click to change storage mode">+ <button class="ldr-storage-mode-btn ldr-warning-message" data-ldr-onclick="ldr-f610ed2f650a" data-ldr-template-token="{{ template_event_token }}" title="Click to change storage mode"><i aria-hidden="true" class="fas fa-file-alt"></i><strong>PDF Storage: Text Only</strong> - Only extracted text stored. Re-download PDFs when needed.<i aria-hidden="true" class="fas fa-pen" style="margin-left: 8px; opacity: 0.6; font-size: 0.85em;"></i>@@ -183,9 +183,9 @@</div><div class="ldr-bulk-actions">- <button class="ldr-btn-bulk" onclick="selectAll()">Select All</button>- <button class="ldr-btn-bulk" onclick="selectNone()">Select None</button>- <button class="ldr-btn-bulk" onclick="selectFiltered()">Select Filtered</button>+ <button class="ldr-btn-bulk" data-ldr-onclick="ldr-f9d9c5429c68" data-ldr-template-token="{{ template_event_token }}">Select All</button>+ <button class="ldr-btn-bulk" data-ldr-onclick="ldr-c83d68f22951" data-ldr-template-token="{{ template_event_token }}">Select None</button>+ <button class="ldr-btn-bulk" data-ldr-onclick="ldr-2879f1d6b0ec" data-ldr-template-token="{{ template_event_token }}">Select Filtered</button></div></div>@@ -389,8 +389,8 @@</div></div><div class="modal-footer">- <button class="btn btn-secondary" onclick="closeProgressModal()">Close</button>- <button class="btn btn-danger" onclick="cancelDownloads()">Cancel</button>+ <button class="btn btn-secondary" data-ldr-onclick="ldr-4ebaf419a72f" data-ldr-template-token="{{ template_event_token }}">Close</button>+ <button class="btn btn-danger" data-ldr-onclick="ldr-6251dc7d9ff9" data-ldr-template-token="{{ template_event_token }}">Cancel</button></div></div></div>@@ -398,7 +398,7 @@{% include 'components/storage_mode_modal.html' %}</div>-<script>+<script nonce="{{ csp_nonce }}">let selectedResearches = new Set();// Per-status counters for the download progress breakdown.diff --git a/src/local_deep_research/web/templates/pages/embedding_settings.html b/src/local_deep_research/web/templates/pages/embedding_settings.htmlindex 89e7a17648..766a8d8333 100644--- a/src/local_deep_research/web/templates/pages/embedding_settings.html+++ b/src/local_deep_research/web/templates/pages/embedding_settings.html@@ -1,5 +1,5 @@{% extends "base.html" %}-{% from "components/help_macros.html" import tooltip, help_panel, help_step, help_tip, glossary_term %}+{% from "components/help_macros.html" import tooltip, help_panel, help_step, help_tip, glossary_term with context %}{% block title %}Embedding Settings{% endblock %}@@ -81,7 +81,7 @@</div><div class="ldr-operations-grid">- <button class="ldr-btn ldr-btn-success ldr-btn-lg" onclick="testConfiguration()" id="test-config-btn">+ <button class="ldr-btn ldr-btn-success ldr-btn-lg" data-ldr-onclick="ldr-4c2b17647c07" data-ldr-template-token="{{ template_event_token }}" id="test-config-btn"><i aria-hidden="true" class="fas fa-play"></i> Test Embedding Model</button></div>diff --git a/src/local_deep_research/web/templates/pages/error.html b/src/local_deep_research/web/templates/pages/error.htmlindex f300116318..f493e367cb 100644--- a/src/local_deep_research/web/templates/pages/error.html+++ b/src/local_deep_research/web/templates/pages/error.html@@ -1,6 +1,7 @@<!DOCTYPE html><html lang="en"><head>+ <script nonce="{{ csp_nonce }}" data-template-token="{{ template_event_token }}" src="/static/js/security/template-events.js"></script><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>{{ error_title|default('Error') }} - Deep Research System</title>@@ -20,7 +21,7 @@<!-- Keep local styles --><link rel="stylesheet" href="/static/css/styles.css">- <style>+ <style nonce="{{ csp_nonce }}">body {min-height: 100vh;background: var(--bg-primary);diff --git a/src/local_deep_research/web/templates/pages/journal_quality.html b/src/local_deep_research/web/templates/pages/journal_quality.htmlindex 95ea7a5b91..301bc74484 100644--- a/src/local_deep_research/web/templates/pages/journal_quality.html+++ b/src/local_deep_research/web/templates/pages/journal_quality.html@@ -1,12 +1,12 @@{% extends "base.html" %}-{% from "components/help_macros.html" import tooltip, help_panel, help_step, help_tip %}+{% from "components/help_macros.html" import tooltip, help_panel, help_step, help_tip with context %}{% set active_page = 'journal-quality' %}{% block title %}Journal Quality - Deep Research System{% endblock %}{% block extra_head %}-<style>+<style nonce="{{ csp_nonce }}">.ldr-journal-quality-container { max-width: 1200px; margin: 0 auto; padding: 2rem; padding-bottom: 120px; }.ldr-metrics-header { background: var(--gradient-bg, var(--bg-secondary)); padding: 1.5rem; border-radius: 0.75rem; margin-bottom: 1.5rem; border: 1px solid var(--border-color); }.ldr-metrics-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 1.5rem; margin-bottom: 1.5rem; }@@ -174,8 +174,8 @@</div><input type="range" id="ldr-threshold-slider-top" min="1" max="10" step="1" value="2"style="width: 100%; cursor: pointer;"- oninput="onThresholdInput(this.value, 'top')"- onchange="onThresholdChange(this.value, 'top')">+ data-ldr-oninput="ldr-732c097d3bd6" data-ldr-template-token="{{ template_event_token }}"+ data-ldr-onchange="ldr-a501e656c944"><div style="display: flex; justify-content: space-between; font-size: 0.7rem; color: var(--text-secondary); margin-top: 0.25rem;"><span>1</span><span>2</span><span>3</span><span>4</span><span>5</span><span>6</span><span>7</span><span>8</span><span>9</span><span>10</span></div>@@ -183,7 +183,7 @@<!-- Filled by updateThresholdExplanation() --></div><div style="font-size: 0.72rem; color: var(--text-secondary); margin-top: 0.4rem;">- See the <a href="#" onclick="switchTab('how-it-works'); return false;" style="color: var(--accent-primary); text-decoration: none;">How It Works</a> tab for the full per-level breakdown.+ See the <a href="#" data-ldr-onclick="ldr-b656cf065727" data-ldr-template-token="{{ template_event_token }}" style="color: var(--accent-primary); text-decoration: none;">How It Works</a> tab for the full per-level breakdown.</div></div>@@ -200,7 +200,7 @@<div id="ldr-data-banner" style="display: none; margin-bottom: 1rem; padding: 1rem 1.5rem; border-radius: 0.75rem; border: 1px solid var(--border-color); background: var(--bg-secondary);"><div style="display: flex; align-items: center; justify-content: space-between; gap: 1rem;"><div id="ldr-data-banner-text" style="color: var(--text-secondary); font-size: 0.9rem;"></div>- <button id="ldr-data-download-btn" onclick="downloadJournalData()" style="padding: 0.5rem 1rem; border-radius: 0.375rem; border: 1px solid var(--accent-primary); background: var(--accent-primary); color: var(--text-on-accent); cursor: pointer; font-size: 0.85rem; white-space: nowrap;"></button>+ <button id="ldr-data-download-btn" data-ldr-onclick="ldr-b08cdb8752cf" data-ldr-template-token="{{ template_event_token }}" style="padding: 0.5rem 1rem; border-radius: 0.375rem; border: 1px solid var(--accent-primary); background: var(--accent-primary); color: var(--text-on-accent); cursor: pointer; font-size: 0.85rem; white-space: nowrap;"></button></div><div id="ldr-data-progress" style="display: none; margin-top: 0.75rem;"><div id="ldr-data-progress-intro" style="font-size: 0.8rem; color: var(--text-secondary); margin-bottom: 0.5rem;">Downloading...</div>@@ -231,9 +231,9 @@actually encountered in their searches, not a list of everyjournal in the bundled reference DB. --><div class="ldr-tab-bar">- <button class="ldr-tab-btn ldr-tab-active" data-tab="your-research" onclick="switchTab('your-research')">Your Research</button>- <button class="ldr-tab-btn" data-tab="global-db" onclick="switchTab('global-db')">Global Database</button>- <button class="ldr-tab-btn" data-tab="how-it-works" onclick="switchTab('how-it-works')">How It Works</button>+ <button class="ldr-tab-btn ldr-tab-active" data-tab="your-research" data-ldr-onclick="ldr-cdb29c0672c4" data-ldr-template-token="{{ template_event_token }}">Your Research</button>+ <button class="ldr-tab-btn" data-tab="global-db" data-ldr-onclick="ldr-b1788a1b608c" data-ldr-template-token="{{ template_event_token }}">Global Database</button>+ <button class="ldr-tab-btn" data-tab="how-it-works" data-ldr-onclick="ldr-1acd607f63be" data-ldr-template-token="{{ template_event_token }}">How It Works</button></div><!-- TAB: HOW IT WORKS -->@@ -315,8 +315,8 @@</div><input type="range" id="ldr-threshold-slider" min="1" max="10" step="1" value="2"style="width: 100%; cursor: pointer;"- oninput="onThresholdInput(this.value)"- onchange="onThresholdChange(this.value)">+ data-ldr-oninput="ldr-4a0c076b7987" data-ldr-template-token="{{ template_event_token }}"+ data-ldr-onchange="ldr-e590c2cc6eea"><div style="display: flex; justify-content: space-between; font-size: 0.7rem; color: var(--text-secondary); margin-top: 0.25rem;"><span>1</span><span>2</span><span>3</span><span>4</span><span>5</span><span>6</span><span>7</span><span>8</span><span>9</span><span>10</span></div>@@ -524,7 +524,7 @@#ldr-sources-banner near the top of the page. --></div>-<script>+<script nonce="{{ csp_nonce }}">/* ------------------------------------------------------------------ *//* State — server-side pagination, no client-side data array *//* ------------------------------------------------------------------ */@@ -1398,15 +1398,15 @@ function renderPagination() {const container = document.getElementById('ldr-pagination');if (totalPages <= 1) { container.innerHTML = ''; return; }- let html = `<button class="ldr-pagination-btn" onclick="goToPage(${currentPage-1})" ${currentPage===1?'disabled':''}>‹ Prev</button>`;+ let html = `<button class="ldr-pagination-btn" ${window.LDRTemplateEvents.attributes("ldr-a88460f4b0fb", [currentPage-1])} ${currentPage===1?'disabled':''}>‹ Prev</button>`;const maxButtons = 7;let startP = Math.max(1, currentPage - 3);let endP = Math.min(totalPages, startP + maxButtons - 1);if (endP - startP < maxButtons - 1) startP = Math.max(1, endP - maxButtons + 1);for (let i = startP; i <= endP; i++) {- html += `<button class="ldr-pagination-btn ${i===currentPage?'ldr-active':''}" onclick="goToPage(${i})">${i}</button>`;+ html += `<button class="ldr-pagination-btn ${i===currentPage?'ldr-active':''}" ${window.LDRTemplateEvents.attributes("ldr-a88460f4b0fb", [i])}>${i}</button>`;}- html += `<button class="ldr-pagination-btn" onclick="goToPage(${currentPage+1})" ${currentPage===totalPages?'disabled':''}>Next ›</button>`;+ html += `<button class="ldr-pagination-btn" ${window.LDRTemplateEvents.attributes("ldr-a88460f4b0fb", [currentPage+1])} ${currentPage===totalPages?'disabled':''}>Next ›</button>`;container.innerHTML = html;}diff --git a/src/local_deep_research/web/templates/pages/library.html b/src/local_deep_research/web/templates/pages/library.htmlindex 6c524eed60..4a84bea551 100644--- a/src/local_deep_research/web/templates/pages/library.html+++ b/src/local_deep_research/web/templates/pages/library.html@@ -1,5 +1,5 @@{% extends "base.html" %}-{% from "components/help_macros.html" import tooltip, help_panel, help_step, help_tip, help_card %}+{% from "components/help_macros.html" import tooltip, help_panel, help_step, help_tip, help_card with context %}{% set active_page = 'library' %}{% block title %}Research Library{% endblock %}@@ -15,7 +15,7 @@<div class="ldr-library-header"><h1>Research Library</h1><div class="ldr-header-actions">- <button class="btn btn-secondary" onclick="showSyncModal()" title="Check if files exist and sync with filesystem">+ <button class="btn btn-secondary" data-ldr-onclick="ldr-dbe8377a6a28" data-ldr-template-token="{{ template_event_token }}" title="Check if files exist and sync with filesystem"><i class="fas fa-sync"></i> Sync Library</button><div class="btn-group">@@ -25,13 +25,13 @@title="PDF storage is disabled. Click the storage mode button above to enable."data-toggle="tooltip"{% else %}- onclick="downloadAllNew()"+ data-ldr-onclick="ldr-9c5e3fe6429b" data-ldr-template-token="{{ template_event_token }}"title="Download PDF files from all your research sources and save to library"{% endif %}><i class="fas fa-file-pdf"></i> Get All Research PDFs</button><button class="btn btn-info"- onclick="downloadAllAsText()"+ data-ldr-onclick="ldr-77470237e7f1" data-ldr-template-token="{{ template_event_token }}"title="Extract text from all research sources without saving PDF files"><i class="fas fa-file-alt"></i> Text Only (from PDFs)</button>@@ -71,15 +71,15 @@<div class="ldr-status-item"><span class="ldr-status-label">{{ tooltip("PDF Storage:", "Database: Encrypted, most secure. Filesystem: Unencrypted files on disk - use only if you need external tool access. Text Only: Smallest footprint, no original PDFs kept.") }}</span>{% if pdf_storage_mode == 'database' %}- <button class="btn btn-sm btn-success" onclick="showStorageModeModal()" title="Click to change storage mode">+ <button class="btn btn-sm btn-success" data-ldr-onclick="ldr-f610ed2f650a" data-ldr-template-token="{{ template_event_token }}" title="Click to change storage mode"><i class="fas fa-database"></i> Database (Encrypted)</button>{% elif pdf_storage_mode == 'filesystem' %}- <button class="btn btn-sm btn-warning" onclick="showStorageModeModal()" title="Click to change storage mode">+ <button class="btn btn-sm btn-warning" data-ldr-onclick="ldr-f610ed2f650a" data-ldr-template-token="{{ template_event_token }}" title="Click to change storage mode"><i class="fas fa-hdd"></i> Filesystem (Unencrypted)</button>{% else %}- <button class="btn btn-sm btn-secondary" onclick="showStorageModeModal()" title="Click to change storage mode">+ <button class="btn btn-sm btn-secondary" data-ldr-onclick="ldr-f610ed2f650a" data-ldr-template-token="{{ template_event_token }}" title="Click to change storage mode"><i class="fas fa-file-alt"></i> Text Only</button>{% endif %}@@ -223,7 +223,7 @@<!-- Card Body --><div class="card-body" data-doc-action="open"><!-- Large action buttons -->- <div class="ldr-action-buttons" onclick="event.stopPropagation()">+ <div class="ldr-action-buttons" data-ldr-onclick="ldr-5e849f3930dc" data-ldr-template-token="{{ template_event_token }}">{% if doc.has_pdf %}<a href="/library/document/{{ doc.id }}/pdf" target="_blank" rel="noopener noreferrer" class="ldr-action-btn ldr-action-btn-pdf"><i class="fas fa-file-pdf"></i> View PDF@@ -273,7 +273,7 @@<!-- Research Info --><div class="ldr-research-info"><span class="ldr-research-link">- From: <a href="/results/{{ doc.research_id }}" onclick="event.stopPropagation()">+ From: <a href="/results/{{ doc.research_id }}" data-ldr-onclick="ldr-5e849f3930dc" data-ldr-template-token="{{ template_event_token }}">{{ doc.research_title|truncate(40) }}</a></span>@@ -384,16 +384,16 @@<p>Text content is always stored encrypted in your personal database.</p></div><div class="ldr-empty-state-actions">- <button class="btn btn-primary" onclick="window.location.href='/settings#research-library'">+ <button class="btn btn-primary" data-ldr-onclick="ldr-c1570cca83a9" data-ldr-template-token="{{ template_event_token }}"><i class="fas fa-cog"></i> Configure Library Settings</button>- <button class="btn btn-secondary" onclick="window.location.href='/library/download-manager'">+ <button class="btn btn-secondary" data-ldr-onclick="ldr-4b7d0f3a810f" data-ldr-template-token="{{ template_event_token }}"><i class="fas fa-download"></i> Download Manager</button></div>{% else %}<p>Start downloading PDFs from your research to build your library</p>- <button class="btn btn-primary" onclick="window.location.href='/library/download-manager'">+ <button class="btn btn-primary" data-ldr-onclick="ldr-4b7d0f3a810f" data-ldr-template-token="{{ template_event_token }}"><i class="fas fa-download"></i> Go to Download Manager</button>{% endif %}@@ -410,7 +410,7 @@<div class="ldr-pdf-header-actions"><button class="ldr-pdf-action-btn"{% if enable_pdf_storage %}- onclick="downloadCurrentPDF()"+ data-ldr-onclick="ldr-fa738477c7c3" data-ldr-template-token="{{ template_event_token }}"title="Download PDF"{% else %}disabled@@ -419,10 +419,10 @@{% endif %}><i class="fas fa-download"></i></button>- <button class="ldr-pdf-action-btn" onclick="openPDFInNewTab()" title="Open in new tab">+ <button class="ldr-pdf-action-btn" data-ldr-onclick="ldr-fdae34cefb54" data-ldr-template-token="{{ template_event_token }}" title="Open in new tab"><i class="fas fa-external-link-alt"></i></button>- <button class="ldr-pdf-close-btn" onclick="closePDFModal()" title="Close">+ <button class="ldr-pdf-close-btn" data-ldr-onclick="ldr-a77923e9b953" data-ldr-template-token="{{ template_event_token }}" title="Close"><i class="fas fa-times"></i></button></div>@@ -439,13 +439,13 @@<div class="ldr-pdf-modal-header"><h2 id="text-title" class="ldr-pdf-title">Text Viewer</h2><div class="ldr-pdf-header-actions">- <button class="ldr-pdf-action-btn" onclick="copyTextContent()" title="Copy to clipboard">+ <button class="ldr-pdf-action-btn" data-ldr-onclick="ldr-93611303c0ce" data-ldr-template-token="{{ template_event_token }}" title="Copy to clipboard"><i class="fas fa-copy"></i></button>- <button class="ldr-pdf-action-btn" onclick="downloadTextContent()" title="Download as .txt">+ <button class="ldr-pdf-action-btn" data-ldr-onclick="ldr-c5accacbff2a" data-ldr-template-token="{{ template_event_token }}" title="Download as .txt"><i class="fas fa-download"></i></button>- <button class="ldr-pdf-close-btn" onclick="closeTextModal()" title="Close">+ <button class="ldr-pdf-close-btn" data-ldr-onclick="ldr-d870f0b6fe62" data-ldr-template-token="{{ template_event_token }}" title="Close"><i class="fas fa-times"></i></button></div>@@ -474,8 +474,8 @@</div></div><div class="modal-footer">- <button class="btn btn-secondary" onclick="closeProgressModal()">Close</button>- <button class="btn btn-danger" onclick="cancelDownloads()">Cancel</button>+ <button class="btn btn-secondary" data-ldr-onclick="ldr-4ebaf419a72f" data-ldr-template-token="{{ template_event_token }}">Close</button>+ <button class="btn btn-danger" data-ldr-onclick="ldr-6251dc7d9ff9" data-ldr-template-token="{{ template_event_token }}">Cancel</button></div></div></div>@@ -487,7 +487,7 @@<div class="modal-content" style="max-width: 600px;"><div class="modal-header"><h2><i class="fas fa-sync"></i> Sync Library with Filesystem</h2>- <button class="close" onclick="closeSyncModal()">×</button>+ <button class="close" data-ldr-onclick="ldr-c3f334819492" data-ldr-template-token="{{ template_event_token }}">×</button></div><div class="modal-body"><div class="ldr-sync-explanation">@@ -536,21 +536,21 @@</div><div id="missing-files-action" class="ldr-alert ldr-alert-info" style="display: none; margin-top: 15px;"><p><strong>Missing files detected!</strong> These files have been marked in the database and can be re-downloaded.</p>- <button class="btn btn-primary" onclick="goToDownloadManager()">Go to Download Manager</button>+ <button class="btn btn-primary" data-ldr-onclick="ldr-dfa4c91ebf6a" data-ldr-template-token="{{ template_event_token }}">Go to Download Manager</button></div></div></div><div class="modal-footer">- <button id="sync-start-btn" class="btn btn-primary" onclick="performSync()">+ <button id="sync-start-btn" class="btn btn-primary" data-ldr-onclick="ldr-e70e663ac02c" data-ldr-template-token="{{ template_event_token }}"><i class="fas fa-play"></i> Start Sync</button>- <button id="sync-close-btn" class="btn btn-secondary" onclick="closeSyncModal()">Close</button>+ <button id="sync-close-btn" class="btn btn-secondary" data-ldr-onclick="ldr-c3f334819492" data-ldr-template-token="{{ template_event_token }}">Close</button></div></div></div>-<script>+<script nonce="{{ csp_nonce }}">// Store current PDF data globallylet currentPDFData = null;let documentViewerRequestId = 0;@@ -1308,7 +1308,7 @@ bindDocumentCardActions();<script defer src="/static/js/deletion/delete_manager.js"></script><!-- Semantic Search -->-<script>+<script nonce="{{ csp_nonce }}">var DEFAULT_LIBRARY_COLLECTION_ID = {{ (default_collection_id or '')|tojson }}; // nosemgrep: generic.html-templates.security.var-in-script-tag.var-in-script-tag, reason: Jinja tojson escapes HTML delimitersvar COLLECTIONS_DATA = {{ collections|tojson }}; // nosemgrep: generic.html-templates.security.var-in-script-tag.var-in-script-tag, reason: Jinja tojson escapes HTML delimiters</script>diff --git a/src/local_deep_research/web/templates/pages/link_analytics.html b/src/local_deep_research/web/templates/pages/link_analytics.htmlindex 6c462bdd87..e257e60d3c 100644--- a/src/local_deep_research/web/templates/pages/link_analytics.html+++ b/src/local_deep_research/web/templates/pages/link_analytics.html@@ -1,5 +1,5 @@{% extends "base.html" %}-{% from "components/help_macros.html" import tooltip, help_panel, help_step, help_tip %}+{% from "components/help_macros.html" import tooltip, help_panel, help_step, help_tip with context %}{% block title %}Link Analytics - Deep Research System{% endblock %}@@ -192,7 +192,7 @@</div><script src="/static/js/pages/link_analytics_render.js"></script>-<script>+<script nonce="{{ csp_nonce }}">let topDomainsChart = null;let domainDistributionChart = null;let sourceTypeChart = null;diff --git a/src/local_deep_research/web/templates/pages/metrics.html b/src/local_deep_research/web/templates/pages/metrics.htmlindex d21b5a1504..99d64aa647 100644--- a/src/local_deep_research/web/templates/pages/metrics.html+++ b/src/local_deep_research/web/templates/pages/metrics.html@@ -1,5 +1,5 @@{% extends "base.html" %}-{% from "components/help_macros.html" import tooltip, help_panel, help_step, help_tip, privacy_note %}+{% from "components/help_macros.html" import tooltip, help_panel, help_step, help_tip, privacy_note with context %}{% set active_page = 'metrics' %}{% block title %}Metrics Dashboard - Deep Research System{% endblock %}{% block extra_head %}@@ -87,7 +87,7 @@<!-- Primary Metrics --><div class="ldr-metrics-grid"><div class="ldr-metric-card ldr-expandable-card">- <div class="ldr-metric-main" id="token-toggle-btn" onclick="toggleTokenDetails()" role="button" tabindex="0" aria-expanded="false" onkeydown="if(event.key==='Enter'||event.key===' '){event.preventDefault();this.click();}">+ <div class="ldr-metric-main" id="token-toggle-btn" data-ldr-onclick="ldr-154c55d5fa77" data-ldr-template-token="{{ template_event_token }}" role="button" tabindex="0" aria-expanded="false" data-ldr-onkeydown="ldr-19b1027885b7"><div class="ldr-metric-icon"><i class="fas fa-coins"></i></div>@@ -179,7 +179,7 @@</div><div class="ldr-metric-value" id="avg-user-rating">-</div></div>- <div class="ldr-metric-card ldr-expandable-card" id="cost-toggle-btn" onclick="toggleCostDetails()" role="button" tabindex="0" aria-expanded="false" onkeydown="if(event.key==='Enter'||event.key===' '){event.preventDefault();this.click();}">+ <div class="ldr-metric-card ldr-expandable-card" id="cost-toggle-btn" data-ldr-onclick="ldr-1e59759d716e" data-ldr-template-token="{{ template_event_token }}" role="button" tabindex="0" aria-expanded="false" data-ldr-onkeydown="ldr-19b1027885b7"><div class="ldr-metric-icon"><i class="fas fa-dollar-sign"></i></div>@@ -530,7 +530,7 @@</div>{% endblock %}{% block component_scripts %}-<script>+<script nonce="{{ csp_nonce }}">// Metrics Dashboard JavaScript(function() {let metricsData = null;diff --git a/src/local_deep_research/web/templates/pages/news-subscription-form.html b/src/local_deep_research/web/templates/pages/news-subscription-form.htmlindex 5129875dda..bc5d1ed412 100644--- a/src/local_deep_research/web/templates/pages/news-subscription-form.html+++ b/src/local_deep_research/web/templates/pages/news-subscription-form.html@@ -180,7 +180,7 @@</div><script defer src="/static/js/components/custom_dropdown.js"></script>-<script>+<script nonce="{{ csp_nonce }}">// Global variableslet currentProvider = {{ (subscription.model_provider if subscription else default_settings.model_provider) | tojson }};let defaultModel = {{ (subscription.model if subscription else default_settings.model) | tojson }};diff --git a/src/local_deep_research/web/templates/pages/news.html b/src/local_deep_research/web/templates/pages/news.htmlindex 76b81ab841..ba12dc7930 100644--- a/src/local_deep_research/web/templates/pages/news.html+++ b/src/local_deep_research/web/templates/pages/news.html@@ -1,6 +1,6 @@{% extends "base.html" %}{% from "components/custom_dropdown.html" import render_dropdown %}-{% from "components/help_macros.html" import tooltip, help_panel, help_step, help_tip %}+{% from "components/help_macros.html" import tooltip, help_panel, help_step, help_tip with context %}{% set active_page = 'news' %}{% block title %}LDR News - AI-Powered Research Feed{% endblock %}@@ -124,31 +124,31 @@<!-- News Templates --><h3><i aria-hidden="true" class="bi bi-table"></i> News Templates</h3><div class="ldr-news-templates">- <button class="ldr-template-btn" onclick="useNewsTemplate('breaking-news')">+ <button class="ldr-template-btn" data-ldr-onclick="ldr-ecc80a8a9227" data-ldr-template-token="{{ template_event_token }}"><i aria-hidden="true" class="bi bi-newspaper"></i><span>Breaking News Table</span></button>- <button class="ldr-template-btn" onclick="useNewsTemplate('market-analysis')">+ <button class="ldr-template-btn" data-ldr-onclick="ldr-561feb93281e" data-ldr-template-token="{{ template_event_token }}"><i aria-hidden="true" class="bi bi-graph-up-arrow"></i><span>Market Analysis</span></button>- <button class="ldr-template-btn" onclick="useNewsTemplate('tech-updates')">+ <button class="ldr-template-btn" data-ldr-onclick="ldr-a016548a6d9d" data-ldr-template-token="{{ template_event_token }}"><i aria-hidden="true" class="bi bi-cpu"></i><span>Tech Updates</span></button>- <button class="ldr-template-btn" onclick="useNewsTemplate('local-news')">+ <button class="ldr-template-btn" data-ldr-onclick="ldr-bebfdb3bdf5e" data-ldr-template-token="{{ template_event_token }}"><i aria-hidden="true" class="bi bi-geo-alt"></i><span>Local News</span></button>- <button class="ldr-template-btn" onclick="useNewsTemplate('topic-news')">+ <button class="ldr-template-btn" data-ldr-onclick="ldr-ba74d1613374" data-ldr-template-token="{{ template_event_token }}"><i aria-hidden="true" class="bi bi-bookmark-ldr-star"></i><span>Topic News</span></button>- <button class="ldr-template-btn" onclick="useNewsTemplate('product-prices')">+ <button class="ldr-template-btn" data-ldr-onclick="ldr-66604a98bfa8" data-ldr-template-token="{{ template_event_token }}"><i aria-hidden="true" class="bi bi-tag"></i><span>Product Prices</span></button>- <button class="ldr-template-btn" onclick="useNewsTemplate('custom')">+ <button class="ldr-template-btn" data-ldr-onclick="ldr-4194a142f077" data-ldr-template-token="{{ template_event_token }}"><i aria-hidden="true" class="bi bi-pencil-square"></i><span>Custom Template</span></button>@@ -162,7 +162,7 @@<h3 class="mt-4 d-flex justify-content-between align-items-center"><span><i aria-hidden="true" class="bi bi-clock-history"></i> Recent Searches</span>- <button class="btn btn-sm btn-outline-secondary" onclick="clearSearchHistory()" title="Clear search history" aria-label="Clear search history">+ <button class="btn btn-sm btn-outline-secondary" data-ldr-onclick="ldr-07597121e78c" data-ldr-template-token="{{ template_event_token }}" title="Clear search history" aria-label="Clear search history"><i aria-hidden="true" class="bi bi-trash"></i></button></h3>@@ -261,7 +261,7 @@<h5 class="modal-title"><i aria-hidden="true" class="bi bi-bell-fill"></i> Create News Subscription</h5><button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button></div>- <form id="news-subscription-form" onsubmit="handleNewsSubscriptionSubmit(event)">+ <form id="news-subscription-form" data-ldr-onsubmit="ldr-a3bb8d0e0519" data-ldr-template-token="{{ template_event_token }}"><div class="modal-body"><div class="mb-3"><label for="news-subscription-query" class="form-label">Search Query</label>diff --git a/src/local_deep_research/web/templates/pages/note_detail.html b/src/local_deep_research/web/templates/pages/note_detail.htmlindex 1572ed85b0..adacc4cd0f 100644--- a/src/local_deep_research/web/templates/pages/note_detail.html+++ b/src/local_deep_research/web/templates/pages/note_detail.html@@ -6,7 +6,7 @@{% block extra_head %}<link rel="stylesheet" href="/static/css/notes.css">-<style>+<style nonce="{{ csp_nonce }}">.ldr-note-detail-container {max-width: 1200px;margin: 0 auto;@@ -1973,7 +1973,7 @@{% block page_scripts %}<!-- Note: url-validator.js, ui.js, urls.js, formatting.js, api.js are already loaded in base.html -->-<script>+<script nonce="{{ csp_nonce }}">// Pass note ID to JavaScriptwindow.noteId = {{ note_id | tojson }}; // nosemgrep: generic.html-templates.security.var-in-script-tag.var-in-script-tag, reason: Jinja tojson escapes HTML delimiters</script>diff --git a/src/local_deep_research/web/templates/pages/research.html b/src/local_deep_research/web/templates/pages/research.htmlindex c6874a942c..c58b6c20db 100644--- a/src/local_deep_research/web/templates/pages/research.html+++ b/src/local_deep_research/web/templates/pages/research.html@@ -1,6 +1,6 @@{% extends "base.html" %}{% from "components/custom_dropdown.html" import render_dropdown %}-{% from "components/help_macros.html" import tooltip, help_panel, help_step, help_tip, label_with_tooltip %}+{% from "components/help_macros.html" import tooltip, help_panel, help_step, help_tip, label_with_tooltip with context %}{% set active_page = 'new-research' %}@@ -117,7 +117,7 @@The data-scope attribute is updated by JS on dropdown change;CSS below colors the frame so the active scopeis instantly recognizable without reading the dropdown value. -->- <style>+ <style nonce="{{ csp_nonce }}">/* Default panel = neutral slate. BOTH no longer wearsan amber "warning" border at the panel level — the"Public search egress enabled" banner does that jobdiff --git a/src/local_deep_research/web/templates/pages/results.html b/src/local_deep_research/web/templates/pages/results.htmlindex 14026dd2fa..ae009b97cb 100644--- a/src/local_deep_research/web/templates/pages/results.html+++ b/src/local_deep_research/web/templates/pages/results.html@@ -1,5 +1,5 @@{% extends "base.html" %}-{% from "components/help_macros.html" import tooltip %}+{% from "components/help_macros.html" import tooltip with context %}{% block title %}Research Results - Deep Research System{% endblock %}@@ -10,7 +10,7 @@<div class="ldr-results-header"><h1 class="ldr-page-title">Research Results</h1><div class="ldr-results-actions">- <button class="btn btn-primary" id="ask-followup-btn" onclick="window.followUpResearch ? followUpResearch.showFollowUpModal() : alert('Follow-up feature loading...')" title="Ask a follow-up question using this research's sources and context"><i aria-hidden="true" class="fas fa-question-circle"></i> Ask Follow-up Question</button>+ <button class="btn btn-primary" id="ask-followup-btn" title="Ask a follow-up question using this research's sources and context"><i aria-hidden="true" class="fas fa-question-circle"></i> Ask Follow-up Question</button><button class="btn ldr-btn-outline" id="view-metrics-btn" title="View token usage and cost metrics for this research session"><i aria-hidden="true" class="fas fa-chart-bar"></i> View Metrics</button><button class="btn ldr-btn-outline" id="download-pdf-btn" title="Download as PDF document for sharing or printing"><i aria-hidden="true" class="fas fa-file-pdf"></i> Download PDF</button><div class="dropdown d-inline-block">diff --git a/src/local_deep_research/web/templates/pages/star_reviews.html b/src/local_deep_research/web/templates/pages/star_reviews.htmlindex 8097abf600..197a866308 100644--- a/src/local_deep_research/web/templates/pages/star_reviews.html+++ b/src/local_deep_research/web/templates/pages/star_reviews.html@@ -1,5 +1,5 @@{% extends "base.html" %}-{% from "components/help_macros.html" import tooltip, help_panel, help_step, help_tip, privacy_note %}+{% from "components/help_macros.html" import tooltip, help_panel, help_step, help_tip, privacy_note with context %}{% block title %}Star Reviews Analytics{% endblock %}@@ -228,7 +228,7 @@</div></div>-<script>+<script nonce="{{ csp_nonce }}">let llmChart, searchEngineChart, trendsChart, doughnutChart, modeChart, llmBreakdownChart, qualityRadarChart;let starReviewsRequestId = 0;diff --git a/src/local_deep_research/web/templates/pages/subscriptions.html b/src/local_deep_research/web/templates/pages/subscriptions.htmlindex a8c685c1dc..37aae297e5 100644--- a/src/local_deep_research/web/templates/pages/subscriptions.html+++ b/src/local_deep_research/web/templates/pages/subscriptions.html@@ -1,12 +1,12 @@{% extends "base.html" %}-{% from "components/help_macros.html" import tooltip, help_panel, help_step, help_tip %}+{% from "components/help_macros.html" import tooltip, help_panel, help_step, help_tip with context %}{% set active_page = 'subscriptions' %}{% block title %}Manage News Subscriptions - LDR{% endblock %}{% block extra_head %}<link rel="stylesheet" href="/static/css/subscriptions.css">-<style>+<style nonce="{{ csp_nonce }}">/* Theme-aware modal and form styles */.modal-content {background-color: var(--bg-secondary);diff --git a/src/local_deep_research/web/templates/pages/zotero.html b/src/local_deep_research/web/templates/pages/zotero.htmlindex 9de7a9e6ba..3821bd5c95 100644--- a/src/local_deep_research/web/templates/pages/zotero.html+++ b/src/local_deep_research/web/templates/pages/zotero.html@@ -3,7 +3,7 @@{% block title %}Zotero - Local Deep Research{% endblock %}{% block extra_head %}-<style>+<style nonce="{{ csp_nonce }}">.ldr-zotero-wrap { max-width: 960px; margin: 0 auto; padding: 20px; }.ldr-zotero-card {background: var(--card-bg);@@ -228,7 +228,7 @@ table.ldr-zotero-table th, table.ldr-zotero-table td {</div></div>-<script>+<script nonce="{{ csp_nonce }}">(function () {const csrf = document.querySelector('meta[name="csrf-token"]')?.content || '';const msg = document.getElementById('zotero-msg');diff --git a/src/local_deep_research/web/utils/csp.py b/src/local_deep_research/web/utils/csp.pynew file mode 100644index 0000000000..c2c498e3fa--- /dev/null+++ b/src/local_deep_research/web/utils/csp.py@@ -0,0 +1,22 @@+"""Per-response authorizations for trusted templates and their UI bindings."""++from dataclasses import dataclass+import secrets+++@dataclass(frozen=True)+class TemplateSecurityContext:+ nonce: str+ event_token: str+++def template_security_context(scope: dict) -> TemplateSecurityContext:+ """Keep request state on the request scope, outside shared app state."""+ context = scope.get("_ldr_template_security")+ if not isinstance(context, TemplateSecurityContext):+ context = TemplateSecurityContext(+ nonce=secrets.token_urlsafe(32),+ event_token=secrets.token_urlsafe(32),+ )+ scope["_ldr_template_security"] = context+ return contextdiff --git a/tests/js/followup.test.js b/tests/js/followup.test.jsindex 48bd22d826..f8b9ebaa5b 100644--- a/tests/js/followup.test.js+++ b/tests/js/followup.test.js@@ -262,8 +262,10 @@ describe('FollowUpResearch browser lifecycle and failure recovery', () => {expect(followup.modalElement.id).toBe('followUpModal');expect(followup.getStartButton()).toBe(followup.modalElement.querySelector('.modal-footer .btn-primary'));- expect(followup.getStartButton().getAttribute('onclick'))- .toBe('followUpResearch.submitFollowUp()');+ expect(followup.getStartButton().hasAttribute('onclick')).toBe(false);+ followup.submitFollowUp = vi.fn();+ followup.getStartButton().click();+ expect(followup.submitFollowUp).toHaveBeenCalledOnce();expect(window.ui.clearInlineError).toHaveBeenCalledWith('followup-error-container');expect(document.querySelectorAll('#followup-modal-styles')).toHaveLength(1);diff --git a/tests/js/pages/link-analytics-bootstrap-runtime.test.js b/tests/js/pages/link-analytics-bootstrap-runtime.test.jsindex b3ddfdbe86..c4682bd4c1 100644--- a/tests/js/pages/link-analytics-bootstrap-runtime.test.js+++ b/tests/js/pages/link-analytics-bootstrap-runtime.test.js@@ -16,7 +16,7 @@ const RENDER_SOURCE = readFileSync(RENDER_PATH, 'utf8');function extractInlineBootstrap() {const match = TEMPLATE_SOURCE.match(- /<script>\s*(let topDomainsChart[\s\S]*?)<\/script>/,+ /<script\b[^>]*>\s*(let topDomainsChart[\s\S]*?)<\/script>/,);if (!match) throw new Error('Link Analytics inline bootstrap not found');return match[1];diff --git a/tests/js/pages/news-localstorage-xss.test.js b/tests/js/pages/news-localstorage-xss.test.jsindex 0479d58078..5756d70b8d 100644--- a/tests/js/pages/news-localstorage-xss.test.js+++ b/tests/js/pages/news-localstorage-xss.test.js@@ -256,25 +256,14 @@ describe('pages/news.js — saved_news_items localStorage re-hydration XSS', ()// no inline handlers of its own, so any on* attribute under a card is// a finding.//- // Scoped to the cards, NOT the whole feed container: renderNewsItems- // also calls updateBulkActionsBar (news.js:1652), which prepends a- // sibling .ldr-bulk-actions-bar into #news-feed-content carrying three- // static onclick="markAllAsRead()" / "expandAll()" / "collapseAll()"- // buttons. That template interpolates only ${unreadCount} and- // ${totalCount} -- both Array#filter/#length results, never strings --- // so no attacker-controlled byte can reach those attributes. Every- // attacker-controlled field in this fixture lands inside a- // .ldr-news-item, which is exactly what is asserted on here.+ // Both cards and their sibling bulk controls use registered listeners.const cards = [...container.querySelectorAll('.ldr-news-item')];expect(cards.length).toBeGreaterThan(0);for (const cardEl of cards) {expect(onHandlerAttributes(cardEl)).toEqual([]);}- // Pin the non-card remainder too, by VALUE rather than by count: the- // only on* attributes outside the cards must be the bulk bar's three- // fixed, argument-less verbs. Any new handler, or any handler that- // grows an interpolated argument list, fails this.+ // Keep the non-card controls free of executable attributes too.const nonCardHandlerValues = [];for (const el of container.querySelectorAll('*')) {if (el.closest('.ldr-news-item')) continue;@@ -282,9 +271,7 @@ describe('pages/news.js — saved_news_items localStorage re-hydration XSS', ()if (/^on/i.test(name)) nonCardHandlerValues.push(el.getAttribute(name));}}- expect(nonCardHandlerValues.sort()).toEqual([- 'collapseAll()', 'expandAll()', 'markAllAsRead()',- ]);+ expect(nonCardHandlerValues).toEqual([]);// Post-parse DOM: nothing executable, payload visible as text.inertContainerAssertions(container);diff --git a/tests/js/pages/zotero-runtime.test.js b/tests/js/pages/zotero-runtime.test.jsindex 6e9af5db37..97f6c0e97f 100644--- a/tests/js/pages/zotero-runtime.test.js+++ b/tests/js/pages/zotero-runtime.test.js@@ -9,7 +9,7 @@ const TEMPLATE_PATH = resolve();const template = readFileSync(TEMPLATE_PATH, 'utf8');const scriptMatch = template.match(- /<script>\s*(\(function \(\) \{[\s\S]*?\}\)\(\);)\s*<\/script>/,+ /<script\b[^>]*>\s*(\(function \(\) \{[\s\S]*?\}\)\(\);)\s*<\/script>/,);function config(overrides = {}) {diff --git a/tests/js/security/template-events.test.js b/tests/js/security/template-events.test.jsnew file mode 100644index 0000000000..d2587ecd80--- /dev/null+++ b/tests/js/security/template-events.test.js@@ -0,0 +1,139 @@+/** Runtime checks for the trusted template event boundary. */+import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';+import { Window } from 'happy-dom';++const SOURCE = readFileSync(resolve(+ __dirname, '../../../src/local_deep_research/web/static/js/security/template-events.js',+), 'utf8');+const TOKEN = 'a'.repeat(43);+const NONCE = 'b'.repeat(43);+let page;++function load(token = TOKEN, nonce = NONCE) {+ page = new Window();+ const script = page.document.createElement('script');+ script.setAttribute('data-template-token', token);+ script.nonce = nonce;+ Object.defineProperty(page.document, 'currentScript', {value: script});+ page.eval(SOURCE);+ page.document.dispatchEvent(new page.Event('DOMContentLoaded'));+ return page.LDRTemplateEvents;+}++async function flush() {+ await new Promise(resolveTick => setTimeout(resolveTick, 0));+}++function button(id, token = TOKEN) {+ const element = page.document.createElement('button');+ element.setAttribute('data-ldr-onclick', id);+ if (token !== null) element.setAttribute('data-ldr-template-token', token);+ page.document.body.appendChild(element);+ return element;+}++afterEach(async () => {+ await page?.happyDOM.close();+});++it('binds newly inserted controls once and keeps the element receiver', async () => {+ load();+ const parent = page.document.createElement('div');+ page.document.body.appendChild(parent);+ const close = button('ldr-d7e9771cf24b');+ parent.appendChild(close);+ await flush();+ page.document.dispatchEvent(new page.Event('DOMContentLoaded'));+ close.setAttribute('data-ldr-onclick', 'ldr-d7e9771cf24b');+ await flush();+ close.click();+ expect(parent.style.display).toBe('none');+});++it.each([null, 'c'.repeat(43), ''])('ignores a control with a different authorization (%s)', async token => {+ load();+ page.clearAllFilters = vi.fn();+ const control = button('ldr-579596525a9b', token);+ await flush();+ control.click();+ expect(page.clearAllFilters).not.toHaveBeenCalled();+});++it('rechecks authorization at dispatch and can recover after it is restored', async () => {+ load();+ page.clearAllFilters = vi.fn();+ const control = button('ldr-579596525a9b');+ await flush();+ control.setAttribute('data-ldr-template-token', 'c'.repeat(43));+ control.click();+ expect(page.clearAllFilters).not.toHaveBeenCalled();+ control.setAttribute('data-ldr-template-token', TOKEN);+ await flush();+ control.click();+ expect(page.clearAllFilters).toHaveBeenCalledOnce();+});++it('carries ordinary punctuation as data without adding attributes or nodes', async () => {+ const events = load();+ page.goToPage = vi.fn();+ const value = 'A "quoted" <label> & 50%';+ const template = page.document.createElement('template');+ // eslint-disable-next-line no-unsanitized/property -- exercises the real attribute encoder with synthetic punctuation, then inspects the parsed DOM.+ template.innerHTML = `<button ${events.attributes('ldr-a88460f4b0fb', [value])}></button>`;+ const control = template.content.firstElementChild;+ page.document.body.appendChild(control);+ await flush();+ control.click();+ expect(page.goToPage).toHaveBeenCalledExactlyOnceWith(value);+ expect([...control.attributes].map(attribute => attribute.name).sort()).toEqual([+ 'data-ldr-onclick', 'data-ldr-onclick-args', 'data-ldr-template-token',+ ]);+ expect(control.childNodes).toHaveLength(0);+});++it.each(['%', '%7B%7D', 'null'])('does not dispatch malformed or non-array argument data (%s)', async data => {+ load();+ page.goToPage = vi.fn();+ const control = button('ldr-a88460f4b0fb');+ control.setAttribute('data-ldr-onclick-args', data);+ await flush();+ control.click();+ expect(page.goToPage).not.toHaveBeenCalled();+});++it('keeps keyboard activation and return-false link behavior', async () => {+ load();+ page.showSchedulerInfo = vi.fn();+ const control = button('ldr-8b7c364b086d');+ control.setAttribute('data-ldr-onkeydown', 'ldr-19b1027885b7');+ await flush();+ const keyboard = new page.KeyboardEvent('keydown', {key: 'Enter', cancelable: true});+ control.dispatchEvent(keyboard);+ expect(keyboard.defaultPrevented).toBe(true);+ expect(page.showSchedulerInfo).toHaveBeenCalledOnce();+ const click = new page.MouseEvent('click', {cancelable: true});+ control.dispatchEvent(click);+ expect(click.defaultPrevented).toBe(true);+ expect(page.showSchedulerInfo).toHaveBeenCalledTimes(2);+});++it('rejects unknown action names, duplicate registration, and unsupported events', () => {+ const events = load();+ expect(() => events.attributes('missing')).toThrow('Invalid template action arguments');+ expect(() => events.attributes('ldr-579596525a9b', {})).toThrow('Invalid template action arguments');+ expect(() => events.register('ldr-579596525a9b', 'click', () => {})).toThrow();+ expect(() => events.register('ldr-000000000000', 'load', () => {})).toThrow();+ expect(Object.isFrozen(events)).toBe(true);+ expect(events.styleNonce).toBe(NONCE);+});++it('leaves bindings inert when the loader authorization is invalid', async () => {+ const events = load('invalid', 'invalid');+ page.clearAllFilters = vi.fn();+ const control = button('ldr-579596525a9b', 'invalid');+ await flush();+ control.click();+ expect(page.clearAllFilters).not.toHaveBeenCalled();+ expect(events.styleNonce).toBe('');+});diff --git a/tests/js/services/pdf-canvas-nonce.test.js b/tests/js/services/pdf-canvas-nonce.test.jsnew file mode 100644index 0000000000..f3c80658b5--- /dev/null+++ b/tests/js/services/pdf-canvas-nonce.test.js@@ -0,0 +1,94 @@+/** The canvas adapter authorizes only the synchronous renderer phase. */+import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';+import { Window } from 'happy-dom';++const SOURCE = readFileSync(resolve(+ __dirname, '../../../src/local_deep_research/web/static/js/services/pdf.js',+), 'utf8');+const NONCE = 'n'.repeat(43);+let page;+let target;+let trusted;+let untrusted;++beforeEach(() => {+ page = new Window();+ page.LDRTemplateEvents = Object.freeze({styleNonce: NONCE});+ page.eval(SOURCE);+ target = page.document.createElement('div');+ trusted = page.document.createElement('style');+ trusted.nonce = NONCE;+ untrusted = page.document.createElement('style');+ page.document.head.append(trusted, untrusted);+ page.document.body.appendChild(target);+});++afterEach(async () => {+ await page.happyDOM.close();+});++it('preserves renderer arguments, authorized style copies and fresh styles', () => {+ const originalCreate = page.document.createElement;+ const trustedClone = trusted.cloneNode;+ const untrustedClone = untrusted.cloneNode;+ const options = {scale: 2};+ const result = {};+ const renderer = vi.fn((element, settings) => {+ expect(element).toBe(target);+ expect(settings).toBe(options);+ expect(trusted.cloneNode(false).nonce).toBe(NONCE);+ expect(untrusted.cloneNode(false).nonce).toBeFalsy();+ expect(page.document.createElement('style').nonce).toBe(NONCE);+ expect(page.document.createElement('script').nonce).toBeFalsy();+ return result;+ });+ expect(page.renderPDFCanvas(renderer, target, options)).toBe(result);+ expect(renderer).toHaveBeenCalledOnce();+ expect(page.document.createElement).toBe(originalCreate);+ expect(trusted.cloneNode).toBe(trustedClone);+ expect(untrusted.cloneNode).toBe(untrustedClone);+});++it('restores method descriptors before an asynchronous renderer settles', async () => {+ const documentDescriptor = Object.getOwnPropertyDescriptor(page.document, 'createElement');+ const styleDescriptor = Object.getOwnPropertyDescriptor(trusted, 'cloneNode');+ let complete;+ const pending = new Promise(resolveRender => { complete = resolveRender; });+ expect(page.renderPDFCanvas(() => pending, target, {})).toBe(pending);+ expect(Object.getOwnPropertyDescriptor(page.document, 'createElement')).toEqual(documentDescriptor);+ expect(Object.getOwnPropertyDescriptor(trusted, 'cloneNode')).toEqual(styleDescriptor);+ expect(page.document.createElement('style').nonce).toBeFalsy();+ complete();+ await pending;+});++it('restores methods after a synchronous renderer failure', () => {+ const originalCreate = page.document.createElement;+ const originalClone = trusted.cloneNode;+ expect(() => page.renderPDFCanvas(() => { throw new Error('fixture failure'); }, target, {})).toThrow('fixture failure');+ expect(page.document.createElement).toBe(originalCreate);+ expect(trusted.cloneNode).toBe(originalClone);+ expect(page.document.createElement('style').nonce).toBeFalsy();+});++it('keeps nested renderer invocations within their own cleanup boundaries', () => {+ const originalCreate = page.document.createElement;+ page.renderPDFCanvas(() => {+ const outerCreate = page.document.createElement;+ page.renderPDFCanvas(() => {+ expect(page.document.createElement('style').nonce).toBe(NONCE);+ }, target, {});+ expect(page.document.createElement).toBe(outerCreate);+ }, target, {});+ expect(page.document.createElement).toBe(originalCreate);+});++it('does not add authorizations without a valid loader context', () => {+ page.LDRTemplateEvents = {styleNonce: ''};+ const originalCreate = page.document.createElement;+ page.renderPDFCanvas(() => {+ expect(page.document.createElement).toBe(originalCreate);+ expect(page.document.createElement('style').nonce).toBeFalsy();+ }, target, {});+});diff --git a/tests/js/services/theme-bootstrap-runtime.test.js b/tests/js/services/theme-bootstrap-runtime.test.jsindex 3a66871d7b..0c19a60050 100644--- a/tests/js/services/theme-bootstrap-runtime.test.js+++ b/tests/js/services/theme-bootstrap-runtime.test.js@@ -13,7 +13,10 @@ const defaultTheme = JSON.parse(readFileSync(resolve(const metadata = Object.fromEntries(['system', 'light', 'hashed', 'sepia', 'nord'].map(id => [id, { label: id }]));// Supply only the server-rendered values; execute the checked-in browser logic.-const bootstrap = template.match(/<script>([\s\S]*?)<\/script>/)[1]+// Read inert source text: parsing a full document can load its stylesheets.+const bootstrap = Array.from(+ template.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/g),+).find(([, attributes]) => !/(?:^|\s)src\s*=/.test(attributes))[2].replace('{{ get_themes_json() }}', JSON.stringify(Object.keys(metadata))).replace('{{ get_theme_metadata() }}', JSON.stringify(metadata)).replace('{{ session.username|default("anonymous", true)|tojson }}', JSON.stringify('reader'));diff --git a/tests/js/setup.js b/tests/js/setup.jsindex 995b91d3b2..8d224789ee 100644--- a/tests/js/setup.js+++ b/tests/js/setup.js@@ -52,6 +52,11 @@ import '@js/components/notes_shared.js';// need a custom buildTieredResults still reassign window.SemanticSearch.import '@js/components/semantic_search.js';+// The base template loads the action registry before every page script.+// Unit fixtures have no response authorization; binding behavior is exercised+// separately with explicit per-document tokens in template-events.test.js.+import '@js/security/template-events.js';+// Shared byte-size formatter (window.formatBytes) — in production,// collection_details.js and delete_manager.js are emitted from// {% block content %}, which base.html renders BEFORE its own shareddiff --git a/tests/security/test_client_side_xss_sinks.py b/tests/security/test_client_side_xss_sinks.pyindex 4b53aff154..7eed29c40f 100644--- a/tests/security/test_client_side_xss_sinks.py+++ b/tests/security/test_client_side_xss_sinks.py@@ -438,6 +438,7 @@ def test_eslint_escape_allow_list_is_name_based_and_pinned():"window.escapeHtml","window.sanitizeHtml","window.XSSProtection.escapeHtml",+ "window.LDRTemplateEvents.attributes",}@@ -586,12 +587,11 @@ def test_context_overflow_rows_reach_innerhtml_without_sanitisation():assert "<" not in ATTR_BREAKOUT and ">" not in ATTR_BREAKOUT-def test_inline_event_handlers_are_permitted_by_the_csp():- """Attribute injection is not blunted by the shipped CSP."""+def test_inline_event_handlers_are_refused_by_the_csp():+ """Keep the attribute policy explicit alongside the sink census."""app = (SRC / "web" / "fastapi_app.py").read_text(encoding="utf-8")- assert "script-src 'self' 'unsafe-inline'; " in app, (- "CSP changed — re-grade the attribute-injection findings"- )+ assert "script-src-attr 'none'; " in app+ assert "script-src 'self' 'unsafe-inline'" not in app# ---------------------------------------------------------------------diff --git a/tests/security/test_injection_and_template_safety.py b/tests/security/test_injection_and_template_safety.pyindex 018ee81681..3ad077cd26 100644--- a/tests/security/test_injection_and_template_safety.py+++ b/tests/security/test_injection_and_template_safety.py@@ -36,7 +36,7 @@ import refrom pathlib import Pathimport pytest-from jinja2 import Environment+from jinja2 import Environment, TemplateSyntaxError, nodesfrom markupsafe import MarkupREPO_ROOT = Path(__file__).resolve().parents[2]@@ -854,7 +854,13 @@ def test_theme_json_escapes_metadata_before_inline_render(monkeypatch, payload):assert all(char not in value for char in "<>&'")source = (TEMPLATES / "base.html").read_text(encoding="utf-8")- script = re.search(r"<script>.*?</script>", source, re.DOTALL).group()+ script = next(+ match.group()+ for match in re.finditer(+ r"<script\b([^>]*)>.*?</script>", source, re.DOTALL+ )+ if not re.search(r"(?:^|\s)src\s*=", match.group(1))+ )rendered = (Environment(autoescape=True).from_string(script)@@ -960,20 +966,46 @@ def test_plain_interpolation_in_a_script_body_is_html_escaped():assert "<svg" not in body-_TOJSON_ATTR_RE = re.compile(r"=\s*\"\{\{[^}]*\|\s*tojson[^}]*\}\}\"")+_TOJSON_ATTR_RE = re.compile(+ r'=\s*"\{\{(?P<expression>[^}]*\|\s*tojson[^}]*)\}\}"'+)+++def _expression_is_uri_encoded(expression: str) -> bool:+ """Require encoding to apply to the whole attribute expression."""+ try:+ output = (+ Environment(autoescape=True).parse("{{" + expression + "}}").body[0]+ )+ except TemplateSyntaxError:+ return False+ if not isinstance(output, nodes.Output) or len(output.nodes) != 1:+ return False+ value = output.nodes[0]+ return (+ isinstance(value, nodes.Filter)+ and value.name == "urlencode"+ and not value.args+ and not value.kwargs+ and value.dyn_args is None+ and value.dyn_kwargs is None+ )def find_tojson_in_attribute(text: str) -> list[int]:"""Find ``|tojson`` used as a double-quoted attribute value.``tojson`` escapes ``<``, ``>``, ``&`` and ``'`` but *not* ``"``,- and its output is Markup so autoescape skips it. The JSON string- delimiters therefore land raw inside the attribute.+ and its output is Markup so autoescape skips it. Require an outer+ URI encoder to protect the JSON delimiters in a double-quoted attribute."""return [numberfor number, line in enumerate(text.splitlines(), start=1)- if _TOJSON_ATTR_RE.search(line)+ if any(+ not _expression_is_uri_encoded(match.group("expression"))+ for match in _TOJSON_ATTR_RE.finditer(line)+ )]@@ -990,8 +1022,46 @@ def test_tojson_attribute_scanner_is_quiet_on_script_use():assert find_tojson_in_attribute(safe) == []+ "expression,expected",+ [+ ("value|tojson|urlencode", []),+ ("value|urlencode|tojson", [1]),+ ("(value|tojson|urlencode) ~ value", [1]),+ ("value|tojson if condition else value|tojson|urlencode", [1]),+ ],+)+def test_tojson_attribute_scanner_requires_terminal_encoding(+ expression, expected+):+ source = '<div data-args="{{ ' + expression + ' }}"></div>'+ assert find_tojson_in_attribute(source) == expected+++def test_uri_encoded_json_round_trips_as_one_attribute():+ from html.parser import HTMLParser+ from urllib.parse import unquote++ class AttributeCollector(HTMLParser):+ def handle_starttag(self, tag, attrs):+ self.attributes = attrs++ value = ['"quoted" <tag> & \' π', {"label": "ordinary value"}]+ rendered = (+ Environment(autoescape=True)+ .from_string('<div data-args="{{ value|tojson|urlencode }}"></div>')+ .render(value=value)+ )+ parser = AttributeCollector()+ parser.feed(rendered)+ assert len(parser.attributes) == 1+ name, encoded = parser.attributes[0]+ assert name == "data-args"+ assert json.loads(unquote(encoded)) == value++def test_tojson_in_an_html_attribute_breaks_out_of_the_attribute():- """Demonstrate why the census below allows exactly one file."""+ """Bare JSON does not preserve a double-quoted attribute boundary."""env = Environment(autoescape=True) # autoescape on, as the apptemplate = env.from_string('<input value="{{ v|tojson }}">')rendered = template.render(v={"k": ATTR_BREAKOUT})@@ -1003,14 +1073,14 @@ def test_tojson_in_an_html_attribute_breaks_out_of_the_attribute():def test_no_template_puts_tojson_in_an_html_attribute():- """No template may put ``|tojson`` in an HTML attribute.+ """Attribute JSON must be URI-encoded as a complete expression.The JSON's own quotes land raw inside the attribute, so the parser sees afresh attribute after the value ends — see- ``test_tojson_in_an_html_attribute_breaks_out_of_the_attribute``. The one- site this census used to pin — ``components/settings_form.html``'s- ``render_setting`` macro, twice — was deleted along with the macro itself,- so the expected census is empty and any hit is a new breakout site.+ ``test_tojson_in_an_html_attribute_breaks_out_of_the_attribute``.+ URI-encoded event arguments preserve data without exposing JSON quotes+ to the HTML parser. Bare JSON and partially encoded expressions remain+ forbidden."""census = {rel: len(hits)@@ -1018,7 +1088,7 @@ def test_no_template_puts_tojson_in_an_html_attribute():if (hits := find_tojson_in_attribute(text))}assert census == {}, (- "|tojson inside an HTML attribute is a live breakout; offending "+ "unencoded |tojson inside an HTML attribute; offending "f"templates (path: hit count): {census}. See ""test_tojson_in_an_html_attribute_breaks_out_of_the_attribute")diff --git a/tests/security/test_security_headers_fastapi.py b/tests/security/test_security_headers_fastapi.pyindex b29d89e832..884f86b34d 100644--- a/tests/security/test_security_headers_fastapi.py+++ b/tests/security/test_security_headers_fastapi.py@@ -51,8 +51,8 @@ from local_deep_research.web.fastapi_app import app as _live_app# docstring. Reused rather than re-copied so a value only has to be updated# in one place when it legitimately changes.from tests.web.test_security_headers import (- EXPECTED_EXACT_HEADERS,EXPECTED_NO_STORE,+ _assert_exact_headers as _assert_policy_headers,)ENV_SETTING = "local_deep_research.settings.env_registry.get_env_setting"@@ -90,12 +90,7 @@ def client(app):def _assert_exact_headers(resp, label):- for name, expected in EXPECTED_EXACT_HEADERS.items():- actual = resp.headers.get(name)- assert actual == expected, (- f"{label} (status={resp.status_code}): header {name!r} expected "- f"{expected!r}, got {actual!r}"- )+ _assert_policy_headers(resp, f"{label} (status={resp.status_code})")# ---------------------------------------------------------------------------diff --git a/tests/security/test_template_security_policy.py b/tests/security/test_template_security_policy.pynew file mode 100644index 0000000000..66542ef7ce--- /dev/null+++ b/tests/security/test_template_security_policy.py@@ -0,0 +1,131 @@+"""Request-scoped template authorization and the served browser policy."""++import concurrent.futures+import re+from pathlib import Path++from bs4 import BeautifulSoup+from fastapi.testclient import TestClient+from starlette.requests import Request++import local_deep_research+from local_deep_research.web.template_config import templates+from local_deep_research.web.utils.csp import template_security_context+++def _nonce(response):+ policy = response.headers["content-security-policy"]+ matches = re.findall(r"'nonce-([A-Za-z0-9_-]{43})'", policy)+ assert len(matches) == 2 and matches[0] == matches[1]+ return matches[0]+++def test_each_response_authorizes_its_own_scripts_and_styles(app):+ client = TestClient(app, raise_server_exceptions=False)+ seen = set()+ for path, status in (("/auth/login", 200), ("/missing-template-page", 404)):+ for _ in range(2):+ response = client.get(path)+ assert response.status_code == status+ nonce = _nonce(response)+ assert nonce not in seen+ seen.add(nonce)+ tags = BeautifulSoup(response.text, "html.parser")+ executable = [+ tag+ for tag in tags.find_all(["script", "style"])+ if tag.name == "style" or not tag.has_attr("src")+ ]+ assert executable+ assert all(tag.get("nonce") == nonce for tag in executable), {+ "path": path,+ "missing": sum(not tag.get("nonce") for tag in executable),+ "mismatched": sum(+ bool(tag.get("nonce")) and tag.get("nonce") != nonce+ for tag in executable+ ),+ }+ helper = tags.find(+ "script", src="/static/js/security/template-events.js"+ )+ assert helper is not None+ assert helper["nonce"] == nonce+ token = helper["data-template-token"]+ assert re.fullmatch(r"[A-Za-z0-9_-]{43}", token)+ assert token != nonce+ for tag in tags.find_all(True):+ assert not any(name.startswith("on") for name in tag.attrs)+ if any(name.startswith("data-ldr-on") for name in tag.attrs):+ assert tag["data-ldr-template-token"] == token+++def test_template_context_is_copied_and_caller_values_cannot_set_authorizations(+ app,+):+ shared = {+ "csp_nonce": "caller-value",+ "template_event_token": "caller-value",+ }+ original = dict(shared)+ authorizations = []+ for legacy in (False, True):+ request = Request(+ {+ "type": "http",+ "method": "GET",+ "path": "/auth/login",+ "root_path": "",+ "scheme": "http",+ "headers": [],+ "query_string": b"",+ "session": {},+ "app": app,+ "router": app.router,+ "server": ("testserver", 80),+ }+ )+ if legacy:+ response = templates.TemplateResponse(+ "auth/login.html", shared, request=request+ )+ else:+ response = templates.TemplateResponse(+ request, "auth/login.html", shared+ )+ security = template_security_context(request.scope)+ assert response.context["csp_nonce"] == security.nonce+ assert response.context["template_event_token"] == security.event_token+ assert response.context is not shared+ assert shared == original+ authorizations.append(security)+ assert authorizations[0] != authorizations[1]+++def test_independent_scopes_remain_independent_under_concurrent_render_preparation():+ def prepare(_):+ scope = {}+ first = template_security_context(scope)+ assert template_security_context(scope) is first+ return first++ with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor:+ results = list(executor.map(prepare, range(16)))+ assert len({value.nonce for value in results}) == 16+ assert len({value.event_token for value in results}) == 16+ assert all(value.nonce != value.event_token for value in results)+++def test_checked_in_html_keeps_event_code_out_of_attributes():+ web = Path(local_deep_research.__file__).parent / "web"+ paths = [+ *(web / "templates").rglob("*.html"),+ *(web / "static/templates").rglob("*.html"),+ ]+ assert paths+ for path in paths:+ tags = BeautifulSoup(path.read_text(encoding="utf-8"), "html.parser")+ assert not any(+ name.startswith("on")+ for tag in tags.find_all(True)+ for name in tag.attrs+ ), path.namediff --git a/tests/test_constants.py b/tests/test_constants.pyindex c9410c9d60..6d132102b0 100644--- a/tests/test_constants.py+++ b/tests/test_constants.py@@ -149,10 +149,11 @@ def test_injected_frontend_local_search_constants_match_defaults():context=ctx,)- assert "local_search_defaults" in ctx+ assert ctx == {"request": req}+ assert "local_search_defaults" in resp.contexthtml = resp.body.decode()assert "window.LDR_LOCAL_SEARCH_DEFAULTS" in html- ls = ctx["local_search_defaults"]+ ls = resp.context["local_search_defaults"]assert ls["provider"] == DEFAULT_LOCAL_SEARCH_PROVIDERassert ls["model"] == DEFAULT_LOCAL_SEARCH_MODELassert ls["chunk_size"] == DEFAULT_LOCAL_SEARCH_CHUNK_SIZEdiff --git a/tests/theme_tests/test_select_forced_colors.py b/tests/theme_tests/test_select_forced_colors.pyindex 1fe2526468..dfa8086adc 100644--- a/tests/theme_tests/test_select_forced_colors.py+++ b/tests/theme_tests/test_select_forced_colors.py@@ -118,10 +118,8 @@ def test_gradient_chevron_select_has_forced_colors_fallback(filename, selector):def _followup_modal_css() -> str:source = (JS_ROOT / "followup.js").read_text(encoding="utf-8")- match = re.search(- r"<style id=\"followup-modal-styles\">(.*?)</style>", source, re.DOTALL- )- assert match, "followup.js: followup-modal-styles <style> block not found"+ match = re.search(r"styles\.textContent\s*=\s*`(.*?)`", source, re.DOTALL)+ assert match, "followup.js: modal style content not found"return match.group(1)diff --git a/tests/web/test_auth_flow_contracts.py b/tests/web/test_auth_flow_contracts.pyindex 0d4aba295e..e7794e8805 100644--- a/tests/web/test_auth_flow_contracts.py+++ b/tests/web/test_auth_flow_contracts.py@@ -15,8 +15,8 @@ behaviour it protects rots:attacker a username oracle. ``routers/auth.py`` funnels both into asingle ``engine is None`` branch, so the two responses are supposed tobe *the same response*, and that is what is asserted here — byte for- byte, off one client so even the CSRF token in the rendered form is- identical and there is no legitimate difference left to excuse.+ byte after checking and normalizing per-response template authorizations,+ off one client so the CSRF token in the rendered form is identical.The same equality also pins, for free, that the submitted username isnever echoed into the 401 body (the two probes use different@@ -253,6 +253,27 @@ def _auth_row_exists(username: str) -> bool:# ---------------------------------------------------------------------------+def _auth_page_without_response_tokens(response):+ """Validate template authorizations and normalize only their values."""+ policy = response.headers["content-security-policy"]+ nonces = set(re.findall(r"'nonce-([^']+)'", policy))+ assert len(nonces) == 1+ nonce = nonces.pop()+ assert re.fullmatch(r"[A-Za-z0-9_-]{43}", nonce)+ assert set(re.findall(r'\bnonce="([^"]*)"', response.text)) == {nonce}++ tokens = re.findall(r'data-template-token="([^"]*)"', response.text)+ assert len(tokens) == 1+ token = tokens[0]+ assert re.fullmatch(r"[A-Za-z0-9_-]{43}", token)+ assert set(+ re.findall(r'data-ldr-template-token="([^"]*)"', response.text)+ ) <= {token}+ return response.content.replace(+ nonce.encode("ascii"), b"<template-nonce>"+ ).replace(token.encode("ascii"), b"<template-event-token>")++class TestLoginFailuresAreIndistinguishable:"""The 401 an attacker sees must carry no signal about the account.@@ -260,8 +281,8 @@ class TestLoginFailuresAreIndistinguishable:``routers/auth.py::login``, which flashes one fixed message andre-renders ``auth/login.html`` with a context that does NOT includethe submitted username. So the two responses are supposed to be the- identical response — and on a single client (one session, therefore- one CSRF token) there is nothing left that may legitimately differ.+ identical response after normalizing the checked template nonce and+ event token. One client keeps the session and CSRF token the same."""def test_unknown_user_and_wrong_password_are_byte_identical(self, app):@@ -276,8 +297,7 @@ class TestLoginFailuresAreIndistinguishable:_register_then_logout(app, real_user)ghost_user = _unique("enum_ghost")- # ONE client for both probes: same session, same CSRF token, so- # the rendered pages have no licence to differ at all.+ # One client keeps the session and CSRF token stable.probe = _client(app)ghost = _login(probe, ghost_user, TEST_PASSWORD)@@ -298,7 +318,9 @@ class TestLoginFailuresAreIndistinguishable:assert ghost.headers.get("content-type") == wrong.headers.get("content-type")- assert ghost.content == wrong.content, (+ assert _auth_page_without_response_tokens(+ ghost+ ) == _auth_page_without_response_tokens(wrong), ("the response to a nonexistent user differs from the response ""to a wrong password — that difference is a username oracle. ""Both must come out of the same generic branch."@@ -371,7 +393,9 @@ class TestLoginFailuresAreIndistinguishable:f"like a rate-limiter 429, not account lockout: "f"{resp.text[:300]}")- assert locked_real.content == locked_ghost.content, (+ assert _auth_page_without_response_tokens(+ locked_real+ ) == _auth_page_without_response_tokens(locked_ghost), ("a locked real account and a locked nonexistent account answer ""differently — the lockout arm leaks whether the username ""exists, which is exactly what the generic 401 prevents"diff --git a/tests/web/test_js_fetch_parity.py b/tests/web/test_js_fetch_parity.pyindex 88d8ac1cf7..fb70c42c08 100644--- a/tests/web/test_js_fetch_parity.py+++ b/tests/web/test_js_fetch_parity.py@@ -980,7 +980,7 @@ LIVE_CASES = (bad={"engineId": "zzz_no_such_engine"},),LiveCase(- js_ref="followup.js:312",+ js_ref="followup.js:311",method="POST",url="/api/followup/prepare",good={"parent_research_id": NOPE_UUID, "question": "q"},diff --git a/tests/web/test_middleware_stack_contracts.py b/tests/web/test_middleware_stack_contracts.pyindex 6d92feae00..b6973adae1 100644--- a/tests/web/test_middleware_stack_contracts.py+++ b/tests/web/test_middleware_stack_contracts.py@@ -81,6 +81,7 @@ from local_deep_research.web.fastapi_app import (_register_exception_handlers,)from local_deep_research.web.fastapi_app import app as _live_app+from tests.web.test_security_headers import _normalise_header# ---------------------------------------------------------------------------# Test-only probe route on the live `app` singleton, registered once at@@ -702,7 +703,8 @@ class TestSecurityHeadersIdenticalOnEveryExitPath:resp.headers.get(name),)for name in _ALL_STAMPED_HEADERS- if baseline.headers.get(name) != resp.headers.get(name)+ if _normalise_header(name, baseline.headers.get(name))+ != _normalise_header(name, resp.headers.get(name))}assert drift == {}, (f"{label} does not carry the same stamped headers as the 200 "diff --git a/tests/web/test_rate_limit_coverage.py b/tests/web/test_rate_limit_coverage.pyindex a93453da3e..dae32f9279 100644--- a/tests/web/test_rate_limit_coverage.py+++ b/tests/web/test_rate_limit_coverage.py@@ -179,6 +179,7 @@ class TestRateLimitExceededHandler:handler = app.exception_handlers[RateLimitExceeded]request = Mock()+ request.scope = {}request.url.path = "/auth/login"request.client = Mock(host="203.0.113.7")# A real Headers object, not a plain dict: _get_forwarded_for()@@ -221,6 +222,7 @@ class TestRateLimitExceededHandler:handler = app.exception_handlers[RateLimitExceeded]request = Mock()+ request.scope = {}request.url.path = "/a'\" ip=6.6.6.6 z="request.client = Mock(host="8.8.8.8")request.headers = Headers({"User-Agent": "x ip=6.6.6.6"})diff --git a/tests/web/test_security_headers.py b/tests/web/test_security_headers.pyindex d33f1d8bb4..5c58e29b6a 100644--- a/tests/web/test_security_headers.py+++ b/tests/web/test_security_headers.py@@ -19,6 +19,8 @@ Representative surfaces:- Static: GET /static/favicon.png (cache-control carve-out)"""+import re+import pytestfrom fastapi.testclient import TestClient@@ -29,13 +31,14 @@ from local_deep_research.web.fastapi_app import SecurityHeadersMiddlewareHTML_PATH = "/auth/login"API_PATH = "/api/v1/health"-# The exact CSP main shipped (security_headers.py) and the ASGI port-# must keep serving. Written out literally on purpose.+# Exact policy apart from the independently validated per-response nonce.EXPECTED_CSP = ("default-src 'self'; ""connect-src 'self'; "- "script-src 'self' 'unsafe-inline'; "- "style-src 'self' 'unsafe-inline'; "+ "script-src 'self'; "+ "script-src-attr 'none'; "+ "style-src 'self'; "+ "style-src-attr 'unsafe-inline'; ""font-src 'self' data:; ""img-src 'self' data:; ""media-src 'self'; "@@ -85,9 +88,18 @@ def https_client(app):)+def _normalise_header(name, value):+ if name != "content-security-policy":+ return value+ assert isinstance(value, str)+ nonces = re.findall(r" 'nonce-([A-Za-z0-9_-]{43})'", value)+ assert len(nonces) == 2 and nonces[0] == nonces[1]+ return re.sub(r" 'nonce-[A-Za-z0-9_-]{43}'", "", value)++def _assert_exact_headers(resp, label):for name, expected in EXPECTED_EXACT_HEADERS.items():- actual = resp.headers.get(name)+ actual = _normalise_header(name, resp.headers.get(name))assert actual == expected, (f"{label}: header {name!r} expected {expected!r}, got {actual!r}")diff --git a/tests/web/test_template_environment_census.py b/tests/web/test_template_environment_census.pyindex 924aeeb29d..4a4b08f233 100644--- a/tests/web/test_template_environment_census.py+++ b/tests/web/test_template_environment_census.py@@ -651,9 +651,26 @@ def test_render_template_helper_and_templateresponse_inject_the_same_defaults(# The two calls mint tokens from two independent session dicts, so# normalise every 64-hex CSRF token (meta tag and hidden inputs) out- # before comparing; everything else must match byte for byte.+ # before comparing. Response authorizations also differ; their shape,+ # isolation and header agreement are checked in test_template_security_policy.+ # Everything else must match byte for byte.strip = re.compile(r"\b[0-9a-f]{64}\b")- assert strip.sub("TOKEN", direct) == strip.sub("TOKEN", via_helper)+ authorization = re.compile(+ r'(?P<name>nonce|data-template-token|data-ldr-template-token)="[A-Za-z0-9_-]{43}"'+ )++ def normalized(html):+ return authorization.sub(+ lambda match: f'{match["name"]}="RESPONSE"',+ strip.sub("TOKEN", html),+ )++ assert normalized(direct) == normalized(via_helper)+ assert (+ len(authorization.findall(direct))+ == len(authorization.findall(via_helper))+ > 0+ )assert len(strip.findall(direct)) == len(strip.findall(via_helper)) > 0diff --git a/tests/web/test_vite_asset_pipeline.py b/tests/web/test_vite_asset_pipeline.pyindex 96264a48d6..59599e2756 100644--- a/tests/web/test_vite_asset_pipeline.py+++ b/tests/web/test_vite_asset_pipeline.py@@ -798,7 +798,7 @@ class TestDevProdSwitch:``vite_hmr``/``vite_asset`` hardcode ``http://localhost:5173``,but ``SecurityHeadersMiddleware`` sends an unconditional- ``script-src 'self' 'unsafe-inline'`` and ``connect-src 'self'``+ ``script-src 'self'`` and ``connect-src 'self'``on every response, dev mode included. A browser loading thePython-rendered page therefore refuses both the module script andthe HMR websocket, and the ``http://`` scheme is additionally@@ -829,7 +829,7 @@ class TestDevProdSwitch:name, _, value = part.partition(" ")directives[name] = value.strip()- assert directives["script-src"] == "'self' 'unsafe-inline'", (+ assert directives["script-src"] == "'self'", (f"script-src changed to {directives['script-src']!r}; recheck ""whether the dev-server origin is now allowed")diff --git a/tests/web/themes/test_theme_jinja_globals.py b/tests/web/themes/test_theme_jinja_globals.pyindex f261dd5a22..a895338e31 100644--- a/tests/web/themes/test_theme_jinja_globals.py+++ b/tests/web/themes/test_theme_jinja_globals.py@@ -120,7 +120,10 @@ def test_initial_html_and_browser_share_the_injected_default():source, _, _ = templates.env.loader.get_source(templates.env, "base.html")# Render the real initial HTML and startup script, before page assets.- head = source.split("</script>", 1)[0] + "</script>"+ theme_script_end = source.index(+ "</script>", source.index("window.LDR_DEFAULT_THEME")+ )+ head = source[:theme_script_end] + "</script>"rendered = templates.env.from_string(head).render(default_theme=theme)assert f'data-theme="{theme}"' in rendered