passcontrol 0.7.2 → 0.9.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.
- package/README.md +95 -61
- package/bin/passcontrol.mjs +745 -154
- package/cli/config.mjs +71 -9
- package/cli/gateway-wait.mjs +79 -0
- package/cli/login.mjs +55 -7
- package/cli/logout.mjs +243 -0
- package/cli/mcp/gateway.mjs +2 -0
- package/cli/menu-session.mjs +64 -0
- package/cli/menu.mjs +733 -0
- package/cli/passport-key-store.mjs +413 -0
- package/cli/protocols.d.mts +3 -0
- package/cli/protocols.mjs +23 -0
- package/cli/selftest.mjs +191 -0
- package/cli/sidecar.mjs +4 -0
- package/cli/verify.mjs +78 -3
- package/cli/visa-client.mjs +30 -2
- package/package.json +1 -1
- package/sdk/README.md +2 -1
- package/sdk/control.d.ts +38 -0
- package/sdk/control.js +32 -0
- package/sdk/index.d.ts +2 -2
- package/sdk/index.js +1 -1
- package/sdk/verify.d.ts +90 -1
- package/sdk/verify.js +83 -5
package/cli/config.mjs
CHANGED
|
@@ -3,6 +3,11 @@ import os from "node:os";
|
|
|
3
3
|
import path from "node:path";
|
|
4
4
|
import { fileURLToPath } from "node:url";
|
|
5
5
|
import { WORKSPACE_EXPORT_PROTOCOL } from "./protocols.mjs";
|
|
6
|
+
import {
|
|
7
|
+
createPassportCredentialStore,
|
|
8
|
+
keyStorageDeclaration,
|
|
9
|
+
resolvePassportKey,
|
|
10
|
+
} from "./passport-key-store.mjs";
|
|
6
11
|
|
|
7
12
|
export const CONFIG_FILE = ".passcontrol";
|
|
8
13
|
|
|
@@ -45,6 +50,7 @@ const CONFIG_KEYS = [
|
|
|
45
50
|
"PASSCONTROL_GATEWAY",
|
|
46
51
|
"PASSPORT_ID",
|
|
47
52
|
"PASSPORT_SECRET",
|
|
53
|
+
"PASSPORT_KEY_STORAGE",
|
|
48
54
|
"PASSCONTROL_API_KEY",
|
|
49
55
|
"PROVIDER",
|
|
50
56
|
"MODEL",
|
|
@@ -58,6 +64,12 @@ const ANSI = {
|
|
|
58
64
|
red: "\x1b[31m",
|
|
59
65
|
yellow: "\x1b[33m",
|
|
60
66
|
heading: "\x1b[1;32m",
|
|
67
|
+
// Two more, for the settings browser's header. Both stay inside the 16-colour
|
|
68
|
+
// set on purpose: nothing in this CLI emits 38;5; or 38;2;, and a lone file
|
|
69
|
+
// that did would look wrong beside the rest and can disappear entirely on a
|
|
70
|
+
// terminal that has not been told its palette.
|
|
71
|
+
lime: "\x1b[92m", // bright green — the focus and healthy colour
|
|
72
|
+
faint: "\x1b[90m", // bright black — a second dim level below \x1b[2m
|
|
61
73
|
};
|
|
62
74
|
|
|
63
75
|
function paint(code, value) {
|
|
@@ -218,10 +230,34 @@ export function resolvedConfig() {
|
|
|
218
230
|
|
|
219
231
|
function currentConfig() {
|
|
220
232
|
const provider = process.env.PROVIDER ?? DEFAULT_PROVIDER;
|
|
233
|
+
const passportId = process.env.PASSPORT_ID ?? "";
|
|
234
|
+
const fileSecret = process.env.PASSPORT_SECRET ?? "";
|
|
235
|
+
const passportStorageMarker = process.env.PASSPORT_KEY_STORAGE ?? "";
|
|
236
|
+
const fileLabel = operatorEnv("PASSPORT_SECRET") !== undefined
|
|
237
|
+
? "environment variable"
|
|
238
|
+
: configPathLabel(configSources);
|
|
239
|
+
let passport = null;
|
|
240
|
+
const resolvedPassport = () => {
|
|
241
|
+
passport ??= resolvePassportKey({
|
|
242
|
+
passportId,
|
|
243
|
+
fileSecret,
|
|
244
|
+
fileLabel,
|
|
245
|
+
preferFileSecret: fileLabel === "environment variable" && Boolean(fileSecret),
|
|
246
|
+
storageMarker: passportStorageMarker,
|
|
247
|
+
store: createPassportCredentialStore(),
|
|
248
|
+
});
|
|
249
|
+
return passport;
|
|
250
|
+
};
|
|
221
251
|
return {
|
|
222
252
|
gateway: trimSlash(process.env.PASSCONTROL_GATEWAY ?? DEFAULT_GATEWAY),
|
|
223
|
-
passportId
|
|
224
|
-
passportSecret
|
|
253
|
+
passportId,
|
|
254
|
+
get passportSecret() {
|
|
255
|
+
return resolvedPassport().secret;
|
|
256
|
+
},
|
|
257
|
+
get passportStorage() {
|
|
258
|
+
return resolvedPassport().storage;
|
|
259
|
+
},
|
|
260
|
+
passportStorageMarker,
|
|
225
261
|
apiKey: process.env.PASSCONTROL_API_KEY ?? "",
|
|
226
262
|
provider,
|
|
227
263
|
model: resolveModel(provider),
|
|
@@ -240,10 +276,11 @@ export function configPathLabel(sources = configSources) {
|
|
|
240
276
|
}
|
|
241
277
|
|
|
242
278
|
/**
|
|
243
|
-
* Write the whole config. Every CONFIG_KEY is emitted, so a key absent
|
|
244
|
-
* `values` is BLANKED — that is correct for `init`, which collects all of
|
|
245
|
-
* and wrong for any caller that means to change a subset.
|
|
246
|
-
*
|
|
279
|
+
* Write the whole config. Every ordinary CONFIG_KEY is emitted, so a key absent
|
|
280
|
+
* from `values` is BLANKED — that is correct for `init`, which collects all of
|
|
281
|
+
* them, and wrong for any caller that means to change a subset. The one
|
|
282
|
+
* exception is an unset PASSPORT_KEY_STORAGE marker: omitting it keeps a Tier 0
|
|
283
|
+
* file byte-for-byte in the old shape. Use mergeConfigFile for partial changes.
|
|
247
284
|
*
|
|
248
285
|
* The chmod is not redundant with the `mode` option. Node applies `mode` only
|
|
249
286
|
* when it CREATES the file, so overwriting a config that already exists as 0644
|
|
@@ -262,6 +299,7 @@ export function writeConfigFile(file, values) {
|
|
|
262
299
|
"",
|
|
263
300
|
];
|
|
264
301
|
for (const key of CONFIG_KEYS) {
|
|
302
|
+
if (key === "PASSPORT_KEY_STORAGE" && !values[key]) continue;
|
|
265
303
|
lines.push(`${key}=${values[key] ?? ""}`);
|
|
266
304
|
}
|
|
267
305
|
fs.writeFileSync(file, `${lines.join("\n")}\n`, { mode: 0o600 });
|
|
@@ -298,6 +336,19 @@ export function heading(message = "") {
|
|
|
298
336
|
return paint(ANSI.heading, message);
|
|
299
337
|
}
|
|
300
338
|
|
|
339
|
+
/**
|
|
340
|
+
* Colour helpers for callers that lay out their own columns.
|
|
341
|
+
*
|
|
342
|
+
* `formatLabel` above owns the label/value shape used by every report. The
|
|
343
|
+
* settings browser's header is a glyph table instead, so it paints its own
|
|
344
|
+
* cells — but it must do so through the same `paint`, which is what keeps
|
|
345
|
+
* NO_COLOR, CI and a piped stdout honoured in one place.
|
|
346
|
+
*/
|
|
347
|
+
export const accent = (value) => paint(ANSI.lime, value);
|
|
348
|
+
export const muted = (value) => paint(ANSI.faint, value);
|
|
349
|
+
export const amber = (value) => paint(ANSI.yellow, value);
|
|
350
|
+
export const alarm = (value) => paint(ANSI.red, value);
|
|
351
|
+
|
|
301
352
|
export function formatLabel(label, value, width = 11) {
|
|
302
353
|
return `${paint(ANSI.cyan, `${label}:`.padEnd(width))}${value}`;
|
|
303
354
|
}
|
|
@@ -327,12 +378,23 @@ export function die(message) {
|
|
|
327
378
|
|
|
328
379
|
export function requirePassport(current = config) {
|
|
329
380
|
assertConfigLoaded();
|
|
330
|
-
|
|
381
|
+
const passportSecret = current.passportSecret;
|
|
382
|
+
const storage = current.passportStorage;
|
|
383
|
+
if (!current.passportId || !passportSecret) {
|
|
331
384
|
die(
|
|
332
|
-
|
|
385
|
+
storage?.tier === 1 && storage?.available === false
|
|
386
|
+
? `No passport key available. ${storage.message}.`
|
|
387
|
+
: "No passport configured. Run `passcontrol init`, copy .passcontrol.example to .passcontrol, or pass PASSPORT_ID/PASSPORT_SECRET as env."
|
|
333
388
|
);
|
|
334
389
|
}
|
|
335
|
-
|
|
390
|
+
if (storage?.fallback) warn(`Key storage fallback: ${storage.message}.`);
|
|
391
|
+
// Handed out beside the secret so every minting caller declares the tier it
|
|
392
|
+
// actually read from, without any of them deriving it a second time.
|
|
393
|
+
return {
|
|
394
|
+
passportId: current.passportId,
|
|
395
|
+
passportSecret,
|
|
396
|
+
keyStorage: keyStorageDeclaration(storage),
|
|
397
|
+
};
|
|
336
398
|
}
|
|
337
399
|
|
|
338
400
|
export function requireControlApiKey(current = config) {
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
// How long to wait for a freshly started local dashboard to answer.
|
|
2
|
+
//
|
|
3
|
+
// This was a flat 30-second budget inside bin/passcontrol.mjs, and it was wrong
|
|
4
|
+
// in the way that matters most: a cold Next.js first compile of this app takes
|
|
5
|
+
// roughly 30 seconds, so the budget expired just as the dashboard was about to
|
|
6
|
+
// come up. `passcontrol setup` then printed "Dashboard did not become ready"
|
|
7
|
+
// against a stack that was working perfectly — the first thing a new
|
|
8
|
+
// self-hoster ever sees from this tool, telling them their install failed.
|
|
9
|
+
//
|
|
10
|
+
// Raising the flat number is the obvious fix and it is a bad one: a genuinely
|
|
11
|
+
// dead start would then sit there for two minutes before admitting it. Slower
|
|
12
|
+
// failure in exchange for fewer false failures is not a trade worth making on a
|
|
13
|
+
// first run, where the user has no idea which of the two they are looking at.
|
|
14
|
+
//
|
|
15
|
+
// So the budget is conditional on evidence, and the three cases are distinct:
|
|
16
|
+
//
|
|
17
|
+
// the supervising process has exited → stop now. It is not coming back, and
|
|
18
|
+
// the log has the reason.
|
|
19
|
+
// the port is listening → the server is up and is compiling.
|
|
20
|
+
// That is slow exactly once, on the
|
|
21
|
+
// first run. Extend, and SAY so.
|
|
22
|
+
// neither → nothing has happened yet. Keep the
|
|
23
|
+
// original short budget so a broken
|
|
24
|
+
// start is still reported quickly.
|
|
25
|
+
//
|
|
26
|
+
// Every probe is a parameter rather than an import: this file makes a decision
|
|
27
|
+
// about time, and a decision about time that can only be tested by waiting is a
|
|
28
|
+
// decision that does not get tested. See cli/__tests__/gateway-wait.test.mjs,
|
|
29
|
+
// which exercises the full 150-second path against a fake clock in no time.
|
|
30
|
+
|
|
31
|
+
const POLL_MS = 250;
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* @param {object} opts
|
|
35
|
+
* @param {() => Promise<boolean>} opts.probeGateway does the gateway answer?
|
|
36
|
+
* @param {() => Promise<boolean>} [opts.probePort] is anything listening on the port?
|
|
37
|
+
* @param {() => boolean} [opts.processAlive] is the dashboard process still up?
|
|
38
|
+
* @param {() => void} [opts.onCompiling] called once, when the wait extends
|
|
39
|
+
* @param {number} [opts.timeoutMs] budget with no sign of life
|
|
40
|
+
* @param {number} [opts.compilingMs] budget once the port is listening
|
|
41
|
+
* @param {() => number} [opts.now]
|
|
42
|
+
* @param {(ms: number) => Promise<void>} [opts.pause]
|
|
43
|
+
* @returns {Promise<boolean>} true if the gateway answered before the budget ran out
|
|
44
|
+
*/
|
|
45
|
+
export async function waitForGateway({
|
|
46
|
+
probeGateway,
|
|
47
|
+
probePort = null,
|
|
48
|
+
processAlive = null,
|
|
49
|
+
onCompiling = null,
|
|
50
|
+
timeoutMs = 30_000,
|
|
51
|
+
compilingMs = 150_000,
|
|
52
|
+
now = () => Date.now(),
|
|
53
|
+
pause = (ms) => new Promise((r) => setTimeout(r, ms)),
|
|
54
|
+
} = {}) {
|
|
55
|
+
const started = now();
|
|
56
|
+
let deadline = started + timeoutMs;
|
|
57
|
+
let announced = false;
|
|
58
|
+
|
|
59
|
+
while (now() < deadline) {
|
|
60
|
+
if (await probeGateway()) return true;
|
|
61
|
+
|
|
62
|
+
// Checked AFTER the gateway probe, never before: a process that exits the
|
|
63
|
+
// instant it finishes handing off would otherwise be declared dead on the
|
|
64
|
+
// same tick it became ready, which is the flaky-test version of this bug.
|
|
65
|
+
if (processAlive && !processAlive()) return false;
|
|
66
|
+
|
|
67
|
+
if (probePort && await probePort()) {
|
|
68
|
+
deadline = Math.max(deadline, started + compilingMs);
|
|
69
|
+
if (!announced) {
|
|
70
|
+
announced = true;
|
|
71
|
+
onCompiling?.();
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
await pause(POLL_MS);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
return false;
|
|
79
|
+
}
|
package/cli/login.mjs
CHANGED
|
@@ -51,6 +51,7 @@ import {
|
|
|
51
51
|
step,
|
|
52
52
|
warn,
|
|
53
53
|
} from "./config.mjs";
|
|
54
|
+
import { proveItWorks } from "./selftest.mjs";
|
|
54
55
|
|
|
55
56
|
export { CLOUD_GATEWAY };
|
|
56
57
|
|
|
@@ -194,7 +195,17 @@ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
|
194
195
|
* Honours the server's `interval` and backs off on `slow_down`, so the poll rate
|
|
195
196
|
* is the server's decision and can be widened without shipping a new CLI.
|
|
196
197
|
*/
|
|
197
|
-
async function pollForGrant(
|
|
198
|
+
async function pollForGrant(
|
|
199
|
+
origin,
|
|
200
|
+
deviceCode,
|
|
201
|
+
// `now` and `wait` are a matched pair, and injecting only one is worse than
|
|
202
|
+
// injecting neither: a fake clock with a real sleep still burns wall time,
|
|
203
|
+
// and a real clock with a fake sleep spins the loop against a deadline that
|
|
204
|
+
// never moves. TRANSPORT_GRACE_MS below is ninety REAL seconds, so a test
|
|
205
|
+
// that drives the give-up path without both of these sleeps through all
|
|
206
|
+
// ninety of them — which is exactly what this file used to do.
|
|
207
|
+
{ interval, expiresIn, fetchImpl, now = Date.now, wait = sleep }
|
|
208
|
+
) {
|
|
198
209
|
const deadline = now() + expiresIn * 1000;
|
|
199
210
|
let waitMs = Math.max(500, interval * 1000);
|
|
200
211
|
// A transport failure is NOT fatal here, and this is the one place in the flow
|
|
@@ -215,7 +226,7 @@ async function pollForGrant(origin, deviceCode, { interval, expiresIn, fetchImpl
|
|
|
215
226
|
let transportFailures = 0;
|
|
216
227
|
let failingSince = 0;
|
|
217
228
|
while (now() < deadline) {
|
|
218
|
-
await
|
|
229
|
+
await wait(waitMs);
|
|
219
230
|
let res;
|
|
220
231
|
try {
|
|
221
232
|
res = await postJson(`${origin}/api/auth/device/token`, { device_code: deviceCode }, { fetchImpl });
|
|
@@ -271,7 +282,13 @@ async function control(origin, apiKey, method, path, body, fetchImpl = fetch) {
|
|
|
271
282
|
if (!res.ok) {
|
|
272
283
|
throw new Error(`Control plane refused ${method} ${path} (${res.status}).`);
|
|
273
284
|
}
|
|
274
|
-
|
|
285
|
+
// Every control route answers `{ data: ... }` (lib/control/respond.ts), and
|
|
286
|
+
// bin/passcontrol.mjs's own `api()` has always unwrapped it. This helper did
|
|
287
|
+
// not, and the callers below then reached for `.agents` and `.id` one level
|
|
288
|
+
// too high — so the agent list was permanently empty and a created agent's id
|
|
289
|
+
// was permanently undefined. Unwrapped HERE rather than at each call site, so
|
|
290
|
+
// the next route this file consumes cannot reintroduce it.
|
|
291
|
+
return parsed && typeof parsed === "object" && "data" in parsed ? parsed.data : parsed;
|
|
275
292
|
}
|
|
276
293
|
|
|
277
294
|
/**
|
|
@@ -377,6 +394,12 @@ export async function loginCommand(opts = {}, deps = {}) {
|
|
|
377
394
|
const openUrl = deps.openUrl ?? (() => {});
|
|
378
395
|
const confirm = deps.confirmYes ?? (async (_q, o = {}) => o.default !== false);
|
|
379
396
|
const promptLine = deps.promptLine ?? (async (_q, fallback) => fallback);
|
|
397
|
+
// Only the poll loop reads these, and only a test passes them. Kept on `deps`
|
|
398
|
+
// beside `fetch` rather than on `opts`, because they are seams for the caller,
|
|
399
|
+
// not options for the operator — there is no flag that makes login lie about
|
|
400
|
+
// the time.
|
|
401
|
+
const now = deps.now ?? Date.now;
|
|
402
|
+
const wait = deps.sleep ?? sleep;
|
|
380
403
|
|
|
381
404
|
// Validate the destination BEFORE anything is requested — the ordering mintVisa
|
|
382
405
|
// uses. A rejected gateway must cost zero sockets.
|
|
@@ -446,6 +469,8 @@ export async function loginCommand(opts = {}, deps = {}) {
|
|
|
446
469
|
interval: Number(started.body.interval ?? 1),
|
|
447
470
|
expiresIn: Number(started.body.expires_in ?? 600),
|
|
448
471
|
fetchImpl,
|
|
472
|
+
now,
|
|
473
|
+
wait,
|
|
449
474
|
});
|
|
450
475
|
ok("approved");
|
|
451
476
|
|
|
@@ -454,7 +479,7 @@ export async function loginCommand(opts = {}, deps = {}) {
|
|
|
454
479
|
// The keypair is generated HERE and only the PUBLIC half is sent. The gateway
|
|
455
480
|
// has never held a passport private key; this command must not be the first
|
|
456
481
|
// thing to change that.
|
|
457
|
-
const agents = (await control(origin, grant.api_key, "GET", "/agents", null, fetchImpl))
|
|
482
|
+
const agents = (await control(origin, grant.api_key, "GET", "/agents", null, fetchImpl)) ?? [];
|
|
458
483
|
let agentId = null;
|
|
459
484
|
if (agents.length > 0 && !opts.new) {
|
|
460
485
|
step(`This workspace has ${agents.length} agent(s).`);
|
|
@@ -482,7 +507,17 @@ export async function loginCommand(opts = {}, deps = {}) {
|
|
|
482
507
|
const created = await control(origin, grant.api_key, "POST", "/agents", {
|
|
483
508
|
name: clientName,
|
|
484
509
|
passportPubkey: passportId,
|
|
485
|
-
|
|
510
|
+
// The demo scope is what makes `proveItWorks` below possible, and it is
|
|
511
|
+
// here rather than added-then-removed for one reason: a brand-new tenant
|
|
512
|
+
// has NO provider key in Vault, so the keyless demo provider is the only
|
|
513
|
+
// call this agent can legally make on its first day. It reaches a
|
|
514
|
+
// synthesized response, never `get_provider_key`, and never forwards
|
|
515
|
+
// anywhere — so it grants no spend and no upstream reach. It also leaves
|
|
516
|
+
// every agent able to self-test forever, which `doctor` can lean on.
|
|
517
|
+
scopes: [
|
|
518
|
+
{ provider: "demo", models: ["*"] },
|
|
519
|
+
{ provider: "anthropic", models: ["claude-*"] },
|
|
520
|
+
],
|
|
486
521
|
}, fetchImpl);
|
|
487
522
|
agentId = created?.id ?? null;
|
|
488
523
|
ok(`created agent ${created?.name ?? clientName}`);
|
|
@@ -506,13 +541,26 @@ export async function loginCommand(opts = {}, deps = {}) {
|
|
|
506
541
|
PASSCONTROL_GATEWAY: origin,
|
|
507
542
|
PASSPORT_ID: passportId,
|
|
508
543
|
PASSPORT_SECRET: passportSecret,
|
|
544
|
+
PASSPORT_KEY_STORAGE: "",
|
|
509
545
|
PASSCONTROL_API_KEY: grant.api_key,
|
|
510
546
|
});
|
|
511
547
|
ok(`wrote ${target}`);
|
|
512
548
|
warnIfShadowed(target);
|
|
513
549
|
|
|
514
550
|
step("");
|
|
515
|
-
|
|
551
|
+
const proof = await proveItWorks({
|
|
552
|
+
origin,
|
|
553
|
+
passportId,
|
|
554
|
+
passportSecret,
|
|
555
|
+
apiKey: grant.api_key,
|
|
556
|
+
fetchImpl,
|
|
557
|
+
// The receipt read waits out the gateway's background write. Injected from
|
|
558
|
+
// the same seam the poll loop uses, so a test drives the retry without
|
|
559
|
+
// burning wall time.
|
|
560
|
+
wait,
|
|
561
|
+
});
|
|
562
|
+
|
|
563
|
+
step("");
|
|
516
564
|
step(`The key is listed in Settings as "CLI on ${clientName}" and can be revoked there.`);
|
|
517
|
-
return { agentId, passportId, target };
|
|
565
|
+
return { agentId, passportId, target, proof };
|
|
518
566
|
}
|
package/cli/logout.mjs
ADDED
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
// `passcontrol logout` — undo a login, on both sides.
|
|
2
|
+
//
|
|
3
|
+
// Until now there was no way to undo `passcontrol login`, and no CLI path to
|
|
4
|
+
// revoke a control key at all: `revokeApiKey` is a dashboard action. The manual
|
|
5
|
+
// equivalent was two halves nobody remembers as a pair — revoke the key in
|
|
6
|
+
// Settings AND delete the config — and doing one without the other leaves either
|
|
7
|
+
// a live write-scoped key on the tenant (create/suspend/revoke agents, rotate
|
|
8
|
+
// passports, arm the kill switch) or a passport private key sitting on disk.
|
|
9
|
+
//
|
|
10
|
+
// ── The ordering here is policy ─────────────────────────────────────────────
|
|
11
|
+
//
|
|
12
|
+
// resolve → look up the agent → decide about the agent → revoke the agent →
|
|
13
|
+
// revoke the control key → blank the file.
|
|
14
|
+
//
|
|
15
|
+
// The control key is revoked LAST because it is the credential doing all of the
|
|
16
|
+
// work above; revoking it first turns every remaining step into a 401. The file
|
|
17
|
+
// is blanked last of all, and — this is the part worth stating — it is blanked
|
|
18
|
+
// EVEN IF the server steps failed. The operator asked to log out. Deciding on
|
|
19
|
+
// their behalf that a live key elsewhere is a reason to leave a private key on
|
|
20
|
+
// their disk gets the trade backwards; the honest response is to clear the
|
|
21
|
+
// machine and say plainly that the key is still live.
|
|
22
|
+
import fs from "node:fs";
|
|
23
|
+
import path from "node:path";
|
|
24
|
+
import {
|
|
25
|
+
PASSPORT_KEY_STORAGE_OS,
|
|
26
|
+
createPassportCredentialStore,
|
|
27
|
+
} from "./passport-key-store.mjs";
|
|
28
|
+
import {
|
|
29
|
+
CONFIG_FILE,
|
|
30
|
+
config,
|
|
31
|
+
configSources,
|
|
32
|
+
globalConfigPath,
|
|
33
|
+
mergeConfigFile,
|
|
34
|
+
ok,
|
|
35
|
+
requireControlGateway,
|
|
36
|
+
step,
|
|
37
|
+
warn,
|
|
38
|
+
} from "./config.mjs";
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* The file that ACTUALLY holds the passport, not the one login would have
|
|
42
|
+
* written today.
|
|
43
|
+
*
|
|
44
|
+
* Mirroring login's `--project ? cwd : global` choice would be the obvious
|
|
45
|
+
* implementation and the wrong one: a user who logged in with `--project` and
|
|
46
|
+
* then runs a bare `logout` would be told their machine was cleared while the
|
|
47
|
+
* project `.passcontrol` still authenticates. That is `warnIfShadowed`'s failure
|
|
48
|
+
* in reverse — right result, wrong file — and it is worse here, because the
|
|
49
|
+
* whole point of the command is that nothing is left behind.
|
|
50
|
+
*
|
|
51
|
+
* `configSources` is pushed global-then-project and merged in that order, so the
|
|
52
|
+
* LAST source defining the key is the one that wins at resolution time.
|
|
53
|
+
*/
|
|
54
|
+
export function credentialFile(opts = {}, { sources = configSources, cwd = process.cwd() } = {}) {
|
|
55
|
+
if (opts.project) return path.join(cwd, CONFIG_FILE);
|
|
56
|
+
if (opts.global) return globalConfigPath();
|
|
57
|
+
// A tier 1 machine holds its passport in the OS credential store, so its
|
|
58
|
+
// config file has an EMPTY PASSPORT_SECRET and a PASSPORT_KEY_STORAGE marker
|
|
59
|
+
// instead. Matching only on the secret makes `logout` answer "nothing to
|
|
60
|
+
// clear" on precisely the machines that still hold a key — the failure this
|
|
61
|
+
// function's own docblock exists to prevent, arriving through the other door.
|
|
62
|
+
const holder = [...sources]
|
|
63
|
+
.reverse()
|
|
64
|
+
.find((source) =>
|
|
65
|
+
String(source?.values?.PASSPORT_SECRET ?? "").trim() ||
|
|
66
|
+
String(source?.values?.PASSPORT_KEY_STORAGE ?? "").trim());
|
|
67
|
+
return holder?.path ?? null;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
async function control(origin, apiKey, method, route, fetchImpl) {
|
|
71
|
+
const res = await fetchImpl(`${origin}/api/control/v1${route}`, {
|
|
72
|
+
method,
|
|
73
|
+
headers: { authorization: `Bearer ${apiKey}` },
|
|
74
|
+
});
|
|
75
|
+
const parsed = await res.json().catch(() => null);
|
|
76
|
+
if (!res.ok) {
|
|
77
|
+
const error = new Error(`${method} ${route} answered ${res.status}`);
|
|
78
|
+
error.status = res.status;
|
|
79
|
+
error.code = parsed?.error ?? null;
|
|
80
|
+
throw error;
|
|
81
|
+
}
|
|
82
|
+
// `{ data: ... }` — see lib/control/respond.ts and the note in cli/login.mjs.
|
|
83
|
+
// Reading the envelope instead of the payload is why the first real run of
|
|
84
|
+
// this command could not name the agent it was logging out of.
|
|
85
|
+
return parsed && typeof parsed === "object" && "data" in parsed ? parsed.data : parsed;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export async function logoutCommand(opts = {}, deps = {}) {
|
|
89
|
+
const fetchImpl = deps.fetch ?? fetch;
|
|
90
|
+
const confirm = deps.confirmYes ?? (async (_q, o = {}) => o.default !== false);
|
|
91
|
+
const warnings = [];
|
|
92
|
+
|
|
93
|
+
const target = credentialFile(opts);
|
|
94
|
+
if (!target || !fs.existsSync(target)) {
|
|
95
|
+
step("No passport is configured on this machine, so there is nothing to clear.");
|
|
96
|
+
return { target: null, keyRevoked: false, agentRevoked: false, agent: null, warnings };
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// ── Ask before destroying the passport, BEFORE touching anything ─────────
|
|
100
|
+
//
|
|
101
|
+
// `login` and `logout` differ by ONE CHARACTER, and only one of them asks.
|
|
102
|
+
// That asymmetry is not theoretical: this guard exists because a `logout` run
|
|
103
|
+
// as a smoke test, against the real config rather than an isolated one,
|
|
104
|
+
// blanked a working Cloud passport in the time it took to press enter.
|
|
105
|
+
// PassControl has never held that private key, so nothing could give it back.
|
|
106
|
+
//
|
|
107
|
+
// It sits here — ahead of every server call — rather than beside the write it
|
|
108
|
+
// guards. Confirming later would mean a declined logout that had already
|
|
109
|
+
// revoked the control key and possibly the agent: a half state the operator
|
|
110
|
+
// never asked for and cannot easily read. Answering "no" to a destructive
|
|
111
|
+
// prompt should mean nothing happened, so nothing has yet.
|
|
112
|
+
if (!opts.yes) {
|
|
113
|
+
// Tier 1 moved the key OUT of this file, so matching only PASSPORT_SECRET
|
|
114
|
+
// would silently stop asking for exactly the passports that are hardest to
|
|
115
|
+
// lose — the migrated ones. The marker is the tier 1 tell, and it stands in
|
|
116
|
+
// for a secret this file no longer contains.
|
|
117
|
+
const contents = fs.readFileSync(target, "utf8");
|
|
118
|
+
const holdsPassport =
|
|
119
|
+
/^PASSPORT_SECRET=(.+)$/mu.exec(contents)?.[1]?.trim() ||
|
|
120
|
+
/^PASSPORT_KEY_STORAGE=(.+)$/mu.exec(contents)?.[1]?.trim();
|
|
121
|
+
if (holdsPassport) {
|
|
122
|
+
warn(`${target} holds a passport secret, and PassControl has no copy of it.`);
|
|
123
|
+
step("Clearing it is permanent — anything still using that passport keeps working, but");
|
|
124
|
+
step("this machine can never authenticate as it again.");
|
|
125
|
+
if (!(await confirm("Log out of this machine? [y/N] ", { default: false }))) {
|
|
126
|
+
step("Left everything as it was.");
|
|
127
|
+
return { target: null, keyRevoked: false, agentRevoked: false, agent: null, warnings, cancelled: true };
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
// Validated before any socket opens, the ordering every other command uses. A
|
|
133
|
+
// logout aimed at a rejected origin must cost zero requests.
|
|
134
|
+
const origin = config.apiKey ? requireControlGateway(config) : null;
|
|
135
|
+
const apiKey = config.apiKey;
|
|
136
|
+
|
|
137
|
+
// ── Which agent is this passport? ─────────────────────────────────────────
|
|
138
|
+
// The config holds a PUBLIC key, not an agent id, so the name has to be looked
|
|
139
|
+
// up — and it has to happen while the control key still works. Best effort: a
|
|
140
|
+
// failure here costs the operator a name, not their logout.
|
|
141
|
+
let agent = null;
|
|
142
|
+
if (origin && apiKey && config.passportId) {
|
|
143
|
+
try {
|
|
144
|
+
const listed = (await control(origin, apiKey, "GET", "/agents", fetchImpl)) ?? [];
|
|
145
|
+
agent = listed.find((row) => row?.passport_pubkey === config.passportId) ?? null;
|
|
146
|
+
} catch {
|
|
147
|
+
warnings.push("Could not list agents, so this could not name the agent behind the passport.");
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
// ── The agent itself ──────────────────────────────────────────────────────
|
|
152
|
+
// Default NO, and not out of timidity: clearing this file destroys the only
|
|
153
|
+
// copy of that agent's private key, but a copy may well exist in a project
|
|
154
|
+
// `.passcontrol`, a password manager, or a CI secret. Revoking on a hunch
|
|
155
|
+
// stops something the operator did not ask to stop.
|
|
156
|
+
let agentRevoked = false;
|
|
157
|
+
if (agent && !opts.keepAgent) {
|
|
158
|
+
const wanted =
|
|
159
|
+
opts.revokeAgent === true ||
|
|
160
|
+
(await confirm(
|
|
161
|
+
`Also revoke agent "${agent.name}"? It can never authenticate again. [y/N] `,
|
|
162
|
+
{ default: false }
|
|
163
|
+
));
|
|
164
|
+
if (wanted) {
|
|
165
|
+
try {
|
|
166
|
+
await control(origin, apiKey, "POST", `/agents/${encodeURIComponent(agent.id)}/revoke`, fetchImpl);
|
|
167
|
+
agentRevoked = true;
|
|
168
|
+
ok(`revoked agent ${agent.name}`);
|
|
169
|
+
} catch {
|
|
170
|
+
warnings.push(`Could not revoke agent "${agent.name}" — do it in the Control Tower.`);
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
// ── The control key ───────────────────────────────────────────────────────
|
|
176
|
+
// Self-revoke: the route takes no id and revokes whatever key authenticated,
|
|
177
|
+
// so this cannot reach another key even by accident.
|
|
178
|
+
let keyRevoked = false;
|
|
179
|
+
if (origin && apiKey) {
|
|
180
|
+
try {
|
|
181
|
+
await control(origin, apiKey, "POST", "/keys/self/revoke", fetchImpl);
|
|
182
|
+
keyRevoked = true;
|
|
183
|
+
ok("revoked this machine's control key");
|
|
184
|
+
} catch (error) {
|
|
185
|
+
// 409 `already_revoked` and 404 `not_found` both mean the key cannot be
|
|
186
|
+
// used again — the route conflates missing and revoked on purpose so that
|
|
187
|
+
// another tenant's id stays indistinguishable from absence. Reporting
|
|
188
|
+
// "STILL LIVE" for either would send the operator to Settings to revoke a
|
|
189
|
+
// key that is not there, and teach them to distrust the message on the one
|
|
190
|
+
// occasion it is true.
|
|
191
|
+
if (error?.status === 409 || error?.status === 404) {
|
|
192
|
+
keyRevoked = true;
|
|
193
|
+
ok("this machine's control key was already revoked");
|
|
194
|
+
} else {
|
|
195
|
+
warnings.push(
|
|
196
|
+
"Could not revoke the control key — it is STILL LIVE. Revoke it in Settings → API keys."
|
|
197
|
+
);
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
// ── The machine ───────────────────────────────────────────────────────────
|
|
203
|
+
// Blank, never delete, and never a full write: PROVIDER, MODEL and the gateway
|
|
204
|
+
// are not credentials and the operator did not ask to lose them. `mergeConfigFile`
|
|
205
|
+
// spreads over what is already there, and writeConfigFile emits `?? ""` for every
|
|
206
|
+
// key, so an empty string is the supported way to clear one.
|
|
207
|
+
// The OS store is cleared BEFORE the file, because the file holds the
|
|
208
|
+
// PASSPORT_ID that addresses the item; blanking first orphans a private key
|
|
209
|
+
// that nothing can then name. A failure here is reported rather than
|
|
210
|
+
// swallowed: "cleared the credentials" must not be printed over a key that is
|
|
211
|
+
// still sitting in the operator's Keychain.
|
|
212
|
+
let osKeyCleared = null;
|
|
213
|
+
if (config.passportStorageMarker === PASSPORT_KEY_STORAGE_OS && config.passportId) {
|
|
214
|
+
// Injectable for the same reason the fetch and confirm seams exist: a test
|
|
215
|
+
// must be able to assert this deletion without reaching into the developer's
|
|
216
|
+
// real Keychain. tests/passport-key-store-os.test.ts covers the real one.
|
|
217
|
+
const store = deps.credentialStore ?? createPassportCredentialStore();
|
|
218
|
+
osKeyCleared = store.delete(config.passportId);
|
|
219
|
+
if (osKeyCleared.ok) {
|
|
220
|
+
ok(`removed the passport key from the ${store.name}`);
|
|
221
|
+
} else {
|
|
222
|
+
warnings.push(
|
|
223
|
+
`The passport key is STILL in the ${store.name}. Remove it there before trusting this machine as logged out.`
|
|
224
|
+
);
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
mergeConfigFile(target, {
|
|
229
|
+
PASSPORT_ID: "",
|
|
230
|
+
PASSPORT_SECRET: "",
|
|
231
|
+
PASSPORT_KEY_STORAGE: "",
|
|
232
|
+
PASSCONTROL_API_KEY: "",
|
|
233
|
+
});
|
|
234
|
+
ok(`cleared the credentials in ${target}`);
|
|
235
|
+
|
|
236
|
+
for (const line of warnings) warn(line);
|
|
237
|
+
if (agent && !agentRevoked) {
|
|
238
|
+
step(`Agent "${agent.name}" is still listed, and this machine no longer holds its passport.`);
|
|
239
|
+
}
|
|
240
|
+
step("Log back in any time with `passcontrol login`.");
|
|
241
|
+
|
|
242
|
+
return { target, keyRevoked, agentRevoked, agent, warnings, osKeyCleared };
|
|
243
|
+
}
|
package/cli/mcp/gateway.mjs
CHANGED
|
@@ -103,6 +103,7 @@ export function createGatewayClient({
|
|
|
103
103
|
gateway,
|
|
104
104
|
passportId,
|
|
105
105
|
passportSecret,
|
|
106
|
+
keyStorage = null,
|
|
106
107
|
fetch: fetchImpl = globalThis.fetch,
|
|
107
108
|
now = () => Date.now(),
|
|
108
109
|
randomUUID = () => globalThis.crypto.randomUUID(),
|
|
@@ -115,6 +116,7 @@ export function createGatewayClient({
|
|
|
115
116
|
gateway: baseUrl,
|
|
116
117
|
passportId,
|
|
117
118
|
passportSecret,
|
|
119
|
+
keyStorage,
|
|
118
120
|
fetch: fetchImpl,
|
|
119
121
|
now,
|
|
120
122
|
randomUUID,
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
export const MENU_STATUS_TIMEOUT_MS = 1200;
|
|
2
|
+
|
|
3
|
+
export async function collectMenuRemoteStatus({
|
|
4
|
+
hasApiKey,
|
|
5
|
+
gatewayStatus,
|
|
6
|
+
request,
|
|
7
|
+
safeText = (value, fallback) => value == null ? fallback : String(value),
|
|
8
|
+
}) {
|
|
9
|
+
if (!hasApiKey) {
|
|
10
|
+
return { account: null, gateway: "not authenticated", fleet: "unavailable", kill: "unavailable", current: {} };
|
|
11
|
+
}
|
|
12
|
+
const options = { timeoutMs: MENU_STATUS_TIMEOUT_MS };
|
|
13
|
+
const [gatewayResult, accountResult, fleetResult, killResult] = await Promise.allSettled([
|
|
14
|
+
gatewayStatus(options),
|
|
15
|
+
request("/account", options),
|
|
16
|
+
request("/agents?limit=100", options),
|
|
17
|
+
request("/kill-switch", options),
|
|
18
|
+
]);
|
|
19
|
+
const gateway = gatewayResult.status === "fulfilled" ? gatewayResult.value.label : "unavailable";
|
|
20
|
+
let account = "unavailable";
|
|
21
|
+
if (accountResult.status === "fulfilled") {
|
|
22
|
+
const email = safeText(accountResult.value?.email, "email unavailable");
|
|
23
|
+
const scope = accountResult.value?.control_key_scope === "write" ? "write key" : "read key";
|
|
24
|
+
account = `${email} · ${scope}`;
|
|
25
|
+
} else if (/^404\b/.test(String(accountResult.reason?.message ?? ""))) {
|
|
26
|
+
account = null;
|
|
27
|
+
}
|
|
28
|
+
let fleet = "unavailable";
|
|
29
|
+
if (fleetResult.status === "fulfilled" && Array.isArray(fleetResult.value)) {
|
|
30
|
+
const records = fleetResult.value;
|
|
31
|
+
const active = records.filter((agent) => agent.status === "active").length;
|
|
32
|
+
const suspended = records.filter((agent) => agent.status === "suspended").length;
|
|
33
|
+
const total = records.length === 100 ? "100+ agents (partial)" : `${records.length} agent${records.length === 1 ? "" : "s"}`;
|
|
34
|
+
fleet = `${total} · ${active} active · ${suspended} suspended`;
|
|
35
|
+
}
|
|
36
|
+
let kill = "unavailable";
|
|
37
|
+
if (killResult.status === "fulfilled") {
|
|
38
|
+
kill = `tenant ${killResult.value?.armed ? "armed" : "clear"} · platform ${killResult.value?.platform_kill ? "armed" : "clear"}`;
|
|
39
|
+
}
|
|
40
|
+
return { account, gateway, fleet, kill, current: { account: account ?? undefined, fleet, kill, gateway } };
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export const integrationPreviewArgv = (integration) => ["configure", integration];
|
|
44
|
+
|
|
45
|
+
export function logsArgv({ agentId = "", callClass = "all", status = "", limit = 20 } = {}) {
|
|
46
|
+
return [
|
|
47
|
+
"logs",
|
|
48
|
+
...(agentId ? ["--agent-id", agentId] : []),
|
|
49
|
+
...(callClass !== "all" ? ["--class", callClass] : []),
|
|
50
|
+
...(status ? ["--status", status] : []),
|
|
51
|
+
"--limit", String(limit),
|
|
52
|
+
];
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export function verificationArgv({ type, artifact, issuer, audience = "" }) {
|
|
56
|
+
return ["verify", type, artifact, "--issuer", issuer, ...(type === "token" ? ["--audience", audience] : [])];
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export const agentStateArgv = ({ suspend, id }) => ["agent", suspend ? "suspend" : "resume", id];
|
|
60
|
+
|
|
61
|
+
export function killSwitchArgv({ armed, typed = "", confirmed = false }) {
|
|
62
|
+
if (armed) return confirmed ? ["kill", "off"] : null;
|
|
63
|
+
return typed === "ARM" ? ["kill", "on"] : null;
|
|
64
|
+
}
|