passcontrol 1.7.0 → 1.7.2

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.
@@ -3018,7 +3018,7 @@ function configureCodexSubscription(opts = {}) {
3018
3018
  }
3019
3019
  step(`Start the sidecar before Codex: ${cliCommand(port === 8788 ? "sidecar" : `sidecar --port ${port}`)}`);
3020
3020
  step("Your ChatGPT login stays between Codex and OpenAI. PassControl never sees it or sits in the path.");
3021
- step("What Codex's tools return is also scanned on this machine for the injection guard (the PostToolUse hook). That hook never blocks a tool or changes what it returned.");
3021
+ step("For the injection guard, the tool output Codex hands its PostToolUse hook is also checked on this machine; some built-in or hosted tools may not hand theirs over. That hook never blocks a tool or changes what it returned.");
3022
3022
  step("What it does: a suspended agent, or the kill switch, blocks the next prompt and refuses tools. The agent's tool rules refuse what they deny; an \"ask the owner\" rule waits for the owner's answer.");
3023
3023
  step("What it cannot do, plainly:");
3024
3024
  step(" Codex has no strict hook mode. If the sidecar is not running, or a hook fails, Codex goes ahead (with a warning when the sidecar is down).");
@@ -41,6 +41,7 @@ const newKey = () => `evt_${randomBytes(16).toString("base64url")}`;
41
41
  function toWire(event, key) {
42
42
  if (event.kind === "tool_decision") return toolDecisionWire(event, key);
43
43
  if (event.kind === "injection_finding") return injectionFindingWire(event, key);
44
+ if (event.kind === "injection_incomplete") return injectionIncompleteWire(event, key);
44
45
  const wire = {
45
46
  key,
46
47
  kind: event.kind === "api_error" ? "model_error" : "model_call",
@@ -97,6 +98,25 @@ function injectionFindingWire(event, key) {
97
98
  return wire;
98
99
  }
99
100
 
101
+ // What the sidecar could not fully check (1.7.1): why, where, and a hash over what went
102
+ // unread. No families: nothing was found, because not all of it was read.
103
+ function injectionIncompleteWire(event, key) {
104
+ const wire = {
105
+ key,
106
+ kind: "injection_incomplete",
107
+ at: event.at,
108
+ source: event.source,
109
+ path: event.path,
110
+ tool: event.tool,
111
+ gap: event.gap,
112
+ detector: event.detector,
113
+ normalization_version: event.normalization_version,
114
+ block_sha256: event.block_sha256,
115
+ };
116
+ for (const name of Object.keys(wire)) if (wire[name] === null || wire[name] === undefined) delete wire[name];
117
+ return wire;
118
+ }
119
+
100
120
  /**
101
121
  * @param {{
102
122
  * send: (events: object[]) => Promise<{ status: number, error?: string, retryAfterS?: number }>,
@@ -1,8 +1,11 @@
1
1
  // Local, best-effort tool-result scan. Only fixed metadata and a hash leave here.
2
- import { createHash } from "node:crypto";
2
+ import { createHash, randomBytes } from "node:crypto";
3
3
  import { scanText, INJECTION_DETECTOR, INJECTION_NORMALIZATION, INJECTION_FAMILIES } from "./injection-scan.mjs";
4
4
 
5
- const MAX_LEAF_BYTES = 1024 * 1024;
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;
6
9
  const MAX_FINDINGS = 20;
7
10
  const MAX_SEEN = 1000;
8
11
  const PATH = /^[A-Za-z0-9_.\[\]?-]{1,512}$/;
@@ -33,13 +36,29 @@ function* stringLeaves(value, path) {
33
36
  }
34
37
  }
35
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
+
36
53
  /** `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.
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.
39
56
  */
40
57
  export function findingsFromHook(input, { seen = new Set(), now = Date.now, scan = scanText } = {}) {
41
58
  const events = [];
42
59
  const found = new Set();
60
+ const unread = { too_large: [], scan_failed: [] };
61
+ let budget = HOOK_SCAN_BUDGET;
43
62
  try {
44
63
  let calls;
45
64
  if (input?.hook_event_name === "PostToolBatch" && Array.isArray(input.tool_calls)) {
@@ -50,29 +69,82 @@ export function findingsFromHook(input, { seen = new Set(), now = Date.now, scan
50
69
  const field = ["tool_response", "tool_output", "output"].find((key) => input[key] != null);
51
70
  calls = field ? [[input, input[field], field]] : [];
52
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).
53
74
  for (const [call, response, root] of calls) {
54
- if (events.length >= MAX_FINDINGS) break;
75
+ const tool = typeof call.tool_name === "string" && TOOL.test(call.tool_name) ? call.tool_name : undefined;
55
76
  for (const [text, path] of stringLeaves(response, root)) {
56
- if (Buffer.byteLength(text, "utf8") > MAX_LEAF_BYTES) continue;
57
77
  const hash = createHash("sha256").update(text, "utf8").digest("hex");
58
78
  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));
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
+ }
61
94
  if (!families.length) continue;
62
95
  events.push({
63
96
  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",
97
+ ...(tool ? { tool } : {}),
98
+ families, severity,
66
99
  detector: INJECTION_DETECTOR, normalization_version: INJECTION_NORMALIZATION, block_sha256: hash,
67
100
  });
68
101
  found.add(hash);
69
- if (events.length >= MAX_FINDINGS) break;
70
102
  }
71
103
  }
72
- for (const hash of found) seen.add(hash);
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);
73
145
  while (seen.size > MAX_SEEN) seen.delete(seen.values().next().value);
74
- return events;
146
+ return event;
75
147
  } catch {
76
- return [];
148
+ return null;
77
149
  }
78
150
  }
