Turn any technical book PDF into a Claude Code skill — ready to study, reference, and use while you work.
Python agent-skillsai-agentsbook-to-skillcontext-engineeringdocument-processingedtechknowledge-baseknowledge-managementllmpdf-to-markdownragself-studystudy-tools
fix(security): mitigate parser vulnerabilities and upgrade PyPDF2 (#53) (#54)
Marcello Mendoa01916c31391
diff --git a/README.md b/README.mdindex 273adf1..cacd12c 100644--- a/README.md+++ b/README.md@@ -125,7 +125,7 @@ The extractor tries tools in order per format and uses the first available. If n| Book type | Tool | Install | Speed ||-----------|------|---------|-------|| Text-heavy (prose, few tables) | `pdftotext` (poppler) | `sudo apt install poppler-utils` | ⚡ instant |-| Text-heavy fallback | `PyPDF2` | `pip3 install PyPDF2` | ⚡ instant |+| Text-heavy fallback | `pypdf` | `pip3 install pypdf` | ⚡ instant || Text-heavy fallback | `pdfminer.six` | `pip3 install pdfminer.six` | ⚡ instant || **Technical (code, tables, formulas)** | **`docling`** | `pip3 install docling` | ~1.5s/page |@@ -159,7 +159,7 @@ One file · a folder · a glob · a list of pathsStep 1.5 — "Technical or text-heavy book?"│├── technical → Docling (tables + code blocks as markdown, ~1.5s/page)- └── text → pdftotext → PyPDF2 → pdfminer (instant)+ └── text → pdftotext → pypdf → pdfminer (instant)│▼scripts/extract.py <paths…> --mode <technical|text>diff --git a/book_to_skill/config.py b/book_to_skill/config.pyindex 3486742..0d4a9fc 100644--- a/book_to_skill/config.py+++ b/book_to_skill/config.py@@ -25,7 +25,7 @@ SUPPORTED_EXTENSIONS = {PYTHON_DEPENDENCIES = {"docling": "docling",- "PyPDF2": "PyPDF2",+ "pypdf": "pypdf","pdfminer": "pdfminer.six","ebooklib": "ebooklib","bs4": "beautifulsoup4",diff --git a/book_to_skill/dependencies.py b/book_to_skill/dependencies.pyindex cab0b8a..903d7a6 100644--- a/book_to_skill/dependencies.py+++ b/book_to_skill/dependencies.py@@ -14,11 +14,11 @@ from book_to_skill.config import PYTHON_DEPENDENCIES, HTML_EXTENSIONSDEPENDENCY_GROUPS = [{"label": "PDF (text-heavy)",- "modules": ["PyPDF2", "pdfminer"],+ "modules": ["pypdf", "pdfminer"],"any_of_modules": True,"any_tool_suffices": True,"system": [("pdftotext", "poppler-utils", "sudo apt install poppler-utils")],- "note": "any one of pdftotext / PyPDF2 / pdfminer is enough",+ "note": "any one of pdftotext / pypdf / pdfminer is enough",},{"label": "PDF (technical: tables, code, formulas)",@@ -175,7 +175,7 @@ def prepare_dependencies(ext: str, extraction_mode: str, install_mode: str) -> Nif ext == ".pdf" and not shutil.which("pdftotext"):offer_dependency_install(feature="PDF text extraction",- module_names=["PyPDF2", "pdfminer"],+ module_names=["pypdf", "pdfminer"],fallback="any installed Python PDF parser; extraction fails if none are available",install_mode=install_mode,)diff --git a/book_to_skill/parsers/calibre.py b/book_to_skill/parsers/calibre.pyindex f182ae0..e02b3d8 100644--- a/book_to_skill/parsers/calibre.py+++ b/book_to_skill/parsers/calibre.py@@ -1,5 +1,6 @@from __future__ import annotations+import osimport shutilimport subprocessimport sys@@ -11,6 +12,7 @@ def extract_with_ebook_convert(input_path: str) -> str | None:return Noneoutput_path = OUTPUT_DIR / "ebook-convert-output.txt"try:+ input_path = os.path.abspath(input_path)result = subprocess.run(["ebook-convert", input_path, str(output_path)],capture_output=True, text=True, timeout=300diff --git a/book_to_skill/parsers/docx.py b/book_to_skill/parsers/docx.pyindex 08d7685..52bf22b 100644--- a/book_to_skill/parsers/docx.py+++ b/book_to_skill/parsers/docx.py@@ -22,6 +22,7 @@ def extract_docx_with_python_docx(docx_path: str) -> str | None:print(f" [warn] extract_docx_with_python_docx failed: {type(e).__name__}: {e}", file=sys.stderr)return None+def extract_docx_with_zipfile(docx_path: str) -> str | None:try:import xml.etree.ElementTree as ET@@ -41,7 +42,32 @@ def extract_docx_with_zipfile(docx_path: str) -> str | None:return None+def validate_docx_xml_safety(docx_path: str) -> None:+ """Scan all XML files in the DOCX zip archive to prevent XML Entity Expansion (Billion Laughs) and XXE injections."""+ try:+ with zipfile.ZipFile(docx_path) as zf:+ for name in zf.namelist():+ if name.endswith(".xml") or name.endswith(".rels"):+ xml_bytes = zf.read(name)+ for encoding in ("utf-8", "utf-16", "utf-16le", "utf-16be", "utf-32"):+ try:+ content = xml_bytes.decode(encoding, errors="ignore").upper()+ except LookupError:+ continue+ if "<!DOCTYPE" in content or "<!ENTITY" in content:+ raise ExtractionError(+ f"Security validation failed: XML file '{name}' in DOCX archive contains forbidden DTD or entity declarations."+ )+ except zipfile.BadZipFile as e:+ raise ExtractionError(f"Invalid DOCX file: {e}")+ except ExtractionError:+ raise+ except Exception as e:+ raise ExtractionError(f"Error during security validation of DOCX archive: {e}")++def extract_docx(docx_path: str) -> tuple[str, str]:+ validate_docx_xml_safety(docx_path)print("Trying python-docx...", end=" ", flush=True)text = extract_docx_with_python_docx(docx_path)if text and text.strip():@@ -61,4 +87,3 @@ def extract_docx(docx_path: str) -> tuple[str, str]:"Install python-docx for best results:\n"" pip3 install python-docx")-diff --git a/book_to_skill/parsers/pdf.py b/book_to_skill/parsers/pdf.pyindex 3ea29c0..b9432fe 100644--- a/book_to_skill/parsers/pdf.py+++ b/book_to_skill/parsers/pdf.py@@ -1,5 +1,6 @@from __future__ import annotations+import osimport shutilimport subprocessimport sys@@ -9,6 +10,7 @@ def extract_with_pdftotext(pdf_path: str) -> str | None:if not shutil.which("pdftotext"):return Nonetry:+ pdf_path = os.path.abspath(pdf_path)result = subprocess.run(["pdftotext", "-layout", pdf_path, "-"],capture_output=True, text=True, timeout=120@@ -20,12 +22,12 @@ def extract_with_pdftotext(pdf_path: str) -> str | None:return None-def extract_with_pypdf2(pdf_path: str) -> str | None:+def extract_with_pypdf(pdf_path: str) -> str | None:try:- import PyPDF2+ import pypdftext_parts = []with open(pdf_path, "rb") as f:- reader = PyPDF2.PdfReader(f)+ reader = pypdf.PdfReader(f)for page in reader.pages:try:text_parts.append(page.extract_text() or "")@@ -35,7 +37,7 @@ def extract_with_pypdf2(pdf_path: str) -> str | None:except ImportError:return Noneexcept Exception as e:- print(f" [warn] extract_with_pypdf2 failed: {type(e).__name__}: {e}", file=sys.stderr)+ print(f" [warn] extract_with_pypdf failed: {type(e).__name__}: {e}", file=sys.stderr)return None@@ -80,6 +82,7 @@ def count_pages(pdf_path: str) -> int:# Try pdfinfo firstif shutil.which("pdfinfo"):try:+ pdf_path = os.path.abspath(pdf_path)result = subprocess.run(["pdfinfo", pdf_path], capture_output=True, text=True, timeout=15)@@ -88,10 +91,10 @@ def count_pages(pdf_path: str) -> int:return int(line.split(":")[1].strip())except Exception:pass- # Fallback: count form-feed chars (pdftotext -layout uses \f between pages)+ # Fallback: count pages with pypdftry:- import PyPDF2+ import pypdfwith open(pdf_path, "rb") as f:- return len(PyPDF2.PdfReader(f).pages)+ return len(pypdf.PdfReader(f).pages)except Exception:return 0diff --git a/book_to_skill/utils.py b/book_to_skill/utils.pyindex 78f671d..4a4fedc 100644--- a/book_to_skill/utils.py+++ b/book_to_skill/utils.py@@ -35,7 +35,7 @@ from book_to_skill.parsers.calibre import extract_with_ebook_convertfrom book_to_skill.parsers.pdf import (extract_with_docling,extract_with_pdftotext,- extract_with_pypdf2,+ extract_with_pypdf,extract_with_pdfminer,count_pages,)@@ -462,10 +462,10 @@ def extract_single_file(input_path: Path, extraction_mode: str, install_mode: stprint("OK")else:print("not available")- print("Trying PyPDF2...", end=" ", flush=True)- text = extract_with_pypdf2(input_str)+ print("Trying pypdf...", end=" ", flush=True)+ text = extract_with_pypdf(input_str)if text:- method = "PyPDF2"+ method = "pypdf"print("OK")else:print("not available")@@ -478,11 +478,12 @@ def extract_single_file(input_path: Path, extraction_mode: str, install_mode: stprint("FAILED")raise ExtractionError("Could not extract text from PDF.\n"- "Install one of: poppler-utils (pdftotext), PyPDF2, or pdfminer.six\n"+ "Install one of: poppler-utils (pdftotext), pypdf, or pdfminer.six\n"" sudo apt install poppler-utils\n"- " pip3 install PyPDF2\n"+ " pip3 install pypdf\n"" pip3 install pdfminer.six")+pages = count_pages(input_str)pages_label = "pages"diff --git a/pyproject.toml b/pyproject.tomlindex 79b6d33..8ad1ef1 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -15,20 +15,21 @@ book-to-skill = "book_to_skill.cli:main"[project.optional-dependencies]epub = ["ebooklib", "beautifulsoup4"]-pdf = ["PyPDF2", "pdfminer.six"]+pdf = ["pypdf", "pdfminer.six"]docx = ["python-docx"]rtf = ["striprtf"]technical = ["docling"]all = ["ebooklib","beautifulsoup4",- "PyPDF2",+ "pypdf","pdfminer.six","python-docx","striprtf","docling"]+# Tooling config so `ruff check .` and `pytest` locally match CI without flags.[tool.ruff]target-version = "py39"diff --git a/tests/test_book_to_skill.py b/tests/test_book_to_skill.pyindex beccabd..f8e6e5b 100644--- a/tests/test_book_to_skill.py+++ b/tests/test_book_to_skill.py@@ -858,6 +858,32 @@ class TestDocxExtraction:assert result["format"] == "docx"assert "DOCX test paragraph" in result["text"]+ def test_extract_docx_xxe_rejection(self, tmp_path):+ """Verify that a DOCX with malicious DTD or entity declarations is rejected."""+ from book_to_skill.parsers.docx import extract_docx++ # Create a malicious DOCX+ ns = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"+ xml = textwrap.dedent(f"""\+ <?xml version="1.0" encoding="UTF-8" standalone="yes"?>+ <!DOCTYPE w:document [+ <!ENTITY xxe SYSTEM "file:///etc/passwd">+ ]>+ <w:document xmlns:w="{ns}">+ <w:body>+ <w:p><w:r><w:t>&xxe;</w:t></w:r></w:p>+ </w:body>+ </w:document>+ """)+ bad_docx = tmp_path / "malicious.docx"+ with zipfile.ZipFile(bad_docx, "w") as zf:+ zf.writestr("word/document.xml", xml)+ zf.writestr("[Content_Types].xml", '<?xml version="1.0"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"/>')++ with pytest.raises(ExtractionError, match="Security validation failed"):+ extract_docx(str(bad_docx))++class TestResolveInputFiles:"""Additional edge-case tests for resolve_input_files."""@@ -943,9 +969,9 @@ class TestDependencyCheck:class TestParserExceptionLogging:"""Verify unexpected parser exceptions surface on stderr, chain returns None."""- def test_pypdf2_warns_on_unexpected_error_and_returns_none(self, tmp_path, capsys):- """Monkeypatch pypdf2 import to raise; confirm None + stderr warning."""- from book_to_skill.parsers.pdf import extract_with_pypdf2+ def test_pypdf_warns_on_unexpected_error_and_returns_none(self, tmp_path, capsys):+ """Monkeypatch pypdf import to raise; confirm None + stderr warning."""+ from book_to_skill.parsers.pdf import extract_with_pypdfbroken = tmp_path / "broken.pdf"broken.write_bytes(b"%PDF-1.4 fake")@@ -953,14 +979,14 @@ class TestParserExceptionLogging:real_import = __import__def fake_import(name, *args, **kwargs):- if name == "PyPDF2":+ if name == "pypdf":raise RuntimeError("simulated failure")return real_import(name, *args, **kwargs)with mock.patch("builtins.__import__", side_effect=fake_import):- result = extract_with_pypdf2(str(broken))+ result = extract_with_pypdf(str(broken))assert result is Nonecaptured = capsys.readouterr()assert "[warn]" in captured.err- assert "failed:" in captured.err\ No newline at end of file+ assert "failed:" in captured.err\ No newline at end of file