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.
package/cli/sidecar.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { randomUUID } from "node:crypto";
1
+ import { createHash, randomUUID } from "node:crypto";
2
2
  import http from "node:http";
3
3
  import net from "node:net";
4
4
  import { Readable } from "node:stream";
@@ -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, gapFromOversizedHook } 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";
@@ -57,9 +59,13 @@ const OTLP_BODY_LIMIT = 4 * 1024 * 1024;
57
59
  // counted a second time. Bounded: the oldest is forgotten first.
58
60
  const RELAYED_SESSIONS_MAX = 1000;
59
61
 
60
- // Claude Code's hook input carries the tool's input (a whole file for Write), so it
61
- // is not small; past this it is refused rather than buffered.
62
- const HOOK_BODY_LIMIT = 1024 * 1024;
62
+ // Claude Code's hook input carries the tool's input (a whole file for Write), and a
63
+ // post-tool hook carries the tool's output, so it is not small; past this it is refused
64
+ // rather than buffered. Above the scan budget (8 MB, cli/injection-sidecar.mjs), so a
65
+ // body near it is still read; past it, a post-tool body is a gap, never clean (1.7.1).
66
+ const HOOK_BODY_LIMIT = 10 * 1024 * 1024;
67
+ // How much of a refused body is kept, to see which hook sent it.
68
+ const HOOK_PEEK_BYTES = 64 * 1024;
63
69
 
64
70
  // How long Claude Code waits for the hook, as configure wrote it into the URL
65
71
  // (`?t=600`); null for a hook that does not say (a Phase 1 install).
@@ -178,7 +184,14 @@ export function createSidecar({
178
184
  // Subscription mode's Stop (cli/subscription-gate.mjs): Claude Code's hooks ask
179
185
  // here, and the answer comes from the gateway's /api/v1/self, read with this
180
186
  // sidecar's visa and the session the hook names.
187
+ let highVersion = 0;
188
+ let relayVersion = 0;
189
+ let readHighVersion = 0;
190
+ let readRelayVersion = 0;
191
+ let holdOptOutWarned = false;
181
192
  async function readSelf(session) {
193
+ const highAtStart = highVersion;
194
+ const relayAtStart = relayVersion;
182
195
  // One deadline over the whole read, a visa mint included: past the hook's own
183
196
  // timeout the action goes ahead with no warning. A mint cut short here is not
184
197
  // aborted (the proxy shares it); it finishes and is cached for the next read.
@@ -201,7 +214,16 @@ export function createSidecar({
201
214
  if (session) headers["x-claude-code-session-id"] = session;
202
215
  return fetch(`${origin}${path}`, { headers, signal });
203
216
  })]);
204
- return await Promise.race([deadline, selfAnswerState(response)]);
217
+ const answer = await Promise.race([deadline, selfAnswerState(response)]);
218
+ if (answer.state === "open") {
219
+ readHighVersion = Math.max(readHighVersion, highAtStart);
220
+ readRelayVersion = Math.max(readRelayVersion, relayAtStart);
221
+ if (answer.injection?.mode === "hold" && !reportCalls && !holdOptOutWarned) {
222
+ holdOptOutWarned = true;
223
+ 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.");
224
+ }
225
+ }
226
+ return answer;
205
227
  } catch (error) {
206
228
  return { state: "unknown", reason: error?.name === "TimeoutError" ? "the gateway did not answer in time" : (error?.message ?? "error") };
207
229
  }
