pi-ai-vault 0.13.0 → 0.14.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
@@ -56,11 +56,12 @@ When the local store asks for its master password is a per-machine setting (`/va
56
56
 
57
57
  | Mode | Behaviour |
58
58
  |---|---|
59
+ | `every` | asks on every call; nothing is kept that could open the store |
59
60
  | `never` | never asks, and reads open no window — the "the agent may use these freely" passwords |
60
61
 
61
- By default (`session`) a read opens no window either: the master password that unlocked the session is the approval, and every read is audited. `/vault confirm on` puts a window on every read.
62
+ By default (`time`) a read opens no window either: the master password that unlocked the session is the approval, and every read is audited. `/vault confirm on` puts a window on every read.
62
63
  | `time` | asks again N hours after the unlock (default 8) |
63
- | `session` | once per session, dies with it (default) |
64
+ | `time` (default, 4 h) | once, then every pi/omp process on the machine uses that unlock for N hours |
64
65
 
65
66
  `vault_get` searches Bitwarden on a local miss; a hit is shown to you, then read once, then — following `bitwarden.import` — offered for import into ai-vault (so it never touches Bitwarden again) or used just this once. So **only the passwords you approve for import ever enter ai-vault**.
66
67
 
package/README.zh.md CHANGED
@@ -51,11 +51,12 @@ omp plugin install npm:pi-ai-vault # omp,同一个包
51
51
 
52
52
  | 模式 | 行为 |
53
53
  |---|---|
54
+ | `every` | 每次调用都问;不留任何能打开库的东西 |
54
55
  | `never` | 永远不问,读取也不弹确认窗——「agent 可以自由使用」的那批密码 |
55
56
 
56
- 默认(`session`)读取同样不弹窗:解锁会话的主密码就是授权,每次读取仍记审计。`/vault confirm on` 让每次读取都弹窗。
57
- | `time` | 解锁后 N 小时(默认 8)再问一次 |
58
- | `session` | 每个会话一次,会话结束失效(默认) |
57
+ 默认(`time`)读取同样不弹窗:解锁会话的主密码就是授权,每次读取仍记审计。`/vault confirm on` 让每次读取都弹窗。
58
+ | `time`(默认,4 小时) | 问一次,之后机器上所有 pi/omp 进程共用这次解锁 N 小时 |
59
+ | `every` | 每次调用都问;不留任何能打开库的东西 |
59
60
 
60
61
  `vault_get` 找不到本地条目时会去 Bitwarden 搜;命中后按 `bitwarden.import` 处理:
61
62
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-ai-vault",
3
- "version": "0.13.0",
3
+ "version": "0.14.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.13.0"
28
+ "@xiaolikt/ai-vault": "0.14.0"
29
29
  },
30
30
  "peerDependencies": {
31
31
  "@earendil-works/pi-coding-agent": "^1.5.0",
package/src/cli.ts CHANGED
@@ -326,7 +326,7 @@ export class VaultCli {
326
326
  return process.env.AI_VAULT_DIR ?? join(homedir(), ".ai-vault");
327
327
  }
328
328
 
329
- async run(args: string[], opts: { stdin?: string; signal?: AbortSignal } = {}): Promise<CliRun> {
329
+ async run(args: string[], opts: { stdin?: string; signal?: AbortSignal; password?: string } = {}): Promise<CliRun> {
330
330
  const launch = this.launch;
331
331
  if (!launch) {
332
332
  throw new CliError(EXIT.error, undefined, "ai-vault CLI not found", "");
@@ -337,7 +337,10 @@ export class VaultCli {
337
337
  const run = await new Promise<CliRun>((resolve, reject) => {
338
338
  // A program Node will not start fails here like any other CLI failure,
339
339
  // not as a bare exception from inside the promise.
340
- const child = startCli(launch, args, { ...process.env, ...this.host.env() }, () => {
340
+ // `every` mode: the master password travels in the child's environment,
341
+ // never on the command line, and lives for exactly this call.
342
+ const passwordEnv = opts.password !== undefined ? { AI_VAULT_PASSWORD: opts.password } : {};
343
+ const child = startCli(launch, args, { ...process.env, ...this.host.env(), ...passwordEnv }, () => {
341
344
  opts.signal?.removeEventListener("abort", onAbort);
342
345
  reject(new CliError(EXIT.error, undefined, `cannot run ${launch.program}: ${lastStartError}`, ""));
343
346
  });
@@ -376,14 +379,14 @@ export class VaultCli {
376
379
  * `init` or `unlock`: returns the parsed result with the token, and keeps
377
380
  * the host secret the CLI minted (or used ours) for later signing.
378
381
  */
379
- async open<T extends { hostSecret?: string }>(subcommand: "init" | "unlock", args: string[], opts: { stdin?: string; signal?: AbortSignal } = {}): Promise<T> {
382
+ async open<T extends { hostSecret?: string }>(subcommand: "init" | "unlock", args: string[], opts: { stdin?: string; signal?: AbortSignal; password?: string } = {}): Promise<T> {
380
383
  const result = await this.json<T>([subcommand, ...args], opts);
381
384
  this.host.adopt(result.hostSecret);
382
385
  return result;
383
386
  }
384
387
 
385
388
  /** One CLI call whose output is a JSON object. */
386
- async json<T>(args: string[], opts: { stdin?: string; signal?: AbortSignal } = {}): Promise<T> {
389
+ async json<T>(args: string[], opts: { stdin?: string; signal?: AbortSignal; password?: string } = {}): Promise<T> {
387
390
  const run = await this.run([...args, "--json"], opts);
388
391
  try {
389
392
  return JSON.parse(run.stdout) as T;
@@ -396,8 +399,11 @@ export class VaultCli {
396
399
  async withPassword(
397
400
  args: string[],
398
401
  ask: () => Promise<string | undefined>,
399
- opts: { stdin?: string; signal?: AbortSignal } = {},
402
+ opts: { stdin?: string; signal?: AbortSignal; password?: string } = {},
400
403
  ): Promise<CliRun> {
404
+ // In `every` mode the call already carries the master password: the CLI
405
+ // reuses it for the verification instead of asking for it again.
406
+ if (opts.password !== undefined) return this.run(args, opts);
401
407
  try {
402
408
  return await this.run(args, opts);
403
409
  } catch (error) {
package/src/index.ts CHANGED
@@ -35,7 +35,7 @@ type Ctx = ExtensionToolContext | ExtensionCommandContext;
35
35
 
36
36
  const GRANT_MS_DEFAULT = 5 * 60_000;
37
37
 
38
- type UnlockModeName = "never" | "time" | "session";
38
+ type UnlockModeName = "never" | "time" | "every";
39
39
 
40
40
  interface StatusResult {
41
41
  ok: boolean;
@@ -97,6 +97,9 @@ interface Scope {
97
97
  mode?: UnlockModeName;
98
98
  /** True when reads use the machine-wide session instead of a token. */
99
99
  auto?: boolean;
100
+ /** `vault.unlock = every`: the master password for the call being made, asked
101
+ * for before each one and dropped after it. Never stored anywhere else. */
102
+ everyPassword?: string;
100
103
  unlocking?: Promise<boolean>;
101
104
  }
102
105
 
@@ -160,6 +163,9 @@ async function lockNow(scope: Scope): Promise<void> {
160
163
 
161
164
  /** Args for a CLI call: this binding's token, or the machine-wide session. */
162
165
  const tokenArgs = (scope: Scope): string[] => (scope.token ? ["--token", scope.token] : []);
166
+ /** The CLI options a vault call needs beyond its arguments: the `every` password. */
167
+ const callOpts = (scope: Scope, signal?: AbortSignal): { signal?: AbortSignal; password?: string } =>
168
+ scope.everyPassword !== undefined ? { signal, password: scope.everyPassword } : { signal };
163
169
 
164
170
  /** Make this binding's unlock happen; never throws. */
165
171
  async function ensureUnlocked(scope: Scope, ctx: Ctx, signal?: AbortSignal): Promise<boolean> {
@@ -190,25 +196,58 @@ async function ensureUnlocked(scope: Scope, ctx: Ctx, signal?: AbortSignal): Pro
190
196
  }
191
197
  }
192
198
  }
193
- // `never` mode keeps a machine-wide session: no token, no window. Ask the
194
- // CLI before opening anything, so that mode really is password-free.
195
- try {
196
- const status = await cli.json<StatusResult>(["status"], { signal });
197
- scope.items = status.items;
198
- scope.mode = status.mode;
199
- scope.auto = status.auto;
200
- setSettingsToken(undefined);
201
- return true;
202
- } catch (error) {
203
- if (error instanceof CliError && /not initialized/i.test(error.message)) {
204
- note(ctx, NOT_INITIALIZED, "warning");
205
- return false;
206
- }
207
- if (!(error instanceof CliError) || !error.auth) {
208
- note(ctx, `ai-vault: ${describe(error)}`, "error");
209
- return false;
199
+ // No token (first call, or `never`/`every`). Ask the CLI what that means:
200
+ // `never` answers outright; `every` says it needs a password — for this
201
+ // call only, since that mode keeps nothing between calls.
202
+ {
203
+ const askEveryPassword = async (): Promise<string | undefined> => {
204
+ const password = await promptSecret(
205
+ dialogs(ctx),
206
+ tr("ai-vault · unlock", "ai-vault · 解锁"),
207
+ tr("master password (asked on every call)", "主密码(每次调用都会问)"),
208
+ signal,
209
+ );
210
+ if (!password && !signal?.aborted) note(ctx, tr("no master password entered", "没有输入主密码"), "warning");
211
+ return password;
212
+ };
213
+ try {
214
+ const status = await cli.json<StatusResult>(["status"], { signal });
215
+ scope.items = status.items;
216
+ scope.mode = status.mode;
217
+ scope.auto = status.auto;
218
+ setSettingsToken(undefined);
219
+ return true;
220
+ } catch (error) {
221
+ if (error instanceof CliError && /not initialized/i.test(error.message)) {
222
+ note(ctx, NOT_INITIALIZED, "warning");
223
+ return false;
224
+ }
225
+ if (error instanceof CliError && error.needsUi === "password") {
226
+ // `every`: the password opens the store for this call alone.
227
+ const password = await askEveryPassword();
228
+ if (!password) return false;
229
+ try {
230
+ const status = await cli.json<StatusResult>(["status"], { signal, password });
231
+ scope.items = status.items;
232
+ scope.mode = "every";
233
+ scope.everyPassword = password;
234
+ return true;
235
+ } catch (retryError) {
236
+ if (retryError instanceof CliError && retryError.auth) {
237
+ note(ctx, tr("ai-vault: wrong master password", "ai-vault: 主密码错误"), "error");
238
+ return false;
239
+ }
240
+ note(ctx, `ai-vault: ${describe(retryError)}`, "error");
241
+ return false;
242
+ }
243
+ }
244
+ if (!(error instanceof CliError) || !error.auth) {
245
+ note(ctx, `ai-vault: ${describe(error)}`, "error");
246
+ return false;
247
+ }
210
248
  }
211
249
  }
250
+ let lastUnlockPassword: string | undefined;
212
251
  const attempt = async (password?: string): Promise<UnlockResult> => {
213
252
  const args = ["--requester", sessionLabel(ctx)];
214
253
  if (password !== undefined) args.push("--password-stdin");
@@ -228,19 +267,24 @@ async function ensureUnlocked(scope: Scope, ctx: Ctx, signal?: AbortSignal): Pro
228
267
  if (!signal?.aborted) note(ctx, tr("no master password entered (the window was cancelled, or there is no desktop/UI)", "没有输入主密码(窗口已取消,或没有桌面/界面)"), "warning");
229
268
  return false;
230
269
  }
270
+ lastUnlockPassword = password;
231
271
  result = await attempt(password);
232
272
  }
233
273
  // /vault lock or a session switch ran while the window was open.
234
274
  if (epoch !== scope.epoch || signal?.aborted) {
235
- await cli.run(["lock", "--token", result.token]).catch(() => undefined);
275
+ if (result.token) await cli.run(["lock", "--token", result.token]).catch(() => undefined);
236
276
  return false;
237
277
  }
238
278
  scope.mode = result.mode;
239
279
  scope.auto = result.mode === "never";
240
280
  // In `never` mode the CLI wrote the machine-wide session; keeping a
241
281
  // per-binding token would bring back a confirm window on every read.
242
- scope.token = result.mode === "never" ? undefined : result.token;
282
+ // In `every` mode no token exists: the store was just proved open by
283
+ // the password that was typed, so this call proceeds on it, and the
284
+ // next call asks again.
285
+ scope.token = result.mode === "never" || result.mode === "every" ? undefined : result.token;
243
286
  scope.items = result.items;
287
+ if (result.mode === "every") scope.everyPassword = lastUnlockPassword;
244
288
  setSettingsToken(scope.token);
245
289
  return true;
246
290
  } catch (error) {
@@ -277,7 +321,7 @@ function vaultListTool(scope: Scope): ToolDefinition<typeof vaultListParams, { o
277
321
  async execute(_id, _params, signal, _onUpdate, ctx) {
278
322
  if (!(await ensureUnlocked(scope, ctx, signal))) return fail(LOCKED);
279
323
  try {
280
- const result = await cli.json<ListResult>(["list", "--token", scope.token!], { signal });
324
+ const result = await cli.json<ListResult>(["list", ...tokenArgs(scope)], callOpts(scope, signal));
281
325
  scope.items = result.count;
282
326
  setStatus(ctx, scope);
283
327
  return {
@@ -286,6 +330,8 @@ function vaultListTool(scope: Scope): ToolDefinition<typeof vaultListParams, { o
286
330
  };
287
331
  } catch (error) {
288
332
  return failure(scope, error);
333
+ } finally {
334
+ scope.everyPassword = undefined;
289
335
  }
290
336
  },
291
337
  };
@@ -337,7 +383,7 @@ async function bitwardenFallback(
337
383
  try {
338
384
  const saved = await cli.json<SaveResult>(["save", "--yes", ...tokenArgs(scope)], {
339
385
  stdin: JSON.stringify([draft]),
340
- signal,
386
+ ...callOpts(scope, signal),
341
387
  });
342
388
  scope.items += saved.count;
343
389
  setStatus(ctx, scope);
@@ -398,8 +444,9 @@ function vaultGetTool(scope: Scope, bw: BwState): ToolDefinition<typeof vaultGet
398
444
  if (!(await ensureUnlocked(scope, ctx, signal))) return fail(LOCKED);
399
445
  const base = ["get", params.name, ...(params.reason ? ["--reason", params.reason] : []), ...tokenArgs(scope)];
400
446
  try {
447
+ // (the `every` password is dropped when this call ends, in the finally below)
401
448
  try {
402
- const run = await cli.run([...base, "--json"], { signal });
449
+ const run = await cli.run([...base, "--json"], callOpts(scope, signal));
403
450
  setStatus(ctx, scope, "·ok");
404
451
  return {
405
452
  content: [{ type: "text" as const, text: run.stdout.trim() }],
@@ -424,7 +471,7 @@ function vaultGetTool(scope: Scope, bw: BwState): ToolDefinition<typeof vaultGet
424
471
  }
425
472
  const run = await cli.run([...base, "--json", "--answer-stdin", "--approval", approval], {
426
473
  stdin: allowed ? "y\n" : "n\n",
427
- signal,
474
+ ...callOpts(scope, signal),
428
475
  });
429
476
  setStatus(ctx, scope, "·granted");
430
477
  return {
@@ -440,6 +487,8 @@ function vaultGetTool(scope: Scope, bw: BwState): ToolDefinition<typeof vaultGet
440
487
  } catch (error) {
441
488
  if (error instanceof CliError && error.denied) setStatus(ctx, scope, "·denied");
442
489
  return failure(scope, error);
490
+ } finally {
491
+ scope.everyPassword = undefined;
443
492
  }
444
493
  },
445
494
  };
@@ -587,7 +636,7 @@ async function saveLocalEntry(scope: Scope, ctx: Ctx, req: SaveRequest): Promise
587
636
  for (let attempt = 0; attempt < 8; attempt++) {
588
637
  flush();
589
638
  try {
590
- const run = await cli.run([...args, "--json"], { signal: req.signal });
639
+ const run = await cli.run([...args, "--json"], { ...callOpts(scope, req.signal) });
591
640
  const saved = JSON.parse(run.stdout) as { item?: string; created?: boolean; type?: string };
592
641
  if (saved.created) scope.items += 1;
593
642
  setStatus(ctx, scope);
@@ -807,7 +856,7 @@ function commandHandler(scope: Scope, bw: BwState) {
807
856
  }
808
857
  case "status": {
809
858
  try {
810
- const status = await cli.json<StatusResult>(["status", ...tokenArgs(scope)]);
859
+ const status = await cli.json<StatusResult>(["status", ...tokenArgs(scope)], callOpts(scope));
811
860
  scope.items = status.items;
812
861
  scope.mode = status.mode;
813
862
  scope.auto = status.auto;
@@ -873,7 +922,7 @@ function commandHandler(scope: Scope, bw: BwState) {
873
922
  const [arg] = rest;
874
923
  if (!arg) {
875
924
  try {
876
- const current = await cli.json<Settings>(["settings", ...tokenArgs(scope)]);
925
+ const current = await cli.json<Settings>(["settings", ...tokenArgs(scope)], callOpts(scope));
877
926
  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
927
  } catch (error) {
879
928
  note(ctx, `ai-vault: ${describe(error)}`, "error");
@@ -889,7 +938,8 @@ function commandHandler(scope: Scope, bw: BwState) {
889
938
  try {
890
939
  const run = await cli.withPassword(["settings", "vault.confirm", turnOff ? "false" : "true", ...tokenArgs(scope)], () =>
891
940
  promptSecret(dialogs(ctx), tr("ai-vault · master password", "ai-vault · 主密码"), tr("turn off the per-read confirmation", "关闭每次读取的确认窗")),
892
- );
941
+ callOpts(scope));
942
+
893
943
  forgetSettings();
894
944
  const updated = JSON.parse(run.stdout) as Settings;
895
945
  note(
@@ -911,11 +961,11 @@ function commandHandler(scope: Scope, bw: BwState) {
911
961
  const value = valueParts.join(" ").trim();
912
962
  try {
913
963
  if (!key) {
914
- note(ctx, settingsText(await cli.json<Settings>(["settings", ...tokenArgs(scope)])));
964
+ note(ctx, settingsText(await cli.json<Settings>(["settings", ...tokenArgs(scope)], callOpts(scope))));
915
965
  return;
916
966
  }
917
967
  if (!value) {
918
- const one = await cli.json<{ key: string; value: string }>(["settings", key, ...tokenArgs(scope)]);
968
+ const one = await cli.json<{ key: string; value: string }>(["settings", key, ...tokenArgs(scope)], callOpts(scope));
919
969
  note(ctx, `${one.key}: ${one.value}`);
920
970
  return;
921
971
  }
@@ -923,7 +973,8 @@ function commandHandler(scope: Scope, bw: BwState) {
923
973
  // needs-ui); the other keys do not prompt at all.
924
974
  const run = await cli.withPassword(["settings", key, value, ...tokenArgs(scope)], () =>
925
975
  promptSecret(dialogs(ctx), tr("ai-vault · master password", "ai-vault · 主密码"), tr("changing the unlock policy needs verification", "改变解锁模式需要验证")),
926
- );
976
+ callOpts(scope));
977
+
927
978
  forgetSettings();
928
979
  const updated = JSON.parse(run.stdout) as Settings;
929
980
  if (key.startsWith("vault.")) await lockNow(scope);
package/src/settings.ts CHANGED
@@ -24,7 +24,7 @@ export interface Settings {
24
24
  }
25
25
 
26
26
  export const DEFAULT_SETTINGS: Settings = {
27
- vault: { unlock: "session", hours: 8, confirm: false, auto: false },
27
+ vault: { unlock: "time", hours: 4, confirm: false, 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
  };