@xiaolikt/ai-vault 0.0.0-stage → 0.5.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.
Files changed (41) hide show
  1. package/Cargo.lock +784 -0
  2. package/Cargo.toml +8 -0
  3. package/LICENSE +21 -0
  4. package/README.md +244 -2
  5. package/bin/ai-vault.cjs +71 -0
  6. package/crates/ai-vault/Cargo.toml +26 -0
  7. package/crates/ai-vault/src/audit.rs +77 -0
  8. package/crates/ai-vault/src/cli.rs +1129 -0
  9. package/crates/ai-vault/src/config.rs +77 -0
  10. package/crates/ai-vault/src/crypto.rs +265 -0
  11. package/crates/ai-vault/src/dialog.rs +222 -0
  12. package/crates/ai-vault/src/import.rs +175 -0
  13. package/crates/ai-vault/src/main.rs +22 -0
  14. package/crates/ai-vault/src/paths.rs +68 -0
  15. package/crates/ai-vault/src/session.rs +280 -0
  16. package/crates/ai-vault/src/store.rs +219 -0
  17. package/install.sh +21 -0
  18. package/package.json +76 -5
  19. package/packages/pi-ai-vault/README.md +62 -0
  20. package/packages/pi-ai-vault/package.json +47 -0
  21. package/packages/pi-ai-vault/src/bitwarden.ts +1482 -0
  22. package/packages/pi-ai-vault/src/cli.ts +171 -0
  23. package/packages/pi-ai-vault/src/host.ts +76 -0
  24. package/packages/pi-ai-vault/src/import-map.ts +91 -0
  25. package/packages/pi-ai-vault/src/index.ts +976 -0
  26. package/packages/pi-ai-vault/src/prompt.ts +195 -0
  27. package/packages/pi-ai-vault/src/scrub.ts +157 -0
  28. package/test/cli.sh +135 -0
  29. package/test/npm.sh +70 -0
  30. package/test/smoke.sh +77 -0
  31. package/tests/bitwarden-tools.test.mjs +330 -0
  32. package/tests/helpers.mjs +131 -0
  33. package/tests/import-map.test.mjs +74 -0
  34. package/tests/mocks/bin/bw +41 -0
  35. package/tests/mocks/bin/wl-copy +15 -0
  36. package/tests/mocks/bin/wl-paste +9 -0
  37. package/tests/mocks/bin/zenity +51 -0
  38. package/tests/prompt.test.mjs +200 -0
  39. package/tests/register.test.mjs +48 -0
  40. package/tests/scrub.test.mjs +98 -0
  41. package/tests/vault-cli.test.mjs +217 -0
