pi-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.
package/README.md CHANGED
@@ -31,7 +31,7 @@ Do not install `pi-bitwarden` or `omp-vault` as well: they register the same `bw
31
31
  |---|---|---|
32
32
  | `vault_list` | local store metadata | no |
33
33
  | `vault_get` | read one: local store first, then Bitwarden; a Bitwarden hit follows `bitwarden.import` (ask / import / read once) | yes, user-approved on the spot |
34
- | `vault_add` | store one; the password is typed in a dialog | no |
34
+ | `vault_add` | store one, any Bitwarden type (login, note, card, identity, sshkey, bankaccount, driverslicense, passport); secret fields are typed in a dialog | no |
35
35
  | `vault_import` | copy Bitwarden logins into the local store (asks first) | no |
36
36
  | `bw_list` / `bw_run` / `bw_clipboard` / `bw_reveal` | live Bitwarden through the `bw` CLI | no (`bw_reveal` excepted) |
37
37
  | `bw_inject` | inject into the bash env (**pi only**; omp does not register it) | no |
package/README.zh.md CHANGED
@@ -29,7 +29,7 @@ omp plugin install npm:pi-ai-vault # omp,同一个包
29
29
  |---|---|---|
30
30
  | `vault_list` | 本地库条目元数据 | 否 |
31
31
  | `vault_get` | 读一条:**先本地库,再 Bitwarden**;Bitwarden 命中会问「读一次 / 导入 ai-vault」 | 是,用户当场允许 |
32
- | `vault_add` | 存一条;密码由用户在弹出的窗口里输入 | 否 |
32
+ | `vault_add` | 存一条,Bitwarden 的全部类型(登录、笔记、银行卡、身份、SSH 密钥、银行账户、驾照、护照);秘密字段在弹窗里输 | 否 |
33
33
  | `vault_import` | 把 Bitwarden 登录项抄进本地库(先确认) | 否 |
34
34
  | `bw_list` / `bw_run` / `bw_clipboard` / `bw_reveal` | 在线 Bitwarden(`bw` CLI) | 否,`bw_reveal` 除外 |
35
35
  | `bw_inject` | 注入 bash 环境(**仅 pi**,omp 不注册) | 否 |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-ai-vault",
3
- "version": "0.10.0",
3
+ "version": "0.12.0",
4
4
  "description": "pi extension for ai-vault: one machine-wide encrypted secret store, live Bitwarden and Ente Auth. Works in pi and in omp (the omp fork reads the same manifest).",
5
5
  "repository": {
6
6
  "type": "git",
@@ -25,7 +25,7 @@
25
25
  "security"
26
26
  ],
27
27
  "dependencies": {
28
- "@xiaolikt/ai-vault": "0.10.0"
28
+ "@xiaolikt/ai-vault": "0.12.0"
29
29
  },
30
30
  "peerDependencies": {
31
31
  "@earendil-works/pi-coding-agent": "^1.5.0",
package/src/bitwarden.ts CHANGED
@@ -52,10 +52,11 @@ 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
- import { getSettingsSafe, settingsCli } from "./settings.js";
59
+ import { getSettingsSafe, settingsCli, settingsToken } from "./settings.js";
59
60
  import { tr } from "./i18n.js";
60
61
  import { scrubDeep, scrubText } from "./scrub.js";
61
62
 
@@ -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
  /**
@@ -598,7 +603,8 @@ async function ensureUnlocked(st: BwState, ctx: ExtensionContext | undefined, si
598
603
  if (policy.unlock !== "session") {
599
604
  // Keep the key where the CLI can hand it back; the file's expiry comes
600
605
  // from the bitwarden.hours policy.
601
- await settingsCli().run(["bw-session", "put"], { stdin: key }).catch(() => undefined);
606
+ const token = settingsToken();
607
+ await settingsCli().run(["bw-session", "put", ...(token ? ["--token", token] : [])], { stdin: key }).catch(() => undefined);
602
608
  }
603
609
  await auditEvent("unlock", "ok", st.sessionLabel);
604
610
  // Refresh in the background: a full sync can take seconds on large vaults.
@@ -624,12 +630,23 @@ async function ensureUnlocked(st: BwState, ctx: ExtensionContext | undefined, si
624
630
  return pending;
625
631
  }
626
632
 
633
+ const BW_TYPE_NAMES: Record<number, string> = { 1: "login", 2: "note", 3: "card", 4: "identity", 5: "sshKey", 6: "bankAccount", 7: "driversLicense", 8: "passport" };
634
+
627
635
  function toLite(raw: BwItem): LiteItem {
636
+ const type = BW_TYPE_NAMES[raw.type ?? 1] ?? `type-${raw.type}`;
637
+ // The identifying, non-secret line of each type: username for a login,
638
+ // cardholder for a card, a person's name for an identity, and so on.
639
+ const who =
640
+ raw.login?.username ??
641
+ raw.card?.cardholderName ??
642
+ (raw.identity ? [raw.identity.title, raw.identity.firstName, raw.identity.lastName].filter(Boolean).join(" ") : "") ??
643
+ "";
628
644
  return {
629
645
  id: raw.id ?? "",
630
646
  name: raw.name ?? "",
631
- username: raw.login?.username ?? "",
647
+ username: who,
632
648
  uri: raw.login?.uris?.[0]?.uri ?? "",
649
+ type,
633
650
  };
634
651
  }
635
652
 
@@ -796,34 +813,35 @@ export async function queryBitwarden(
796
813
  }
797
814
 
798
815
  /**
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.
816
+ * Every item that matches `search`, ready to store in the local vault: all
817
+ * types, field for field. Call only after the user has agreed to the import —
818
+ * this reads secrets.
801
819
  */
802
- export async function pullBitwardenLogins(
820
+ export async function pullBitwardenItems(
803
821
  st: BwState,
804
822
  ctx: ExtensionContext | undefined,
805
823
  search: string | undefined,
806
824
  signal?: AbortSignal,
807
- ): Promise<LoginDraft[]> {
825
+ ): Promise<Draft[]> {
808
826
  const session = await ensureUnlocked(st, ctx, signal);
809
827
  const raw: unknown = await runBwJson(["list", "items"], session, signal);
810
- return filterLogins(bitwardenLogins(raw), search);
828
+ return filterItems(bitwardenItems(raw), search);
811
829
  }
812
830
 
813
- export type BitwardenLoginHit = { id: string; name: string; username: string; password: string; uris: string[] };
831
+ export type BitwardenHit = { draft: Draft; label: string };
814
832
 
815
833
  /**
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.
834
+ * Look one item up, of any type, and return it as a draft with its secrets,
835
+ * with no window of its own: the caller shows the user what was found and asks
836
+ * whether to read it. `undefined` means "no such item"; an ambiguous reference
837
+ * throws with the candidates so the model can pick one.
820
838
  */
821
- export async function lookupBitwardenLogin(
839
+ export async function lookupBitwardenItem(
822
840
  st: BwState,
823
841
  ctx: ExtensionContext | undefined,
824
842
  ref: string,
825
843
  signal?: AbortSignal,
826
- ): Promise<BitwardenLoginHit | undefined> {
844
+ ): Promise<BitwardenHit | undefined> {
827
845
  const session = await ensureUnlocked(st, ctx, signal);
828
846
  let item: LiteItem;
829
847
  try {
@@ -832,14 +850,12 @@ export async function lookupBitwardenLogin(
832
850
  if (e instanceof Error && /^No Bitwarden item matches/.test(e.message)) return undefined;
833
851
  throw e;
834
852
  }
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
- };
853
+ if (!item.id) throw new Error(`Bitwarden item "${item.name}" has no id, so it cannot be read.`);
854
+ const full = (await runBwJson(["get", "item", item.id], session, signal)) as unknown;
855
+ const [draft] = bitwardenItems([full]);
856
+ if (!draft) return undefined;
857
+ const who = item.username ? ` ${item.username}` : "";
858
+ return { draft, label: `${draft.name}${who} (${item.type})` };
843
859
  }
844
860
 
845
861
  function normalizeEnvName(raw: string): string {
package/src/cli.ts CHANGED
@@ -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
  }
package/src/import-map.ts CHANGED
@@ -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
  }
package/src/index.ts CHANGED
@@ -15,19 +15,21 @@ 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
- import { CliError, VaultCli } from "./cli.js";
26
+ import { CliError } 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";
30
- import { forgetSettings, getSettingsSafe, type Settings } from "./settings.js";
32
+ import { forgetSettings, getSettingsSafe, setSettingsToken, settingsCli, settingsToken, type Settings } from "./settings.js";
31
33
 
32
34
  type Ctx = ExtensionToolContext | ExtensionCommandContext;
33
35
 
@@ -98,7 +100,7 @@ interface Scope {
98
100
  unlocking?: Promise<boolean>;
99
101
  }
100
102
 
101
- const cli = new VaultCli();
103
+ const cli = settingsCli();
102
104
 
103
105
  const CLI_MISSING =
104
106
  tr("ai-vault CLI not found. Install it once for a machine-wide store: cargo install --path <repo>/crates/ai-vault (or point AI_VAULT_BIN at a compiled binary)", "ai-vault CLI 没找到。装一次就有全机共享的库:cargo install --path <repo>/crates/ai-vault(或用 AI_VAULT_BIN 指向编译好的二进制)");
@@ -146,6 +148,8 @@ async function lockNow(scope: Scope): Promise<void> {
146
148
  scope.token = undefined;
147
149
  scope.epoch++;
148
150
  scope.items = 0;
151
+ setSettingsToken(undefined);
152
+ forgetSettings();
149
153
  if (!token || !cli.available) return;
150
154
  try {
151
155
  await cli.run(["lock", "--token", token]);
@@ -172,6 +176,7 @@ async function ensureUnlocked(scope: Scope, ctx: Ctx, signal?: AbortSignal): Pro
172
176
  scope.items = status.items;
173
177
  scope.mode = status.mode;
174
178
  scope.auto = false;
179
+ setSettingsToken(scope.token);
175
180
  return true;
176
181
  } catch (error) {
177
182
  if (!(error instanceof CliError) || !error.auth) {
@@ -192,6 +197,7 @@ async function ensureUnlocked(scope: Scope, ctx: Ctx, signal?: AbortSignal): Pro
192
197
  scope.items = status.items;
193
198
  scope.mode = status.mode;
194
199
  scope.auto = status.auto;
200
+ setSettingsToken(undefined);
195
201
  return true;
196
202
  } catch (error) {
197
203
  if (error instanceof CliError && /not initialized/i.test(error.message)) {
@@ -235,6 +241,7 @@ async function ensureUnlocked(scope: Scope, ctx: Ctx, signal?: AbortSignal): Pro
235
241
  // per-binding token would bring back a confirm window on every read.
236
242
  scope.token = result.mode === "never" ? undefined : result.token;
237
243
  scope.items = result.items;
244
+ setSettingsToken(scope.token);
238
245
  return true;
239
246
  } catch (error) {
240
247
  if (error instanceof CliError && error.auth) {
@@ -308,44 +315,34 @@ async function bitwardenFallback(
308
315
  const missing = localMiss;
309
316
  let hit;
310
317
  try {
311
- hit = await lookupBitwardenLogin(bw, ctx, name, signal);
318
+ hit = await lookupBitwardenItem(bw, ctx, name, signal);
312
319
  } catch (error) {
313
320
  return fail(`${missing} — the Bitwarden lookup failed: ${describe(error)}`);
314
321
  }
315
322
  if (!hit) return fail(`${missing} — not in Bitwarden either${reason ? ` (reason: ${reason})` : ""}`);
323
+ const draft = hit.draft;
324
+ const secret = draft.type === "login" ? draft.password : (draft.data?.[ITEM_TYPES[draft.type].primary ?? ""] ?? "");
316
325
 
317
326
  const asValue = (via: string): ToolOutcome => ({
318
327
  content: [
319
328
  {
320
329
  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
- ),
330
+ text: JSON.stringify({ ...draft, password: secret ?? draft.password, via }, null, 1),
326
331
  },
327
332
  ],
328
- details: { item: hit.name, via },
333
+ details: { item: draft.name, via },
329
334
  });
330
335
 
331
336
  const importIt = async (): Promise<ToolOutcome> => {
332
337
  try {
333
338
  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
- ]),
339
+ stdin: JSON.stringify([draft]),
343
340
  signal,
344
341
  });
345
342
  scope.items += saved.count;
346
343
  setStatus(ctx, scope);
347
344
  } catch (error) {
348
- return fail(`found "${hit.name}" in Bitwarden but could not import it: ${describe(error)}`);
345
+ return fail(`found "${draft.name}" in Bitwarden but could not import it: ${describe(error)}`);
349
346
  }
350
347
  return asValue("imported-from-bitwarden");
351
348
  };
@@ -356,20 +353,25 @@ async function bitwardenFallback(
356
353
  return importIt();
357
354
  }
358
355
 
359
- const label = `${hit.name}${hit.username ? ` user:${hit.username}` : ""}`;
360
356
  const allow = await confirmWindow(
361
357
  dialogs(ctx),
362
358
  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读取这一次吗?`),
