passcontrol 0.9.3 → 0.9.5

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.
@@ -47,6 +47,7 @@ import {
47
47
  probeGatewayOrigin,
48
48
  requirePassportGateway,
49
49
  requirePassport,
50
+ shellQuotingHint,
50
51
  step,
51
52
  warn,
52
53
  writeConfigFile,
@@ -86,6 +87,7 @@ import { defaultAllowedModelForProvider } from "../cli/integration-defaults.mjs"
86
87
  import {
87
88
  PASSPORT_KEY_STORAGE_OS,
88
89
  createPassportCredentialStore,
90
+ importPassportKey,
89
91
  keyStorageDeclaration,
90
92
  migratePassportKey,
91
93
  } from "../cli/passport-key-store.mjs";
@@ -1247,13 +1249,28 @@ async function startDashboard(opts = {}) {
1247
1249
  // work (that is all the npm script is now), minus npm/cmd wrappers. Next's CLI
1248
1250
  // still forks its HTTP worker, so this pid is deliberately the SUPERVISOR.
1249
1251
  // Unix stops its process group; Windows uses taskkill /T for the whole tree.
1252
+ //
1253
+ // `detached` is set on BOTH platforms, and the two reasons are different.
1254
+ // Unix needs it for the process group `stopDashboard` signals with kill(-pid).
1255
+ // Windows needs it for something else entirely: it is what lets the child
1256
+ // outlive us at all. This read `process.platform !== "win32"` — detached only
1257
+ // on Unix, on the reasoning that Windows takes its tree from taskkill and so
1258
+ // has no use for a process group. True, and it answered the wrong question.
1259
+ //
1260
+ // `child.unref()` below only lets the PARENT exit; it does not let the child
1261
+ // survive. So on Windows `passcontrol start` raised the dashboard, waited for
1262
+ // it, truthfully printed "dashboard online" — waitForGateway requires a live
1263
+ // pid and an answering gateway on the same poll — and then killed it by
1264
+ // returning. `setup` did the same, which is worse: a first-run self-hoster is
1265
+ // handed a URL that stops working as they read it, with an empty log and no
1266
+ // error anywhere. Reported and reproduced on Windows 11, 2026-09-13.
1250
1267
  const devServer = path.join(appRoot, "scripts", "dev-docker.mjs");
1251
1268
  if (!fs.existsSync(devServer)) {
1252
1269
  throw new Error(`${devServer} is missing — this checkout is incomplete or predates the local-stack launcher. Re-clone, or run \`npm run dev:docker\` from ${appRoot} by hand.`);
1253
1270
  }
1254
1271
  const child = spawn(process.execPath, [devServer], {
1255
1272
  cwd: appRoot,
1256
- detached: process.platform !== "win32",
1273
+ detached: true,
1257
1274
  env: { ...process.env, PORT: String(dashboard.port) },
1258
1275
  stdio: ["ignore", logFd, logFd],
1259
1276
  });
@@ -1274,6 +1291,35 @@ async function startDashboard(opts = {}) {
1274
1291
  return dashboard;
1275
1292
  }
1276
1293
 
1294
+ /**
1295
+ * Take down pid and everything below it on Windows. Reports, never throws.
1296
+ *
1297
+ * `taskkill /T` WITHOUT `/F` asks politely, and asking needs somewhere to ask:
1298
+ * a `DETACHED_PROCESS` child has no console and no window, so Windows answers
1299
+ * "This process can only be terminated forcefully (with /F option)" and taskkill
1300
+ * exits NON-ZERO. `execFileSync` turns a non-zero exit into a throw.
1301
+ *
1302
+ * That throw is why `passcontrol stop --dashboard-only` refused on Windows the
1303
+ * moment the dashboard started being spawned detached: the catch around it only
1304
+ * rescued `ESRCH`, a POSIX errno a failing taskkill cannot produce, so it
1305
+ * rethrew and abandoned the stop eight lines above the `/F` escalation the
1306
+ * function already had. The two-stage design was right; the throw jumped stage
1307
+ * two. Reported from a Windows 11 box, 2026-09-13.
1308
+ *
1309
+ * So a non-zero exit is an ANSWER here, not an exception — it is how Windows
1310
+ * says "use /F" — and the caller decides what to do about it. Whether the
1311
+ * dashboard is actually down is settled by the port, not by this.
1312
+ */
1313
+ function windowsTaskkillTree(pid, { force }) {
1314
+ const args = ["/PID", String(pid), "/T", ...(force ? ["/F"] : [])];
1315
+ try {
1316
+ execFileSync("taskkill.exe", args, { encoding: "utf8", timeout: 10_000, windowsHide: true });
1317
+ return true;
1318
+ } catch {
1319
+ return false;
1320
+ }
1321
+ }
1322
+
1277
1323
  async function stopDashboard() {
1278
1324
  const state = runningManagedDashboard();
1279
1325
  if (!state) {
@@ -1281,34 +1327,32 @@ async function stopDashboard() {
1281
1327
  return;
1282
1328
  }
1283
1329
 
1284
- try {
1285
- if (process.platform === "win32") {
1286
- execFileSync("taskkill.exe", ["/PID", String(state.pid), "/T"], {
1287
- encoding: "utf8",
1288
- timeout: 10_000,
1289
- windowsHide: true,
1290
- });
1291
- } else process.kill(-state.pid, "SIGTERM");
1292
- } catch (error) {
1293
- if (error.code === "ESRCH") {
1294
- removeDashboardState();
1295
- ok("No CLI-managed local dashboard is running.");
1296
- return;
1330
+ if (process.platform === "win32") {
1331
+ // Politely first — it lets Next flush if anything is listening for it — but
1332
+ // escalate the instant taskkill says it cannot, rather than waiting out a
1333
+ // port that a refused kill is never going to release. The port check below
1334
+ // is still the authority, and still escalates on its own.
1335
+ if (!windowsTaskkillTree(state.pid, { force: false })) {
1336
+ windowsTaskkillTree(state.pid, { force: true });
1337
+ }
1338
+ } else {
1339
+ try {
1340
+ process.kill(-state.pid, "SIGTERM");
1341
+ } catch (error) {
1342
+ if (error.code === "ESRCH") {
1343
+ removeDashboardState();
1344
+ ok("No CLI-managed local dashboard is running.");
1345
+ return;
1346
+ }
1347
+ throw error;
1297
1348
  }
1298
- throw error;
1299
1349
  }
1300
1350
 
1301
1351
  if (!await waitForPortRelease(state.port)) {
1302
- if (process.platform === "win32") {
1303
- execFileSync("taskkill.exe", ["/PID", String(state.pid), "/T", "/F"], {
1304
- encoding: "utf8",
1305
- timeout: 10_000,
1306
- windowsHide: true,
1307
- });
1308
- }
1352
+ if (process.platform === "win32") windowsTaskkillTree(state.pid, { force: true });
1309
1353
  else process.kill(-state.pid, "SIGKILL");
1310
1354
  if (!await waitForPortRelease(state.port)) {
1311
- throw new Error(`Dashboard process group ${state.pid} did not release port ${state.port}.`);
1355
+ throw new Error(`Dashboard (PID ${state.pid}) did not release port ${state.port}.`);
1312
1356
  }
1313
1357
  }
1314
1358
  removeDashboardState();
@@ -2741,7 +2785,13 @@ async function passportCommand(rest, opts = {}) {
2741
2785
  const gateway = bareGatewayOrigin(opts.gateway, "--gateway");
2742
2786
  const passportId = opts.id.trim();
2743
2787
  if (!isEncodedEd25519Key(passportId)) {
2744
- throw new Error("--id must be a 32-byte Ed25519 public key encoded as unpadded base64url.");
2788
+ // Same hint as --gateway above, because it is the same operator on the same
2789
+ // line: cmd.exe hands both flags their quotes. The id at least refuses a
2790
+ // quoted value rather than storing one — base64url has no quote character —
2791
+ // so this only ever needed the explanation, never a repair.
2792
+ throw new Error(
2793
+ `--id must be a 32-byte Ed25519 public key encoded as unpadded base64url.${shellQuotingHint(passportId)}`
2794
+ );
2745
2795
  }
2746
2796
 
2747
2797
  const project = config.sources.find((source) =>
@@ -2771,34 +2821,30 @@ async function passportCommand(rest, opts = {}) {
2771
2821
  throw new Error("Passport secret does not match the supplied Passport ID. Nothing was stored.");
2772
2822
  }
2773
2823
 
2824
+ // The write/readback/commit sequence and its rollbacks live in
2825
+ // importPassportKey, which is where they can be tested: nothing in this file
2826
+ // is exported, and the store is built here with no seam, so a test of the
2827
+ // rollback would have to reach the operator's real Keychain.
2774
2828
  const store = createPassportCredentialStore();
2775
- const written = store.write(passportId, secret);
2776
- if (!written.ok) throw new Error(`${written.reason}. Nothing was written to the PassControl config.`);
2777
- const readback = store.read(passportId);
2778
- if (!readback.ok || readback.secret !== secret) {
2779
- store.delete(passportId);
2780
- throw new Error(`${store.name} did not return the key that was just stored. The new item was removed and config was not changed.`);
2781
- }
2782
-
2783
- try {
2784
- mergeConfigFileAtomic(target, {
2829
+ const result = importPassportKey({
2830
+ passportId,
2831
+ secret,
2832
+ store,
2833
+ oldId,
2834
+ oldStorage,
2835
+ commitConfig: () => mergeConfigFileAtomic(target, {
2785
2836
  PASSCONTROL_GATEWAY: gateway,
2786
2837
  PASSPORT_ID: passportId,
2787
2838
  PASSPORT_SECRET: "",
2788
2839
  PASSPORT_KEY_STORAGE: PASSPORT_KEY_STORAGE_OS,
2789
- });
2790
- } catch (error) {
2791
- store.delete(passportId);
2792
- throw error;
2793
- }
2840
+ }),
2841
+ });
2842
+ // The message already carries the filesystem detail: main()'s handler prints
2843
+ // `error.message` and nothing else, so a bare `cause` would never be seen.
2844
+ if (!result.ok) throw new Error(result.message, { cause: result.cause });
2845
+ if (result.warning) warn(result.warning);
2794
2846
 
2795
- if (oldStorage === PASSPORT_KEY_STORAGE_OS && oldId && oldId !== passportId) {
2796
- const removed = store.delete(oldId);
2797
- if (!removed.ok) {
2798
- warn(`The previous Passport key could not be confirmed removed from ${store.name}; the new import is active, but the old OS item needs manual cleanup.`);
2799
- }
2800
- }
2801
- ok(`Passport ${passportId} imported into ${store.name}.`);
2847
+ ok(result.message);
2802
2848
  step(`Global gateway: ${gateway}`);
2803
2849
  step("The private key was verified and never written to the config file or command line.");
2804
2850
  }
package/cli/config.mjs CHANGED
@@ -431,6 +431,42 @@ export function requireControlApiKey(current = config) {
431
431
  */
432
432
  const LOOPBACK_HOSTNAMES = new Set(["localhost", "127.0.0.1", "[::1]"]);
433
433
 
434
+ /**
435
+ * A value that still carries its own quote characters, explained.
436
+ *
437
+ * `cmd.exe` does not treat `'` as quoting. A Windows operator copying a POSIX
438
+ * invocation out of a README types `--gateway 'http://localhost:3000'` and the
439
+ * CLI receives those quotes as part of the argument — so a value that is right
440
+ * on the line they typed is refused by a message about the string that arrived.
441
+ * The same trap already broke `npm run dev:docker`, which was a bash one-liner
442
+ * in single quotes until cmd handed bash `'set` as its whole command; see the
443
+ * header of `scripts/dev-docker.mjs`.
444
+ *
445
+ * Deliberately a hint and not a repair. The callers below validate values that
446
+ * decide where a credential is sent, and quietly normalizing an argument before
447
+ * a strict rule sees it is how strict rules stop being strict. This only
448
+ * explains the refusal.
449
+ *
450
+ * Returns a sentence to append, or "". It describes the shape and never the
451
+ * value: a gateway URL or a passport id can itself be a credential.
452
+ *
453
+ * @param {unknown} value
454
+ * @returns {string}
455
+ */
456
+ export function shellQuotingHint(value) {
457
+ const text = String(value ?? "");
458
+ if (text.length < 2) return "";
459
+ const quote = text[0];
460
+ if ((quote !== "'" && quote !== '"') || text[text.length - 1] !== quote) return "";
461
+ // Only single quotes get the cmd.exe sentence: cmd *does* strip double
462
+ // quotes, so a value that arrives wrapped in them came from a config file or
463
+ // another shell, and naming cmd would send the reader somewhere wrong.
464
+ const cause =
465
+ quote === "'" ? " Windows cmd.exe does not treat ' as quoting and passes it through literally." : "";
466
+ const name = quote === "'" ? "a single quote" : "a double quote";
467
+ return ` The value starts and ends with ${name}, so the quote characters are part of it.${cause} Retype it with no quotes around it.`;
468
+ }
469
+
434
470
  /**
435
471
  * Validate a gateway value and return the origin to build URLs from.
436
472
  *
@@ -452,6 +488,11 @@ const LOOPBACK_HOSTNAMES = new Set(["localhost", "127.0.0.1", "[::1]"]);
452
488
  * prints the message and exits 1, and `doctor` catches it to report a failed
453
489
  * check instead of vanishing mid-diagnosis. The message never quotes the value,
454
490
  * because a rejected gateway can itself carry credentials.
491
+ *
492
+ * The unparseable branch appends `shellQuotingHint`, which the SDK has no reason
493
+ * to carry — it is never handed a cmd.exe argv. That is a message, not a rule:
494
+ * what this accepts and refuses is still identical to the SDK's, which is all
495
+ * the parity test asserts.
455
496
  */
456
497
  export function bareGatewayOrigin(gateway, label = "PASSCONTROL_GATEWAY") {
457
498
  let url;
@@ -459,7 +500,8 @@ export function bareGatewayOrigin(gateway, label = "PASSCONTROL_GATEWAY") {
459
500
  url = new URL(String(gateway ?? ""));
460
501
  } catch {
461
502
  throw new Error(
462
- `${label} must be an absolute URL (for example https://passcontrol.example.com).`
503
+ `${label} must be an absolute URL (for example https://passcontrol.example.com).` +
504
+ shellQuotingHint(gateway)
463
505
  );
464
506
  }
465
507
  const loopback = LOOPBACK_HOSTNAMES.has(url.hostname);
@@ -433,3 +433,109 @@ export function migratePassportKey({ passportId, secret, store, removeFileSecret
433
433
  message: `Migrated to tier 1 — ${store.name}; verified readback before removing the file key.`,
434
434
  };
435
435
  }
436
+
437
+ /**
438
+ * Move a verified passport secret into the OS store and commit the config that
439
+ * points at it, with one invariant holding the rollbacks together:
440
+ *
441
+ * **this function may only delete an item that it created.**
442
+ *
443
+ * Both failure paths below used to end in `store.delete(passportId)`, on the
444
+ * reasoning that the item under that id was the one just written. That is true
445
+ * exactly until `--replace` is used to re-import the SAME passport id, which it
446
+ * permits. OS storage is keyed by the id — macOS `add-generic-password -U`
447
+ * updates in place, and the DPAPI blob path is derived from the id — so in that
448
+ * one case the item removed is the operator's existing key, and the config left
449
+ * behind still points at a store that no longer has it.
450
+ *
451
+ * The pre-existence probe is UNCONDITIONAL, and not gated on the config saying
452
+ * `PASSPORT_KEY_STORAGE=os` for this id. The config is not authoritative about
453
+ * what the store contains: `cli/logout.mjs` blanks that marker in the same write
454
+ * that asks the store to delete, and the store is allowed to report that it
455
+ * could not confirm the removal — so an item can outlive the marker. The store
456
+ * is the only authority on its own contents. The cost is one extra read per
457
+ * import, which on a locked Keychain may mean one extra unlock prompt.
458
+ *
459
+ * The honest limit, and it is the same one `confirmGone` states above: a failed
460
+ * `read()` does not prove absence. A locked store reads as empty, so a rollback
461
+ * can still remove a real item. This narrows the window to that case; it does
462
+ * not close it, because the store cannot give positive evidence of absence.
463
+ *
464
+ * `commitConfig` is injected rather than called directly for the same reason
465
+ * `migratePassportKey` takes `removeFileSecret`: the rollback is the behaviour
466
+ * worth testing, and it is only reachable if the commit can be made to fail.
467
+ */
468
+ export function importPassportKey({
469
+ passportId,
470
+ secret,
471
+ store,
472
+ oldId = "",
473
+ oldStorage = "",
474
+ commitConfig,
475
+ }) {
476
+ if (!passportId || !secret) {
477
+ return { ok: false, message: "A Passport ID and secret are required." };
478
+ }
479
+
480
+ const existing = store.read(passportId);
481
+ const preExisting = existing.ok && typeof existing.secret === "string" && existing.secret.length > 0;
482
+ // The caller proves `secret` derives `passportId` before reaching here, so a
483
+ // same-id import is provably the same key the store already holds. Writing it
484
+ // changes nothing and only opens a window in which a rollback could take it.
485
+ const alreadyStored = preExisting && sameSecret(secret, existing.secret);
486
+
487
+ if (!alreadyStored) {
488
+ const written = store.write(passportId, secret);
489
+ if (!written.ok) {
490
+ // Nothing was created, so there is nothing to roll back.
491
+ return { ok: false, message: `${written.reason}. Nothing was written to the PassControl config.` };
492
+ }
493
+
494
+ const readback = store.read(passportId);
495
+ if (!readback.ok || !sameSecret(secret, readback.secret)) {
496
+ if (!preExisting) store.delete(passportId);
497
+ return {
498
+ ok: false,
499
+ message: preExisting
500
+ ? `${store.name} did not return the key that was just stored. The item already under this Passport ID was left in place, and config was not changed.`
501
+ : `${store.name} did not return the key that was just stored. The new item was removed and config was not changed.`,
502
+ };
503
+ }
504
+ }
505
+
506
+ try {
507
+ commitConfig();
508
+ } catch (error) {
509
+ if (!preExisting) store.delete(passportId);
510
+ // The CLI's top-level handler prints `error.message` and nothing else, so
511
+ // the filesystem detail has to travel inside the message or the operator
512
+ // loses the only line that says which path failed. An fs error names a
513
+ // path, not a key — the collapse-to-fixed-text rule above is about
514
+ // subprocess stderr, which can echo the secret back.
515
+ const detail = error instanceof Error ? error.message : String(error);
516
+ return {
517
+ ok: false,
518
+ cause: error,
519
+ message: preExisting
520
+ ? `The PassControl config could not be written; the key already in ${store.name} was left in place. ${detail}`
521
+ : `The PassControl config could not be written; the new item was removed from ${store.name}. ${detail}`,
522
+ };
523
+ }
524
+
525
+ let warning = null;
526
+ if (oldStorage === PASSPORT_KEY_STORAGE_OS && oldId && oldId !== passportId) {
527
+ const removed = store.delete(oldId);
528
+ if (!removed.ok) {
529
+ warning = `The previous Passport key could not be confirmed removed from ${store.name}; the new import is active, but the old OS item needs manual cleanup.`;
530
+ }
531
+ }
532
+
533
+ return {
534
+ ok: true,
535
+ alreadyStored,
536
+ warning,
537
+ message: alreadyStored
538
+ ? `${store.name} already held this Passport key; it was verified and left in place.`
539
+ : `Passport ${passportId} imported into ${store.name}.`,
540
+ };
541
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "passcontrol",
3
- "version": "0.9.3",
3
+ "version": "0.9.5",
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",