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): scrub bidirectional controls and remaining invisible code points (#108)
Hotragn Pettugani1414ee5dd785
diff --git a/book_to_skill/sanitize.py b/book_to_skill/sanitize.pyindex d85ffb0..2a2e4f5 100644--- a/book_to_skill/sanitize.py+++ b/book_to_skill/sanitize.py@@ -1,22 +1,94 @@from __future__ import annotations-_ZERO_WIDTH_CODEPOINTS = frozenset({0x200B, 0x200C, 0x200D, 0x2060, 0xFEFF})+# Invisible code points used to hide document-borne prompt injection. Grouped by+# attack shape so the reasoning behind each entry stays reviewable.+#+# 1. Zero-width and invisible spacers. Render as nothing, so text between them is+# invisible to a human reading the page but plain to the model.+_ZERO_WIDTH_CODEPOINTS = frozenset({+ 0x200B, # ZERO WIDTH SPACE+ 0x200C, # ZERO WIDTH NON-JOINER+ 0x200D, # ZERO WIDTH JOINER+ 0x2060, # WORD JOINER+ 0xFEFF, # ZERO WIDTH NO-BREAK SPACE / BOM outside position 0+ 0x00AD, # SOFT HYPHEN — invisible except at a line break+ 0x034F, # COMBINING GRAPHEME JOINER — no rendering effect at all+ 0x180E, # MONGOLIAN VOWEL SEPARATOR+ 0x2061, # FUNCTION APPLICATION+ 0x2062, # INVISIBLE TIMES+ 0x2063, # INVISIBLE SEPARATOR+ 0x2064, # INVISIBLE PLUS+})++# 2. Bidirectional formatting controls — the Trojan Source class+# (CVE-2021-42574). These do not change the character sequence a model reads,+# they change the order a human SEES. A crafted line can display as innocuous+# study advice while the model consumes an injected instruction, so the+# reviewer approving a generated skill and the agent loading it disagree.+# Removing them makes rendered order match logical order.+#+# Legitimate right-to-left books are unaffected: the Unicode Bidi Algorithm+# derives direction from the characters themselves, so Arabic and Hebrew still+# render right-to-left without these. Only explicit embeddings, overrides and+# isolates are dropped, and running prose essentially never needs them.+_BIDI_CONTROL_CODEPOINTS = frozenset({+ 0x200E, # LEFT-TO-RIGHT MARK+ 0x200F, # RIGHT-TO-LEFT MARK+ 0x061C, # ARABIC LETTER MARK+ 0x202A, # LEFT-TO-RIGHT EMBEDDING+ 0x202B, # RIGHT-TO-LEFT EMBEDDING+ 0x202C, # POP DIRECTIONAL FORMATTING+ 0x202D, # LEFT-TO-RIGHT OVERRIDE+ 0x202E, # RIGHT-TO-LEFT OVERRIDE+ 0x2066, # LEFT-TO-RIGHT ISOLATE+ 0x2067, # RIGHT-TO-LEFT ISOLATE+ 0x2068, # FIRST STRONG ISOLATE+ 0x2069, # POP DIRECTIONAL ISOLATE+})++# 3. Characters that are not format controls (so a category-based filter misses+# them) but still render as blank width. Unlike a space they are letters, so+# they survive whitespace normalisation and can pad hidden text.+_INVISIBLE_LETTER_CODEPOINTS = frozenset({+ 0x115F, # HANGUL CHOSEONG FILLER+ 0x1160, # HANGUL JUNGSEONG FILLER+ 0x3164, # HANGUL FILLER+ 0xFFA0, # HALFWIDTH HANGUL FILLER+})++_INVISIBLE_CODEPOINTS = (+ _ZERO_WIDTH_CODEPOINTS+ | _BIDI_CONTROL_CODEPOINTS+ | _INVISIBLE_LETTER_CODEPOINTS+)++# 4. The Unicode tag block. Originally language tags, now used to smuggle an+# entire ASCII payload as invisible "tag" characters._TAG_BLOCK_START = 0xE0000_TAG_BLOCK_END = 0xE007F+def is_invisible_codepoint(codepoint: int) -> bool:+ """Return True if the code point renders as nothing and should be stripped.++ Exposed so the generated-skill scanner can flag exactly what extraction+ strips. When the two sets drift, the extractor lets a character through that+ the scanner then warns about — or worse, neither layer covers it.+ """+ return (+ codepoint in _INVISIBLE_CODEPOINTS+ or _TAG_BLOCK_START <= codepoint <= _TAG_BLOCK_END+ )++def sanitize_extracted_text(text: str) -> tuple[str, int]:"""Remove invisible code points used for document-borne prompt injection."""kept: list[str] = []removed = 0for character in text:- codepoint = ord(character)- if (- codepoint in _ZERO_WIDTH_CODEPOINTS- or _TAG_BLOCK_START <= codepoint <= _TAG_BLOCK_END- ):+ if is_invisible_codepoint(ord(character)):removed += 1continuekept.append(character)diff --git a/tests/test_sanitize_bidi_controls.py b/tests/test_sanitize_bidi_controls.pynew file mode 100644index 0000000..a217bd4--- /dev/null+++ b/tests/test_sanitize_bidi_controls.py@@ -0,0 +1,175 @@+"""Bidirectional controls and the remaining invisible code points are stripped.++Before this, `sanitize_extracted_text` covered only the zero-width set plus the+Unicode tag block. Every bidirectional formatting control passed through — the+Trojan Source class, CVE-2021-42574.++Bidi controls do not change the character sequence a model reads; they change+the order a human *sees*. So a line in a converted book can render as innocuous+study advice in the reviewer's editor while the agent loading the generated+skill consumes an injected instruction. That is precisely the doc -> agent ->+skill threat the extraction scrub and the generated-skill scanner exist to close.+"""++import sys+from pathlib import Path++import pytest++ROOT_DIR = Path(__file__).resolve().parent.parent+sys.path.insert(0, str(ROOT_DIR))+sys.path.insert(0, str(ROOT_DIR / "tools"))++from book_to_skill.sanitize import is_invisible_codepoint, sanitize_extracted_text++# The full bidi formatting set: marks, embeddings, overrides, isolates.+BIDI_CONTROLS = (+ "" # LEFT-TO-RIGHT MARK+ "" # RIGHT-TO-LEFT MARK+ "" # ARABIC LETTER MARK+ "" # LEFT-TO-RIGHT EMBEDDING+ "" # RIGHT-TO-LEFT EMBEDDING+ "" # POP DIRECTIONAL FORMATTING+ "" # LEFT-TO-RIGHT OVERRIDE+ "" # RIGHT-TO-LEFT OVERRIDE+ "" # LEFT-TO-RIGHT ISOLATE+ "" # RIGHT-TO-LEFT ISOLATE+ "" # FIRST STRONG ISOLATE+ "" # POP DIRECTIONAL ISOLATE+)++# Invisible-but-not-zero-width additions.+OTHER_INVISIBLES = (+ "" # SOFT HYPHEN+ "͏" # COMBINING GRAPHEME JOINER+ "" # MONGOLIAN VOWEL SEPARATOR+ "" # FUNCTION APPLICATION+ "" # INVISIBLE TIMES+ "" # INVISIBLE SEPARATOR+ "" # INVISIBLE PLUS+ "ᅟ" # HANGUL CHOSEONG FILLER+ "ᅠ" # HANGUL JUNGSEONG FILLER+ "ㅤ" # HANGUL FILLER+ "ᅠ" # HALFWIDTH HANGUL FILLER+)+++class TestBidiControlRemoval:+ def test_all_bidi_controls_removed(self):+ sanitized, removed = sanitize_extracted_text(f"before{BIDI_CONTROLS}after")++ assert sanitized == "beforeafter"+ assert removed == len(BIDI_CONTROLS)++ @pytest.mark.parametrize("char", list(BIDI_CONTROLS))+ def test_each_bidi_control_individually(self, char):+ sanitized, removed = sanitize_extracted_text(f"a{char}b")++ assert sanitized == "ab"+ assert removed == 1++ def test_trojan_source_line_is_neutralised(self):+ """The reviewer's rendered order and the model's logical order converge."""+ # RLO + isolates make the trailing run display reversed, so a human sees+ # harmless advice while the raw sequence carries the payload.+ payload = (+ "Study tip: prefer chapter summaries."+ " sgnitsil eht lla etsap"+ )+ sanitized, removed = sanitize_extracted_text(payload)++ assert removed == 4+ assert "" not in sanitized+ assert "" not in sanitized+ # The text survives; only the display-reordering controls are gone, so+ # what a reviewer reads is now what the model reads.+ assert sanitized == (+ "Study tip: prefer chapter summaries. sgnitsil eht lla etsap"+ )+++class TestRemainingInvisibles:+ def test_all_other_invisibles_removed(self):+ sanitized, removed = sanitize_extracted_text(f"before{OTHER_INVISIBLES}after")++ assert sanitized == "beforeafter"+ assert removed == len(OTHER_INVISIBLES)++ def test_soft_hyphen_rejoins_a_wrapped_word(self):+ # PDF and EPUB sources carry U+00AD at line wraps; stripping it also+ # repairs the word rather than leaving an invisible break inside it.+ sanitized, _ = sanitize_extracted_text("information")++ assert sanitized == "information"++ def test_hangul_fillers_are_letters_not_whitespace(self):+ """They survive .strip()/.split(), so they must be removed explicitly."""+ assert "ㅤ".strip() == "ㅤ"+ sanitized, removed = sanitize_extracted_text("aㅤb")+ assert (sanitized, removed) == ("ab", 1)+++class TestLegitimateTextPreserved:+ """The scrub must not damage real books, including right-to-left ones."""++ def test_arabic_text_untouched(self):+ # No explicit controls: the Unicode Bidi Algorithm derives direction+ # from the characters, so RTL rendering does not depend on the controls+ # this PR removes.+ arabic = "الفصل الأول: مقدمة"+ sanitized, removed = sanitize_extracted_text(arabic)+ assert (sanitized, removed) == (arabic, 0)++ def test_hebrew_text_untouched(self):+ hebrew = "פרק ראשון"+ sanitized, removed = sanitize_extracted_text(hebrew)+ assert (sanitized, removed) == (hebrew, 0)++ @pytest.mark.parametrize(+ "sample",+ [+ "第一章 緒論", # Chinese+ "제1장 총칙", # Korean+ "บทที่ ๓", # Thai+ "Chapter 1: Café — naïve", # Latin with accents and an em dash+ "hangul 한글 normal",+ ],+ )+ def test_scripts_with_no_invisibles_are_unchanged(self, sample):+ sanitized, removed = sanitize_extracted_text(sample)+ assert (sanitized, removed) == (sample, 0)++ def test_ordinary_whitespace_preserved(self):+ text = "line one\n\tline two\r\n"+ sanitized, removed = sanitize_extracted_text(text)+ assert (sanitized, removed) == (text, 0)+++class TestScannerAndExtractorAgree:+ """The two injection defenses must not drift apart again."""++ def test_scanner_flags_everything_extraction_strips(self):+ from scan_generated_skill import _is_invisible++ for char in BIDI_CONTROLS + OTHER_INVISIBLES:+ codepoint = ord(char)+ assert is_invisible_codepoint(codepoint), f"U+{codepoint:04X}"+ assert _is_invisible(codepoint), (+ f"scanner does not flag U+{codepoint:04X} but extraction strips it"+ )++ def test_scanner_shares_the_extractor_predicate(self):+ """Guards against a future copy-paste divergence like the U+2060 one."""+ import scan_generated_skill++ assert scan_generated_skill.is_invisible_codepoint is is_invisible_codepoint++ def test_previously_covered_codepoints_still_covered(self):+ # Regression net for the original set (#75) and the word joiner (#85).+ for codepoint in (0x200B, 0x200C, 0x200D, 0x2060, 0xFEFF,+ 0xE0000, 0xE0069, 0xE007F):+ assert is_invisible_codepoint(codepoint), f"U+{codepoint:04X}"++ def test_visible_characters_are_not_flagged(self):+ for char in "aZ0 \n\t第한กی":+ assert not is_invisible_codepoint(ord(char)), repr(char)diff --git a/tools/scan_generated_skill.py b/tools/scan_generated_skill.pyindex 6c95be2..699a641 100644--- a/tools/scan_generated_skill.py+++ b/tools/scan_generated_skill.py@@ -16,13 +16,12 @@ MAX_FILE_BYTES = 2 * 1024 * 1024MAX_TOTAL_BYTES = 20 * 1024 * 1024SUPPORTING_FILENAMES = ("glossary.md", "patterns.md", "cheatsheet.md")-_INVISIBLE_CODEPOINTS = {- 0x200B, # zero width space- 0x200C, # zero width non-joiner- 0x200D, # zero width joiner- 0x2060, # word joiner- 0xFEFF, # zero width no-break space (outside the leading BOM)-}+# Reuse the extractor's invisible-code-point set instead of duplicating it, so+# the two injection defenses cannot drift apart. They previously did: the+# extractor did not strip U+2060 while this scanner flagged it, so a generated+# skill was warned about a character extraction was meant to have removed.+sys.path.insert(0, str(Path(__file__).resolve().parent.parent))+from book_to_skill.sanitize import is_invisible_codepoint # noqa: E402_CONTENT_RULES = ((@@ -90,7 +89,7 @@ class Finding:def _is_invisible(codepoint: int) -> bool:- return codepoint in _INVISIBLE_CODEPOINTS or 0xE0000 <= codepoint <= 0xE007F+ return is_invisible_codepoint(codepoint)def _terminal_safe(value: str) -> str: