@xiaolikt/ai-vault 0.4.1 → 0.5.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.
@@ -13,7 +13,15 @@
13
13
  */
14
14
  import type { ExtensionAPI, ExtensionCommandContext, ExtensionToolContext, ToolDefinition } from "@earendil-works/pi-coding-agent";
15
15
  import { Type } from "typebox";
16
- import { newBwState, pullBitwardenLogins, queryBitwarden, registerBitwarden, type BitwardenMeta, type BwState } from "./bitwarden.js";
16
+ import {
17
+ lookupBitwardenLogin,
18
+ newBwState,
19
+ pullBitwardenLogins,
20
+ queryBitwarden,
21
+ registerBitwarden,
22
+ type BitwardenMeta,
23
+ type BwState,
24
+ } from "./bitwarden.js";
17
25
  import { CliError, VaultCli } from "./cli.js";
18
26
  import { isOmpHost, onSessionLeave, sessionLabel, subagentId, withTier } from "./host.js";
19
27
  import { confirmWindow, promptSecret, promptText, type PromptHost } from "./prompt.js";
@@ -22,21 +30,28 @@ type Ctx = ExtensionToolContext | ExtensionCommandContext;
22
30
 
23
31
  const GRANT_MS_DEFAULT = 5 * 60_000;
24
32
 
33
+ type UnlockModeName = "never" | "time" | "session";
34
+
25
35
  interface StatusResult {
26
36
  ok: boolean;
27
37
  unlocked: boolean;
28
38
  items: number;
29
39
  requester: string;
30
40
  idleMs: number;
31
- expiresAt: number;
41
+ expiresAt: number | null;
42
+ mode: UnlockModeName;
43
+ hours: number;
44
+ auto: boolean;
32
45
  grants: Record<string, { expiresAt: number; leftMs: number }>;
33
46
  }
34
47
 
35
48
  interface UnlockResult {
36
49
  ok: boolean;
37
50
  token: string;
38
- expiresAt: number;
51
+ expiresAt: number | null;
39
52
  items: number;
53
+ mode?: UnlockModeName;
54
+ auto?: boolean;
40
55
  }
41
56
 
