passcontrol 1.8.0 → 1.9.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/codex.mjs CHANGED
@@ -4,9 +4,10 @@
4
4
  // `.codex/config.toml` cannot set one, and the old `profile = "..."` selector is
5
5
  // refused (verified 2026-10-07, Codex CLI 0.160.1). So this writes a profile file,
6
6
  // `$CODEX_HOME/passcontrol.config.toml`, which Codex layers over config.toml when
7
- // started with `codex --profile passcontrol`. With no key configured for the
8
- // provider, Codex sends no Authorization header at all (captured); the sidecar
9
- // adds the agent's credential and the gateway injects the real OpenAI key.
7
+ // started with `codex --profile passcontrol`. The provider's bearer token is the
8
+ // sidecar's own key (review C-03, cli/sidecar-token.mjs): it opens the sidecar on
9
+ // this machine and nothing else. The sidecar strips it, adds the agent's
10
+ // credential, and the gateway injects the real OpenAI key.
10
11
  //
11
12
  // config.toml is never opened: the Codex app shares it, and PassControl would
12
13
  // need a TOML parser to edit it safely. The profile file is PassControl's own,
@@ -45,7 +46,10 @@ export function codexStoresApiKey({ env = process.env } = {}) {
45
46
  // escapes, so a value cannot close its string and start a key of its own.
46
47
  const tomlString = (value) => JSON.stringify(String(value));
47
48
 
48
- export function codexProfileToml({ baseUrl, model }) {
49
+ export function codexProfileToml({ baseUrl, model, sidecarKey }) {
50
+ if (typeof sidecarKey !== "string" || !sidecarKey) {
51
+ throw new Error("No sidecar key to write: run `passcontrol login` first.");
52
+ }
49
53
  let url;
50
54
  try {
51
55
  url = new URL(baseUrl);
@@ -66,6 +70,8 @@ export function codexProfileToml({ baseUrl, model }) {
66
70
  `[model_providers.${CODEX_PROFILE}]`,
67
71
  'name = "PassControl"',
68
72
  `base_url = ${tomlString(baseUrl)}`,
73
+ // Not an OpenAI key: the sidecar's own, which this 0600 file already sits beside.
74
+ `experimental_bearer_token = ${tomlString(sidecarKey)}`,
69
75
  'wire_api = "responses"',
70
76
  "",
71
77
  ].join("\n");
@@ -73,8 +79,8 @@ export function codexProfileToml({ baseUrl, model }) {
73
79
 
74
80
  const isOurs = (text) => text.startsWith(CODEX_PROFILE_MARKER);
75
81
 
76
- export function writeCodexProfile({ target, baseUrl, model, force = false }) {
77
- const next = codexProfileToml({ baseUrl, model });
82
+ export function writeCodexProfile({ target, baseUrl, model, sidecarKey, force = false }) {
83
+ const next = codexProfileToml({ baseUrl, model, sidecarKey });
78
84
  const exists = fs.existsSync(target);
79
85
  let backupPath = null;
80
86
  if (exists) {
package/cli/config.mjs CHANGED
@@ -478,7 +478,7 @@ export function requireControlApiKey(current = config) {
478
478
  assertConfigLoaded();
479
479
  if (!current.apiKey) {
480
480
  die(
481
- "No control-plane API key configured. Run `passcontrol init`, set PASSCONTROL_API_KEY in .passcontrol, or pass it as env."
481
+ "No control-plane API key configured. Run `passcontrol login` (it keeps a read-only key), set PASSCONTROL_API_KEY in .passcontrol, or pass it as env."
482
482
  );
483
483
  }
484
484
  return current.apiKey;
@@ -654,6 +654,9 @@ export function formatChallengeError(status, body) {
654
654
  if (status === 403 && detail.includes("agent_not_active")) {
655
655
  return "Challenge failed: this agent is suspended or revoked. Re-enable it in the dashboard, or run `passcontrol agent resume <id>`.";
656
656
  }
657
+ if (status === 409 && detail.includes("agent_scope_invalid")) {
658
+ return "Challenge failed: this agent's scope list is malformed, so no visa can be minted for it. The passport itself is fine. Open the agent in the dashboard and save its scopes again.";
659
+ }
657
660
  if (status === 401) {
658
661
  return `Challenge failed: 401 ${detail}. Check PASSPORT_ID/PASSPORT_SECRET, then retry.`;
659
662
  }
@@ -677,6 +680,12 @@ export function formatProxyError(status, body) {
677
680
  if (status === 402 && error === "blocked_budget_period") {
678
681
  return `${blocked}\n→ The agent's daily or monthly limit is spent; it resets at the next UTC day or month (see the retry-after header).\n→ Fix: wait for the reset, or raise the limit in the dashboard.`;
679
682
  }
683
+ if ((status === 402 || status === 403) && error === "blocked_session_cap") {
684
+ return `${blocked}\n→ This session reached one of the session's caps the agent's policy sets (money, calls or minutes). The agent's other sessions keep running.\n→ Fix: start a new session, or raise session_caps in the agent's policy.`;
685
+ }
686
+ if (status === 429 && error === "blocked_loop") {
687
+ return `${blocked}\n→ The agent sent the same request over and over, which looks like a loop, so PassControl paused its model calls. The pause lifts by itself (see the retry-after header).\n→ Fix: find what the agent is stuck on, or raise loop_breaker.repeats in the agent's policy if the repeats are intended.`;
688
+ }
680
689
  if (status === 402 && error === "blocked_budget_pause") {
681
690
  return `${blocked}\n→ The agent reached the pause line its owner set on its spending limit; the limit itself is not used up.\n→ Fix: let it go on for an hour from the agent's page in the dashboard, or raise the pause line.`;
682
691
  }
package/cli/login.mjs CHANGED
@@ -52,6 +52,7 @@ import {
52
52
  warn,
53
53
  } from "./config.mjs";
54
54
  import { defaultAllowedModelForProvider } from "./integration-defaults.mjs";
55
+ import { loweredKeysFile, rememberReadKey } from "./lowered-keys.mjs";
55
56
  import { proveItWorks } from "./selftest.mjs";
56
57
 
57
58
  export { CLOUD_GATEWAY };
@@ -397,28 +398,46 @@ export function gatewaySource(
397
398
  return { from: "default" };
398
399
  }
399
400
 
400
- export async function loginCommand(opts = {}, deps = {}) {
401
- const fetchImpl = deps.fetch ?? fetch;
402
- const openUrl = deps.openUrl ?? (() => {});
403
- const confirm = deps.confirmYes ?? (async (_q, o = {}) => o.default !== false);
404
- const promptLine = deps.promptLine ?? (async (_q, fallback) => fallback);
405
- // Only the poll loop reads these, and only a test passes them. Kept on `deps`
406
- // beside `fetch` rather than on `opts`, because they are seams for the caller,
407
- // not options for the operator — there is no flag that makes login lie about
408
- // the time.
409
- const now = deps.now ?? Date.now;
410
- const wait = deps.sleep ?? sleep;
401
+ /**
402
+ * Lower the login's key to read, and return it for saving; or revoke it and return
403
+ * "" when it could not be lowered. A write key is never handed back for saving.
404
+ */
405
+ async function keepReadOnly(origin, apiKey, fetchImpl, clientName) {
406
+ try {
407
+ await control(origin, apiKey, "POST", "/keys/self/downgrade", null, fetchImpl);
408
+ ok("this machine keeps a read-only control key");
409
+ return apiKey;
410
+ } catch {
411
+ const revoked = await revokeOwnKey(origin, apiKey, fetchImpl);
412
+ warn("Could not make the control key read-only, so it was not saved.");
413
+ if (!revoked) step(`It is STILL LIVE with write scope: revoke "CLI on ${clientName}" in Settings → API keys.`);
414
+ step("Status, spend and audit commands need a key: create a read-only one in Settings.");
415
+ return "";
416
+ }
417
+ }
411
418
 
412
- // Validate the destination BEFORE anything is requested — the ordering mintVisa
413
- // uses. A rejected gateway must cost zero sockets.
414
- const origin = resolveLoginGateway(opts);
419
+ /** Self-revoke, best effort. True when the key can no longer be used. */
420
+ async function revokeOwnKey(origin, apiKey, fetchImpl) {
421
+ try {
422
+ await control(origin, apiKey, "POST", "/keys/self/revoke", null, fetchImpl);
423
+ return true;
424
+ } catch {
425
+ return false;
426
+ }
427
+ }
415
428
 
416
- const clientName = String(opts.name || os.hostname() || "this machine");
429
+ /**
430
+ * The browser approval both `login` and a one-command write use: start a device
431
+ * authorization, show the code, wait for the operator to approve it in the dashboard
432
+ * (which needs their second factor), and return the grant. Nothing is saved here.
433
+ */
434
+ export async function approveInBrowser(origin, { clientName, title = "Approve this machine", oneCommand = false, opts = {}, fetchImpl = fetch, openUrl = () => {}, now = Date.now, wait = sleep }) {
417
435
  let started;
418
436
  try {
419
437
  started = await postJson(
420
438
  `${origin}/api/auth/device/start`,
421
- { client_name: clientName },
439
+ // `one_command`: the gateway gives that key a fixed 15-minute life (review C-01).
440
+ oneCommand ? { client_name: clientName, one_command: true } : { client_name: clientName },
422
441
  { fetchImpl }
423
442
  );
424
443
  } catch (error) {
@@ -466,7 +485,7 @@ export async function loginCommand(opts = {}, deps = {}) {
466
485
  // worse than one that never mentioned a clipboard at all.
467
486
  const copied = await copyToClipboard(userCode);
468
487
  console.log("");
469
- console.log(heading("Approve this machine"));
488
+ console.log(heading(title));
470
489
  console.log(` Code: ${formatCode(userCode)}${copied ? " (copied to your clipboard)" : ""}`);
471
490
  console.log(` Open: ${verificationUri}`);
472
491
  console.log("");
@@ -481,6 +500,27 @@ export async function loginCommand(opts = {}, deps = {}) {
481
500
  wait,
482
501
  });
483
502
  ok("approved");
503
+ return grant;
504
+ }
505
+
506
+ export async function loginCommand(opts = {}, deps = {}) {
507
+ const fetchImpl = deps.fetch ?? fetch;
508
+ const openUrl = deps.openUrl ?? (() => {});
509
+ const confirm = deps.confirmYes ?? (async (_q, o = {}) => o.default !== false);
510
+ const promptLine = deps.promptLine ?? (async (_q, fallback) => fallback);
511
+ // Only the poll loop reads these, and only a test passes them. Kept on `deps`
512
+ // beside `fetch` rather than on `opts`, because they are seams for the caller,
513
+ // not options for the operator — there is no flag that makes login lie about
514
+ // the time.
515
+ const now = deps.now ?? Date.now;
516
+ const wait = deps.sleep ?? sleep;
517
+
518
+ // Validate the destination BEFORE anything is requested — the ordering mintVisa
519
+ // uses. A rejected gateway must cost zero sockets.
520
+ const origin = resolveLoginGateway(opts);
521
+
522
+ const clientName = String(opts.name || os.hostname() || "this machine");
523
+ const grant = await approveInBrowser(origin, { clientName, opts, fetchImpl, openUrl, now, wait });
484
524
 
485
525
  // ── Provision a passport for this machine ─────────────────────────────────
486
526
  //
@@ -541,17 +581,32 @@ export async function loginCommand(opts = {}, deps = {}) {
541
581
  // rather than pretending nothing happened. Leaving the operator with an
542
582
  // orphaned agent AND no explanation would be the worse failure.
543
583
  warn("Left the existing config unchanged.");
544
- step(`The new passport was NOT saved. Agent ${agentId ?? "(unknown)"} and the key`);
545
- step(`"CLI on ${clientName}" now exist unused — revoke them in Settings.`);
584
+ const revoked = await revokeOwnKey(origin, grant.api_key, fetchImpl);
585
+ step(`The new passport was NOT saved. Agent ${agentId ?? "(unknown)"} now exists unused;`);
586
+ step(revoked
587
+ ? `revoke it in the Control Tower. The key "CLI on ${clientName}" was revoked.`
588
+ : `revoke it and the key "CLI on ${clientName}" in the Control Tower.`);
546
589
  return { agentId, passportId, target: null };
547
590
  }
591
+ // ── What stays on disk can look, not act (review C-01) ───────────────────
592
+ //
593
+ // The key was minted with write scope because creating the agent and registering
594
+ // its passport need it. That need ends here. The file below also holds the
595
+ // passport, and the governed agent can read it, so a write key saved there would
596
+ // let the agent act as its owner: lift the tenant stop, resume itself, raise its
597
+ // own budget, create an agent with no limits. So the key is lowered to read FIRST,
598
+ // and saved only if that worked. A write command later asks for a one-command
599
+ // key, approved in the browser (cli/write-approval.mjs).
600
+ const keptKey = await keepReadOnly(origin, grant.api_key, fetchImpl, clientName);
548
601
  mergeConfigFile(target, {
549
602
  PASSCONTROL_GATEWAY: origin,
550
603
  PASSPORT_ID: passportId,
551
604
  PASSPORT_SECRET: passportSecret,
552
605
  PASSPORT_KEY_STORAGE: "",
553
- PASSCONTROL_API_KEY: grant.api_key,
606
+ PASSCONTROL_API_KEY: keptKey,
554
607
  });
608
+ // Known read-only, so later commands do not ask the gateway to lower it again.
609
+ rememberReadKey(keptKey, loweredKeysFile(globalConfigPath()));
555
610
  ok(`wrote ${target}`);
556
611
  warnIfShadowed(target);
557
612
 
@@ -568,7 +623,7 @@ export async function loginCommand(opts = {}, deps = {}) {
568
623
  origin,
569
624
  passportId,
570
625
  passportSecret,
571
- apiKey: grant.api_key,
626
+ apiKey: keptKey,
572
627
  fetchImpl,
573
628
  // The receipt read waits out the gateway's background write. Injected from
574
629
  // the same seam the poll loop uses, so a test drives the retry without
@@ -577,6 +632,9 @@ export async function loginCommand(opts = {}, deps = {}) {
577
632
  });
578
633
 
579
634
  step("");
580
- step(`The key is listed in Settings as "CLI on ${clientName}" and can be revoked there.`);
635
+ if (keptKey) {
636
+ step(`Its read-only key is listed in Settings as "CLI on ${clientName}" and can be revoked there.`);
637
+ step("Commands that change something (kill off, resume, new agents) ask you to approve them in the browser.");
638
+ }
581
639
  return { agentId, passportId, target, proof };
582
640
  }
package/cli/logout.mjs CHANGED
@@ -12,6 +12,11 @@
12
12
  // resolve → look up the agent → decide about the agent → revoke the agent →
13
13
  // revoke the control key → blank the file.
14
14
  //
15
+ // Since review C-01 (2026-11-15) the key login leaves is READ-only: it can name the
16
+ // agent and revoke itself, but not revoke the agent, so that step answers 403 and
17
+ // logout says to do it in the Control Tower. A key from before that release still
18
+ // has write scope and works as described here.
19
+ //
15
20
  // The control key is revoked LAST because it is the credential doing all of the
16
21
  // work above; revoking it first turns every remaining step into a 401. The file
17
22
  // is blanked last of all, and — this is the part worth stating — it is blanked
@@ -166,8 +171,15 @@ export async function logoutCommand(opts = {}, deps = {}) {
166
171
  await control(origin, apiKey, "POST", `/agents/${encodeURIComponent(agent.id)}/revoke`, fetchImpl);
167
172
  agentRevoked = true;
168
173
  ok(`revoked agent ${agent.name}`);
169
- } catch {
170
- warnings.push(`Could not revoke agent "${agent.name}" — do it in the Control Tower.`);
174
+ } catch (error) {
175
+ // Since review C-01 login keeps a read-only key, which cannot revoke an agent.
176
+ // Owner's call (2026-11-15): logout clears this machine and points to the
177
+ // dashboard for the agent, rather than asking the browser for a write key.
178
+ warnings.push(
179
+ error?.status === 403
180
+ ? `This machine's control key is read-only, so revoke agent "${agent.name}" in the Control Tower.`
181
+ : `Could not revoke agent "${agent.name}" — do it in the Control Tower.`
182
+ );
171
183
  }
172
184
  }
173
185
  }
@@ -0,0 +1,67 @@
1
+ // The stored control key, lowered to read-only once per install (owner 2026-11-15,
2
+ // review C-01 follow-up). bin/passcontrol.mjs calls lowerStoredKeyOnce before the first
3
+ // control call of a command; `passcontrol login` calls rememberReadKey for the key it
4
+ // has just saved read-only, so a fresh login never asks the gateway again.
5
+ import { createHash } from "node:crypto";
6
+ import fs from "node:fs";
7
+ import path from "node:path";
8
+
9
+ // ── Keys saved by a login from before this release (owner 2026-11-15) ────────────
10
+ //
11
+ // Those still have write scope. Before such a key is used for anything, it is lowered
12
+ // to read, once per install: the lowered key's hash (never the key) is kept in
13
+ // `lowered-keys.json` beside the CLI's other caches. A key passed in the shell
14
+ // (PASSCONTROL_API_KEY=… passcontrol …) is never lowered: that is how an owner makes
15
+ // one change without the browser, on purpose.
16
+
17
+ /** Beside the CLI's other caches, in the global config's folder. */
18
+ export function loweredKeysFile(globalConfig) {
19
+ return path.join(path.dirname(globalConfig), "lowered-keys.json");
20
+ }
21
+
22
+ const digestOf = (key) => createHash("sha256").update(String(key)).digest("hex").slice(0, 32);
23
+
24
+ function readLowered(stateFile) {
25
+ try {
26
+ const list = JSON.parse(fs.readFileSync(stateFile, "utf8"));
27
+ return Array.isArray(list) ? list.filter((d) => typeof d === "string") : [];
28
+ } catch {
29
+ return [];
30
+ }
31
+ }
32
+
33
+ /** Note that `key` is known to be read-only (login saved it that way, or it was just lowered). */
34
+ export function rememberReadKey(key, stateFile) {
35
+ if (!key) return;
36
+ const list = readLowered(stateFile);
37
+ const digest = digestOf(key);
38
+ if (list.includes(digest)) return;
39
+ try {
40
+ fs.mkdirSync(path.dirname(stateFile), { recursive: true, mode: 0o700 });
41
+ fs.writeFileSync(stateFile, `${JSON.stringify([...list, digest].slice(-50))}\n`, { mode: 0o600 });
42
+ } catch {
43
+ // Best effort: without the note the next command asks the gateway again.
44
+ }
45
+ }
46
+
47
+ /**
48
+ * Lower the stored key to read unless this install already knows it is. Returns
49
+ * `{ lowered: true }` only when the gateway confirmed it. Anything else (an older
50
+ * gateway without the route, a revoked key, no network) changes nothing here and is
51
+ * tried again next time; the command then runs as it would have.
52
+ */
53
+ export async function lowerStoredKeyOnce({ origin, key, stateFile, fetchImpl = fetch }) {
54
+ if (!key || readLowered(stateFile).includes(digestOf(key))) return { lowered: false };
55
+ try {
56
+ const res = await fetchImpl(`${origin}/api/control/v1/keys/self/downgrade`, {
57
+ method: "POST",
58
+ headers: { authorization: `Bearer ${key}` },
59
+ });
60
+ await res.text().catch(() => "");
61
+ if (!res.ok) return { lowered: false };
62
+ } catch {
63
+ return { lowered: false };
64
+ }
65
+ rememberReadKey(key, stateFile);
66
+ return { lowered: true };
67
+ }
@@ -52,13 +52,18 @@ export function formatReview(answer, { dashboard = "the agent's page on the dash
52
52
  return lines;
53
53
  }
54
54
 
55
- export async function memoryReviewCommand({ sidecarUrl, cwd = process.cwd(), client = "claude-code", fetchImpl = fetch, print = console.log }) {
55
+ export async function memoryReviewCommand({ sidecarUrl, sidecarKey = null, cwd = process.cwd(), client = "claude-code", fetchImpl = fetch, print = console.log }) {
56
56
  const url = `${sidecarUrl.replace(/\/+$/, "")}/_passcontrol/memory?cwd=${encodeURIComponent(cwd)}${client === "codex" ? "&client=codex" : ""}`;
57
57
  let answer;
58
58
  try {
59
- const res = await fetchImpl(url, { signal: AbortSignal.timeout(10_000) });
59
+ // The sidecar's own paths ask for its key (review C-03 follow-up).
60
+ const res = await fetchImpl(url, { headers: sidecarKey ? { authorization: `Bearer ${sidecarKey}` } : {}, signal: AbortSignal.timeout(10_000) });
60
61
  answer = await res.json();
61
- } catch {
62
+ if (res.status === 401) throw Object.assign(new Error("keyless"), { keyless: true });
63
+ } catch (error) {
64
+ if (error?.keyless) {
65
+ throw new Error(`The sidecar at ${sidecarUrl} asked for its key, and this machine's config has no matching passport. Run \`passcontrol login\`, then this again.`);
66
+ }
62
67
  throw new Error(`No sidecar answered at ${sidecarUrl}. Start it with \`passcontrol sidecar\`, then run this again.`);
63
68
  }
64
69
  for (const line of formatReview(answer)) print(line);
package/cli/presets.mjs CHANGED
@@ -51,7 +51,7 @@ export const SERVICE_ENV = {
51
51
  "# GitHub REST through PassControl. What this agent may do is set on its page in the",
52
52
  "# dashboard, under GitHub access; the workspace's GitHub token stays in PassControl.",
53
53
  ],
54
- usage: "# Octokit: new Octokit({ baseUrl: process.env.GITHUB_API_URL }) — and no auth option.",
54
+ usage: "# Octokit: new Octokit({ baseUrl: process.env.GITHUB_API_URL, auth: process.env.PASSCONTROL_SIDECAR_KEY })",
55
55
  },
56
56
  telegram: {
57
57
  label: "Telegram",
@@ -60,7 +60,7 @@ export const SERVICE_ENV = {
60
60
  "# Telegram Bot API through PassControl. What this agent may do is set on its page in the",
61
61
  "# dashboard, under Telegram access; the bot token stays in PassControl.",
62
62
  ],
63
- usage: '# Call a method by name, with no token in the URL: curl "$TELEGRAM_API_URL/getMe"',
63
+ usage: '# Call a method by name, with no bot token in the URL: curl -H "x-api-key: $PASSCONTROL_SIDECAR_KEY" "$TELEGRAM_API_URL/getMe"',
64
64
  },
65
65
  brave: {
66
66
  label: "Brave Search",
@@ -69,7 +69,7 @@ export const SERVICE_ENV = {
69
69
  "# Brave Search through PassControl. What this agent may search is set on its page in the",
70
70
  "# dashboard, under Brave Search access; the API key stays in PassControl. Brave bills per search.",
71
71
  ],
72
- usage: '# Search with no key header: curl "$BRAVE_SEARCH_API_URL/web/search?q=passcontrol"',
72
+ usage: '# Search with the sidecar key, not a Brave key: curl -H "x-api-key: $PASSCONTROL_SIDECAR_KEY" "$BRAVE_SEARCH_API_URL/web/search?q=passcontrol"',
73
73
  },
74
74
  notion: {
75
75
  label: "Notion",
@@ -78,7 +78,7 @@ export const SERVICE_ENV = {
78
78
  "# Notion through PassControl. What this agent may do is set on its page in the dashboard,",
79
79
  "# under Notion access; the integration token stays in PassControl.",
80
80
  ],
81
- usage: "# @notionhq/client: new Client({ baseUrl: process.env.NOTION_API_URL }) — and no auth option.",
81
+ usage: "# @notionhq/client: new Client({ baseUrl: process.env.NOTION_API_URL, auth: process.env.PASSCONTROL_SIDECAR_KEY })",
82
82
  },
83
83
  discord: {
84
84
  label: "Discord",
@@ -87,7 +87,7 @@ export const SERVICE_ENV = {
87
87
  "# Discord's bot API through PassControl. What this agent may do is set on its page in the",
88
88
  "# dashboard, under Discord access; the bot token stays in PassControl.",
89
89
  ],
90
- usage: '# discord.js: new REST({ api: process.env.DISCORD_API_URL, version: "10" }).setToken("sidecar") — any token; the sidecar replaces it.',
90
+ usage: '# discord.js: new REST({ api: process.env.DISCORD_API_URL, version: "10" }).setToken(process.env.PASSCONTROL_SIDECAR_KEY)',
91
91
  },
92
92
  };
93
93
 
package/cli/protocols.mjs CHANGED
@@ -5,7 +5,8 @@ export const CONTROL_API_PROTOCOL = { minimum: 1, maximum: 1 };
5
5
  export const GATEWAY_API_PROTOCOL = { minimum: 1, maximum: 1 };
6
6
  // 3 (Bet D, 2026-10-10): a WORKER's receipt, auth.kind "delegated". Moved so a verifier
7
7
  // that predates delegation refuses it as too new instead of rendering it as passport-signed.
8
- export const RECEIPT_PROTOCOL = { minimum: 1, maximum: 3 };
8
+ // 4: an ending sent by the gateway on the owner's stop. Older verifiers must refuse it.
9
+ export const RECEIPT_PROTOCOL = { minimum: 1, maximum: 4 };
9
10
  export const AGENT_TOKEN_PROTOCOL = { minimum: 1, maximum: 1 };
10
11
  export const WORKSPACE_EXPORT_PROTOCOL = { minimum: 1, maximum: 1 };
11
12
 
@@ -0,0 +1,83 @@
1
+ // The sidecar's own key (review C-03, 2026-11-15).
2
+ //
3
+ // The sidecar holds the agent's passport and attaches a visa to what it forwards. It
4
+ // refuses web pages, but until this release it asked a local program for nothing, and
5
+ // a loopback port is shared by every user account on the machine. So a second user,
6
+ // or a process deliberately denied the passport file, could spend inside the agent's
7
+ // scope and budget through it.
8
+ //
9
+ // Now every forwarded call must present this key, in any header an API client puts
10
+ // its key in (Authorization Bearer, x-api-key, api-key, x-goog-api-key, or the
11
+ // password of a proxy URL). It is derived from the passport secret, so:
12
+ // - nothing new is stored: whoever can read the passport can compute it, which is
13
+ // exactly who may use the sidecar already;
14
+ // - the sidecar and `passcontrol env` / `configure` compute the same value;
15
+ // - rotating the passport changes it (re-run `passcontrol env` or `configure`).
16
+ // It is NOT a provider key and grants nothing at the gateway: the sidecar strips it
17
+ // before forwarding, like every credential header.
18
+ //
19
+ // The old public placeholder ("passcontrol-sidecar", "passcontrol") is refused: it is
20
+ // printed in the docs, so accepting it would leave the gap open.
21
+ import { createHmac, timingSafeEqual } from "node:crypto";
22
+
23
+ export const SIDECAR_KEY_PREFIX = "pcs_";
24
+ const LABEL = "passcontrol-sidecar-local-v1";
25
+
26
+ /** The key callers must present to a sidecar running with this passport secret. */
27
+ export function sidecarKey(passportSecret) {
28
+ const secret = String(passportSecret ?? "");
29
+ if (!secret) return null;
30
+ return `${SIDECAR_KEY_PREFIX}${createHmac("sha256", Buffer.from(secret, "utf8")).update(LABEL).digest("base64url")}`;
31
+ }
32
+
33
+ /** Looks like a sidecar key this CLI wrote (for finding and undoing its own settings). */
34
+ export function isSidecarKey(value) {
35
+ return typeof value === "string" && value.startsWith(SIDECAR_KEY_PREFIX);
36
+ }
37
+
38
+ const CREDENTIAL_HEADER = /(^|[-_])(api[-_]?key|authorization|auth|token|secret|credentials?)$/i;
39
+
40
+ /** Every value a caller could have meant as its key, from any credential-shaped header. */
41
+ export function presentedKeys(headers = {}) {
42
+ const out = [];
43
+ for (const [name, raw] of Object.entries(headers)) {
44
+ if (!CREDENTIAL_HEADER.test(name)) continue;
45
+ for (const value of Array.isArray(raw) ? raw : [raw]) {
46
+ if (typeof value !== "string") continue;
47
+ const v = value.trim();
48
+ const space = v.indexOf(" ");
49
+ const scheme = space > 0 ? v.slice(0, space).toLowerCase() : "";
50
+ const rest = space > 0 ? v.slice(space + 1).trim() : v;
51
+ if (scheme === "basic") {
52
+ // A proxy URL's credentials (HTTP_PROXY=http://user:<key>@127.0.0.1:8788).
53
+ let decoded = "";
54
+ try {
55
+ decoded = Buffer.from(rest, "base64").toString("utf8");
56
+ } catch {
57
+ decoded = "";
58
+ }
59
+ const colon = decoded.indexOf(":");
60
+ if (colon >= 0) out.push(decoded.slice(0, colon), decoded.slice(colon + 1));
61
+ else if (decoded) out.push(decoded);
62
+ } else {
63
+ // The whole value (x-api-key: <key>), and after any scheme word too:
64
+ // "Bearer <key>", Octokit's "token <key>", discord.js's "Bot <key>".
65
+ out.push(v);
66
+ if (scheme) out.push(rest);
67
+ }
68
+ }
69
+ }
70
+ return out;
71
+ }
72
+
73
+ /** True when some header carries `expected`. Compared in constant time per candidate. */
74
+ export function presentsSidecarKey(headers, expected) {
75
+ if (!expected) return false;
76
+ const want = Buffer.from(expected, "utf8");
77
+ let found = false;
78
+ for (const candidate of presentedKeys(headers)) {
79
+ const got = Buffer.from(candidate, "utf8");
80
+ if (got.length === want.length && timingSafeEqual(got, want)) found = true;
81
+ }
82
+ return found;
83
+ }
package/cli/sidecar.mjs CHANGED
@@ -18,6 +18,7 @@ import { OTLP_LOGS_PATH, readClaudeCodeEvents } from "./otlp-logs.mjs";
18
18
  import { CLIENT_EVENTS_PATH, CLIENT_EVENTS_SOURCE, createCallUploader } from "./client-events-upload.mjs";
19
19
  import { heldUsageWindow, WINDOW_PATH } from "./usage-window.mjs";
20
20
  import { createMemoryCustody } from "./memory-custody-sidecar.mjs";
21
+ import { presentsSidecarKey, sidecarKey } from "./sidecar-token.mjs";
21
22
 
22
23
  // Hop-by-hop headers plus the ones the sidecar rebuilds itself. `proxy-connection`
23
24
  // and friends only appear once something is used as a FORWARD proxy, which is
@@ -49,6 +50,31 @@ const STRIP_REQ = new Set([
49
50
  // machine at all, since not sending the key IS the sidecar.
50
51
  const CREDENTIAL_HEADER = /(^|[-_])(api[-_]?key|authorization|auth|token|secret|credentials?)$/i;
51
52
 
53
+ /** What a caller without the sidecar's key is told (review C-03). */
54
+ const SIDECAR_KEY_HELP =
55
+ "This sidecar only forwards calls that present its key. On this machine run `passcontrol env <client>` " +
56
+ "(or `passcontrol configure claude-code|codex --write`) and use the API key it prints. The old placeholder no longer works.";
57
+
58
+ // A hook call without the key (review C-03 follow-up). Claude Code treats an HTTP error
59
+ // from a hook as "carry on", so a 401 here would quietly switch the tool gate off for
60
+ // anyone whose settings predate the key. Instead it gets a 2xx answer that stops the
61
+ // session and refuses the tool, and nothing in it is scanned, reported or decided.
62
+ const KEYLESS_HOOK_REASON =
63
+ "PassControl refused this hook call: it carries no sidecar key. Run `passcontrol configure claude-code --write` " +
64
+ "(or `passcontrol configure codex --write`) again on this machine, then restart the session.";
65
+
66
+ export function keylessHookAnswer(head) {
67
+ const event = /"hook_event_name"\s*:\s*"([A-Za-z]{1,40})"/u.exec(String(head ?? ""))?.[1] ?? "";
68
+ const out = { continue: false, stopReason: KEYLESS_HOOK_REASON };
69
+ if (event === "PreToolUse") {
70
+ out.hookSpecificOutput = { hookEventName: "PreToolUse", permissionDecision: "deny", permissionDecisionReason: KEYLESS_HOOK_REASON };
71
+ } else {
72
+ out.decision = "block";
73
+ out.reason = KEYLESS_HOOK_REASON;
74
+ }
75
+ return out;
76
+ }
77
+
52
78
  function isStripped(name) {
53
79
  const key = name.toLowerCase();
54
80
  return STRIP_REQ.has(key) || CREDENTIAL_HEADER.test(key);
@@ -169,6 +195,9 @@ export function createSidecar({
169
195
  // sidecar forwards a bearer visa on every proxied request, so its destination
170
196
  // is part of the credential's security rather than a formatting detail.
171
197
  const origin = bareGatewayOrigin(gateway);
198
+ // Review C-03: what a local caller must present before anything is forwarded with
199
+ // this run's visa (cli/sidecar-token.mjs). Derived from the passport, never stored.
200
+ const callerKey = sidecarKey(passportSecret);
172
201
  const visas = createVisaClient({
173
202
  gateway: origin,
174
203
  passportId,
@@ -520,6 +549,20 @@ export function createSidecar({
520
549
  res.end(body);
521
550
  }
522
551
 
552
+ function refuseKeylessHook(req, res) {
553
+ // Only the start is kept, for the event name; the rest is drained, never parsed.
554
+ let head = "";
555
+ req.on("data", (c) => {
556
+ if (head.length < HOOK_PEEK_BYTES) head += c.toString("utf8").slice(0, HOOK_PEEK_BYTES - head.length);
557
+ });
558
+ req.on("end", () => {
559
+ const body = JSON.stringify(keylessHookAnswer(head));
560
+ res.writeHead(200, { "content-type": "application/json", "content-length": Buffer.byteLength(body), "cache-control": "no-store" });
561
+ res.end(body);
562
+ });
563
+ req.on("error", () => res.destroy());
564
+ }
565
+
523
566
  function serveHook(req, res) {
524
567
  const port = server.address()?.port;
525
568
  if (req.method !== "POST") {
@@ -813,6 +856,14 @@ export function createSidecar({
813
856
  // The sidecar's own paths: answered here, never forwarded with a visa.
814
857
  if (String(req.url ?? "").startsWith(LOCAL_PREFIX)) {
815
858
  const localPath = String(req.url).split("?")[0];
859
+ // Review C-03 follow-up: the sidecar's own paths ask for the key too. The hook
860
+ // reports tool output and files approvals with the visa, the receiver reports
861
+ // calls, and the rest show what the agent did.
862
+ if (!presentsSidecarKey(req.headers, callerKey)) {
863
+ if (localPath === HOOK_PATH && req.method === "POST") return void refuseKeylessHook(req, res);
864
+ req.resume();
865
+ return answer(res, 401, "sidecar_caller_unauthenticated", SIDECAR_KEY_HELP);
866
+ }
816
867
  if (localPath === HOOK_PATH) return serveHook(req, res);
817
868
  if (localPath === MEMORY_REVIEW_PATH) return void serveMemoryReview(req, res);
818
869
  if (localPath === OTLP_LOGS_PATH) return serveOtlpLogs(req, res);
@@ -834,19 +885,31 @@ export function createSidecar({
834
885
 
835
886
  let watch = null;
836
887
  try {
837
- const body = await readBody(req);
838
888
  // Idea 12: a planted decoy in a credential header is Used. The sidecar would strip
839
889
  // it and send its own visa, so the gateway would never see it: refuse here with the
840
890
  // answer an unknown key gets, and report it first, so the stop happens before the
841
891
  // answer. A report that fails still refuses; nothing is forwarded either way.
892
+ // Read from the headers only, so it runs before the body and before the key check
893
+ // below: a caller without the key who presents a decoy still trips the wire.
842
894
  const decoy = tripwires ? decoyInHeaders(req.headers, tripwireDigests, isStripped) : null;
843
895
  if (decoy) {
896
+ req.resume();
844
897
  await tripwires.used(decoy, recentTools());
845
898
  feed.record({ outcome: "denied", code: "invalid_credential", status: 401, lineage: lineageOf(req.headers), startedAt });
846
899
  res.writeHead(401, { "content-type": "application/json" });
847
900
  res.end(JSON.stringify({ error: "invalid_credential" }));
848
901
  return;
849
902
  }
903
+ // Review C-03: a local caller must present this sidecar's key, or nothing is
904
+ // forwarded with the visa. Checked before the body is read, so a refused caller
905
+ // cannot make the sidecar buffer it.
906
+ if (!presentsSidecarKey(req.headers, callerKey)) {
907
+ req.resume();
908
+ feed.record({ outcome: "denied", code: "sidecar_caller_unauthenticated", status: 401, lineage: lineageOf(req.headers), startedAt });
909
+ answer(res, 401, "sidecar_caller_unauthenticated", SIDECAR_KEY_HELP);
910
+ return;
911
+ }
912
+ const body = await readBody(req);
850
913
  watch = watchCall(req, verdict.path, body, startedAt);
851
914
  // Idea 13: in withhold mode the body may come back with pending memory cut out.
852
915
  const sent = (await memoryCustodyOfRequest(req, body)) ?? body;
@@ -986,13 +1049,17 @@ export function startSidecar(opts) {
986
1049
  if (ollamaPort != null) {
987
1050
  ollamaServer.listen(ollamaPort, host, () => {
988
1051
  step(`Ollama API (local models) on http://${host}:${ollamaPort}: set OLLAMA_HOST=${host}:${ollamaPort}`);
1052
+ // Review C-03: OLLAMA_HOST is host:port only, so an Ollama client cannot send a key,
1053
+ // and this port cannot ask for one. Said out loud rather than left implied.
1054
+ step(" Any program on this machine can use that port, inside this agent's scope and budget.");
989
1055
  });
990
1056
  }
991
1057
  server.listen(port, host, () => {
992
1058
  step(`PassControl visa sidecar forwarding to ${gateway}`);
993
1059
  step(`Listening on http://${host}:${port}`);
994
1060
  step(`Point your agent at: http://${host}:${port}/api/v1/anthropic (or /api/v1/openai)`);
995
- step("API key = anything (ignored). Visa is minted + refreshed automatically.");
1061
+ step("API key = this sidecar's key: `passcontrol env <client>` prints it. Other callers are refused.");
1062
+ step("Visa is minted + refreshed automatically.");
996
1063
  step(
997
1064
  journal
998
1065
  ? `Journal: ${journal.path} (receipt ids, times, statuses and declared sessions only; --no-journal turns it off)`