@xiaolikt/ai-vault 0.13.0 → 0.14.1
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 +53 -51
- package/README.zh.md +28 -35
- package/crates/ai-vault/Cargo.toml +1 -1
- package/crates/ai-vault/src/cli.rs +196 -34
- package/crates/ai-vault/src/config.rs +88 -11
- package/crates/ai-vault/src/crypto.rs +10 -1
- package/crates/ai-vault/src/sealed.rs +3 -1
- package/crates/ai-vault/src/session.rs +74 -0
- package/package.json +6 -6
- package/packages/pi-ai-vault/README.md +3 -2
- package/packages/pi-ai-vault/README.zh.md +4 -3
- package/packages/pi-ai-vault/package.json +2 -2
- package/packages/pi-ai-vault/src/bitwarden.ts +3 -3
- package/packages/pi-ai-vault/src/cli.ts +11 -5
- package/packages/pi-ai-vault/src/ente.ts +2 -2
- package/packages/pi-ai-vault/src/index.ts +121 -51
- package/packages/pi-ai-vault/src/settings.ts +14 -2
- package/test/cli.sh +67 -2
- package/tests/vault-cli.test.mjs +98 -3
|
@@ -29,17 +29,19 @@ import type { Draft, ItemType } from "./types.js";
|
|
|
29
29
|
import { registerEnte } from "./ente.js";
|
|
30
30
|
import { isOmpHost, onSessionLeave, sessionLabel, subagentId, withTier } from "./host.js";
|
|
31
31
|
import { confirmWindow, forDialog, promptSecret, promptText, type PromptHost } from "./prompt.js";
|
|
32
|
-
import { forgetSettings, getSettingsSafe, setSettingsToken, settingsCli, settingsToken, type Settings } from "./settings.js";
|
|
32
|
+
import { forgetSettings, getSettingsSafe, setEveryPassword, setSettingsToken, settingsCli, settingsOpts, settingsToken, type Settings } from "./settings.js";
|
|
33
33
|
|
|
34
34
|
type Ctx = ExtensionToolContext | ExtensionCommandContext;
|
|
35
35
|
|
|
36
36
|
const GRANT_MS_DEFAULT = 5 * 60_000;
|
|
37
37
|
|
|
38
|
-
type UnlockModeName = "never" | "time" | "
|
|
38
|
+
type UnlockModeName = "never" | "time" | "every";
|
|
39
39
|
|
|
40
40
|
interface StatusResult {
|
|
41
41
|
ok: boolean;
|
|
42
42
|
unlocked: boolean;
|
|
43
|
+
/** The session the call ran under; a binding that came without a token adopts it. */
|
|
44
|
+
token?: string | null;
|
|
43
45
|
items: number;
|
|
44
46
|
requester: string;
|
|
45
47
|
idleMs: number;
|
|
@@ -97,6 +99,9 @@ interface Scope {
|
|
|
97
99
|
mode?: UnlockModeName;
|
|
98
100
|
/** True when reads use the machine-wide session instead of a token. */
|
|
99
101
|
auto?: boolean;
|
|
102
|
+
/** `vault.unlock = every`: the master password for the call being made, asked
|
|
103
|
+
* for before each one and dropped after it. Never stored anywhere else. */
|
|
104
|
+
everyPassword?: string;
|
|
100
105
|
unlocking?: Promise<boolean>;
|
|
101
106
|
}
|
|
102
107
|
|
|
@@ -149,6 +154,7 @@ async function lockNow(scope: Scope): Promise<void> {
|
|
|
149
154
|
scope.epoch++;
|
|
150
155
|
scope.items = 0;
|
|
151
156
|
setSettingsToken(undefined);
|
|
157
|
+
setEveryPassword(undefined);
|
|
152
158
|
forgetSettings();
|
|
153
159
|
if (!token || !cli.available) return;
|
|
154
160
|
try {
|
|
@@ -160,6 +166,9 @@ async function lockNow(scope: Scope): Promise<void> {
|
|
|
160
166
|
|
|
161
167
|
/** Args for a CLI call: this binding's token, or the machine-wide session. */
|
|
162
168
|
const tokenArgs = (scope: Scope): string[] => (scope.token ? ["--token", scope.token] : []);
|
|
169
|
+
/** The CLI options a vault call needs beyond its arguments: the `every` password. */
|
|
170
|
+
const callOpts = (scope: Scope, signal?: AbortSignal): { signal?: AbortSignal; password?: string } =>
|
|
171
|
+
scope.everyPassword !== undefined ? { signal, password: scope.everyPassword } : { signal };
|
|
163
172
|
|
|
164
173
|
/** Make this binding's unlock happen; never throws. */
|
|
165
174
|
async function ensureUnlocked(scope: Scope, ctx: Ctx, signal?: AbortSignal): Promise<boolean> {
|
|
@@ -190,25 +199,63 @@ async function ensureUnlocked(scope: Scope, ctx: Ctx, signal?: AbortSignal): Pro
|
|
|
190
199
|
}
|
|
191
200
|
}
|
|
192
201
|
}
|
|
193
|
-
//
|
|
194
|
-
//
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
note(ctx,
|
|
205
|
-
return
|
|
206
|
-
}
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
202
|
+
// No token (first call, or `never`/`every`). Ask the CLI what that means:
|
|
203
|
+
// `never` answers outright; `every` says it needs a password — for this
|
|
204
|
+
// call only, since that mode keeps nothing between calls.
|
|
205
|
+
{
|
|
206
|
+
const askEveryPassword = async (): Promise<string | undefined> => {
|
|
207
|
+
const password = await promptSecret(
|
|
208
|
+
dialogs(ctx),
|
|
209
|
+
tr("ai-vault · unlock", "ai-vault · 解锁"),
|
|
210
|
+
tr("master password (asked on every call)", "主密码(每次调用都会问)"),
|
|
211
|
+
signal,
|
|
212
|
+
);
|
|
213
|
+
if (!password && !signal?.aborted) note(ctx, tr("no master password entered", "没有输入主密码"), "warning");
|
|
214
|
+
return password;
|
|
215
|
+
};
|
|
216
|
+
try {
|
|
217
|
+
const status = await cli.json<StatusResult>(["status"], { signal });
|
|
218
|
+
scope.items = status.items;
|
|
219
|
+
scope.mode = status.mode;
|
|
220
|
+
scope.auto = status.auto;
|
|
221
|
+
// In `time` mode the CLI found an existing unlock and minted a
|
|
222
|
+
// session of our own under it: keep that token, so relayed
|
|
223
|
+
// approvals are signed for the session that will check them.
|
|
224
|
+
scope.token = status.token ?? undefined;
|
|
225
|
+
setSettingsToken(scope.token);
|
|
226
|
+
return true;
|
|
227
|
+
} catch (error) {
|
|
228
|
+
if (error instanceof CliError && /not initialized/i.test(error.message)) {
|
|
229
|
+
note(ctx, NOT_INITIALIZED, "warning");
|
|
230
|
+
return false;
|
|
231
|
+
}
|
|
232
|
+
if (error instanceof CliError && error.needsUi === "password") {
|
|
233
|
+
// `every`: the password opens the store for this call alone.
|
|
234
|
+
const password = await askEveryPassword();
|
|
235
|
+
if (!password) return false;
|
|
236
|
+
try {
|
|
237
|
+
const status = await cli.json<StatusResult>(["status"], { signal, password });
|
|
238
|
+
scope.items = status.items;
|
|
239
|
+
scope.mode = "every";
|
|
240
|
+
scope.everyPassword = password;
|
|
241
|
+
setEveryPassword(password);
|
|
242
|
+
return true;
|
|
243
|
+
} catch (retryError) {
|
|
244
|
+
if (retryError instanceof CliError && retryError.auth) {
|
|
245
|
+
note(ctx, tr("ai-vault: wrong master password", "ai-vault: 主密码错误"), "error");
|
|
246
|
+
return false;
|
|
247
|
+
}
|
|
248
|
+
note(ctx, `ai-vault: ${describe(retryError)}`, "error");
|
|
249
|
+
return false;
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
if (!(error instanceof CliError) || !error.auth) {
|
|
253
|
+
note(ctx, `ai-vault: ${describe(error)}`, "error");
|
|
254
|
+
return false;
|
|
255
|
+
}
|
|
210
256
|
}
|
|
211
257
|
}
|
|
258
|
+
let lastUnlockPassword: string | undefined;
|
|
212
259
|
const attempt = async (password?: string): Promise<UnlockResult> => {
|
|
213
260
|
const args = ["--requester", sessionLabel(ctx)];
|
|
214
261
|
if (password !== undefined) args.push("--password-stdin");
|
|
@@ -228,19 +275,27 @@ async function ensureUnlocked(scope: Scope, ctx: Ctx, signal?: AbortSignal): Pro
|
|
|
228
275
|
if (!signal?.aborted) note(ctx, tr("no master password entered (the window was cancelled, or there is no desktop/UI)", "没有输入主密码(窗口已取消,或没有桌面/界面)"), "warning");
|
|
229
276
|
return false;
|
|
230
277
|
}
|
|
278
|
+
lastUnlockPassword = password;
|
|
231
279
|
result = await attempt(password);
|
|
232
280
|
}
|
|
233
281
|
// /vault lock or a session switch ran while the window was open.
|
|
234
282
|
if (epoch !== scope.epoch || signal?.aborted) {
|
|
235
|
-
await cli.run(["lock", "--token", result.token]).catch(() => undefined);
|
|
283
|
+
if (result.token) await cli.run(["lock", "--token", result.token]).catch(() => undefined);
|
|
236
284
|
return false;
|
|
237
285
|
}
|
|
238
286
|
scope.mode = result.mode;
|
|
239
287
|
scope.auto = result.mode === "never";
|
|
240
288
|
// In `never` mode the CLI wrote the machine-wide session; keeping a
|
|
241
289
|
// per-binding token would bring back a confirm window on every read.
|
|
242
|
-
|
|
290
|
+
// In `every` mode no token exists: the store was just proved open by
|
|
291
|
+
// the password that was typed, so this call proceeds on it, and the
|
|
292
|
+
// next call asks again.
|
|
293
|
+
scope.token = result.mode === "never" || result.mode === "every" ? undefined : result.token;
|
|
243
294
|
scope.items = result.items;
|
|
295
|
+
if (result.mode === "every") {
|
|
296
|
+
scope.everyPassword = lastUnlockPassword;
|
|
297
|
+
setEveryPassword(lastUnlockPassword);
|
|
298
|
+
}
|
|
244
299
|
setSettingsToken(scope.token);
|
|
245
300
|
return true;
|
|
246
301
|
} catch (error) {
|
|
@@ -277,7 +332,7 @@ function vaultListTool(scope: Scope): ToolDefinition<typeof vaultListParams, { o
|
|
|
277
332
|
async execute(_id, _params, signal, _onUpdate, ctx) {
|
|
278
333
|
if (!(await ensureUnlocked(scope, ctx, signal))) return fail(LOCKED);
|
|
279
334
|
try {
|
|
280
|
-
const result = await cli.json<ListResult>(["list",
|
|
335
|
+
const result = await cli.json<ListResult>(["list", ...tokenArgs(scope)], callOpts(scope, signal));
|
|
281
336
|
scope.items = result.count;
|
|
282
337
|
setStatus(ctx, scope);
|
|
283
338
|
return {
|
|
@@ -286,6 +341,9 @@ function vaultListTool(scope: Scope): ToolDefinition<typeof vaultListParams, { o
|
|
|
286
341
|
};
|
|
287
342
|
} catch (error) {
|
|
288
343
|
return failure(scope, error);
|
|
344
|
+
} finally {
|
|
345
|
+
scope.everyPassword = undefined;
|
|
346
|
+
setEveryPassword(undefined);
|
|
289
347
|
}
|
|
290
348
|
},
|
|
291
349
|
};
|
|
@@ -337,7 +395,7 @@ async function bitwardenFallback(
|
|
|
337
395
|
try {
|
|
338
396
|
const saved = await cli.json<SaveResult>(["save", "--yes", ...tokenArgs(scope)], {
|
|
339
397
|
stdin: JSON.stringify([draft]),
|
|
340
|
-
signal,
|
|
398
|
+
...callOpts(scope, signal),
|
|
341
399
|
});
|
|
342
400
|
scope.items += saved.count;
|
|
343
401
|
setStatus(ctx, scope);
|
|
@@ -398,8 +456,9 @@ function vaultGetTool(scope: Scope, bw: BwState): ToolDefinition<typeof vaultGet
|
|
|
398
456
|
if (!(await ensureUnlocked(scope, ctx, signal))) return fail(LOCKED);
|
|
399
457
|
const base = ["get", params.name, ...(params.reason ? ["--reason", params.reason] : []), ...tokenArgs(scope)];
|
|
400
458
|
try {
|
|
459
|
+
// (the `every` password is dropped when this call ends, in the finally below)
|
|
401
460
|
try {
|
|
402
|
-
const run = await cli.run([...base, "--json"],
|
|
461
|
+
const run = await cli.run([...base, "--json"], callOpts(scope, signal));
|
|
403
462
|
setStatus(ctx, scope, "·ok");
|
|
404
463
|
return {
|
|
405
464
|
content: [{ type: "text" as const, text: run.stdout.trim() }],
|
|
@@ -424,7 +483,7 @@ function vaultGetTool(scope: Scope, bw: BwState): ToolDefinition<typeof vaultGet
|
|
|
424
483
|
}
|
|
425
484
|
const run = await cli.run([...base, "--json", "--answer-stdin", "--approval", approval], {
|
|
426
485
|
stdin: allowed ? "y\n" : "n\n",
|
|
427
|
-
signal,
|
|
486
|
+
...callOpts(scope, signal),
|
|
428
487
|
});
|
|
429
488
|
setStatus(ctx, scope, "·granted");
|
|
430
489
|
return {
|
|
@@ -440,6 +499,9 @@ function vaultGetTool(scope: Scope, bw: BwState): ToolDefinition<typeof vaultGet
|
|
|
440
499
|
} catch (error) {
|
|
441
500
|
if (error instanceof CliError && error.denied) setStatus(ctx, scope, "·denied");
|
|
442
501
|
return failure(scope, error);
|
|
502
|
+
} finally {
|
|
503
|
+
scope.everyPassword = undefined;
|
|
504
|
+
setEveryPassword(undefined);
|
|
443
505
|
}
|
|
444
506
|
},
|
|
445
507
|
};
|
|
@@ -566,7 +628,7 @@ async function saveLocalEntry(scope: Scope, ctx: Ctx, req: SaveRequest): Promise
|
|
|
566
628
|
if (!name) return "cancelled: no entry name";
|
|
567
629
|
|
|
568
630
|
const kind = req.type ?? "login";
|
|
569
|
-
const args = ["add", "--name", name, "--type", kind,
|
|
631
|
+
const args = ["add", "--name", name, "--type", kind, ...tokenArgs(scope)];
|
|
570
632
|
if (req.username !== undefined) args.push("--username", req.username);
|
|
571
633
|
if (req.uri?.trim()) args.push("--uri", req.uri.trim());
|
|
572
634
|
if (req.notes?.trim()) args.push("--notes", req.notes.trim());
|
|
@@ -587,7 +649,7 @@ async function saveLocalEntry(scope: Scope, ctx: Ctx, req: SaveRequest): Promise
|
|
|
587
649
|
for (let attempt = 0; attempt < 8; attempt++) {
|
|
588
650
|
flush();
|
|
589
651
|
try {
|
|
590
|
-
const run = await cli.run([...args, "--json"], {
|
|
652
|
+
const run = await cli.run([...args, "--json"], { ...callOpts(scope, req.signal) });
|
|
591
653
|
const saved = JSON.parse(run.stdout) as { item?: string; created?: boolean; type?: string };
|
|
592
654
|
if (saved.created) scope.items += 1;
|
|
593
655
|
setStatus(ctx, scope);
|
|
@@ -674,9 +736,9 @@ async function importBitwarden(
|
|
|
674
736
|
return { text: "nothing matched; nothing imported", ok: false, count: 0 };
|
|
675
737
|
}
|
|
676
738
|
try {
|
|
677
|
-
const saved = await cli.json<SaveResult>(["save", "--yes",
|
|
739
|
+
const saved = await cli.json<SaveResult>(["save", "--yes", ...tokenArgs(scope)], {
|
|
678
740
|
stdin: JSON.stringify(drafts),
|
|
679
|
-
signal,
|
|
741
|
+
...callOpts(scope, signal),
|
|
680
742
|
});
|
|
681
743
|
scope.items += saved.count;
|
|
682
744
|
setStatus(ctx, scope);
|
|
@@ -807,7 +869,7 @@ function commandHandler(scope: Scope, bw: BwState) {
|
|
|
807
869
|
}
|
|
808
870
|
case "status": {
|
|
809
871
|
try {
|
|
810
|
-
const status = await cli.json<StatusResult>(["status", ...tokenArgs(scope)]);
|
|
872
|
+
const status = await cli.json<StatusResult>(["status", ...tokenArgs(scope)], callOpts(scope));
|
|
811
873
|
scope.items = status.items;
|
|
812
874
|
scope.mode = status.mode;
|
|
813
875
|
scope.auto = status.auto;
|
|
@@ -852,14 +914,15 @@ function commandHandler(scope: Scope, bw: BwState) {
|
|
|
852
914
|
case "ente-key": {
|
|
853
915
|
// Ente's unattended key: generated by `ente vault key generate`.
|
|
854
916
|
// Saved sealed, so `ente.unlock = never | time` can use it.
|
|
917
|
+
if (!(await ensureUnlocked(scope, ctx))) return;
|
|
855
918
|
const key = await promptSecret(dialogs(ctx), tr("ai-vault · Ente key", "ai-vault · Ente 密钥"), tr("the key printed by ente vault key generate", "ente vault key generate 输出的密钥"));
|
|
856
919
|
if (!key) {
|
|
857
920
|
note(ctx, tr("cancelled", "已取消"), "warning");
|
|
858
921
|
return;
|
|
859
922
|
}
|
|
860
923
|
try {
|
|
861
|
-
const args = ["ente-session", "put"];
|
|
862
|
-
await cli.run(args, { stdin: key });
|
|
924
|
+
const args = ["ente-session", "put", ...tokenArgs(scope)];
|
|
925
|
+
await cli.run(args, { stdin: key, ...callOpts(scope) });
|
|
863
926
|
forgetSettings();
|
|
864
927
|
note(ctx, tr("saved (sealed). You can now set /vault settings ente.unlock never", "已保存(封存)。现在可以设置 /vault settings ente.unlock never"));
|
|
865
928
|
} catch (error) {
|
|
@@ -871,9 +934,10 @@ function commandHandler(scope: Scope, bw: BwState) {
|
|
|
871
934
|
// /vault confirm show
|
|
872
935
|
// /vault confirm off|on turn the per-read window off (asks the master password) / on
|
|
873
936
|
const [arg] = rest;
|
|
937
|
+
if (!(await ensureUnlocked(scope, ctx))) return;
|
|
874
938
|
if (!arg) {
|
|
875
939
|
try {
|
|
876
|
-
const current = await cli.json<Settings>(["settings", ...tokenArgs(scope)]);
|
|
940
|
+
const current = await cli.json<Settings>(["settings", ...tokenArgs(scope)], callOpts(scope));
|
|
877
941
|
note(ctx, `vault.confirm: ${current.vault.confirm}${current.vault.confirm ? tr(" (a window per read while unlocked)", " (解锁后每次读取弹确认窗)") : tr(" (the unlock is the approval; reads are audited)", " (解锁即授权;读取仍记审计)")}`);
|
|
878
942
|
} catch (error) {
|
|
879
943
|
note(ctx, `ai-vault: ${describe(error)}`, "error");
|
|
@@ -889,7 +953,8 @@ function commandHandler(scope: Scope, bw: BwState) {
|
|
|
889
953
|
try {
|
|
890
954
|
const run = await cli.withPassword(["settings", "vault.confirm", turnOff ? "false" : "true", ...tokenArgs(scope)], () =>
|
|
891
955
|
promptSecret(dialogs(ctx), tr("ai-vault · master password", "ai-vault · 主密码"), tr("turn off the per-read confirmation", "关闭每次读取的确认窗")),
|
|
892
|
-
);
|
|
956
|
+
callOpts(scope));
|
|
957
|
+
|
|
893
958
|
forgetSettings();
|
|
894
959
|
const updated = JSON.parse(run.stdout) as Settings;
|
|
895
960
|
note(
|
|
@@ -909,13 +974,16 @@ function commandHandler(scope: Scope, bw: BwState) {
|
|
|
909
974
|
case "settings": {
|
|
910
975
|
const [key, ...valueParts] = rest;
|
|
911
976
|
const value = valueParts.join(" ").trim();
|
|
977
|
+
// Reading the settings means opening the store: in `every` mode
|
|
978
|
+
// that is a password for this call, asked here.
|
|
979
|
+
if (!(await ensureUnlocked(scope, ctx))) return;
|
|
912
980
|
try {
|
|
913
981
|
if (!key) {
|
|
914
|
-
note(ctx, settingsText(await cli.json<Settings>(["settings", ...tokenArgs(scope)])));
|
|
982
|
+
note(ctx, settingsText(await cli.json<Settings>(["settings", ...tokenArgs(scope)], callOpts(scope))));
|
|
915
983
|
return;
|
|
916
984
|
}
|
|
917
985
|
if (!value) {
|
|
918
|
-
const one = await cli.json<{ key: string; value: string }>(["settings", key, ...tokenArgs(scope)]);
|
|
986
|
+
const one = await cli.json<{ key: string; value: string }>(["settings", key, ...tokenArgs(scope)], callOpts(scope));
|
|
919
987
|
note(ctx, `${one.key}: ${one.value}`);
|
|
920
988
|
return;
|
|
921
989
|
}
|
|
@@ -923,7 +991,8 @@ function commandHandler(scope: Scope, bw: BwState) {
|
|
|
923
991
|
// needs-ui); the other keys do not prompt at all.
|
|
924
992
|
const run = await cli.withPassword(["settings", key, value, ...tokenArgs(scope)], () =>
|
|
925
993
|
promptSecret(dialogs(ctx), tr("ai-vault · master password", "ai-vault · 主密码"), tr("changing the unlock policy needs verification", "改变解锁模式需要验证")),
|
|
926
|
-
);
|
|
994
|
+
callOpts(scope));
|
|
995
|
+
|
|
927
996
|
forgetSettings();
|
|
928
997
|
const updated = JSON.parse(run.stdout) as Settings;
|
|
929
998
|
if (key.startsWith("vault.")) await lockNow(scope);
|
|
@@ -935,6 +1004,7 @@ function commandHandler(scope: Scope, bw: BwState) {
|
|
|
935
1004
|
}
|
|
936
1005
|
case "mode": {
|
|
937
1006
|
const [sub, hoursArg] = rest;
|
|
1007
|
+
if (!(await ensureUnlocked(scope, ctx))) return;
|
|
938
1008
|
if (!sub || sub === "get" || sub === "status") {
|
|
939
1009
|
try {
|
|
940
1010
|
const current = await cli.json<{ mode: string; hours: number; auto: boolean }>(["mode"]);
|
|
@@ -953,8 +1023,8 @@ function commandHandler(scope: Scope, bw: BwState) {
|
|
|
953
1023
|
}
|
|
954
1024
|
return;
|
|
955
1025
|
}
|
|
956
|
-
if (!["
|
|
957
|
-
note(ctx, tr("usage: /vault mode [
|
|
1026
|
+
if (!["every", "time", "never", "no-password", "every-time"].includes(sub)) {
|
|
1027
|
+
note(ctx, tr("usage: /vault mode [every|time|never] [hours]", "用法: /vault mode [every|time|never] [小时]"), "warning");
|
|
958
1028
|
return;
|
|
959
1029
|
}
|
|
960
1030
|
const args = ["mode", "set", sub];
|
|
@@ -970,9 +1040,9 @@ function commandHandler(scope: Scope, bw: BwState) {
|
|
|
970
1040
|
const how =
|
|
971
1041
|
result.mode === "never"
|
|
972
1042
|
? tr("no password from now on (the key is on disk: anything that can read your files can read every password in the store)", "以后免密(密钥已写盘,任何能读你文件的程序都能读到库里的密码)")
|
|
973
|
-
: result.mode === "
|
|
974
|
-
? tr(
|
|
975
|
-
: tr(
|
|
1043
|
+
: result.mode === "every"
|
|
1044
|
+
? tr("the password is asked on every call from now on; nothing that can open the store is kept", "以后每次调用都要密码;不留任何能打开库的东西")
|
|
1045
|
+
: tr(`the password is asked again every ${result.hours} hours from now on`, `以后每 ${result.hours} 小时要一次密码`);
|
|
976
1046
|
note(ctx, `mode → ${result.mode},${how}`);
|
|
977
1047
|
} catch (error) {
|
|
978
1048
|
note(ctx, `ai-vault: ${error instanceof CliError && error.denied ? tr("cancelled", "已取消") : describe(error)}`, "warning");
|
|
@@ -982,7 +1052,7 @@ function commandHandler(scope: Scope, bw: BwState) {
|
|
|
982
1052
|
case "list": {
|
|
983
1053
|
if (!(await ensureUnlocked(scope, ctx))) return;
|
|
984
1054
|
try {
|
|
985
|
-
const result = await cli.json<ListResult>(["list",
|
|
1055
|
+
const result = await cli.json<ListResult>(["list", ...tokenArgs(scope)], callOpts(scope));
|
|
986
1056
|
scope.items = result.count;
|
|
987
1057
|
const rows = result.items.map((i) => `${i.name}\t${i.username ?? ""}\t${i.uris[0] ?? ""}`);
|
|
988
1058
|
note(ctx, rows.join("\n") || "(empty)");
|
|
@@ -1026,9 +1096,9 @@ function commandHandler(scope: Scope, bw: BwState) {
|
|
|
1026
1096
|
note(ctx, tr("usage: /vault remove <name>", "用法: /vault remove <名称>"), "warning");
|
|
1027
1097
|
return;
|
|
1028
1098
|
}
|
|
1029
|
-
const args = ["remove", name,
|
|
1099
|
+
const args = ["remove", name, ...tokenArgs(scope)];
|
|
1030
1100
|
try {
|
|
1031
|
-
const result = await cli.json<RemovingResult>(args);
|
|
1101
|
+
const result = await cli.json<RemovingResult>(args, callOpts(scope));
|
|
1032
1102
|
if (result.removed) scope.items = Math.max(0, scope.items - 1);
|
|
1033
1103
|
setStatus(ctx, scope);
|
|
1034
1104
|
note(ctx, result.removed ? "removed" : "not found", result.removed ? "info" : "warning");
|
|
@@ -1040,7 +1110,7 @@ function commandHandler(scope: Scope, bw: BwState) {
|
|
|
1040
1110
|
const sure = await confirmWindow(dialogs(ctx), tr("ai-vault · delete entry", "ai-vault · 删除条目"), tr(`Delete "${forDialog(name)}"? This cannot be undone.`, `删除「${forDialog(name)}」?删除后无法恢复。`));
|
|
1041
1111
|
if (!sure) return;
|
|
1042
1112
|
try {
|
|
1043
|
-
const result = await cli.json<RemovingResult>([...args, "--yes"]);
|
|
1113
|
+
const result = await cli.json<RemovingResult>([...args, "--yes"], callOpts(scope));
|
|
1044
1114
|
if (result.removed) scope.items = Math.max(0, scope.items - 1);
|
|
1045
1115
|
setStatus(ctx, scope);
|
|
1046
1116
|
note(ctx, result.removed ? "removed" : "not found", result.removed ? "info" : "warning");
|
|
@@ -1060,7 +1130,7 @@ function commandHandler(scope: Scope, bw: BwState) {
|
|
|
1060
1130
|
note(ctx, tr("unlock first; usage: /vault grant <name> [minutes] (quote names with spaces)", "先解锁;用法: /vault grant <名称> [分钟](带空格的名称加引号)"), "warning");
|
|
1061
1131
|
return;
|
|
1062
1132
|
}
|
|
1063
|
-
const args = ["grant", name,
|
|
1133
|
+
const args = ["grant", name, ...tokenArgs(scope)];
|
|
1064
1134
|
if (minutes) args.push("--minutes", minutes);
|
|
1065
1135
|
try {
|
|
1066
1136
|
// A standing grant costs the master password, like a mode change.
|
|
@@ -1078,7 +1148,7 @@ function commandHandler(scope: Scope, bw: BwState) {
|
|
|
1078
1148
|
case "revoke": {
|
|
1079
1149
|
if (!(await ensureUnlocked(scope, ctx))) return;
|
|
1080
1150
|
const target = rest[0] === "all" ? "all" : rest.join(" ").trim();
|
|
1081
|
-
const args = ["revoke",
|
|
1151
|
+
const args = ["revoke", ...tokenArgs(scope)];
|
|
1082
1152
|
if (target === "all") args.push("--all");
|
|
1083
1153
|
else if (target) args.push(target);
|
|
1084
1154
|
else {
|
|
@@ -1115,9 +1185,9 @@ function commandHandler(scope: Scope, bw: BwState) {
|
|
|
1115
1185
|
return;
|
|
1116
1186
|
}
|
|
1117
1187
|
if (!(await ensureUnlocked(scope, ctx))) return;
|
|
1118
|
-
const args = ["import", path,
|
|
1188
|
+
const args = ["import", path, ...tokenArgs(scope)];
|
|
1119
1189
|
try {
|
|
1120
|
-
const result = await cli.json<SaveResult>(args);
|
|
1190
|
+
const result = await cli.json<SaveResult>(args, callOpts(scope));
|
|
1121
1191
|
scope.items += result.count;
|
|
1122
1192
|
setStatus(ctx, scope);
|
|
1123
1193
|
note(ctx, `imported ${result.count} login items`);
|
|
@@ -1133,7 +1203,7 @@ function commandHandler(scope: Scope, bw: BwState) {
|
|
|
1133
1203
|
);
|
|
1134
1204
|
if (!sure) return;
|
|
1135
1205
|
try {
|
|
1136
|
-
const result = await cli.json<SaveResult>([...args, "--yes"]);
|
|
1206
|
+
const result = await cli.json<SaveResult>([...args, "--yes"], callOpts(scope));
|
|
1137
1207
|
scope.items += result.count;
|
|
1138
1208
|
setStatus(ctx, scope);
|
|
1139
1209
|
note(ctx, `imported ${result.count} login items`);
|
|
@@ -24,7 +24,7 @@ export interface Settings {
|
|
|
24
24
|
}
|
|
25
25
|
|
|
26
26
|
export const DEFAULT_SETTINGS: Settings = {
|
|
27
|
-
vault: { unlock: "
|
|
27
|
+
vault: { unlock: "time", hours: 4, confirm: false, auto: false },
|
|
28
28
|
bitwarden: { unlock: "session", hours: 8, import: "ask", persisted: false, expiresAt: null },
|
|
29
29
|
ente: { unlock: "session", hours: 8, persisted: false, expiresAt: null },
|
|
30
30
|
};
|
|
@@ -50,6 +50,8 @@ let cache: { at: number; value: Settings } | undefined;
|
|
|
50
50
|
* the binding that unlocked sets this before asking.
|
|
51
51
|
*/
|
|
52
52
|
let sessionToken: string | undefined;
|
|
53
|
+
/** In `every` mode there is no token: the settings are read with the call's password. */
|
|
54
|
+
let everyPassword: string | undefined;
|
|
53
55
|
|
|
54
56
|
export function setSettingsToken(token: string | undefined): void {
|
|
55
57
|
if (token !== sessionToken) {
|
|
@@ -58,17 +60,27 @@ export function setSettingsToken(token: string | undefined): void {
|
|
|
58
60
|
}
|
|
59
61
|
}
|
|
60
62
|
|
|
63
|
+
/** The password an `every` call was opened with, for reading the settings under it. */
|
|
64
|
+
export function setEveryPassword(password: string | undefined): void {
|
|
65
|
+
everyPassword = password;
|
|
66
|
+
}
|
|
67
|
+
|
|
61
68
|
export function settingsToken(): string | undefined {
|
|
62
69
|
return sessionToken;
|
|
63
70
|
}
|
|
64
71
|
|
|
72
|
+
/** CLI options for a settings read under whatever this binding holds. */
|
|
73
|
+
export function settingsOpts(): { password?: string } {
|
|
74
|
+
return everyPassword !== undefined ? { password: everyPassword } : {};
|
|
75
|
+
}
|
|
76
|
+
|
|
65
77
|
/**
|
|
66
78
|
* Settings change rarely, so a short cache keeps a Bitwarden call from paying
|
|
67
79
|
* for the read. `/vault settings ...` drops it explicitly.
|
|
68
80
|
*/
|
|
69
81
|
export async function getSettings(signal?: AbortSignal, options: { fresh?: boolean } = {}): Promise<Settings> {
|
|
70
82
|
if (!options.fresh && cache && Date.now() - cache.at < 30_000) return cache.value;
|
|
71
|
-
const value = await settingsCli().json<Settings>(["settings", ...(sessionToken ? ["--token", sessionToken] : [])], { signal });
|
|
83
|
+
const value = await settingsCli().json<Settings>(["settings", ...(sessionToken ? ["--token", sessionToken] : [])], { signal, ...settingsOpts() });
|
|
72
84
|
cache = { at: Date.now(), value };
|
|
73
85
|
return value;
|
|
74
86
|
}
|
package/test/cli.sh
CHANGED
|
@@ -253,13 +253,16 @@ grep -q '"confirm"' "$AI_VAULT_DIR/store.json" && bad "settings are readable in
|
|
|
253
253
|
# protection, so the attack gains nothing.
|
|
254
254
|
echo '{"vault":{"unlock":"session","hours":8,"confirm":false}}' >"$AI_VAULT_DIR/config.json"
|
|
255
255
|
TKH=$(printf 'correct horse' | env -u AI_VAULT_HOST -u AI_VAULT_HOST_SECRET "$BIN" unlock --password-stdin --json | json token)
|
|
256
|
+
[[ -n "$TKH" ]] && ok "the unlock after a legacy file still mints a token (mode read as time, not session)" || bad "no token: the legacy session mode came through as per-process"
|
|
256
257
|
setting vault.confirm --token "$TKH" >"$TMP/c2"
|
|
257
258
|
[[ "$(setting_value "$TMP/c2")" == "true" ]] && ok "the legacy file's confirm=false did not make it in" || bad "confirm=false was migrated from the file"
|
|
259
|
+
setting vault.unlock --token "$TKH" >"$TMP/c2s"
|
|
260
|
+
[[ "$(setting_value "$TMP/c2s")" == "time" ]] && ok "the legacy file's session is read as time" || bad "session was carried into the store"
|
|
258
261
|
[[ -f "$AI_VAULT_DIR/config.json" ]] && bad "config.json still there" || ok "the legacy file was removed after migration"
|
|
259
262
|
echo '{"vault":{"unlock":"never","hours":8,"confirm":true}}' >"$AI_VAULT_DIR/config.json"
|
|
260
263
|
TKH=$(printf 'correct horse' | env -u AI_VAULT_HOST -u AI_VAULT_HOST_SECRET "$BIN" unlock --password-stdin --json | python3 -c 'import json,sys;d=json.load(sys.stdin);print(d["token"] if not d.get("auto") else "")')
|
|
261
264
|
setting vault.unlock --token "$TKH" >"$TMP/c2b"
|
|
262
|
-
[[ "$(setting_value "$TMP/c2b")" == "
|
|
265
|
+
[[ "$(setting_value "$TMP/c2b")" == "time" ]] && ok "the legacy file's unlock=never did not make it in either (read as time)" || bad "unlock=never was migrated from the file"
|
|
263
266
|
# Flipping one byte of the store (where the settings now live) is a tamper.
|
|
264
267
|
cp "$AI_VAULT_DIR/store.json" "$TMP/store.bak"
|
|
265
268
|
python3 -c "
|
|
@@ -276,6 +279,65 @@ setting vault.confirm true --token "$TKH" >"$TMP/c4"
|
|
|
276
279
|
setting vault.confirm --token "$TKH" >"$TMP/c4v"
|
|
277
280
|
[[ "$(setting_value "$TMP/c4v")" == "true" ]] && ok "turning it back on needs no password" || bad "confirm could not be turned back on"
|
|
278
281
|
|
|
282
|
+
echo "== every mode =="
|
|
283
|
+
# On its own store, so the main one stays in the mode the later sections expect.
|
|
284
|
+
MAIN_DIR="$AI_VAULT_DIR"; MAIN_RT="$XDG_RUNTIME_DIR"
|
|
285
|
+
export AI_VAULT_DIR="$TMP/store-every" XDG_RUNTIME_DIR="$TMP/runtime-every"
|
|
286
|
+
mkdir -p "$XDG_RUNTIME_DIR"
|
|
287
|
+
printf 'correct horse\n' | env -u AI_VAULT_HOST -u AI_VAULT_HOST_SECRET "$BIN" init --password-stdin --json >/dev/null
|
|
288
|
+
# Still in time mode here: a token opens the store, stdin carries the entry's password.
|
|
289
|
+
TE=$(printf 'correct horse' | env -u AI_VAULT_HOST -u AI_VAULT_HOST_SECRET "$BIN" unlock --password-stdin --json | json token)
|
|
290
|
+
printf 'SECR3T\n' | env -u AI_VAULT_HOST -u AI_VAULT_HOST_SECRET "$BIN" add --name Login --username u --password-stdin --yes --token "$TE" --json >/dev/null
|
|
291
|
+
# The strict end: nothing that opens the store is kept; each call brings the password.
|
|
292
|
+
TH=$(printf 'correct horse' | env -u AI_VAULT_HOST -u AI_VAULT_HOST_SECRET "$BIN" unlock --password-stdin --json | json token)
|
|
293
|
+
setting vault.unlock every --token "$TH" >"$TMP/e0"
|
|
294
|
+
grep -q '"unlock": *"every"' "$TMP/e0" && ok "switched to every" || bad "could not switch to every: $(head -c 120 "$TMP/e0")"
|
|
295
|
+
count_ours() { python3 - "$AI_VAULT_DIR/store.json" "$XDG_RUNTIME_DIR/ai-vault/sessions" <<'PY'
|
|
296
|
+
import json,hashlib,sys,glob,os
|
|
297
|
+
sid=hashlib.sha256(json.load(open(sys.argv[1]))["salt"].encode()).hexdigest()[:24]
|
|
298
|
+
print(sum(1 for f in glob.glob(sys.argv[2]+"/*.json") if (lambda d: d and d.get("storeId")==sid)(json.load(open(f)))))
|
|
299
|
+
PY
|
|
300
|
+
}
|
|
301
|
+
[[ "$(count_ours)" == "0" ]] && ok "every live token of this store is gone" || bad "tokens survived the switch"
|
|
302
|
+
check "the old token is dead" 5 "$BIN" status --token "$TH"
|
|
303
|
+
check "no password -> needs-ui (exit 3)" 3 "$BIN" list
|
|
304
|
+
printf 'correct horse\n' | env -u AI_VAULT_HOST -u AI_VAULT_HOST_SECRET "$BIN" list --password-stdin --json >"$TMP/e1"
|
|
305
|
+
[[ $? -eq 0 ]] && ok "the password with the call opens it" || bad "list with password failed"
|
|
306
|
+
AI_VAULT_PASSWORD='correct horse' env -u AI_VAULT_HOST -u AI_VAULT_HOST_SECRET "$BIN" status --json >"$TMP/e2"
|
|
307
|
+
[[ $? -eq 0 ]] && ok "a host may pass it as AI_VAULT_PASSWORD" || bad "env password failed"
|
|
308
|
+
grep -q '"mode":"every"' "$TMP/e2" && ok "status reports the mode" || bad "mode not reported"
|
|
309
|
+
[[ "$(count_ours)" == "0" ]] && ok "still nothing on disk after two calls" || bad "a call wrote a token"
|
|
310
|
+
printf 'correct horse\n' | env -u AI_VAULT_HOST -u AI_VAULT_HOST_SECRET "$BIN" get Login --password-stdin --json >"$TMP/e3" 2>"$TMP/e3err"
|
|
311
|
+
[[ $? -eq 0 ]] && ok "a read goes through on the call's password" || bad "get failed: $(head -1 "$TMP/e3err")"
|
|
312
|
+
grep -q '"via": *"every"' "$TMP/e3" && ok "labelled via: every" || bad "via is not every"
|
|
313
|
+
printf 'wrong\n' | env -u AI_VAULT_HOST -u AI_VAULT_HOST_SECRET "$BIN" list --password-stdin >/dev/null 2>&1
|
|
314
|
+
[[ $? -eq 5 ]] && ok "a wrong password is an auth error" || bad "wrong password not refused"
|
|
315
|
+
printf 'wrong\n' | env -u AI_VAULT_HOST -u AI_VAULT_HOST_SECRET "$BIN" settings vault.unlock time --password-stdin >/dev/null 2>&1
|
|
316
|
+
[[ $? -eq 5 ]] && ok "leaving every with a wrong password is refused" || bad "left every with a wrong password"
|
|
317
|
+
printf 'correct horse\n' | env -u AI_VAULT_HOST -u AI_VAULT_HOST_SECRET "$BIN" settings vault.unlock time --password-stdin --json >"$TMP/e4"
|
|
318
|
+
[[ "$(grep -o '"unlock":"time"' "$TMP/e4" | head -1)" ]] && ok "leaving every with the right password, asked once" || bad "could not leave every"
|
|
319
|
+
printf 'correct horse' | env -u AI_VAULT_HOST -u AI_VAULT_HOST_SECRET "$BIN" unlock --password-stdin --json | python3 -c 'import json,sys;d=json.load(sys.stdin);print(" back to time: token minted:", bool(d.get("token")))'
|
|
320
|
+
# tamper: the plaintext hint only says "ask"; clearing it must not open anything.
|
|
321
|
+
# Enter `every` for real, and prove it took before tampering.
|
|
322
|
+
TKH=$(printf 'correct horse' | env -u AI_VAULT_HOST -u AI_VAULT_HOST_SECRET "$BIN" unlock --password-stdin --json | json token)
|
|
323
|
+
setting vault.unlock every --token "$TKH" >"$TMP/ev"
|
|
324
|
+
grep -q '"unlock": *"every"' "$TMP/ev" && ok "entered every" || bad "could not enter every for the hint test"
|
|
325
|
+
grep -q '"askEvery": *true' "$AI_VAULT_DIR/store.json" && ok "the hint is set" || bad "hint missing in every mode"
|
|
326
|
+
# and back, through the real path (every -> time needs the password once) —
|
|
327
|
+
# BEFORE tampering, since a cleared hint leaves the CLI unable to ask.
|
|
328
|
+
printf 'correct horse\n' | env -u AI_VAULT_HOST -u AI_VAULT_HOST_SECRET "$BIN" settings vault.unlock time --password-stdin --json >"$TMP/back" 2>"$TMP/backerr"
|
|
329
|
+
grep -q '"unlock": *"time"' "$TMP/back" && ok "left every with one password" || bad "could not leave every: $(head -c 160 "$TMP/backerr")"
|
|
330
|
+
# Now the tamper, on a throwaway copy of the store: enter every, clear the hint.
|
|
331
|
+
TKH=$(printf 'correct horse' | env -u AI_VAULT_HOST -u AI_VAULT_HOST_SECRET "$BIN" unlock --password-stdin --json | json token)
|
|
332
|
+
setting vault.unlock every --token "$TKH" >/dev/null
|
|
333
|
+
cp "$AI_VAULT_DIR/store.json" "$TMP/store.bak2"
|
|
334
|
+
python3 -c "import json;p='$AI_VAULT_DIR/store.json';d=json.load(open(p));d.pop('askEvery',None);json.dump(d,open(p,'w'))"
|
|
335
|
+
check "hint cleared: the CLI stops asking and finds no token (nothing lowered)" 5 bash -c "printf 'correct horse\n' | env -u AI_VAULT_HOST -u AI_VAULT_HOST_SECRET '$BIN' list --password-stdin"
|
|
336
|
+
check "hint cleared: a bare call is locked too" 5 bash -c "env -u AI_VAULT_HOST -u AI_VAULT_HOST_SECRET '$BIN' list --json"
|
|
337
|
+
cp "$TMP/store.bak2" "$AI_VAULT_DIR/store.json"
|
|
338
|
+
printf 'correct horse\n' | env -u AI_VAULT_HOST -u AI_VAULT_HOST_SECRET "$BIN" settings vault.unlock time --password-stdin --json >/dev/null
|
|
339
|
+
export AI_VAULT_DIR="$MAIN_DIR" XDG_RUNTIME_DIR="$MAIN_RT"
|
|
340
|
+
|
|
279
341
|
echo "== rekey (L2) =="
|
|
280
342
|
OLD_N=$(python3 -c "import json;print(json.load(open('$AI_VAULT_DIR/store.json'))['kdf']['N'])")
|
|
281
343
|
check "rekey with the password" 0 bash -c "printf 'correct horse' | '$BIN' rekey --password-stdin --json"
|
|
@@ -309,7 +371,10 @@ d = json.load(open(sys.argv[1]))
|
|
|
309
371
|
assert d["mode"] == "never" and d["auto"] is True, d
|
|
310
372
|
PY
|
|
311
373
|
check "back to session mode" 0 bash -c "printf 'correct horse\n' | env -u AI_VAULT_HOST -u AI_VAULT_HOST_SECRET '$BIN' mode set session --password-stdin --token '$TOKEN_HUMAN' --json"
|
|
312
|
-
|
|
374
|
+
# No `session` mode any more. Back in `time`, a bare call adopts the unlock
|
|
375
|
+
# that is still on disk (that is what `time` means) — not a lock, not a prompt.
|
|
376
|
+
TKH2=$(printf 'correct horse' | env -u AI_VAULT_HOST -u AI_VAULT_HOST_SECRET "$BIN" unlock --password-stdin --json | json token)
|
|
377
|
+
check "back in time: a bare call adopts the existing unlock" 0 bash -c "env -u AI_VAULT_HOST -u AI_VAULT_HOST_SECRET '$BIN' status --json"
|
|
313
378
|
|
|
314
379
|
echo "== settings =="
|
|
315
380
|
check "settings prints everything" 0 bash -c "printf 'correct horse\n' | env -u AI_VAULT_HOST -u AI_VAULT_HOST_SECRET '$BIN' settings --password-stdin --token '$TOKEN_HUMAN' --json"
|