passcontrol 0.9.2 → 0.9.4

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
@@ -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
 
@@ -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,
@@ -81,9 +82,11 @@ import {
81
82
  } from "../cli/instance-key.mjs";
82
83
  import { FAILURE_REASONS, verifyAgentToken, verifyReceipt, verifyStatement } from "../cli/verify.mjs";
83
84
  import { compareProtocolSets } from "../cli/protocols.mjs";
85
+ import { defaultAllowedModelForProvider } from "../cli/integration-defaults.mjs";
84
86
  import {
85
87
  PASSPORT_KEY_STORAGE_OS,
86
88
  createPassportCredentialStore,
89
+ importPassportKey,
87
90
  keyStorageDeclaration,
88
91
  migratePassportKey,
89
92
  } from "../cli/passport-key-store.mjs";
@@ -114,6 +117,7 @@ const PUBLIC_REPO_URL = "https://github.com/Vertias3u/PassControl.git";
114
117
  // origin, and keeping two copies is how they stop being the same origin.
115
118
  const HOSTED_DEMO_URL = CLOUD_GATEWAY;
116
119
  const LOCAL_DASHBOARD_HOSTS = new Set(["localhost", "127.0.0.1", "::1", "[::1]"]);
120
+ const LOCAL_DASHBOARD_ORIGIN = "http://localhost:3000";
117
121
  const LOCAL_STACK_PORTS = [54321, 54322, 54324, 54327, 8079];
118
122
  // The local stack (Supabase + Redis + dashboard) lives in a PassControl repo
119
123
  // checkout — NOT in the installed CLI package (which ships only bin/ + cli/).
@@ -185,6 +189,8 @@ ${heading("Operate")}
185
189
  ${cmd} open open the Control Tower in a browser
186
190
  ${cmd} logout [--revoke-agent] revoke this machine's key and clear its credentials
187
191
  ${cmd} init [--global] configure by hand, without a browser
192
+ ${cmd} passport import --global --gateway <origin> --id <passport-id> [--replace]
193
+ securely import a dashboard-issued passport
188
194
 
189
195
  ${heading("Manage")}
190
196
  ${cmd} agent list [--json] list agents
@@ -228,11 +234,13 @@ ${heading("Trust")}
228
234
  ${heading("Self-host — run your own gateway")}
229
235
  Clones the app and runs Docker + Supabase + Redis here. You operate it, and
230
236
  your instance signs its own receipts — they verify against your JWKS, not ours.
231
- ${cmd} setup [--no-open] [--port-offset N] [--app-dir DIR]
237
+ ${cmd} setup [--no-open] [--port-offset N] [--app-dir DIR] [--forget-active-credentials]
232
238
  clone the app, start Docker + Supabase + Redis
233
- ${cmd} start [--dashboard-only] start the whole local stack (clones the app if missing)
239
+ ${cmd} start [--dashboard-only] [--forget-active-credentials]
240
+ start the whole local stack (clones the app if missing)
234
241
  ${cmd} stop [--dashboard-only] stop the whole local stack (dashboard + Supabase + Redis)
235
- ${cmd} restart restart the CLI-managed local dashboard
242
+ ${cmd} restart [--forget-active-credentials]
243
+ restart the CLI-managed local dashboard
236
244
  ${cmd} local-logs [--follow] show local dashboard logs
237
245
  ${cmd} reset --local --confirm RESET
238
246
  destroy and recreate the local stack
@@ -297,13 +305,21 @@ async function fetchWithTimeout(url, init = {}, timeoutMs = 1200) {
297
305
  }
298
306
  }
299
307
 
