~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
refactor: improve URL parsing and enhance security in Research Library
LearningCircuit680c923ded21
diff --git a/src/local_deep_research/research_library/downloaders/direct_pdf.py b/src/local_deep_research/research_library/downloaders/direct_pdf.pyindex 8304595b8d..26e4aea010 100644--- a/src/local_deep_research/research_library/downloaders/direct_pdf.py+++ b/src/local_deep_research/research_library/downloaders/direct_pdf.py@@ -3,6 +3,7 @@ Direct PDF Link Downloader"""from typing import Optional+from urllib.parse import urlparsefrom loguru import loggerfrom .base import BaseDownloader, ContentType, DownloadResult@@ -12,16 +13,34 @@ class DirectPDFDownloader(BaseDownloader):"""Downloader for direct PDF links."""def can_handle(self, url: str) -> bool:- """Check if URL is a direct PDF link."""- # Check for .pdf extension or PDF in query params- url_lower = url.lower()- return (- url_lower.endswith(".pdf")- or ".pdf?" in url_lower- or "/pdf/" in url_lower- or "type=pdf" in url_lower- or "format=pdf" in url_lower- )+ """Check if URL is a direct PDF link using proper URL parsing."""+ try:+ # Parse the URL+ parsed = urlparse(url.lower())+ path = parsed.path or ""+ query = parsed.query or ""++ # Check for .pdf extension in path+ if path.endswith(".pdf"):+ return True++ # Check for .pdf with query parameters+ if ".pdf?" in url.lower():+ return True++ # Check for /pdf/ in path+ if "/pdf/" in path:+ return True++ # Check query parameters for PDF format+ if "type=pdf" in query or "format=pdf" in query:+ return True++ return False++ except Exception as e:+ logger.warning(f"Error parsing URL {url}: {e}")+ return Falsedef download(self, url: str, content_type: ContentType = ContentType.PDFdiff --git a/src/local_deep_research/research_library/downloaders/generic.py b/src/local_deep_research/research_library/downloaders/generic.pyindex 1bcfcecdef..6d6c026aff 100644--- a/src/local_deep_research/research_library/downloaders/generic.py+++ b/src/local_deep_research/research_library/downloaders/generic.py@@ -4,6 +4,7 @@ Generic PDF Downloader for unspecified sourcesfrom typing import Optionalimport requests+from urllib.parse import urlparsefrom loguru import loggerfrom .base import BaseDownloader, ContentType, DownloadResult@@ -62,14 +63,20 @@ class GenericDownloader(BaseDownloader):return DownloadResult(content=pdf_content, is_success=True)# If the URL doesn't end with .pdf, try adding it- if not url.endswith(".pdf"):- pdf_url = url.rstrip("/") + ".pdf"- logger.debug(f"Trying with .pdf extension: {pdf_url}")- pdf_content = super()._download_pdf(pdf_url)+ try:+ parsed = urlparse(url)+ if not parsed.path.endswith(".pdf"):+ pdf_url = url.rstrip("/") + ".pdf"+ logger.debug(f"Trying with .pdf extension: {pdf_url}")+ pdf_content = super()._download_pdf(pdf_url)+ else:+ pdf_content = None+ except:+ pdf_content = None- if pdf_content:- logger.info(f"Successfully downloaded PDF from {pdf_url}")- return DownloadResult(content=pdf_content, is_success=True)+ if pdf_content:+ logger.info(f"Successfully downloaded PDF from {pdf_url}")+ return DownloadResult(content=pdf_content, is_success=True)# Try to determine more specific reasontry:@@ -136,14 +143,20 @@ class GenericDownloader(BaseDownloader):return pdf_content# If the URL doesn't end with .pdf, try adding it- if not url.endswith(".pdf"):- pdf_url = url.rstrip("/") + ".pdf"- logger.debug(f"Trying with .pdf extension: {pdf_url}")- pdf_content = super()._download_pdf(pdf_url)+ try:+ parsed = urlparse(url)+ if not parsed.path.endswith(".pdf"):+ pdf_url = url.rstrip("/") + ".pdf"+ logger.debug(f"Trying with .pdf extension: {pdf_url}")+ pdf_content = super()._download_pdf(pdf_url)+ else:+ pdf_content = None+ except:+ pdf_content = None- if pdf_content:- logger.info(f"Successfully downloaded PDF from {pdf_url}")- return pdf_content+ if pdf_content:+ logger.info(f"Successfully downloaded PDF from {pdf_url}")+ return pdf_contentlogger.warning(f"Failed to download PDF from {url}")return Nonediff --git a/src/local_deep_research/research_library/routes/library_routes.py b/src/local_deep_research/research_library/routes/library_routes.pyindex dbbb3e4b8b..29c292a68f 100644--- a/src/local_deep_research/research_library/routes/library_routes.py+++ b/src/local_deep_research/research_library/routes/library_routes.py@@ -9,6 +9,7 @@ Provides web endpoints for:import jsonfrom pathlib import Path+from urllib.parse import urlparsefrom flask import (Blueprint,jsonify,@@ -34,6 +35,96 @@ from ...utilities.db_utils import get_settings_managerlibrary_bp = Blueprint("library", __name__, url_prefix="/library")+def is_downloadable_domain(url: str) -> bool:+ """Check if URL is from a downloadable academic domain using proper URL parsing."""+ try:+ if not url:+ return False++ parsed = urlparse(url.lower())+ hostname = parsed.hostname or ""+ path = parsed.path or ""+ query = parsed.query or ""++ # Check for direct PDF files+ if path.endswith(".pdf") or ".pdf?" in url.lower():+ return True++ # List of downloadable academic domains+ downloadable_domains = [+ "arxiv.org",+ "biorxiv.org",+ "medrxiv.org",+ "ncbi.nlm.nih.gov",+ "pubmed.ncbi.nlm.nih.gov",+ "europepmc.org",+ "semanticscholar.org",+ "researchgate.net",+ "academia.edu",+ "sciencedirect.com",+ "springer.com",+ "nature.com",+ "wiley.com",+ "ieee.org",+ "acm.org",+ "plos.org",+ "frontiersin.org",+ "mdpi.com",+ "acs.org",+ "rsc.org",+ "tandfonline.com",+ "sagepub.com",+ "oxford.com",+ "cambridge.org",+ "bmj.com",+ "nejm.org",+ "thelancet.com",+ "jamanetwork.com",+ "annals.org",+ "ahajournals.org",+ "cell.com",+ "science.org",+ "pnas.org",+ "elifesciences.org",+ "embopress.org",+ "journals.asm.org",+ "microbiologyresearch.org",+ "jvi.asm.org",+ "genome.cshlp.org",+ "genetics.org",+ "g3journal.org",+ "plantphysiol.org",+ "plantcell.org",+ "aspb.org",+ "bioone.org",+ "company-of-biologists.org",+ "biologists.org",+ "jeb.biologists.org",+ "dmm.biologists.org",+ "bio.biologists.org",+ "doi.org",+ ]++ # Check if hostname matches any downloadable domain+ for domain in downloadable_domains:+ if hostname == domain or hostname.endswith("." + domain):+ return True++ # Special case for PubMed which might appear in path+ if "pubmed" in hostname or "/pubmed/" in path:+ return True++ # Check for PDF in path or query parameters+ if "/pdf/" in path or "type=pdf" in query or "format=pdf" in query:+ return True++ return False++ except Exception as e:+ logger.warning(f"Error parsing URL {url}: {e}")+ return False++# ============= Page Routes =============@@ -547,46 +638,21 @@ def queue_all_undownloaded():skipped_count = 0for resource in undownloaded:- # Check if it's downloadable- url = resource.url.lower() if resource.url else ""-- if not url:+ # Check if it's downloadable using proper URL parsing+ if not resource.url:skipped_count += 1continue- # Check for downloadable sources - be more inclusive- # Include any PDF link or known academic sources- is_downloadable = (- ".pdf" in url- or "arxiv.org" in url- or "biorxiv.org" in url- or "medrxiv.org" in url- or "ncbi.nlm.nih.gov" in url- or "pubmed" in url- or "pubmed.ncbi.nlm.nih.gov" in url # Explicit PubMed domain- or "semanticscholar.org" in url- or "researchgate.net" in url- or "academia.edu" in url- or "sciencedirect.com" in url- or "springer.com" in url- or "nature.com" in url- or "ieee.org" in url- or "acm.org" in url- or "plos.org" in url- or "frontiersin.org" in url- or "mdpi.com" in url- or "doi.org"- in url # DOI links often lead to downloadable papers- )+ is_downloadable = is_downloadable_domain(resource.url)# Log what we're checking- if "pubmed" in url:+ if resource.url and "pubmed" in resource.url.lower():logger.info(f"Found PubMed URL: {resource.url[:100]}")if not is_downloadable:skipped_count += 1logger.debug(- f"Skipping non-downloadable URL: {resource.url[:100]}"+ f"Skipping non-downloadable URL: {resource.url[:100] if resource.url else 'None'}")continuediff --git a/src/local_deep_research/research_library/services/download_service.py b/src/local_deep_research/research_library/services/download_service.pyindex f10c7184fb..eb1e46bb49 100644--- a/src/local_deep_research/research_library/services/download_service.py+++ b/src/local_deep_research/research_library/services/download_service.py@@ -28,6 +28,7 @@ from ...database.models.library import LibraryDocument, LibraryDownloadQueuefrom ...database.models.research import ResearchResourcefrom ...database.session_context import get_user_db_sessionfrom ...utilities.db_utils import get_settings_manager+from ...security.path_validator import PathValidator# Import our modular downloadersfrom ..downloaders import (@@ -504,12 +505,18 @@ class DownloadService:pdf_path = Path(self.library_root) / "pdfs"pdf_path.mkdir(parents=True, exist_ok=True)- # Save file with unique name- file_path = str(pdf_path / filename)- with open(file_path, "wb") as f:+ # Save file with unique name using PathValidator for security+ file_path = pdf_path / filename++ # Validate the path is safe and within library root+ validated_path = PathValidator.validate_safe_path(+ str(file_path), base_dir=str(self.library_root), must_exist=False+ )++ with open(validated_path, "wb") as f:f.write(content)- return file_path+ return validated_pathdef _download_generic(self, url: str) -> Optional[bytes]:"""Generic PDF download method."""