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.

ci: add pre-commit hook to detect double HTML escaping (#2198)

LearningCircuit9b785b75ac7d
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index b3ff2b791e..7b9a5a062a 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -146,6 +146,14 @@ repos:
language: script
files: \.js$
description: "Ensure JavaScript code validates URLs to prevent XSS attacks"
+ - id: check-double-escaping
+ name: Check for double HTML escaping in JavaScript
+ entry: .pre-commit-hooks/check-double-escaping.py
+ language: script
+ files: \.js$
+ exclude: (tests?/|spec\.|test\.|\.test\.|\.spec\.)
+ description: "Detect escapeHtml() inside functions that already escape internally
+ (showError, showSuccess, showInfo, showAlert)"
- id: check-image-pinning
name: Check Docker Image Pinning
entry: .pre-commit-hooks/check-image-pinning.sh
diff --git a/.pre-commit-hooks/check-double-escaping.py b/.pre-commit-hooks/check-double-escaping.py
new file mode 100755
index 0000000000..36a65b3eba
--- /dev/null
+++ b/.pre-commit-hooks/check-double-escaping.py
@@ -0,0 +1,148 @@
+#!/usr/bin/env python3
+"""
+Pre-commit hook to detect double-escaping in JavaScript files.
+
+Catches patterns where escapeHtml() is called on values that are then
+passed to functions which already escape internally (showError, showSuccess,
+showInfo, showAlert).
+
+Known limitations:
+- Multi-line function calls are not detected (line-by-line processing).
+- Variable indirection bypasses detection
+ (e.g., ``const safe = escapeHtml(msg); showError(safe);``).
+"""
+
+import re
+import sys
+
+
+# Functions that escape their arguments internally
+ESCAPING_FUNCTIONS = ["showError", "showSuccess", "showInfo", "showAlert"]
+
+# Build pattern: showError(...escapeHtml(...)...)
+PATTERN = re.compile(
+ r"\b(" + "|".join(ESCAPING_FUNCTIONS) + r")\s*\("
+ r".*?"
+ r"(?:escapeHtml|XSSProtection\.escapeHtml)\s*\("
+)
+
+
+def strip_js_comments(line, in_block_comment):
+ """Strip JavaScript comments from a line, respecting string literals.
+
+ Handles ``//`` line comments, ``/* */`` block comments (including
+ multi-line), and correctly ignores comment-like sequences inside
+ single-quoted, double-quoted, and template-literal strings.
+
+ Returns ``(code_without_comments, still_in_block_comment)``.
+ """
+ result = []
+ i = 0
+ in_single_quote = False
+ in_double_quote = False
+ in_template = False
+
+ while i < len(line):
+ ch = line[i]
+
+ # Inside a block comment — scan for */
+ if in_block_comment:
+ if ch == "*" and i + 1 < len(line) and line[i + 1] == "/":
+ in_block_comment = False
+ i += 2
+ else:
+ i += 1
+ continue
+
+ # Handle escape sequences inside strings
+ if (in_single_quote or in_double_quote or in_template) and ch == "\\":
+ result.append(ch)
+ if i + 1 < len(line):
+ result.append(line[i + 1])
+ i += 2
+ else:
+ i += 1
+ continue
+
+ # Track string state
+ if ch == "'" and not in_double_quote and not in_template:
+ in_single_quote = not in_single_quote
+ elif ch == '"' and not in_single_quote and not in_template:
+ in_double_quote = not in_double_quote
+ elif ch == "`" and not in_single_quote and not in_double_quote:
+ in_template = not in_template
+ elif not in_single_quote and not in_double_quote and not in_template:
+ # Outside strings — check for comments
+ if ch == "/" and i + 1 < len(line):
+ if line[i + 1] == "/":
+ break # Line comment — rest of line is comment
+ if line[i + 1] == "*":
+ in_block_comment = True
+ i += 2
+ continue
+
+ result.append(ch)
+ i += 1
+
+ return "".join(result), in_block_comment
+
+
+def check_file(file_path):
+ """Check a JavaScript file for double-escaping patterns."""
+ issues = []
+
+ try:
+ with open(file_path, "r", encoding="utf-8") as f:
+ lines = f.readlines()
+ except (UnicodeDecodeError, IOError):
+ # Skip binary files or files we can't read
+ return []
+
+ in_block_comment = False
+ for line_num, line in enumerate(lines, 1):
+ code, in_block_comment = strip_js_comments(line, in_block_comment)
+
+ if PATTERN.search(code):
+ issues.append(
+ f"{file_path}:{line_num}: Possible double-escaping — "
+ f"escapeHtml() inside a function that already escapes: "
+ f"{line.strip()}"
+ )
+
+ return issues
+
+
+def main():
+ """Main function to check all provided files."""
+ if len(sys.argv) < 2:
+ print("No files to check")
+ return 0
+
+ all_issues = []
+
+ for file_path in sys.argv[1:]:
+ if not file_path.endswith(".js"):
+ continue
+
+ try:
+ issues = check_file(file_path)
+ all_issues.extend(issues)
+ except Exception as e:
+ print(f"Error checking {file_path}: {e}")
+ continue
+
+ if all_issues:
+ print("Double-escaping detected:")
+ print("-" * 60)
+ for issue in all_issues:
+ print(f" {issue}")
+ print("-" * 60)
+ print("\nThese functions already escape their arguments internally.")
+ print("Pass raw text instead of pre-escaping with escapeHtml().")
+ return 1
+
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/src/local_deep_research/web/static/js/collection_upload.js b/src/local_deep_research/web/static/js/collection_upload.js
index 85b681d10f..6000fe84f0 100644
--- a/src/local_deep_research/web/static/js/collection_upload.js
+++ b/src/local_deep_research/web/static/js/collection_upload.js
@@ -810,10 +810,12 @@ function showError(message) {
progressDiv.style.display = 'none';
}
+ // Escape message before including in HTML template
+ const escapedMessage = escapeHtml(message);
const html = `
<div class="ldr-alert ldr-alert-danger" style="padding: 1rem; border-radius: 8px; margin-bottom: 1rem;">
<h4 style="margin: 0 0 0.5rem 0;"><i class="fas fa-exclamation-triangle"></i> Upload Error</h4>
- <p>${escapeHtml(message)}</p>
+ <p>${escapedMessage}</p>
</div>
`;
diff --git a/src/local_deep_research/web/static/js/embedding_settings.js b/src/local_deep_research/web/static/js/embedding_settings.js
index caf9084cb1..a2c1d03e81 100644
--- a/src/local_deep_research/web/static/js/embedding_settings.js
+++ b/src/local_deep_research/web/static/js/embedding_settings.js
@@ -524,6 +524,7 @@ async function testConfiguration() {
Error: ${window.XSSProtection.escapeHtml(data.error || 'Unknown error')}
</div>
`;
+ // Safe: showError escapes internally
showError('Embedding test failed: ' + (data.error || 'Unknown error'));
}
} catch (error) {
@@ -534,6 +535,7 @@ async function testConfiguration() {
Error: ${window.XSSProtection.escapeHtml(error.message)}
</div>
`;
+ // Safe: showError escapes internally
showError('Test failed: ' + error.message);
} finally {
// Re-enable button
@@ -549,6 +551,7 @@ async function testConfiguration() {
function showSuccess(message) {
const alertDiv = document.createElement('div');
alertDiv.className = 'ldr-alert ldr-alert-success';
+ // Escape message before including in HTML template
// bearer:disable javascript_lang_dangerous_insert_html
alertDiv.innerHTML = `<i class="fas fa-check-circle"></i>${escapeHtml(message)}`;
@@ -571,6 +574,7 @@ function showSuccess(message) {
function showInfo(message) {
const alertDiv = document.createElement('div');
alertDiv.className = 'ldr-alert ldr-alert-info';
+ // Escape message before including in HTML template
// bearer:disable javascript_lang_dangerous_insert_html
alertDiv.innerHTML = `<i class="fas fa-info-circle"></i>${escapeHtml(message)}`;
@@ -593,6 +597,7 @@ function showInfo(message) {
function showError(message) {
const alertDiv = document.createElement('div');
alertDiv.className = 'ldr-alert ldr-alert-danger';
+ // Escape message before including in HTML template
// bearer:disable javascript_lang_dangerous_insert_html
alertDiv.innerHTML = `<i class="fas fa-exclamation-triangle"></i>${escapeHtml(message)}`;
diff --git a/src/local_deep_research/web/static/js/pages/subscriptions.js b/src/local_deep_research/web/static/js/pages/subscriptions.js
index 55b4241901..01abd64a53 100644
--- a/src/local_deep_research/web/static/js/pages/subscriptions.js
+++ b/src/local_deep_research/web/static/js/pages/subscriptions.js
@@ -355,13 +355,15 @@ async function runSubscriptionNow(subscriptionId) {
// window.open('/news', '_blank');
} else {
SafeLogger.error('Unexpected response:', data);
- showAlert('Failed to start research: ' + escapeHtml(data.message || 'Unknown error'), 'error');
+ // Safe: showAlert escapes internally
+ showAlert('Failed to start research: ' + (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(escapeHtml(errorData.message || 'Failed to start research'), 'error');
+ // Safe: showAlert escapes internally
+ showAlert(errorData.message || 'Failed to start research', 'error');
}
} catch (error) {
SafeLogger.error('Error running subscription:', error);
@@ -529,7 +531,8 @@ async function deleteSubscriptionDirect(subscriptionId) {
await loadSubscriptions();
} else {
const error = await response.json();
- showAlert(escapeHtml(error.error || 'Failed to delete subscription'), 'error');
+ // Safe: showAlert escapes internally
+ showAlert(error.error || 'Failed to delete subscription', 'error');
}
} catch (error) {
SafeLogger.error('Error deleting subscription:', error);
@@ -619,7 +622,8 @@ async function createNewFolder() {
if (response.ok) {
const folder = await response.json();
- showAlert(`Folder "${escapeHtml(folder.name)}" created successfully!`, 'success');
+ // Safe: showAlert escapes internally
+ showAlert(`Folder "${folder.name}" created successfully!`, 'success');
// Reload folders
await loadFolders();
@@ -631,7 +635,8 @@ async function createNewFolder() {
if (response.status === 409) {
showAlert('A folder with that name already exists', 'warning');
} else {
- showAlert(escapeHtml(error.error || 'Failed to create folder'), 'error');
+ // Safe: showAlert escapes internally
+ showAlert(error.error || 'Failed to create folder', 'error');
}
}
} catch (error) {
@@ -658,9 +663,10 @@ function showAlert(message, type) {
// Simple alert implementation
const alertDiv = document.createElement('div');
alertDiv.className = `alert alert-${type} alert-dismissible fade show`;
+ // Sanitize message: allows safe HTML tags (links, lists) while stripping dangerous ones
// bearer:disable javascript_lang_dangerous_insert_html
alertDiv.innerHTML = `
- ${message}
+ ${(window.sanitizeHtml || escapeHtml)(message)}
<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
`;
@@ -752,7 +758,8 @@ async function startScheduler() {
setTimeout(() => checkSchedulerStatus(), 1000);
} else {
const error = await response.json();
- showAlert(`Failed to start scheduler: ${escapeHtml(error.error || 'Unknown error')}`, 'error');
+ // Safe: showAlert escapes internally
+ showAlert(`Failed to start scheduler: ${error.error || 'Unknown error'}`, 'error');
toggleButton.disabled = false;
}
} catch (error) {