passcontrol 1.7.2 → 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.
@@ -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
@@ -244,8 +247,8 @@ export async function runCodexHook({ input, port, fetchImpl = fetch, promptTimeo
244
247
  timer = setTimeout(() => { controller.abort(); resolve(""); }, postToolTimeoutMs);
245
248
  });
246
249
  const relay = async () => {
247
- await fetchImpl(`http://127.0.0.1:${port}${HOOK_PATH}`, {
248
- method: "POST", headers: { "content-type": "application/json" }, body: input, signal: controller.signal,
250
+ await fetchImpl(`http://127.0.0.1:${port}${HOOK_PATH}?client=codex`, {
251
+ method: "POST", headers, body: input, signal: controller.signal,
249
252
  });
250
253
  return "";
251
254
  };
@@ -261,10 +264,10 @@ export async function runCodexHook({ input, port, fetchImpl = fetch, promptTimeo
261
264
  const timer = setTimeout(() => controller.abort(), tool ? toolTimeoutMs : promptTimeoutMs);
262
265
  const warn = (why) => JSON.stringify({ systemMessage: `PassControl: ${why}, so this goes ahead unchecked.` });
263
266
  try {
264
- const url = `http://127.0.0.1:${port}${HOOK_PATH}${tool ? `?t=${CODEX_TOOL_HOOK_TIMEOUT_S}` : ""}`;
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
  });
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
+ }
@@ -0,0 +1,19 @@
1
+ export interface MemoryCustody {
2
+ hook(input: Record<string, unknown>, options?: { client?: "claude-code" | "codex"; api?: boolean }): Promise<void>;
3
+ /** In withhold mode: the request body with pending memory cut out, or null when unchanged. */
4
+ modelRequest(sessionId: string, body: unknown): Promise<any>;
5
+ fallback(sessionId: string | null | undefined, body: unknown): any;
6
+ mode(): string;
7
+ setView(view: unknown): void;
8
+ state(sessionId?: string): "off" | "clear" | "held";
9
+ review(cwd: string, client?: "claude-code" | "codex"): Promise<{ state: string; items: Record<string, unknown>[] }>;
10
+ _debug: { sessions: Map<string, unknown>; roots: Map<string, unknown> };
11
+ }
12
+ export function createMemoryCustody(options: {
13
+ send: (body: Record<string, unknown>) => Promise<{ status: number; body: any }>;
14
+ env?: Record<string, string | undefined>;
15
+ now?: () => number;
16
+ salt?: string | null;
17
+ onWarn?: (message: string) => void;
18
+ }): MemoryCustody;
19
+ export function workspaceRoot(cwd: string): string;