@xiaolikt/ai-vault 0.6.0 → 0.8.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.
@@ -0,0 +1,278 @@
1
+ /**
2
+ * Ente CLI client.
3
+ *
4
+ * `ente` (Ente's "client for terminals and agents") is logged in once —
5
+ * `ente account login --app auth` — and then keeps its session on disk
6
+ * (`$XDG_DATA_HOME/ente-cli`) with the database key in the OS keychain, or in
7
+ * `ENTE_CLI_VAULT_KEY` for unattended use. So no password per call here: we
8
+ * only run the CLI and parse its JSON.
9
+ *
10
+ * What this module adds on top of the bare CLI is the extension's rules:
11
+ * metadata listing returns no secrets, reading one current code always passes
12
+ * through a confirm window that names the entry, and every read is audited.
13
+ *
14
+ * JSON contract (ente.com/help/cli/auth):
15
+ * `auth code list --json` -> [{ id, name, issuer, accountName, type }]
16
+ * `auth code view <q> --json` -> the same object plus { otp, validUntil }
17
+ */
18
+ import { spawn } from "node:child_process";
19
+ import { existsSync } from "node:fs";
20
+ import { homedir } from "node:os";
21
+ import { delimiter, join } from "node:path";
22
+ import type { ExtensionAPI, ExtensionContext, ToolDefinition } from "@earendil-works/pi-coding-agent";
23
+ import { Type } from "typebox";
24
+
25
+ import { auditEvent } from "./bitwarden.js";
26
+ import { confirmWindow, forDialog } from "./prompt.js";
27
+ import { withTier } from "./host.js";
28
+
29
+ export interface EnteCodeMeta {
30
+ id: string;
31
+ name: string;
32
+ issuer: string;
33
+ accountName: string;
34
+ type: string;
35
+ }
36
+
37
+ export interface EnteCode extends EnteCodeMeta {
38
+ otp: string;
39
+ validUntil: string;
40
+ }
41
+
42
+ export class EnteError extends Error {
43
+ constructor(message: string, readonly code: number) {
44
+ super(message);
45
+ this.name = "EnteError";
46
+ }
47
+ }
48
+
49
+ const ENTE_MISSING =
50
+ "ente CLI 没找到(要的是 ente.com 的 `ente`,0.4+)。装好后先 `ente account login --app auth` 登录一次;也可以用 ENTE_BIN 指到二进制。";
51
+
52
+ /** `ENTE_BIN`, then PATH, then the usual install spots. */
53
+ export function resolveEnte(): string | undefined {
54
+ const explicit = process.env.ENTE_BIN;
55
+ if (explicit) return existsSync(explicit) ? explicit : undefined;
56
+ for (const dir of (process.env.PATH ?? "").split(delimiter)) {
57
+ if (!dir) continue;
58
+ const candidate = join(dir, "ente");
59
+ if (existsSync(candidate)) return candidate;
60
+ }
61
+ for (const candidate of [
62
+ join(homedir(), ".local", "opt", "ente-cli", "bin", "ente"),
63
+ join(homedir(), ".local", "bin", "ente"),
64
+ join(homedir(), ".cargo", "bin", "ente"),
65
+ ]) {
66
+ if (existsSync(candidate)) return candidate;
67
+ }
68
+ return undefined;
69
+ }
70
+
71
+ interface Run {
72
+ code: number;
73
+ stdout: string;
74
+ stderr: string;
75
+ }
76
+
77
+ async function runEnte(args: string[], signal?: AbortSignal): Promise<Run> {
78
+ const bin = resolveEnte();
79
+ if (!bin) throw new EnteError(ENTE_MISSING, 127);
80
+ if (signal?.aborted) throw new EnteError("Cancelled.", 4);
81
+ return new Promise<Run>((resolve, reject) => {
82
+ const child = spawn(bin, args, { stdio: ["ignore", "pipe", "pipe"] });
83
+ let stdout = "";
84
+ let stderr = "";
85
+ const onAbort = () => child.kill("SIGKILL");
86
+ signal?.addEventListener("abort", onAbort, { once: true });
87
+ child.stdout?.on("data", (chunk: Buffer | string) => {
88
+ if (stdout.length < 8 * 1024 * 1024) stdout += chunk;
89
+ });
90
+ child.stderr?.on("data", (chunk: Buffer | string) => {
91
+ if (stderr.length < 64_000) stderr += chunk;
92
+ });
93
+ child.on("error", (error) => {
94
+ signal?.removeEventListener("abort", onAbort);
95
+ reject(new EnteError(`cannot run ente: ${error.message}`, 127));
96
+ });
97
+ child.on("close", (code) => {
98
+ signal?.removeEventListener("abort", onAbort);
99
+ resolve({ code: code ?? -1, stdout, stderr });
100
+ });
101
+ });
102
+ }
103
+
104
+ async function enteJson<T>(args: string[], signal?: AbortSignal): Promise<T> {
105
+ // --no-input: a prompt becomes an error instead of a hang behind our back.
106
+ const run = await runEnte(["--json", "--no-input", ...args], signal);
107
+ if (run.code !== 0) {
108
+ const message = run.stderr
109
+ .split(/\r?\n/)
110
+ .map((line) => line.trim())
111
+ .filter(Boolean)
112
+ .slice(-3)
113
+ .join(" ");
114
+ throw new EnteError(message || `ente exited with ${run.code}`, run.code);
115
+ }
116
+ try {
117
+ return JSON.parse(run.stdout) as T;
118
+ } catch {
119
+ throw new EnteError(`ente returned non-JSON output: ${run.stdout.slice(0, 200)}`, 1);
120
+ }
121
+ }
122
+
123
+ const asString = (value: unknown): string => (typeof value === "string" ? value : "");
124
+ const normalize = (raw: unknown): EnteCodeMeta => {
125
+ const r = (raw ?? {}) as Record<string, unknown>;
126
+ return {
127
+ id: asString(r.id),
128
+ name: forDialog(asString(r.name), 80),
129
+ issuer: forDialog(asString(r.issuer), 60),
130
+ accountName: forDialog(asString(r.accountName), 60),
131
+ type: asString(r.type) || "totp",
132
+ };
133
+ };
134
+
135
+ /** Metadata only: names, issuers, account names. No codes, no secrets. */
136
+ export async function listCodes(signal?: AbortSignal): Promise<EnteCodeMeta[]> {
137
+ const list = async (extra: string[] = []): Promise<EnteCodeMeta[]> => {
138
+ const raw = await enteJson<unknown[]>(["auth", "code", "list", ...extra], signal);
139
+ return Array.isArray(raw) ? raw.map(normalize) : [];
140
+ };
141
+ try {
142
+ return await list();
143
+ } catch (error) {
144
+ // A first run may have nothing synced yet; --offline reads what is cached.
145
+ // A not-logged-in CLI fails both ways, and the error is what the user needs.
146
+ if (!(error instanceof EnteError)) throw error;
147
+ return list(["--offline"]);
148
+ }
149
+ }
150
+
151
+ /** One current code. The caller must have shown the user which entry this is. */
152
+ export async function viewCode(ref: string, signal?: AbortSignal): Promise<EnteCode> {
153
+ const raw = await enteJson<Record<string, unknown>>(["auth", "code", "view", ref], signal);
154
+ const meta = normalize(raw);
155
+ const otp = asString(raw.otp);
156
+ if (!otp) throw new EnteError(`ente returned no code for "${ref}"`, 1);
157
+ return { ...meta, otp, validUntil: asString(raw.validUntil) };
158
+ }
159
+
160
+ /** The entry a reference really names, so the window shows what will be read. */
161
+ export function resolveRef(items: EnteCodeMeta[], ref: string): EnteCodeMeta | undefined {
162
+ const query = ref.trim().toLowerCase();
163
+ if (!query) return undefined;
164
+ const haystack = (item: EnteCodeMeta): string =>
165
+ `${item.name}\n${item.issuer}\n${item.accountName}`.toLowerCase();
166
+ const exact = items.filter((item) => item.name.toLowerCase() === query);
167
+ if (exact.length === 1) return exact[0];
168
+ const hits = items.filter((item) => haystack(item).includes(query));
169
+ return hits.length === 1 ? hits[0] : exact[0] ?? (hits.length > 1 ? undefined : undefined);
170
+ }
171
+
172
+ type ToolOutcome = {
173
+ content: { type: "text"; text: string }[];
174
+ details: { ok?: boolean; denied?: boolean; item?: string; count?: number };
175
+ isError?: boolean;
176
+ };
177
+
178
+ const fail = (text: string, denied = false): ToolOutcome => ({
179
+ content: [{ type: "text" as const, text }],
180
+ details: { ok: false, ...(denied ? { denied: true } : {}) },
181
+ isError: true,
182
+ });
183
+
184
+ const describe = (error: unknown): string => (error instanceof Error ? error.message : String(error));
185
+
186
+ export function registerEnte(pi: ExtensionAPI): void {
187
+ const listParams = Type.Object({});
188
+ const listTool: ToolDefinition<typeof listParams, { ok?: boolean; count?: number }> = {
189
+ name: "ente_list",
190
+ label: "Ente: list Auth codes",
191
+ description:
192
+ "List the entries saved in Ente Auth through the `ente` CLI: name, issuer, account name, type (totp/hotp/steam). " +
193
+ "NEVER returns codes or secrets. Use ente_code to read one; the user must approve a window first. " +
194
+ "Sessions come from `ente account login --app auth` (and optionally ENTE_CLI_VAULT_KEY), not from the master password of ai-vault.",
195
+ promptSnippet: "List Ente Auth entries (metadata only).",
196
+ parameters: listParams,
197
+ async execute(_id, _params, signal, _onUpdate, ctx) {
198
+ try {
199
+ const items = await listCodes(signal);
200
+ await auditEvent(`ente.list`, `count=${items.length}`, sessionLabelOf(ctx));
201
+ return {
202
+ content: [{ type: "text" as const, text: JSON.stringify(items, null, 1) }],
203
+ details: { count: items.length },
204
+ };
205
+ } catch (error) {
206
+ return fail(describe(error));
207
+ }
208
+ },
209
+ };
210
+
211
+ const codeParams = Type.Object({
212
+ name: Type.String({ description: "Entry name, or part of its name/issuer/account" }),
213
+ });
214
+ const codeTool: ToolDefinition<typeof codeParams, { ok?: boolean; denied?: boolean; item?: string }> = {
215
+ name: "ente_code",
216
+ label: "Ente: show a current code",
217
+ description:
218
+ "Return the current TOTP/Steam code for one Ente Auth entry. The user approves a window that names the entry; the code is short-lived. " +
219
+ "If the user denies, do not retry. Codes go into the conversation — prefer passing them on in the same turn.",
220
+ promptSnippet: "Read one current Ente Auth code after the user approves a window.",
221
+ parameters: codeParams,
222
+ async execute(_id, params, signal, _onUpdate, ctx) {
223
+ try {
224
+ const items = await listCodes(signal);
225
+ if (items.length === 0) return fail("Ente Auth has no saved codes on this device — run `ente account login --app auth` first.");
226
+ const item = resolveRef(items, params.name);
227
+ if (!item) {
228
+ const names = items.slice(0, 15).map((i) => `${i.name}${i.issuer ? ` (${i.issuer})` : ""}`);
229
+ return fail(`no single Ente entry matches "${params.name}". candidates: ${names.join(", ") || "(none)"}`);
230
+ }
231
+ const ok = await confirmWindow(
232
+ ctx as unknown as Parameters<typeof confirmWindow>[0],
233
+ "pi-ai-vault · Ente Auth 验证码",
234
+ `条目: ${item.name}\n签发方: ${item.issuer || "-"}\n账号: ${item.accountName || "-"}\n\n读取当前验证码?(会进入对话)`,
235
+ signal,
236
+ );
237
+ if (!ok) {
238
+ await auditEvent("ente.code", `deny item="${item.name}"`, sessionLabelOf(ctx));
239
+ return fail(`user denied reading the code for "${item.name}" — do not retry`, true);
240
+ }
241
+ const code = await viewCode(item.name, signal);
242
+ await auditEvent("ente.code", `allow item="${item.name}"`, sessionLabelOf(ctx));
243
+ return {
244
+ content: [
245
+ {
246
+ type: "text" as const,
247
+ text: JSON.stringify(
248
+ { name: code.name, issuer: code.issuer, accountName: code.accountName, code: code.otp, validUntil: code.validUntil, via: "ente" },
249
+ null,
250
+ 1,
251
+ ),
252
+ },
253
+ ],
254
+ details: { ok: true, item: code.name },
255
+ };
256
+ } catch (error) {
257
+ if (signal?.aborted) return fail("cancelled", true);
258
+ return fail(describe(error));
259
+ }
260
+ },
261
+ };
262
+
263
+ pi.registerTool(withTier(listTool, "read"));
264
+ pi.registerTool(withTier(codeTool, "write"));
265
+ }
266
+
267
+ /** Same shape as the Bitwarden audit lines: the session or subagent that asked. */
268
+ function sessionLabelOf(ctx: ExtensionContext | undefined): string {
269
+ const agent = (ctx as { agent?: { kind?: string; id?: string } } | undefined)?.agent;
270
+ if (agent?.kind === "sub" && agent.id) return agent.id.replace(/[^\w.-]/g, "").slice(0, 24);
271
+ let id = "";
272
+ try {
273
+ id = (ctx as { sessionManager?: { getSessionId?: () => string } } | undefined)?.sessionManager?.getSessionId?.() ?? "";
274
+ } catch {
275
+ /* a context without a session manager */
276
+ }
277
+ return id.replace(/-/g, "").slice(0, 8) || "main";
278
+ }
@@ -23,8 +23,9 @@ import {
23
23
  type BwState,
24
24
  } from "./bitwarden.js";
