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.

refactor: delete dead encryption_check.py and orphaned sanitizer.js (#3153)

LearningCircuitf7f2139ef534
diff --git a/src/local_deep_research/database/encryption_check.py b/src/local_deep_research/database/encryption_check.py
deleted file mode 100644
index b4e723dcbf..0000000000
--- a/src/local_deep_research/database/encryption_check.py
+++ /dev/null
@@ -1,103 +0,0 @@
-"""
-Check for SQLCipher availability and provide fallback options.
-"""
-
-import warnings
-from typing import Optional, Tuple
-
-from loguru import logger
-
-
-def check_sqlcipher_available() -> Tuple[bool, Optional[str]]:
- """
- Check if SQLCipher is available for use.
-
- Returns:
- Tuple of (is_available, error_message)
- """
- try:
- # Try to import sqlcipher3 (covers both sqlcipher3 and sqlcipher3-binary)
- import importlib.util
-
- if importlib.util.find_spec("sqlcipher3") is not None:
- return True, None
- except ImportError:
- pass
-
- # Check if sqlcipher command is available
- import subprocess
-
- try:
- result = subprocess.run(
- ["sqlcipher", "--version"],
- capture_output=True,
- text=True,
- timeout=5,
- )
- if result.returncode == 0:
- return (
- False,
- "SQLCipher is installed but Python bindings are missing. Reinstall the project with: pdm install",
- )
- except (subprocess.TimeoutExpired, FileNotFoundError):
- pass
-
- return (
- False,
- "SQLCipher is not installed. See docs/SQLCIPHER_INSTALL.md for installation instructions.",
- )
-
-
-def warn_if_no_encryption():
- """Warn user if encryption is not available."""
- available, message = check_sqlcipher_available()
-
- if not available:
- warning_msg = (
- "\n" + "=" * 60 + "\n"
- "⚠️ SECURITY WARNING: Database Encryption Not Available\n"
- + "="
- * 60
- + "\n"
- f"{message}\n\n"
- "Your data will be stored in UNENCRYPTED SQLite databases.\n"
- "This means:\n"
- " - API keys are stored in plain text\n"
- " - Research data is not encrypted at rest\n"
- " - Anyone with file system access can read your data\n\n"
- "For production use, we strongly recommend installing SQLCipher.\n"
- + "="
- * 60
- )
-
- warnings.warn(warning_msg, category=UserWarning, stacklevel=2)
- logger.warning(
- "Running without database encryption - SQLCipher not available"
- )
-
- return available
-
-
-def get_connection_string(db_path: str, password: Optional[str] = None) -> str:
- """
- Get the appropriate connection string based on SQLCipher availability.
-
- Args:
- db_path: Path to the database file
- password: Password for encryption (ignored if SQLCipher not available)
-
- Returns:
- SQLAlchemy connection string
- """
- available, _ = check_sqlcipher_available()
-
- if available and password:
- # Use encrypted connection
- return f"sqlite+pysqlcipher://:{password}@/{db_path}"
- else:
- # Fall back to regular SQLite
- if password:
- logger.warning(
- "Password provided but SQLCipher not available - using unencrypted database"
- )
- return f"sqlite:///{db_path}"
diff --git a/src/local_deep_research/web/static/js/utils/sanitizer.js b/src/local_deep_research/web/static/js/utils/sanitizer.js
deleted file mode 100644
index 6805076ede..0000000000
--- a/src/local_deep_research/web/static/js/utils/sanitizer.js
+++ /dev/null
@@ -1,233 +0,0 @@
-/**
- * HTML Sanitization Utility using DOMPurify
- *
- * Provides XSS protection for dynamic content by sanitizing HTML before insertion.
- * Use these functions instead of direct innerHTML assignments to prevent XSS attacks.
- *
- * @module sanitizer
- */
-
-import DOMPurify from 'dompurify';
-
-/**
- * Configuration for different sanitization contexts
- */
-const SANITIZE_CONFIG = {
- // Strict: For user-generated content, only allow safe formatting
- strict: {
- ALLOWED_TAGS: ['b', 'i', 'em', 'strong', 'a', 'p', 'br', 'span', 'div'],
- ALLOWED_ATTR: ['href', 'title', 'class'],
- ALLOW_DATA_ATTR: false,
- ALLOW_UNKNOWN_PROTOCOLS: false,
- SAFE_FOR_TEMPLATES: true
- },
-
- // UI: For UI components, allow common elements
- ui: {
- ALLOWED_TAGS: ['div', 'span', 'i', 'strong', 'em', 'b', 'p', 'br', 'small', 'code', 'pre'],
- ALLOWED_ATTR: ['class', 'id', 'title', 'aria-label', 'role', 'data-*'],
- ALLOW_DATA_ATTR: true,
- ALLOW_UNKNOWN_PROTOCOLS: false,
- SAFE_FOR_TEMPLATES: true
- },
-
- // Rich: For research content, allow more formatting
- rich: {
- ALLOWED_TAGS: [
- 'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
- 'p', 'br', 'hr', 'div', 'span',
- 'strong', 'em', 'b', 'i', 'u', 's', 'strike',
- 'ul', 'ol', 'li',
- 'a', 'code', 'pre',
- 'blockquote', 'q', 'cite',
- 'table', 'thead', 'tbody', 'tr', 'th', 'td',
- 'img'
- ],
- ALLOWED_ATTR: [
- 'href', 'title', 'class', 'id',
- 'alt', 'src', // For images
- 'cite', // For citations
- 'target', 'rel' // For links
- ],
- ALLOW_DATA_ATTR: false,
- ALLOW_UNKNOWN_PROTOCOLS: false,
- SAFE_FOR_TEMPLATES: true,
- // Enforce safe link targets
- ADD_ATTR: ['target'],
- FORBID_ATTR: ['onerror', 'onload']
- }
-};
-
-/**
- * Sanitize HTML string using DOMPurify with given configuration
- *
- * @param {string} dirty - Potentially unsafe HTML string
- * @param {string} level - Sanitization level: 'strict', 'ui', or 'rich'
- * @returns {string} Sanitized HTML string safe for insertion
- *
- * @example
- * const clean = sanitizeHTML('<script>alert("xss")</script><p>Safe content</p>', 'strict');
- * // Returns: '<p>Safe content</p>'
- */
-export function sanitizeHTML(dirty, level = 'ui') {
- if (!dirty || typeof dirty !== 'string') {
- return '';
- }
-
- const config = SANITIZE_CONFIG[level] || SANITIZE_CONFIG.ui;
- return DOMPurify.sanitize(dirty, config);
-}
-
-/**
- * Safely set innerHTML of an element with sanitized HTML
- *
- * @param {HTMLElement} element - Target element
- * @param {string} htmlString - HTML string to sanitize and insert
- * @param {string} level - Sanitization level: 'strict', 'ui', or 'rich'
- *
- * @example
- * safeSetHTML(element, '<b>Bold text</b><script>alert("xss")</script>', 'ui');
- * // Sets element.innerHTML to: '<b>Bold text</b>'
- */
-export function safeSetHTML(element, htmlString, level = 'ui') {
- if (!element || !(element instanceof HTMLElement)) {
- SafeLogger.error('safeSetHTML: Invalid element provided');
- return;
- }
-
- // bearer:disable javascript_lang_dangerous_insert_html
- element.innerHTML = sanitizeHTML(htmlString, level);
-}
-
-/**
- * Escape HTML special characters for plain text display
- * Use this when you want to display user input as-is without any HTML parsing
- *
- * @param {string} text - Text to escape
- * @returns {string} Escaped text safe for HTML context
- *
- * @example
- * const safe = escapeHTML('<script>alert("xss")</script>');
- * // Returns: '&lt;script&gt;alert(&quot;xss&quot;)&lt;/script&gt;'
- */
-export function escapeHTML(text) {
- if (!text || typeof text !== 'string') {
- return '';
- }
-
- const div = document.createElement('div');
- div.textContent = text;
- return div.innerHTML;
-}
-
-/**
- * Safely set text content of an element (no HTML parsing)
- * Use this for plain text that should never be interpreted as HTML
- *
- * @param {HTMLElement} element - Target element
- * @param {string} text - Plain text to set
- *
- * @example
- * safeSetText(element, '<b>This will be displayed as literal text</b>');
- */
-export function safeSetText(element, text) {
- if (!element || !(element instanceof HTMLElement)) {
- SafeLogger.error('safeSetText: Invalid element provided');
- return;
- }
-
- element.textContent = text || '';
-}
-
-/**
- * Create a safe DOM element from HTML string
- * Returns a DocumentFragment containing sanitized elements
- *
- * @param {string} htmlString - HTML string to parse
- * @param {string} level - Sanitization level
- * @returns {DocumentFragment} Document fragment with sanitized content
- *
- * @example
- * const fragment = createSafeElement('<div>Safe content</div>');
- * parentElement.appendChild(fragment);
- */
-export function createSafeElement(htmlString, level = 'ui') {
- const template = document.createElement('template');
- // bearer:disable javascript_lang_dangerous_insert_html
- template.innerHTML = sanitizeHTML(htmlString, level);
- return template.content;
-}
-
-/**
- * Sanitize URL to prevent javascript: and data: URI attacks
- *
- * @param {string} url - URL to sanitize
- * @returns {string} Safe URL or empty string if unsafe
- *
- * @example
- * const safe = sanitizeURL('javascript:alert("xss")');
- * // Returns: ''
- *
- * const safe2 = sanitizeURL('https://example.com');
- * // Returns: 'https://example.com'
- */
-export function sanitizeURL(url) {
- if (!url || typeof url !== 'string') {
- return '';
- }
-
- const trimmed = url.trim().toLowerCase();
-
- // Block dangerous protocols
- const dangerousProtocols = ['javascript:', 'data:', 'vbscript:', 'file:'];
- for (const protocol of dangerousProtocols) {
- if (trimmed.startsWith(protocol)) {
- SafeLogger.warn(`Blocked dangerous URL protocol: ${protocol}`);
- return '';
- }
- }
-
- // Allow safe protocols
- const safeProtocols = ['http:', 'https:', 'mailto:', 'tel:', 'ftp:', '//', '/'];
- const isSafe = safeProtocols.some(proto => trimmed.startsWith(proto));
-
- if (!isSafe && trimmed.includes(':')) {
- SafeLogger.warn('Blocked URL with unknown protocol:', url);
- return '';
- }
-
- return url;
-}
-
-/**
- * Configure DOMPurify hooks for additional security
- */
-function configureDOMPurify() {
- // Hook to enforce safe link targets
- DOMPurify.addHook('afterSanitizeAttributes', (node) => {
- // Set all links to open in new tab with noopener noreferrer
- if (node.tagName === 'A') {
- node.setAttribute('target', '_blank');
- node.setAttribute('rel', 'noopener noreferrer');
- }
-
- // Remove any remaining inline event handlers
- for (const attr of node.attributes) {
- if (attr.name.startsWith('on')) {
- node.removeAttribute(attr.name);
- }
- }
- });
-}
-
-// Initialize DOMPurify configuration on module load
-configureDOMPurify();
-
-export default {
- sanitizeHTML,
- safeSetHTML,
- escapeHTML,
- safeSetText,
- createSafeElement,
- sanitizeURL
-};
diff --git a/tests/database/test_encryption_check.py b/tests/database/test_encryption_check.py
deleted file mode 100644
index 31893fb7ce..0000000000
--- a/tests/database/test_encryption_check.py
+++ /dev/null
@@ -1,233 +0,0 @@
-"""
-Tests for encryption_check module.
-
-Covers functions for checking SQLCipher availability and providing
-appropriate connection strings and warnings.
-"""
-
-import subprocess
-import warnings
-from unittest.mock import MagicMock, patch
-
-
-from tests.test_utils import add_src_to_path
-
-add_src_to_path()
-
-from local_deep_research.database.encryption_check import ( # noqa: E402
- check_sqlcipher_available,
- get_connection_string,
- warn_if_no_encryption,
-)
-
-
-class TestCheckSqlcipherAvailable:
- """Tests for check_sqlcipher_available function."""
-
- def test_returns_true_when_sqlcipher3_available(self):
- """Should return (True, None) when sqlcipher3 module is found."""
- mock_spec = MagicMock()
- with patch("importlib.util.find_spec", return_value=mock_spec):
- available, message = check_sqlcipher_available()
-
- assert available is True
- assert message is None
-
- def test_returns_false_when_module_not_found(self):
- """Should return (False, message) when sqlcipher3 not found."""
- with patch("importlib.util.find_spec", return_value=None):
- with patch("subprocess.run") as mock_run:
- mock_run.side_effect = FileNotFoundError()
-
- available, message = check_sqlcipher_available()
-
- assert available is False
- assert message is not None
- assert "not installed" in message.lower()
-
- def test_detects_sqlcipher_without_python_bindings(self):
- """Should detect when SQLCipher CLI exists but Python bindings missing."""
- with patch("importlib.util.find_spec", return_value=None):
- mock_result = MagicMock()
- mock_result.returncode = 0
- with patch("subprocess.run", return_value=mock_result):
- available, message = check_sqlcipher_available()
-
- assert available is False
- assert message is not None
- assert "bindings" in message.lower()
- assert "pdm install" in message.lower()
-
- def test_handles_subprocess_timeout(self):
- """Should handle subprocess timeout gracefully."""
- with patch("importlib.util.find_spec", return_value=None):
- with patch("subprocess.run") as mock_run:
- mock_run.side_effect = subprocess.TimeoutExpired(
- cmd="sqlcipher", timeout=5
- )
-
- available, message = check_sqlcipher_available()
-
- assert available is False
- assert message is not None
- assert "not installed" in message.lower()
-
- def test_handles_import_error(self):
- """Should handle ImportError during find_spec."""
- with patch("importlib.util.find_spec") as mock_find:
- mock_find.side_effect = ImportError("Test error")
- with patch("subprocess.run") as mock_run:
- mock_run.side_effect = FileNotFoundError()
-
- available, message = check_sqlcipher_available()
-
- assert available is False
- assert message is not None
-
- def test_subprocess_called_with_correct_args(self):
- """Should call subprocess.run with correct arguments."""
- with patch("importlib.util.find_spec", return_value=None):
- with patch("subprocess.run") as mock_run:
- mock_run.side_effect = FileNotFoundError()
-
- check_sqlcipher_available()
-
- mock_run.assert_called_once()
- call_args = mock_run.call_args
- assert call_args[0][0] == ["sqlcipher", "--version"]
- assert call_args[1]["capture_output"] is True
- assert call_args[1]["text"] is True
- assert call_args[1]["timeout"] == 5
-
-
-class TestWarnIfNoEncryption:
- """Tests for warn_if_no_encryption function."""
-
- def test_returns_true_when_encryption_available(self):
- """Should return True when SQLCipher is available."""
- mock_spec = MagicMock()
- with patch("importlib.util.find_spec", return_value=mock_spec):
- result = warn_if_no_encryption()
-
- assert result is True
-
- def test_issues_user_warning_when_not_available(self):
- """Should issue UserWarning with security info when not available."""
- with patch("importlib.util.find_spec", return_value=None):
- with patch("subprocess.run") as mock_run:
- mock_run.side_effect = FileNotFoundError()
-
- with warnings.catch_warnings(record=True) as w:
- warnings.simplefilter("always")
- result = warn_if_no_encryption()
-
- assert result is False
- assert len(w) == 1
- assert issubclass(w[0].category, UserWarning)
- warning_msg = str(w[0].message)
- assert "SECURITY WARNING" in warning_msg
- assert "UNENCRYPTED" in warning_msg
- assert "API keys" in warning_msg
-
- def test_logs_warning_when_not_available(self):
- """Should log warning when encryption not available."""
- with patch("importlib.util.find_spec", return_value=None):
- with patch("subprocess.run") as mock_run:
- mock_run.side_effect = FileNotFoundError()
- with patch(
- "local_deep_research.database.encryption_check.logger"
- ) as mock_logger:
- with warnings.catch_warnings():
- warnings.simplefilter("ignore")
- warn_if_no_encryption()
-
- mock_logger.warning.assert_called_once()
- call_args = mock_logger.warning.call_args[0][0]
- assert "without database encryption" in call_args.lower()
-
-
-class TestGetConnectionString:
- """Tests for get_connection_string function."""
-
- def test_returns_encrypted_string_when_available_and_password(self):
- """Should return encrypted connection string when SQLCipher available."""
- mock_spec = MagicMock()
- with patch("importlib.util.find_spec", return_value=mock_spec):
- result = get_connection_string("/path/to/db.sqlite", "mypassword")
-
- assert (
- result == "sqlite+pysqlcipher://:mypassword@//path/to/db.sqlite"
- )
-
- def test_returns_sqlite_when_not_available(self):
- """Should return regular SQLite string when SQLCipher not available."""
- with patch("importlib.util.find_spec", return_value=None):
- with patch("subprocess.run") as mock_run:
- mock_run.side_effect = FileNotFoundError()
-
- result = get_connection_string(
- "/path/to/db.sqlite", "mypassword"
- )
-
- assert result == "sqlite:////path/to/db.sqlite"
-
- def test_returns_sqlite_when_no_password(self):
- """Should return SQLite string when no password provided."""
- mock_spec = MagicMock()
- with patch("importlib.util.find_spec", return_value=mock_spec):
- result = get_connection_string("/path/to/db.sqlite")
-
- assert result == "sqlite:////path/to/db.sqlite"
-
- def test_returns_sqlite_when_password_is_none(self):
- """Should return SQLite string when password is explicitly None."""
- mock_spec = MagicMock()
- with patch("importlib.util.find_spec", return_value=mock_spec):
- result = get_connection_string("/path/to/db.sqlite", None)
-
- assert result == "sqlite:////path/to/db.sqlite"
-
- def test_logs_warning_when_password_ignored(self):
- """Should log warning when password provided but SQLCipher unavailable."""
- with patch("importlib.util.find_spec", return_value=None):
- with patch("subprocess.run") as mock_run:
- mock_run.side_effect = FileNotFoundError()
- with patch(
- "local_deep_research.database.encryption_check.logger"
- ) as mock_logger:
- get_connection_string("/path/to/db.sqlite", "mypassword")
-
- mock_logger.warning.assert_called_once()
- call_args = mock_logger.warning.call_args[0][0]
- assert "password provided" in call_args.lower()
- assert "unencrypted" in call_args.lower()
-
- def test_no_warning_when_no_password_and_unavailable(self):
- """Should not log warning when no password and SQLCipher unavailable."""
- with patch("importlib.util.find_spec", return_value=None):
- with patch("subprocess.run") as mock_run:
- mock_run.side_effect = FileNotFoundError()
- with patch(
- "local_deep_research.database.encryption_check.logger"
- ) as mock_logger:
- get_connection_string("/path/to/db.sqlite")
-
- mock_logger.warning.assert_not_called()
-
- def test_connection_string_format_verification(self):
- """Verify exact format of connection strings."""
- # Test encrypted format
- mock_spec = MagicMock()
- with patch("importlib.util.find_spec", return_value=mock_spec):
- result = get_connection_string("test.db", "secret")
- assert result.startswith("sqlite+pysqlcipher://")
- assert ":secret@/" in result
- assert result.endswith("test.db")
-
- # Test unencrypted format
- with patch("importlib.util.find_spec", return_value=None):
- with patch("subprocess.run") as mock_run:
- mock_run.side_effect = FileNotFoundError()
- result = get_connection_string("test.db")
- assert result.startswith("sqlite:///")
- assert result.endswith("test.db")