359
+ tr(
360
+ `Not in the local store as "${forDialog(name)}", but Bitwarden has:\n${forDialog(hit.label)}\n\nRead it this once?`,
361
+ `本地库没有「${forDialog(name)}」,Bitwarden 里有:\n${forDialog(hit.label)}\n\n读取这一次吗?`,
362
+ ),
364
363
  signal,
365
364
  );
366
- if (!allow) return fail(`user denied reading "${hit.name}" from Bitwarden — do not retry`, true);
365
+ if (!allow) return fail(`user denied reading "${draft.name}" from Bitwarden — do not retry`, true);
367
366
  if (policy === "never") return asValue("bitwarden-once");
368
367
 
369
368
  const confirmed = await confirmWindow(
370
369
  dialogs(ctx),
371
370
  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拒绝 → 只用这一次,不写入本地库`),
371
+ tr(
372
+ `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`,
373
+ `把「${forDialog(draft.name)}」写进 ai-vault 吗?\n\n允许 → 以后直接读本地库(按当前解锁模式,可能免密)\n拒绝 → 只用这一次,不写入本地库`,
374
+ ),
373
375
  signal,
374
376
  );
375
377
  return confirmed ? importIt() : asValue("bitwarden-once");
@@ -446,26 +448,62 @@ function vaultGetTool(scope: Scope, bw: BwState): ToolDefinition<typeof vaultGet
446
448
 
447
449
  const vaultAddParams = Type.Object({
448
450
  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." })),
451
+ type: Type.Optional(
452
+ Type.String({
453
+ description:
454
+ "Item type, as in Bitwarden: login (default), note, card, identity, sshkey, bankaccount, driverslicense, passport. " +
455
+ "A note's content goes in `notes`.",
456
+ }),
457
+ ),
458
+ username: Type.Optional(Type.String({ description: "Login: account username. Omit to let the user type it in a dialog." })),
459
+ uri: Type.Optional(Type.String({ description: "Login: site or host URI" })),
460
+ notes: Type.Optional(Type.String({ description: "Notes shared by every type. For a `note` entry this is its content." })),
461
+ fields: Type.Optional(
462
+ Type.Record(
463
+ Type.String(),
464
+ Type.Optional(Type.String()),
465
+ {
466
+ description:
467
+ "The type's own fields by Bitwarden's names (card: cardholderName, brand, number, expMonth, expYear, code; " +
468
+ "sshkey: publicKey, privateKey, keyFingerprint; identity: firstName, lastName, email, …). " +
469
+ "Give a non-secret field as text; give a secret field (password, code, number, privateKey, pin, ssn…) " +
470
+ "as null/undefined so the user types it in a dialog. NEVER put a secret value here.",
471
+ },
472
+ ),
473
+ ),
452
474
  });
453
475
  function vaultAddTool(scope: Scope): ToolDefinition<typeof vaultAddParams, { ok?: boolean; item?: string }> {
454
476
  const tool: ToolDefinition<typeof vaultAddParams, { ok?: boolean; item?: string }> = {
455
477
  name: "vault_add",
456
478
  label: "Vault: store a secret via dialog",
457
479
  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.",
480
+ "Create or update an entry of any Bitwarden type in the machine-wide ai-vault store (login, note, card, identity, sshkey, " +
481
+ "bankaccount, driverslicense, passport). You supply the name, the type and its non-secret fields. " +
482
+ "Secret fields (password, card number and code, private key, PIN, SSN…) are typed by the user in a desktop window: " +
483
+ "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
484
  promptSnippet: "Save a local vault entry; the user types the password in a window.",
462
485
  parameters: vaultAddParams,
463
486
  async execute(_id, params, signal, _onUpdate, ctx) {
487
+ const kind = parseItemType(params.type);
488
+ if (!kind) {
489
+ return fail(`unknown type "${params.type}" — login, note, card, identity, sshkey, bankaccount, driverslicense, passport`);
490
+ }
491
+ // A secret field the model filled in is refused rather than stored:
492
+ // only the user types secrets, in a dialog.
493
+ const fields: Record<string, string | undefined> = {};
494
+ for (const [field, value] of Object.entries(params.fields ?? {})) {
495
+ if (value !== undefined && value !== "" && isSecretField(kind, field)) {
496
+ return fail(`"${field}" is a secret field: leave it empty so the user types it in a dialog`);
497
+ }
498
+ fields[field] = value === "" ? undefined : value;
499
+ }
464
500
  const result = await saveLocalEntry(scope, ctx, {
465
501
  name: params.name,
502
+ type: kind,
466
503
  username: params.username,
467
504
  uri: params.uri,
468
505
  notes: params.notes,
506
+ fields,
469
507
  signal,
470
508
  });
471
509
  const ok = result.startsWith("saved ");
@@ -508,9 +546,12 @@ function vaultImportTool(scope: Scope, bw: BwState): ToolDefinition<typeof vault
508
546
 
509
547
  interface SaveRequest {
510
548
  name?: string;
549
+ type?: ItemType;
511
550
  username?: string;
512
551
  uri?: string;
513
552
  notes?: string;
553
+ /** The type's own fields, NAME=VALUE; a value of `undefined` means "typed in a dialog". */
554
+ fields?: Record<string, string | undefined>;
514
555
  signal?: AbortSignal;
515
556
  }
516
557
 
@@ -524,18 +565,33 @@ async function saveLocalEntry(scope: Scope, ctx: Ctx, req: SaveRequest): Promise
524
565
  }
525
566
  if (!name) return "cancelled: no entry name";
526
567
 
527
- const args = ["add", "--name", name, "--token", scope.token!];
568
+ const kind = req.type ?? "login";
569
+ const args = ["add", "--name", name, "--type", kind, "--token", scope.token!];
528
570
  if (req.username !== undefined) args.push("--username", req.username);
529
571
  if (req.uri?.trim()) args.push("--uri", req.uri.trim());
530
572
  if (req.notes?.trim()) args.push("--notes", req.notes.trim());
531
- let stdin: string | undefined;
532
- for (let attempt = 0; attempt < 5; attempt++) {
573
+ const secrets = new Map<string, string>();
574
+ const shown: string[] = [];
575
+ for (const [field, value] of Object.entries(req.fields ?? {})) {
576
+ if (value === undefined) shown.push(`${field} ••••`);
577
+ else {
578
+ args.push("--field", `${field}=${value}`);
579
+ shown.push(`${field} ${isSecretField(kind, field) ? "••••" : forDialog(value, 120)}`);
580
+ }
581
+ }
582
+ const flush = () => {
583
+ // --secret args are re-added on every attempt: the CLI is stateless.
584
+ for (let i = args.length - 1; i >= 0; i--) if (args[i] === "--secret") args.splice(i, 2);
585
+ for (const [field, value] of secrets) args.push("--secret", `${field}=${value}`);
586
+ };
587
+ for (let attempt = 0; attempt < 8; attempt++) {
588
+ flush();
533
589
  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 };
590
+ const run = await cli.run([...args, "--json"], { signal: req.signal });
591
+ const saved = JSON.parse(run.stdout) as { item?: string; created?: boolean; type?: string };
536
592
  if (saved.created) scope.items += 1;
537
593
  setStatus(ctx, scope);
538
- return `saved "${saved.item ?? name}" (password entered in the dialog, not shown)`;
594
+ return `saved "${saved.item ?? name}" as a ${saved.type ?? kind} (hidden fields entered in dialogs, not shown)`;
539
595
  } catch (error) {
540
596
  if (!(error instanceof CliError) || !error.needsUi) {
541
597
  if (error instanceof CliError && error.auth) scope.token = undefined;
@@ -543,6 +599,7 @@ async function saveLocalEntry(scope: Scope, ctx: Ctx, req: SaveRequest): Promise
543
599
  }
544
600
  if (error.needsUi === "confirm") {
545
601
  const meta = [
602
+ ...shown,
546
603
  req.username?.trim() ? tr(`Username: ${forDialog(req.username, 60)}`, `用户名: ${forDialog(req.username, 60)}`) : "",
547
604
  req.uri?.trim() ? `URI: ${forDialog(req.uri, 120)}` : "",
548
605
  req.notes?.trim() ? tr(`Notes: ${forDialog(req.notes, 120)}`, `备注: ${forDialog(req.notes, 120)}`) : "",
@@ -552,7 +609,10 @@ async function saveLocalEntry(scope: Scope, ctx: Ctx, req: SaveRequest): Promise
552
609
  const ok = await confirmWindow(
553
610
  dialogs(ctx),
554
611
  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下一步会弹出窗口,由你输入密码。密码不会进入对话。`),
