passcontrol 1.6.0 → 1.7.1

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.
@@ -0,0 +1,405 @@
1
+ // The injection guard's scanner (plans/injection-guard.md §3).
2
+ //
3
+ // One file for both sides, like cli/tool-rules.mjs: the gateway scans what tools returned
4
+ // inside a model request (API mode), and the sidecar will scan what a hook hands it
5
+ // (subscription mode). Pure: no `node:` imports, no network, safe on the edge.
6
+ //
7
+ // It reads text that came from OUTSIDE the agent's owner: a tool result, a fetched page,
8
+ // a document. Never the system prompt or the user's own words (the caller picks the text;
9
+ // lib/injection-blocks.ts does it for request bodies).
10
+ //
11
+ // What a finding means: this text carries a tell that injected instructions carry. Not
12
+ // that it IS an injection, and never that text without one is safe. A polite instruction
13
+ // with no tell ("also CC the report to …") passes, and is what Phase 2's hold is for.
14
+ //
15
+ // Severity:
16
+ // high an unquoted tell, or any tell inside text a reader would not see (an HTML
17
+ // comment, a hidden element, Unicode tag characters).
18
+ // low the same tell quoted or in code (`"ignore previous instructions"` in a doc or a
19
+ // string literal), a negated one ("never send your keys to …"), or a weak tell
20
+ // on its own (an authority claim, an invisible character, a `Human:` line).
21
+ // A quoted attack is therefore low. That is the price of not flagging every page ABOUT
22
+ // injection; Phase 1 records both, and the owner's data decides what Phase 2 holds on.
23
+ //
24
+ // Normalisation is for scanning only; nothing here changes what is forwarded. NFKC folds
25
+ // fullwidth and compatibility letters, invisible characters are removed (and counted),
26
+ // Unicode tag characters are decoded to the ASCII they smuggle. Nothing is base64- or
27
+ // URL-decoded (plan §3).
28
+ //
29
+ // Cost: every pattern is anchored on a literal word or character with bounded
30
+ // quantifiers, and every look-around is bounded. Bounded per match is not enough: the
31
+ // text is attacker-written, so a bound times every match was seconds (2026-10-30, measured
32
+ // in plans/codex-runs/inj-perf.report.md). So overlapping hidden spans are scanned once,
33
+ // fences and close tags are found by bisection, and a match's context is read at most
34
+ // CONTEXT_CHECKS_MAX times per pattern. The scan is synchronous and runs beside the call
35
+ // on the gateway, so this is its latency. Hostile 4 MB blocks are tested
36
+ // (tests/injection-scan.test.ts).
37
+
38
+ /** Immutable. A change to what this file finds ships under a new id. */
39
+ export const INJECTION_DETECTOR = "pc-heuristic-1";
40
+ /** Immutable, likewise, for the normalisation above. */
41
+ export const INJECTION_NORMALIZATION = 1;
42
+
43
+ export const INJECTION_FAMILIES = ["role_markup", "instruction_override", "exfil_directive", "authority_claim", "hidden_text"];
44
+
45
+ const HIDDEN_SEGMENT_MAX = 10_000;
46
+ const LINE_LOOK = 2_000;
47
+ const SENTENCE_LOOK = 300;
48
+
49
+ // ── Normalisation ────────────────────────────────────────────────────────────
50
+
51
+ // Invisible characters that have no business in ordinary text, and are counted. Joiners,
52
+ // directional marks and the soft hyphen are real in Persian, Hebrew, German or emoji, so
53
+ // they are removed for matching but never counted (a leading byte-order mark likewise).
54
+ const COUNTED_INVISIBLE = /[​⁠-⁤‭‮]/g;
55
+ const SILENT_INVISIBLE = /[‌‍‎‏­‪-‬⁦-⁩᠎]/g;
56
+ const TAG_RUN = /[\u{e0000}-\u{e007f}]+/gu;
57
+ const BLACK_FLAG = 0x1f3f4;
58
+
59
+ /**
60
+ * The text as scanned, plus what normalisation took out of sight: the ASCII decoded
61
+ * from tag characters (a subdivision flag's tags are an emoji, not a message), and how
62
+ * many counted invisible characters there were.
63
+ */
64
+ function normalize(raw) {
65
+ const smuggled = [];
66
+ let text = raw.replace(TAG_RUN, (run, offset) => {
67
+ const before = offset > 0 ? raw.codePointAt(offset - 2) : undefined;
68
+ if (before === BLACK_FLAG) return "";
69
+ let ascii = "";
70
+ for (const ch of run) {
71
+ const cp = ch.codePointAt(0) - 0xe0000;
72
+ if (cp >= 0x20 && cp <= 0x7e) ascii += String.fromCharCode(cp);
73
+ }
74
+ if (ascii) smuggled.push(ascii);
75
+ return "";
76
+ });
77
+ if (text.charCodeAt(0) === 0xfeff) text = text.slice(1);
78
+ text = text.normalize("NFKC");
79
+ let invisible = 0;
80
+ text = text.replace(COUNTED_INVISIBLE, () => {
81
+ invisible++;
82
+ return "";
83
+ });
84
+ text = text.replace(SILENT_INVISIBLE, "").replace(/[ \t \f\v]+/g, " ");
85
+ return { text, smuggled, invisible };
86
+ }
87
+
88
+ // ── Hidden HTML ──────────────────────────────────────────────────────────────
89
+
90
+ const OPEN_TAG = /<([a-zA-Z][a-zA-Z0-9-]{0,20})\b([^<>]{0,1000})>/g;
91
+ const HIDING_ATTR = /display\s{0,3}:\s{0,3}none|visibility\s{0,3}:\s{0,3}hidden|font-size\s{0,3}:\s{0,3}0(?![.\d])|opacity\s{0,3}:\s{0,3}0(?![.\d])|(?:^|\s)hidden(?=\s|=|$)/i;
92
+
93
+ const CLOSE_TAG = /<\/([a-zA-Z][a-zA-Z0-9-]{0,20})/g;
94
+ const ROLE_LOW_AT = /(?:Human|Assistant)\s{0,2}:/y;
95
+
96
+ /** The first value in ascending `list` that is >= `at`, or -1. */
97
+ function firstAtOrAfter(list, at) {
98
+ let lo = 0;
99
+ let hi = list.length;
100
+ while (lo < hi) {
101
+ const mid = (lo + hi) >>> 1;
102
+ if (list[mid] < at) lo = mid + 1;
103
+ else hi = mid;
104
+ }
105
+ return lo < list.length ? list[lo] : -1;
106
+ }
107
+
108
+ /**
109
+ * Where each closing tag starts, under every prefix of its lowercased name: a hidden
110
+ * `<i>` ends at the first `</i…` after it (`</img` too, as a plain search for `</i` would).
111
+ */
112
+ function closeTagIndex(text) {
113
+ const index = new Map();
114
+ CLOSE_TAG.lastIndex = 0;
115
+ for (const m of text.matchAll(CLOSE_TAG)) {
116
+ const name = m[1].toLowerCase();
117
+ for (let n = 1; n <= name.length; n++) {
118
+ const key = name.slice(0, n);
119
+ const list = index.get(key);
120
+ if (list) list.push(m.index ?? 0);
121
+ else index.set(key, [m.index ?? 0]);
122
+ }
123
+ }
124
+ return index;
125
+ }
126
+
127
+ /**
128
+ * Text a browser would not show: comment bodies and hidden elements' contents, each up to
129
+ * HIDDEN_SEGMENT_MAX characters. Spans that overlap are merged and returned once, so no
130
+ * character is scanned twice: before, every one of 400,000 nested `<i hidden>` opened its
131
+ * own 10,000-character window, and one 4 MB block took over 20 s. `roleAtStart`: a span
132
+ * merged into an earlier one starts with a `Human:` line, which its own segment would have
133
+ * matched at `^` and the merged text does not.
134
+ */
135
+ function hiddenSegments(text) {
136
+ const spans = [];
137
+ let at = 0;
138
+ for (;;) {
139
+ const open = text.indexOf("<!--", at);
140
+ if (open === -1) break;
141
+ const close = text.indexOf("-->", open + 4);
142
+ const end = close === -1 ? text.length : close;
143
+ spans.push([open + 4, Math.min(end, open + 4 + HIDDEN_SEGMENT_MAX)]);
144
+ if (close === -1) break;
145
+ at = close + 3;
146
+ }
147
+ let closes = null;
148
+ OPEN_TAG.lastIndex = 0;
149
+ for (const m of text.matchAll(OPEN_TAG)) {
150
+ if (!HIDING_ATTR.test(m[2])) continue;
151
+ const start = (m.index ?? 0) + m[0].length;
152
+ const limit = Math.min(text.length, start + HIDDEN_SEGMENT_MAX);
153
+ closes ??= closeTagIndex(text);
154
+ const name = m[1].toLowerCase();
155
+ const close = firstAtOrAfter(closes.get(name) ?? [], start);
156
+ // The whole `</name` inside the window, as a search of the window alone required.
157
+ spans.push([start, close !== -1 && close + 2 + name.length <= limit ? close : limit]);
158
+ }
159
+ spans.sort((x, y) => x[0] - y[0]);
160
+ const segments = [];
161
+ let roleAtStart = false;
162
+ let from = -1;
163
+ let to = -1;
164
+ for (const [s, e] of spans) {
165
+ if (s < to) {
166
+ ROLE_LOW_AT.lastIndex = s;
167
+ if (ROLE_LOW_AT.test(text) && ROLE_LOW_AT.lastIndex <= e) roleAtStart = true;
168
+ to = Math.max(to, e);
169
+ continue;
170
+ }
171
+ if (from !== -1) segments.push(text.slice(from, to));
172
+ from = s;
173
+ to = e;
174
+ }
175
+ if (from !== -1) segments.push(text.slice(from, to));
176
+ return { segments, roleAtStart };
177
+ }
178
+
179
+ // ── Quoted and code context ──────────────────────────────────────────────────
180
+
181
+ const FENCE = /^ {0,3}(?:```|~~~)/gm;
182
+ const CLOSERS = { '"': '"', "`": "`", "“": "”", "‘": "’", "«": "»", "'": "'" };
183
+ const WORD_CHAR = /[\p{L}\p{N}_]/u;
184
+
185
+ function fenceRanges(text) {
186
+ const ranges = [];
187
+ let open = -1;
188
+ FENCE.lastIndex = 0;
189
+ for (const m of text.matchAll(FENCE)) {
190
+ if (open === -1) open = m.index ?? 0;
191
+ else {
192
+ ranges.push([open, m.index ?? 0]);
193
+ open = -1;
194
+ }
195
+ }
196
+ if (open !== -1) ranges.push([open, text.length]);
197
+ return ranges;
198
+ }
199
+
200
+ /** Whether [start, end) sits inside a quote or inline code span on its own line. */
201
+ function quotedOnLine(text, start, end) {
202
+ let lineStart = start;
203
+ const floor = Math.max(0, start - LINE_LOOK);
204
+ while (lineStart > floor && text[lineStart - 1] !== "\n") lineStart--;
205
+ let lineEnd = end;
206
+ const ceiling = Math.min(text.length, end + LINE_LOOK);
207
+ while (lineEnd < ceiling && text[lineEnd] !== "\n") lineEnd++;
208
+ let opener = null;
209
+ let openAt = -1;
210
+ for (let i = lineStart; i < lineEnd; i++) {
211
+ const c = text[i];
212
+ if (opener !== null) {
213
+ if (c === CLOSERS[opener]) {
214
+ if (openAt < start && i >= end) return true;
215
+ opener = null;
216
+ }
217
+ } else if (i >= start) {
218
+ // No span is open at the match, so none can contain it.
219
+ return false;
220
+ } else if (c in CLOSERS && c !== "”" && c !== "’" && c !== "»") {
221
+ if (c === "'" && i > 0 && WORD_CHAR.test(text[i - 1])) continue;
222
+ opener = c;
223
+ openAt = i;
224
+ }
225
+ }
226
+ return false;
227
+ }
228
+
229
+ function quotedContext(text, fences, start, end) {
230
+ // Fences are disjoint and in order, so only the last one opening at or before `start`
231
+ // can hold the match. Found by bisection: a walk over every fence, per match, took 12 s
232
+ // on 100,000 fenced overrides.
233
+ let lo = 0;
234
+ let hi = fences.length;
235
+ while (lo < hi) {
236
+ const mid = (lo + hi) >>> 1;
237
+ if (fences[mid][0] <= start) lo = mid + 1;
238
+ else hi = mid;
239
+ }
240
+ if (lo > 0 && end <= fences[lo - 1][1]) return true;
241
+ return quotedOnLine(text, start, end);
242
+ }
243
+
244
+ // ── The tells ────────────────────────────────────────────────────────────────
245
+
246
+ const OVERRIDE = [
247
+ /\b(?:ignore|disregard|forget|override|bypass|skip)\s{1,3}(?:(?:all|any|the|your|these|those|my|of)\s{1,3}){0,3}(?:previous|prior|above|preceding|earlier|existing|original|initial|system|developer)\s{1,3}(?:instructions?|prompts?|rules|directives|guidelines|guidance|commands|messages|context|constraints)\b/gi,
248
+ /\bnew\s{1,3}(?:system\s{1,3})?instructions?\s{0,3}:/gi,
249
+ ];
250
+
251
+ const ROLE_HIGH = [
252
+ /<\|(?:im_start|im_end|im_sep|system|user|assistant|endoftext|eot_id|start_header_id|end_header_id|begin_of_text)\|>/gi,
253
+ /\[\/?INST\]|<<\/?SYS>>/g,
254
+ /<\/(?:tool_result|function_results|tool_output|tool_response|system|instructions)>/gi,
255
+ /<system>/gi,
256
+ ];
257
+ // Not `<system-reminder>`: Claude Code writes that markup into its own requests, tool
258
+ // results included, so it would flag every Claude Code tool call. A fake one in a page
259
+ // is a real tell this version does not see.
260
+ const ROLE_LOW = /^(?:Human|Assistant)\s{0,2}:/gm;
261
+
262
+ const AUTHORITY = [
263
+ /\b(?:user|owner|admin(?:istrator)?|developer|operator)\s{1,2}(?:has\s{1,2})?(?:already\s{1,2})?(?:authori[sz]ed|approved|permitted|granted\s{1,2}(?:you\s{1,2})?permission)\b/gi,
264
+ /\b(?:note|message|instructions?|attention|important)\s{0,2}(?:to|for)\s{1,2}(?:the\s{1,2}|all\s{1,2}|any\s{1,2})?(?:ai|llm|language\s{1,2}model|assistant|agent|model|chatbot)s?\b/gi,
265
+ /\bsystem\s{0,2}(?:override|administrator|admin)\b/gi,
266
+ ];
267
+
268
+ const SECRET_NOUN = /\.env\b|\benv(?:ironment)?\s{1,2}(?:file|variables|vars)\b|\bsystem\s{1,2}prompt\b|\b(?:api|access|secret|private|ssh|aws)\s{0,2}keys\b|\ball\s{1,2}(?:the\s{1,2})?keys\b|\bcredentials\b|\bprivate\s{1,2}key\b|\bssh\s{1,2}key\b|\bpasswords?\b|\bsecrets\b|\bcookies\b|~\/\.ssh|\bid_rsa\b/gi;
269
+ const SEND_VERB = /\b(?:send|forward|upload|e-?mail|exfiltrate|transmit|leak|paste|share|copy|curl|wget)\b/i;
270
+ const DESTINATION = /https?:\/\/[^\s"'<>)]{1,300}|\b[\w.+-]{1,64}@[\w-]{1,63}(?:\.[\w-]{1,63}){1,8}\b/i;
271
+ const NEGATION = /\b(?:never|not|don'?t|do\s{1,2}not|must\s{1,2}not|mustn'?t|shouldn'?t|should\s{1,2}not|avoid|without)\b/i;
272
+ const MD_IMAGE = /!\[[^\]\n]{0,200}\]\(([^\s)]{1,1000})\)/g;
273
+ const BEACON_QUERY = /\{|%7b|\$|</i;
274
+
275
+ const isStop = (c) => c === "." || c === "!" || c === "?";
276
+
277
+ /** The sentence around [start, end): bounded, ending at `. ` / `! ` / `? ` or a newline. */
278
+ function sentenceAround(text, start, end) {
279
+ let a = start;
280
+ const floor = Math.max(0, start - SENTENCE_LOOK);
281
+ while (a > floor && text[a - 1] !== "\n" && !(isStop(text[a - 1]) && /\s/.test(text[a] ?? " "))) a--;
282
+ let b = end;
283
+ const ceiling = Math.min(text.length, end + SENTENCE_LOOK);
284
+ while (b < ceiling && text[b] !== "\n" && !(isStop(text[b]) && /\s/.test(text[b + 1] ?? " "))) b++;
285
+ return text.slice(a, b);
286
+ }
287
+
288
+ // What a sentence needs before SEND_VERB and DESTINATION can match in it, without their
289
+ // word boundaries (a sentence cut mid-word can match where the whole text does not). Their
290
+ // positions are found once per text, so a secret noun with neither near it costs a bisection:
291
+ // `password ` 470,000 times over, each reading its sentence, took 4 s.
292
+ const SEND_LOOSE = /send|forward|upload|e-?mail|exfiltrate|transmit|leak|paste|share|copy|curl|wget/gi;
293
+ const DESTINATION_LOOSE = /https?:\/\/|@/gi;
294
+
295
+ function positions(text, re) {
296
+ re.lastIndex = 0;
297
+ return Array.from(text.matchAll(re), (m) => m.index ?? 0);
298
+ }
299
+
300
+ /** Whether any position in ascending `list` falls in [from, to). */
301
+ const anyIn = (list, from, to) => {
302
+ const p = firstAtOrAfter(list, from);
303
+ return p !== -1 && p < to;
304
+ };
305
+
306
+ // A backstop on top of the bounds above: per pattern per text, at most this many matches
307
+ // get their quote, code or sentence context read. Past it the pattern stops, keeping what
308
+ // it found (fail open: the scan must never stall the call it rides on). Reaching it takes
309
+ // a thousand quoted, fenced or negated tells in one block.
310
+ const CONTEXT_CHECKS_MAX = 1_000;
311
+
312
+ /**
313
+ * Every tell in one normalised text, as family → severity. `hidden`: the text was out of
314
+ * a reader's sight, so every tell in it is high, quoted or not.
315
+ */
316
+ function tellsIn(text, hidden, found) {
317
+ const fences = hidden ? [] : fenceRanges(text);
318
+ const mark = (family, severity) => {
319
+ if (found.get(family) !== "high") found.set(family, severity);
320
+ };
321
+ const strong = (family, re) => {
322
+ re.lastIndex = 0;
323
+ let checks = 0;
324
+ for (const m of text.matchAll(re)) {
325
+ const start = m.index ?? 0;
326
+ const quoted = !hidden && quotedContext(text, fences, start, start + m[0].length);
327
+ mark(family, quoted ? "low" : "high");
328
+ if (found.get(family) === "high" || ++checks >= CONTEXT_CHECKS_MAX) return;
329
+ }
330
+ };
331
+
332
+ for (const re of OVERRIDE) strong("instruction_override", re);
333
+ for (const re of ROLE_HIGH) strong("role_markup", re);
334
+ ROLE_LOW.lastIndex = 0;
335
+ if (ROLE_LOW.test(text)) mark("role_markup", hidden ? "high" : "low");
336
+ for (const re of AUTHORITY) {
337
+ re.lastIndex = 0;
338
+ if (re.test(text)) mark("authority_claim", hidden ? "high" : "low");
339
+ }
340
+
341
+ SECRET_NOUN.lastIndex = 0;
342
+ let sends = null;
343
+ let destinations = null;
344
+ let checks = 0;
345
+ for (const m of text.matchAll(SECRET_NOUN)) {
346
+ const start = m.index ?? 0;
347
+ const end = start + m[0].length;
348
+ // The sentence lies within SENTENCE_LOOK of the noun on either side. A verb at the
349
+ // sentence's start can be one the text-wide scan skipped, inside an overlapping earlier
350
+ // match ("shar|email" cut at the bar); that match starts at most 10 characters before.
351
+ const from = start - SENTENCE_LOOK - 16;
352
+ const to = end + SENTENCE_LOOK;
353
+ sends ??= positions(text, SEND_LOOSE);
354
+ if (!anyIn(sends, from, to)) continue;
355
+ destinations ??= positions(text, DESTINATION_LOOSE);
356
+ if (!anyIn(destinations, from, to)) continue;
357
+ if (++checks > CONTEXT_CHECKS_MAX) break;
358
+ const sentence = sentenceAround(text, start, end);
359
+ if (!SEND_VERB.test(sentence) || !DESTINATION.test(sentence)) continue;
360
+ const softened = !hidden && (NEGATION.test(sentence) || quotedContext(text, fences, start, end));
361
+ mark("exfil_directive", softened ? "low" : "high");
362
+ if (found.get("exfil_directive") === "high") break;
363
+ }
364
+ MD_IMAGE.lastIndex = 0;
365
+ for (const m of text.matchAll(MD_IMAGE)) {
366
+ const url = m[1];
367
+ const q = url.indexOf("?");
368
+ if (!/^https?:\/\//i.test(url) || q === -1 || !BEACON_QUERY.test(url.slice(q + 1))) continue;
369
+ mark("exfil_directive", "high");
370
+ break;
371
+ }
372
+ }
373
+
374
+ /**
375
+ * The tells in one piece of untrusted text, one entry per family at its highest
376
+ * severity, in INJECTION_FAMILIES order. Empty when there are none.
377
+ *
378
+ * @param {string} raw
379
+ * @returns {{ family: string, severity: "high" | "low" }[]}
380
+ */
381
+ export function scanText(raw) {
382
+ if (typeof raw !== "string" || raw.length === 0) return [];
383
+ const { text, smuggled, invisible } = normalize(raw);
384
+ const found = new Map();
385
+ tellsIn(text, false, found);
386
+
387
+ const { segments, roleAtStart } = hiddenSegments(text);
388
+ const hidden = [...segments, ...smuggled.map((s) => normalize(s).text)];
389
+ let hiddenTell = false;
390
+ if (roleAtStart) {
391
+ hiddenTell = true;
392
+ found.set("role_markup", "high");
393
+ }
394
+ for (const segment of hidden) {
395
+ const inner = new Map();
396
+ tellsIn(segment, true, inner);
397
+ if (inner.size === 0) continue;
398
+ hiddenTell = true;
399
+ for (const family of inner.keys()) found.set(family, "high");
400
+ }
401
+ if (hiddenTell || smuggled.length > 0) found.set("hidden_text", "high");
402
+ else if (invisible > 0) found.set("hidden_text", "low");
403
+
404
+ return INJECTION_FAMILIES.filter((f) => found.has(f)).map((family) => ({ family, severity: found.get(family) }));
405
+ }
@@ -0,0 +1,150 @@
1
+ // Local, best-effort tool-result scan. Only fixed metadata and a hash leave here.
2
+ import { createHash, randomBytes } from "node:crypto";
3
+ import { scanText, INJECTION_DETECTOR, INJECTION_NORMALIZATION, INJECTION_FAMILIES } from "./injection-scan.mjs";
4
+
5
+ // What one hook may scan, in UTF-8 bytes. Each leaf is scanned whole, never in chunks
6
+ // (a chunk boundary would split a fence or hidden-text span); 8 MB of hostile text scans
7
+ // in under half a second (measured 2026-10-31). Past it, the rest is a gap.
8
+ export const HOOK_SCAN_BUDGET = 8 * 1024 * 1024;
9
+ const MAX_FINDINGS = 20;
10
+ const MAX_SEEN = 1000;
11
+ const PATH = /^[A-Za-z0-9_.\[\]?-]{1,512}$/;
12
+ const TOOL = /^[A-Za-z0-9_.-]{1,128}$/;
13
+
14
+ // Iterative traversal avoids a stack overflow on deeply nested responses. Objects
15
+ // are visited once, including if a non-JSON caller hands us a cycle.
16
+ function* stringLeaves(value, path) {
17
+ const pending = [[value, path]];
18
+ const visited = new WeakSet();
19
+ while (pending.length) {
20
+ const [node, place] = pending.pop();
21
+ if (!PATH.test(place)) continue;
22
+ if (typeof node === "string") {
23
+ yield [node, place];
24
+ } else if (node && typeof node === "object" && !visited.has(node)) {
25
+ visited.add(node);
26
+ const keys = Object.keys(node);
27
+ for (let i = keys.length - 1; i >= 0; i--) {
28
+ const key = keys[i];
29
+ const segment = /^[A-Za-z0-9_-]{1,128}$/.test(key) ? key : "?";
30
+ const suffix = Array.isArray(node) ? `[${segment}]` : `.${segment}`;
31
+ // Unknown/overlong keys still get scanned; the path carries a placeholder.
32
+ const next = place.length + suffix.length <= 512 ? place + suffix : `${place.slice(0, 510)}.?`;
33
+ pending.push([node[key], next]);
34
+ }
35
+ }
36
+ }
37
+ }
38
+
39
+ /** One `injection_incomplete` event for what went unread (1.7.1, external review P1):
40
+ * where the first such leaf was, and a hash over the hashes of every one, so the same
41
+ * output re-sent is the same gap and different unread output is a new one. */
42
+ function gapEvent(gap, unread, at) {
43
+ const [first] = unread;
44
+ const digest = createHash("sha256").update(`gap:${gap}:`);
45
+ for (const leaf of unread) digest.update(leaf.hash);
46
+ return {
47
+ kind: "injection_incomplete", at, source: "tool_result", path: first.path,
48
+ ...(first.tool ? { tool: first.tool } : {}),
49
+ gap, detector: INJECTION_DETECTOR, normalization_version: INJECTION_NORMALIZATION, block_sha256: digest.digest("hex"),
50
+ };
51
+ }
52
+
53
+ /** `seen` belongs to one sidecar; no text or hook input is retained. Never throws.
54
+ * `scan` is injectable for failure tests. What could not be read (past the budget, or
55
+ * where the scanner threw) is reported as a gap, never left out as if clean.
56
+ */
57
+ export function findingsFromHook(input, { seen = new Set(), now = Date.now, scan = scanText } = {}) {
58
+ const events = [];
59
+ const found = new Set();
60
+ const unread = { too_large: [], scan_failed: [] };
61
+ let budget = HOOK_SCAN_BUDGET;
62
+ try {
63
+ let calls;
64
+ if (input?.hook_event_name === "PostToolBatch" && Array.isArray(input.tool_calls)) {
65
+ calls = input.tool_calls.map((call, i) => [call, call?.tool_response, `tool_calls[${i}].tool_response`]);
66
+ } else if (input?.hook_event_name === "PostToolUse") {
67
+ // Codex 0.163's embedded schema names tool_response. Accept aliases for
68
+ // compatible clients; keep the actual field name in metadata paths.
69
+ const field = ["tool_response", "tool_output", "output"].find((key) => input[key] != null);
70
+ calls = field ? [[input, input[field], field]] : [];
71
+ } else return [];
72
+ // Every leaf is read; MAX_FINDINGS caps what is uploaded, strong findings first
73
+ // (1.7.1: a cap that stopped the scan let twenty weak tells hide a strong one).
74
+ for (const [call, response, root] of calls) {
75
+ const tool = typeof call.tool_name === "string" && TOOL.test(call.tool_name) ? call.tool_name : undefined;
76
+ for (const [text, path] of stringLeaves(response, root)) {
77
+ const hash = createHash("sha256").update(text, "utf8").digest("hex");
78
+ if (seen.has(hash) || found.has(hash)) continue;
79
+ const bytes = Buffer.byteLength(text, "utf8");
80
+ if (bytes > budget) {
81
+ unread.too_large.push({ path, tool, hash });
82
+ continue;
83
+ }
84
+ budget -= bytes;
85
+ let families, severity;
86
+ try {
87
+ const hits = scan(text);
88
+ families = INJECTION_FAMILIES.filter((family) => hits.some((hit) => hit.family === family));
89
+ severity = hits.some((hit) => hit.severity === "high") ? "high" : "low";
90
+ } catch {
91
+ unread.scan_failed.push({ path, tool, hash });
92
+ continue;
93
+ }
94
+ if (!families.length) continue;
95
+ events.push({
96
+ kind: "injection_finding", at: now(), source: "tool_result", path,
97
+ ...(tool ? { tool } : {}),
98
+ families, severity,
99
+ detector: INJECTION_DETECTOR, normalization_version: INJECTION_NORMALIZATION, block_sha256: hash,
100
+ });
101
+ found.add(hash);
102
+ }
103
+ }
104
+ // Gaps first: at most one per kind, and the hold depends on them as on a strong tell.
105
+ const gaps = Object.entries(unread).filter(([, leaves]) => leaves.length).map(([gap, leaves]) => gapEvent(gap, leaves, now()))
106
+ .filter((e) => !seen.has(e.block_sha256));
107
+ const kept = [...gaps, ...events.filter((e) => e.severity === "high"), ...events.filter((e) => e.severity !== "high")].slice(0, MAX_FINDINGS);
108
+ // Only what is uploaded is seen: a block past the cap is found again by a later hook.
109
+ for (const event of kept) seen.add(event.block_sha256);
110
+ while (seen.size > MAX_SEEN) seen.delete(seen.values().next().value);
111
+ return kept;
112
+ } catch {
113
+ // The hook as a whole went unread. Nothing identifies it, so the gap is new each
114
+ // time: in hold mode that holds, the safe side for a failure this rare.
115
+ try {
116
+ const path = input.hook_event_name === "PostToolUse" ? "tool_response" : "tool_calls";
117
+ return [gapEvent("scan_failed", [{ path, hash: randomBytes(32).toString("hex") }], Date.now())];
118
+ } catch {
119
+ return [];
120
+ }
121
+ }
122
+ }
123
+
124
+ const HOOK_NAME = /"hook_event_name"\s*:\s*"([A-Za-z]{1,64})"/;
125
+ // A tool's own fields. A name that comes after one may be inside the tool's output.
126
+ const TOOL_FIELD = /"(?:tool_response|tool_output|tool_calls|tool_input|output)"\s*:/;
127
+
128
+ /**
129
+ * A hook body over the sidecar's limit is refused unread (cli/sidecar.mjs). Unless its
130
+ * start plainly names a hook that carries no tool output, that output went unchecked:
131
+ * one too_large gap, from the start of the body (`head`) and a SHA-256 of all of it.
132
+ * Never throws.
133
+ */
134
+ export function gapFromOversizedHook(head, bodySha256, { seen = new Set(), now = Date.now } = {}) {
135
+ try {
136
+ const match = HOOK_NAME.exec(head);
137
+ const toolField = TOOL_FIELD.exec(head);
138
+ // Claude Code and Codex both send the hook's name before the tool's fields.
139
+ const name = match && !(toolField && toolField.index < match.index) ? match[1] : undefined;
140
+ if (name && name !== "PostToolBatch" && name !== "PostToolUse") return null;
141
+ const path = name === "PostToolBatch" ? "tool_calls" : name === "PostToolUse" ? "tool_response" : "hook_input";
142
+ const event = gapEvent("too_large", [{ path, hash: bodySha256 }], now());
143
+ if (seen.has(event.block_sha256)) return null;
144
+ seen.add(event.block_sha256);
145
+ while (seen.size > MAX_SEEN) seen.delete(seen.values().next().value);
146
+ return event;
147
+ } catch {
148
+ return null;
149
+ }
150
+ }