passcontrol 1.6.0 → 1.7.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/bin/passcontrol.mjs +20 -8
- package/cli/claude-code.mjs +41 -12
- package/cli/client-events-upload.mjs +22 -0
- package/cli/codex-hooks.mjs +44 -8
- package/cli/injection-hold.d.mts +7 -0
- package/cli/injection-hold.mjs +30 -0
- package/cli/injection-scan.d.mts +11 -0
- package/cli/injection-scan.mjs +405 -0
- package/cli/injection-sidecar.mjs +78 -0
- package/cli/sidecar.mjs +73 -2
- package/cli/subscription-gate.mjs +18 -1
- package/cli/tool-gate.mjs +70 -13
- package/cli/watch-feed.mjs +39 -0
- package/cli/watch.mjs +39 -3
- package/package.json +1 -1
- package/sdk/verify.d.ts +13 -0
|
@@ -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,78 @@
|
|
|
1
|
+
// Local, best-effort tool-result scan. Only fixed metadata and a hash leave here.
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
3
|
+
import { scanText, INJECTION_DETECTOR, INJECTION_NORMALIZATION, INJECTION_FAMILIES } from "./injection-scan.mjs";
|
|
4
|
+
|
|
5
|
+
const MAX_LEAF_BYTES = 1024 * 1024;
|
|
6
|
+
const MAX_FINDINGS = 20;
|
|
7
|
+
const MAX_SEEN = 1000;
|
|
8
|
+
const PATH = /^[A-Za-z0-9_.\[\]?-]{1,512}$/;
|
|
9
|
+
const TOOL = /^[A-Za-z0-9_.-]{1,128}$/;
|
|
10
|
+
|
|
11
|
+
// Iterative traversal avoids a stack overflow on deeply nested responses. Objects
|
|
12
|
+
// are visited once, including if a non-JSON caller hands us a cycle.
|
|
13
|
+
function* stringLeaves(value, path) {
|
|
14
|
+
const pending = [[value, path]];
|
|
15
|
+
const visited = new WeakSet();
|
|
16
|
+
while (pending.length) {
|
|
17
|
+
const [node, place] = pending.pop();
|
|
18
|
+
if (!PATH.test(place)) continue;
|
|
19
|
+
if (typeof node === "string") {
|
|
20
|
+
yield [node, place];
|
|
21
|
+
} else if (node && typeof node === "object" && !visited.has(node)) {
|
|
22
|
+
visited.add(node);
|
|
23
|
+
const keys = Object.keys(node);
|
|
24
|
+
for (let i = keys.length - 1; i >= 0; i--) {
|
|
25
|
+
const key = keys[i];
|
|
26
|
+
const segment = /^[A-Za-z0-9_-]{1,128}$/.test(key) ? key : "?";
|
|
27
|
+
const suffix = Array.isArray(node) ? `[${segment}]` : `.${segment}`;
|
|
28
|
+
// Unknown/overlong keys still get scanned; the path carries a placeholder.
|
|
29
|
+
const next = place.length + suffix.length <= 512 ? place + suffix : `${place.slice(0, 510)}.?`;
|
|
30
|
+
pending.push([node[key], next]);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** `seen` belongs to one sidecar; no text or hook input is retained. Never throws.
|
|
37
|
+
* `scan` is injectable for failure tests. Failed scans emit nothing and do not
|
|
38
|
+
* consume hashes, allowing a later hook to retry.
|
|
39
|
+
*/
|
|
40
|
+
export function findingsFromHook(input, { seen = new Set(), now = Date.now, scan = scanText } = {}) {
|
|
41
|
+
const events = [];
|
|
42
|
+
const found = new Set();
|
|
43
|
+
try {
|
|
44
|
+
let calls;
|
|
45
|
+
if (input?.hook_event_name === "PostToolBatch" && Array.isArray(input.tool_calls)) {
|
|
46
|
+
calls = input.tool_calls.map((call, i) => [call, call?.tool_response, `tool_calls[${i}].tool_response`]);
|
|
47
|
+
} else if (input?.hook_event_name === "PostToolUse") {
|
|
48
|
+
// Codex 0.163's embedded schema names tool_response. Accept aliases for
|
|
49
|
+
// compatible clients; keep the actual field name in metadata paths.
|
|
50
|
+
const field = ["tool_response", "tool_output", "output"].find((key) => input[key] != null);
|
|
51
|
+
calls = field ? [[input, input[field], field]] : [];
|
|
52
|
+
} else return [];
|
|
53
|
+
for (const [call, response, root] of calls) {
|
|
54
|
+
if (events.length >= MAX_FINDINGS) break;
|
|
55
|
+
for (const [text, path] of stringLeaves(response, root)) {
|
|
56
|
+
if (Buffer.byteLength(text, "utf8") > MAX_LEAF_BYTES) continue;
|
|
57
|
+
const hash = createHash("sha256").update(text, "utf8").digest("hex");
|
|
58
|
+
if (seen.has(hash) || found.has(hash)) continue;
|
|
59
|
+
const hits = scan(text);
|
|
60
|
+
const families = INJECTION_FAMILIES.filter((family) => hits.some((hit) => hit.family === family));
|
|
61
|
+
if (!families.length) continue;
|
|
62
|
+
events.push({
|
|
63
|
+
kind: "injection_finding", at: now(), source: "tool_result", path,
|
|
64
|
+
...(typeof call.tool_name === "string" && TOOL.test(call.tool_name) ? { tool: call.tool_name } : {}),
|
|
65
|
+
families, severity: hits.some((hit) => hit.severity === "high") ? "high" : "low",
|
|
66
|
+
detector: INJECTION_DETECTOR, normalization_version: INJECTION_NORMALIZATION, block_sha256: hash,
|
|
67
|
+
});
|
|
68
|
+
found.add(hash);
|
|
69
|
+
if (events.length >= MAX_FINDINGS) break;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
for (const hash of found) seen.add(hash);
|
|
73
|
+
while (seen.size > MAX_SEEN) seen.delete(seen.values().next().value);
|
|
74
|
+
return events;
|
|
75
|
+
} catch {
|
|
76
|
+
return [];
|
|
77
|
+
}
|
|
78
|
+
}
|
package/cli/sidecar.mjs
CHANGED
|
@@ -7,6 +7,8 @@ import { classifyConnect, classifyProxyRequest, isLoopbackBindHost } from "./pro
|
|
|
7
7
|
import { createVisaClient } from "./visa-client.mjs";
|
|
8
8
|
import { declaredLineage, declaredSession } from "./declared-session.mjs";
|
|
9
9
|
import { defaultJournalDir, openJournal } from "./journal.mjs";
|
|
10
|
+
import { heldUnderTaint } from "./injection-hold.mjs";
|
|
11
|
+
import { findingsFromHook } from "./injection-sidecar.mjs";
|
|
10
12
|
import { answer, createWatchFeed, isNotACall, isLocalCaller, LOCAL_PREFIX, peekText, providerOf, refusalCode, requestModel } from "./watch-feed.mjs";
|
|
11
13
|
import { createStopGate, HOOK_PATH, SELF_READ_TIMEOUT_MS, selfAnswerState } from "./subscription-gate.mjs";
|
|
12
14
|
import { createToolGate } from "./tool-gate.mjs";
|
|
@@ -178,7 +180,14 @@ export function createSidecar({
|
|
|
178
180
|
// Subscription mode's Stop (cli/subscription-gate.mjs): Claude Code's hooks ask
|
|
179
181
|
// here, and the answer comes from the gateway's /api/v1/self, read with this
|
|
180
182
|
// sidecar's visa and the session the hook names.
|
|
183
|
+
let highVersion = 0;
|
|
184
|
+
let relayVersion = 0;
|
|
185
|
+
let readHighVersion = 0;
|
|
186
|
+
let readRelayVersion = 0;
|
|
187
|
+
let holdOptOutWarned = false;
|
|
181
188
|
async function readSelf(session) {
|
|
189
|
+
const highAtStart = highVersion;
|
|
190
|
+
const relayAtStart = relayVersion;
|
|
182
191
|
// One deadline over the whole read, a visa mint included: past the hook's own
|
|
183
192
|
// timeout the action goes ahead with no warning. A mint cut short here is not
|
|
184
193
|
// aborted (the proxy shares it); it finishes and is cached for the next read.
|
|
@@ -201,7 +210,16 @@ export function createSidecar({
|
|
|
201
210
|
if (session) headers["x-claude-code-session-id"] = session;
|
|
202
211
|
return fetch(`${origin}${path}`, { headers, signal });
|
|
203
212
|
})]);
|
|
204
|
-
|
|
213
|
+
const answer = await Promise.race([deadline, selfAnswerState(response)]);
|
|
214
|
+
if (answer.state === "open") {
|
|
215
|
+
readHighVersion = Math.max(readHighVersion, highAtStart);
|
|
216
|
+
readRelayVersion = Math.max(readRelayVersion, relayAtStart);
|
|
217
|
+
if (answer.injection?.mode === "hold" && !reportCalls && !holdOptOutWarned) {
|
|
218
|
+
holdOptOutWarned = true;
|
|
219
|
+
warn("The injection guard's hold needs this sidecar to upload what it finds. --no-report-calls turns that off, so tools are held only for what the gateway itself saw.");
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
return answer;
|
|
205
223
|
} catch (error) {
|
|
206
224
|
return { state: "unknown", reason: error?.name === "TimeoutError" ? "the gateway did not answer in time" : (error?.message ?? "error") };
|
|
207
225
|
}
|
|
@@ -272,14 +290,42 @@ export function createSidecar({
|
|
|
272
290
|
const body = await response.json().catch(() => ({}));
|
|
273
291
|
return { status: response.status, error: body?.error, retryAfterS: Number(response.headers.get("retry-after")) };
|
|
274
292
|
}
|
|
293
|
+
const injectionSeen = new Set();
|
|
275
294
|
const uploader = reportCalls ? createCallUploader({ send: sendReportedCalls }) : null;
|
|
276
295
|
// Its decisions reach the agent's page with the reported calls (same opt-out).
|
|
277
296
|
const toolGate = createToolGate({
|
|
278
297
|
askOwner,
|
|
279
298
|
dashboardUrl: `${origin}/dashboard`,
|
|
280
299
|
onDecision: (record) => uploader?.add({ kind: "tool_decision", at: Date.now(), ...record }),
|
|
300
|
+
onHold: (record) => feed.toolHold({ at: Date.now(), ...record }),
|
|
301
|
+
refresh: async () => {
|
|
302
|
+
await stopGate.refresh();
|
|
303
|
+
return { rulesEntry: stopGate.toolRules(), injection: stopGate.injection() };
|
|
304
|
+
},
|
|
281
305
|
});
|
|
282
306
|
|
|
307
|
+
let injectionRefresh = null;
|
|
308
|
+
async function freshInjectionFor(tool) {
|
|
309
|
+
if (!heldUnderTaint(tool) || !stopGate.injectionHoldMode()) return;
|
|
310
|
+
if (injectionRefresh) return injectionRefresh;
|
|
311
|
+
if (highVersion <= readHighVersion && relayVersion <= readRelayVersion) return;
|
|
312
|
+
injectionRefresh = (async () => {
|
|
313
|
+
if (uploader && highVersion > readHighVersion) {
|
|
314
|
+
let timer;
|
|
315
|
+
try {
|
|
316
|
+
await Promise.race([
|
|
317
|
+
Promise.resolve().then(() => uploader.flush()),
|
|
318
|
+
new Promise((resolve) => { timer = setTimeout(resolve, 3_000); }),
|
|
319
|
+
]);
|
|
320
|
+
} catch {
|
|
321
|
+
// A failed upload must not prevent the read or change the opt-out.
|
|
322
|
+
} finally { clearTimeout(timer); }
|
|
323
|
+
}
|
|
324
|
+
await stopGate.refresh();
|
|
325
|
+
})();
|
|
326
|
+
try { await injectionRefresh; } finally { injectionRefresh = null; }
|
|
327
|
+
}
|
|
328
|
+
|
|
283
329
|
const relayedSessions = new Set();
|
|
284
330
|
function rememberRelayed(headers) {
|
|
285
331
|
const session = lineageOf(headers)?.session;
|
|
@@ -410,6 +456,7 @@ export function createSidecar({
|
|
|
410
456
|
}
|
|
411
457
|
let out;
|
|
412
458
|
try {
|
|
459
|
+
if (input.hook_event_name === "PreToolUse") await freshInjectionFor(input.tool_name);
|
|
413
460
|
out = await stopGate.decide(input, { note: hookNote(req.url) });
|
|
414
461
|
} catch {
|
|
415
462
|
out = {};
|
|
@@ -419,7 +466,7 @@ export function createSidecar({
|
|
|
419
466
|
if (out.continue !== false && input.hook_event_name === "PreToolUse") {
|
|
420
467
|
let tool;
|
|
421
468
|
try {
|
|
422
|
-
tool = await toolGate.decide(input, stopGate.toolRules(), hookTimeoutS(req.url));
|
|
469
|
+
tool = await toolGate.decide(input, stopGate.toolRules(), hookTimeoutS(req.url), stopGate.injection());
|
|
423
470
|
} catch {
|
|
424
471
|
tool = {};
|
|
425
472
|
}
|
|
@@ -429,6 +476,23 @@ export function createSidecar({
|
|
|
429
476
|
const body = JSON.stringify(out);
|
|
430
477
|
res.writeHead(200, { "content-type": "application/json", "content-length": Buffer.byteLength(body), "cache-control": "no-store" });
|
|
431
478
|
res.end(body);
|
|
479
|
+
// Injection tells in what the tools returned (plans/injection-guard.md §2b): after
|
|
480
|
+
// the answer is written, so the scan never delays or changes it.
|
|
481
|
+
if (input.hook_event_name === "PostToolBatch" || input.hook_event_name === "PostToolUse") {
|
|
482
|
+
setImmediate(() => {
|
|
483
|
+
try {
|
|
484
|
+
for (const event of findingsFromHook(input, { seen: injectionSeen })) {
|
|
485
|
+
if (event.severity === "high") highVersion++;
|
|
486
|
+
feed.injection(event);
|
|
487
|
+
// With the reported calls (same opt-out). The gateway records it only while
|
|
488
|
+
// the owner has the guard on, and never says which.
|
|
489
|
+
uploader?.add(event);
|
|
490
|
+
}
|
|
491
|
+
} catch {
|
|
492
|
+
// Local telemetry must never change or delay the hook answer.
|
|
493
|
+
}
|
|
494
|
+
});
|
|
495
|
+
}
|
|
432
496
|
});
|
|
433
497
|
req.on("error", () => res.destroy());
|
|
434
498
|
}
|
|
@@ -472,6 +536,13 @@ export function createSidecar({
|
|
|
472
536
|
// from a capped peek at a CLONE of the body, so the client's bytes are untouched
|
|
473
537
|
// and nothing here waits on the peek.
|
|
474
538
|
function writeResponse(res, upstream, reqHeaders, watch = null) {
|
|
539
|
+
// Also mark streamed responses on completion: a /self read while the stream
|
|
540
|
+
// was open cannot cover a finding the gateway sees later in that stream.
|
|
541
|
+
if (watch) {
|
|
542
|
+
relayVersion++;
|
|
543
|
+
res.once("finish", () => { relayVersion++; });
|
|
544
|
+
res.once("close", () => { relayVersion++; });
|
|
545
|
+
}
|
|
475
546
|
// At the headers, not at the end of the body: a streamed call whose client
|
|
476
547
|
// disconnects mid-stream still produced a receipt, and the user's record of
|
|
477
548
|
// it must not depend on how long they kept reading. With the session the call
|
|
@@ -109,6 +109,7 @@ export function createStopGate({
|
|
|
109
109
|
let agent = null;
|
|
110
110
|
// The agent's tool rules as the last answer that carried them gave them.
|
|
111
111
|
let rules = null;
|
|
112
|
+
let injectionEntry = null;
|
|
112
113
|
// The limits from the latest open answer, for the note; and each session's last note.
|
|
113
114
|
let latest = null;
|
|
114
115
|
const noted = new Map();
|
|
@@ -144,6 +145,7 @@ export function createStopGate({
|
|
|
144
145
|
answer ??= { state: "unknown", reason: "no answer" };
|
|
145
146
|
if (answer.state === "open" && answer.self) latest = { self: answer.self, at: now() };
|
|
146
147
|
if (answer.state === "open") {
|
|
148
|
+
injectionEntry = { value: answer.injection, at: now() };
|
|
147
149
|
rules = { read: answer.toolRules && typeof answer.toolRules === "object" ? answer.toolRules : { state: "none" }, at: now() };
|
|
148
150
|
}
|
|
149
151
|
if (["open", "stopped"].includes(answer.state) || (session !== null && answer.state === "session_stopped")) {
|
|
@@ -240,7 +242,21 @@ export function createStopGate({
|
|
|
240
242
|
return rules && age(rules) <= maxStaleMs ? rules : null;
|
|
241
243
|
}
|
|
242
244
|
|
|
243
|
-
|
|
245
|
+
function injection() {
|
|
246
|
+
if (!injectionEntry || injectionEntry.value === undefined) return "off";
|
|
247
|
+
if (age(injectionEntry) > maxStaleMs) return "unknown";
|
|
248
|
+
const value = injectionEntry.value;
|
|
249
|
+
if (!value || value.mode !== "hold" || value.readable !== true) return "unknown";
|
|
250
|
+
if (value.tainted_until === null) return "clear";
|
|
251
|
+
if (typeof value.tainted_until !== "string") return "unknown";
|
|
252
|
+
const until = Date.parse(value.tainted_until);
|
|
253
|
+
if (!Number.isFinite(until)) return "unknown";
|
|
254
|
+
return until > now() ? "tainted" : "clear";
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
// Keep the last known mode even after max-stale: a fresh read may recover it.
|
|
258
|
+
const injectionHoldMode = () => injectionEntry?.value?.mode === "hold";
|
|
259
|
+
return { decide, toolRules, injection, injectionHoldMode, refresh: () => ask(null) };
|
|
244
260
|
}
|
|
245
261
|
|
|
246
262
|
/**
|
|
@@ -253,6 +269,7 @@ export async function selfAnswerState(response) {
|
|
|
253
269
|
const body = await response.json().catch(() => null);
|
|
254
270
|
const toolRules = body && typeof body === "object" ? body.tool_rules : undefined;
|
|
255
271
|
const answer = toolRules && typeof toolRules === "object" ? { state: "open", toolRules } : { state: "open" };
|
|
272
|
+
if (body && typeof body === "object" && Object.hasOwn(body, "injection")) answer.injection = body.injection;
|
|
256
273
|
// The limits and the soft pause, for the agent's note; nothing else from the answer is kept.
|
|
257
274
|
if (body && typeof body === "object" && body.budget && typeof body.budget === "object") {
|
|
258
275
|
const kept = (v) => (v && typeof v === "object" ? v : null);
|