612
+ tr(
613
+ `Save the ${kind} entry "${forDialog(name)}".${meta ? `\n${meta}` : ""}\nA window opens next for each hidden field. Nothing enters the conversation.`,
614
+ `保存${kind}条目「${forDialog(name)}」。${meta ? `\n${meta}` : ""}\n接下来每个隐藏字段弹一个窗口。密码不会进入对话。`,
615
+ ),
556
616
  req.signal,
557
617
  );
558
618
  if (!ok) return `user denied saving "${name}"`;
@@ -565,10 +625,11 @@ async function saveLocalEntry(scope: Scope, ctx: Ctx, req: SaveRequest): Promise
565
625
  args.push("--username", entered);
566
626
  continue;
567
627
  }
568
- const password = await promptSecret(dialogs(ctx), tr("ai-vault · password", "ai-vault · 密码"), name, req.signal);
628
+ // needsUi === "password": one hidden field at a time, named by the CLI.
629
+ const field = error.field ?? ITEM_TYPES[kind].primary ?? "password";
630
+ const password = await promptSecret(dialogs(ctx), tr("ai-vault · password", "ai-vault · 密码"), `${name} · ${field}`, req.signal);
569
631
  if (!password) return "cancelled: no password entered";
570
- args.push("--password-stdin");
571
- stdin = `${password}\n`;
632
+ secrets.set(field, password);
572
633
  }
