~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
feat: add centralized JavaScript URL validator and improve pre-commit hook
LearningCircuite3ea6aef19e4
diff --git a/.pre-commit-hooks/check-url-security.py b/.pre-commit-hooks/check-url-security.pyindex efe91675a6..7419fbeac9 100755--- a/.pre-commit-hooks/check-url-security.py+++ b/.pre-commit-hooks/check-url-security.py@@ -30,24 +30,18 @@ def check_url_validation(file_path):"URLValidator" in contentor "isUnsafeScheme" in contentor "isSafeUrl" in content+ or "url-validator.js" in content # Check for script include)# Now focusing on external URLs only instead of all URL handling- # Only check new files in the Research Library feature- # Skip existing codebase files to avoid blocking the PR- if "sources-slider" not in file_path and "sources-panel" not in file_path:- # Skip existing files - they will be fixed in a separate PR- return issues-# For now, only warn about files that handle external URLs# Skip files that only handle internal navigationhandles_external_urls = ("fetch(" in contentor "XMLHttpRequest" in content- or re.search(- r"href\s*=\s*['\"][^/'#]", content- ) # External URL assignment+ or re.search(r"window\.open\s*\([^)]*http", content)+ or re.search(r"href\s*=\s*['\"]https?://", content))# If the file handles external URLs but doesn't have validation, that's concerning@@ -72,12 +66,18 @@ def check_url_validation(file_path):# Check for .href or .src assignments without proper validationif re.search(r"\.(href|src)\s*=\s*[a-zA-Z_$]", line):- # Skip safe internal navigation patterns+ # Only skip truly safe patternssafe_patterns = [- r"window\.location\.href\s*=\s*(URLS\.|URLBuilder\.)", # Internal URL constants- r"\.href\s*=\s*(URL\.createObjectURL|canvas\.toDataURL)", # Safe generated URLs- r"\.src\s*=\s*imgElement\.src", # Copying existing src- r"window\.location\.href\s*=\s*viewBtn\.href", # Copying from existing element+ # Internal navigation using known safe constants+ r"window\.location\.href\s*=\s*URLS\.",+ r"\.href\s*=\s*URLBuilder\.",+ # Explicit relative/fragment URLs (safe by definition)+ r"\.href\s*=\s*['\"][/#]",+ # Safe browser APIs for generating URLs+ r"\.href\s*=\s*URL\.createObjectURL",+ r"\.href\s*=\s*canvas\.toDataURL",+ # Already using the URLValidator+ r"URLValidator\.(safeAssign|isSafeUrl)",]if any(re.search(pattern, line) for pattern in safe_patterns):@@ -146,16 +146,27 @@ def main():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("\n📋 HOW TO FIX:")+ print(+ "\n1️⃣ Add this script tag to your HTML template (or include in your JS bundle):"+ )+ print(' <script src="/static/js/security/url-validator.js"></script>')+ print(+ "\n2️⃣ For dynamic URL assignments, use URLValidator.safeAssign():"+ )+ print(" // Instead of: element.href = url;")+ print(" // Use: URLValidator.safeAssign(element, 'href', url);")+ print("\n3️⃣ For URL validation before use:")+ print(" if (URLValidator.isSafeUrl(url)) {")+ print(" // URL is safe to use")+ print(" }")+ print("\n📁 URL Validator location:")+ print(+ " src/local_deep_research/web/static/js/security/url-validator.js"+ )print(- "2. Use URLValidator.isUnsafeScheme() to check for unsafe schemes"+ "\n🔒 This prevents XSS attacks through javascript:, data:, and vbscript: URLs")- print("3. Use URLValidator.isSafeUrl() before assigning to href/src")- print("\nExample:")- print(" if (!URLValidator.isUnsafeScheme(url)) {")- print(" element.href = url;")- print(" }")return 1return 0diff --git a/src/local_deep_research/web/static/js/security/url-validator.js b/src/local_deep_research/web/static/js/security/url-validator.jsnew file mode 100644index 0000000000..a4119dd103--- /dev/null+++ b/src/local_deep_research/web/static/js/security/url-validator.js@@ -0,0 +1,140 @@+/**+ * URL Validation Utilities+ * Provides secure URL validation to prevent XSS attacks+ */++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;+ },++ /**+ * Safe URL assignment with validation+ * Use this for any dynamic URL assignments+ */+ safeAssign: function(element, property, url, options = {}) {+ // Special handling for internal navigation+ if (url && (url.startsWith('/') || url.startsWith('#'))) {+ element[property] = url;+ return true;+ }++ // Special handling for blob and data URLs (safe for downloads)+ if (url && (url.startsWith('blob:') || url.startsWith('data:'))) {+ element[property] = url;+ return true;+ }++ // Validate external URLs+ if (this.isSafeUrl(url, options)) {+ element[property] = url;+ return true;+ }++ console.warn(`Blocked unsafe URL assignment: ${url}`);+ return false;+ }+};++// Export for use in other files+if (typeof module !== 'undefined' && module.exports) {+ module.exports = URLValidator;+}