pi-ai-vault 0.11.0 → 0.12.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/package.json +2 -2
- package/src/bitwarden.ts +154 -27
- package/src/cli.ts +117 -25
- package/src/ente.ts +5 -2
- package/src/index.ts +51 -6
- package/src/settings.ts +37 -7
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-ai-vault",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.12.1",
|
|
4
4
|
"description": "pi extension for ai-vault: one machine-wide encrypted secret store, live Bitwarden and Ente Auth. Works in pi and in omp (the omp fork reads the same manifest).",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -25,7 +25,7 @@
|
|
|
25
25
|
"security"
|
|
26
26
|
],
|
|
27
27
|
"dependencies": {
|
|
28
|
-
"@xiaolikt/ai-vault": "0.
|
|
28
|
+
"@xiaolikt/ai-vault": "0.12.1"
|
|
29
29
|
},
|
|
30
30
|
"peerDependencies": {
|
|
31
31
|
"@earendil-works/pi-coding-agent": "^1.5.0",
|
package/src/bitwarden.ts
CHANGED
|
@@ -46,7 +46,7 @@
|
|
|
46
46
|
*/
|
|
47
47
|
|
|
48
48
|
import { spawn, spawnSync } from "node:child_process";
|
|
49
|
-
import { constants as fsConstants, accessSync, readFileSync, promises as fs } from "node:fs";
|
|
49
|
+
import { constants as fsConstants, accessSync, existsSync, readFileSync, promises as fs } from "node:fs";
|
|
50
50
|
import { homedir, tmpdir } from "node:os";
|
|
51
51
|
import path from "node:path";
|
|
52
52
|
import type { ExtensionAPI, ExtensionContext, ToolDefinition, ToolResultEventResult } from "@earendil-works/pi-coding-agent";
|
|
@@ -56,7 +56,8 @@ import { bitwardenItems, filterItems } from "./import-map.js";
|
|
|
56
56
|
import type { Draft } from "./types.js";
|
|
57
57
|
import { onSessionLeave, sessionLabel, withTier } from "./host.js";
|
|
58
58
|
import { confirmWindow, hasDisplay, promptSecret } from "./prompt.js";
|
|
59
|
-
import {
|
|
59
|
+
import { npmShimLaunch, type CliLaunch } from "./cli.js";
|
|
60
|
+
import { getSettingsSafe, settingsCli, settingsToken } from "./settings.js";
|
|
60
61
|
import { tr } from "./i18n.js";
|
|
61
62
|
import { scrubDeep, scrubText } from "./scrub.js";
|
|
62
63
|
|
|
@@ -292,6 +293,62 @@ function childEnv(extra?: Record<string, string>): NodeJS.ProcessEnv {
|
|
|
292
293
|
return env;
|
|
293
294
|
}
|
|
294
295
|
|
|
296
|
+
const WIN32 = process.platform === "win32";
|
|
297
|
+
|
|
298
|
+
/** A file under the Windows directory: `%SystemRoot%` already is `C:\Windows`. */
|
|
299
|
+
const systemFile = (...parts: string[]): string => path.join(process.env.SystemRoot ?? "C:/Windows", ...parts);
|
|
300
|
+
|
|
301
|
+
/** `taskkill /T /F`: the process and everything it started. Windows has no process groups. Exported for tests. */
|
|
302
|
+
export function killTree(pid: number): void {
|
|
303
|
+
const taskkill = systemFile("System32", "taskkill.exe");
|
|
304
|
+
try {
|
|
305
|
+
spawnSync(taskkill, ["/PID", String(pid), "/T", "/F"], { stdio: "ignore", timeout: 5000, windowsHide: true });
|
|
306
|
+
} catch {
|
|
307
|
+
/* best-effort: the caller still kills the process itself */
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
/** How long a copy command may take to set the clipboard and exit. */
|
|
312
|
+
const COPY_TIMEOUT_MS = 15_000;
|
|
313
|
+
|
|
314
|
+
let bashLaunch: CliLaunch | undefined;
|
|
315
|
+
|
|
316
|
+
/**
|
|
317
|
+
* The shell `bw_run` runs a command in. Git for Windows keeps `bash.exe` in
|
|
318
|
+
* `<install>\bin` and does not put that on PATH (`git.exe` is what is found
|
|
319
|
+
* there), so the installation git.exe came from is searched as well.
|
|
320
|
+
* Exported for tests.
|
|
321
|
+
*/
|
|
322
|
+
export function resolveBash(): CliLaunch {
|
|
323
|
+
if (bashLaunch) return bashLaunch;
|
|
324
|
+
bashLaunch = { program: "bash", pre: [] };
|
|
325
|
+
if (WIN32) {
|
|
326
|
+
const onPath = (exe: string): string | undefined => {
|
|
327
|
+
for (const dir of (process.env.PATH ?? "").split(path.delimiter)) {
|
|
328
|
+
if (dir && existsSync(path.join(dir, exe))) return path.join(dir, exe);
|
|
329
|
+
}
|
|
330
|
+
return undefined;
|
|
331
|
+
};
|
|
332
|
+
const roots = [process.env.ProgramFiles, process.env["ProgramFiles(x86)"], process.env.LOCALAPPDATA && path.join(process.env.LOCALAPPDATA, "Programs")];
|
|
333
|
+
bashLaunch.program =
|
|
334
|
+
onPath("bash.exe") ??
|
|
335
|
+
bashBeside(onPath("git.exe")) ??
|
|
336
|
+
roots.filter((base): base is string => !!base).map((base) => path.join(base, "Git", "bin", "bash.exe")).find((candidate) => existsSync(candidate)) ??
|
|
337
|
+
"bash";
|
|
338
|
+
}
|
|
339
|
+
return bashLaunch;
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
/** `<install>\bin\bash.exe`, from whichever directory of a Git for Windows installation one starts. */
|
|
343
|
+
function bashBeside(gitExe: string | undefined): string | undefined {
|
|
344
|
+
for (let dir = gitExe && path.dirname(gitExe); dir; dir = path.dirname(dir)) {
|
|
345
|
+
const candidate = path.join(dir, "bin", "bash.exe");
|
|
346
|
+
if (existsSync(candidate)) return candidate;
|
|
347
|
+
if (path.dirname(dir) === dir) break;
|
|
348
|
+
}
|
|
349
|
+
return undefined;
|
|
350
|
+
}
|
|
351
|
+
|
|
295
352
|
function exec(cmd: string, args: string[], opts: ExecOptions = {}): Promise<ExecResult> {
|
|
296
353
|
if (opts.signal?.aborted) return Promise.reject(new Error(`${cmd} cancelled`));
|
|
297
354
|
const { promise, resolve, reject } = Promise.withResolvers<ExecResult>();
|
|
@@ -300,12 +357,20 @@ function exec(cmd: string, args: string[], opts: ExecOptions = {}): Promise<Exec
|
|
|
300
357
|
cwd: opts.cwd,
|
|
301
358
|
stdio: ["pipe", "pipe", "pipe"],
|
|
302
359
|
detached: opts.group === true,
|
|
360
|
+
windowsHide: true,
|
|
303
361
|
});
|
|
304
362
|
let out = "";
|
|
305
363
|
let err = "";
|
|
306
364
|
let truncated = false;
|
|
307
365
|
let settled = false;
|
|
308
366
|
const kill = () => {
|
|
367
|
+
if (WIN32) {
|
|
368
|
+
// No process groups on Windows: take the whole tree down, or a command
|
|
369
|
+
// that timed out leaves what it started running with the secret in its environment.
|
|
370
|
+
if (child.pid) killTree(child.pid);
|
|
371
|
+
child.kill("SIGKILL");
|
|
372
|
+
return;
|
|
373
|
+
}
|
|
309
374
|
if (opts.group && child.pid) {
|
|
310
375
|
try {
|
|
311
376
|
process.kill(-child.pid, "SIGKILL");
|
|
@@ -388,16 +453,42 @@ export async function auditEvent(event: string, detail: string, session?: string
|
|
|
388
453
|
// ---------------------------------------------------------------------------
|
|
389
454
|
// Bitwarden CLI plumbing (secrets only ever travel via env vars / pipes)
|
|
390
455
|
// ---------------------------------------------------------------------------
|
|
391
|
-
|
|
456
|
+
/** How to start the Bitwarden CLI; `pre` is empty unless an npm wrapper had to be unwrapped. Exported for tests. */
|
|
457
|
+
let bwLaunch: CliLaunch | undefined;
|
|
392
458
|
|
|
393
|
-
|
|
394
|
-
|
|
459
|
+
/** Runs at all: answers `--version` with exit 0. */
|
|
460
|
+
async function bwRuns(launch: CliLaunch): Promise<boolean> {
|
|
395
461
|
try {
|
|
396
|
-
await exec(
|
|
397
|
-
|
|
398
|
-
return bwBin;
|
|
462
|
+
const r = await exec(launch.program, [...launch.pre, "--version"], { timeout: 20_000 });
|
|
463
|
+
return r.code === 0;
|
|
399
464
|
} catch {
|
|
400
|
-
|
|
465
|
+
return false;
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
export async function resolveBw(): Promise<CliLaunch> {
|
|
470
|
+
if (bwLaunch) return bwLaunch;
|
|
471
|
+
// `bw.exe` is found by the bare name on Windows, `bw` elsewhere.
|
|
472
|
+
if (await bwRuns({ program: "bw", pre: [] })) {
|
|
473
|
+
bwLaunch = { program: "bw", pre: [] };
|
|
474
|
+
return bwLaunch;
|
|
475
|
+
}
|
|
476
|
+
// npm installs `bw` as bw.cmd (with a .ps1 and a sh script beside it), which
|
|
477
|
+
// Windows cannot start without a shell: start the JavaScript it wraps with
|
|
478
|
+
// this Node instead.
|
|
479
|
+
if (WIN32) {
|
|
480
|
+
for (const dir of (process.env.PATH ?? "").split(path.delimiter)) {
|
|
481
|
+
if (!dir) continue;
|
|
482
|
+
for (const name of ["bw.exe", "bw.cmd", "bw.bat"]) {
|
|
483
|
+
const candidate = path.join(dir, name);
|
|
484
|
+
if (!existsSync(candidate)) continue;
|
|
485
|
+
const launch = name === "bw.exe" ? { program: candidate, pre: [] } : npmShimLaunch(candidate);
|
|
486
|
+
if (launch && (await bwRuns(launch))) {
|
|
487
|
+
bwLaunch = launch;
|
|
488
|
+
return bwLaunch;
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
}
|
|
401
492
|
}
|
|
402
493
|
try {
|
|
403
494
|
const nvmDir = path.join(homedir(), ".nvm", "versions", "node");
|
|
@@ -408,8 +499,8 @@ async function resolveBw(): Promise<string> {
|
|
|
408
499
|
for (const v of versions) {
|
|
409
500
|
const p = path.join(nvmDir, v, "bin", "bw");
|
|
410
501
|
if (await fs.access(p).then(() => true, () => false)) {
|
|
411
|
-
|
|
412
|
-
return
|
|
502
|
+
bwLaunch = { program: p, pre: [] };
|
|
503
|
+
return bwLaunch;
|
|
413
504
|
}
|
|
414
505
|
}
|
|
415
506
|
} catch {
|
|
@@ -422,10 +513,10 @@ async function runBw(
|
|
|
422
513
|
args: string[],
|
|
423
514
|
opts: { session?: string; extraEnv?: Record<string, string>; signal?: AbortSignal } = {},
|
|
424
515
|
): Promise<string> {
|
|
425
|
-
const
|
|
516
|
+
const bw = await resolveBw();
|
|
426
517
|
const env: Record<string, string> = { ...opts.extraEnv };
|
|
427
518
|
if (opts.session) env.BW_SESSION = opts.session;
|
|
428
|
-
const r = await exec(
|
|
519
|
+
const r = await exec(bw.program, [...bw.pre, ...args, "--nointeraction"], { env, signal: opts.signal });
|
|
429
520
|
if (r.code !== 0) {
|
|
430
521
|
const hint = tail(r.stderr) || `exit ${r.code}`;
|
|
431
522
|
// Never include stdout in errors — some commands print secrets on success-ish paths.
|
|
@@ -522,8 +613,8 @@ async function lock(st: BwState, reason: string): Promise<void> {
|
|
|
522
613
|
await auditEvent("lock", `reason=${reason}`, st.sessionLabel);
|
|
523
614
|
if (!releaseSessionKey()) return; // another binding still uses its own key
|
|
524
615
|
try {
|
|
525
|
-
const
|
|
526
|
-
await exec(
|
|
616
|
+
const bw = await resolveBw();
|
|
617
|
+
await exec(bw.program, [...bw.pre, "lock", "--nointeraction"], { timeout: 15_000 });
|
|
527
618
|
} catch {
|
|
528
619
|
/* best-effort; dropping our session key is what matters */
|
|
529
620
|
}
|
|
@@ -580,8 +671,8 @@ async function ensureUnlocked(st: BwState, ctx: ExtensionContext | undefined, si
|
|
|
580
671
|
if (status?.status === "unauthenticated") throw new Error(BW_LOGIN_HINT);
|
|
581
672
|
|
|
582
673
|
const pw = await askMasterPassword(ctx, signal);
|
|
583
|
-
const
|
|
584
|
-
const r = await exec(
|
|
674
|
+
const bw = await resolveBw();
|
|
675
|
+
const r = await exec(bw.program, [...bw.pre, "unlock", "--passwordenv", "BW_MASTER_PASSWORD", "--raw"], {
|
|
585
676
|
env: { BW_MASTER_PASSWORD: pw },
|
|
586
677
|
timeout: 60_000,
|
|
587
678
|
signal,
|
|
@@ -603,7 +694,8 @@ async function ensureUnlocked(st: BwState, ctx: ExtensionContext | undefined, si
|
|
|
603
694
|
if (policy.unlock !== "session") {
|
|
604
695
|
// Keep the key where the CLI can hand it back; the file's expiry comes
|
|
605
696
|
// from the bitwarden.hours policy.
|
|
606
|
-
|
|
697
|
+
const token = settingsToken();
|
|
698
|
+
await settingsCli().run(["bw-session", "put", ...(token ? ["--token", token] : [])], { stdin: key }).catch(() => undefined);
|
|
607
699
|
}
|
|
608
700
|
await auditEvent("unlock", "ok", st.sessionLabel);
|
|
609
701
|
// Refresh in the background: a full sync can take seconds on large vaults.
|
|
@@ -880,8 +972,26 @@ type ClipboardBackend = {
|
|
|
880
972
|
copy: [string, string[]];
|
|
881
973
|
clear: [string, string[]];
|
|
882
974
|
read: [string, string[]];
|
|
975
|
+
/** wl-copy and xclip keep running to own the selection; the others set it and exit. */
|
|
976
|
+
lingers: boolean;
|
|
883
977
|
};
|
|
884
978
|
|
|
979
|
+
/**
|
|
980
|
+
* Windows: Windows PowerShell with WinForms. The value travels as UTF-8
|
|
981
|
+
* bytes on stdin and stdout: never on a command line, and never through the
|
|
982
|
+
* console's code page, which is not UTF-8 on a Chinese Windows.
|
|
983
|
+
*/
|
|
984
|
+
const PS_CLIP_ARGS = ["-NoProfile", "-NonInteractive", "-STA", "-Command"];
|
|
985
|
+
const PS_SET_CLIP =
|
|
986
|
+
"Add-Type -AssemblyName System.Windows.Forms; $stdin = [Console]::OpenStandardInput(); $buffer = New-Object System.IO.MemoryStream; " +
|
|
987
|
+
"$stdin.CopyTo($buffer); $text = [System.Text.Encoding]::UTF8.GetString($buffer.ToArray()); " +
|
|
988
|
+
"if ($text.Length -eq 0) { exit 1 }; [System.Windows.Forms.Clipboard]::SetText($text); exit 0";
|
|
989
|
+
const PS_GET_CLIP =
|
|
990
|
+
"Add-Type -AssemblyName System.Windows.Forms; $bytes = [System.Text.Encoding]::UTF8.GetBytes([System.Windows.Forms.Clipboard]::GetText()); " +
|
|
991
|
+
"$stdout = [Console]::OpenStandardOutput(); $stdout.Write($bytes, 0, $bytes.Length); $stdout.Flush(); exit 0";
|
|
992
|
+
const PS_CLEAR_CLIP =
|
|
993
|
+
"Add-Type -AssemblyName System.Windows.Forms; [System.Windows.Forms.Clipboard]::Clear(); exit 0";
|
|
994
|
+
|
|
885
995
|
/** Whether an executable is on PATH, so a Wayland session can fall back to X11. */
|
|
886
996
|
function commandExists(command: string): boolean {
|
|
887
997
|
for (const dir of (process.env.PATH ?? "").split(path.delimiter)) {
|
|
@@ -896,15 +1006,25 @@ function commandExists(command: string): boolean {
|
|
|
896
1006
|
return false;
|
|
897
1007
|
}
|
|
898
1008
|
|
|
899
|
-
function clipboardBackend(): ClipboardBackend | undefined {
|
|
1009
|
+
export function clipboardBackend(): ClipboardBackend | undefined {
|
|
1010
|
+
if (WIN32) {
|
|
1011
|
+
const powershell = systemFile("System32", "WindowsPowerShell", "v1.0", "powershell.exe");
|
|
1012
|
+
return {
|
|
1013
|
+
copy: [powershell, [...PS_CLIP_ARGS, PS_SET_CLIP]],
|
|
1014
|
+
clear: [powershell, [...PS_CLIP_ARGS, PS_CLEAR_CLIP]],
|
|
1015
|
+
read: [powershell, [...PS_CLIP_ARGS, PS_GET_CLIP]],
|
|
1016
|
+
lingers: false,
|
|
1017
|
+
};
|
|
1018
|
+
}
|
|
900
1019
|
if (process.platform === "darwin") {
|
|
901
|
-
return { copy: ["pbcopy", []], clear: ["pbcopy", []], read: ["pbpaste", []] };
|
|
1020
|
+
return { copy: ["pbcopy", []], clear: ["pbcopy", []], read: ["pbpaste", []], lingers: false };
|
|
902
1021
|
}
|
|
903
1022
|
if (process.env.WAYLAND_DISPLAY && commandExists("wl-copy") && commandExists("wl-paste")) {
|
|
904
1023
|
return {
|
|
905
1024
|
copy: ["wl-copy", []],
|
|
906
1025
|
clear: ["wl-copy", ["-c"]],
|
|
907
1026
|
read: ["wl-paste", ["--no-newline"]],
|
|
1027
|
+
lingers: true,
|
|
908
1028
|
};
|
|
909
1029
|
}
|
|
910
1030
|
if (process.env.DISPLAY && commandExists("xclip")) {
|
|
@@ -912,6 +1032,7 @@ function clipboardBackend(): ClipboardBackend | undefined {
|
|
|
912
1032
|
copy: ["xclip", ["-selection", "clipboard"]],
|
|
913
1033
|
clear: ["xclip", ["-selection", "clipboard", "/dev/null"]],
|
|
914
1034
|
read: ["xclip", ["-selection", "clipboard", "-o"]],
|
|
1035
|
+
lingers: true,
|
|
915
1036
|
};
|
|
916
1037
|
}
|
|
917
1038
|
return undefined;
|
|
@@ -935,17 +1056,19 @@ function clipboardMatches(current: string, value: string): boolean {
|
|
|
935
1056
|
|
|
936
1057
|
async function copyToClipboard(value: string): Promise<void> {
|
|
937
1058
|
const backend = clipboardBackend();
|
|
938
|
-
if (!backend) throw new Error("No clipboard available (need Wayland, X11, or
|
|
1059
|
+
if (!backend) throw new Error("No clipboard available (need Wayland, X11, macOS, or Windows PowerShell).");
|
|
939
1060
|
const drops = clipboardDrops;
|
|
940
1061
|
const [cmd, args] = backend.copy;
|
|
941
1062
|
const { promise, resolve, reject } = Promise.withResolvers<void>();
|
|
942
|
-
//
|
|
943
|
-
const child = spawn(cmd, args, { stdio: ["pipe", "ignore", "pipe"], detached:
|
|
1063
|
+
// A backend that owns the selection stays alive, detached from this process.
|
|
1064
|
+
const child = spawn(cmd, args, { stdio: ["pipe", "ignore", "pipe"], detached: backend.lingers, env: childEnv(), windowsHide: true });
|
|
944
1065
|
let settled = false;
|
|
945
1066
|
let stderr = "";
|
|
1067
|
+
const watchdog = setTimeout(() => finish(new Error(`${cmd} did not finish`)), COPY_TIMEOUT_MS);
|
|
946
1068
|
const finish = (err?: Error) => {
|
|
947
1069
|
if (settled) return;
|
|
948
1070
|
settled = true;
|
|
1071
|
+
clearTimeout(watchdog);
|
|
949
1072
|
if (err) reject(err);
|
|
950
1073
|
else {
|
|
951
1074
|
child.unref();
|
|
@@ -965,7 +1088,10 @@ async function copyToClipboard(value: string): Promise<void> {
|
|
|
965
1088
|
return;
|
|
966
1089
|
}
|
|
967
1090
|
child.stdin?.end();
|
|
968
|
-
|
|
1091
|
+
// A backend that owns the selection never exits: after a moment without an
|
|
1092
|
+
// error, the value is in place. Every other backend is waited for, so that
|
|
1093
|
+
// a copy that failed is reported and never looks like success.
|
|
1094
|
+
if (backend.lingers) setTimeout(() => finish(), 500);
|
|
969
1095
|
});
|
|
970
1096
|
clipboardPending = value;
|
|
971
1097
|
try {
|
|
@@ -1028,13 +1154,13 @@ function clearClipboardSync(): void {
|
|
|
1028
1154
|
clipboardPending = undefined;
|
|
1029
1155
|
if (!value || !backend) return;
|
|
1030
1156
|
try {
|
|
1031
|
-
const r = spawnSync(backend.read[0], backend.read[1], { encoding: "utf8", timeout: 1000, env: childEnv() });
|
|
1157
|
+
const r = spawnSync(backend.read[0], backend.read[1], { encoding: "utf8", timeout: WIN32 ? 3000 : 1000, env: childEnv(), windowsHide: true });
|
|
1032
1158
|
if (r.status === 0 && typeof r.stdout === "string" && r.stdout.length > 0 && !clipboardMatches(r.stdout, value)) return;
|
|
1033
1159
|
} catch {
|
|
1034
1160
|
/* clear anyway */
|
|
1035
1161
|
}
|
|
1036
1162
|
try {
|
|
1037
|
-
spawnSync(backend.clear[0], backend.clear[1], { input: "", timeout: 2000, env: childEnv() });
|
|
1163
|
+
spawnSync(backend.clear[0], backend.clear[1], { input: "", timeout: WIN32 ? 3000 : 2000, env: childEnv(), windowsHide: true });
|
|
1038
1164
|
} catch {
|
|
1039
1165
|
/* best-effort */
|
|
1040
1166
|
}
|
|
@@ -1315,7 +1441,8 @@ export function registerBitwarden(pi: ExtensionAPI, st: BwState, ompHost: boolea
|
|
|
1315
1441
|
if (!approved) throw new Error("User declined the command.");
|
|
1316
1442
|
const { value, itemName } = await secretOf(approved.session, approved.item, field, signal);
|
|
1317
1443
|
rememberScrubValue(envName, value);
|
|
1318
|
-
const
|
|
1444
|
+
const bash = resolveBash();
|
|
1445
|
+
const r = await exec(bash.program, [...bash.pre, "-c", params.command], {
|
|
1319
1446
|
env: { [envName]: value },
|
|
1320
1447
|
cwd,
|
|
1321
1448
|
timeout: seconds * 1000,
|
package/src/cli.ts
CHANGED
|
@@ -8,10 +8,11 @@
|
|
|
8
8
|
* dialog takes over here.
|
|
9
9
|
*/
|
|
10
10
|
import { createHmac, randomBytes } from "node:crypto";
|
|
11
|
-
import { spawn } from "node:child_process";
|
|
12
|
-
import { existsSync } from "node:fs";
|
|
11
|
+
import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
|
|
12
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
13
|
+
import { createRequire } from "node:module";
|
|
13
14
|
import { homedir } from "node:os";
|
|
14
|
-
import { delimiter, dirname, join } from "node:path";
|
|
15
|
+
import { delimiter, dirname, extname, join } from "node:path";
|
|
15
16
|
import { lang } from "./i18n.js";
|
|
16
17
|
import { fileURLToPath } from "node:url";
|
|
17
18
|
|
|
@@ -58,45 +59,132 @@ export class CliError extends Error {
|
|
|
58
59
|
}
|
|
59
60
|
}
|
|
60
61
|
|
|
62
|
+
/** How to start the CLI: a program, plus what has to precede our arguments. */
|
|
63
|
+
export interface CliLaunch {
|
|
64
|
+
program: string;
|
|
65
|
+
pre: string[];
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
const WIN32 = process.platform === "win32";
|
|
69
|
+
/** The file npm links for the bin: an `.exe` where there is one, else its `.cmd` wrapper. */
|
|
70
|
+
const BIN_NAMES = WIN32 ? ["ai-vault.exe", "ai-vault.cmd"] : ["ai-vault"];
|
|
71
|
+
|
|
61
72
|
/**
|
|
62
|
-
*
|
|
63
|
-
*
|
|
64
|
-
*
|
|
73
|
+
* What an npm `.cmd` wrapper starts, so that that can be started instead.
|
|
74
|
+
*
|
|
75
|
+
* npm links a package's bin as a sh script, a `.cmd` and a `.ps1` beside the
|
|
76
|
+
* real thing. Node refuses to run any of them without a shell on Windows
|
|
77
|
+
* (`spawn EINVAL`), and a shell would hand every argument to cmd.exe's parser.
|
|
78
|
+
* A `.cmd` is a fixed format, though; it ends with
|
|
79
|
+
*
|
|
80
|
+
* "%_prog%" "%dp0%\node_modules\pkg\bin\tool.js" %*
|
|
81
|
+
*
|
|
82
|
+
* so it is read, and what it names is started directly: a script with this
|
|
83
|
+
* very Node, anything else as the program it is.
|
|
65
84
|
*/
|
|
66
|
-
export function
|
|
85
|
+
export function npmShimLaunch(shim: string): CliLaunch | undefined {
|
|
86
|
+
let text: string;
|
|
87
|
+
try {
|
|
88
|
+
text = readFileSync(shim, "utf8");
|
|
89
|
+
} catch {
|
|
90
|
+
return undefined;
|
|
91
|
+
}
|
|
92
|
+
const target = /"%dp0%([^"\r\n]+)"\s*%\*/.exec(text)?.[1];
|
|
93
|
+
if (!target) return undefined;
|
|
94
|
+
const wrapped = join(dirname(shim), target);
|
|
95
|
+
if (!existsSync(wrapped)) return undefined;
|
|
96
|
+
return /\.[cm]?js$/i.test(wrapped) ? { program: process.execPath, pre: [wrapped] } : { program: wrapped, pre: [] };
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** A file that was found, as something `spawn` can start. */
|
|
100
|
+
function launchOf(candidate: string): CliLaunch | undefined {
|
|
101
|
+
if (!existsSync(candidate)) return undefined;
|
|
102
|
+
if (!WIN32) return { program: candidate, pre: [] };
|
|
103
|
+
const ext = extname(candidate).toLowerCase();
|
|
104
|
+
if (ext === ".exe" || ext === ".com") return { program: candidate, pre: [] };
|
|
105
|
+
if (ext === ".cmd" || ext === ".bat") return npmShimLaunch(candidate);
|
|
106
|
+
return undefined; // the sh script and the .ps1 need a shell as well
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* The prebuilt binary that came with this package: `@xiaolikt/ai-vault`
|
|
111
|
+
* depends on `@xiaolikt/ai-vault-<os>-<arch>`, resolved by Node from here, so
|
|
112
|
+
* a hoisted and a nested node_modules layout both work.
|
|
113
|
+
*/
|
|
114
|
+
function platformBinary(): CliLaunch | undefined {
|
|
115
|
+
const id = `@xiaolikt/ai-vault-${process.platform}-${process.arch}/package.json`;
|
|
116
|
+
try {
|
|
117
|
+
const manifest = createRequire(import.meta.url).resolve(id);
|
|
118
|
+
const binary = join(dirname(manifest), "bin", WIN32 ? "ai-vault.exe" : "ai-vault");
|
|
119
|
+
return existsSync(binary) ? { program: binary, pre: [] } : undefined;
|
|
120
|
+
} catch {
|
|
121
|
+
return undefined; // no prebuilt binary for this platform
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* `AI_VAULT_BIN`, then the prebuilt binary that came with this package, then
|
|
127
|
+
* the wrappers npm links in a node_modules/.bin next to or above the plugin,
|
|
128
|
+
* then PATH, then the usual install spots.
|
|
129
|
+
*
|
|
130
|
+
* On Windows the program is always a real executable: a wrapper is unwrapped
|
|
131
|
+
* to what it starts, never handed to `spawn` as it is.
|
|
132
|
+
*/
|
|
133
|
+
export function resolveLaunch(): CliLaunch | undefined {
|
|
67
134
|
const explicit = process.env.AI_VAULT_BIN;
|
|
68
|
-
if (explicit) return
|
|
135
|
+
if (explicit) return launchOf(explicit);
|
|
136
|
+
|
|
137
|
+
const bundled = platformBinary();
|
|
138
|
+
if (bundled) return bundled;
|
|
69
139
|
|
|
70
|
-
//
|
|
140
|
+
// npm layouts hoist differently: walk up from packages/pi-ai-vault/src.
|
|
71
141
|
let dir = dirname(fileURLToPath(import.meta.url));
|
|
72
142
|
for (let depth = 0; depth < 5; depth++) {
|
|
73
|
-
for (const name of
|
|
74
|
-
const
|
|
75
|
-
if (
|
|
143
|
+
for (const name of BIN_NAMES) {
|
|
144
|
+
const found = launchOf(join(dir, "node_modules", ".bin", name));
|
|
145
|
+
if (found) return found;
|
|
76
146
|
}
|
|
77
147
|
const parent = dirname(dir);
|
|
78
148
|
if (parent === dir) break;
|
|
79
149
|
dir = parent;
|
|
80
150
|
}
|
|
81
151
|
|
|
82
|
-
// Windows has no execute bit and npm links .cmd/.ps1 wrappers beside the exe.
|
|
83
|
-
const names = process.platform === "win32" ? ["ai-vault.exe", "ai-vault.cmd", "ai-vault.ps1", "ai-vault"] : ["ai-vault"];
|
|
84
152
|
for (const entry of (process.env.PATH ?? "").split(delimiter)) {
|
|
85
153
|
if (!entry) continue;
|
|
86
|
-
for (const name of
|
|
87
|
-
const
|
|
88
|
-
if (
|
|
154
|
+
for (const name of BIN_NAMES) {
|
|
155
|
+
const found = launchOf(join(entry, name));
|
|
156
|
+
if (found) return found;
|
|
89
157
|
}
|
|
90
158
|
}
|
|
91
159
|
for (const base of [join(homedir(), ".local", "bin"), join(homedir(), ".cargo", "bin"), join(homedir(), ".ai-vault", "bin")]) {
|
|
92
|
-
for (const name of
|
|
93
|
-
const
|
|
94
|
-
if (
|
|
160
|
+
for (const name of BIN_NAMES) {
|
|
161
|
+
const found = launchOf(join(base, name));
|
|
162
|
+
if (found) return found;
|
|
95
163
|
}
|
|
96
164
|
}
|
|
97
165
|
return undefined;
|
|
98
166
|
}
|
|
99
167
|
|
|
168
|
+
/** The program `resolveLaunch()` would start, for messages and the like. */
|
|
169
|
+
export function resolveBinary(): string | undefined {
|
|
170
|
+
return resolveLaunch()?.program;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* Start one CLI call. A program Node will not start is reported through
|
|
175
|
+
* `CliError` like every other failure, not thrown from inside the promise.
|
|
176
|
+
*/
|
|
177
|
+
function startCli(launch: CliLaunch, args: string[], env: NodeJS.ProcessEnv): ChildProcessWithoutNullStreams {
|
|
178
|
+
try {
|
|
179
|
+
// windowsHide: the CLI is a console program, and gets no window of its
|
|
180
|
+
// own when the host has none. The dialogs it opens are windows it opens
|
|
181
|
+
// on purpose, and show regardless.
|
|
182
|
+
return spawn(launch.program, [...launch.pre, ...args], { stdio: ["pipe", "pipe", "pipe"], env, windowsHide: true });
|
|
183
|
+
} catch (error) {
|
|
184
|
+
throw new CliError(EXIT.error, undefined, `cannot run ${launch.program}: ${error instanceof Error ? error.message : String(error)}`, "");
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
|
|
100
188
|
const NEEDS_UI = /^needs-ui:\s*(\w+)(?:\s+field=(\S+))?/m;
|
|
101
189
|
|
|
102
190
|
function message(stderr: string, fallback: string): string {
|
|
@@ -152,7 +240,9 @@ export class HostSecret {
|
|
|
152
240
|
}
|
|
153
241
|
|
|
154
242
|
export class VaultCli {
|
|
155
|
-
readonly
|
|
243
|
+
private readonly launch = resolveLaunch();
|
|
244
|
+
/** The program that gets started: `AI_VAULT_BIN` when that was set. */
|
|
245
|
+
readonly bin = this.launch?.program;
|
|
156
246
|
/** Set by the extension at startup; the same secret for every binding. */
|
|
157
247
|
host = new HostSecret();
|
|
158
248
|
|
|
@@ -166,15 +256,17 @@ export class VaultCli {
|
|
|
166
256
|
}
|
|
167
257
|
|
|
168
258
|
async run(args: string[], opts: { stdin?: string; signal?: AbortSignal } = {}): Promise<CliRun> {
|
|
169
|
-
const
|
|
170
|
-
if (!
|
|
259
|
+
const launch = this.launch;
|
|
260
|
+
if (!launch) {
|
|
171
261
|
throw new CliError(EXIT.error, undefined, "ai-vault CLI not found", "");
|
|
172
262
|
}
|
|
173
263
|
if (opts.signal?.aborted) {
|
|
174
264
|
throw new CliError(EXIT.denied, undefined, "aborted", "");
|
|
175
265
|
}
|
|
176
266
|
const run = await new Promise<CliRun>((resolve, reject) => {
|
|
177
|
-
|
|
267
|
+
// A program Node will not start fails here like any other CLI failure,
|
|
268
|
+
// not as a bare exception from inside the promise.
|
|
269
|
+
const child = startCli(launch, args, { ...process.env, ...this.host.env() });
|
|
178
270
|
let stdout = "";
|
|
179
271
|
let stderr = "";
|
|
180
272
|
const onAbort = () => child.kill("SIGKILL");
|
|
@@ -187,7 +279,7 @@ export class VaultCli {
|
|
|
187
279
|
});
|
|
188
280
|
child.on("error", (error) => {
|
|
189
281
|
opts.signal?.removeEventListener("abort", onAbort);
|
|
190
|
-
reject(new CliError(EXIT.error, undefined, `cannot run ${
|
|
282
|
+
reject(new CliError(EXIT.error, undefined, `cannot run ${launch.program}: ${error.message}`, ""));
|
|
191
283
|
});
|
|
192
284
|
child.on("close", (code) => {
|
|
193
285
|
opts.signal?.removeEventListener("abort", onAbort);
|
package/src/ente.ts
CHANGED
|
@@ -57,8 +57,11 @@ export function resolveEnte(): string | undefined {
|
|
|
57
57
|
if (explicit) return existsSync(explicit) ? explicit : undefined;
|
|
58
58
|
for (const dir of (process.env.PATH ?? "").split(delimiter)) {
|
|
59
59
|
if (!dir) continue;
|
|
60
|
-
|
|
61
|
-
|
|
60
|
+
// Windows: the program is ente.exe; the bare name matches no file there.
|
|
61
|
+
for (const name of process.platform === "win32" ? ["ente.exe", "ente"] : ["ente"]) {
|
|
62
|
+
const candidate = join(dir, name);
|
|
63
|
+
if (existsSync(candidate)) return candidate;
|
|
64
|
+
}
|
|
62
65
|
}
|
|
63
66
|
for (const candidate of [
|
|
64
67
|
join(homedir(), ".local", "opt", "ente-cli", "bin", "ente"),
|
package/src/index.ts
CHANGED
|
@@ -23,13 +23,13 @@ import {
|
|
|
23
23
|
type BitwardenMeta,
|
|
24
24
|
type BwState,
|
|
25
25
|
} from "./bitwarden.js";
|
|
26
|
-
import { CliError
|
|
26
|
+
import { CliError } from "./cli.js";
|
|
27
27
|
import { ITEM_TYPES, isSecretField, parseItemType } from "./import-map.js";
|
|
28
28
|
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, type Settings } from "./settings.js";
|
|
32
|
+
import { forgetSettings, getSettingsSafe, setSettingsToken, settingsCli, settingsToken, type Settings } from "./settings.js";
|
|
33
33
|
|
|
34
34
|
type Ctx = ExtensionToolContext | ExtensionCommandContext;
|
|
35
35
|
|
|
@@ -100,7 +100,7 @@ interface Scope {
|
|
|
100
100
|
unlocking?: Promise<boolean>;
|
|
101
101
|
}
|
|
102
102
|
|
|
103
|
-
const cli =
|
|
103
|
+
const cli = settingsCli();
|
|
104
104
|
|
|
105
105
|
const CLI_MISSING =
|
|
106
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 指向编译好的二进制)");
|
|
@@ -148,6 +148,8 @@ async function lockNow(scope: Scope): Promise<void> {
|
|
|
148
148
|
scope.token = undefined;
|
|
149
149
|
scope.epoch++;
|
|
150
150
|
scope.items = 0;
|
|
151
|
+
setSettingsToken(undefined);
|
|
152
|
+
forgetSettings();
|
|
151
153
|
if (!token || !cli.available) return;
|
|
152
154
|
try {
|
|
153
155
|
await cli.run(["lock", "--token", token]);
|
|
@@ -174,6 +176,7 @@ async function ensureUnlocked(scope: Scope, ctx: Ctx, signal?: AbortSignal): Pro
|
|
|
174
176
|
scope.items = status.items;
|
|
175
177
|
scope.mode = status.mode;
|
|
176
178
|
scope.auto = false;
|
|
179
|
+
setSettingsToken(scope.token);
|
|
177
180
|
return true;
|
|
178
181
|
} catch (error) {
|
|
179
182
|
if (!(error instanceof CliError) || !error.auth) {
|
|
@@ -194,6 +197,7 @@ async function ensureUnlocked(scope: Scope, ctx: Ctx, signal?: AbortSignal): Pro
|
|
|
194
197
|
scope.items = status.items;
|
|
195
198
|
scope.mode = status.mode;
|
|
196
199
|
scope.auto = status.auto;
|
|
200
|
+
setSettingsToken(undefined);
|
|
197
201
|
return true;
|
|
198
202
|
} catch (error) {
|
|
199
203
|
if (error instanceof CliError && /not initialized/i.test(error.message)) {
|
|
@@ -237,6 +241,7 @@ async function ensureUnlocked(scope: Scope, ctx: Ctx, signal?: AbortSignal): Pro
|
|
|
237
241
|
// per-binding token would bring back a confirm window on every read.
|
|
238
242
|
scope.token = result.mode === "never" ? undefined : result.token;
|
|
239
243
|
scope.items = result.items;
|
|
244
|
+
setSettingsToken(scope.token);
|
|
240
245
|
return true;
|
|
241
246
|
} catch (error) {
|
|
242
247
|
if (error instanceof CliError && error.auth) {
|
|
@@ -693,6 +698,7 @@ const HELP = [
|
|
|
693
698
|
tr("/vault init create the machine-wide encrypted store (a dialog sets the master password)", "/vault init 创建全机共享的本地加密库(弹出窗口设置主密码)"),
|
|
694
699
|
tr("/vault unlock | lock unlock / lock (clears this session's grants)", "/vault unlock | lock 解锁 / 锁定(清空本会话的授权)"),
|
|
695
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] 解锁后每次读取是否弹确认窗(关要主密码)"),
|
|
696
702
|
tr("/vault settings [key value] show/change settings (vault.unlock, bitwarden.*, ente.* …)", "/vault settings [键 值] 查看/修改设置(vault.unlock、bitwarden.*、ente.* …)"),
|
|
697
703
|
tr("/vault ente-key save Ente's ENTE_CLI_VAULT_KEY (no keychain, no login)", "/vault ente-key 保存 ente 的 ENTE_CLI_VAULT_KEY(免钥匙串/免登录)"),
|
|
698
704
|
tr("/vault status state and grants left", "/vault status 状态与授权剩余时间"),
|
|
@@ -861,22 +867,61 @@ function commandHandler(scope: Scope, bw: BwState) {
|
|
|
861
867
|
}
|
|
862
868
|
return;
|
|
863
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
|
+
}
|
|
864
909
|
case "settings": {
|
|
865
910
|
const [key, ...valueParts] = rest;
|
|
866
911
|
const value = valueParts.join(" ").trim();
|
|
867
912
|
try {
|
|
868
913
|
if (!key) {
|
|
869
|
-
note(ctx, settingsText(await cli.json<Settings>(["settings"])));
|
|
914
|
+
note(ctx, settingsText(await cli.json<Settings>(["settings", ...tokenArgs(scope)])));
|
|
870
915
|
return;
|
|
871
916
|
}
|
|
872
917
|
if (!value) {
|
|
873
|
-
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)]);
|
|
874
919
|
note(ctx, `${one.key}: ${one.value}`);
|
|
875
920
|
return;
|
|
876
921
|
}
|
|
877
922
|
// `vault.unlock` opens its own password window (or answers
|
|
878
923
|
// needs-ui); the other keys do not prompt at all.
|
|
879
|
-
const run = await cli.withPassword(["settings", key, value], () =>
|
|
924
|
+
const run = await cli.withPassword(["settings", key, value, ...tokenArgs(scope)], () =>
|
|
880
925
|
promptSecret(dialogs(ctx), tr("ai-vault · master password", "ai-vault · 主密码"), tr("changing the unlock policy needs verification", "改变解锁模式需要验证")),
|
|
881
926
|
);
|
|
882
927
|
forgetSettings();
|
package/src/settings.ts
CHANGED
|
@@ -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
|
+
});
|