passcontrol 1.8.0 → 1.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -273,8 +273,15 @@ are separate from signature verification.
273
273
  and budget checks; it is not arbitrary API translation. Embeddings never fail over.
274
274
  - The injected provider key is removed from what comes back: if an upstream echoes it in
275
275
  an error body, a JSON answer or an event stream (even split across chunks), the agent
276
- receives `[REDACTED_PROVIDER_KEY]` instead. This covers the exact key, not a key an
277
- upstream has transformed.
276
+ receives `[REDACTED_PROVIDER_KEY]` instead. For keys of 16+ characters this also covers
277
+ base64 (including inside Basic auth), hex, percent-encoded and reversed copies, and any
278
+ run of 12+ characters of the key's secret part (a key cut in halves or truncated). A key
279
+ streamed back a few characters per event is caught too: for Anthropic Messages, OpenAI
280
+ Chat Completions and OpenAI Responses streams the text is followed the way the client's
281
+ SDK joins it. Ordinary events are not delayed; an event waits only while the text ends
282
+ with the first four or more characters of the key. Not followed: Ollama's native
283
+ (newline-delimited) stream and streamed fields other than text, tool input and thinking,
284
+ which keep the byte-level check.
278
285
 
279
286
  Passport scopes are snapshots in visas; scope edits can take up to the configured visa
280
287
  TTL to replace those snapshots. Other live controls have their own cache/invalidation
@@ -357,6 +364,8 @@ the provider credential. Upstream redirects are refused, never followed.
357
364
 
358
365
  ### Receipts, statements, and identity evidence
359
366
 
367
+ Receipt versions distinguish passport calls (v1), Direct Agent Key calls (v2), delegated worker calls (v3), and gateway endings on the owner's stop (v4, with no passport or agent key); older verifiers refuse v4.
368
+
360
369
  A signed call receipt records the issuer's decision, authentication method, reported
361
370
  usage/cost, and (when read) a digest of client request bytes. It does not include the
362
371
  provider response body. Verify it with an explicitly trusted issuer:
