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 Research Library (Issue #207)

LearningCircuitff8132e4c9fd
diff --git a/src/local_deep_research/research_library/downloaders/arxiv.py b/src/local_deep_research/research_library/downloaders/arxiv.py
index 4d366c7430..0cd12b2240 100644
--- a/src/local_deep_research/research_library/downloaders/arxiv.py
+++ b/src/local_deep_research/research_library/downloaders/arxiv.py
@@ -4,6 +4,7 @@ arXiv PDF and Text Downloader
import re
from typing import Optional
+from urllib.parse import urlparse
from loguru import logger
from .base import BaseDownloader, ContentType, DownloadResult
@@ -14,7 +15,14 @@ class ArxivDownloader(BaseDownloader):
def can_handle(self, url: str) -> bool:
"""Check if URL is from arXiv."""
- return "arxiv.org" in url
+ try:
+ hostname = urlparse(url).hostname
+ return bool(
+ hostname
+ and (hostname == "arxiv.org" or hostname.endswith(".arxiv.org"))
+ )
+ except Exception:
+ return False
def download(
self, url: str, content_type: ContentType = ContentType.PDF
diff --git a/src/local_deep_research/research_library/downloaders/biorxiv.py b/src/local_deep_research/research_library/downloaders/biorxiv.py
index eb461c79f4..399dd03891 100644
--- a/src/local_deep_research/research_library/downloaders/biorxiv.py
+++ b/src/local_deep_research/research_library/downloaders/biorxiv.py
@@ -4,6 +4,7 @@ bioRxiv/medRxiv PDF and Text Downloader
import re
from typing import Optional
+from urllib.parse import urlparse
from loguru import logger
from .base import BaseDownloader, ContentType, DownloadResult
@@ -14,7 +15,18 @@ class BioRxivDownloader(BaseDownloader):
def can_handle(self, url: str) -> bool:
"""Check if URL is from bioRxiv or medRxiv."""
- return "biorxiv.org" in url or "medrxiv.org" in url
+ try:
+ hostname = urlparse(url).hostname
+ if not hostname:
+ return False
+ return (
+ hostname == "biorxiv.org"
+ or hostname.endswith(".biorxiv.org")
+ or hostname == "medrxiv.org"
+ or hostname.endswith(".medrxiv.org")
+ )
+ except Exception:
+ return False
def download(
self, url: str, content_type: ContentType = ContentType.PDF
diff --git a/src/local_deep_research/research_library/downloaders/pubmed.py b/src/local_deep_research/research_library/downloaders/pubmed.py
index 727c0b985b..50dcf01435 100644
--- a/src/local_deep_research/research_library/downloaders/pubmed.py
+++ b/src/local_deep_research/research_library/downloaders/pubmed.py
@@ -5,6 +5,7 @@ PubMed/PMC PDF Downloader
import re
import time
from typing import Optional
+from urllib.parse import urlparse
from loguru import logger
from .base import BaseDownloader, ContentType, DownloadResult
@@ -27,14 +28,29 @@ class PubMedDownloader(BaseDownloader):
def can_handle(self, url: str) -> bool:
"""Check if URL is from PubMed or PMC."""
- return any(
- domain in url
- for domain in [
- "pubmed.ncbi.nlm.nih.gov",
- "ncbi.nlm.nih.gov/pmc",
- "europepmc.org",
- ]
- )
+ try:
+ parsed = urlparse(url)
+ hostname = parsed.hostname
+ if not hostname:
+ return False
+
+ # Check for pubmed.ncbi.nlm.nih.gov
+ if hostname == "pubmed.ncbi.nlm.nih.gov":
+ return True
+
+ # Check for ncbi.nlm.nih.gov with /pmc in path
+ if hostname == "ncbi.nlm.nih.gov" and "/pmc" in parsed.path:
+ return True
+
+ # Check for europepmc.org and its subdomains
+ if hostname == "europepmc.org" or hostname.endswith(
+ ".europepmc.org"
+ ):
+ return True
+
+ return False
+ except Exception:
+ return False
def download(
self, url: str, content_type: ContentType = ContentType.PDF
@@ -72,11 +88,18 @@ class PubMedDownloader(BaseDownloader):
def _download_pdf_content(self, url: str) -> Optional[bytes]:
"""Download PDF from PubMed/PMC."""
# Handle different URL types
- if "/pmc/articles/PMC" in url:
+ parsed = urlparse(url)
+ hostname = parsed.hostname or ""
+ path = parsed.path or ""
+
+ # Check for PMC article direct download
+ if hostname == "ncbi.nlm.nih.gov" and "/pmc/articles/PMC" in path:
return self._download_pmc_direct(url)
- elif "pubmed.ncbi.nlm.nih.gov" in url:
+ # Check for PubMed main site
+ elif hostname == "pubmed.ncbi.nlm.nih.gov":
return self._download_pubmed(url)
- elif "europepmc.org" in url:
+ # Check for Europe PMC and subdomains
+ elif hostname == "europepmc.org" or hostname.endswith(".europepmc.org"):
return self._download_europe_pmc(url)
return None
@@ -106,7 +129,7 @@ class PubMedDownloader(BaseDownloader):
skip_reason=f"PMC article {pmc_id} not accessible - may be retracted or embargoed"
)
- elif "pubmed.ncbi.nlm.nih.gov" in url:
+ elif urlparse(url).hostname == "pubmed.ncbi.nlm.nih.gov":
# Extract PMID
pmid_match = re.search(r"/(\d+)/?", url)
if not pmid_match:
@@ -183,19 +206,30 @@ class PubMedDownloader(BaseDownloader):
skip_reason="No free full-text available - article may be paywalled"
)
- elif "europepmc.org" in url:
- pmc_match = re.search(r"(PMC\d+)", url)
- if pmc_match:
- pmc_id = pmc_match.group(1)
- pdf_content = self._download_via_europe_pmc(pmc_id)
- if pdf_content:
- return DownloadResult(content=pdf_content, is_success=True)
+ else:
+ parsed = urlparse(url)
+ hostname = parsed.hostname or ""
+ if hostname == "europepmc.org" or hostname.endswith(
+ ".europepmc.org"
+ ):
+ pmc_match = re.search(r"(PMC\d+)", url)
+ if pmc_match:
+ pmc_id = pmc_match.group(1)
+ pdf_content = self._download_via_europe_pmc(pmc_id)
+ if pdf_content:
+ return DownloadResult(
+ content=pdf_content, is_success=True
+ )
+ return DownloadResult(
+ skip_reason=f"Europe PMC article {pmc_id} not accessible"
+ )
return DownloadResult(
- skip_reason=f"Europe PMC article {pmc_id} not accessible"
+ skip_reason="Invalid Europe PMC URL format"
+ )
+ else:
+ return DownloadResult(
+ skip_reason="Unsupported PubMed/PMC URL format"
)
- return DownloadResult(skip_reason="Invalid Europe PMC URL format")
-
- return DownloadResult(skip_reason="Unsupported PubMed/PMC URL format")
def _download_text(self, url: str) -> Optional[bytes]:
"""Download full text content from PubMed/PMC APIs."""
@@ -203,7 +237,8 @@ class PubMedDownloader(BaseDownloader):
pmid = None
pmc_id = None
- if "pubmed.ncbi.nlm.nih.gov" in url:
+ parsed_url = urlparse(url)
+ if parsed_url.hostname == "pubmed.ncbi.nlm.nih.gov":
pmid_match = re.search(r"/(\d+)/?", url)
if pmid_match:
pmid = pmid_match.group(1)
diff --git a/src/local_deep_research/research_library/routes/library_routes.py b/src/local_deep_research/research_library/routes/library_routes.py
index 787850db2a..b1c5afb57b 100644
--- a/src/local_deep_research/research_library/routes/library_routes.py
+++ b/src/local_deep_research/research_library/routes/library_routes.py
@@ -27,6 +27,8 @@ from ...database.models.research import ResearchResource
from ...database.models.library import LibraryDocument, LibraryDownloadQueue
from ..services.download_service import DownloadService
from ..services.library_service import LibraryService
+from ...security.path_validator import PathValidator
+from ...utilities.db_utils import get_settings_manager
# Create Blueprint
library_bp = Blueprint("library", __name__, url_prefix="/library")
@@ -226,26 +228,55 @@ def open_folder():
data = request.json
path = data.get("path")
- if path and Path(path).exists():
- folder = str(Path(path).parent)
+ if not path:
+ return jsonify({"success": False, "error": "Path not provided"})
+
+ try:
+ # Get library root path from settings
+ settings = get_settings_manager()
+ library_root = (
+ Path(
+ settings.get_setting(
+ "research_library.storage_path",
+ "~/.local-deep-research/library",
+ )
+ )
+ .expanduser()
+ .resolve()
+ )
- import sys
- import subprocess
+ # Validate the path is within library root
+ validated_path = PathValidator.validate_safe_path(
+ path, library_root, allow_absolute=False
+ )
- try:
- if sys.platform == "win32":
- import os
+ if not validated_path or not validated_path.exists():
+ return jsonify(
+ {"success": False, "error": "Invalid or non-existent path"}
+ )
- os.startfile(folder)
- elif sys.platform == "darwin":
- subprocess.run(["open", folder])
- else:
- subprocess.run(["xdg-open", folder])
- return jsonify({"success": True})
- except Exception as e:
- return jsonify({"success": False, "error": str(e)})
+ folder = str(validated_path.parent)
+
+ import sys
+ import subprocess
- return jsonify({"success": False, "error": "Path not found"})
+ if sys.platform == "win32":
+ import os
+
+ os.startfile(folder)
+ elif sys.platform == "darwin":
+ subprocess.run(["open", folder])
+ else:
+ subprocess.run(["xdg-open", folder])
+ return jsonify({"success": True})
+ except ValueError as e:
+ logger.warning(f"Path validation failed: {e}")
+ return jsonify({"success": False, "error": "Invalid path"})
+ except Exception:
+ logger.exception("Failed to open folder")
+ return jsonify(
+ {"success": False, "error": "An internal error has occurred."}
+ )
@library_bp.route("/api/download/<int:resource_id>", methods=["POST"])
diff --git a/src/local_deep_research/research_library/services/download_service.py b/src/local_deep_research/research_library/services/download_service.py
index 82727f31d2..95ec08b716 100644
--- a/src/local_deep_research/research_library/services/download_service.py
+++ b/src/local_deep_research/research_library/services/download_service.py
@@ -453,14 +453,17 @@ class DownloadService:
timestamp = datetime.now(UTC).strftime("%Y%m%d")
# Try to extract identifier from URL
- if "arxiv.org" in resource.url:
+ parsed_url = urlparse(resource.url)
+ hostname = parsed_url.hostname or ""
+
+ if hostname == "arxiv.org" or hostname.endswith(".arxiv.org"):
# Extract arXiv ID
match = re.search(r"(\d{4}\.\d{4,5})", resource.url)
if match:
filename = f"arxiv_{match.group(1)}.pdf"
else:
filename = f"arxiv_{timestamp}_{resource.id}.pdf"
- elif "ncbi.nlm.nih.gov/pmc" in resource.url:
+ elif hostname == "ncbi.nlm.nih.gov" and "/pmc" in parsed_url.path:
# Extract PMC ID
match = re.search(r"(PMC\d+)", resource.url)
if match:
@@ -615,7 +618,7 @@ class DownloadService:
return None
# If it's a regular PubMed URL, try to find PMC version
- elif "pubmed.ncbi.nlm.nih.gov" in url:
+ elif urlparse(url).hostname == "pubmed.ncbi.nlm.nih.gov":
# Extract PMID from URL
pmid_match = re.search(r"/(\d+)/?", url)
if pmid_match:
diff --git a/src/local_deep_research/research_library/services/library_service.py b/src/local_deep_research/research_library/services/library_service.py
index f7fd793832..6b79b58b3f 100644
--- a/src/local_deep_research/research_library/services/library_service.py
+++ b/src/local_deep_research/research_library/services/library_service.py
@@ -12,6 +12,7 @@ import subprocess
import sys
from pathlib import Path
from typing import Dict, List, Optional
+from urllib.parse import urlparse
from loguru import logger
from sqlalchemy import and_, or_, func, Integer, case
@@ -30,6 +31,41 @@ class LibraryService:
"""Initialize library service for a user."""
self.username = username
+ def _is_arxiv_url(self, url: str) -> bool:
+ """Check if URL is from arXiv domain."""
+ try:
+ hostname = urlparse(url).hostname
+ return bool(
+ hostname
+ and (hostname == "arxiv.org" or hostname.endswith(".arxiv.org"))
+ )
+ except Exception:
+ return False
+
+ def _is_pubmed_url(self, url: str) -> bool:
+ """Check if URL is from PubMed or NCBI domains."""
+ try:
+ parsed = urlparse(url)
+ hostname = parsed.hostname
+ if not hostname:
+ return False
+
+ # Check for pubmed.ncbi.nlm.nih.gov
+ if hostname == "pubmed.ncbi.nlm.nih.gov":
+ return True
+
+ # Check for ncbi.nlm.nih.gov with PMC path
+ if hostname == "ncbi.nlm.nih.gov" and "/pmc" in parsed.path:
+ return True
+
+ # Check for pubmed in subdomain
+ if "pubmed" in hostname:
+ return True
+
+ return False
+ except Exception:
+ return False
+
def get_library_stats(self) -> Dict:
"""Get overall library statistics."""
with get_user_db_session(self.username) as session:
@@ -245,9 +281,8 @@ class LibraryService:
"research_mode": research.mode,
"research_date": research.created_at,
# Classification flags
- "is_arxiv": "arxiv.org" in doc.original_url,
- "is_pubmed": "pubmed" in doc.original_url
- or "ncbi.nlm.nih.gov" in doc.original_url,
+ "is_arxiv": self._is_arxiv_url(doc.original_url),
+ "is_pubmed": self._is_pubmed_url(doc.original_url),
"is_pdf": doc.file_type == "pdf",
}
)