passcontrol 0.8.0 → 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/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: process.env.PASSPORT_ID ?? "",
224
- passportSecret: process.env.PASSPORT_SECRET ?? "",
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 from
244
- * `values` is BLANKED — that is correct for `init`, which collects all of them,
245
- * and wrong for any caller that means to change a subset. Use mergeConfigFile
246
- * for those.
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
- if (!current.passportId || !current.passportSecret) {
381
+ const passportSecret = current.passportSecret;
382
+ const storage = current.passportStorage;
383
+ if (!current.passportId || !passportSecret) {
331
384
  die(
332
- "No passport configured. Run `passcontrol init`, copy .passcontrol.example to .passcontrol, or pass PASSPORT_ID/PASSPORT_SECRET as env."
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
- return { passportId: current.passportId, passportSecret: current.passportSecret };
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
@@ -541,6 +541,7 @@ export async function loginCommand(opts = {}, deps = {}) {
541
541
  PASSCONTROL_GATEWAY: origin,
542
542
  PASSPORT_ID: passportId,
543
543
  PASSPORT_SECRET: passportSecret,
544
+ PASSPORT_KEY_STORAGE: "",
544
545
  PASSCONTROL_API_KEY: grant.api_key,
545
546
  });
546
547
  ok(`wrote ${target}`);
@@ -553,6 +554,10 @@ export async function loginCommand(opts = {}, deps = {}) {
553
554
  passportSecret,
554
555
  apiKey: grant.api_key,
555
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,
556
561
  });
557
562
 
558
563
  step("");
package/cli/logout.mjs CHANGED
@@ -21,6 +21,10 @@
21
21
  // machine and say plainly that the key is still live.
22
22
  import fs from "node:fs";
23
23
  import path from "node:path";
24
+ import {
25
+ PASSPORT_KEY_STORAGE_OS,
26
+ createPassportCredentialStore,
27
+ } from "./passport-key-store.mjs";
24
28
  import {
25
29
  CONFIG_FILE,
26
30
  config,
@@ -50,9 +54,16 @@ import {
50
54
  export function credentialFile(opts = {}, { sources = configSources, cwd = process.cwd() } = {}) {
51
55
  if (opts.project) return path.join(cwd, CONFIG_FILE);
52
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.
53
62
  const holder = [...sources]
54
63
  .reverse()
55
- .find((source) => String(source?.values?.PASSPORT_SECRET ?? "").trim());
64
+ .find((source) =>
65
+ String(source?.values?.PASSPORT_SECRET ?? "").trim() ||
66
+ String(source?.values?.PASSPORT_KEY_STORAGE ?? "").trim());
56
67
  return holder?.path ?? null;
57
68
  }
58
69
 
@@ -99,7 +110,14 @@ export async function logoutCommand(opts = {}, deps = {}) {
99
110
  // never asked for and cannot easily read. Answering "no" to a destructive
100
111
  // prompt should mean nothing happened, so nothing has yet.
101
112
  if (!opts.yes) {
102
- const holdsPassport = /^PASSPORT_SECRET=(.+)$/mu.exec(fs.readFileSync(target, "utf8"))?.[1]?.trim();
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();
103
121
  if (holdsPassport) {
104
122
  warn(`${target} holds a passport secret, and PassControl has no copy of it.`);
105
123
  step("Clearing it is permanent — anything still using that passport keeps working, but");
@@ -186,7 +204,33 @@ export async function logoutCommand(opts = {}, deps = {}) {
186
204
  // are not credentials and the operator did not ask to lose them. `mergeConfigFile`
187
205
  // spreads over what is already there, and writeConfigFile emits `?? ""` for every
188
206
  // key, so an empty string is the supported way to clear one.
189
- mergeConfigFile(target, { PASSPORT_ID: "", PASSPORT_SECRET: "", PASSCONTROL_API_KEY: "" });
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
+ });
190
234
  ok(`cleared the credentials in ${target}`);
191
235
 
192
236
  for (const line of warnings) warn(line);
@@ -195,5 +239,5 @@ export async function logoutCommand(opts = {}, deps = {}) {
195
239
  }
196
240
  step("Log back in any time with `passcontrol login`.");
197
241
 
198
- return { target, keyRevoked, agentRevoked, agent, warnings };
242
+ return { target, keyRevoked, agentRevoked, agent, warnings, osKeyCleared };
199
243
  }
@@ -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
+ }