@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.
@@ -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
  });