Skip to content

Turn any technical book PDF into a Claude Code skill — ready to study, reference, and use while you work.

fix(security): scrub invisible Unicode from extraction (#75)

Rhein1 / Agoragentic9c2d56dbc559
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 31847cc..85a64cd 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -18,6 +18,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
screen instead of being buried mid-page.
### Security
+- **Invisible-Unicode extraction hardening** — every parser result now removes
+ zero-width U+200B/U+200C/U+200D/U+FEFF characters and the Unicode tag block
+ U+E0000-U+E007F before metrics or `full_text.txt` are produced, reports the
+ removal count, and rejects sources containing no visible content after the scrub.
- **DOCX XXE / Billion Laughs hardening** — the DOCX extractor now scans the
archive and rejects any XML part that declares a DTD or entities before
parsing, blocking XML external-entity and entity-expansion attacks (#53, #54).
diff --git a/book_to_skill/sanitize.py b/book_to_skill/sanitize.py
new file mode 100644
index 0000000..e16ae63
--- /dev/null
+++ b/book_to_skill/sanitize.py
@@ -0,0 +1,24 @@
+from __future__ import annotations
+
+
+_ZERO_WIDTH_CODEPOINTS = frozenset({0x200B, 0x200C, 0x200D, 0xFEFF})
+_TAG_BLOCK_START = 0xE0000
+_TAG_BLOCK_END = 0xE007F
+
+
+def sanitize_extracted_text(text: str) -> tuple[str, int]:
+ """Remove invisible code points used for document-borne prompt injection."""
+ kept: list[str] = []
+ removed = 0
+
+ for character in text:
+ codepoint = ord(character)
+ if (
+ codepoint in _ZERO_WIDTH_CODEPOINTS
+ or _TAG_BLOCK_START <= codepoint <= _TAG_BLOCK_END
+ ):
+ removed += 1
+ continue
+ kept.append(character)
+
+ return "".join(kept), removed
diff --git a/book_to_skill/utils.py b/book_to_skill/utils.py
index 4a4fedc..d7624c9 100644
--- a/book_to_skill/utils.py
+++ b/book_to_skill/utils.py
@@ -44,6 +44,7 @@ from book_to_skill.parsers.epub import (
extract_with_zipfile,
count_epub_chapters,
)
+from book_to_skill.sanitize import sanitize_extracted_text
def estimate_tokens(text: str) -> int:
@@ -523,7 +524,20 @@ def extract_single_file(input_path: Path, extraction_mode: str, install_mode: st
method = "ebook-convert"
pages = 0
pages_label = "sections"
-
+
+ text, removed_invisible = sanitize_extracted_text(text)
+ if removed_invisible:
+ print(
+ f" [security] removed {removed_invisible} invisible Unicode "
+ f"code point(s) from {input_path.name}",
+ file=sys.stderr,
+ )
+ if not text.strip():
+ raise ExtractionError(
+ f"Extracted text from {input_path.name} contained no visible content "
+ "after Unicode sanitization."
+ )
+
tokens = estimate_tokens(text)
structure = detect_structure(text)
file_size_mb = os.path.getsize(input_str) / (1024 * 1024)
diff --git a/tests/test_sanitize_extracted_text.py b/tests/test_sanitize_extracted_text.py
new file mode 100644
index 0000000..77a016a
--- /dev/null
+++ b/tests/test_sanitize_extracted_text.py
@@ -0,0 +1,94 @@
+import json
+import sys
+from unittest import mock
+
+import pytest
+
+from book_to_skill.exceptions import ExtractionError
+from book_to_skill.sanitize import sanitize_extracted_text
+from book_to_skill.utils import extract_single_file, main
+
+
+INVISIBLE_CODEPOINTS = (
+ "\u200b"
+ "\u200c"
+ "\u200d"
+ "\ufeff"
+ "\U000e0000"
+ "\U000e0069"
+ "\U000e007f"
+)
+
+
+def test_sanitizer_removes_zero_width_and_tag_block_codepoints():
+ sanitized, removed = sanitize_extracted_text(
+ f"before{INVISIBLE_CODEPOINTS}after"
+ )
+
+ assert sanitized == "beforeafter"
+ assert removed == len(INVISIBLE_CODEPOINTS)
+
+
+def test_sanitizer_preserves_normal_multilingual_text_byte_for_byte():
+ original = "Cafe\u0301 - \u4e2d\u6587 - \U0001f642 - plain ASCII\n"
+
+ sanitized, removed = sanitize_extracted_text(original)
+
+ assert sanitized == original
+ assert sanitized.encode("utf-8") == original.encode("utf-8")
+ assert removed == 0
+
+
+def test_extract_single_file_sanitizes_before_metrics(tmp_path, capsys):
+ source = tmp_path / "source.txt"
+ source.write_text(
+ "No customer PII\u200b leaves the repo.\U000e0069",
+ encoding="utf-8",
+ )
+
+ with mock.patch("book_to_skill.utils.prepare_dependencies"):
+ result = extract_single_file(source, "text", "no")
+
+ assert result["text"] == "No customer PII leaves the repo."
+ assert result["chars"] == len(result["text"])
+ assert result["words"] == 6
+ captured = capsys.readouterr()
+ assert "removed 2 invisible Unicode code point(s)" in captured.err
+
+
+def test_extract_single_file_rejects_invisible_only_source(tmp_path):
+ source = tmp_path / "invisible.txt"
+ source.write_text(INVISIBLE_CODEPOINTS, encoding="utf-8")
+
+ with mock.patch("book_to_skill.utils.prepare_dependencies"):
+ with pytest.raises(ExtractionError, match="no visible content"):
+ extract_single_file(source, "text", "no")
+
+
+def test_main_writes_only_sanitized_text_and_metrics(tmp_path, monkeypatch):
+ source = tmp_path / "source.txt"
+ source.write_text(
+ "Chapter 1\nPolicy\u200b text.\U000e0069",
+ encoding="utf-8",
+ )
+ output_dir = tmp_path / "output"
+ output_text = output_dir / "full_text.txt"
+ output_meta = output_dir / "metadata.json"
+
+ monkeypatch.setattr(sys, "argv", ["extract.py", str(source)])
+ monkeypatch.setattr("book_to_skill.utils.OUTPUT_DIR", output_dir)
+ monkeypatch.setattr("book_to_skill.utils.OUTPUT_TEXT", output_text)
+ monkeypatch.setattr("book_to_skill.utils.OUTPUT_META", output_meta)
+ monkeypatch.setattr("book_to_skill.utils.prepare_dependencies", lambda *args: None)
+
+ main()
+
+ extracted = output_text.read_text(encoding="utf-8")
+ metadata = json.loads(output_meta.read_text(encoding="utf-8"))
+ expected_source, _ = sanitize_extracted_text(
+ source.read_bytes().decode("utf-8")
+ )
+ assert "Policy text." in extracted
+ assert all(character not in extracted for character in INVISIBLE_CODEPOINTS)
+ assert metadata["chars"] == len(extracted)
+ assert metadata["sources"][0]["chars"] == len(expected_source)