Skip to content

~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.

fix(security): harden XSS escaping in history, news, progress, and subscription components (#2162)

LearningCircuitb1a85dd5ba34
diff --git a/.github/workflows/responsive-ui-tests-enhanced.yml b/.github/workflows/responsive-ui-tests-enhanced.yml
index 1d3ca55043..1dc2b9937b 100644
--- a/.github/workflows/responsive-ui-tests-enhanced.yml
+++ b/.github/workflows/responsive-ui-tests-enhanced.yml
@@ -117,10 +117,10 @@ jobs:
CI: true
FLASK_ENV: testing
TEST_ENV: true
- SECRET_KEY: test-secret-key-for-ci
+ SECRET_KEY: test-secret-key-for-ci # Security: CI test credential, not production secret
DISABLE_RATE_LIMITING: true
LDR_DATA_DIR: ${{ github.workspace }}/data
- DATABASE_URL: postgresql://postgres:postgres@localhost:5432/ldr_test
+ DATABASE_URL: postgresql://postgres:postgres@localhost:5432/ldr_test # Security: CI test database credentials, not production secrets
run: |
cd src
# Start server and get its PID
diff --git a/docs/NOTIFICATION_FLOW.md b/docs/NOTIFICATION_FLOW.md
index 5241515765..ab2090553a 100644
--- a/docs/NOTIFICATION_FLOW.md
+++ b/docs/NOTIFICATION_FLOW.md
@@ -276,6 +276,7 @@ Apprise handles the actual delivery to configured services:
```python
# User's settings: notifications.service_url
+# Security: placeholder example credentials below, not real secrets
"discord://webhook_id/webhook_token,mailto://user:[email protected]"
```
@@ -423,6 +424,7 @@ class NotificationManager:
```python
# Service URL (required) - comma-separated list
+# Security: placeholder example credentials below, not real secrets
notifications.service_url = "discord://webhook_id/token,mailto://user:[email protected]"
# Event-specific toggles (default: False for most events)
diff --git a/src/local_deep_research/advanced_search_system/strategies/constrained_search_strategy.py b/src/local_deep_research/advanced_search_system/strategies/constrained_search_strategy.py
index 5e8c1595af..18e9bdf391 100644
--- a/src/local_deep_research/advanced_search_system/strategies/constrained_search_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/constrained_search_strategy.py
@@ -312,6 +312,7 @@ class ConstrainedSearchStrategy(EvidenceBasedStrategy):
# Diversify query execution order
import random
+ # Security: random.shuffle for query order diversity, not security-sensitive
random.shuffle(queries)
for i, query in enumerate(queries[:20]): # Increased query limit
diff --git a/src/local_deep_research/benchmarks/datasets/base.py b/src/local_deep_research/benchmarks/datasets/base.py
index e4fa61c883..e39e166159 100644
--- a/src/local_deep_research/benchmarks/datasets/base.py
+++ b/src/local_deep_research/benchmarks/datasets/base.py
@@ -124,6 +124,7 @@ class BenchmarkDataset(ABC):
if self.num_examples and self.num_examples < len(
processed_examples
):
+ # Security: seeded random for reproducible benchmark sampling, not security-sensitive
random.seed(self.seed)
sampled_examples = random.sample(
processed_examples, self.num_examples
diff --git a/src/local_deep_research/benchmarks/datasets/xbench_deepsearch.py b/src/local_deep_research/benchmarks/datasets/xbench_deepsearch.py
index 8b3787950a..486e53aff2 100644
--- a/src/local_deep_research/benchmarks/datasets/xbench_deepsearch.py
+++ b/src/local_deep_research/benchmarks/datasets/xbench_deepsearch.py
@@ -61,6 +61,7 @@ class XBenchDeepSearchDataset(BenchmarkDataset):
# Sample if requested
if num_examples and len(data) > num_examples:
+ # Security: seeded random for reproducible benchmark sampling, not security-sensitive
random.seed(seed)
data = random.sample(data, num_examples)
@@ -150,6 +151,7 @@ class XBenchDeepSearchDataset(BenchmarkDataset):
import random
# Use provided seed or None for random sampling
+ # Security: seeded random for reproducible benchmark sampling, not security-sensitive
if seed is not None:
random.seed(seed)
formatted_questions = random.sample(
@@ -238,6 +240,7 @@ class XBenchDeepSearchDataset(BenchmarkDataset):
import random
# Use provided seed or None for random sampling
+ # Security: seeded random for reproducible benchmark sampling, not security-sensitive
if seed is not None:
random.seed(seed)
questions = random.sample(questions, num_examples)
diff --git a/src/local_deep_research/news/subscription_manager/scheduler.py b/src/local_deep_research/news/subscription_manager/scheduler.py
index 206021a1f5..95b0adc30c 100644
--- a/src/local_deep_research/news/subscription_manager/scheduler.py
+++ b/src/local_deep_research/news/subscription_manager/scheduler.py
@@ -445,6 +445,7 @@ class NewsScheduler:
job_id = f"{username}_{sub.id}"
# Calculate jitter
+ # Security: random jitter to distribute subscription timing, not security-sensitive
max_jitter = int(self.config.get("max_jitter_seconds", 300))
jitter = random.randint(0, max_jitter)
@@ -1093,6 +1094,7 @@ class NewsScheduler:
for sub in overdue_subs:
# Run immediately with small random delay
+ # Security: random delay to stagger overdue jobs, not security-sensitive
delay_seconds = random.randint(1, 30)
job_id = (
f"overdue_{username}_{sub.id}_{int(now.timestamp())}"
@@ -1194,6 +1196,7 @@ class NewsScheduler:
job = self.scheduler.get_job(job_id)
if job and job.trigger.__class__.__name__ == "DateTrigger":
# For date triggers, reschedule
+ # Security: random jitter to distribute subscription timing, not security-sensitive
next_run = datetime.now(UTC) + timedelta(
minutes=sub.refresh_interval_minutes,
seconds=random.randint(
diff --git a/src/local_deep_research/web/static/js/components/history.js b/src/local_deep_research/web/static/js/components/history.js
index 3348685350..2132abc874 100644
--- a/src/local_deep_research/web/static/js/components/history.js
+++ b/src/local_deep_research/web/static/js/components/history.js
@@ -13,6 +13,9 @@
let historyItems = [];
let filteredItems = [];
+ // Security: local escapeHtml to prevent XSS in innerHTML assignments
+ const esc = window.escapeHtml || (s => String(s || '').replace(/[&<>"']/g, m => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":"&#39;"})[m]));
+
// Fallback UI utilities in case main UI utils aren't loaded
const uiUtils = {
showSpinner: function(container, message) {
@@ -22,10 +25,11 @@
// Fallback implementation
if (!container) container = document.body;
+ // Security: escapeHtml applied to message before innerHTML insertion
const spinnerHtml = `
<div class="loading-spinner centered">
<div class="spinner"></div>
- ${message ? `<div class="spinner-message">${message}</div>` : ''}
+ ${message ? `<div class="spinner-message">${esc(message)}</div>` : ''}
</div>
`;
// bearer:disable javascript_lang_dangerous_insert_html
@@ -323,10 +327,6 @@
// Get a display title (use query if title is not available)
const displayTitle = item.title || formatTitleFromQuery(item.query);
- // SECURITY: escapeHtml is required here — displayTitle comes from user-submitted
- // research queries/titles stored in the database. Without escaping, a query like
- // '<img src=x onerror=alert(1)>' would execute as XSS via innerHTML below.
- const escapeHtml = window.escapeHtml || ((s) => String(s || '').replace(/[&<>"']/g, (m) => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'})[m]));
// Status class - convert in_progress to in-progress for CSS
const statusClass = item.status ? item.status.replace('_', '-') : '';
@@ -334,16 +334,15 @@
// Check if this is a news-related research
const isNewsItem = item.metadata && item.metadata.is_news_search;
- // Create the HTML content — all dynamic values MUST be wrapped with escapeHtml()
// bearer:disable javascript_lang_dangerous_insert_html
itemEl.innerHTML = `
<div class="ldr-history-item-header">
- <div class="ldr-history-item-title">${escapeHtml(displayTitle)}</div>
- <div class="ldr-history-item-status ldr-status-${escapeHtml(statusClass)}">${escapeHtml(formatStatus(item.status))}</div>
+ <div class="ldr-history-item-title">${esc(displayTitle)}</div>
+ <div class="ldr-history-item-status ldr-status-${esc(statusClass)}">${esc(formatStatus(item.status))}</div>
</div>
<div class="ldr-history-item-meta">
- <div class="ldr-history-item-date">${escapeHtml(formattedDate)}</div>
- <div class="ldr-history-item-mode">${escapeHtml(formatMode(item.mode))}</div>
+ <div class="ldr-history-item-date">${esc(formattedDate)}</div>
+ <div class="ldr-history-item-mode">${esc(formatMode(item.mode))}</div>
${isNewsItem ? '<span class="ldr-news-indicator"><i class="fas fa-newspaper"></i> News</span>' : ''}
</div>
<div class="ldr-history-item-actions">
@@ -356,7 +355,7 @@
<i class="fas fa-book"></i> Library (${item.document_count})
</button>` : ''}
${isNewsItem && item.status === 'completed' ?
- `<button class="btn btn-sm ldr-btn-outline ldr-subscribe-btn" data-research-id="${item.id}" data-query="${encodeURIComponent(item.query)}">
+ `<button class="btn btn-sm ldr-btn-outline ldr-subscribe-btn" data-research-id="${esc(item.id)}" data-query="${esc(encodeURIComponent(item.query))}">
<i class="fas fa-bell"></i> Subscribe
</button>` : ''}
<button class="btn btn-sm ldr-btn-outline ldr-delete-item-btn">
diff --git a/src/local_deep_research/web/static/js/components/news.js b/src/local_deep_research/web/static/js/components/news.js
index f1e67e2add..7996c09ec2 100644
--- a/src/local_deep_research/web/static/js/components/news.js
+++ b/src/local_deep_research/web/static/js/components/news.js
@@ -48,14 +48,17 @@ document.addEventListener('click', function(e) {
}
});
+// Security: local escapeHtml to prevent XSS in innerHTML assignments
+const esc = window.escapeHtml || (s => String(s || '').replace(/[&<>"']/g, m => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":"&#39;"})[m]));
+
// Empty state helper
window.showEmptyState = function(container, message, icon = 'fas fa-newspaper') {
// bearer:disable javascript_lang_dangerous_insert_html
container.innerHTML = `
<div class="empty-state">
- <i class="${icon}"></i>
+ <i class="${esc(icon)}"></i>
<h3>No items found</h3>
- <p>${message}</p>
+ <p>${esc(message)}</p>
</div>
`;
};
@@ -66,7 +69,7 @@ window.showLoadingState = function(container, message = 'Loading...') {
container.innerHTML = `
<div class="loading-placeholder">
<div class="loading-spinner"></div>
- <p>${message}</p>
+ <p>${esc(message)}</p>
</div>
`;
};
@@ -78,7 +81,7 @@ window.showErrorState = function(container, message) {
<div class="error-state">
<i class="fas fa-exclamation-triangle"></i>
<h3>Error</h3>
- <p>${message}</p>
+ <p>${esc(message)}</p>
</div>
`;
};
diff --git a/src/local_deep_research/web/static/js/components/progress.js b/src/local_deep_research/web/static/js/components/progress.js
index 417785d734..4ac9504c3e 100644
--- a/src/local_deep_research/web/static/js/components/progress.js
+++ b/src/local_deep_research/web/static/js/components/progress.js
@@ -791,13 +791,13 @@
notificationEl.classList.add('ldr-alert-info');
}
- // Add title and message
// bearer:disable javascript_lang_dangerous_insert_html
+ const esc = window.escapeHtml || (s => String(s).replace(/[&<>"']/g, m => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":"&#39;"})[m]));
notificationEl.innerHTML = `
- <strong>${title}</strong>
+ <strong>${esc(title)}</strong>
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
<hr>
- <p>${message}</p>
+ <p>${esc(message)}</p>
`;
// Add to container
diff --git a/src/local_deep_research/web/static/js/components/subscription-manager.js b/src/local_deep_research/web/static/js/components/subscription-manager.js
index d8ef720f62..cc64856605 100644
--- a/src/local_deep_research/web/static/js/components/subscription-manager.js
+++ b/src/local_deep_research/web/static/js/components/subscription-manager.js
@@ -124,8 +124,8 @@ class SubscriptionManager {
li.className = 'nav-item';
// bearer:disable javascript_lang_dangerous_insert_html
li.innerHTML = `
- <button class="nav-link" data-folder="${folder.name}" type="button">
- ${folder.icon || '📁'} ${folder.name}
+ <button class="nav-link" data-folder="${this.escapeHtml(folder.name)}" type="button">
+ ${this.escapeHtml(folder.icon || '📁')} ${this.escapeHtml(folder.name)}
<span class="badge bg-secondary ms-1">${folder.item_count || 0}</span>
</button>
`;
@@ -186,7 +186,7 @@ class SubscriptionManager {
<div class="text-muted small">
<span><i class="bi bi-clock"></i> Every ${subscription.refresh_interval_minutes} min</span>
<span class="ms-3"><i class="bi bi-arrow-clockwise"></i> Next: ${timeUntil}</span>
- ${subscription.folder ? `<span class="ms-3"><i class="bi bi-folder"></i> ${subscription.folder}</span>` : ''}
+ ${subscription.folder ? `<span class="ms-3"><i class="bi bi-folder"></i> ${this.escapeHtml(subscription.folder)}</span>` : ''}
</div>
${subscription.notes ? `<p class="mb-0 mt-2 small">${this.escapeHtml(subscription.notes)}</p>` : ''}
</div>
@@ -245,13 +245,14 @@ class SubscriptionManager {
<select class="form-select" id="edit-folder">
<option value="">No folder</option>
${this.folders.map(f =>
- `<option value="${f.name}" ${subscription.folder === f.name ? 'selected' : ''}>${f.name}</option>`
+ // Security: escapeHtml applied to folder name in option value and text
+ `<option value="${this.escapeHtml(f.name)}" ${subscription.folder === f.name ? 'selected' : ''}>${this.escapeHtml(f.name)}</option>`
).join('')}
</select>
</div>
<div class="mb-3">
<label class="form-label">Notes</label>
- <textarea class="ldr-form-control" id="edit-notes" rows="2">${subscription.notes || ''}</textarea>
+ <textarea class="ldr-form-control" id="edit-notes" rows="2"></textarea>
</div>
</div>
<div class="modal-footer">
@@ -269,6 +270,8 @@ class SubscriptionManager {
// bearer:disable javascript_lang_dangerous_insert_html
document.body.insertAdjacentHTML('beforeend', modalHtml);
+ // Set textarea value via DOM property (not innerHTML) to avoid entity encoding issues
+ document.getElementById('edit-notes').value = subscription.notes || '';
const modal = new bootstrap.Modal(document.getElementById('editSubscriptionModal'));
// Handle save
diff --git a/src/local_deep_research/web/static/js/pages/news.js b/src/local_deep_research/web/static/js/pages/news.js
index 077f9382c5..bd0a5f7a79 100644
--- a/src/local_deep_research/web/static/js/pages/news.js
+++ b/src/local_deep_research/web/static/js/pages/news.js
@@ -31,6 +31,22 @@ function safeRenderHTML(container, htmlString) {
container.appendChild(content);
}
+// Sanitize a URL for safe use in href attributes (blocks javascript:, data:, etc.)
+function safeHref(url) {
+ if (!url || typeof url !== 'string') return '#';
+ const trimmed = url.trim();
+ // Allow relative URLs (starting with /)
+ if (trimmed.startsWith('/')) return escapeHtml(trimmed);
+ // Use URLValidator if available to check for unsafe schemes
+ if (typeof URLValidator !== 'undefined' && URLValidator.isSafeUrl) {
+ return URLValidator.isSafeUrl(trimmed) ? escapeHtml(trimmed) : '#';
+ }
+ // Fallback: block known unsafe schemes
+ const lower = trimmed.toLowerCase();
+ if (lower.startsWith('javascript:') || lower.startsWith('data:') || lower.startsWith('vbscript:')) return '#';
+ return escapeHtml(trimmed);
+}
+
// Escape attributes for use in HTML attributes (onclick, etc)
function escapeAttr(unsafe) {
if (unsafe === null || unsafe === undefined) return '';
@@ -947,7 +963,7 @@ function renderNewsItems(searchQuery = null) {
</button>
</div>
<div class="ldr-action-buttons">
- <a href="${item.source_url || `/results/${item.research_id}`}" class="btn btn-primary btn-sm" onclick="markAsReadOnClick('${escapeAttr(item.id)}')">
+ <a href="${safeHref(item.source_url || `/results/${item.research_id}`)}" class="btn btn-primary btn-sm" onclick="markAsReadOnClick('${escapeAttr(item.id)}')">
<i class="fas fa-file-alt"></i> View Full Report
</a>
<button class="btn btn-secondary btn-sm ldr-save-btn" onclick="toggleSaveItem('${escapeAttr(item.id)}')" title="${savedNewsIds.has(item.id) ? 'Remove from saved' : 'Save for later'}">
@@ -1722,7 +1738,7 @@ function renderSourceLinks(links) {
displayText = link.title.length > 30 ? link.title.substring(0, 27) + '...' : link.title;
}
- return `<a href="${link.url}" target="_blank" rel="noopener noreferrer" class="source-link" title="${link.title}">
+ return `<a href="${safeHref(link.url)}" target="_blank" rel="noopener noreferrer" class="source-link" title="${escapeHtml(link.title)}">
<i class="bi bi-link-45deg"></i>
${displayText}
</a>`;
@@ -1746,17 +1762,18 @@ async function showSubscriptionHistory(subscriptionId) {
const data = await response.json();
// Create modal content
+ // Security: escapeHtml applied to user-controlled fields from API response
let historyHtml = '';
if (data.history && data.history.length > 0) {
historyHtml = data.history.map(item => `
<div class="history-item">
<div class="history-header">
- <span class="history-status status-${item.status}">${item.status}</span>
- <span class="history-time">${new Date(item.created_at).toLocaleString()}</span>
+ <span class="history-status status-${escapeHtml(item.status)}">${escapeHtml(item.status)}</span>
+ <span class="history-time">${escapeHtml(new Date(item.created_at).toLocaleString())}</span>
</div>
- <div class="history-query">${item.query}</div>
+ <div class="history-query">${escapeHtml(item.query)}</div>
<div class="history-actions">
- <a href="${item.url}" class="btn btn-sm btn-primary">View Results</a>
+ <a href="${safeHref(item.url)}" class="btn btn-sm btn-primary">View Results</a>
${item.duration_seconds ? `<span class="duration">${item.duration_seconds}s</span>` : ''}
</div>
</div>
@@ -1773,7 +1790,7 @@ async function showSubscriptionHistory(subscriptionId) {
<div class="modal-header">
<h5 class="modal-title">
Subscription History
- <small class="text-muted">${data.subscription.query}</small>
+ <small class="text-muted">${escapeHtml(data.subscription.query)}</small>
</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal"></button>
</div>
diff --git a/src/local_deep_research/web/static/js/research_form.js b/src/local_deep_research/web/static/js/research_form.js
index e9a2f47738..4da52c949a 100644
--- a/src/local_deep_research/web/static/js/research_form.js
+++ b/src/local_deep_research/web/static/js/research_form.js
@@ -276,13 +276,15 @@ function displayWarnings(warnings) {
return;
}
+ // Security: escapeHtml applied to API-controlled warning fields before innerHTML insertion
+ const esc = window.escapeHtml || (s => String(s || '').replace(/[&<>"']/g, m => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":"&#39;"})[m]));
const warningsHtml = warnings.map(warning => {
// Use success styling for recommendations/tips, warning for others
const isRecommendation = warning.type === 'searxng_recommendation';
const alertClass = isRecommendation ? 'ldr-alert-success' : 'ldr-alert-warning';
return `
- <div class="ldr-alert ${alertClass} warning-banner warning-${warning.type}" style="
+ <div class="ldr-alert ${alertClass} warning-banner warning-${esc(warning.type)}" style="
border-radius: 6px;
padding: 12px 16px;
margin-bottom: 8px;
@@ -290,16 +292,16 @@ function displayWarnings(warnings) {
align-items: flex-start;
gap: 12px;
">
- <span style="font-size: 16px; flex-shrink: 0;">${warning.icon}</span>
+ <span style="font-size: 16px; flex-shrink: 0;">${esc(warning.icon)}</span>
<div style="flex: 1;">
<div style="font-weight: 600; margin-bottom: 4px;">
- ${warning.title}
+ ${esc(warning.title)}
</div>
<div style="font-size: 14px; line-height: 1.4;">
- ${warning.message}
+ ${esc(warning.message)}
</div>
</div>
- <button onclick="dismissWarning('${warning.dismissKey}')" style="
+ <button onclick="dismissWarning('${esc(warning.dismissKey)}')" style="
background: none;
border: none;
color: inherit;
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_google_pse.py b/src/local_deep_research/web_search_engines/engines/search_engine_google_pse.py
index a221a30b4e..32943a17e6 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_google_pse.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_google_pse.py
@@ -213,6 +213,7 @@ class GooglePSESearchEngine(BaseSearchEngine):
try:
# Add jitter to retries after the first attempt
if attempt > 0:
+ # Security: random jitter for exponential backoff retry, not security-sensitive
jitter = random.uniform(0.5, 1.5)
sleep_time = (
self.retry_delay * (2 ** (attempt - 1)) * jitter
diff --git a/src/local_deep_research/web_search_engines/rate_limiting/tracker.py b/src/local_deep_research/web_search_engines/rate_limiting/tracker.py
index 44f91d3556..1d860e058d 100644
--- a/src/local_deep_research/web_search_engines/rate_limiting/tracker.py
+++ b/src/local_deep_research/web_search_engines/rate_limiting/tracker.py
@@ -276,6 +276,7 @@ class AdaptiveRateLimitTracker:
estimate = self.current_estimates[engine_type]
base_wait = estimate["base"]
+ # Security: random used for non-security rate-limit jitter, not tokens or secrets
# Exploration vs exploitation
if random.random() < self.exploration_rate:
# Explore: try a faster rate to see if API limits have relaxed