@@ -0,0 +1,171 @@
1
+ /**
2
+ * Thin client for the `ai-vault` binary.
3
+ *
4
+ * The extension holds no key and does no cryptography: it asks the CLI to
5
+ * unlock (one desktop password window), keeps the session token, and passes
6
+ * that token back for every later call. Passwords are typed into the CLI's own
7
+ * windows; a headless machine answers exit code 3 ("needs-ui") and the host
8
+ * dialog takes over here.
9
+ */
10
+ import { spawn } from "node:child_process";
11
+ import { existsSync } from "node:fs";
12
+ import { homedir } from "node:os";
13
+ import { delimiter, dirname, join } from "node:path";
14
+ import { fileURLToPath } from "node:url";
15
+
16
+ export const EXIT = {
17
+ error: 1,
18
+ usage: 2,
19
+ needsUi: 3,
20
+ denied: 4,
21
+ auth: 5,
22
+ } as const;
23
+
24
+ /** Which dialog the CLI would have opened, when it cannot open one. */
25
+ export type UiStep = "password" | "text" | "confirm";
26
+
27
+ export interface CliRun {
28
+ code: number;
29
+ stdout: string;
30
+ stderr: string;
31
+ }
32
+
33
+ /** Non-zero exit from the CLI, with the meaning of the code preserved. */
34
+ export class CliError extends Error {
35
+ constructor(
36
+ readonly code: number,
37
+ readonly needsUi: UiStep | undefined,
38
+ message: string,
39
+ readonly stderr: string,
40
+ ) {
41
+ super(message);
42
+ this.name = "CliError";
43
+ }
44
+
45
+ get denied(): boolean {
46
+ return this.code === EXIT.denied;
47
+ }
48
+
49
+ get auth(): boolean {
50
+ return this.code === EXIT.auth;
51
+ }
52
+ }
53
+
54
+ /**
55
+ * `AI_VAULT_BIN`, then the copy this package depends on (npm puts the shim in
56
+ * a node_modules/.bin next to or above the plugin), then PATH, then the usual
57
+ * install spots.
58
+ */
59
+ export function resolveBinary(): string | undefined {
60
+ const explicit = process.env.AI_VAULT_BIN;
61
+ if (explicit) return existsSync(explicit) ? explicit : undefined;
62
+
63
+ // pip/npm layouts hoist differently: walk up from packages/pi-ai-vault/src.
64
+ let dir = dirname(fileURLToPath(import.meta.url));
65
+ for (let depth = 0; depth < 5; depth++) {
66
+ const bundled = join(dir, "node_modules", ".bin", "ai-vault");
67
+ if (existsSync(bundled)) return bundled;
68
+ const parent = dirname(dir);
69
+ if (parent === dir) break;
70
+ dir = parent;
71
+ }
72
+
73
+ for (const entry of (process.env.PATH ?? "").split(delimiter)) {
74
+ if (!entry) continue;
75
+ const candidate = join(entry, "ai-vault");
76
+ if (existsSync(candidate)) return candidate;
77
+ }
78
+ for (const candidate of [join(homedir(), ".local", "bin", "ai-vault"), join(homedir(), ".cargo", "bin", "ai-vault")]) {
79
+ if (existsSync(candidate)) return candidate;
80
+ }
81
+ return undefined;
82
+ }
83
+
84
+ const NEEDS_UI = /^needs-ui:\s*(\w+)/m;
85
+
86
+ function message(stderr: string, fallback: string): string {
87
+ const lines = stderr
88
+ .split(/\r?\n/)
89
+ .map((line) => line.trim())
90
+ .filter((line) => line.length > 0 && !line.startsWith("needs-ui:") && !line.startsWith("no desktop window"));
91
+ return lines[0]?.replace(/^ai-vault:\s*/, "") ?? fallback;
92
+ }
93
+
94
+ export class VaultCli {
95
+ readonly bin = resolveBinary();
96
+
97
+ get available(): boolean {
98
+ return this.bin !== undefined;
99
+ }
100
+
101
+ /** The store directory the CLI will use, for messages only. */
102
+ get dir(): string {
103
+ return process.env.AI_VAULT_DIR ?? join(homedir(), ".ai-vault");
104
+ }
105
+
106
+ async run(args: string[], opts: { stdin?: string; signal?: AbortSignal } = {}): Promise<CliRun> {
107
+ const bin = this.bin;
108
+ if (!bin) {
109
+ throw new CliError(EXIT.error, undefined, "ai-vault CLI not found", "");
110
+ }
111
+ if (opts.signal?.aborted) {
112
+ throw new CliError(EXIT.denied, undefined, "aborted", "");
113
+ }
114
+ const run = await new Promise<CliRun>((resolve, reject) => {
115
+ const child = spawn(bin, args, { stdio: ["pipe", "pipe", "pipe"] });
116
+ let stdout = "";
117
+ let stderr = "";
118
+ const onAbort = () => child.kill("SIGKILL");
119
+ opts.signal?.addEventListener("abort", onAbort, { once: true });
120
+ child.stdout?.on("data", (chunk: Buffer | string) => {
121
+ if (stdout.length < 32 * 1024 * 1024) stdout += chunk;
122
+ });
123
+ child.stderr?.on("data", (chunk: Buffer | string) => {
124
+ if (stderr.length < 256_000) stderr += chunk;
125
+ });
126
+ child.on("error", (error) => {
127
+ opts.signal?.removeEventListener("abort", onAbort);
128
+ reject(new CliError(EXIT.error, undefined, `cannot run ${bin}: ${error.message}`, ""));
129
+ });
130
+ child.on("close", (code) => {
131
+ opts.signal?.removeEventListener("abort", onAbort);
132
+ resolve({ code: code ?? -1, stdout, stderr });
133
+ });
134
+ // A dialog may keep stdin open for minutes; closing it early would
135
+ // make a password read fail, so only write when there is input.
136
+ if (opts.stdin !== undefined) child.stdin?.end(opts.stdin);
137
+ else child.stdin?.end();
138
+ });
139
+ if (run.code !== 0) {
140
+ const step = NEEDS_UI.exec(run.stderr)?.[1] as UiStep | undefined;
141
+ throw new CliError(run.code, step, message(run.stderr, `ai-vault exited with ${run.code}`), run.stderr);
142
+ }
143
+ return run;
144
+ }
145
+
146
+ /** One CLI call whose output is a JSON object. */
147
+ async json<T>(args: string[], opts: { stdin?: string; signal?: AbortSignal } = {}): Promise<T> {
148
+ const run = await this.run([...args, "--json"], opts);
149
+ try {
150
+ return JSON.parse(run.stdout) as T;
151
+ } catch {
152
+ throw new CliError(EXIT.error, undefined, `ai-vault returned non-JSON output: ${run.stdout.slice(0, 200)}`, run.stderr);
153
+ }
154
+ }
155
+
156
+ /** Start a call, turning a "needs-ui password" into the host secret dialog. */
157
+ async withPassword(
158
+ args: string[],
159
+ ask: () => Promise<string | undefined>,
160
+ opts: { stdin?: string; signal?: AbortSignal } = {},
161
+ ): Promise<CliRun> {
162
+ try {
163
+ return await this.run(args, opts);
164
+ } catch (error) {
165
+ if (!(error instanceof CliError) || !error.needsUi) throw error;
166
+ const password = await ask();
167
+ if (!password) throw new CliError(EXIT.denied, undefined, "cancelled: no password entered", "");
168
+ return this.run([...args, "--password-stdin"], { stdin: `${password}\n`, signal: opts.signal });
169
+ }
170
+ }
171
+ }
@@ -0,0 +1,76 @@
1
+ /**
2
+ * Where omp and upstream pi differ, kept in one place.
3
+ *
4
+ * omp is a pi-compatible fork: same package manifest, same tool and command
5
+ * API, so one extension serves both hosts. The differences are small and are
6
+ * feature-detected here instead of being spread through the code:
7
+ * - `api.pi` exists only on omp.
8
+ * - pi says why a session ended on `session_start` / `session_shutdown`;
9
+ * omp says it on `session_switch`, and its start and shutdown events carry
10
+ * no reason.
11
+ * - `ctx.agent` names the agent a binding serves (omp only).
12
+ * - omp tiers tools for its approval modes; pi has no such field.
13
+ */
14
+ import type { ExtensionAPI, ExtensionContext, ToolDefinition } from "@earendil-works/pi-coding-agent";
15
+
16
+ export function isOmpHost(pi: ExtensionAPI): boolean {
17
+ return "pi" in pi;
18
+ }
19
+
20
+ /**
21
+ * omp asks for approval by tier and defaults to "exec" when none is given, so
22
+ * a read-only tool would be prompted like a shell command. pi ignores the field.
23
+ */
24
+ export function withTier<T extends ToolDefinition<any, any>>(tool: T, approval: "read" | "write" | "exec"): T {
25
+ return { ...tool, approval } as T;
26
+ }
27
+
28
+ /** Why the bound session stopped being the one that unlocked. */
29
+ export type LeaveReason = "new" | "fork" | "resume" | "quit" | "reload";
30
+ type LeaveHandler = (reason: LeaveReason, ctx: ExtensionContext | undefined) => void | Promise<void>;
31
+
32
+ /**
33
+ * Call `handler` when the session served by this binding is left: `/new`,
34
+ * `/fork`, `/resume`, reload, or shutdown. Startup is not a leave.
35
+ */
36
+ export function onSessionLeave(pi: ExtensionAPI, omp: boolean, handler: LeaveHandler): void {
37
+ if (omp) {
38
+ // omp's `session_switch` and its reason-less `session_shutdown`. The start
39
+ // event has no reason, so it must never be read as one.
40
+ const on = (event: string, h: (event: { reason?: string }, ctx: ExtensionContext) => unknown) =>
41
+ (pi as unknown as { on(name: string, handler: typeof h): void }).on(event, h);
42
+ on("session_switch", (event, ctx) => handler((event.reason ?? "quit") as LeaveReason, ctx));
43
+ on("session_shutdown", (_event, ctx) => handler("quit", ctx));
44
+ return;
45
+ }
46
+ pi.on("session_start", async (event, ctx) => {
47
+ if (event.reason === "startup" || event.reason === "reload") return;
48
+ await handler(event.reason, ctx);
49
+ });
50
+ pi.on("session_shutdown", async (event, ctx) => {
51
+ await handler(event.reason, ctx);
52
+ });
53
+ }
54
+
55
+ /** The subagent this context serves, or undefined for a top-level session. */
56
+ export function subagentId(ctx: unknown): string | undefined {
57
+ const agent = (ctx as { agent?: { kind?: string; id?: string } } | undefined)?.agent;
58
+ return agent?.kind === "sub" && agent.id ? agent.id : undefined;
59
+ }
60
+
61
+ /**
62
+ * Short, stable label for the audit log: the first bytes of the session id,
63
+ * plus the agent id for a subagent.
64
+ */
65
+ export function sessionLabel(ctx: unknown): string {
66
+ let id = "";
67
+ try {
68
+ const manager = (ctx as { sessionManager?: { getSessionId?: () => string } } | undefined)?.sessionManager;
69
+ id = manager?.getSessionId?.() ?? "";
70
+ } catch {
71
+ /* a context without a session manager */
72
+ }
73
+ const base = id.replace(/-/g, "").slice(0, 8) || "main";
74
+ const sub = subagentId(ctx);
75
+ return sub ? `${base}/${sub.replace(/[^\w.-]/g, "").slice(0, 24) || "sub"}` : base;
76
+ }
@@ -0,0 +1,91 @@
1
+ /**
2
+ * Map a Bitwarden JSON export or `bw list items` payload onto local vault
3
+ * entries. Secrets stay in the returned objects for the caller to encrypt;
4
+ * this module never writes them.
5
+ */
6
+ export interface LoginDraft {
7
+ name: string;
8
+ username?: string;
9
+ password: string;
10
+ uris: string[];
11
+ notes?: string;
12
+ /** Bitwarden item id: a re-import updates the same entry even after a rename. */
13
+ source?: { kind: "bitwarden"; id: string };
14
+ }
15
+
16
+ function asItems(raw: unknown): unknown[] {
17
+ if (Array.isArray(raw)) return raw;
18
+ if (raw && typeof raw === "object") {
19
+ const rec = raw as { encrypted?: unknown; items?: unknown };
20
+ // An encrypted export carries ciphertext under `data`, not entries.
21
+ if (rec.encrypted === true) {
22
+ throw new Error(
23
+ "This is an encrypted Bitwarden export. Use `bw export --format json` (password-protected, unencrypted) or /vault import-bw.",
24
+ );
25
+ }
26
+ if (Array.isArray(rec.items)) return rec.items;
27
+ }
28
+ throw new Error("Not a Bitwarden export: expected an array of items or an object with `items`.");
29
+ }
30
+
31
+ function uriList(login: Record<string, unknown>): string[] {
32
+ if (!Array.isArray(login.uris)) return [];
33
+ return login.uris.flatMap((entry) => {
34
+ if (!entry || typeof entry !== "object" || !("uri" in entry)) return [];
35
+ const uri = (entry as { uri?: unknown }).uri;
36
+ return typeof uri === "string" && uri ? [uri] : [];
37
+ });
38
+ }
39
+
40
+ /**
41
+ * Login items that have a password. Names are sorted, then duplicates become
42
+ * `Name (2)`, `Name (3)`, … Each entry keeps its Bitwarden id, so a later
43
+ * import updates the same row even when the numbering shifts.
44
+ */
45
+ export function bitwardenLogins(raw: unknown): LoginDraft[] {
46
+ const drafts: LoginDraft[] = [];
47
+ for (const item of asItems(raw)) {
48
+ if (!item || typeof item !== "object") continue;
49
+ const rec = item as Record<string, unknown>;
50
+ if (!rec.login || typeof rec.login !== "object") continue;
51
+ const login = rec.login as Record<string, unknown>;
52
+ const password = typeof login.password === "string" ? login.password : "";
53
+ if (!password) continue;
54
+ const username = typeof login.username === "string" && login.username ? login.username : undefined;
55
+ const notes = typeof rec.notes === "string" && rec.notes ? rec.notes : undefined;
56
+ const nameRaw = typeof rec.name === "string" ? rec.name : "";
57
+ const name = nameRaw.replace(/[\r\n]+/g, " ").trim().slice(0, 200) || "unnamed";
58
+ const id = typeof rec.id === "string" && rec.id ? rec.id : undefined;
59
+ drafts.push({
60
+ name,
61
+ username,
62
+ password,
63
+ uris: uriList(login),
64
+ notes,
65
+ ...(id ? { source: { kind: "bitwarden" as const, id } } : {}),
66
+ });
67
+ }
68
+ drafts.sort(
69
+ (a, b) =>
70
+ a.name.localeCompare(b.name) ||
71
+ (a.username ?? "").localeCompare(b.username ?? "") ||
72
+ (a.uris[0] ?? "").localeCompare(b.uris[0] ?? ""),
73
+ );
74
+ const seen = new Map<string, number>();
75
+ for (const item of drafts) {
76
+ const key = item.name.toLowerCase();
77
+ const n = (seen.get(key) ?? 0) + 1;
78
+ seen.set(key, n);
79
+ if (n > 1) item.name = `${item.name} (${n})`;
80
+ }
81
+ return drafts;
82
+ }
83
+
84
+ /** Case-insensitive substring match on name, username, and URIs. */
85
+ export function filterLogins(items: LoginDraft[], search?: string): LoginDraft[] {
86
+ const query = (search ?? "").trim().toLowerCase();
87
+ if (!query) return items;
88
+ return items.filter((item) =>
89
+ `${item.name}\n${item.username ?? ""}\n${item.uris.join("\n")}`.toLowerCase().includes(query),
90
+ );
91
+ }