~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
security: add module whitelist and input validation (#1887)
LearningCircuit8d10a267968b
diff --git a/src/local_deep_research/defaults/default_settings.json b/src/local_deep_research/defaults/default_settings.jsonindex a4e5f57c2d..de1612ee41 100644--- a/src/local_deep_research/defaults/default_settings.json+++ b/src/local_deep_research/defaults/default_settings.json@@ -1292,7 +1292,7 @@"search.engine.web.arxiv.class_name": {"category": "arxiv","description": "Internal: Python class implementing the arXiv search engine.",- "editable": true,+ "editable": false,"max_value": null,"min_value": null,"name": "Class Name",@@ -1301,7 +1301,7 @@"type": "SEARCH","ui_element": "text","value": "ArXivSearchEngine",- "visible": true+ "visible": false},"search.engine.web.arxiv.journal_reputation.enabled": {"category": "arxiv",@@ -1384,7 +1384,7 @@"search.engine.web.arxiv.module_path": {"category": "arxiv","description": "Internal: Python module path for the arXiv search engine implementation.",- "editable": true,+ "editable": false,"max_value": null,"min_value": null,"name": "Module Path",@@ -1393,7 +1393,7 @@"type": "SEARCH","ui_element": "text","value": ".engines.search_engine_arxiv",- "visible": true+ "visible": false},"search.engine.web.arxiv.reliability": {"category": "arxiv",@@ -1496,7 +1496,7 @@"search.engine.auto.class_name": {"category": "auto","description": "Internal: Python class implementing the automatic search engine selector.",- "editable": true,+ "editable": false,"max_value": null,"min_value": null,"name": "Class Name",@@ -1505,7 +1505,7 @@"type": "SEARCH","ui_element": "text","value": "MetaSearchEngine",- "visible": true+ "visible": false},"search.engine.auto.default_params.max_engines_to_try": {"category": "auto",@@ -1538,7 +1538,7 @@"search.engine.auto.module_path": {"category": "auto","description": "Internal: Python module path for the auto search engine selector.",- "editable": true,+ "editable": false,"max_value": null,"min_value": null,"name": "Module Path",@@ -1547,7 +1547,7 @@"type": "SEARCH","ui_element": "text","value": ".engines.meta_search_engine",- "visible": true+ "visible": false},"search.engine.auto.reliability": {"category": "auto",@@ -1670,7 +1670,7 @@"search.engine.web.brave.class_name": {"category": "brave","description": "Internal: Python class implementing the Brave search engine.",- "editable": true,+ "editable": false,"max_value": null,"min_value": null,"name": "Class Name",@@ -1679,7 +1679,7 @@"type": "SEARCH","ui_element": "text","value": "BraveSearchEngine",- "visible": true+ "visible": false},"search.engine.web.brave.default_params.region": {"category": "brave",@@ -1762,13 +1762,13 @@"step": null,"type": "SEARCH","ui_element": "text",- "value": "local_deep_research.web_search_engines.engines.full_search",+ "value": ".engines.full_search","visible": true},"search.engine.web.brave.module_path": {"category": "brave","description": "Internal: Python module path for the Brave search engine implementation.",- "editable": true,+ "editable": false,"max_value": null,"min_value": null,"name": "Module Path",@@ -1777,7 +1777,7 @@"type": "SEARCH","ui_element": "text","value": ".engines.search_engine_brave",- "visible": true+ "visible": false},"search.engine.web.brave.reliability": {"category": "brave",@@ -1960,7 +1960,7 @@"search.engine.web.github.class_name": {"category": "github","description": "Internal: Python class implementing the GitHub search engine.",- "editable": true,+ "editable": false,"max_value": null,"min_value": null,"name": "Class Name",@@ -1969,7 +1969,7 @@"type": "SEARCH","ui_element": "text","value": "GitHubSearchEngine",- "visible": true+ "visible": false},"search.engine.web.github.default_params.include_issues": {"category": "github",@@ -2047,7 +2047,7 @@"search.engine.web.github.module_path": {"category": "github","description": "Internal: Python module path for the GitHub search engine implementation.",- "editable": true,+ "editable": false,"max_value": null,"min_value": null,"name": "Module Path",@@ -2056,7 +2056,7 @@"type": "SEARCH","ui_element": "text","value": ".engines.search_engine_github",- "visible": true+ "visible": false},"search.engine.web.github.reliability": {"category": "github",@@ -2198,7 +2198,7 @@"search.engine.web.google_pse.class_name": {"category": "google_pse","description": "Internal: Python class implementing this search engine. Do not modify unless extending functionality.",- "editable": true,+ "editable": false,"max_value": null,"min_value": null,"name": "Class Name",@@ -2207,7 +2207,7 @@"type": "SEARCH","ui_element": "text","value": "GooglePSESearchEngine",- "visible": true+ "visible": false},"search.engine.web.google_pse.default_params.region": {"category": "google_pse",@@ -2282,7 +2282,7 @@"search.engine.web.google_pse.module_path": {"category": "google_pse","description": "Internal: Python module path for this search engine implementation. Do not modify.",- "editable": true,+ "editable": false,"max_value": null,"min_value": null,"name": "Module Path",@@ -2291,7 +2291,7 @@"type": "SEARCH","ui_element": "text","value": ".engines.search_engine_google_pse",- "visible": true+ "visible": false},"search.engine.web.google_pse.reliability": {"category": "google_pse",@@ -2418,7 +2418,7 @@"search.engine.local.local_all.class_name": {"category": "local_all","description": "Internal: Python class implementing local document search. Do not modify.",- "editable": true,+ "editable": false,"max_value": null,"min_value": null,"name": "Class Name",@@ -2427,12 +2427,12 @@"type": "SEARCH","ui_element": "text","value": "LocalAllSearchEngine",- "visible": true+ "visible": false},"search.engine.local.local_all.module_path": {"category": "local_all","description": "Internal: Python module path for local search implementation. Do not modify.",- "editable": true,+ "editable": false,"max_value": null,"min_value": null,"name": "Module Path",@@ -2441,7 +2441,7 @@"type": "SEARCH","ui_element": "text","value": ".engines.search_engine_local_all",- "visible": true+ "visible": false},"search.engine.local.local_all.reliability": {"category": "local_all",@@ -3039,7 +3039,7 @@"search.engine.web.pubmed.class_name": {"category": "pubmed","description": "Internal: Python class implementing the PubMed search engine.",- "editable": true,+ "editable": false,"max_value": null,"min_value": null,"name": "Class Name",@@ -3048,7 +3048,7 @@"type": "SEARCH","ui_element": "text","value": "PubMedSearchEngine",- "visible": true+ "visible": false},"search.engine.web.pubmed.default_params.days_limit": {"category": "pubmed",@@ -3165,7 +3165,7 @@"search.engine.web.pubmed.module_path": {"category": "pubmed","description": "Internal: Python module path for the PubMed search engine implementation.",- "editable": true,+ "editable": false,"max_value": null,"min_value": null,"name": "Module Path",@@ -3174,7 +3174,7 @@"type": "SEARCH","ui_element": "text","value": ".engines.search_engine_pubmed",- "visible": true+ "visible": false},"search.engine.web.pubmed.reliability": {"category": "pubmed",@@ -3525,7 +3525,7 @@"search.engine.web.searxng.class_name": {"category": "searxng","description": "Internal: Python class implementing the SearXNG search engine.",- "editable": true,+ "editable": false,"max_value": null,"min_value": null,"name": "Class Name",@@ -3534,7 +3534,7 @@"type": "SEARCH","ui_element": "text","value": "SearXNGSearchEngine",- "visible": true+ "visible": false},"search.engine.web.searxng.default_params.instance_url": {"category": "searxng",@@ -3681,7 +3681,7 @@"search.engine.web.searxng.module_path": {"category": "searxng","description": "Internal: Python module path for the SearXNG search engine implementation.",- "editable": true,+ "editable": false,"max_value": null,"min_value": null,"name": "Module Path",@@ -3690,7 +3690,7 @@"type": "SEARCH","ui_element": "text","value": ".engines.search_engine_searxng",- "visible": true+ "visible": false},"search.engine.web.searxng.reliability": {"category": "searxng",@@ -3822,7 +3822,7 @@"search.engine.web.serpapi.class_name": {"category": "serpapi","description": "Internal: Python class implementing the SerpAPI search engine. Do not modify.",- "editable": true,+ "editable": false,"max_value": null,"min_value": null,"name": "Class Name",@@ -3831,7 +3831,7 @@"type": "SEARCH","ui_element": "text","value": "SerpAPISearchEngine",- "visible": true+ "visible": false},"search.engine.web.serpapi.default_params.region": {"category": "serpapi",@@ -3914,13 +3914,13 @@"step": null,"type": "SEARCH","ui_element": "text",- "value": "local_deep_research.web_search_engines.engines.full_serp_search_results_old",+ "value": ".engines.full_serp_search_results_old","visible": true},"search.engine.web.serpapi.module_path": {"category": "serpapi","description": "Internal: Python module path for this search engine implementation. Do not modify.",- "editable": true,+ "editable": false,"max_value": null,"min_value": null,"name": "Module Path",@@ -3929,7 +3929,7 @@"type": "SEARCH","ui_element": "text","value": ".engines.search_engine_serpapi",- "visible": true+ "visible": false},"search.engine.web.serpapi.reliability": {"category": "serpapi",@@ -4042,7 +4042,7 @@"search.engine.web.wayback.class_name": {"category": "wayback","description": "Internal: Python class implementing the Wayback Machine search. Do not modify.",- "editable": true,+ "editable": false,"max_value": null,"min_value": null,"name": "Class Name",@@ -4051,7 +4051,7 @@"type": "SEARCH","ui_element": "text","value": "WaybackSearchEngine",- "visible": true+ "visible": false},"search.engine.web.wayback.default_params.closest_only": {"category": "wayback",@@ -4112,7 +4112,7 @@"search.engine.web.wayback.module_path": {"category": "wayback","description": "Internal: Python module path for this search engine implementation. Do not modify.",- "editable": true,+ "editable": false,"max_value": null,"min_value": null,"name": "Module Path",@@ -4121,7 +4121,7 @@"type": "SEARCH","ui_element": "text","value": ".engines.search_engine_wayback",- "visible": true+ "visible": false},"search.engine.web.wayback.reliability": {"category": "wayback",@@ -4276,7 +4276,7 @@"search.engine.web.wikipedia.class_name": {"category": "wikipedia","description": "Internal: Python class implementing Wikipedia search. Do not modify.",- "editable": true,+ "editable": false,"max_value": null,"min_value": null,"name": "Class Name",@@ -4285,7 +4285,7 @@"type": "SEARCH","ui_element": "text","value": "WikipediaSearchEngine",- "visible": true+ "visible": false},"search.engine.web.wikipedia.default_params.include_content": {"category": "wikipedia",@@ -4318,7 +4318,7 @@"search.engine.web.wikipedia.module_path": {"category": "wikipedia","description": "Internal: Python module path for this search engine implementation. Do not modify.",- "editable": true,+ "editable": false,"max_value": null,"min_value": null,"name": "Module Path",@@ -4327,7 +4327,7 @@"type": "SEARCH","ui_element": "text","value": ".engines.search_engine_wikipedia",- "visible": true+ "visible": false},"search.engine.web.wikipedia.reliability": {"category": "wikipedia",@@ -4731,7 +4731,7 @@"search.engine.web.tavily.class_name": {"category": "tavily","description": "Internal: Python class implementing Tavily AI search. Do not modify.",- "editable": true,+ "editable": false,"max_value": null,"min_value": null,"name": "Class Name",@@ -4740,7 +4740,7 @@"type": "SEARCH","ui_element": "text","value": "TavilySearchEngine",- "visible": true+ "visible": false},"search.engine.web.tavily.default_params.search_depth": {"category": "tavily",@@ -4776,7 +4776,7 @@"search.engine.web.tavily.module_path": {"category": "tavily","description": "Internal: Python module path for this search engine implementation. Do not modify.",- "editable": true,+ "editable": false,"max_value": null,"min_value": null,"name": "Module Path",@@ -4785,7 +4785,7 @@"type": "SEARCH","ui_element": "text","value": ".engines.search_engine_tavily",- "visible": true+ "visible": false},"search.engine.web.tavily.requires_api_key": {"category": "tavily",diff --git a/src/local_deep_research/defaults/settings/search_engines/elasticsearch.json b/src/local_deep_research/defaults/settings/search_engines/elasticsearch.jsonindex 719908d480..6d83b02b41 100644--- a/src/local_deep_research/defaults/settings/search_engines/elasticsearch.json+++ b/src/local_deep_research/defaults/settings/search_engines/elasticsearch.json@@ -30,7 +30,7 @@"search.engine.web.elasticsearch.class_name": {"category": "elasticsearch","description": "Setting for elasticsearch.class_name",- "editable": true,+ "editable": false,"max_value": null,"min_value": null,"name": "Class Name",@@ -39,12 +39,12 @@"type": "SEARCH","ui_element": "text","value": "ElasticsearchSearchEngine",- "visible": true+ "visible": false},"search.engine.web.elasticsearch.module_path": {"category": "elasticsearch","description": "Setting for elasticsearch.module_path",- "editable": true,+ "editable": false,"max_value": null,"min_value": null,"name": "Module Path",@@ -52,8 +52,8 @@"step": null,"type": "SEARCH","ui_element": "text",- "value": "local_deep_research.web_search_engines.engines.search_engine_elasticsearch",- "visible": true+ "value": ".engines.search_engine_elasticsearch",+ "visible": false},"search.engine.web.elasticsearch.default_params.hosts": {"category": "elasticsearch",diff --git a/src/local_deep_research/defaults/settings/search_engines/paperless.json b/src/local_deep_research/defaults/settings/search_engines/paperless.jsonindex d4cf6f7702..f4fb0a5b44 100644--- a/src/local_deep_research/defaults/settings/search_engines/paperless.json+++ b/src/local_deep_research/defaults/settings/search_engines/paperless.json@@ -44,7 +44,7 @@"search.engine.web.paperless.class_name": {"category": "paperless","description": "Class name for the Paperless search engine",- "editable": true,+ "editable": false,"max_value": null,"min_value": null,"name": "Class Name",@@ -53,12 +53,12 @@"type": "SEARCH","ui_element": "text","value": "PaperlessSearchEngine",- "visible": true+ "visible": false},"search.engine.web.paperless.module_path": {"category": "paperless","description": "Python module path for the search engine",- "editable": true,+ "editable": false,"max_value": null,"min_value": null,"name": "Module Path",@@ -67,7 +67,7 @@"type": "SEARCH","ui_element": "text","value": ".engines.search_engine_paperless",- "visible": true+ "visible": false},"search.engine.web.paperless.default_params.api_url": {"category": "paperless",diff --git a/src/local_deep_research/defaults/settings/search_engines/parallel.json b/src/local_deep_research/defaults/settings/search_engines/parallel.jsonindex f71f82a4da..788a180148 100644--- a/src/local_deep_research/defaults/settings/search_engines/parallel.json+++ b/src/local_deep_research/defaults/settings/search_engines/parallel.json@@ -30,7 +30,7 @@"search.engine.web.parallel.class_name": {"category": "parallel","description": "Class name for the parallel search engine",- "editable": true,+ "editable": false,"max_value": null,"min_value": null,"name": "Class Name",@@ -39,12 +39,12 @@"type": "SEARCH","ui_element": "text","value": "ParallelSearchEngine",- "visible": true+ "visible": false},"search.engine.web.parallel.module_path": {"category": "parallel","description": "Module path for the parallel search engine",- "editable": true,+ "editable": false,"max_value": null,"min_value": null,"name": "Module Path",@@ -52,8 +52,8 @@"step": null,"type": "SEARCH","ui_element": "text",- "value": "local_deep_research.web_search_engines.engines.parallel_search_engine",- "visible": true+ "value": ".engines.parallel_search_engine",+ "visible": false},"search.engine.web.parallel.default_params.max_engines_to_select": {"category": "parallel",diff --git a/src/local_deep_research/defaults/settings/search_engines/scaleserp.json b/src/local_deep_research/defaults/settings/search_engines/scaleserp.jsonindex efe3c6ca71..a63c7a646c 100644--- a/src/local_deep_research/defaults/settings/search_engines/scaleserp.json+++ b/src/local_deep_research/defaults/settings/search_engines/scaleserp.json@@ -44,7 +44,7 @@"search.engine.web.scaleserp.class_name": {"category": "scaleserp","description": "Class name for the ScaleSerp search engine",- "editable": true,+ "editable": false,"max_value": null,"min_value": null,"name": "Class Name",@@ -53,12 +53,12 @@"type": "SEARCH","ui_element": "text","value": "ScaleSerpSearchEngine",- "visible": true+ "visible": false},"search.engine.web.scaleserp.module_path": {"category": "scaleserp","description": "Module path for the ScaleSerp search engine",- "editable": true,+ "editable": false,"max_value": null,"min_value": null,"name": "Module Path",@@ -66,8 +66,8 @@"step": null,"type": "SEARCH","ui_element": "text",- "value": "local_deep_research.web_search_engines.engines.search_engine_scaleserp",- "visible": true+ "value": ".engines.search_engine_scaleserp",+ "visible": false},"search.engine.web.scaleserp.default_params.location": {"category": "scaleserp",diff --git a/src/local_deep_research/defaults/settings/search_engines/serper.json b/src/local_deep_research/defaults/settings/search_engines/serper.jsonindex ebd688b30c..5731abe11e 100644--- a/src/local_deep_research/defaults/settings/search_engines/serper.json+++ b/src/local_deep_research/defaults/settings/search_engines/serper.json@@ -44,7 +44,7 @@"search.engine.web.serper.class_name": {"category": "serper","description": "Class name for the Serper search engine",- "editable": true,+ "editable": false,"max_value": null,"min_value": null,"name": "Class Name",@@ -53,12 +53,12 @@"type": "SEARCH","ui_element": "text","value": "SerperSearchEngine",- "visible": true+ "visible": false},"search.engine.web.serper.module_path": {"category": "serper","description": "Module path for the Serper search engine",- "editable": true,+ "editable": false,"max_value": null,"min_value": null,"name": "Module Path",@@ -66,8 +66,8 @@"step": null,"type": "SEARCH","ui_element": "text",- "value": "local_deep_research.web_search_engines.engines.search_engine_serper",- "visible": true+ "value": ".engines.search_engine_serper",+ "visible": false},"search.engine.web.serper.default_params.region": {"category": "serper",diff --git a/src/local_deep_research/defaults/settings_nasa_ads.json b/src/local_deep_research/defaults/settings_nasa_ads.jsonindex af39f9f2cb..fc3b92c020 100644--- a/src/local_deep_research/defaults/settings_nasa_ads.json+++ b/src/local_deep_research/defaults/settings_nasa_ads.json@@ -51,7 +51,7 @@"search.engine.web.nasa_ads.class_name": {"category": "nasa_ads","description": "Python class name for the NASA ADS search engine implementation",- "editable": true,+ "editable": false,"max_value": null,"min_value": null,"name": "Class Name",@@ -60,12 +60,12 @@"type": "SEARCH","ui_element": "text","value": "NasaAdsSearchEngine",- "visible": true+ "visible": false},"search.engine.web.nasa_ads.module_path": {"category": "nasa_ads","description": "Python module path for importing the NASA ADS search engine class",- "editable": true,+ "editable": false,"max_value": null,"min_value": null,"name": "Module Path",@@ -74,7 +74,7 @@"type": "SEARCH","ui_element": "text","value": ".engines.search_engine_nasa_ads",- "visible": true+ "visible": false},"search.engine.web.nasa_ads.reliability": {"category": "nasa_ads",diff --git a/src/local_deep_research/defaults/settings_openalex.json b/src/local_deep_research/defaults/settings_openalex.jsonindex 1fc3ae7137..bf0b88ab52 100644--- a/src/local_deep_research/defaults/settings_openalex.json+++ b/src/local_deep_research/defaults/settings_openalex.json@@ -51,7 +51,7 @@"search.engine.web.openalex.class_name": {"category": "openalex","description": "Python class name for the OpenAlex search engine implementation",- "editable": true,+ "editable": false,"max_value": null,"min_value": null,"name": "Class Name",@@ -60,12 +60,12 @@"type": "SEARCH","ui_element": "text","value": "OpenAlexSearchEngine",- "visible": true+ "visible": false},"search.engine.web.openalex.module_path": {"category": "openalex","description": "Python module path for importing the OpenAlex search engine class",- "editable": true,+ "editable": false,"max_value": null,"min_value": null,"name": "Module Path",@@ -74,7 +74,7 @@"type": "SEARCH","ui_element": "text","value": ".engines.search_engine_openalex",- "visible": true+ "visible": false},"search.engine.web.openalex.reliability": {"category": "openalex",diff --git a/src/local_deep_research/defaults/settings_semantic_scholar.json b/src/local_deep_research/defaults/settings_semantic_scholar.jsonindex df50bdf942..348de1afb8 100644--- a/src/local_deep_research/defaults/settings_semantic_scholar.json+++ b/src/local_deep_research/defaults/settings_semantic_scholar.json@@ -51,7 +51,7 @@"search.engine.web.semantic_scholar.class_name": {"category": "semantic_scholar","description": "Class name for the search engine implementation",- "editable": true,+ "editable": false,"max_value": null,"min_value": null,"name": "Class Name",@@ -60,12 +60,12 @@"type": "SEARCH","ui_element": "text","value": "SemanticScholarSearchEngine",- "visible": true+ "visible": false},"search.engine.web.semantic_scholar.module_path": {"category": "semantic_scholar","description": "Module path for the search engine implementation",- "editable": true,+ "editable": false,"max_value": null,"min_value": null,"name": "Module Path",@@ -74,7 +74,7 @@"type": "SEARCH","ui_element": "text","value": ".engines.search_engine_semantic_scholar",- "visible": true+ "visible": false},"search.engine.web.semantic_scholar.reliability": {"category": "semantic_scholar",diff --git a/src/local_deep_research/notifications/templates.py b/src/local_deep_research/notifications/templates.pyindex c89a5f8d0b..50639264e3 100644--- a/src/local_deep_research/notifications/templates.py+++ b/src/local_deep_research/notifications/templates.py@@ -108,15 +108,22 @@ class NotificationTemplate:Dict with 'title' and 'body' keys"""# If custom template is provided, use the old string format for backward compatibility+ # Security: Sanitize context values to prevent format string attacksif custom_template:try:- title = custom_template["title"].format(**context)- body = custom_template["body"].format(**context)+ # Only allow simple string substitution - convert all values to strings+ # This prevents format string attacks like {query.__class__}+ safe_context = {+ k: str(v) if v is not None else ""+ for k, v in context.items()+ }+ title = custom_template["title"].format(**safe_context)+ body = custom_template["body"].format(**safe_context)return {"title": title, "body": body}except KeyError as e:return {"title": f"Notification: {event_type.value}",- "body": f"Template error: Missing variable {e}. Context: {context}",+ "body": f"Template error: Missing variable {e}",}# Get template filename for this event typediff --git a/src/local_deep_research/research_library/routes/library_routes.py b/src/local_deep_research/research_library/routes/library_routes.pyindex 5a6ae3ec73..b77eae043a 100644--- a/src/local_deep_research/research_library/routes/library_routes.py+++ b/src/local_deep_research/research_library/routes/library_routes.py@@ -576,6 +576,15 @@ def serve_text_api(document_id):@login_requireddef open_folder():"""Open folder containing a document."""+ # Security: This endpoint is disabled for server deployments+ # It only makes sense for desktop usage where the server and client are on the same machine+ return jsonify(+ {+ "status": "error",+ "message": "This feature is disabled. It is only available in desktop mode.",+ }+ ), 403+data = request.jsonpath = data.get("path")diff --git a/src/local_deep_research/security/__init__.py b/src/local_deep_research/security/__init__.pyindex afcd85aa71..9b0b8feb54 100644--- a/src/local_deep_research/security/__init__.py+++ b/src/local_deep_research/security/__init__.py@@ -11,6 +11,11 @@ from .safe_requests import safe_get, safe_post, SafeSessionfrom .security_headers import SecurityHeadersfrom .ssrf_validator import validate_url, get_safe_url, is_ip_blockedfrom .url_validator import URLValidator+from .module_whitelist import (+ get_safe_module_class,+ ModuleNotAllowedError,+ ALLOWED_MODULES,+)# PathValidator requires werkzeug (Flask dependency), import conditionallytry:@@ -66,4 +71,7 @@ __all__ = ["validate_url","get_safe_url","is_ip_blocked",+ "get_safe_module_class",+ "ModuleNotAllowedError",+ "ALLOWED_MODULES",]diff --git a/src/local_deep_research/security/module_whitelist.py b/src/local_deep_research/security/module_whitelist.pynew file mode 100644index 0000000000..10765f73f4--- /dev/null+++ b/src/local_deep_research/security/module_whitelist.py@@ -0,0 +1,234 @@+"""+Module whitelist for safe dynamic imports.++This module provides secure dynamic import functionality with a strict whitelist+of allowed modules and class names. This prevents arbitrary code execution through+user-controlled configuration values.++Security Features:+- Validates module paths against a whitelist of trusted modules+- Validates class names against a whitelist of legitimate search engine classes+- Prevents loading of arbitrary code through malicious configuration+- Logs security-relevant events for auditing+"""++import importlib+from typing import Optional, Type++from loguru import logger+++# Whitelist of allowed module paths for dynamic import.+# Only modules in this list can be loaded dynamically.+# SECURITY: Only relative paths (starting with ".") are allowed.+# This ensures all imports are relative to local_deep_research.web_search_engines+# and prevents arbitrary module imports from other packages.+ALLOWED_MODULE_PATHS: frozenset[str] = frozenset(+ [+ # Relative imports only (relative to local_deep_research.web_search_engines)+ # Absolute paths are NOT allowed for security reasons+ ".engines.full_search",+ ".engines.full_serp_search_results_old",+ ".engines.meta_search_engine",+ ".engines.parallel_search_engine",+ ".engines.search_engine_arxiv",+ ".engines.search_engine_brave",+ ".engines.search_engine_collection",+ ".engines.search_engine_ddg",+ ".engines.search_engine_elasticsearch",+ ".engines.search_engine_github",+ ".engines.search_engine_google_pse",+ ".engines.search_engine_guardian",+ ".engines.search_engine_library",+ ".engines.search_engine_local",+ ".engines.search_engine_local_all",+ ".engines.search_engine_nasa_ads",+ ".engines.search_engine_openalex",+ ".engines.search_engine_paperless",+ ".engines.search_engine_pubmed",+ ".engines.search_engine_retriever",+ ".engines.search_engine_scaleserp",+ ".engines.search_engine_searxng",+ ".engines.search_engine_semantic_scholar",+ ".engines.search_engine_serper",+ ".engines.search_engine_serpapi",+ ".engines.search_engine_tavily",+ ".engines.search_engine_wayback",+ ".engines.search_engine_wikipedia",+ ".engines.search_engine_wikinews",+ ".search_engine_base",+ ]+)++# Legacy alias for backward compatibility+ALLOWED_MODULES = ALLOWED_MODULE_PATHS+++# Whitelist of allowed class names for search engines.+# Only classes in this list can be instantiated through dynamic import.+ALLOWED_CLASS_NAMES: frozenset[str] = frozenset(+ [+ # Search engine implementation classes+ "ArXivSearchEngine",+ "BaseSearchEngine",+ "BraveSearchEngine",+ "CollectionSearchEngine",+ "DuckDuckGoSearchEngine",+ "ElasticsearchSearchEngine",+ "FullSearchResults",+ "GitHubSearchEngine",+ "GooglePSESearchEngine",+ "GuardianSearchEngine",+ "LibraryRAGSearchEngine",+ "LocalAllSearchEngine",+ "LocalSearchEngine",+ "MetaSearchEngine",+ "NasaAdsSearchEngine",+ "OpenAlexSearchEngine",+ "PaperlessSearchEngine",+ "ParallelSearchEngine",+ "PubMedSearchEngine",+ "RetrieverSearchEngine",+ "ScaleSerpSearchEngine",+ "SearXNGSearchEngine",+ "SemanticScholarSearchEngine",+ "SerpAPISearchEngine",+ "SerperSearchEngine",+ "TavilySearchEngine",+ "WaybackSearchEngine",+ "WikinewsSearchEngine",+ "WikipediaSearchEngine",+ ]+)+++class SecurityError(Exception):+ """Raised when a security validation fails during module import."""++ pass+++# Legacy alias for backward compatibility+ModuleNotAllowedError = SecurityError+++def validate_module_import(module_path: str, class_name: str) -> bool:+ """+ Validate that both module_path and class_name are in their respective whitelists.++ This function provides a security check to ensure that dynamically loaded+ search engine modules are from trusted sources only. It validates:+ 1. Module path starts with "." (relative import only)+ 2. Module path is in the whitelist+ 3. Class name is in the whitelist++ Args:+ module_path: The Python module path (MUST be relative, starting with ".")+ class_name: The class name to import from the module++ Returns:+ True if all validations pass, False otherwise++ Example:+ >>> validate_module_import(".engines.search_engine_brave", "BraveSearchEngine")+ True+ >>> validate_module_import("os", "system")+ False+ """+ if not module_path or not class_name:+ logger.warning(+ "Module validation failed: empty module_path or class_name"+ )+ return False++ # SECURITY: Only allow relative imports (starting with ".")+ # This ensures imports are relative to local_deep_research.web_search_engines+ # and prevents loading arbitrary modules like "os" or "subprocess"+ if not module_path.startswith("."):+ logger.warning(+ f"Security: Rejected non-relative module path: {module_path}. "+ f"Only relative imports (starting with '.') are allowed."+ )+ return False++ module_valid = module_path in ALLOWED_MODULE_PATHS+ class_valid = class_name in ALLOWED_CLASS_NAMES++ if not module_valid:+ logger.warning(f"Module path not in whitelist: {module_path}")++ if not class_valid:+ logger.warning(f"Class name not in whitelist: {class_name}")++ return module_valid and class_valid+++def get_safe_module_class(+ module_path: str,+ class_name: str,+ package: Optional[str] = None,+) -> Type:+ """+ Safely import a class from a module, validating against both whitelists.++ This function provides secure dynamic import functionality by:+ 1. Validating the module path against a strict whitelist+ 2. Validating the class name against a strict whitelist+ 3. Only allowing imports from trusted local_deep_research modules+ 4. Preventing arbitrary code execution through configuration++ Args:+ module_path: The module path to import from+ (e.g., "local_deep_research.web_search_engines.engines.search_engine_brave"+ or ".engines.search_engine_brave" for relative imports)+ class_name: The class name to retrieve from the module+ package: Optional package for relative imports. If not provided and+ module_path starts with ".", defaults to+ "local_deep_research.web_search_engines"++ Returns:+ The requested class from the module++ Raises:+ SecurityError: If the module path or class name is not in the whitelist+ ModuleNotFoundError: If the module cannot be imported+ AttributeError: If the class does not exist in the module++ Example:+ >>> cls = get_safe_module_class(".engines.search_engine_brave", "BraveSearchEngine")+ >>> engine = cls(api_key="...")+ """+ # Validate both module path and class name against whitelists+ if not validate_module_import(module_path, class_name):+ logger.error(+ f"Security: Blocked attempt to import non-whitelisted module/class: "+ f"module_path={module_path!r}, class_name={class_name!r}"+ )+ raise SecurityError(+ f"Import blocked: module_path={module_path!r} or class_name={class_name!r} "+ f"is not in the security whitelist. Only trusted local_deep_research "+ f"modules and classes can be dynamically imported."+ )++ # Determine package for relative imports+ if package is None and module_path.startswith("."):+ package = "local_deep_research.web_search_engines"++ # Import the module+ try:+ module = importlib.import_module(module_path, package=package)+ except ModuleNotFoundError:+ logger.exception(f"Failed to import whitelisted module {module_path}")+ raise++ # Get the class from the module+ try:+ engine_class = getattr(module, class_name)+ except AttributeError:+ logger.exception(+ f"Class '{class_name}' not found in module '{module_path}'"+ )+ raise++ logger.debug(f"Successfully loaded {class_name} from {module_path}")+ return engine_classdiff --git a/src/local_deep_research/web/routes/api_routes.py b/src/local_deep_research/web/routes/api_routes.pyindex 98b42526f8..002cae9ea8 100644--- a/src/local_deep_research/web/routes/api_routes.py+++ b/src/local_deep_research/web/routes/api_routes.py@@ -248,6 +248,19 @@ def api_add_resource(research_id):400,)+ # Security: Validate URL to prevent SSRF attacks+ from ...security.ssrf_validator import validate_url++ is_valid, error_msg = validate_url(url)+ if not is_valid:+ logger.warning(f"SSRF protection: Rejected URL {url}: {error_msg}")+ return (+ jsonify(+ {"status": "error", "message": f"Invalid URL: {error_msg}"}+ ),+ 400,+ )+# Check if the research existswith get_user_db_session() as db_session:research = (diff --git a/src/local_deep_research/web/routes/research_routes.py b/src/local_deep_research/web/routes/research_routes.pyindex 0b97d1add5..58f9e7faf5 100644--- a/src/local_deep_research/web/routes/research_routes.py+++ b/src/local_deep_research/web/routes/research_routes.py@@ -922,6 +922,15 @@ def clear_history():@login_requireddef open_file_location():"""Open a file location in the system file explorer"""+ # Security: This endpoint is disabled for server deployments+ # It only makes sense for desktop usage where the server and client are on the same machine+ return jsonify(+ {+ "status": "error",+ "message": "This feature is disabled. It is only available in desktop mode.",+ }+ ), 403+data = request.jsonfile_path = data.get("path")@@ -995,6 +1004,55 @@ def save_raw_config():400,)+ # Security: Parse and validate the TOML to block dangerous keys+ try:+ import tomllib+ except ImportError:+ import tomli as tomllib++ try:+ parsed_config = tomllib.loads(raw_config)+ except Exception as e:+ logger.warning(f"Invalid TOML configuration: {e}")+ return jsonify(+ {"success": False, "error": f"Invalid TOML syntax: {e}"}+ ), 400++ # Security: Check for dangerous keys that could enable code execution+ # These patterns match keys used for dynamic module imports+ BLOCKED_KEY_PATTERNS = ["module_path", "class_name", "module", "class"]++ def find_blocked_keys(obj, path=""):+ """Recursively find any blocked keys in the config."""+ blocked = []+ if isinstance(obj, dict):+ for key, value in obj.items():+ current_path = f"{path}.{key}" if path else key+ key_lower = key.lower()+ for pattern in BLOCKED_KEY_PATTERNS:+ if pattern in key_lower:+ blocked.append(current_path)+ break+ # Recurse into nested dicts+ blocked.extend(find_blocked_keys(value, current_path))+ elif isinstance(obj, list):+ for i, item in enumerate(obj):+ blocked.extend(find_blocked_keys(item, f"{path}[{i}]"))+ return blocked++ blocked_keys = find_blocked_keys(parsed_config)+ if blocked_keys:+ logger.warning(+ f"Security: Blocked attempt to write config with dangerous keys: {blocked_keys}"+ )+ return jsonify(+ {+ "success": False,+ "error": "Configuration contains protected keys that cannot be modified",+ "blocked_keys": blocked_keys,+ }+ ), 403+try:from ...security.file_write_verifier import write_file_verifieddiff --git a/src/local_deep_research/web/routes/settings_routes.py b/src/local_deep_research/web/routes/settings_routes.pyindex 3028144d8f..e696c5e170 100644--- a/src/local_deep_research/web/routes/settings_routes.py+++ b/src/local_deep_research/web/routes/settings_routes.py@@ -80,6 +80,60 @@ settings_bp = Blueprint("settings", __name__, url_prefix="/settings")# Settings with dynamically populated options (excluded from validation)DYNAMIC_SETTINGS = ["llm.provider", "llm.model", "search.tool"]+# Security: Block modification of settings that could enable code execution+# These patterns match setting keys that could be used for dynamic imports+# or other security-sensitive operations+BLOCKED_SETTING_PATTERNS = [+ "module_path", # Any setting ending with .module_path or containing module_path+ "class_name", # Any setting ending with .class_name or containing class_name+ "module", # Any setting containing "module" (e.g., custom_module, module_loader)+ "class", # Any setting containing "class" (e.g., handler_class, class_loader)+]+++def is_blocked_setting(key: str) -> bool:+ """+ Check if a setting key matches any blocked pattern.++ These settings are blocked because they could potentially be used+ for dynamic code imports/execution, which is a security risk.++ Args:+ key: The setting key to check (e.g., "search.custom_engine.module_path")++ Returns:+ True if the setting is blocked, False otherwise+ """+ key_lower = key.lower()+ for pattern in BLOCKED_SETTING_PATTERNS:+ if pattern in key_lower:+ return True+ return False+++def get_blocked_settings_error(blocked_keys: list) -> dict:+ """+ Generate an error response for blocked setting modification attempts.++ Args:+ blocked_keys: List of setting keys that were blocked++ Returns:+ Error response dictionary+ """+ return {+ "status": "error",+ "message": "Security violation: Attempted to modify protected settings",+ "errors": [+ {+ "key": key,+ "name": key,+ "error": "This setting cannot be modified for security reasons",+ }+ for key in blocked_keys+ ],+ }+def _get_setting_from_session(key: str, default=None):"""Helper to get a setting using the current session context."""@@ -263,6 +317,16 @@ def save_all_settings():400,)+ # Security check: Block any attempts to modify dangerous settings+ blocked_keys = [+ key for key in form_data.keys() if is_blocked_setting(key)+ ]+ if blocked_keys:+ logger.warning(+ f"Blocked attempt to modify protected settings: {blocked_keys}"+ )+ return jsonify(get_blocked_settings_error(blocked_keys)), 403+# Track validation errorsvalidation_errors = []settings_by_type = {}@@ -619,6 +683,21 @@ def save_settings():# Remove CSRF token from the dataform_data.pop("csrf_token", None)+ # Security check: Block any attempts to modify dangerous settings+ blocked_keys = [+ key for key in form_data.keys() if is_blocked_setting(key)+ ]+ if blocked_keys:+ logger.warning(+ f"Blocked attempt to modify protected settings: {blocked_keys}"+ )+ flash(+ "Security error: Attempted to modify protected settings. "+ "These settings cannot be modified for security reasons.",+ "error",+ )+ return redirect(url_for("settings.settings_page"))+with get_user_db_session(username) as db_session:settings_manager = SettingsManager(db_session)@@ -775,6 +854,17 @@ def api_get_db_setting(key):def api_update_setting(key):"""Update a setting"""try:+ # Security check: Block any attempts to modify dangerous settings+ if is_blocked_setting(key):+ logger.warning(+ f"Blocked attempt to modify protected setting via API: {key}"+ )+ return jsonify(+ {+ "error": "This setting cannot be modified for security reasons"+ }+ ), 403+# Get request datadata = request.get_json()if not data:@@ -903,6 +993,17 @@ def api_update_setting(key):def api_delete_setting(key):"""Delete a setting"""try:+ # Security check: Block any attempts to delete dangerous settings+ if is_blocked_setting(key):+ logger.warning(+ f"Blocked attempt to delete protected setting via API: {key}"+ )+ return jsonify(+ {+ "error": "This setting cannot be modified for security reasons"+ }+ ), 403+username = session.get("username")with get_user_db_session(username) as db_session:@@ -1540,7 +1641,10 @@ def api_get_available_search_engines():if search_engines:# Format engines for API response with metadata- from importlib import import_module+ from ...security.module_whitelist import (+ get_safe_module_class,+ SecurityError,+ )for engine_id, engine_data in search_engines.items():# Try to load the engine class to get metadata@@ -1549,14 +1653,14 @@ def api_get_available_search_engines():module_path = engine_data.get("module_path")class_name = engine_data.get("class_name")if module_path and class_name:- # Handle relative imports- package = None- if module_path.startswith("."):- package = (- "local_deep_research.web_search_engines"- )- module = import_module(module_path, package=package)- engine_class = getattr(module, class_name, None)+ # Use secure whitelist-validated import+ engine_class = get_safe_module_class(+ module_path, class_name+ )+ except SecurityError as e:+ logger.warning(+ f"Security: Blocked unsafe module for {engine_id}: {e}"+ )except Exception as e:logger.debug(f"Could not load engine class for {engine_id}: {e}"@@ -1755,6 +1859,15 @@ def search_engines_config_page():@login_requireddef open_file_location():"""Open the location of a configuration file"""+ # Security: This endpoint is disabled for server deployments+ # It only makes sense for desktop usage where the server and client are on the same machine+ return jsonify(+ {+ "status": "error",+ "message": "This feature is disabled. It is only available in desktop mode.",+ }+ ), 403+file_path = request.form.get("file_path")if not file_path:diff --git a/src/local_deep_research/web_search_engines/search_engine_base.py b/src/local_deep_research/web_search_engines/search_engine_base.pyindex 650b5b86de..dfa5bc57fd 100644--- a/src/local_deep_research/web_search_engines/search_engine_base.py+++ b/src/local_deep_research/web_search_engines/search_engine_base.py@@ -74,7 +74,10 @@ class BaseSearchEngine(ABC):Returns:Tuple of (success: bool, engine_class or None, error_msg or None)"""- import importlib+ from ..security.module_whitelist import (+ ModuleNotAllowedError,+ get_safe_module_class,+ )try:module_path = config.get("module_path")@@ -87,16 +90,17 @@ class BaseSearchEngine(ABC):f"Missing module_path or class_name for {name}",)- # Import the module- package = None- if module_path.startswith("."):- # This is a relative import- package = "local_deep_research.web_search_engines"- module = importlib.import_module(module_path, package=package)- engine_class = getattr(module, class_name)+ # Use whitelist-validated safe import+ engine_class = get_safe_module_class(module_path, class_name)return True, engine_class, None+ except ModuleNotAllowedError as e:+ return (+ False,+ None,+ f"Security error loading engine class for {name}: {e}",+ )except Exception as e:return False, None, f"Could not load engine class for {name}: {e}"diff --git a/src/local_deep_research/web_search_engines/search_engine_factory.py b/src/local_deep_research/web_search_engines/search_engine_factory.pyindex aa2185c5b5..e37a77d04a 100644--- a/src/local_deep_research/web_search_engines/search_engine_factory.py+++ b/src/local_deep_research/web_search_engines/search_engine_factory.py@@ -1,9 +1,9 @@-import importlibimport inspectfrom typing import Any, Dict, Optionalfrom loguru import logger+from ..security.module_whitelist import get_safe_module_classfrom ..utilities.enums import SearchModefrom .retriever_registry import retriever_registryfrom .search_engine_base import BaseSearchEngine@@ -196,13 +196,7 @@ def create_search_engine(module_path = engine_config["module_path"]class_name = engine_config["class_name"]- package = None- if module_path.startswith("."):- # This is a relative import. Assume it's relative to- # `web_search_engines`.- package = "local_deep_research.web_search_engines"- module = importlib.import_module(module_path, package=package)- engine_class = getattr(module, class_name)+ engine_class = get_safe_module_class(module_path, class_name)# Get the engine class's __init__ parameters to filter out unsupported onesengine_init_signature = inspect.signature(engine_class.__init__)@@ -404,8 +398,7 @@ def _create_full_search_wrapper(return base_engine# Import the full search class- module = importlib.import_module(module_path)- full_search_class = getattr(module, class_name)+ full_search_class = get_safe_module_class(module_path, class_name)# Get the wrapper's __init__ parameters to filter out unsupported oneswrapper_init_signature = inspect.signature(full_search_class.__init__)