42
57
  interface ListResult {
@@ -71,6 +86,10 @@ interface Scope {
71
86
  epoch: number;
72
87
  /** Cached entry count for the status line. */
73
88
  items: number;
89
+ /** The machine-wide unlock policy, as the CLI last reported it. */
90
+ mode?: UnlockModeName;
91
+ /** True when reads use the machine-wide session instead of a token. */
92
+ auto?: boolean;
74
93
  unlocking?: Promise<boolean>;
75
94
  }
76
95
 
@@ -86,12 +105,15 @@ const note = (ctx: Ctx, text: string, level: "info" | "warning" | "error" = "inf
86
105
 
87
106
  const describe = (error: unknown): string => (error instanceof Error ? error.message : String(error));
88
107
 
89
- interface Failure {
108
+ /** What a tool call hands back; every error path uses the same shape. */
109
+ interface ToolOutcome {
90
110
  content: { type: "text"; text: string }[];
91
- details: { ok: false; denied?: boolean };
92
- isError: true;
111
+ details: { ok?: boolean; denied?: boolean; item?: string; via?: string; count?: number };
112
+ isError?: boolean;
93
113
  }
94
114
 
115
+ type Failure = ToolOutcome;
116
+
95
117
  const fail = (text: string, denied = false): Failure => ({
96
118
  content: [{ type: "text" as const, text }],
97
119
  details: { ok: false, ...(denied ? { denied: true } : {}) },
@@ -127,6 +149,9 @@ async function lockNow(scope: Scope): Promise<void> {
127
149
  }
128
150
  }
129
151
 
152
+ /** Args for a CLI call: this binding's token, or the machine-wide session. */
153
+ const tokenArgs = (scope: Scope): string[] => (scope.token ? ["--token", scope.token] : []);
154
+
130
155
  /** Make this binding's unlock happen; never throws. */
131
156
  async function ensureUnlocked(scope: Scope, ctx: Ctx, signal?: AbortSignal): Promise<boolean> {
132
157
  if (!cli.available) {
@@ -140,6 +165,8 @@ async function ensureUnlocked(scope: Scope, ctx: Ctx, signal?: AbortSignal): Pro
140
165
  try {
141
166
  const status = await cli.json<StatusResult>(["status", "--token", scope.token], { signal });
142
167
  scope.items = status.items;
168
+ scope.mode = status.mode;
169
+ scope.auto = false;
143
170
  return true;
144
171
  } catch (error) {
145
172
  if (!(error instanceof CliError) || !error.auth) {
@@ -153,6 +180,24 @@ async function ensureUnlocked(scope: Scope, ctx: Ctx, signal?: AbortSignal): Pro
153
180
  }
154
181
  }
155
182
  }
183
+ // `never` mode keeps a machine-wide session: no token, no window. Ask the
184
+ // CLI before opening anything, so that mode really is password-free.
185
+ try {
186
+ const status = await cli.json<StatusResult>(["status"], { signal });
187
+ scope.items = status.items;
188
+ scope.mode = status.mode;
189
+ scope.auto = status.auto;
190
+ return true;
191
+ } catch (error) {
192
+ if (error instanceof CliError && /not initialized/i.test(error.message)) {
193
+ note(ctx, NOT_INITIALIZED, "warning");
194
+ return false;
195
+ }
196
+ if (!(error instanceof CliError) || !error.auth) {
197
+ note(ctx, `ai-vault: ${describe(error)}`, "error");
198
+ return false;
199
+ }
200
+ }
156
201
  const attempt = async (password?: string): Promise<UnlockResult> => {
157
202
  const args = ["unlock", "--requester", sessionLabel(ctx)];
158
203
  if (password !== undefined) args.push("--password-stdin");
@@ -179,7 +224,11 @@ async function ensureUnlocked(scope: Scope, ctx: Ctx, signal?: AbortSignal): Pro
179
224
  await cli.run(["lock", "--token", result.token]).catch(() => undefined);
180
225
  return false;
181
226
  }
182
- scope.token = result.token;
227
+ scope.mode = result.mode;
228
+ scope.auto = result.mode === "never";
229
+ // In `never` mode the CLI wrote the machine-wide session; keeping a
230
+ // per-binding token would bring back a confirm window on every read.
231
+ scope.token = result.mode === "never" ? undefined : result.token;
183
232
  scope.items = result.items;
184
233
  return true;
185
234
  } catch (error) {
@@ -236,53 +285,146 @@ const vaultGetParams = Type.Object({
236
285
  reason: Type.Optional(Type.String({ description: "Why this secret is needed (shown to the user in the confirm window)" })),
237
286
  });
238
287
  type VaultGetDetails = { ok?: boolean; denied?: boolean; item?: string; via?: string };
239
- function vaultGetTool(scope: Scope): ToolDefinition<typeof vaultGetParams, VaultGetDetails> {
288
+
289
+ /**
290
+ * The local vault is the first stop; Bitwarden is the fallback. A hit there is
291
+ * offered to the user twice: read it this once, then optionally import it so
292
+ * later reads never touch Bitwarden.
293
+ */
294
+ async function bitwardenFallback(
295
+ scope: Scope,
296
+ ctx: Ctx,
297
+ bw: BwState,
298
+ name: string,
299
+ reason: string | undefined,
300
+ localMiss: string,
301
+ signal?: AbortSignal,
302
+ ): Promise<ToolOutcome> {
303
+ const missing = localMiss;
304
+ let hit;
305
+ try {
306
+ hit = await lookupBitwardenLogin(bw, ctx, name, signal);
307
+ } catch (error) {
308
+ return fail(`${missing} — the Bitwarden lookup failed: ${describe(error)}`);
309
+ }
310
+ if (!hit) return fail(`${missing} — not in Bitwarden either${reason ? ` (reason: ${reason})` : ""}`);
311
+
312
+ const label = `${hit.name}${hit.username ? ` user:${hit.username}` : ""}`;
313
+ const allow = await confirmWindow(
314
+ dialogs(ctx),
315
+ "pi-ai-vault · Bitwarden 里找到",
316
+ `本地库没有「${name}」,Bitwarden 里有:\n${label}\n\n读取这一次吗?`,
317
+ signal,
318
+ );
319
+ if (!allow) return fail(`user denied reading "${hit.name}" from Bitwarden — do not retry`, true);
320
+
321
+ const importIt = await confirmWindow(
322
+ dialogs(ctx),
323
+ "pi-ai-vault · 导入到 ai-vault",
324
+ `把「${hit.name}」写进 ai-vault 吗?\n\n允许 → 以后直接读本地库(按当前解锁模式,可能免密)\n拒绝 → 只用这一次,不写入本地库`,
325
+ signal,
326
+ );
327
+ if (importIt) {
328
+ try {
329
+ const saved = await cli.json<SaveResult>(["save", "--yes", ...tokenArgs(scope)], {
330
+ stdin: JSON.stringify([
331
+ {
332
+ name: hit.name,
333
+ username: hit.username || undefined,
334
+ password: hit.password,
335
+ uris: hit.uris,
336
+ source: { kind: "bitwarden", id: hit.id },
337
+ },
338
+ ]),
339
+ signal,
340
+ });
341
+ scope.items += saved.count;
342
+ setStatus(ctx, scope);
343
+ } catch (error) {
344
+ return fail(`found "${hit.name}" in Bitwarden but could not import it: ${describe(error)}`);
345
+ }
346
+ return {
347
+ content: [
348
+ {
349
+ type: "text" as const,
350
+ text: JSON.stringify(
351
+ { name: hit.name, username: hit.username || undefined, password: hit.password, uris: hit.uris, via: "imported-from-bitwarden" },
352
+ null,
353
+ 1,
354
+ ),
355
+ },
356
+ ],
357
+ details: { item: hit.name, via: "imported-from-bitwarden" },
358
+ };
359
+ }
360
+
361
+ return {
362
+ content: [
363
+ {
364
+ type: "text" as const,
365
+ text: JSON.stringify(
366
+ { name: hit.name, username: hit.username || undefined, password: hit.password, uris: hit.uris, via: "bitwarden-once" },
367
+ null,
368
+ 1,
369
+ ),
370
+ },
371
+ ],
372
+ details: { item: hit.name, via: "bitwarden-once" },
373
+ };
374
+ }
375
+
376
+ function vaultGetTool(scope: Scope, bw: BwState): ToolDefinition<typeof vaultGetParams, VaultGetDetails> {
377
+ const viaOf = (stdout: string): string => {
378
+ try {
379
+ return (JSON.parse(stdout) as { via?: string }).via ?? "grant";
380
+ } catch {
381
+ return "grant";
382
+ }
383
+ };
240
384
  const tool: ToolDefinition<typeof vaultGetParams, VaultGetDetails> = {
241
385
  name: "vault_get",
242
- label: "Vault: read a local secret",
386
+ label: "Vault: read a secret (local first, Bitwarden second)",
243
387
  description:
244
- "Read one secret from the machine-wide ai-vault store (not Bitwarden). " +
245
- "The user must approve a desktop confirm window; the grant then lasts 5 minutes for the session or subagent that asked. " +
246
- "If the user denies, do not retry. Prefer bw_run when the secret should stay out of the chat.",
388
+ "Read one secret. The machine-wide ai-vault store is asked first; that is the vault the agent may use freely, and in `never` unlock mode it answers without any window. " +
389
+ "If the entry is not local, Bitwarden is searched: the user is shown the hit, then asked whether to read it once or import it into ai-vault. " +
390
+ "If the user denies, do not retry. Use bw_run when the value must never enter the chat.",
391
+ promptSnippet: "Read a secret: local vault first, then Bitwarden (with an import offer).",
247
392
  parameters: vaultGetParams,
248
393
  async execute(_id, params, signal, _onUpdate, ctx) {
249
394
  if (!(await ensureUnlocked(scope, ctx, signal))) return fail(LOCKED);
250
- const args = ["get", params.name, "--token", scope.token!];
251
- if (params.reason) args.push("--reason", params.reason);
395
+ const base = ["get", params.name, ...(params.reason ? ["--reason", params.reason] : []), ...tokenArgs(scope)];
252
396
  try {
253
- const viaOf = (stdout: string): string => {
254
- try {
255
- return (JSON.parse(stdout) as { via?: string }).via ?? "grant";
256
- } catch {
257
- return "grant";
258
- }
259
- };
260
397
  try {
261
- const run = await cli.run([...args, "--json"], { signal });
262
- setStatus(ctx, scope, "·granted");
398
+ const run = await cli.run([...base, "--json"], { signal });
399
+ setStatus(ctx, scope, "·ok");
263
400
  return {
264
401
  content: [{ type: "text" as const, text: run.stdout.trim() }],
265
402
  details: { item: params.name, via: viaOf(run.stdout) },
266
403
  };
267
404
  } catch (error) {
268
- if (!(error instanceof CliError) || error.needsUi !== "confirm") throw error;
269
- const sub = subagentId(ctx);
270
- const allowed = await confirmWindow(
271
- dialogs(ctx),
272
- "ai-vault · 读取本地密码",
273
- `条目: ${params.name}\n请求方: ${sub ? `子代理 ${sub}` : "主会话"}\n原因: ${params.reason ?? "(未说明)"}\n\n` +
274
- "允许后 5 分钟内同一请求方可再次读取。密码会进入对话。",
275
- signal,
276
- );
277
- const run = await cli.run([...args, "--json", "--answer-stdin"], {
278
- stdin: allowed ? "y\n" : "n\n",
279
- signal,
280
- });
281
- setStatus(ctx, scope, "·granted");
282
- return {
283
- content: [{ type: "text" as const, text: run.stdout.trim() }],
284
- details: { item: params.name, via: viaOf(run.stdout) },
285
- };
405
+ if (error instanceof CliError && error.needsUi === "confirm") {
406
+ const sub = subagentId(ctx);
407
+ const allowed = await confirmWindow(
408
+ dialogs(ctx),
409
+ "ai-vault · 读取本地密码",
410
+ `条目: ${params.name}\n请求方: ${sub ? `子代理 ${sub}` : "主会话"}\n原因: ${params.reason ?? "(未说明)"}\n\n` +
411
+ "允许后 5 分钟内同一请求方可再次读取。密码会进入对话。",
412
+ signal,
413
+ );
414
+ const run = await cli.run([...base, "--json", "--answer-stdin"], {
415
+ stdin: allowed ? "y\n" : "n\n",
416
+ signal,
417
+ });
418
+ setStatus(ctx, scope, "·granted");
419
+ return {
420
+ content: [{ type: "text" as const, text: run.stdout.trim() }],
421
+ details: { item: params.name, via: viaOf(run.stdout) },
422
+ };
423
+ }
424
+ if (error instanceof CliError && /^no such entry/.test(error.message)) {
425
+ return await bitwardenFallback(scope, ctx, bw, params.name, params.reason, error.message, signal);
426
+ }
427
+ throw error;
286
428
  }
287
429
  } catch (error) {
288
430
  if (error instanceof CliError && error.denied) setStatus(ctx, scope, "·denied");
@@ -485,6 +627,7 @@ async function importBitwarden(
485
627
  const HELP = [
486
628
  "/vault init 创建全机共享的本地加密库(弹出窗口设置主密码)",
487
629
  "/vault unlock | lock 解锁 / 锁定(清空本会话的授权)",
630
+ "/vault mode [never|time|session] 查看/切换解锁模式(切换要主密码)",
488
631
  "/vault status 状态与授权剩余时间",
489
632
  "/vault list 本地条目元数据",
490
633
  "/vault add [名称] 新增本地条目(用户名、密码在弹窗里输入)",
@@ -570,33 +713,94 @@ function commandHandler(scope: Scope, bw: BwState) {
570
713
  return;
571
714
  }
572
715
  case "status": {
573
- if (!scope.token) {
574
- note(ctx, [`store: ${cli.dir}/store.json`, `session: ${label}`, "state: locked"].join("\n"));
575
- setStatus(ctx, scope);
576
- return;
577
- }
578
716
  try {
579
- const status = await cli.json<StatusResult>(["status", "--token", scope.token]);
717
+ const status = await cli.json<StatusResult>(["status", ...tokenArgs(scope)]);
580
718
  scope.items = status.items;
719
+ scope.mode = status.mode;
720
+ scope.auto = status.auto;
721
+ setStatus(ctx, scope);
722
+ const expiry = status.expiresAt
723
+ ? `${Math.max(0, Math.round((status.expiresAt - Date.now()) / 1000))}s`
724
+ : "never";
725
+ const how =
726
+ status.mode === "never"
727
+ ? "never(免密)"
728
+ : status.mode === "time"
729
+ ? `time(每 ${status.hours}h 要一次密码)`
730
+ : "session(每个会话一次)";
581
731
  const lines = [
582
732
  `store: ${cli.dir}/store.json`,
583
733
  `session: ${status.requester}`,
584
734
  "state: unlocked",
735
+ `mode: ${how}`,
585
736
  `items: ${status.items}`,
586
- `expires: ${Math.max(0, Math.round((status.expiresAt - Date.now()) / 1000))}s (idle lock ${Math.round(status.idleMs / 1000)}s)`,
737
+ `expires: ${expiry}`,
587
738
  ];
588
739
  for (const [name, grant] of Object.entries(status.grants)) {
589
740
  lines.push(`grant: ${name} (${Math.ceil(grant.leftMs / 1000)}s left)`);
590
741
  }
591
742
  note(ctx, lines.join("\n"));
592
- setStatus(ctx, scope);
593
743
  } catch (error) {
594
744
  scope.token = undefined;
595
- note(ctx, `ai-vault: ${describe(error)}`, "warning");
745
+ note(
746
+ ctx,
747
+ [
748
+ `store: ${cli.dir}/store.json`,
749
+ `session: ${label}`,
750
+ "state: locked",
751
+ `ai-vault: ${describe(error)}`,
752
+ ].join("\n"),
753
+ "warning",
754
+ );
596
755
  setStatus(ctx, scope);
597
756
  }
598
757
  return;
599
758
  }
759
+ case "mode": {
760
+ const [sub, hoursArg] = rest;
761
+ if (!sub || sub === "get" || sub === "status") {
762
+ try {
763
+ const current = await cli.json<{ mode: string; hours: number; auto: boolean }>(["mode"]);
764
+ note(
765
+ ctx,
766
+ [
767
+ `mode: ${current.mode}`,
768
+ `hours: ${current.hours}(time 模式用)`,
769
+ `machine-wide session: ${current.auto ? "yes(免密)" : "no"}`,
770
+ "",
771
+ "/vault mode never|time|session [小时] 切换(要主密码)",
772
+ ].join("\n"),
773
+ );
774
+ } catch (error) {
775
+ note(ctx, `ai-vault: ${describe(error)}`, "error");
776
+ }
777
+ return;
778
+ }
779
+ if (!["never", "time", "session", "no-password"].includes(sub)) {
780
+ note(ctx, "用法: /vault mode [never|time|session] [小时]", "warning");
781
+ return;
782
+ }
783
+ const args = ["mode", "set", sub];
784
+ if (hoursArg) args.push("--hours", hoursArg);
785
+ try {
786
+ const run = await cli.withPassword(args, () => promptSecret(dialogs(ctx), "ai-vault · 主密码", "切换解锁模式"));
787
+ const result = JSON.parse(run.stdout) as { mode: UnlockModeName; hours: number; auto: boolean };
788
+ await lockNow(scope);
789
+ scope.mode = result.mode;
790
+ scope.auto = result.auto;
791
+ setStatus(ctx, scope);
792
+ const how =
793
+ result.mode === "never"
794
+ ? "以后免密(密钥已写盘,任何能读你文件的程序都能读到库里的密码)"
795
+ : result.mode === "time"
796
+ ? `以后每 ${result.hours} 小时要一次密码`
797
+ : "以后每个会话要一次密码";
798
+ note(ctx, `mode → ${result.mode},${how}`);
799
+ } catch (error) {
800
+ note(ctx, `ai-vault: ${error instanceof CliError && error.denied ? "已取消" : describe(error)}`, "warning");
801
+ }
802
+ return;
803
+ }
600
804
  case "list": {
601
805
  if (!(await ensureUnlocked(scope, ctx))) return;
602
806
  try {
@@ -752,7 +956,7 @@ export default function aiVault(pi: ExtensionAPI): void {
752
956
  const scope: Scope = { token: undefined, epoch: 0, items: 0, unlocking: undefined };
753
957
  const bw = newBwState();
754
958
  pi.registerTool(vaultListTool(scope));
755
- pi.registerTool(vaultGetTool(scope));
959
+ pi.registerTool(vaultGetTool(scope, bw));
756
960
  pi.registerTool(vaultAddTool(scope));
757
961
  pi.registerTool(vaultImportTool(scope, bw));
758
962
  registerBitwarden(pi, bw, omp);
package/test/cli.sh CHANGED
@@ -113,6 +113,21 @@ assert not any("p1ssw0rd" in json.dumps(e) or "exp-pass" in json.dumps(e) for e
113
113
  PY
114
114
  grep -q 'p1ssw0rd' "$AI_VAULT_DIR/audit.log" && bad "a secret reached the audit log" || ok "no secret in audit.log"
115
115
 
116
+ echo "== unlock modes =="
117
+ check "mode get works without a token" 0 "$BIN" mode --json
118
+ check "switching the mode needs the password" 3 "$BIN" mode set never
119
+ check "a wrong password does not switch it" 5 bash -c "printf 'wrong password' | '$BIN' mode set never --password-stdin"
120
+ check "never mode is set with the password" 0 bash -c "printf 'correct horse' | '$BIN' mode set never --password-stdin --json"
121
+ check "never mode needs no token" 0 "$BIN" status --json
122
+ printf 'correct horse' | "$BIN" unlock --password-stdin --json >"$TMP/u2" 2>&1
123
+ python3 - "$TMP/u2" <<'PY' && ok "unlock reports the mode" || bad "unlock output is wrong"
124
+ import json,sys
125
+ d = json.load(open(sys.argv[1]))
126
+ assert d["mode"] == "never" and d["auto"] is True, d
127
+ PY
128
+ check "back to session mode" 0 bash -c "printf 'correct horse' | '$BIN' mode set session --password-stdin --json"
129
+ check "session mode needs a token again" 5 "$BIN" status
130
+
116
131
  echo "== doctor =="
117
132
  check "doctor runs" 0 "$BIN" doctor --json
118
133
 
package/test/smoke.sh CHANGED
@@ -35,13 +35,13 @@ case "$HOST" in
35
35
  MODEL_ARGS=()
36
36
  [[ -n "${OMP_MODEL:-}" ]] && MODEL_ARGS=(--model "$OMP_MODEL")
37
37
  (cd "$STATE/cwd" && timeout 300 omp --session-dir "$STATE/sessions" --no-extensions \
38
- -e "$ROOT/src/index.ts" "${MODEL_ARGS[@]}" --auto-approve --mode json -p "$PROMPT" 2>&1) >"$STATE/events"
38
+ -e "$ROOT/packages/pi-ai-vault/src/index.ts" "${MODEL_ARGS[@]}" --auto-approve --mode json -p "$PROMPT" 2>&1) >"$STATE/events"
39
39
  ;;
40
40
  pi)
41
41
  MODEL_ARGS=()
42
42
  [[ -n "${PI_MODEL:-}" ]] && MODEL_ARGS=(--model "$PI_MODEL")
43
43
  (cd "$STATE/cwd" && timeout 300 pi --no-session --no-extensions \
44
- -e "$ROOT/src/index.ts" "${MODEL_ARGS[@]}" --mode json -p "$PROMPT" 2>&1) >"$STATE/events"
44
+ -e "$ROOT/packages/pi-ai-vault/src/index.ts" "${MODEL_ARGS[@]}" --mode json -p "$PROMPT" 2>&1) >"$STATE/events"
45
45
  ;;
46
46
  *)
47
47
  echo "usage: $0 [omp|pi]" >&2
@@ -8,7 +8,7 @@ import { spawnSync } from "node:child_process";
8
8
  import { answers, bind, cleanUpOnExit, dialogTrace, makeCtx, passwordPrompts, subCtx, textOf, useMocks } from "./helpers.mjs";
9
9
 
10
10
  const dir = useMocks();
11
- const { default: ompVault } = await import("../src/index.ts");
11
+ const { default: ompVault } = await import("../packages/pi-ai-vault/src/index.ts");
12
12
  cleanUpOnExit(dir);
13
13
 
14
14
  const SECRET = "supersecret-value-123";
package/tests/helpers.mjs CHANGED
@@ -58,6 +58,8 @@ export const answers = {
58
58
  /** The dialog that types a new entry's password. */
59
59
  entryPassword: (dir, password) => writeFileSync(join(dir, "entry-passwords"), `${password}\n`),
60
60
  entries: (dir, ...lines) => writeFileSync(join(dir, "entries"), lines.map((l) => `${l}\n`).join("")),
61
+ /** --question answers, one per window ("y"/"n"). */
62
+ questions: (dir, ...lines) => writeFileSync(join(dir, "questions"), lines.map((l) => `${l}\n`).join("")),
61
63
  deny: (dir, on = true) =>
62
64
  on ? writeFileSync(join(dir, "deny"), "") : rmSync(join(dir, "deny"), { force: true }),
63
65
  };
@@ -1,6 +1,6 @@
1
1
  import { test } from "node:test";
2
2
  import assert from "node:assert/strict";
3
- import { bitwardenLogins, filterLogins } from "../src/import-map.ts";
3
+ import { bitwardenLogins, filterLogins } from "../packages/pi-ai-vault/src/import-map.ts";
4
4
 
5
5
  const item = (name, extra = {}) => ({
6
6
  id: extra.id,
@@ -6,7 +6,8 @@
6
6
  # when that file is missing or empty; any other password dialog
7
7
  # answers with the first line of $OMP_VAULT_MOCK/entry-passwords
8
8
  # --entry first line of $OMP_VAULT_MOCK/entries; empty when the file is gone
9
- # --question allow, unless $OMP_VAULT_MOCK/deny exists (then exit 1)
9
+ # --question first line of $OMP_VAULT_MOCK/questions ("n" denies), else
10
+ # allow unless $OMP_VAULT_MOCK/deny exists (then exit 1)
10
11
  DIR="${OMP_VAULT_MOCK:-/tmp/omp-vault-mock}"
11
12
  mkdir -p "$DIR"
12
13
  printf '%s\n' "${*//$'\n'/⏎}" >> "$DIR/zenity.log"
@@ -36,6 +37,13 @@ for arg in "$@"; do
36
37
  if [[ -f "$DIR/entries" ]]; then take_first "$DIR/entries"; else echo ""; fi
37
38
  exit 0 ;;
38
39
  --question)
40
+ # An explicit queue ("y"/"n" per line) wins, so a flow with two
41
+ # different questions can answer them differently.
42
+ if [[ -f "$DIR/questions" ]]; then
43
+ answer="$(take_first "$DIR/questions")"
44
+ [[ "$answer" == "n" || "$answer" == "no" ]] && exit 1
45
+ exit 0
46
+ fi
39
47
  [[ -f "$DIR/deny" ]] && exit 1
40
48
  exit 0 ;;
41
49
  esac
@@ -3,7 +3,7 @@ import assert from "node:assert/strict";
3
3
  import { mkdtempSync, writeFileSync, readFileSync, rmSync } from "node:fs";
4
4
  import { tmpdir } from "node:os";
5
5
  import { join } from "node:path";
6
- import { confirmWindow, promptSecret, promptText } from "../src/prompt.ts";
6
+ import { confirmWindow, promptSecret, promptText } from "../packages/pi-ai-vault/src/prompt.ts";
7
7
 
8
8
  const saved = {
9
9
  PATH: process.env.PATH,
@@ -3,7 +3,7 @@ import assert from "node:assert/strict";
3
3
  import { bind, cleanUpOnExit, useMocks } from "./helpers.mjs";
4
4
 
5
5
  const dir = useMocks();
6
- const { default: ompVault } = await import("../src/index.ts");
6
+ const { default: ompVault } = await import("../packages/pi-ai-vault/src/index.ts");
7
7
  cleanUpOnExit(dir);
8
8
 
9
9
  test("omp: one extension registers the local vault and live Bitwarden, without bw_inject", () => {
@@ -1,6 +1,6 @@
1
1
  import { test } from "node:test";
2
2
  import assert from "node:assert/strict";
3
- import { scrubDeep, scrubText } from "../src/scrub.ts";
3
+ import { scrubDeep, scrubText } from "../packages/pi-ai-vault/src/scrub.ts";
4
4
 
5
5
  const SECRET = "supersecret-value-123";
6
6
  const values = [{ env: "T1", value: SECRET }];
@@ -1,5 +1,6 @@
1
1
  import { test, before, after } from "node:test";
2
2
  import assert from "node:assert/strict";
3
+ import { spawnSync } from "node:child_process";
3
4
  import { existsSync } from "node:fs";
4
5
  import { join } from "node:path";
5
6
  import { answers, bind, cleanUpOnExit, dialogTrace, makeCtx, subCtx, textOf, useMocks } from "./helpers.mjs";
@@ -7,7 +8,7 @@ import { answers, bind, cleanUpOnExit, dialogTrace, makeCtx, subCtx, textOf, use
7
8
  // The extension is only a client: these drive the real ai-vault binary (built
8
9
  // by `npm test`) plus the mock zenity, with a throwaway store.
9
10
  const dir = useMocks();
10
- const { default: aiVault } = await import("../src/index.ts");
11
+ const { default: aiVault } = await import("../packages/pi-ai-vault/src/index.ts");
11
12
  cleanUpOnExit(dir);
12
13
 
13
14
  const PW = "correct horse battery";
@@ -129,3 +130,88 @@ test("a missing entry names what is available", async () => {
129
130
  assert.match(textOf(result), /no such entry/);
130
131
  assert.match(textOf(result), /GitHub/);
131
132
  });
133
+
134
+ test("a local miss falls back to Bitwarden: read once, no import", async () => {
135
+ const b = bind(aiVault, true);
136
+ const ctx = makeCtx().ctx;
137
+ answers.master(dir, PW);
138
+ await b.cmd("unlock", ctx);
139
+ // The Bitwarden mock unlocks with "testmaster"; the two windows are the
140
+ // read approval (yes) and the import offer (no).
141
+ answers.master(dir, "testmaster");
142
+ answers.questions(dir, "y", "n");
143
+ const result = await b.tool("vault_get", { name: "TestService" }, ctx);
144
+ assert.equal(result.details.via, "bitwarden-once");
145
+ assert.match(textOf(result), /supersecret-value-123/);
146
+
147
+ answers.master(dir, PW);
148
+ const listed = await b.tool("vault_list", {}, ctx);
149
+ assert.equal(
150
+ JSON.parse(textOf(listed)).some((i) => i.name === "TestService"),
151
+ false,
152
+ "a one-off read must not write the entry",
153
+ );
154
+ });
155
+
156
+ test("a local miss can be imported from Bitwarden", async () => {
157
+ const b = bind(aiVault, true);
158
+ const ctx = makeCtx().ctx;
159
+ answers.master(dir, PW);
160
+ await b.cmd("unlock", ctx);
161
+ answers.master(dir, "testmaster");
162
+ answers.questions(dir, "y", "y");
163
+ const result = await b.tool("vault_get", { name: "TestService" }, ctx);
164
+ assert.equal(result.details.via, "imported-from-bitwarden");
165
+ assert.match(textOf(result), /supersecret-value-123/);
166
+
167
+ answers.master(dir, PW);
168
+ const listed = await b.tool("vault_list", {}, ctx);
169
+ assert.equal(
170
+ JSON.parse(textOf(listed)).some((i) => i.name === "TestService"),
171
+ true,
172
+ "the import must land in the local vault",
173
+ );
174
+ });
175
+
176
+ test("a denied Bitwarden read is not retried", async () => {
177
+ const b = bind(aiVault, true);
178
+ const ctx = makeCtx().ctx;
179
+ answers.master(dir, PW);
180
+ await b.cmd("unlock", ctx);
181
+ answers.master(dir, "testmaster");
182
+ answers.questions(dir, "n");
183
+ const result = await b.tool("vault_get", { name: "OtherService" }, ctx);
184
+ assert.equal(result.isError, true);
185
+ assert.match(textOf(result), /do not retry/);
186
+ });
187
+
188
+ test("never mode reads without any window, and the switch needs the password", async () => {
189
+ const bin = process.env.AI_VAULT_BIN;
190
+ const switchMode = (mode) =>
191
+ spawnSync(bin, ["mode", "set", mode, "--password-stdin"], {
192
+ input: `${PW}\n`,
193
+ env: process.env,
194
+ encoding: "utf8",
195
+ });
196
+ const toNever = switchMode("never");
197
+ assert.equal(toNever.status, 0, toNever.stderr);
198
+
199
+ const b = bind(aiVault, true);
200
+ const ctx = makeCtx().ctx;
201
+ const before = prompts("--question") + prompts("--password");
202
+ const result = await b.tool("vault_get", { name: "GitHub" }, ctx);
203
+ assert.equal(result.details.via, "no-password");
204
+ assert.match(textOf(result), /pw-one/);
205
+ assert.equal(prompts("--question") + prompts("--password"), before, "no window in never mode");
206
+
207
+ // A wrong password must not change the policy.
208
+ const wrong = spawnSync(bin, ["mode", "set", "session", "--password-stdin"], {
209
+ input: "definitely-wrong\n",
210
+ env: process.env,
211
+ encoding: "utf8",
212
+ });
213
+ assert.equal(wrong.status, 5);
214
+
215
+ const back = switchMode("session");
216
+ assert.equal(back.status, 0, back.stderr);
217
+ });
File without changes
File without changes
File without changes
File without changes