pi-ai-vault 0.6.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
@@ -61,6 +61,10 @@ omp plugin install npm:pi-ai-vault # omp,同一个包
61
61
 
62
62
  所以默认情况下 **只有你同意导入的密码才会进 ai-vault**。Bitwarden 自己的主密码请求频率也有单独设置(`bitwarden.unlock`:`never` / `time` / `session`),用 `/vault settings` 查看和修改。
63
63
 
64
+ ## 安全边界(一句话版)
65
+
66
+ 模型的 `bash` 能找到会话令牌、能 `list`,但**签不出读取确认**(签名密钥只在插件进程内存里)、**改不了令牌文件**(带 HMAC,改了就作废)、**免费拿不到 `grant`**(要主密码)。详见仓库 README「安全」一节。
67
+
64
68
  ## 隔离
65
69
 
66
70
  每个会话、每个子代理各自 `ai-vault unlock`,拿自己的令牌和读授权;父会话的解锁子代理继承不到。空闲 10 分钟自动失效,`/new`、`/fork`、退出会清掉本绑定的令牌。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-ai-vault",
3
- "version": "0.6.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.6.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/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,7 @@ 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
28
  import { forgetSettings, getSettingsSafe, type Settings } from "./settings.js";
29
29
 
30
30
  type Ctx = ExtensionToolContext | ExtensionCommandContext;
@@ -53,6 +53,8 @@ interface UnlockResult {
53
53
  items: number;
54
54
  mode?: UnlockModeName;
55
55
  auto?: boolean;
56
+ /** Minted by the CLI for a host; kept in memory only, signs approvals. */
57
+ hostSecret?: string;
56
58
  }
57
59
 
58
60
  interface ListResult {
@@ -200,9 +202,9 @@ async function ensureUnlocked(scope: Scope, ctx: Ctx, signal?: AbortSignal): Pro
200
202
  }
201
203
  }
202
204
  const attempt = async (password?: string): Promise<UnlockResult> => {
203
- const args = ["unlock", "--requester", sessionLabel(ctx)];
205
+ const args = ["--requester", sessionLabel(ctx)];
204
206
  if (password !== undefined) args.push("--password-stdin");
205
- return cli.json<UnlockResult>(args, {
207
+ return cli.open<UnlockResult>("unlock", args, {
206
208
  stdin: password === undefined ? undefined : `${password}\n`,
207
209
  signal,
208
210
  });
@@ -356,7 +358,7 @@ async function bitwardenFallback(
356
358
  const allow = await confirmWindow(
357
359
  dialogs(ctx),
358
360
  "pi-ai-vault · Bitwarden 里找到",
359
- `本地库没有「${name}」,Bitwarden 里有:\n${label}\n\n读取这一次吗?`,
361
+ `本地库没有「${forDialog(name)}」,Bitwarden 里有:\n${forDialog(label)}\n\n读取这一次吗?`,
360
362
  signal,
361
363
  );
362
364
  if (!allow) return fail(`user denied reading "${hit.name}" from Bitwarden — do not retry`, true);
@@ -365,7 +367,7 @@ async function bitwardenFallback(
365
367
  const confirmed = await confirmWindow(
366
368
  dialogs(ctx),
367
369
  "pi-ai-vault · 导入到 ai-vault",
368
- `把「${hit.name}」写进 ai-vault 吗?\n\n允许 → 以后直接读本地库(按当前解锁模式,可能免密)\n拒绝 → 只用这一次,不写入本地库`,
370
+ `把「${forDialog(hit.name)}」写进 ai-vault 吗?\n\n允许 → 以后直接读本地库(按当前解锁模式,可能免密)\n拒绝 → 只用这一次,不写入本地库`,
369
371
  signal,
370
372
  );
371
373
  return confirmed ? importIt() : asValue("bitwarden-once");
@@ -405,11 +407,18 @@ function vaultGetTool(scope: Scope, bw: BwState): ToolDefinition<typeof vaultGet
405
407
  const allowed = await confirmWindow(
406
408
  dialogs(ctx),
407
409
  "ai-vault · 读取本地密码",
408
- `条目: ${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` +
409
411
  "允许后 5 分钟内同一请求方可再次读取。密码会进入对话。",
410
412
  signal,
411
413
  );
412
- 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], {
413
422
  stdin: allowed ? "y\n" : "n\n",
414
423
  signal,
415
424
  });
@@ -532,16 +541,16 @@ async function saveLocalEntry(scope: Scope, ctx: Ctx, req: SaveRequest): Promise
532
541
  }
533
542
  if (error.needsUi === "confirm") {
534
543
  const meta = [
535
- req.username?.trim() ? `用户名: ${req.username.trim()}` : "",
536
- req.uri?.trim() ? `URI: ${req.uri.trim()}` : "",
537
- 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)}` : "",
538
547
  ]
539
548
  .filter(Boolean)
540
549
  .join("\n");
541
550
  const ok = await confirmWindow(
542
551
  dialogs(ctx),
543
552
  "ai-vault · 保存到本地库",
544
- `保存条目「${name}」。${meta ? `\n${meta}` : ""}\n下一步会弹出窗口,由你输入密码。密码不会进入对话。`,
553
+ `保存条目「${forDialog(name)}」。${meta ? `\n${meta}` : ""}\n下一步会弹出窗口,由你输入密码。密码不会进入对话。`,
545
554
  req.signal,
546
555
  );
547
556
  if (!ok) return `user denied saving "${name}"`;
@@ -658,7 +667,7 @@ async function initStore(scope: Scope, ctx: Ctx, label: string): Promise<void> {
658
667
  note(ctx, `ai-vault 已创建: ${cli.dir}/store.json`);
659
668
  };
660
669
  try {
661
- finish(await cli.json<UnlockResult>(["init", "--requester", label]));
670
+ finish(await cli.open<UnlockResult>("init", ["--requester", label]));
662
671
  return;
663
672
  } catch (error) {
664
673
  if (!(error instanceof CliError)) {
@@ -681,7 +690,7 @@ async function initStore(scope: Scope, ctx: Ctx, label: string): Promise<void> {
681
690
  return;
682
691
  }
683
692
  try {
684
- 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` }));
685
694
  } catch (error) {
686
695
  note(ctx, `ai-vault: ${error instanceof CliError ? error.message : describe(error)}`, "error");
687
696
  }
@@ -880,7 +889,7 @@ function commandHandler(scope: Scope, bw: BwState) {
880
889
  note(ctx, `ai-vault: ${describe(error)}`, error instanceof CliError && error.denied ? "warning" : "error");
881
890
  return;
882
891
  }
883
- const sure = await confirmWindow(dialogs(ctx), "ai-vault · 删除条目", `删除「${name}」?删除后无法恢复。`);
892
+ const sure = await confirmWindow(dialogs(ctx), "ai-vault · 删除条目", `删除「${forDialog(name)}」?删除后无法恢复。`);
884
893
  if (!sure) return;
885
894
  try {
886
895
  const result = await cli.json<RemovingResult>([...args, "--yes"]);
@@ -906,7 +915,11 @@ function commandHandler(scope: Scope, bw: BwState) {
906
915
  const args = ["grant", name, "--token", scope.token!];
907
916
  if (minutes) args.push("--minutes", minutes);
908
917
  try {
909
- 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 };
910
923
  setStatus(ctx, scope, "·granted");
911
924
  note(ctx, `granted "${result.name}" for ${result.minutes}m`);
912
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,