@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.
@@ -52,7 +52,8 @@ import path from "node:path";
52
52
  import type { ExtensionAPI, ExtensionContext, ToolDefinition, ToolResultEventResult } from "@earendil-works/pi-coding-agent";
53
53
  import { createBashTool } from "@earendil-works/pi-coding-agent";
54
54
  import { Type } from "typebox";
55
- import { bitwardenLogins, filterLogins, type LoginDraft } from "./import-map.js";
55
+ import { bitwardenItems, filterItems } from "./import-map.js";
56
+ import type { Draft } from "./types.js";
56
57
  import { onSessionLeave, sessionLabel, withTier } from "./host.js";
57
58
  import { confirmWindow, hasDisplay, promptSecret } from "./prompt.js";
58
59
  import { getSettingsSafe, settingsCli } from "./settings.js";
@@ -152,12 +153,16 @@ const BW_LOGIN_HINT =
152
153
  type BwItem = {
153
154
  id?: string;
154
155
  name?: string;
156
+ type?: number;
155
157
  notes?: string;
156
158
  login?: { username?: string; password?: string; totp?: string; uris?: { uri?: string }[] };
157
- fields?: { name?: string; value?: string }[];
159
+ card?: { cardholderName?: string; brand?: string; number?: string; code?: string };
160
+ identity?: { title?: string; firstName?: string; lastName?: string; email?: string; phone?: string };
161
+ sshKey?: { publicKey?: string; keyFingerprint?: string };
162
+ fields?: { name?: string; value?: string; type?: number }[];
158
163
  };
159
164
  /** Only metadata is cached; secrets stay in the vault process until needed. */
160
- type LiteItem = { id: string; name: string; username: string; uri: string };
165
+ type LiteItem = { id: string; name: string; username: string; uri: string; type: string };
161
166
  type InjectedSecret = { value: string; item: string; field: string; at: number };
162
167
 
163
168
  /**
@@ -624,12 +629,23 @@ async function ensureUnlocked(st: BwState, ctx: ExtensionContext | undefined, si
624
629
  return pending;
625
630
  }
626
631
 
632
+ const BW_TYPE_NAMES: Record<number, string> = { 1: "login", 2: "note", 3: "card", 4: "identity", 5: "sshKey", 6: "bankAccount", 7: "driversLicense", 8: "passport" };
633
+
627
634
  function toLite(raw: BwItem): LiteItem {
635
+ const type = BW_TYPE_NAMES[raw.type ?? 1] ?? `type-${raw.type}`;
636
+ // The identifying, non-secret line of each type: username for a login,
637
+ // cardholder for a card, a person's name for an identity, and so on.
638
+ const who =
639
+ raw.login?.username ??
640
+ raw.card?.cardholderName ??
641
+ (raw.identity ? [raw.identity.title, raw.identity.firstName, raw.identity.lastName].filter(Boolean).join(" ") : "") ??
642
+ "";
628
643
  return {
629
644
  id: raw.id ?? "",
630
645
  name: raw.name ?? "",
631
- username: raw.login?.username ?? "",
646
+ username: who,
632
647
  uri: raw.login?.uris?.[0]?.uri ?? "",
648
+ type,
633
649
  };
634
650
  }
635
651
 
@@ -796,34 +812,35 @@ export async function queryBitwarden(
796
812
  }
797
813
 
798
814
  /**
799
- * Login items that have a password, ready to store in the local vault.
800
- * Call only after the user has agreed to the import — this reads secrets.
815
+ * Every item that matches `search`, ready to store in the local vault: all
816
+ * types, field for field. Call only after the user has agreed to the import —
817
+ * this reads secrets.
801
818
  */
