pi-ai-vault 0.5.0 → 0.7.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
@@ -51,7 +51,19 @@ omp plugin install npm:pi-ai-vault # omp,同一个包
51
51
  | `time` | 解锁后 N 小时(默认 8)再问一次 |
52
52
  | `session` | 每个会话一次,会话结束失效(默认) |
53
53
 
54
- `vault_get` 找不到本地条目时会去 Bitwarden 搜;命中后先给你看这一条并问是否读取,读了再问「导入 ai-vault(以后免 Bitwarden)还是只用这一次」。所以 **只有你同意导入的密码才会进 ai-vault**。
54
+ `vault_get` 找不到本地条目时会去 Bitwarden 搜;命中后按 `bitwarden.import` 处理:
55
+
56
+ | `bitwarden.import` | 行为 |
57
+ |---|---|
58
+ | `ask`(默认) | 给你看这一条 → 读一次 → 问「导入 ai-vault / 只用这一次」 |
59
+ | `always` | 命中直接导入并返回,不开窗口 |
60
+ | `never` | 只读一次,永不写入本地库 |
61
+
62
+ 所以默认情况下 **只有你同意导入的密码才会进 ai-vault**。Bitwarden 自己的主密码请求频率也有单独设置(`bitwarden.unlock`:`never` / `time` / `session`),用 `/vault settings` 查看和修改。
63
+
64
+ ## 安全边界(一句话版)
65
+
66
+ 模型的 `bash` 能找到会话令牌、能 `list`,但**签不出读取确认**(签名密钥只在插件进程内存里)、**改不了令牌文件**(带 HMAC,改了就作废)、**免费拿不到 `grant`**(要主密码)。详见仓库 README「安全」一节。
55
67
 
56
68
  ## 隔离
57
69
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-ai-vault",
3
- "version": "0.5.0",
3
+ "version": "0.7.0",
4
4
  "description": "pi extension for ai-vault: one machine-wide encrypted secret store plus live Bitwarden. 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.5.0"
28
+ "@xiaolikt/ai-vault": "0.7.0"
29
29
  },