@@ -272,14 +294,55 @@ export function createSidecar({
272
294
  const body = await response.json().catch(() => ({}));
273
295
  return { status: response.status, error: body?.error, retryAfterS: Number(response.headers.get("retry-after")) };
274
296
  }
297
+ // 1.7.1 F2: a self-hosted gateway is a dev server that compiles each route on its first
298
+ // request, which outlasted the hooks' short wait, so a held agent's first tools after a
299
+ // start went ahead with the warning. Asked once, after the visa works: /self as the hooks
300
+ // ask it, and the two POST routes with a GET and no credential, which loads them, asks
301
+ // the owner nothing and uploads nothing. Never throws.
302
+ const WARM_ROUTE_TIMEOUT_MS = 60_000;
303
+ async function warmRoutes() {
304
+ const touch = (path) =>
305
+ fetch(`${origin}${path}`, { method: "GET", signal: AbortSignal.timeout(WARM_ROUTE_TIMEOUT_MS) })
306
+ .then((response) => response.body?.cancel())
307
+ .catch(() => {});
308
+ await Promise.all([readSelf(null).catch(() => {}), touch(TOOL_APPROVALS_PATH), touch(CLIENT_EVENTS_PATH)]);
309
+ }
310
+ const injectionSeen = new Set();
275
311
  const uploader = reportCalls ? createCallUploader({ send: sendReportedCalls }) : null;
276
312
  // Its decisions reach the agent's page with the reported calls (same opt-out).
277
313
  const toolGate = createToolGate({
278
314
  askOwner,
279
315
  dashboardUrl: `${origin}/dashboard`,
280
316
  onDecision: (record) => uploader?.add({ kind: "tool_decision", at: Date.now(), ...record }),
317
+ onHold: (record) => feed.toolHold({ at: Date.now(), ...record }),
318
+ refresh: async () => {
319
+ await stopGate.refresh();
320
+ return { rulesEntry: stopGate.toolRules(), injection: stopGate.injection() };
321
+ },
281
322
  });
282
323
 
324
+ let injectionRefresh = null;
325
+ async function freshInjectionFor(tool) {
326
+ if (!heldUnderTaint(tool) || !stopGate.injectionHoldMode()) return;
327
+ if (injectionRefresh) return injectionRefresh;
328
+ if (highVersion <= readHighVersion && relayVersion <= readRelayVersion) return;
329
+ injectionRefresh = (async () => {
330
+ if (uploader && highVersion > readHighVersion) {
331
+ let timer;
332
+ try {
333
+ await Promise.race([
334
+ Promise.resolve().then(() => uploader.flush()),
335
+ new Promise((resolve) => { timer = setTimeout(resolve, 3_000); }),
336
+ ]);
337
+ } catch {
338
+ // A failed upload must not prevent the read or change the opt-out.
339
+ } finally { clearTimeout(timer); }
340
+ }
341
+ await stopGate.refresh();
342
+ })();
343
+ try { await injectionRefresh; } finally { injectionRefresh = null; }
344
+ }
345
+
283
346
  const relayedSessions = new Set();
284
347
  function rememberRelayed(headers) {
285
348
  const session = lineageOf(headers)?.session;
@@ -391,14 +454,34 @@ export function createSidecar({
391
454
  }
392
455
  const chunks = [];
393
456
  let size = 0;
394
- let tooBig = false;
457
+ // Past the limit: only a hash of the whole body and its start are kept.
458
+ let digest = null;
459
+ let head = "";
395
460
  req.on("data", (c) => {
396
461
  size += c.length;
397
- if (size > HOOK_BODY_LIMIT) tooBig = true;
398
- else chunks.push(c);
462
+ if (digest) return void digest.update(c);
463
+ chunks.push(c);
464
+ if (size <= HOOK_BODY_LIMIT) return;
465
+ digest = createHash("sha256");
466
+ for (const chunk of chunks) digest.update(chunk);
467
+ head = Buffer.concat(chunks).subarray(0, HOOK_PEEK_BYTES).toString("utf8");
468
+ chunks.length = 0;
399
469
  });
400
470
  req.on("end", async () => {
401
- if (tooBig) return answer(res, 413, "hook_too_large", "Hook input over 1 MB.");
471
+ if (digest) {
472
+ // Synchronous, like the scan below: the next PreToolUse already knows.
473
+ try {
474
+ const gap = gapFromOversizedHook(head, digest.digest("hex"), { seen: injectionSeen });
475
+ if (gap) {
476
+ highVersion++;
477
+ feed.injection(gap);
478
+ uploader?.add(gap);
479
+ }
480
+ } catch {
481
+ // Local telemetry must never change the hook answer.
482
+ }
483
+ return answer(res, 413, "hook_too_large", "Hook input over 10 MB.");
484
+ }
402
485
  let input;
403
486
  try {
404
487
  input = JSON.parse(Buffer.concat(chunks).toString("utf8"));
@@ -408,8 +491,29 @@ export function createSidecar({
408
491
  if (!input || typeof input !== "object" || Array.isArray(input)) {
409
492
  return answer(res, 400, "hook_not_json", "Expected Claude Code's hook input, a JSON object.");
410
493
  }
494
+ // Injection tells in what the tools returned (plans/injection-guard.md §2b). Before
495
+ // the answer and before any await (1.7.1, external review P4): the event loop runs
496
+ // nothing else meanwhile, so no PreToolUse can be decided before a finding here has
497
+ // bumped highVersion, which makes it flush the upload and re-read the taint first.
498
+ // Bounded by HOOK_BODY_LIMIT; 8 MB of hostile text scans in under half a second
499
+ // (measured 2026-10-31). Only the upload is asynchronous.
500
+ if (input.hook_event_name === "PostToolBatch" || input.hook_event_name === "PostToolUse") {
501
+ try {
502
+ for (const event of findingsFromHook(input, { seen: injectionSeen })) {
503
+ // A gap holds like a strong finding (1.7.1).
504
+ if (event.severity === "high" || event.kind === "injection_incomplete") highVersion++;
505
+ feed.injection(event);
506
+ // With the reported calls (same opt-out). The gateway records it only while
507
+ // the owner has the guard on, and never says which.
508
+ uploader?.add(event);
509
+ }
510
+ } catch {
511
+ // Local telemetry must never change the hook answer.
512
+ }
513
+ }
411
514
  let out;
412
515
  try {
516
+ if (input.hook_event_name === "PreToolUse") await freshInjectionFor(input.tool_name);
413
517
  out = await stopGate.decide(input, { note: hookNote(req.url) });
414
518
  } catch {
415
519
  out = {};
@@ -419,7 +523,7 @@ export function createSidecar({
419
523
  if (out.continue !== false && input.hook_event_name === "PreToolUse") {
420
524
  let tool;
421
525
  try {
422
- tool = await toolGate.decide(input, stopGate.toolRules(), hookTimeoutS(req.url));
526
+ tool = await toolGate.decide(input, stopGate.toolRules(), hookTimeoutS(req.url), stopGate.injection());
423
527
  } catch {
424
528
  tool = {};
425
529
  }
@@ -472,6 +576,13 @@ export function createSidecar({
472
576
  // from a capped peek at a CLONE of the body, so the client's bytes are untouched
473
577
  // and nothing here waits on the peek.
474
578
  function writeResponse(res, upstream, reqHeaders, watch = null) {
579
+ // Also mark streamed responses on completion: a /self read while the stream
580
+ // was open cannot cover a finding the gateway sees later in that stream.
581
+ if (watch) {
582
+ relayVersion++;
583
+ res.once("finish", () => { relayVersion++; });
584
+ res.once("close", () => { relayVersion++; });
585
+ }
475
586
  // At the headers, not at the end of the body: a streamed call whose client
476
587
  // disconnects mid-stream still produced a receipt, and the user's record of
477
588
  // it must not depend on how long they kept reading. With the session the call
@@ -667,7 +778,7 @@ export function createSidecar({
667
778
  });
668
779
 
669
780
  server.on("close", () => uploader?.close());
670
- return { server, ollamaServer, getVisa: visas.getVisa, runId, feed, uploader };
781
+ return { server, ollamaServer, getVisa: visas.getVisa, warmRoutes, runId, feed, uploader };
671
782
  }
672
783
 
673
784
  /**
@@ -700,7 +811,7 @@ export function startSidecar(opts) {
700
811
  onError: (e) =>
701
812
  warn(`journal: could not write ${journal.path} (${e.message}). Calls are unaffected; this run is no longer being recorded.`),
702
813
  });
703
- const { server, ollamaServer, getVisa, feed } = createSidecar({ ...opts, runId, journal });
814
+ const { server, ollamaServer, getVisa, warmRoutes, feed } = createSidecar({ ...opts, runId, journal });
704
815
  if (ollamaPort != null) {
705
816
  ollamaServer.listen(ollamaPort, host, () => {
706
817
  step(`Ollama API (local models) on http://${host}:${ollamaPort}: set OLLAMA_HOST=${host}:${ollamaPort}`);
@@ -746,6 +857,8 @@ export function startSidecar(opts) {
746
857
  if (ollamaServer.listening) ollamaServer.close();
747
858
  setTimeout(() => process.exit(1), 1000).unref();
748
859
  },
860
+ }).then((warmed) => {
861
+ if (warmed) void warmRoutes();
749
862
  });
750
863
  });
751
864
  return server;
@@ -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
- return { decide, toolRules };
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);
package/cli/tool-gate.mjs CHANGED
@@ -25,6 +25,7 @@
25
25
  //
26
26
  // Each outcome that is not a plain pass is handed to `onDecision` for the agent's
27
27
  // page: tool name, decision, rule number and wait. Never the command, path or URL.
28
+ import { underTaint } from "./injection-hold.mjs";
28
29
  import { evaluateToolRules, parseToolRules } from "./tool-rules.mjs";
29
30
 
30
31
  /** The wait ends this long before Claude Code would give up on the hook. */
@@ -46,12 +47,17 @@ function verdict(permissionDecision, reason) {
46
47
  * askOwner: (input: object, ask: { ruleIndex: number, subject: string, session: string | null, waitMs: number }) =>
47
48
  * Promise<{ state: "approved" | "denied" | "timeout" | "unavailable" | "full" | "refused" | "too_large" }>,
48
49
  * onDecision?: (record: { session: string | null, agent: string | null, tool: string, decision: string, ruleIndex: number | null, waitMs: number }) => void,
50
+ * onHold?: (record: { tool: string, outcome: string }) => void,
51
+ * refresh?: () => Promise<object | null>,
49
52
  * now?: () => number,
50
53
  * dashboardUrl?: string,
51
54
  * }} options
52
55
  */
53
- export function createToolGate({ askOwner, onDecision = () => {}, now = () => Date.now(), dashboardUrl = "" }) {
56
+ export function createToolGate({ askOwner, onDecision = () => {}, now = () => Date.now(), dashboardUrl = "", onHold = () => {}, refresh = async () => null }) {
54
57
  let warnedAt = null;
58
+ let injectionWarnedAt = null;
59
+ let needsRefresh = false;
60
+ let refreshing = null;
55
61
  const where = dashboardUrl ? ` on ${dashboardUrl}` : " on the agent's dashboard page";
56
62
  // Said with every rule's refusal: told only "the tool rules refuse this", Claude
57
63
  // Code went looking for the rule in the local PassControl config, which has none.
@@ -79,16 +85,24 @@ export function createToolGate({ askOwner, onDecision = () => {}, now = () => Da
79
85
  * @param {{ read: { state: string, document?: unknown }, at: number } | null} rulesEntry
80
86
  * The rules from the latest trusted /self read, or null.
81
87
  * @param {number | null} hookTimeoutS What the hook's URL says it waits; null when it does not say.
88
+ * @param {"off" | "clear" | "tainted" | "unknown"} injection
82
89
  */
83
- async function decide(input, rulesEntry, hookTimeoutS) {
90
+ async function decide(input, rulesEntry, hookTimeoutS, injection = "off") {
84
91
  if (input?.hook_event_name !== "PreToolUse") return {};
92
+ if (needsRefresh || refreshing) {
93
+ if (!refreshing) {
94
+ needsRefresh = false;
95
+ refreshing = Promise.resolve().then(refresh).finally(() => { refreshing = null; });
96
+ }
97
+ const fresh = await refreshing;
98
+ if (fresh) ({ rulesEntry, injection } = fresh);
99
+ }
85
100
  const read = rulesEntry?.read;
86
- if (read?.state === "none") return {};
87
101
  if (read?.state === "invalid") {
88
102
  record(input, "rules_invalid", null, 0);
89
103
  return verdict("deny", `PassControl: this agent's tool rules cannot be read here, so no tool runs until they are fixed${where}.`);
90
104
  }
91
- const parsed = read?.state === "ok" ? parseToolRules(read.document) : null;
105
+ const parsed = read?.state === "none" ? parseToolRules({ rules: [] }) : read?.state === "ok" ? parseToolRules(read.document) : null;
92
106
  if (!parsed) {
93
107
  if (warnedAt !== null && now() - warnedAt < WARN_EVERY_MS) return {};
94
108
  warnedAt = now();
@@ -99,36 +113,78 @@ export function createToolGate({ askOwner, onDecision = () => {}, now = () => Da
99
113
  return verdict("deny", `PassControl: this agent's tool rules cannot be read here, so no tool runs until they are fixed${where}.`);
100
114
  }
101
115
 
102
- const hit = evaluateToolRules(parsed, input);
103
- if (hit.effect === null) return {};
104
- const rule = `rule ${hit.ruleIndex + 1}`;
116
+ const original = evaluateToolRules(parsed, input);
117
+ const hit = injection === "tainted" ? underTaint(original, input.tool_name) : original;
118
+ const escalated = hit.reason === "injection_taint";
119
+ // `/self` says only that the agent is tainted, not why: a tell, or output not fully checked (1.7.1).
120
+ const guardText = "This tool was held by the injection guard: something the agent recently read looked like a prompt injection, or could not be fully checked.";
121
+ let warning = {};
122
+ if (injection === "unknown" && (injectionWarnedAt === null || now() - injectionWarnedAt >= WARN_EVERY_MS)) {
123
+ injectionWarnedAt = now();
124
+ warning = { systemMessage: "PassControl could not check this agent's injection guard, so this goes ahead." };
125
+ }
126
+ const withWarning = (out) => ({ ...out, ...warning });
127
+ function holdRecord(outcome) {
128
+ if (escalated) {
129
+ try { onHold({ tool: String(input.tool_name ?? "").slice(0, 128), outcome }); } catch {}
130
+ }
131
+ }
132
+ const ruleIndex = escalated ? null : hit.ruleIndex;
133
+ if (hit.effect === null) return withWarning({});
134
+ const rule = escalated ? "injection guard" : `rule ${hit.ruleIndex + 1}`;
105
135
  if (hit.effect === "deny") {
106
136
  record(input, "deny", hit.ruleIndex, 0);
107
- return verdict("deny", `PassControl: the agent's tool rules refuse this (${rule}: ${short(hit.subject)}). ${rulesLive}`);
137
+ return withWarning(verdict("deny", `PassControl: the agent's tool rules refuse this (${rule}: ${short(hit.subject)}). ${rulesLive}`));
108
138
  }
109
139
  if (hit.effect === "ask") {
110
140
  record(input, "ask", hit.ruleIndex, 0);
111
- return verdict("ask", `PassControl: the agent's tool rules ask you to confirm this (${rule}: ${short(hit.subject)}). ${rulesLive}`);
141
+ return withWarning(verdict("ask", `PassControl: the agent's tool rules ask you to confirm this (${rule}: ${short(hit.subject)}). ${rulesLive}`));
112
142
  }
113
143
 
114
144
  // ask_owner
115
145
  const waitS = hookTimeoutS === null ? 0 : Math.min(parsed.approvalWaitS, hookTimeoutS - HOOK_MARGIN_S);
146
+ if (waitS < MIN_WAIT_S && escalated) {
147
+ record(input, "owner_unavailable", null, 0);
148
+ holdRecord("unavailable");
149
+ return verdict("deny", `PassControl: ${guardText} The hook cannot wait for the owner. Run \`passcontrol configure claude-code --subscription --write\`, then try again.`);
150
+ }
116
151
  if (waitS < MIN_WAIT_S) {
117
152
  record(input, "owner_unavailable", hit.ruleIndex, 0);
118
- return verdict(
153
+ return withWarning(verdict(
119
154
  "deny",
120
155
  `PassControl: this needs the agent's owner to say yes (${rule}), and Claude Code's hook would give up before the answer. Run \`passcontrol configure claude-code --subscription --write\`, then try again.`
121
- );
156
+ ));
122
157
  }
123
158
  const started = now();
124
159
  let answer;
125
160
  try {
126
- answer = await askOwner(input, { ruleIndex: hit.ruleIndex, subject: hit.subject, session: declared(input.session_id), waitMs: waitS * 1000 });
161
+ answer = await askOwner(input, { ruleIndex, subject: escalated ? "injection guard" : hit.subject, session: declared(input.session_id), waitMs: waitS * 1000 });
127
162
  } catch {
128
163
  answer = { state: "unavailable" };
129
164
  }
130
165
  const waited = Math.max(0, now() - started);
131
- switch (answer?.state) {
166
+ if (escalated) {
167
+ const state = answer?.state;
168
+ if (state === "refused") {
169
+ // Not an owner outcome: the tool goes ahead on its own rules, so the agent's page
170
+ // gets the record those rules give (only an "ask"), never "owner unavailable".
171
+ needsRefresh = true;
172
+ holdRecord("through");
173
+ if (original.effect === "ask") {
174
+ record(input, "ask", original.ruleIndex, 0);
175
+ return verdict("ask", `PassControl: ${guardText} The gateway now sees no taint. The tool rules still ask you to confirm this (rule ${original.ruleIndex + 1}: ${short(original.subject)}). ${rulesLive}`);
176
+ }
177
+ return { systemMessage: `PassControl: ${guardText} The gateway now sees no taint, so this goes ahead.` };
178
+ }
179
+ const outcome = ["approved", "denied", "timeout"].includes(state) ? state : "unavailable";
180
+ holdRecord(outcome);
181
+ record(input, `owner_${outcome}`, null, waited);
182
+ if (outcome === "approved") return { systemMessage: `PassControl: ${guardText} The agent's owner approved it.` };
183
+ const ending = outcome === "denied" ? "The agent's owner said no." : outcome === "timeout" ? `The agent's owner did not answer within ${waitS} s, so this was not run.` : "The owner could not be asked, so this was not run.";
184
+ return verdict("deny", `PassControl: ${guardText} ${ending}`);
185
+ }
186
+ function ruleAnswer() {
187
+ switch (answer?.state) {
132
188
  case "approved":
133
189
  record(input, "owner_approved", hit.ruleIndex, waited);
134
190
  return {};
@@ -150,7 +206,9 @@ export function createToolGate({ askOwner, onDecision = () => {}, now = () => Da
150
206
  default:
151
207
  record(input, "owner_unavailable", hit.ruleIndex, waited);
152
208
  return verdict("deny", `PassControl: this needs the agent's owner to say yes (${rule}), and they could not be reached, so it was not run.`);
209
+ }
153
210
  }
211
+ return withWarning(ruleAnswer());
154
212
  }
155
213
 
156
214
  return { decide };
@@ -21,6 +21,8 @@
21
21
  // cannot keep up is dropped rather than buffered for, and nothing on the proxy
22
22
  // path waits on a subscriber.
23
23
 
24
+ import { INJECTION_FAMILIES } from "./injection-scan.mjs";
25
+
24
26
  export const WATCH_PATH = "/_passcontrol/watch";
25
27
  /** Paths under this prefix are the sidecar's own and are never forwarded. */
26
28
  export const LOCAL_PREFIX = "/_passcontrol/";
@@ -270,6 +272,41 @@ export function createWatchFeed({ runId, capacity = 200, maxSubscribers = 8, ena
270
272
  }
271
273
  }
272
274
 
275
+ /** A local scan saw a tell; this says nothing about server recording. */
276
+ function injection(event) {
277
+ try {
278
+ const families = INJECTION_FAMILIES.filter((f) => Array.isArray(event.families) && event.families.includes(f));
279
+ if (!families.length) return;
280
+ const record = {
281
+ type: "injection_finding", seq: ++seq,
282
+ at: Number.isFinite(event.at) ? event.at : now(), source: "tool_result",
283
+ tool: held(/^[A-Za-z0-9_.-]{1,128}$/, event.tool), families,
284
+ };
285
+ remember(record);
286
+ broadcast(record);
287
+ } catch {
288
+ // Like calls, findings are best-effort metadata only.
289
+ }
290
+ }
291
+
292
+ /**
293
+ * One tool the injection guard held (Phase 2): tool name and outcome only, never
294
+ * its input. Not a call, so the board does not count it. Never throws.
295
+ */
296
+ function toolHold(event) {
297
+ try {
298
+ if (!["approved", "denied", "timeout", "unavailable", "through"].includes(event?.outcome)) return;
299
+ const record = {
300
+ type: "tool_hold", seq: ++seq,
301
+ at: Number.isFinite(event.at) ? event.at : now(),
302
+ tool: held(/^[A-Za-z0-9_.-]{1,128}$/, event.tool),
303
+ outcome: event.outcome,
304
+ };
305
+ remember(record);
306
+ broadcast(record);
307
+ } catch {}
308
+ }
309
+
273
310
  /**
274
311
  * The latest usage window, already held to its shape by the caller. Replaces the
275
312
  * last one and tells every board. Never throws.
@@ -335,6 +372,8 @@ export function createWatchFeed({ runId, capacity = 200, maxSubscribers = 8, ena
335
372
  begin,
336
373
  record,
337
374
  report,
375
+ injection,
376
+ toolHold,
338
377
  setWindow,
339
378
  window: () => usageWindow,
340
379
  serve,
package/cli/watch.mjs CHANGED
@@ -16,6 +16,7 @@
16
16
  // fields are held to the feed's own patterns on arrival, and every cell is stripped
17
17
  // of control characters again before it is drawn.
18
18
  import http from "node:http";
19
+ import { INJECTION_FAMILIES } from "./injection-scan.mjs";
19
20
  import { formatUsd, limitReached, panelRows, paused } from "./budget-format.mjs";
20
21
  import { WATCH_PATH } from "./watch-feed.mjs";
21
22
  import { heldUsageWindow, resetTime, usageWindowText } from "./usage-window.mjs";
@@ -141,6 +142,29 @@ export function applyEvent(state, event) {
141
142
  state.feed = { state: "live" };
142
143
  return state;
143
144
  }
145
+ if (event.type === "tool_hold") {
146
+ if (!Number.isInteger(event.seq) || event.seq < 1 || !["approved", "denied", "timeout", "unavailable", "through"].includes(event.outcome)) return state;
147
+ const row = { type: "tool_hold", seq: event.seq, at: count(event.at), tool: held(/^[A-Za-z0-9_.-]{1,128}$/, event.tool), outcome: event.outcome };
148
+ const existing = state.rows.findIndex((r) => r.seq === row.seq);
149
+ if (existing === -1) state.rows.push(row);
150
+ else state.rows[existing] = row;
151
+ if (state.rows.length > MAX_ROWS) state.rows.splice(0, state.rows.length - MAX_ROWS);
152
+ return state;
153
+ }
154
+ if (event.type === "injection_finding") {
155
+ if (!Number.isInteger(event.seq) || event.seq < 1 || event.source !== "tool_result") return state;
156
+ const families = INJECTION_FAMILIES.filter((f) => Array.isArray(event.families) && event.families.includes(f));
157
+ if (!families.length) return state;
158
+ const row = {
159
+ type: "injection_finding", seq: event.seq, at: count(event.at), source: "tool_result",
160
+ tool: held(/^[A-Za-z0-9_.-]{1,128}$/, event.tool), families,
161
+ };
162
+ const existing = state.rows.findIndex((r) => r.seq === row.seq);
163
+ if (existing === -1) state.rows.push(row);
164
+ else state.rows[existing] = row;
165
+ if (state.rows.length > MAX_ROWS) state.rows.splice(0, state.rows.length - MAX_ROWS);
166
+ return state;
167
+ }
144
168
  if (event.type === "call") {
145
169
  if (!Number.isInteger(event.seq) || event.seq < 1) return state;
146
170
  const row = {
@@ -275,6 +299,17 @@ const BAR_STYLE = { boarded: "green", denied: "red", error: "yellow" };
275
299
 
276
300
  /** One board row, `width` wide at most. */
277
301
  function rowLine(row, cols, { run, now, formatTime, color }) {
302
+ if (row.type === "tool_hold") {
303
+ const tool = held(/^[A-Za-z0-9_.-]{1,128}$/, row.tool) ?? "—";
304
+ return paint(color, "yellow", clean(`${fit(row.at !== null ? formatTime(row.at) : "", cols.time)} HELD · injection guard · ${tool} · ${row.outcome}`));
305
+ }
306
+ if (row.type === "injection_finding") {
307
+ const families = INJECTION_FAMILIES.filter((f) => Array.isArray(row.families) && row.families.includes(f));
308
+ const tool = held(/^[A-Za-z0-9_.-]{1,128}$/, row.tool) ?? "—";
309
+ // The local scan saw it; whether the gateway recorded it is the owner's policy, unknown here.
310
+ const text = `${fit(row.at ? formatTime(row.at) : "", cols.time)} INJECTION? · tool_result · ${tool} · ${families.join("+")}`;
311
+ return paint(color, "yellow", clean(text));
312
+ }
278
313
  const cells = [fit(row.at !== null ? formatTime(row.at) : "", cols.time)];
279
314
  if (cols.withSession) cells.push(fit(sessionText(row, run), cols.session));
280
315
  cells.push(agentText(row, cols.agent));
@@ -396,9 +431,10 @@ export function renderBoard(state, { width, height, port, now = Date.now(), form
396
431
  const cols = columns(w);
397
432
  const rows = state.rows;
398
433
  const tally = { boarded: 0, denied: 0, error: 0, seen: 0 };
399
- for (const r of rows) tally[r.outcome] += 1;
400
- const counts = rows.length
401
- ? `${rows.length} call${rows.length === 1 ? "" : "s"}: ${tally.seen ? `${tally.seen} seen, ` : ""}${tally.boarded} boarded, ${tally.denied} denied${tally.error ? `, ${tally.error} error` : ""}`
434
+ const calls = rows.filter((r) => r.type !== "injection_finding" && r.type !== "tool_hold");
435
+ for (const r of calls) tally[r.outcome] += 1;
436
+ const counts = calls.length
437
+ ? `${calls.length} call${calls.length === 1 ? "" : "s"}: ${tally.seen ? `${tally.seen} seen, ` : ""}${tally.boarded} boarded, ${tally.denied} denied${tally.error ? `, ${tally.error} error` : ""}`
402
438
  : "no calls yet";
403
439
  const lines = [
404
440
  `${paint(color, "bold", "PassControl watch")} · sidecar :${port} · ${feedText(state.feed, port)} · ${counts}`,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "passcontrol",
3
- "version": "1.6.0",
3
+ "version": "1.7.1",
4
4
  "description": "Identity, scope and budget controls for AI agents while provider keys stay server-side.",
5
5
  "license": "BUSL-1.1",
6
6
  "homepage": "https://passcontrol.vertias.eu",
@@ -45,6 +45,6 @@
45
45
  "@noble/curves": "^1.6.0",
46
46
  "@noble/hashes": "^1.5.0",
47
47
  "jose": "^5.9.3",
48
- "zod": "^3.25.76"
48
+ "zod": "^4.6.7"
49
49
  }
50
50
  }
package/sdk/verify.d.ts CHANGED
@@ -120,6 +120,19 @@ export interface ReceiptClaims {
120
120
  * the earlier provider refused before doing any work.
121
121
  */
122
122
  why?: string;
123
+ /**
124
+ * Present only when the issuing gateway's injection guard flagged tool output in
125
+ * this call's request: the detector, how many blocks, and their kinds (for example
126
+ * `instruction_override`). Kinds only, never the text. A tell is a hint, not proof.
127
+ *
128
+ * Optional, and `ver` stays where it was: a verifier that predates it ignores it.
129
+ * Treat `f` as open-ended strings: a newer detector may add kinds.
130
+ */
131
+ inj?: {
132
+ d: string;
133
+ n: number;
134
+ f: string[];
135
+ };
123
136
  ver: number;
124
137
  [claim: string]: unknown;
125
138
  }