agent-sanitizer 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2026 Alexander Turner
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,217 @@
1
+ # `agent-sanitizer`
2
+
3
+ Most prompt-injection tools run a classifier _over_ the text and hope it
4
+ generalizes. This library targets a narrower, verifiable claim: the
5
+ specific byte-level channels—invisible Unicode, ANSI escapes, human-hidden
6
+ HTML, confusable glyphs, exfil-shaped URLs—that let an attacker smuggle a
7
+ payload the operator can't see but the model still reads. Every layer is a
8
+ deterministic transform you can unit-test with equality assertions.
9
+
10
+ ```sh
11
+ npm install agent-sanitizer
12
+ ```
13
+
14
+ ## Quick start
15
+
16
+ ```js
17
+ import { sanitize } from "agent-sanitizer";
18
+
19
+ // Layer 1 (invisible chars + ANSI), zero heavy deps:
20
+ const { cleaned, found, warnings } = await sanitize(untrustedText);
21
+
22
+ // Opt into the HTML layers for web ingress (lazy-loads ~200 ms of deps):
23
+ const result = await sanitize(pageSource, { html: true });
24
+ ```
25
+
26
+ `sanitize` never throws and never silently drops content—any change comes with
27
+ at least one `warnings` entry. `found` names the neutralized category codes
28
+ (e.g. `["cf-format", "hidden-html"]`); `cleaned` is the safe text, with
29
+ placeholders where hidden HTML was spliced out.
30
+
31
+ ## Entry points
32
+
33
+ Split into subpaths so the heavy HTML dependency stays opt-in. The **seam**
34
+ column marks entry points that inject the agent-specific concern (a callback
35
+ you supply) rather than baking it in; `—` means the function is a pure
36
+ transform with no such hook, and `fs (direct)` means it does its own file I/O
37
+ (Node's filesystem, not an agent harness) instead of taking a callback.
38
+
39
+ | # | Import | Purpose | Seam |
40
+ | --- | --------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------- |
41
+ | 1 | `/invisible` | Strip zero-width, bidi, variation-selector and tag chars + ANSI/SGR escapes. Preserves ZWNJ/ZWJ for Arabic/Indic/emoji. Zero deps. | — |
42
+ | 2 | `/html` | Splice out instructions hidden in comments, `display:none`, off-screen, white-on-white, `hidden`. Leaves a placeholder. | — |
43
+ | 3 | `/html` | Detect exfil-shaped URLs (payloads in query/path, embedded creds, `data:`/`javascript:`, off-origin redirects). Reports only. | — |
44
+ | 4 | `/confusables` | Fold look-alike glyphs in tool-call input (paths, commands) to ASCII, closing a cross-script deny-rule bypass. | `scan` |
45
+ | 5 | `/instructions` | Scan/auto-clean `CLAUDE.md`, `AGENTS.md`, `SKILL.md`, etc., decoding Unicode-tag + zero-width-binary payloads. | `fs` (direct) |
46
+ | 6 | `/prompt` | Classify a prompt pass / SGR-note / block on payload-capable invisible/ANSI content. | — |
47
+ | 7 | `/output` | Run Layers 1–4 over structured tool output, preserving shape. The Layer-5 slot takes a delete-only filter. | `redact`, `filterInjection` |
48
+ | 8 | `/rehydrate` | Re-anchor a model Edit composed from the _sanitized_ view back onto real bytes; deny anything ambiguous or secret-exposing. | `io` |
49
+ | — | `/view-map` | Pure offset/text machinery mapping a file's on-disk bytes ↔ the sanitized view (Layer-1 deletions, Layer-4 redactions). No I/O — consumed by `/rehydrate`. | — |
50
+
51
+ See [`THREAT-MODEL.md`](./THREAT-MODEL.md) for per-vector detail.
52
+
53
+ ### `found` codes
54
+
55
+ `found` (from `sanitize`/`stripInvisibleWithReport`) is a stable, machine-readable
56
+ contract—branch on these codes, not on `warnings` prose, which can be reworded
57
+ without notice.
58
+
59
+ | Code | Meaning |
60
+ | --------------------- | ------------------------------------------------------------------------------------------------------- |
61
+ | `cf-format` | Unicode format chars (`Cf`): zero-width space/joiner, bidi overrides, tag chars |
62
+ | `variation-selectors` | Variation selectors (U+FE00–FE0F, U+E0100–E01EF) |
63
+ | `blank-fillers` | Blank-rendering fillers not covered by `Cf` (Hangul fillers, Braille blank, zero-width combining marks) |
64
+ | `ansi` | ANSI/SGR escapes and other terminal control sequences |
65
+ | `lone-surrogates` | Unpaired UTF-16 surrogates |
66
+ | `html-comments` | HTML comments spliced out by Layer 2 |
67
+ | `hidden-html` | Elements hidden via CSS/attribute (`display:none`, `hidden`, etc.) spliced out by Layer 2 |
68
+ | `exfil-urls` | Exfil-shaped URLs detected by Layer 3 (reported, not removed) |
69
+
70
+ ### `FILTER_WARNING` codes (Layer 5)
71
+
72
+ The Layer-5 `filterInjection` seam is deliberately thin: the injected filter may
73
+ only ask for **verbatim span deletions** (`removeSpans`) and may only warn with a
74
+ **closed enum code** (`warning`), never free text. Because the filter runs on
75
+ attacker-influenced content and its `warning` would otherwise be concatenated
76
+ straight into the model-facing context **without** re-passing Layer 1, a
77
+ compromised or prompt-injected filter emitting arbitrary text would defeat the
78
+ "a compromised filter can only remove bytes, never inject" contract. So the
79
+ **library owns the message** for each code, and a filter returning any value
80
+ outside this enum makes `sanitizeText` **throw** (fail loud). Branch on the code,
81
+ like `found`:
82
+
83
+ | `FILTER_WARNING` code | Meaning |
84
+ | --------------------- | --------------------------------------------------------------------------------------- |
85
+ | `spans-removed` | The filter removed one or more verbatim spans it flagged as prompt injection |
86
+ | `filter-flagged` | The filter flagged the output as a possible injection without deleting (content intact) |
87
+ | `filter-error` | The filter reported a non-fatal internal error while scanning (a fatal filter throws) |
88
+
89
+ ## How this compares
90
+
91
+ The "sanitize untrusted LLM input" space mostly splits into two camps: ML
92
+ classifiers that score a prompt's _intent_ (Lakera Guard, Meta's Prompt
93
+ Guard, Rebuff, NeMo Guardrails' input rails), and PII-focused redactors
94
+ (Microsoft Presidio). Neither targets the byte-level hiding channel this
95
+ library covers, and that gap is exactly where invisible-Unicode and
96
+ hidden-HTML payloads live—content a semantic classifier never "sees" as
97
+ suspicious because it renders as blank space or doesn't render at all.
98
+
99
+ | | `agent-sanitizer` | Semantic guard/classifier (Lakera, Prompt Guard, Rebuff, NeMo rails) | PII redactor (Presidio) |
100
+ | ----------------------------- | ------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------ |
101
+ | **What it catches** | Payload-capable invisible chars, ANSI/SGR, hidden HTML, confusable glyphs, exfil-shaped URLs | Malicious _intent_—jailbreaks, injected instructions, off-topic asks | Names, emails, SSNs, and other PII spans |
102
+ | **How it decides** | Deterministic parsing/regex over real tokenizer output—no model call | ML/LLM classification—probabilistic, needs a threshold and retuning as attacks shift | NER + pattern matching |
103
+ | **Failure mode** | Fails open on ambiguous input (see [`THREAT-MODEL.md`](./THREAT-MODEL.md)); false negative over false positive by design | False positives silently mangle or block legitimate prompts; false negatives are invisible until exploited | Under/over-redaction depending on locale and entity coverage |
104
+ | **Latency / infra** | Pure JS, mostly zero-dep (`/html` lazy-loads ~200 ms once) | Network round-trip to a hosted model, or a local model to host yourself | Local, but heavier NLP pipeline |
105
+ | **Determinism / testability** | Exact-equality unit tests, no flakiness across runs | Same input can classify differently across model versions | Deterministic per rule, but rule coverage varies |
106
+ | **Reversibility** | `/rehydrate` re-anchors a model's edit from the sanitized view back onto real bytes, denying anything ambiguous | N/A—classifiers only pass/block, they don't rewrite-and-reverse | N/A |
107
+ | **Non-JS support** | Same verdicts via a bundled CLI/worker—Python client included, no reimplementation | Usually a hosted API (language-agnostic) or Python-only SDK | Python-first (spaCy-based) |
108
+
109
+ In practice these are complementary, not competing: run a semantic guard for
110
+ intent, Presidio for PII you must not leak, and this library for the hidden
111
+ channel both of those are blind to. If you already run a classifier and are
112
+ still getting bitten by zero-width payloads or `display:none` instructions
113
+ riding along in RAG context, that's the gap this library closes.
114
+
115
+ ### Examples
116
+
117
+ ```js
118
+ import { stripInvisibleWithReport } from "agent-sanitizer/invisible";
119
+ const { cleaned, found } = stripInvisibleWithReport(text); // found: ["variation-selectors"]
120
+
121
+ import { sanitizeHtml, detectExfil, checkExfilUrl } from "agent-sanitizer/html";
122
+ sanitizeHtml(pageSource); // { text, removed, warned } | null — text may be unchanged if only reportable (not strippable) tags were found
123
+ detectExfil(pageSource); // [{ isImage, reason, target }] or null
124
+ checkExfilUrl(oneUrl); // reason string or null
125
+ ```
126
+
127
+ The agent-pipeline entry points take plain arguments and inject their
128
+ agent-specific seam:
129
+
130
+ ```js
131
+ import { normalizeConfusables } from "agent-sanitizer/confusables";
132
+ normalizeConfusables(
133
+ "Bash",
134
+ { command: "/аpt update" },
135
+ { scan: (t) => myHomoglyphEngine.scan(t) }, // -> { findings: [{ index, char, latinEquivalent }] }
136
+ ); // null, or { updatedInput, normalized }
137
+
138
+ import { scanInstructionFiles, cleanFile } from "agent-sanitizer/instructions";
139
+ const findings = scanInstructionFiles(["CLAUDE.md", "**/SKILL.md"], {
140
+ cwd: projectDir,
141
+ });
142
+ for (const { file } of findings) cleanFile(`${projectDir}/${file}`);
143
+
144
+ import { classifyPrompt } from "agent-sanitizer/prompt";
145
+ classifyPrompt(submittedPrompt); // { action: "pass" | "note" | "block", reason? }
146
+
147
+ import { sanitizeText } from "agent-sanitizer/output";
148
+ await sanitizeText(toolText, {
149
+ html: isWebPage,
150
+ exfilScan: isUntrustedIngress,
151
+ redact: async (t) => myRedactor.redact(t), // -> { text, found, note? } | null
152
+ filterInjection: (t) => mySemanticFilter(t), // -> { removeSpans, warning } | null
153
+ // removeSpans: verbatim spans to delete (delete-only — never replacement text)
154
+ // warning: a FILTER_WARNING enum CODE, never free text (see below)
155
+ });
156
+
157
+ import { rehydrateRedacted } from "agent-sanitizer/rehydrate";
158
+ await rehydrateRedacted("Edit", toolInput, {
159
+ readFile: (p) => fs.readFileSync(p, "utf8"),
160
+ redactMap: (t) => myRedactor.map(t), // -> { text, pairs } | { unmappable }
161
+ redact: (t) => myRedactor.redact(t), // -> string | null
162
+ }); // { updatedInput, context } | { deny } | null — a deny never exposes a secret
163
+ ```
164
+
165
+ ## Limits
166
+
167
+ The CLI (and the worker that backs the Python client) rejects any single request
168
+ larger than `AGENT_SANITIZER_MAX_INPUT_BYTES` UTF-8 bytes — **default 10 MiB** —
169
+ with a structured error instead of buffering an unbounded payload. Raise or lower
170
+ it by setting that environment variable in the calling process.
171
+
172
+ ## Security
173
+
174
+ Found a vulnerability? See [`SECURITY.md`](./SECURITY.md) for the private
175
+ disclosure channel — it ships in the npm tarball, so it is also available offline
176
+ from an installed copy. [`THREAT-MODEL.md`](./THREAT-MODEL.md) covers what each
177
+ layer does and does not defend against.
178
+
179
+ ## Non-JS pipelines (Python, etc.)
180
+
181
+ The JS is the **single source of truth**—non-JS callers drive the same verdicts
182
+ through the bundled CLI, so there’s
183
+ no second implementation to drift. An `op` field selects the entry point
184
+ (default `sanitize`); the self-contained ones—`sanitizeText`, `classifyPrompt`,
185
+ `scanInstructionFiles`, `cleanFile`—are all bridged. Entry points with an
186
+ injected JS callback have no wire form and stay JS-only. The bridged
187
+ `sanitizeText` runs Layers 1–3 only (invisible/ANSI strip, HTML hidden-content
188
+ splice, exfil detection): it never redacts secrets (Layer 4) or runs injection
189
+ filtering (Layer 5), and the wire protocol's `sgrNote` (Python's
190
+ `TextResult.sgr_note`) is always `false`, since the bridge never wires
191
+ `sgrCarveOut`.
192
+
193
+ ```sh
194
+ echo '{"text":"a​b"}' | npx sanitize-cli # default op: sanitize
195
+ echo '{"op":"classifyPrompt","text":"…"}' | npx sanitize-cli
196
+ sanitize-cli --worker # newline-delimited, one response/line
197
+ ```
198
+
199
+ The [`python/`](./python) client wraps every bridged op (`sanitize`,
200
+ `sanitize_text`, `classify_prompt`, `scan_instruction_files`, `clean_file`). The
201
+ wheel ships a self-contained, single-file build of the CLI (`src/` and its npm
202
+ dependencies bundled into one `.mjs` at release time), so a `pip install` plus
203
+ Node.js (>=22) on `PATH` works with no separate JavaScript checkout to clone.
204
+ `AGENT_SANITIZER_CLI` is only an override escape hatch (e.g. to point at a
205
+ custom/dev build)—a normal install never needs to set it. The first
206
+ `html=True` call starts a shared worker, so the ~200 ms HTML module-load is
207
+ paid **once per process**; Layer-1 calls stay one-shot. `persist=True/False`
208
+ forces the mode and `shutdown_worker()` (also an `atexit` hook) stops it.
209
+
210
+ ```python
211
+ from agent_sanitizer import sanitize, Sanitizer
212
+
213
+ sanitize(untrusted_text) # Layer 1, one-shot
214
+ sanitize(page_source, html=True) # HTML layers, warm worker reused
215
+ with Sanitizer() as s: # own the worker’s lifetime
216
+ s.sanitize(page, html=True)
217
+ ```
package/SECURITY.md ADDED
@@ -0,0 +1,31 @@
1
+ # Security Policy
2
+
3
+ `agent-sanitizer` is a security library: it sits between untrusted text
4
+ and a model, so a vulnerability here can defeat the very protection a downstream
5
+ pipeline is relying on. Please treat reports accordingly.
6
+
7
+ ## Reporting a vulnerability
8
+
9
+ **Do not open a public GitHub issue for a security vulnerability.** A public
10
+ report tips off attackers before downstream users can update.
11
+
12
+ Instead, report privately through one of:
13
+
14
+ - GitHub's [private vulnerability reporting](https://github.com/AlexanderMattTurner/agent-sanitizer/security/advisories/new)
15
+ ("Report a vulnerability" under the **Security** tab), or
16
+ - email the maintainer at `security@turntrout.com`.
17
+
18
+ Please include enough to reproduce: the input that triggers it, the entry point
19
+ (`/invisible`, `/html`, `/confusables`, `/rehydrate`, etc.), what the sanitizer
20
+ did versus what it should have done, and the package version.
21
+
22
+ A bypass that lets payload-capable content reach the model unflagged, a splice
23
+ that exposes a secret, or a crash on adversarial input are all in scope. Please
24
+ don't include real credentials in a report—a credential-shaped placeholder is
25
+ enough.
26
+
27
+ ## What to expect
28
+
29
+ The maintainer will acknowledge your report and work with you on a fix and a
30
+ coordinated disclosure timeline before any public detail is published. Fixes
31
+ ship in a patched release with the advisory.
@@ -0,0 +1,173 @@
1
+ # Threat model
2
+
3
+ `agent-sanitizer` defends the boundary where untrusted text enters an
4
+ agent-driven pipeline (agent tool output, RAG retrieval, fetched web pages). It is
5
+ a detect/neutralize layer, not an enforcement boundary: it makes hidden content
6
+ visible-or-gone and surfaces exfil-shaped URLs, so the model and the operator
7
+ see the same thing. Egress controls remain your enforcement layer.
8
+
9
+ The three layers are independent; use only the ones your ingress needs.
10
+
11
+ ## Layer 1—invisible characters & ANSI (zero-dependency)
12
+
13
+ **What it removes**
14
+
15
+ | Category | Examples | Why it’s a payload channel |
16
+ | -------------------------- | -------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------- |
17
+ | Format chars (`Cf`) | zero-width space/joiner, bidi overrides, Unicode **tag** chars | render blank but reach the model as bytes; tags smuggle ASCII |
18
+ | Variation selectors | U+FE00–FE0F, U+E0100–E01EF | not `Cf`; a run encodes a hidden payload |
19
+ | Blank-rendering fillers | Hangul fillers U+115F/1160/3164/FFA0, Braille blank U+2800, zero-width combining marks (`Mn`) U+034F/17B4/17B5 | render blank, not `Cf`, so a naive `\p{Cf}` strip misses them |
20
+ | Soft hyphen / interior BOM | U+00AD, interior U+FEFF | either can encode hidden instructions |
21
+ | ANSI / SGR escapes | `ESC[…m`, cursor moves, OSC | repaint or hide what an operator reads in a terminal |
22
+
23
+ **What it preserves**
24
+
25
+ - A **single leading BOM** (a legitimate marker); interior BOMs are stripped.
26
+ - **ZWNJ (U+200C) / ZWJ (U+200D)** in genuine linguistic context: between two
27
+ letters of a script whose orthography requires them (Arabic, Devanagari,
28
+ Bengali, Gurmukhi, Gujarati, Oriya, Tamil, Telugu, Kannada, Malayalam,
29
+ Sinhala) or inside an emoji ZWJ sequence. The carve-out fires only when **both**
30
+ neighbors clearly belong to the context, and it is disabled once the total
31
+ invisible count crosses a scatter floor—over-stripping beats under-stripping.
32
+
33
+ **Reassembly hardening.** Stripping an invisible char can reconstitute an ANSI
34
+ escape its split had hidden, and removing one ANSI sequence can reconstitute
35
+ another. Layer 1 strips ANSI to a fixed point and then sweeps any residual raw
36
+ control introducer—7-bit ESC (U+001B) or 8-bit C1 CSI (U+009B)—outright, so the
37
+ result carries no raw ANSI introducer for _any_ input and the operation is
38
+ idempotent. OSC strings (titles, clickable-hyperlink URLs) are consumed as a
39
+ whole, for every terminator form—ST (`ESC\` or 8-bit C1 ST U+009C) and the
40
+ legacy BEL—and for the 8-bit C1 OSC introducer (U+009D); an _unterminated_ OSC
41
+ introducer is dropped through end-of-string (fail-closed), so no OSC body
42
+ survives to carry a payload.
43
+
44
+ ## Layer 2—hidden HTML (remark/rehype)
45
+
46
+ For web/HTML ingress, splice out exactly what a human viewing the rendered page
47
+ cannot see:
48
+
49
+ - `<!-- HTML comments -->`
50
+ - elements hidden by inline style: `display:none`, `visibility:hidden`,
51
+ `content-visibility:hidden`, `opacity:0`, `filter:opacity(0)`, off-screen
52
+ positioning, zero/negative sizes, `text-indent` off-screen, collapsing
53
+ `clip`/`clip-path`/`transform:scale(0)`, white-on-white / transparent text,
54
+ `overflow:hidden` with a zero dimension
55
+ - elements hidden by attribute: `hidden`, `aria-hidden="true"`
56
+
57
+ Spliced ranges are replaced with a placeholder; **every byte outside a spliced
58
+ range is preserved verbatim** (no re-serialization). Unclosed hidden markup
59
+ extends to the end of the fragment—fail-closed for truncated input.
60
+
61
+ Scripting/resource tags (`script`, `style`, `object`, `embed`, `iframe`, `svg`,
62
+ `math`) and `data:` URI resources are **reported, not removed**: their bodies are
63
+ page source the model may legitimately need to inspect.
64
+
65
+ ## Layer 3—exfil URLs (detection only)
66
+
67
+ Report—never rewrite—URLs in markdown links/images/definitions and HTML
68
+ attributes (`src`/`href`/`background`/`srcset`/`ping`, form `action`/`formaction`,
69
+ `meta refresh`) that are shaped to carry data off-origin:
70
+
71
+ - suspicious query/fragment parameters (long base64/hex blobs, credential-shaped
72
+ tokens), tuned to skip request-signing / pagination / analytics parameters
73
+ that are legitimately long (`X-Amz-*`, SAS, `cursor`, `utm_*`, `gclid`, …)
74
+ - oversized or active-content (`text/html`, `image/svg+xml`, JS) `data:` URIs
75
+ - embedded `user:password@host` credentials
76
+ - unusually long query strings or fragments
77
+ - encoded-data blobs smuggled in a path segment (a beacon that avoids the query)
78
+ - off-origin form actions and `meta refresh` redirects
79
+ - `javascript:` / `vbscript:` targets
80
+
81
+ Each threat carries a `reason` and the destination `target` (never the
82
+ payload-bearing query/fragment), suitable for a warning shown to the operator.
83
+
84
+ ## Confusable folding (tool input)
85
+
86
+ `./confusables` folds look-alike glyphs in tool-call **input** fields (paths,
87
+ commands) to their ASCII canon. A denied path/command spelled in homoglyphs (a
88
+ Cyrillic `а` for ASCII `a`) would not match an ASCII deny rule; folding closes
89
+ that cross-script bypass (CVE-2025-54794 class). Folding is per-character and
90
+ context-free, so it also catches an **isolated** confusable with no ASCII anchor
91
+ that a context-sensitive canonicaliser would leave alone. The homoglyph engine
92
+ is **injected** (`{ scan }`)—the package owns no glyph map. An all-ASCII field
93
+ never invokes the scanner. This narrows a steganographic channel; it is not an
94
+ enforcement boundary (distinct code points would not match a deny rule anyway).
95
+
96
+ ## Instruction-file scanning
97
+
98
+ `./instructions` scans the markdown that loads as model context (`CLAUDE.md`,
99
+ `AGENTS.md`, `SKILL.md`, any `.claude` markdown—a **caller-supplied glob
100
+ set**), which bypasses a tool-output sanitizer entirely. It flags long invisible
101
+ runs, decodes the two common smuggling encodings (Unicode **tag** characters →
102
+ ASCII, zero-width **binary**), and catches scattered payloads below the long-run
103
+ threshold. `cleanFile` strips the payload in place (Layer-1 strip), failing loud
104
+ if a contaminated file cannot be rewritten.
105
+
106
+ ## User-prompt verdict
107
+
108
+ `./prompt` classifies a submitted prompt as **pass / pass-with-note / block** on
109
+ payload-capable invisible Unicode and ANSI. A prompt-submission channel usually
110
+ cannot rewrite the prompt in place, so the only neutralization is to block.
111
+ One carve-out: a prompt whose only escape content is display-only SGR color
112
+ passes with a note (pasting colored terminal output is the common case, and SGR
113
+ cannot move the cursor, erase, or carry an OSC payload). The SGR-only test
114
+ gates on both the 7-bit ESC (`U+001B`) introducer and the whole 8-bit C1
115
+ control block (U+0080–U+009F)—not just the CSI byte (`U+009B`)—so a
116
+ C1-introduced cursor-move, erase, or OSC/DCS/SOS/PM/APC string is never
117
+ mistaken for benign color.
118
+
119
+ ## Tool-output pipeline & Layer 5
120
+
121
+ `./output` runs Layers 1–4 over structured tool output, **preserving its shape**
122
+ (a harness that gets a shape-mismatched value silently shows the raw output).
123
+ Layer 4 (secret redaction) is an **injected** redactor and is the one
124
+ fail-closed path: a redactor that throws makes the pipeline rethrow, so the
125
+ caller suppresses the output rather than emit an unvetted value. Layer 5 is a
126
+ deliberately thin, safe slot: the injected filter returns **verbatim spans to
127
+ delete** (never replacement text), so even a compromised filter can only remove
128
+ legitimate content—it can never inject bytes into the model’s view. A live
129
+ second-LLM injection filter is the caller’s to wire behind that contract.
130
+
131
+ The same "never inject" property governs the filter’s `warning`: it is a
132
+ **closed enum code** (`FILTER_WARNING`: `spans-removed` / `filter-flagged` /
133
+ `filter-error`), and the **library**—not the filter—owns the human-readable
134
+ string each code maps into `warnings`. This closes a seam the delete-only span
135
+ contract left open: `warnings` is concatenated into the model-facing context
136
+ **without** re-running Layer 1, so a compromised or prompt-injected filter that
137
+ could return free-text `warning` would smuggle attacker bytes straight to the
138
+ model. A filter that returns any value outside the enum makes the pipeline
139
+ **throw** (fail loud), exactly as an unrunnable Layer-4 redactor does—no
140
+ filter-supplied byte (span or warning) ever reaches the model’s view.
141
+
142
+ ## Edit-repair / rehydration
143
+
144
+ Sanitizing the model’s view of a file makes that view diverge from disk: Layer 1
145
+ deletes invisible/ANSI runs, and Layer 4 replaces secrets with `[REDACTED…]`
146
+ placeholders. An Edit whose `old_string` was copied from that view then fails
147
+ exact-match, and a whole-file Write would persist the placeholder over the real
148
+ secret—so a sanitizer _without_ rehydration silently breaks editing.
149
+ `./rehydrate` (offset machinery in `./view-map`) re-derives the sanitized view,
150
+ locates the model’s `old_string` in it, and maps it span-exact back to the
151
+ on-disk bytes across both placeholder expansion and stripped invisible runs,
152
+ substituting placeholders in `new_string` with the real secrets. Two invariants
153
+ are load-bearing and **fail closed**:
154
+
155
+ - **Never mis-anchor.** Greedy deletion alignment is ambiguous when a stripped
156
+ run abuts kept text it resembles; any call that does not re-clean back to the
157
+ span’s view, matches multiple view locations, or cuts through a placeholder is
158
+ **denied** with an instructive reason rather than edited at a guessed anchor.
159
+ - **Never expose a secret this call rehydrated.** Before rewriting, the
160
+ would-be post-edit content is re-sanitized (Layer 1 + the injected
161
+ redactor); if any secret THIS EDIT resolved from a placeholder would survive
162
+ in the model’s next view (e.g. an edit whose `old_string`/`new_string`
163
+ carries a placeholder and relabels a field the redactor no longer
164
+ recognizes), the call is **denied**. This check only runs when the edit
165
+ touches a placeholder — a relabel that never names one (e.g. `password=` →
166
+ `notes=` with no `[REDACTED…]` in either string) is an accepted scope gap,
167
+ not covered here: simulating full-file exposure on every relabel-adjacent
168
+ edit would re-run redaction on every `Edit` call and risk false denials on a
169
+ legitimate relabel in a large file. The secret flows disk → tool input only;
170
+ the model’s next view is sanitized again.
171
+
172
+ File access and the redactor are injected via `io`; the package performs no I/O
173
+ of its own and bundles no secret engine.