pi-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.
- package/README.md +10 -0
- package/package.json +2 -2
- package/src/bitwarden.ts +12 -9
- package/src/cli.ts +58 -1
- package/src/ente.ts +278 -0
- package/src/index.ts +31 -15
- package/src/prompt.ts +13 -0
package/README.md
CHANGED
|
@@ -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,14 @@ 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
|
+
|
|
70
|
+
## 安全边界(一句话版)
|
|
71
|
+
|
|
72
|
+
模型的 `bash` 能找到会话令牌、能 `list`,但**签不出读取确认**(签名密钥只在插件进程内存里)、**改不了令牌文件**(带 HMAC,改了就作废)、**免费拿不到 `grant`**(要主密码)。详见仓库 README「安全」一节。
|
|
73
|
+
|
|
64
74
|
## 隔离
|
|
65
75
|
|
|
66
76
|
每个会话、每个子代理各自 `ai-vault unlock`,拿自己的令牌和读授权;父会话的解锁子代理继承不到。空闲 10 分钟自动失效,`/new`、`/fork`、退出会清掉本绑定的令牌。
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-ai-vault",
|
|
3
|
-
"version": "0.
|
|
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.
|
|
28
|
+
"@xiaolikt/ai-vault": "0.8.0"
|
|
29
29
|
},
|
|
30
30
|
"peerDependencies": {
|
|
31
31
|
"@earendil-works/pi-coding-agent": "^1.5.0",
|
package/src/bitwarden.ts
CHANGED
|
@@ -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
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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 },
|
package/src/cli.ts
CHANGED
|
@@ -7,6 +7,7 @@
|
|
|
7
7
|
* windows; a headless machine answers exit code 3 ("needs-ui") and the host
|
|
8
8
|
* dialog takes over here.
|
|
9
9
|
*/
|
|
10
|
+
import { createHmac, randomBytes } from "node:crypto";
|
|
10
11
|
import { spawn } from "node:child_process";
|
|
11
12
|
import { existsSync } from "node:fs";
|
|
12
13
|
import { homedir } from "node:os";
|
|
@@ -91,8 +92,54 @@ function message(stderr: string, fallback: string): string {
|
|
|
91
92
|
return lines[0]?.replace(/^ai-vault:\s*/, "") ?? fallback;
|
|
92
93
|
}
|
|
93
94
|
|
|
95
|
+
/**
|
|
96
|
+
* The secret this process keeps for the sessions it unlocked. It never reaches
|
|
97
|
+
* disk: the CLI writes it into the HMAC on each session file, and uses it to
|
|
98
|
+
* check the approvals we relay. A model-driven `bash` that finds a session
|
|
99
|
+
* token can therefore `list`, but can neither forge a read approval nor edit
|
|
100
|
+
* the token's grants.
|
|
101
|
+
*/
|
|
102
|
+
export class HostSecret {
|
|
103
|
+
#value: string | undefined;
|
|
104
|
+
|
|
105
|
+
get present(): boolean {
|
|
106
|
+
return this.#value !== undefined;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** Use the one the CLI echoed back at unlock time (it is ours already). */
|
|
110
|
+
adopt(secret: string | undefined): void {
|
|
111
|
+
if (secret && secret.length >= 32) this.#value = secret;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** 32 fresh bytes, hex — minted once per process, before the first unlock. */
|
|
115
|
+
rotate(): string {
|
|
116
|
+
this.#value = randomBytes(32).toString("hex");
|
|
117
|
+
return this.#value;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** The secret, minting it on first use. */
|
|
121
|
+
get value(): string {
|
|
122
|
+
return (this.#value ??= randomBytes(32).toString("hex"));
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** Environment for a CLI child: marks us as the host and passes the secret. */
|
|
126
|
+
env(): Record<string, string> {
|
|
127
|
+
return { AI_VAULT_HOST: "1", AI_VAULT_HOST_SECRET: this.value };
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** HMAC over "allow:<token>:<entry>:<y|n>", what `get --answer-stdin` expects. */
|
|
131
|
+
approve(token: string, entry: string, answer: boolean): string | undefined {
|
|
132
|
+
if (!this.#value) return undefined;
|
|
133
|
+
return createHmac("sha256", this.#value)
|
|
134
|
+
.update(`allow:${token}:${entry.toLowerCase()}:${answer ? "y" : "n"}`)
|
|
135
|
+
.digest("hex");
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
94
139
|
export class VaultCli {
|
|
95
140
|
readonly bin = resolveBinary();
|
|
141
|
+
/** Set by the extension at startup; the same secret for every binding. */
|
|
142
|
+
host = new HostSecret();
|
|
96
143
|
|
|
97
144
|
get available(): boolean {
|
|
98
145
|
return this.bin !== undefined;
|
|
@@ -112,7 +159,7 @@ export class VaultCli {
|
|
|
112
159
|
throw new CliError(EXIT.denied, undefined, "aborted", "");
|
|
113
160
|
}
|
|
114
161
|
const run = await new Promise<CliRun>((resolve, reject) => {
|
|
115
|
-
const child = spawn(bin, args, { stdio: ["pipe", "pipe", "pipe"] });
|
|
162
|
+
const child = spawn(bin, args, { stdio: ["pipe", "pipe", "pipe"], env: { ...process.env, ...this.host.env() } });
|
|
116
163
|
let stdout = "";
|
|
117
164
|
let stderr = "";
|
|
118
165
|
const onAbort = () => child.kill("SIGKILL");
|
|
@@ -143,6 +190,16 @@ export class VaultCli {
|
|
|
143
190
|
return run;
|
|
144
191
|
}
|
|
145
192
|
|
|
193
|
+
/**
|
|
194
|
+
* `init` or `unlock`: returns the parsed result with the token, and keeps
|
|
195
|
+
* the host secret the CLI minted (or used ours) for later signing.
|
|
196
|
+
*/
|
|
197
|
+
async open<T extends { hostSecret?: string }>(subcommand: "init" | "unlock", args: string[], opts: { stdin?: string; signal?: AbortSignal } = {}): Promise<T> {
|
|
198
|
+
const result = await this.json<T>([subcommand, ...args], opts);
|
|
199
|
+
this.host.adopt(result.hostSecret);
|
|
200
|
+
return result;
|
|
201
|
+
}
|
|
202
|
+
|
|
146
203
|
/** One CLI call whose output is a JSON object. */
|
|
147
204
|
async json<T>(args: string[], opts: { stdin?: string; signal?: AbortSignal } = {}): Promise<T> {
|
|
148
205
|
const run = await this.run([...args, "--json"], opts);
|
package/src/ente.ts
ADDED
|
@@ -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
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -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 = ["
|
|
206
|
+
const args = ["--requester", sessionLabel(ctx)];
|
|
204
207
|
if (password !== undefined) args.push("--password-stdin");
|
|
205
|
-
return cli.
|
|
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
|
-
|
|
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
|
|
536
|
-
req.uri?.trim() ? `URI: ${req.uri
|
|
537
|
-
req.notes?.trim() ? `备注: ${req.notes
|
|
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.
|
|
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.
|
|
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
|
-
|
|
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),
|
package/src/prompt.ts
CHANGED
|
@@ -105,6 +105,19 @@ function failedToOpen(result: ZenityResult): boolean {
|
|
|
105
105
|
return result.stderr.split(/\r?\n/).some((line) => line.trim() !== "" && !gtkDiagnostic.test(line));
|
|
106
106
|
}
|
|
107
107
|
|
|
108
|
+
/**
|
|
109
|
+
* Make a model-supplied value safe to put in a confirm window.
|
|
110
|
+
*
|
|
111
|
+
* The window is the one place the user reads what they are approving, so an
|
|
112
|
+
* entry name or reason that carries newlines could otherwise forge a whole
|
|
113
|
+
* second message ("请求方: 主会话 / 已授权, 点允许"). One line, bounded
|
|
114
|
+
* length, control characters gone.
|
|
115
|
+
*/
|
|
116
|
+
export function forDialog(value: string, max = 80): string {
|
|
117
|
+
const oneLine = value.replace(/[\u0000-\u001f\u007f\u2028\u2029]+/g, " ").replace(/\s+/g, " ").trim();
|
|
118
|
+
return oneLine.length > max ? `${oneLine.slice(0, max - 1)}…` : oneLine;
|
|
119
|
+
}
|
|
120
|
+
|
|
108
121
|
/** Secret entry. Empty and cancel are both "no value". */
|
|
109
122
|
export async function promptSecret(
|
|
110
123
|
ctx: PromptHost | undefined,
|