300
- async function gatewayStatus(noNetwork = false) {
308
+ async function gatewayStatus(noNetwork = false, gateway = config.gateway) {
301
309
  if (noNetwork) return { label: "not checked", ok: null };
302
- const origin = probeGatewayOrigin(config);
310
+ const origin = probeGatewayOrigin({ gateway });
303
311
  if (!origin) return { label: "invalid configuration", ok: false };
304
312
  try {
305
- const res = await fetchWithTimeout(origin, { method: "GET" });
306
- return { label: res.ok ? `online (${res.status})` : `unhealthy (${res.status})`, ok: res.ok };
313
+ const res = await fetchWithTimeout(`${origin}/api/version`, {
314
+ method: "GET",
315
+ headers: { accept: "application/json" },
316
+ });
317
+ if (!res.ok) return { label: `unhealthy (${res.status})`, ok: false };
318
+ const body = await res.json().catch(() => null);
319
+ const version = typeof body?.version === "string" && body.version.trim() ? body.version.trim() : null;
320
+ return version
321
+ ? { label: `online (${res.status}, PassControl ${version})`, ok: true, version }
322
+ : { label: "unhealthy (not a PassControl version response)", ok: false };
307
323
  } catch {
308
324
  return { label: "offline or unreachable", ok: false };
309
325
  }
@@ -311,11 +327,13 @@ async function gatewayStatus(noNetwork = false) {
311
327
 
312
328
  async function printCockpit({ noNetwork = false, json = false } = {}) {
313
329
  const gateway = await gatewayStatus(noNetwork);
330
+ const local = managedDashboardTarget();
331
+ const localGateway = await gatewayStatus(noNetwork, local.url);
314
332
  const passportSecret = config.passportSecret;
315
333
  const passportStorage = config.passportStorage;
316
334
  const passportConfigured = Boolean(config.passportId && passportSecret);
317
335
  const adminConfigured = Boolean(config.apiKey);
318
- const dashboard = dashboardStatusLabel(gateway, noNetwork);
336
+ const dashboard = dashboardStatusLabel(localGateway, noNetwork, local);
319
337
  const app = appRootLabel();
320
338
  const configFile = configPathLabel(config.sources);
321
339
  // This is deliberately credential-gated. Status remains useful to an agent
@@ -327,7 +345,7 @@ async function printCockpit({ noNetwork = false, json = false } = {}) {
327
345
  console.log(JSON.stringify({
328
346
  version: CLI_VERSION,
329
347
  gateway: { url: config.gateway, state: gateway.label, healthy: gateway.ok },
330
- dashboard: { state: dashboard },
348
+ dashboard: { url: local.url, state: dashboard, healthy: localGateway.ok },
331
349
  app: { state: app },
332
350
  config: {
333
351
  source: configFile,
@@ -346,7 +364,7 @@ async function printCockpit({ noNetwork = false, json = false } = {}) {
346
364
 
347
365
  console.log(`${heading("PassControl")}\n`);
348
366
  console.log(formatLabel("Gateway", `${gateway.label} ${config.gateway}`));
349
- console.log(formatLabel("Dashboard", dashboard));
367
+ console.log(formatLabel("Dashboard", `${dashboard} ${local.url}`));
350
368
  console.log(formatLabel("App", app));
351
369
  console.log(formatLabel("Config", configFile));
352
370
  console.log(formatLabel("Provider", config.provider));
@@ -653,6 +671,40 @@ async function promptLine(question, fallback) {
653
671
  }
654
672
  }
655
673
 
674
+ async function readHiddenLine(question) {
675
+ if (!process.stdin.isTTY) {
676
+ let value = "";
677
+ for await (const chunk of process.stdin) value += chunk;
678
+ return value.replace(/\r?\n$/u, "").trim();
679
+ }
680
+ if (typeof process.stdin.setRawMode !== "function") {
681
+ throw new Error("This terminal cannot hide secret input. Redirect the secret on stdin from a private file or secret manager.");
682
+ }
683
+ process.stdout.write(question);
684
+ process.stdin.setRawMode(true);
685
+ process.stdin.resume();
686
+ return await new Promise((resolve, reject) => {
687
+ let value = "";
688
+ const finish = (error = null) => {
689
+ process.stdin.off("data", onData);
690
+ process.stdin.setRawMode(false);
691
+ process.stdin.pause();
692
+ process.stdout.write("\n");
693
+ if (error) reject(error);
694
+ else resolve(value);
695
+ };
696
+ const onData = (chunk) => {
697
+ for (const byte of Buffer.from(chunk)) {
698
+ if (byte === 3) return finish(new Error("Passport import cancelled."));
699
+ if (byte === 10 || byte === 13) return finish();
700
+ if (byte === 8 || byte === 127) value = value.slice(0, -1);
701
+ else value += String.fromCharCode(byte);
702
+ }
703
+ };
704
+ process.stdin.on("data", onData);
705
+ });
706
+ }
707
+
656
708
  /**
657
709
  * Yes/no prompt. Enter means YES unless `{ default: false }` is passed.
658
710
  *
@@ -667,6 +719,123 @@ async function confirmYes(question, { default: fallback = true } = {}) {
667
719
  return answer === "y" || answer === "yes";
668
720
  }
669
721
 
722
+ const GATEWAY_BOUND_CONFIG_KEYS = [
723
+ "PASSCONTROL_GATEWAY",
724
+ "PASSPORT_ID",
725
+ "PASSPORT_SECRET",
726
+ "PASSPORT_KEY_STORAGE",
727
+ "PASSCONTROL_API_KEY",
728
+ ];
729
+
730
+ function sameOrigin(left, right) {
731
+ try {
732
+ return bareGatewayOrigin(left) === bareGatewayOrigin(right);
733
+ } catch {
734
+ return false;
735
+ }
736
+ }
737
+
738
+ /** Decide a local-mode transition before starting any service. The decision is
739
+ * committed only after the local PassControl endpoint is healthy. */
740
+ async function prepareLocalActivation(target, opts = {}) {
741
+ const shellOverride = GATEWAY_BOUND_CONFIG_KEYS.find((key) => operatorEnv(key) !== undefined);
742
+ if (shellOverride) {
743
+ throw new Error(
744
+ `${shellOverride} comes from the operator environment, so a global self-host configuration cannot replace it. Unset it before running this command.`
745
+ );
746
+ }
747
+
748
+ const project = config.sources.find((source) =>
749
+ source.type === "project" && GATEWAY_BOUND_CONFIG_KEYS.some((key) => Object.hasOwn(source.values, key))
750
+ );
751
+ if (project) {
752
+ throw new Error(
753
+ `${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.`
754
+ );
755
+ }
756
+
757
+ const global = config.sources.find((source) => source.type === "global");
758
+ const values = global?.values ?? {};
759
+ const switching = !sameOrigin(config.gateway, target.url);
760
+ const passportId = String(values.PASSPORT_ID ?? "").trim();
761
+ const storageMarker = String(values.PASSPORT_KEY_STORAGE ?? "").trim();
762
+ const hasCredentials = switching && Boolean(
763
+ passportId ||
764
+ String(values.PASSPORT_SECRET ?? "").trim() ||
765
+ storageMarker ||
766
+ String(values.PASSCONTROL_API_KEY ?? "").trim()
767
+ );
768
+
769
+ if (hasCredentials && opts.forgetActiveCredentials !== true) {
770
+ const interactive = Boolean(process.stdin.isTTY && process.stdout.isTTY);
771
+ if (!interactive) {
772
+ throw new Error(
773
+ "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."
774
+ );
775
+ }
776
+ warn(`The current credentials are bound to ${config.gateway}.`);
777
+ warn("Forgetting them locally does not revoke the remote control key or Passport agent.");
778
+ const confirmed = await confirmYes(
779
+ `Forget the local credentials and switch this machine to ${target.url}? [y/N] `,
780
+ { default: false }
781
+ );
782
+ if (!confirmed) throw new Error("Self-host switch cancelled; no services or credentials were changed.");
783
+ }
784
+
785
+ return {
786
+ target,
787
+ switching,
788
+ hasCredentials,
789
+ passportId,
790
+ storageMarker,
791
+ previousGateway: config.gateway,
792
+ globalPath: globalConfigPath(),
793
+ };
794
+ }
795
+
796
+ function restoreFileAtomically(file, contents) {
797
+ const directory = path.dirname(file);
798
+ fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
799
+ const temporary = path.join(directory, `.restore-${process.pid}-${Date.now()}.tmp`);
800
+ try {
801
+ fs.writeFileSync(temporary, contents, { mode: 0o600 });
802
+ fs.renameSync(temporary, file);
803
+ } finally {
804
+ fs.rmSync(temporary, { force: true });
805
+ }
806
+ }
807
+
808
+ function commitLocalActivation(prepared) {
809
+ if (!prepared.switching) return;
810
+ const existed = fs.existsSync(prepared.globalPath);
811
+ const previous = existed ? fs.readFileSync(prepared.globalPath, "utf8") : null;
812
+ mergeConfigFileAtomic(prepared.globalPath, {
813
+ PASSCONTROL_GATEWAY: prepared.target.url,
814
+ PASSPORT_ID: "",
815
+ PASSPORT_SECRET: "",
816
+ PASSPORT_KEY_STORAGE: "",
817
+ PASSCONTROL_API_KEY: "",
818
+ });
819
+
820
+ if (prepared.storageMarker === PASSPORT_KEY_STORAGE_OS && prepared.passportId) {
821
+ const removed = createPassportCredentialStore().delete(prepared.passportId);
822
+ if (!removed.ok) {
823
+ if (previous === null) fs.rmSync(prepared.globalPath, { force: true });
824
+ else restoreFileAtomically(prepared.globalPath, previous);
825
+ throw new Error(
826
+ `${removed.message}. The gateway switch was rolled back because the old Passport key could not be removed from the OS credential store.`
827
+ );
828
+ }
829
+ }
830
+
831
+ ok(`active gateway set to ${prepared.target.url}`);
832
+ if (prepared.hasCredentials) {
833
+ warn(`Credentials for ${prepared.previousGateway} were forgotten locally, not revoked remotely.`);
834
+ if (prepared.passportId) warn(`Remote Passport ID that may still need cleanup: ${prepared.passportId}`);
835
+ warn("Return to the previous gateway with an authorised machine to revoke any remaining remote identity.");
836
+ }
837
+ }
838
+
670
839
  // Resolve the stack checkout, cloning the public repo on demand when the CLI is
671
840
  // installed globally. `clone: false` never clones — it errors with a pointer to
672
841
  // `passcontrol setup` (used by reset/doctor, where there's nothing yet to act on).
@@ -830,27 +999,64 @@ async function startLocalServices() {
830
999
  }
831
1000
  }
832
1001
 
833
- function localDashboard() {
1002
+ function parseLocalDashboard(value, label = "PASSCONTROL_GATEWAY") {
834
1003
  let url;
835
1004
  try {
836
- url = new URL(config.gateway);
1005
+ url = new URL(value);
837
1006
  } catch {
838
- throw new Error(`Invalid PASSCONTROL_GATEWAY URL: ${config.gateway}`);
1007
+ throw new Error(`Invalid ${label} URL.`);
839
1008
  }
840
1009
 
841
1010
  if (url.protocol !== "http:" || !LOCAL_DASHBOARD_HOSTS.has(url.hostname)) {
842
1011
  throw new Error(
843
- `passcontrol only manages local gateways (http://localhost or 127.0.0.1); configured gateway is ${config.gateway}.`
1012
+ `passcontrol only manages local HTTP gateways on localhost, 127.0.0.1 or [::1].`
844
1013
  );
845
1014
  }
846
-
847
- const port = Number(url.port || 80);
1015
+ if (!url.port) {
1016
+ throw new Error(
1017
+ `${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.`
1018
+ );
1019
+ }
1020
+ const port = Number(url.port);
848
1021
  if (!Number.isInteger(port) || port < 1 || port > 65535) {
849
- throw new Error(`Invalid local dashboard port in PASSCONTROL_GATEWAY: ${config.gateway}`);
1022
+ throw new Error(`Invalid local dashboard port in ${label}.`);
850
1023
  }
851
1024
  return { url: url.toString().replace(/\/$/, ""), port };
852
1025
  }
853
1026
 
1027
+ function canonicalLocalDashboard() {
1028
+ return parseLocalDashboard(LOCAL_DASHBOARD_ORIGIN, "the canonical local dashboard");
1029
+ }
1030
+
1031
+ /** Resolve the local process target independently from the active Cloud/API
1032
+ * gateway. A running state file wins, then an explicit valid local gateway;
1033
+ * remote active config falls back to the canonical local dashboard. */
1034
+ function managedDashboardTarget({ forceCanonical = false } = {}) {
1035
+ if (!forceCanonical) {
1036
+ const state = readDashboardState();
1037
+ if (state?.gateway) {
1038
+ try {
1039
+ return { ...parseLocalDashboard(state.gateway, "saved dashboard state"), state };
1040
+ } catch {
1041
+ removeDashboardState();
1042
+ }
1043
+ }
1044
+ let parsed = null;
1045
+ try {
1046
+ parsed = new URL(config.gateway);
1047
+ } catch {
1048
+ // The active gateway is reported separately; local management still has
1049
+ // a deterministic target.
1050
+ }
1051
+ if (parsed?.protocol === "http:" && LOCAL_DASHBOARD_HOSTS.has(parsed.hostname)) {
1052
+ // Deliberately outside the URL parse catch: a local URL without a port is
1053
+ // a configuration error, not a reason to silently choose another port.
1054
+ return parseLocalDashboard(config.gateway);
1055
+ }
1056
+ }
1057
+ return canonicalLocalDashboard();
1058
+ }
1059
+
854
1060
  function readDashboardState() {
855
1061
  const statePath = dashboardStatePath();
856
1062
  try {
@@ -878,16 +1084,11 @@ function runningManagedDashboard() {
878
1084
  }
879
1085
  }
880
1086
 
881
- function dashboardStatusLabel(gateway, noNetwork) {
882
- try {
883
- localDashboard();
884
- } catch {
885
- return "remote gateway (not managed locally)";
886
- }
1087
+ function dashboardStatusLabel(gateway, noNetwork, target = managedDashboardTarget()) {
887
1088
  if (noNetwork) return "local server not checked";
888
1089
  const managed = runningManagedDashboard();
889
1090
  if (managed) return gateway.ok ? `CLI-managed (PID ${managed.pid})` : `CLI-managed, unhealthy (PID ${managed.pid})`;
890
- return gateway.ok ? "online (not managed by CLI)" : "stopped";
1091
+ return gateway.ok ? `online at ${target.url} (not managed by CLI)` : `stopped (${target.url})`;
891
1092
  }
892
1093
 
893
1094
  const pause = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
@@ -921,9 +1122,9 @@ async function waitForPortRelease(port, timeoutMs = 5000) {
921
1122
  * caller (an already-running dashboard we did not spawn) knows the pid but the
922
1123
  * budget logic is the same either way.
923
1124
  */
924
- async function waitForGateway({ port = null, pid = null } = {}) {
1125
+ async function waitForGateway({ gateway = LOCAL_DASHBOARD_ORIGIN, port = null, pid = null } = {}) {
925
1126
  return awaitGateway({
926
- probeGateway: async () => (await gatewayStatus(false)).ok,
1127
+ probeGateway: async () => (await gatewayStatus(false, gateway)).ok,
927
1128
  probePort: port ? () => portIsListening(port) : null,
928
1129
  processAlive: pid
929
1130
  ? () => {
@@ -1014,7 +1215,7 @@ async function runLocalPrerequisiteChecks({ offset = 0, report = false, enforce
1014
1215
  // a Control Tower talking to a stopped database.
1015
1216
  async function startDashboard(opts = {}) {
1016
1217
  await ensureAppRoot({ clone: true, appDir: opts.appDir, yes: opts.yes });
1017
- const dashboard = localDashboard();
1218
+ const dashboard = opts.dashboardTarget ?? managedDashboardTarget({ forceCanonical: opts.forceCanonical === true });
1018
1219
 
1019
1220
  const envFile = path.join(appRoot, ".env.docker");
1020
1221
  if (!fs.existsSync(envFile)) {
@@ -1024,7 +1225,7 @@ async function startDashboard(opts = {}) {
1024
1225
  if (opts.dashboardOnly) step("Leaving Supabase and Redis alone (--dashboard-only).");
1025
1226
  else await startLocalServices();
1026
1227
 
1027
- if ((await gatewayStatus(false)).ok) {
1228
+ if ((await gatewayStatus(false, dashboard.url)).ok) {
1028
1229
  ok(`dashboard already online at ${dashboard.url}`);
1029
1230
  return dashboard;
1030
1231
  }
@@ -1032,7 +1233,7 @@ async function startDashboard(opts = {}) {
1032
1233
  const running = runningManagedDashboard();
1033
1234
  if (running) {
1034
1235
  step(`dashboard is still starting (PID ${running.pid}); waiting for ${dashboard.url}…`);
1035
- if (await waitForGateway({ port: dashboard.port, pid: running.pid })) {
1236
+ if (await waitForGateway({ gateway: dashboard.url, port: dashboard.port, pid: running.pid })) {
1036
1237
  ok(`dashboard online at ${dashboard.url}`);
1037
1238
  return dashboard;
1038
1239
  }
@@ -1044,12 +1245,9 @@ async function startDashboard(opts = {}) {
1044
1245
  fs.mkdirSync(path.dirname(statePath), { recursive: true, mode: 0o700 });
1045
1246
  const logFd = fs.openSync(logPath, "a", 0o600);
1046
1247
  // `node scripts/dev-docker.mjs` rather than `npm run dev:docker`: identical
1047
- // work (that is all the npm script is now), minus two wrapper processes. The
1048
- // pid recorded below is then the dev server itself, which matters because
1049
- // stopDashboard signals a single pid on Windows rather than a process group —
1050
- // through npm.cmd it would kill the wrapper and leave the server holding the
1051
- // port. It also keeps the one path that runs daily clear of the Windows
1052
- // batch-file spawn restriction that batchFileShell exists to work around.
1248
+ // work (that is all the npm script is now), minus npm/cmd wrappers. Next's CLI
1249
+ // still forks its HTTP worker, so this pid is deliberately the SUPERVISOR.
1250
+ // Unix stops its process group; Windows uses taskkill /T for the whole tree.
1053
1251
  const devServer = path.join(appRoot, "scripts", "dev-docker.mjs");
1054
1252
  if (!fs.existsSync(devServer)) {
1055
1253
  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.`);
@@ -1069,7 +1267,8 @@ async function startDashboard(opts = {}) {
1069
1267
  );
1070
1268
 
1071
1269
  step(`starting local dashboard at ${dashboard.url}…`);
1072
- if (!await waitForGateway({ port: dashboard.port, pid: child.pid })) {
1270
+ if (!await waitForGateway({ gateway: dashboard.url, port: dashboard.port, pid: child.pid })) {
1271
+ removeDashboardState();
1073
1272
  throw new Error(`Dashboard did not become ready. See ${logPath}.`);
1074
1273
  }
1075
1274
  ok(`dashboard online at ${dashboard.url}`);
@@ -1084,8 +1283,13 @@ async function stopDashboard() {
1084
1283
  }
1085
1284
 
1086
1285
  try {
1087
- if (process.platform === "win32") process.kill(state.pid, "SIGTERM");
1088
- else process.kill(-state.pid, "SIGTERM");
1286
+ if (process.platform === "win32") {
1287
+ execFileSync("taskkill.exe", ["/PID", String(state.pid), "/T"], {
1288
+ encoding: "utf8",
1289
+ timeout: 10_000,
1290
+ windowsHide: true,
1291
+ });
1292
+ } else process.kill(-state.pid, "SIGTERM");
1089
1293
  } catch (error) {
1090
1294
  if (error.code === "ESRCH") {
1091
1295
  removeDashboardState();
@@ -1096,7 +1300,13 @@ async function stopDashboard() {
1096
1300
  }
1097
1301
 
1098
1302
  if (!await waitForPortRelease(state.port)) {
1099
- if (process.platform === "win32") process.kill(state.pid, "SIGKILL");
1303
+ if (process.platform === "win32") {
1304
+ execFileSync("taskkill.exe", ["/PID", String(state.pid), "/T", "/F"], {
1305
+ encoding: "utf8",
1306
+ timeout: 10_000,
1307
+ windowsHide: true,
1308
+ });
1309
+ }
1100
1310
  else process.kill(-state.pid, "SIGKILL");
1101
1311
  if (!await waitForPortRelease(state.port)) {
1102
1312
  throw new Error(`Dashboard process group ${state.pid} did not release port ${state.port}.`);
@@ -1169,16 +1379,32 @@ async function stopLocalService(label, command, args, cwd, env = process.env) {
1169
1379
  }
1170
1380
 
1171
1381
  async function restartDashboard(opts = {}) {
1172
- localDashboard();
1382
+ const target = opts.dashboardTarget ?? managedDashboardTarget();
1173
1383
  const managed = runningManagedDashboard();
1174
1384
  if (!managed) {
1175
- if ((await gatewayStatus(false)).ok) {
1385
+ if ((await gatewayStatus(false, target.url)).ok) {
1176
1386
  throw new Error("Dashboard is online but was not started by passcontrol; stop it manually before restarting.");
1177
1387
  }
1178
- return startDashboard(opts);
1388
+ return startDashboard({ ...opts, dashboardTarget: target });
1179
1389
  }
1180
1390
  await stopDashboard();
1181
- return startDashboard(opts);
1391
+ return startDashboard({ ...opts, dashboardTarget: target });
1392
+ }
1393
+
1394
+ async function startLocalCommand(opts = {}) {
1395
+ const target = managedDashboardTarget();
1396
+ const activation = await prepareLocalActivation(target, opts);
1397
+ const dashboard = await startDashboard({ ...opts, dashboardTarget: target });
1398
+ commitLocalActivation(activation);
1399
+ return dashboard;
1400
+ }
1401
+
1402
+ async function restartLocalCommand(opts = {}) {
1403
+ const target = managedDashboardTarget();
1404
+ const activation = await prepareLocalActivation(target, opts);
1405
+ const dashboard = await restartDashboard({ ...opts, dashboardTarget: target });
1406
+ commitLocalActivation(activation);
1407
+ return dashboard;
1182
1408
  }
1183
1409
 
1184
1410
  async function localLogsCommand(opts = {}) {
@@ -1260,7 +1486,7 @@ async function resetLocalStack(opts = {}) {
1260
1486
  if (opts.local !== true) {
1261
1487
  throw new Error("Usage: passcontrol reset --local --confirm RESET");
1262
1488
  }
1263
- localDashboard();
1489
+ managedDashboardTarget();
1264
1490
  if (opts.confirm !== "RESET") {
1265
1491
  throw new Error("reset refuses to delete local data without `--confirm RESET`.");
1266
1492
  }
@@ -1279,7 +1505,8 @@ async function resetLocalStack(opts = {}) {
1279
1505
  }
1280
1506
 
1281
1507
  async function setupLocal(opts = {}) {
1282
- const dashboard = localDashboard();
1508
+ const dashboard = canonicalLocalDashboard();
1509
+ const activation = await prepareLocalActivation(dashboard, opts);
1283
1510
  const offset = opts.portOffset === undefined ? 0 : Number(opts.portOffset);
1284
1511
  if (!Number.isInteger(offset) || offset < 0 || offset > 10000) {
1285
1512
  throw new Error("--port-offset must be an integer from 0 to 10000.");
@@ -1294,8 +1521,9 @@ async function setupLocal(opts = {}) {
1294
1521
  // dev:stack has just brought Supabase and Redis up (and would have exited
1295
1522
  // non-zero if it hadn't), so skip start's own service pass rather than print
1296
1523
  // two "already running" lines under a banner that just said the stack is up.
1297
- await startDashboard({ ...opts, dashboardOnly: true });
1298
- if (!opts.noOpen) await openDashboard(opts);
1524
+ await startDashboard({ ...opts, dashboardOnly: true, dashboardTarget: dashboard });
1525
+ commitLocalActivation(activation);
1526
+ if (!opts.noOpen) openUrl(dashboard.url);
1299
1527
  console.log(`\n${formatLabel("Local dashboard", dashboard.url, 19)}`);
1300
1528
  console.log(formatLabel("Login", "the account you created during setup", 19));
1301
1529
  step("Add a non-critical provider key, issue a passport, then run `passcontrol doctor --deep`.");
@@ -1549,7 +1777,7 @@ async function agentCommand(rest, opts) {
1549
1777
  if (!name) throw new Error("Usage: passcontrol agent create <name>");
1550
1778
  const provider = String(opts.provider || config.provider);
1551
1779
  assertProvider(provider);
1552
- const scopeModel = String(opts.scope || (provider === "anthropic" ? "claude-*" : activeModel(provider, opts)));
1780
+ const scopeModel = String(opts.scope || defaultAllowedModelForProvider(provider));
1553
1781
  const priv = ed25519.utils.randomPrivateKey();
1554
1782
  const pub = ed25519.getPublicKey(priv);
1555
1783
  const passportId = b64url(pub);
@@ -2153,7 +2381,7 @@ async function doctorCommand(opts = {}) {
2153
2381
  console.log("");
2154
2382
  let dashboard;
2155
2383
  try {
2156
- dashboard = localDashboard();
2384
+ dashboard = managedDashboardTarget();
2157
2385
  } catch {
2158
2386
  step("--fix manages only a local dashboard; remote gateways are not changed.");
2159
2387
  }
@@ -2491,6 +2719,87 @@ async function keyCommand(rest, opts = {}) {
2491
2719
  step(`Removed PASSPORT_SECRET from ${file.path} only after verified readback.`);
2492
2720
  }
2493
2721
 
2722
+ function isEncodedEd25519Key(value) {
2723
+ return /^[A-Za-z0-9_-]{43}$/u.test(value) && fromB64url(value).length === 32;
2724
+ }
2725
+
2726
+ async function passportCommand(rest, opts = {}) {
2727
+ const subcommand = rest[0];
2728
+ if (subcommand !== "import" || rest.length !== 1) {
2729
+ throw new Error(
2730
+ `Usage: ${cliCommand("passport import --global --gateway <origin> --id <passport-id> [--replace]")}`
2731
+ );
2732
+ }
2733
+ if (opts.global !== true) {
2734
+ throw new Error("Passport import is machine-wide for sidecar and MCP use; pass --global explicitly.");
2735
+ }
2736
+ if (typeof opts.gateway !== "string" || typeof opts.id !== "string") {
2737
+ throw new Error(
2738
+ `Usage: ${cliCommand("passport import --global --gateway <origin> --id <passport-id> [--replace]")}`
2739
+ );
2740
+ }
2741
+
2742
+ const gateway = bareGatewayOrigin(opts.gateway, "--gateway");
2743
+ const passportId = opts.id.trim();
2744
+ if (!isEncodedEd25519Key(passportId)) {
2745
+ throw new Error("--id must be a 32-byte Ed25519 public key encoded as unpadded base64url.");
2746
+ }
2747
+
2748
+ const project = config.sources.find((source) =>
2749
+ source.type === "project" && GATEWAY_BOUND_CONFIG_KEYS.some((key) => Object.hasOwn(source.values, key))
2750
+ );
2751
+ const shellOverride = GATEWAY_BOUND_CONFIG_KEYS.find((key) => operatorEnv(key) !== undefined);
2752
+ if (project) warn(`${project.path} contains gateway-bound values and will shadow this global import.`);
2753
+ if (shellOverride) warn(`${shellOverride} comes from the shell and will shadow this global import.`);
2754
+
2755
+ const target = globalConfigPath();
2756
+ const global = config.sources.find((source) => source.type === "global");
2757
+ const oldId = String(global?.values?.PASSPORT_ID ?? "").trim();
2758
+ const oldSecret = String(global?.values?.PASSPORT_SECRET ?? "").trim();
2759
+ const oldStorage = String(global?.values?.PASSPORT_KEY_STORAGE ?? "").trim();
2760
+ if ((oldId || oldSecret || oldStorage) && opts.replace !== true) {
2761
+ throw new Error(
2762
+ `A global Passport is already configured. Refusing to replace an unrecoverable key; re-run with --replace after verifying the old identity can be retired.`
2763
+ );
2764
+ }
2765
+
2766
+ const secret = await readHiddenLine("Paste the Passport secret (input hidden): ");
2767
+ if (!isEncodedEd25519Key(secret)) {
2768
+ throw new Error("Passport secret must be a 32-byte Ed25519 private key encoded as unpadded base64url.");
2769
+ }
2770
+ const derived = b64url(ed25519.getPublicKey(fromB64url(secret)));
2771
+ if (derived !== passportId) {
2772
+ throw new Error("Passport secret does not match the supplied Passport ID. Nothing was stored.");
2773
+ }
2774
+
2775
+ // The write/readback/commit sequence and its rollbacks live in
2776
+ // importPassportKey, which is where they can be tested: nothing in this file
2777
+ // is exported, and the store is built here with no seam, so a test of the
2778
+ // rollback would have to reach the operator's real Keychain.
2779
+ const store = createPassportCredentialStore();
2780
+ const result = importPassportKey({
2781
+ passportId,
2782
+ secret,
2783
+ store,
2784
+ oldId,
2785
+ oldStorage,
2786
+ commitConfig: () => mergeConfigFileAtomic(target, {
2787
+ PASSCONTROL_GATEWAY: gateway,
2788
+ PASSPORT_ID: passportId,
2789
+ PASSPORT_SECRET: "",
2790
+ PASSPORT_KEY_STORAGE: PASSPORT_KEY_STORAGE_OS,
2791
+ }),
2792
+ });
2793
+ // The message already carries the filesystem detail: main()'s handler prints
2794
+ // `error.message` and nothing else, so a bare `cause` would never be seen.
2795
+ if (!result.ok) throw new Error(result.message, { cause: result.cause });
2796
+ if (result.warning) warn(result.warning);
2797
+
2798
+ ok(result.message);
2799
+ step(`Global gateway: ${gateway}`);
2800
+ step("The private key was verified and never written to the config file or command line.");
2801
+ }
2802
+
2494
2803
  async function openDashboard(opts = {}) {
2495
2804
  let parsed;
2496
2805
  try {
@@ -2499,7 +2808,7 @@ async function openDashboard(opts = {}) {
2499
2808
  throw new Error(`Invalid PASSCONTROL_GATEWAY URL: ${config.gateway}`);
2500
2809
  }
2501
2810
  const url = parsed.protocol === "http:" && LOCAL_DASHBOARD_HOSTS.has(parsed.hostname)
2502
- ? (await startDashboard(opts)).url
2811
+ ? (await startDashboard({ ...opts, dashboardTarget: parseLocalDashboard(config.gateway) })).url
2503
2812
  : config.gateway;
2504
2813
  openUrl(url);
2505
2814
  }
@@ -3140,13 +3449,13 @@ async function main(argv = process.argv.slice(2), runtime = {}) {
3140
3449
  await doctorCommand(opts);
3141
3450
  break;
3142
3451
  case "start":
3143
- await startDashboard(opts);
3452
+ await startLocalCommand(opts);
3144
3453
  break;
3145
3454
  case "stop":
3146
3455
  await stopCommand(opts);
3147
3456
  break;
3148
3457
  case "restart":
3149
- await restartDashboard(opts);
3458
+ await restartLocalCommand(opts);
3150
3459
  break;
3151
3460
  case "local-logs":
3152
3461
  await localLogsCommand(opts);
@@ -3219,6 +3528,9 @@ async function main(argv = process.argv.slice(2), runtime = {}) {
3219
3528
  case "keygen":
3220
3529
  await keygenCommand(commandRest, opts);
3221
3530
  break;
3531
+ case "passport":
3532
+ await passportCommand(commandRest, opts);
3533
+ break;
3222
3534
  case "key":
3223
3535
  await keyCommand(commandRest, opts);
3224
3536
  break;
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
@@ -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
  {
@@ -433,3 +433,109 @@ export function migratePassportKey({ passportId, secret, store, removeFileSecret
433
433
  message: `Migrated to tier 1 — ${store.name}; verified readback before removing the file key.`,
434
434
  };
435
435
  }
436
+
437
+ /**
438
+ * Move a verified passport secret into the OS store and commit the config that
439
+ * points at it, with one invariant holding the rollbacks together:
440
+ *
441
+ * **this function may only delete an item that it created.**
442
+ *
443
+ * Both failure paths below used to end in `store.delete(passportId)`, on the
444
+ * reasoning that the item under that id was the one just written. That is true
445
+ * exactly until `--replace` is used to re-import the SAME passport id, which it
446
+ * permits. OS storage is keyed by the id — macOS `add-generic-password -U`
447
+ * updates in place, and the DPAPI blob path is derived from the id — so in that
448
+ * one case the item removed is the operator's existing key, and the config left
449
+ * behind still points at a store that no longer has it.
450
+ *
451
+ * The pre-existence probe is UNCONDITIONAL, and not gated on the config saying
452
+ * `PASSPORT_KEY_STORAGE=os` for this id. The config is not authoritative about
453
+ * what the store contains: `cli/logout.mjs` blanks that marker in the same write
454
+ * that asks the store to delete, and the store is allowed to report that it
455
+ * could not confirm the removal — so an item can outlive the marker. The store
456
+ * is the only authority on its own contents. The cost is one extra read per
457
+ * import, which on a locked Keychain may mean one extra unlock prompt.
458
+ *
459
+ * The honest limit, and it is the same one `confirmGone` states above: a failed
460
+ * `read()` does not prove absence. A locked store reads as empty, so a rollback
461
+ * can still remove a real item. This narrows the window to that case; it does
462
+ * not close it, because the store cannot give positive evidence of absence.
463
+ *
464
+ * `commitConfig` is injected rather than called directly for the same reason
465
+ * `migratePassportKey` takes `removeFileSecret`: the rollback is the behaviour
466
+ * worth testing, and it is only reachable if the commit can be made to fail.
467
+ */
468
+ export function importPassportKey({
469
+ passportId,
470
+ secret,
471
+ store,
472
+ oldId = "",
473
+ oldStorage = "",
474
+ commitConfig,
475
+ }) {
476
+ if (!passportId || !secret) {
477
+ return { ok: false, message: "A Passport ID and secret are required." };
478
+ }
479
+
480
+ const existing = store.read(passportId);
481
+ const preExisting = existing.ok && typeof existing.secret === "string" && existing.secret.length > 0;
482
+ // The caller proves `secret` derives `passportId` before reaching here, so a
483
+ // same-id import is provably the same key the store already holds. Writing it
484
+ // changes nothing and only opens a window in which a rollback could take it.
485
+ const alreadyStored = preExisting && sameSecret(secret, existing.secret);
486
+
487
+ if (!alreadyStored) {
488
+ const written = store.write(passportId, secret);
489
+ if (!written.ok) {
490
+ // Nothing was created, so there is nothing to roll back.
491
+ return { ok: false, message: `${written.reason}. Nothing was written to the PassControl config.` };
492
+ }
493
+
494
+ const readback = store.read(passportId);
495
+ if (!readback.ok || !sameSecret(secret, readback.secret)) {
496
+ if (!preExisting) store.delete(passportId);
497
+ return {
498
+ ok: false,
499
+ message: preExisting
500
+ ? `${store.name} did not return the key that was just stored. The item already under this Passport ID was left in place, and config was not changed.`
501
+ : `${store.name} did not return the key that was just stored. The new item was removed and config was not changed.`,
502
+ };
503
+ }
504
+ }
505
+
506
+ try {
507
+ commitConfig();
508
+ } catch (error) {
509
+ if (!preExisting) store.delete(passportId);
510
+ // The CLI's top-level handler prints `error.message` and nothing else, so
511
+ // the filesystem detail has to travel inside the message or the operator
512
+ // loses the only line that says which path failed. An fs error names a
513
+ // path, not a key — the collapse-to-fixed-text rule above is about
514
+ // subprocess stderr, which can echo the secret back.
515
+ const detail = error instanceof Error ? error.message : String(error);
516
+ return {
517
+ ok: false,
518
+ cause: error,
519
+ message: preExisting
520
+ ? `The PassControl config could not be written; the key already in ${store.name} was left in place. ${detail}`
521
+ : `The PassControl config could not be written; the new item was removed from ${store.name}. ${detail}`,
522
+ };
523
+ }
524
+
525
+ let warning = null;
526
+ if (oldStorage === PASSPORT_KEY_STORAGE_OS && oldId && oldId !== passportId) {
527
+ const removed = store.delete(oldId);
528
+ if (!removed.ok) {
529
+ warning = `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.`;
530
+ }
531
+ }
532
+
533
+ return {
534
+ ok: true,
535
+ alreadyStored,
536
+ warning,
537
+ message: alreadyStored
538
+ ? `${store.name} already held this Passport key; it was verified and left in place.`
539
+ : `Passport ${passportId} imported into ${store.name}.`,
540
+ };
541
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "passcontrol",
3
- "version": "0.9.2",
3
+ "version": "0.9.4",
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 }),