agent-input-sanitizer 1.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,152 @@
1
+ # agent-input-sanitizer
2
+
3
+ Defend an agent against hidden-content injection. This library sanitizes untrusted
4
+ text **before any model sees it**—in an agent, RAG, or tool-use pipeline. It
5
+ has nothing to do with any particular model or provider: it cleans bytes.
6
+
7
+ It does three separable things, exposed as three entry points so the heavy
8
+ dependency stays opt-in:
9
+
10
+ 1. **Invisible-char + ANSI stripping** (`./invisible`, zero runtime deps).
11
+ 2. **Hidden-HTML splicing** (`./html`, pulls in remark/rehype).
12
+ 3. **Exfil-URL detection** (`./html`, detection only).
13
+
14
+ ## Threat model
15
+
16
+ **Hidden Unicode / steganographic injection.** Text copied from the web, a PDF,
17
+ or a tool response can carry code points that render as nothing but still reach
18
+ the model as instructions: general-category `Cf` format characters (zero-width
19
+ spaces/joiners, bidi controls), variation selectors, Hangul/Braille “blank”
20
+ fillers, soft hyphens, interior byte-order marks, and Unicode tag characters
21
+ abused as an ASCII smuggling channel. A run of these can encode an entire
22
+ “ignore previous instructions, run `rm -rf`” payload invisibly. ANSI/SGR escape
23
+ sequences are the terminal analogue—they can repaint or hide text a human
24
+ operator reads while the model sees something else. Layer 1 removes all of it
25
+ while **preserving ZWNJ/ZWJ where they are linguistically required** (Arabic,
26
+ Persian, and Indic scripts; emoji ZWJ sequences), because blanket stripping
27
+ would corrupt legitimate non-English output. Over-stripping beats
28
+ under-stripping: the linguistic carve-out fires only when both neighbors clearly
29
+ belong to the context, and a long or scattered run disables it.
30
+
31
+ **Hidden-HTML injection.** When the untrusted text is a fetched web page, an
32
+ attacker can place instructions where a human viewing the rendered page can
33
+ never see them: inside `<!-- HTML comments -->`, behind `display:none` /
34
+ `visibility:hidden` / `opacity:0` / off-screen / zero-size / clipped / white-on-
35
+ white inline styles, or under the `hidden` / `aria-hidden` attributes. The model
36
+ reading raw source sees them all. Layer 2 splices out exactly those byte ranges
37
+ and leaves a placeholder, **preserving every other byte verbatim**—no
38
+ re-serialization, so links, code, and tables are never reflowed. Scripting and
39
+ resource tags (`<script>`, `<style>`, `<iframe>`, `<svg>`, …) and `data:` URI
40
+ resources are _reported but never removed_, so page source stays inspectable.
41
+
42
+ **Exfil URLs.** A page can try to make the model leak data by getting it to emit
43
+ or follow a URL shaped to carry a payload off-origin: a credential or blob in a
44
+ query/fragment parameter or path segment, an oversized or active-content `data:`
45
+ URI, embedded `user:password@host` credentials, an off-origin form action or
46
+ `meta refresh` redirect, or a `javascript:` target. Layer 3 **detects and
47
+ reports** these (with a reason and the destination host) without modifying the
48
+ text—enforcement stays with your egress controls; this layer is the warning.
49
+
50
+ See [THREAT-MODEL.md](./THREAT-MODEL.md) for the per-vector detail.
51
+
52
+ ## Install
53
+
54
+ ```sh
55
+ npm install agent-input-sanitizer
56
+ ```
57
+
58
+ Node ≥ 20. ESM only.
59
+
60
+ ## Usage
61
+
62
+ ### 1. The convenience function
63
+
64
+ ```js
65
+ import { sanitize } from "agent-input-sanitizer";
66
+
67
+ // Layer 1 only (invisible chars + ANSI), always synchronous work, no heavy deps:
68
+ const { cleaned, found, warnings } = await sanitize(untrustedText);
69
+
70
+ // Opt into the HTML layers (Layers 2 & 3) for web/HTML ingress:
71
+ const result = await sanitize(fetchedPageSource, { html: true });
72
+ // result.cleaned — hidden HTML spliced out, placeholders left in place
73
+ // result.found — categories neutralized (e.g. ["Format chars (Cf)", "hidden HTML"])
74
+ // result.warnings — human-facing notices (long-run alerts, exfil reasons, …)
75
+ ```
76
+
77
+ `sanitize` never throws and never silently drops content: any change to the text
78
+ is accompanied by at least one entry in `warnings`.
79
+
80
+ ### 2. Just the zero-dependency invisible-char core
81
+
82
+ ```js
83
+ import {
84
+ stripInvisible,
85
+ stripInvisibleWithReport,
86
+ } from "agent-input-sanitizer/invisible";
87
+
88
+ stripInvisible(text); // -> cleaned string
89
+ const { cleaned, found } = stripInvisibleWithReport(text);
90
+ // found names exactly the categories removed, e.g. ["Variation selectors"]
91
+ ```
92
+
93
+ This entry pulls in **no runtime dependencies**.
94
+
95
+ ### 3. Just the HTML layer
96
+
97
+ ```js
98
+ import {
99
+ sanitizeHtml,
100
+ detectExfil,
101
+ checkExfilUrl,
102
+ } from "agent-input-sanitizer/html";
103
+
104
+ const layer2 = sanitizeHtml(pageSource); // null when nothing to strip/report
105
+ const threats = detectExfil(pageSource); // null or [{ isImage, reason, target }]
106
+ const reason = checkExfilUrl(oneUrl); // null or a string reason
107
+ ```
108
+
109
+ > **The HTML entry is heavier—import it only when you need it.** It pulls in
110
+ > the unified/remark/rehype graph (~200 ms of module-load time). The convenience
111
+ > `sanitize` lazy-loads it only on the `{ html: true }` path, so a Layer-1-only
112
+ > caller never pays for it. If you import from `agent-input-sanitizer/html`
113
+ > directly, you take that cost at import time.
114
+
115
+ ## Public surface
116
+
117
+ `agent-input-sanitizer` (main)—`sanitize`, everything re-exported from
118
+ `./invisible`, and the cheap Layer 2/3 pre-gates `HTML_TAG_PRESENT`,
119
+ `MD_LINK_HINT`, `SECRET_HINT`, `SECRET_HINT_EXT`, `matchesSecretHint` (these are
120
+ dependency-free, so re-exporting them never pulls in the heavy HTML graph).
121
+
122
+ `agent-input-sanitizer/invisible` — `stripInvisible`, `stripInvisibleWithReport`,
123
+ `isSgrOnly`, and the constants `STRIP`, `SGR_RE`, `CHECKS`, `VS`,
124
+ `BLANK_NON_CF`, `LONG_RUN_RE`, `LONG_RUN_THRESHOLD`, `SCATTERED_THRESHOLD`,
125
+ `LINGUISTIC_SCRIPTS`.
126
+
127
+ `agent-input-sanitizer/html` — `sanitizeHtml`, `scanHtmlFragment`,
128
+ `looksLikeHtmlSource`, `spliceRanges`, `isHiddenStyle`, `isHiddenElement`,
129
+ `isHiddenOpen`, `closingTagName`, `detectExfil`, `checkExfilUrl`, `urlHost`, the
130
+ constants `REPORTED_TAGS`, `COMMENT_PLACEHOLDER`, `HIDDEN_PLACEHOLDER`,
131
+ `DATA_URI_LENGTH_THRESHOLD`, and the pre-gates `HTML_TAG_PRESENT`,
132
+ `MD_LINK_HINT`, `SECRET_HINT`, `SECRET_HINT_EXT`, `matchesSecretHint`.
133
+
134
+ ## Development
135
+
136
+ ```sh
137
+ npm test # node --test
138
+ npm run coverage # c8, enforced at 100% lines/branches/functions
139
+ npm run lint # eslint
140
+ npm run typecheck # tsc --noEmit (the source is typed via JSDoc)
141
+ ```
142
+
143
+ The test suite is the selling point: 100% coverage is enforced in CI, and the
144
+ enumerated members (each linguistic script, each invisible category, each
145
+ reported tag) are driven from single-source-of-truth lists so adding a member
146
+ without a test fails. Property and fuzz tests (fast-check) exercise idempotence,
147
+ deletion-only output, never-throwing on lone surrogates / astral input, and the
148
+ `found` ⇔ changed invariant over the real Unicode input domain.
149
+
150
+ ## License
151
+
152
+ [Apache-2.0](./LICENSE)
@@ -0,0 +1,77 @@
1
+ # Threat model
2
+
3
+ `agent-input-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 | 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.
39
+
40
+ ## Layer 2—hidden HTML (remark/rehype)
41
+
42
+ For web/HTML ingress, splice out exactly what a human viewing the rendered page
43
+ cannot see:
44
+
45
+ - `<!-- HTML comments -->`
46
+ - elements hidden by inline style: `display:none`, `visibility:hidden`,
47
+ `opacity:0`, off-screen positioning, zero/negative sizes, `text-indent`
48
+ off-screen, collapsing `clip`/`clip-path`/`transform:scale(0)`, white-on-white
49
+ / transparent text, `overflow:hidden` with a zero dimension
50
+ - elements hidden by attribute: `hidden`, `aria-hidden="true"`
51
+
52
+ Spliced ranges are replaced with a placeholder; **every byte outside a spliced
53
+ range is preserved verbatim** (no re-serialization). Unclosed hidden markup
54
+ extends to the end of the fragment—fail-closed for truncated input.
55
+
56
+ Scripting/resource tags (`script`, `style`, `object`, `embed`, `iframe`, `svg`,
57
+ `math`) and `data:` URI resources are **reported, not removed**: their bodies are
58
+ page source the model may legitimately need to inspect.
59
+
60
+ ## Layer 3—exfil URLs (detection only)
61
+
62
+ Report—never rewrite—URLs in markdown links/images/definitions and HTML
63
+ attributes (`src`/`href`/`background`/`srcset`/`ping`, form `action`/`formaction`,
64
+ `meta refresh`) that are shaped to carry data off-origin:
65
+
66
+ - suspicious query/fragment parameters (long base64/hex blobs, credential-shaped
67
+ tokens), tuned to skip request-signing / pagination / analytics parameters
68
+ that are legitimately long (`X-Amz-*`, SAS, `cursor`, `utm_*`, `gclid`, …)
69
+ - oversized or active-content (`text/html`, `image/svg+xml`, JS) `data:` URIs
70
+ - embedded `user:password@host` credentials
71
+ - unusually long query strings or fragments
72
+ - encoded-data blobs smuggled in a path segment (a beacon that avoids the query)
73
+ - off-origin form actions and `meta refresh` redirects
74
+ - `javascript:` / `vbscript:` targets
75
+
76
+ Each threat carries a `reason` and the destination `host` (never the
77
+ payload-bearing query/fragment), suitable for a warning shown to the operator.
package/package.json ADDED
@@ -0,0 +1,106 @@
1
+ {
2
+ "name": "agent-input-sanitizer",
3
+ "version": "1.0.0",
4
+ "description": "Defend an agent against hidden-content injection: strip payload-capable invisible Unicode and ANSI, splice out human-invisible HTML, and flag data-exfil URLs in untrusted text before any model sees it.",
5
+ "type": "module",
6
+ "packageManager": "pnpm@11.8.0",
7
+ "scripts": {
8
+ "postinstall": "git config core.hooksPath .hooks",
9
+ "test": "c8 node --test",
10
+ "check": "tsc --noEmit",
11
+ "build:types": "tsc -p tsconfig.build.json",
12
+ "prepack": "pnpm build:types",
13
+ "lint": "eslint .",
14
+ "format": "prettier --write ."
15
+ },
16
+ "lint-staged": {
17
+ "*.{css,scss}": [
18
+ "prettier --write"
19
+ ],
20
+ "*.json": [
21
+ "prettier --write"
22
+ ],
23
+ "*.json.example": [
24
+ "prettier --write --parser json"
25
+ ],
26
+ "*.{js,jsx,ts,tsx}": [
27
+ "prettier --write"
28
+ ],
29
+ "*.{yaml,yml}": [
30
+ "prettier --write"
31
+ ],
32
+ "*.md": [
33
+ "prettier --write"
34
+ ],
35
+ ".claude/skills/*/SKILL.md": [
36
+ ".hooks/lint-skills.sh"
37
+ ],
38
+ "{*.sh,.hooks/*}": [
39
+ "shfmt -i 2 -w"
40
+ ],
41
+ "*.py": [
42
+ "ruff check --fix",
43
+ "ruff format"
44
+ ]
45
+ },
46
+ "devDependencies": {
47
+ "@commitlint/cli": "^21.0.1",
48
+ "@commitlint/config-conventional": "^21.0.1",
49
+ "@eslint/js": "10.0.1",
50
+ "@types/node": "25.9.1",
51
+ "c8": "11.0.0",
52
+ "eslint": "10.4.0",
53
+ "fast-check": "4.8.0",
54
+ "globals": "17.6.0",
55
+ "lint-staged": "^17.0.5",
56
+ "prettier": "^3.0.0",
57
+ "punctilio": "^3.10.0",
58
+ "typescript": "6.0.3",
59
+ "typescript-eslint": "8.61.0"
60
+ },
61
+ "license": "Apache-2.0",
62
+ "engines": {
63
+ "node": ">=20"
64
+ },
65
+ "keywords": [
66
+ "llm",
67
+ "prompt-injection",
68
+ "sanitize",
69
+ "unicode",
70
+ "invisible-characters",
71
+ "ansi",
72
+ "exfiltration",
73
+ "rag",
74
+ "agent",
75
+ "security"
76
+ ],
77
+ "exports": {
78
+ ".": {
79
+ "types": "./types/index.d.mts",
80
+ "default": "./src/index.mjs"
81
+ },
82
+ "./invisible": {
83
+ "types": "./types/invisible.d.mts",
84
+ "default": "./src/invisible.mjs"
85
+ },
86
+ "./html": {
87
+ "types": "./types/html.d.mts",
88
+ "default": "./src/html.mjs"
89
+ }
90
+ },
91
+ "files": [
92
+ "src",
93
+ "types",
94
+ "LICENSE",
95
+ "README.md",
96
+ "THREAT-MODEL.md"
97
+ ],
98
+ "dependencies": {
99
+ "rehype-parse": "9.0.1",
100
+ "remark-gfm": "4.0.1",
101
+ "remark-parse": "11.0.0",
102
+ "style-to-object": "1.0.14",
103
+ "unified": "11.0.5",
104
+ "unist-util-visit": "5.1.0"
105
+ }
106
+ }
package/src/gates.mjs ADDED
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Cheap, dependency-free pre-gates shared by the HTML layer (Layers 2 & 3) and
3
+ * re-exported from both the package root and the `./html` subpath.
4
+ *
5
+ * These are pulled out of `html.mjs` so the package root can re-export them
6
+ * without dragging in the heavy remark/rehype/unified graph: a static
7
+ * `export … from "./html.mjs"` would eagerly evaluate that ~200ms module on
8
+ * every root import, defeating the lazy-load design. This module imports
9
+ * nothing, so re-exporting it is free.
10
+ */
11
+
12
+ // ─── Cheap pre-gates ─────────────────────────────────────────────────────────
13
+
14
+ /**
15
+ * Matches any HTML tag-like construct: opening tags, closing tags (`</`),
16
+ * comments (`<!`), and fragments with attributes. Gate for Layer 2 (HTML
17
+ * sanitization) and the HTML img/a exfil path in Layer 3.
18
+ */
19
+ export const HTML_TAG_PRESENT = /<[a-zA-Z/!][^<>]*>/;
20
+
21
+ /**
22
+ * Matches markdown link/image syntax (`](`, `![`) and reference link
23
+ * definitions (`[label]: url` at line start). Gate for Layer 3 (markdown
24
+ * exfiltration detection).
25
+ */
26
+ export const MD_LINK_HINT = /\]\(|!\[|^[ \t]*\[[^[\]\n]+\]:\s/m;
27
+
28
+ // ─── Secret-shape pre-gate (Layer 3 URL-param reuse) ─────────────────────────
29
+ // Cheap shape match that decides whether a URL parameter value carries a
30
+ // credential (Layer 3). Split across TWO regexes, combined by matchesSecretHint:
31
+ // one alternation of every arm makes a redos analyzer see cross-arm polynomial
32
+ // backtracking (each arm is linear alone, but the union was a 3rd-degree
33
+ // polynomial on a long alnum run). Testing two independently-safe literals with
34
+ // || is linear and keeps each under the analyzer's bar. The `(?<!...)`
35
+ // lookbehinds on the EXT run-matching arms pin them to a token boundary so they
36
+ // can't be retried at every offset; the atlasv1 arm in SECRET_HINT does the same.
37
+ export const SECRET_HINT =
38
+ /secret|token|password|passwd|pwd|bearer|credential|authorization|contrase[nñ]a|-----BEGIN|(?:api|auth|service|account|db|database|priv|private|client|access)[_-]?key|(?:db|database|key)[_-]?pass|(?:A3T|AKIA|AGPA|AIDA|AROA|AIPA|ANPA|ANVA|ASIA)[A-Z0-9]{16}|gh[pousr]_[A-Za-z0-9]|github_pat_|gl[a-z]{2,12}-[0-9A-Za-z_-]{20}|sk-ant-|AIza[0-9A-Za-z_-]{35}|sk_live_|sk_test_|rk_live_|rk_test_|xox[bpasr]-|eyJ[A-Za-z0-9]|do[opr]_v1_[a-f0-9]{16}|v1\.0-[a-f0-9]{24}-|hv[sb]\.[A-Za-z0-9_-]{20}|(?<![a-z0-9])[a-z0-9]{14}\.atlasv1\.|sk-or-v1-[0-9a-f]{16}|gsk_[A-Za-z0-9]{16}|xai-[A-Za-z0-9]{16}|r8_[A-Za-z0-9]{16}/i;
39
+
40
+ // Second alternation (see SECRET_HINT): kept a separate literal so a redos
41
+ // analyzer vets each alternation in isolation.
42
+ export const SECRET_HINT_EXT =
43
+ /(?:AC|SK)[a-z0-9]{32}|SG\.[A-Za-z0-9_-]{22}\.[A-Za-z0-9_-]{43}|sq0csp-[0-9A-Za-z_-]{43}|(?<![0-9])[0-9]{8,10}:[0-9A-Za-z_-]{35}|(?<![0-9a-z])[0-9a-z]{32}-us[0-9]{1,2}|(?<![A-Za-z0-9_-])[MNO][A-Za-z0-9_-]{23,25}\.[A-Za-z0-9_-]{6}\.[A-Za-z0-9_-]{27}|T3BlbkFJ|pypi-AgE|(?<![A-Za-z0-9])AKC[A-Za-z0-9]{10}|(?<![A-Za-z0-9])AP[0-9A-Fa-f][A-Za-z0-9]{8}|:\/\/[^\s:/@]{1,64}:[^\s:/@]{1,64}@|(?:key|pw|pass)["']?[\s:=>]+["']?[A-Za-z0-9_/+-]{20}/i;
44
+
45
+ /**
46
+ * True when either pre-gate alternation shape-matches `text`. Split into two
47
+ * literals (see SECRET_HINT) and OR'd so neither grows into a
48
+ * polynomial-backtracking shape.
49
+ * @param {string} text
50
+ * @returns {boolean}
51
+ */
52
+ export function matchesSecretHint(text) {
53
+ return SECRET_HINT.test(text) || SECRET_HINT_EXT.test(text);
54
+ }