@@ -96,7 +96,7 @@ const NOT_IN_A_HOSTNAME = /[\s/\\@?#]/;
96
96
  * `api.anthropic.com`, so a string comparison that treats them as different
97
97
  * hosts is a one-character bypass of the provider refusal below.
98
98
  */
99
- function normalizeHostname(value) {
99
+ export function normalizeHostname(value) {
100
100
  let host = String(value ?? "").trim().toLowerCase();
101
101
  if (host.startsWith("[") && host.endsWith("]")) host = host.slice(1, -1);
102
102
  if (host.endsWith(".")) host = host.slice(0, -1);
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";
@@ -8,8 +8,8 @@ import { createVisaClient } from "./visa-client.mjs";
8
8
  import { declaredLineage, declaredSession } from "./declared-session.mjs";
9
9
  import { defaultJournalDir, openJournal } from "./journal.mjs";
10
10
  import { heldUnderTaint } from "./injection-hold.mjs";
11
- import { findingsFromHook } from "./injection-sidecar.mjs";
12
- import { answer, createWatchFeed, isNotACall, isLocalCaller, LOCAL_PREFIX, peekText, providerOf, refusalCode, requestModel } from "./watch-feed.mjs";
11
+ import { findingsFromHook, gapFromOversizedHook } from "./injection-sidecar.mjs";
12
+ import { answer, createWatchFeed, hostIsThisListener, isNotACall, isLocalCaller, LOCAL_PREFIX, peekText, providerOf, refusalCode, requestModel } from "./watch-feed.mjs";
13
13
  import { createStopGate, HOOK_PATH, SELF_READ_TIMEOUT_MS, selfAnswerState } from "./subscription-gate.mjs";
14
14
  import { createToolGate } from "./tool-gate.mjs";
15
15
  import { OTLP_LOGS_PATH, readClaudeCodeEvents } from "./otlp-logs.mjs";
@@ -59,9 +59,13 @@ const OTLP_BODY_LIMIT = 4 * 1024 * 1024;
59
59
  // counted a second time. Bounded: the oldest is forgotten first.
60
60
  const RELAYED_SESSIONS_MAX = 1000;
61
61
 
62
- // Claude Code's hook input carries the tool's input (a whole file for Write), so it
63
- // is not small; past this it is refused rather than buffered.
64
- 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;
65
69
 
66
70
  // How long Claude Code waits for the hook, as configure wrote it into the URL
67
71
  // (`?t=600`); null for a hook that does not say (a Phase 1 install).
@@ -208,7 +212,7 @@ export function createSidecar({
208
212
  "accept-encoding": "identity",
209
213
  };
210
214
  if (session) headers["x-claude-code-session-id"] = session;
211
- return fetch(`${origin}${path}`, { headers, signal });
215
+ return fetch(`${origin}${path}`, { headers, signal, redirect: "manual" });
212
216
  })]);
