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: resolve XSS vulnerabilities and ESLint security warnings (#1006)

LearningCircuit3eabfd8e98db
diff --git a/package.json b/package.json
index a80818f7a9..fbfd38e5a4 100644
--- a/package.json
+++ b/package.json
@@ -4,27 +4,34 @@
"description": "Web frontend for Local Deep Research",
"private": true,
"type": "module",
+ "engines": {
+ "node": ">=20.0.0"
+ },
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview",
"update": "npm update",
"audit": "npm audit",
- "audit-fix": "npm audit fix"
+ "audit-fix": "npm audit fix",
+ "security-check": "npm audit && npm outdated",
+ "preinstall": "npm audit --audit-level=high",
+ "test": "echo \"Error: no test specified\" && exit 1"
},
"dependencies": {
"@fortawesome/fontawesome-free": "^7.0.0",
- "bootstrap": "^5.3.0",
- "bootstrap-icons": "^1.11.0",
- "chart.js": "^4.4.0",
+ "bootstrap": "^5.3.3",
+ "bootstrap-icons": "^1.11.3",
+ "chart.js": "^4.4.6",
"chartjs-adapter-date-fns": "^3.0.0",
- "chartjs-plugin-annotation": "^3.0.0",
+ "chartjs-plugin-annotation": "^3.0.1",
"date-fns": "^4.1.0",
- "highlight.js": "^11.9.0",
+ "dompurify": "^3.3.0",
+ "highlight.js": "^11.10.0",
"html2canvas": "^1.4.1",
"jspdf": "^3.0.2",
"marked": "^17.0.0",
- "socket.io-client": "^4.6.0"
+ "socket.io-client": "^4.8.1"
},
"devDependencies": {
"axe-core": "^4.8.0",
diff --git a/src/local_deep_research/web/static/js/components/custom_dropdown.js b/src/local_deep_research/web/static/js/components/custom_dropdown.js
index e221afe2b0..0e067b95d0 100644
--- a/src/local_deep_research/web/static/js/components/custom_dropdown.js
+++ b/src/local_deep_research/web/static/js/components/custom_dropdown.js
@@ -48,17 +48,26 @@
// Update dropdown content
const filteredData = dropdownInfo.getOptions();
- dropdownList.innerHTML = '';
+ // Clear dropdown list using safe DOM methods
+ while (dropdownList.firstChild) {
+ dropdownList.removeChild(dropdownList.firstChild);
+ }
if (filteredData.length === 0) {
- dropdownList.innerHTML = `<div class="custom-dropdown-no-results">${dropdownInfo.noResultsText}</div>`;
+ // Create no results message using safe DOM methods
+ const noResultsDiv = document.createElement('div');
+ noResultsDiv.className = 'ldr-custom-dropdown-no-results';
+ noResultsDiv.textContent = dropdownInfo.noResultsText;
+ dropdownList.appendChild(noResultsDiv);
return;
}
filteredData.forEach((item, index) => {
const div = document.createElement('div');
div.className = 'ldr-custom-dropdown-item';
- div.innerHTML = item.label;
+
+ // Use safe text content instead of innerHTML to prevent XSS
+ window.safeSetTextContent(div, item.label);
div.setAttribute('data-value', item.value);
div.addEventListener('click', () => {
// Set display value
@@ -232,10 +241,17 @@
const searchText = input.value;
const filteredData = filterOptions(searchText, showAllOptions);
- dropdownList.innerHTML = '';
+ // Clear dropdown list using safe DOM methods
+ while (dropdownList.firstChild) {
+ dropdownList.removeChild(dropdownList.firstChild);
+ }
if (filteredData.length === 0) {
- dropdownList.innerHTML = `<div class="custom-dropdown-no-results">${noResultsText}</div>`;
+ // Create no results message using safe DOM methods
+ const noResultsDiv = document.createElement('div');
+ noResultsDiv.className = 'ldr-custom-dropdown-no-results';
+ noResultsDiv.textContent = noResultsText;
+ dropdownList.appendChild(noResultsDiv);
if (allowCustomValues && searchText.trim()) {
const customOption = document.createElement('div');
@@ -250,7 +266,11 @@
filteredData.forEach((item, index) => {
const div = document.createElement('div');
div.className = 'ldr-custom-dropdown-item';
- div.innerHTML = highlightText(item.label, searchText);
+
+ // Sanitize highlighted text to prevent XSS
+ const highlightedText = highlightText(item.label, searchText);
+ // Allow basic HTML tags for highlighting but escape dangerous content
+ window.safeSetInnerHTML(div, highlightedText, true);
div.setAttribute('data-value', item.value);
div.addEventListener('click', (e) => {
e.preventDefault();
diff --git a/src/local_deep_research/web/static/js/components/details.js b/src/local_deep_research/web/static/js/components/details.js
index 7d55457c53..878b007aea 100644
--- a/src/local_deep_research/web/static/js/components/details.js
+++ b/src/local_deep_research/web/static/js/components/details.js
@@ -116,37 +116,58 @@
// Display domain list
const domainList = document.getElementById('domain-list');
if (data.domains && data.domains.length > 0) {
- domainList.innerHTML = data.domains.map(domain => `
+ // Use DOMPurify for secure HTML rendering
+ const domainHtml = data.domains.map(domain => `
<div style="display: flex; justify-content: space-between; align-items: center; padding: 0.75rem; border-bottom: 1px solid var(--border-color);">
- <span style="font-weight: 500;">${domain.domain}</span>
+ <span style="font-weight: 500;">${window.escapeHtml(domain.domain)}</span>
<div style="display: flex; gap: 1rem; align-items: center;">
<span style="background: var(--primary-color); color: white; padding: 0.25rem 0.5rem; border-radius: 0.25rem; font-size: 0.875rem;">
- ${domain.count} links
+ ${window.escapeHtml(domain.count)} links
</span>
<span style="color: var(--text-secondary); font-size: 0.875rem;">
- ${domain.percentage}%
+ ${window.escapeHtml(domain.percentage)}%
</span>
</div>
</div>
`).join('');
+ if (window.sanitizeHtml) {
+ domainList.innerHTML = window.sanitizeHtml(domainHtml);
+ } else if (window.escapeHtml) {
+ domainList.innerHTML = domainHtml; // Already escaped individual fields above
+ } else {
+ domainList.textContent = 'Domain data unavailable (security module not loaded)';
+ }
} else {
- domainList.innerHTML = '<div style="text-align: center; color: var(--text-secondary); padding: 1rem;">No domain data available</div>';
+ if (window.safeSetInnerHTML) {
+ window.safeSetInnerHTML(domainList, '<div style="text-align: center; color: var(--text-secondary); padding: 1rem;">No domain data available</div>', true);
+ } else {
+ domainList.textContent = 'No domain data available';
+ }
}
// Display resource samples
const resourceSample = document.getElementById('resource-sample');
if (data.resources && data.resources.length > 0) {
- resourceSample.innerHTML = data.resources.map(resource => `
+ const resourceHtml = data.resources.map(resource => `
<div style="padding: 0.75rem; border-bottom: 1px solid var(--border-color);">
- <div style="font-weight: 500; margin-bottom: 0.25rem;">${resource.title}</div>
- <a href="${resource.url}" target="_blank" style="color: var(--primary-color); text-decoration: none; font-size: 0.875rem; word-break: break-all;">
- ${resource.url}
+ <div style="font-weight: 500; margin-bottom: 0.25rem;">${window.escapeHtml ? window.escapeHtml(resource.title) : resource.title}</div>
+ <a href="${window.escapeHtmlAttribute ? window.escapeHtmlAttribute(resource.url) : resource.url}" target="_blank" style="color: var(--primary-color); text-decoration: none; font-size: 0.875rem; word-break: break-all;">
+ ${window.escapeHtml ? window.escapeHtml(resource.url) : resource.url}
</a>
- ${resource.preview ? `<div style="color: var(--text-secondary); font-size: 0.875rem; margin-top: 0.5rem;">${resource.preview}</div>` : ''}
+ ${resource.preview ? `<div style="color: var(--text-secondary); font-size: 0.875rem; margin-top: 0.5rem;">${window.escapeHtml ? window.escapeHtml(resource.preview) : resource.preview}</div>` : ''}
</div>
`).join('');
+ if (window.sanitizeHtml) {
+ resourceSample.innerHTML = window.sanitizeHtml(resourceHtml);
+ } else {
+ resourceSample.innerHTML = resourceHtml; // Fields already escaped above
+ }
} else {
- resourceSample.innerHTML = '<div style="text-align: center; color: var(--text-secondary); padding: 1rem;">No resource samples available</div>';
+ if (window.safeSetInnerHTML) {
+ window.safeSetInnerHTML(resourceSample, '<div style="text-align: center; color: var(--text-secondary); padding: 1rem;">No resource samples available</div>', true);
+ } else {
+ resourceSample.textContent = 'No resource samples available';
+ }
}
// Create generic source type pie chart
diff --git a/src/local_deep_research/web/static/js/components/research.js b/src/local_deep_research/web/static/js/components/research.js
index 97967e8e8b..8ae1e97daa 100644
--- a/src/local_deep_research/web/static/js/components/research.js
+++ b/src/local_deep_research/web/static/js/components/research.js
@@ -2050,18 +2050,15 @@
// Disable the submit button to prevent multiple submissions
startBtn.disabled = true;
- startBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Starting...';
-
- // Show loading overlay for better feedback
- const loadingOverlay = document.createElement('div');
- loadingOverlay.className = 'ldr-loading-overlay';
- loadingOverlay.innerHTML = `
- <div class="loading-content" style="text-align: center;">
- <i class="fas fa-spinner fa-spin fa-3x" style="margin-bottom: 20px;"></i>
- <h3 style="margin: 10px 0;">Preparing your research...</h3>
- <p style="opacity: 0.8;">Securing settings and initializing search engines</p>
- </div>
- `;
+
+ // Use centralized security utilities for button update
+ window.safeUpdateButton(startBtn, 'fa-spinner', ' Starting...', true);
+
+ // Show loading overlay for better feedback using centralized utility
+ const loadingOverlay = window.createSafeLoadingOverlay({
+ title: 'Preparing your research...',
+ description: 'Securing settings and initializing search engines'
+ });
loadingOverlay.style.cssText = `
position: fixed;
top: 0;
@@ -2113,7 +2110,8 @@
// Re-enable the button
startBtn.disabled = false;
- startBtn.innerHTML = '<i class="fas fa-rocket"></i> Start Research';
+ // Use centralized security utilities for button reset
+ window.safeUpdateButton(startBtn, 'fa-rocket', ' Start Research');
// Remove loading overlay
const overlay = document.querySelector('.ldr-loading-overlay');
@@ -2166,7 +2164,8 @@
// Re-enable the button
startBtn.disabled = false;
- startBtn.innerHTML = '<i class="fas fa-rocket"></i> Start Research';
+ // Use centralized security utilities for button reset
+ window.safeUpdateButton(startBtn, 'fa-rocket', ' Start Research');
// Remove loading overlay
const overlay = document.querySelector('.ldr-loading-overlay');
@@ -2181,7 +2180,8 @@
// Re-enable the button
startBtn.disabled = false;
- startBtn.innerHTML = '<i class="fas fa-rocket"></i> Start Research';
+ // Use centralized security utilities for button reset
+ window.safeUpdateButton(startBtn, 'fa-rocket', ' Start Research');
// Remove loading overlay
const overlay = document.querySelector('.ldr-loading-overlay');
@@ -2195,46 +2195,22 @@
* @param {string} type - The alert type (success, error, warning, info)
*/
function showAlert(message, type = 'info') {
- const alertContainer = document.getElementById('research-alert');
- if (!alertContainer) return;
-
- // Clear any existing alerts
- alertContainer.innerHTML = '';
-
- // Create the alert element
- const alert = document.createElement('div');
- alert.className = `alert alert-${type}`;
- alert.innerHTML = `
- <i class="fas ${type === 'success' ? 'fa-check-circle' :
- type === 'error' ? 'fa-exclamation-circle' :
- type === 'warning' ? 'fa-exclamation-triangle' :
- 'fa-info-circle'}"></i>
- ${message}
- <span class="alert-close">&times;</span>
- `;
-
- // Add click handler for the close button
- const closeBtn = alert.querySelector('.ldr-alert-close');
- if (closeBtn) {
- closeBtn.addEventListener('click', () => {
- alert.remove();
- alertContainer.style.display = 'none';
- });
- }
+ // Use centralized security utility for alerts with auto-hide functionality
+ window.showSafeAlert('research-alert', message, type);
- // Add to the container and show it
- alertContainer.appendChild(alert);
- alertContainer.style.display = 'block';
-
- // Auto-hide after 5 seconds
- setTimeout(() => {
- if (alertContainer.contains(alert)) {
- alert.remove();
- if (alertContainer.children.length === 0) {
- alertContainer.style.display = 'none';
+ // Add auto-hide functionality after 5 seconds (preserving dev branch behavior)
+ const alertContainer = document.getElementById('research-alert');
+ if (alertContainer && alertContainer.firstChild) {
+ const alert = alertContainer.firstChild;
+ setTimeout(() => {
+ if (alertContainer.contains(alert)) {
+ alert.remove();
+ if (alertContainer.children.length === 0) {
+ alertContainer.style.display = 'none';
+ }
}
- }
- }, 5000);
+ }, 5000);
+ }
}
// Initialize research component when DOM is loaded
diff --git a/src/local_deep_research/web/static/js/components/results.js b/src/local_deep_research/web/static/js/components/results.js
index 4fd4755eda..1bf613491c 100644
--- a/src/local_deep_research/web/static/js/components/results.js
+++ b/src/local_deep_research/web/static/js/components/results.js
@@ -552,9 +552,18 @@
// Markdown content
content = data.markdown;
} else if (data.html) {
- // HTML content
- resultsContainer.innerHTML = data.html;
- return; // Return early since we've set HTML directly
+ // HTML content - sanitize for security
+ if (window.sanitizeHtml) {
+ resultsContainer.innerHTML = window.sanitizeHtml(data.html);
+ } else if (window.escapeHtml) {
+ // Fallback to HTML escaping if DOMPurify not available
+ resultsContainer.innerHTML = window.escapeHtml(data.html);
+ } else {
+ // Last resort: use textContent to prevent XSS if no sanitization available
+ console.warn('XSS protection not available, displaying HTML as text');
+ resultsContainer.textContent = data.html;
+ }
+ return; // Return early since we've set content directly
} else if (data.text) {
// Text content
content = data.text;
diff --git a/src/local_deep_research/web/static/js/components/settings.js b/src/local_deep_research/web/static/js/components/settings.js
index 368d9ecd94..16e4272e71 100644
--- a/src/local_deep_research/web/static/js/components/settings.js
+++ b/src/local_deep_research/web/static/js/components/settings.js
@@ -1459,11 +1459,14 @@
const kdfIter = settings.kdf_iterations || 256000;
const kdfIterDisplay = kdfIter >= 1000 ? `${kdfIter/1000}k` : kdfIter;
+ // Sanitize data directory path to prevent XSS
+ const safeDataDir = window.escapeHtml(data.data_directory);
+
html += `
<div class="data-location-detailed">
<div class="data-path">
<i class="fas fa-folder"></i>
- <code>${data.data_directory}</code>
+ <code>${safeDataDir}</code>
</div>
<div class="security-status encrypted">
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.js
new file mode 100644
index 0000000000..aed271cb3c
--- /dev/null
+++ b/src/local_deep_research/web/static/js/security/xss-protection.js
@@ -0,0 +1,387 @@
+/**
+ * XSS Protection utilities for Local Deep Research
+ *
+ * This module provides secure HTML sanitization functions to prevent
+ * cross-site scripting (XSS) attacks when rendering dynamic content.
+ * Uses DOMPurify for proven, security-reviewed HTML sanitization.
+ */
+
+(function() {
+ 'use strict';
+
+ // Check if DOMPurify is available (should be loaded via app.js/Vite)
+ const hasDOMPurify = typeof DOMPurify !== 'undefined';
+
+ /**
+ * HTML entity encoding map for XSS prevention
+ */
+ const HTML_ESCAPE_MAP = {
+ '&': '&amp;',
+ '<': '&lt;',
+ '>': '&gt;',
+ '"': '&quot;',
+ "'": '&#39;',
+ '/': '&#x2F;'
+ };
+
+ /**
+ * DOMPurify configuration for secure sanitization
+ */
+ const SANITIZE_CONFIG = {
+ ALLOWED_TAGS: ['b', 'i', 'em', 'strong', 'span', 'br', 'p', 'div', 'ul', 'ol', 'li', 'a', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'],
+ ALLOWED_ATTR: ['class', 'id', 'href', 'title', 'alt', 'target'],
+ ALLOW_DATA_ATTR: false,
+ FORBID_TAGS: ['script', 'iframe', 'object', 'embed', 'form', 'input', 'button', 'style', 'meta', 'link'],
+ FORBID_ATTR: ['onerror', 'onload', 'onclick', 'onmouseover', 'onfocus', 'onblur', 'onchange', 'onsubmit', 'on*'],
+ KEEP_CONTENT: false,
+ SANITIZE_DOM: true,
+ SANITIZE_NAMED_PROPS: true,
+ SAFE_FOR_TEMPLATES: true,
+ WHOLE_DOCUMENT: false,
+ RETURN_DOM: false,
+ RETURN_DOM_FRAGMENT: false,
+ RETURN_DOM_IMPORT: false,
+ CUSTOM_ELEMENT_HANDLING: {
+ tagNameCheck: null,
+ attributeNameCheck: null,
+ allowCustomizedBuiltInElements: false
+ }
+ };
+
+ /**
+ * Escape HTML entities in a string to prevent XSS
+ * @param {string} text - The text to escape
+ * @returns {string} - The escaped text safe for HTML content
+ */
+ function escapeHtml(text) {
+ if (typeof text !== 'string') {
+ text = String(text);
+ }
+
+ return text.replace(/[&<>"'/]/g, (match) => HTML_ESCAPE_MAP[match]);
+}
+
+/**
+ * Escape HTML attributes to prevent XSS
+ * @param {string} text - The text to escape for attribute context
+ * @returns {string} - The escaped text safe for HTML attributes
+ */
+function escapeHtmlAttribute(text) {
+ if (typeof text !== 'string') {
+ text = String(text);
+ }
+
+ // For attributes, we need to escape quotes and ampersands
+ return text.replace(/["&'<>]/g, (match) => HTML_ESCAPE_MAP[match]);
+}
+
+/**
+ * Safely set innerHTML with content sanitization using DOMPurify
+ * @param {Element} element - The DOM element to update
+ * @param {string} content - The content to set (will be sanitized)
+ * @param {boolean} allowHtmlTags - If true, allows basic HTML tags, otherwise escapes everything
+ */
+function safeSetInnerHTML(element, content, allowHtmlTags = false) {
+ if (!element || !content) {
+ return;
+ }
+
+ const contentString = String(content);
+
+ if (allowHtmlTags && hasDOMPurify) {
+ // Use DOMPurify for secure HTML sanitization
+ const sanitized = DOMPurify.sanitize(contentString, SANITIZE_CONFIG);
+ element.innerHTML = sanitized;
+ } else if (allowHtmlTags) {
+ // DOMPurify not available but HTML requested - escape all HTML for safety
+ console.warn('DOMPurify not available, escaping HTML instead of sanitizing');
+ element.textContent = contentString;
+ } else {
+ // Escape all HTML - use textContent for maximum security
+ element.textContent = contentString;
+ }
+}
+
+/**
+ * Create a safe DOM element with text content
+ * @param {string} tagName - The HTML tag name
+ * @param {string} text - The text content (will be escaped)
+ * @param {Object} attributes - Optional attributes object
+ * @param {string[]} classNames - Optional CSS class names
+ * @returns {Element} - The created DOM element
+ */
+function safeCreateElement(tagName, text = '', attributes = {}, classNames = []) {
+ const element = document.createElement(tagName);
+
+ if (text) {
+ element.textContent = text; // Safe - no HTML interpretation
+ }
+
+ // Set attributes safely
+ Object.entries(attributes).forEach(([key, value]) => {
+ if (key && value !== null && value !== undefined) {
+ element.setAttribute(key, escapeHtmlAttribute(String(value)));
+ }
+ });
+
+ // Add CSS classes safely
+ if (classNames.length > 0) {
+ element.className = classNames.join(' ');
+ }
+
+ return element;
+}
+
+/**
+ * Safe text content setter that prevents XSS
+ * @param {Element} element - The DOM element to update
+ * @param {string} content - The content to set safely
+ */
+function safeSetTextContent(element, content) {
+ if (!element) {
+ return;
+ }
+
+ element.textContent = String(content || '');
+}
+
+/**
+ * Create a safe alert message element
+ * @param {string} message - The alert message (will be escaped)
+ * @param {string} type - Alert type (success, error, warning, info)
+ * @returns {Element} - The created alert element
+ */
+function createSafeAlertElement(message, type = 'info') {
+ const alert = document.createElement('div');
+ alert.className = `alert alert-${type}`;
+
+ // Create icon
+ const iconMap = {
+ 'success': 'fa-check-circle',
+ 'error': 'fa-exclamation-circle',
+ 'warning': 'fa-exclamation-triangle',
+ 'info': 'fa-info-circle'
+ };
+
+ const icon = document.createElement('i');
+ icon.className = `fas ${iconMap[type] || iconMap['info']}`;
+
+ // Create message text (escaped)
+ const messageText = document.createElement('span');
+ messageText.textContent = message; // Safe - textContent prevents HTML injection
+
+ // Create close button
+ const closeBtn = document.createElement('span');
+ closeBtn.className = 'ldr-alert-close';
+ closeBtn.textContent = '×';
+ closeBtn.addEventListener('click', () => {
+ alert.remove();
+ });
+
+ // Assemble alert
+ alert.appendChild(icon);
+ alert.appendChild(messageText);
+ alert.appendChild(closeBtn);
+
+ return alert;
+}
+
+/**
+ * Secure HTML sanitization using DOMPurify
+ * @param {string} dirty - The potentially dirty HTML string
+ * @param {Object} config - Optional DOMPurify configuration overrides
+ * @returns {string} - The sanitized HTML string
+ */
+function sanitizeHtml(dirty, config = {}) {
+ if (!dirty) return '';
+
+ if (hasDOMPurify) {
+ const finalConfig = { ...SANITIZE_CONFIG, ...config };
+ return DOMPurify.sanitize(String(dirty), finalConfig);
+ } else {
+ // Fallback: escape all HTML if DOMPurify is not available
+ console.warn('DOMPurify not available, falling back to HTML escaping');
+ return escapeHtml(String(dirty));
+ }
+}
+
+/**
+ * Validate and sanitize user input for safe display
+ * @param {any} input - The input to validate and sanitize
+ * @param {Object} options - Sanitization options
+ * @returns {string} - The sanitized string
+ */
+function sanitizeUserInput(input, options = {}) {
+ const {
+ maxLength = 10000,
+ allowLineBreaks = true,
+ trimWhitespace = true,
+ allowHtml = false
+ } = options;
+
+ if (input === null || input === undefined) {
+ return '';
+ }
+
+ let sanitized = String(input);
+
+ // Trim if requested
+ if (trimWhitespace) {
+ sanitized = sanitized.trim();
+ }
+
+ // Enforce max length
+ if (sanitized.length > maxLength) {
+ sanitized = sanitized.substring(0, maxLength);
+ }
+
+ // Handle line breaks
+ if (allowLineBreaks) {
+ sanitized = sanitized.replace(/\r\n/g, '\n').replace(/\r/g, '\n');
+ }
+
+ // Either escape HTML or sanitize it
+ if (allowHtml) {
+ return sanitizeHtml(sanitized);
+ } else {
+ return escapeHtml(sanitized);
+ }
+}
+
+ // Export to global scope
+ window.XSSProtection = {
+ escapeHtml: escapeHtml,
+ escapeHtmlAttribute: escapeHtmlAttribute,
+ safeSetInnerHTML: safeSetInnerHTML,
+ safeCreateElement: safeCreateElement,
+ safeSetTextContent: safeSetTextContent,
+ createSafeAlertElement: createSafeAlertElement,
+ sanitizeUserInput: sanitizeUserInput,
+ sanitizeHtml: sanitizeHtml
+ };
+
+ /**
+ * Safely update button content with icon and text
+ * @param {HTMLElement} button - The button element to update
+ * @param {string} iconClass - Font Awesome icon class (without 'fas')
+ * @param {string} text - Button text content
+ * @param {boolean} addSpinner - Whether to add spinner animation
+ */
+ function safeUpdateButton(button, iconClass, text, addSpinner = false) {
+ if (!button) return;
+
+ // Clear existing content
+ while (button.firstChild) {
+ button.removeChild(button.firstChild);
+ }
+
+ // Create icon
+ const icon = document.createElement('i');
+ icon.className = `fas ${iconClass}`;
+ if (addSpinner) {
+ icon.className += ' fa-spin';
+ }
+
+ // Add icon and text
+ button.appendChild(icon);
+ if (text) {
+ button.appendChild(document.createTextNode(text));
+ }
+ }
+
+ /**
+ * Create a loading overlay with safe DOM manipulation
+ * @param {Object} options - Loading overlay options
+ * @returns {HTMLElement} - The created loading overlay element
+ */
+ function createSafeLoadingOverlay(options = {}) {
+ const {
+ iconClass = 'fa-spinner fa-spin fa-3x',
+ title = 'Loading...',
+ description = 'Please wait...',
+ iconMarginBottom = '20px',
+ titleMargin = '10px 0',
+ textOpacity = '0.8'
+ } = options;
+
+ const overlay = document.createElement('div');
+ overlay.className = 'ldr-loading-overlay';
+
+ const content = document.createElement('div');
+ content.className = 'ldr-loading-content';
+ content.style.textAlign = 'center';
+
+ // Icon
+ const icon = document.createElement('i');
+ icon.className = `fas ${iconClass}`;
+ icon.style.marginBottom = iconMarginBottom;
+
+ // Title
+ const titleElement = document.createElement('h3');
+ titleElement.style.margin = titleMargin;
+ titleElement.textContent = title;
+
+ // Description
+ const descriptionElement = document.createElement('p');
+ descriptionElement.style.opacity = textOpacity;
+ descriptionElement.textContent = description;
+
+ // Assemble overlay
+ content.appendChild(icon);
+ content.appendChild(titleElement);
+ content.appendChild(descriptionElement);
+ overlay.appendChild(content);
+
+ return overlay;
+ }
+
+ /**
+ * Safely set CSS styles on an element
+ * @param {HTMLElement} element - The element to style
+ * @param {Object} styles - Style object with CSS properties
+ */
+ function safeSetStyles(element, styles) {
+ if (!element || !styles) return;
+
+ Object.entries(styles).forEach(([property, value]) => {
+ element.style[property] = value;
+ });
+ }
+
+ /**
+ * Show a safe alert message
+ * @param {string} containerId - ID of the alert container
+ * @param {string} message - Alert message (will be sanitized)
+ * @param {string} type - Alert type (success, error, warning, info)
+ */
+ function showSafeAlert(containerId, message, type = 'info') {
+ const alertContainer = document.getElementById(containerId);
+ if (!alertContainer) return;
+
+ // Clear existing alerts
+ while (alertContainer.firstChild) {
+ alertContainer.removeChild(alertContainer.firstChild);
+ }
+
+ // Create alert using our secure method
+ const alert = createSafeAlertElement(message, type);
+ alertContainer.appendChild(alert);
+ }
+
+ // Also export individual functions for convenience
+ window.escapeHtml = escapeHtml;
+ window.escapeHtmlAttribute = escapeHtmlAttribute;
+ window.safeSetInnerHTML = safeSetInnerHTML;
+ window.safeCreateElement = safeCreateElement;
+ window.safeSetTextContent = safeSetTextContent;
+ window.createSafeAlertElement = createSafeAlertElement;
+ window.sanitizeUserInput = sanitizeUserInput;
+ window.sanitizeHtml = sanitizeHtml;
+
+ // Export UI helper functions
+ window.safeUpdateButton = safeUpdateButton;
+ window.createSafeLoadingOverlay = createSafeLoadingOverlay;
+ window.safeSetStyles = safeSetStyles;
+ window.showSafeAlert = showSafeAlert;
+
+})();
diff --git a/src/local_deep_research/web/templates/base.html b/src/local_deep_research/web/templates/base.html
index 7f4ba1c511..48489133bd 100644
--- a/src/local_deep_research/web/templates/base.html
+++ b/src/local_deep_research/web/templates/base.html
@@ -111,6 +111,9 @@
<script src="/static/js/services/socket.js"></script>
<script src="/static/js/services/keyboard.js"></script>
+ <!-- Security Utilities -->
+ <script src="/static/js/security/xss-protection.js"></script>
+
<!-- Shared Components -->
<script src="/static/js/components/logpanel.js"></script>
diff --git a/tests/ui_tests/test-xss-protection.html b/tests/ui_tests/test-xss-protection.html
new file mode 100644
index 0000000000..19bdbb0d6a
--- /dev/null
+++ b/tests/ui_tests/test-xss-protection.html
@@ -0,0 +1,56 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <title>XSS Protection Test</title>
+ <!-- Load the XSS protection script -->
+ <script src="./src/local_deep_research/web/static/js/security/xss-protection.js"></script>
+ <script>
+ // Wait for XSS protection to load
+ document.addEventListener('DOMContentLoaded', () => {
+ // Test XSS protection functions
+ if (!window.XSSProtection) {
+ console.error('XSS protection not loaded!');
+ return;
+ }
+
+ const { escapeHtml, sanitizeHtml, sanitizeUserInput } = window.XSSProtection;
+
+ // Test cases
+ const testCases = [
+ '<script>alert("XSS")</script>',
+ '<img src="x" onerror="alert(\'XSS\')">',
+ '<iframe src="javascript:alert(\'XSS\')"></iframe>',
+ '<div onclick="alert(\'XSS\')">Click me</div>',
+ '<a href="javascript:alert(\'XSS\')">Link</a>',
+ 'Normal text <b>bold</b> and <i>italic</i>',
+ '<div class="safe">Safe content</div>'
+ ];
+
+ console.log('Testing XSS Protection:');
+ testCases.forEach((testCase, index) => {
+ console.log(`\nTest ${index + 1}: ${testCase}`);
+ console.log('escapeHtml:', escapeHtml(testCase));
+ console.log('sanitizeHtml:', sanitizeHtml(testCase));
+ console.log('sanitizeUserInput:', sanitizeUserInput(testCase));
+ });
+
+ // DOM test
+ const testDiv = document.getElementById('test');
+ const dangerousContent = '<script>alert("XSS Test")</script><b>Safe content</b>';
+
+ // Test safeSetInnerHTML
+ if (window.safeSetInnerHTML) {
+ window.safeSetInnerHTML(testDiv, dangerousContent, true);
+ console.log('DOM test completed - check if script executed (it should not)');
+ }
+ });
+ </script>
+</head>
+<body>
+ <h1>XSS Protection Test</h1>
+ <p>Check browser console for test results.</p>
+ <div id="test"></div>
+</body>
+</html>