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 security vulnerabilities in URL handling (PR #793)

LearningCircuitecd913787a81
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index ae0a477697..03ddd0d03a 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -93,3 +93,9 @@ repos:
language: script
files: \.py$
description: "Prevent logging of sensitive data"
+ - id: check-url-security
+ name: Check for unsafe URL handling in JavaScript
+ entry: .pre-commit-hooks/check-url-security.py
+ language: script
+ files: \.js$
+ description: "Ensure JavaScript code validates URLs to prevent XSS attacks"
diff --git a/.pre-commit-hooks/check-url-security.py b/.pre-commit-hooks/check-url-security.py
new file mode 100755
index 0000000000..e472d7ac89
--- /dev/null
+++ b/.pre-commit-hooks/check-url-security.py
@@ -0,0 +1,149 @@
+#!/usr/bin/env python3
+"""
+Pre-commit hook to check for unsafe URL scheme validation in JavaScript files.
+
+This hook ensures that JavaScript code properly validates URLs to prevent
+XSS attacks through javascript:, data:, and vbscript: schemes.
+"""
+
+import sys
+import re
+
+
+def check_url_validation(file_path):
+ """
+ Check if JavaScript file has proper URL validation.
+
+ Returns list of issues found.
+ """
+ issues = []
+
+ with open(file_path, "r", encoding="utf-8") as f:
+ content = f.read()
+ lines = content.split("\n")
+
+ # Note: More advanced pattern checking could be added here
+ # Currently focusing on basic URL validation presence
+
+ # Check if the file imports or includes URL validation
+ has_url_validator = (
+ "URLValidator" in content
+ or "isUnsafeScheme" in content
+ or "isSafeUrl" in content
+ )
+
+ # Look for URL handling patterns
+ url_handling_patterns = [
+ r"\.href\s*=",
+ r"\.src\s*=",
+ r"window\.open\s*\(",
+ r"window\.location",
+ r"new\s+URL\s*\(",
+ ]
+
+ handles_urls = any(
+ re.search(pattern, content) for pattern in url_handling_patterns
+ )
+
+ # If the file handles URLs but doesn't have validation, that's concerning
+ if handles_urls and not has_url_validator:
+ # Check for basic javascript: protection at least
+ has_basic_protection = "javascript:" in content and (
+ "startsWith" in content
+ or "includes" in content
+ or "indexOf" in content
+ )
+
+ if not has_basic_protection:
+ issues.append(
+ f"{file_path}: File handles URLs but lacks URL validation checks"
+ )
+
+ # Check for specific problematic patterns
+ for line_num, line in enumerate(lines, 1):
+ # Skip comments
+ if line.strip().startswith("//") or line.strip().startswith("*"):
+ continue
+
+ # Check for .href or .src assignments without proper validation
+ if re.search(r"\.(href|src)\s*=\s*[a-zA-Z_$]", line):
+ # Check if it's preceded by validation
+ context_start = max(0, line_num - 5)
+ context = "\n".join(lines[context_start:line_num])
+
+ if not any(
+ check in context
+ for check in [
+ "URLValidator",
+ "isUnsafeScheme",
+ "isSafeUrl",
+ "javascript:",
+ "data:",
+ "vbscript:",
+ ]
+ ):
+ issues.append(
+ f"{file_path}:{line_num}: URL assignment without validation: {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:]:
+ # Only check JavaScript files
+ if not file_path.endswith(".js"):
+ continue
+
+ # Skip test files and vendor files
+ if any(
+ skip in file_path
+ for skip in [
+ "test",
+ "spec",
+ "vendor",
+ "node_modules",
+ "dist",
+ "build",
+ ".min.js",
+ ]
+ ):
+ continue
+
+ try:
+ issues = check_url_validation(file_path)
+ all_issues.extend(issues)
+ except Exception as e:
+ print(f"Error checking {file_path}: {e}")
+ continue
+
+ if all_issues:
+ print("❌ URL Security Issues Found:")
+ print("-" * 60)
+ for issue in all_issues:
+ print(f" • {issue}")
+ print("-" * 60)
+ print("\nTo fix these issues:")
+ print("1. Import the URLValidator from the security module")
+ print(
+ "2. Use URLValidator.isUnsafeScheme() to check for unsafe schemes"
+ )
+ print("3. Use URLValidator.isSafeUrl() before assigning to href/src")
+ print("\nExample:")
+ print(" if (!URLValidator.isUnsafeScheme(url)) {")
+ print(" element.href = url;")
+ print(" }")
+ return 1
+
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/src/local_deep_research/security/url_validator.py b/src/local_deep_research/security/url_validator.py
new file mode 100644
index 0000000000..d470c0c459
--- /dev/null
+++ b/src/local_deep_research/security/url_validator.py
@@ -0,0 +1,388 @@
+"""
+Centralized URL validation utilities for security.
+
+This module provides secure URL validation to prevent XSS attacks,
+data exfiltration, and other URL-based security vulnerabilities.
+"""
+
+import re
+from typing import Optional, List
+from urllib.parse import urlparse
+from loguru import logger
+
+
+class URLValidator:
+ """Centralized URL validation for security."""
+
+ # Unsafe URL schemes that could lead to XSS or data exfiltration
+ UNSAFE_SCHEMES = (
+ "javascript",
+ "data",
+ "vbscript",
+ "about",
+ "blob",
+ "file",
+ )
+
+ # Safe schemes for external links
+ SAFE_SCHEMES = ("http", "https", "ftp", "ftps")
+
+ # Email scheme
+ EMAIL_SCHEME = "mailto"
+
+ # Common academic/research domains that should be allowed
+ TRUSTED_ACADEMIC_DOMAINS = (
+ "arxiv.org",
+ "pubmed.ncbi.nlm.nih.gov",
+ "ncbi.nlm.nih.gov",
+ "biorxiv.org",
+ "medrxiv.org",
+ "doi.org",
+ "nature.com",
+ "science.org",
+ "sciencedirect.com",
+ "springer.com",
+ "wiley.com",
+ "plos.org",
+ "pnas.org",
+ "ieee.org",
+ "acm.org",
+ )
+
+ @staticmethod
+ def is_unsafe_scheme(url: str) -> bool:
+ """
+ Check if a URL uses an unsafe scheme.
+
+ Args:
+ url: The URL to check
+
+ Returns:
+ True if the URL uses an unsafe scheme, False otherwise
+ """
+ if not url:
+ return False
+
+ # Normalize the URL - trim whitespace and convert to lowercase
+ normalized_url = url.strip().lower()
+
+ # Check for unsafe schemes
+ for scheme in URLValidator.UNSAFE_SCHEMES:
+ if normalized_url.startswith(f"{scheme}:"):
+ logger.warning(
+ f"Unsafe URL scheme detected: {scheme} in URL: {url[:100]}"
+ )
+ return True
+
+ return False
+
+ @staticmethod
+ def is_safe_url(
+ url: str,
+ require_scheme: bool = True,
+ allow_fragments: bool = True,
+ allow_mailto: bool = False,
+ trusted_domains: Optional[List[str]] = None,
+ ) -> bool:
+ """
+ Validate if a URL is safe to use.
+
+ Args:
+ url: The URL to validate
+ require_scheme: Whether to require an explicit scheme
+ allow_fragments: Whether to allow fragment identifiers (#)
+ allow_mailto: Whether to allow mailto: links
+ trusted_domains: Optional list of trusted domains
+
+ Returns:
+ True if the URL is safe, False otherwise
+ """
+ if not url or not isinstance(url, str):
+ return False
+
+ # Check for unsafe schemes first
+ if URLValidator.is_unsafe_scheme(url):
+ return False
+
+ # Handle fragment-only URLs
+ if url.startswith("#"):
+ return allow_fragments
+
+ # Parse the URL
+ try:
+ parsed = urlparse(url)
+ except Exception as e:
+ logger.warning(f"Failed to parse URL '{url[:100]}': {e}")
+ return False
+
+ # Check scheme
+ if not parsed.scheme:
+ if require_scheme:
+ return False
+ # If no scheme is required, assume http/https
+ parsed = urlparse(f"http://{url}")
+
+ scheme_lower = parsed.scheme.lower()
+
+ # Check if it's a mailto link
+ if scheme_lower == URLValidator.EMAIL_SCHEME:
+ return allow_mailto
+
+ # Check if it's a safe scheme
+ if scheme_lower not in URLValidator.SAFE_SCHEMES:
+ logger.warning(f"Unsafe URL scheme: {scheme_lower}")
+ return False
+
+ # Validate domain if trusted domains are specified
+ if trusted_domains and parsed.hostname:
+ hostname_lower = parsed.hostname.lower()
+ if not any(
+ hostname_lower == domain.lower()
+ or hostname_lower.endswith(f".{domain.lower()}")
+ for domain in trusted_domains
+ ):
+ logger.warning(
+ f"URL domain not in trusted list: {parsed.hostname}"
+ )
+ return False
+
+ # Check for suspicious patterns in the URL
+ if URLValidator._has_suspicious_patterns(url):
+ return False
+
+ return True
+
+ @staticmethod
+ def _has_suspicious_patterns(url: str) -> bool:
+ """
+ Check for suspicious patterns in URLs that might indicate attacks.
+
+ Args:
+ url: The URL to check
+
+ Returns:
+ True if suspicious patterns are found, False otherwise
+ """
+ suspicious_patterns = [
+ # Double encoding
+ r"%25[0-9a-fA-F]{2}",
+ # Null bytes
+ r"%00",
+ # Unicode encoding bypass attempts
+ r"\\u[0-9a-fA-F]{4}",
+ # HTML entity encoding
+ r"&(#x?[0-9a-fA-F]+|[a-zA-Z]+);",
+ ]
+
+ for pattern in suspicious_patterns:
+ if re.search(pattern, url, re.IGNORECASE):
+ logger.warning(f"Suspicious pattern found in URL: {pattern}")
+ return True
+
+ return False
+
+ @staticmethod
+ def sanitize_url(url: str, default_scheme: str = "https") -> Optional[str]:
+ """
+ Sanitize a URL by adding a scheme if missing and validating it.
+
+ Args:
+ url: The URL to sanitize
+ default_scheme: The default scheme to add if missing
+
+ Returns:
+ Sanitized URL or None if the URL is unsafe
+ """
+ if not url:
+ return None
+
+ # Check for unsafe schemes
+ if URLValidator.is_unsafe_scheme(url):
+ return None
+
+ # Strip whitespace
+ url = url.strip()
+
+ # Parse the URL
+ try:
+ parsed = urlparse(url)
+
+ # Add scheme if missing
+ if not parsed.scheme:
+ url = f"{default_scheme}://{url}"
+ parsed = urlparse(url)
+
+ # Validate the final URL
+ if URLValidator.is_safe_url(url, require_scheme=True):
+ return url
+
+ except Exception as e:
+ logger.warning(f"Failed to sanitize URL '{url[:100]}': {e}")
+
+ return None
+
+ @staticmethod
+ def is_academic_url(url: str) -> bool:
+ """
+ Check if a URL is from a known academic/research domain.
+
+ Args:
+ url: The URL to check
+
+ Returns:
+ True if the URL is from an academic domain, False otherwise
+ """
+ try:
+ parsed = urlparse(url)
+ if parsed.hostname:
+ hostname_lower = parsed.hostname.lower()
+ return any(
+ hostname_lower == domain
+ or hostname_lower.endswith(f".{domain}")
+ for domain in URLValidator.TRUSTED_ACADEMIC_DOMAINS
+ )
+ except Exception:
+ pass
+
+ return False
+
+ @staticmethod
+ def extract_doi(url: str) -> Optional[str]:
+ """
+ Extract DOI from a URL if present.
+
+ Args:
+ url: The URL to extract DOI from
+
+ Returns:
+ The DOI if found, None otherwise
+ """
+ # Common DOI patterns
+ doi_patterns = [
+ r"10\.\d{4,}(?:\.\d+)*\/[-._;()\/:a-zA-Z0-9]+",
+ r"doi\.org\/(10\.\d{4,}[^\s]*)",
+ ]
+
+ for pattern in doi_patterns:
+ match = re.search(pattern, url, re.IGNORECASE)
+ if match:
+ return (
+ match.group(1) if "doi.org" in pattern else match.group(0)
+ )
+
+ return None
+
+
+def get_javascript_url_validator() -> str:
+ """
+ Get JavaScript code for URL validation that matches the Python implementation.
+
+ Returns:
+ JavaScript code as a string that can be embedded in web pages
+ """
+ return """
+ // URL validation utilities matching Python URLValidator
+ const URLValidator = {
+ UNSAFE_SCHEMES: ['javascript', 'data', 'vbscript', 'about', 'blob', 'file'],
+ SAFE_SCHEMES: ['http', 'https', 'ftp', 'ftps'],
+ EMAIL_SCHEME: 'mailto',
+
+ isUnsafeScheme: function(url) {
+ if (!url) return false;
+
+ const normalizedUrl = url.trim().toLowerCase();
+
+ for (const scheme of this.UNSAFE_SCHEMES) {
+ if (normalizedUrl.startsWith(scheme + ':')) {
+ console.warn(`Unsafe URL scheme detected: ${scheme}`);
+ return true;
+ }
+ }
+
+ return false;
+ },
+
+ isSafeUrl: function(url, options = {}) {
+ const {
+ requireScheme = true,
+ allowFragments = true,
+ allowMailto = false,
+ trustedDomains = []
+ } = options;
+
+ if (!url || typeof url !== 'string') {
+ return false;
+ }
+
+ // Check for unsafe schemes first
+ if (this.isUnsafeScheme(url)) {
+ return false;
+ }
+
+ // Handle fragment-only URLs
+ if (url.startsWith('#')) {
+ return allowFragments;
+ }
+
+ // Parse the URL
+ try {
+ const parsed = new URL(url, window.location.href);
+ const scheme = parsed.protocol.slice(0, -1).toLowerCase(); // Remove trailing ':'
+
+ // Check if it's a mailto link
+ if (scheme === this.EMAIL_SCHEME) {
+ return allowMailto;
+ }
+
+ // Check if it's a safe scheme
+ if (!this.SAFE_SCHEMES.includes(scheme)) {
+ console.warn(`Unsafe URL scheme: ${scheme}`);
+ return false;
+ }
+
+ // Validate domain if trusted domains are specified
+ if (trustedDomains.length > 0 && parsed.hostname) {
+ const hostname = parsed.hostname.toLowerCase();
+ const isTrusted = trustedDomains.some(domain =>
+ hostname === domain.toLowerCase() ||
+ hostname.endsWith('.' + domain.toLowerCase())
+ );
+
+ if (!isTrusted) {
+ console.warn(`URL domain not in trusted list: ${parsed.hostname}`);
+ return false;
+ }
+ }
+
+ return true;
+ } catch (e) {
+ console.warn(`Failed to parse URL: ${e.message}`);
+ return false;
+ }
+ },
+
+ sanitizeUrl: function(url, defaultScheme = 'https') {
+ if (!url) return null;
+
+ // Check for unsafe schemes
+ if (this.isUnsafeScheme(url)) {
+ return null;
+ }
+
+ // Strip whitespace
+ url = url.trim();
+
+ // Add scheme if missing
+ if (!url.match(/^[a-zA-Z][a-zA-Z\d+\-.]*:/)) {
+ url = `${defaultScheme}://${url}`;
+ }
+
+ // Validate the final URL
+ if (this.isSafeUrl(url, { requireScheme: true })) {
+ return url;
+ }
+
+ return null;
+ }
+ };
+ """
diff --git a/src/local_deep_research/web/static/js/components/sources-slider.js b/src/local_deep_research/web/static/js/components/sources-slider.js
index c63a05db87..5df65b1ff6 100644
--- a/src/local_deep_research/web/static/js/components/sources-slider.js
+++ b/src/local_deep_research/web/static/js/components/sources-slider.js
@@ -2,6 +2,112 @@
* Sources Slider Component
* Displays research sources with links to downloaded documents
*/
+
+// URL validation utilities matching Python URLValidator
+const URLValidator = {
+ UNSAFE_SCHEMES: ['javascript', 'data', 'vbscript', 'about', 'blob', 'file'],
+ SAFE_SCHEMES: ['http', 'https', 'ftp', 'ftps'],
+ EMAIL_SCHEME: 'mailto',
+
+ isUnsafeScheme: function(url) {
+ if (!url) return false;
+
+ const normalizedUrl = url.trim().toLowerCase();
+
+ for (const scheme of this.UNSAFE_SCHEMES) {
+ if (normalizedUrl.startsWith(scheme + ':')) {
+ console.warn(`Unsafe URL scheme detected: ${scheme}`);
+ return true;
+ }
+ }
+
+ return false;
+ },
+
+ isSafeUrl: function(url, options = {}) {
+ const {
+ requireScheme = true,
+ allowFragments = true,
+ allowMailto = false,
+ trustedDomains = []
+ } = options;
+
+ if (!url || typeof url !== 'string') {
+ return false;
+ }
+
+ // Check for unsafe schemes first
+ if (this.isUnsafeScheme(url)) {
+ return false;
+ }
+
+ // Handle fragment-only URLs
+ if (url.startsWith('#')) {
+ return allowFragments;
+ }
+
+ // Parse the URL
+ try {
+ const parsed = new URL(url, window.location.href);
+ const scheme = parsed.protocol.slice(0, -1).toLowerCase(); // Remove trailing ':'
+
+ // Check if it's a mailto link
+ if (scheme === this.EMAIL_SCHEME) {
+ return allowMailto;
+ }
+
+ // Check if it's a safe scheme
+ if (!this.SAFE_SCHEMES.includes(scheme)) {
+ console.warn(`Unsafe URL scheme: ${scheme}`);
+ return false;
+ }
+
+ // Validate domain if trusted domains are specified
+ if (trustedDomains.length > 0 && parsed.hostname) {
+ const hostname = parsed.hostname.toLowerCase();
+ const isTrusted = trustedDomains.some(domain =>
+ hostname === domain.toLowerCase() ||
+ hostname.endsWith('.' + domain.toLowerCase())
+ );
+
+ if (!isTrusted) {
+ console.warn(`URL domain not in trusted list: ${parsed.hostname}`);
+ return false;
+ }
+ }
+
+ return true;
+ } catch (e) {
+ console.warn(`Failed to parse URL: ${e.message}`);
+ return false;
+ }
+ },
+
+ sanitizeUrl: function(url, defaultScheme = 'https') {
+ if (!url) return null;
+
+ // Check for unsafe schemes
+ if (this.isUnsafeScheme(url)) {
+ return null;
+ }
+
+ // Strip whitespace
+ url = url.trim();
+
+ // Add scheme if missing
+ if (!url.match(/^[a-zA-Z][a-zA-Z\d+\-.]*:/)) {
+ url = `${defaultScheme}://${url}`;
+ }
+
+ // Validate the final URL
+ if (this.isSafeUrl(url, { requireScheme: true })) {
+ return url;
+ }
+
+ return null;
+ }
+};
+
(function() {
let sources = [];
let filteredSources = [];
@@ -271,12 +377,12 @@
const url = link.href;
const text = link.textContent || '';
- // Skip internal links, anchors, and duplicates
+ // Skip internal links, anchors, unsafe schemes, and duplicates
if (!url ||
url === '' ||
url === window.location.href ||
url.startsWith('#') ||
- url.startsWith('javascript:') ||
+ URLValidator.isUnsafeScheme(url) ||
url.startsWith('mailto:') ||
seenUrls.has(url)) {
return;
@@ -334,7 +440,7 @@
const sourceLinks = sourcesSection.querySelectorAll('a[href]');
sourceLinks.forEach((link, index) => {
const url = link.href;
- if (!seenUrls.has(url) && !url.startsWith('#') && !url.startsWith('javascript:')) {
+ if (!seenUrls.has(url) && !url.startsWith('#') && !URLValidator.isUnsafeScheme(url)) {
seenUrls.add(url);
extractedSources.push({
number: extractedSources.length + 1,