30
30
  "peerDependencies": {
31
31
  "@earendil-works/pi-coding-agent": "^1.5.0",
package/src/bitwarden.ts CHANGED
@@ -55,6 +55,7 @@ import { Type } from "typebox";
55
55
  import { bitwardenLogins, filterLogins, type LoginDraft } from "./import-map.js";
56
56
  import { onSessionLeave, sessionLabel, withTier } from "./host.js";
57
57
  import { confirmWindow, hasDisplay, promptSecret } from "./prompt.js";
58
+ import { getSettingsSafe, settingsCli } from "./settings.js";
58
59
  import { scrubDeep, scrubText } from "./scrub.js";
59
60
 
60
61
  // ---------------------------------------------------------------------------
@@ -492,6 +493,9 @@ function startAutoLock(st: BwState, ctx: ExtensionContext | undefined): void {
492
493
  /** Drop this binding's session key and injected variables, and the clipboard. */
493
494
  async function lock(st: BwState, reason: string): Promise<void> {
494
495
  const hadSession = !!st.key;
496
+ // A key kept for `bitwarden.unlock = never | time` must go with an explicit
497
+ // lock, or the next call would silently unlock again.
498
+ void settingsCli().run(["bw-session", "clear"]).catch(() => undefined);
495
499
  st.epoch++;
496
500
  st.key = undefined;
497
501
  st.verifiedAt = 0;
@@ -545,6 +549,27 @@ async function ensureUnlocked(st: BwState, ctx: ExtensionContext | undefined, si
545
549
 
546
550
  const epoch = st.epoch;
547
551
  const pending = (async () => {
552
+ const policy = (await getSettingsSafe(signal)).bitwarden;
553
+ // `never` / `time`: the CLI keeps the session key (0600, in the store
554
+ // directory), so Bitwarden costs no window at all.
555
+ if (policy.unlock !== "session") {
556
+ try {
557
+ const saved = await settingsCli().json<{ key: string }>(["bw-session", "get"], { signal });
558
+ if (saved?.key) {
559
+ const verify = await bwStatus(saved.key, signal);
560
+ if (verify?.status === "unlocked") {
561
+ st.key = saved.key;
562
+ st.verifiedAt = Date.now();
563
+ acquireSessionKey();
564
+ startAutoLock(st, ctx);
565
+ return saved.key;
566
+ }
567
+ }
568
+ } catch {
569
+ /* absent or expired: fall through to the password */
570
+ }
571
+ }
572
+
548
573
  const status = await bwStatus(undefined, signal); // no session env
549
574
  if (status?.status === "unauthenticated") throw new Error(BW_LOGIN_HINT);
550
575
 
@@ -569,6 +594,11 @@ async function ensureUnlocked(st: BwState, ctx: ExtensionContext | undefined, si
569
594
  st.verifiedAt = Date.now();
570
595
  acquireSessionKey();
571
596
  startAutoLock(st, ctx);
597
+ if (policy.unlock !== "session") {
598
+ // Keep the key where the CLI can hand it back; the file's expiry comes
599
+ // from the bitwarden.hours policy.
600
+ await settingsCli().run(["bw-session", "put"], { stdin: key }).catch(() => undefined);
601
+ }
572
602
  await audit("unlock", "ok", st.sessionLabel);
573
603
  // Refresh in the background: a full sync can take seconds on large vaults.
574
604
  const lastSync = Date.parse(status?.lastSync ?? "");
package/src/cli.ts CHANGED
@@ -7,6 +7,7 @@
7
7
  * windows; a headless machine answers exit code 3 ("needs-ui") and the host
8
8
  * dialog takes over here.
9
9
  */
10
+ import { createHmac, randomBytes } from "node:crypto";
10
11
  import { spawn } from "node:child_process";
11
12
  import { existsSync } from "node:fs";
12
13
  import { homedir } from "node:os";
@@ -91,8 +92,54 @@ function message(stderr: string, fallback: string): string {
91
92
  return lines[0]?.replace(/^ai-vault:\s*/, "") ?? fallback;
92
93
  }
93
94
 
95
+ /**
96
+ * The secret this process keeps for the sessions it unlocked. It never reaches
97
+ * disk: the CLI writes it into the HMAC on each session file, and uses it to
98
+ * check the approvals we relay. A model-driven `bash` that finds a session
99
+ * token can therefore `list`, but can neither forge a read approval nor edit
100
+ * the token's grants.
101
+ */
102
+ export class HostSecret {
103
+ #value: string | undefined;
104
+
105
+ get present(): boolean {
106
+ return this.#value !== undefined;
107
+ }
108
+
109
+ /** Use the one the CLI echoed back at unlock time (it is ours already). */
110
+ adopt(secret: string | undefined): void {
111
+ if (secret && secret.length >= 32) this.#value = secret;
112
+ }
113
+
114
+ /** 32 fresh bytes, hex — minted once per process, before the first unlock. */
115
+ rotate(): string {
116
+ this.#value = randomBytes(32).toString("hex");
117
+ return this.#value;
118
+ }
119
+
120
+ /** The secret, minting it on first use. */
121
+ get value(): string {
122
+ return (this.#value ??= randomBytes(32).toString("hex"));
123
+ }
124
+
125
+ /** Environment for a CLI child: marks us as the host and passes the secret. */
126
+ env(): Record<string, string> {
127
+ return { AI_VAULT_HOST: "1", AI_VAULT_HOST_SECRET: this.value };
128
+ }
129
+
130
+ /** HMAC over "allow:<token>:<entry>:<y|n>", what `get --answer-stdin` expects. */
131
+ approve(token: string, entry: string, answer: boolean): string | undefined {
132
+ if (!this.#value) return undefined;
133
+ return createHmac("sha256", this.#value)
134
+ .update(`allow:${token}:${entry.toLowerCase()}:${answer ? "y" : "n"}`)
135
+ .digest("hex");
136
+ }
137
+ }
138
+
94
139
  export class VaultCli {
95
140
  readonly bin = resolveBinary();
141
+ /** Set by the extension at startup; the same secret for every binding. */
142
+ host = new HostSecret();
96
143
 
97
144
  get available(): boolean {
98
145
  return this.bin !== undefined;
@@ -112,7 +159,7 @@ export class VaultCli {
112
159
  throw new CliError(EXIT.denied, undefined, "aborted", "");
113
160
  }
114
161
  const run = await new Promise<CliRun>((resolve, reject) => {
115
- const child = spawn(bin, args, { stdio: ["pipe", "pipe", "pipe"] });
162
+ const child = spawn(bin, args, { stdio: ["pipe", "pipe", "pipe"], env: { ...process.env, ...this.host.env() } });
116
163
  let stdout = "";
117
164
  let stderr = "";
118
165
  const onAbort = () => child.kill("SIGKILL");
@@ -143,6 +190,16 @@ export class VaultCli {
143
190
  return run;
144
191
  }
145
192
 
193
+ /**
194
+ * `init` or `unlock`: returns the parsed result with the token, and keeps
195
+ * the host secret the CLI minted (or used ours) for later signing.
196
+ */
197
+ async open<T extends { hostSecret?: string }>(subcommand: "init" | "unlock", args: string[], opts: { stdin?: string; signal?: AbortSignal } = {}): Promise<T> {
198
+ const result = await this.json<T>([subcommand, ...args], opts);
199
+ this.host.adopt(result.hostSecret);
200
+ return result;
201
+ }
202
+
146
203
  /** One CLI call whose output is a JSON object. */
147
204
  async json<T>(args: string[], opts: { stdin?: string; signal?: AbortSignal } = {}): Promise<T> {
148
205
  const run = await this.run([...args, "--json"], opts);
package/src/index.ts CHANGED
@@ -24,7 +24,8 @@ import {
24
24
  } from "./bitwarden.js";
25
25
  import { CliError, VaultCli } from "./cli.js";
26
26
  import { isOmpHost, onSessionLeave, sessionLabel, subagentId, withTier } from "./host.js";
27
- import { confirmWindow, promptSecret, promptText, type PromptHost } from "./prompt.js";
27
+ import { confirmWindow, forDialog, promptSecret, promptText, type PromptHost } from "./prompt.js";
28
+ import { forgetSettings, getSettingsSafe, type Settings } from "./settings.js";
28
29
 
29
30
  type Ctx = ExtensionToolContext | ExtensionCommandContext;
30
31
 
@@ -52,6 +53,8 @@ interface UnlockResult {
52
53
  items: number;
53
54
  mode?: UnlockModeName;
54
55
  auto?: boolean;
56
+ /** Minted by the CLI for a host; kept in memory only, signs approvals. */
57
+ hostSecret?: string;
55
58
  }
56
59
 
57
60
  interface ListResult {
@@ -199,9 +202,9 @@ async function ensureUnlocked(scope: Scope, ctx: Ctx, signal?: AbortSignal): Pro
199
202
  }
200
203
  }
201
204
  const attempt = async (password?: string): Promise<UnlockResult> => {
202
- const args = ["unlock", "--requester", sessionLabel(ctx)];
205
+ const args = ["--requester", sessionLabel(ctx)];
203
206
  if (password !== undefined) args.push("--password-stdin");
204
- return cli.json<UnlockResult>(args, {
207
+ return cli.open<UnlockResult>("unlock", args, {
205
208
  stdin: password === undefined ? undefined : `${password}\n`,
206
209
  signal,
207
210
  });
@@ -309,22 +312,21 @@ async function bitwardenFallback(
309
312
  }
310
313
  if (!hit) return fail(`${missing} — not in Bitwarden either${reason ? ` (reason: ${reason})` : ""}`);
311
314
 
312
- const label = `${hit.name}${hit.username ? ` user:${hit.username}` : ""}`;
313
- const allow = await confirmWindow(
314
- dialogs(ctx),
315
- "pi-ai-vault · Bitwarden 里找到",
316
- `本地库没有「${name}」,Bitwarden 里有:\n${label}\n\n读取这一次吗?`,
317
- signal,
318
- );
319
- if (!allow) return fail(`user denied reading "${hit.name}" from Bitwarden — do not retry`, true);
315
+ const asValue = (via: string): ToolOutcome => ({
316
+ content: [
317
+ {
318
+ type: "text" as const,
319
+ text: JSON.stringify(
320
+ { name: hit.name, username: hit.username || undefined, password: hit.password, uris: hit.uris, via },
321
+ null,
322
+ 1,
323
+ ),
324
+ },
325
+ ],
326
+ details: { item: hit.name, via },
327
+ });
320
328
 
321
- const importIt = await confirmWindow(
322
- dialogs(ctx),
323
- "pi-ai-vault · 导入到 ai-vault",
324
- `把「${hit.name}」写进 ai-vault 吗?\n\n允许 → 以后直接读本地库(按当前解锁模式,可能免密)\n拒绝 → 只用这一次,不写入本地库`,
325
- signal,
326
- );
327
- if (importIt) {
329
+ const importIt = async (): Promise<ToolOutcome> => {
328
330
  try {
329
331
  const saved = await cli.json<SaveResult>(["save", "--yes", ...tokenArgs(scope)], {
330
332
  stdin: JSON.stringify([
@@ -343,34 +345,32 @@ async function bitwardenFallback(
343
345
  } catch (error) {
344
346
  return fail(`found "${hit.name}" in Bitwarden but could not import it: ${describe(error)}`);
345
347
  }
346
- return {
347
- content: [
348
- {
349
- type: "text" as const,
350
- text: JSON.stringify(
351
- { name: hit.name, username: hit.username || undefined, password: hit.password, uris: hit.uris, via: "imported-from-bitwarden" },
352
- null,
353
- 1,
354
- ),
355
- },
356
- ],
357
- details: { item: hit.name, via: "imported-from-bitwarden" },
358
- };
348
+ return asValue("imported-from-bitwarden");
349
+ };
350
+
351
+ const policy = (await getSettingsSafe(signal)).bitwarden.import;
352
+ if (policy === "always") {
353
+ // bitwarden.import = always: the user opted into pulling hits in silently.
354
+ return importIt();
359
355
  }
360
356
 
361
- return {
362
- content: [
363
- {
364
- type: "text" as const,
365
- text: JSON.stringify(
366
- { name: hit.name, username: hit.username || undefined, password: hit.password, uris: hit.uris, via: "bitwarden-once" },
367
- null,
368
- 1,
369
- ),
370
- },
371
- ],
372
- details: { item: hit.name, via: "bitwarden-once" },
373
- };
357
+ const label = `${hit.name}${hit.username ? ` user:${hit.username}` : ""}`;
358
+ const allow = await confirmWindow(
359
+ dialogs(ctx),
360
+ "pi-ai-vault · Bitwarden 里找到",
361
+ `本地库没有「${forDialog(name)}」,Bitwarden 里有:\n${forDialog(label)}\n\n读取这一次吗?`,
362
+ signal,
363
+ );
364
+ if (!allow) return fail(`user denied reading "${hit.name}" from Bitwarden — do not retry`, true);
365
+ if (policy === "never") return asValue("bitwarden-once");
366
+
367
+ const confirmed = await confirmWindow(
368
+ dialogs(ctx),
369
+ "pi-ai-vault · 导入到 ai-vault",
370
+ `把「${forDialog(hit.name)}」写进 ai-vault 吗?\n\n允许 → 以后直接读本地库(按当前解锁模式,可能免密)\n拒绝 → 只用这一次,不写入本地库`,
371
+ signal,
372
+ );
373
+ return confirmed ? importIt() : asValue("bitwarden-once");
374
374
  }
375
375
 
376
376
  function vaultGetTool(scope: Scope, bw: BwState): ToolDefinition<typeof vaultGetParams, VaultGetDetails> {
@@ -407,11 +407,18 @@ function vaultGetTool(scope: Scope, bw: BwState): ToolDefinition<typeof vaultGet
407
407
  const allowed = await confirmWindow(
408
408
  dialogs(ctx),
409
409
  "ai-vault · 读取本地密码",
410
- `条目: ${params.name}\n请求方: ${sub ? `子代理 ${sub}` : "主会话"}\n原因: ${params.reason ?? "(未说明)"}\n\n` +
410
+ `条目: ${forDialog(params.name)}\n请求方: ${sub ? `子代理 ${forDialog(sub, 32)}` : "主会话"}\n原因: ${forDialog(params.reason ?? "(未说明)", 120)}\n\n` +
411
411
  "允许后 5 分钟内同一请求方可再次读取。密码会进入对话。",
412
412
  signal,
413
413
  );
414
- const run = await cli.run([...base, "--json", "--answer-stdin"], {
414
+ // Relaying is our privilege as the host: sign the answer under the
415
+ // host secret so the CLI can tell us from the model's own bash.
416
+ const token = scope.token ?? "";
417
+ const approval = cli.host.approve(token, params.name, allowed);
418
+ if (!approval) {
419
+ return fail("cannot relay an approval: no host secret for this session — run /vault unlock again");
420
+ }
421
+ const run = await cli.run([...base, "--json", "--answer-stdin", "--approval", approval], {
415
422
  stdin: allowed ? "y\n" : "n\n",
416
423
  signal,
417
424
  });
@@ -534,16 +541,16 @@ async function saveLocalEntry(scope: Scope, ctx: Ctx, req: SaveRequest): Promise
534
541
  }
535
542
  if (error.needsUi === "confirm") {
536
543
  const meta = [
537
- req.username?.trim() ? `用户名: ${req.username.trim()}` : "",
538
- req.uri?.trim() ? `URI: ${req.uri.trim()}` : "",
539
- req.notes?.trim() ? `备注: ${req.notes.trim()}` : "",
544
+ req.username?.trim() ? `用户名: ${forDialog(req.username, 60)}` : "",
545
+ req.uri?.trim() ? `URI: ${forDialog(req.uri, 120)}` : "",
546
+ req.notes?.trim() ? `备注: ${forDialog(req.notes, 120)}` : "",
540
547
  ]
541
548
  .filter(Boolean)
542
549
  .join("\n");
543
550
  const ok = await confirmWindow(
544
551
  dialogs(ctx),
545
552
  "ai-vault · 保存到本地库",
546
- `保存条目「${name}」。${meta ? `\n${meta}` : ""}\n下一步会弹出窗口,由你输入密码。密码不会进入对话。`,
553
+ `保存条目「${forDialog(name)}」。${meta ? `\n${meta}` : ""}\n下一步会弹出窗口,由你输入密码。密码不会进入对话。`,
547
554
  req.signal,
548
555
  );
549
556
  if (!ok) return `user denied saving "${name}"`;
@@ -628,6 +635,7 @@ const HELP = [
628
635
  "/vault init 创建全机共享的本地加密库(弹出窗口设置主密码)",
629
636
  "/vault unlock | lock 解锁 / 锁定(清空本会话的授权)",
630
637
  "/vault mode [never|time|session] 查看/切换解锁模式(切换要主密码)",
638
+ "/vault settings [键 值] 查看/修改设置(vault.unlock、bitwarden.unlock、bitwarden.import …)",
631
639
  "/vault status 状态与授权剩余时间",
632
640
  "/vault list 本地条目元数据",
633
641
  "/vault add [名称] 新增本地条目(用户名、密码在弹窗里输入)",
@@ -659,7 +667,7 @@ async function initStore(scope: Scope, ctx: Ctx, label: string): Promise<void> {
659
667
  note(ctx, `ai-vault 已创建: ${cli.dir}/store.json`);
660
668
  };
661
669
  try {
662
- finish(await cli.json<UnlockResult>(["init", "--requester", label]));
670
+ finish(await cli.open<UnlockResult>("init", ["--requester", label]));
663
671
  return;
664
672
  } catch (error) {
665
673
  if (!(error instanceof CliError)) {
@@ -682,12 +690,29 @@ async function initStore(scope: Scope, ctx: Ctx, label: string): Promise<void> {
682
690
  return;
683
691
  }
684
692
  try {
685
- finish(await cli.json<UnlockResult>(["init", "--requester", label, "--password-stdin"], { stdin: `${pass}\n` }));
693
+ finish(await cli.open<UnlockResult>("init", ["--requester", label, "--password-stdin"], { stdin: `${pass}\n` }));
686
694
  } catch (error) {
687
695
  note(ctx, `ai-vault: ${error instanceof CliError ? error.message : describe(error)}`, "error");
688
696
  }
689
697
  }
690
698
 
699
+ function settingsText(s: Settings): string {
700
+ const persisted = s.bitwarden.persisted
701
+ ? s.bitwarden.expiresAt
702
+ ? `有(${Math.max(0, Math.round((s.bitwarden.expiresAt - Date.now()) / 60_000))} 分钟后过期)`
703
+ : "有(不过期)"
704
+ : "无";
705
+ return [
706
+ `vault.unlock: ${s.vault.unlock} (never | time | session)`,
707
+ `vault.hours: ${s.vault.hours} (time 模式用)`,
708
+ `vault 机器级会话: ${s.vault.auto ? "有(免密)" : "无"}`,
709
+ `bitwarden.unlock: ${s.bitwarden.unlock} (never | time | session)`,
710
+ `bitwarden.hours: ${s.bitwarden.hours}`,
711
+ `bitwarden.import: ${s.bitwarden.import} (ask | always | never)`,
712
+ `bitwarden 已落盘的会话: ${persisted}`,
713
+ ].join("\n");
714
+ }
715
+
691
716
  function commandHandler(scope: Scope, bw: BwState) {
692
717
  return async (args: string, ctx: ExtensionCommandContext): Promise<void> => {
693
718
  const [sub = "status", ...rest] = words(args);
@@ -756,6 +781,33 @@ function commandHandler(scope: Scope, bw: BwState) {
756
781
  }
757
782
  return;
758
783
  }
784
+ case "settings": {
785
+ const [key, ...valueParts] = rest;
786
+ const value = valueParts.join(" ").trim();
787
+ try {
788
+ if (!key) {
789
+ note(ctx, settingsText(await cli.json<Settings>(["settings"])));
790
+ return;
791
+ }
792
+ if (!value) {
793
+ const one = await cli.json<{ key: string; value: string }>(["settings", key]);
794
+ note(ctx, `${one.key}: ${one.value}`);
795
+ return;
796
+ }
797
+ // `vault.unlock` opens its own password window (or answers
798
+ // needs-ui); the other keys do not prompt at all.
799
+ const run = await cli.withPassword(["settings", key, value], () =>
800
+ promptSecret(dialogs(ctx), "ai-vault · 主密码", "改变解锁模式需要验证"),
801
+ );
802
+ forgetSettings();
803
+ const updated = JSON.parse(run.stdout) as Settings;
804
+ if (key.startsWith("vault.")) await lockNow(scope);
805
+ note(ctx, settingsText(updated));
806
+ } catch (error) {
807
+ note(ctx, `ai-vault: ${error instanceof CliError && error.denied ? "已取消" : describe(error)}`, "warning");
808
+ }
809
+ return;
810
+ }
759
811
  case "mode": {
760
812
  const [sub, hoursArg] = rest;
761
813
  if (!sub || sub === "get" || sub === "status") {
@@ -785,6 +837,7 @@ function commandHandler(scope: Scope, bw: BwState) {
785
837
  try {
786
838
  const run = await cli.withPassword(args, () => promptSecret(dialogs(ctx), "ai-vault · 主密码", "切换解锁模式"));
787
839
  const result = JSON.parse(run.stdout) as { mode: UnlockModeName; hours: number; auto: boolean };
840
+ forgetSettings();
788
841
  await lockNow(scope);
789
842
  scope.mode = result.mode;
790
843
  scope.auto = result.auto;
@@ -836,7 +889,7 @@ function commandHandler(scope: Scope, bw: BwState) {
836
889
  note(ctx, `ai-vault: ${describe(error)}`, error instanceof CliError && error.denied ? "warning" : "error");
837
890
  return;
838
891
  }
839
- const sure = await confirmWindow(dialogs(ctx), "ai-vault · 删除条目", `删除「${name}」?删除后无法恢复。`);
892
+ const sure = await confirmWindow(dialogs(ctx), "ai-vault · 删除条目", `删除「${forDialog(name)}」?删除后无法恢复。`);
840
893
  if (!sure) return;
841
894
  try {
842
895
  const result = await cli.json<RemovingResult>([...args, "--yes"]);
@@ -862,7 +915,11 @@ function commandHandler(scope: Scope, bw: BwState) {
862
915
  const args = ["grant", name, "--token", scope.token!];
863
916
  if (minutes) args.push("--minutes", minutes);
864
917
  try {
865
- const result = await cli.json<{ name: string; minutes: number }>(args);
918
+ // A standing grant costs the master password, like a mode change.
919
+ const run = await cli.withPassword(args, () =>
920
+ promptSecret(dialogs(ctx), "ai-vault · 授权读取", "主密码(给这条条目 N 分钟免确认)"),
921
+ );
922
+ const result = JSON.parse(run.stdout) as { name: string; minutes: number };
866
923
  setStatus(ctx, scope, "·granted");
867
924
  note(ctx, `granted "${result.name}" for ${result.minutes}m`);
868
925
  } catch (error) {
package/src/prompt.ts CHANGED
@@ -105,6 +105,19 @@ function failedToOpen(result: ZenityResult): boolean {
105
105
  return result.stderr.split(/\r?\n/).some((line) => line.trim() !== "" && !gtkDiagnostic.test(line));
106
106
  }
107
107
 
108
+ /**
109
+ * Make a model-supplied value safe to put in a confirm window.
110
+ *
111
+ * The window is the one place the user reads what they are approving, so an
112
+ * entry name or reason that carries newlines could otherwise forge a whole
113
+ * second message ("请求方: 主会话 / 已授权, 点允许"). One line, bounded
114
+ * length, control characters gone.
115
+ */
116
+ export function forDialog(value: string, max = 80): string {
117
+ const oneLine = value.replace(/[\u0000-\u001f\u007f\u2028\u2029]+/g, " ").replace(/\s+/g, " ").trim();
118
+ return oneLine.length > max ? `${oneLine.slice(0, max - 1)}…` : oneLine;
119
+ }
120
+
108
121
  /** Secret entry. Empty and cancel are both "no value". */
109
122
  export async function promptSecret(
110
123
  ctx: PromptHost | undefined,
@@ -0,0 +1,59 @@
1
+ /**
2
+ * Machine-wide settings, owned by the CLI (`ai-vault settings`), read here.
3
+ *
4
+ * The vault decides when to ask for its password; the Bitwarden side decides
5
+ * separately whether its `bw` session key may live on disk, and whether a hit
6
+ * may be imported into the vault without a window.
7
+ */
8
+ import { VaultCli } from "./cli.js";
9
+
10
+ export type UnlockModeName = "never" | "time" | "session";
11
+ export type ImportPolicy = "ask" | "always" | "never";
12
+
13
+ export interface Settings {
14
+ vault: { unlock: UnlockModeName; hours: number; auto: boolean };
15
+ bitwarden: {
16
+ unlock: UnlockModeName;
17
+ hours: number;
18
+ import: ImportPolicy;
19
+ persisted: boolean;
20
+ expiresAt: number | null;
21
+ };
22
+ }
23
+
24
+ export const DEFAULT_SETTINGS: Settings = {
25
+ vault: { unlock: "session", hours: 8, auto: false },
26
+ bitwarden: { unlock: "session", hours: 8, import: "ask", persisted: false, expiresAt: null },
27
+ };
28
+
29
+ const cli = new VaultCli();
30
+ let cache: { at: number; value: Settings } | undefined;
31
+
32
+ /** The shared CLI client, for the pieces that read and write the settings. */
33
+ export function settingsCli(): VaultCli {
34
+ return cli;
35
+ }
36
+
37
+ /**
38
+ * Settings change rarely, so a short cache keeps a Bitwarden call from paying
39
+ * for the read. `/vault settings ...` drops it explicitly.
40
+ */
41
+ export async function getSettings(signal?: AbortSignal, options: { fresh?: boolean } = {}): Promise<Settings> {
42
+ if (!options.fresh && cache && Date.now() - cache.at < 30_000) return cache.value;
43
+ const value = await cli.json<Settings>(["settings"], { signal });
44
+ cache = { at: Date.now(), value };
45
+ return value;
46
+ }
47
+
48
+ /** For paths that must keep working when the CLI is missing: defaults instead. */
49
+ export async function getSettingsSafe(signal?: AbortSignal): Promise<Settings> {
50
+ try {
51
+ return await getSettings(signal);
52
+ } catch {
53
+ return DEFAULT_SETTINGS;
54
+ }
55
+ }
56
+
57
+ export function forgetSettings(): void {
58
+ cache = undefined;
59
+ }