@xiaolikt/ai-vault 0.5.0 → 0.7.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 +2 -1
- package/README.md +73 -11
- package/crates/ai-vault/Cargo.toml +2 -1
- package/crates/ai-vault/src/bwsession.rs +163 -0
- package/crates/ai-vault/src/cli.rs +380 -75
- package/crates/ai-vault/src/config.rs +99 -5
- package/crates/ai-vault/src/crypto.rs +34 -8
- package/crates/ai-vault/src/dialog.rs +45 -0
- package/crates/ai-vault/src/main.rs +1 -0
- package/crates/ai-vault/src/paths.rs +12 -0
- package/crates/ai-vault/src/session.rs +82 -13
- package/package.json +2 -2
- package/packages/pi-ai-vault/README.md +13 -1
- package/packages/pi-ai-vault/package.json +2 -2
- package/packages/pi-ai-vault/src/bitwarden.ts +30 -0
- package/packages/pi-ai-vault/src/cli.ts +58 -1
- package/packages/pi-ai-vault/src/index.ts +111 -54
- package/packages/pi-ai-vault/src/prompt.ts +13 -0
- package/packages/pi-ai-vault/src/settings.ts +59 -0
- package/test/cli.sh +106 -5
- package/tests/prompt.test.mjs +12 -0
- package/tests/vault-cli.test.mjs +98 -0
|
@@ -24,7 +24,8 @@ import {
|
|
|
24
24
|
} from "./bitwarden.js";
|
|
25
25
|
import { CliError, VaultCli } from "./cli.js";
|
|
26
26
|
import { isOmpHost, onSessionLeave, sessionLabel, subagentId, withTier } from "./host.js";
|
|
27
|
-
import { confirmWindow, promptSecret, promptText, type PromptHost } from "./prompt.js";
|
|
27
|
+
import { confirmWindow, forDialog, promptSecret, promptText, type PromptHost } from "./prompt.js";
|
|
28
|
+
import { forgetSettings, getSettingsSafe, type Settings } from "./settings.js";
|
|
28
29
|
|
|
29
30
|
type Ctx = ExtensionToolContext | ExtensionCommandContext;
|
|
30
31
|
|
|
@@ -52,6 +53,8 @@ interface UnlockResult {
|
|
|
52
53
|
items: number;
|
|
53
54
|
mode?: UnlockModeName;
|
|
54
55
|
auto?: boolean;
|
|
56
|
+
/** Minted by the CLI for a host; kept in memory only, signs approvals. */
|
|
57
|
+
hostSecret?: string;
|
|
55
58
|
}
|
|
56
59
|
|
|
57
60
|
interface ListResult {
|
|
@@ -199,9 +202,9 @@ async function ensureUnlocked(scope: Scope, ctx: Ctx, signal?: AbortSignal): Pro
|
|
|
199
202
|
}
|
|
200
203
|
}
|
|
201
204
|
const attempt = async (password?: string): Promise<UnlockResult> => {
|
|
202
|
-
const args = ["
|
|
205
|
+
const args = ["--requester", sessionLabel(ctx)];
|
|
203
206
|
if (password !== undefined) args.push("--password-stdin");
|
|
204
|
-
return cli.
|
|
207
|
+
return cli.open<UnlockResult>("unlock", args, {
|
|
205
208
|
stdin: password === undefined ? undefined : `${password}\n`,
|
|
206
209
|
signal,
|
|
207
210
|
});
|
|
@@ -309,22 +312,21 @@ async function bitwardenFallback(
|
|
|
309
312
|
}
|
|
310
313
|
if (!hit) return fail(`${missing} — not in Bitwarden either${reason ? ` (reason: ${reason})` : ""}`);
|
|
311
314
|
|
|
312
|
-
const
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
315
|
+
const asValue = (via: string): ToolOutcome => ({
|
|
316
|
+
content: [
|
|
317
|
+
{
|
|
318
|
+
type: "text" as const,
|
|
319
|
+
text: JSON.stringify(
|
|
320
|
+
{ name: hit.name, username: hit.username || undefined, password: hit.password, uris: hit.uris, via },
|
|
321
|
+
null,
|
|
322
|
+
1,
|
|
323
|
+
),
|
|
324
|
+
},
|
|
325
|
+
],
|
|
326
|
+
details: { item: hit.name, via },
|
|
327
|
+
});
|
|
320
328
|
|
|
321
|
-
const importIt =
|
|
322
|
-
dialogs(ctx),
|
|
323
|
-
"pi-ai-vault · 导入到 ai-vault",
|
|
324
|
-
`把「${hit.name}」写进 ai-vault 吗?\n\n允许 → 以后直接读本地库(按当前解锁模式,可能免密)\n拒绝 → 只用这一次,不写入本地库`,
|
|
325
|
-
signal,
|
|
326
|
-
);
|
|
327
|
-
if (importIt) {
|
|
329
|
+
const importIt = async (): Promise<ToolOutcome> => {
|
|
328
330
|
try {
|
|
329
331
|
const saved = await cli.json<SaveResult>(["save", "--yes", ...tokenArgs(scope)], {
|
|
330
332
|
stdin: JSON.stringify([
|
|
@@ -343,34 +345,32 @@ async function bitwardenFallback(
|
|
|
343
345
|
} catch (error) {
|
|
344
346
|
return fail(`found "${hit.name}" in Bitwarden but could not import it: ${describe(error)}`);
|
|
345
347
|
}
|
|
346
|
-
return
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
1,
|
|
354
|
-
),
|
|
355
|
-
},
|
|
356
|
-
],
|
|
357
|
-
details: { item: hit.name, via: "imported-from-bitwarden" },
|
|
358
|
-
};
|
|
348
|
+
return asValue("imported-from-bitwarden");
|
|
349
|
+
};
|
|
350
|
+
|
|
351
|
+
const policy = (await getSettingsSafe(signal)).bitwarden.import;
|
|
352
|
+
if (policy === "always") {
|
|
353
|
+
// bitwarden.import = always: the user opted into pulling hits in silently.
|
|
354
|
+
return importIt();
|
|
359
355
|
}
|
|
360
356
|
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
357
|
+
const label = `${hit.name}${hit.username ? ` user:${hit.username}` : ""}`;
|
|
358
|
+
const allow = await confirmWindow(
|
|
359
|
+
dialogs(ctx),
|
|
360
|
+
"pi-ai-vault · Bitwarden 里找到",
|
|
361
|
+
`本地库没有「${forDialog(name)}」,Bitwarden 里有:\n${forDialog(label)}\n\n读取这一次吗?`,
|
|
362
|
+
signal,
|
|
363
|
+
);
|
|
364
|
+
if (!allow) return fail(`user denied reading "${hit.name}" from Bitwarden — do not retry`, true);
|
|
365
|
+
if (policy === "never") return asValue("bitwarden-once");
|
|
366
|
+
|
|
367
|
+
const confirmed = await confirmWindow(
|
|
368
|
+
dialogs(ctx),
|
|
369
|
+
"pi-ai-vault · 导入到 ai-vault",
|
|
370
|
+
`把「${forDialog(hit.name)}」写进 ai-vault 吗?\n\n允许 → 以后直接读本地库(按当前解锁模式,可能免密)\n拒绝 → 只用这一次,不写入本地库`,
|
|
371
|
+
signal,
|
|
372
|
+
);
|
|
373
|
+
return confirmed ? importIt() : asValue("bitwarden-once");
|
|
374
374
|
}
|
|
375
375
|
|
|
376
376
|
function vaultGetTool(scope: Scope, bw: BwState): ToolDefinition<typeof vaultGetParams, VaultGetDetails> {
|
|
@@ -407,11 +407,18 @@ function vaultGetTool(scope: Scope, bw: BwState): ToolDefinition<typeof vaultGet
|
|
|
407
407
|
const allowed = await confirmWindow(
|
|
408
408
|
dialogs(ctx),
|
|
409
409
|
"ai-vault · 读取本地密码",
|
|
410
|
-
`条目: ${params.name}\n请求方: ${sub ? `子代理 ${sub}` : "主会话"}\n原因: ${params.reason ?? "(未说明)"}\n\n` +
|
|
410
|
+
`条目: ${forDialog(params.name)}\n请求方: ${sub ? `子代理 ${forDialog(sub, 32)}` : "主会话"}\n原因: ${forDialog(params.reason ?? "(未说明)", 120)}\n\n` +
|
|
411
411
|
"允许后 5 分钟内同一请求方可再次读取。密码会进入对话。",
|
|
412
412
|
signal,
|
|
413
413
|
);
|
|
414
|
-
|
|
414
|
+
// Relaying is our privilege as the host: sign the answer under the
|
|
415
|
+
// host secret so the CLI can tell us from the model's own bash.
|
|
416
|
+
const token = scope.token ?? "";
|
|
417
|
+
const approval = cli.host.approve(token, params.name, allowed);
|
|
418
|
+
if (!approval) {
|
|
419
|
+
return fail("cannot relay an approval: no host secret for this session — run /vault unlock again");
|
|
420
|
+
}
|
|
421
|
+
const run = await cli.run([...base, "--json", "--answer-stdin", "--approval", approval], {
|
|
415
422
|
stdin: allowed ? "y\n" : "n\n",
|
|
416
423
|
signal,
|
|
417
424
|
});
|
|
@@ -534,16 +541,16 @@ async function saveLocalEntry(scope: Scope, ctx: Ctx, req: SaveRequest): Promise
|
|
|
534
541
|
}
|
|
535
542
|
if (error.needsUi === "confirm") {
|
|
536
543
|
const meta = [
|
|
537
|
-
req.username?.trim() ? `用户名: ${req.username
|
|
538
|
-
req.uri?.trim() ? `URI: ${req.uri
|
|
539
|
-
req.notes?.trim() ? `备注: ${req.notes
|
|
544
|
+
req.username?.trim() ? `用户名: ${forDialog(req.username, 60)}` : "",
|
|
545
|
+
req.uri?.trim() ? `URI: ${forDialog(req.uri, 120)}` : "",
|
|
546
|
+
req.notes?.trim() ? `备注: ${forDialog(req.notes, 120)}` : "",
|
|
540
547
|
]
|
|
541
548
|
.filter(Boolean)
|
|
542
549
|
.join("\n");
|
|
543
550
|
const ok = await confirmWindow(
|
|
544
551
|
dialogs(ctx),
|
|
545
552
|
"ai-vault · 保存到本地库",
|
|
546
|
-
`保存条目「${name}」。${meta ? `\n${meta}` : ""}\n下一步会弹出窗口,由你输入密码。密码不会进入对话。`,
|
|
553
|
+
`保存条目「${forDialog(name)}」。${meta ? `\n${meta}` : ""}\n下一步会弹出窗口,由你输入密码。密码不会进入对话。`,
|
|
547
554
|
req.signal,
|
|
548
555
|
);
|
|
549
556
|
if (!ok) return `user denied saving "${name}"`;
|
|
@@ -628,6 +635,7 @@ const HELP = [
|
|
|
628
635
|
"/vault init 创建全机共享的本地加密库(弹出窗口设置主密码)",
|
|
629
636
|
"/vault unlock | lock 解锁 / 锁定(清空本会话的授权)",
|
|
630
637
|
"/vault mode [never|time|session] 查看/切换解锁模式(切换要主密码)",
|
|
638
|
+
"/vault settings [键 值] 查看/修改设置(vault.unlock、bitwarden.unlock、bitwarden.import …)",
|
|
631
639
|
"/vault status 状态与授权剩余时间",
|
|
632
640
|
"/vault list 本地条目元数据",
|
|
633
641
|
"/vault add [名称] 新增本地条目(用户名、密码在弹窗里输入)",
|
|
@@ -659,7 +667,7 @@ async function initStore(scope: Scope, ctx: Ctx, label: string): Promise<void> {
|
|
|
659
667
|
note(ctx, `ai-vault 已创建: ${cli.dir}/store.json`);
|
|
660
668
|
};
|
|
661
669
|
try {
|
|
662
|
-
finish(await cli.
|
|
670
|
+
finish(await cli.open<UnlockResult>("init", ["--requester", label]));
|
|
663
671
|
return;
|
|
664
672
|
} catch (error) {
|
|
665
673
|
if (!(error instanceof CliError)) {
|
|
@@ -682,12 +690,29 @@ async function initStore(scope: Scope, ctx: Ctx, label: string): Promise<void> {
|
|
|
682
690
|
return;
|
|
683
691
|
}
|
|
684
692
|
try {
|
|
685
|
-
finish(await cli.
|
|
693
|
+
finish(await cli.open<UnlockResult>("init", ["--requester", label, "--password-stdin"], { stdin: `${pass}\n` }));
|
|
686
694
|
} catch (error) {
|
|
687
695
|
note(ctx, `ai-vault: ${error instanceof CliError ? error.message : describe(error)}`, "error");
|
|
688
696
|
}
|
|
689
697
|
}
|
|
690
698
|
|
|
699
|
+
function settingsText(s: Settings): string {
|
|
700
|
+
const persisted = s.bitwarden.persisted
|
|
701
|
+
? s.bitwarden.expiresAt
|
|
702
|
+
? `有(${Math.max(0, Math.round((s.bitwarden.expiresAt - Date.now()) / 60_000))} 分钟后过期)`
|
|
703
|
+
: "有(不过期)"
|
|
704
|
+
: "无";
|
|
705
|
+
return [
|
|
706
|
+
`vault.unlock: ${s.vault.unlock} (never | time | session)`,
|
|
707
|
+
`vault.hours: ${s.vault.hours} (time 模式用)`,
|
|
708
|
+
`vault 机器级会话: ${s.vault.auto ? "有(免密)" : "无"}`,
|
|
709
|
+
`bitwarden.unlock: ${s.bitwarden.unlock} (never | time | session)`,
|
|
710
|
+
`bitwarden.hours: ${s.bitwarden.hours}`,
|
|
711
|
+
`bitwarden.import: ${s.bitwarden.import} (ask | always | never)`,
|
|
712
|
+
`bitwarden 已落盘的会话: ${persisted}`,
|
|
713
|
+
].join("\n");
|
|
714
|
+
}
|
|
715
|
+
|
|
691
716
|
function commandHandler(scope: Scope, bw: BwState) {
|
|
692
717
|
return async (args: string, ctx: ExtensionCommandContext): Promise<void> => {
|
|
693
718
|
const [sub = "status", ...rest] = words(args);
|
|
@@ -756,6 +781,33 @@ function commandHandler(scope: Scope, bw: BwState) {
|
|
|
756
781
|
}
|
|
757
782
|
return;
|
|
758
783
|
}
|
|
784
|
+
case "settings": {
|
|
785
|
+
const [key, ...valueParts] = rest;
|
|
786
|
+
const value = valueParts.join(" ").trim();
|
|
787
|
+
try {
|
|
788
|
+
if (!key) {
|
|
789
|
+
note(ctx, settingsText(await cli.json<Settings>(["settings"])));
|
|
790
|
+
return;
|
|
791
|
+
}
|
|
792
|
+
if (!value) {
|
|
793
|
+
const one = await cli.json<{ key: string; value: string }>(["settings", key]);
|
|
794
|
+
note(ctx, `${one.key}: ${one.value}`);
|
|
795
|
+
return;
|
|
796
|
+
}
|
|
797
|
+
// `vault.unlock` opens its own password window (or answers
|
|
798
|
+
// needs-ui); the other keys do not prompt at all.
|
|
799
|
+
const run = await cli.withPassword(["settings", key, value], () =>
|
|
800
|
+
promptSecret(dialogs(ctx), "ai-vault · 主密码", "改变解锁模式需要验证"),
|
|
801
|
+
);
|
|
802
|
+
forgetSettings();
|
|
803
|
+
const updated = JSON.parse(run.stdout) as Settings;
|
|
804
|
+
if (key.startsWith("vault.")) await lockNow(scope);
|
|
805
|
+
note(ctx, settingsText(updated));
|
|
806
|
+
} catch (error) {
|
|
807
|
+
note(ctx, `ai-vault: ${error instanceof CliError && error.denied ? "已取消" : describe(error)}`, "warning");
|
|
808
|
+
}
|
|
809
|
+
return;
|
|
810
|
+
}
|
|
759
811
|
case "mode": {
|
|
760
812
|
const [sub, hoursArg] = rest;
|
|
761
813
|
if (!sub || sub === "get" || sub === "status") {
|
|
@@ -785,6 +837,7 @@ function commandHandler(scope: Scope, bw: BwState) {
|
|
|
785
837
|
try {
|
|
786
838
|
const run = await cli.withPassword(args, () => promptSecret(dialogs(ctx), "ai-vault · 主密码", "切换解锁模式"));
|
|
787
839
|
const result = JSON.parse(run.stdout) as { mode: UnlockModeName; hours: number; auto: boolean };
|
|
840
|
+
forgetSettings();
|
|
788
841
|
await lockNow(scope);
|
|
789
842
|
scope.mode = result.mode;
|
|
790
843
|
scope.auto = result.auto;
|
|
@@ -836,7 +889,7 @@ function commandHandler(scope: Scope, bw: BwState) {
|
|
|
836
889
|
note(ctx, `ai-vault: ${describe(error)}`, error instanceof CliError && error.denied ? "warning" : "error");
|
|
837
890
|
return;
|
|
838
891
|
}
|
|
839
|
-
const sure = await confirmWindow(dialogs(ctx), "ai-vault · 删除条目", `删除「${name}」?删除后无法恢复。`);
|
|
892
|
+
const sure = await confirmWindow(dialogs(ctx), "ai-vault · 删除条目", `删除「${forDialog(name)}」?删除后无法恢复。`);
|
|
840
893
|
if (!sure) return;
|
|
841
894
|
try {
|
|
842
895
|
const result = await cli.json<RemovingResult>([...args, "--yes"]);
|
|
@@ -862,7 +915,11 @@ function commandHandler(scope: Scope, bw: BwState) {
|
|
|
862
915
|
const args = ["grant", name, "--token", scope.token!];
|
|
863
916
|
if (minutes) args.push("--minutes", minutes);
|
|
864
917
|
try {
|
|
865
|
-
|
|
918
|
+
// A standing grant costs the master password, like a mode change.
|
|
919
|
+
const run = await cli.withPassword(args, () =>
|
|
920
|
+
promptSecret(dialogs(ctx), "ai-vault · 授权读取", "主密码(给这条条目 N 分钟免确认)"),
|
|
921
|
+
);
|
|
922
|
+
const result = JSON.parse(run.stdout) as { name: string; minutes: number };
|
|
866
923
|
setStatus(ctx, scope, "·granted");
|
|
867
924
|
note(ctx, `granted "${result.name}" for ${result.minutes}m`);
|
|
868
925
|
} catch (error) {
|
|
@@ -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,
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Machine-wide settings, owned by the CLI (`ai-vault settings`), read here.
|
|
3
|
+
*
|
|
4
|
+
* The vault decides when to ask for its password; the Bitwarden side decides
|
|
5
|
+
* separately whether its `bw` session key may live on disk, and whether a hit
|
|
6
|
+
* may be imported into the vault without a window.
|
|
7
|
+
*/
|
|
8
|
+
import { VaultCli } from "./cli.js";
|
|
9
|
+
|
|
10
|
+
export type UnlockModeName = "never" | "time" | "session";
|
|
11
|
+
export type ImportPolicy = "ask" | "always" | "never";
|
|
12
|
+
|
|
13
|
+
export interface Settings {
|
|
14
|
+
vault: { unlock: UnlockModeName; hours: number; auto: boolean };
|
|
15
|
+
bitwarden: {
|
|
16
|
+
unlock: UnlockModeName;
|
|
17
|
+
hours: number;
|
|
18
|
+
import: ImportPolicy;
|
|
19
|
+
persisted: boolean;
|
|
20
|
+
expiresAt: number | null;
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export const DEFAULT_SETTINGS: Settings = {
|
|
25
|
+
vault: { unlock: "session", hours: 8, auto: false },
|
|
26
|
+
bitwarden: { unlock: "session", hours: 8, import: "ask", persisted: false, expiresAt: null },
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
const cli = new VaultCli();
|
|
30
|
+
let cache: { at: number; value: Settings } | undefined;
|
|
31
|
+
|
|
32
|
+
/** The shared CLI client, for the pieces that read and write the settings. */
|
|
33
|
+
export function settingsCli(): VaultCli {
|
|
34
|
+
return cli;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Settings change rarely, so a short cache keeps a Bitwarden call from paying
|
|
39
|
+
* for the read. `/vault settings ...` drops it explicitly.
|
|
40
|
+
*/
|
|
41
|
+
export async function getSettings(signal?: AbortSignal, options: { fresh?: boolean } = {}): Promise<Settings> {
|
|
42
|
+
if (!options.fresh && cache && Date.now() - cache.at < 30_000) return cache.value;
|
|
43
|
+
const value = await cli.json<Settings>(["settings"], { signal });
|
|
44
|
+
cache = { at: Date.now(), value };
|
|
45
|
+
return value;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** For paths that must keep working when the CLI is missing: defaults instead. */
|
|
49
|
+
export async function getSettingsSafe(signal?: AbortSignal): Promise<Settings> {
|
|
50
|
+
try {
|
|
51
|
+
return await getSettings(signal);
|
|
52
|
+
} catch {
|
|
53
|
+
return DEFAULT_SETTINGS;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export function forgetSettings(): void {
|
|
58
|
+
cache = undefined;
|
|
59
|
+
}
|
package/test/cli.sh
CHANGED
|
@@ -49,7 +49,26 @@ echo "== unlock =="
|
|
|
49
49
|
check "unlock without a window asks the host" 3 "$BIN" unlock
|
|
50
50
|
check "a wrong password is an auth failure" 5 bash -c "printf 'wrong password' | '$BIN' unlock --password-stdin"
|
|
51
51
|
check "the right password opens it" 0 bash -c "printf 'correct horse' | '$BIN' unlock --password-stdin --json"
|
|
52
|
-
|
|
52
|
+
# The extension is the host: it mints its own secret before the first unlock
|
|
53
|
+
# and presents it on every call. A caller that only says AI_VAULT_HOST=1
|
|
54
|
+
# without a secret is treated as a human (see the attacker block).
|
|
55
|
+
HS=$(python3 -c "import secrets;print(secrets.token_hex(32))")
|
|
56
|
+
export AI_VAULT_HOST=1 AI_VAULT_HOST_SECRET="$HS"
|
|
57
|
+
check "a host that presents no secret is not handed one" 0 bash -c "printf 'correct horse' | env -u AI_VAULT_HOST_SECRET '$BIN' unlock --password-stdin --json >'$TMP/nosec'"
|
|
58
|
+
python3 - "$TMP/nosec" <<'PY' && ok "AI_VAULT_HOST=1 alone yields no hostSecret" || bad "a secret was handed to a caller without one"
|
|
59
|
+
import json,sys
|
|
60
|
+
assert json.load(open(sys.argv[1])).get("hostSecret") is None
|
|
61
|
+
PY
|
|
62
|
+
HOST_JSON=$(printf 'correct horse' | "$BIN" unlock --password-stdin --json)
|
|
63
|
+
ECHOED=$(printf '%s' "$HOST_JSON" | python3 -c "import json,sys;print(json.load(sys.stdin).get('hostSecret',''))")
|
|
64
|
+
[[ "$ECHOED" == "$HS" ]] && ok "the host's own secret is echoed back" || bad "hostSecret echo mismatch"
|
|
65
|
+
TOKEN=$(printf '%s' "$HOST_JSON" | json token)
|
|
66
|
+
# relay <entry> <y|n>: a signed approval for the host's token.
|
|
67
|
+
relay() {
|
|
68
|
+
local ap
|
|
69
|
+
ap=$(python3 -c "import hmac,hashlib;print(hmac.new('$HS'.encode(),('allow:$TOKEN:$1:$2'.lower()).encode(),hashlib.sha256).hexdigest())")
|
|
70
|
+
printf '%s\n' "$2" | "$BIN" get "$1" --token "$TOKEN" --answer-stdin --approval "$ap" --json
|
|
71
|
+
}
|
|
53
72
|
[[ ${#TOKEN} -ge 32 ]] && ok "a session token is printed" || bad "no token"
|
|
54
73
|
SESS="$XDG_RUNTIME_DIR/ai-vault/sessions/$TOKEN.json"
|
|
55
74
|
[[ -f "$SESS" ]] && ok "the token file lives under XDG_RUNTIME_DIR" || bad "token file missing"
|
|
@@ -70,9 +89,9 @@ grep -q 'p1ssw0rd' "$AI_VAULT_DIR/store.json" && bad "the password is in plainte
|
|
|
70
89
|
|
|
71
90
|
echo "== read approval =="
|
|
72
91
|
check "get without a window asks the host" 3 bash -c "'$BIN' get GitHub --token '$TOKEN'"
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
[[ $? -eq 0 ]] && ok "an approved
|
|
92
|
+
relay GitHub n >"$TMP/deny" 2>"$TMP/denyerr"; [[ $? -eq 4 ]] && ok "a denied relay is not a lock (exit 4)" || bad "a denied relay was not exit 4"
|
|
93
|
+
relay GitHub y >"$TMP/get" 2>"$TMP/err"
|
|
94
|
+
[[ $? -eq 0 ]] && ok "an approved relay reveals the entry" || bad "an approved relay failed"
|
|
76
95
|
python3 - "$TMP/get" <<'PY' && ok "the approved entry carries the password" || bad "get output is wrong"
|
|
77
96
|
import json,sys
|
|
78
97
|
item = json.load(open(sys.argv[1]))
|
|
@@ -99,6 +118,50 @@ grep -q 'exp-pass' "$AI_VAULT_DIR/store.json" && bad "an imported password is on
|
|
|
99
118
|
check "save requires the caller's --yes" 2 bash -c "printf '[]' | '$BIN' save --token '$TOKEN'"
|
|
100
119
|
check "save inserts drafts" 0 bash -c "printf '[{\"name\":\"Draft\",\"password\":\"dr-pw\",\"uris\":[\"https://d\"]}]' | '$BIN' save --yes --token '$TOKEN' --json"
|
|
101
120
|
|
|
121
|
+
echo "== tamper resistance (H1 / H2) =="
|
|
122
|
+
# A fresh, non-host session for the attacker tests.
|
|
123
|
+
# The attacker: a valid token, but no host identity and no secret (the model's bash).
|
|
124
|
+
T2=$(printf 'correct horse' | env -u AI_VAULT_HOST -u AI_VAULT_HOST_SECRET "$BIN" unlock --password-stdin --json | json token)
|
|
125
|
+
check "attacker: --answer-stdin without a host secret is refused" 2 bash -c "printf 'y\n' | env -u AI_VAULT_HOST -u AI_VAULT_HOST_SECRET '$BIN' get Draft --token '$T2' --answer-stdin"
|
|
126
|
+
check "attacker: a guessed approval with no secret is refused" 2 bash -c "printf 'y\n' | env -u AI_VAULT_HOST -u AI_VAULT_HOST_SECRET '$BIN' get Draft --token '$T2' --answer-stdin --approval 00"
|
|
127
|
+
check "attacker: grant now costs the password (window -> needs-ui)" 3 env -u AI_VAULT_HOST -u AI_VAULT_HOST_SECRET "$BIN" grant Draft --token "$T2"
|
|
128
|
+
T3="$TOKEN"
|
|
129
|
+
"$BIN" revoke Draft --token "$T3" --json >/dev/null
|
|
130
|
+
AP=$(python3 -c "import hmac,hashlib;print(hmac.new('$HS'.encode(),b'allow:$T3:draft:y',hashlib.sha256).hexdigest())")
|
|
131
|
+
check "host: a signed relay is accepted" 0 bash -c "printf 'y\n' | '$BIN' get Draft --token '$T3' --answer-stdin --approval '$AP' --json"
|
|
132
|
+
AP_N=$(python3 -c "import hmac,hashlib;print(hmac.new('$HS'.encode(),b'allow:$T3:draft:n',hashlib.sha256).hexdigest())")
|
|
133
|
+
"$BIN" revoke Draft --token "$T3" --json >/dev/null
|
|
134
|
+
check "a signature for 'n' with stdin 'y' is a mismatch" 4 bash -c "printf 'y\n' | '$BIN' get Draft --token '$T3' --answer-stdin --approval '$AP_N' --json"
|
|
135
|
+
# H2: edit the token file (mint a grant, rename the requester)
|
|
136
|
+
F="$XDG_RUNTIME_DIR/ai-vault/sessions/$T3.json"
|
|
137
|
+
python3 - "$F" <<'PY'
|
|
138
|
+
import json,sys
|
|
139
|
+
d=json.load(open(sys.argv[1])); d['grants']={'draft':9999999999999}; d['requester']='主会话'
|
|
140
|
+
json.dump(d,open(sys.argv[1],'w'))
|
|
141
|
+
PY
|
|
142
|
+
check "an edited token file is rejected" 5 bash -c "'$BIN' get Draft --token '$T3' --json"
|
|
143
|
+
[[ -f "$F" ]] && bad "the tampered file survived" || ok "the tampered file is deleted"
|
|
144
|
+
check "M1: a junk file in the sessions dir is swept on the next call" 0 "$BIN" path --json
|
|
145
|
+
|
|
146
|
+
echo "== sealed Bitwarden session (M4) =="
|
|
147
|
+
check "switch bitwarden.unlock to never" 0 "$BIN" settings bitwarden.unlock never --json
|
|
148
|
+
check "store a bw session key" 0 bash -c "printf 'BW_BEARER_TOKEN_PLAINTEXT' | '$BIN' bw-session put --json"
|
|
149
|
+
grep -q 'BW_BEARER_TOKEN_PLAINTEXT' "$AI_VAULT_DIR/bitwarden.session.json" && bad "the bw key is plaintext on disk" || ok "the bw key is not plaintext on disk"
|
|
150
|
+
[[ -f "$AI_VAULT_DIR/.wrap" ]] && ok "a wrap key exists" || bad "no wrap key"
|
|
151
|
+
[[ "$(stat -c %a "$AI_VAULT_DIR/.wrap")" == "600" ]] && ok "the wrap key is 0600" || bad "the wrap key is not 0600"
|
|
152
|
+
"$BIN" bw-session get --json | grep -q 'BW_BEARER_TOKEN_PLAINTEXT' && ok "bw-session get unseals it" || bad "bw-session get cannot unseal"
|
|
153
|
+
mv "$AI_VAULT_DIR/.wrap" "$TMP/wrap.bak"
|
|
154
|
+
check "without the wrap key the session does not open" 1 "$BIN" bw-session get
|
|
155
|
+
mv "$TMP/wrap.bak" "$AI_VAULT_DIR/.wrap"
|
|
156
|
+
"$BIN" settings bitwarden.unlock session --json >/dev/null
|
|
157
|
+
|
|
158
|
+
echo "== rekey (L2) =="
|
|
159
|
+
OLD_N=$(python3 -c "import json;print(json.load(open('$AI_VAULT_DIR/store.json'))['kdf']['N'])")
|
|
160
|
+
check "rekey with the password" 0 bash -c "printf 'correct horse' | '$BIN' rekey --password-stdin --json"
|
|
161
|
+
NEW_N=$(python3 -c "import json;print(json.load(open('$AI_VAULT_DIR/store.json'))['kdf']['N'])")
|
|
162
|
+
[[ "$NEW_N" == "131072" ]] && ok "scrypt N raised ($OLD_N -> $NEW_N)" || bad "kdf N is $NEW_N after rekey"
|
|
163
|
+
check "the store still opens with the same password" 0 bash -c "printf 'correct horse' | '$BIN' unlock --password-stdin --json"
|
|
164
|
+
|
|
102
165
|
echo "== lock / audit =="
|
|
103
166
|
check "lock drops the token" 0 "$BIN" lock --token "$TOKEN" --json
|
|
104
167
|
check "a dropped token no longer works" 5 "$BIN" list --token "$TOKEN"
|
|
@@ -107,7 +170,7 @@ python3 - "$TMP/audit" <<'PY' && ok "the audit log records events without values
|
|
|
107
170
|
import json,sys
|
|
108
171
|
entries = json.load(open(sys.argv[1]))["entries"]
|
|
109
172
|
events = {e["event"] for e in entries}
|
|
110
|
-
for want in ("init", "unlock", "unlock_failed", "add", "grant", "read_deny", "read_allow", "remove", "import", "lock"):
|
|
173
|
+
for want in ("init", "unlock", "unlock_failed", "add", "grant", "read_deny", "read_allow", "remove", "import", "lock", "rekey", "bw_session"):
|
|
111
174
|
assert want in events, (want, events)
|
|
112
175
|
assert not any("p1ssw0rd" in json.dumps(e) or "exp-pass" in json.dumps(e) for e in entries)
|
|
113
176
|
PY
|
|
@@ -128,6 +191,44 @@ PY
|
|
|
128
191
|
check "back to session mode" 0 bash -c "printf 'correct horse' | '$BIN' mode set session --password-stdin --json"
|
|
129
192
|
check "session mode needs a token again" 5 "$BIN" status
|
|
130
193
|
|
|
194
|
+
echo "== settings =="
|
|
195
|
+
check "settings prints everything" 0 "$BIN" settings --json
|
|
196
|
+
check "set bitwarden.import" 0 "$BIN" settings bitwarden.import never --json
|
|
197
|
+
"$BIN" settings bitwarden.import --json >"$TMP/set1"
|
|
198
|
+
python3 - "$TMP/set1" <<'PY' && ok "the import policy was stored" || bad "the import policy was not stored"
|
|
199
|
+
import json,sys
|
|
200
|
+
assert json.load(open(sys.argv[1]))["value"] == "never"
|
|
201
|
+
PY
|
|
202
|
+
check "an unknown setting is a usage error" 2 "$BIN" settings nope.value 1
|
|
203
|
+
check "bw-session put is refused in session mode" 1 bash -c "printf 'K' | '$BIN' bw-session put"
|
|
204
|
+
check "switch bitwarden.unlock to never" 0 "$BIN" settings bitwarden.unlock never --json
|
|
205
|
+
check "bw-session put stores the key" 0 bash -c "printf 'GOOD_SESSION' | '$BIN' bw-session put --json"
|
|
206
|
+
[[ "$(stat -c %a "$AI_VAULT_DIR/bitwarden.session.json")" == "600" ]] && ok "the bw session file is 0600" || bad "the bw session file is not 0600"
|
|
207
|
+
check "bw-session get returns it" 0 "$BIN" bw-session get --json
|
|
208
|
+
check "switch back to session" 0 "$BIN" settings bitwarden.unlock session --json
|
|
209
|
+
check "the stored key is gone" 5 "$BIN" bw-session get
|
|
210
|
+
check "bitwarden.unlock time keeps an expiry" 0 "$BIN" settings bitwarden.unlock time --json
|
|
211
|
+
check "bw-session put in time mode" 0 bash -c "printf 'K2' | '$BIN' bw-session put --json"
|
|
212
|
+
grep -q '"expiresAt": *[0-9]' "$AI_VAULT_DIR/bitwarden.session.json" && ok "time mode writes a deadline" || bad "time mode wrote no deadline"
|
|
213
|
+
"$BIN" settings bitwarden.unlock session --json >/dev/null
|
|
214
|
+
|
|
215
|
+
echo "== two stores share the sessions dir =="
|
|
216
|
+
# A second store in another directory uses the same XDG_RUNTIME_DIR sessions
|
|
217
|
+
# directory. Housekeeping of one must not delete the other's live token.
|
|
218
|
+
TA=$(printf 'correct horse' | "$BIN" unlock --password-stdin --json | json token)
|
|
219
|
+
check "store A: token works" 0 "$BIN" list --token "$TA" --json
|
|
220
|
+
export AI_VAULT_DIR="$TMP/store2"
|
|
221
|
+
printf 'other horse' | "$BIN" init --password-stdin --json >/dev/null
|
|
222
|
+
TOK2=$(printf 'other horse' | "$BIN" unlock --password-stdin --json | json token)
|
|
223
|
+
# B's init and unlock each ran a sweep; A's token must still be there.
|
|
224
|
+
export AI_VAULT_DIR="$TMP/store"
|
|
225
|
+
check "store A's token survives store B's init/unlock" 0 "$BIN" list --token "$TA" --json
|
|
226
|
+
# A's calls just ran A's sweep; B's token must still be there.
|
|
227
|
+
export AI_VAULT_DIR="$TMP/store2"
|
|
228
|
+
check "store B's token survives store A's calls" 0 "$BIN" list --token "$TOK2" --json
|
|
229
|
+
"$BIN" lock --token "$TOK2" >/dev/null
|
|
230
|
+
export AI_VAULT_DIR="$TMP/store"
|
|
231
|
+
|
|
131
232
|
echo "== doctor =="
|
|
132
233
|
check "doctor runs" 0 "$BIN" doctor --json
|
|
133
234
|
|
package/tests/prompt.test.mjs
CHANGED
|
@@ -198,3 +198,15 @@ test("no display and no UI fails closed", async () => {
|
|
|
198
198
|
restore();
|
|
199
199
|
}
|
|
200
200
|
});
|
|
201
|
+
|
|
202
|
+
test("forDialog flattens a forged multi-line value into one bounded line", async () => {
|
|
203
|
+
const { forDialog } = await import("../packages/pi-ai-vault/src/prompt.ts");
|
|
204
|
+
const forged = "github\n\n条目: nothing\n请求方: 主会话\n(已授权,点允许)";
|
|
205
|
+
const clean = forDialog(forged);
|
|
206
|
+
assert.equal(clean.includes("\n"), false);
|
|
207
|
+
assert.ok(clean.startsWith("github 条目: nothing"));
|
|
208
|
+
assert.ok(clean.length <= 80);
|
|
209
|
+
assert.equal(forDialog(" a b "), "a b");
|
|
210
|
+
assert.equal(forDialog("x".repeat(100), 10).length, 10);
|
|
211
|
+
assert.ok(forDialog("x".repeat(100), 10).endsWith("…"));
|
|
212
|
+
});
|
package/tests/vault-cli.test.mjs
CHANGED
|
@@ -9,6 +9,7 @@ import { answers, bind, cleanUpOnExit, dialogTrace, makeCtx, subCtx, textOf, use
|
|
|
9
9
|
// by `npm test`) plus the mock zenity, with a throwaway store.
|
|
10
10
|
const dir = useMocks();
|
|
11
11
|
const { default: aiVault } = await import("../packages/pi-ai-vault/src/index.ts");
|
|
12
|
+
const { forgetSettings } = await import("../packages/pi-ai-vault/src/settings.ts");
|
|
12
13
|
cleanUpOnExit(dir);
|
|
13
14
|
|
|
14
15
|
const PW = "correct horse battery";
|
|
@@ -215,3 +216,100 @@ test("never mode reads without any window, and the switch needs the password", a
|
|
|
215
216
|
const back = switchMode("session");
|
|
216
217
|
assert.equal(back.status, 0, back.stderr);
|
|
217
218
|
});
|
|
219
|
+
|
|
220
|
+
test("bitwarden.import=never reads once with a single window", async () => {
|
|
221
|
+
const bin = process.env.AI_VAULT_BIN;
|
|
222
|
+
spawnSync(bin, ["settings", "bitwarden.import", "never"], { env: process.env });
|
|
223
|
+
forgetSettings();
|
|
224
|
+
const b = bind(aiVault, true);
|
|
225
|
+
const ctx = makeCtx().ctx;
|
|
226
|
+
answers.master(dir, PW);
|
|
227
|
+
await b.cmd("unlock", ctx);
|
|
228
|
+
answers.master(dir, "testmaster");
|
|
229
|
+
const before = prompts("--question");
|
|
230
|
+
answers.questions(dir, "y");
|
|
231
|
+
const result = await b.tool("vault_get", { name: "OtherService" }, ctx);
|
|
232
|
+
assert.equal(result.details.via, "bitwarden-once");
|
|
233
|
+
assert.equal(prompts("--question"), before + 1, "never: read approval only, no import question");
|
|
234
|
+
});
|
|
235
|
+
|
|
236
|
+
test("bitwarden.import=always pulls the entry in without a window", async () => {
|
|
237
|
+
const bin = process.env.AI_VAULT_BIN;
|
|
238
|
+
spawnSync(bin, ["settings", "bitwarden.import", "always"], { env: process.env });
|
|
239
|
+
forgetSettings();
|
|
240
|
+
const b = bind(aiVault, true);
|
|
241
|
+
const ctx = makeCtx().ctx;
|
|
242
|
+
answers.master(dir, PW);
|
|
243
|
+
await b.cmd("unlock", ctx);
|
|
244
|
+
answers.master(dir, "testmaster");
|
|
245
|
+
const before = prompts("--question");
|
|
246
|
+
const result = await b.tool("vault_get", { name: "OtherService" }, ctx);
|
|
247
|
+
assert.equal(result.details.via, "imported-from-bitwarden");
|
|
248
|
+
assert.equal(prompts("--question"), before, "always: no window at all");
|
|
249
|
+
|
|
250
|
+
answers.master(dir, PW);
|
|
251
|
+
const listed = await b.tool("vault_list", {}, ctx);
|
|
252
|
+
assert.equal(
|
|
253
|
+
JSON.parse(textOf(listed)).some((i) => i.name === "OtherService"),
|
|
254
|
+
true,
|
|
255
|
+
);
|
|
256
|
+
spawnSync(bin, ["settings", "bitwarden.import", "ask"], { env: process.env });
|
|
257
|
+
forgetSettings();
|
|
258
|
+
});
|
|
259
|
+
|
|
260
|
+
test("a persisted Bitwarden session costs no password", async () => {
|
|
261
|
+
const bin = process.env.AI_VAULT_BIN;
|
|
262
|
+
const set = (key, value) => spawnSync(bin, ["settings", key, value], { env: process.env, encoding: "utf8" });
|
|
263
|
+
assert.equal(set("bitwarden.unlock", "never").status, 0);
|
|
264
|
+
forgetSettings();
|
|
265
|
+
const put = spawnSync(bin, ["bw-session", "put"], { input: "GOOD_SESSION", env: process.env, encoding: "utf8" });
|
|
266
|
+
assert.equal(put.status, 0, put.stderr);
|
|
267
|
+
|
|
268
|
+
const b = bind(aiVault, true);
|
|
269
|
+
const ctx = makeCtx().ctx;
|
|
270
|
+
answers.master(dir, PW);
|
|
271
|
+
answers.master(dir, PW); // would be consumed only by a Bitwarden prompt
|
|
272
|
+
const before = prompts("--password");
|
|
273
|
+
const listed = await b.tool("bw_list", {}, ctx);
|
|
274
|
+
assert.equal(listed.isError, undefined);
|
|
275
|
+
assert.equal(prompts("--password"), before, "the stored bw session must be used silently");
|
|
276
|
+
|
|
277
|
+
// Restoring the session policy drops the key from disk.
|
|
278
|
+
assert.equal(set("bitwarden.unlock", "session").status, 0);
|
|
279
|
+
forgetSettings();
|
|
280
|
+
const get = spawnSync(bin, ["bw-session", "get"], { env: process.env, encoding: "utf8" });
|
|
281
|
+
assert.equal(get.status, 5, "switching back to session must remove the stored key");
|
|
282
|
+
});
|
|
283
|
+
|
|
284
|
+
test("a relayed read approval is signed by the host: the raw CLI refuses a bare 'y'", async () => {
|
|
285
|
+
const bin = process.env.AI_VAULT_BIN;
|
|
286
|
+
// A session opened by a human (no host identity): the attacker's position.
|
|
287
|
+
const human = spawnSync(bin, ["unlock", "--password-stdin", "--json"], {
|
|
288
|
+
input: `${PW}\n`,
|
|
289
|
+
env: { ...process.env, AI_VAULT_HOST: "", AI_VAULT_HOST_SECRET: "" },
|
|
290
|
+
encoding: "utf8",
|
|
291
|
+
});
|
|
292
|
+
const token = JSON.parse(human.stdout).token;
|
|
293
|
+
assert.equal(JSON.parse(human.stdout).hostSecret ?? null, null, "a human caller is not handed a secret");
|
|
294
|
+
const bare = spawnSync(bin, ["get", "GitHub", "--token", token, "--answer-stdin", "--json"], {
|
|
295
|
+
input: "y\n",
|
|
296
|
+
env: { ...process.env, AI_VAULT_HOST: "", AI_VAULT_HOST_SECRET: "" },
|
|
297
|
+
encoding: "utf8",
|
|
298
|
+
});
|
|
299
|
+
assert.equal(bare.status, 2, bare.stderr);
|
|
300
|
+
assert.match(bare.stderr, /--approval/);
|
|
301
|
+
|
|
302
|
+
// The same token, with the file edited to carry a grant: rejected on load.
|
|
303
|
+
const { readdirSync, readFileSync, writeFileSync } = await import("node:fs");
|
|
304
|
+
const { join } = await import("node:path");
|
|
305
|
+
const dir = join(process.env.XDG_RUNTIME_DIR ?? "/tmp", "ai-vault", "sessions");
|
|
306
|
+
const file = join(dir, `${token}.json`);
|
|
307
|
+
const edited = JSON.parse(readFileSync(file, "utf8"));
|
|
308
|
+
edited.grants = { github: 9999999999999 };
|
|
309
|
+
edited.requester = "主会话";
|
|
310
|
+
writeFileSync(file, JSON.stringify(edited));
|
|
311
|
+
const tampered = spawnSync(bin, ["get", "GitHub", "--token", token, "--json"], { encoding: "utf8" });
|
|
312
|
+
assert.equal(tampered.status, 5);
|
|
313
|
+
assert.match(tampered.stderr, /modified outside ai-vault/);
|
|
314
|
+
assert.equal(readdirSync(dir).includes(`${token}.json`), false, "the tampered file is deleted");
|
|
315
|
+
});
|