573
634
  }
574
635
  return "cancelled: the save dialog did not settle";
@@ -605,12 +666,12 @@ async function importBitwarden(
605
666
  if (!allowed) return { text: "user denied the Bitwarden import", ok: false, count: 0 };
606
667
  let drafts;
607
668
  try {
608
- drafts = await pullBitwardenLogins(bw, ctx, search, signal);
669
+ drafts = await pullBitwardenItems(bw, ctx, search, signal);
609
670
  } catch (error) {
610
671
  return { text: `Bitwarden: ${describe(error)}`, ok: false, count: 0 };
611
672
  }
612
673
  if (drafts.length === 0) {
613
- return { text: "matched items have no login password; nothing imported", ok: false, count: 0 };
674
+ return { text: "nothing matched; nothing imported", ok: false, count: 0 };
614
675
  }
615
676
  try {
616
677
  const saved = await cli.json<SaveResult>(["save", "--yes", "--token", scope.token!], {
@@ -637,6 +698,7 @@ const HELP = [
637
698
  tr("/vault init create the machine-wide encrypted store (a dialog sets the master password)", "/vault init 创建全机共享的本地加密库(弹出窗口设置主密码)"),
638
699
  tr("/vault unlock | lock unlock / lock (clears this session's grants)", "/vault unlock | lock 解锁 / 锁定(清空本会话的授权)"),
639
700
  tr("/vault mode [never|time|session] show/switch the unlock policy (switching needs the master password)", "/vault mode [never|time|session] 查看/切换解锁模式(切换要主密码)"),
701
+ tr("/vault confirm [off|on] a window per read while unlocked (off asks the master password)", "/vault confirm [off|on] 解锁后每次读取是否弹确认窗(关要主密码)"),
640
702
  tr("/vault settings [key value] show/change settings (vault.unlock, bitwarden.*, ente.* …)", "/vault settings [键 值] 查看/修改设置(vault.unlock、bitwarden.*、ente.* …)"),
641
703
  tr("/vault ente-key save Ente's ENTE_CLI_VAULT_KEY (no keychain, no login)", "/vault ente-key 保存 ente 的 ENTE_CLI_VAULT_KEY(免钥匙串/免登录)"),
642
704
  tr("/vault status state and grants left", "/vault status 状态与授权剩余时间"),
@@ -805,22 +867,61 @@ function commandHandler(scope: Scope, bw: BwState) {
805
867
  }
806
868
  return;
807
869
  }
870
+ case "confirm": {
871
+ // /vault confirm show
872
+ // /vault confirm off|on turn the per-read window off (asks the master password) / on
873
+ const [arg] = rest;
874
+ if (!arg) {
875
+ try {
876
+ const current = await cli.json<Settings>(["settings", ...tokenArgs(scope)]);
877
+ note(ctx, `vault.confirm: ${current.vault.confirm}${current.vault.confirm ? tr(" (a window per read while unlocked)", " (解锁后每次读取弹确认窗)") : tr(" (the unlock is the approval; reads are audited)", " (解锁即授权;读取仍记审计)")}`);
878
+ } catch (error) {
879
+ note(ctx, `ai-vault: ${describe(error)}`, "error");
880
+ }
881
+ return;
882
+ }
883
+ const value = arg.toLowerCase();
884
+ if (!["off", "on", "false", "true"].includes(value)) {
885
+ note(ctx, tr("usage: /vault confirm [off|on]", "用法: /vault confirm [off|on]"), "warning");
886
+ return;
887
+ }
888
+ const turnOff = value === "off" || value === "false";
889
+ try {
890
+ const run = await cli.withPassword(["settings", "vault.confirm", turnOff ? "false" : "true", ...tokenArgs(scope)], () =>
891
+ promptSecret(dialogs(ctx), tr("ai-vault · master password", "ai-vault · 主密码"), tr("turn off the per-read confirmation", "关闭每次读取的确认窗")),
892
+ );
893
+ forgetSettings();
894
+ const updated = JSON.parse(run.stdout) as Settings;
895
+ note(
896
+ ctx,
897
+ updated.vault.confirm
898
+ ? tr("vault.confirm is on: every read opens a confirm window.", "vault.confirm 已开:每次读取弹确认窗。")
899
+ : tr(
900
+ "vault.confirm is off: while a session is unlocked, reads return without a window. Each read is still written to the audit log. Turning it back on: /vault confirm on",
901
+ "vault.confirm 已关:会话解锁期间读取不再弹窗。每次读取仍写审计。重新打开:/vault confirm on",
902
+ ),
903
+ );
904
+ } catch (error) {
905
+ note(ctx, `ai-vault: ${error instanceof CliError && error.denied ? tr("cancelled", "已取消") : describe(error)}`, "warning");
906
+ }
907
+ return;
908
+ }
808
909
  case "settings": {
809
910
  const [key, ...valueParts] = rest;
810
911
  const value = valueParts.join(" ").trim();
811
912
  try {
812
913
  if (!key) {
813
- note(ctx, settingsText(await cli.json<Settings>(["settings"])));
914
+ note(ctx, settingsText(await cli.json<Settings>(["settings", ...tokenArgs(scope)])));
814
915
  return;
815
916
  }
816
917
  if (!value) {
817
- const one = await cli.json<{ key: string; value: string }>(["settings", key]);
918
+ const one = await cli.json<{ key: string; value: string }>(["settings", key, ...tokenArgs(scope)]);
818
919
  note(ctx, `${one.key}: ${one.value}`);
819
920
  return;
820
921
  }
821
922
  // `vault.unlock` opens its own password window (or answers
822
923
  // needs-ui); the other keys do not prompt at all.
823
- const run = await cli.withPassword(["settings", key, value], () =>
924
+ const run = await cli.withPassword(["settings", key, value, ...tokenArgs(scope)], () =>
824
925
  promptSecret(dialogs(ctx), tr("ai-vault · master password", "ai-vault · 主密码"), tr("changing the unlock policy needs verification", "改变解锁模式需要验证")),
825
926
  );
826
927
  forgetSettings();
@@ -891,7 +992,30 @@ function commandHandler(scope: Scope, bw: BwState) {
891
992
  return;
892
993
  }
893
994
  case "add": {
894
- const text = await saveLocalEntry(scope, ctx, { name: rest.join(" ") || undefined });
995
+ // /vault add [type:]name [field=value ...] [field] — a bare
996
+ // `field` is typed in a dialog. /vault add card:Visa brand=Visa code
997
+ const [first, ...pairs] = rest;
998
+ let type: ItemType | undefined;
999
+ let name = first ?? "";
1000
+ const m = /^([a-z]+):(.+)$/.exec(first ?? "");
1001
+ if (m) {
1002
+ const parsed = parseItemType(m[1]);
1003
+ if (parsed) {
1004
+ type = parsed;
1005
+ name = m[2] ?? name;
1006
+ }
1007
+ }
1008
+ const fields: Record<string, string | undefined> = {};
1009
+ let notes: string | undefined;
1010
+ for (const pair of pairs) {
1011
+ const eq = pair.indexOf("=");
1012
+ const key = eq < 0 ? pair : pair.slice(0, eq);
1013
+ const value = eq < 0 ? "" : pair.slice(eq + 1);
1014
+ if (!key) continue;
1015
+ if (key === "notes" || key === "note") notes = value;
1016
+ else fields[key] = value === "" ? undefined : value;
1017
+ }
1018
+ const text = await saveLocalEntry(scope, ctx, { name: name.trim() || undefined, type, fields, notes });
895
1019
  note(ctx, text, text.startsWith("saved ") ? "info" : "warning");
896
1020
  return;
897
1021
  }
package/src/settings.ts CHANGED
@@ -11,7 +11,7 @@ export type UnlockModeName = "never" | "time" | "session";
11
11
  export type ImportPolicy = "ask" | "always" | "never";
12
12
 
13
13
  export interface Settings {
14
- vault: { unlock: UnlockModeName; hours: number; auto: boolean };
14
+ vault: { unlock: UnlockModeName; hours: number; confirm: boolean; auto: boolean };
15
15
  bitwarden: {
16
16
  unlock: UnlockModeName;
17
17
  hours: number;
@@ -24,17 +24,42 @@ export interface Settings {
24
24
  }
25
25
 
26
26
  export const DEFAULT_SETTINGS: Settings = {
27
- vault: { unlock: "session", hours: 8, auto: false },
27
+ vault: { unlock: "session", hours: 8, confirm: true, auto: false },
28
28
  bitwarden: { unlock: "session", hours: 8, import: "ask", persisted: false, expiresAt: null },
29
29
  ente: { unlock: "session", hours: 8, persisted: false, expiresAt: null },
30
30
  };
31
31
 
32
- const cli = new VaultCli();
33
- let cache: { at: number; value: Settings } | undefined;
32
+ /**
33
+ * One CLI client for the whole extension. It carries the one `HostSecret`
34
+ * every call must be signed under: a second instance would have its own
35
+ * (empty) secret, and a call made through it would fail the session file's
36
+ * HMAC and get it deleted — locking the binding out. Keep this the same
37
+ * object the tools use.
38
+ */
39
+ let cli: VaultCli | undefined;
34
40
 
35
- /** The shared CLI client, for the pieces that read and write the settings. */
36
41
  export function settingsCli(): VaultCli {
37
- return cli;
42
+ return (cli ??= new VaultCli());
43
+ }
44
+
45
+ let cache: { at: number; value: Settings } | undefined;
46
+
47
+ /**
48
+ * The session token the settings are read under. The settings live inside the
49
+ * store's ciphertext, so reading them is a privileged call like any other;
50
+ * the binding that unlocked sets this before asking.
51
+ */
52
+ let sessionToken: string | undefined;
53
+
54
+ export function setSettingsToken(token: string | undefined): void {
55
+ if (token !== sessionToken) {
56
+ sessionToken = token;
57
+ cache = undefined;
58
+ }
59
+ }
60
+
61
+ export function settingsToken(): string | undefined {
62
+ return sessionToken;
38
63
  }
39
64
 
40
65
  /**
@@ -43,7 +68,7 @@ export function settingsCli(): VaultCli {
43
68
  */
44
69
  export async function getSettings(signal?: AbortSignal, options: { fresh?: boolean } = {}): Promise<Settings> {
45
70
  if (!options.fresh && cache && Date.now() - cache.at < 30_000) return cache.value;
46
- const value = await cli.json<Settings>(["settings"], { signal });
71
+ const value = await settingsCli().json<Settings>(["settings", ...(sessionToken ? ["--token", sessionToken] : [])], { signal });
47
72
  cache = { at: Date.now(), value };
48
73
  return value;
49
74
  }
@@ -60,3 +85,8 @@ export async function getSettingsSafe(signal?: AbortSignal): Promise<Settings> {
60
85
  export function forgetSettings(): void {
61
86
  cache = undefined;
62
87
  }
88
+
89
+ /** Tests change the store's settings from outside the process; let them drop the cache. */
90
+ process.on("ai-vault:settings-changed", () => {
91
+ cache = undefined;
92
+ });
package/src/types.ts ADDED
@@ -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
+ }