@xiaolikt/ai-vault 0.10.0 → 0.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/Cargo.lock +1 -1
- package/README.md +45 -7
- package/README.zh.md +34 -5
- package/crates/ai-vault/Cargo.toml +1 -1
- package/crates/ai-vault/src/cli.rs +441 -119
- package/crates/ai-vault/src/config.rs +41 -12
- package/crates/ai-vault/src/crypto.rs +69 -18
- package/crates/ai-vault/src/import.rs +85 -48
- package/crates/ai-vault/src/sealed.rs +1 -9
- package/crates/ai-vault/src/session.rs +79 -22
- package/crates/ai-vault/src/store.rs +237 -5
- package/package.json +4 -4
- package/packages/pi-ai-vault/README.md +1 -1
- package/packages/pi-ai-vault/README.zh.md +1 -1
- package/packages/pi-ai-vault/package.json +2 -2
- package/packages/pi-ai-vault/src/bitwarden.ts +42 -26
- package/packages/pi-ai-vault/src/cli.ts +9 -3
- package/packages/pi-ai-vault/src/import-map.ts +166 -58
- package/packages/pi-ai-vault/src/index.ts +172 -48
- package/packages/pi-ai-vault/src/settings.ts +37 -7
- package/packages/pi-ai-vault/src/types.ts +52 -0
- package/test/cli.sh +112 -24
- package/tests/bitwarden-tools.test.mjs +2 -2
- package/tests/ente.test.mjs +25 -6
- package/tests/helpers.mjs +36 -0
- package/tests/import-map.test.mjs +75 -38
- package/tests/mocks/bin/bw +5 -1
- package/tests/vault-cli.test.mjs +77 -19
|
@@ -15,19 +15,21 @@ import { tr } from "./i18n.js";
|
|
|
15
15
|
import type { ExtensionAPI, ExtensionCommandContext, ExtensionToolContext, ToolDefinition } from "@earendil-works/pi-coding-agent";
|
|
16
16
|
import { Type } from "typebox";
|
|
17
17
|
import {
|
|
18
|
-
|
|
18
|
+
lookupBitwardenItem,
|
|
19
19
|
newBwState,
|
|
20
|
-
|
|
20
|
+
pullBitwardenItems,
|
|
21
21
|
queryBitwarden,
|
|
22
22
|
registerBitwarden,
|
|
23
23
|
type BitwardenMeta,
|
|
24
24
|
type BwState,
|
|
25
25
|
} from "./bitwarden.js";
|
|
26
|
-
import { CliError
|
|
26
|
+
import { CliError } from "./cli.js";
|
|
27
|
+
import { ITEM_TYPES, isSecretField, parseItemType } from "./import-map.js";
|
|
28
|
+
import type { Draft, ItemType } from "./types.js";
|
|
27
29
|
import { registerEnte } from "./ente.js";
|
|
28
30
|
import { isOmpHost, onSessionLeave, sessionLabel, subagentId, withTier } from "./host.js";
|
|
29
31
|
import { confirmWindow, forDialog, promptSecret, promptText, type PromptHost } from "./prompt.js";
|
|
30
|
-
import { forgetSettings, getSettingsSafe, type Settings } from "./settings.js";
|
|
32
|
+
import { forgetSettings, getSettingsSafe, setSettingsToken, settingsCli, settingsToken, type Settings } from "./settings.js";
|
|
31
33
|
|
|
32
34
|
type Ctx = ExtensionToolContext | ExtensionCommandContext;
|
|
33
35
|
|
|
@@ -98,7 +100,7 @@ interface Scope {
|
|
|
98
100
|
unlocking?: Promise<boolean>;
|
|
99
101
|
}
|
|
100
102
|
|
|
101
|
-
const cli =
|
|
103
|
+
const cli = settingsCli();
|
|
102
104
|
|
|
103
105
|
const CLI_MISSING =
|
|
104
106
|
tr("ai-vault CLI not found. Install it once for a machine-wide store: cargo install --path <repo>/crates/ai-vault (or point AI_VAULT_BIN at a compiled binary)", "ai-vault CLI 没找到。装一次就有全机共享的库:cargo install --path <repo>/crates/ai-vault(或用 AI_VAULT_BIN 指向编译好的二进制)");
|
|
@@ -146,6 +148,8 @@ async function lockNow(scope: Scope): Promise<void> {
|
|
|
146
148
|
scope.token = undefined;
|
|
147
149
|
scope.epoch++;
|
|
148
150
|
scope.items = 0;
|
|
151
|
+
setSettingsToken(undefined);
|
|
152
|
+
forgetSettings();
|
|
149
153
|
if (!token || !cli.available) return;
|
|
150
154
|
try {
|
|
151
155
|
await cli.run(["lock", "--token", token]);
|
|
@@ -172,6 +176,7 @@ async function ensureUnlocked(scope: Scope, ctx: Ctx, signal?: AbortSignal): Pro
|
|
|
172
176
|
scope.items = status.items;
|
|
173
177
|
scope.mode = status.mode;
|
|
174
178
|
scope.auto = false;
|
|
179
|
+
setSettingsToken(scope.token);
|
|
175
180
|
return true;
|
|
176
181
|
} catch (error) {
|
|
177
182
|
if (!(error instanceof CliError) || !error.auth) {
|
|
@@ -192,6 +197,7 @@ async function ensureUnlocked(scope: Scope, ctx: Ctx, signal?: AbortSignal): Pro
|
|
|
192
197
|
scope.items = status.items;
|
|
193
198
|
scope.mode = status.mode;
|
|
194
199
|
scope.auto = status.auto;
|
|
200
|
+
setSettingsToken(undefined);
|
|
195
201
|
return true;
|
|
196
202
|
} catch (error) {
|
|
197
203
|
if (error instanceof CliError && /not initialized/i.test(error.message)) {
|
|
@@ -235,6 +241,7 @@ async function ensureUnlocked(scope: Scope, ctx: Ctx, signal?: AbortSignal): Pro
|
|
|
235
241
|
// per-binding token would bring back a confirm window on every read.
|
|
236
242
|
scope.token = result.mode === "never" ? undefined : result.token;
|
|
237
243
|
scope.items = result.items;
|
|
244
|
+
setSettingsToken(scope.token);
|
|
238
245
|
return true;
|
|
239
246
|
} catch (error) {
|
|
240
247
|
if (error instanceof CliError && error.auth) {
|
|
@@ -308,44 +315,34 @@ async function bitwardenFallback(
|
|
|
308
315
|
const missing = localMiss;
|
|
309
316
|
let hit;
|
|
310
317
|
try {
|
|
311
|
-
hit = await
|
|
318
|
+
hit = await lookupBitwardenItem(bw, ctx, name, signal);
|
|
312
319
|
} catch (error) {
|
|
313
320
|
return fail(`${missing} — the Bitwarden lookup failed: ${describe(error)}`);
|
|
314
321
|
}
|
|
315
322
|
if (!hit) return fail(`${missing} — not in Bitwarden either${reason ? ` (reason: ${reason})` : ""}`);
|
|
323
|
+
const draft = hit.draft;
|
|
324
|
+
const secret = draft.type === "login" ? draft.password : (draft.data?.[ITEM_TYPES[draft.type].primary ?? ""] ?? "");
|
|
316
325
|
|
|
317
326
|
const asValue = (via: string): ToolOutcome => ({
|
|
318
327
|
content: [
|
|
319
328
|
{
|
|
320
329
|
type: "text" as const,
|
|
321
|
-
text: JSON.stringify(
|
|
322
|
-
{ name: hit.name, username: hit.username || undefined, password: hit.password, uris: hit.uris, via },
|
|
323
|
-
null,
|
|
324
|
-
1,
|
|
325
|
-
),
|
|
330
|
+
text: JSON.stringify({ ...draft, password: secret ?? draft.password, via }, null, 1),
|
|
326
331
|
},
|
|
327
332
|
],
|
|
328
|
-
details: { item:
|
|
333
|
+
details: { item: draft.name, via },
|
|
329
334
|
});
|
|
330
335
|
|
|
331
336
|
const importIt = async (): Promise<ToolOutcome> => {
|
|
332
337
|
try {
|
|
333
338
|
const saved = await cli.json<SaveResult>(["save", "--yes", ...tokenArgs(scope)], {
|
|
334
|
-
stdin: JSON.stringify([
|
|
335
|
-
{
|
|
336
|
-
name: hit.name,
|
|
337
|
-
username: hit.username || undefined,
|
|
338
|
-
password: hit.password,
|
|
339
|
-
uris: hit.uris,
|
|
340
|
-
source: { kind: "bitwarden", id: hit.id },
|
|
341
|
-
},
|
|
342
|
-
]),
|
|
339
|
+
stdin: JSON.stringify([draft]),
|
|
343
340
|
signal,
|
|
344
341
|
});
|
|
345
342
|
scope.items += saved.count;
|
|
346
343
|
setStatus(ctx, scope);
|
|
347
344
|
} catch (error) {
|
|
348
|
-
return fail(`found "${
|
|
345
|
+
return fail(`found "${draft.name}" in Bitwarden but could not import it: ${describe(error)}`);
|
|
349
346
|
}
|
|
350
347
|
return asValue("imported-from-bitwarden");
|
|
351
348
|
};
|
|
@@ -356,20 +353,25 @@ async function bitwardenFallback(
|
|
|
356
353
|
return importIt();
|
|
357
354
|
}
|
|
358
355
|
|
|
359
|
-
const label = `${hit.name}${hit.username ? ` user:${hit.username}` : ""}`;
|
|
360
356
|
const allow = await confirmWindow(
|
|
361
357
|
dialogs(ctx),
|
|
362
358
|
tr("pi-ai-vault · found in Bitwarden", "pi-ai-vault · Bitwarden 里找到"),
|
|
363
|
-
tr(
|
|
359
|
+
tr(
|
|
360
|
+
`Not in the local store as "${forDialog(name)}", but Bitwarden has:\n${forDialog(hit.label)}\n\nRead it this once?`,
|
|
361
|
+
`本地库没有「${forDialog(name)}」,Bitwarden 里有:\n${forDialog(hit.label)}\n\n读取这一次吗?`,
|
|
362
|
+
),
|
|
364
363
|
signal,
|
|
365
364
|
);
|
|
366
|
-
if (!allow) return fail(`user denied reading "${
|
|
365
|
+
if (!allow) return fail(`user denied reading "${draft.name}" from Bitwarden — do not retry`, true);
|
|
367
366
|
if (policy === "never") return asValue("bitwarden-once");
|
|
368
367
|
|
|
369
368
|
const confirmed = await confirmWindow(
|
|
370
369
|
dialogs(ctx),
|
|
371
370
|
tr("pi-ai-vault · import into ai-vault", "pi-ai-vault · 导入到 ai-vault"),
|
|
372
|
-
tr(
|
|
371
|
+
tr(
|
|
372
|
+
`Write "${forDialog(draft.name)}" into ai-vault?\n\nAllow → read from the local store from now on (no password under the current unlock policy)\nDeny → use it once only; nothing is written to the local store`,
|
|
373
|
+
`把「${forDialog(draft.name)}」写进 ai-vault 吗?\n\n允许 → 以后直接读本地库(按当前解锁模式,可能免密)\n拒绝 → 只用这一次,不写入本地库`,
|
|
374
|
+
),
|
|
373
375
|
signal,
|
|
374
376
|
);
|
|
375
377
|
return confirmed ? importIt() : asValue("bitwarden-once");
|
|
@@ -446,26 +448,62 @@ function vaultGetTool(scope: Scope, bw: BwState): ToolDefinition<typeof vaultGet
|
|
|
446
448
|
|
|
447
449
|
const vaultAddParams = Type.Object({
|
|
448
450
|
name: Type.String({ description: "Entry name to create or update, e.g. 'github'" }),
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
451
|
+
type: Type.Optional(
|
|
452
|
+
Type.String({
|
|
453
|
+
description:
|
|
454
|
+
"Item type, as in Bitwarden: login (default), note, card, identity, sshkey, bankaccount, driverslicense, passport. " +
|
|
455
|
+
"A note's content goes in `notes`.",
|
|
456
|
+
}),
|
|
457
|
+
),
|
|
458
|
+
username: Type.Optional(Type.String({ description: "Login: account username. Omit to let the user type it in a dialog." })),
|
|
459
|
+
uri: Type.Optional(Type.String({ description: "Login: site or host URI" })),
|
|
460
|
+
notes: Type.Optional(Type.String({ description: "Notes shared by every type. For a `note` entry this is its content." })),
|
|
461
|
+
fields: Type.Optional(
|
|
462
|
+
Type.Record(
|
|
463
|
+
Type.String(),
|
|
464
|
+
Type.Optional(Type.String()),
|
|
465
|
+
{
|
|
466
|
+
description:
|
|
467
|
+
"The type's own fields by Bitwarden's names (card: cardholderName, brand, number, expMonth, expYear, code; " +
|
|
468
|
+
"sshkey: publicKey, privateKey, keyFingerprint; identity: firstName, lastName, email, …). " +
|
|
469
|
+
"Give a non-secret field as text; give a secret field (password, code, number, privateKey, pin, ssn…) " +
|
|
470
|
+
"as null/undefined so the user types it in a dialog. NEVER put a secret value here.",
|
|
471
|
+
},
|
|
472
|
+
),
|
|
473
|
+
),
|
|
452
474
|
});
|
|
453
475
|
function vaultAddTool(scope: Scope): ToolDefinition<typeof vaultAddParams, { ok?: boolean; item?: string }> {
|
|
454
476
|
const tool: ToolDefinition<typeof vaultAddParams, { ok?: boolean; item?: string }> = {
|
|
455
477
|
name: "vault_add",
|
|
456
478
|
label: "Vault: store a secret via dialog",
|
|
457
479
|
description:
|
|
458
|
-
"Create or update an entry in the machine-wide ai-vault store
|
|
459
|
-
"
|
|
460
|
-
"
|
|
480
|
+
"Create or update an entry of any Bitwarden type in the machine-wide ai-vault store (login, note, card, identity, sshkey, " +
|
|
481
|
+
"bankaccount, driverslicense, passport). You supply the name, the type and its non-secret fields. " +
|
|
482
|
+
"Secret fields (password, card number and code, private key, PIN, SSN…) are typed by the user in a desktop window: " +
|
|
483
|
+
"leave them empty, they are NEVER accepted from you and NEVER returned. Do not ask the user to paste a secret into the chat.",
|
|
461
484
|
promptSnippet: "Save a local vault entry; the user types the password in a window.",
|
|
462
485
|
parameters: vaultAddParams,
|
|
463
486
|
async execute(_id, params, signal, _onUpdate, ctx) {
|
|
487
|
+
const kind = parseItemType(params.type);
|
|
488
|
+
if (!kind) {
|
|
489
|
+
return fail(`unknown type "${params.type}" — login, note, card, identity, sshkey, bankaccount, driverslicense, passport`);
|
|
490
|
+
}
|
|
491
|
+
// A secret field the model filled in is refused rather than stored:
|
|
492
|
+
// only the user types secrets, in a dialog.
|
|
493
|
+
const fields: Record<string, string | undefined> = {};
|
|
494
|
+
for (const [field, value] of Object.entries(params.fields ?? {})) {
|
|
495
|
+
if (value !== undefined && value !== "" && isSecretField(kind, field)) {
|
|
496
|
+
return fail(`"${field}" is a secret field: leave it empty so the user types it in a dialog`);
|
|
497
|
+
}
|
|
498
|
+
fields[field] = value === "" ? undefined : value;
|
|
499
|
+
}
|
|
464
500
|
const result = await saveLocalEntry(scope, ctx, {
|
|
465
501
|
name: params.name,
|
|
502
|
+
type: kind,
|
|
466
503
|
username: params.username,
|
|
467
504
|
uri: params.uri,
|
|
468
505
|
notes: params.notes,
|
|
506
|
+
fields,
|
|
469
507
|
signal,
|
|
470
508
|
});
|
|
471
509
|
const ok = result.startsWith("saved ");
|
|
@@ -508,9 +546,12 @@ function vaultImportTool(scope: Scope, bw: BwState): ToolDefinition<typeof vault
|
|
|
508
546
|
|
|
509
547
|
interface SaveRequest {
|
|
510
548
|
name?: string;
|
|
549
|
+
type?: ItemType;
|
|
511
550
|
username?: string;
|
|
512
551
|
uri?: string;
|
|
513
552
|
notes?: string;
|
|
553
|
+
/** The type's own fields, NAME=VALUE; a value of `undefined` means "typed in a dialog". */
|
|
554
|
+
fields?: Record<string, string | undefined>;
|
|
514
555
|
signal?: AbortSignal;
|
|
515
556
|
}
|
|
516
557
|
|
|
@@ -524,18 +565,33 @@ async function saveLocalEntry(scope: Scope, ctx: Ctx, req: SaveRequest): Promise
|
|
|
524
565
|
}
|
|
525
566
|
if (!name) return "cancelled: no entry name";
|
|
526
567
|
|
|
527
|
-
const
|
|
568
|
+
const kind = req.type ?? "login";
|
|
569
|
+
const args = ["add", "--name", name, "--type", kind, "--token", scope.token!];
|
|
528
570
|
if (req.username !== undefined) args.push("--username", req.username);
|
|
529
571
|
if (req.uri?.trim()) args.push("--uri", req.uri.trim());
|
|
530
572
|
if (req.notes?.trim()) args.push("--notes", req.notes.trim());
|
|
531
|
-
|
|
532
|
-
|
|
573
|
+
const secrets = new Map<string, string>();
|
|
574
|
+
const shown: string[] = [];
|
|
575
|
+
for (const [field, value] of Object.entries(req.fields ?? {})) {
|
|
576
|
+
if (value === undefined) shown.push(`${field} ••••`);
|
|
577
|
+
else {
|
|
578
|
+
args.push("--field", `${field}=${value}`);
|
|
579
|
+
shown.push(`${field} ${isSecretField(kind, field) ? "••••" : forDialog(value, 120)}`);
|
|
580
|
+
}
|
|
581
|
+
}
|
|
582
|
+
const flush = () => {
|
|
583
|
+
// --secret args are re-added on every attempt: the CLI is stateless.
|
|
584
|
+
for (let i = args.length - 1; i >= 0; i--) if (args[i] === "--secret") args.splice(i, 2);
|
|
585
|
+
for (const [field, value] of secrets) args.push("--secret", `${field}=${value}`);
|
|
586
|
+
};
|
|
587
|
+
for (let attempt = 0; attempt < 8; attempt++) {
|
|
588
|
+
flush();
|
|
533
589
|
try {
|
|
534
|
-
const run = await cli.run([...args, "--json"], {
|
|
535
|
-
const saved = JSON.parse(run.stdout) as { item?: string; created?: boolean };
|
|
590
|
+
const run = await cli.run([...args, "--json"], { signal: req.signal });
|
|
591
|
+
const saved = JSON.parse(run.stdout) as { item?: string; created?: boolean; type?: string };
|
|
536
592
|
if (saved.created) scope.items += 1;
|
|
537
593
|
setStatus(ctx, scope);
|
|
538
|
-
return `saved "${saved.item ?? name}" (
|
|
594
|
+
return `saved "${saved.item ?? name}" as a ${saved.type ?? kind} (hidden fields entered in dialogs, not shown)`;
|
|
539
595
|
} catch (error) {
|
|
540
596
|
if (!(error instanceof CliError) || !error.needsUi) {
|
|
541
597
|
if (error instanceof CliError && error.auth) scope.token = undefined;
|
|
@@ -543,6 +599,7 @@ async function saveLocalEntry(scope: Scope, ctx: Ctx, req: SaveRequest): Promise
|
|
|
543
599
|
}
|
|
544
600
|
if (error.needsUi === "confirm") {
|
|
545
601
|
const meta = [
|
|
602
|
+
...shown,
|
|
546
603
|
req.username?.trim() ? tr(`Username: ${forDialog(req.username, 60)}`, `用户名: ${forDialog(req.username, 60)}`) : "",
|
|
547
604
|
req.uri?.trim() ? `URI: ${forDialog(req.uri, 120)}` : "",
|
|
548
605
|
req.notes?.trim() ? tr(`Notes: ${forDialog(req.notes, 120)}`, `备注: ${forDialog(req.notes, 120)}`) : "",
|
|
@@ -552,7 +609,10 @@ async function saveLocalEntry(scope: Scope, ctx: Ctx, req: SaveRequest): Promise
|
|
|
552
609
|
const ok = await confirmWindow(
|
|
553
610
|
dialogs(ctx),
|
|
554
611
|
tr("ai-vault · save to local store", "ai-vault · 保存到本地库"),
|
|
555
|
-
tr(
|
|
612
|
+
tr(
|
|
613
|
+
`Save the ${kind} entry "${forDialog(name)}".${meta ? `\n${meta}` : ""}\nA window opens next for each hidden field. Nothing enters the conversation.`,
|
|
614
|
+
`保存${kind}条目「${forDialog(name)}」。${meta ? `\n${meta}` : ""}\n接下来每个隐藏字段弹一个窗口。密码不会进入对话。`,
|
|
615
|
+
),
|
|
556
616
|
req.signal,
|
|
557
617
|
);
|
|
558
618
|
if (!ok) return `user denied saving "${name}"`;
|
|
@@ -565,10 +625,11 @@ async function saveLocalEntry(scope: Scope, ctx: Ctx, req: SaveRequest): Promise
|
|
|
565
625
|
args.push("--username", entered);
|
|
566
626
|
continue;
|
|
567
627
|
}
|
|
568
|
-
|
|
628
|
+
// needsUi === "password": one hidden field at a time, named by the CLI.
|
|
629
|
+
const field = error.field ?? ITEM_TYPES[kind].primary ?? "password";
|
|
630
|
+
const password = await promptSecret(dialogs(ctx), tr("ai-vault · password", "ai-vault · 密码"), `${name} · ${field}`, req.signal);
|
|
569
631
|
if (!password) return "cancelled: no password entered";
|
|
570
|
-
|
|
571
|
-
stdin = `${password}\n`;
|
|
632
|
+
secrets.set(field, password);
|
|
572
633
|
}
|
|
573
634
|
}
|
|
574
635
|
return "cancelled: the save dialog did not settle";
|
|
@@ -605,12 +666,12 @@ async function importBitwarden(
|
|
|
605
666
|
if (!allowed) return { text: "user denied the Bitwarden import", ok: false, count: 0 };
|
|
606
667
|
let drafts;
|
|
607
668
|
try {
|
|
608
|
-
drafts = await
|
|
669
|
+
drafts = await pullBitwardenItems(bw, ctx, search, signal);
|
|
609
670
|
} catch (error) {
|
|
610
671
|
return { text: `Bitwarden: ${describe(error)}`, ok: false, count: 0 };
|
|
611
672
|
}
|
|
612
673
|
if (drafts.length === 0) {
|
|
613
|
-
return { text: "matched
|
|
674
|
+
return { text: "nothing matched; nothing imported", ok: false, count: 0 };
|
|
614
675
|
}
|
|
615
676
|
try {
|
|
616
677
|
const saved = await cli.json<SaveResult>(["save", "--yes", "--token", scope.token!], {
|
|
@@ -637,6 +698,7 @@ const HELP = [
|
|
|
637
698
|
tr("/vault init create the machine-wide encrypted store (a dialog sets the master password)", "/vault init 创建全机共享的本地加密库(弹出窗口设置主密码)"),
|
|
638
699
|
tr("/vault unlock | lock unlock / lock (clears this session's grants)", "/vault unlock | lock 解锁 / 锁定(清空本会话的授权)"),
|
|
639
700
|
tr("/vault mode [never|time|session] show/switch the unlock policy (switching needs the master password)", "/vault mode [never|time|session] 查看/切换解锁模式(切换要主密码)"),
|
|
701
|
+
tr("/vault confirm [off|on] a window per read while unlocked (off asks the master password)", "/vault confirm [off|on] 解锁后每次读取是否弹确认窗(关要主密码)"),
|
|
640
702
|
tr("/vault settings [key value] show/change settings (vault.unlock, bitwarden.*, ente.* …)", "/vault settings [键 值] 查看/修改设置(vault.unlock、bitwarden.*、ente.* …)"),
|
|
641
703
|
tr("/vault ente-key save Ente's ENTE_CLI_VAULT_KEY (no keychain, no login)", "/vault ente-key 保存 ente 的 ENTE_CLI_VAULT_KEY(免钥匙串/免登录)"),
|
|
642
704
|
tr("/vault status state and grants left", "/vault status 状态与授权剩余时间"),
|
|
@@ -805,22 +867,61 @@ function commandHandler(scope: Scope, bw: BwState) {
|
|
|
805
867
|
}
|
|
806
868
|
return;
|
|
807
869
|
}
|
|
870
|
+
case "confirm": {
|
|
871
|
+
// /vault confirm show
|
|
872
|
+
// /vault confirm off|on turn the per-read window off (asks the master password) / on
|
|
873
|
+
const [arg] = rest;
|
|
874
|
+
if (!arg) {
|
|
875
|
+
try {
|
|
876
|
+
const current = await cli.json<Settings>(["settings", ...tokenArgs(scope)]);
|
|
877
|
+
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
|
+
} catch (error) {
|
|
879
|
+
note(ctx, `ai-vault: ${describe(error)}`, "error");
|
|
880
|
+
}
|
|
881
|
+
return;
|
|
882
|
+
}
|
|
883
|
+
const value = arg.toLowerCase();
|
|
884
|
+
if (!["off", "on", "false", "true"].includes(value)) {
|
|
885
|
+
note(ctx, tr("usage: /vault confirm [off|on]", "用法: /vault confirm [off|on]"), "warning");
|
|
886
|
+
return;
|
|
887
|
+
}
|
|
888
|
+
const turnOff = value === "off" || value === "false";
|
|
889
|
+
try {
|
|
890
|
+
const run = await cli.withPassword(["settings", "vault.confirm", turnOff ? "false" : "true", ...tokenArgs(scope)], () =>
|
|
891
|
+
promptSecret(dialogs(ctx), tr("ai-vault · master password", "ai-vault · 主密码"), tr("turn off the per-read confirmation", "关闭每次读取的确认窗")),
|
|
892
|
+
);
|
|
893
|
+
forgetSettings();
|
|
894
|
+
const updated = JSON.parse(run.stdout) as Settings;
|
|
895
|
+
note(
|
|
896
|
+
ctx,
|
|
897
|
+
updated.vault.confirm
|
|
898
|
+
? tr("vault.confirm is on: every read opens a confirm window.", "vault.confirm 已开:每次读取弹确认窗。")
|
|
899
|
+
: tr(
|
|
900
|
+
"vault.confirm is off: while a session is unlocked, reads return without a window. Each read is still written to the audit log. Turning it back on: /vault confirm on",
|
|
901
|
+
"vault.confirm 已关:会话解锁期间读取不再弹窗。每次读取仍写审计。重新打开:/vault confirm on",
|
|
902
|
+
),
|
|
903
|
+
);
|
|
904
|
+
} catch (error) {
|
|
905
|
+
note(ctx, `ai-vault: ${error instanceof CliError && error.denied ? tr("cancelled", "已取消") : describe(error)}`, "warning");
|
|
906
|
+
}
|
|
907
|
+
return;
|
|
908
|
+
}
|
|
808
909
|
case "settings": {
|
|
809
910
|
const [key, ...valueParts] = rest;
|
|
810
911
|
const value = valueParts.join(" ").trim();
|
|
811
912
|
try {
|
|
812
913
|
if (!key) {
|
|
813
|
-
note(ctx, settingsText(await cli.json<Settings>(["settings"])));
|
|
914
|
+
note(ctx, settingsText(await cli.json<Settings>(["settings", ...tokenArgs(scope)])));
|
|
814
915
|
return;
|
|
815
916
|
}
|
|
816
917
|
if (!value) {
|
|
817
|
-
const one = await cli.json<{ key: string; value: string }>(["settings", key]);
|
|
918
|
+
const one = await cli.json<{ key: string; value: string }>(["settings", key, ...tokenArgs(scope)]);
|
|
818
919
|
note(ctx, `${one.key}: ${one.value}`);
|
|
819
920
|
return;
|
|
820
921
|
}
|
|
821
922
|
// `vault.unlock` opens its own password window (or answers
|
|
822
923
|
// needs-ui); the other keys do not prompt at all.
|
|
823
|
-
const run = await cli.withPassword(["settings", key, value], () =>
|
|
924
|
+
const run = await cli.withPassword(["settings", key, value, ...tokenArgs(scope)], () =>
|
|
824
925
|
promptSecret(dialogs(ctx), tr("ai-vault · master password", "ai-vault · 主密码"), tr("changing the unlock policy needs verification", "改变解锁模式需要验证")),
|
|
825
926
|
);
|
|
826
927
|
forgetSettings();
|
|
@@ -891,7 +992,30 @@ function commandHandler(scope: Scope, bw: BwState) {
|
|
|
891
992
|
return;
|
|
892
993
|
}
|
|
893
994
|
case "add": {
|
|
894
|
-
|
|
995
|
+
// /vault add [type:]name [field=value ...] [field] — a bare
|
|
996
|
+
// `field` is typed in a dialog. /vault add card:Visa brand=Visa code
|
|
997
|
+
const [first, ...pairs] = rest;
|
|
998
|
+
let type: ItemType | undefined;
|
|
999
|
+
let name = first ?? "";
|
|
1000
|
+
const m = /^([a-z]+):(.+)$/.exec(first ?? "");
|
|
1001
|
+
if (m) {
|
|
1002
|
+
const parsed = parseItemType(m[1]);
|
|
1003
|
+
if (parsed) {
|
|
1004
|
+
type = parsed;
|
|
1005
|
+
name = m[2] ?? name;
|
|
1006
|
+
}
|
|
1007
|
+
}
|
|
1008
|
+
const fields: Record<string, string | undefined> = {};
|
|
1009
|
+
let notes: string | undefined;
|
|
1010
|
+
for (const pair of pairs) {
|
|
1011
|
+
const eq = pair.indexOf("=");
|
|
1012
|
+
const key = eq < 0 ? pair : pair.slice(0, eq);
|
|
1013
|
+
const value = eq < 0 ? "" : pair.slice(eq + 1);
|
|
1014
|
+
if (!key) continue;
|
|
1015
|
+
if (key === "notes" || key === "note") notes = value;
|
|
1016
|
+
else fields[key] = value === "" ? undefined : value;
|
|
1017
|
+
}
|
|
1018
|
+
const text = await saveLocalEntry(scope, ctx, { name: name.trim() || undefined, type, fields, notes });
|
|
895
1019
|
note(ctx, text, text.startsWith("saved ") ? "info" : "warning");
|
|
896
1020
|
return;
|
|
897
1021
|
}
|
|
@@ -11,7 +11,7 @@ export type UnlockModeName = "never" | "time" | "session";
|
|
|
11
11
|
export type ImportPolicy = "ask" | "always" | "never";
|
|
12
12
|
|
|
13
13
|
export interface Settings {
|
|
14
|
-
vault: { unlock: UnlockModeName; hours: number; auto: boolean };
|
|
14
|
+
vault: { unlock: UnlockModeName; hours: number; confirm: boolean; auto: boolean };
|
|
15
15
|
bitwarden: {
|
|
16
16
|
unlock: UnlockModeName;
|
|
17
17
|
hours: number;
|
|
@@ -24,17 +24,42 @@ export interface Settings {
|
|
|
24
24
|
}
|
|
25
25
|
|
|
26
26
|
export const DEFAULT_SETTINGS: Settings = {
|
|
27
|
-
vault: { unlock: "session", hours: 8, auto: false },
|
|
27
|
+
vault: { unlock: "session", hours: 8, confirm: true, 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
|
};
|
|
31
31
|
|
|
32
|
-
|
|
33
|
-
|
|
32
|
+
/**
|
|
33
|
+
* One CLI client for the whole extension. It carries the one `HostSecret`
|
|
34
|
+
* every call must be signed under: a second instance would have its own
|
|
35
|
+
* (empty) secret, and a call made through it would fail the session file's
|
|
36
|
+
* HMAC and get it deleted — locking the binding out. Keep this the same
|
|
37
|
+
* object the tools use.
|
|
38
|
+
*/
|
|
39
|
+
let cli: VaultCli | undefined;
|
|
34
40
|
|
|
35
|
-
/** The shared CLI client, for the pieces that read and write the settings. */
|
|
36
41
|
export function settingsCli(): VaultCli {
|
|
37
|
-
return cli;
|
|
42
|
+
return (cli ??= new VaultCli());
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
let cache: { at: number; value: Settings } | undefined;
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* The session token the settings are read under. The settings live inside the
|
|
49
|
+
* store's ciphertext, so reading them is a privileged call like any other;
|
|
50
|
+
* the binding that unlocked sets this before asking.
|
|
51
|
+
*/
|
|
52
|
+
let sessionToken: string | undefined;
|
|
53
|
+
|
|
54
|
+
export function setSettingsToken(token: string | undefined): void {
|
|
55
|
+
if (token !== sessionToken) {
|
|
56
|
+
sessionToken = token;
|
|
57
|
+
cache = undefined;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export function settingsToken(): string | undefined {
|
|
62
|
+
return sessionToken;
|
|
38
63
|
}
|
|
39
64
|
|
|
40
65
|
/**
|
|
@@ -43,7 +68,7 @@ export function settingsCli(): VaultCli {
|
|
|
43
68
|
*/
|
|
44
69
|
export async function getSettings(signal?: AbortSignal, options: { fresh?: boolean } = {}): Promise<Settings> {
|
|
45
70
|
if (!options.fresh && cache && Date.now() - cache.at < 30_000) return cache.value;
|
|
46
|
-
const value = await
|
|
71
|
+
const value = await settingsCli().json<Settings>(["settings", ...(sessionToken ? ["--token", sessionToken] : [])], { signal });
|
|
47
72
|
cache = { at: Date.now(), value };
|
|
48
73
|
return value;
|
|
49
74
|
}
|
|
@@ -60,3 +85,8 @@ export async function getSettingsSafe(signal?: AbortSignal): Promise<Settings> {
|
|
|
60
85
|
export function forgetSettings(): void {
|
|
61
86
|
cache = undefined;
|
|
62
87
|
}
|
|
88
|
+
|
|
89
|
+
/** Tests change the store's settings from outside the process; let them drop the cache. */
|
|
90
|
+
process.on("ai-vault:settings-changed", () => {
|
|
91
|
+
cache = undefined;
|
|
92
|
+
});
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The shape of a vault entry, shared by the extension's import mapping and
|
|
3
|
+
* its tools. Mirrors the CLI's `store.rs` and Bitwarden's own item envelope:
|
|
4
|
+
* a type, the type's own fields under `data`, plus `notes` and custom
|
|
5
|
+
* `fields` that every type carries.
|
|
6
|
+
*/
|
|
7
|
+
export type ItemType =
|
|
8
|
+
| "login"
|
|
9
|
+
| "secureNote"
|
|
10
|
+
| "card"
|
|
11
|
+
| "identity"
|
|
12
|
+
| "sshKey"
|
|
13
|
+
| "bankAccount"
|
|
14
|
+
| "driversLicense"
|
|
15
|
+
| "passport";
|
|
16
|
+
|
|
17
|
+
/** A custom field, as Bitwarden stores it: 0 text · 1 hidden · 2 boolean · 3 linked. */
|
|
18
|
+
export interface Field {
|
|
19
|
+
name: string;
|
|
20
|
+
value: string;
|
|
21
|
+
type: number;
|
|
22
|
+
linkedId?: string;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export interface Source {
|
|
26
|
+
kind: string;
|
|
27
|
+
id: string;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** What a tool hands to `ai-vault save` / `add`: the same envelope, sparse. */
|
|
31
|
+
export interface Draft {
|
|
32
|
+
name: string;
|
|
33
|
+
type: ItemType;
|
|
34
|
+
username?: string;
|
|
35
|
+
password?: string;
|
|
36
|
+
uris?: string[];
|
|
37
|
+
data?: Record<string, string>;
|
|
38
|
+
notes?: string;
|
|
39
|
+
fields?: Field[];
|
|
40
|
+
source?: Source;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** What `list` returns: metadata only, every secret masked. */
|
|
44
|
+
export interface ItemSummary {
|
|
45
|
+
name: string;
|
|
46
|
+
type: ItemType;
|
|
47
|
+
username?: string | null;
|
|
48
|
+
uris: string[];
|
|
49
|
+
fields: Record<string, string>;
|
|
50
|
+
hasNotes?: boolean;
|
|
51
|
+
updatedAt: string;
|
|
52
|
+
}
|