@xiaolikt/ai-vault 0.10.0 → 0.11.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.
@@ -15,15 +15,17 @@ import { tr } from "./i18n.js";
15
15
  import type { ExtensionAPI, ExtensionCommandContext, ExtensionToolContext, ToolDefinition } from "@earendil-works/pi-coding-agent";
16
16
  import { Type } from "typebox";
17
17
  import {
18
- lookupBitwardenLogin,
18
+ lookupBitwardenItem,
19
19
  newBwState,
20
- pullBitwardenLogins,
20
+ pullBitwardenItems,
21
21
  queryBitwarden,
22
22
  registerBitwarden,
23
23
  type BitwardenMeta,
24
24
  type BwState,
25
25
  } from "./bitwarden.js";
26
26
  import { CliError, VaultCli } from "./cli.js";
27
+ import { ITEM_TYPES, isSecretField, parseItemType } from "./import-map.js";
28
+ import type { Draft, ItemType } from "./types.js";
27
29
  import { registerEnte } from "./ente.js";
28
30
  import { isOmpHost, onSessionLeave, sessionLabel, subagentId, withTier } from "./host.js";
29
31
  import { confirmWindow, forDialog, promptSecret, promptText, type PromptHost } from "./prompt.js";
@@ -308,44 +310,34 @@ async function bitwardenFallback(
308
310
  const missing = localMiss;
309
311
  let hit;
310
312
  try {
311
- hit = await lookupBitwardenLogin(bw, ctx, name, signal);
313
+ hit = await lookupBitwardenItem(bw, ctx, name, signal);
312
314
  } catch (error) {
313
315
  return fail(`${missing} — the Bitwarden lookup failed: ${describe(error)}`);
314
316
  }
315
317
  if (!hit) return fail(`${missing} — not in Bitwarden either${reason ? ` (reason: ${reason})` : ""}`);
318
+ const draft = hit.draft;
319
+ const secret = draft.type === "login" ? draft.password : (draft.data?.[ITEM_TYPES[draft.type].primary ?? ""] ?? "");
316
320
 
317
321
  const asValue = (via: string): ToolOutcome => ({
318
322
  content: [
319
323
  {
320
324
  type: "text" as const,
321
- text: JSON.stringify(
322
- { name: hit.name, username: hit.username || undefined, password: hit.password, uris: hit.uris, via },
323
- null,
324
- 1,
325
- ),
325
+ text: JSON.stringify({ ...draft, password: secret ?? draft.password, via }, null, 1),
326
326
  },
327
327
  ],
328
- details: { item: hit.name, via },
328
+ details: { item: draft.name, via },
329
329
  });
330
330
 
331
331
  const importIt = async (): Promise<ToolOutcome> => {
332
332
  try {
333
333
  const saved = await cli.json<SaveResult>(["save", "--yes", ...tokenArgs(scope)], {
334
- stdin: JSON.stringify([
335
- {
336
- name: hit.name,
337
- username: hit.username || undefined,
338
- password: hit.password,
339
- uris: hit.uris,
340
- source: { kind: "bitwarden", id: hit.id },
341
- },
342
- ]),
334
+ stdin: JSON.stringify([draft]),
343
335
  signal,
344
336
  });
345
337
  scope.items += saved.count;
346
338
  setStatus(ctx, scope);
347
339
  } catch (error) {
348
- return fail(`found "${hit.name}" in Bitwarden but could not import it: ${describe(error)}`);
340
+ return fail(`found "${draft.name}" in Bitwarden but could not import it: ${describe(error)}`);
349
341
  }
350
342
  return asValue("imported-from-bitwarden");
351
343
  };
@@ -356,20 +348,25 @@ async function bitwardenFallback(
356
348
  return importIt();
357
349
  }
358
350
 
359
- const label = `${hit.name}${hit.username ? ` user:${hit.username}` : ""}`;
360
351
  const allow = await confirmWindow(
361
352
  dialogs(ctx),
362
353
  tr("pi-ai-vault · found in Bitwarden", "pi-ai-vault · Bitwarden 里找到"),
363
- tr(`Not in the local store as "${forDialog(name)}」,Bitwarden 里yes:\n${forDialog(label)}\n\n读取这一次吗?`, `本地库没有「${forDialog(name)}」,Bitwarden 里有:\n${forDialog(label)}\n\n读取这一次吗?`),
354
+ tr(
355
+ `Not in the local store as "${forDialog(name)}", but Bitwarden has:\n${forDialog(hit.label)}\n\nRead it this once?`,
356
+ `本地库没有「${forDialog(name)}」,Bitwarden 里有:\n${forDialog(hit.label)}\n\n读取这一次吗?`,
357
+ ),
364
358
  signal,
365
359
  );
366
- if (!allow) return fail(`user denied reading "${hit.name}" from Bitwarden — do not retry`, true);
360
+ if (!allow) return fail(`user denied reading "${draft.name}" from Bitwarden — do not retry`, true);
367
361
  if (policy === "never") return asValue("bitwarden-once");
368
362
 
369
363
  const confirmed = await confirmWindow(
370
364
  dialogs(ctx),
371
365
  tr("pi-ai-vault · import into ai-vault", "pi-ai-vault · 导入到 ai-vault"),
372
- tr(`Write "${forDialog(hit.name)}」写进 ai-vault 吗?\n\nAllow → read from the local store from now on (no password under the current unlock policy)\nDeny → use it once only; nothing is written to the local store`, `把「${forDialog(hit.name)}」写进 ai-vault 吗?\n\n允许 → 以后直接读本地库(按当前解锁模式,可能免密)\n拒绝 → 只用这一次,不写入本地库`),
366
+ tr(
367
+ `Write "${forDialog(draft.name)}" into ai-vault?\n\nAllow → read from the local store from now on (no password under the current unlock policy)\nDeny → use it once only; nothing is written to the local store`,
368
+ `把「${forDialog(draft.name)}」写进 ai-vault 吗?\n\n允许 → 以后直接读本地库(按当前解锁模式,可能免密)\n拒绝 → 只用这一次,不写入本地库`,
369
+ ),
373
370
  signal,
374
371
  );
375
372
  return confirmed ? importIt() : asValue("bitwarden-once");
@@ -446,26 +443,62 @@ function vaultGetTool(scope: Scope, bw: BwState): ToolDefinition<typeof vaultGet
446
443
 
447
444
  const vaultAddParams = Type.Object({
448
445
  name: Type.String({ description: "Entry name to create or update, e.g. 'github'" }),
449
- username: Type.Optional(Type.String({ description: "Account username. Omit to let the user type it in a dialog." })),
450
- uri: Type.Optional(Type.String({ description: "Optional site or host URI" })),
451
- notes: Type.Optional(Type.String({ description: "Optional non-secret note. Do NOT put the password here." })),
446
+ type: Type.Optional(
447
+ Type.String({
448
+ description:
449
+ "Item type, as in Bitwarden: login (default), note, card, identity, sshkey, bankaccount, driverslicense, passport. " +
450
+ "A note's content goes in `notes`.",
451
+ }),
452
+ ),
453
+ username: Type.Optional(Type.String({ description: "Login: account username. Omit to let the user type it in a dialog." })),
454
+ uri: Type.Optional(Type.String({ description: "Login: site or host URI" })),
455
+ notes: Type.Optional(Type.String({ description: "Notes shared by every type. For a `note` entry this is its content." })),
456
+ fields: Type.Optional(
457
+ Type.Record(
458
+ Type.String(),
459
+ Type.Optional(Type.String()),
460
+ {
461
+ description:
462
+ "The type's own fields by Bitwarden's names (card: cardholderName, brand, number, expMonth, expYear, code; " +
463
+ "sshkey: publicKey, privateKey, keyFingerprint; identity: firstName, lastName, email, …). " +
464
+ "Give a non-secret field as text; give a secret field (password, code, number, privateKey, pin, ssn…) " +
465
+ "as null/undefined so the user types it in a dialog. NEVER put a secret value here.",
466
+ },
467
+ ),
468
+ ),
452
469
  });
453
470
  function vaultAddTool(scope: Scope): ToolDefinition<typeof vaultAddParams, { ok?: boolean; item?: string }> {
454
471
  const tool: ToolDefinition<typeof vaultAddParams, { ok?: boolean; item?: string }> = {
455
472
  name: "vault_add",
456
473
  label: "Vault: store a secret via dialog",
457
474
  description:
458
- "Create or update an entry in the machine-wide ai-vault store. You supply the name and optional username, URI, and notes. " +
459
- "The password is typed by the user in a desktop window and is NEVER accepted from you and NEVER returned. " +
460
- "Do not ask the user to paste a password into the chat.",
475
+ "Create or update an entry of any Bitwarden type in the machine-wide ai-vault store (login, note, card, identity, sshkey, " +
476
+ "bankaccount, driverslicense, passport). You supply the name, the type and its non-secret fields. " +
477
+ "Secret fields (password, card number and code, private key, PIN, SSN…) are typed by the user in a desktop window: " +
478
+ "leave them empty, they are NEVER accepted from you and NEVER returned. Do not ask the user to paste a secret into the chat.",
461
479
  promptSnippet: "Save a local vault entry; the user types the password in a window.",
462
480
  parameters: vaultAddParams,
463
481
  async execute(_id, params, signal, _onUpdate, ctx) {
482
+ const kind = parseItemType(params.type);
483
+ if (!kind) {
484
+ return fail(`unknown type "${params.type}" — login, note, card, identity, sshkey, bankaccount, driverslicense, passport`);
485
+ }
486
+ // A secret field the model filled in is refused rather than stored:
487
+ // only the user types secrets, in a dialog.
488
+ const fields: Record<string, string | undefined> = {};
489
+ for (const [field, value] of Object.entries(params.fields ?? {})) {
490
+ if (value !== undefined && value !== "" && isSecretField(kind, field)) {
491
+ return fail(`"${field}" is a secret field: leave it empty so the user types it in a dialog`);
492
+ }
493
+ fields[field] = value === "" ? undefined : value;
494
+ }
464
495
  const result = await saveLocalEntry(scope, ctx, {
465
496
  name: params.name,
497
+ type: kind,
466
498
  username: params.username,
467
499
  uri: params.uri,
468
500
  notes: params.notes,
501
+ fields,
469
502
  signal,
470
503
  });
471
504
  const ok = result.startsWith("saved ");
@@ -508,9 +541,12 @@ function vaultImportTool(scope: Scope, bw: BwState): ToolDefinition<typeof vault
508
541
 
509
542
  interface SaveRequest {
510
543
  name?: string;
544
+ type?: ItemType;
511
545
  username?: string;
512
546
  uri?: string;
513
547
  notes?: string;
548
+ /** The type's own fields, NAME=VALUE; a value of `undefined` means "typed in a dialog". */
549
+ fields?: Record<string, string | undefined>;
514
550
  signal?: AbortSignal;
515
551
  }
516
552
 
@@ -524,18 +560,33 @@ async function saveLocalEntry(scope: Scope, ctx: Ctx, req: SaveRequest): Promise
524
560
  }
525
561
  if (!name) return "cancelled: no entry name";
526
562
 
527
- const args = ["add", "--name", name, "--token", scope.token!];
563
+ const kind = req.type ?? "login";
564
+ const args = ["add", "--name", name, "--type", kind, "--token", scope.token!];
528
565
  if (req.username !== undefined) args.push("--username", req.username);
529
566
  if (req.uri?.trim()) args.push("--uri", req.uri.trim());
530
567
  if (req.notes?.trim()) args.push("--notes", req.notes.trim());
531
- let stdin: string | undefined;
532
- for (let attempt = 0; attempt < 5; attempt++) {
568
+ const secrets = new Map<string, string>();
569
+ const shown: string[] = [];
570
+ for (const [field, value] of Object.entries(req.fields ?? {})) {
571
+ if (value === undefined) shown.push(`${field} ••••`);
572
+ else {
573
+ args.push("--field", `${field}=${value}`);
574
+ shown.push(`${field} ${isSecretField(kind, field) ? "••••" : forDialog(value, 120)}`);
575
+ }
576
+ }
577
+ const flush = () => {
578
+ // --secret args are re-added on every attempt: the CLI is stateless.
579
+ for (let i = args.length - 1; i >= 0; i--) if (args[i] === "--secret") args.splice(i, 2);
580
+ for (const [field, value] of secrets) args.push("--secret", `${field}=${value}`);
581
+ };
582
+ for (let attempt = 0; attempt < 8; attempt++) {
583
+ flush();
533
584
  try {
534
- const run = await cli.run([...args, "--json"], { stdin, signal: req.signal });
535
- const saved = JSON.parse(run.stdout) as { item?: string; created?: boolean };
585
+ const run = await cli.run([...args, "--json"], { signal: req.signal });
586
+ const saved = JSON.parse(run.stdout) as { item?: string; created?: boolean; type?: string };
536
587
  if (saved.created) scope.items += 1;
537
588
  setStatus(ctx, scope);
538
- return `saved "${saved.item ?? name}" (password entered in the dialog, not shown)`;
589
+ return `saved "${saved.item ?? name}" as a ${saved.type ?? kind} (hidden fields entered in dialogs, not shown)`;
539
590
  } catch (error) {
540
591
  if (!(error instanceof CliError) || !error.needsUi) {
541
592
  if (error instanceof CliError && error.auth) scope.token = undefined;
@@ -543,6 +594,7 @@ async function saveLocalEntry(scope: Scope, ctx: Ctx, req: SaveRequest): Promise
543
594
  }
544
595
  if (error.needsUi === "confirm") {
545
596
  const meta = [
597
+ ...shown,
546
598
  req.username?.trim() ? tr(`Username: ${forDialog(req.username, 60)}`, `用户名: ${forDialog(req.username, 60)}`) : "",
547
599
  req.uri?.trim() ? `URI: ${forDialog(req.uri, 120)}` : "",
548
600
  req.notes?.trim() ? tr(`Notes: ${forDialog(req.notes, 120)}`, `备注: ${forDialog(req.notes, 120)}`) : "",
@@ -552,7 +604,10 @@ async function saveLocalEntry(scope: Scope, ctx: Ctx, req: SaveRequest): Promise
552
604
  const ok = await confirmWindow(
553
605
  dialogs(ctx),
554
606
  tr("ai-vault · save to local store", "ai-vault · 保存到本地库"),
555
- tr(`Save the entry "${forDialog(name)}".${meta ? `\n${meta}` : ""}\nA window opens next for you to type the password. It never enters the conversation.`, `保存条目「${forDialog(name)}」。${meta ? `\n${meta}` : ""}\n下一步会弹出窗口,由你输入密码。密码不会进入对话。`),
607
+ tr(
608
+ `Save the ${kind} entry "${forDialog(name)}".${meta ? `\n${meta}` : ""}\nA window opens next for each hidden field. Nothing enters the conversation.`,
609
+ `保存${kind}条目「${forDialog(name)}」。${meta ? `\n${meta}` : ""}\n接下来每个隐藏字段弹一个窗口。密码不会进入对话。`,
610
+ ),
556
611
  req.signal,
557
612
  );
558
613
  if (!ok) return `user denied saving "${name}"`;
@@ -565,10 +620,11 @@ async function saveLocalEntry(scope: Scope, ctx: Ctx, req: SaveRequest): Promise
565
620
  args.push("--username", entered);
566
621
  continue;
567
622
  }
568
- const password = await promptSecret(dialogs(ctx), tr("ai-vault · password", "ai-vault · 密码"), name, req.signal);
623
+ // needsUi === "password": one hidden field at a time, named by the CLI.
624
+ const field = error.field ?? ITEM_TYPES[kind].primary ?? "password";
625
+ const password = await promptSecret(dialogs(ctx), tr("ai-vault · password", "ai-vault · 密码"), `${name} · ${field}`, req.signal);
569
626
  if (!password) return "cancelled: no password entered";
570
- args.push("--password-stdin");
571
- stdin = `${password}\n`;
627
+ secrets.set(field, password);
572
628
  }
573
629
  }
574
630
  return "cancelled: the save dialog did not settle";
@@ -605,12 +661,12 @@ async function importBitwarden(
605
661
  if (!allowed) return { text: "user denied the Bitwarden import", ok: false, count: 0 };
606
662
  let drafts;
607
663
  try {
608
- drafts = await pullBitwardenLogins(bw, ctx, search, signal);
664
+ drafts = await pullBitwardenItems(bw, ctx, search, signal);
609
665
  } catch (error) {
610
666
  return { text: `Bitwarden: ${describe(error)}`, ok: false, count: 0 };
611
667
  }
612
668
  if (drafts.length === 0) {
613
- return { text: "matched items have no login password; nothing imported", ok: false, count: 0 };
669
+ return { text: "nothing matched; nothing imported", ok: false, count: 0 };
614
670
  }
615
671
  try {
616
672
  const saved = await cli.json<SaveResult>(["save", "--yes", "--token", scope.token!], {
@@ -891,7 +947,30 @@ function commandHandler(scope: Scope, bw: BwState) {
891
947
  return;
892
948
  }
893
949
  case "add": {
894
- const text = await saveLocalEntry(scope, ctx, { name: rest.join(" ") || undefined });
950
+ // /vault add [type:]name [field=value ...] [field] — a bare
951
+ // `field` is typed in a dialog. /vault add card:Visa brand=Visa code
952
+ const [first, ...pairs] = rest;
953
+ let type: ItemType | undefined;
954
+ let name = first ?? "";
955
+ const m = /^([a-z]+):(.+)$/.exec(first ?? "");
956
+ if (m) {
957
+ const parsed = parseItemType(m[1]);
958
+ if (parsed) {
959
+ type = parsed;
960
+ name = m[2] ?? name;
961
+ }
962
+ }
963
+ const fields: Record<string, string | undefined> = {};
964
+ let notes: string | undefined;
965
+ for (const pair of pairs) {
966
+ const eq = pair.indexOf("=");
967
+ const key = eq < 0 ? pair : pair.slice(0, eq);
968
+ const value = eq < 0 ? "" : pair.slice(eq + 1);
969
+ if (!key) continue;
970
+ if (key === "notes" || key === "note") notes = value;
971
+ else fields[key] = value === "" ? undefined : value;
972
+ }
973
+ const text = await saveLocalEntry(scope, ctx, { name: name.trim() || undefined, type, fields, notes });
895
974
  note(ctx, text, text.startsWith("saved ") ? "info" : "warning");
896
975
  return;
897
976
  }
@@ -0,0 +1,52 @@
1
+ /**
2
+ * The shape of a vault entry, shared by the extension's import mapping and
3
+ * its tools. Mirrors the CLI's `store.rs` and Bitwarden's own item envelope:
4
+ * a type, the type's own fields under `data`, plus `notes` and custom
5
+ * `fields` that every type carries.
6
+ */
7
+ export type ItemType =
8
+ | "login"
9
+ | "secureNote"
10
+ | "card"
11
+ | "identity"
12
+ | "sshKey"
13
+ | "bankAccount"
14
+ | "driversLicense"
15
+ | "passport";
16
+
17
+ /** A custom field, as Bitwarden stores it: 0 text · 1 hidden · 2 boolean · 3 linked. */
18
+ export interface Field {
19
+ name: string;
20
+ value: string;
21
+ type: number;
22
+ linkedId?: string;
23
+ }
24
+
25
+ export interface Source {
26
+ kind: string;
27
+ id: string;
28
+ }
29
+
30
+ /** What a tool hands to `ai-vault save` / `add`: the same envelope, sparse. */
31
+ export interface Draft {
32
+ name: string;
33
+ type: ItemType;
34
+ username?: string;
35
+ password?: string;
36
+ uris?: string[];
37
+ data?: Record<string, string>;
38
+ notes?: string;
39
+ fields?: Field[];
40
+ source?: Source;
41
+ }
42
+
43
+ /** What `list` returns: metadata only, every secret masked. */
44
+ export interface ItemSummary {
45
+ name: string;
46
+ type: ItemType;
47
+ username?: string | null;
48
+ uris: string[];
49
+ fields: Record<string, string>;
50
+ hasNotes?: boolean;
51
+ updatedAt: string;
52
+ }
package/test/cli.sh CHANGED
@@ -168,6 +168,50 @@ grep -q 'ENTE_KEY_PLAINTEXT' "$AI_VAULT_DIR/ente.session.json" && bad "the ente
168
168
  "$BIN" settings ente.unlock session --json >/dev/null
169
169
  check "switching back to session clears the ente key" 5 "$BIN" ente-session get
170
170
 
171
+ echo "== item types =="
172
+ # The tamper block consumed the earlier host token; open a fresh host session.
173
+ HOST_JSON=$(printf 'correct horse' | "$BIN" unlock --password-stdin --json)
174
+ TOKEN=$(printf '%s' "$HOST_JSON" | json token)
175
+ cat >"$TMP/all-types.json" <<'JSON'
176
+ {"items":[
177
+ {"id":"t1","type":1,"name":"Login","login":{"username":"u","password":"gh-pw","totp":"JBSWY3DP"},"fields":[{"name":"API_KEY","value":"hf_sk_abc987xyz456","type":1},{"name":"Plan","value":"Team","type":0}]},
178
+ {"id":"t2","type":2,"name":"Note","secureNote":{},"notes":"body: hunter2"},
179
+ {"id":"t3","type":3,"name":"Card","card":{"cardholderName":"Li","brand":"Visa","number":"4111111111111111","expMonth":"12","expYear":"2029","code":"123"}},
180
+ {"id":"t4","type":4,"name":"Identity","identity":{"firstName":"Jun","ssn":"123-45-6789","licenseNumber":"DL-99"}},
181
+ {"id":"t5","type":5,"name":"Key","sshKey":{"privateKey":"PEM-PRIVATE","publicKey":"ssh-ed25519 PUB"}},
182
+ {"id":"t6","type":6,"name":"Bank","bankAccount":{"bankName":"ICBC","accountNumber":"6222000011112222","pin":"9080"}},
183
+ {"id":"t7","type":7,"name":"Licence","driversLicense":{"licenseNumber":"110101"}},
184
+ {"id":"t8","type":8,"name":"Passport","passport":{"passportNumber":"E1234567","nationality":"CN"}}
185
+ ]}
186
+ JSON
187
+ check "import every item type" 0 "$BIN" import "$TMP/all-types.json" --yes --token "$TOKEN" --json
188
+ "$BIN" list --token "$TOKEN" --json >"$TMP/typed-list"
189
+ python3 - "$TMP/typed-list" <<'PY' && ok "list carries the type of each entry" || bad "list does not carry types"
190
+ import json,sys
191
+ items = json.load(open(sys.argv[1]))["items"]
192
+ types = {i["name"]: i["type"] for i in items}
193
+ for name, kind in {"Login":"login","Note":"secureNote","Card":"card","Identity":"identity","Key":"sshKey","Bank":"bankAccount","Licence":"driversLicense","Passport":"passport"}.items():
194
+ assert types.get(name) == kind, (name, types.get(name))
195
+ PY
196
+ for secret in gh-pw hunter2 4111111111111111 123-45-6789 DL-99 hf_sk_abc987xyz456 PEM-PRIVATE 6222000011112222 110101 E1234567 JBSWY3DP; do
197
+ grep -q "$secret" "$TMP/typed-list" && bad "list leaked $secret"
198
+ done
199
+ ok "list masks passwords, card number and code, keys, PIN, account and document numbers, hidden fields, TOTP seeds"
200
+ grep -q '"hasNotes":true' "$TMP/typed-list" && ok "list flags which entries carry notes" || bad "hasNotes missing"
201
+ # a manual entry of a non-login type, secret typed (stdin here for the primary field)
202
+ check "add a card by hand with --type and --field" 0 bash -c "printf '999\n' | '$BIN' add --name HandCard --type card --field brand=Amex --field cardholderName='Li Jun' --field expYear=2031 --field number=378282246310005 --password-stdin --yes --token '$TOKEN' --json"
203
+ check "a wrong field name is refused" 2 "$BIN" add --name X --type card --field cvv=1 --yes --token "$TOKEN"
204
+ check "a wrong type name is refused" 2 "$BIN" add --name X --type wifi --yes --token "$TOKEN"
205
+ check "--secret rejects a non-secret field" 2 bash -c "'$BIN' add --name X --type card --field brand=Visa --secret brand=Visa --secret code=1 --yes --token '$TOKEN'"
206
+ relay Card y >"$TMP/card" 2>&1; [[ $? -eq 0 ]] && ok "get returns a card with its data block" || bad "get of a card failed"
207
+ python3 - "$TMP/card" <<'PY' && ok "get shows the type's fields by Bitwarden's names" || bad "get output is wrong"
208
+ import json,sys
209
+ d = json.load(open(sys.argv[1]))
210
+ assert d["type"] == "card" and d["data"]["code"] == "123" and d["data"]["number"] == "4111111111111111", d
211
+ PY
212
+ relay Note y >"$TMP/note" 2>&1; [[ $? -eq 0 ]] && ok "get returns a secure note's body" || bad "get of a note failed"
213
+ grep -q 'body: hunter2' "$TMP/note" && ok "the note body is in notes" || bad "note body missing"
214
+
171
215
  echo "== rekey (L2) =="
172
216
  OLD_N=$(python3 -c "import json;print(json.load(open('$AI_VAULT_DIR/store.json'))['kdf']['N'])")
173
217
  check "rekey with the password" 0 bash -c "printf 'correct horse' | '$BIN' rekey --password-stdin --json"
@@ -175,8 +175,8 @@ test("a denied confirmation never fetches the entry; an approved one fetches it
175
175
 
176
176
  // An id is looked up in the listing, so a wrong one fails before any window.
177
177
  await assert.rejects(
178
- b.tool("bw_run", { item: "cccc3333-3333-4333-8333-333333333333", command: "true" }),
179
- /No Bitwarden item with id cccc3333/,
178
+ b.tool("bw_run", { item: "ffff9999-9999-4999-8999-999999999999", command: "true" }),
179
+ /No Bitwarden item with id ffff9999/,
180
180
  );
181
181
  });
182
182
 
@@ -1,22 +1,23 @@
1
1
  import { test } from "node:test";
2
2
  import assert from "node:assert/strict";
3
- import { bitwardenLogins, filterLogins } from "../packages/pi-ai-vault/src/import-map.ts";
3
+ import { bitwardenItems, filterItems, isSecretField, parseItemType } from "../packages/pi-ai-vault/src/import-map.ts";
4
4
 
5
- const item = (name, extra = {}) => ({
5
+ const login = (name, extra = {}) => ({
6
6
  id: extra.id,
7
+ type: 1,
7
8
  name,
8
9
  login: { username: extra.username, password: extra.password ?? "pw-value-1", uris: extra.uri ? [{ uri: extra.uri }] : [] },
9
10
  notes: extra.notes,
11
+ fields: extra.fields,
10
12
  });
11
13
 
12
14
  test("reads a Bitwarden export object and a raw array", () => {
13
- const fromExport = bitwardenLogins({
14
- items: [item("GitHub", { username: "me", uri: "https://github.com", notes: "n" })],
15
- });
16
- const fromArray = bitwardenLogins([item("GitHub", { username: "me", uri: "https://github.com", notes: "n" })]);
15
+ const fromExport = bitwardenItems({ items: [login("GitHub", { username: "me", uri: "https://github.com", notes: "n" })] });
16
+ const fromArray = bitwardenItems([login("GitHub", { username: "me", uri: "https://github.com", notes: "n" })]);
17
17
  assert.equal(fromExport.length, 1);
18
18
  assert.deepEqual(fromExport[0], {
19
19
  name: "GitHub",
20
+ type: "login",
20
21
  username: "me",
21
22
  password: "pw-value-1",
22
23
  uris: ["https://github.com"],
@@ -25,50 +26,86 @@ test("reads a Bitwarden export object and a raw array", () => {
25
26
  assert.deepEqual(fromArray, fromExport);
26
27
  });
27
28
 
29
+ test("every item type maps field for field, by Bitwarden's names", () => {
30
+ const drafts = bitwardenItems({
31
+ items: [
32
+ { id: "n", type: 2, name: "Wifi", secureNote: {}, notes: "guest: hunter2" },
33
+ { id: "c", type: 3, name: "Visa", card: { cardholderName: "Li", brand: "Visa", number: "4111", expMonth: "12", expYear: "2029", code: "123" } },
34
+ { id: "i", type: 4, name: "Me", identity: { title: "Mr", firstName: "Jun", lastName: "Li", ssn: "123-45-6789" } },
35
+ { id: "k", type: 5, name: "key", sshKey: { privateKey: "PEM", publicKey: "ssh-ed25519 AAA", keyFingerprint: "SHA256:x" } },
36
+ { id: "b", type: 6, name: "Bank", bankAccount: { bankName: "ICBC", accountNumber: "6222", pin: "9080", iban: null } },
37
+ { id: "d", type: 7, name: "Licence", driversLicense: { licenseNumber: "110101", expirationDate: "2030-01-01" } },
38
+ { id: "p", type: 8, name: "Passport", passport: { passportNumber: "E123", nationality: "CN" } },
39
+ ],
40
+ });
41
+ const byName = Object.fromEntries(drafts.map((d) => [d.name, d]));
42
+ assert.equal(byName.Wifi.type, "secureNote");
43
+ assert.equal(byName.Wifi.notes, "guest: hunter2");
44
+ assert.equal(byName.Wifi.data, undefined, "a secure note has no fields of its own");
45
+ assert.deepEqual(byName.Visa.data, { cardholderName: "Li", brand: "Visa", number: "4111", expMonth: "12", expYear: "2029", code: "123" });
46
+ assert.equal(byName.Me.data.ssn, "123-45-6789");
47
+ assert.equal(byName["key"].data.privateKey, "PEM");
48
+ assert.deepEqual(byName.Bank.data, { bankName: "ICBC", accountNumber: "6222", pin: "9080" }, "a null field is dropped");
49
+ assert.equal(byName.Licence.data.licenseNumber, "110101");
50
+ assert.equal(byName.Passport.data.passportNumber, "E123");
51
+ assert.equal(byName.Me.password, undefined, "only a login carries the flat password mirror");
52
+ });
53
+
54
+ test("custom fields keep their Bitwarden type, so a hidden one stays hidden", () => {
55
+ const [draft] = bitwardenItems([login("GH", { fields: [{ name: "API_KEY", value: "hf_abc", type: 1 }, { name: "Plan", value: "Team", type: 0 }] })]);
56
+ assert.deepEqual(draft.fields, [
57
+ { name: "API_KEY", value: "hf_abc", type: 1 },
58
+ { name: "Plan", value: "Team", type: 0 },
59
+ ]);
60
+ });
61
+
28
62
  test("each entry keeps the id of the Bitwarden item it came from", () => {
29
- const [draft] = bitwardenLogins({ items: [item("Cloud", { id: "bw-1", username: "root" })] });
63
+ const [draft] = bitwardenItems({ items: [login("Cloud", { id: "bw-1", username: "root" })] });
30
64
  assert.deepEqual(draft.source, { kind: "bitwarden", id: "bw-1" });
31
65
  });
32
66
 
33
67
  test("an encrypted export is refused instead of importing nothing", () => {
34
- assert.throws(
35
- () => bitwardenLogins({ encrypted: true, encKeyValidation: "…", data: "2.0|…" }),
36
- /encrypted Bitwarden export/,
37
- );
68
+ assert.throws(() => bitwardenItems({ encrypted: true, encKeyValidation: "…", data: "2.0|…" }), /encrypted Bitwarden export/);
38
69
  });
39
70
 
40
71
  test("a payload that is neither an export nor an item array is refused", () => {
41
- assert.throws(() => bitwardenLogins({ hello: "world" }), /Not a Bitwarden export/);
42
- assert.throws(() => bitwardenLogins(null), /Not a Bitwarden export/);
72
+ assert.throws(() => bitwardenItems({ hello: "world" }), /Not a Bitwarden export/);
73
+ assert.throws(() => bitwardenItems(null), /Not a Bitwarden export/);
43
74
  });
44
75
 
45
- test("skips items with no login password and blank names", () => {
46
- const drafts = bitwardenLogins({
47
- items: [
48
- { name: "note-only", notes: "x" },
49
- { name: "empty-login", login: { username: "a", password: "" } },
50
- { name: " \n", login: { password: "pw-value-1" } },
51
- ],
52
- });
53
- assert.equal(drafts.length, 1);
54
- assert.equal(drafts[0].name, "unnamed");
76
+ test("an unknown type number is an error, a blank name becomes 'unnamed'", () => {
77
+ assert.throws(() => bitwardenItems([{ type: 99, name: "x" }]), /unsupported Bitwarden item type 99/);
78
+ const [draft] = bitwardenItems([{ type: 1, name: " \n", login: { password: "p" } }]);
79
+ assert.equal(draft.name, "unnamed");
55
80
  });
56
81
 
57
- test("disambiguates duplicate names in a stable order", () => {
58
- const drafts = bitwardenLogins([item("GitHub", { username: "b" }), item("GitHub", { username: "a" }), item("Other", { username: "z" })]);
59
- assert.deepEqual(
60
- drafts.map((d) => `${d.name}|${d.username}`),
61
- ["GitHub|a", "GitHub (2)|b", "Other|z"],
62
- );
82
+ test("disambiguates duplicate names within a type, not across types", () => {
83
+ const drafts = bitwardenItems([login("GitHub", { username: "b" }), login("GitHub", { username: "a" }), { type: 2, name: "GitHub", secureNote: {} }]);
84
+ const names = drafts.map((d) => `${d.type}:${d.name}|${d.username ?? ""}`);
85
+ assert.deepEqual(names, ["login:GitHub|a", "login:GitHub (2)|b", "secureNote:GitHub|"]);
63
86
  });
64
87
 
65
- test("filter matches name, username, and uri", () => {
66
- const drafts = bitwardenLogins([
67
- item("GitHub", { username: "octo", uri: "https://github.com" }),
68
- item("Mail", { username: "me", uri: "https://mail.example" }),
69
- ]);
70
- assert.equal(filterLogins(drafts, "octo").length, 1);
71
- assert.equal(filterLogins(drafts, "mail.example")[0].name, "Mail");
72
- assert.equal(filterLogins(drafts, "nope").length, 0);
73
- assert.equal(filterLogins(drafts, " ").length, 2);
88
+ test("type names parse the way a human writes them", () => {
89
+ assert.equal(parseItemType(undefined), "login");
90
+ assert.equal(parseItemType("SSH key"), "sshKey");
91
+ assert.equal(parseItemType("secure-note"), "secureNote");
92
+ assert.equal(parseItemType("driver's licence"), "driversLicense");
93
+ assert.equal(parseItemType("wifi"), undefined);
94
+ });
95
+
96
+ test("secret fields are known per type", () => {
97
+ assert.equal(isSecretField("login", "password"), true);
98
+ assert.equal(isSecretField("card", "number"), true);
99
+ assert.equal(isSecretField("card", "brand"), false);
100
+ assert.equal(isSecretField("bankAccount", "pin"), true);
101
+ assert.equal(isSecretField("identity", "ssn"), true);
102
+ assert.equal(isSecretField("passport", "passportNumber"), true);
103
+ assert.equal(isSecretField("passport", "nationality"), false);
104
+ });
105
+
106
+ test("filterItems matches name, username, and URIs across every type", () => {
107
+ const items = bitwardenItems([login("GitHub", { username: "me", uri: "https://github.com" }), { type: 3, name: "Visa", card: { brand: "Visa" } }]);
108
+ assert.equal(filterItems(items, "visa")[0]?.name, "Visa");
109
+ assert.equal(filterItems(items, "github.com")[0]?.name, "GitHub");
110
+ assert.equal(filterItems(items).length, 2);
74
111
  });
@@ -30,11 +30,15 @@ case "$args" in
30
30
  fi ;;
31
31
  "sync --nointeraction") exit 0 ;;
32
32
  "list items --nointeraction")
33
- echo '[{"id":"aaaa1111-1111-4111-8111-111111111111","name":"TestService","login":{"username":"alice","password":"supersecret-value-123","totp":null,"uris":[{"uri":"https://test.example.com"}]},"notes":"note-secret-abc","fields":[{"name":"API_KEY","value":"hf_sk-abc987xyz456","type":1}]},{"id":"bbbb2222-2222-4222-8222-222222222222","name":"OtherService","login":{"username":"bob","password":"other-pw-999","uris":[]},"fields":[]}]' ;;
33
+ echo '[{"id":"aaaa1111-1111-4111-8111-111111111111","name":"TestService","login":{"username":"alice","password":"supersecret-value-123","totp":null,"uris":[{"uri":"https://test.example.com"}]},"notes":"note-secret-abc","fields":[{"name":"API_KEY","value":"hf_sk-abc987xyz456","type":1}]},{"id":"bbbb2222-2222-4222-8222-222222222222","name":"OtherService","login":{"username":"bob","password":"other-pw-999","uris":[]},"fields":[]},{"id":"cccc3333-3333-4333-8333-333333333333","type":3,"name":"CorpCard","card":{"cardholderName":"Li Jun","brand":"Visa","number":"4111111111111111","expMonth":"12","expYear":"2029","code":"123"}},{"id":"dddd4444-4444-4444-8444-444444444444","type":2,"name":"WifiNote","secureNote":{},"notes":"guest network: hunter2"}]' ;;
34
34
  "get item aaaa1111-1111-4111-8111-111111111111 --nointeraction")
35
35
  echo '{"id":"aaaa1111-1111-4111-8111-111111111111","name":"TestService","login":{"username":"alice","password":"supersecret-value-123","uris":[]},"fields":[{"name":"API_KEY","value":"hf_sk-abc987xyz456","type":1}]}' ;;
36
36
  "get item bbbb2222-2222-4222-8222-222222222222 --nointeraction")
37
37
  echo '{"id":"bbbb2222-2222-4222-8222-222222222222","name":"OtherService","login":{"username":"bob","password":"other-pw-999","uris":[]},"fields":[]}' ;;
38
+ "get item cccc3333-3333-4333-8333-333333333333 --nointeraction")
39
+ echo '{"id":"cccc3333-3333-4333-8333-333333333333","type":3,"name":"CorpCard","card":{"cardholderName":"Li Jun","brand":"Visa","number":"4111111111111111","expMonth":"12","expYear":"2029","code":"123"}}' ;;
40
+ "get item dddd4444-4444-4444-8444-444444444444 --nointeraction")
41
+ echo '{"id":"dddd4444-4444-4444-8444-444444444444","type":2,"name":"WifiNote","secureNote":{},"notes":"guest network: hunter2"}' ;;
38
42
  "lock --nointeraction") touch "$MOCK_DIR/locked"; exit 0 ;;
39
43
  "get item "*" --nointeraction") echo "Not found." >&2; exit 1 ;;
40
44
  *) echo "mock bw: unhandled: $args" >&2; exit 1 ;;