213
217
  const answer = await Promise.race([deadline, selfAnswerState(response)]);
214
218
  if (answer.state === "open") {
@@ -249,6 +253,7 @@ export function createSidecar({
249
253
  if (session) headers["x-claude-code-session-id"] = session;
250
254
  return fetch(`${origin}${TOOL_APPROVALS_PATH}`, {
251
255
  method: "POST",
256
+ redirect: "manual",
252
257
  headers,
253
258
  body,
254
259
  signal: AbortSignal.timeout(Math.min(APPROVAL_REQUEST_TIMEOUT_MS, Math.max(1_000, deadline - Date.now()))),
@@ -276,6 +281,7 @@ export function createSidecar({
276
281
  const response = await visas.fetchWithVisa((visa) =>
277
282
  fetch(`${origin}${CLIENT_EVENTS_PATH}`, {
278
283
  method: "POST",
284
+ redirect: "manual",
279
285
  headers: {
280
286
  "content-type": "application/json",
281
287
  authorization: `Bearer ${visa}`,
@@ -290,6 +296,19 @@ export function createSidecar({
290
296
  const body = await response.json().catch(() => ({}));
291
297
  return { status: response.status, error: body?.error, retryAfterS: Number(response.headers.get("retry-after")) };
292
298
  }
299
+ // 1.7.1 F2: a self-hosted gateway is a dev server that compiles each route on its first
300
+ // request, which outlasted the hooks' short wait, so a held agent's first tools after a
301
+ // start went ahead with the warning. Asked once, after the visa works: /self as the hooks
302
+ // ask it, and the two POST routes with a GET and no credential, which loads them, asks
303
+ // the owner nothing and uploads nothing. Never throws.
304
+ const WARM_ROUTE_TIMEOUT_MS = 60_000;
305
+ async function warmRoutes() {
306
+ const touch = (path) =>
307
+ fetch(`${origin}${path}`, { method: "GET", signal: AbortSignal.timeout(WARM_ROUTE_TIMEOUT_MS) })
308
+ .then((response) => response.body?.cancel())
309
+ .catch(() => {});
310
+ await Promise.all([readSelf(null).catch(() => {}), touch(TOOL_APPROVALS_PATH), touch(CLIENT_EVENTS_PATH)]);
311
+ }
293
312
  const injectionSeen = new Set();
294
313
  const uploader = reportCalls ? createCallUploader({ send: sendReportedCalls }) : null;
295
314
  // Its decisions reach the agent's page with the reported calls (same opt-out).
@@ -437,14 +456,34 @@ export function createSidecar({
437
456
  }
438
457
  const chunks = [];
439
458
  let size = 0;
440
- let tooBig = false;
459
+ // Past the limit: only a hash of the whole body and its start are kept.
460
+ let digest = null;
461
+ let head = "";
441
462
  req.on("data", (c) => {
442
463
  size += c.length;
443
- if (size > HOOK_BODY_LIMIT) tooBig = true;
444
- else chunks.push(c);
464
+ if (digest) return void digest.update(c);
465
+ chunks.push(c);
466
+ if (size <= HOOK_BODY_LIMIT) return;
467
+ digest = createHash("sha256");
468
+ for (const chunk of chunks) digest.update(chunk);
469
+ head = Buffer.concat(chunks).subarray(0, HOOK_PEEK_BYTES).toString("utf8");
470
+ chunks.length = 0;
445
471
  });
446
472
  req.on("end", async () => {
447
- if (tooBig) return answer(res, 413, "hook_too_large", "Hook input over 1 MB.");
473
+ if (digest) {
474
+ // Synchronous, like the scan below: the next PreToolUse already knows.
475
+ try {
476
+ const gap = gapFromOversizedHook(head, digest.digest("hex"), { seen: injectionSeen });
477
+ if (gap) {
478
+ highVersion++;
479
+ feed.injection(gap);
480
+ uploader?.add(gap);
481
+ }
482
+ } catch {
483
+ // Local telemetry must never change the hook answer.
484
+ }
485
+ return answer(res, 413, "hook_too_large", "Hook input over 10 MB.");
486
+ }
448
487
  let input;
449
488
  try {
450
489
  input = JSON.parse(Buffer.concat(chunks).toString("utf8"));
@@ -454,6 +493,26 @@ export function createSidecar({
454
493
  if (!input || typeof input !== "object" || Array.isArray(input)) {
455
494
  return answer(res, 400, "hook_not_json", "Expected Claude Code's hook input, a JSON object.");
456
495
  }
496
+ // Injection tells in what the tools returned (plans/injection-guard.md §2b). Before
497
+ // the answer and before any await (1.7.1, external review P4): the event loop runs
498
+ // nothing else meanwhile, so no PreToolUse can be decided before a finding here has
499
+ // bumped highVersion, which makes it flush the upload and re-read the taint first.
500
+ // Bounded by HOOK_BODY_LIMIT; 8 MB of hostile text scans in under half a second
501
+ // (measured 2026-10-31). Only the upload is asynchronous.
502
+ if (input.hook_event_name === "PostToolBatch" || input.hook_event_name === "PostToolUse") {
503
+ try {
504
+ for (const event of findingsFromHook(input, { seen: injectionSeen })) {
505
+ // A gap holds like a strong finding (1.7.1).
506
+ if (event.severity === "high" || event.kind === "injection_incomplete") highVersion++;
507
+ feed.injection(event);
508
+ // With the reported calls (same opt-out). The gateway records it only while
509
+ // the owner has the guard on, and never says which.
510
+ uploader?.add(event);
511
+ }
512
+ } catch {
513
+ // Local telemetry must never change the hook answer.
514
+ }
515
+ }
457
516
  let out;
458
517
  try {
459
518
  if (input.hook_event_name === "PreToolUse") await freshInjectionFor(input.tool_name);
@@ -466,7 +525,13 @@ export function createSidecar({
466
525
  if (out.continue !== false && input.hook_event_name === "PreToolUse") {
467
526
  let tool;
468
527
  try {
469
- tool = await toolGate.decide(input, stopGate.toolRules(), hookTimeoutS(req.url), stopGate.injection());
528
+ // A strong local finding the gateway has not yet been read after (the read
529
+ // just failed) puts a held tool to the gateway's own taint, whatever the cached
530
+ // "clear" says: an agent that floods /self straight after reading an injection
531
+ // must not outrun its taint (cloud review 2026-11-03, SC-B). The gateway then
532
+ // decides: no taint there answers `not_ask_owner`, and the tool goes.
533
+ const unconfirmed = stopGate.injectionHoldMode() && heldUnderTaint(input.tool_name) && highVersion > readHighVersion;
534
+ tool = await toolGate.decide(input, stopGate.toolRules(), hookTimeoutS(req.url), unconfirmed ? "tainted" : stopGate.injection());
470
535
  } catch {
471
536
  tool = {};
472
537
  }
@@ -476,23 +541,6 @@ export function createSidecar({
476
541
  const body = JSON.stringify(out);
477
542
  res.writeHead(200, { "content-type": "application/json", "content-length": Buffer.byteLength(body), "cache-control": "no-store" });
478
543
  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
- }
496
544
  });
497
545
  req.on("error", () => res.destroy());
498
546
  }
@@ -521,7 +569,8 @@ export function createSidecar({
521
569
  headers["x-passcontrol-run"] = runId;
522
570
  headers["x-passcontrol-proof"] = visas.createProof(visa, req.method, new URL(path, origin));
523
571
  headers["accept-encoding"] = "identity";
524
- return fetch(`${origin}${path}`, { method: req.method, headers, body: body ?? undefined });
572
+ // Hand redirects to the agent; never replay the visa, proof or body at Location.
573
+ return fetch(`${origin}${path}`, { method: req.method, headers, body: body ?? undefined, redirect: "manual" });
525
574
  }
526
575
 
527
576
  // A service call's pagination `link` and same-origin `location` name the
@@ -614,7 +663,32 @@ export function createSidecar({
614
663
  }
615
664
  }
616
665
 
666
+ // A proxied call carries this run's visa, so a web page must never get one
667
+ // (cloud review 2026-11-03, SC-A). Browsers mark what they send: an Origin on a
668
+ // cross-origin or non-GET request, and Sec-Fetch-Site on every request
669
+ // (Chrome, Firefox, Safari 16.4+). Agent clients send neither. Node's own fetch
670
+ // does send `sec-fetch-mode: cors`, so that header proves nothing and is not read.
671
+ // A DNS-rebound page sends no Origin, but its Host names the attacker's domain:
672
+ // an origin-form request on a loopback bind must name this listener exactly. A
673
+ // forward-proxy request (absolute form) names its target and goes to the classifier;
674
+ // a page cannot send one. Off loopback (an explicit opt-in) the Host is whatever the
675
+ // network calls this machine, so only the browser check applies there.
676
+ const checksHost = isLoopbackBindHost(host);
677
+ function refuseBrowserCaller(req, res, port) {
678
+ const browser = req.headers.origin !== undefined || req.headers["sec-fetch-site"] !== undefined;
679
+ const rebound = checksHost && String(req.url ?? "").startsWith("/") && !hostIsThisListener(req.headers.host, port);
680
+ if (!browser && !rebound) return false;
681
+ req.resume();
682
+ if (browser) {
683
+ answer(res, 403, "sidecar_browser_refused", "The PassControl sidecar serves agents on this machine, not web pages.");
684
+ } else {
685
+ answer(res, 403, "sidecar_host_refused", `Address the sidecar as 127.0.0.1:${port} or localhost:${port}.`);
686
+ }
687
+ return true;
688
+ }
689
+
617
690
  const server = http.createServer(async (req, res) => {
691
+ if (refuseBrowserCaller(req, res, server.address()?.port)) return;
618
692
  // The sidecar's own paths: answered here, never forwarded with a visa.
619
693
  if (String(req.url ?? "").startsWith(LOCAL_PREFIX)) {
620
694
  const localPath = String(req.url).split("?")[0];
@@ -662,6 +736,7 @@ export function createSidecar({
662
736
  // is not answered here: it goes to the gateway as `/api/version`, so an app
663
737
  // sees the gateway's real answer, including a refusal where `local` is off.
664
738
  const ollamaServer = http.createServer(async (req, res) => {
739
+ if (refuseBrowserCaller(req, res, ollamaServer.address()?.port)) return;
665
740
  if (!String(req.url ?? "").startsWith("/")) {
666
741
  req.resume();
667
742
  res.writeHead(400, { "content-type": "application/json" });
@@ -738,7 +813,7 @@ export function createSidecar({
738
813
  });
739
814
 
740
815
  server.on("close", () => uploader?.close());
741
- return { server, ollamaServer, getVisa: visas.getVisa, runId, feed, uploader };
816
+ return { server, ollamaServer, getVisa: visas.getVisa, warmRoutes, runId, feed, uploader };
742
817
  }
743
818
 
744
819
  /**
@@ -771,7 +846,7 @@ export function startSidecar(opts) {
771
846
  onError: (e) =>
772
847
  warn(`journal: could not write ${journal.path} (${e.message}). Calls are unaffected; this run is no longer being recorded.`),
773
848
  });
774
- const { server, ollamaServer, getVisa, feed } = createSidecar({ ...opts, runId, journal });
849
+ const { server, ollamaServer, getVisa, warmRoutes, feed } = createSidecar({ ...opts, runId, journal });
775
850
  if (ollamaPort != null) {
776
851
  ollamaServer.listen(ollamaPort, host, () => {
777
852
  step(`Ollama API (local models) on http://${host}:${ollamaPort}: set OLLAMA_HOST=${host}:${ollamaPort}`);
@@ -817,6 +892,8 @@ export function startSidecar(opts) {
817
892
  if (ollamaServer.listening) ollamaServer.close();
818
893
  setTimeout(() => process.exit(1), 1000).unref();
819
894
  },
895
+ }).then((warmed) => {
896
+ if (warmed) void warmRoutes();
820
897
  });
821
898
  });
822
899
  return server;
@@ -237,21 +237,35 @@ export function createStopGate({
237
237
  return warnOnce(session ?? "", reason ?? "no answer");
238
238
  }
239
239
 
240
- /** The tool rules from the latest answer, or null once they are older than `maxStaleMs`. */
240
+ /**
241
+ * The tool rules from the latest answer, however old; null only before the first.
242
+ *
243
+ * They used to lapse after `maxStaleMs`, and lapsed rules let every tool through. A
244
+ * read fails when /self's own rate limit is spent, which anything on the machine can
245
+ * do through the sidecar, so "the reads fail" switched the rules off on demand (cloud
246
+ * review 2026-11-03, SC-B). The last rules the gateway gave stay in force until it
247
+ * gives others (owner, 2026-11-04: option 1). Stops are not kept this way: those are
248
+ * the gateway's to enforce, and it does, ahead of the rate limit.
249
+ */
241
250
  function toolRules() {
242
- return rules && age(rules) <= maxStaleMs ? rules : null;
251
+ return rules;
243
252
  }
244
253
 
245
254
  function injection() {
246
255
  if (!injectionEntry || injectionEntry.value === undefined) return "off";
247
- if (age(injectionEntry) > maxStaleMs) return "unknown";
248
256
  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";
257
+ let state = "unknown";
258
+ if (value && value.mode === "hold" && value.readable === true) {
259
+ if (value.tainted_until === null) state = "clear";
260
+ else if (typeof value.tainted_until === "string") {
261
+ const until = Date.parse(value.tainted_until);
262
+ if (Number.isFinite(until)) state = until > now() ? "tainted" : "clear";
263
+ }
264
+ }
265
+ // A taint the gateway named holds until the end it named, read or no read (SC-B,
266
+ // as above). Any other state is only as good as its age.
267
+ if (age(injectionEntry) > maxStaleMs && state !== "tainted") return "unknown";
268
+ return state;
255
269
  }
256
270
 
257
271
  // Keep the last known mode even after max-stale: a fresh read may recover it.
package/cli/tool-gate.mjs CHANGED
@@ -116,7 +116,8 @@ export function createToolGate({ askOwner, onDecision = () => {}, now = () => Da
116
116
  const original = evaluateToolRules(parsed, input);
117
117
  const hit = injection === "tainted" ? underTaint(original, input.tool_name) : original;
118
118
  const escalated = hit.reason === "injection_taint";
119
- const guardText = "This tool was held by the injection guard because the agent recently read something that looked like a prompt injection.";
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.";
120
121
  let warning = {};
121
122
  if (injection === "unknown" && (injectionWarnedAt === null || now() - injectionWarnedAt >= WARN_EVERY_MS)) {
122
123
  injectionWarnedAt = now();
@@ -25,4 +25,8 @@ export const TOOL_RULE_LIMITS: {
25
25
  };
26
26
  export function globMatch(pattern: string, text: string): boolean;
27
27
  export function parseToolRules(value: unknown): ParsedToolRules;
28
- export function evaluateToolRules(parsed: { rules: ToolRule[] }, input: ToolRuleInput): ToolRuleVerdict;
28
+ export function evaluateToolRules(
29
+ parsed: { rules: ToolRule[] },
30
+ input: ToolRuleInput,
31
+ options?: { platform?: string; caseless?: boolean }
32
+ ): ToolRuleVerdict;
@@ -25,6 +25,8 @@
25
25
  // Honest limit: these are guard rails for the owner's own sessions. `sh -c`, an alias,
26
26
  // a script file or a different tool gets round a command rule.
27
27
 
28
+ import { normalizeHostname } from "./proxy-policy.mjs";
29
+
28
30
  export const TOOL_RULE_EFFECTS = ["deny", "ask_owner", "ask"];
29
31
  const STRICTNESS = { deny: 3, ask_owner: 2, ask: 1 };
30
32
 
@@ -144,10 +146,17 @@ function normalisePath(raw) {
144
146
  }
145
147
 
146
148
  function commandPieces(command) {
149
+ // Cheap shell forms only, not a Bash parser: quoting, escapes, wrappers and
150
+ // program-specific options can still evade these guard rails.
147
151
  return command
148
- .split(/&&|\|\||[;|\n]/)
152
+ .split(/&&|\|\||\$\(|[;&|\n()`]/)
149
153
  .map((piece) => piece.trim())
150
- .filter(Boolean);
154
+ .filter(Boolean)
155
+ .flatMap((piece) => {
156
+ const stripped = piece.replace(/^(?:[A-Za-z_][A-Za-z0-9_]*=(?:'[^']*'|"[^"]*"|[^\s'"]*)\s+)+/, "");
157
+ return stripped === piece ? [piece] : [piece, stripped];
158
+ })
159
+ .map((piece) => piece.replace(/\s+/g, " "));
151
160
  }
152
161
 
153
162
  function toolMatches(pattern, name) {
@@ -161,14 +170,22 @@ function toolMatches(pattern, name) {
161
170
  *
162
171
  * Input a rule needs but cannot read (no command, a URL that does not parse) counts as
163
172
  * matching that rule: a rule the owner wrote is not skipped because the input was odd.
173
+ *
174
+ * Path rules ignore case where the filesystem does (cloud review 2026-11-03, SC-E):
175
+ * macOS and Windows by default, so `/users/NAS/.SSH/key` meets a deny on
176
+ * `/Users/nas/.ssh/*`. Every effect is restrictive, so this only ever makes the gate
177
+ * stricter for the sidecar. `caseless` overrides the platform; the gateway passes it
178
+ * both ways (see app/api/v1/tool-approvals), since a caseless deny must not pre-empt
179
+ * its taint hold.
164
180
  */
165
- export function evaluateToolRules(parsed, input) {
181
+ export function evaluateToolRules(parsed, input, { platform = typeof process === "undefined" ? "" : process.platform, caseless } = {}) {
182
+ const ignoreCase = caseless ?? (platform === "darwin" || platform === "win32");
166
183
  const name = typeof input?.tool_name === "string" ? input.tool_name : "";
167
184
  const toolInput = isRecord(input?.tool_input) ? input.tool_input : {};
168
185
  let best = null;
169
186
  parsed.rules.forEach((rule, ruleIndex) => {
170
187
  if (!toolMatches(rule.tool, name)) return;
171
- const subject = subjectFor(rule, name, toolInput, input);
188
+ const subject = subjectFor(rule, name, toolInput, input, ignoreCase);
172
189
  if (subject === undefined) return;
173
190
  if (!best || STRICTNESS[rule.effect] > STRICTNESS[best.effect]) best = { effect: rule.effect, ruleIndex, subject };
174
191
  });
@@ -176,7 +193,7 @@ export function evaluateToolRules(parsed, input) {
176
193
  }
177
194
 
178
195
  // The matched text, `undefined` when the rule does not apply to this input.
179
- function subjectFor(rule, name, toolInput, input) {
196
+ function subjectFor(rule, name, toolInput, input, ignoreCase) {
180
197
  if (rule.command !== undefined) {
181
198
  if (typeof toolInput.command !== "string") return "";
182
199
  return commandPieces(toolInput.command).find((piece) => globMatch(rule.command, piece));
@@ -187,20 +204,22 @@ function subjectFor(rule, name, toolInput, input) {
187
204
  if (raw === undefined && SEARCH_TOOLS.has(name) && typeof input?.cwd === "string") raw = input.cwd;
188
205
  if (raw === undefined) return "";
189
206
  const path = normalisePath(raw);
190
- return globMatch(rule.path, path) ? path : undefined;
207
+ const hit = ignoreCase ? globMatch(rule.path.toLowerCase(), path.toLowerCase()) : globMatch(rule.path, path);
208
+ return hit ? path : undefined;
191
209
  }
192
210
  if (rule.domain !== undefined) {
193
211
  let host;
194
212
  try {
195
- host = new URL(String(toolInput.url)).hostname.toLowerCase();
213
+ host = normalizeHostname(new URL(String(toolInput.url)).hostname);
196
214
  } catch {
197
215
  return "";
198
216
  }
199
- if (rule.domain.startsWith("*.")) {
200
- const base = rule.domain.slice(2);
217
+ const domain = normalizeHostname(rule.domain);
218
+ if (domain.startsWith("*.")) {
219
+ const base = domain.slice(2);
201
220
  return host === base || host.endsWith(`.${base}`) ? host : undefined;
202
221
  }
203
- return host === rule.domain ? host : undefined;
222
+ return host === domain ? host : undefined;
204
223
  }
205
224
  return name;
206
225
  }
@@ -39,6 +39,9 @@ export function createVisaClient({
39
39
  passport_id: passportId,
40
40
  ts: now(),
41
41
  nonce: randomUUID(),
42
+ // Signed, so this proof is good at the challenge door only (cloud review
43
+ // CP5). An older gateway ignores the field.
44
+ purpose: "challenge",
42
45
  // Omitted, never guessed at: every older client, the SDK and the examples
43
46
  // mint without one, and an absent claim is a state the dashboard says out
44
47
  // loud rather than a tier it assumes.
@@ -116,7 +116,7 @@ export async function peekText(body, limit = REFUSAL_PEEK_BYTES) {
116
116
  const LOOPBACK_PEER = /^(127\.\d{1,3}\.\d{1,3}\.\d{1,3}|::1|::ffff:127\.\d{1,3}\.\d{1,3}\.\d{1,3})$/;
117
117
  const LOOPBACK_NAMES = new Set(["127.0.0.1", "localhost", "[::1]"]);
118
118
 
119
- function hostIsThisListener(hostHeader, port) {
119
+ export function hostIsThisListener(hostHeader, port) {
120
120
  if (typeof hostHeader !== "string") return false;
121
121
  const match = /^(\[[^\]]+\]|[^:]+):(\d+)$/.exec(hostHeader.trim().toLowerCase());
122
122
  return Boolean(match && LOOPBACK_NAMES.has(match[1]) && Number(match[2]) === port);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "passcontrol",
3
- "version": "1.7.0",
3
+ "version": "1.7.2",
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
  }
@@ -102,7 +102,14 @@ export class PassControl {
102
102
  }
103
103
  /** Sign a fresh challenge and exchange it for a visa. */
104
104
  async mint() {
105
- const payloadObj = { passport_id: this.passportId, ts: Date.now(), nonce: crypto.randomUUID() };
105
+ // `purpose` is signed, so this proof is good at one passport door only (cloud
106
+ // review CP5). An older gateway ignores the field.
107
+ const payloadObj = {
108
+ passport_id: this.passportId,
109
+ ts: Date.now(),
110
+ nonce: crypto.randomUUID(),
111
+ purpose: this.delegationChain ? "delegated" : "challenge",
112
+ };
106
113
  const payloadBytes = new TextEncoder().encode(JSON.stringify(payloadObj));
107
114
  const payload = bytesToB64url(payloadBytes);
108
115
  const signature = bytesToB64url(ed25519.sign(payloadBytes, this.secret));