@xiaolikt/ai-vault 0.12.3 → 0.12.4

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
 
@@ -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
  }
@@ -266,7 +286,10 @@ export class VaultCli {
266
286
  const run = await new Promise<CliRun>((resolve, reject) => {
267
287
  // A program Node will not start fails here like any other CLI failure,
268
288
  // not as a bare exception from inside the promise.
269
- const child = startCli(launch, args, { ...process.env, ...this.host.env() });
289
+ const child = startCli(launch, args, { ...process.env, ...this.host.env() }, () => {
290
+ opts.signal?.removeEventListener("abort", onAbort);
291
+ reject(new CliError(EXIT.error, undefined, `cannot run ${launch.program}: ${lastStartError}`, ""));
292
+ });
270
293
  let stdout = "";
271
294
  let stderr = "";
272
295
  const onAbort = () => child.kill("SIGKILL");
@@ -20,6 +20,7 @@ const ROOT = join(dirname(fileURLToPath(import.meta.url)), "..");
20
20
  const CLI_BINARY = cliBinary();
21
21
  const PS = join(process.env.SystemRoot ?? "C:/", "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
22
22
  const PS_ARGS = ["-NoProfile", "-NonInteractive", "-STA"];
23
+ const CSC = join(process.env.SystemRoot ?? "C:/", "Microsoft.NET", "Framework64", "v4.0.30319", "csc.exe");
23
24
  const windowsOnly = { skip: WIN32 ? false : "Windows only" };
24
25
 
25
26
  const { npmShimLaunch } = await import("../packages/pi-ai-vault/src/cli.ts");
@@ -319,7 +320,14 @@ test("Windows: a command that is killed takes what it started with it", windowsO
319
320
  if (!existsSync(bash.program)) return t.skip("no bash on this machine");
320
321
  const child = spawn(bash.program, [...bash.pre, "-c", "sleep 60 & wait"], { stdio: "ignore", windowsHide: true });
321
322
  await new Promise((resolve) => setTimeout(resolve, 1500)); // let `sleep` start
322
- killTree(child.pid);
323
+ // Asynchronous on purpose: a kill happens while the host's UI must stay live.
324
+ let ticks = 0;
325
+ const beat = setInterval(() => ticks++, 10);
326
+ const killing = killTree(child.pid);
327
+ await Promise.race([killing, new Promise((resolve) => setTimeout(resolve, 5))]);
328
+ assert.ok(ticks > 0, "the event loop kept running while the tree was being killled");
329
+ await killing;
330
+ clearInterval(beat);
323
331
  await new Promise((resolve) => setTimeout(resolve, 800));
324
332
  assert.notEqual(child.exitCode, null, "the shell itself is gone");
325
333
  const left = spawnSync(
@@ -332,99 +340,145 @@ test("Windows: a command that is killed takes what it started with it", windowsO
332
340
 
333
341
  // ---------------------------------------------------------------- the CLI's own windows
334
342
 
335
- // The scripts are taken verbatim from dialog.rs and answered by a WinForms
336
- // timer inside the window, so the real ShowDialog() and the real stdout path
337
- // are covered without anyone at the keyboard. They need a desktop; a locked
338
- // screen is fine, a service session is not.
343
+ // The windows are the CLI's own program (windows/dialog.cs): each test builds a
344
+ // copy that answers itself after a moment, so the real Form, the real IME-capable
345
+ // field and the real JSON on stdout are covered with nobody at the keyboard.
346
+ // They need a desktop; a locked screen is fine, a service session is not.
339
347
  const canShowWindows = () =>
340
348
  WIN32 &&
341
349
  spawnSync(PS, [...PS_ARGS, "-Command", "[Environment]::UserInteractive"], { encoding: "utf8", windowsHide: true, timeout: 20_000 }).stdout.trim() === "True";
342
350
  const onDesktop = { skip: WIN32 ? (canShowWindows() ? false : "no interactive session") : "Windows only" };
343
351
 
344
- /** A dialog script exactly as the Rust source holds it. */
345
- function dialogScript(name) {
346
- const source = readFileSync(join(ROOT, "crates", "ai-vault", "src", "dialog.rs"), "utf8");
347
- const match = new RegExp(`const ${name}: &str = r#"(.*?)"#;`, "s").exec(source);
348
- assert.ok(match, `${name} is in dialog.rs`);
349
- return match[1];
350
- }
352
+ /** The dialog program the CLI ships (`build.rs` compiles windows/dialog.cs). */
353
+ const DIALOG = join(ROOT, "target", "release", "dialog.exe");
351
354
 
352
- /** Answers the window in place of the user, 600 ms after it is shown. */
353
- const autoAnswer = (action) =>
354
- [" $t = New-Object System.Windows.Forms.Timer", " $t.Interval = 600", ` $t.Add_Tick({ $t.Stop(); ${action} })`, " $t.Start()"].join("\n");
355
-
356
- function showWindow(script) {
357
- return spawnSync(PS, [...PS_ARGS, "-Command", script], {
358
- encoding: "buffer",
359
- timeout: 60_000,
360
- windowsHide: true,
361
- env: {
362
- ...process.env,
363
- AI_VAULT_DLG_TITLE: "ai-vault · test window",
364
- AI_VAULT_DLG_TEXT: "master password / 主密码",
365
- AI_VAULT_DLG_SECRET: "1",
366
- AI_VAULT_DLG_CANCEL: "取消",
367
- },
368
- });
355
+ /**
356
+ * Ask the dialog program exactly as the CLI does: one JSON request on stdin,
357
+ * one JSON answer on stdout. A testing copy answers itself after a moment, so
358
+ * the suite needs nobody at the keyboard; the windows are real.
359
+ */
360
+ function askProgram(request, { action = "dialog.DialogResult = DialogResult.Cancel", ms = 400 } = {}) {
361
+ const dir = scratch();
362
+ const source = join(ROOT, "crates", "ai-vault", "windows", "dialog.cs");
363
+ const anchored = " var dialog = new Dialog(theme, request);\n var result = dialog.ShowDialog();";
364
+ // A checkout with core.autocrlf=true (GitHub's Windows runners) has CRLF
365
+ // line endings; the anchor is written with LF, so normalise before matching.
366
+ const text = readFileSync(source, "utf8").replace(/\r\n/g, "\n");
367
+ const occurrences = text.split(anchored).length - 1;
368
+ assert.equal(occurrences, 1, "dialog.cs still shows the dialog the same way");
369
+ const script = text.replace(anchored, `${anchored.replace("var result = dialog.ShowDialog();", "")}
370
+ var auto = new Timer(); auto.Interval = ${ms};
371
+ auto.Tick += delegate {
372
+ auto.Stop();
373
+ ${action.replace(/;?\s*$/, ";")}
374
+ dialog.Close();
375
+ };
376
+ auto.Start();
377
+ var result = dialog.ShowDialog();`);
378
+ const file = join(dir, "auto.cs");
379
+ writeFileSync(file, script);
380
+ const exe = join(dir, "auto.exe");
381
+ const build = spawnSync(CSC, ["/nologo", "/target:winexe", "/optimize+", `/out:${exe}`, "/r:System.Windows.Forms.dll", "/r:System.Drawing.dll", file], { encoding: "utf8", timeout: 120_000 });
382
+ assert.equal(build.status, 0, build.stderr || build.stdout);
383
+ const run = spawnSync(exe, [], { input: Buffer.from(JSON.stringify(request), "utf8"), timeout: 120_000, windowsHide: true });
384
+ // UTF-8 on the wire, checked as bytes: decoding a mojibake stream would hide
385
+ // exactly the bug this suite exists to catch.
386
+ const out = run.stdout.toString("utf8");
387
+ assert.ok(new TextEncoder().encode(out).every((b) => b !== 0xef) || !out.includes("�"), "the answer is UTF-8, not a code-page guess");
388
+ const value = /"value":"(.*?)"/s.exec(out)?.[1] ?? "";
389
+ removeScratch(dir);
390
+ return { status: run.status, raw: out, json: out.startsWith("{") ? JSON.parse(out) : undefined, value: JSON.parse(`"${value}"`) };
369
391
  }
370
392
 
371
- const SHOWN = " if ($f.ShowDialog() -eq 'OK') {";
372
- const passwordWindow = (action) => {
373
- const script = dialogScript("PRELUDE") + dialogScript("PREAMBLE");
374
- assert.ok(script.includes(SHOWN), "the password window still calls ShowDialog()");
375
- return script.replace(SHOWN, `${autoAnswer(action)}\n${SHOWN}`);
376
- };
393
+ const PASSWORD = { kind: "password", title: "ai-vault · 测试窗口", label: "本地库主密码", mask: true, reveal: true, ok: "确定", cancel: "取消", show: "显示" };
394
+ const ENTRY = { ...PASSWORD, title: "ai-vault · 保存", label: "条目密码", reveal: false };
395
+ const CONFIRM = { kind: "confirm", title: "ai-vault · 读取", label: "条目: github", allow: "允许", deny: "拒绝" };
396
+ /** The text box of the window, found by the name the program gives it. */
397
+ const BOX = 'dialog.Controls.Find("value", true)[0]';
398
+ /** C# source for "set the box to this text and answer OK". Only the escapes a
399
+ * password can contain are needed: a quote, or a backslash. */
400
+ function setText(text) {
401
+ const escaped = text.split("\\").join("\\\\").split('"').join('\\"');
402
+ return `${BOX}.Text = "${escaped}"; dialog.DialogResult = DialogResult.OK;`;
403
+ }
377
404
 
378
405
  test("Windows: the password window answers in UTF-8, whatever the console's code page", onDesktop, () => {
379
406
  const value = "密码测试-Pässw0rd";
380
- // The field must not be a password edit control (Windows turns the IME off
381
- // there): the text is hidden by colour, and bullets are drawn over the field.
382
- const kept = [
383
- "if ($box.UseSystemPasswordChar) { throw 'the field is a password edit control: no IME there' }",
384
- "if ($box.ForeColor -ne $box.BackColor) { throw 'the typed text is visible' }",
385
- `$box.Text = '${value}'`,
386
- "if ($mask.Text -notmatch '●') { throw 'no bullets are drawn over the field' }",
387
- "if ($mask.Parent.Controls.GetChildIndex($mask) -ge $mask.Parent.Controls.GetChildIndex($box)) { throw 'the bullets are behind the text box: Controls.Add puts a control at the back' }",
388
- "$f.DialogResult = 'OK'",
389
- ].join("; ");
390
- const r = showWindow(passwordWindow(kept));
391
- assert.equal(r.status, 0, r.stderr.toString());
392
- assert.equal(new TextDecoder().decode(r.stdout), value);
407
+ const answer = askProgram(PASSWORD, { action: setText(value) });
408
+ assert.equal(answer.json?.ok, true, answer.raw);
409
+ assert.equal(answer.json?.on, "a screen");
410
+ assert.equal(answer.value, value, "a non-ASCII password survives the round trip");
411
+ });
412
+
413
+ test("Windows: the program says when it has no screen, so the CLI can fall back", onDesktop, () => {
414
+ const probe = spawnSync(DIALOG, ["--probe"], { encoding: "utf8", timeout: 30_000 });
415
+ assert.equal(probe.stdout, "on");
416
+ // and a request carries the same answer, so the CLI can tell "no screen" from "cancelled"
417
+ const answer = askProgram(PASSWORD);
418
+ assert.equal(answer.json?.on, "a screen");
419
+ assert.equal(answer.json?.cancelled, true);
393
420
  });
394
421
 
395
- test("Windows: cancel and an empty field end the prompt cleanly (exit 1 / empty, nothing on stderr)", onDesktop, () => {
396
- const cancel = showWindow(passwordWindow("$f.DialogResult = 'Cancel'"));
397
- assert.equal(cancel.status, 1);
398
- assert.equal(cancel.stdout.length, 0);
399
- assert.equal(cancel.stderr.length, 0);
400
- const empty = showWindow(passwordWindow("$box.Text = ''; $f.DialogResult = 'OK'"));
401
- assert.equal(empty.status, 0);
402
- assert.equal(empty.stdout.length, 0);
422
+ test("Windows: the link that shows what was typed is there for a master password, and not for an entry's", onDesktop, () => {
423
+ const links = (request) => (askProgram(request).raw && readDump(request));
424
+ const withLink = spawnSync(DIALOG, [], { input: JSON.stringify(PASSWORD), encoding: "utf8", timeout: 5_000 });
425
+ void withLink; // (a real window would wait; the shape is checked through the testing copy below)
426
+ const shape = (request) => {
427
+ const dir = scratch();
428
+ try {
429
+ const source = readFileSync(join(ROOT, "crates", "ai-vault", "windows", "dialog.cs"), "utf8");
430
+ const anchor = " var dialog = new Dialog(theme, request);";
431
+ const probe = `${anchor}
432
+ var seen = new System.Text.StringBuilder();
433
+ var t = new Timer(); t.Interval = 500;
434
+ t.Tick += delegate {
435
+ t.Stop();
436
+ foreach (Control c in dialog.Controls) if (c is LinkLabel) seen.Append("link[").Append(c.Text).Append("] colour=").Append(c.ForeColor.ToArgb().ToString("X8"));
437
+ File.WriteAllText(Environment.GetEnvironmentVariable("AV_DUMP"), seen.ToString());
438
+ dialog.DialogResult = DialogResult.Cancel; dialog.Close();
439
+ };
440
+ t.Start();`;
441
+ const file = join(dir, "shape.cs");
442
+ writeFileSync(file, source.replace(anchor, probe));
443
+ const exe = join(dir, "shape.exe");
444
+ const build = spawnSync(CSC, ["/nologo", "/target:winexe", "/optimize+", `/out:${exe}`, "/r:System.Windows.Forms.dll", "/r:System.Drawing.dll", file], { encoding: "utf8", timeout: 120_000 });
445
+ assert.equal(build.status, 0, build.stderr || build.stdout);
446
+ const dump = join(dir, "dump.txt");
447
+ spawnSync(exe, [], { input: JSON.stringify(request), encoding: "utf8", timeout: 60_000, env: { ...process.env, AV_DUMP: dump } });
448
+ return existsSync(dump) ? readFileSync(dump, "utf8") : "";
449
+ } finally {
450
+ removeScratch(dir);
451
+ }
452
+ };
453
+ const master = shape(PASSWORD);
454
+ assert.match(master, /link\[显示\]/, "a master password can be shown");
455
+ assert.match(master, /colour=FF[0-9A-F]{6}/, "and the link is drawn in a colour of its own, not the window's text colour");
456
+ assert.doesNotMatch(shape(ENTRY), /link\[/, "an entry's password cannot");
403
457
  });
404
458
 
405
- test("Windows: a window that cannot open exits 2; a script that will not parse exits 1 with the error on stderr", onDesktop, () => {
406
- const script = dialogScript("PRELUDE") + dialogScript("PREAMBLE");
407
- // A policy that forbids Add-Type, simulated by shadowing the cmdlet.
408
- const forbidden = showWindow("function Add-Type { throw 'Add-Type is blocked by policy (simulated)' }\n" + script);
409
- assert.equal(forbidden.status, 2, "reported as no window, which is needs-ui to the host");
410
- assert.match(forbidden.stderr.toString(), /blocked by policy/);
411
- // WinForms that will not load.
412
- const missing = showWindow(script.replace("System.Windows.Forms, System.Drawing", "System.Windows.Forms.NoSuchAssembly"));
413
- assert.equal(missing.status, 2);
414
- // PowerShell's own parse error is exit 1: only the text on stderr tells it from a cancel.
415
- const unparsable = showWindow(script + "\nif ( { not powershell\n");
416
- assert.equal(unparsable.status, 1);
417
- assert.notEqual(unparsable.stderr.toString().trim(), "");
459
+ test("Windows: Deny is the default, and only Allow answers true", onDesktop, () => {
460
+ const none = askProgram(CONFIRM, { action: "dialog.DialogResult = DialogResult.Cancel" });
461
+ assert.equal(none.json?.ok, false, "a closed window is never a yes");
462
+ const allow = askProgram(CONFIRM, { action: "dialog.DialogResult = DialogResult.OK" });
463
+ assert.equal(allow.json?.ok, true, "Allow");
418
464
  });
419
465
 
420
- test("Windows: the confirm window is one of its own: Enter is Deny, a click on Allow is the only way to exit 0", onDesktop, () => {
421
- const script = dialogScript("PRELUDE") + dialogScript("CONFIRM");
422
- assert.match(script, /\$f\.AcceptButton = \$deny/, "Enter is the safe answer");
423
- assert.match(script, /\$f\.CancelButton = \$deny/, "Esc is the safe answer");
424
- const shown = " if ($f.ShowDialog() -eq 'OK') { exit 0 }";
425
- assert.ok(script.includes(shown), "the confirm window still ends in ShowDialog()");
426
- const answer = (click) => showWindow(script.replace(shown, `${autoAnswer(click)}\n${shown}`)).status;
427
- assert.notEqual(answer("$f.Close()"), 0, "a closed window must never read as approval");
428
- assert.equal(answer("$deny.PerformClick()"), 1, "Deny");
429
- assert.equal(answer("$allow.PerformClick()"), 0, "Allow");
466
+ test("Windows: a bw that exists but will not start is reported as such, not as missing", windowsOnly, async (t) => {
467
+ if (!WIN32) return t.skip();
468
+ // A bw.cmd whose target is not npm's format, first on PATH: it is found, and it cannot start.
469
+ const dir = scratch();
470
+ const saved = { PATH: process.env.PATH, APPDATA: process.env.APPDATA, USERPROFILE: process.env.USERPROFILE };
471
+ try {
472
+ writeFileSync(join(dir, "bw.cmd"), "@ECHO off\r\nsomething that is not npm's wrapper\r\n");
473
+ process.env.PATH = dir;
474
+ process.env.USERPROFILE = join(dir, "home"); // ~/.nvm is searched under it
475
+ // resolveBw caches what it found once; reload the module for this one.
476
+ const mod = await import(`${pathToFileURL(join(ROOT, "packages", "pi-ai-vault", "src", "bitwarden.ts")).href}?fresh=${Date.now()}`);
477
+ const error = await mod.resolveBw().then(() => undefined, (e) => e);
478
+ assert.ok(error, "it must not resolve");
479
+ assert.match(error.message, /does not start|not found/);
480
+ } finally {
481
+ Object.assign(process.env, saved);
482
+ removeScratch(dir);
483
+ }
430
484
  });