@xiaolikt/ai-vault 0.10.0 → 0.12.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.
@@ -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
  }