passcontrol 0.9.1 → 0.9.3

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
@@ -1,6 +1,6 @@
1
1
  # PassControl
2
2
 
3
- PassControl **0.9.0** is an identity and credential gateway for AI agents. It keeps
3
+ PassControl is an identity and credential gateway for AI agents. It keeps
4
4
  provider API keys out of agent configuration and applies per-agent scopes, policies,
5
5
  budgets, and stop controls before forwarding model requests.
6
6
 
@@ -44,7 +44,7 @@ Passport sender-proof modes are **off**, **observe**, and **required**. Off igno
44
44
  proofs; observe records what would pass without enforcing it; required rejects missing,
45
45
  invalid, stale, or replayed proofs. Only enforced success is recorded as
46
46
  `passport_proof_per_request`; observing a valid proof does not upgrade authentication.
47
- The 0.9.0 sidecar supplies proofs; the direct CLI call, MCP chat, and TypeScript SDK
47
+ The sidecar supplies proofs; the direct CLI call, MCP chat, and TypeScript SDK
48
48
  do not attach them and cannot use required mode without an additional proof implementation.
49
49
  Proofs do **not** bind the request body or query string and do not attest hardware or
50
50
  key storage. See [authentication and lifecycle](https://github.com/Vertias3u/PassControl/blob/main/DOCUMENTATION.md).
@@ -93,6 +93,11 @@ provider fallback rate. **Custom endpoints are unpriced**, even when the model n
93
93
  matches: logs mark cost unknown, receipts carry `unp`, and token accounting continues.
94
94
  The cost budget retains a proxy estimate; it does not become knowledge of actual dollars.
95
95
  Known/table-priced cost, conservative enforced spend, and open holds are different figures.
96
+ The dashboard therefore labels the all-time counter **Settled budget charges** and shows its
97
+ durable call-attributed charges, separate operator adjustments, any visible difference, and
98
+ live open reservations marked **not yet charged**. The call table keeps observed cost and budget
99
+ charge in separate columns and can load older durable rows on demand. An unavailable database or
100
+ Redis explanation is shown as unavailable, never as zero.
96
101
 
97
102
  ## Supported providers and endpoints
98
103
 
@@ -164,7 +169,7 @@ output; it does not exercise a billed provider.
164
169
  With Node installed:
165
170
 
166
171
  ```bash
167
- npm install -g passcontrol@0.9.0
172
+ npm install -g passcontrol
168
173
  passcontrol login
169
174
  ```
170
175
 
@@ -194,6 +199,19 @@ can use an existing file fallback with a warning. Custody shown by the gateway i
194
199
  **DECLARED evidence**, not proof of storage. The signer still reads key material into
195
200
  process memory; this is not a non-exportable hardware key.
196
201
 
202
+ For a Passport issued in the dashboard for Sidecar or MCP, import it without putting the
203
+ one-time secret in shell history:
204
+
205
+ ```bash
206
+ passcontrol passport import --global --gateway https://YOUR-PASSCONTROL-HOST \
207
+ --id PUBLIC_PASSPORT_ID
208
+ # paste the secret at the hidden prompt, or provide it on raw stdin
209
+ ```
210
+
211
+ The CLI proves the 32-byte Ed25519 secret matches the public ID, stores it in macOS Keychain,
212
+ Linux Secret Service, or Windows DPAPI, verifies readback, and only then atomically updates the
213
+ global profile. Replacement requires `--replace`. The public command contains no secret.
214
+
197
215
  ## Connect a real agent
198
216
 
199
217
  For example, the direct OpenAI configuration has this shape:
@@ -217,6 +235,11 @@ its scope and suitable budgets. Choose by what your client supports:
217
235
  | Static-key client needing Passport | `passcontrol sidecar`, then `passcontrol env <integration>` |
218
236
  | MCP client | `passcontrol mcp`; configure as below |
219
237
 
238
+ Direct Agent Keys point the client at the PassControl gateway origin. Passport Sidecar clients
239
+ point at loopback (default `http://127.0.0.1:8788`) and the sidecar forwards to the gateway.
240
+ The sidecar adds per-request sender proof; the current SDK and MCP paths use bearer visas and are
241
+ refused when sender proof is required.
242
+
220
243
  ```bash
221
244
  # Passport bridge: talks to Cloud or your self-hosted gateway
222
245
  passcontrol sidecar
@@ -260,6 +283,20 @@ applies migrations, and seeds a local account. It writes `.env.docker`; use
260
283
  There are no shared default credentials. `passcontrol setup --app-dir <path>` selects a
261
284
  checkout; `passcontrol unlink` forgets a remembered one.
262
285
 
286
+ Local lifecycle commands manage `http://localhost:3000` independently from the active Cloud API
287
+ gateway. `setup`, `start`, and `restart` verify PassControl at `/api/version` and require the
288
+ launcher to remain alive before switching the global active gateway. `status` reports the active
289
+ API gateway and CLI-managed local dashboard separately; `open` opens the active gateway. Explicit
290
+ loopback ports remain supported, but a portless local URL is rejected instead of becoming port 80.
291
+ `--port-offset` moves Supabase and Redis ports only; the dashboard remains on port 3000.
292
+
293
+ Switching from a credentialed remote gateway clears gateway-bound local credentials only—it does
294
+ not revoke the remote key or Passport. Interactive use requires a separate confirmation;
295
+ noninteractive use requires `--forget-active-credentials`, and `--yes` is not a substitute.
296
+ Shell or project-file gateway overrides are refused and named before services start, because a
297
+ global write could not override them safely. Clean up any still-active remote identity at its
298
+ original gateway.
299
+
263
300
  For production, configure [`.env.example`](https://github.com/Vertias3u/PassControl/blob/main/.env.example), use Supabase (plain Postgres
264
301
  is insufficient), apply the public migrations with `DATABASE_URL=… npm run migrate`,
265
302
  and build/run the app. Supported paths are Next.js on Vercel, `npm run build` then
@@ -36,6 +36,7 @@ import {
36
36
  formatProxyError,
37
37
  globalConfigPath,
38
38
  mergeConfigFile,
39
+ mergeConfigFileAtomic,
39
40
  muted,
40
41
  heading,
41
42
  ok,
@@ -77,9 +78,11 @@ import {
77
78
  checkIssuerPublishesKey,
78
79
  generateInstanceKey,
79
80
  instanceKidFromSeed,
81
+ retiredKeyEntry,
80
82
  } from "../cli/instance-key.mjs";
81
83
  import { FAILURE_REASONS, verifyAgentToken, verifyReceipt, verifyStatement } from "../cli/verify.mjs";
82
84
  import { compareProtocolSets } from "../cli/protocols.mjs";
85
+ import { defaultAllowedModelForProvider } from "../cli/integration-defaults.mjs";
83
86
  import {
84
87
  PASSPORT_KEY_STORAGE_OS,
85
88
  createPassportCredentialStore,
@@ -113,6 +116,7 @@ const PUBLIC_REPO_URL = "https://github.com/Vertias3u/PassControl.git";
113
116
  // origin, and keeping two copies is how they stop being the same origin.
114
117
  const HOSTED_DEMO_URL = CLOUD_GATEWAY;
115
118
  const LOCAL_DASHBOARD_HOSTS = new Set(["localhost", "127.0.0.1", "::1", "[::1]"]);
119
+ const LOCAL_DASHBOARD_ORIGIN = "http://localhost:3000";
116
120
  const LOCAL_STACK_PORTS = [54321, 54322, 54324, 54327, 8079];
117
121
  // The local stack (Supabase + Redis + dashboard) lives in a PassControl repo
118
122
  // checkout — NOT in the installed CLI package (which ships only bin/ + cli/).
@@ -184,6 +188,8 @@ ${heading("Operate")}
184
188
  ${cmd} open open the Control Tower in a browser
185
189
  ${cmd} logout [--revoke-agent] revoke this machine's key and clear its credentials
186
190
  ${cmd} init [--global] configure by hand, without a browser
191
+ ${cmd} passport import --global --gateway <origin> --id <passport-id> [--replace]
192
+ securely import a dashboard-issued passport
187
193
 
188
194
  ${heading("Manage")}
189
195
  ${cmd} agent list [--json] list agents
@@ -216,6 +222,9 @@ ${heading("Trust")}
216
222
  ${cmd} key status show the local passport key storage tier
217
223
  ${cmd} key migrate move a tier 0 file key into the OS credential store
218
224
  ${cmd} keygen instance create the receipt-signing key
225
+ ${cmd} keygen instance --retire <seed>
226
+ print the public entry that keeps a rotated-out
227
+ key's receipts verifiable
219
228
  ${cmd} verify receipt <jws> --issuer <origin>
220
229
  verify a signed call receipt
221
230
  ${cmd} verify token <jwt> --audience <aud> --issuer <origin>
@@ -224,11 +233,13 @@ ${heading("Trust")}
224
233
  ${heading("Self-host — run your own gateway")}
225
234
  Clones the app and runs Docker + Supabase + Redis here. You operate it, and
226
235
  your instance signs its own receipts — they verify against your JWKS, not ours.
227
- ${cmd} setup [--no-open] [--port-offset N] [--app-dir DIR]
236
+ ${cmd} setup [--no-open] [--port-offset N] [--app-dir DIR] [--forget-active-credentials]
228
237
  clone the app, start Docker + Supabase + Redis
229
- ${cmd} start [--dashboard-only] start the whole local stack (clones the app if missing)
238
+ ${cmd} start [--dashboard-only] [--forget-active-credentials]
239
+ start the whole local stack (clones the app if missing)
230
240
  ${cmd} stop [--dashboard-only] stop the whole local stack (dashboard + Supabase + Redis)
231
- ${cmd} restart restart the CLI-managed local dashboard
241
+ ${cmd} restart [--forget-active-credentials]
242
+ restart the CLI-managed local dashboard
232
243
  ${cmd} local-logs [--follow] show local dashboard logs
233
244
  ${cmd} reset --local --confirm RESET
234
245
  destroy and recreate the local stack
@@ -293,13 +304,21 @@ async function fetchWithTimeout(url, init = {}, timeoutMs = 1200) {
293
304
  }
294
305
  }
295
306
 
296
- async function gatewayStatus(noNetwork = false) {
307
+ async function gatewayStatus(noNetwork = false, gateway = config.gateway) {
297
308
  if (noNetwork) return { label: "not checked", ok: null };
298
- const origin = probeGatewayOrigin(config);
309
+ const origin = probeGatewayOrigin({ gateway });
299
310
  if (!origin) return { label: "invalid configuration", ok: false };
300
311
  try {
301
- const res = await fetchWithTimeout(origin, { method: "GET" });
302
- return { label: res.ok ? `online (${res.status})` : `unhealthy (${res.status})`, ok: res.ok };
312
+ const res = await fetchWithTimeout(`${origin}/api/version`, {
313
+ method: "GET",
314
+ headers: { accept: "application/json" },
315
+ });
316
+ if (!res.ok) return { label: `unhealthy (${res.status})`, ok: false };
317
+ const body = await res.json().catch(() => null);
318
+ const version = typeof body?.version === "string" && body.version.trim() ? body.version.trim() : null;
319
+ return version
320
+ ? { label: `online (${res.status}, PassControl ${version})`, ok: true, version }
321
+ : { label: "unhealthy (not a PassControl version response)", ok: false };
303
322
  } catch {
304
323
  return { label: "offline or unreachable", ok: false };
305
324
  }
@@ -307,11 +326,13 @@ async function gatewayStatus(noNetwork = false) {
307
326
 
308
327
  async function printCockpit({ noNetwork = false, json = false } = {}) {
309
328
  const gateway = await gatewayStatus(noNetwork);
329
+ const local = managedDashboardTarget();
330
+ const localGateway = await gatewayStatus(noNetwork, local.url);
310
331
  const passportSecret = config.passportSecret;
311
332
  const passportStorage = config.passportStorage;
312
333
  const passportConfigured = Boolean(config.passportId && passportSecret);
313
334
  const adminConfigured = Boolean(config.apiKey);
314
- const dashboard = dashboardStatusLabel(gateway, noNetwork);
335
+ const dashboard = dashboardStatusLabel(localGateway, noNetwork, local);
315
336
  const app = appRootLabel();
316
337
  const configFile = configPathLabel(config.sources);
317
338
  // This is deliberately credential-gated. Status remains useful to an agent
@@ -323,7 +344,7 @@ async function printCockpit({ noNetwork = false, json = false } = {}) {
323
344
  console.log(JSON.stringify({
324
345
  version: CLI_VERSION,
325
346
  gateway: { url: config.gateway, state: gateway.label, healthy: gateway.ok },
326
- dashboard: { state: dashboard },
347
+ dashboard: { url: local.url, state: dashboard, healthy: localGateway.ok },
327
348
  app: { state: app },
328
349
  config: {
329
350
  source: configFile,
@@ -342,7 +363,7 @@ async function printCockpit({ noNetwork = false, json = false } = {}) {
342
363
 
343
364
  console.log(`${heading("PassControl")}\n`);
344
365
  console.log(formatLabel("Gateway", `${gateway.label} ${config.gateway}`));
345
- console.log(formatLabel("Dashboard", dashboard));
366
+ console.log(formatLabel("Dashboard", `${dashboard} ${local.url}`));
346
367
  console.log(formatLabel("App", app));
347
368
  console.log(formatLabel("Config", configFile));
348
369
  console.log(formatLabel("Provider", config.provider));
@@ -649,6 +670,40 @@ async function promptLine(question, fallback) {
649
670
  }
650
671
  }
651
672
 
673
+ async function readHiddenLine(question) {
674
+ if (!process.stdin.isTTY) {
675
+ let value = "";
676
+ for await (const chunk of process.stdin) value += chunk;
677
+ return value.replace(/\r?\n$/u, "").trim();
678
+ }
679
+ if (typeof process.stdin.setRawMode !== "function") {
680
+ throw new Error("This terminal cannot hide secret input. Redirect the secret on stdin from a private file or secret manager.");
681
+ }
682
+ process.stdout.write(question);
683
+ process.stdin.setRawMode(true);
684
+ process.stdin.resume();
685
+ return await new Promise((resolve, reject) => {
686
+ let value = "";
687
+ const finish = (error = null) => {
688
+ process.stdin.off("data", onData);
689
+ process.stdin.setRawMode(false);
690
+ process.stdin.pause();
691
+ process.stdout.write("\n");
692
+ if (error) reject(error);
693
+ else resolve(value);
694
+ };
695
+ const onData = (chunk) => {
696
+ for (const byte of Buffer.from(chunk)) {
697
+ if (byte === 3) return finish(new Error("Passport import cancelled."));
698
+ if (byte === 10 || byte === 13) return finish();
699
+ if (byte === 8 || byte === 127) value = value.slice(0, -1);
700
+ else value += String.fromCharCode(byte);
701
+ }
702
+ };
703
+ process.stdin.on("data", onData);
704
+ });
705
+ }
706
+
652
707
  /**
653
708
  * Yes/no prompt. Enter means YES unless `{ default: false }` is passed.
654
709
  *
@@ -663,6 +718,123 @@ async function confirmYes(question, { default: fallback = true } = {}) {
663
718
  return answer === "y" || answer === "yes";
664
719
  }
665
720
 
721
+ const GATEWAY_BOUND_CONFIG_KEYS = [
722
+ "PASSCONTROL_GATEWAY",
723
+ "PASSPORT_ID",
724
+ "PASSPORT_SECRET",
725
+ "PASSPORT_KEY_STORAGE",
726
+ "PASSCONTROL_API_KEY",
727
+ ];
728
+
729
+ function sameOrigin(left, right) {
730
+ try {
731
+ return bareGatewayOrigin(left) === bareGatewayOrigin(right);
732
+ } catch {
733
+ return false;
734
+ }
735
+ }
736
+
737
+ /** Decide a local-mode transition before starting any service. The decision is
738
+ * committed only after the local PassControl endpoint is healthy. */
739
+ async function prepareLocalActivation(target, opts = {}) {
740
+ const shellOverride = GATEWAY_BOUND_CONFIG_KEYS.find((key) => operatorEnv(key) !== undefined);
741
+ if (shellOverride) {
742
+ throw new Error(
743
+ `${shellOverride} comes from the operator environment, so a global self-host configuration cannot replace it. Unset it before running this command.`
744
+ );
745
+ }
746
+
747
+ const project = config.sources.find((source) =>
748
+ source.type === "project" && GATEWAY_BOUND_CONFIG_KEYS.some((key) => Object.hasOwn(source.values, key))
749
+ );
750
+ if (project) {
751
+ throw new Error(
752
+ `${project.path} overrides gateway-bound configuration. PassControl will not rewrite a project file during a machine-wide self-host switch. Remove those lines or run the command outside that project.`
753
+ );
754
+ }
755
+
756
+ const global = config.sources.find((source) => source.type === "global");
757
+ const values = global?.values ?? {};
758
+ const switching = !sameOrigin(config.gateway, target.url);
759
+ const passportId = String(values.PASSPORT_ID ?? "").trim();
760
+ const storageMarker = String(values.PASSPORT_KEY_STORAGE ?? "").trim();
761
+ const hasCredentials = switching && Boolean(
762
+ passportId ||
763
+ String(values.PASSPORT_SECRET ?? "").trim() ||
764
+ storageMarker ||
765
+ String(values.PASSCONTROL_API_KEY ?? "").trim()
766
+ );
767
+
768
+ if (hasCredentials && opts.forgetActiveCredentials !== true) {
769
+ const interactive = Boolean(process.stdin.isTTY && process.stdout.isTTY);
770
+ if (!interactive) {
771
+ throw new Error(
772
+ "Switching this machine to self-host would forget gateway-bound credentials. Re-run interactively to confirm, or pass --forget-active-credentials. --yes never authorises credential deletion."
773
+ );
774
+ }
775
+ warn(`The current credentials are bound to ${config.gateway}.`);
776
+ warn("Forgetting them locally does not revoke the remote control key or Passport agent.");
777
+ const confirmed = await confirmYes(
778
+ `Forget the local credentials and switch this machine to ${target.url}? [y/N] `,
779
+ { default: false }
780
+ );
781
+ if (!confirmed) throw new Error("Self-host switch cancelled; no services or credentials were changed.");
782
+ }
783
+
784
+ return {
785
+ target,
786
+ switching,
787
+ hasCredentials,
788
+ passportId,
789
+ storageMarker,
790
+ previousGateway: config.gateway,
791
+ globalPath: globalConfigPath(),
792
+ };
793
+ }
794
+
795
+ function restoreFileAtomically(file, contents) {
796
+ const directory = path.dirname(file);
797
+ fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
798
+ const temporary = path.join(directory, `.restore-${process.pid}-${Date.now()}.tmp`);
799
+ try {
800
+ fs.writeFileSync(temporary, contents, { mode: 0o600 });
801
+ fs.renameSync(temporary, file);
802
+ } finally {
803
+ fs.rmSync(temporary, { force: true });
804
+ }
805
+ }
806
+
807
+ function commitLocalActivation(prepared) {
808
+ if (!prepared.switching) return;
809
+ const existed = fs.existsSync(prepared.globalPath);
810
+ const previous = existed ? fs.readFileSync(prepared.globalPath, "utf8") : null;
811
+ mergeConfigFileAtomic(prepared.globalPath, {
812
+ PASSCONTROL_GATEWAY: prepared.target.url,
813
+ PASSPORT_ID: "",
814
+ PASSPORT_SECRET: "",
815
+ PASSPORT_KEY_STORAGE: "",
816
+ PASSCONTROL_API_KEY: "",
817
+ });
818
+
819
+ if (prepared.storageMarker === PASSPORT_KEY_STORAGE_OS && prepared.passportId) {
820
+ const removed = createPassportCredentialStore().delete(prepared.passportId);
821
+ if (!removed.ok) {
822
+ if (previous === null) fs.rmSync(prepared.globalPath, { force: true });
823
+ else restoreFileAtomically(prepared.globalPath, previous);
824
+ throw new Error(
825
+ `${removed.message}. The gateway switch was rolled back because the old Passport key could not be removed from the OS credential store.`
826
+ );
827
+ }
828
+ }
829
+
830
+ ok(`active gateway set to ${prepared.target.url}`);
831
+ if (prepared.hasCredentials) {
832
+ warn(`Credentials for ${prepared.previousGateway} were forgotten locally, not revoked remotely.`);
833
+ if (prepared.passportId) warn(`Remote Passport ID that may still need cleanup: ${prepared.passportId}`);
834
+ warn("Return to the previous gateway with an authorised machine to revoke any remaining remote identity.");
835
+ }
836
+ }
837
+
666
838
  // Resolve the stack checkout, cloning the public repo on demand when the CLI is
667
839
  // installed globally. `clone: false` never clones — it errors with a pointer to
668
840
  // `passcontrol setup` (used by reset/doctor, where there's nothing yet to act on).
@@ -826,27 +998,64 @@ async function startLocalServices() {
826
998
  }
827
999
  }
828
1000
 
829
- function localDashboard() {
1001
+ function parseLocalDashboard(value, label = "PASSCONTROL_GATEWAY") {
830
1002
  let url;
831
1003
  try {
832
- url = new URL(config.gateway);
1004
+ url = new URL(value);
833
1005
  } catch {
834
- throw new Error(`Invalid PASSCONTROL_GATEWAY URL: ${config.gateway}`);
1006
+ throw new Error(`Invalid ${label} URL.`);
835
1007
  }
836
1008
 
837
1009
  if (url.protocol !== "http:" || !LOCAL_DASHBOARD_HOSTS.has(url.hostname)) {
838
1010
  throw new Error(
839
- `passcontrol only manages local gateways (http://localhost or 127.0.0.1); configured gateway is ${config.gateway}.`
1011
+ `passcontrol only manages local HTTP gateways on localhost, 127.0.0.1 or [::1].`
840
1012
  );
841
1013
  }
842
-
843
- const port = Number(url.port || 80);
1014
+ if (!url.port) {
1015
+ throw new Error(
1016
+ `${label} is a local URL without an explicit port. Use ${LOCAL_DASHBOARD_ORIGIN}, or specify the port of the local dashboard you intend PassControl to manage.`
1017
+ );
1018
+ }
1019
+ const port = Number(url.port);
844
1020
  if (!Number.isInteger(port) || port < 1 || port > 65535) {
845
- throw new Error(`Invalid local dashboard port in PASSCONTROL_GATEWAY: ${config.gateway}`);
1021
+ throw new Error(`Invalid local dashboard port in ${label}.`);
846
1022
  }
847
1023
  return { url: url.toString().replace(/\/$/, ""), port };
848
1024
  }
849
1025
 
1026
+ function canonicalLocalDashboard() {
1027
+ return parseLocalDashboard(LOCAL_DASHBOARD_ORIGIN, "the canonical local dashboard");
1028
+ }
1029
+
1030
+ /** Resolve the local process target independently from the active Cloud/API
1031
+ * gateway. A running state file wins, then an explicit valid local gateway;
1032
+ * remote active config falls back to the canonical local dashboard. */
1033
+ function managedDashboardTarget({ forceCanonical = false } = {}) {
1034
+ if (!forceCanonical) {
1035
+ const state = readDashboardState();
1036
+ if (state?.gateway) {
1037
+ try {
1038
+ return { ...parseLocalDashboard(state.gateway, "saved dashboard state"), state };
1039
+ } catch {
1040
+ removeDashboardState();
1041
+ }
1042
+ }
1043
+ let parsed = null;
1044
+ try {
1045
+ parsed = new URL(config.gateway);
1046
+ } catch {
1047
+ // The active gateway is reported separately; local management still has
1048
+ // a deterministic target.
1049
+ }
1050
+ if (parsed?.protocol === "http:" && LOCAL_DASHBOARD_HOSTS.has(parsed.hostname)) {
1051
+ // Deliberately outside the URL parse catch: a local URL without a port is
1052
+ // a configuration error, not a reason to silently choose another port.
1053
+ return parseLocalDashboard(config.gateway);
1054
+ }
1055
+ }
1056
+ return canonicalLocalDashboard();
1057
+ }
1058
+
850
1059
  function readDashboardState() {
851
1060
  const statePath = dashboardStatePath();
852
1061
  try {
@@ -874,16 +1083,11 @@ function runningManagedDashboard() {
874
1083
  }
875
1084
  }
876
1085
 
877
- function dashboardStatusLabel(gateway, noNetwork) {
878
- try {
879
- localDashboard();
880
- } catch {
881
- return "remote gateway (not managed locally)";
882
- }
1086
+ function dashboardStatusLabel(gateway, noNetwork, target = managedDashboardTarget()) {
883
1087
  if (noNetwork) return "local server not checked";
884
1088
  const managed = runningManagedDashboard();
885
1089
  if (managed) return gateway.ok ? `CLI-managed (PID ${managed.pid})` : `CLI-managed, unhealthy (PID ${managed.pid})`;
886
- return gateway.ok ? "online (not managed by CLI)" : "stopped";
1090
+ return gateway.ok ? `online at ${target.url} (not managed by CLI)` : `stopped (${target.url})`;
887
1091
  }
888
1092
 
889
1093
  const pause = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
@@ -917,9 +1121,9 @@ async function waitForPortRelease(port, timeoutMs = 5000) {
917
1121
  * caller (an already-running dashboard we did not spawn) knows the pid but the
918
1122
  * budget logic is the same either way.
919
1123
  */
920
- async function waitForGateway({ port = null, pid = null } = {}) {
1124
+ async function waitForGateway({ gateway = LOCAL_DASHBOARD_ORIGIN, port = null, pid = null } = {}) {
921
1125
  return awaitGateway({
922
- probeGateway: async () => (await gatewayStatus(false)).ok,
1126
+ probeGateway: async () => (await gatewayStatus(false, gateway)).ok,
923
1127
  probePort: port ? () => portIsListening(port) : null,
924
1128
  processAlive: pid
925
1129
  ? () => {
@@ -1010,7 +1214,7 @@ async function runLocalPrerequisiteChecks({ offset = 0, report = false, enforce
1010
1214
  // a Control Tower talking to a stopped database.
1011
1215
  async function startDashboard(opts = {}) {
1012
1216
  await ensureAppRoot({ clone: true, appDir: opts.appDir, yes: opts.yes });
1013
- const dashboard = localDashboard();
1217
+ const dashboard = opts.dashboardTarget ?? managedDashboardTarget({ forceCanonical: opts.forceCanonical === true });
1014
1218
 
1015
1219
  const envFile = path.join(appRoot, ".env.docker");
1016
1220
  if (!fs.existsSync(envFile)) {
@@ -1020,7 +1224,7 @@ async function startDashboard(opts = {}) {
1020
1224
  if (opts.dashboardOnly) step("Leaving Supabase and Redis alone (--dashboard-only).");
1021
1225
  else await startLocalServices();
1022
1226
 
1023
- if ((await gatewayStatus(false)).ok) {
1227
+ if ((await gatewayStatus(false, dashboard.url)).ok) {
1024
1228
  ok(`dashboard already online at ${dashboard.url}`);
1025
1229
  return dashboard;
1026
1230
  }
@@ -1028,7 +1232,7 @@ async function startDashboard(opts = {}) {
1028
1232
  const running = runningManagedDashboard();
1029
1233
  if (running) {
1030
1234
  step(`dashboard is still starting (PID ${running.pid}); waiting for ${dashboard.url}…`);
1031
- if (await waitForGateway({ port: dashboard.port, pid: running.pid })) {
1235
+ if (await waitForGateway({ gateway: dashboard.url, port: dashboard.port, pid: running.pid })) {
1032
1236
  ok(`dashboard online at ${dashboard.url}`);
1033
1237
  return dashboard;
1034
1238
  }
@@ -1039,7 +1243,15 @@ async function startDashboard(opts = {}) {
1039
1243
  const logPath = dashboardLogPath();
1040
1244
  fs.mkdirSync(path.dirname(statePath), { recursive: true, mode: 0o700 });
1041
1245
  const logFd = fs.openSync(logPath, "a", 0o600);
1042
- const child = spawn(process.platform === "win32" ? "npm.cmd" : "npm", ["run", "dev:docker"], {
1246
+ // `node scripts/dev-docker.mjs` rather than `npm run dev:docker`: identical
1247
+ // work (that is all the npm script is now), minus npm/cmd wrappers. Next's CLI
1248
+ // still forks its HTTP worker, so this pid is deliberately the SUPERVISOR.
1249
+ // Unix stops its process group; Windows uses taskkill /T for the whole tree.
1250
+ const devServer = path.join(appRoot, "scripts", "dev-docker.mjs");
1251
+ if (!fs.existsSync(devServer)) {
1252
+ throw new Error(`${devServer} is missing — this checkout is incomplete or predates the local-stack launcher. Re-clone, or run \`npm run dev:docker\` from ${appRoot} by hand.`);
1253
+ }
1254
+ const child = spawn(process.execPath, [devServer], {
1043
1255
  cwd: appRoot,
1044
1256
  detached: process.platform !== "win32",
1045
1257
  env: { ...process.env, PORT: String(dashboard.port) },
@@ -1054,7 +1266,8 @@ async function startDashboard(opts = {}) {
1054
1266
  );
1055
1267
 
1056
1268
  step(`starting local dashboard at ${dashboard.url}…`);
1057
- if (!await waitForGateway({ port: dashboard.port, pid: child.pid })) {
1269
+ if (!await waitForGateway({ gateway: dashboard.url, port: dashboard.port, pid: child.pid })) {
1270
+ removeDashboardState();
1058
1271
  throw new Error(`Dashboard did not become ready. See ${logPath}.`);
1059
1272
  }
1060
1273
  ok(`dashboard online at ${dashboard.url}`);
@@ -1069,8 +1282,13 @@ async function stopDashboard() {
1069
1282
  }
1070
1283
 
1071
1284
  try {
1072
- if (process.platform === "win32") process.kill(state.pid, "SIGTERM");
1073
- else process.kill(-state.pid, "SIGTERM");
1285
+ if (process.platform === "win32") {
1286
+ execFileSync("taskkill.exe", ["/PID", String(state.pid), "/T"], {
1287
+ encoding: "utf8",
1288
+ timeout: 10_000,
1289
+ windowsHide: true,
1290
+ });
1291
+ } else process.kill(-state.pid, "SIGTERM");
1074
1292
  } catch (error) {
1075
1293
  if (error.code === "ESRCH") {
1076
1294
  removeDashboardState();
@@ -1081,7 +1299,13 @@ async function stopDashboard() {
1081
1299
  }
1082
1300
 
1083
1301
  if (!await waitForPortRelease(state.port)) {
1084
- if (process.platform === "win32") process.kill(state.pid, "SIGKILL");
1302
+ if (process.platform === "win32") {
1303
+ execFileSync("taskkill.exe", ["/PID", String(state.pid), "/T", "/F"], {
1304
+ encoding: "utf8",
1305
+ timeout: 10_000,
1306
+ windowsHide: true,
1307
+ });
1308
+ }
1085
1309
  else process.kill(-state.pid, "SIGKILL");
1086
1310
  if (!await waitForPortRelease(state.port)) {
1087
1311
  throw new Error(`Dashboard process group ${state.pid} did not release port ${state.port}.`);
@@ -1154,16 +1378,32 @@ async function stopLocalService(label, command, args, cwd, env = process.env) {
1154
1378
  }
1155
1379
 
1156
1380
  async function restartDashboard(opts = {}) {
1157
- localDashboard();
1381
+ const target = opts.dashboardTarget ?? managedDashboardTarget();
1158
1382
  const managed = runningManagedDashboard();
1159
1383
  if (!managed) {
1160
- if ((await gatewayStatus(false)).ok) {
1384
+ if ((await gatewayStatus(false, target.url)).ok) {
1161
1385
  throw new Error("Dashboard is online but was not started by passcontrol; stop it manually before restarting.");
1162
1386
  }
1163
- return startDashboard(opts);
1387
+ return startDashboard({ ...opts, dashboardTarget: target });
1164
1388
  }
1165
1389
  await stopDashboard();
1166
- return startDashboard(opts);
1390
+ return startDashboard({ ...opts, dashboardTarget: target });
1391
+ }
1392
+
1393
+ async function startLocalCommand(opts = {}) {
1394
+ const target = managedDashboardTarget();
1395
+ const activation = await prepareLocalActivation(target, opts);
1396
+ const dashboard = await startDashboard({ ...opts, dashboardTarget: target });
1397
+ commitLocalActivation(activation);
1398
+ return dashboard;
1399
+ }
1400
+
1401
+ async function restartLocalCommand(opts = {}) {
1402
+ const target = managedDashboardTarget();
1403
+ const activation = await prepareLocalActivation(target, opts);
1404
+ const dashboard = await restartDashboard({ ...opts, dashboardTarget: target });
1405
+ commitLocalActivation(activation);
1406
+ return dashboard;
1167
1407
  }
1168
1408
 
1169
1409
  async function localLogsCommand(opts = {}) {
@@ -1185,9 +1425,22 @@ async function localLogsCommand(opts = {}) {
1185
1425
  });
1186
1426
  }
1187
1427
 
1428
+ // Windows will not spawn a `.cmd`/`.bat` without a shell. Since Node 18.20.2 /
1429
+ // 20.12.2 (the CVE-2024-27980 hardening) it refuses outright with EINVAL rather
1430
+ // than executing it, which is how `passcontrol setup` died on the very first
1431
+ // step with nothing but `✗ spawn EINVAL` to go on.
1432
+ //
1433
+ // Scoped to batch files ON PURPOSE, not applied to every spawn. `runCommand`
1434
+ // also carries `docker compose -f docker/compose.yml` and `supabase start`;
1435
+ // routing those through cmd.exe would re-introduce shell quoting to arguments
1436
+ // that today are passed as an array and are safe in a path containing spaces.
1437
+ function batchFileShell(command) {
1438
+ return process.platform === "win32" && /\.(cmd|bat)$/i.test(command) ? { shell: true } : {};
1439
+ }
1440
+
1188
1441
  async function runCommand(command, args, { cwd = appRoot, env = process.env } = {}) {
1189
1442
  await new Promise((resolve, reject) => {
1190
- const child = spawn(command, args, { cwd, env, stdio: "inherit" });
1443
+ const child = spawn(command, args, { cwd, env, stdio: "inherit", ...batchFileShell(command) });
1191
1444
  child.once("error", reject);
1192
1445
  child.once("exit", (code) => code === 0 ? resolve() : reject(new Error(`${command} exited with code ${code}.`)));
1193
1446
  });
@@ -1232,7 +1485,7 @@ async function resetLocalStack(opts = {}) {
1232
1485
  if (opts.local !== true) {
1233
1486
  throw new Error("Usage: passcontrol reset --local --confirm RESET");
1234
1487
  }
1235
- localDashboard();
1488
+ managedDashboardTarget();
1236
1489
  if (opts.confirm !== "RESET") {
1237
1490
  throw new Error("reset refuses to delete local data without `--confirm RESET`.");
1238
1491
  }
@@ -1251,7 +1504,8 @@ async function resetLocalStack(opts = {}) {
1251
1504
  }
1252
1505
 
1253
1506
  async function setupLocal(opts = {}) {
1254
- const dashboard = localDashboard();
1507
+ const dashboard = canonicalLocalDashboard();
1508
+ const activation = await prepareLocalActivation(dashboard, opts);
1255
1509
  const offset = opts.portOffset === undefined ? 0 : Number(opts.portOffset);
1256
1510
  if (!Number.isInteger(offset) || offset < 0 || offset > 10000) {
1257
1511
  throw new Error("--port-offset must be an integer from 0 to 10000.");
@@ -1266,8 +1520,9 @@ async function setupLocal(opts = {}) {
1266
1520
  // dev:stack has just brought Supabase and Redis up (and would have exited
1267
1521
  // non-zero if it hadn't), so skip start's own service pass rather than print
1268
1522
  // two "already running" lines under a banner that just said the stack is up.
1269
- await startDashboard({ ...opts, dashboardOnly: true });
1270
- if (!opts.noOpen) await openDashboard(opts);
1523
+ await startDashboard({ ...opts, dashboardOnly: true, dashboardTarget: dashboard });
1524
+ commitLocalActivation(activation);
1525
+ if (!opts.noOpen) openUrl(dashboard.url);
1271
1526
  console.log(`\n${formatLabel("Local dashboard", dashboard.url, 19)}`);
1272
1527
  console.log(formatLabel("Login", "the account you created during setup", 19));
1273
1528
  step("Add a non-critical provider key, issue a passport, then run `passcontrol doctor --deep`.");
@@ -1521,7 +1776,7 @@ async function agentCommand(rest, opts) {
1521
1776
  if (!name) throw new Error("Usage: passcontrol agent create <name>");
1522
1777
  const provider = String(opts.provider || config.provider);
1523
1778
  assertProvider(provider);
1524
- const scopeModel = String(opts.scope || (provider === "anthropic" ? "claude-*" : activeModel(provider, opts)));
1779
+ const scopeModel = String(opts.scope || defaultAllowedModelForProvider(provider));
1525
1780
  const priv = ed25519.utils.randomPrivateKey();
1526
1781
  const pub = ed25519.getPublicKey(priv);
1527
1782
  const passportId = b64url(pub);
@@ -2125,7 +2380,7 @@ async function doctorCommand(opts = {}) {
2125
2380
  console.log("");
2126
2381
  let dashboard;
2127
2382
  try {
2128
- dashboard = localDashboard();
2383
+ dashboard = managedDashboardTarget();
2129
2384
  } catch {
2130
2385
  step("--fix manages only a local dashboard; remote gateways are not changed.");
2131
2386
  }
@@ -2355,12 +2610,35 @@ async function statementsCommand(opts) {
2355
2610
  );
2356
2611
  }
2357
2612
 
2358
- async function keygenCommand(rest) {
2613
+ async function keygenCommand(rest, opts = {}) {
2359
2614
  const target = rest[0];
2360
2615
  if (target !== "instance") {
2361
2616
  throw new Error(`Usage: ${cliCommand("keygen instance")}`);
2362
2617
  }
2363
2618
 
2619
+ // `--retire <seed>` prints the public pair for a key being taken out of
2620
+ // service. Nothing about it is secret, and that is the point: the operator
2621
+ // has no other way to derive a public half, and the alternative they reach
2622
+ // for — pasting the seed — is 32 base64url bytes too.
2623
+ // From `opts`, not `rest`: parseArgv consumes every `--flag` and its value
2624
+ // before the command ever sees the array, so scanning `rest` for "--retire"
2625
+ // finds nothing and silently generates a NEW key instead — which, run against
2626
+ // a live deployment's seed, looks like it worked.
2627
+ if (opts.retire !== undefined) {
2628
+ const seed = typeof opts.retire === "string" ? opts.retire : "";
2629
+ if (!seed) throw new Error(`Usage: ${cliCommand("keygen instance --retire <seed>")}`);
2630
+ const { entry, kid } = retiredKeyEntry(seed);
2631
+ ok(`Retired key ${kid}.`);
2632
+ step("Append this to INSTANCE_SIGNING_KEY_HISTORY (comma-separated) and leave it there");
2633
+ step("forever — receipts carry no expiry, so this is what keeps old ones checkable:");
2634
+ console.log(` ${entry}`);
2635
+ console.log("");
2636
+ step("It is a PUBLIC key. It cannot sign, which is why history takes this and not the");
2637
+ step("seed: a retired seed left in configuration can mint new receipts under the old kid.");
2638
+ step("Delete the seed once this is in place.");
2639
+ return;
2640
+ }
2641
+
2364
2642
  const { seed, kid } = generateInstanceKey();
2365
2643
  ok("Generated an Ed25519 instance signing key.");
2366
2644
  step("This key signs call receipts and agent-to-agent tokens. Store the seed like a password:");
@@ -2370,10 +2648,14 @@ async function keygenCommand(rest) {
2370
2648
  step("Also set PASSCONTROL_ISSUER to this deployment's https origin — it becomes the");
2371
2649
  step("`iss` claim, and the origin other deployments use to find this one's JWKS.");
2372
2650
  step("");
2373
- step("Rotating? Move the current value to INSTANCE_SIGNING_KEY_PREV and keep it there.");
2374
- step("Unlike VISA_SECRET_PREV we never sign with it — its public key stays published so");
2375
- step("receipts signed before the rotation still verify. Publish the new key, wait one");
2376
- step("JWKS max-age window, then start signing with it.");
2651
+ step("Rotating? Two steps, and the FIRST is the one that lasts:");
2652
+ step(` 1. ${cliCommand("keygen instance --retire <the old seed>")} — append the pair it prints`);
2653
+ step(" to INSTANCE_SIGNING_KEY_HISTORY. That list is permanent and public-only.");
2654
+ step(" 2. Move the old seed to INSTANCE_SIGNING_KEY_PREV for the changeover, then delete it.");
2655
+ step("Unlike VISA_SECRET_PREV we never sign with either — their public keys stay published");
2656
+ step("so receipts signed before the rotation still verify. _PREV holds ONE generation, so");
2657
+ step("history is what keeps the receipts from the rotation before this one checkable.");
2658
+ step("Publish the new key, wait one JWKS max-age window, then start signing with it.");
2377
2659
  }
2378
2660
 
2379
2661
  function passportFileForMigration() {
@@ -2436,6 +2718,91 @@ async function keyCommand(rest, opts = {}) {
2436
2718
  step(`Removed PASSPORT_SECRET from ${file.path} only after verified readback.`);
2437
2719
  }
2438
2720
 
2721
+ function isEncodedEd25519Key(value) {
2722
+ return /^[A-Za-z0-9_-]{43}$/u.test(value) && fromB64url(value).length === 32;
2723
+ }
2724
+
2725
+ async function passportCommand(rest, opts = {}) {
2726
+ const subcommand = rest[0];
2727
+ if (subcommand !== "import" || rest.length !== 1) {
2728
+ throw new Error(
2729
+ `Usage: ${cliCommand("passport import --global --gateway <origin> --id <passport-id> [--replace]")}`
2730
+ );
2731
+ }
2732
+ if (opts.global !== true) {
2733
+ throw new Error("Passport import is machine-wide for sidecar and MCP use; pass --global explicitly.");
2734
+ }
2735
+ if (typeof opts.gateway !== "string" || typeof opts.id !== "string") {
2736
+ throw new Error(
2737
+ `Usage: ${cliCommand("passport import --global --gateway <origin> --id <passport-id> [--replace]")}`
2738
+ );
2739
+ }
2740
+
2741
+ const gateway = bareGatewayOrigin(opts.gateway, "--gateway");
2742
+ const passportId = opts.id.trim();
2743
+ if (!isEncodedEd25519Key(passportId)) {
2744
+ throw new Error("--id must be a 32-byte Ed25519 public key encoded as unpadded base64url.");
2745
+ }
2746
+
2747
+ const project = config.sources.find((source) =>
2748
+ source.type === "project" && GATEWAY_BOUND_CONFIG_KEYS.some((key) => Object.hasOwn(source.values, key))
2749
+ );
2750
+ const shellOverride = GATEWAY_BOUND_CONFIG_KEYS.find((key) => operatorEnv(key) !== undefined);
2751
+ if (project) warn(`${project.path} contains gateway-bound values and will shadow this global import.`);
2752
+ if (shellOverride) warn(`${shellOverride} comes from the shell and will shadow this global import.`);
2753
+
2754
+ const target = globalConfigPath();
2755
+ const global = config.sources.find((source) => source.type === "global");
2756
+ const oldId = String(global?.values?.PASSPORT_ID ?? "").trim();
2757
+ const oldSecret = String(global?.values?.PASSPORT_SECRET ?? "").trim();
2758
+ const oldStorage = String(global?.values?.PASSPORT_KEY_STORAGE ?? "").trim();
2759
+ if ((oldId || oldSecret || oldStorage) && opts.replace !== true) {
2760
+ throw new Error(
2761
+ `A global Passport is already configured. Refusing to replace an unrecoverable key; re-run with --replace after verifying the old identity can be retired.`
2762
+ );
2763
+ }
2764
+
2765
+ const secret = await readHiddenLine("Paste the Passport secret (input hidden): ");
2766
+ if (!isEncodedEd25519Key(secret)) {
2767
+ throw new Error("Passport secret must be a 32-byte Ed25519 private key encoded as unpadded base64url.");
2768
+ }
2769
+ const derived = b64url(ed25519.getPublicKey(fromB64url(secret)));
2770
+ if (derived !== passportId) {
2771
+ throw new Error("Passport secret does not match the supplied Passport ID. Nothing was stored.");
2772
+ }
2773
+
2774
+ const store = createPassportCredentialStore();
2775
+ const written = store.write(passportId, secret);
2776
+ if (!written.ok) throw new Error(`${written.reason}. Nothing was written to the PassControl config.`);
2777
+ const readback = store.read(passportId);
2778
+ if (!readback.ok || readback.secret !== secret) {
2779
+ store.delete(passportId);
2780
+ throw new Error(`${store.name} did not return the key that was just stored. The new item was removed and config was not changed.`);
2781
+ }
2782
+
2783
+ try {
2784
+ mergeConfigFileAtomic(target, {
2785
+ PASSCONTROL_GATEWAY: gateway,
2786
+ PASSPORT_ID: passportId,
2787
+ PASSPORT_SECRET: "",
2788
+ PASSPORT_KEY_STORAGE: PASSPORT_KEY_STORAGE_OS,
2789
+ });
2790
+ } catch (error) {
2791
+ store.delete(passportId);
2792
+ throw error;
2793
+ }
2794
+
2795
+ if (oldStorage === PASSPORT_KEY_STORAGE_OS && oldId && oldId !== passportId) {
2796
+ const removed = store.delete(oldId);
2797
+ if (!removed.ok) {
2798
+ warn(`The previous Passport key could not be confirmed removed from ${store.name}; the new import is active, but the old OS item needs manual cleanup.`);
2799
+ }
2800
+ }
2801
+ ok(`Passport ${passportId} imported into ${store.name}.`);
2802
+ step(`Global gateway: ${gateway}`);
2803
+ step("The private key was verified and never written to the config file or command line.");
2804
+ }
2805
+
2439
2806
  async function openDashboard(opts = {}) {
2440
2807
  let parsed;
2441
2808
  try {
@@ -2444,7 +2811,7 @@ async function openDashboard(opts = {}) {
2444
2811
  throw new Error(`Invalid PASSCONTROL_GATEWAY URL: ${config.gateway}`);
2445
2812
  }
2446
2813
  const url = parsed.protocol === "http:" && LOCAL_DASHBOARD_HOSTS.has(parsed.hostname)
2447
- ? (await startDashboard(opts)).url
2814
+ ? (await startDashboard({ ...opts, dashboardTarget: parseLocalDashboard(config.gateway) })).url
2448
2815
  : config.gateway;
2449
2816
  openUrl(url);
2450
2817
  }
@@ -2546,11 +2913,32 @@ async function importCommand(rest = [], opts = {}) {
2546
2913
  );
2547
2914
  }
2548
2915
 
2916
+ // The envelope, before anything is planned or sent.
2917
+ //
2918
+ // This used to be `snapshot.workspace?.agents ?? []`, which turns a truncated
2919
+ // file into an empty fleet: the API plans nothing, `every()` over an empty
2920
+ // plan is true, the report says `complete: true`, and the CLI prints "Nothing
2921
+ // to create." and exits 0. A damaged snapshot restored no fleet at all and
2922
+ // every surface reported success (T4-03). A MISSING agents collection is
2923
+ // corruption; an EMPTY one is a workspace that genuinely has no agents and
2924
+ // still imports fine.
2925
+ //
2926
+ // The server validates this independently — it has to, since anyone can curl
2927
+ // it — but the operator holding the damaged file is here, so this is where the
2928
+ // message can name the file and say what is wrong with it.
2929
+ if (!Array.isArray(snapshot.workspace?.agents)) {
2930
+ throw new Error(
2931
+ `${file} has no "workspace.agents" array. That is a truncated or damaged export, ` +
2932
+ `not an empty workspace — importing it would restore nothing and report success. ` +
2933
+ `Re-export from the source deployment.`
2934
+ );
2935
+ }
2936
+
2549
2937
  // Only what the import writes goes on the wire. Provider mappings, break-glass
2550
2938
  // grants, the exclusions prose and the display settings stay on disk — they
2551
2939
  // are not importable, so sending them would spend the size budget on bytes the
2552
2940
  // server ignores.
2553
- const agents = snapshot.workspace?.agents ?? [];
2941
+ const agents = snapshot.workspace.agents;
2554
2942
  const payload = { agents, ownership: snapshot.workspace?.ownership ?? null };
2555
2943
  const size = Buffer.byteLength(JSON.stringify(payload));
2556
2944
  if (size > IMPORT_BODY_LIMIT) {
@@ -3064,13 +3452,13 @@ async function main(argv = process.argv.slice(2), runtime = {}) {
3064
3452
  await doctorCommand(opts);
3065
3453
  break;
3066
3454
  case "start":
3067
- await startDashboard(opts);
3455
+ await startLocalCommand(opts);
3068
3456
  break;
3069
3457
  case "stop":
3070
3458
  await stopCommand(opts);
3071
3459
  break;
3072
3460
  case "restart":
3073
- await restartDashboard(opts);
3461
+ await restartLocalCommand(opts);
3074
3462
  break;
3075
3463
  case "local-logs":
3076
3464
  await localLogsCommand(opts);
@@ -3141,7 +3529,10 @@ async function main(argv = process.argv.slice(2), runtime = {}) {
3141
3529
  await openDashboard(opts);
3142
3530
  break;
3143
3531
  case "keygen":
3144
- await keygenCommand(commandRest);
3532
+ await keygenCommand(commandRest, opts);
3533
+ break;
3534
+ case "passport":
3535
+ await passportCommand(commandRest, opts);
3145
3536
  break;
3146
3537
  case "key":
3147
3538
  await keyCommand(commandRest, opts);
package/cli/config.mjs CHANGED
@@ -8,6 +8,7 @@ import {
8
8
  keyStorageDeclaration,
9
9
  resolvePassportKey,
10
10
  } from "./passport-key-store.mjs";
11
+ import { defaultClientModelForProvider } from "./integration-defaults.mjs";
11
12
 
12
13
  export const CONFIG_FILE = ".passcontrol";
13
14
 
@@ -84,23 +85,7 @@ function paint(code, value) {
84
85
  }
85
86
 
86
87
  export function defaultModelForProvider(provider) {
87
- switch (provider) {
88
- case "openai":
89
- return "gpt-4o-mini";
90
- case "groq":
91
- return "llama-3.1-8b-instant";
92
- case "mistral":
93
- return "mistral-small-latest";
94
- case "together":
95
- return "openai/gpt-oss-20b";
96
- case "deepseek":
97
- return "deepseek-chat";
98
- case "gemini":
99
- return "gemini-2.5-flash";
100
- case "anthropic":
101
- default:
102
- return "claude-haiku-4-5";
103
- }
88
+ return defaultClientModelForProvider(provider);
104
89
  }
105
90
 
106
91
  function unquote(value) {
@@ -332,6 +317,36 @@ export function mergeConfigFile(file, patch) {
332
317
  writeConfigFile(file, { ...existing, ...patch });
333
318
  }
334
319
 
320
+ /** Merge a partial config through a same-directory temporary file and rename.
321
+ * Credential/gateway transitions use this so interruption cannot leave a
322
+ * half-written dotenv file that points a credential at the wrong origin. */
323
+ export function mergeConfigFileAtomic(file, patch) {
324
+ let existing = {};
325
+ try {
326
+ existing = readConfigFile(file);
327
+ } catch {
328
+ // First global configuration: the patch is the complete known state.
329
+ }
330
+ const directory = path.dirname(file);
331
+ fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
332
+ const temporary = path.join(
333
+ directory,
334
+ `.config-${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}.tmp`
335
+ );
336
+ try {
337
+ writeConfigFile(temporary, { ...existing, ...patch });
338
+ fs.renameSync(temporary, file);
339
+ try {
340
+ fs.chmodSync(file, 0o600);
341
+ fs.chmodSync(directory, 0o700);
342
+ } catch {
343
+ // Same portability rule as writeConfigFile.
344
+ }
345
+ } finally {
346
+ fs.rmSync(temporary, { force: true });
347
+ }
348
+ }
349
+
335
350
  export function heading(message = "") {
336
351
  return paint(ANSI.heading, message);
337
352
  }
@@ -57,7 +57,14 @@ export async function waitForGateway({
57
57
  let announced = false;
58
58
 
59
59
  while (now() < deadline) {
60
- if (await probeGateway()) return true;
60
+ if (await probeGateway()) {
61
+ // A response from the target is not proof that the process we launched
62
+ // owns it. In particular, a port conflict can leave an unrelated server
63
+ // answering while the launcher exits. The managed path requires both
64
+ // facts on the same poll.
65
+ if (processAlive && !processAlive()) return false;
66
+ return true;
67
+ }
61
68
 
62
69
  // Checked AFTER the gateway probe, never before: a process that exits the
63
70
  // instant it finishes handing off would otherwise be declared dead on the
@@ -27,6 +27,24 @@ export function generateInstanceKey() {
27
27
  return { seed, kid: instanceKidFromSeed(seed) };
28
28
  }
29
29
 
30
+ /**
31
+ * Turn a retiring SEED into the `<kid>:<x>` pair that goes in
32
+ * INSTANCE_SIGNING_KEY_HISTORY — public half only, so a retired key can never
33
+ * sign again.
34
+ *
35
+ * This exists because the operator cannot derive a public key by hand. Without
36
+ * it they would paste the seed, which is also 32 base64url bytes and would sail
37
+ * through any length check; the app rejects that pair because the kid does not
38
+ * recompute, but "rejected" only helps if there is a right value to type
39
+ * instead. Throws on anything that is not a 32-byte seed.
40
+ */
41
+ export function retiredKeyEntry(seed) {
42
+ const bytes = fromB64url(seed);
43
+ if (bytes.length !== 32) throw new Error("A signing seed is 32 bytes, base64url-encoded.");
44
+ const x = b64url(ed25519.getPublicKey(bytes));
45
+ return { entry: `${instanceKidFromSeed(seed)}:${x}`, kid: instanceKidFromSeed(seed) };
46
+ }
47
+
30
48
  /**
31
49
  * Verify that PASSCONTROL_ISSUER resolves to a deployment publishing OUR key.
32
50
  *
@@ -0,0 +1,13 @@
1
+ export type IntegrationProvider =
2
+ | "anthropic"
3
+ | "openai"
4
+ | "groq"
5
+ | "mistral"
6
+ | "together"
7
+ | "deepseek"
8
+ | "gemini";
9
+
10
+ export const DEFAULT_ALLOWED_MODELS: Readonly<Record<IntegrationProvider, string>>;
11
+ export const DEFAULT_CLIENT_MODELS: Readonly<Record<IntegrationProvider, string>>;
12
+ export function defaultAllowedModelForProvider(provider: string): string;
13
+ export function defaultClientModelForProvider(provider: string): string;
@@ -0,0 +1,33 @@
1
+ // Runtime-neutral defaults shared by the shipped CLI and the dashboard.
2
+ //
3
+ // Capability patterns and concrete provider model ids are different kinds of
4
+ // values. Keeping them beside each other, in the one module both runtimes can
5
+ // import, prevents onboarding from authorising one model and then calling
6
+ // another.
7
+ export const DEFAULT_ALLOWED_MODELS = Object.freeze({
8
+ anthropic: "claude-*",
9
+ openai: "gpt-*",
10
+ groq: "llama-*",
11
+ mistral: "mistral-*",
12
+ together: "openai/gpt-oss-*",
13
+ deepseek: "deepseek-*",
14
+ gemini: "gemini-*",
15
+ });
16
+
17
+ export const DEFAULT_CLIENT_MODELS = Object.freeze({
18
+ anthropic: "claude-haiku-4-5",
19
+ openai: "gpt-5-mini",
20
+ groq: "llama-3.3-70b-versatile",
21
+ mistral: "mistral-small-latest",
22
+ together: "openai/gpt-oss-20b",
23
+ deepseek: "deepseek-chat",
24
+ gemini: "gemini-2.5-flash",
25
+ });
26
+
27
+ export function defaultAllowedModelForProvider(provider) {
28
+ return DEFAULT_ALLOWED_MODELS[provider] ?? DEFAULT_ALLOWED_MODELS.anthropic;
29
+ }
30
+
31
+ export function defaultClientModelForProvider(provider) {
32
+ return DEFAULT_CLIENT_MODELS[provider] ?? DEFAULT_CLIENT_MODELS.anthropic;
33
+ }
package/cli/login.mjs CHANGED
@@ -51,6 +51,7 @@ import {
51
51
  step,
52
52
  warn,
53
53
  } from "./config.mjs";
54
+ import { defaultAllowedModelForProvider } from "./integration-defaults.mjs";
54
55
  import { proveItWorks } from "./selftest.mjs";
55
56
 
56
57
  export { CLOUD_GATEWAY };
@@ -516,7 +517,7 @@ export async function loginCommand(opts = {}, deps = {}) {
516
517
  // every agent able to self-test forever, which `doctor` can lean on.
517
518
  scopes: [
518
519
  { provider: "demo", models: ["*"] },
519
- { provider: "anthropic", models: ["claude-*"] },
520
+ { provider: "anthropic", models: [defaultAllowedModelForProvider("anthropic")] },
520
521
  ],
521
522
  }, fetchImpl);
522
523
  agentId = created?.id ?? null;
package/cli/mcp/README.md CHANGED
@@ -7,9 +7,15 @@ passport in the global profile so clients can launch from any working directory
7
7
  embedding a secret:
8
8
 
9
9
  ```sh
10
- passcontrol init --global
10
+ passcontrol passport import --global --gateway https://YOUR-PASSCONTROL-HOST --id PUBLIC_PASSPORT_ID
11
+ # paste the one-time secret at the hidden prompt
11
12
  ```
12
13
 
14
+ The import command contains public values only. The CLI proves the Ed25519 secret matches the
15
+ ID, writes it to Keychain, Secret Service, or DPAPI, verifies readback, and atomically updates the
16
+ global profile. Existing global Passports require `--replace`; project and shell overrides are
17
+ reported because they shadow the global profile.
18
+
13
19
  The client receives neither the provider key nor the short-lived work visa. The
14
20
  server signs locally and obtains the visa from the gateway and sends every model call through the configured
15
21
  PassControl gateway.
@@ -54,7 +60,7 @@ backed up to `.bak`, and a different PassControl entry requires `--force`. No ge
54
60
  config contains a passport secret or provider key.
55
61
 
56
62
 
57
- In 0.9.0 `chat` sends a bearer visa, without a sender proof. Required sender-proof mode
63
+ `chat` sends a bearer visa, without a sender proof. Required sender-proof mode
58
64
  therefore refuses it; use off/observe for this client. `list_models` reads model patterns
59
65
  from the visa scope, not a live upstream model catalog; a wildcard is not a callable model.
60
66
  Providers: OpenAI, Anthropic, Groq, Mistral, Together, DeepSeek, and Gemini (OpenAI-compatible).
package/cli/menu.mjs CHANGED
@@ -194,6 +194,13 @@ export const GROUPS = [
194
194
  items: [
195
195
  command({ id: "key-status", label: "Show the local key storage tier", run: ["key", "status"], detail: "key status", description: "Report where this machine resolves its passport private key.", current: currentFrom("key") }),
196
196
  command({ id: "key-migrate", label: "Move a file key into the OS store", run: ["key", "migrate"], detail: "key migrate", description: "Store the passport in the OS credential store, verify it, then remove the file copy.", effect: "local_write", guide: "key-migrate", current: currentFrom("key") }),
197
+ // Sits with `key migrate` rather than under Setup & config because what it
198
+ // decides is where a passport private key ends up living, which is this
199
+ // group's question. `needsArgs` for the usual reason plus one of its own:
200
+ // the gateway and passport ID have to come from the operator, and the
201
+ // secret is read from a hidden prompt that the command owns — it must
202
+ // never be reachable as a bare selection that then asks for a key.
203
+ command({ id: "passport-import", label: "Import an issued passport", run: ["passport", "import"], detail: "passport import --global", description: "Prove a passport secret against its public ID, then store it in the OS store.", effect: "local_write", network: "none", needsArgs: true, current: currentFrom("key") }),
197
204
  ],
198
205
  },
199
206
  {
@@ -22,7 +22,11 @@ const MACOS_PASSWORD_PROMPT = /password data for new item/iu;
22
22
  * exists for the same reason — so that check costs under a second instead of the
23
23
  * full helper timeout.
24
24
  */
25
- export function runProcess(command, args, { input = "", env = {}, timeoutMs = COMMAND_TIMEOUT_MS } = {}) {
25
+ export function runProcess(
26
+ command,
27
+ args,
28
+ { input = "", env = {}, timeoutMs = COMMAND_TIMEOUT_MS, detached = false } = {}
29
+ ) {
26
30
  const result = spawnSync(command, args, {
27
31
  input,
28
32
  encoding: "utf8",
@@ -31,6 +35,11 @@ export function runProcess(command, args, { input = "", env = {}, timeoutMs = CO
31
35
  maxBuffer: 64 * 1024,
32
36
  env: { ...process.env, ...env },
33
37
  stdio: ["pipe", "pipe", "pipe"],
38
+ // `detached` puts the child in its own session (setsid), which leaves it with
39
+ // NO controlling terminal. Only one caller wants that and it is documented at
40
+ // that call site; it is off by default because on Windows the same flag opens
41
+ // a new console window, which no adapter here has any use for.
42
+ detached,
34
43
  });
35
44
  // Deliberately omit stderr and the native Error object. Helpers sometimes
36
45
  // repeat their input in diagnostics, and no caller may log that raw text.
@@ -159,10 +168,23 @@ export function createPassportCredentialStore({
159
168
  if (/[\r\n]/u.test(secret)) {
160
169
  return fixedFailure("macOS Keychain cannot store a key containing a newline");
161
170
  }
171
+ // `detached` is what makes the stdin above reachable, and without it none
172
+ // of the reasoning in the comment above holds. Given a controlling
173
+ // terminal, security(1) does not read the prompt from stdin at all — it
174
+ // opens /dev/tty and asks the human, so the pipe is ignored, the write
175
+ // stalls until the helper timeout, and the key never lands. Detaching the
176
+ // child into its own session removes the terminal it would have reached
177
+ // for, and it falls back to stdin, which is where the secret already is.
178
+ //
179
+ // The consequence of getting this wrong is not a flaky test: it is that
180
+ // the feature works in every context that has no tty — CI, an agent shell,
181
+ // a piped script — and fails in the ONLY context that has one, which is a
182
+ // person at a terminal. tests/passport-key-store-os.test.ts owns a pty for
183
+ // exactly this reason.
162
184
  const result = invoke(run,
163
185
  "security",
164
186
  ["add-generic-password", "-U", "-a", passportId, "-s", SERVICE, "-w"],
165
- { input: `${secret}\n${secret}\n` }
187
+ { input: `${secret}\n${secret}\n`, detached: true }
166
188
  );
167
189
  if (result.timedOut) {
168
190
  // The one place the prompt bit earns its keep: `security` stalling
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "passcontrol",
3
- "version": "0.9.1",
3
+ "version": "0.9.3",
4
4
  "description": "Identity, scope and budget controls for AI agents while provider keys stay server-side.",
5
5
  "license": "BUSL-1.1",
6
6
  "homepage": "https://passcontrol.vertias.eu",
package/sdk/control.d.ts CHANGED
@@ -24,11 +24,47 @@ export interface ControlAccount {
24
24
  email: string | null;
25
25
  control_key_scope: "read" | "write";
26
26
  }
27
+ export interface SpendReconciliation {
28
+ state: "reconciled" | "pending" | "unavailable";
29
+ settled_tokens: number;
30
+ settled_microcents: number;
31
+ log_attributed_tokens: number | null;
32
+ log_attributed_microcents: number | null;
33
+ adjustment_tokens: number | null;
34
+ adjustment_microcents: number | null;
35
+ attributable_tokens: number | null;
36
+ attributable_microcents: number | null;
37
+ difference_tokens: number | null;
38
+ difference_microcents: number | null;
39
+ contributing_logs: number | null;
40
+ contributing_adjustments: number | null;
41
+ last_reconciled_at: string | null;
42
+ holds_state: "available" | "unavailable";
43
+ open_reserved_tokens: number | null;
44
+ open_reserved_microcents: number | null;
45
+ open_holds: number | null;
46
+ }
47
+ export interface SpendResponse {
48
+ fleet: {
49
+ spent_tokens: number;
50
+ spent_microcents: number;
51
+ basis: "enforced";
52
+ };
53
+ agents: Array<{
54
+ id: string;
55
+ name: string;
56
+ spent_tokens: number;
57
+ spent_microcents: number;
58
+ basis: "enforced";
59
+ }>;
60
+ reconciliation: SpendReconciliation;
61
+ }
27
62
  export declare class ControlClient {
28
63
  #private;
29
64
  private readonly base;
30
65
  private readonly transport;
31
66
  constructor(opts: ControlClientOptions);
67
+ private request;
32
68
  private req;
33
69
  readonly agents: {
34
70
  list: (params?: {
@@ -90,7 +126,18 @@ export declare class ControlClient {
90
126
  status?: string;
91
127
  class?: "inference" | "housekeeping";
92
128
  limit?: number;
129
+ cursor?: string;
93
130
  }) => Promise<any[]>;
131
+ page: (params?: {
132
+ agent_id?: string;
133
+ status?: string;
134
+ class?: "inference" | "housekeeping";
135
+ limit?: number;
136
+ cursor?: string;
137
+ }) => Promise<{
138
+ data: any[];
139
+ next_cursor: string | null;
140
+ }>;
94
141
  };
95
142
  readonly audit: {
96
143
  list: (params?: {
@@ -127,13 +174,7 @@ export declare class ControlClient {
127
174
  inclusion: (seq: number, receiptId: string) => Promise<any>;
128
175
  };
129
176
  readonly spend: {
130
- get: () => Promise<{
131
- fleet: {
132
- spent_tokens: number;
133
- spent_microcents: number;
134
- };
135
- agents: any[];
136
- }>;
177
+ get: () => Promise<SpendResponse>;
137
178
  };
138
179
  readonly killSwitch: {
139
180
  get: () => Promise<{
package/sdk/control.js CHANGED
@@ -53,7 +53,7 @@ export class ControlClient {
53
53
  throw new Error("ControlClient: no fetch available; pass options.fetch.");
54
54
  this.transport = (...a) => f(...a);
55
55
  }
56
- async req(method, path, opts = {}) {
56
+ async request(method, path, opts = {}) {
57
57
  const url = new URL(this.base + path);
58
58
  for (const [k, v] of Object.entries(opts.query ?? {})) {
59
59
  if (v !== undefined && v !== null)
@@ -75,7 +75,10 @@ export class ControlClient {
75
75
  const e = (json?.error ?? {});
76
76
  throw new ControlApiError(res.status, e.code ?? "error", e.message ?? res.statusText, e.request_id);
77
77
  }
78
- return json.data;
78
+ return json;
79
+ }
80
+ async req(method, path, opts = {}) {
81
+ return (await this.request(method, path, opts)).data;
79
82
  }
80
83
  agents = {
81
84
  list: (params) => this.req("GET", "/agents", { query: params }),
@@ -97,6 +100,7 @@ export class ControlClient {
97
100
  * filter, so a filtered page can be shorter than the limit asked for.
98
101
  */
99
102
  list: (params) => this.req("GET", "/logs", { query: params }),
103
+ page: (params) => this.request("GET", "/logs", { query: params }),
100
104
  };
101
105
  audit = {
102
106
  list: (params) => this.req("GET", "/audit", { query: params }),