passcontrol 0.6.2 → 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.
@@ -52,6 +52,7 @@ import {
52
52
  import { importCompletionMessage, noAgentCreateMessage } from "../cli/workspace-import-report.mjs";
53
53
  import { checkForUpdate } from "../cli/update-check.mjs";
54
54
  import { startSidecar } from "../cli/sidecar.mjs";
55
+ import { loginCommand } from "../cli/login.mjs";
55
56
  import {
56
57
  checkIssuerPublishesKey,
57
58
  generateInstanceKey,
@@ -85,6 +86,12 @@ const DEMO_API_KEY = "pc_demolocaltrydemolocaltrydemolocaltry0000";
85
86
  const DASHBOARD_STATE_FILE = "local-dashboard.json";
86
87
  const APP_STATE_FILE = "app.json";
87
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";
88
95
  const LOCAL_DASHBOARD_HOSTS = new Set(["localhost", "127.0.0.1", "::1", "[::1]"]);
89
96
  const LOCAL_STACK_PORTS = [54321, 54322, 54324, 54327, 8079];
90
97
  // The local stack (Supabase + Redis + dashboard) lives in a PassControl repo
@@ -141,19 +148,21 @@ ${heading("Usage:")}
141
148
  ${cmd} <command> [options]
142
149
 
143
150
  ${heading("Quick start")}
144
- ${cmd} init [--global] configure this project
145
- ${cmd} start [--dashboard-only] start the whole local stack (dashboard + Supabase + Redis)
146
- ${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
147
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
148
158
 
149
159
  ${heading("Operate")}
150
160
  ${cmd} status [--no-network] [--json]
151
161
  show active config and instance state
152
162
  ${cmd} version [--json] CLI, gateway and database schema versions
153
163
  ${cmd} doctor [--deep] [--fix] diagnose setup and repair a stopped dashboard
154
- ${cmd} call "hi" mint a visa and make a governed model call
155
- ${cmd} sidecar [--port 8788] [--allow-connect host[,host]]
156
- 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
157
166
 
158
167
  ${heading("Manage")}
159
168
  ${cmd} agent list [--json] list agents
@@ -177,7 +186,6 @@ ${heading("Integrate")}
177
186
  ${cmd} env [integration] print settings without writing anything
178
187
  ${cmd} configure <integration> [--write] [--force]
179
188
  preview or write integration config
180
- ${cmd} mcp start the stdio MCP server
181
189
  integrations: ${integrationChoices()}
182
190
 
183
191
  ${heading("Trust")}
@@ -187,9 +195,12 @@ ${heading("Trust")}
187
195
  ${cmd} verify token <jwt> --audience <aud> --issuer <origin>
188
196
  verify an agent-to-agent token
189
197
 
190
- ${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.
191
201
  ${cmd} setup [--no-open] [--port-offset N] [--app-dir DIR]
192
- 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)
193
204
  ${cmd} stop [--dashboard-only] stop the whole local stack (dashboard + Supabase + Redis)
194
205
  ${cmd} restart restart the CLI-managed local dashboard
195
206
  ${cmd} local-logs [--follow] show local dashboard logs
@@ -199,8 +210,8 @@ ${heading("Local stack")}
199
210
 
200
211
  ${heading("Config:")}
201
212
  Env vars win, then nearest .passcontrol, then ~/.config/passcontrol/config.
202
- Installed globally, the local-stack commands (setup/start/reset) use a cloned
203
- 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:
204
215
  --app-dir DIR → PASSCONTROL_APP_ROOT → surrounding checkout → remembered
205
216
  checkout in ~/.config/passcontrol/app.json (survives npm uninstall; clear
206
217
  it with \`${cmd} unlink\`).
@@ -530,6 +541,14 @@ function checkDockerInstalled() {
530
541
  };
531
542
  }
532
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
+
533
552
  function checkDockerDaemon() {
534
553
  if (!commandExists("docker")) {
535
554
  return {
@@ -548,7 +567,7 @@ function checkDockerDaemon() {
548
567
  // where Docker was available throughout, and it would tell a first-time user
549
568
  // on a slow laptop to go start something already running. A wedged engine
550
569
  // still gets caught; it just takes fifteen seconds to say so.
551
- execFileSync("docker", ["info"], { stdio: "ignore", timeout: 15_000 });
570
+ execFileSync("docker", ["info"], { stdio: "ignore", timeout: DOCKER_TIMEOUT_MS });
552
571
  return { ok: true, message: "Docker daemon: running." };
553
572
  } catch (error) {
554
573
  // A timeout and a stopped daemon need different things from the reader, so
@@ -594,9 +613,18 @@ async function promptLine(question, fallback) {
594
613
  }
595
614
  }
596
615
 
597
- 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 } = {}) {
598
625
  const answer = (await promptLine(question, "")).toLowerCase();
599
- return answer === "" || answer === "y" || answer === "yes";
626
+ if (answer === "") return fallback;
627
+ return answer === "y" || answer === "yes";
600
628
  }
601
629
 
602
630
  // Resolve the stack checkout, cloning the public repo on demand when the CLI is
@@ -694,7 +722,7 @@ function localSupabaseIsRunning() {
694
722
  execFileSync(
695
723
  "docker",
696
724
  ["ps", "-q", "--filter", `label=com.supabase.cli.project=${localSupabaseProjectId()}`, "--filter", "name=supabase_db"],
697
- { encoding: "utf8" }
725
+ { encoding: "utf8", timeout: DOCKER_TIMEOUT_MS }
698
726
  ).trim()
699
727
  );
700
728
  } catch {
@@ -863,7 +891,7 @@ function ownSupabaseDatabaseIsRunning(offset = 0) {
863
891
  if (!root) return false;
864
892
  const project = `${path.basename(root)}${offset ? `-${offset}` : ""}`;
865
893
  return Boolean(
866
- 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()
867
895
  );
868
896
  } catch {
869
897
  return false;
@@ -910,8 +938,16 @@ async function runLocalPrerequisiteChecks({ offset = 0, report = false, enforce
910
938
  }
911
939
 
912
940
  if (enforce) {
913
- const failure = results.find((result) => !result.ok);
914
- 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
+ }
915
951
  }
916
952
  return results;
917
953
  }
@@ -1383,7 +1419,8 @@ async function tryCommand() {
1383
1419
  step(" PASSCONTROL_DEMO=1 npm run dev:docker # enables the keyless demo provider");
1384
1420
  } else {
1385
1421
  fail(`Could not reach the gateway at ${gateway} (${msg}).`);
1386
- 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:");
1387
1424
  step(" PASSCONTROL_DEMO=1 npm run dev:stack # Supabase + Redis + migrate + seed the demo passport");
1388
1425
  step(" PASSCONTROL_DEMO=1 npm run dev:docker # start the gateway with the demo provider enabled");
1389
1426
  }
@@ -2250,11 +2287,32 @@ async function openDashboard(opts = {}) {
2250
2287
  const url = parsed.protocol === "http:" && LOCAL_DASHBOARD_HOSTS.has(parsed.hostname)
2251
2288
  ? (await startDashboard(opts)).url
2252
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) {
2253
2309
  const platform = process.platform;
2254
2310
  const command =
2255
2311
  platform === "darwin" ? "open" : platform === "win32" ? "cmd" : "xdg-open";
2256
2312
  const args = platform === "win32" ? ["/c", "start", "", url] : [url];
2257
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.
2258
2316
  child.on("error", () => step(`Open this URL: ${url}`));
2259
2317
  child.unref();
2260
2318
  ok(`opening ${url}`);
@@ -2416,6 +2474,11 @@ async function main() {
2416
2474
  case "status":
2417
2475
  await printCockpit({ noNetwork: Boolean(opts.noNetwork), json: Boolean(opts.json) });
2418
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;
2419
2482
  case "init":
2420
2483
  await initCommand(opts);
2421
2484
  break;
package/cli/config.mjs CHANGED
@@ -225,8 +225,23 @@ export function configPathLabel(sources = configSources) {
225
225
  return "none";
226
226
  }
227
227
 
228
+ /**
229
+ * Write the whole config. Every CONFIG_KEY is emitted, so a key absent from
230
+ * `values` is BLANKED — that is correct for `init`, which collects all of them,
231
+ * and wrong for any caller that means to change a subset. Use mergeConfigFile
232
+ * for those.
233
+ *
234
+ * The chmod is not redundant with the `mode` option. Node applies `mode` only
235
+ * when it CREATES the file, so overwriting a config that already exists as 0644
236
+ * leaves it 0644 — and this file holds a passport secret. The directory mode is
237
+ * applied on the global path only: for a project-local `.passcontrol` the
238
+ * dirname is the user's own project directory, and silently 0700-ing that is a
239
+ * surprising thing for a config write to do.
240
+ */
228
241
  export function writeConfigFile(file, values) {
229
- fs.mkdirSync(path.dirname(file), { recursive: true });
242
+ const dir = path.dirname(file);
243
+ const isGlobal = path.resolve(file) === path.resolve(globalConfigPath());
244
+ fs.mkdirSync(dir, { recursive: true, ...(isGlobal ? { mode: 0o700 } : {}) });
230
245
  const lines = [
231
246
  "# PassControl CLI config.",
232
247
  "# Keep this file private: it can contain a passport secret.",
@@ -236,6 +251,33 @@ export function writeConfigFile(file, values) {
236
251
  lines.push(`${key}=${values[key] ?? ""}`);
237
252
  }
238
253
  fs.writeFileSync(file, `${lines.join("\n")}\n`, { mode: 0o600 });
254
+ // Explicit, because `mode` above is a no-op on an existing file.
255
+ try {
256
+ fs.chmodSync(file, 0o600);
257
+ if (isGlobal) fs.chmodSync(dir, 0o700);
258
+ } catch {
259
+ // Windows and some network filesystems have no meaningful POSIX mode. A
260
+ // config that is written but not tightened beats a login that dies here.
261
+ }
262
+ }
263
+
264
+ /**
265
+ * Change SOME keys, keeping the rest.
266
+ *
267
+ * `passcontrol login` writes three credential keys. Routing that through
268
+ * writeConfigFile would emit `PROVIDER=`, `MODEL=` and `PASSCONTROL_GATEWAY=`
269
+ * as empty strings and wipe a working setup — right result, wrong side effect,
270
+ * and invisible until the next call failed against the wrong provider.
271
+ */
272
+ export function mergeConfigFile(file, patch) {
273
+ let existing = {};
274
+ try {
275
+ existing = readConfigFile(file);
276
+ } catch {
277
+ // No file yet, or unreadable. A first login lands here, and writing the
278
+ // patch alone is exactly right — there is nothing to preserve.
279
+ }
280
+ writeConfigFile(file, { ...existing, ...patch });
239
281
  }
240
282
 
241
283
  export function heading(message = "") {
package/cli/login.mjs ADDED
@@ -0,0 +1,378 @@
1
+ // `passcontrol login` — browser-approved credentials for this machine.
2
+ //
3
+ // The problem it removes: getting a passport onto a machine used to mean opening
4
+ // the dashboard, issuing an agent, copying two 43-character base64url strings,
5
+ // and pasting both into an interactive prompt with the secret echoed to the
6
+ // terminal. That is the friction that loses the "$5 vs. do it myself" user, and
7
+ // it produced this repo's one real incident — a passport secret pasted into a
8
+ // provider `api_key` field, rejected 401 with no audit row to explain it.
9
+ //
10
+ // ── The shape, and why it is this shape ──────────────────────────────────────
11
+ //
12
+ // RFC 8628 device flow. The CLI opens a login, prints an 8-character code,
13
+ // copies it to the clipboard, opens the browser, and polls. The operator pastes
14
+ // the code and approves once.
15
+ //
16
+ // The code travels TERMINAL → BROWSER and never the reverse, and never in a URL.
17
+ // The human moving it across IS the channel binding — it is the only evidence
18
+ // that the person at the browser is the person at the terminal. A pre-filled
19
+ // approval link removes exactly that: the attacker starts the flow on their own
20
+ // machine, keeps the device_code, sends the victim the link, and the signed-in
21
+ // victim's click hands over a write-scoped control-plane key on their own tenant.
22
+ // tests/cli-login-shape.test.ts pins the URL against that design returning.
23
+ //
24
+ // The clipboard copy is not the same thing and does not reopen it: an attacker
25
+ // cannot write to your clipboard from a link. The code reaches the browser from
26
+ // a process the operator launched on their own machine.
27
+ //
28
+ // ── Why this file exists at all, instead of living in bin/ ───────────────────
29
+ //
30
+ // It must not be able to reach the self-host clone. `openDashboard` in bin/ is
31
+ // not a URL opener — for a localhost gateway it routes through `startDashboard`,
32
+ // which is `ensureAppRoot({ clone: true })`. Putting login beside it invites the
33
+ // obvious reuse, which would make a `git clone` the second thing a Cloud user's
34
+ // first command does. This module opens URLs through `openUrl` only, and the
35
+ // test suite asserts it names neither of the cloning helpers.
36
+ import { spawn } from "node:child_process";
37
+ import os from "node:os";
38
+ import { ed25519 } from "@noble/curves/ed25519";
39
+ import fs from "node:fs";
40
+ import {
41
+ fail,
42
+ findProjectConfig,
43
+ globalConfigPath,
44
+ heading,
45
+ mergeConfigFile,
46
+ ok,
47
+ requireControlGateway,
48
+ step,
49
+ warn,
50
+ } from "./config.mjs";
51
+
52
+ const b64url = (bytes) => Buffer.from(bytes).toString("base64url");
53
+
54
+ /** Display form, `FKDR-8T2W`. Presentation only — the wire form has no hyphen. */
55
+ function formatCode(code) {
56
+ return code.length === 8 ? `${code.slice(0, 4)}-${code.slice(4)}` : code;
57
+ }
58
+
59
+ /**
60
+ * Copy text to the OS clipboard. Resolves true on success, false on ANY failure.
61
+ *
62
+ * Never throws and never rejects: a clipboard is a convenience, and a login that
63
+ * dies because a Linux box has no `wl-copy` would be a worse product than one
64
+ * that just prints the code. The caller prints the code unconditionally and uses
65
+ * this only to decide whether to add "(copied to your clipboard)".
66
+ *
67
+ * Both failure modes are handled, and they are easy to conflate:
68
+ * - `error` the binary is absent. On Linux this is the COMMON case — none of
69
+ * wl-copy / xclip / xsel is guaranteed installed.
70
+ * - `close` the binary exists and exited non-zero (no display, no Wayland
71
+ * socket, a wedged X server). `error` does not fire for this.
72
+ */
73
+ export function copyToClipboard(text, { platform = process.platform } = {}) {
74
+ const candidates =
75
+ platform === "darwin"
76
+ ? [["pbcopy", []]]
77
+ : platform === "win32"
78
+ ? [["clip", []]]
79
+ : [
80
+ ["wl-copy", []],
81
+ ["xclip", ["-selection", "clipboard"]],
82
+ ["xsel", ["--clipboard", "--input"]],
83
+ ];
84
+
85
+ const tryOne = (index) =>
86
+ new Promise((resolve) => {
87
+ const candidate = candidates[index];
88
+ if (!candidate) return resolve(false);
89
+ const [command, args] = candidate;
90
+ let settled = false;
91
+ const done = (value) => {
92
+ if (settled) return;
93
+ settled = true;
94
+ resolve(value);
95
+ };
96
+ let child;
97
+ try {
98
+ child = spawn(command, args, { stdio: ["pipe", "ignore", "ignore"] });
99
+ } catch {
100
+ return done(false);
101
+ }
102
+ child.on("error", () => done(false));
103
+ child.on("close", (code) => done(code === 0));
104
+ try {
105
+ child.stdin.on("error", () => done(false));
106
+ child.stdin.write(text);
107
+ // pbcopy does not exit until stdin closes. A forgotten end() here hangs
108
+ // the login on the one step that was supposed to make it effortless.
109
+ child.stdin.end();
110
+ } catch {
111
+ done(false);
112
+ }
113
+ });
114
+
115
+ return (async () => {
116
+ for (let i = 0; i < candidates.length; i++) {
117
+ if (await tryOne(i)) return true;
118
+ }
119
+ return false;
120
+ })();
121
+ }
122
+
123
+ /** The approval route. Fixed here, not taken on trust from the response. */
124
+ export const APPROVAL_PATH = "/dashboard/cli";
125
+
126
+ /**
127
+ * Decide where the browser is sent — locally, from the origin the operator
128
+ * configured, and never from the response body alone.
129
+ *
130
+ * The server does send a `verification_uri`, and honouring it blindly would make
131
+ * "where does my browser go" a value supplied over the network. Two things fall
132
+ * out of that, both bad: a gateway that is wrong or compromised could point the
133
+ * operator anywhere, and a future server could reintroduce the rejected
134
+ * pre-filled `#code=` design without a single line changing in the CLI.
135
+ *
136
+ * So the response is accepted only if it agrees with what we would have built:
137
+ * same origin, same path, and NO fragment or query. Anything else falls back to
138
+ * the local construction rather than failing the login — the code still has to
139
+ * be entered by hand either way, so a mismatch is a reason to distrust the URL,
140
+ * not a reason to strand the operator.
141
+ */
142
+ export function approvalUrl(origin, offered, { onMismatch = () => {} } = {}) {
143
+ const expected = `${origin}${APPROVAL_PATH}`;
144
+ if (offered && offered !== expected) {
145
+ // Always the locally-built URL — the report exists so a disagreement is
146
+ // visible rather than silently obeyed. A gateway offering a different origin,
147
+ // a different path, or a `#code=` fragment is either misconfigured or
148
+ // hostile, and both are worth saying out loud.
149
+ onMismatch(String(offered));
150
+ }
151
+ return expected;
152
+ }
153
+
154
+ /** POST JSON with no credential attached. `login` has no key yet by definition. */
155
+ async function postJson(url, body, { timeoutMs = 15_000, fetchImpl = fetch } = {}) {
156
+ const controller = new AbortController();
157
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
158
+ try {
159
+ const res = await fetchImpl(url, {
160
+ method: "POST",
161
+ headers: { "content-type": "application/json" },
162
+ body: JSON.stringify(body ?? {}),
163
+ signal: controller.signal,
164
+ });
165
+ let parsed = null;
166
+ try {
167
+ parsed = await res.json();
168
+ } catch {
169
+ parsed = null;
170
+ }
171
+ return { status: res.status, body: parsed };
172
+ } finally {
173
+ clearTimeout(timer);
174
+ }
175
+ }
176
+
177
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
178
+
179
+ /**
180
+ * Poll until the operator approves, denies, or the login expires.
181
+ *
182
+ * Honours the server's `interval` and backs off on `slow_down`, so the poll rate
183
+ * is the server's decision and can be widened without shipping a new CLI.
184
+ */
185
+ async function pollForGrant(origin, deviceCode, { interval, expiresIn, fetchImpl, now = Date.now }) {
186
+ const deadline = now() + expiresIn * 1000;
187
+ let waitMs = Math.max(500, interval * 1000);
188
+ while (now() < deadline) {
189
+ await sleep(waitMs);
190
+ const res = await postJson(`${origin}/api/auth/device/token`, { device_code: deviceCode }, { fetchImpl });
191
+ if (res.status === 200 && res.body?.api_key) return res.body;
192
+ const error = res.body?.error;
193
+ if (error === "access_denied") {
194
+ throw new Error("Login was denied in the browser. Nothing was created.");
195
+ }
196
+ if (error === "expired_token") {
197
+ throw new Error("That login expired before it was approved. Run `passcontrol login` again.");
198
+ }
199
+ // slow_down is the server asking for room; anything else unexpected gets the
200
+ // same treatment rather than a tight retry loop against an unhealthy host.
201
+ if (error === "slow_down" || res.status >= 500) waitMs = Math.min(waitMs * 2, 10_000);
202
+ }
203
+ throw new Error("Timed out waiting for approval. Run `passcontrol login` again.");
204
+ }
205
+
206
+ /** Authenticated control-plane call, using the key this flow just collected. */
207
+ async function control(origin, apiKey, method, path, body, fetchImpl = fetch) {
208
+ const res = await fetchImpl(`${origin}/api/control/v1${path}`, {
209
+ method,
210
+ headers: {
211
+ authorization: `Bearer ${apiKey}`,
212
+ ...(body ? { "content-type": "application/json" } : {}),
213
+ },
214
+ ...(body ? { body: JSON.stringify(body) } : {}),
215
+ });
216
+ const parsed = await res.json().catch(() => null);
217
+ if (!res.ok) {
218
+ throw new Error(`Control plane refused ${method} ${path} (${res.status}).`);
219
+ }
220
+ return parsed;
221
+ }
222
+
223
+ /**
224
+ * Warn when the file we are about to write will NOT be the one that wins.
225
+ *
226
+ * `cli/config.mjs` resolves env → nearest project `.passcontrol` → global. A
227
+ * user with a project config in cwd would otherwise see "✓ Wrote
228
+ * ~/.config/passcontrol/config" and then watch `passcontrol call` keep using the
229
+ * old passport — right result, wrong file wins, and nothing visibly broken.
230
+ */
231
+ function warnIfShadowed(target, { cwd = process.cwd() } = {}) {
232
+ if (target !== globalConfigPath()) return false;
233
+ const project = findProjectConfig(cwd);
234
+ if (!project) return false;
235
+ warn(`A project config at ${project} takes priority over the file just written.`);
236
+ step("Commands run from this directory will keep using it. Use --project to write there instead.");
237
+ return true;
238
+ }
239
+
240
+ /**
241
+ * Refuse to destroy a working passport without being told to.
242
+ *
243
+ * `mergeConfigFile` preserves PROVIDER and MODEL, but it necessarily REPLACES
244
+ * PASSPORT_ID and PASSPORT_SECRET — and PassControl has never held a copy of
245
+ * that private key, so overwriting it is unrecoverable. `init` has always asked
246
+ * before clobbering a config; a command designed to be run casually must ask at
247
+ * least as loudly.
248
+ *
249
+ * Defaults to NO. The safe answer is the one you get by pressing enter, because
250
+ * the cost of a stray yes here is an agent that silently stops authenticating on
251
+ * every other machine that shared the passport.
252
+ */
253
+ async function confirmReplacingPassport(target, confirm) {
254
+ let existing = "";
255
+ try {
256
+ existing = fs.readFileSync(target, "utf8");
257
+ } catch {
258
+ return true; // Nothing there. Nothing to lose.
259
+ }
260
+ const current = /^PASSPORT_SECRET=(.+)$/mu.exec(existing)?.[1]?.trim();
261
+ if (!current) return true;
262
+
263
+ warn(`${target} already holds a passport secret.`);
264
+ step("Continuing replaces it, and PassControl has no copy — anything still using that");
265
+ step("passport keeps working only until you revoke or rotate the agent behind it.");
266
+ return confirm("Replace it? [y/N] ", { default: false });
267
+ }
268
+
269
+ export async function loginCommand(opts = {}, deps = {}) {
270
+ const fetchImpl = deps.fetch ?? fetch;
271
+ const openUrl = deps.openUrl ?? (() => {});
272
+ const confirm = deps.confirmYes ?? (async (_q, o = {}) => o.default !== false);
273
+ const promptLine = deps.promptLine ?? (async (_q, fallback) => fallback);
274
+
275
+ // Validate the destination BEFORE anything is requested — the ordering mintVisa
276
+ // uses. A rejected gateway must cost zero sockets.
277
+ const origin = requireControlGateway();
278
+
279
+ const clientName = String(opts.name || os.hostname() || "this machine");
280
+ const started = await postJson(
281
+ `${origin}/api/auth/device/start`,
282
+ { client_name: clientName },
283
+ { fetchImpl }
284
+ );
285
+ if (started.status !== 200 || !started.body?.user_code) {
286
+ throw new Error(`Could not start a login at ${origin} (${started.status}).`);
287
+ }
288
+ const { device_code: deviceCode, user_code: userCode } = started.body;
289
+ const verificationUri = approvalUrl(origin, started.body.verification_uri, {
290
+ onMismatch: () => warn("The gateway offered a different approval URL. Using the configured origin."),
291
+ });
292
+
293
+ // Print FIRST and unconditionally. Only the suffix depends on the clipboard —
294
+ // a headless box that says "copied to your clipboard" with nothing to paste is
295
+ // worse than one that never mentioned a clipboard at all.
296
+ const copied = await copyToClipboard(userCode);
297
+ console.log("");
298
+ console.log(heading("Approve this machine"));
299
+ console.log(` Code: ${formatCode(userCode)}${copied ? " (copied to your clipboard)" : ""}`);
300
+ console.log(` Open: ${verificationUri}`);
301
+ console.log("");
302
+ step("Paste the code there and press Approve. Waiting…");
303
+ openUrl(verificationUri);
304
+
305
+ const grant = await pollForGrant(origin, deviceCode, {
306
+ interval: Number(started.body.interval ?? 1),
307
+ expiresIn: Number(started.body.expires_in ?? 600),
308
+ fetchImpl,
309
+ });
310
+ ok("approved");
311
+
312
+ // ── Provision a passport for this machine ─────────────────────────────────
313
+ //
314
+ // The keypair is generated HERE and only the PUBLIC half is sent. The gateway
315
+ // has never held a passport private key; this command must not be the first
316
+ // thing to change that.
317
+ const agents = (await control(origin, grant.api_key, "GET", "/agents", null, fetchImpl))?.agents ?? [];
318
+ let agentId = null;
319
+ if (agents.length > 0 && !opts.new) {
320
+ step(`This workspace has ${agents.length} agent(s).`);
321
+ const existing = await promptLine("Agent id to reuse, or blank to create a new one: ", "");
322
+ if (existing) {
323
+ // Reusing means ROTATING, and rotation is not free — say so before doing it.
324
+ warn(`PassControl has never held that agent's private key, so this machine cannot be given`);
325
+ step(`the existing one. Continuing rotates it: any other machine using that passport stops`);
326
+ step(`working once the grace window lapses.`);
327
+ if (await confirm("Create a NEW agent for this machine instead? [Y/n] ")) agentId = null;
328
+ else agentId = existing;
329
+ }
330
+ }
331
+
332
+ const priv = ed25519.utils.randomPrivateKey();
333
+ const passportId = b64url(ed25519.getPublicKey(priv));
334
+ const passportSecret = b64url(priv);
335
+
336
+ if (agentId) {
337
+ await control(origin, grant.api_key, "POST", `/agents/${encodeURIComponent(agentId)}/rotate`, {
338
+ passportPubkey: passportId,
339
+ }, fetchImpl);
340
+ ok(`rotated passport for agent ${agentId}`);
341
+ } else {
342
+ const created = await control(origin, grant.api_key, "POST", "/agents", {
343
+ name: clientName,
344
+ passportPubkey: passportId,
345
+ scopes: [{ provider: "anthropic", models: ["claude-*"] }],
346
+ }, fetchImpl);
347
+ agentId = created?.id ?? null;
348
+ ok(`created agent ${created?.name ?? clientName}`);
349
+ }
350
+
351
+ // MERGE, never a full write. writeConfigFile emits every CONFIG_KEY, so a
352
+ // three-key write would blank PROVIDER, MODEL and PASSCONTROL_GATEWAY — right
353
+ // result, wrong side effect, invisible until the next call hit the wrong
354
+ // provider.
355
+ const target = opts.project ? `${process.cwd()}/.passcontrol` : globalConfigPath();
356
+ if (!(await confirmReplacingPassport(target, confirm))) {
357
+ // The agent and its key were already created server-side, so say what exists
358
+ // rather than pretending nothing happened. Leaving the operator with an
359
+ // orphaned agent AND no explanation would be the worse failure.
360
+ warn("Left the existing config unchanged.");
361
+ step(`The new passport was NOT saved. Agent ${agentId ?? "(unknown)"} and the key`);
362
+ step(`"CLI on ${clientName}" now exist unused — revoke them in Settings.`);
363
+ return { agentId, passportId, target: null };
364
+ }
365
+ mergeConfigFile(target, {
366
+ PASSCONTROL_GATEWAY: origin,
367
+ PASSPORT_ID: passportId,
368
+ PASSPORT_SECRET: passportSecret,
369
+ PASSCONTROL_API_KEY: grant.api_key,
370
+ });
371
+ ok(`wrote ${target}`);
372
+ warnIfShadowed(target);
373
+
374
+ step("");
375
+ step('Try it: passcontrol call "hi"');
376
+ step(`The key is listed in Settings as "CLI on ${clientName}" and can be revoked there.`);
377
+ return { agentId, passportId, target };
378
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "passcontrol",
3
- "version": "0.6.2",
3
+ "version": "0.7.0",
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",