Skip to content

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

fix(text): reject malformed BOM-encoded input (#292)

Stamina9a5534cbb97d2
diff --git a/book_to_skill/parsers/text.py b/book_to_skill/parsers/text.py
index 4055c5a..f015bb1 100644
--- a/book_to_skill/parsers/text.py
+++ b/book_to_skill/parsers/text.py
@@ -27,9 +27,12 @@ def read_text_file(path: str) -> str | None:
try:
return data.decode(encoding)
except (UnicodeDecodeError, LookupError):
- break
+ # The BOM is an explicit encoding declaration. Trying cp1252 or
+ # latin-1 here would silently accept damaged data as mojibake.
+ print(f" [warn] read_text_file: invalid {encoding} data after BOM", file=sys.stderr)
+ return None
- # No (usable) BOM: fall back to the prior chain for BOM-less files.
+ # No BOM: fall back to the prior chain for BOM-less files.
for encoding in ("utf-8", "cp1252", "latin-1"):
try:
return data.decode(encoding)
diff --git a/tests/test_malformed_text_bom.py b/tests/test_malformed_text_bom.py
new file mode 100644
index 0000000..8cf8e1f
--- /dev/null
+++ b/tests/test_malformed_text_bom.py
@@ -0,0 +1,32 @@
+"""Regression coverage for malformed BOM-encoded text documents."""
+
+from pathlib import Path
+
+import pytest
+
+import book_to_skill.utils as utils
+from book_to_skill.exceptions import ExtractionError
+from book_to_skill.parsers.text import read_text_file
+
+
+ "raw",
+ [
+ b"\xef\xbb\xbf\xff", # invalid UTF-8 after its BOM
+ b"\xff\xfeA", # truncated UTF-16 LE code unit
+ b"\xfe\xffA", # truncated UTF-16 BE code unit
+ b"\xff\xfe\x00\x00A", # truncated UTF-32 LE code unit
+ b"\x00\x00\xfe\xffA", # truncated UTF-32 BE code unit
+ ],
+)
+def test_malformed_bom_does_not_fall_back_to_legacy_encoding(tmp_path: Path, raw: bytes) -> None:
+ path = tmp_path / "book.txt"
+ path.write_bytes(raw)
+ assert read_text_file(str(path)) is None
+
+
+def test_malformed_bom_is_rejected_by_text_extractor(tmp_path: Path) -> None:
+ path = tmp_path / "book.txt"
+ path.write_bytes(b"\xff\xfeA")
+ with pytest.raises(ExtractionError, match="Could not read text document"):
+ utils.extract_single_file(path, "text", "no")