@xiaolikt/ai-vault 0.7.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.
package/Cargo.lock CHANGED
@@ -14,7 +14,7 @@ dependencies = [
14
14
 
15
15
  [[package]]
16
16
  name = "ai-vault"
17
- version = "0.7.0"
17
+ version = "0.8.0"
18
18
  dependencies = [
19
19
  "base64",
20
20
  "chacha20poly1305",
package/README.md CHANGED
@@ -146,6 +146,8 @@ ai-vault get <条目> --token <T> --answer-stdin --approval <hex> <<< 'y'
146
146
  | `bw_inject` | 注入 bash 环境(**仅 pi**) | exec | 否 |
147
147
  | `bw_clipboard` | 复制到剪贴板,到时清除 | write | 否 |
148
148
  | `bw_reveal` | 明文返回(默认关闭,每次确认) | exec | 是,用户当场允许 |
149
+ | `ente_list` | Ente Auth 条目元数据(名称/签发方/账号/类型) | read | 否 |
150
+ | `ente_code` | 读一条当前 TOTP/Steam 验证码,每次弹窗确认 | write | 是,用户当场允许 |
149
151
 
150
152
  字段选择:`password`(默认)· `totp`(种子)· `code`(动态验证码)· `notes` · `field:<自定义字段名>`。
151
153
 
@@ -244,6 +246,35 @@ ai-vault settings bitwarden.hours 24
244
246
  - `/bw lock` 只丢弃当前绑定的会话密钥;同一进程里还有别的绑定持有时不会执行全局 `bw lock`,最后一个绑定释放时才真正作废 CLI 会话。
245
247
  - Bitwarden 会话密钥只在 agent 进程内存里,不落盘、不进 bash 环境。
246
248
 
249
+ ## Ente(Auth 验证码)
250
+
251
+ `ente` 是 Ente 官方的终端客户端(0.4+)。它**自己登录一次**:
252
+
253
+ ```bash
254
+ ente account login --app auth # 邮箱 + 密码(+ 2FA 验证码)
255
+ ente auth code list # 之后每次都不再问密码
256
+ ```
257
+
258
+ 会话存在 `$XDG_DATA_HOME/ente-cli`(Linux 默认 `~/.local/share/ente-cli`),数据库密钥默认放系统钥匙串;无桌面/无人值守时用
259
+
260
+ ```bash
261
+ ente vault key generate # 打印一个 key
262
+ export ENTE_CLI_VAULT_KEY=<那个 key> # 之后连钥匙串都不用
263
+ ```
264
+
265
+ 所以在 `session` 这种日常形态下,**每次查看不会再要你的密码**,最多要一次系统钥匙串解锁。
266
+
267
+ pi-ai-vault 只是这套 CLI 的客户端,本身不保存 Ente 的任何密钥:
268
+
269
+ | 工具 | 作用 |
270
+ |---|---|
271
+ | `ente_list` | 列出条目(name / issuer / accountName / type),**不含验证码** |
272
+ | `ente_code <名字>` | 弹窗显示实际命中的条目,允许后返回当前验证码和过期时间 |
273
+
274
+ 安全上和 `bw_*` 一套规则:列表只给元数据;读码每次确认;拒绝后不重试;允许/拒绝都写审计(`~/.bw/pi-extension/audit.log`,`ente.code` 事件,不含码本身);条目名/签发方进窗口前会被压成一行,防伪造。
275
+
276
+ 插件启动的 bash 会剔除 `ENTE_CLI_VAULT_KEY` / `ENTE_CLI_PASSWORD`,避免你 shell 里导出的免密 key 漏进模型自己的命令环境。**注意**:`ente` 二进制本身也在 PATH 上,模型直接跑 `ente auth code view` 仍能绕过这个扩展的确认窗——要收紧要靠 `ENTE_CLI_VAULT_KEY` + 把模型的 `ENTE_CLI_HOME` 指到别处,或者干脆不让 agent 有 shell。
277
+
247
278
  ## 安全
248
279
 
249
280
  ### 威胁模型:谁能做什么
@@ -1,6 +1,6 @@
1
1
  [package]
2
2
  name = "ai-vault"
3
- version = "0.7.0"
3
+ version = "0.8.0"
4
4
  edition = "2021"
5
5
  description = "Machine-wide encrypted secret store shared by AI coding agents"
6
6
  license = "MIT"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xiaolikt/ai-vault",
3
- "version": "0.7.0",
3
+ "version": "0.8.0",
4
4
  "description": "One machine-wide encrypted secret store for AI coding agents: the ai-vault Rust CLI (npm-installable) plus the pi-ai-vault extension for pi and omp.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -33,7 +33,7 @@
33
33
  "access": "public"
34
34
  },
35
35
  "optionalDependencies": {
36
- "@xiaolikt/ai-vault-linux-x64": "0.7.0"
36
+ "@xiaolikt/ai-vault-linux-x64": "0.8.0"
37
37
  },
38
38
  "files": [
39
39
  "bin",
@@ -31,6 +31,8 @@ omp plugin install npm:pi-ai-vault # omp,同一个包
31
31
  | `vault_import` | 把 Bitwarden 登录项抄进本地库(先确认) | 否 |
32
32
  | `bw_list` / `bw_run` / `bw_clipboard` / `bw_reveal` | 在线 Bitwarden(`bw` CLI) | 否,`bw_reveal` 除外 |
33
33
  | `bw_inject` | 注入 bash 环境(**仅 pi**,omp 不注册) | 否 |
34
+ | `ente_list` | Ente Auth 条目元数据 | 否 |
35
+ | `ente_code` | 当前 TOTP/Steam 验证码(每次确认) | 是,用户当场允许 |
34
36
 
35
37
  ## 命令
36
38
 
@@ -61,6 +63,10 @@ omp plugin install npm:pi-ai-vault # omp,同一个包
61
63
 
62
64
  所以默认情况下 **只有你同意导入的密码才会进 ai-vault**。Bitwarden 自己的主密码请求频率也有单独设置(`bitwarden.unlock`:`never` / `time` / `session`),用 `/vault settings` 查看和修改。
63
65
 
66
+ ## Ente
67
+
68
+ `ente` CLI 自己登录一次(`ente account login --app auth`),插件只是它的客户端:`ente_list` 只给元数据,`ente_code` 每次弹窗确认。详见仓库 README。
69
+
64
70
  ## 安全边界(一句话版)
65
71
 
66
72
  模型的 `bash` 能找到会话令牌、能 `list`,但**签不出读取确认**(签名密钥只在插件进程内存里)、**改不了令牌文件**(带 HMAC,改了就作废)、**免费拿不到 `grant`**(要主密码)。详见仓库 README「安全」一节。
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-ai-vault",
3
- "version": "0.7.0",
3
+ "version": "0.8.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.7.0"
28
+ "@xiaolikt/ai-vault": "0.8.0"
29
29
  },
30
30
  "peerDependencies": {
31
31
  "@earendil-works/pi-coding-agent": "^1.5.0",
@@ -354,7 +354,7 @@ const AUDIT_MAX_BYTES = 1024 * 1024;
354
354
  let auditModeFixed = false;
355
355
 
356
356
  /** One audit line per event. `session` is the binding's label, so a subagent's `bw_run` can be told from its parent's. */
357
- async function audit(event: string, detail: string, session?: string): Promise<void> {
357
+ export async function auditEvent(event: string, detail: string, session?: string): Promise<void> {
358
358
  try {
359
359
  await fs.mkdir(STATE_DIR, { recursive: true, mode: 0o700 });
360
360
  const log = path.join(STATE_DIR, "audit.log");
@@ -513,7 +513,7 @@ async function lock(st: BwState, reason: string): Promise<void> {
513
513
  st.lockTimer = undefined;
514
514
  }
515
515
  if (hadSession) {
516
- await audit("lock", `reason=${reason}`, st.sessionLabel);
516
+ await auditEvent("lock", `reason=${reason}`, st.sessionLabel);
517
517
  if (!releaseSessionKey()) return; // another binding still uses its own key
518
518
  try {
519
519
  const bin = await resolveBw();
@@ -581,7 +581,7 @@ async function ensureUnlocked(st: BwState, ctx: ExtensionContext | undefined, si
581
581
  signal,
582
582
  });
583
583
  if (r.code !== 0) {
584
- await audit("unlock", "deny=bad-password", st.sessionLabel);
584
+ await auditEvent("unlock", "deny=bad-password", st.sessionLabel);
585
585
  throw new Error(`Unlock failed (wrong master password or CLI error). ${tail(r.stderr, 120)}`);
586
586
  }
587
587
  const key = r.stdout.replace(/[\r\n]+$/, "");
@@ -599,7 +599,7 @@ async function ensureUnlocked(st: BwState, ctx: ExtensionContext | undefined, si
599
599
  // from the bitwarden.hours policy.
600
600
  await settingsCli().run(["bw-session", "put"], { stdin: key }).catch(() => undefined);
601
601
  }
602
- await audit("unlock", "ok", st.sessionLabel);
602
+ await auditEvent("unlock", "ok", st.sessionLabel);
603
603
  // Refresh in the background: a full sync can take seconds on large vaults.
604
604
  const lastSync = Date.parse(status?.lastSync ?? "");
605
605
  if (!Number.isFinite(lastSync) || Date.now() - lastSync > 15 * 60_000) {
@@ -750,7 +750,7 @@ async function approveItem(
750
750
  const user = item.username ? ` (user: ${item.username})` : "";
751
751
  const ok = await confirmAction(ctx, title, `Item: ${name}${user}\nField: ${field}\n${detail}\n\nAllow?`, signal);
752
752
  if (!ok) {
753
- await audit(event, `deny item="${name}" field=${field}`, st.sessionLabel);
753
+ await auditEvent(event, `deny item="${name}" field=${field}`, st.sessionLabel);
754
754
  return undefined;
755
755
  }
756
756
  return { session, item };
@@ -1116,6 +1116,9 @@ export function registerBitwarden(pi: ExtensionAPI, st: BwState, ompHost: boolea
1116
1116
  spawnHook: ({ command, cwd, env }) => {
1117
1117
  // A BW_SESSION exported in the user's shell must not reach bash.
1118
1118
  for (const name of Object.keys(env)) if (name.startsWith("BW_")) delete env[name];
1119
+ // Same for Ente's unattended vault key / export password: the model's
1120
+ // shell must not be able to open Ente Auth with what the user exported.
1121
+ for (const name of ["ENTE_CLI_VAULT_KEY", "ENTE_CLI_PASSWORD"]) delete env[name];
1119
1122
  for (const [name, rec] of st.injected) env[name] = rec.value;
1120
1123
  return { command, cwd, env };
1121
1124
  },
@@ -1230,7 +1233,7 @@ export function registerBitwarden(pi: ExtensionAPI, st: BwState, ompHost: boolea
1230
1233
  const { value, itemId, itemName } = await secretOf(approved.session, approved.item, field, signal);
1231
1234
  st.injected.set(envName, { value, item: itemName, field, at: Date.now() });
1232
1235
  rememberScrubValue(envName, value);
1233
- await audit("inject", `allow env=${envName} item="${itemName}" (${itemId}) field=${field}`, st.sessionLabel);
1236
+ await auditEvent("inject", `allow env=${envName} item="${itemName}" (${itemId}) field=${field}`, st.sessionLabel);
1234
1237
  safeStatus(ctx, `🔓 bw: ${st.injected.size} env var(s)`);
1235
1238
  const weak =
1236
1239
  value.length < 6
@@ -1303,7 +1306,7 @@ export function registerBitwarden(pi: ExtensionAPI, st: BwState, ompHost: boolea
1303
1306
  signal,
1304
1307
  group: true,
1305
1308
  });
1306
- await audit("run", `allow env=${envName} item="${itemName}" field=${field} exit=${r.code}`, st.sessionLabel);
1309
+ await auditEvent("run", `allow env=${envName} item="${itemName}" field=${field} exit=${r.code}`, st.sessionLabel);
1307
1310
  const raw = [r.stdout, r.stderr].filter((s) => s.length > 0).join("\n");
1308
1311
  const scrubbed = scrubText(raw, scrubValues.values()).text;
1309
1312
  const output =
@@ -1356,7 +1359,7 @@ export function registerBitwarden(pi: ExtensionAPI, st: BwState, ompHost: boolea
1356
1359
  // so tool output carrying it must be scrubbed like an injected var.
1357
1360
  rememberScrubValue("CLIPBOARD", value);
1358
1361
  await copyToClipboard(value);
1359
- await audit("clipboard", `allow item="${itemName}" field=${field}`, st.sessionLabel);
1362
+ await auditEvent("clipboard", `allow item="${itemName}" field=${field}`, st.sessionLabel);
1360
1363
  const clears =
1361
1364
  CONFIG.clipboardClearSeconds > 0 ? `Clears in ${CONFIG.clipboardClearSeconds}s.` : "Auto-clear disabled.";
1362
1365
  return {
@@ -1401,7 +1404,7 @@ export function registerBitwarden(pi: ExtensionAPI, st: BwState, ompHost: boolea
1401
1404
  );
1402
1405
  if (!approved) throw new Error("User declined the reveal.");
1403
1406
  const { value, itemName } = await secretOf(approved.session, approved.item, field, signal);
1404
- await audit("reveal", `allow item="${itemName}" field=${field}`, st.sessionLabel);
1407
+ await auditEvent("reveal", `allow item="${itemName}" field=${field}`, st.sessionLabel);
1405
1408
  return {
1406
1409
  content: [{ type: "text", text: `${itemName} (${field}):\n<secret>${value}</secret>` }],
1407
1410
  details: { item: itemName, field },
@@ -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,6 +23,7 @@ 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
28
  import { confirmWindow, forDialog, promptSecret, promptText, type PromptHost } from "./prompt.js";
28
29
  import { forgetSettings, getSettingsSafe, type Settings } from "./settings.js";
@@ -1017,6 +1018,8 @@ export default function aiVault(pi: ExtensionAPI): void {
1017
1018
  pi.registerTool(vaultAddTool(scope));
1018
1019
  pi.registerTool(vaultImportTool(scope, bw));
1019
1020
  registerBitwarden(pi, bw, omp);
1021
+ // Ente Auth: the `ente` CLI keeps its own login; these tools only read codes.
1022
+ registerEnte(pi);
1020
1023
  pi.registerCommand("vault", {
1021
1024
  description: "本地密码库 + Bitwarden 导入(/vault help)",
1022
1025
  handler: commandHandler(scope, bw),
@@ -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;
@@ -0,0 +1,61 @@
1
+ #!/bin/bash
2
+ # Mock `ente` CLI for the ai-vault tests.
3
+ #
4
+ # Contract under test (ente.com/help/cli/auth):
5
+ # ente --json --no-input auth code list -> [{id,name,issuer,accountName,type}]
6
+ # ente --json --no-input auth code view <ref> -> the same object + {otp,validUntil}
7
+ #
8
+ # Every call is one line in $ENTE_MOCK_DIR/ente.log, so a test can assert that
9
+ # the list path never asked for a code.
10
+ DIR="${ENTE_MOCK_DIR:-/tmp/ente-mock}"
11
+ mkdir -p "$DIR"
12
+ printf '%s\n' "$*" >>"$DIR/ente.log"
13
+ if [[ -f "$DIR/unauthenticated" ]]; then
14
+ echo "no account logged in; run ente account login --app auth" >&2
15
+ exit 3
16
+ fi
17
+ # --offline still needs a synced database: same failure when nothing was ever
18
+ # logged in, which is what the tool must report to the user.
19
+ if [[ -f "$DIR/no-cache" ]]; then
20
+ echo "nothing has been synced yet" >&2
21
+ exit 4
22
+ fi
23
+
24
+ # Drop the global flags we do not care about, keep the subcommand path.
25
+ args=()
26
+ for a in "$@"; do
27
+ case "$a" in
28
+ --json|--no-input|--offline) ;;
29
+ *) args+=("$a") ;;
30
+ esac
31
+ done
32
+ joined="${args[*]}"
33
+
34
+ case "$joined" in
35
+ "auth code list")
36
+ if [[ -f "$DIR/list-fails-once" ]]; then
37
+ rm -f "$DIR/list-fails-once"
38
+ echo "sync needed" >&2
39
+ exit 1
40
+ fi
41
+ cat <<'JSON'
42
+ [{"id":"c1","name":"GitHub","issuer":"github.com","accountName":"octo@example.com","type":"totp"},
43
+ {"id":"c2","name":"Cloudflare","issuer":"Cloudflare","accountName":"ops@example.com","type":"totp"},
44
+ {"id":"c3","name":"Steam","issuer":"Steam","accountName":"gamer","type":"steam"}]
45
+ JSON
46
+ ;;
47
+ "auth code view GitHub")
48
+ echo '{"id":"c1","name":"GitHub","issuer":"github.com","accountName":"octo@example.com","type":"totp","otp":"00420731","validUntil":"2030-01-01T00:00:30Z"}'
49
+ ;;
50
+ "auth code view "*)
51
+ echo "no saved code matches that entry" >&2
52
+ exit 1
53
+ ;;
54
+ "account list")
55
+ echo '[{"name":"default","email":"t@example.com","apps":["auth"]}]'
56
+ ;;
57
+ *)
58
+ echo "mock ente: unhandled: $joined" >&2
59
+ exit 2
60
+ ;;
61
+ esac
@@ -6,7 +6,7 @@ const dir = useMocks();
6
6
  const { default: ompVault } = await import("../packages/pi-ai-vault/src/index.ts");
7
7
  cleanUpOnExit(dir);
8
8
 
9
- test("omp: one extension registers the local vault and live Bitwarden, without bw_inject", () => {
9
+ test("omp: one extension registers the local vault, Bitwarden and Ente, without bw_inject", () => {
10
10
  const b = bind(ompVault, true);
11
11
  assert.deepEqual([...b.tools.keys()], [
12
12
  "vault_list",
@@ -17,6 +17,8 @@ test("omp: one extension registers the local vault and live Bitwarden, without b
17
17
  "bw_run",
18
18
  "bw_clipboard",
19
19
  "bw_reveal",
20
+ "ente_list",
21
+ "ente_code",
20
22
  ]);
21
23
  assert.deepEqual([...b.commands.keys()].sort(), ["bw", "vault"]);
22
24
  // omp reads the reason from session_switch; its session_start has none.
@@ -42,6 +44,8 @@ test("tools declare the approval tier omp prompts by: reads read, writes write",
42
44
  assert.equal(b.tools.get("vault_import").approval, "write");
43
45
  assert.equal(b.tools.get("bw_clipboard").approval, "write");
44
46
  assert.equal(b.tools.get("bw_run").approval, "exec");
47
+ assert.equal(b.tools.get("ente_list").approval, "read");
48
+ assert.equal(b.tools.get("ente_code").approval, "write");
45
49
  // A secret handed to the model keeps the strictest tier.
46
50
  assert.equal(b.tools.get("vault_get").approval, undefined);
47
51
  assert.equal(b.tools.get("bw_reveal").approval, undefined);