802
- export async function pullBitwardenLogins(
819
+ export async function pullBitwardenItems(
803
820
  st: BwState,
804
821
  ctx: ExtensionContext | undefined,
805
822
  search: string | undefined,
806
823
  signal?: AbortSignal,
807
- ): Promise<LoginDraft[]> {
824
+ ): Promise<Draft[]> {
808
825
  const session = await ensureUnlocked(st, ctx, signal);
809
826
  const raw: unknown = await runBwJson(["list", "items"], session, signal);
810
- return filterLogins(bitwardenLogins(raw), search);
827
+ return filterItems(bitwardenItems(raw), search);
811
828
  }
812
829
 
813
- export type BitwardenLoginHit = { id: string; name: string; username: string; password: string; uris: string[] };
830
+ export type BitwardenHit = { draft: Draft; label: string };
814
831
 
815
832
  /**
816
- * Look one login up by name/URI and return its password, with no window of its
817
- * own: the caller shows the user what was found and asks whether to read it.
818
- * `undefined` means "no such item"; an ambiguous reference throws with the
819
- * candidates so the model can pick one.
833
+ * Look one item up, of any type, and return it as a draft with its secrets,
834
+ * with no window of its own: the caller shows the user what was found and asks
835
+ * whether to read it. `undefined` means "no such item"; an ambiguous reference
836
+ * throws with the candidates so the model can pick one.
820
837
  */
821
- export async function lookupBitwardenLogin(
838
+ export async function lookupBitwardenItem(
822
839
  st: BwState,
823
840
  ctx: ExtensionContext | undefined,
824
841
  ref: string,
825
842
  signal?: AbortSignal,
826
- ): Promise<BitwardenLoginHit | undefined> {
843
+ ): Promise<BitwardenHit | undefined> {
827
844
  const session = await ensureUnlocked(st, ctx, signal);
828
845
  let item: LiteItem;
829
846
  try {
@@ -832,14 +849,12 @@ export async function lookupBitwardenLogin(
832
849
  if (e instanceof Error && /^No Bitwarden item matches/.test(e.message)) return undefined;
833
850
  throw e;
834
851
  }
835
- const secret = await secretOf(session, item, "password", signal);
836
- return {
837
- id: item.id ?? "",
838
- name: item.name || "unnamed",
839
- username: item.username,
840
- password: secret.value,
841
- uris: item.uri ? [item.uri] : [],
842
- };
852
+ if (!item.id) throw new Error(`Bitwarden item "${item.name}" has no id, so it cannot be read.`);
853
+ const full = (await runBwJson(["get", "item", item.id], session, signal)) as unknown;
854
+ const [draft] = bitwardenItems([full]);
855
+ if (!draft) return undefined;
856
+ const who = item.username ? ` ${item.username}` : "";
857
+ return { draft, label: `${draft.name}${who} (${item.type})` };
843
858
  }
844
859
 
845
860
  function normalizeEnvName(raw: string): string {
@@ -34,14 +34,19 @@ export interface CliRun {
34
34
 
35
35
  /** Non-zero exit from the CLI, with the meaning of the code preserved. */
36
36
  export class CliError extends Error {
37
+ /** For `needsUi === "password"`: the hidden field the CLI wants next. */
38
+ readonly field: string | undefined;
39
+
37
40
  constructor(
38
41
  readonly code: number,
39
42
  readonly needsUi: UiStep | undefined,
40
43
  message: string,
41
44
  readonly stderr: string,
45
+ field?: string,
42
46
  ) {
43
47
  super(message);
44
48
  this.name = "CliError";
49
+ this.field = field;
45
50
  }
46
51
 
47
52
  get denied(): boolean {
@@ -92,7 +97,7 @@ export function resolveBinary(): string | undefined {
92
97
  return undefined;
93
98
  }
94
99
 
95
- const NEEDS_UI = /^needs-ui:\s*(\w+)/m;
100
+ const NEEDS_UI = /^needs-ui:\s*(\w+)(?:\s+field=(\S+))?/m;
96
101
 
97
102
  function message(stderr: string, fallback: string): string {
98
103
  const lines = stderr
@@ -194,8 +199,9 @@ export class VaultCli {
194
199
  else child.stdin?.end();
195
200
  });
196
201
  if (run.code !== 0) {
197
- const step = NEEDS_UI.exec(run.stderr)?.[1] as UiStep | undefined;
198
- throw new CliError(run.code, step, message(run.stderr, `ai-vault exited with ${run.code}`), run.stderr);
202
+ const match = NEEDS_UI.exec(run.stderr);
203
+ const step = match?.[1] as UiStep | undefined;
204
+ throw new CliError(run.code, step, message(run.stderr, `ai-vault exited with ${run.code}`), run.stderr, match?.[2]);
199
205
  }
200
206
  return run;
201
207
  }
@@ -1,91 +1,199 @@
1
1
  /**
2
- * Map a Bitwarden JSON export or `bw list items` payload onto local vault
3
- * entries. Secrets stay in the returned objects for the caller to encrypt;
4
- * this module never writes them.
2
+ * Map a Bitwarden item onto a local vault entry, for every item type, field
3
+ * for field — the same table the CLI's `import.rs` uses, so both import paths
4
+ * (the CLI's `import` and this extension's `import-bw` / `vault_get` fallback)
5
+ * write identical entries.
6
+ *
7
+ * Type numbers and field names are Bitwarden's own, read out of its CLI:
8
+ * 1 login · 2 secureNote · 3 card · 4 identity · 5 sshKey
9
+ * 6 bankAccount · 7 driversLicense · 8 passport (behind its "new item types" flag)
10
+ * A secure note has no fields of its own: its content is the item's `notes`.
5
11
  */
6
- export interface LoginDraft {
7
- name: string;
8
- username?: string;
9
- password: string;
10
- uris: string[];
11
- notes?: string;
12
- /** Bitwarden item id: a re-import updates the same entry even after a rename. */
13
- source?: { kind: "bitwarden"; id: string };
12
+ import type { Draft, Field, ItemType } from "./types.js";
13
+
14
+ export const ITEM_TYPES: Record<ItemType, { code: number; key: string; fields: string[]; primary?: string }> = {
15
+ login: { code: 1, key: "login", fields: ["username", "password", "totp"], primary: "password" },
16
+ secureNote: { code: 2, key: "secureNote", fields: [] },
17
+ card: { code: 3, key: "card", fields: ["cardholderName", "brand", "number", "expMonth", "expYear", "code"], primary: "code" },
18
+ identity: {
19
+ code: 4,
20
+ key: "identity",
21
+ fields: [
22
+ "title", "firstName", "middleName", "lastName", "address1", "address2", "address3", "city", "state",
23
+ "postalCode", "country", "company", "email", "phone", "ssn", "username", "passportNumber", "licenseNumber",
24
+ ],
25
+ },
26
+ sshKey: { code: 5, key: "sshKey", fields: ["privateKey", "publicKey", "keyFingerprint"], primary: "privateKey" },
27
+ bankAccount: {
28
+ code: 6,
29
+ key: "bankAccount",
30
+ fields: ["bankName", "nameOnAccount", "accountType", "accountNumber", "routingNumber", "branchNumber", "pin", "swiftCode", "iban", "bankContactPhone"],
31
+ primary: "pin",
32
+ },
33
+ driversLicense: {
34
+ code: 7,
35
+ key: "driversLicense",
36
+ fields: ["firstName", "middleName", "lastName", "dateOfBirth", "licenseNumber", "issuingCountry", "issuingState", "issueDate", "expirationDate", "issuingAuthority", "licenseClass"],
37
+ },
38
+ passport: {
39
+ code: 8,
40
+ key: "passport",
41
+ fields: [
42
+ "surname", "givenName", "dateOfBirth", "sex", "birthPlace", "nationality", "issuingCountry", "passportNumber",
43
+ "passportType", "nationalIdentificationNumber", "issuingAuthority", "issueDate", "expirationDate",
44
+ ],
45
+ },
46
+ };
47
+
48
+ const BY_CODE = new Map(Object.entries(ITEM_TYPES).map(([name, spec]) => [spec.code, name as ItemType]));
49
+
50
+ /** The item type for Bitwarden's `.type`, as a human types it: note, ssh key, … */
51
+ export function parseItemType(raw: string | undefined): ItemType | undefined {
52
+ if (!raw) return "login";
53
+ const key = raw.toLowerCase().replace(/[^a-z0-9]/g, "");
54
+ const aliases: Record<string, ItemType> = {
55
+ login: "login",
56
+ password: "login",
57
+ note: "secureNote",
58
+ securenote: "secureNote",
59
+ card: "card",
60
+ creditcard: "card",
61
+ identity: "identity",
62
+ person: "identity",
63
+ sshkey: "sshKey",
64
+ ssh: "sshKey",
65
+ key: "sshKey",
66
+ bankaccount: "bankAccount",
67
+ bank: "bankAccount",
68
+ driverslicense: "driversLicense",
69
+ driverlicense: "driversLicense",
70
+ driverslicence: "driversLicense",
71
+ drivinglicence: "driversLicense",
72
+ license: "driversLicense",
73
+ passport: "passport",
74
+ };
75
+ return aliases[key] ?? (key === "" ? "login" : undefined);
14
76
  }
15
77
 
78
+ /** Fields whose value never appears in a listing or a confirm window. */
79
+ export function isSecretField(type: ItemType, field: string): boolean {
80
+ if (["password", "privateKey", "totp", "ssn", "licenseNumber", "passportNumber"].includes(field)) return true;
81
+ if (type === "card") return field === "code" || field === "number";
82
+ if (type === "bankAccount") return ["pin", "accountNumber", "routingNumber"].includes(field);
83
+ if (type === "passport") return field === "nationalIdentificationNumber";
84
+ return false;
85
+ }
86
+
87
+ const asRecord = (value: unknown): Record<string, unknown> | undefined =>
88
+ value && typeof value === "object" && !Array.isArray(value) ? (value as Record<string, unknown>) : undefined;
89
+ const text = (value: unknown): string | undefined => (typeof value === "string" && value.length > 0 ? value : undefined);
90
+
16
91
  function asItems(raw: unknown): unknown[] {
17
92
  if (Array.isArray(raw)) return raw;
18
- if (raw && typeof raw === "object") {
19
- const rec = raw as { encrypted?: unknown; items?: unknown };
20
- // An encrypted export carries ciphertext under `data`, not entries.
93
+ const rec = asRecord(raw);
94
+ if (rec) {
21
95
  if (rec.encrypted === true) {
22
- throw new Error(
23
- "This is an encrypted Bitwarden export. Use `bw export --format json` (password-protected, unencrypted) or /vault import-bw.",
24
- );
96
+ throw new Error("This is an encrypted Bitwarden export. Use `bw export --format json` (unencrypted) or /vault import-bw.");
25
97
  }
26
98
  if (Array.isArray(rec.items)) return rec.items;
27
99
  }
28
100
  throw new Error("Not a Bitwarden export: expected an array of items or an object with `items`.");
29
101
  }
30
102
 
31
- function uriList(login: Record<string, unknown>): string[] {
32
- if (!Array.isArray(login.uris)) return [];
33
- return login.uris.flatMap((entry) => {
34
- if (!entry || typeof entry !== "object" || !("uri" in entry)) return [];
35
- const uri = (entry as { uri?: unknown }).uri;
36
- return typeof uri === "string" && uri ? [uri] : [];
37
- });
103
+ /** Custom fields as Bitwarden stores them: 0 text · 1 hidden · 2 boolean · 3 linked. */
104
+ function customFields(rec: Record<string, unknown>): Field[] | undefined {
105
+ const list = Array.isArray(rec.fields) ? rec.fields : [];
106
+ const out: Field[] = [];
107
+ for (const raw of list) {
108
+ const f = asRecord(raw);
109
+ if (!f) continue;
110
+ out.push({
111
+ name: text(f.name) ?? "",
112
+ value: typeof f.value === "string" ? f.value : "",
113
+ type: typeof f.type === "number" ? f.type : 0,
114
+ ...(typeof f.linkedId === "number" ? { linkedId: String(f.linkedId) } : {}),
115
+ });
116
+ }
117
+ return out.length > 0 ? out : undefined;
38
118
  }
39
119
 
120
+ const cleanName = (raw: unknown): string => {
121
+ const cleaned = (typeof raw === "string" ? raw : "").replace(/[\r\n]+/g, " ").trim().slice(0, 200);
122
+ return cleaned || "unnamed";
123
+ };
124
+
40
125
  /**
41
- * Login items that have a password. Names are sorted, then duplicates become
42
- * `Name (2)`, `Name (3)`, … Each entry keeps its Bitwarden id, so a later
43
- * import updates the same row even when the numbering shifts.
126
+ * Every item of a Bitwarden export (or `bw list items` payload) as a draft.
127
+ * Items are matched to local entries by Bitwarden id, so a re-import updates
128
+ * the same row after a rename. Duplicate names within a type become `Name (2)`.
44
129
  */
45
- export function bitwardenLogins(raw: unknown): LoginDraft[] {
46
- const drafts: LoginDraft[] = [];
130
+ export function bitwardenItems(raw: unknown): Draft[] {
131
+ const drafts: Draft[] = [];
47
132
  for (const item of asItems(raw)) {
48
- if (!item || typeof item !== "object") continue;
49
- const rec = item as Record<string, unknown>;
50
- if (!rec.login || typeof rec.login !== "object") continue;
51
- const login = rec.login as Record<string, unknown>;
52
- const password = typeof login.password === "string" ? login.password : "";
53
- if (!password) continue;
54
- const username = typeof login.username === "string" && login.username ? login.username : undefined;
55
- const notes = typeof rec.notes === "string" && rec.notes ? rec.notes : undefined;
56
- const nameRaw = typeof rec.name === "string" ? rec.name : "";
57
- const name = nameRaw.replace(/[\r\n]+/g, " ").trim().slice(0, 200) || "unnamed";
58
- const id = typeof rec.id === "string" && rec.id ? rec.id : undefined;
133
+ const rec = asRecord(item);
134
+ if (!rec) continue;
135
+ const code = typeof rec.type === "number" ? rec.type : 1;
136
+ const type = BY_CODE.get(code);
137
+ if (!type) throw new Error(`unsupported Bitwarden item type ${code}`);
138
+ const spec = ITEM_TYPES[type];
139
+
140
+ const data: Record<string, string> = {};
141
+ const block = asRecord(rec[spec.key]);
142
+ if (block) {
143
+ for (const [field, value] of Object.entries(block)) {
144
+ if (field === "uris") continue;
145
+ const t = text(value);
146
+ if (t !== undefined) data[field] = t;
147
+ }
148
+ }
149
+ // A login carries username/password at the top level as well; the CLI
150
+ // mirrors those into `data`, so the block here keeps only `totp`.
151
+ if (type === "login") {
152
+ delete data.username;
153
+ delete data.password;
154
+ }
155
+ const loginUsername = type === "login" ? block?.username : undefined;
156
+ const loginPassword = type === "login" ? block?.password : undefined;
157
+ const uris = block && Array.isArray(block.uris)
158
+ ? block.uris.map((u) => text(asRecord(u)?.uri)).filter((u): u is string => u !== undefined)
159
+ : undefined;
160
+ const notes = text(rec.notes);
161
+ const source = text(rec.id) ? { kind: "bitwarden", id: text(rec.id) as string } : undefined;
162
+ const fields = customFields(rec);
163
+
59
164
  drafts.push({
60
- name,
61
- username,
62
- password,
63
- uris: uriList(login),
64
- notes,
65
- ...(id ? { source: { kind: "bitwarden" as const, id } } : {}),
165
+ name: cleanName(rec.name),
166
+ type,
167
+ ...(text(loginUsername) !== undefined ? { username: text(loginUsername) } : {}),
168
+ ...(text(loginPassword) !== undefined ? { password: text(loginPassword) } : {}),
169
+ ...(uris && uris.length > 0 ? { uris } : {}),
170
+ ...(Object.keys(data).length > 0 ? { data } : {}),
171
+ ...(notes !== undefined ? { notes } : {}),
172
+ ...(fields ? { fields } : {}),
173
+ ...(source ? { source } : {}),
66
174
  });
67
175
  }
68
- drafts.sort(
69
- (a, b) =>
70
- a.name.localeCompare(b.name) ||
71
- (a.username ?? "").localeCompare(b.username ?? "") ||
72
- (a.uris[0] ?? "").localeCompare(b.uris[0] ?? ""),
176
+
177
+ drafts.sort((a, b) =>
178
+ a.name.localeCompare(b.name) ||
179
+ a.type.localeCompare(b.type) ||
180
+ (a.username ?? "").localeCompare(b.username ?? ""),
73
181
  );
74
182
  const seen = new Map<string, number>();
75
- for (const item of drafts) {
76
- const key = item.name.toLowerCase();
77
- const n = (seen.get(key) ?? 0) + 1;
78
- seen.set(key, n);
79
- if (n > 1) item.name = `${item.name} (${n})`;
183
+ for (const d of drafts) {
184
+ const k = `${d.name.toLowerCase()}\n${d.type}`;
185
+ const n = (seen.get(k) ?? 0) + 1;
186
+ seen.set(k, n);
187
+ if (n > 1) d.name = `${d.name} (${n})`;
80
188
  }
81
189
  return drafts;
82
190
  }
83
191
 
84
192
  /** Case-insensitive substring match on name, username, and URIs. */
85
- export function filterLogins(items: LoginDraft[], search?: string): LoginDraft[] {
193
+ export function filterItems(items: Draft[], search?: string): Draft[] {
86
194
  const query = (search ?? "").trim().toLowerCase();
87
195
  if (!query) return items;
88
196
  return items.filter((item) =>
89
- `${item.name}\n${item.username ?? ""}\n${item.uris.join("\n")}`.toLowerCase().includes(query),
197
+ `${item.name}\n${item.username ?? ""}\n${(item.uris ?? []).join("\n")}`.toLowerCase().includes(query),
90
198
  );
91
199
  }