@xiaolikt/ai-vault 0.12.3 → 0.13.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.
@@ -298,14 +298,27 @@ const WIN32 = process.platform === "win32";
298
298
  /** A file under the Windows directory: `%SystemRoot%` already is `C:\Windows`. */
299
299
  const systemFile = (...parts: string[]): string => path.join(process.env.SystemRoot ?? "C:/Windows", ...parts);
300
300
 
301
- /** `taskkill /T /F`: the process and everything it started. Windows has no process groups. Exported for tests. */
302
- export function killTree(pid: number): void {
301
+ /**
302
+ * `taskkill /T /F`: the process and everything it started. Windows has no
303
+ * process groups. Exported for tests.
304
+ *
305
+ * Asynchronous on purpose: this runs when a command times out or the user
306
+ * cancels, which is a moment the host's UI must stay live. The promise is
307
+ * unref'd, so a pending taskkill never holds the process open.
308
+ */
309
+ export function killTree(pid: number): Promise<void> {
303
310
  const taskkill = systemFile("System32", "taskkill.exe");
304
- try {
305
- spawnSync(taskkill, ["/PID", String(pid), "/T", "/F"], { stdio: "ignore", timeout: 5000, windowsHide: true });
306
- } catch {
307
- /* best-effort: the caller still kills the process itself */
308
- }
311
+ return new Promise<void>((resolve) => {
312
+ try {
313
+ const child = spawn(taskkill, ["/PID", String(pid), "/T", "/F"], { stdio: "ignore", windowsHide: true });
314
+ child.on("error", () => resolve());
315
+ child.on("close", () => resolve());
316
+ child.unref();
317
+ setTimeout(resolve, 5000).unref();
318
+ } catch {
319
+ resolve();
320
+ }
321
+ });
309
322
  }
310
323
 
311
324
  /** How long a copy command may take to set the clipboard and exit. */
@@ -366,9 +379,11 @@ function exec(cmd: string, args: string[], opts: ExecOptions = {}): Promise<Exec
366
379
  const kill = () => {
367
380
  if (WIN32) {
368
381
  // No process groups on Windows: take the whole tree down, or a command
369
- // that timed out leaves what it started running with the secret in its environment.
370
- if (child.pid) killTree(child.pid);
382
+ // that timed out leaves what it started running with the secret in its
383
+ // environment. The child goes first and at once; the tree follows off
384
+ // the event loop, so a slow taskkill cannot freeze the host's UI.
371
385
  child.kill("SIGKILL");
386
+ if (child.pid) void killTree(child.pid);
372
387
  return;
373
388
  }
374
389
  if (opts.group && child.pid) {
@@ -457,22 +472,28 @@ export async function auditEvent(event: string, detail: string, session?: string
457
472
  let bwLaunch: CliLaunch | undefined;
458
473
 
459
474
  /** Runs at all: answers `--version` with exit 0. */
460
- async function bwRuns(launch: CliLaunch): Promise<boolean> {
475
+ async function bwRuns(launch: CliLaunch): Promise<{ ok: boolean; why?: string }> {
461
476
  try {
462
477
  const r = await exec(launch.program, [...launch.pre, "--version"], { timeout: 20_000 });
463
- return r.code === 0;
464
- } catch {
465
- return false;
478
+ return r.code === 0 ? { ok: true } : { ok: false, why: `exit ${r.code}${r.stderr ? `: ${tail(r.stderr, 120)}` : ""}` };
479
+ } catch (error) {
480
+ // A timeout or a refused start is worth reporting; a missing file is not.
481
+ const why = error instanceof Error && !(error as NodeJS.ErrnoException).code ? error.message : undefined;
482
+ return { ok: false, why };
466
483
  }
467
484
  }
468
485
 
469
486
  export async function resolveBw(): Promise<CliLaunch> {
470
487
  if (bwLaunch) return bwLaunch;
471
488
  // `bw.exe` is found by the bare name on Windows, `bw` elsewhere.
472
- if (await bwRuns({ program: "bw", pre: [] })) {
489
+ const first = await bwRuns({ program: "bw", pre: [] });
490
+ if (first.ok) {
473
491
  bwLaunch = { program: "bw", pre: [] };
474
492
  return bwLaunch;
475
493
  }
494
+ // "Not found" is what the search below fixes; a bw that is there but will
495
+ // not answer is not, and saying so beats a list of places it is not.
496
+ let trouble = first.why;
476
497
  // npm installs `bw` as bw.cmd (with a .ps1 and a sh script beside it), which
477
498
  // Windows cannot start without a shell: start the JavaScript it wraps with
478
499
  // this Node instead.
@@ -483,10 +504,13 @@ export async function resolveBw(): Promise<CliLaunch> {
483
504
  const candidate = path.join(dir, name);
484
505
  if (!existsSync(candidate)) continue;
485
506
  const launch = name === "bw.exe" ? { program: candidate, pre: [] } : npmShimLaunch(candidate);
486
- if (launch && (await bwRuns(launch))) {
507
+ if (!launch) continue;
508
+ const run = await bwRuns(launch);
509
+ if (run.ok) {
487
510
  bwLaunch = launch;
488
511
  return bwLaunch;
489
512
  }
513
+ trouble ??= run.why && `${candidate}: ${run.why}`;
490
514
  }
491
515
  }
492
516
  }
@@ -506,6 +530,7 @@ export async function resolveBw(): Promise<CliLaunch> {
506
530
  } catch {
507
531
  /* ignore */
508
532
  }
533
+ if (trouble) throw new Error(`Bitwarden CLI (\`bw\`) does not start: ${trouble}`);
509
534
  throw new Error("Bitwarden CLI (`bw`) not found in PATH or ~/.nvm. Install it, `bw login`, and retry.");
510
535
  }
511
536
 
@@ -9,7 +9,7 @@
9
9
  */
10
10
  import { createHmac, randomBytes } from "node:crypto";
11
11
  import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
12
- import { existsSync, readFileSync } from "node:fs";
12
+ import { chmodSync, existsSync, readFileSync, writeFileSync } from "node:fs";
13
13
  import { createRequire } from "node:module";
14
14
  import { homedir } from "node:os";
15
15
  import { delimiter, dirname, extname, join } from "node:path";
@@ -174,12 +174,32 @@ export function resolveBinary(): string | undefined {
174
174
  * Start one CLI call. A program Node will not start is reported through
175
175
  * `CliError` like every other failure, not thrown from inside the promise.
176
176
  */
177
- function startCli(launch: CliLaunch, args: string[], env: NodeJS.ProcessEnv): ChildProcessWithoutNullStreams {
177
+ /** The message of the last start failure, for the callback below. */
178
+ let lastStartError = "";
179
+
180
+ /**
181
+ * Start one CLI call. A program Node will not start is reported through
182
+ * `CliError` like every other failure — thrown here when `spawn` refuses
183
+ * outright, or handed to `onError` when the failure arrives as an event (a
184
+ * policy, a virus scanner holding the file) — never thrown from inside the
185
+ * promise the caller is building.
186
+ */
187
+ function startCli(
188
+ launch: CliLaunch,
189
+ args: string[],
190
+ env: NodeJS.ProcessEnv,
191
+ onError: () => void,
192
+ ): ChildProcessWithoutNullStreams {
178
193
  try {
179
194
  // windowsHide: the CLI is a console program, and gets no window of its
180
195
  // own when the host has none. The dialogs it opens are windows it opens
181
196
  // on purpose, and show regardless.
182
- return spawn(launch.program, [...launch.pre, ...args], { stdio: ["pipe", "pipe", "pipe"], env, windowsHide: true });
197
+ const child = spawn(launch.program, [...launch.pre, ...args], { stdio: ["pipe", "pipe", "pipe"], env, windowsHide: true });
198
+ child.on("error", (error) => {
199
+ lastStartError = error.message;
200
+ onError();
201
+ });
202
+ return child;
183
203
  } catch (error) {
184
204
  throw new CliError(EXIT.error, undefined, `cannot run ${launch.program}: ${error instanceof Error ? error.message : String(error)}`, "");
185
205
  }
@@ -196,14 +216,31 @@ function message(stderr: string, fallback: string): string {
196
216
  }
197
217
 
198
218
  /**
199
- * The secret this process keeps for the sessions it unlocked. It never reaches
200
- * disk: the CLI writes it into the HMAC on each session file, and uses it to
201
- * check the approvals we relay. A model-driven `bash` that finds a session
202
- * token can therefore `list`, but can neither forge a read approval nor edit
203
- * the token's grants.
219
+ * The secret every pi/omp process on this machine shares for the sessions
220
+ * it unlocked. It lives in `<store>/.host` (0600), next to the store and its
221
+ * `.wrap` key, so it is protected by exactly what protects them: the user's
222
+ * home directory.
223
+ *
224
+ * It used to be minted per process, which meant every herdr tab, every
225
+ * subagent and every `/new` had its own secret and could not read a session
226
+ * another one had opened — so each of them asked for the master password
227
+ * again. One secret per store fixes that: a session opened in one tab is
228
+ * usable in the next.
229
+ *
230
+ * What this does not change: a session file is still signed with this secret,
231
+ * so the model's bash still cannot use a token it finds on disk *unless* it
232
+ * also reads `.host`. That is the same exposure as `.wrap` — the "same user"
233
+ * line the README already draws — and the per-read confirm window is the
234
+ * control on top of it, unchanged.
204
235
  */
205
236
  export class HostSecret {
206
237
  #value: string | undefined;
238
+ #file: string | undefined;
239
+
240
+ /** Point the secret at a store directory: the first `value` reads or creates it there. */
241
+ attach(storeDir: string): void {
242
+ this.#file = join(storeDir, ".host");
243
+ }
207
244
 
208
245
  get present(): boolean {
209
246
  return this.#value !== undefined;
@@ -214,15 +251,19 @@ export class HostSecret {
214
251
  if (secret && secret.length >= 32) this.#value = secret;
215
252
  }
216
253
 
217
- /** 32 fresh bytes, hex — minted once per process, before the first unlock. */
254
+ /** 32 fresh bytes, hex — a new secret for this store; every live session is voided. */
218
255
  rotate(): string {
219
- this.#value = randomBytes(32).toString("hex");
220
- return this.#value;
256
+ const fresh = randomBytes(32).toString("hex");
257
+ this.#value = fresh;
258
+ if (this.#file) this.#persist(fresh);
259
+ return fresh;
221
260
  }
222
261
 
223
- /** The secret, minting it on first use. */
262
+ /** The secret: the store's, read or created on first use. */
224
263
  get value(): string {
225
- return (this.#value ??= randomBytes(32).toString("hex"));
264
+ if (this.#value) return this.#value;
265
+ this.#value = this.#read() ?? this.rotate();
266
+ return this.#value;
226
267
  }
227
268
 
228
269
  /** Environment for a CLI child: marks us as the host and passes the secret. */
@@ -237,15 +278,45 @@ export class HostSecret {
237
278
  .update(`allow:${token}:${entry.toLowerCase()}:${answer ? "y" : "n"}`)
238
279
  .digest("hex");
239
280
  }
281
+
282
+ #read(): string | undefined {
283
+ if (!this.#file) return undefined;
284
+ try {
285
+ const text = readFileSync(this.#file, "utf8").trim();
286
+ if (/^[0-9a-f]{64}$/.test(text)) return text;
287
+ } catch {
288
+ /* not there yet */
289
+ }
290
+ return undefined;
291
+ }
292
+
293
+ #persist(secret: string): void {
294
+ if (!this.#file) return;
295
+ try {
296
+ writeFileSync(this.#file, `${secret}\n`, { mode: 0o600 });
297
+ chmodSync(this.#file, 0o600);
298
+ } catch {
299
+ /* a read-only store directory: the secret stays in memory for this process */
300
+ }
301
+ }
302
+ }
303
+
304
+ /** The store directory, by the CLI's own rule: `AI_VAULT_DIR`, else `~/.ai-vault`. */
305
+ export function storeDir(): string {
306
+ return process.env.AI_VAULT_DIR || join(homedir(), ".ai-vault");
240
307
  }
241
308
 
242
309
  export class VaultCli {
243
310
  private readonly launch = resolveLaunch();
244
311
  /** The program that gets started: `AI_VAULT_BIN` when that was set. */
245
312
  readonly bin = this.launch?.program;
246
- /** Set by the extension at startup; the same secret for every binding. */
313
+ /** One per store, shared by every process that uses it: `<store>/.host`. */
247
314
  host = new HostSecret();
248
315
 
316
+ constructor() {
317
+ this.host.attach(storeDir());
318
+ }
319
+
249
320
  get available(): boolean {
250
321
  return this.bin !== undefined;
251
322
  }
@@ -266,7 +337,10 @@ export class VaultCli {
266
337
  const run = await new Promise<CliRun>((resolve, reject) => {
267
338
  // A program Node will not start fails here like any other CLI failure,
268
339
  // not as a bare exception from inside the promise.
269
- const child = startCli(launch, args, { ...process.env, ...this.host.env() });
340
+ const child = startCli(launch, args, { ...process.env, ...this.host.env() }, () => {
341
+ opts.signal?.removeEventListener("abort", onAbort);
342
+ reject(new CliError(EXIT.error, undefined, `cannot run ${launch.program}: ${lastStartError}`, ""));
343
+ });
270
344
  let stdout = "";
271
345
  let stderr = "";
272
346
  const onAbort = () => child.kill("SIGKILL");
@@ -24,7 +24,7 @@ export interface Settings {
24
24
  }
25
25
 
26
26
  export const DEFAULT_SETTINGS: Settings = {
27
- vault: { unlock: "session", hours: 8, confirm: true, auto: false },
27
+ vault: { unlock: "session", hours: 8, confirm: false, auto: false },
28
28
  bitwarden: { unlock: "session", hours: 8, import: "ask", persisted: false, expiresAt: null },
29
29
  ente: { unlock: "session", hours: 8, persisted: false, expiresAt: null },
30
30
  };
package/test/cli.sh CHANGED
@@ -79,6 +79,10 @@ setting() {
79
79
  }
80
80
  # The value of one setting, as `settings KEY` prints it.
81
81
  setting_value() { python3 -c "import json,sys;print(json.load(open(sys.argv[1]))['value'])" "$1"; }
82
+ # The per-read window is off by default (the unlock is the approval). Everything
83
+ # below about the relay, the denial and the grant is about that window, so it is
84
+ # turned on for this store first, the way a user would.
85
+ setting vault.confirm true >/dev/null
82
86
  # relay <entry> <y|n>: a signed approval for the host's token.
83
87
  relay() {
84
88
  local ap
@@ -90,6 +94,21 @@ SESS="$XDG_RUNTIME_DIR/ai-vault/sessions/$TOKEN.json"
90
94
  [[ -f "$SESS" ]] && ok "the token file lives under XDG_RUNTIME_DIR" || bad "token file missing"
91
95
  [[ "$(stat -c %a "$SESS")" == "600" ]] && ok "the token file is 0600" || bad "the token file is not 0600"
92
96
 
97
+ echo "== the default: a read after unlock opens no window =="
98
+ export AI_VAULT_DIR="$TMP/store-default"
99
+ printf 'correct horse' | "$BIN" init --password-stdin --json >/dev/null
100
+ TD=$(printf 'correct horse' | env -u AI_VAULT_HOST -u AI_VAULT_HOST_SECRET "$BIN" unlock --password-stdin --json | json token)
101
+ printf 'D3FAULT\n' | "$BIN" add --name Quiet --username u --password-stdin --yes --token "$TD" >/dev/null
102
+ unset DISPLAY WAYLAND_DISPLAY
103
+ "$BIN" get Quiet --token "$TD" --json >"$TMP/quiet" 2>"$TMP/quieterr"
104
+ [[ $? -eq 0 ]] && ok "a bare read succeeds with no window and no relay" || bad "the default read needed a window: $(head -1 "$TMP/quieterr")"
105
+ grep -q '"via": *"unlocked-no-confirm"' "$TMP/quiet" && ok "and is labelled unlocked-no-confirm" || bad "via is wrong"
106
+ grep -q '"reason": *"confirm-off"' "$AI_VAULT_DIR/audit.log" && ok "the read is audited as confirm-off" || bad "not audited"
107
+ setting_default() { printf 'correct horse\n' | env -u AI_VAULT_HOST -u AI_VAULT_HOST_SECRET "$BIN" settings "$@" --password-stdin --token "$TD" --json; }
108
+ setting_default vault.confirm >"$TMP/cf"
109
+ [[ "$(python3 -c 'import json,sys;print(json.load(open(sys.argv[1]))["value"])' "$TMP/cf")" == "false" ]] && ok "a fresh store reads vault.confirm as false" || bad "default is not false: $(head -c 160 "$TMP/cf")"
110
+ export AI_VAULT_DIR="$TMP/store"
111
+
93
112
  echo "== add / list =="
94
113
  check "add needs a window for the password" 3 bash -c "'$BIN' add --name GitHub --username octo --token '$TOKEN'"
95
114
  check "add with a typed password" 0 bash -c "printf 'p1ssw0rd' | '$BIN' add --name GitHub --username octo --uri https://github.com --password-stdin --yes --token '$TOKEN' --json"
@@ -238,7 +238,10 @@ test("a session switch while the master password is being typed discards the unl
238
238
  () => "resolved",
239
239
  (error) => error.message,
240
240
  );
241
- for (let i = 0; i < 50 && !answer; i++) await new Promise((resolve) => setImmediate(resolve));
241
+ // Wait for the dialog to open, with a real deadline: a fixed number of
242
+ // setImmediate ticks raced under a full test run.
243
+ const deadline = Date.now() + 10_000;
244
+ while (!answer && Date.now() < deadline) await new Promise((resolve) => setTimeout(resolve, 5));
242
245
  assert.equal(typeof answer, "function", "the password dialog opened");
243
246
 
244
247
  await b.fire("session_switch", { reason: "new" }, ctx.ctx);
@@ -22,6 +22,11 @@ before(async () => {
22
22
  answers.master(dir, PW, PW);
23
23
  await boot.cmd("init", makeCtx().ctx);
24
24
  assert.ok(existsSync(STORE), "init created the shared store");
25
+ // The per-read window is off by default (the unlock is the approval). These
26
+ // tests are about the window itself: grant, denial, the signed relay — so
27
+ // it is turned on for this store, the way a user would.
28
+ const on = setSetting("vault.confirm", "true");
29
+ assert.equal(on.status, 0, on.stderr);
25
30
  });
26
31
 
27
32
  after(() => answers.deny(dir, false));
@@ -371,3 +376,54 @@ test("vault_get falls back to Bitwarden for a non-login hit and imports it with
371
376
  assert.equal(JSON.stringify(listed).includes("4111111111111111"), false, "list must mask the card number");
372
377
  });
373
378
 
379
+
380
+ test("two processes on one machine share the host secret: a session opened in one is usable in the other", async () => {
381
+ // Each `bind()` is a fresh extension; each VaultCli is a fresh process as far
382
+ // as the secret goes. Before, each minted its own and the second could not
383
+ // read what the first had opened — so every herdr tab asked again.
384
+ const { VaultCli } = await import("../packages/pi-ai-vault/src/cli.ts");
385
+ const { mkdtempSync, readFileSync, statSync } = await import("node:fs");
386
+ const { join } = await import("node:path");
387
+ const previous = process.env.AI_VAULT_DIR;
388
+ const store = mkdtempSync(join(process.env.TMPDIR ?? "/tmp", "ai-vault-shared-"));
389
+ process.env.AI_VAULT_DIR = store;
390
+ try {
391
+ const a = new VaultCli();
392
+ const b = new VaultCli();
393
+ assert.notEqual(a.host.value, undefined);
394
+ assert.equal(a.host.value, b.host.value, "both read the same <store>/.host");
395
+ const secret = readFileSync(join(store, ".host"), "utf8").trim();
396
+ assert.equal(secret, a.host.value);
397
+ assert.equal(statSync(join(store, ".host")).mode & 0o777, 0o600);
398
+
399
+ // A session minted under a's secret is accepted by a call made under b's.
400
+ const init = await a.json(["init", "--requester", "tab-a", "--password-stdin"], { stdin: `${PW}\n` });
401
+ const status = await b.json(["status", "--token", init.token]);
402
+ assert.equal(status.unlocked, true);
403
+ assert.equal(status.requester, "tab-a");
404
+ } finally {
405
+ if (previous === undefined) delete process.env.AI_VAULT_DIR;
406
+ else process.env.AI_VAULT_DIR = previous;
407
+ }
408
+ });
409
+
410
+ test("by default a read after unlock opens no window: the unlock is the approval (and it is audited)", async () => {
411
+ // Through the raw CLI on a fresh store, so the default is the CLI's and not
412
+ // whatever this file's other tests set on the shared one.
413
+ const { mkdtempSync, readFileSync } = await import("node:fs");
414
+ const { join } = await import("node:path");
415
+ const { spawnSync } = await import("node:child_process");
416
+ const bin = process.env.AI_VAULT_BIN;
417
+ const dir = mkdtempSync(join(process.env.TMPDIR ?? "/tmp", "ai-vault-default-"));
418
+ const run = (args, input) => spawnSync(bin, args, { input, env: { ...process.env, AI_VAULT_DIR: dir, AI_VAULT_HOST: "", AI_VAULT_HOST_SECRET: "" }, encoding: "utf8" });
419
+ assert.equal(run(["init", "--password-stdin"], `${PW}\n`).status, 0);
420
+ const token = JSON.parse(run(["unlock", "--password-stdin", "--json"], `${PW}\n`).stdout).token;
421
+ assert.equal(run(["add", "--name", "DefaultRead", "--username", "u", "--password-stdin", "--yes", "--token", token], "default-pw\n").status, 0);
422
+ // No --answer-stdin, no approval: the bare read must succeed with no window.
423
+ const read = run(["get", "DefaultRead", "--token", token, "--json"]);
424
+ assert.equal(read.status, 0, read.stderr);
425
+ assert.equal(JSON.parse(read.stdout).via, "unlocked-no-confirm");
426
+ const audit = readFileSync(join(dir, "audit.log"), "utf8");
427
+ assert.match(audit, /"event":"read_allow","item":"DefaultRead"/, "the read is still audited");
428
+ assert.match(audit, /"reason":"confirm-off"/, "and says the window was off");
429
+ });