@xiaolikt/ai-vault 0.7.0 → 0.9.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 +1 -1
- package/README.md +44 -1
- package/crates/ai-vault/Cargo.toml +1 -1
- package/crates/ai-vault/src/cli.rs +71 -24
- package/crates/ai-vault/src/config.rs +25 -7
- package/crates/ai-vault/src/main.rs +1 -1
- package/crates/ai-vault/src/paths.rs +0 -6
- package/crates/ai-vault/src/{bwsession.rs → sealed.rs} +48 -21
- package/package.json +2 -2
- package/packages/pi-ai-vault/README.md +8 -0
- package/packages/pi-ai-vault/package.json +2 -2
- package/packages/pi-ai-vault/src/bitwarden.ts +12 -9
- package/packages/pi-ai-vault/src/ente.ts +304 -0
- package/packages/pi-ai-vault/src/index.ts +26 -1
- package/packages/pi-ai-vault/src/settings.ts +3 -0
- package/test/cli.sh +12 -1
- package/tests/ente.test.mjs +137 -0
- package/tests/helpers.mjs +5 -0
- package/tests/mocks/bin/ente +68 -0
- package/tests/register.test.mjs +5 -1
|
@@ -0,0 +1,304 @@
|
|
|
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
|
+
import { getSettingsSafe, settingsCli } from "./settings.js";
|
|
29
|
+
|
|
30
|
+
export interface EnteCodeMeta {
|
|
31
|
+
id: string;
|
|
32
|
+
name: string;
|
|
33
|
+
issuer: string;
|
|
34
|
+
accountName: string;
|
|
35
|
+
type: string;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export interface EnteCode extends EnteCodeMeta {
|
|
39
|
+
otp: string;
|
|
40
|
+
validUntil: string;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export class EnteError extends Error {
|
|
44
|
+
constructor(message: string, readonly code: number) {
|
|
45
|
+
super(message);
|
|
46
|
+
this.name = "EnteError";
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const ENTE_MISSING =
|
|
51
|
+
"ente CLI 没找到(要的是 ente.com 的 `ente`,0.4+)。装好后先 `ente account login --app auth` 登录一次;也可以用 ENTE_BIN 指到二进制。";
|
|
52
|
+
|
|
53
|
+
/** `ENTE_BIN`, then PATH, then the usual install spots. */
|
|
54
|
+
export function resolveEnte(): string | undefined {
|
|
55
|
+
const explicit = process.env.ENTE_BIN;
|
|
56
|
+
if (explicit) return existsSync(explicit) ? explicit : undefined;
|
|
57
|
+
for (const dir of (process.env.PATH ?? "").split(delimiter)) {
|
|
58
|
+
if (!dir) continue;
|
|
59
|
+
const candidate = join(dir, "ente");
|
|
60
|
+
if (existsSync(candidate)) return candidate;
|
|
61
|
+
}
|
|
62
|
+
for (const candidate of [
|
|
63
|
+
join(homedir(), ".local", "opt", "ente-cli", "bin", "ente"),
|
|
64
|
+
join(homedir(), ".local", "bin", "ente"),
|
|
65
|
+
join(homedir(), ".cargo", "bin", "ente"),
|
|
66
|
+
]) {
|
|
67
|
+
if (existsSync(candidate)) return candidate;
|
|
68
|
+
}
|
|
69
|
+
return undefined;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
interface Run {
|
|
73
|
+
code: number;
|
|
74
|
+
stdout: string;
|
|
75
|
+
stderr: string;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* The environment for one `ente` run.
|
|
80
|
+
*
|
|
81
|
+
* `ente.unlock = never | time`: the key is kept sealed by ai-vault (the same
|
|
82
|
+
* wrapping as the Bitwarden session), so Ente needs neither the OS keychain
|
|
83
|
+
* nor a login window. `session` (default) leaves the keychain in charge and
|
|
84
|
+
* passes nothing.
|
|
85
|
+
*/
|
|
86
|
+
async function enteEnv(signal?: AbortSignal): Promise<Record<string, string | undefined>> {
|
|
87
|
+
const env: Record<string, string | undefined> = { ...process.env };
|
|
88
|
+
// Never let a key the user exported in their shell decide this.
|
|
89
|
+
delete env.ENTE_CLI_VAULT_KEY;
|
|
90
|
+
const settings = await getSettingsSafe(signal);
|
|
91
|
+
if (settings.ente.unlock === "session") return env;
|
|
92
|
+
try {
|
|
93
|
+
const sealed = await settingsCli().json<{ key: string }>(["ente-session", "get"], { signal });
|
|
94
|
+
if (sealed?.key) env.ENTE_CLI_VAULT_KEY = sealed.key;
|
|
95
|
+
} catch {
|
|
96
|
+
// No key saved yet, or it expired: ente will fall back to the keychain,
|
|
97
|
+
// which is exactly what a `session` policy would have done.
|
|
98
|
+
}
|
|
99
|
+
return env;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
async function runEnte(args: string[], signal?: AbortSignal): Promise<Run> {
|
|
103
|
+
const bin = resolveEnte();
|
|
104
|
+
if (!bin) throw new EnteError(ENTE_MISSING, 127);
|
|
105
|
+
if (signal?.aborted) throw new EnteError("Cancelled.", 4);
|
|
106
|
+
const env = await enteEnv(signal);
|
|
107
|
+
return new Promise<Run>((resolve, reject) => {
|
|
108
|
+
const child = spawn(bin, args, { stdio: ["ignore", "pipe", "pipe"], env });
|
|
109
|
+
let stdout = "";
|
|
110
|
+
let stderr = "";
|
|
111
|
+
const onAbort = () => child.kill("SIGKILL");
|
|
112
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
113
|
+
child.stdout?.on("data", (chunk: Buffer | string) => {
|
|
114
|
+
if (stdout.length < 8 * 1024 * 1024) stdout += chunk;
|
|
115
|
+
});
|
|
116
|
+
child.stderr?.on("data", (chunk: Buffer | string) => {
|
|
117
|
+
if (stderr.length < 64_000) stderr += chunk;
|
|
118
|
+
});
|
|
119
|
+
child.on("error", (error) => {
|
|
120
|
+
signal?.removeEventListener("abort", onAbort);
|
|
121
|
+
reject(new EnteError(`cannot run ente: ${error.message}`, 127));
|
|
122
|
+
});
|
|
123
|
+
child.on("close", (code) => {
|
|
124
|
+
signal?.removeEventListener("abort", onAbort);
|
|
125
|
+
resolve({ code: code ?? -1, stdout, stderr });
|
|
126
|
+
});
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
async function enteJson<T>(args: string[], signal?: AbortSignal): Promise<T> {
|
|
131
|
+
// --no-input: a prompt becomes an error instead of a hang behind our back.
|
|
132
|
+
const run = await runEnte(["--json", "--no-input", ...args], signal);
|
|
133
|
+
if (run.code !== 0) {
|
|
134
|
+
const message = run.stderr
|
|
135
|
+
.split(/\r?\n/)
|
|
136
|
+
.map((line) => line.trim())
|
|
137
|
+
.filter(Boolean)
|
|
138
|
+
.slice(-3)
|
|
139
|
+
.join(" ");
|
|
140
|
+
throw new EnteError(message || `ente exited with ${run.code}`, run.code);
|
|
141
|
+
}
|
|
142
|
+
try {
|
|
143
|
+
return JSON.parse(run.stdout) as T;
|
|
144
|
+
} catch {
|
|
145
|
+
throw new EnteError(`ente returned non-JSON output: ${run.stdout.slice(0, 200)}`, 1);
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
const asString = (value: unknown): string => (typeof value === "string" ? value : "");
|
|
150
|
+
const normalize = (raw: unknown): EnteCodeMeta => {
|
|
151
|
+
const r = (raw ?? {}) as Record<string, unknown>;
|
|
152
|
+
return {
|
|
153
|
+
id: asString(r.id),
|
|
154
|
+
name: forDialog(asString(r.name), 80),
|
|
155
|
+
issuer: forDialog(asString(r.issuer), 60),
|
|
156
|
+
accountName: forDialog(asString(r.accountName), 60),
|
|
157
|
+
type: asString(r.type) || "totp",
|
|
158
|
+
};
|
|
159
|
+
};
|
|
160
|
+
|
|
161
|
+
/** Metadata only: names, issuers, account names. No codes, no secrets. */
|
|
162
|
+
export async function listCodes(signal?: AbortSignal): Promise<EnteCodeMeta[]> {
|
|
163
|
+
const list = async (extra: string[] = []): Promise<EnteCodeMeta[]> => {
|
|
164
|
+
const raw = await enteJson<unknown[]>(["auth", "code", "list", ...extra], signal);
|
|
165
|
+
return Array.isArray(raw) ? raw.map(normalize) : [];
|
|
166
|
+
};
|
|
167
|
+
try {
|
|
168
|
+
return await list();
|
|
169
|
+
} catch (error) {
|
|
170
|
+
// A first run may have nothing synced yet; --offline reads what is cached.
|
|
171
|
+
// A not-logged-in CLI fails both ways, and the error is what the user needs.
|
|
172
|
+
if (!(error instanceof EnteError)) throw error;
|
|
173
|
+
return list(["--offline"]);
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/** One current code. The caller must have shown the user which entry this is. */
|
|
178
|
+
export async function viewCode(ref: string, signal?: AbortSignal): Promise<EnteCode> {
|
|
179
|
+
const raw = await enteJson<Record<string, unknown>>(["auth", "code", "view", ref], signal);
|
|
180
|
+
const meta = normalize(raw);
|
|
181
|
+
const otp = asString(raw.otp);
|
|
182
|
+
if (!otp) throw new EnteError(`ente returned no code for "${ref}"`, 1);
|
|
183
|
+
return { ...meta, otp, validUntil: asString(raw.validUntil) };
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/** The entry a reference really names, so the window shows what will be read. */
|
|
187
|
+
export function resolveRef(items: EnteCodeMeta[], ref: string): EnteCodeMeta | undefined {
|
|
188
|
+
const query = ref.trim().toLowerCase();
|
|
189
|
+
if (!query) return undefined;
|
|
190
|
+
const haystack = (item: EnteCodeMeta): string =>
|
|
191
|
+
`${item.name}\n${item.issuer}\n${item.accountName}`.toLowerCase();
|
|
192
|
+
const exact = items.filter((item) => item.name.toLowerCase() === query);
|
|
193
|
+
if (exact.length === 1) return exact[0];
|
|
194
|
+
const hits = items.filter((item) => haystack(item).includes(query));
|
|
195
|
+
return hits.length === 1 ? hits[0] : exact[0] ?? (hits.length > 1 ? undefined : undefined);
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
type ToolOutcome = {
|
|
199
|
+
content: { type: "text"; text: string }[];
|
|
200
|
+
details: { ok?: boolean; denied?: boolean; item?: string; count?: number };
|
|
201
|
+
isError?: boolean;
|
|
202
|
+
};
|
|
203
|
+
|
|
204
|
+
const fail = (text: string, denied = false): ToolOutcome => ({
|
|
205
|
+
content: [{ type: "text" as const, text }],
|
|
206
|
+
details: { ok: false, ...(denied ? { denied: true } : {}) },
|
|
207
|
+
isError: true,
|
|
208
|
+
});
|
|
209
|
+
|
|
210
|
+
const describe = (error: unknown): string => (error instanceof Error ? error.message : String(error));
|
|
211
|
+
|
|
212
|
+
export function registerEnte(pi: ExtensionAPI): void {
|
|
213
|
+
const listParams = Type.Object({});
|
|
214
|
+
const listTool: ToolDefinition<typeof listParams, { ok?: boolean; count?: number }> = {
|
|
215
|
+
name: "ente_list",
|
|
216
|
+
label: "Ente: list Auth codes",
|
|
217
|
+
description:
|
|
218
|
+
"List the entries saved in Ente Auth through the `ente` CLI: name, issuer, account name, type (totp/hotp/steam). " +
|
|
219
|
+
"NEVER returns codes or secrets. Use ente_code to read one; the user must approve a window first. " +
|
|
220
|
+
"Sessions come from `ente account login --app auth` (and optionally ENTE_CLI_VAULT_KEY), not from the master password of ai-vault.",
|
|
221
|
+
promptSnippet: "List Ente Auth entries (metadata only).",
|
|
222
|
+
parameters: listParams,
|
|
223
|
+
async execute(_id, _params, signal, _onUpdate, ctx) {
|
|
224
|
+
try {
|
|
225
|
+
const items = await listCodes(signal);
|
|
226
|
+
await auditEvent(`ente.list`, `count=${items.length}`, sessionLabelOf(ctx));
|
|
227
|
+
return {
|
|
228
|
+
content: [{ type: "text" as const, text: JSON.stringify(items, null, 1) }],
|
|
229
|
+
details: { count: items.length },
|
|
230
|
+
};
|
|
231
|
+
} catch (error) {
|
|
232
|
+
return fail(describe(error));
|
|
233
|
+
}
|
|
234
|
+
},
|
|
235
|
+
};
|
|
236
|
+
|
|
237
|
+
const codeParams = Type.Object({
|
|
238
|
+
name: Type.String({ description: "Entry name, or part of its name/issuer/account" }),
|
|
239
|
+
});
|
|
240
|
+
const codeTool: ToolDefinition<typeof codeParams, { ok?: boolean; denied?: boolean; item?: string }> = {
|
|
241
|
+
name: "ente_code",
|
|
242
|
+
label: "Ente: show a current code",
|
|
243
|
+
description:
|
|
244
|
+
"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. " +
|
|
245
|
+
"If the user denies, do not retry. Codes go into the conversation — prefer passing them on in the same turn.",
|
|
246
|
+
promptSnippet: "Read one current Ente Auth code after the user approves a window.",
|
|
247
|
+
parameters: codeParams,
|
|
248
|
+
async execute(_id, params, signal, _onUpdate, ctx) {
|
|
249
|
+
try {
|
|
250
|
+
const items = await listCodes(signal);
|
|
251
|
+
if (items.length === 0) return fail("Ente Auth has no saved codes on this device — run `ente account login --app auth` first.");
|
|
252
|
+
const item = resolveRef(items, params.name);
|
|
253
|
+
if (!item) {
|
|
254
|
+
const names = items.slice(0, 15).map((i) => `${i.name}${i.issuer ? ` (${i.issuer})` : ""}`);
|
|
255
|
+
return fail(`no single Ente entry matches "${params.name}". candidates: ${names.join(", ") || "(none)"}`);
|
|
256
|
+
}
|
|
257
|
+
const ok = await confirmWindow(
|
|
258
|
+
ctx as unknown as Parameters<typeof confirmWindow>[0],
|
|
259
|
+
"pi-ai-vault · Ente Auth 验证码",
|
|
260
|
+
`条目: ${item.name}\n签发方: ${item.issuer || "-"}\n账号: ${item.accountName || "-"}\n\n读取当前验证码?(会进入对话)`,
|
|
261
|
+
signal,
|
|
262
|
+
);
|
|
263
|
+
if (!ok) {
|
|
264
|
+
await auditEvent("ente.code", `deny item="${item.name}"`, sessionLabelOf(ctx));
|
|
265
|
+
return fail(`user denied reading the code for "${item.name}" — do not retry`, true);
|
|
266
|
+
}
|
|
267
|
+
const code = await viewCode(item.name, signal);
|
|
268
|
+
await auditEvent("ente.code", `allow item="${item.name}"`, sessionLabelOf(ctx));
|
|
269
|
+
return {
|
|
270
|
+
content: [
|
|
271
|
+
{
|
|
272
|
+
type: "text" as const,
|
|
273
|
+
text: JSON.stringify(
|
|
274
|
+
{ name: code.name, issuer: code.issuer, accountName: code.accountName, code: code.otp, validUntil: code.validUntil, via: "ente" },
|
|
275
|
+
null,
|
|
276
|
+
1,
|
|
277
|
+
),
|
|
278
|
+
},
|
|
279
|
+
],
|
|
280
|
+
details: { ok: true, item: code.name },
|
|
281
|
+
};
|
|
282
|
+
} catch (error) {
|
|
283
|
+
if (signal?.aborted) return fail("cancelled", true);
|
|
284
|
+
return fail(describe(error));
|
|
285
|
+
}
|
|
286
|
+
},
|
|
287
|
+
};
|
|
288
|
+
|
|
289
|
+
pi.registerTool(withTier(listTool, "read"));
|
|
290
|
+
pi.registerTool(withTier(codeTool, "write"));
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
/** Same shape as the Bitwarden audit lines: the session or subagent that asked. */
|
|
294
|
+
function sessionLabelOf(ctx: ExtensionContext | undefined): string {
|
|
295
|
+
const agent = (ctx as { agent?: { kind?: string; id?: string } } | undefined)?.agent;
|
|
296
|
+
if (agent?.kind === "sub" && agent.id) return agent.id.replace(/[^\w.-]/g, "").slice(0, 24);
|
|
297
|
+
let id = "";
|
|
298
|
+
try {
|
|
299
|
+
id = (ctx as { sessionManager?: { getSessionId?: () => string } } | undefined)?.sessionManager?.getSessionId?.() ?? "";
|
|
300
|
+
} catch {
|
|
301
|
+
/* a context without a session manager */
|
|
302
|
+
}
|
|
303
|
+
return id.replace(/-/g, "").slice(0, 8) || "main";
|
|
304
|
+
}
|
|
@@ -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";
|
|
@@ -635,7 +636,8 @@ const HELP = [
|
|
|
635
636
|
"/vault init 创建全机共享的本地加密库(弹出窗口设置主密码)",
|
|
636
637
|
"/vault unlock | lock 解锁 / 锁定(清空本会话的授权)",
|
|
637
638
|
"/vault mode [never|time|session] 查看/切换解锁模式(切换要主密码)",
|
|
638
|
-
"/vault settings [键 值] 查看/修改设置(vault.unlock、bitwarden
|
|
639
|
+
"/vault settings [键 值] 查看/修改设置(vault.unlock、bitwarden.*、ente.* …)",
|
|
640
|
+
"/vault ente-key 保存 ente 的 ENTE_CLI_VAULT_KEY(免钥匙串/免登录)",
|
|
639
641
|
"/vault status 状态与授权剩余时间",
|
|
640
642
|
"/vault list 本地条目元数据",
|
|
641
643
|
"/vault add [名称] 新增本地条目(用户名、密码在弹窗里输入)",
|
|
@@ -710,6 +712,9 @@ function settingsText(s: Settings): string {
|
|
|
710
712
|
`bitwarden.hours: ${s.bitwarden.hours}`,
|
|
711
713
|
`bitwarden.import: ${s.bitwarden.import} (ask | always | never)`,
|
|
712
714
|
`bitwarden 已落盘的会话: ${persisted}`,
|
|
715
|
+
`ente.unlock: ${s.ente.unlock} (never | time | session)`,
|
|
716
|
+
`ente.hours: ${s.ente.hours}`,
|
|
717
|
+
`ente 已落盘的密钥: ${s.ente.persisted ? "有" : "无"}`,
|
|
713
718
|
].join("\n");
|
|
714
719
|
}
|
|
715
720
|
|
|
@@ -781,6 +786,24 @@ function commandHandler(scope: Scope, bw: BwState) {
|
|
|
781
786
|
}
|
|
782
787
|
return;
|
|
783
788
|
}
|
|
789
|
+
case "ente-key": {
|
|
790
|
+
// Ente's unattended key: generated by `ente vault key generate`.
|
|
791
|
+
// Saved sealed, so `ente.unlock = never | time` can use it.
|
|
792
|
+
const key = await promptSecret(dialogs(ctx), "ai-vault · Ente 密钥", "ente vault key generate 输出的密钥");
|
|
793
|
+
if (!key) {
|
|
794
|
+
note(ctx, "已取消", "warning");
|
|
795
|
+
return;
|
|
796
|
+
}
|
|
797
|
+
try {
|
|
798
|
+
const args = ["ente-session", "put"];
|
|
799
|
+
await cli.run(args, { stdin: key });
|
|
800
|
+
forgetSettings();
|
|
801
|
+
note(ctx, "已保存(封存)。现在可以设置 /vault settings ente.unlock never");
|
|
802
|
+
} catch (error) {
|
|
803
|
+
note(ctx, `ai-vault: ${describe(error)}`, "error");
|
|
804
|
+
}
|
|
805
|
+
return;
|
|
806
|
+
}
|
|
784
807
|
case "settings": {
|
|
785
808
|
const [key, ...valueParts] = rest;
|
|
786
809
|
const value = valueParts.join(" ").trim();
|
|
@@ -1017,6 +1040,8 @@ export default function aiVault(pi: ExtensionAPI): void {
|
|
|
1017
1040
|
pi.registerTool(vaultAddTool(scope));
|
|
1018
1041
|
pi.registerTool(vaultImportTool(scope, bw));
|
|
1019
1042
|
registerBitwarden(pi, bw, omp);
|
|
1043
|
+
// Ente Auth: the `ente` CLI keeps its own login; these tools only read codes.
|
|
1044
|
+
registerEnte(pi);
|
|
1020
1045
|
pi.registerCommand("vault", {
|
|
1021
1046
|
description: "本地密码库 + Bitwarden 导入(/vault help)",
|
|
1022
1047
|
handler: commandHandler(scope, bw),
|
|
@@ -19,11 +19,14 @@ export interface Settings {
|
|
|
19
19
|
persisted: boolean;
|
|
20
20
|
expiresAt: number | null;
|
|
21
21
|
};
|
|
22
|
+
/** Ente's ENTE_CLI_VAULT_KEY: session leaves it to the OS keychain. */
|
|
23
|
+
ente: { unlock: UnlockModeName; hours: number; persisted: boolean; expiresAt: number | null };
|
|
22
24
|
}
|
|
23
25
|
|
|
24
26
|
export const DEFAULT_SETTINGS: Settings = {
|
|
25
27
|
vault: { unlock: "session", hours: 8, auto: false },
|
|
26
28
|
bitwarden: { unlock: "session", hours: 8, import: "ask", persisted: false, expiresAt: null },
|
|
29
|
+
ente: { unlock: "session", hours: 8, persisted: false, expiresAt: null },
|
|
27
30
|
};
|
|
28
31
|
|
|
29
32
|
const cli = new VaultCli();
|
package/test/cli.sh
CHANGED
|
@@ -155,6 +155,17 @@ check "without the wrap key the session does not open" 1 "$BIN" bw-session get
|
|
|
155
155
|
mv "$TMP/wrap.bak" "$AI_VAULT_DIR/.wrap"
|
|
156
156
|
"$BIN" settings bitwarden.unlock session --json >/dev/null
|
|
157
157
|
|
|
158
|
+
echo "== ente sealed key (M4 pattern) =="
|
|
159
|
+
check "ente.unlock is readable" 0 "$BIN" settings ente.unlock --json
|
|
160
|
+
check "ente-session put refused in session mode" 1 bash -c "printf 'K' | '$BIN' ente-session put"
|
|
161
|
+
check "switch ente.unlock to never" 0 "$BIN" settings ente.unlock never --json
|
|
162
|
+
check "store the Ente vault key" 0 bash -c "printf 'ENTE_KEY_PLAINTEXT' | '$BIN' ente-session put --json"
|
|
163
|
+
grep -q 'ENTE_KEY_PLAINTEXT' "$AI_VAULT_DIR/ente.session.json" && bad "the ente key is plaintext on disk" || ok "the ente key is sealed at rest"
|
|
164
|
+
[[ "$(stat -c %a "$AI_VAULT_DIR/ente.session.json")" == "600" ]] && ok "ente.session.json is 0600" || bad "ente.session.json is not 0600"
|
|
165
|
+
"$BIN" ente-session get --json | grep -q 'ENTE_KEY_PLAINTEXT' && ok "ente-session get unseals it" || bad "ente-session get cannot unseal"
|
|
166
|
+
"$BIN" settings ente.unlock session --json >/dev/null
|
|
167
|
+
check "switching back to session clears the ente key" 5 "$BIN" ente-session get
|
|
168
|
+
|
|
158
169
|
echo "== rekey (L2) =="
|
|
159
170
|
OLD_N=$(python3 -c "import json;print(json.load(open('$AI_VAULT_DIR/store.json'))['kdf']['N'])")
|
|
160
171
|
check "rekey with the password" 0 bash -c "printf 'correct horse' | '$BIN' rekey --password-stdin --json"
|
|
@@ -170,7 +181,7 @@ python3 - "$TMP/audit" <<'PY' && ok "the audit log records events without values
|
|
|
170
181
|
import json,sys
|
|
171
182
|
entries = json.load(open(sys.argv[1]))["entries"]
|
|
172
183
|
events = {e["event"] for e in entries}
|
|
173
|
-
for want in ("init", "unlock", "unlock_failed", "add", "grant", "read_deny", "read_allow", "remove", "import", "lock", "rekey", "
|
|
184
|
+
for want in ("init", "unlock", "unlock_failed", "add", "grant", "read_deny", "read_allow", "remove", "import", "lock", "rekey", "sealed"):
|
|
174
185
|
assert want in events, (want, events)
|
|
175
186
|
assert not any("p1ssw0rd" in json.dumps(e) or "exp-pass" in json.dumps(e) for e in entries)
|
|
176
187
|
PY
|
|
@@ -0,0 +1,137 @@
|
|
|
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 { spawnSync } from "node:child_process";
|
|
6
|
+
import { answers, bind, cleanUpOnExit, dialogTrace, makeCtx, textOf, useMocks } from "./helpers.mjs";
|
|
7
|
+
|
|
8
|
+
const { forgetSettings } = await import("../packages/pi-ai-vault/src/settings.ts");
|
|
9
|
+
|
|
10
|
+
const dir = useMocks();
|
|
11
|
+
const { default: aiVault } = await import("../packages/pi-ai-vault/src/index.ts");
|
|
12
|
+
cleanUpOnExit(dir);
|
|
13
|
+
|
|
14
|
+
const enteLog = () => {
|
|
15
|
+
try {
|
|
16
|
+
return readFileSync(join(dir, "ente.log"), "utf8");
|
|
17
|
+
} catch {
|
|
18
|
+
return "";
|
|
19
|
+
}
|
|
20
|
+
};
|
|
21
|
+
const codePrompts = () => dialogTrace(dir).split("\n").filter((line) => line.includes("Ente Auth")).length;
|
|
22
|
+
|
|
23
|
+
test("ente_list returns metadata and never touches a code", async () => {
|
|
24
|
+
const b = bind(aiVault, true);
|
|
25
|
+
const result = await b.tool("ente_list", {}, makeCtx().ctx);
|
|
26
|
+
assert.equal(result.isError, undefined);
|
|
27
|
+
const items = JSON.parse(textOf(result));
|
|
28
|
+
assert.deepEqual(items.map((i) => i.name), ["GitHub", "Cloudflare", "Steam"]);
|
|
29
|
+
assert.equal(items[0].otp, undefined, "listing must not leak a code");
|
|
30
|
+
assert.equal(/auth code view/.test(enteLog()), false, "listing must not run a code view");
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
test("ente_code asks a window naming the entry, then returns the code", async () => {
|
|
34
|
+
const b = bind(aiVault, true);
|
|
35
|
+
const ctx = makeCtx().ctx;
|
|
36
|
+
const before = codePrompts();
|
|
37
|
+
answers.questions(dir, "y");
|
|
38
|
+
const result = await b.tool("ente_code", { name: "github" }, ctx);
|
|
39
|
+
const body = JSON.parse(textOf(result));
|
|
40
|
+
assert.equal(result.details.via ?? body.via, "ente");
|
|
41
|
+
assert.equal(body.code, "00420731", "leading zeroes survive");
|
|
42
|
+
assert.match(dialogTrace(dir), /GitHub/);
|
|
43
|
+
assert.equal(codePrompts(), before + 1);
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
test("ente_code denial is reported and not retried", async () => {
|
|
47
|
+
const b = bind(aiVault, true);
|
|
48
|
+
answers.questions(dir, "n");
|
|
49
|
+
const result = await b.tool("ente_code", { name: "Cloudflare" }, makeCtx().ctx);
|
|
50
|
+
assert.equal(result.isError, true);
|
|
51
|
+
assert.equal(result.details.denied, true);
|
|
52
|
+
assert.match(textOf(result), /do not retry/);
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
test("ente_code reports the candidates when the name matches more than one", async () => {
|
|
56
|
+
const b = bind(aiVault, true);
|
|
57
|
+
answers.questions(dir, "y");
|
|
58
|
+
const result = await b.tool("ente_code", { name: "example.com" }, makeCtx().ctx);
|
|
59
|
+
// "example.com" is part of two account names, so no single entry is chosen.
|
|
60
|
+
assert.equal(result.isError, true);
|
|
61
|
+
assert.match(textOf(result), /no single Ente entry matches/);
|
|
62
|
+
assert.match(textOf(result), /Cloudflare/);
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
test("ente tools say what to do when the CLI has no account", async () => {
|
|
66
|
+
writeFileSync(join(dir, "unauthenticated"), "");
|
|
67
|
+
writeFileSync(join(dir, "no-cache"), "");
|
|
68
|
+
const b = bind(aiVault, true);
|
|
69
|
+
const result = await b.tool("ente_list", {}, makeCtx().ctx);
|
|
70
|
+
assert.equal(result.isError, true, textOf(result));
|
|
71
|
+
assert.match(textOf(result), /ente account login|no account/i);
|
|
72
|
+
rmSync(join(dir, "unauthenticated"), { force: true });
|
|
73
|
+
rmSync(join(dir, "no-cache"), { force: true });
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
test("a secrets audit line exists for allow and deny, without the code", async () => {
|
|
77
|
+
const log = readFileSync(join(process.env.HOME, ".bw", "pi-extension", "audit.log"), "utf8");
|
|
78
|
+
assert.match(log, /ente\.code session=\S+ allow item="GitHub"/);
|
|
79
|
+
assert.match(log, /ente\.code session=\S+ deny item="Cloudflare"/);
|
|
80
|
+
assert.equal(log.includes("00420731"), false, "the audit log must not carry the code");
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
test("a failed sync falls back to the offline cache", async () => {
|
|
84
|
+
writeFileSync(join(dir, "list-fails-once"), "");
|
|
85
|
+
const b = bind(aiVault, true);
|
|
86
|
+
const result = await b.tool("ente_list", {}, makeCtx().ctx);
|
|
87
|
+
assert.equal(result.isError, undefined, textOf(result));
|
|
88
|
+
assert.equal(JSON.parse(textOf(result)).length, 3);
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
const enteEnv = () => {
|
|
92
|
+
try {
|
|
93
|
+
return readFileSync(join(dir, "ente.env"), "utf8").trim();
|
|
94
|
+
} catch {
|
|
95
|
+
return "";
|
|
96
|
+
}
|
|
97
|
+
};
|
|
98
|
+
|
|
99
|
+
test("session mode passes no vault key: the OS keychain stays in charge", async () => {
|
|
100
|
+
const bin = process.env.AI_VAULT_BIN;
|
|
101
|
+
spawnSync(bin, ["settings", "ente.unlock", "session"], { env: process.env });
|
|
102
|
+
forgetSettings();
|
|
103
|
+
const b = bind(aiVault, true);
|
|
104
|
+
await b.tool("ente_list", {}, makeCtx().ctx);
|
|
105
|
+
assert.match(enteEnv(), /^key=$/m);
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
test("ente.unlock=never feeds the sealed key to the ente child", async () => {
|
|
109
|
+
const bin = process.env.AI_VAULT_BIN;
|
|
110
|
+
const set = spawnSync(bin, ["settings", "ente.unlock", "never"], { env: process.env, encoding: "utf8" });
|
|
111
|
+
assert.equal(set.status, 0, set.stderr);
|
|
112
|
+
const put = spawnSync(bin, ["ente-session", "put"], { input: "MY_SECRET_VAULT_KEY", env: process.env, encoding: "utf8" });
|
|
113
|
+
assert.equal(put.status, 0, put.stderr);
|
|
114
|
+
forgetSettings();
|
|
115
|
+
|
|
116
|
+
const b = bind(aiVault, true);
|
|
117
|
+
const result = await b.tool("ente_list", {}, makeCtx().ctx);
|
|
118
|
+
assert.equal(result.isError, undefined, textOf(result));
|
|
119
|
+
assert.match(enteEnv(), /^key=MY_SECRET_VAULT_KEY$/m);
|
|
120
|
+
});
|
|
121
|
+
|
|
122
|
+
test("an inherited ENTE_CLI_VAULT_KEY is not trusted in session mode", async () => {
|
|
123
|
+
const bin = process.env.AI_VAULT_BIN;
|
|
124
|
+
spawnSync(bin, ["settings", "ente.unlock", "session"], { env: process.env });
|
|
125
|
+
spawnSync(bin, ["ente-session", "clear"], { env: process.env });
|
|
126
|
+
forgetSettings();
|
|
127
|
+
const previous = process.env.ENTE_CLI_VAULT_KEY;
|
|
128
|
+
process.env.ENTE_CLI_VAULT_KEY = "LEAKED_FROM_SHELL";
|
|
129
|
+
try {
|
|
130
|
+
const b = bind(aiVault, true);
|
|
131
|
+
await b.tool("ente_list", {}, makeCtx().ctx);
|
|
132
|
+
assert.match(enteEnv(), /^key=$/m, "the shell-exported key must not reach ente");
|
|
133
|
+
} finally {
|
|
134
|
+
if (previous === undefined) delete process.env.ENTE_CLI_VAULT_KEY;
|
|
135
|
+
else process.env.ENTE_CLI_VAULT_KEY = previous;
|
|
136
|
+
}
|
|
137
|
+
});
|
package/tests/helpers.mjs
CHANGED
|
@@ -36,8 +36,13 @@ 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();
|
|
43
|
+
// The extension resolves the CLI from PATH; the tests pass one explicitly.
|
|
44
|
+
// Put the same build first so both halves run the same version.
|
|
45
|
+
process.env.PATH = `${dirname(process.env.AI_VAULT_BIN)}:${process.env.PATH}`;
|
|
41
46
|
return dir;
|
|
42
47
|
}
|
|
43
48
|
|
|
@@ -0,0 +1,68 @@
|
|
|
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
|
+
# Record whether a vault key reached us and which, so tests can tell a
|
|
13
|
+
# keychain-backed run (nothing) from a sealed-key run (a value).
|
|
14
|
+
printf '%s\n' "$*" >>"$DIR/ente.log"
|
|
15
|
+
if [[ -n "${ENTE_CLI_VAULT_KEY:-}" ]]; then
|
|
16
|
+
printf 'key=%s\n' "$ENTE_CLI_VAULT_KEY" >>"$DIR/ente.env"
|
|
17
|
+
else
|
|
18
|
+
printf 'key=\n' >>"$DIR/ente.env"
|
|
19
|
+
fi
|
|
20
|
+
if [[ -f "$DIR/unauthenticated" ]]; then
|
|
21
|
+
echo "no account logged in; run ente account login --app auth" >&2
|
|
22
|
+
exit 3
|
|
23
|
+
fi
|
|
24
|
+
# --offline still needs a synced database: same failure when nothing was ever
|
|
25
|
+
# logged in, which is what the tool must report to the user.
|
|
26
|
+
if [[ -f "$DIR/no-cache" ]]; then
|
|
27
|
+
echo "nothing has been synced yet" >&2
|
|
28
|
+
exit 4
|
|
29
|
+
fi
|
|
30
|
+
|
|
31
|
+
# Drop the global flags we do not care about, keep the subcommand path.
|
|
32
|
+
args=()
|
|
33
|
+
for a in "$@"; do
|
|
34
|
+
case "$a" in
|
|
35
|
+
--json|--no-input|--offline) ;;
|
|
36
|
+
*) args+=("$a") ;;
|
|
37
|
+
esac
|
|
38
|
+
done
|
|
39
|
+
joined="${args[*]}"
|
|
40
|
+
|
|
41
|
+
case "$joined" in
|
|
42
|
+
"auth code list")
|
|
43
|
+
if [[ -f "$DIR/list-fails-once" ]]; then
|
|
44
|
+
rm -f "$DIR/list-fails-once"
|
|
45
|
+
echo "sync needed" >&2
|
|
46
|
+
exit 1
|
|
47
|
+
fi
|
|
48
|
+
cat <<'JSON'
|
|
49
|
+
[{"id":"c1","name":"GitHub","issuer":"github.com","accountName":"octo@example.com","type":"totp"},
|
|
50
|
+
{"id":"c2","name":"Cloudflare","issuer":"Cloudflare","accountName":"ops@example.com","type":"totp"},
|
|
51
|
+
{"id":"c3","name":"Steam","issuer":"Steam","accountName":"gamer","type":"steam"}]
|
|
52
|
+
JSON
|
|
53
|
+
;;
|
|
54
|
+
"auth code view GitHub")
|
|
55
|
+
echo '{"id":"c1","name":"GitHub","issuer":"github.com","accountName":"octo@example.com","type":"totp","otp":"00420731","validUntil":"2030-01-01T00:00:30Z"}'
|
|
56
|
+
;;
|
|
57
|
+
"auth code view "*)
|
|
58
|
+
echo "no saved code matches that entry" >&2
|
|
59
|
+
exit 1
|
|
60
|
+
;;
|
|
61
|
+
"account list")
|
|
62
|
+
echo '[{"name":"default","email":"t@example.com","apps":["auth"]}]'
|
|
63
|
+
;;
|
|
64
|
+
*)
|
|
65
|
+
echo "mock ente: unhandled: $joined" >&2
|
|
66
|
+
exit 2
|
|
67
|
+
;;
|
|
68
|
+
esac
|
package/tests/register.test.mjs
CHANGED
|
@@ -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
|
|
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);
|