@@ -28,6 +28,7 @@ import {
28
28
  assertConfigLoaded,
29
29
  bareGatewayOrigin,
30
30
  config,
31
+ configInjectedKeys,
31
32
  configPathLabel,
32
33
  defaultModelForProvider,
33
34
  fail,
@@ -124,6 +125,9 @@ import {
124
125
  } from "../cli/codex-hooks.mjs";
125
126
  import { waitForGateway as awaitGateway } from "../cli/gateway-wait.mjs";
126
127
  import { loginCommand } from "../cli/login.mjs";
128
+ import { commandLabel, heldWriteKey, obtainWriteKey, releaseWriteKey } from "../cli/write-approval.mjs";
129
+ import { loweredKeysFile, lowerStoredKeyOnce } from "../cli/lowered-keys.mjs";
130
+ import { isSidecarKey, sidecarKey } from "../cli/sidecar-token.mjs";
127
131
  import { logoutCommand } from "../cli/logout.mjs";
128
132
  import { proveItWorks } from "../cli/selftest.mjs";
129
133
  import {
@@ -132,7 +136,7 @@ import {
132
136
  instanceKidFromSeed,
133
137
  retiredKeyEntry,
134
138
  } from "../cli/instance-key.mjs";
135
- import { FAILURE_REASONS, verifyAgentToken, verifyReceipt, verifySession, verifyStatement } from "../cli/verify.mjs";
139
+ import { describeGatewayEnding, FAILURE_REASONS, verifyAgentToken, verifyReceipt, verifySession, verifyStatement } from "../cli/verify.mjs";
136
140
  import { compareProtocolSets } from "../cli/protocols.mjs";
137
141
  import { memoryReviewCommand } from "../cli/memory-review.mjs";
138
142
  import { defaultAllowedModelForProvider } from "../cli/integration-defaults.mjs";
@@ -2137,13 +2141,31 @@ async function callCommand(rest, opts) {
2137
2141
  ok("done - check the dashboard audit log + spend for this call.");
2138
2142
  }
2139
2143
 
2144
+ /** What api() needs to know about the command running (review C-01). */
2145
+ const writeContext = { command: "a command", storedKeyChecked: false };
2146
+
2140
2147
  async function api(method, pathPart, body, { timeoutMs } = {}) {
2141
2148
  // Destination first, key second — same order and same reason as the SDK's
2142
2149
  // ControlClient. `config.gateway` is whatever PASSCONTROL_GATEWAY said, and
2143
2150
  // this is the one place a long-lived fleet-wide `pc_` key goes on the wire, so
2144
2151
  // the URL is built from the validated origin rather than from that string.
2145
2152
  const origin = requireControlGateway(config);
2146
- const apiKey = requireControlApiKey(config);
2153
+ const storedKey = requireControlApiKey(config);
2154
+ // Review C-01: the stored key is read-only since login lowers it. A change asks for a
2155
+ // one-command key approved in the browser (cli/write-approval.mjs), and keeps using
2156
+ // it for the rest of this command.
2157
+ const held = heldWriteKey(origin);
2158
+ // A key saved by an older login still has write scope: lowered before its first use
2159
+ // (owner 2026-11-15). Only a key that came from a config file, never one from the shell.
2160
+ if (!held && !writeContext.storedKeyChecked && configInjectedKeys.has("PASSCONTROL_API_KEY")) {
2161
+ writeContext.storedKeyChecked = true;
2162
+ const lowered = await lowerStoredKeyOnce({ origin, key: storedKey, stateFile: loweredKeysFile(globalConfigPath()) });
2163
+ if (lowered.lowered) {
2164
+ warn("This machine's saved control key could change things, so it is read-only now (an agent can read that file).");
2165
+ step("A command that changes something asks you to approve it in the browser.");
2166
+ }
2167
+ }
2168
+ const apiKey = held ?? storedKey;
2147
2169
  // Unbounded by default, deliberately: a fleet mutation must not be abandoned
2148
2170
  // halfway because a caller guessed a duration. `timeoutMs` is opt-in, for the
2149
2171
  // one kind of caller that is a REPORT — where a gateway that never answers is
@@ -2172,6 +2194,10 @@ async function api(method, pathPart, body, { timeoutMs } = {}) {
2172
2194
  } catch {
2173
2195
  json = { error: { message: text || "non-JSON response" } };
2174
2196
  }
2197
+ if (!res.ok && res.status === 403 && json.error?.code === "insufficient_scope" && !held) {
2198
+ await obtainWriteKey(origin, { command: writeContext.command, openUrl });
2199
+ return api(method, pathPart, body, { timeoutMs });
2200
+ }
2175
2201
  if (!res.ok) {
2176
2202
  const e = json.error ?? {};
2177
2203
  throw new Error(`${res.status} ${e.code ?? ""} ${e.message ?? ""} (req ${e.request_id ?? "?"})`);
@@ -2571,8 +2597,10 @@ async function statuslineCommand(opts) {
2571
2597
  // the calls go to Anthropic directly; `configure claude-code --subscription`
2572
2598
  // names the sidecar the hooks and telemetry use instead.
2573
2599
  const reported = !route && opts.port === undefined ? sidecarFromBaseUrl(process.env.PASSCONTROL_SIDECAR_URL) : null;
2600
+ const panelPort = route?.port ?? reported?.port ?? port;
2574
2601
  return await statusPanelText({
2575
- port: route?.port ?? reported?.port ?? port,
2602
+ port: panelPort,
2603
+ sidecarKey: sidecarKeyForPort(panelPort),
2576
2604
  gateway: config.gateway,
2577
2605
  session: typeof opts.session === "string" ? opts.session : null,
2578
2606
  subscription: Boolean(reported?.port),
@@ -2581,7 +2609,8 @@ async function statuslineCommand(opts) {
2581
2609
  const cacheFile = path.join(path.dirname(globalConfigPath()), `statusline-${port}.json`);
2582
2610
  // On a Pro/Max login Claude Code adds the usage window to its input (cli/usage-window.mjs).
2583
2611
  const input = await readStatusInput();
2584
- return await statuslineWithWindow({ input, port, budgetLine: () => statuslineText({ port, cacheFile }) });
2612
+ const statusKey = sidecarKeyForPort(port);
2613
+ return await statuslineWithWindow({ input, port, sidecarKey: statusKey, budgetLine: () => statuslineText({ port, cacheFile, sidecarKey: statusKey }) });
2585
2614
  } catch (error) {
2586
2615
  return `PassControl · ${error instanceof Error && /--port/.test(error.message) ? "bad --port" : "unavailable"}`;
2587
2616
  }
@@ -2594,6 +2623,35 @@ function statusLineSettingsCommand(port) {
2594
2623
  return `node ${JSON.stringify(CLI_ENTRY)} ${args}`;
2595
2624
  }
2596
2625
 
2626
+ /** Shown where the sidecar's key would be when this machine has no passport yet. */
2627
+ const NO_SIDECAR_KEY = "run-passcontrol-login-first";
2628
+
2629
+ /**
2630
+ * The key the sidecar on `port` asks its callers for (review C-03, cli/sidecar-token.mjs):
2631
+ * derived from the passport that sidecar runs with. A dedicated tool profile that serves
2632
+ * this port has its own passport (cli/profiles.mjs); otherwise it is this config's.
2633
+ */
2634
+ function sidecarKeyForPort(port) {
2635
+ for (const profile of listProfiles()) {
2636
+ if (!profile.port || Number(profile.port) !== Number(port)) continue;
2637
+ const secret = readProfile(profile.name)?.PASSPORT_SECRET;
2638
+ if (secret) return sidecarKey(secret);
2639
+ }
2640
+ return sidecarKey(config.passportSecret);
2641
+ }
2642
+
2643
+ /** A preview prints the key's first characters only: it lands in terminals and logs. */
2644
+ function maskSidecarKey(text, key) {
2645
+ return isSidecarKey(key) ? String(text).split(key).join(`${key.slice(0, 8)}…`) : String(text);
2646
+ }
2647
+
2648
+ function sidecarApiKey(port) {
2649
+ const key = sidecarKeyForPort(port);
2650
+ if (key) return key;
2651
+ warn("No passport on this machine yet, so there is no sidecar key to print. Run `passcontrol login`, then this again.");
2652
+ return NO_SIDECAR_KEY;
2653
+ }
2654
+
2597
2655
  function sidecarBaseUrl(opts = {}) {
2598
2656
  const provider = String(opts.provider || config.provider);
2599
2657
  assertProvider(provider);
@@ -2602,7 +2660,11 @@ function sidecarBaseUrl(opts = {}) {
2602
2660
  return {
2603
2661
  provider,
2604
2662
  model: activeModel(provider, opts),
2605
- apiKey: "passcontrol",
2663
+ // Review C-03: the sidecar's own key, not a placeholder. It opens the sidecar on
2664
+ // this machine and nothing else; the sidecar strips it before forwarding.
2665
+ get apiKey() {
2666
+ return sidecarApiKey(port);
2667
+ },
2606
2668
  baseUrl: `http://${host}:${port}/api/v1/${provider}`,
2607
2669
  port,
2608
2670
  };
@@ -2639,9 +2701,9 @@ function printMcpPreset(integration, opts = {}) {
2639
2701
  // configureMcpClient); the MCP clients below launch `passcontrol mcp`, which needs it.
2640
2702
  if (integration !== "claude-code") requireGlobalMcpPassport();
2641
2703
  if (integration === "claude-code") {
2642
- const { baseUrl } = sidecarBaseUrl({ ...opts, provider: "anthropic" });
2704
+ const { baseUrl, apiKey } = sidecarBaseUrl({ ...opts, provider: "anthropic" });
2643
2705
  console.log("# Route Claude Code's model calls through the sidecar (start it first):");
2644
- printExports(Object.entries(claudeCodeEnv(baseUrl)));
2706
+ printExports(Object.entries(claudeCodeEnv(baseUrl, apiKey)));
2645
2707
  console.log("# Optional: also add PassControl's chat tool to Claude Code:");
2646
2708
  console.log(`# ${CLAUDE_CODE_ADD_COMMAND}`);
2647
2709
  return;
@@ -2703,8 +2765,8 @@ function printAgentPreset(name = "generic", opts = {}) {
2703
2765
  console.log(`# Start the bridge first: ${sidecarStart}`);
2704
2766
 
2705
2767
  // Desktop / GUI clients: there is nothing to export, you type these into a
2706
- // settings form. The API-key field is required by the UI but ignored by the
2707
- // sidecar — that is the point. It is where your real provider key used to go.
2768
+ // settings form. The API-key field takes the sidecar's own key (review C-03),
2769
+ // where your real provider key used to go. It opens the sidecar, nothing else.
2708
2770
  if (isGuiPreset(preset)) {
2709
2771
  console.log(`# ${GUI_PRESET_LABELS[preset]} settings:`);
2710
2772
  console.log(`Base URL: ${baseUrl}`);
@@ -2722,7 +2784,7 @@ function printAgentPreset(name = "generic", opts = {}) {
2722
2784
  console.log(" provider: custom");
2723
2785
  console.log(` base_url: ${JSON.stringify(`${baseUrl}/v1`)}`);
2724
2786
  console.log(` api_key: ${JSON.stringify(apiKey)}`);
2725
- console.log("# The placeholder key is stripped by the sidecar. Keep `passcontrol sidecar` running.");
2787
+ console.log("# That key only opens the sidecar on this machine; it is not a provider key. Keep `passcontrol sidecar` running.");
2726
2788
  break;
2727
2789
  case "openhands":
2728
2790
  console.log("# OpenHands / LiteLLM-compatible starting point:");
@@ -2763,7 +2825,8 @@ function printAgentPreset(name = "generic", opts = {}) {
2763
2825
 
2764
2826
  // A service preset has no provider and no model: the client is pointed at the
2765
2827
  // governed service route and sends no service token at all — the gateway
2766
- // injects the workspace's, and only for calls the agent's rules admit.
2828
+ // injects the workspace's, and only for calls the agent's rules admit. It does
2829
+ // send the sidecar's own key (review C-03), which opens the sidecar and nothing else.
2767
2830
  function printServicePreset(service, opts = {}) {
2768
2831
  const host = String(opts.host ?? process.env.SIDECAR_HOST ?? "127.0.0.1");
2769
2832
  const port = sidecarPort(opts);
@@ -2774,7 +2837,10 @@ function printServicePreset(service, opts = {}) {
2774
2837
  const entry = Object.hasOwn(SERVICE_ENV, service) ? SERVICE_ENV[service] : null;
2775
2838
  if (!entry) throw new Error(`Usage: passcontrol env <${integrationChoices()}>`);
2776
2839
  for (const line of entry.about) console.log(line);
2777
- printExports([[entry.envVar, `http://${host}:${port}/api/v1/svc/${service}`]]);
2840
+ printExports([
2841
+ [entry.envVar, `http://${host}:${port}/api/v1/svc/${service}`],
2842
+ ["PASSCONTROL_SIDECAR_KEY", sidecarApiKey(port)],
2843
+ ]);
2778
2844
  console.log(entry.usage);
2779
2845
  }
2780
2846
 
@@ -2807,16 +2873,19 @@ function configureClaudeCode(opts = {}) {
2807
2873
  return;
2808
2874
  }
2809
2875
  const { baseUrl, port } = sidecarBaseUrl({ ...opts, provider: "anthropic" });
2876
+ const sidecarKeyValue = sidecarApiKey(port);
2810
2877
  const note = Boolean(opts.agentNote);
2811
- const preview = { env: claudeCodeEnv(baseUrl), hooks: apiToolHooks(port) };
2812
- if (note) preview.hooks = { ...preview.hooks, UserPromptSubmit: [{ hooks: [{ type: "http", url: `http://127.0.0.1:${port}/_passcontrol/hook?note=only`, timeout: 5 }] }] };
2813
- console.log(`Preview: ${target}\n\n${JSON.stringify(preview, null, 2)}`);
2878
+ // The preview prints the key's first characters only: it lands in terminals and logs.
2879
+ const preview = { env: claudeCodeEnv(baseUrl, sidecarKeyValue), hooks: apiToolHooks(port, sidecarKeyValue) };
2880
+ if (note) preview.hooks = { ...preview.hooks, UserPromptSubmit: [{ hooks: [{ type: "http", url: `http://127.0.0.1:${port}/_passcontrol/hook?note=only`, ...(isSidecarKey(sidecarKeyValue) ? { headers: { Authorization: `Bearer ${sidecarKeyValue}` } } : {}), timeout: 5 }] }] };
2881
+ console.log(`Preview: ${target}\n\n${maskSidecarKey(JSON.stringify(preview, null, 2), sidecarKeyValue)}`);
2814
2882
  if (!opts.write) {
2815
2883
  step(`Dry run only. Re-run with \`--write\` to merge these env keys and the tool hook${scope === "project" ? " (or --write --global for every session)" : ""}.`);
2816
2884
  } else {
2817
2885
  const result = writeClaudeCodeSettings({
2818
2886
  target,
2819
2887
  baseUrl,
2888
+ sidecarKey: sidecarKeyValue,
2820
2889
  force: Boolean(opts.force),
2821
2890
  statusLineCommand: opts.statusline ? statusLineSettingsCommand(port) : null,
2822
2891
  noteHookPort: note ? port : null,
@@ -2867,12 +2936,14 @@ function configureClaudeCodeSubscription(opts = {}) {
2867
2936
  return;
2868
2937
  }
2869
2938
  const note = Boolean(opts.agentNote);
2870
- const preview = { env: subscriptionEnv(port), hooks: subscriptionHooks(port, { note }), statusLine: { type: "command", command: statusLineSettingsCommand(port) } };
2871
- console.log(`Preview: ${target}\n\n${JSON.stringify(preview, null, 2)}`);
2939
+ // Review C-03 follow-up: the hooks and the logs export carry the sidecar's key.
2940
+ const subscriptionKey = opts.write ? sidecarApiKey(port) : sidecarKeyForPort(port);
2941
+ const preview = { env: subscriptionEnv(port, subscriptionKey), hooks: subscriptionHooks(port, { note, key: subscriptionKey }), statusLine: { type: "command", command: statusLineSettingsCommand(port) } };
2942
+ console.log(`Preview: ${target}\n\n${maskSidecarKey(JSON.stringify(preview, null, 2), subscriptionKey)}`);
2872
2943
  if (!opts.write) {
2873
2944
  step("Dry run only. Re-run with `--write` to merge these into your Claude Code user settings (anything of yours is kept).");
2874
2945
  } else {
2875
- const result = writeClaudeCodeSubscription({ target, port, statusLineCommand: statusLineSettingsCommand(port), force: Boolean(opts.force), note });
2946
+ const result = writeClaudeCodeSubscription({ target, port, sidecarKey: subscriptionKey, statusLineCommand: statusLineSettingsCommand(port), force: Boolean(opts.force), note });
2876
2947
  if (!result.changed) ok(`${target} already has PassControl's subscription mode`);
2877
2948
  else {
2878
2949
  if (result.backupPath) step(`backed up ${result.backupPath}`);
@@ -2914,13 +2985,13 @@ function codexSettings(opts = {}) {
2914
2985
  }
2915
2986
  const { baseUrl, port } = sidecarBaseUrl({ ...opts, provider: "openai" });
2916
2987
  const model = typeof opts.model === "string" && opts.model ? opts.model : undefined;
2917
- return { baseUrl, port, model };
2988
+ return { baseUrl, port, model, sidecarKey: sidecarApiKey(port) };
2918
2989
  }
2919
2990
 
2920
2991
  function printCodexPreset(opts = {}) {
2921
- const { baseUrl, model } = codexSettings(opts);
2992
+ const { baseUrl, model, sidecarKey: key } = codexSettings(opts);
2922
2993
  console.log(`# Save as ${codexProfilePath()} (or run: ${cliCommand("configure codex --write")}):`);
2923
- console.log(codexProfileToml({ baseUrl, model }).trimEnd());
2994
+ console.log(codexProfileToml({ baseUrl, model, sidecarKey: key }).trimEnd());
2924
2995
  }
2925
2996
 
2926
2997
  /**
@@ -3043,12 +3114,13 @@ function configureCodex(opts = {}) {
3043
3114
  else step(`${target} is not a profile PassControl wrote; nothing to remove.`);
3044
3115
  return;
3045
3116
  }
3046
- const { baseUrl, port, model } = codexSettings(opts);
3047
- console.log(`Preview: ${target}\n\n${codexProfileToml({ baseUrl, model })}`);
3117
+ const { baseUrl, port, model, sidecarKey: key } = codexSettings(opts);
3118
+ // The preview shows the key's first characters only: it lands in terminals and logs.
3119
+ console.log(`Preview: ${target}\n\n${codexProfileToml({ baseUrl, model, sidecarKey: `${key.slice(0, 8)}…` })}`);
3048
3120
  if (!opts.write) {
3049
3121
  step("Dry run only. Re-run with `--write` to create this profile. Codex's config.toml is not touched.");
3050
3122
  } else {
3051
- const result = writeCodexProfile({ target, baseUrl, model, force: Boolean(opts.force) });
3123
+ const result = writeCodexProfile({ target, baseUrl, model, sidecarKey: key, force: Boolean(opts.force) });
3052
3124
  if (!result.changed) ok(`${target} already routes Codex through PassControl`);
3053
3125
  else {
3054
3126
  if (result.backupPath) step(`backed up ${result.backupPath}`);
@@ -3513,7 +3585,11 @@ async function verifyCommand(rest, opts) {
3513
3585
  step("would need every receipt in the window.");
3514
3586
  return;
3515
3587
  }
3516
- step(`Passport: ${c.sub}`);
3588
+ if (what === "receipt" && c.auth?.kind === "gateway_ending") {
3589
+ step(describeGatewayEnding(c.end));
3590
+ } else {
3591
+ step(`Passport: ${c.sub}`);
3592
+ }
3517
3593
  if (what === "token") {
3518
3594
  step(`Audience: ${c.aud}`);
3519
3595
  step(`Expires: ${new Date(c.exp * 1000).toISOString()}`);
@@ -4557,6 +4633,9 @@ async function settingsCommand() {
4557
4633
  } catch (error) {
4558
4634
  if (!chosen.returnToMenu) throw error;
4559
4635
  fail(error.message);
4636
+ } finally {
4637
+ // One approval covers one command, not the rest of the menu session (review C-01).
4638
+ await releaseWriteKey();
4560
4639
  }
4561
4640
  recentIds = updateRecents(recentIds, chosen);
4562
4641
  if (!chosen.returnToMenu || !(await pauseForSettings())) return;
@@ -4566,6 +4645,7 @@ async function settingsCommand() {
4566
4645
  async function main(argv = process.argv.slice(2), runtime = {}) {
4567
4646
  const { opts, rest } = parseArgv(argv);
4568
4647
  const [command, ...commandRest] = rest;
4648
+ writeContext.command = commandLabel(rest);
4569
4649
 
4570
4650
  // First, before the update check or anything else that could print or wait:
4571
4651
  // Claude Code shows this command's whole stdout as its status line, runs it
@@ -4583,7 +4663,7 @@ async function main(argv = process.argv.slice(2), runtime = {}) {
4583
4663
  try {
4584
4664
  for await (const chunk of process.stdin) input += chunk;
4585
4665
  const port = sidecarPort(opts);
4586
- const out = await runCodexHook({ input, port });
4666
+ const out = await runCodexHook({ input, port, sidecarKey: sidecarKeyForPort(port) });
4587
4667
  if (out) process.stdout.write(`${out}\n`);
4588
4668
  } catch {
4589
4669
  // Nothing: a hook that cannot run lets Codex go ahead, as a failed hook would.
@@ -4594,7 +4674,7 @@ async function main(argv = process.argv.slice(2), runtime = {}) {
4594
4674
  // Also before the update check: a full-screen board owns the terminal from its
4595
4675
  // first frame, and the check's cache would be the one file `watch` ever wrote.
4596
4676
  if (command === "watch" && !opts.help) {
4597
- process.exit(await runWatch({ port: sidecarPort(opts) }));
4677
+ process.exit(await runWatch({ port: sidecarPort(opts), sidecarKey: sidecarKeyForPort(sidecarPort(opts)) }));
4598
4678
  }
4599
4679
 
4600
4680
  // Started here and awaited at the very end, so the registry lookup overlaps
@@ -4739,7 +4819,7 @@ async function main(argv = process.argv.slice(2), runtime = {}) {
4739
4819
  // Idea 13. Shows only; the decision is the owner's, on the agent's page.
4740
4820
  if (commandRest[0] !== "review") throw new Error("Usage: passcontrol memory review [--port 8788] [--codex]");
4741
4821
  const port = Number(opts.port ?? process.env.SIDECAR_PORT ?? 8788);
4742
- await memoryReviewCommand({ sidecarUrl: process.env.PASSCONTROL_SIDECAR_URL || `http://127.0.0.1:${port}`, client: opts.codex ? "codex" : "claude-code" });
4822
+ await memoryReviewCommand({ sidecarUrl: process.env.PASSCONTROL_SIDECAR_URL || `http://127.0.0.1:${port}`, sidecarKey: sidecarKeyForPort(port), client: opts.codex ? "codex" : "claude-code" });
4743
4823
  break;
4744
4824
  }
4745
4825
  case "kill":
@@ -4773,7 +4853,17 @@ async function main(argv = process.argv.slice(2), runtime = {}) {
4773
4853
  await announceUpdate();
4774
4854
  }
4775
4855
 
4776
- main().catch((error) => {
4856
+ /**
4857
+ * After every command, whatever its outcome (review C-01): give back a one-command
4858
+ * write key if one was approved, and say so once if the key stored in a config file
4859
+ * turned out to have write scope (a login from before this release).
4860
+ */
4861
+ async function afterCommand() {
4862
+ await releaseWriteKey();
4863
+ }
4864
+
4865
+ main().then(afterCommand, async (error) => {
4866
+ await afterCommand().catch(() => undefined);
4777
4867
  fail(error.message);
4778
4868
  process.exit(1);
4779
4869
  });
@@ -2,9 +2,11 @@
2
2
  //
3
3
  // Claude Code reads an `env` block from its settings files wherever it is
4
4
  // started (verified 2026-10-07, Claude Code 2.1.292): ANTHROPIC_BASE_URL sends
5
- // its calls to the sidecar, and ANTHROPIC_AUTH_TOKEN, a placeholder, rides as a
6
- // Bearer token with no "use this API key?" prompt. The sidecar strips it and the
7
- // gateway injects the real key, so Claude Code never holds one.
5
+ // its calls to the sidecar, and ANTHROPIC_AUTH_TOKEN rides as a Bearer token with
6
+ // no "use this API key?" prompt. That token is the sidecar's own key (review C-03,
7
+ // cli/sidecar-token.mjs): it opens the sidecar on this machine and nothing else.
8
+ // The sidecar strips it and the gateway injects the real key, so Claude Code never
9
+ // holds one.
8
10
  //
9
11
  // The settings file belongs to the user. The env keys and tool hook, and with
10
12
  // --statusline a `statusLine` running `passcontrol statusline`, are written or
@@ -16,12 +18,21 @@ import fs from "node:fs";
16
18
  import os from "node:os";
17
19
  import path from "node:path";
18
20
  import { GATE_HOOK_TIMEOUT_S } from "./subscription-gate.mjs";
21
+ import { isSidecarKey } from "./sidecar-token.mjs";
19
22
 
20
- /** Not a secret: the sidecar discards whatever arrives in this header. */
23
+ /**
24
+ * What this command wrote before review C-03. Public, so the sidecar refuses it now;
25
+ * kept only to recognise (and replace or remove) settings an older version wrote.
26
+ */
21
27
  export const CLAUDE_CODE_AUTH_PLACEHOLDER = "passcontrol-sidecar";
22
28
 
23
- export function claudeCodeEnv(baseUrl) {
24
- return { ANTHROPIC_BASE_URL: baseUrl, ANTHROPIC_AUTH_TOKEN: CLAUDE_CODE_AUTH_PLACEHOLDER };
29
+ /** A token this command wrote: today's sidecar key, or the old placeholder. */
30
+ export function isOurAuthToken(value) {
31
+ return value === CLAUDE_CODE_AUTH_PLACEHOLDER || isSidecarKey(value);
32
+ }
33
+
34
+ export function claudeCodeEnv(baseUrl, sidecarKey) {
35
+ return { ANTHROPIC_BASE_URL: baseUrl, ANTHROPIC_AUTH_TOKEN: sidecarKey };
25
36
  }
26
37
 
27
38
  /**
@@ -70,7 +81,7 @@ function save(target, value, exists) {
70
81
  * `hooks` with API mode's note-only prompt hook for `port`, or without it when `port`
71
82
  * is null. Every other hook, subscription mode's included, is left as it is.
72
83
  */
73
- function withNoteOnlyHook(hooks, port) {
84
+ function withNoteOnlyHook(hooks, port, key) {
74
85
  const isNoteOnly = (h) => isObject(h) && h.type === "http" && typeof h.url === "string" && OUR_NOTE_ONLY_URL.test(h.url);
75
86
  const base = isObject(hooks) ? hooks : null;
76
87
  const groups = Array.isArray(base?.UserPromptSubmit) ? base.UserPromptSubmit : [];
@@ -82,7 +93,7 @@ function withNoteOnlyHook(hooks, port) {
82
93
  if (rest.length) kept.push({ ...group, hooks: rest });
83
94
  }
84
95
  }
85
- const ours = { hooks: [{ type: "http", url: `${LOOPBACK_BASE}${port}/_passcontrol/hook?note=only`, timeout: GATE_HOOK_TIMEOUT_S }] };
96
+ const ours = { hooks: [{ type: "http", url: `${LOOPBACK_BASE}${port}/_passcontrol/hook?note=only`, ...keyHeaders(key), timeout: GATE_HOOK_TIMEOUT_S }] };
86
97
  if (port !== null && groups.length === kept.length + 1 && groups.some((g) => same(g, ours))) return hooks;
87
98
  if (port !== null) kept.push(ours);
88
99
  if (!base && !kept.length) return hooks;
@@ -96,18 +107,19 @@ function withNoteOnlyHook(hooks, port) {
96
107
  * The env keys, and with `statusLineCommand` the status line too, in ONE save:
97
108
  * two saves would back up the first save's output and lose the user's original.
98
109
  */
99
- export function writeClaudeCodeSettings({ target, baseUrl, force = false, statusLineCommand = null, noteHookPort = null, toolHookPort = null }) {
110
+ export function writeClaudeCodeSettings({ target, baseUrl, sidecarKey, force = false, statusLineCommand = null, noteHookPort = null, toolHookPort = null }) {
111
+ if (!isSidecarKey(sidecarKey)) throw new Error("No sidecar key to write: run `passcontrol login` first.");
100
112
  const { exists, value } = readSettings(target);
101
113
  const env = typeof value.env === "object" && value.env !== null && !Array.isArray(value.env) ? value.env : {};
102
114
  const rawKeyFound = typeof env.ANTHROPIC_API_KEY === "string" && env.ANTHROPIC_API_KEY.length > 0;
103
115
  const current = env.ANTHROPIC_BASE_URL;
104
- const envDone = current === baseUrl && env.ANTHROPIC_AUTH_TOKEN === CLAUDE_CODE_AUTH_PLACEHOLDER;
116
+ const envDone = current === baseUrl && env.ANTHROPIC_AUTH_TOKEN === sidecarKey;
105
117
  if (!envDone && typeof current === "string" && current && current !== baseUrl && !force) {
106
118
  throw new Error(
107
119
  `${target} already points Claude Code at ${current}. Re-run with --force to replace that address with PassControl's.`
108
120
  );
109
121
  }
110
- let next = envDone ? value : { ...value, env: { ...env, ...claudeCodeEnv(baseUrl) } };
122
+ let next = envDone ? value : { ...value, env: { ...env, ...claudeCodeEnv(baseUrl, sidecarKey) } };
111
123
  let statusLine;
112
124
  if (statusLineCommand) {
113
125
  const line = withStatusLine(next, statusLineCommand);
@@ -115,7 +127,7 @@ export function writeClaudeCodeSettings({ target, baseUrl, force = false, status
115
127
  statusLine = line.existing !== undefined ? { changed: false, existing: line.existing } : { changed: line.changed };
116
128
  }
117
129
  // configure passes the sidecar's port; URL.port is "" for :80, which would write a hook to nowhere.
118
- const hooks = withApiTools(withNoteOnlyHook(value.hooks, noteHookPort), toolHookPort ?? (new URL(baseUrl).port || 80));
130
+ const hooks = withApiTools(withNoteOnlyHook(value.hooks, noteHookPort, sidecarKey), toolHookPort ?? (new URL(baseUrl).port || 80), sidecarKey);
119
131
  const hooksChanged = !same(hooks ?? null, value.hooks ?? null);
120
132
  if (hooksChanged) {
121
133
  next = { ...next };
@@ -135,7 +147,7 @@ export function removeClaudeCodeSettings({ target }) {
135
147
  const env = typeof value.env === "object" && value.env !== null && !Array.isArray(value.env) ? value.env : null;
136
148
  // Only an address this command could have written: a gateway someone else set
137
149
  // up is not ours to remove.
138
- if (env && env.ANTHROPIC_AUTH_TOKEN === CLAUDE_CODE_AUTH_PLACEHOLDER) {
150
+ if (env && isOurAuthToken(env.ANTHROPIC_AUTH_TOKEN)) {
139
151
  const { ANTHROPIC_BASE_URL: _url, ANTHROPIC_AUTH_TOKEN: _token, ...rest } = env;
140
152
  next = { ...value };
141
153
  if (Object.keys(rest).length) next.env = rest;
@@ -231,17 +243,28 @@ const LOGS_ENV = {
231
243
  OTEL_LOGS_EXPORT_INTERVAL: "1000",
232
244
  };
233
245
 
234
- export function subscriptionEnv(port) {
246
+ // Review C-03 follow-up: the sidecar's own paths ask for its key too, so each hook and
247
+ // the logs export carry it. Claude Code sends hook `headers` as written (it only
248
+ // interpolates `$VAR`, which a pcs_ key never contains) and merges
249
+ // OTEL_EXPORTER_OTLP_LOGS_HEADERS into the logs export.
250
+ function keyHeaders(key) {
251
+ return isSidecarKey(key) ? { headers: { Authorization: `Bearer ${key}` } } : {};
252
+ }
253
+ const OUR_LOGS_HEADERS = /^Authorization=Bearer pcs_[A-Za-z0-9_-]{43}$/;
254
+
255
+ /** Without a key (a preview on a machine with no passport) the headers line is left out; the writer refuses. */
256
+ export function subscriptionEnv(port, key = null) {
235
257
  return {
236
258
  CLAUDE_CODE_ENABLE_TELEMETRY: "1",
237
259
  ...LOGS_ENV,
238
260
  OTEL_EXPORTER_OTLP_LOGS_ENDPOINT: `${LOOPBACK_BASE}${port}/_passcontrol/otlp/v1/logs`,
261
+ ...(isSidecarKey(key) ? { OTEL_EXPORTER_OTLP_LOGS_HEADERS: `Authorization=Bearer ${key}` } : {}),
239
262
  PASSCONTROL_SIDECAR_URL: `${LOOPBACK_BASE}${port}`,
240
263
  };
241
264
  }
242
265
 
243
- function gateHook(port, note = false) {
244
- return { type: "http", url: `${LOOPBACK_BASE}${port}/_passcontrol/hook${note ? "?note=1" : ""}`, timeout: GATE_HOOK_TIMEOUT_S };
266
+ function gateHook(port, note = false, key = null) {
267
+ return { type: "http", url: `${LOOPBACK_BASE}${port}/_passcontrol/hook${note ? "?note=1" : ""}`, ...keyHeaders(key), timeout: GATE_HOOK_TIMEOUT_S };
245
268
  }
246
269
 
247
270
  // PreToolUse may hold a tool while the owner is asked (Phase 2), and Claude Code lets
@@ -250,13 +273,13 @@ function gateHook(port, note = false) {
250
273
  // told, and a Phase 1 hook (no `t`, 5 s) refuses a tool that would need the owner
251
274
  // instead of letting it through on the timeout.
252
275
  export const TOOL_HOOK_TIMEOUT_S = 600;
253
- function toolHook(port, api = false) {
254
- return { type: "http", url: `${LOOPBACK_BASE}${port}/_passcontrol/hook?t=${TOOL_HOOK_TIMEOUT_S}${api ? "&mode=api" : ""}`, timeout: TOOL_HOOK_TIMEOUT_S };
276
+ function toolHook(port, api = false, key = null) {
277
+ return { type: "http", url: `${LOOPBACK_BASE}${port}/_passcontrol/hook?t=${TOOL_HOOK_TIMEOUT_S}${api ? "&mode=api" : ""}`, ...keyHeaders(key), timeout: TOOL_HOOK_TIMEOUT_S };
255
278
  }
256
279
 
257
280
  /** API mode always asks the sidecar before a tool. */
258
- export function apiToolHooks(port) {
259
- return { PreToolUse: [{ matcher: "*", hooks: [toolHook(port, true)] }] };
281
+ export function apiToolHooks(port, key = null) {
282
+ return { PreToolUse: [{ matcher: "*", hooks: [toolHook(port, true, key)] }] };
260
283
  }
261
284
 
262
285
  const OUR_API_TOOL_URL = /^http:\/\/127\.0\.0\.1:\d{1,5}\/_passcontrol\/hook\?t=\d{1,4}&mode=api$/;
@@ -265,12 +288,12 @@ const OUR_API_TOOL_URL = /^http:\/\/127\.0\.0\.1:\d{1,5}\/_passcontrol\/hook\?t=
265
288
  // an API setup replaces subscription mode's tool hook instead of adding a second one.
266
289
  // Removing (port null): only API mode's own hook. Subscription mode's stays, or a Pro/Max
267
290
  // setup would keep its prompt and batch hooks and lose its tool rules.
268
- function withApiTools(hooks, port) {
291
+ function withApiTools(hooks, port, key) {
269
292
  const base = isObject(hooks) ? hooks : {};
270
293
  const tools = Object.hasOwn(base, "PreToolUse") ? { PreToolUse: base.PreToolUse } : {};
271
294
  const next = { ...base };
272
295
  delete next.PreToolUse;
273
- if (port !== null) return { ...next, ...withOurHooks(tools, port, false, apiToolHooks(port)) };
296
+ if (port !== null) return { ...next, ...withOurHooks(tools, port, false, apiToolHooks(port, key)) };
274
297
  if (!Array.isArray(tools.PreToolUse)) return isObject(hooks) ? { ...next, ...tools } : hooks;
275
298
  const isApiTool = (h) => isObject(h) && h.type === "http" && typeof h.url === "string" && OUR_API_TOOL_URL.test(h.url);
276
299
  const kept = [];
@@ -285,11 +308,11 @@ function withApiTools(hooks, port) {
285
308
  }
286
309
 
287
310
  /** `note`: the agent's opt-in note rides on the prompt hook (`--agent-note`). */
288
- export function subscriptionHooks(port, { note = false } = {}) {
289
- const hook = gateHook(port);
311
+ export function subscriptionHooks(port, { note = false, key = null } = {}) {
312
+ const hook = gateHook(port, false, key);
290
313
  return {
291
- UserPromptSubmit: [{ hooks: [gateHook(port, note)] }],
292
- PreToolUse: [{ matcher: "*", hooks: [toolHook(port)] }],
314
+ UserPromptSubmit: [{ hooks: [gateHook(port, note, key)] }],
315
+ PreToolUse: [{ matcher: "*", hooks: [toolHook(port, false, key)] }],
293
316
  PostToolBatch: [{ hooks: [hook] }],
294
317
  };
295
318
  }
@@ -323,6 +346,7 @@ function withoutOurHooks(hooks) {
323
346
 
324
347
  /** `hooks` with exactly this port's gate hooks, leaving them where they are when already right. */
325
348
  function withOurHooks(hooks, port, note = false, ours = subscriptionHooks(port, { note })) {
349
+ // An old hook of ours (no key header) is not `same` as the new one, so it is replaced.
326
350
  const base = isObject(hooks) ? hooks : {};
327
351
  const next = withoutOurHooks(base);
328
352
  for (const event of Object.keys(ours)) {
@@ -347,7 +371,8 @@ function urlAllowed(patterns, url) {
347
371
  * Subscription mode's settings, in one save. Throws, writing nothing, when the
348
372
  * user already exports Claude Code's logs somewhere else and `force` is not set.
349
373
  */
350
- export function writeClaudeCodeSubscription({ target, port, statusLineCommand, force = false, note = false }) {
374
+ export function writeClaudeCodeSubscription({ target, port, sidecarKey, statusLineCommand, force = false, note = false }) {
375
+ if (!isSidecarKey(sidecarKey)) throw new Error("No sidecar key to write: run `passcontrol login` first.");
351
376
  const { exists, value } = readSettings(target);
352
377
  const env = isObject(value.env) ? value.env : {};
353
378
  const endpoint = env.OTEL_EXPORTER_OTLP_LOGS_ENDPOINT;
@@ -360,7 +385,7 @@ export function writeClaudeCodeSubscription({ target, port, statusLineCommand, f
360
385
  `${target} already exports Claude Code's logs (${theirs.join(", ")}). Subscription mode would send them to the sidecar instead. Re-run with --force to do that; nothing was written.`
361
386
  );
362
387
  }
363
- let next = { ...value, env: { ...env, ...subscriptionEnv(port) }, hooks: withOurHooks(value.hooks, port, note) };
388
+ let next = { ...value, env: { ...env, ...subscriptionEnv(port, sidecarKey) }, hooks: withOurHooks(value.hooks, port, note, subscriptionHooks(port, { note, key: sidecarKey })) };
364
389
  let statusLine;
365
390
  if (statusLineCommand) {
366
391
  const line = withStatusLine(next, statusLineCommand);
@@ -375,7 +400,7 @@ export function writeClaudeCodeSubscription({ target, port, statusLineCommand, f
375
400
  backupPath,
376
401
  ...(statusLine ? { statusLine } : {}),
377
402
  hookUrlsBlocked: Boolean(allowlist && [gateHook(port), gateHook(port, note), toolHook(port)].some((h) => !urlAllowed(allowlist, h.url))),
378
- routed: env.ANTHROPIC_AUTH_TOKEN === CLAUDE_CODE_AUTH_PLACEHOLDER && typeof env.ANTHROPIC_BASE_URL === "string",
403
+ routed: isOurAuthToken(env.ANTHROPIC_AUTH_TOKEN) && typeof env.ANTHROPIC_BASE_URL === "string",
379
404
  };
380
405
  }
381
406
 
@@ -392,6 +417,7 @@ export function removeClaudeCodeSubscription({ target }) {
392
417
  const env = { ...value.env };
393
418
  if (typeof env.OTEL_EXPORTER_OTLP_LOGS_ENDPOINT === "string" && OUR_LOGS_ENDPOINT.test(env.OTEL_EXPORTER_OTLP_LOGS_ENDPOINT)) {
394
419
  delete env.OTEL_EXPORTER_OTLP_LOGS_ENDPOINT;
420
+ if (typeof env.OTEL_EXPORTER_OTLP_LOGS_HEADERS === "string" && OUR_LOGS_HEADERS.test(env.OTEL_EXPORTER_OTLP_LOGS_HEADERS)) delete env.OTEL_EXPORTER_OTLP_LOGS_HEADERS;
395
421
  for (const [key, ours] of Object.entries(LOGS_ENV)) if (env[key] === ours) delete env[key];
396
422
  if (env.CLAUDE_CODE_ENABLE_TELEMETRY === "1" && !Object.keys(env).some((k) => k.startsWith("OTEL_"))) {
397
423
  delete env.CLAUDE_CODE_ENABLE_TELEMETRY;
@@ -223,7 +223,7 @@ export function codexHookAnswer(event, out) {
223
223
  * failure: a sidecar that is down or slow lets the action go ahead, with a warning
224
224
  * for prompts/pre-tool events. Post-tool telemetry always prints nothing.
225
225
  */
226
- export async function runCodexHook({ input, port, fetchImpl = fetch, promptTimeoutMs = PROMPT_RELAY_MS, toolTimeoutMs = TOOL_RELAY_MS, postToolTimeoutMs = POST_TOOL_RELAY_MS }) {
226
+ export async function runCodexHook({ input, port, sidecarKey = null, fetchImpl = fetch, promptTimeoutMs = PROMPT_RELAY_MS, toolTimeoutMs = TOOL_RELAY_MS, postToolTimeoutMs = POST_TOOL_RELAY_MS }) {
227
227
  let parsed;
228
228
  try {
229
229
  parsed = JSON.parse(input);
@@ -232,6 +232,9 @@ export async function runCodexHook({ input, port, fetchImpl = fetch, promptTimeo
232
232
  }
233
233
  const event = isObject(parsed) ? parsed.hook_event_name : null;
234
234
  if (!EVENTS.includes(event)) return "";
235
+ // The sidecar's own paths ask for its key (review C-03 follow-up). Without one the
236
+ // sidecar answers with a stop, which codexHookAnswer passes on.
237
+ const headers = { "content-type": "application/json", ...(sidecarKey ? { authorization: `Bearer ${sidecarKey}` } : {}) };
235
238
  const tool = event === "PreToolUse";
236
239
  const postTool = event === "PostToolUse";
237
240
  // A post-tool hook is telemetry only. Bound the entire operation, including a
@@ -245,7 +248,7 @@ export async function runCodexHook({ input, port, fetchImpl = fetch, promptTimeo
245
248
  });
246
249
  const relay = async () => {
247
250
  await fetchImpl(`http://127.0.0.1:${port}${HOOK_PATH}?client=codex`, {
248
- method: "POST", headers: { "content-type": "application/json" }, body: input, signal: controller.signal,
251
+ method: "POST", headers, body: input, signal: controller.signal,
249
252
  });
250
253
  return "";
251
254
  };
@@ -264,7 +267,7 @@ export async function runCodexHook({ input, port, fetchImpl = fetch, promptTimeo
264
267
  const url = `http://127.0.0.1:${port}${HOOK_PATH}?client=codex${tool ? `&t=${CODEX_TOOL_HOOK_TIMEOUT_S}` : ""}`;
265
268
  const response = await fetchImpl(url, {
266
269
  method: "POST",
267
- headers: { "content-type": "application/json" },
270
+ headers,
268
271
  body: input,
269
272
  signal: controller.signal,
270
273
  });