passcontrol 0.6.1 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -11,6 +11,7 @@ import {
11
11
  CONFIG_FILE,
12
12
  OPENAI_SHAPE_PROVIDERS,
13
13
  PROVIDERS,
14
+ WORKSPACE_IMPORT_MAX_VERSION,
14
15
  assertConfigLoaded,
15
16
  config,
16
17
  configPathLabel,
@@ -26,6 +27,7 @@ import {
26
27
  requireControlApiKey,
27
28
  requireControlGateway,
28
29
  operatorEnv,
30
+ probeGatewayOrigin,
29
31
  requirePassportGateway,
30
32
  requirePassport,
31
33
  step,
@@ -47,13 +49,17 @@ import {
47
49
  isIntegration,
48
50
  supportsWrite,
49
51
  } from "../cli/presets.mjs";
52
+ import { importCompletionMessage, noAgentCreateMessage } from "../cli/workspace-import-report.mjs";
53
+ import { checkForUpdate } from "../cli/update-check.mjs";
50
54
  import { startSidecar } from "../cli/sidecar.mjs";
55
+ import { loginCommand } from "../cli/login.mjs";
51
56
  import {
52
57
  checkIssuerPublishesKey,
53
58
  generateInstanceKey,
54
59
  instanceKidFromSeed,
55
60
  } from "../cli/instance-key.mjs";
56
61
  import { FAILURE_REASONS, verifyAgentToken, verifyReceipt } from "../cli/verify.mjs";
62
+ import { compareProtocolSets } from "../cli/protocols.mjs";
57
63
 
58
64
  const b64url = (bytes) =>
59
65
  Buffer.from(bytes).toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
@@ -80,6 +86,12 @@ const DEMO_API_KEY = "pc_demolocaltrydemolocaltrydemolocaltry0000";
80
86
  const DASHBOARD_STATE_FILE = "local-dashboard.json";
81
87
  const APP_STATE_FILE = "app.json";
82
88
  const PUBLIC_REPO_URL = "https://github.com/Vertias3u/PassControl.git";
89
+ // The hosted demo. `try` cannot simply DEFAULT here: its second step arms and
90
+ // disarms the tenant kill switch, so concurrent visitors would collide on shared
91
+ // demo-tenant state and an aborted run would leave the public demo killed. It is
92
+ // offered as a browser link instead — the one zero-install way to see the
93
+ // pipeline when there is no local stack yet.
94
+ const HOSTED_DEMO_URL = "https://passcontrol.vertias.eu";
83
95
  const LOCAL_DASHBOARD_HOSTS = new Set(["localhost", "127.0.0.1", "::1", "[::1]"]);
84
96
  const LOCAL_STACK_PORTS = [54321, 54322, 54324, 54327, 8079];
85
97
  // The local stack (Supabase + Redis + dashboard) lives in a PassControl repo
@@ -136,18 +148,21 @@ ${heading("Usage:")}
136
148
  ${cmd} <command> [options]
137
149
 
138
150
  ${heading("Quick start")}
139
- ${cmd} init [--global] configure this project
140
- ${cmd} start [--dashboard-only] start the whole local stack (dashboard + Supabase + Redis)
141
- ${cmd} open start if needed and open the Control Tower
151
+ Cloud. No Docker, no database — this CLI is the only thing you install.
152
+ ${cmd} login [--project] sign in through your browser and set this machine up
142
153
  ${cmd} try run the 60-second keyless guided demo
154
+ ${cmd} call "hi" mint a visa and make a governed model call
155
+ ${cmd} mcp passport identity for Claude Desktop, Cursor, Claude Code
156
+ ${cmd} sidecar [--port 8788] [--allow-connect host[,host]]
157
+ passport identity for any tool that takes an api_key
143
158
 
144
159
  ${heading("Operate")}
145
160
  ${cmd} status [--no-network] [--json]
146
161
  show active config and instance state
162
+ ${cmd} version [--json] CLI, gateway and database schema versions
147
163
  ${cmd} doctor [--deep] [--fix] diagnose setup and repair a stopped dashboard
148
- ${cmd} call "hi" mint a visa and make a governed model call
149
- ${cmd} sidecar [--port 8788] [--allow-connect host[,host]]
150
- start the local agent bridge
164
+ ${cmd} open open the Control Tower in a browser
165
+ ${cmd} init [--global] configure by hand, without a browser
151
166
 
152
167
  ${heading("Manage")}
153
168
  ${cmd} agent list [--json] list agents
@@ -163,12 +178,14 @@ ${heading("Manage")}
163
178
  ${cmd} logs [--limit 20] [--json]
164
179
  show governed call logs
165
180
  ${cmd} kill on|off toggle the tenant kill switch
181
+ ${cmd} export [--out FILE] save a workspace configuration snapshot
182
+ ${cmd} import <file> [--confirm IMPORT]
183
+ restore agents from a snapshot (never overwrites)
166
184
 
167
185
  ${heading("Integrate")}
168
186
  ${cmd} env [integration] print settings without writing anything
169
187
  ${cmd} configure <integration> [--write] [--force]
170
188
  preview or write integration config
171
- ${cmd} mcp start the stdio MCP server
172
189
  integrations: ${integrationChoices()}
173
190
 
174
191
  ${heading("Trust")}
@@ -178,9 +195,12 @@ ${heading("Trust")}
178
195
  ${cmd} verify token <jwt> --audience <aud> --issuer <origin>
179
196
  verify an agent-to-agent token
180
197
 
181
- ${heading("Local stack")}
198
+ ${heading("Self-host — run your own gateway")}
199
+ Clones the app and runs Docker + Supabase + Redis here. You operate it, and
200
+ your instance signs its own receipts — they verify against your JWKS, not ours.
182
201
  ${cmd} setup [--no-open] [--port-offset N] [--app-dir DIR]
183
- clone if needed, start services, open dashboard
202
+ clone the app, start Docker + Supabase + Redis
203
+ ${cmd} start [--dashboard-only] start the whole local stack (clones the app if missing)
184
204
  ${cmd} stop [--dashboard-only] stop the whole local stack (dashboard + Supabase + Redis)
185
205
  ${cmd} restart restart the CLI-managed local dashboard
186
206
  ${cmd} local-logs [--follow] show local dashboard logs
@@ -190,8 +210,8 @@ ${heading("Local stack")}
190
210
 
191
211
  ${heading("Config:")}
192
212
  Env vars win, then nearest .passcontrol, then ~/.config/passcontrol/config.
193
- Installed globally, the local-stack commands (setup/start/reset) use a cloned
194
- app checkout, resolved in this order:
213
+ Only the self-host commands (setup/start/reset) ever clone anything. Installed
214
+ globally, they resolve a cloned app checkout in this order:
195
215
  --app-dir DIR → PASSCONTROL_APP_ROOT → surrounding checkout → remembered
196
216
  checkout in ~/.config/passcontrol/app.json (survives npm uninstall; clear
197
217
  it with \`${cmd} unlink\`).
@@ -262,6 +282,10 @@ async function printCockpit({ noNetwork = false, json = false } = {}) {
262
282
  const dashboard = dashboardStatusLabel(gateway, noNetwork);
263
283
  const app = appRootLabel();
264
284
  const configFile = configPathLabel(config.sources);
285
+ // This is deliberately credential-gated. Status remains useful to an agent
286
+ // install with no Control key, but it must never probe a tenant endpoint
287
+ // anonymously or make that normal setup state look like a failure.
288
+ const systemHealth = noNetwork ? { state: "not-checked" } : await fetchSystemHealth();
265
289
 
266
290
  if (json) {
267
291
  console.log(JSON.stringify({
@@ -276,6 +300,7 @@ async function printCockpit({ noNetwork = false, json = false } = {}) {
276
300
  passport_configured: passportConfigured,
277
301
  control_api_key_configured: adminConfigured,
278
302
  },
303
+ system_health: systemHealthForJson(systemHealth),
279
304
  }, null, 2));
280
305
  return;
281
306
  }
@@ -289,6 +314,7 @@ async function printCockpit({ noNetwork = false, json = false } = {}) {
289
314
  console.log(formatLabel("Model", config.model));
290
315
  console.log(formatLabel("Passport", passportConfigured ? redact(config.passportId) : "missing"));
291
316
  console.log(formatLabel("Admin key", adminConfigured ? redact(config.apiKey, 6) : "missing"));
317
+ console.log(formatLabel("System health", systemHealthLabel(systemHealth)));
292
318
  console.log(`${formatLabel("Sidecar", `foreground command (\`${cliCommand("sidecar")}\`)`)}\n`);
293
319
  const next = [];
294
320
  if (config.sources.length === 0) {
@@ -312,6 +338,99 @@ async function printCockpit({ noNetwork = false, json = false } = {}) {
312
338
  }
313
339
  }
314
340
 
341
+ function safeHealthText(value, fallback = "unavailable") {
342
+ if (typeof value !== "string") return fallback;
343
+ // Keep a compromised/misconfigured server from writing terminal control
344
+ // sequences or an unbounded line into an operator's terminal.
345
+ const clean = value.replace(/[\x00-\x1f\x7f]/g, " ").trim().slice(0, 240);
346
+ return clean || fallback;
347
+ }
348
+
349
+ async function fetchSystemHealth() {
350
+ if (!config.apiKey) return { state: "skipped" };
351
+ try {
352
+ const health = await api("GET", "/system");
353
+ if (!health || typeof health !== "object") return { state: "unavailable", reason: "invalid response" };
354
+ return { state: "available", health };
355
+ } catch (error) {
356
+ const message = error instanceof Error ? error.message : "request failed";
357
+ return { state: message.startsWith("403 ") ? "restricted" : "unavailable", reason: message };
358
+ }
359
+ }
360
+
361
+ function healthCompatibility(health) {
362
+ return compareProtocolSets(health && typeof health === "object" ? health.protocols : undefined);
363
+ }
364
+
365
+ function shortBuildCommit(value) {
366
+ return typeof value === "string" && /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/i.test(value)
367
+ ? value.slice(0, 12).toLowerCase()
368
+ : "unknown";
369
+ }
370
+
371
+ function systemBuildSummary(health) {
372
+ const build = health?.build && typeof health.build === "object" ? health.build : {};
373
+ const migrations = health?.migrations && typeof health.migrations === "object" ? health.migrations : {};
374
+ return {
375
+ version: safeHealthText(build.version, "unknown"),
376
+ channel: safeHealthText(build.channel, "unknown"),
377
+ commit: shortBuildCommit(build.commit),
378
+ migrationState: safeHealthText(migrations.state, "unknown"),
379
+ migrationHead: safeHealthText(migrations.expected_head, "unknown"),
380
+ appliedMigrationHead: migrations.applied_head == null
381
+ ? "not recorded"
382
+ : safeHealthText(migrations.applied_head, "unknown"),
383
+ };
384
+ }
385
+
386
+ function systemHealthLabel(result) {
387
+ if (result.state === "skipped") return "skipped (operator read key required)";
388
+ if (result.state === "not-checked") return "not checked (--no-network)";
389
+ if (result.state === "restricted") return "restricted (control key cannot read system health)";
390
+ if (result.state !== "available") return `unavailable (${safeHealthText(result.reason)})`;
391
+ const build = systemBuildSummary(result.health);
392
+ const observed = safeHealthText(result.health.generated_at, "unknown");
393
+ return `${safeHealthText(result.health.overall, "reported")} · observed ${observed} · v${build.version} ${build.channel} ${build.commit} · migrations ${build.migrationState} (${build.appliedMigrationHead} → ${build.migrationHead}) · protocols ${healthCompatibility(result.health).state}`;
394
+ }
395
+
396
+ function systemHealthForJson(result) {
397
+ if (result.state !== "available") return { state: result.state };
398
+ return {
399
+ state: "available",
400
+ overall: safeHealthText(result.health.overall, "reported"),
401
+ observed_at: safeHealthText(result.health.generated_at, "unknown"),
402
+ protocol_compatibility: healthCompatibility(result.health).state,
403
+ build: systemBuildSummary(result.health),
404
+ };
405
+ }
406
+
407
+ function printSystemHealthDiagnostic(result) {
408
+ if (result.state === "skipped") {
409
+ step("System health skipped: an operator read key is required.");
410
+ return;
411
+ }
412
+ if (result.state === "restricted") {
413
+ fail("System health diagnostic restricted (403): this key's owner is not an allowlisted MFA-enrolled system operator.");
414
+ return;
415
+ }
416
+ if (result.state !== "available") {
417
+ fail(`System health diagnostic failed: ${safeHealthText(result.reason)}`);
418
+ return;
419
+ }
420
+ const compatibility = healthCompatibility(result.health);
421
+ const build = systemBuildSummary(result.health);
422
+ const observed = safeHealthText(result.health.generated_at, "unknown");
423
+ ok(`System health ${safeHealthText(result.health.overall, "reported")} · observed ${observed} · v${build.version} ${build.channel} ${build.commit} · migrations ${build.migrationState} (${build.appliedMigrationHead} → ${build.migrationHead}) · protocol compatibility ${compatibility.state}`);
424
+ for (const check of Array.isArray(result.health.checks) ? result.health.checks : []) {
425
+ if (!check || typeof check !== "object") continue;
426
+ const label = safeHealthText(check.label, "System check");
427
+ const state = safeHealthText(check.state, "unknown");
428
+ const summary = safeHealthText(check.summary, "No summary provided.");
429
+ console.log(` ${label}: ${state} — ${summary}`);
430
+ if (typeof check.action === "string" && check.action.trim()) step(`Remediation: ${safeHealthText(check.action)}`);
431
+ }
432
+ }
433
+
315
434
  function appConfigDir(env = process.env) {
316
435
  const base = env.XDG_CONFIG_HOME || path.join(os.homedir(), ".config");
317
436
  return path.join(base, "passcontrol");
@@ -422,6 +541,14 @@ function checkDockerInstalled() {
422
541
  };
423
542
  }
424
543
 
544
+ // Every docker call the CLI makes needs a bound, not just the daemon probe. A
545
+ // wedged Docker Desktop leaves its CLI socket present and answers nothing, so an
546
+ // unbounded `docker ps` waits forever — which is how `doctor --deep` hung
547
+ // indefinitely on the very check that exists to REPORT a wedged engine. The
548
+ // value is the cold-start allowance argued for in checkDockerDaemon below;
549
+ // sharing it keeps one number rather than three that drift.
550
+ const DOCKER_TIMEOUT_MS = 15_000;
551
+
425
552
  function checkDockerDaemon() {
426
553
  if (!commandExists("docker")) {
427
554
  return {
@@ -440,7 +567,7 @@ function checkDockerDaemon() {
440
567
  // where Docker was available throughout, and it would tell a first-time user
441
568
  // on a slow laptop to go start something already running. A wedged engine
442
569
  // still gets caught; it just takes fifteen seconds to say so.
443
- execFileSync("docker", ["info"], { stdio: "ignore", timeout: 15_000 });
570
+ execFileSync("docker", ["info"], { stdio: "ignore", timeout: DOCKER_TIMEOUT_MS });
444
571
  return { ok: true, message: "Docker daemon: running." };
445
572
  } catch (error) {
446
573
  // A timeout and a stopped daemon need different things from the reader, so
@@ -486,9 +613,18 @@ async function promptLine(question, fallback) {
486
613
  }
487
614
  }
488
615
 
489
- async function confirmYes(question) {
616
+ /**
617
+ * Yes/no prompt. Enter means YES unless `{ default: false }` is passed.
618
+ *
619
+ * The option exists for one caller — `passcontrol login` asking before it
620
+ * replaces a passport secret. That answer is unrecoverable, so the reply an
621
+ * operator gives by reflex has to be the one that changes nothing. Every other
622
+ * caller keeps the enter-means-yes behaviour it was written against.
623
+ */
624
+ async function confirmYes(question, { default: fallback = true } = {}) {
490
625
  const answer = (await promptLine(question, "")).toLowerCase();
491
- return answer === "" || answer === "y" || answer === "yes";
626
+ if (answer === "") return fallback;
627
+ return answer === "y" || answer === "yes";
492
628
  }
493
629
 
494
630
  // Resolve the stack checkout, cloning the public repo on demand when the CLI is
@@ -586,7 +722,7 @@ function localSupabaseIsRunning() {
586
722
  execFileSync(
587
723
  "docker",
588
724
  ["ps", "-q", "--filter", `label=com.supabase.cli.project=${localSupabaseProjectId()}`, "--filter", "name=supabase_db"],
589
- { encoding: "utf8" }
725
+ { encoding: "utf8", timeout: DOCKER_TIMEOUT_MS }
590
726
  ).trim()
591
727
  );
592
728
  } catch {
@@ -755,7 +891,7 @@ function ownSupabaseDatabaseIsRunning(offset = 0) {
755
891
  if (!root) return false;
756
892
  const project = `${path.basename(root)}${offset ? `-${offset}` : ""}`;
757
893
  return Boolean(
758
- execFileSync("docker", ["ps", "-q", "--filter", `name=^/supabase_db_${project}$`], { encoding: "utf8" }).trim()
894
+ execFileSync("docker", ["ps", "-q", "--filter", `name=^/supabase_db_${project}$`], { encoding: "utf8", timeout: DOCKER_TIMEOUT_MS }).trim()
759
895
  );
760
896
  } catch {
761
897
  return false;
@@ -802,8 +938,16 @@ async function runLocalPrerequisiteChecks({ offset = 0, report = false, enforce
802
938
  }
803
939
 
804
940
  if (enforce) {
805
- const failure = results.find((result) => !result.ok);
806
- if (failure) throw new Error(failure.message);
941
+ // Every failure, not just the first. These checks are independent, and each
942
+ // one a first-time user hits is its own install-and-come-back detour; finding
943
+ // them one run at a time turns a single setup into three sittings. `results`
944
+ // already holds them all — only the reporting was lossy.
945
+ const failures = results.filter((result) => !result.ok);
946
+ if (failures.length > 0) {
947
+ // `fail()` marks the first line; the rest carry their own marker so a
948
+ // four-item list does not read as one failure with three stray sentences.
949
+ throw new Error(failures.map((failure) => failure.message).join("\n\u2717 "));
950
+ }
807
951
  }
808
952
  return results;
809
953
  }
@@ -1275,7 +1419,8 @@ async function tryCommand() {
1275
1419
  step(" PASSCONTROL_DEMO=1 npm run dev:docker # enables the keyless demo provider");
1276
1420
  } else {
1277
1421
  fail(`Could not reach the gateway at ${gateway} (${msg}).`);
1278
- step("Bring the local demo stack up first:");
1422
+ step(`Nothing installed yet? The same pipeline runs keyless in your browser: ${HOSTED_DEMO_URL}`);
1423
+ step("To run it here instead, bring the local demo stack up first:");
1279
1424
  step(" PASSCONTROL_DEMO=1 npm run dev:stack # Supabase + Redis + migrate + seed the demo passport");
1280
1425
  step(" PASSCONTROL_DEMO=1 npm run dev:docker # start the gateway with the demo provider enabled");
1281
1426
  }
@@ -1327,22 +1472,34 @@ async function tryCommand() {
1327
1472
  step("Next: add a real provider key in the Control Tower and re-point your agent at the gateway (see the README).");
1328
1473
  }
1329
1474
 
1330
- async function api(method, pathPart, body) {
1475
+ async function api(method, pathPart, body, { timeoutMs } = {}) {
1331
1476
  // Destination first, key second — same order and same reason as the SDK's
1332
1477
  // ControlClient. `config.gateway` is whatever PASSCONTROL_GATEWAY said, and
1333
1478
  // this is the one place a long-lived fleet-wide `pc_` key goes on the wire, so
1334
1479
  // the URL is built from the validated origin rather than from that string.
1335
1480
  const origin = requireControlGateway(config);
1336
1481
  const apiKey = requireControlApiKey(config);
1337
- const res = await fetch(`${origin}/api/control/v1${pathPart}`, {
1338
- method,
1339
- headers: {
1340
- authorization: `Bearer ${apiKey}`,
1341
- ...(body ? { "content-type": "application/json" } : {}),
1342
- ...(method !== "GET" ? { "idempotency-key": crypto.randomUUID() } : {}),
1343
- },
1344
- body: body ? JSON.stringify(body) : undefined,
1345
- });
1482
+ // Unbounded by default, deliberately: a fleet mutation must not be abandoned
1483
+ // halfway because a caller guessed a duration. `timeoutMs` is opt-in, for the
1484
+ // one kind of caller that is a REPORT — where a gateway that never answers is
1485
+ // itself the finding, and hanging turns a diagnostic into a hang.
1486
+ const controller = timeoutMs ? new AbortController() : null;
1487
+ const timer = controller ? setTimeout(() => controller.abort(), timeoutMs) : null;
1488
+ let res;
1489
+ try {
1490
+ res = await fetch(`${origin}/api/control/v1${pathPart}`, {
1491
+ method,
1492
+ headers: {
1493
+ authorization: `Bearer ${apiKey}`,
1494
+ ...(body ? { "content-type": "application/json" } : {}),
1495
+ ...(method !== "GET" ? { "idempotency-key": crypto.randomUUID() } : {}),
1496
+ },
1497
+ body: body ? JSON.stringify(body) : undefined,
1498
+ ...(controller ? { signal: controller.signal } : {}),
1499
+ });
1500
+ } finally {
1501
+ if (timer) clearTimeout(timer);
1502
+ }
1346
1503
  const text = await res.text();
1347
1504
  let json = {};
1348
1505
  try {
@@ -1354,7 +1511,7 @@ async function api(method, pathPart, body) {
1354
1511
  const e = json.error ?? {};
1355
1512
  throw new Error(`${res.status} ${e.code ?? ""} ${e.message ?? ""} (req ${e.request_id ?? "?"})`);
1356
1513
  }
1357
- return json.data;
1514
+ return Object.prototype.hasOwnProperty.call(json, "data") ? json.data : json;
1358
1515
  }
1359
1516
 
1360
1517
  function controlPath(pathPart, params = {}) {
@@ -1811,6 +1968,133 @@ async function configureCommand(rest, opts = {}) {
1811
1968
  ok(`wrote ${target}`);
1812
1969
  }
1813
1970
 
1971
+ // ── Which build is which ─────────────────────────────────────────────────────
1972
+ //
1973
+ // Version drift between the CLI, the gateway and the database is the support
1974
+ // question that hides behind every other support question, and until now the
1975
+ // CLI could only answer a third of it. `passcontrol version` printed its own
1976
+ // number and stopped.
1977
+ //
1978
+ // The three rows come from three different places on purpose, and each degrades
1979
+ // on its own:
1980
+ //
1981
+ // CLI — the installed package. Always available.
1982
+ // Server — GET /api/version on the configured gateway. Unauthenticated,
1983
+ // because the release version is already on the site footer.
1984
+ // Schema — the migration block of /api/control/v1/system, which is behind
1985
+ // the operator gate. How far behind a database is doubles as a
1986
+ // list of the fixes it does not have, so it stays authenticated;
1987
+ // on a self-host the operator is the person running this, and on
1988
+ // Cloud a tenant correctly cannot read the instance's lag.
1989
+
1990
+ /** The gateway's own build, or null. Never throws: this is a report, not a gate. */
1991
+ async function serverVersion() {
1992
+ // Same origin rule as every other outbound path in this file, even though no
1993
+ // credential travels here — see probeGatewayOrigin.
1994
+ const origin = probeGatewayOrigin();
1995
+ if (!origin) return { version: null, detail: "the configured gateway is not a bare origin" };
1996
+ try {
1997
+ const res = await fetchWithTimeout(`${origin}/api/version`);
1998
+ // A gateway that predates this endpoint is a real PassControl gateway, and
1999
+ // saying "unreachable" about one that answered would send an operator to
2000
+ // debug their network instead of deploying.
2001
+ if (res.status === 404) return { version: null, detail: "running a build older than /api/version" };
2002
+ if (!res.ok) return { version: null, detail: `the gateway answered ${res.status}` };
2003
+ const body = await res.json();
2004
+ const version = typeof body?.version === "string" ? body.version : null;
2005
+ return { version, detail: version ? null : "the gateway did not report a version" };
2006
+ } catch {
2007
+ return { version: null, detail: "unreachable" };
2008
+ }
2009
+ }
2010
+
2011
+ /**
2012
+ * The migration block, or why it could not be read.
2013
+ *
2014
+ * Every branch is a distinct, actionable answer. "not checked" is not the same
2015
+ * as "forbidden", and neither is the same as a gateway that is simply down —
2016
+ * collapsing them is how an operator ends up debugging the wrong thing.
2017
+ */
2018
+ async function schemaState() {
2019
+ if (!config.apiKey) return { state: "unchecked", detail: "no control API key configured" };
2020
+ try {
2021
+ // Bounded: `doctor` exists to explain an unavailable gateway, so this line
2022
+ // must never be the reason the report does not print.
2023
+ const snapshot = await api("GET", "/system", undefined, { timeoutMs: 2500 });
2024
+ const migrations = snapshot?.data?.migrations ?? snapshot?.migrations ?? null;
2025
+ if (!migrations) return { state: "unchecked", detail: "the gateway returned no migration block" };
2026
+ return { state: migrations.state ?? "unknown", migrations };
2027
+ } catch (error) {
2028
+ const message = String(error?.message ?? error);
2029
+ if (/system_forbidden|system_not_configured|system_totp_required|system_allowlist_invalid/.test(message)) {
2030
+ return { state: "unchecked", detail: "this control key is not an operator of that instance" };
2031
+ }
2032
+ // A bare "fetch failed" reads as a bug in the CLI rather than as a gateway
2033
+ // that is not running, which is what it almost always means.
2034
+ if (/fetch failed|ECONNREFUSED|ENOTFOUND|aborted/i.test(message)) {
2035
+ return { state: "unchecked", detail: "the gateway is unreachable" };
2036
+ }
2037
+ // Never echo the upstream error body into this report: it is remote text,
2038
+ // and "401 invalid_api_key no (req ?)" tells an operator less than the
2039
+ // sentence it is standing in for.
2040
+ if (/invalid_api_key|\b401\b/.test(message)) {
2041
+ return { state: "unchecked", detail: "the control API key was rejected" };
2042
+ }
2043
+ if (/\b404\b/.test(message)) {
2044
+ return { state: "unchecked", detail: "this gateway is too old to report its schema" };
2045
+ }
2046
+ return { state: "unchecked", detail: "the gateway did not answer the system check" };
2047
+ }
2048
+ }
2049
+
2050
+ const SCHEMA_WORD = {
2051
+ current: "compatible",
2052
+ behind: "the database is missing migrations this build expects",
2053
+ ahead: "the database is newer than this build — was the app rolled back?",
2054
+ incompatible: "the applied migrations do not match this build",
2055
+ unknown: "could not be determined",
2056
+ };
2057
+
2058
+ async function versionCommand({ json = false } = {}) {
2059
+ const [server, schema] = await Promise.all([serverVersion(), schemaState()]);
2060
+ const migrations = schema.migrations ?? null;
2061
+ const serverLabel =
2062
+ server.version === null
2063
+ ? `not reported (${server.detail})`
2064
+ : `${server.version}${server.version === CLI_VERSION ? " ✓" : " ✗ different build from this CLI"}`;
2065
+
2066
+ if (json) {
2067
+ console.log(JSON.stringify({
2068
+ cli: CLI_VERSION,
2069
+ server: server.version,
2070
+ server_detail: server.detail,
2071
+ server_matches_cli: server.version === null ? null : server.version === CLI_VERSION,
2072
+ schema: migrations
2073
+ ? {
2074
+ state: schema.state,
2075
+ applied_head: migrations.applied_head ?? null,
2076
+ expected_head: migrations.expected_head ?? null,
2077
+ missing_count: migrations.missing_count ?? 0,
2078
+ extra_count: migrations.extra_count ?? 0,
2079
+ }
2080
+ : { state: schema.state, detail: schema.detail ?? null },
2081
+ }, null, 2));
2082
+ return;
2083
+ }
2084
+
2085
+ console.log(`${heading("PassControl")}\n`);
2086
+ console.log(formatLabel("CLI", CLI_VERSION, 18));
2087
+ console.log(formatLabel("Server", serverLabel, 18));
2088
+ if (migrations) {
2089
+ console.log(formatLabel("Database schema", migrations.applied_head ?? "none recorded", 18));
2090
+ console.log(formatLabel("Expected schema", migrations.expected_head ?? "unknown", 18));
2091
+ console.log(formatLabel("Status", `${schema.state} — ${SCHEMA_WORD[schema.state] ?? "see the dashboard"}`, 18));
2092
+ if (migrations.action) step(migrations.action);
2093
+ } else {
2094
+ console.log(formatLabel("Database schema", `not checked (${schema.detail})`, 18));
2095
+ }
2096
+ }
2097
+
1814
2098
  async function doctorCommand(opts = {}) {
1815
2099
  const gateway = await gatewayStatus(false);
1816
2100
  console.log(`${heading("PassControl doctor")}\n`);
@@ -1820,6 +2104,16 @@ async function doctorCommand(opts = {}) {
1820
2104
  );
1821
2105
  (config.apiKey ? ok : step)(`Control API key ${config.apiKey ? "configured" : "missing (needed only for agent/kill commands)"}`);
1822
2106
  step(`Config source: ${configPathLabel(config.sources)}`);
2107
+ // The check that answers "why did this work yesterday". A database behind the
2108
+ // build it serves is not visible from any other line in this report.
2109
+ const schema = await schemaState();
2110
+ if (schema.migrations) {
2111
+ (schema.state === "current" ? ok : fail)(
2112
+ `Database migrations ${schema.state} — ${SCHEMA_WORD[schema.state] ?? "see the dashboard"}`
2113
+ );
2114
+ } else {
2115
+ step(`Database migrations not checked (${schema.detail})`);
2116
+ }
1823
2117
 
1824
2118
  if (opts.fix) {
1825
2119
  console.log("");
@@ -1848,6 +2142,9 @@ async function doctorCommand(opts = {}) {
1848
2142
 
1849
2143
  console.log("");
1850
2144
  step("Deep checks");
2145
+ // One authenticated request for this command. Its failure is a failed
2146
+ // diagnostic, not a CLI crash: remaining local checks are still useful.
2147
+ printSystemHealthDiagnostic(await fetchSystemHealth());
1851
2148
  await runLocalPrerequisiteChecks({ report: true });
1852
2149
  if (config.passportId && config.passportSecret) {
1853
2150
  try {
@@ -1990,27 +2287,185 @@ async function openDashboard(opts = {}) {
1990
2287
  const url = parsed.protocol === "http:" && LOCAL_DASHBOARD_HOSTS.has(parsed.hostname)
1991
2288
  ? (await startDashboard(opts)).url
1992
2289
  : config.gateway;
2290
+ openUrl(url);
2291
+ }
2292
+
2293
+ /**
2294
+ * Open a URL in the operator's browser. Nothing else.
2295
+ *
2296
+ * Extracted from openDashboard because openDashboard is NOT a URL opener: for a
2297
+ * localhost gateway it routes through startDashboard, which is
2298
+ * `ensureAppRoot({ clone: true })`. Any new caller that reached for the obvious
2299
+ * function would have put a self-host `git clone` on the Cloud path — and
2300
+ * tests/cli-cloud-path-no-clone.test.ts could not have seen it, because that
2301
+ * guard pins DIRECT cloning callers and startDashboard is legitimately one.
2302
+ *
2303
+ * So this is the safe half, with no stack logic attached.
2304
+ * tests/cli-login-shape.test.ts pins both that it exists and that openDashboard
2305
+ * still delegates to it — a second hand-rolled spawn would pass the first check
2306
+ * and quietly lose the degradation below.
2307
+ */
2308
+ function openUrl(url) {
1993
2309
  const platform = process.platform;
1994
2310
  const command =
1995
2311
  platform === "darwin" ? "open" : platform === "win32" ? "cmd" : "xdg-open";
1996
2312
  const args = platform === "win32" ? ["/c", "start", "", url] : [url];
1997
2313
  const child = spawn(command, args, { detached: true, stdio: "ignore" });
2314
+ // A headless box, a container, or a machine with no handler: say the URL out
2315
+ // loud rather than appearing to hang.
1998
2316
  child.on("error", () => step(`Open this URL: ${url}`));
1999
2317
  child.unref();
2000
2318
  ok(`opening ${url}`);
2001
2319
  }
2002
2320
 
2321
+ // ── Workspace snapshots ─────────────────────────────────────────────────────
2322
+ // A recovery snapshot is CONFIGURATION, not a backup: it carries agents, their
2323
+ // scopes, budgets, policies and failover order, and deliberately carries no
2324
+ // secret value at all. What it cannot restore is stated in the file itself,
2325
+ // under `exclusions`, because this is the artifact someone opens at the worst
2326
+ // possible moment.
2327
+
2328
+ // lib/control/body.ts caps every control-plane request at 64 KiB, and it is not
2329
+ // raised for one route. Checking here means a large fleet is told what to do
2330
+ // instead of being handed a bare 413 by the server.
2331
+ const IMPORT_BODY_LIMIT = 64 * 1024;
2332
+
2333
+ // Wide enough for "Skipped (already exist)", the longest label below. formatLabel
2334
+ // pads to the width and does not truncate, so a short width silently glues the
2335
+ // value onto the colon.
2336
+ const REPORT_LABEL_WIDTH = 26;
2337
+
2338
+ // A passport public key is unique across the whole instance, not per workspace,
2339
+ // because the gateway identifies an agent BY that key. So importing a file into
2340
+ // a second workspace on the SAME instance refuses every agent still held by the
2341
+ // first — which is correct, and is not what a restore looks like. A restore
2342
+ // goes into a fresh instance, where the passports are free.
2343
+ const IMPORT_REASONS = {
2344
+ passport_registered_elsewhere:
2345
+ "its passport is already registered on this instance. Nothing was created for it. " +
2346
+ "Passports are unique per instance, so this file restores into a FRESH deployment, " +
2347
+ "not alongside the workspace it came from.",
2348
+ policy_malformed: "its policy could not be parsed, and creating it without one would leave it unrestricted.",
2349
+ policy_shadow_malformed: "its shadow policy could not be parsed.",
2350
+ unknown_status: "it records a status this version does not recognise.",
2351
+ };
2352
+
2353
+ async function exportCommand(opts = {}) {
2354
+ const snapshot = await api("GET", "/workspace/export");
2355
+ const body = JSON.stringify(snapshot, null, 2);
2356
+ const target = typeof opts.out === "string" ? opts.out : null;
2357
+ if (!target) {
2358
+ console.log(body);
2359
+ return;
2360
+ }
2361
+ fs.writeFileSync(target, `${body}\n`, { mode: 0o600 });
2362
+ ok(`Wrote ${snapshot.workspace.agents.length} agents to ${target}`);
2363
+ console.log(`\n${heading("Not in this file")}`);
2364
+ for (const line of snapshot.exclusions) console.log(` • ${line}`);
2365
+ }
2366
+
2367
+ async function importCommand(rest = [], opts = {}) {
2368
+ const file = rest[0];
2369
+ if (!file) throw new Error(`Usage: ${cliPrefix()} import <file> [--confirm IMPORT]`);
2370
+
2371
+ let snapshot;
2372
+ try {
2373
+ snapshot = JSON.parse(fs.readFileSync(file, "utf8"));
2374
+ } catch (error) {
2375
+ throw new Error(`Could not read ${file} as JSON: ${error.message}`);
2376
+ }
2377
+ if (snapshot?.format !== "passcontrol-export") {
2378
+ throw new Error(`${file} is not a PassControl workspace export.`);
2379
+ }
2380
+ // A file from a LATER schema may describe fields this CLI would silently drop.
2381
+ // Refusing is the honest move: a partial restore that reports success is the
2382
+ // failure this whole feature exists to prevent.
2383
+ if (Number(snapshot.version) > WORKSPACE_IMPORT_MAX_VERSION) {
2384
+ throw new Error(
2385
+ `${file} uses export format v${snapshot.version}; this CLI understands up to ` +
2386
+ `v${WORKSPACE_IMPORT_MAX_VERSION}. Upgrade PassControl and try again.`
2387
+ );
2388
+ }
2389
+
2390
+ // Only what the import writes goes on the wire. Provider mappings, break-glass
2391
+ // grants, the exclusions prose and the display settings stay on disk — they
2392
+ // are not importable, so sending them would spend the size budget on bytes the
2393
+ // server ignores.
2394
+ const agents = snapshot.workspace?.agents ?? [];
2395
+ const payload = { agents, ownership: snapshot.workspace?.ownership ?? null };
2396
+ const size = Buffer.byteLength(JSON.stringify(payload));
2397
+ if (size > IMPORT_BODY_LIMIT) {
2398
+ throw new Error(
2399
+ `This snapshot holds ${agents.length} agents (${Math.ceil(size / 1024)} KiB) and the import ` +
2400
+ `API accepts ${IMPORT_BODY_LIMIT / 1024} KiB per request. Split the "agents" array across ` +
2401
+ `several files and import them one at a time — importing is additive, so the parts combine.`
2402
+ );
2403
+ }
2404
+
2405
+ const preview = await api("POST", "/workspace/import?dry_run=true", payload);
2406
+ printImportReport(preview, { preview: true });
2407
+
2408
+ if (preview.agents.create === 0) {
2409
+ ok(noAgentCreateMessage(preview.agents));
2410
+ return;
2411
+ }
2412
+ if (opts.confirm !== "IMPORT") {
2413
+ console.log(
2414
+ `\nNothing has been written. Re-run with \`--confirm IMPORT\` to create the ` +
2415
+ `${preview.agents.create} agent(s) above.`
2416
+ );
2417
+ return;
2418
+ }
2419
+
2420
+ const result = await api("POST", "/workspace/import", payload);
2421
+ printImportReport(result, { preview: false });
2422
+ ok(importCompletionMessage(result));
2423
+ }
2424
+
2425
+ function printImportReport(report, { preview }) {
2426
+ console.log(`\n${heading(preview ? "Dry run — nothing written yet" : "Imported")}`);
2427
+ const created = preview ? report.agents.create : report.agents.created.length;
2428
+ console.log(formatLabel(preview ? "Will create" : "Created", String(created), REPORT_LABEL_WIDTH));
2429
+ if (report.agents.skipped.length > 0) {
2430
+ console.log(formatLabel("Skipped (already exist)", report.agents.skipped.join(", "), REPORT_LABEL_WIDTH));
2431
+ }
2432
+ for (const entry of report.agents.rejected) {
2433
+ console.log(formatLabel("Refused", `${entry.name} — ${IMPORT_REASONS[entry.reason] ?? entry.reason}`, REPORT_LABEL_WIDTH));
2434
+ }
2435
+ console.log(formatLabel("Ownership", report.ownership, REPORT_LABEL_WIDTH));
2436
+ console.log(`\n${heading("Not restored")}`);
2437
+ for (const line of report.not_restored) console.log(` • ${line}`);
2438
+ // Said once, plainly: an existing agent is never touched, so a re-run is safe.
2439
+ console.log(`\nAn agent already in the workspace is left exactly as it is — import never overwrites.`);
2440
+ }
2441
+
2003
2442
  async function main() {
2004
2443
  const { opts, rest } = parseArgv(process.argv.slice(2));
2005
2444
  const [command, ...commandRest] = rest;
2006
2445
 
2446
+ // Started here and awaited at the very end, so the registry lookup overlaps
2447
+ // the command instead of being tacked onto the exit. On anything that touches
2448
+ // the network — which is most of this CLI — it costs nothing measurable, and
2449
+ // it can never turn a registry outage into a slow `passcontrol call`.
2450
+ // .catch() rather than try/catch: an unhandled rejection from a background
2451
+ // nicety must not take down a command that already did its job.
2452
+ const updateNotice = checkForUpdate({
2453
+ current: CLI_VERSION,
2454
+ json: Boolean(opts.json),
2455
+ }).catch(() => null);
2456
+ const announceUpdate = async () => {
2457
+ const notice = await updateNotice;
2458
+ if (notice) console.log(`\n${notice}`);
2459
+ };
2460
+
2007
2461
  if (opts.help || command === "help") {
2008
2462
  const target = command === "help" ? commandRest[0] : command;
2009
2463
  console.log(target === "agent" || target === "fleet" ? agentUsage() : usage());
2010
2464
  return;
2011
2465
  }
2012
2466
  if (opts.version || command === "version") {
2013
- console.log(`passcontrol ${CLI_VERSION}`);
2467
+ await versionCommand({ json: Boolean(opts.json) });
2468
+ await announceUpdate();
2014
2469
  return;
2015
2470
  }
2016
2471
 
@@ -2019,6 +2474,11 @@ async function main() {
2019
2474
  case "status":
2020
2475
  await printCockpit({ noNetwork: Boolean(opts.noNetwork), json: Boolean(opts.json) });
2021
2476
  break;
2477
+ case "login":
2478
+ // openUrl, never openDashboard: the latter routes a localhost gateway
2479
+ // through startDashboard, which clones the self-host repo.
2480
+ await loginCommand(opts, { openUrl, promptLine, confirmYes });
2481
+ break;
2022
2482
  case "init":
2023
2483
  await initCommand(opts);
2024
2484
  break;
@@ -2080,6 +2540,12 @@ async function main() {
2080
2540
  case "kill":
2081
2541
  await killCommand(commandRest);
2082
2542
  break;
2543
+ case "export":
2544
+ await exportCommand(opts);
2545
+ break;
2546
+ case "import":
2547
+ await importCommand(commandRest, opts);
2548
+ break;
2083
2549
  case "open":
2084
2550
  await openDashboard(opts);
2085
2551
  break;
@@ -2092,6 +2558,8 @@ async function main() {
2092
2558
  default:
2093
2559
  throw new Error(`Unknown command "${command}". Run \`passcontrol help\`.`);
2094
2560
  }
2561
+ // Only on success. A notice printed under a failure buries the error.
2562
+ await announceUpdate();
2095
2563
  }
2096
2564
 
2097
2565
  main().catch((error) => {