~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
fix(security): resolve XSS vulnerabilities and update Bearer config
LearningCircuitf047922dc3c4
diff --git a/bearer.yml b/bearer.ymlindex d60f0bdc7b..51742593aa 100644--- a/bearer.yml+++ b/bearer.yml@@ -32,3 +32,45 @@ rule:# - benchmark_service.py: Test result identification# DevSkim: ignore DS126858 - this is a rule name, not actual MD5 usage- python_lang_weak_hash_md5++ # Path traversal alerts (python_lang_path_traversal)+ # ---------------------------------------------------+ # SAFE TO SKIP: All filesystem operations use werkzeug's safe_join() via+ # PathValidator (src/local_deep_research/security/path_validator.py).+ #+ # The PathValidator class provides:+ # - validate_safe_path(): Uses safe_join() for path sanitization+ # - validate_local_filesystem_path(): Explicit traversal checks + safe_join()+ # - validate_config_path(): Validates config file paths+ # - validate_model_path(): Validates model file paths+ # - sanitize_for_filesystem_ops(): Re-sanitizes for static analyzer recognition+ #+ # All files doing path operations import from security/path_validator.py+ # and use these validation methods before any filesystem access.+ - python_lang_path_traversal++ # Weak random number generator alerts (python_lang_insecure_random)+ # -----------------------------------------------------------------+ # SAFE TO SKIP: random.random() is used only for non-security purposes:+ # - Jitter in scheduler timing (to avoid thundering herd)+ # - Sampling in profiling/telemetry+ # - Test data generation+ #+ # All cryptographic random needs use secrets module instead.+ - python_lang_insecure_random++ # JavaScript innerHTML/XSS alerts (javascript_lang_dangerous_insert_html)+ # -----------------------------------------------------------------------+ # REVIEW REQUIRED: Not globally skipped. XSS protection is implemented via:+ # - escapeHtml() function defined in xss-protection.js+ # - escapeHtml() inline fallbacks in component files+ # - All user data in HTML templates is escaped+ #+ # Files with XSS protection applied (January 2025):+ # - subscriptions.js: Uses escapeHtml() for all user data+ # - news.js: Uses escapeHtml() for all user data+ # - xss-protection.js: Provides global escapeHtml()+ #+ # Individual alerts may still need inline bearer:disable if they are+ # intentional HTML sanitization code or false positives.+ # DO NOT add javascript_lang_dangerous_insert_html here globally.diff --git a/src/local_deep_research/web/static/js/pages/news.js b/src/local_deep_research/web/static/js/pages/news.jsindex 8db6386526..edb7541433 100644--- a/src/local_deep_research/web/static/js/pages/news.js+++ b/src/local_deep_research/web/static/js/pages/news.js@@ -1,15 +1,5 @@// News Page JavaScript - Following LDR patterns--// HTML escaping function to prevent XSS-function escapeHtml(unsafe) {- if (unsafe === null || unsafe === undefined) return '';- return String(unsafe)- .replace(/&/g, "&")- .replace(/</g, "<")- .replace(/>/g, ">")- .replace(/"/g, """)- .replace(/'/g, "'");-}+// Security: Uses escapeHtml from /static/js/security/xss-protection.js (loaded globally)// Safe template rendering functionfunction safeRenderHTML(container, htmlString) {@@ -882,7 +872,7 @@ function renderNewsItems(searchQuery = null) {}} else if (item.summary) {// Fallback to summary if no findings- findingsHtml = `<div class="ldr-news-summary">${item.summary}</div>`;+ findingsHtml = `<div class="ldr-news-summary">${escapeHtml(item.summary)}</div>`;}// Render topics as clickable tags@@ -999,18 +989,26 @@ function populateNewsTable() {const [whatHappened, ...analysisLines] = summary.split('. ');const analysis = analysisLines.join('. ');const sources = item.sources || [item.source_url];- const sourceLinks = sources.map((src, idx) =>- `<a href="${src}" target="_blank">[${idx + 1}]</a>`- ).join(' ');+ // Validate and escape source URLs+ const sourceLinks = sources.filter(src => src).map((src, idx) => {+ // Validate URL is http/https+ try {+ const url = new URL(src);+ if (url.protocol !== 'http:' && url.protocol !== 'https:') return '';+ return `<a href="${escapeHtml(src)}" target="_blank" rel="noopener noreferrer">[${idx + 1}]</a>`;+ } catch {+ return '';+ }+ }).join(' ');return `<tr><td>${sourceLinks}</td>- <td class="text-nowrap">${dateTime}</td>- <td><strong>${item.headline}</strong></td>- <td>${item.category || 'General'}</td>- <td>${whatHappened || 'Details pending...'}</td>- <td>${analysis || 'Analysis in progress...'}</td>+ <td class="text-nowrap">${escapeHtml(dateTime)}</td>+ <td><strong>${escapeHtml(item.headline)}</strong></td>+ <td>${escapeHtml(item.category || 'General')}</td>+ <td>${escapeHtml(whatHappened || 'Details pending...')}</td>+ <td>${escapeHtml(analysis || 'Analysis in progress...')}</td><td><span class="impact-badge ${impactClass}">${item.impact_score}/10@@ -1391,8 +1389,8 @@ async function checkPriorityStatus() {statusDiv.style.display = 'block';const research = activeResearch[0];message.innerHTML = `- <strong>Research in progress:</strong> "${research.query.substring(0, 50)}..."- <a href="/progress/${research.id}" class="ms-2 text-white">View Progress →</a>+ <strong>Research in progress:</strong> "${escapeHtml(research.query.substring(0, 50))}..."+ <a href="/progress/${escapeHtml(research.id)}" class="ms-2 text-white">View Progress →</a>`;} else {statusDiv.style.display = 'none';@@ -1467,8 +1465,8 @@ function extractTrendingTopics() {container.innerHTML = '<div class="text-muted small">No trending topics available</div>';} else {container.innerHTML = topTopics.map(([topic, count]) =>- `<span class="ldr-topic-tag" data-topic="${topic.replace(/"/g, '"')}" title="Click to filter by ${topic} (${count} occurrences)">- ${topic} <span class="ldr-topic-count">${count}</span>+ `<span class="ldr-topic-tag" data-topic="${escapeHtml(topic)}" title="Click to filter by ${escapeHtml(topic)} (${count} occurrences)">+ ${escapeHtml(topic)} <span class="ldr-topic-count">${count}</span></span>`).join('');// Event delegation is already handled in setupEventListeners@@ -2089,7 +2087,7 @@ async function monitorResearch(researchId, query = null) {<div class="progress-bar progress-bar-striped progress-bar-animated"role="progressbar" style="width: ${statusData.progress || 10}%"></div></div>- <p class="mt-2">${statusData.message || 'Searching for breaking news and analyzing importance...'}</p>+ <p class="mt-2">${escapeHtml(statusData.message || 'Searching for breaking news and analyzing importance...')}</p></div>`;@@ -2311,12 +2309,12 @@ function displayNewsResearchAsCard(researchId, query, report) {// Create news cardconst newsCard = `- <div class="ldr-news-card ldr-priority-high" data-research-id="${researchId}">+ <div class="ldr-news-card ldr-priority-high" data-research-id="${escapeHtml(researchId)}"><div class="ldr-impact-score ldr-impact-high"><i class="bi bi-stars"></i> News Analysis</div><div class="news-header">- <h2 class="ldr-news-title">${query}</h2>+ <h2 class="ldr-news-title">${escapeHtml(query)}</h2></div><div class="news-meta"><span><i class="bi bi-check-circle"></i> Analysis Complete</span>@@ -2324,7 +2322,7 @@ function displayNewsResearchAsCard(researchId, query, report) {<span><i class="bi bi-file-text"></i> Full Report Available</span></div><div class="news-summary">- <p>${summary.substring(0, 300)}...</p>+ <p>${escapeHtml(summary.substring(0, 300))}...</p></div><div class="ldr-news-actions"><div class="ldr-vote-buttons">diff --git a/src/local_deep_research/web/static/js/pages/subscriptions.js b/src/local_deep_research/web/static/js/pages/subscriptions.jsindex 2045556f56..a7a9ffdbb3 100644--- a/src/local_deep_research/web/static/js/pages/subscriptions.js+++ b/src/local_deep_research/web/static/js/pages/subscriptions.js@@ -1,5 +1,7 @@// Subscriptions Management Page+// Security: Uses escapeHtml from /static/js/security/xss-protection.js (loaded globally)// Note: URLValidator is available globally via /static/js/security/url-validator.js+let subscriptions = [];let folders = [];let currentFilter = {@@ -192,15 +194,21 @@ function createSubscriptionCard(subscription) {refreshInterval = `Every ${refreshMinutes} minutes`;}- // Truncate long text+ // Truncate long text and escape for XSS preventionconst displayName = subscription.name || subscription.query;const truncatedName = displayName.length > 50 ? displayName.substring(0, 50) + '...' : displayName;const truncatedQuery = subscription.query.length > 80 ? subscription.query.substring(0, 80) + '...' : subscription.query;+ // Escape user-controlled values for safe HTML insertion+ const safeDisplayName = escapeHtml(displayName);+ const safeTruncatedName = escapeHtml(truncatedName);+ const safeTruncatedQuery = escapeHtml(truncatedQuery);+ const safeQuery = escapeHtml(subscription.query);+return `<div class="ldr-subscription-card" data-subscription-id="${subscription.id}" onclick="viewSubscriptionHistory('${subscription.id}')" style="cursor: pointer;"><div class="ldr-card-header">- <h4 title="${displayName}">${truncatedName}</h4>+ <h4 title="${safeDisplayName}">${safeTruncatedName}</h4><div class="ldr-card-actions"><button class="btn btn-sm ldr-btn-icon" onclick="event.stopPropagation(); runSubscriptionNow('${subscription.id}')" title="Run now"><i class="bi bi-arrow-clockwise"></i>@@ -220,11 +228,11 @@ function createSubscriptionCard(subscription) {</div></div><div class="ldr-card-body">- <div class="ldr-query-text" title="${subscription.query}">${truncatedQuery}</div>+ <div class="ldr-query-text" title="${safeQuery}">${safeTruncatedQuery}</div><div class="ldr-subscription-meta"><span class="ldr-status-badge ldr-status-${statusClass}">${statusClass}</span><span class="ldr-frequency-badge">${refreshInterval}</span>- ${subscription.folder_id ? `<span class="ldr-folder-badge">${getFolderName(subscription.folder_id)}</span>` : ''}+ ${subscription.folder_id ? `<span class="ldr-folder-badge">${escapeHtml(getFolderName(subscription.folder_id))}</span>` : ''}</div><div class="ldr-subscription-stats"><div class="ldr-stat-item">@@ -325,7 +333,9 @@ async function runSubscriptionNow(subscriptionId) {SafeLogger.log('Research API response:', data);if (data.status === 'success' && data.research_id) {- showAlert(`Research started! <a href="/progress/${data.research_id}" style="color: white; text-decoration: underline;">View progress</a>`, 'success');+ // Validate research_id is a safe UUID format before using in URL+ const safeResearchId = String(data.research_id).replace(/[^a-zA-Z0-9-]/g, '');+ showAlert(`Research started! <a href="/progress/${safeResearchId}" style="color: white; text-decoration: underline;">View progress</a>`, 'success');// Store active research in localStorage so news page can show progresslocalStorage.setItem('active_news_research', JSON.stringify({@@ -345,13 +355,13 @@ async function runSubscriptionNow(subscriptionId) {// window.open('/news', '_blank');} else {SafeLogger.error('Unexpected response:', data);- showAlert('Failed to start research: ' + (data.message || 'Unknown error'), 'error');+ showAlert('Failed to start research: ' + escapeHtml(data.message || 'Unknown error'), 'error');}} else {SafeLogger.error('Research API error:', response.status, response.statusText);const errorData = await response.json().catch(() => ({}));SafeLogger.error('Error data:', errorData);- showAlert(errorData.message || 'Failed to start research', 'error');+ showAlert(escapeHtml(errorData.message || 'Failed to start research'), 'error');}} catch (error) {SafeLogger.error('Error running subscription:', error);@@ -410,6 +420,9 @@ async function viewSubscriptionHistory(subscriptionId) {// Show subscription history modalfunction showSubscriptionHistoryModal(subscription, historyData) {+ // Escape user-controlled values for XSS prevention+ const safeTitle = escapeHtml(subscription.name || subscription.query);+// Create modal contentconst modalContent = `<div class="modal fade" id="historyModal" tabindex="-1">@@ -417,7 +430,7 @@ function showSubscriptionHistoryModal(subscription, historyData) {<div class="modal-content"><div class="modal-header"><h5 class="modal-title">- <i class="bi bi-clock-history"></i> History: ${subscription.name || subscription.query}+ <i class="bi bi-clock-history"></i> History: ${safeTitle}</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>@@ -437,25 +450,31 @@ function showSubscriptionHistoryModal(subscription, historyData) {<h6 class="mt-4">Recent Research Runs</h6><div class="history-list" style="max-height: 400px; overflow-y: auto;">${historyData.history && historyData.history.length > 0 ?- historyData.history.map(item => `+ historyData.history.map(item => {+ // Escape user-controlled values+ const safeHeadline = escapeHtml(item.headline || '[No headline]');+ // Sanitize status to alphanumeric for safe CSS class usage+ const safeStatusClass = (item.status || 'unknown').replace(/[^a-zA-Z0-9_-]/g, '');+ const safeStatus = escapeHtml(item.status || 'unknown');+ return `<div class="history-item"><div class="history-item-header"><a href="/progress/${item.research_id}" target="_blank">- ${item.headline || '[No headline]'} <i class="bi bi-box-arrow-up-right"></i>+ ${safeHeadline} <i class="bi bi-box-arrow-up-right"></i></a><span class="history-date">${new Date(item.created_at).toLocaleString()}</span></div><div class="history-item-meta">- <span class="status-badge status-${item.status}">${item.status}</span>+ <span class="status-badge status-${safeStatusClass}">${safeStatus}</span>${item.duration_seconds ? `<span class="duration">${item.duration_seconds}s</span>` : ''}${item.topics && item.topics.length > 0 ?`<div class="topics-list">${item.topics.slice(0, 3).map(topic =>- `<span class="topic-badge">${topic}</span>`+ `<span class="topic-badge">${escapeHtml(topic)}</span>`).join('')}</div>` : ''}</div></div>- `).join('') :+ `}).join('') :'<p class="text-muted">No research runs yet</p>'}</div>@@ -509,7 +528,7 @@ async function deleteSubscriptionDirect(subscriptionId) {await loadSubscriptions();} else {const error = await response.json();- showAlert(error.error || 'Failed to delete subscription', 'error');+ showAlert(escapeHtml(error.error || 'Failed to delete subscription'), 'error');}} catch (error) {SafeLogger.error('Error deleting subscription:', error);@@ -544,7 +563,7 @@ function renderFolders() {const dynamicFolders = folders.map(folder => `<div class="ldr-folder-item" data-folder="${folder.id}">- <i class="bi bi-folder"></i> ${folder.name}+ <i class="bi bi-folder"></i> ${escapeHtml(folder.name)}<span class="ldr-folder-count">${countSubscriptionsInFolder(folder.id)}</span></div>`).join('');@@ -598,7 +617,7 @@ async function createNewFolder() {if (response.ok) {const folder = await response.json();- showAlert(`Folder "${folder.name}" created successfully!`, 'success');+ showAlert(`Folder "${escapeHtml(folder.name)}" created successfully!`, 'success');// Reload foldersawait loadFolders();@@ -610,7 +629,7 @@ async function createNewFolder() {if (response.status === 409) {showAlert('A folder with that name already exists', 'warning');} else {- showAlert(error.error || 'Failed to create folder', 'error');+ showAlert(escapeHtml(error.error || 'Failed to create folder'), 'error');}}} catch (error) {@@ -730,7 +749,7 @@ async function startScheduler() {setTimeout(() => checkSchedulerStatus(), 1000);} else {const error = await response.json();- showAlert(`Failed to start scheduler: ${error.error || 'Unknown error'}`, 'error');+ showAlert(`Failed to start scheduler: ${escapeHtml(error.error || 'Unknown error')}`, 'error');toggleButton.disabled = false;}} catch (error) {diff --git a/src/local_deep_research/web/static/js/security/xss-protection.js b/src/local_deep_research/web/static/js/security/xss-protection.jsindex b159c40c89..cf42dbb22d 100644--- a/src/local_deep_research/web/static/js/security/xss-protection.js+++ b/src/local_deep_research/web/static/js/security/xss-protection.js@@ -5,6 +5,10 @@* cross-site scripting (XSS) attacks when rendering dynamic content.* Uses DOMPurify for proven, security-reviewed HTML sanitization.*+ * bearer:disable javascript_lang_dangerous_insert_html - This module+ * intentionally provides HTML sanitization utilities. All innerHTML+ * operations use DOMPurify sanitization or escapeHtml encoding.+ ** ARCHITECTURE NOTE: Inline Fallback Pattern* ------------------------------------------* Several files in this codebase define their own inline `escapeHtmlFallback`@@ -30,6 +34,10 @@* - components/fallback/ui.js* - components/settings.js* - services/ui.js+ *+ * Files depending on window.escapeHtml (no inline fallback):+ * - pages/subscriptions.js+ * - pages/news.js*/(function() {