25
25
  import { CliError, VaultCli } from "./cli.js";
26
+ import { registerEnte } from "./ente.js";
26
27
  import { isOmpHost, onSessionLeave, sessionLabel, subagentId, withTier } from "./host.js";
27
- import { confirmWindow, promptSecret, promptText, type PromptHost } from "./prompt.js";
28
+ import { confirmWindow, forDialog, promptSecret, promptText, type PromptHost } from "./prompt.js";
28
29
  import { forgetSettings, getSettingsSafe, type Settings } from "./settings.js";
29
30
 
30
31
  type Ctx = ExtensionToolContext | ExtensionCommandContext;
@@ -53,6 +54,8 @@ interface UnlockResult {
53
54
  items: number;
54
55
  mode?: UnlockModeName;
55
56
  auto?: boolean;
57
+ /** Minted by the CLI for a host; kept in memory only, signs approvals. */
58
+ hostSecret?: string;
56
59
  }
57
60
 
58
61
  interface ListResult {
@@ -200,9 +203,9 @@ async function ensureUnlocked(scope: Scope, ctx: Ctx, signal?: AbortSignal): Pro
200
203
  }
201
204
  }
202
205
  const attempt = async (password?: string): Promise<UnlockResult> => {
203
- const args = ["unlock", "--requester", sessionLabel(ctx)];
206
+ const args = ["--requester", sessionLabel(ctx)];
204
207
  if (password !== undefined) args.push("--password-stdin");
205
- return cli.json<UnlockResult>(args, {
208
+ return cli.open<UnlockResult>("unlock", args, {
206
209
  stdin: password === undefined ? undefined : `${password}\n`,
207
210
  signal,
208
211
  });
@@ -356,7 +359,7 @@ async function bitwardenFallback(
356
359
  const allow = await confirmWindow(
357
360
  dialogs(ctx),
358
361
  "pi-ai-vault · Bitwarden 里找到",
359
- `本地库没有「${name}」,Bitwarden 里有:\n${label}\n\n读取这一次吗?`,
362
+ `本地库没有「${forDialog(name)}」,Bitwarden 里有:\n${forDialog(label)}\n\n读取这一次吗?`,
360
363
  signal,
361
364
  );
362
365
  if (!allow) return fail(`user denied reading "${hit.name}" from Bitwarden — do not retry`, true);
@@ -365,7 +368,7 @@ async function bitwardenFallback(
365
368
  const confirmed = await confirmWindow(
366
369
  dialogs(ctx),
367
370
  "pi-ai-vault · 导入到 ai-vault",
368
- `把「${hit.name}」写进 ai-vault 吗?\n\n允许 → 以后直接读本地库(按当前解锁模式,可能免密)\n拒绝 → 只用这一次,不写入本地库`,
371
+ `把「${forDialog(hit.name)}」写进 ai-vault 吗?\n\n允许 → 以后直接读本地库(按当前解锁模式,可能免密)\n拒绝 → 只用这一次,不写入本地库`,
369
372
  signal,
370
373
  );
371
374
  return confirmed ? importIt() : asValue("bitwarden-once");
@@ -405,11 +408,18 @@ function vaultGetTool(scope: Scope, bw: BwState): ToolDefinition<typeof vaultGet
405
408
  const allowed = await confirmWindow(
406
409
  dialogs(ctx),
407
410
  "ai-vault · 读取本地密码",
408
- `条目: ${params.name}\n请求方: ${sub ? `子代理 ${sub}` : "主会话"}\n原因: ${params.reason ?? "(未说明)"}\n\n` +
411
+ `条目: ${forDialog(params.name)}\n请求方: ${sub ? `子代理 ${forDialog(sub, 32)}` : "主会话"}\n原因: ${forDialog(params.reason ?? "(未说明)", 120)}\n\n` +
409
412
  "允许后 5 分钟内同一请求方可再次读取。密码会进入对话。",
410
413
  signal,
411
414
  );
412
- const run = await cli.run([...base, "--json", "--answer-stdin"], {
415
+ // Relaying is our privilege as the host: sign the answer under the
416
+ // host secret so the CLI can tell us from the model's own bash.
417
+ const token = scope.token ?? "";
418
+ const approval = cli.host.approve(token, params.name, allowed);
419
+ if (!approval) {
420
+ return fail("cannot relay an approval: no host secret for this session — run /vault unlock again");
421
+ }
422
+ const run = await cli.run([...base, "--json", "--answer-stdin", "--approval", approval], {
413
423
  stdin: allowed ? "y\n" : "n\n",
414
424
  signal,
415
425
  });
@@ -532,16 +542,16 @@ async function saveLocalEntry(scope: Scope, ctx: Ctx, req: SaveRequest): Promise
532
542
  }
533
543
  if (error.needsUi === "confirm") {
534
544
  const meta = [
535
- req.username?.trim() ? `用户名: ${req.username.trim()}` : "",
536
- req.uri?.trim() ? `URI: ${req.uri.trim()}` : "",
537
- req.notes?.trim() ? `备注: ${req.notes.trim()}` : "",
545
+ req.username?.trim() ? `用户名: ${forDialog(req.username, 60)}` : "",
546
+ req.uri?.trim() ? `URI: ${forDialog(req.uri, 120)}` : "",
547
+ req.notes?.trim() ? `备注: ${forDialog(req.notes, 120)}` : "",
538
548
  ]
539
549
  .filter(Boolean)
540
550
  .join("\n");
541
551
  const ok = await confirmWindow(
542
552
  dialogs(ctx),
543
553
  "ai-vault · 保存到本地库",
544
- `保存条目「${name}」。${meta ? `\n${meta}` : ""}\n下一步会弹出窗口,由你输入密码。密码不会进入对话。`,
554
+ `保存条目「${forDialog(name)}」。${meta ? `\n${meta}` : ""}\n下一步会弹出窗口,由你输入密码。密码不会进入对话。`,
545
555
  req.signal,
546
556
  );
547
557
  if (!ok) return `user denied saving "${name}"`;
@@ -658,7 +668,7 @@ async function initStore(scope: Scope, ctx: Ctx, label: string): Promise<void> {
658
668
  note(ctx, `ai-vault 已创建: ${cli.dir}/store.json`);
659
669
  };
660
670
  try {
661
- finish(await cli.json<UnlockResult>(["init", "--requester", label]));
671
+ finish(await cli.open<UnlockResult>("init", ["--requester", label]));
662
672
  return;
663
673
  } catch (error) {
664
674
  if (!(error instanceof CliError)) {
@@ -681,7 +691,7 @@ async function initStore(scope: Scope, ctx: Ctx, label: string): Promise<void> {
681
691
  return;
682
692
  }
683
693
  try {
684
- finish(await cli.json<UnlockResult>(["init", "--requester", label, "--password-stdin"], { stdin: `${pass}\n` }));
694
+ finish(await cli.open<UnlockResult>("init", ["--requester", label, "--password-stdin"], { stdin: `${pass}\n` }));
685
695
  } catch (error) {
686
696
  note(ctx, `ai-vault: ${error instanceof CliError ? error.message : describe(error)}`, "error");
687
697
  }
@@ -880,7 +890,7 @@ function commandHandler(scope: Scope, bw: BwState) {
880
890
  note(ctx, `ai-vault: ${describe(error)}`, error instanceof CliError && error.denied ? "warning" : "error");
881
891
  return;
882
892
  }
883
- const sure = await confirmWindow(dialogs(ctx), "ai-vault · 删除条目", `删除「${name}」?删除后无法恢复。`);
893
+ const sure = await confirmWindow(dialogs(ctx), "ai-vault · 删除条目", `删除「${forDialog(name)}」?删除后无法恢复。`);
884
894
  if (!sure) return;
885
895
  try {
886
896
  const result = await cli.json<RemovingResult>([...args, "--yes"]);
@@ -906,7 +916,11 @@ function commandHandler(scope: Scope, bw: BwState) {
906
916
  const args = ["grant", name, "--token", scope.token!];
907
917
  if (minutes) args.push("--minutes", minutes);
908
918
  try {
909
- const result = await cli.json<{ name: string; minutes: number }>(args);
919
+ // A standing grant costs the master password, like a mode change.
920
+ const run = await cli.withPassword(args, () =>
921
+ promptSecret(dialogs(ctx), "ai-vault · 授权读取", "主密码(给这条条目 N 分钟免确认)"),
922
+ );
923
+ const result = JSON.parse(run.stdout) as { name: string; minutes: number };
910
924
  setStatus(ctx, scope, "·granted");
911
925
  note(ctx, `granted "${result.name}" for ${result.minutes}m`);
912
926
  } catch (error) {
@@ -1004,6 +1018,8 @@ export default function aiVault(pi: ExtensionAPI): void {
1004
1018
  pi.registerTool(vaultAddTool(scope));
1005
1019
  pi.registerTool(vaultImportTool(scope, bw));
1006
1020
  registerBitwarden(pi, bw, omp);
1021
+ // Ente Auth: the `ente` CLI keeps its own login; these tools only read codes.
1022
+ registerEnte(pi);
1007
1023
  pi.registerCommand("vault", {
1008
1024
  description: "本地密码库 + Bitwarden 导入(/vault help)",
1009
1025
  handler: commandHandler(scope, bw),
@@ -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,
package/test/cli.sh CHANGED
@@ -49,7 +49,26 @@ echo "== unlock =="
49
49
  check "unlock without a window asks the host" 3 "$BIN" unlock
50
50
  check "a wrong password is an auth failure" 5 bash -c "printf 'wrong password' | '$BIN' unlock --password-stdin"
51
51
  check "the right password opens it" 0 bash -c "printf 'correct horse' | '$BIN' unlock --password-stdin --json"
52
- TOKEN=$(printf 'correct horse' | "$BIN" unlock --password-stdin --json | json token)
52
+ # The extension is the host: it mints its own secret before the first unlock
53
+ # and presents it on every call. A caller that only says AI_VAULT_HOST=1
54
+ # without a secret is treated as a human (see the attacker block).
55
+ HS=$(python3 -c "import secrets;print(secrets.token_hex(32))")
56
+ export AI_VAULT_HOST=1 AI_VAULT_HOST_SECRET="$HS"
57
+ check "a host that presents no secret is not handed one" 0 bash -c "printf 'correct horse' | env -u AI_VAULT_HOST_SECRET '$BIN' unlock --password-stdin --json >'$TMP/nosec'"
58
+ python3 - "$TMP/nosec" <<'PY' && ok "AI_VAULT_HOST=1 alone yields no hostSecret" || bad "a secret was handed to a caller without one"
59
+ import json,sys
60
+ assert json.load(open(sys.argv[1])).get("hostSecret") is None
61
+ PY
62
+ HOST_JSON=$(printf 'correct horse' | "$BIN" unlock --password-stdin --json)
63
+ ECHOED=$(printf '%s' "$HOST_JSON" | python3 -c "import json,sys;print(json.load(sys.stdin).get('hostSecret',''))")
64
+ [[ "$ECHOED" == "$HS" ]] && ok "the host's own secret is echoed back" || bad "hostSecret echo mismatch"
65
+ TOKEN=$(printf '%s' "$HOST_JSON" | json token)
66
+ # relay <entry> <y|n>: a signed approval for the host's token.
67
+ relay() {
68
+ local ap
69
+ ap=$(python3 -c "import hmac,hashlib;print(hmac.new('$HS'.encode(),('allow:$TOKEN:$1:$2'.lower()).encode(),hashlib.sha256).hexdigest())")
70
+ printf '%s\n' "$2" | "$BIN" get "$1" --token "$TOKEN" --answer-stdin --approval "$ap" --json
71
+ }
53
72
  [[ ${#TOKEN} -ge 32 ]] && ok "a session token is printed" || bad "no token"
54
73
  SESS="$XDG_RUNTIME_DIR/ai-vault/sessions/$TOKEN.json"
55
74
  [[ -f "$SESS" ]] && ok "the token file lives under XDG_RUNTIME_DIR" || bad "token file missing"
@@ -70,9 +89,9 @@ grep -q 'p1ssw0rd' "$AI_VAULT_DIR/store.json" && bad "the password is in plainte
70
89
 
71
90
  echo "== read approval =="
72
91
  check "get without a window asks the host" 3 bash -c "'$BIN' get GitHub --token '$TOKEN'"
73
- check "a denied window is not a lock" 4 bash -c "printf 'n\n' | '$BIN' get GitHub --token '$TOKEN' --answer-stdin"
74
- printf 'y\n' | "$BIN" get GitHub --token "$TOKEN" --answer-stdin --json >"$TMP/get" 2>"$TMP/err"
75
- [[ $? -eq 0 ]] && ok "an approved window reveals the entry" || bad "an approved window failed"
92
+ relay GitHub n >"$TMP/deny" 2>"$TMP/denyerr"; [[ $? -eq 4 ]] && ok "a denied relay is not a lock (exit 4)" || bad "a denied relay was not exit 4"
93
+ relay GitHub y >"$TMP/get" 2>"$TMP/err"
94
+ [[ $? -eq 0 ]] && ok "an approved relay reveals the entry" || bad "an approved relay failed"
76
95
  python3 - "$TMP/get" <<'PY' && ok "the approved entry carries the password" || bad "get output is wrong"
77
96
  import json,sys
78
97
  item = json.load(open(sys.argv[1]))
@@ -99,6 +118,50 @@ grep -q 'exp-pass' "$AI_VAULT_DIR/store.json" && bad "an imported password is on
99
118
  check "save requires the caller's --yes" 2 bash -c "printf '[]' | '$BIN' save --token '$TOKEN'"
100
119
  check "save inserts drafts" 0 bash -c "printf '[{\"name\":\"Draft\",\"password\":\"dr-pw\",\"uris\":[\"https://d\"]}]' | '$BIN' save --yes --token '$TOKEN' --json"
101
120
 
121
+ echo "== tamper resistance (H1 / H2) =="
122
+ # A fresh, non-host session for the attacker tests.
123
+ # The attacker: a valid token, but no host identity and no secret (the model's bash).
124
+ T2=$(printf 'correct horse' | env -u AI_VAULT_HOST -u AI_VAULT_HOST_SECRET "$BIN" unlock --password-stdin --json | json token)
125
+ check "attacker: --answer-stdin without a host secret is refused" 2 bash -c "printf 'y\n' | env -u AI_VAULT_HOST -u AI_VAULT_HOST_SECRET '$BIN' get Draft --token '$T2' --answer-stdin"
126
+ check "attacker: a guessed approval with no secret is refused" 2 bash -c "printf 'y\n' | env -u AI_VAULT_HOST -u AI_VAULT_HOST_SECRET '$BIN' get Draft --token '$T2' --answer-stdin --approval 00"
127
+ check "attacker: grant now costs the password (window -> needs-ui)" 3 env -u AI_VAULT_HOST -u AI_VAULT_HOST_SECRET "$BIN" grant Draft --token "$T2"
128
+ T3="$TOKEN"
129
+ "$BIN" revoke Draft --token "$T3" --json >/dev/null
130
+ AP=$(python3 -c "import hmac,hashlib;print(hmac.new('$HS'.encode(),b'allow:$T3:draft:y',hashlib.sha256).hexdigest())")
131
+ check "host: a signed relay is accepted" 0 bash -c "printf 'y\n' | '$BIN' get Draft --token '$T3' --answer-stdin --approval '$AP' --json"
132
+ AP_N=$(python3 -c "import hmac,hashlib;print(hmac.new('$HS'.encode(),b'allow:$T3:draft:n',hashlib.sha256).hexdigest())")
133
+ "$BIN" revoke Draft --token "$T3" --json >/dev/null
134
+ check "a signature for 'n' with stdin 'y' is a mismatch" 4 bash -c "printf 'y\n' | '$BIN' get Draft --token '$T3' --answer-stdin --approval '$AP_N' --json"
135
+ # H2: edit the token file (mint a grant, rename the requester)
136
+ F="$XDG_RUNTIME_DIR/ai-vault/sessions/$T3.json"
137
+ python3 - "$F" <<'PY'
138
+ import json,sys
139
+ d=json.load(open(sys.argv[1])); d['grants']={'draft':9999999999999}; d['requester']='主会话'
140
+ json.dump(d,open(sys.argv[1],'w'))
141
+ PY
142
+ check "an edited token file is rejected" 5 bash -c "'$BIN' get Draft --token '$T3' --json"
143
+ [[ -f "$F" ]] && bad "the tampered file survived" || ok "the tampered file is deleted"
144
+ check "M1: a junk file in the sessions dir is swept on the next call" 0 "$BIN" path --json
145
+
146
+ echo "== sealed Bitwarden session (M4) =="
147
+ check "switch bitwarden.unlock to never" 0 "$BIN" settings bitwarden.unlock never --json
148
+ check "store a bw session key" 0 bash -c "printf 'BW_BEARER_TOKEN_PLAINTEXT' | '$BIN' bw-session put --json"
149
+ grep -q 'BW_BEARER_TOKEN_PLAINTEXT' "$AI_VAULT_DIR/bitwarden.session.json" && bad "the bw key is plaintext on disk" || ok "the bw key is not plaintext on disk"
150
+ [[ -f "$AI_VAULT_DIR/.wrap" ]] && ok "a wrap key exists" || bad "no wrap key"
151
+ [[ "$(stat -c %a "$AI_VAULT_DIR/.wrap")" == "600" ]] && ok "the wrap key is 0600" || bad "the wrap key is not 0600"
152
+ "$BIN" bw-session get --json | grep -q 'BW_BEARER_TOKEN_PLAINTEXT' && ok "bw-session get unseals it" || bad "bw-session get cannot unseal"
153
+ mv "$AI_VAULT_DIR/.wrap" "$TMP/wrap.bak"
154
+ check "without the wrap key the session does not open" 1 "$BIN" bw-session get
155
+ mv "$TMP/wrap.bak" "$AI_VAULT_DIR/.wrap"
156
+ "$BIN" settings bitwarden.unlock session --json >/dev/null
157
+
158
+ echo "== rekey (L2) =="
159
+ OLD_N=$(python3 -c "import json;print(json.load(open('$AI_VAULT_DIR/store.json'))['kdf']['N'])")
160
+ check "rekey with the password" 0 bash -c "printf 'correct horse' | '$BIN' rekey --password-stdin --json"
161
+ NEW_N=$(python3 -c "import json;print(json.load(open('$AI_VAULT_DIR/store.json'))['kdf']['N'])")
162
+ [[ "$NEW_N" == "131072" ]] && ok "scrypt N raised ($OLD_N -> $NEW_N)" || bad "kdf N is $NEW_N after rekey"
163
+ check "the store still opens with the same password" 0 bash -c "printf 'correct horse' | '$BIN' unlock --password-stdin --json"
164
+
102
165
  echo "== lock / audit =="
103
166
  check "lock drops the token" 0 "$BIN" lock --token "$TOKEN" --json
104
167
  check "a dropped token no longer works" 5 "$BIN" list --token "$TOKEN"
@@ -107,7 +170,7 @@ python3 - "$TMP/audit" <<'PY' && ok "the audit log records events without values
107
170
  import json,sys
108
171
  entries = json.load(open(sys.argv[1]))["entries"]
109
172
  events = {e["event"] for e in entries}
110
- for want in ("init", "unlock", "unlock_failed", "add", "grant", "read_deny", "read_allow", "remove", "import", "lock"):
173
+ for want in ("init", "unlock", "unlock_failed", "add", "grant", "read_deny", "read_allow", "remove", "import", "lock", "rekey", "bw_session"):
111
174
  assert want in events, (want, events)
112
175
  assert not any("p1ssw0rd" in json.dumps(e) or "exp-pass" in json.dumps(e) for e in entries)
113
176
  PY
@@ -149,6 +212,23 @@ check "bw-session put in time mode" 0 bash -c "printf 'K2' | '$BIN' bw-session p
149
212
  grep -q '"expiresAt": *[0-9]' "$AI_VAULT_DIR/bitwarden.session.json" && ok "time mode writes a deadline" || bad "time mode wrote no deadline"
150
213
  "$BIN" settings bitwarden.unlock session --json >/dev/null
151
214
 
215
+ echo "== two stores share the sessions dir =="
216
+ # A second store in another directory uses the same XDG_RUNTIME_DIR sessions
217
+ # directory. Housekeeping of one must not delete the other's live token.
218
+ TA=$(printf 'correct horse' | "$BIN" unlock --password-stdin --json | json token)
219
+ check "store A: token works" 0 "$BIN" list --token "$TA" --json
220
+ export AI_VAULT_DIR="$TMP/store2"
221
+ printf 'other horse' | "$BIN" init --password-stdin --json >/dev/null
222
+ TOK2=$(printf 'other horse' | "$BIN" unlock --password-stdin --json | json token)
223
+ # B's init and unlock each ran a sweep; A's token must still be there.
224
+ export AI_VAULT_DIR="$TMP/store"
225
+ check "store A's token survives store B's init/unlock" 0 "$BIN" list --token "$TA" --json
226
+ # A's calls just ran A's sweep; B's token must still be there.
227
+ export AI_VAULT_DIR="$TMP/store2"
228
+ check "store B's token survives store A's calls" 0 "$BIN" list --token "$TOK2" --json
229
+ "$BIN" lock --token "$TOK2" >/dev/null
230
+ export AI_VAULT_DIR="$TMP/store"
231
+
152
232
  echo "== doctor =="
153
233
  check "doctor runs" 0 "$BIN" doctor --json
154
234
 
@@ -0,0 +1,86 @@
1
+ import { test } from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { readFileSync, writeFileSync, rmSync } from "node:fs";
4
+ import { join } from "node:path";
5
+ import { answers, bind, cleanUpOnExit, dialogTrace, makeCtx, textOf, useMocks } from "./helpers.mjs";
6
+
7
+ const dir = useMocks();
8
+ const { default: aiVault } = await import("../packages/pi-ai-vault/src/index.ts");
9
+ cleanUpOnExit(dir);
10
+
11
+ const enteLog = () => {
12
+ try {
13
+ return readFileSync(join(dir, "ente.log"), "utf8");
14
+ } catch {
15
+ return "";
16
+ }
17
+ };
18
+ const codePrompts = () => dialogTrace(dir).split("\n").filter((line) => line.includes("Ente Auth")).length;
19
+
20
+ test("ente_list returns metadata and never touches a code", async () => {
21
+ const b = bind(aiVault, true);
22
+ const result = await b.tool("ente_list", {}, makeCtx().ctx);
23
+ assert.equal(result.isError, undefined);
24
+ const items = JSON.parse(textOf(result));
25
+ assert.deepEqual(items.map((i) => i.name), ["GitHub", "Cloudflare", "Steam"]);
26
+ assert.equal(items[0].otp, undefined, "listing must not leak a code");
27
+ assert.equal(/auth code view/.test(enteLog()), false, "listing must not run a code view");
28
+ });
29
+
30
+ test("ente_code asks a window naming the entry, then returns the code", async () => {
31
+ const b = bind(aiVault, true);
32
+ const ctx = makeCtx().ctx;
33
+ const before = codePrompts();
34
+ answers.questions(dir, "y");
35
+ const result = await b.tool("ente_code", { name: "github" }, ctx);
36
+ const body = JSON.parse(textOf(result));
37
+ assert.equal(result.details.via ?? body.via, "ente");
38
+ assert.equal(body.code, "00420731", "leading zeroes survive");
39
+ assert.match(dialogTrace(dir), /GitHub/);
40
+ assert.equal(codePrompts(), before + 1);
41
+ });
42
+
43
+ test("ente_code denial is reported and not retried", async () => {
44
+ const b = bind(aiVault, true);
45
+ answers.questions(dir, "n");
46
+ const result = await b.tool("ente_code", { name: "Cloudflare" }, makeCtx().ctx);
47
+ assert.equal(result.isError, true);
48
+ assert.equal(result.details.denied, true);
49
+ assert.match(textOf(result), /do not retry/);
50
+ });
51
+
52
+ test("ente_code reports the candidates when the name matches more than one", async () => {
53
+ const b = bind(aiVault, true);
54
+ answers.questions(dir, "y");
55
+ const result = await b.tool("ente_code", { name: "example.com" }, makeCtx().ctx);
56
+ // "example.com" is part of two account names, so no single entry is chosen.
57
+ assert.equal(result.isError, true);
58
+ assert.match(textOf(result), /no single Ente entry matches/);
59
+ assert.match(textOf(result), /Cloudflare/);
60
+ });
61
+
62
+ test("ente tools say what to do when the CLI has no account", async () => {
63
+ writeFileSync(join(dir, "unauthenticated"), "");
64
+ writeFileSync(join(dir, "no-cache"), "");
65
+ const b = bind(aiVault, true);
66
+ const result = await b.tool("ente_list", {}, makeCtx().ctx);
67
+ assert.equal(result.isError, true, textOf(result));
68
+ assert.match(textOf(result), /ente account login|no account/i);
69
+ rmSync(join(dir, "unauthenticated"), { force: true });
70
+ rmSync(join(dir, "no-cache"), { force: true });
71
+ });
72
+
73
+ test("a secrets audit line exists for allow and deny, without the code", async () => {
74
+ const log = readFileSync(join(process.env.HOME, ".bw", "pi-extension", "audit.log"), "utf8");
75
+ assert.match(log, /ente\.code session=\S+ allow item="GitHub"/);
76
+ assert.match(log, /ente\.code session=\S+ deny item="Cloudflare"/);
77
+ assert.equal(log.includes("00420731"), false, "the audit log must not carry the code");
78
+ });
79
+
80
+ test("a failed sync falls back to the offline cache", async () => {
81
+ writeFileSync(join(dir, "list-fails-once"), "");
82
+ const b = bind(aiVault, true);
83
+ const result = await b.tool("ente_list", {}, makeCtx().ctx);
84
+ assert.equal(result.isError, undefined, textOf(result));
85
+ assert.equal(JSON.parse(textOf(result)).length, 3);
86
+ });
package/tests/helpers.mjs CHANGED
@@ -36,6 +36,8 @@ export function useMocks() {
36
36
  process.env.PATH = `${MOCKS}:${process.env.PATH}`;
37
37
  process.env.OMP_VAULT_BW_MOCK_DIR = dir;
38
38
  process.env.OMP_VAULT_MOCK = dir;
39
+ // The ente mock keeps its own state directory, like the bw one.
40
+ process.env.ENTE_MOCK_DIR = dir;
39
41
  process.env.AI_VAULT_DIR = join(dir, "vault");
40
42
  process.env.AI_VAULT_BIN = cliBinary();
41
43
  return dir;