passcontrol 0.9.5 → 1.1.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.
@@ -36,6 +36,7 @@ import {
36
36
  formatProxyError,
37
37
  globalConfigPath,
38
38
  mergeConfigFile,
39
+ localActivationPatch,
39
40
  mergeConfigFileAtomic,
40
41
  muted,
41
42
  heading,
@@ -66,10 +67,25 @@ import {
66
67
  integrationChoices,
67
68
  isGuiPreset,
68
69
  isIntegration,
70
+ isServicePreset,
69
71
  supportsWrite,
70
72
  } from "../cli/presets.mjs";
71
73
  import { importCompletionMessage, noAgentCreateMessage } from "../cli/workspace-import-report.mjs";
72
- import { checkForUpdate } from "../cli/update-check.mjs";
74
+ import { checkForUpdate, fetchLatest, REGISTRY_URL } from "../cli/update-check.mjs";
75
+ import {
76
+ clearMarker,
77
+ detectInstall,
78
+ dirtyBlockers,
79
+ expectedProjectId,
80
+ formatPlan,
81
+ isPublicRepoUrl,
82
+ planUpdate,
83
+ readMarker,
84
+ stackFromConfig,
85
+ writeMarker,
86
+ } from "../cli/update.mjs";
87
+ import { isLocalGatewayOrigin, probeGatewayVersion, probeTimeoutMs } from "../cli/gateway-probe.mjs";
88
+ import { dashboardOriginForOffset } from "../cli/local-stack.mjs";
73
89
  import { startSidecar } from "../cli/sidecar.mjs";
74
90
  import { waitForGateway as awaitGateway } from "../cli/gateway-wait.mjs";
75
91
  import { loginCommand } from "../cli/login.mjs";
@@ -186,6 +202,7 @@ ${heading("Operate")}
186
202
  ${cmd} status [--no-network] [--json]
187
203
  show active config and instance state
188
204
  ${cmd} version [--json] CLI, gateway and database schema versions
205
+ ${cmd} update [--check] [--yes] update this CLI and the local self-host app (code, dependencies, migrations)
189
206
  ${cmd} doctor [--deep] [--fix] diagnose setup and repair a stopped dashboard
190
207
  ${cmd} open open the Control Tower in a browser
191
208
  ${cmd} logout [--revoke-agent] revoke this machine's key and clear its credentials
@@ -310,20 +327,7 @@ async function gatewayStatus(noNetwork = false, gateway = config.gateway) {
310
327
  if (noNetwork) return { label: "not checked", ok: null };
311
328
  const origin = probeGatewayOrigin({ gateway });
312
329
  if (!origin) return { label: "invalid configuration", ok: false };
313
- try {
314
- const res = await fetchWithTimeout(`${origin}/api/version`, {
315
- method: "GET",
316
- headers: { accept: "application/json" },
317
- });
318
- if (!res.ok) return { label: `unhealthy (${res.status})`, ok: false };
319
- const body = await res.json().catch(() => null);
320
- const version = typeof body?.version === "string" && body.version.trim() ? body.version.trim() : null;
321
- return version
322
- ? { label: `online (${res.status}, PassControl ${version})`, ok: true, version }
323
- : { label: "unhealthy (not a PassControl version response)", ok: false };
324
- } catch {
325
- return { label: "offline or unreachable", ok: false };
326
- }
330
+ return probeGatewayVersion(origin);
327
331
  }
328
332
 
329
333
  async function printCockpit({ noNetwork = false, json = false } = {}) {
@@ -791,6 +795,7 @@ async function prepareLocalActivation(target, opts = {}) {
791
795
  storageMarker,
792
796
  previousGateway: config.gateway,
793
797
  globalPath: globalConfigPath(),
798
+ globalValues: values,
794
799
  };
795
800
  }
796
801
 
@@ -807,16 +812,21 @@ function restoreFileAtomically(file, contents) {
807
812
  }
808
813
 
809
814
  function commitLocalActivation(prepared) {
810
- if (!prepared.switching) return;
815
+ const patch = localActivationPatch({
816
+ switching: prepared.switching,
817
+ globalValues: prepared.globalValues,
818
+ targetUrl: prepared.target.url,
819
+ });
820
+ if (!patch) return;
811
821
  const existed = fs.existsSync(prepared.globalPath);
812
822
  const previous = existed ? fs.readFileSync(prepared.globalPath, "utf8") : null;
813
- mergeConfigFileAtomic(prepared.globalPath, {
814
- PASSCONTROL_GATEWAY: prepared.target.url,
815
- PASSPORT_ID: "",
816
- PASSPORT_SECRET: "",
817
- PASSPORT_KEY_STORAGE: "",
818
- PASSCONTROL_API_KEY: "",
819
- });
823
+ mergeConfigFileAtomic(prepared.globalPath, patch);
824
+ if (!prepared.switching) {
825
+ // A fresh machine: nothing to forget, only the gateway to record so that
826
+ // `login` targets this stack instead of Cloud.
827
+ ok(`active gateway set to ${prepared.target.url}`);
828
+ return;
829
+ }
820
830
 
821
831
  if (prepared.storageMarker === PASSPORT_KEY_STORAGE_OS && prepared.passportId) {
822
832
  const removed = createPassportCredentialStore().delete(prepared.passportId);
@@ -1073,16 +1083,65 @@ function removeDashboardState() {
1073
1083
  fs.rmSync(dashboardStatePath(), { force: true });
1074
1084
  }
1075
1085
 
1086
+ /**
1087
+ * The command line of a live process, or null when it cannot be read.
1088
+ *
1089
+ * `ps -o command=` on macOS and Linux; on Windows, the CIM process record via
1090
+ * PowerShell (present on every supported Windows). Bounded, never throws.
1091
+ */
1092
+ function processCommandLine(pid) {
1093
+ try {
1094
+ if (process.platform === "win32") {
1095
+ const out = execFileSync(
1096
+ "powershell.exe",
1097
+ ["-NoProfile", "-NonInteractive", "-Command", `(Get-CimInstance Win32_Process -Filter "ProcessId=${Number(pid)}").CommandLine`],
1098
+ { encoding: "utf8", timeout: 10_000, windowsHide: true }
1099
+ );
1100
+ return out.trim() || null;
1101
+ }
1102
+ const out = execFileSync("ps", ["-o", "command=", "-p", String(Number(pid))], { encoding: "utf8", timeout: 5_000 });
1103
+ return out.trim() || null;
1104
+ } catch {
1105
+ return null;
1106
+ }
1107
+ }
1108
+
1109
+ /**
1110
+ * Whether the recorded PID is still the supervisor this CLI spawned (C7).
1111
+ *
1112
+ * A live PID alone is not proof: after a crash or reboot the state file
1113
+ * survives and the OS reuses the number, and `stop` then signalled the new
1114
+ * owner's whole process group — or, on Windows, `taskkill /T` its tree. The
1115
+ * state records the script the supervisor runs; the PID is ours only while its
1116
+ * command line still names it. Older state files without `script` fall back to
1117
+ * the launcher's file name.
1118
+ *
1119
+ * "unknown" (the command line could not be read) is not "ours": status still
1120
+ * reports it, but nothing is killed on an unverified PID.
1121
+ */
1122
+ function managedDashboardIdentity(state) {
1123
+ const command = processCommandLine(state.pid);
1124
+ if (command === null) return "unknown";
1125
+ const expected = typeof state.script === "string" && state.script ? state.script : "dev-docker.mjs";
1126
+ return command.includes(expected) ? "ours" : "other";
1127
+ }
1128
+
1076
1129
  function runningManagedDashboard() {
1077
1130
  const state = readDashboardState();
1078
1131
  if (!state) return null;
1079
1132
  try {
1080
1133
  process.kill(state.pid, 0);
1081
- return state;
1082
1134
  } catch (error) {
1083
1135
  if (error.code === "ESRCH") removeDashboardState();
1084
1136
  return null;
1085
1137
  }
1138
+ const identity = managedDashboardIdentity(state);
1139
+ if (identity === "other") {
1140
+ // The PID now belongs to something else. The dashboard we started is gone.
1141
+ removeDashboardState();
1142
+ return null;
1143
+ }
1144
+ return { ...state, verified: identity === "ours" };
1086
1145
  }
1087
1146
 
1088
1147
  function dashboardStatusLabel(gateway, noNetwork, target = managedDashboardTarget()) {
@@ -1169,17 +1228,38 @@ async function assertLocalStackPortsAvailable(offset = 0) {
1169
1228
  }
1170
1229
 
1171
1230
  async function checkLocalStackPorts(offset = 0) {
1231
+ // Named in the line, so an install made with --port-offset can see which
1232
+ // ports were actually checked.
1233
+ const label = offset ? `Local stack ports (offset ${offset})` : "Local stack ports";
1172
1234
  try {
1173
1235
  await assertLocalStackPortsAvailable(offset);
1174
- return { ok: true, message: "Local stack ports: available." };
1236
+ return { ok: true, message: `${label}: available.` };
1175
1237
  } catch (error) {
1176
1238
  return {
1177
1239
  ok: false,
1178
- message: `Local stack ports: unavailable. Fix: stop the conflicting project or rerun setup with --port-offset N. Details: ${error.message}`,
1240
+ message: `${label}: unavailable. Fix: stop the conflicting project or rerun setup with --port-offset N. Details: ${error.message}`,
1179
1241
  };
1180
1242
  }
1181
1243
  }
1182
1244
 
1245
+ /**
1246
+ * The port offset `setup` baked into this checkout's supabase/config.toml, or 0
1247
+ * when it was never set up. Read back, as `update` does (stackFromConfig),
1248
+ * because the offset is a setup-time flag nobody passes again: checking at 0
1249
+ * reported a working --port-offset install as "ports unavailable".
1250
+ */
1251
+ function installedStackOffset() {
1252
+ try {
1253
+ const root = appRoot ?? resolveAppRoot();
1254
+ if (!root) return 0;
1255
+ const configPath = path.join(root, "supabase", "config.toml");
1256
+ if (!fs.existsSync(configPath)) return 0;
1257
+ return stackFromConfig(fs.readFileSync(configPath, "utf8"))?.offset ?? 0;
1258
+ } catch {
1259
+ return 0;
1260
+ }
1261
+ }
1262
+
1183
1263
  async function runLocalPrerequisiteChecks({ offset = 0, report = false, enforce = false } = {}) {
1184
1264
  const results = [
1185
1265
  checkDockerInstalled(),
@@ -1278,7 +1358,8 @@ async function startDashboard(opts = {}) {
1278
1358
  child.unref();
1279
1359
  fs.writeFileSync(
1280
1360
  statePath,
1281
- `${JSON.stringify({ pid: child.pid, gateway: dashboard.url, port: dashboard.port, logPath, startedAt: new Date().toISOString() })}\n`,
1361
+ // `script` is the identity check's anchor — see managedDashboardIdentity.
1362
+ `${JSON.stringify({ pid: child.pid, script: devServer, gateway: dashboard.url, port: dashboard.port, logPath, startedAt: new Date().toISOString() })}\n`,
1282
1363
  { mode: 0o600 }
1283
1364
  );
1284
1365
 
@@ -1326,6 +1407,14 @@ async function stopDashboard() {
1326
1407
  ok("No CLI-managed local dashboard is running.");
1327
1408
  return;
1328
1409
  }
1410
+ if (!state.verified) {
1411
+ // Refuse rather than guess: signalling a process group we cannot identify
1412
+ // is exactly the failure this check exists to prevent.
1413
+ throw new Error(
1414
+ `Could not confirm that PID ${state.pid} is the dashboard this CLI started, so it was not stopped. ` +
1415
+ `Stop it yourself if it is, then delete ${dashboardStatePath()}.`
1416
+ );
1417
+ }
1329
1418
 
1330
1419
  if (process.platform === "win32") {
1331
1420
  // Politely first — it lets Next flush if anything is listening for it — but
@@ -1547,19 +1636,210 @@ async function resetLocalStack(opts = {}) {
1547
1636
  ok("Local stack recreated. Run `passcontrol start` to launch the dashboard.");
1548
1637
  }
1549
1638
 
1639
+ // ── passcontrol update ───────────────────────────────────────────────────────
1640
+ //
1641
+ // The decisions live in cli/update.mjs (pure, tested); this is the half that
1642
+ // runs git, npm and the stack. Order matters and is the whole design: read
1643
+ // everything, show the plan, ask once, update the CLI, then hand the app phase
1644
+ // to the NEW CLI so the version doing the work is the one that knows the steps.
1645
+
1646
+ function gitIn(root, args, timeout = 60_000, { raw = false } = {}) {
1647
+ const out = execFileSync("git", args, { cwd: root, encoding: "utf8", timeout, stdio: ["ignore", "pipe", "pipe"] });
1648
+ // `raw` for porcelain output, whose leading space is a status column.
1649
+ return raw ? out : out.trim();
1650
+ }
1651
+
1652
+ /** The self-host checkout's state, or why it is left alone. Fetches origin/main. */
1653
+ function analyzeAppForUpdate({ fetchRemote = true } = {}) {
1654
+ let source;
1655
+ try {
1656
+ source = resolveAppRootSource();
1657
+ } catch (error) {
1658
+ return { status: "refuse", reason: error.message };
1659
+ }
1660
+ if (!source) return { status: "none" };
1661
+ const root = source.path;
1662
+ const marker = readMarker();
1663
+ const resume = marker && path.resolve(marker.appRoot) === root ? marker : null;
1664
+ const refuse = (reason) => ({ status: "refuse", root, reason, resume });
1665
+
1666
+ if (!fs.existsSync(path.join(root, ".git"))) {
1667
+ return refuse(`${root} is not a git checkout (a downloaded archive?), so it cannot be fast-forwarded. Update it by hand, or replace it with a fresh \`${cliCommand("setup")}\` clone.`);
1668
+ }
1669
+ let origin = "";
1670
+ try {
1671
+ origin = gitIn(root, ["config", "--get", "remote.origin.url"]);
1672
+ } catch {
1673
+ // No origin: refused just below.
1674
+ }
1675
+ if (!isPublicRepoUrl(origin, PUBLIC_REPO_URL)) {
1676
+ return refuse(`${root} is not a clone of the public PassControl repo (origin: ${origin || "none"}), so it is its owner's to update.`);
1677
+ }
1678
+ let branch = "";
1679
+ try {
1680
+ branch = gitIn(root, ["symbolic-ref", "--short", "HEAD"]);
1681
+ } catch {
1682
+ // Detached HEAD: refused just below.
1683
+ }
1684
+ if (branch !== "main") return refuse(`${root} is on ${branch || "a detached HEAD"}, not main.`);
1685
+ const blockers = dirtyBlockers(gitIn(root, ["status", "--porcelain", "--untracked-files=no"], 60_000, { raw: true }));
1686
+ if (blockers.length) {
1687
+ return refuse(`${root} has local changes (${blockers.join(", ")}). Commit or discard them, then rerun.`);
1688
+ }
1689
+ const configPath = path.join(root, "supabase", "config.toml");
1690
+ const stack = fs.existsSync(configPath) ? stackFromConfig(fs.readFileSync(configPath, "utf8")) : null;
1691
+ if (!stack) return refuse(`the local stack was never set up in ${root}; run \`${cliCommand("setup")}\` first.`);
1692
+ const expected = expectedProjectId(path.basename(root), stack.offset);
1693
+ if (stack.projectId !== expected) {
1694
+ return refuse(
1695
+ `supabase/config.toml names the project "${stack.projectId}", but this directory would now run as "${expected}". ` +
1696
+ "Was the checkout moved or renamed? Re-running the stack here would start an EMPTY database, so it is left alone. Move it back, then rerun."
1697
+ );
1698
+ }
1699
+ if (fetchRemote) {
1700
+ try {
1701
+ gitIn(root, ["fetch", "--quiet", "origin", "main"], 120_000);
1702
+ } catch (error) {
1703
+ return refuse(`could not fetch the public repo (${String(error.message).split("\n")[0]}).`);
1704
+ }
1705
+ }
1706
+ const head = gitIn(root, ["rev-parse", "HEAD"]);
1707
+ const target = gitIn(root, ["rev-parse", "origin/main"]);
1708
+ const ahead = Number(gitIn(root, ["rev-list", "--count", "origin/main..HEAD"]));
1709
+ if (ahead > 0) return refuse(`${root} has ${ahead} commit(s) that are not in the public repo, so it cannot be fast-forwarded.`);
1710
+ const behind = Number(gitIn(root, ["rev-list", "--count", "HEAD..origin/main"]));
1711
+ const base = { root, offset: stack.offset, head, target, resume, lockfileDirty: gitIn(root, ["status", "--porcelain", "--untracked-files=no", "--", "package-lock.json"]) !== "" };
1712
+ if (behind === 0) return { status: "current", ...base };
1713
+ const migrations = gitIn(root, ["diff", "--name-only", "--diff-filter=A", head, target, "--", "db/migrations"]).split("\n").filter(Boolean);
1714
+ return { status: "behind", behind, from: head.slice(0, 7), to: target.slice(0, 7), migrations, ...base };
1715
+ }
1716
+
1717
+ async function applyAppUpdate(app) {
1718
+ appRoot = app.root;
1719
+ const npm = process.platform === "win32" ? "npm.cmd" : "npm";
1720
+ const dashboard = managedDashboardTarget();
1721
+ const managed = runningManagedDashboard();
1722
+ // A dashboard the CLI did not start (\`npm run dev\` by hand) would have its
1723
+ // dependencies and env rewritten underneath it — the same trap as building
1724
+ // while dev runs. Refuse rather than break it.
1725
+ if (!managed && await portIsListening(dashboard.port)) {
1726
+ throw new Error(
1727
+ `Port ${dashboard.port} is served by something this CLI did not start (a dashboard run by hand?). Stop it, then rerun \`${cliCommand("update")}\`. Nothing was changed.`
1728
+ );
1729
+ }
1730
+ const restart = app.resume?.wasRunning ?? Boolean(managed);
1731
+ const from = app.resume?.from ?? app.head;
1732
+ writeMarker({ appRoot: app.root, from, to: app.target, wasRunning: restart, startedAt: new Date().toISOString() });
1733
+ try {
1734
+ if (managed) {
1735
+ step("Stopping the dashboard…");
1736
+ await stopDashboard();
1737
+ }
1738
+ if (app.status === "behind") {
1739
+ // npm's own rewrite of the lockfile (see dirtyBlockers); \`npm ci\` below
1740
+ // installs exactly what the new lockfile says.
1741
+ if (app.lockfileDirty) gitIn(app.root, ["checkout", "--", "package-lock.json"]);
1742
+ step(`Fast-forwarding ${app.from} → ${app.to}…`);
1743
+ await runCommand("git", ["merge", "--ff-only", "origin/main"], { cwd: app.root });
1744
+ }
1745
+ step("Installing dependencies (npm ci)…");
1746
+ await runCommand(npm, ["ci"], { cwd: app.root });
1747
+ step("Applying migrations and refreshing the local stack…");
1748
+ await runCommand(npm, ["run", "dev:stack"], {
1749
+ cwd: app.root,
1750
+ env: { ...process.env, PASSCONTROL_PORT_OFFSET: String(app.offset), PASSCONTROL_SKIP_SEED: "1", PASSCONTROL_VIA_CLI: "1" },
1751
+ });
1752
+ if (restart) await startDashboard({ dashboardOnly: true });
1753
+ } catch (error) {
1754
+ throw new Error(
1755
+ `The update stopped part way: ${error.message}\n` +
1756
+ `Fix the cause, then run \`${cliCommand("update --app-only")}\` to finish (install, migrations${restart ? ", restart" : ""}). ` +
1757
+ "The dashboard is stopped until then."
1758
+ );
1759
+ }
1760
+ clearMarker();
1761
+ ok(`App updated to ${String(app.target).slice(0, 7)}.`);
1762
+ step(`To roll back the code: git -C ${app.root} checkout ${from}. Database migrations only go forward.`);
1763
+ }
1764
+
1765
+ async function updateCommand(opts = {}) {
1766
+ const appOnly = Boolean(opts.appOnly);
1767
+ if (appOnly && opts.expectVersion && String(opts.expectVersion) !== CLI_VERSION) {
1768
+ throw new Error(
1769
+ `Expected the updated CLI ${opts.expectVersion}, but this is ${CLI_VERSION}. The CLI update did not land where this command runs from; nothing in the app was changed.`
1770
+ );
1771
+ }
1772
+ const latest = appOnly ? CLI_VERSION : await fetchLatest(REGISTRY_URL, 10_000);
1773
+ const install = detectInstall({
1774
+ scriptPath: fs.realpathSync(CLI_ENTRY),
1775
+ isSourceCheckout: isRepoCheckout(PACKAGE_ROOT) && process.env.PASSCONTROL_FORCE_INSTALLED !== "1",
1776
+ version: latest ?? CLI_VERSION,
1777
+ });
1778
+ const app = analyzeAppForUpdate();
1779
+ const plan = planUpdate({ current: CLI_VERSION, latest, install, app });
1780
+ if (opts.json) {
1781
+ console.log(JSON.stringify(plan, null, 2));
1782
+ return;
1783
+ }
1784
+ for (const line of formatPlan(plan)) console.log(line);
1785
+ if (opts.check) return;
1786
+ if (plan.nothingToDo) {
1787
+ ok("Nothing to update.");
1788
+ return;
1789
+ }
1790
+ if (!opts.yes) {
1791
+ if (!(process.stdin.isTTY && process.stdout.isTTY)) {
1792
+ throw new Error("Refusing to update without a terminal to confirm. Rerun with --yes, or --check to only see the plan.");
1793
+ }
1794
+ if (!await confirmYes("\nProceed? [Y/n] ")) {
1795
+ step("Nothing was changed.");
1796
+ return;
1797
+ }
1798
+ }
1799
+ const appWork = plan.app.status === "behind" || Boolean(plan.app.resume);
1800
+ if (plan.cli.needed && plan.cli.command) {
1801
+ step(`Updating the CLI: ${plan.cli.command.join(" ")}`);
1802
+ try {
1803
+ await runCommand(plan.cli.command[0], plan.cli.command.slice(1), { cwd: os.homedir() });
1804
+ } catch (error) {
1805
+ throw new Error(
1806
+ `The CLI update failed (${error.message}). If npm reported EACCES, run it yourself with the permissions your install needs:\n ${plan.cli.manual}\nNothing else was changed.`
1807
+ );
1808
+ }
1809
+ ok(`CLI updated to ${plan.cli.to}.`);
1810
+ if (!appWork) return;
1811
+ // Hand the app phase to the NEW CLI and do nothing else here: any lazy import
1812
+ // after npm replaced these files would load the new code into the old process.
1813
+ const child = spawn(process.execPath, [CLI_ENTRY, "update", "--app-only", "--yes", "--expect-version", String(plan.cli.to)], { stdio: "inherit" });
1814
+ process.exitCode = await new Promise((resolve) => child.once("exit", (code) => resolve(code ?? 1)));
1815
+ return;
1816
+ }
1817
+ if (plan.cli.needed) step(`Update the CLI yourself: ${plan.cli.manual}`);
1818
+ if (appWork) await applyAppUpdate(plan.app);
1819
+ }
1820
+
1550
1821
  async function setupLocal(opts = {}) {
1551
- const dashboard = canonicalLocalDashboard();
1552
- const activation = await prepareLocalActivation(dashboard, opts);
1553
1822
  const offset = opts.portOffset === undefined ? 0 : Number(opts.portOffset);
1554
1823
  if (!Number.isInteger(offset) || offset < 0 || offset > 10000) {
1555
1824
  throw new Error("--port-offset must be an integer from 0 to 10000.");
1556
1825
  }
1826
+ // The dashboard moves with the offset, like Supabase and Redis: a second
1827
+ // install on :3000 would collide with the first one's dashboard. Saved as the
1828
+ // gateway by the activation below, so `start`, `stop` and `status` follow it.
1829
+ const dashboard = parseLocalDashboard(
1830
+ dashboardOriginForOffset(offset),
1831
+ offset ? "the offset local dashboard" : "the canonical local dashboard"
1832
+ );
1833
+ const activation = await prepareLocalActivation(dashboard, opts);
1557
1834
  await runLocalPrerequisiteChecks({ offset, enforce: true });
1558
1835
  await ensureAppRoot({ clone: true, appDir: opts.appDir, yes: opts.yes });
1559
1836
  step("Preparing the local Supabase, Redis, migrations, and dev user…");
1560
1837
  await runLocalCommand(process.platform === "win32" ? "npm.cmd" : "npm", ["run", "dev:stack"], {
1561
1838
  ...process.env,
1562
1839
  PASSCONTROL_PORT_OFFSET: String(offset),
1840
+ // Supabase's site URL and the receipt issuer are written from PORT.
1841
+ PORT: String(dashboard.port),
1842
+ PASSCONTROL_VIA_CLI: "1",
1563
1843
  });
1564
1844
  // dev:stack has just brought Supabase and Redis up (and would have exited
1565
1845
  // non-zero if it hadn't), so skip start's own service pass rather than print
@@ -2125,6 +2405,11 @@ function printAgentPreset(name = "generic", opts = {}) {
2125
2405
  return;
2126
2406
  }
2127
2407
 
2408
+ if (isServicePreset(preset)) {
2409
+ printServicePreset(preset, opts);
2410
+ return;
2411
+ }
2412
+
2128
2413
  const { provider, model, apiKey, baseUrl, port } = sidecarBaseUrl(opts);
2129
2414
  const modelWithProvider = `${provider}/${model}`;
2130
2415
  const sidecarStart = opts.port != null || process.env.SIDECAR_PORT != null
@@ -2192,6 +2477,34 @@ function printAgentPreset(name = "generic", opts = {}) {
2192
2477
  }
2193
2478
  }
2194
2479
 
2480
+ // A service preset has no provider and no model: the client is pointed at the
2481
+ // governed service route and sends no service token at all — the gateway
2482
+ // injects the workspace's, and only for calls the agent's rules admit.
2483
+ function printServicePreset(service, opts = {}) {
2484
+ const host = String(opts.host ?? process.env.SIDECAR_HOST ?? "127.0.0.1");
2485
+ const port = sidecarPort(opts);
2486
+ const sidecarStart = opts.port != null || process.env.SIDECAR_PORT != null
2487
+ ? cliCommand(`sidecar --port ${port}`)
2488
+ : cliCommand("sidecar");
2489
+ console.log(`# Start the bridge first: ${sidecarStart}`);
2490
+ switch (service) {
2491
+ case "github":
2492
+ console.log("# GitHub REST through PassControl. What this agent may do is set on its page in the");
2493
+ console.log("# dashboard, under GitHub access; the workspace's GitHub token stays in PassControl.");
2494
+ printExports([["GITHUB_API_URL", `http://${host}:${port}/api/v1/svc/github`]]);
2495
+ console.log("# Octokit: new Octokit({ baseUrl: process.env.GITHUB_API_URL }) — and no auth option.");
2496
+ break;
2497
+ case "telegram":
2498
+ console.log("# Telegram Bot API through PassControl. What this agent may do is set on its page in the");
2499
+ console.log("# dashboard, under Telegram access; the bot token stays in PassControl.");
2500
+ printExports([["TELEGRAM_API_URL", `http://${host}:${port}/api/v1/svc/telegram`]]);
2501
+ console.log('# Call a method by name, with no token in the URL: curl "$TELEGRAM_API_URL/getMe"');
2502
+ break;
2503
+ default:
2504
+ throw new Error(`Usage: passcontrol env <${integrationChoices()}>`);
2505
+ }
2506
+ }
2507
+
2195
2508
  function aiderConfig(opts = {}) {
2196
2509
  const { provider, model, baseUrl } = sidecarBaseUrl(opts);
2197
2510
  return [
@@ -2299,7 +2612,7 @@ async function serverVersion() {
2299
2612
  const origin = probeGatewayOrigin();
2300
2613
  if (!origin) return { version: null, detail: "the configured gateway is not a bare origin" };
2301
2614
  try {
2302
- const res = await fetchWithTimeout(`${origin}/api/version`);
2615
+ const res = await fetchWithTimeout(`${origin}/api/version`, {}, probeTimeoutMs(origin));
2303
2616
  // A gateway that predates this endpoint is a real PassControl gateway, and
2304
2617
  // saying "unreachable" about one that answered would send an operator to
2305
2618
  // debug their network instead of deploying.
@@ -2450,7 +2763,25 @@ async function doctorCommand(opts = {}) {
2450
2763
  // One authenticated request for this command. Its failure is a failed
2451
2764
  // diagnostic, not a CLI crash: remaining local checks are still useful.
2452
2765
  printSystemHealthDiagnostic(await fetchSystemHealth());
2453
- await runLocalPrerequisiteChecks({ report: true });
2766
+ // Docker, Supabase and the stack's ports matter only where a stack runs. A CLI
2767
+ // pointed at a remote gateway (Cloud) with no app checkout here has none, and
2768
+ // a failing "Local stack ports" line would send that user hunting for one.
2769
+ const probeOrigin = probeGatewayOrigin();
2770
+ const remoteGateway = probeOrigin !== null && !isLocalGatewayOrigin(probeOrigin);
2771
+ let localApp = null;
2772
+ try {
2773
+ localApp = resolveAppRoot();
2774
+ } catch {
2775
+ localApp = null;
2776
+ }
2777
+ if (remoteGateway && !localApp) {
2778
+ step(
2779
+ `Local prerequisites skipped: this CLI uses a remote gateway (${probeOrigin}). Docker and the ` +
2780
+ "local stack are needed only to self-host on this machine."
2781
+ );
2782
+ } else {
2783
+ await runLocalPrerequisiteChecks({ offset: installedStackOffset(), report: true });
2784
+ }
2454
2785
  if (config.passportId && config.passportSecret) {
2455
2786
  // The whole chain, not just the mint. "Visa mint works" proves the passport
2456
2787
  // authenticates and says nothing about scope, budget, the proxy or receipts —
@@ -2484,17 +2815,24 @@ async function doctorCommand(opts = {}) {
2484
2815
  step("Skipping control API check: no PASSCONTROL_API_KEY configured.");
2485
2816
  }
2486
2817
 
2487
- await checkInstanceSigningKey();
2818
+ await checkInstanceSigningKey({ remoteOrigin: remoteGateway ? probeOrigin : null });
2488
2819
  }
2489
2820
 
2490
2821
  // Receipts and agent tokens are signed by a key the DEPLOYMENT owns. A missing
2491
2822
  // key is loud (nothing is signed), but a PASSCONTROL_ISSUER pointing somewhere
2492
2823
  // that does not serve this deployment's JWKS fails silently: every receipt then
2493
2824
  // carries an `iss` whose key set cannot verify it. Check it explicitly.
2494
- async function checkInstanceSigningKey() {
2825
+ async function checkInstanceSigningKey({ remoteOrigin = null } = {}) {
2495
2826
  const seed = process.env.INSTANCE_SIGNING_KEY;
2496
2827
  const issuer = process.env.PASSCONTROL_ISSUER;
2497
2828
 
2829
+ // The key belongs to the deployment. A remote gateway signs with its own, so
2830
+ // its absence from this shell disables nothing.
2831
+ if (!seed && remoteOrigin) {
2832
+ step(`Receipts are signed by the gateway (${remoteOrigin}); its public keys are at ${remoteOrigin}/.well-known/jwks.json.`);
2833
+ return;
2834
+ }
2835
+
2498
2836
  if (!seed) {
2499
2837
  step(
2500
2838
  "Instance signing key not set in this shell — receipts and agent tokens are disabled " +
@@ -3162,7 +3500,9 @@ function keyTone(storage) {
3162
3500
  if (storage?.fallback) return ["warn", "file fallback", "the OS store was unavailable"];
3163
3501
  if (storage?.available !== true) return ["idle", "not configured", ""];
3164
3502
  if (storage?.tier === 1) return ["ok", "ready", String(storage.source ?? "OS store")];
3165
- return ["ok", "ready", "file"];
3503
+ // Tier 0 is a config file or the operator's environment; saying "file" for a
3504
+ // key that came from PASSPORT_SECRET sends them looking for a file to clean up.
3505
+ return ["ok", "ready", storage?.source === "environment variable" ? "env var" : "file"];
3166
3506
  }
3167
3507
 
3168
3508
  /**
@@ -3512,6 +3852,9 @@ async function main(argv = process.argv.slice(2), runtime = {}) {
3512
3852
  case "reset":
3513
3853
  await resetLocalStack(opts);
3514
3854
  break;
3855
+ case "update":
3856
+ await updateCommand(opts);
3857
+ break;
3515
3858
  case "setup":
3516
3859
  await setupLocal(opts);
3517
3860
  break;