passcontrol 0.6.2 → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/cli/login.mjs ADDED
@@ -0,0 +1,466 @@
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
+ CLOUD_GATEWAY,
42
+ fail,
43
+ findProjectConfig,
44
+ globalConfigPath,
45
+ heading,
46
+ mergeConfigFile,
47
+ ok,
48
+ requireControlGateway,
49
+ step,
50
+ warn,
51
+ } from "./config.mjs";
52
+
53
+ export { CLOUD_GATEWAY };
54
+
55
+ const b64url = (bytes) => Buffer.from(bytes).toString("base64url");
56
+
57
+ /** Display form, `FKDR-8T2W`. Presentation only — the wire form has no hyphen. */
58
+ function formatCode(code) {
59
+ return code.length === 8 ? `${code.slice(0, 4)}-${code.slice(4)}` : code;
60
+ }
61
+
62
+ /**
63
+ * Copy text to the OS clipboard. Resolves true on success, false on ANY failure.
64
+ *
65
+ * Never throws and never rejects: a clipboard is a convenience, and a login that
66
+ * dies because a Linux box has no `wl-copy` would be a worse product than one
67
+ * that just prints the code. The caller prints the code unconditionally and uses
68
+ * this only to decide whether to add "(copied to your clipboard)".
69
+ *
70
+ * Both failure modes are handled, and they are easy to conflate:
71
+ * - `error` the binary is absent. On Linux this is the COMMON case — none of
72
+ * wl-copy / xclip / xsel is guaranteed installed.
73
+ * - `close` the binary exists and exited non-zero (no display, no Wayland
74
+ * socket, a wedged X server). `error` does not fire for this.
75
+ */
76
+ export function copyToClipboard(text, { platform = process.platform } = {}) {
77
+ const candidates =
78
+ platform === "darwin"
79
+ ? [["pbcopy", []]]
80
+ : platform === "win32"
81
+ ? [["clip", []]]
82
+ : [
83
+ ["wl-copy", []],
84
+ ["xclip", ["-selection", "clipboard"]],
85
+ ["xsel", ["--clipboard", "--input"]],
86
+ ];
87
+
88
+ const tryOne = (index) =>
89
+ new Promise((resolve) => {
90
+ const candidate = candidates[index];
91
+ if (!candidate) return resolve(false);
92
+ const [command, args] = candidate;
93
+ let settled = false;
94
+ const done = (value) => {
95
+ if (settled) return;
96
+ settled = true;
97
+ resolve(value);
98
+ };
99
+ let child;
100
+ try {
101
+ child = spawn(command, args, { stdio: ["pipe", "ignore", "ignore"] });
102
+ } catch {
103
+ return done(false);
104
+ }
105
+ child.on("error", () => done(false));
106
+ child.on("close", (code) => done(code === 0));
107
+ try {
108
+ child.stdin.on("error", () => done(false));
109
+ child.stdin.write(text);
110
+ // pbcopy does not exit until stdin closes. A forgotten end() here hangs
111
+ // the login on the one step that was supposed to make it effortless.
112
+ child.stdin.end();
113
+ } catch {
114
+ done(false);
115
+ }
116
+ });
117
+
118
+ return (async () => {
119
+ for (let i = 0; i < candidates.length; i++) {
120
+ if (await tryOne(i)) return true;
121
+ }
122
+ return false;
123
+ })();
124
+ }
125
+
126
+ /** The approval route. Fixed here, not taken on trust from the response. */
127
+ export const APPROVAL_PATH = "/dashboard/cli";
128
+
129
+ /**
130
+ * Decide where the browser is sent — locally, from the origin the operator
131
+ * configured, and never from the response body alone.
132
+ *
133
+ * The server does send a `verification_uri`, and honouring it blindly would make
134
+ * "where does my browser go" a value supplied over the network. Two things fall
135
+ * out of that, both bad: a gateway that is wrong or compromised could point the
136
+ * operator anywhere, and a future server could reintroduce the rejected
137
+ * pre-filled `#code=` design without a single line changing in the CLI.
138
+ *
139
+ * So the response is accepted only if it agrees with what we would have built:
140
+ * same origin, same path, and NO fragment or query. Anything else falls back to
141
+ * the local construction rather than failing the login — the code still has to
142
+ * be entered by hand either way, so a mismatch is a reason to distrust the URL,
143
+ * not a reason to strand the operator.
144
+ */
145
+ export function approvalUrl(origin, offered, { onMismatch = () => {} } = {}) {
146
+ const expected = `${origin}${APPROVAL_PATH}`;
147
+ if (offered && offered !== expected) {
148
+ // Always the locally-built URL — the report exists so a disagreement is
149
+ // visible rather than silently obeyed. A gateway offering a different origin,
150
+ // a different path, or a `#code=` fragment is either misconfigured or
151
+ // hostile, and both are worth saying out loud.
152
+ onMismatch(String(offered));
153
+ }
154
+ return expected;
155
+ }
156
+
157
+ /** POST JSON with no credential attached. `login` has no key yet by definition. */
158
+ async function postJson(url, body, { timeoutMs = 15_000, fetchImpl = fetch } = {}) {
159
+ const controller = new AbortController();
160
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
161
+ try {
162
+ let res;
163
+ try {
164
+ res = await fetchImpl(url, {
165
+ method: "POST",
166
+ headers: { "content-type": "application/json" },
167
+ body: JSON.stringify(body ?? {}),
168
+ signal: controller.signal,
169
+ });
170
+ } catch (error) {
171
+ const origin = new URL(url).origin;
172
+ const detail = error instanceof Error ? error.message : String(error);
173
+ throw new Error(`Could not reach the gateway at ${origin} (${detail}).`, { cause: error });
174
+ }
175
+ let parsed = null;
176
+ try {
177
+ parsed = await res.json();
178
+ } catch {
179
+ parsed = null;
180
+ }
181
+ return { status: res.status, body: parsed };
182
+ } finally {
183
+ clearTimeout(timer);
184
+ }
185
+ }
186
+
187
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
188
+
189
+ /**
190
+ * Poll until the operator approves, denies, or the login expires.
191
+ *
192
+ * Honours the server's `interval` and backs off on `slow_down`, so the poll rate
193
+ * is the server's decision and can be widened without shipping a new CLI.
194
+ */
195
+ async function pollForGrant(origin, deviceCode, { interval, expiresIn, fetchImpl, now = Date.now }) {
196
+ const deadline = now() + expiresIn * 1000;
197
+ let waitMs = Math.max(500, interval * 1000);
198
+ // A transport failure is NOT fatal here, and this is the one place in the flow
199
+ // where that distinction matters. By the time we are polling, the operator is
200
+ // already looking at a code and waiting; ending the login on a single dropped
201
+ // request costs them the whole flow and a fresh code because a packet went
202
+ // missing or an edge function was cold. Only the deadline ends this loop.
203
+ //
204
+ // The `start` call above is the opposite case and stays fatal: nothing has been
205
+ // shown to anyone yet, and an unreachable gateway there is a configuration
206
+ // problem the operator needs told about immediately, not retried over.
207
+ // Bounded, because "survive a blip" and "hang for ten minutes" are not the same
208
+ // promise. A gateway that is genuinely down would otherwise leave the operator
209
+ // watching "Still waiting…" until the 600s code expiry, which reads as a frozen
210
+ // command. Ninety seconds of continuous failure is long enough to ride out a
211
+ // cold start or a reconnecting VPN and short enough to still feel like an answer.
212
+ const TRANSPORT_GRACE_MS = 90_000;
213
+ let transportFailures = 0;
214
+ let failingSince = 0;
215
+ while (now() < deadline) {
216
+ await sleep(waitMs);
217
+ let res;
218
+ try {
219
+ res = await postJson(`${origin}/api/auth/device/token`, { device_code: deviceCode }, { fetchImpl });
220
+ } catch {
221
+ // Back off like a slow_down, and say so once rather than every second — a
222
+ // wall of identical warnings buries the code the operator still needs.
223
+ transportFailures += 1;
224
+ if (transportFailures === 1) {
225
+ failingSince = now();
226
+ warn("Lost contact with the gateway. Still waiting…");
227
+ }
228
+ if (now() - failingSince > TRANSPORT_GRACE_MS) {
229
+ throw new Error(
230
+ `Lost contact with ${origin} and could not get it back. ` +
231
+ "Check the gateway is up, then run `passcontrol login` again."
232
+ );
233
+ }
234
+ waitMs = Math.min(waitMs * 2, 10_000);
235
+ continue;
236
+ }
237
+ if (transportFailures > 0) {
238
+ ok("reconnected");
239
+ transportFailures = 0;
240
+ failingSince = 0;
241
+ waitMs = Math.max(500, interval * 1000);
242
+ }
243
+ if (res.status === 200 && res.body?.api_key) return res.body;
244
+ const error = res.body?.error;
245
+ if (error === "access_denied") {
246
+ throw new Error("Login was denied in the browser. Nothing was created.");
247
+ }
248
+ if (error === "expired_token") {
249
+ throw new Error("That login expired before it was approved. Run `passcontrol login` again.");
250
+ }
251
+ // slow_down is the server asking for room; anything else unexpected gets the
252
+ // same treatment rather than a tight retry loop against an unhealthy host.
253
+ if (error === "slow_down" || res.status >= 500) waitMs = Math.min(waitMs * 2, 10_000);
254
+ }
255
+ throw new Error("Timed out waiting for approval. Run `passcontrol login` again.");
256
+ }
257
+
258
+ /** Authenticated control-plane call, using the key this flow just collected. */
259
+ async function control(origin, apiKey, method, path, body, fetchImpl = fetch) {
260
+ const res = await fetchImpl(`${origin}/api/control/v1${path}`, {
261
+ method,
262
+ headers: {
263
+ authorization: `Bearer ${apiKey}`,
264
+ ...(body ? { "content-type": "application/json" } : {}),
265
+ },
266
+ ...(body ? { body: JSON.stringify(body) } : {}),
267
+ });
268
+ const parsed = await res.json().catch(() => null);
269
+ if (!res.ok) {
270
+ throw new Error(`Control plane refused ${method} ${path} (${res.status}).`);
271
+ }
272
+ return parsed;
273
+ }
274
+
275
+ /**
276
+ * Warn when the file we are about to write will NOT be the one that wins.
277
+ *
278
+ * `cli/config.mjs` resolves env → nearest project `.passcontrol` → global. A
279
+ * user with a project config in cwd would otherwise see "✓ Wrote
280
+ * ~/.config/passcontrol/config" and then watch `passcontrol call` keep using the
281
+ * old passport — right result, wrong file wins, and nothing visibly broken.
282
+ */
283
+ function warnIfShadowed(target, { cwd = process.cwd() } = {}) {
284
+ if (target !== globalConfigPath()) return false;
285
+ const project = findProjectConfig(cwd);
286
+ if (!project) return false;
287
+ warn(`A project config at ${project} takes priority over the file just written.`);
288
+ step("Commands run from this directory will keep using it. Use --project to write there instead.");
289
+ return true;
290
+ }
291
+
292
+ /**
293
+ * Refuse to destroy a working passport without being told to.
294
+ *
295
+ * `mergeConfigFile` preserves PROVIDER and MODEL, but it necessarily REPLACES
296
+ * PASSPORT_ID and PASSPORT_SECRET — and PassControl has never held a copy of
297
+ * that private key, so overwriting it is unrecoverable. `init` has always asked
298
+ * before clobbering a config; a command designed to be run casually must ask at
299
+ * least as loudly.
300
+ *
301
+ * Defaults to NO. The safe answer is the one you get by pressing enter, because
302
+ * the cost of a stray yes here is an agent that silently stops authenticating on
303
+ * every other machine that shared the passport.
304
+ */
305
+ async function confirmReplacingPassport(target, confirm) {
306
+ let existing = "";
307
+ try {
308
+ existing = fs.readFileSync(target, "utf8");
309
+ } catch {
310
+ return true; // Nothing there. Nothing to lose.
311
+ }
312
+ const current = /^PASSPORT_SECRET=(.+)$/mu.exec(existing)?.[1]?.trim();
313
+ if (!current) return true;
314
+
315
+ warn(`${target} already holds a passport secret.`);
316
+ step("Continuing replaces it, and PassControl has no copy — anything still using that");
317
+ step("passport keeps working only until you revoke or rotate the agent behind it.");
318
+ return confirm("Replace it? [y/N] ", { default: false });
319
+ }
320
+
321
+ /**
322
+ * Resolve login's destination without inheriting the ordinary localhost fallback.
323
+ *
324
+ * An explicit flag wins, then an environment/config value, then Cloud. Other
325
+ * commands keep DEFAULT_GATEWAY because they may intentionally operate a local
326
+ * stack; login is the exception because it is designed to run before any config
327
+ * exists. requireControlGateway keeps the existing bare-origin and HTTPS rules.
328
+ */
329
+ export function resolveLoginGateway(opts = {}, env = process.env) {
330
+ const fromFlag = typeof opts.gateway === "string" ? opts.gateway.trim() : "";
331
+ const fromConfig = typeof env.PASSCONTROL_GATEWAY === "string"
332
+ ? env.PASSCONTROL_GATEWAY.trim()
333
+ : "";
334
+ return requireControlGateway({ gateway: fromFlag || fromConfig || CLOUD_GATEWAY });
335
+ }
336
+
337
+ export async function loginCommand(opts = {}, deps = {}) {
338
+ const fetchImpl = deps.fetch ?? fetch;
339
+ const openUrl = deps.openUrl ?? (() => {});
340
+ const confirm = deps.confirmYes ?? (async (_q, o = {}) => o.default !== false);
341
+ const promptLine = deps.promptLine ?? (async (_q, fallback) => fallback);
342
+
343
+ // Validate the destination BEFORE anything is requested — the ordering mintVisa
344
+ // uses. A rejected gateway must cost zero sockets.
345
+ const origin = resolveLoginGateway(opts);
346
+
347
+ const clientName = String(opts.name || os.hostname() || "this machine");
348
+ let started;
349
+ try {
350
+ started = await postJson(
351
+ `${origin}/api/auth/device/start`,
352
+ { client_name: clientName },
353
+ { fetchImpl }
354
+ );
355
+ } catch (error) {
356
+ // postJson has already named the host and kept the underlying failure on
357
+ // `cause`. This adds the part a first-run operator actually needs: what to do
358
+ // about it. Read `cause`, not `error.name` — the error reaching here is
359
+ // postJson's plain wrapper, so testing `error.name` for "AbortError" would
360
+ // never be true and the timeout wording would be dead code.
361
+ const underlying = error?.cause ?? error;
362
+ const reason = underlying?.name === "AbortError" ? "timed out" : "could not be reached";
363
+ throw new Error(
364
+ `${origin} ${reason} (${underlying?.message ?? "unknown"}).\n` +
365
+ ` • Self-hosting? Start your stack, or pass --gateway <origin>.\n` +
366
+ ` • Meant to use Cloud? Unset PASSCONTROL_GATEWAY, or pass --gateway ${CLOUD_GATEWAY}.`,
367
+ { cause: error }
368
+ );
369
+ }
370
+ if (started.status !== 200 || !started.body?.user_code) {
371
+ throw new Error(
372
+ `${origin} answered ${started.status} to the login request. ` +
373
+ `If that origin is a PassControl instance, it may be older than this CLI.`
374
+ );
375
+ }
376
+ const { device_code: deviceCode, user_code: userCode } = started.body;
377
+ const verificationUri = approvalUrl(origin, started.body.verification_uri, {
378
+ onMismatch: () => warn("The gateway offered a different approval URL. Using the configured origin."),
379
+ });
380
+
381
+ // Print FIRST and unconditionally. Only the suffix depends on the clipboard —
382
+ // a headless box that says "copied to your clipboard" with nothing to paste is
383
+ // worse than one that never mentioned a clipboard at all.
384
+ const copied = await copyToClipboard(userCode);
385
+ console.log("");
386
+ console.log(heading("Approve this machine"));
387
+ console.log(` Code: ${formatCode(userCode)}${copied ? " (copied to your clipboard)" : ""}`);
388
+ console.log(` Open: ${verificationUri}`);
389
+ console.log("");
390
+ step("Paste the code there and press Approve. Waiting…");
391
+ openUrl(verificationUri);
392
+
393
+ const grant = await pollForGrant(origin, deviceCode, {
394
+ interval: Number(started.body.interval ?? 1),
395
+ expiresIn: Number(started.body.expires_in ?? 600),
396
+ fetchImpl,
397
+ });
398
+ ok("approved");
399
+
400
+ // ── Provision a passport for this machine ─────────────────────────────────
401
+ //
402
+ // The keypair is generated HERE and only the PUBLIC half is sent. The gateway
403
+ // has never held a passport private key; this command must not be the first
404
+ // thing to change that.
405
+ const agents = (await control(origin, grant.api_key, "GET", "/agents", null, fetchImpl))?.agents ?? [];
406
+ let agentId = null;
407
+ if (agents.length > 0 && !opts.new) {
408
+ step(`This workspace has ${agents.length} agent(s).`);
409
+ const existing = await promptLine("Agent id to reuse, or blank to create a new one: ", "");
410
+ if (existing) {
411
+ // Reusing means ROTATING, and rotation is not free — say so before doing it.
412
+ warn(`PassControl has never held that agent's private key, so this machine cannot be given`);
413
+ step(`the existing one. Continuing rotates it: any other machine using that passport stops`);
414
+ step(`working once the grace window lapses.`);
415
+ if (await confirm("Create a NEW agent for this machine instead? [Y/n] ")) agentId = null;
416
+ else agentId = existing;
417
+ }
418
+ }
419
+
420
+ const priv = ed25519.utils.randomPrivateKey();
421
+ const passportId = b64url(ed25519.getPublicKey(priv));
422
+ const passportSecret = b64url(priv);
423
+
424
+ if (agentId) {
425
+ await control(origin, grant.api_key, "POST", `/agents/${encodeURIComponent(agentId)}/rotate`, {
426
+ passportPubkey: passportId,
427
+ }, fetchImpl);
428
+ ok(`rotated passport for agent ${agentId}`);
429
+ } else {
430
+ const created = await control(origin, grant.api_key, "POST", "/agents", {
431
+ name: clientName,
432
+ passportPubkey: passportId,
433
+ scopes: [{ provider: "anthropic", models: ["claude-*"] }],
434
+ }, fetchImpl);
435
+ agentId = created?.id ?? null;
436
+ ok(`created agent ${created?.name ?? clientName}`);
437
+ }
438
+
439
+ // MERGE, never a full write. writeConfigFile emits every CONFIG_KEY, so a
440
+ // three-key write would blank PROVIDER, MODEL and PASSCONTROL_GATEWAY — right
441
+ // result, wrong side effect, invisible until the next call hit the wrong
442
+ // provider.
443
+ const target = opts.project ? `${process.cwd()}/.passcontrol` : globalConfigPath();
444
+ if (!(await confirmReplacingPassport(target, confirm))) {
445
+ // The agent and its key were already created server-side, so say what exists
446
+ // rather than pretending nothing happened. Leaving the operator with an
447
+ // orphaned agent AND no explanation would be the worse failure.
448
+ warn("Left the existing config unchanged.");
449
+ step(`The new passport was NOT saved. Agent ${agentId ?? "(unknown)"} and the key`);
450
+ step(`"CLI on ${clientName}" now exist unused — revoke them in Settings.`);
451
+ return { agentId, passportId, target: null };
452
+ }
453
+ mergeConfigFile(target, {
454
+ PASSCONTROL_GATEWAY: origin,
455
+ PASSPORT_ID: passportId,
456
+ PASSPORT_SECRET: passportSecret,
457
+ PASSCONTROL_API_KEY: grant.api_key,
458
+ });
459
+ ok(`wrote ${target}`);
460
+ warnIfShadowed(target);
461
+
462
+ step("");
463
+ step('Try it: passcontrol call "hi"');
464
+ step(`The key is listed in Settings as "CLI on ${clientName}" and can be revoked there.`);
465
+ return { agentId, passportId, target };
466
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "passcontrol",
3
- "version": "0.6.2",
3
+ "version": "0.7.1",
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",