@xiaolikt/ai-vault 0.0.0-stage → 0.4.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 +784 -0
- package/Cargo.toml +8 -0
- package/LICENSE +21 -0
- package/README.md +188 -2
- package/bin/ai-vault.cjs +71 -0
- package/crates/ai-vault/Cargo.toml +26 -0
- package/crates/ai-vault/src/audit.rs +77 -0
- package/crates/ai-vault/src/cli.rs +942 -0
- package/crates/ai-vault/src/crypto.rs +265 -0
- package/crates/ai-vault/src/dialog.rs +222 -0
- package/crates/ai-vault/src/import.rs +175 -0
- package/crates/ai-vault/src/main.rs +21 -0
- package/crates/ai-vault/src/paths.rs +58 -0
- package/crates/ai-vault/src/session.rs +230 -0
- package/crates/ai-vault/src/store.rs +219 -0
- package/install.sh +21 -0
- package/package.json +76 -5
- package/src/bitwarden.ts +1450 -0
- package/src/cli.ts +155 -0
- package/src/host.ts +76 -0
- package/src/import-map.ts +91 -0
- package/src/index.ts +772 -0
- package/src/prompt.ts +195 -0
- package/src/scrub.ts +157 -0
- package/test/cli.sh +120 -0
- package/test/npm.sh +70 -0
- package/test/smoke.sh +77 -0
- package/tests/bitwarden-tools.test.mjs +330 -0
- package/tests/helpers.mjs +129 -0
- package/tests/import-map.test.mjs +74 -0
- package/tests/mocks/bin/bw +41 -0
- package/tests/mocks/bin/wl-copy +15 -0
- package/tests/mocks/bin/wl-paste +9 -0
- package/tests/mocks/bin/zenity +43 -0
- package/tests/prompt.test.mjs +200 -0
- package/tests/register.test.mjs +48 -0
- package/tests/scrub.test.mjs +98 -0
- package/tests/vault-cli.test.mjs +131 -0
|
@@ -0,0 +1,330 @@
|
|
|
1
|
+
import { test } from "node:test";
|
|
2
|
+
import assert from "node:assert/strict";
|
|
3
|
+
import { existsSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
|
|
4
|
+
import { randomBytes } from "node:crypto";
|
|
5
|
+
import { tmpdir } from "node:os";
|
|
6
|
+
import { join } from "node:path";
|
|
7
|
+
import { spawnSync } from "node:child_process";
|
|
8
|
+
import { answers, bind, cleanUpOnExit, dialogTrace, makeCtx, passwordPrompts, subCtx, textOf, useMocks } from "./helpers.mjs";
|
|
9
|
+
|
|
10
|
+
const dir = useMocks();
|
|
11
|
+
const { default: ompVault } = await import("../src/index.ts");
|
|
12
|
+
cleanUpOnExit(dir);
|
|
13
|
+
|
|
14
|
+
const SECRET = "supersecret-value-123";
|
|
15
|
+
const bwAudit = () => {
|
|
16
|
+
const file = join(process.env.HOME, ".bw", "pi-extension", "audit.log");
|
|
17
|
+
return existsSync(file) ? readFileSync(file, "utf8") : "";
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
test("one binding's lock does not destroy another binding's Bitwarden key", async () => {
|
|
21
|
+
// First test in the file: no earlier binding has left a key behind.
|
|
22
|
+
const first = bind(ompVault, true);
|
|
23
|
+
const second = bind(ompVault, true);
|
|
24
|
+
answers.master(dir, "testmaster", "testmaster");
|
|
25
|
+
await first.tool("bw_list", {}, makeCtx().ctx);
|
|
26
|
+
await second.tool("bw_list", {}, makeCtx().ctx);
|
|
27
|
+
|
|
28
|
+
await first.commands.get("bw").handler("lock", makeCtx().ctx);
|
|
29
|
+
assert.equal(existsSync(join(dir, "locked")), false, "the first lock ran a global bw lock");
|
|
30
|
+
|
|
31
|
+
await second.commands.get("bw").handler("lock", makeCtx().ctx);
|
|
32
|
+
assert.equal(existsSync(join(dir, "locked")), true, "the last lock did not run bw lock");
|
|
33
|
+
// Leave the mock back at its default password for the tests that follow.
|
|
34
|
+
answers.master(dir);
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
test("/bw subcommands are case-insensitive", async () => {
|
|
38
|
+
const b = bind(ompVault, true);
|
|
39
|
+
answers.master(dir, "testmaster");
|
|
40
|
+
await b.tool("bw_list", {}, makeCtx().ctx);
|
|
41
|
+
const ctx = makeCtx();
|
|
42
|
+
await b.commands.get("bw").handler("LOCK", ctx.ctx);
|
|
43
|
+
assert.match(ctx.last().message, /locked/);
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
test("omp: bw_run gives one command the secret and scrubs it and its base64, for short passwords too", async () => {
|
|
47
|
+
const b = bind(ompVault, true);
|
|
48
|
+
assert.equal(b.tools.has("bw_inject"), false, "bw_inject cannot work on omp, so it is not offered");
|
|
49
|
+
|
|
50
|
+
const out = textOf(
|
|
51
|
+
await b.tool("bw_run", {
|
|
52
|
+
item: "TestService",
|
|
53
|
+
command: 'echo LEN=${#VAULT_SECRET}; printf %s "$VAULT_SECRET" | base64; printf "\\n%s\\n" "$VAULT_SECRET"',
|
|
54
|
+
}),
|
|
55
|
+
);
|
|
56
|
+
assert.match(out, /LEN=21/);
|
|
57
|
+
assert.match(out, /\[BW_SCRUBBED:VAULT_SECRET\]/);
|
|
58
|
+
assert.match(out, /\[BW_SCRUBBED-B64:VAULT_SECRET\]/);
|
|
59
|
+
assert.equal(out.includes("c3VwZXJzZWNyZXQ"), false, "base64 of the secret leaked");
|
|
60
|
+
|
|
61
|
+
// 12 characters: below the old 16-character threshold for base64 scrubbing.
|
|
62
|
+
const short = textOf(await b.tool("bw_run", { item: "OtherService", command: 'printf %s "$VAULT_SECRET" | base64' }));
|
|
63
|
+
assert.equal(short.includes("b3RoZXItcHctOTk5"), false, "base64 of a short secret leaked");
|
|
64
|
+
assert.match(short, /\[BW_SCRUBBED-B64:VAULT_SECRET\]/);
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
test("a BW_SESSION exported in the host shell does not reach bw_run", async () => {
|
|
68
|
+
const b = bind(ompVault, true);
|
|
69
|
+
answers.master(dir, "testmaster");
|
|
70
|
+
answers.deny(dir, false);
|
|
71
|
+
const saved = process.env.BW_SESSION;
|
|
72
|
+
process.env.BW_SESSION = "LEAKED_HOST_SESSION";
|
|
73
|
+
try {
|
|
74
|
+
const out = textOf(
|
|
75
|
+
await b.tool("bw_run", { item: "TestService", command: 'printf "session=%s\\n" "${BW_SESSION:-unset}"' }),
|
|
76
|
+
);
|
|
77
|
+
assert.equal(out.includes("LEAKED_HOST_SESSION"), false);
|
|
78
|
+
assert.match(out, /session=unset/);
|
|
79
|
+
} finally {
|
|
80
|
+
if (saved === undefined) delete process.env.BW_SESSION;
|
|
81
|
+
else process.env.BW_SESSION = saved;
|
|
82
|
+
}
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
test("only bash's own temp output artifact can be scrubbed or removed", async () => {
|
|
86
|
+
const b = bind(ompVault, true);
|
|
87
|
+
answers.master(dir, "testmaster");
|
|
88
|
+
answers.deny(dir, false);
|
|
89
|
+
await b.tool("bw_run", { item: "TestService", command: "true" });
|
|
90
|
+
|
|
91
|
+
// A real bash artifact: scrubbed in place.
|
|
92
|
+
const artifact = join(tmpdir(), `pi-bash-${randomBytes(8).toString("hex")}.log`);
|
|
93
|
+
writeFileSync(artifact, `before ${SECRET} after`);
|
|
94
|
+
try {
|
|
95
|
+
await b.fire("tool_result", {
|
|
96
|
+
toolName: "bash",
|
|
97
|
+
content: [{ type: "text", text: "ok" }],
|
|
98
|
+
details: { fullOutputPath: artifact },
|
|
99
|
+
});
|
|
100
|
+
const text = readFileSync(artifact, "utf8");
|
|
101
|
+
assert.equal(text.includes(SECRET), false);
|
|
102
|
+
assert.match(text, /BW_SCRUBBED/);
|
|
103
|
+
} finally {
|
|
104
|
+
rmSync(artifact, { force: true });
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
// A non-bash result, or a bash result pointing outside the temp dir, is ignored.
|
|
108
|
+
const outside = mkdtempSync(join(tmpdir(), "ai-vault-artifact-"));
|
|
109
|
+
const big = join(outside, "big.log");
|
|
110
|
+
writeFileSync(big, "x".repeat(9 * 1024 * 1024));
|
|
111
|
+
try {
|
|
112
|
+
await b.fire("tool_result", {
|
|
113
|
+
toolName: "read",
|
|
114
|
+
content: [{ type: "text", text: "ok" }],
|
|
115
|
+
details: { fullOutputPath: big },
|
|
116
|
+
});
|
|
117
|
+
assert.equal(existsSync(big), true, "a non-bash result deleted a file");
|
|
118
|
+
await b.fire("tool_result", {
|
|
119
|
+
toolName: "bash",
|
|
120
|
+
content: [{ type: "text", text: "ok" }],
|
|
121
|
+
details: { fullOutputPath: big },
|
|
122
|
+
});
|
|
123
|
+
assert.equal(existsSync(big), true, "a bash result deleted a file outside the temp dir");
|
|
124
|
+
} finally {
|
|
125
|
+
rmSync(outside, { recursive: true, force: true });
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
// A symlink with an artifact name is not followed.
|
|
129
|
+
const targetDir = mkdtempSync(join(tmpdir(), "ai-vault-artifact-"));
|
|
130
|
+
const target = join(targetDir, "target");
|
|
131
|
+
writeFileSync(target, `target ${SECRET}`);
|
|
132
|
+
const link = join(tmpdir(), `pi-bash-${randomBytes(8).toString("hex")}.log`);
|
|
133
|
+
symlinkSync(target, link);
|
|
134
|
+
try {
|
|
135
|
+
await b.fire("tool_result", {
|
|
136
|
+
toolName: "bash",
|
|
137
|
+
content: [{ type: "text", text: "ok" }],
|
|
138
|
+
details: { fullOutputPath: link },
|
|
139
|
+
});
|
|
140
|
+
assert.match(readFileSync(target, "utf8"), /target/);
|
|
141
|
+
} finally {
|
|
142
|
+
rmSync(link, { force: true });
|
|
143
|
+
rmSync(targetDir, { recursive: true, force: true });
|
|
144
|
+
}
|
|
145
|
+
});
|
|
146
|
+
|
|
147
|
+
test("the confirm window names the entry that was really matched", async () => {
|
|
148
|
+
const b = bind(ompVault, true);
|
|
149
|
+
await b.tool("bw_run", { item: "Test", command: "true" });
|
|
150
|
+
assert.match(dialogTrace(dir), /--question .*Item: TestService \(user: alice\)⏎Field: password⏎Env: \$VAULT_SECRET/);
|
|
151
|
+
|
|
152
|
+
answers.deny(dir, true);
|
|
153
|
+
await assert.rejects(b.tool("bw_run", { item: "Test", command: "true" }), /User declined/);
|
|
154
|
+
assert.match(bwAudit(), /run session=\S+ deny item="TestService" field=password/);
|
|
155
|
+
answers.deny(dir, false);
|
|
156
|
+
});
|
|
157
|
+
|
|
158
|
+
test("a denied confirmation never fetches the entry; an approved one fetches it by id", async () => {
|
|
159
|
+
const b = bind(ompVault, true);
|
|
160
|
+
answers.master(dir, "testmaster");
|
|
161
|
+
answers.deny(dir, true);
|
|
162
|
+
rmSync(join(dir, "bw.log"), { force: true });
|
|
163
|
+
await assert.rejects(b.tool("bw_run", { item: "TestService", command: "true" }), /User declined/);
|
|
164
|
+
const denied = existsSync(join(dir, "bw.log")) ? readFileSync(join(dir, "bw.log"), "utf8") : "";
|
|
165
|
+
assert.equal(denied.includes("get item"), false, "the entry was fetched before the user agreed");
|
|
166
|
+
|
|
167
|
+
answers.deny(dir, false);
|
|
168
|
+
rmSync(join(dir, "bw.log"), { force: true });
|
|
169
|
+
await b.tool("bw_run", { item: "TestService", command: "true" });
|
|
170
|
+
assert.match(
|
|
171
|
+
readFileSync(join(dir, "bw.log"), "utf8"),
|
|
172
|
+
/get item aaaa1111-1111-4111-8111-111111111111/,
|
|
173
|
+
"the approved entry was not fetched by the id the window showed",
|
|
174
|
+
);
|
|
175
|
+
|
|
176
|
+
// An id is looked up in the listing, so a wrong one fails before any window.
|
|
177
|
+
await assert.rejects(
|
|
178
|
+
b.tool("bw_run", { item: "cccc3333-3333-4333-8333-333333333333", command: "true" }),
|
|
179
|
+
/No Bitwarden item with id cccc3333/,
|
|
180
|
+
);
|
|
181
|
+
});
|
|
182
|
+
|
|
183
|
+
test("the Bitwarden audit names the session, or the subagent, behind each command", async () => {
|
|
184
|
+
const b = bind(ompVault, true);
|
|
185
|
+
answers.master(dir, "testmaster", "testmaster");
|
|
186
|
+
answers.deny(dir, false);
|
|
187
|
+
const main = makeCtx();
|
|
188
|
+
await b.tool("bw_run", { item: "TestService", command: "true" }, main.ctx);
|
|
189
|
+
await b.tool("bw_run", { item: "TestService", command: "true" }, subCtx().ctx);
|
|
190
|
+
const log = bwAudit();
|
|
191
|
+
assert.match(log, new RegExp(`run session=${main.sid.replace(/-/g, "").slice(0, 8)} allow`));
|
|
192
|
+
assert.match(log, /run session=[0-9a-f]{8}\/0-Explore allow/);
|
|
193
|
+
});
|
|
194
|
+
|
|
195
|
+
test("omp: /new and /fork lock Bitwarden; session_start and /resume do not", async () => {
|
|
196
|
+
const b = bind(ompVault, true);
|
|
197
|
+
const ctx = makeCtx();
|
|
198
|
+
await b.tool("bw_list", {}, ctx.ctx);
|
|
199
|
+
const prompts = passwordPrompts(dir);
|
|
200
|
+
|
|
201
|
+
await b.fire("session_start", {}, ctx.ctx);
|
|
202
|
+
await b.fire("session_switch", { reason: "resume" }, ctx.ctx);
|
|
203
|
+
await b.tool("bw_list", {}, ctx.ctx);
|
|
204
|
+
assert.equal(passwordPrompts(dir), prompts, "session_start or /resume locked Bitwarden");
|
|
205
|
+
|
|
206
|
+
await b.fire("session_switch", { reason: "new" }, ctx.ctx);
|
|
207
|
+
await b.tool("bw_list", {}, ctx.ctx);
|
|
208
|
+
assert.equal(passwordPrompts(dir), prompts + 1, "/new did not lock Bitwarden");
|
|
209
|
+
|
|
210
|
+
await b.fire("session_switch", { reason: "fork" }, ctx.ctx);
|
|
211
|
+
await b.tool("bw_list", {}, ctx.ctx);
|
|
212
|
+
assert.equal(passwordPrompts(dir), prompts + 2, "/fork did not lock Bitwarden");
|
|
213
|
+
assert.match(bwAudit(), /lock session=\S+ reason=session-new/);
|
|
214
|
+
});
|
|
215
|
+
|
|
216
|
+
test("a second binding, a subagent or another session, does not inherit the unlock", async () => {
|
|
217
|
+
const first = bind(ompVault, true);
|
|
218
|
+
const second = bind(ompVault, true);
|
|
219
|
+
await first.tool("bw_list", {}, makeCtx().ctx);
|
|
220
|
+
const prompts = passwordPrompts(dir);
|
|
221
|
+
await second.tool("bw_list", {}, makeCtx().ctx);
|
|
222
|
+
assert.equal(passwordPrompts(dir), prompts + 1, "the second binding used the first one's unlock");
|
|
223
|
+
});
|
|
224
|
+
|
|
225
|
+
test("bw_reveal stays off until allowReveal is set", async () => {
|
|
226
|
+
const b = bind(ompVault, true);
|
|
227
|
+
await assert.rejects(b.tool("bw_reveal", { item: "TestService", reason: "test" }), /disabled/);
|
|
228
|
+
});
|
|
229
|
+
|
|
230
|
+
test("a session switch while the master password is being typed discards the unlock", async () => {
|
|
231
|
+
delete process.env.DISPLAY;
|
|
232
|
+
delete process.env.WAYLAND_DISPLAY;
|
|
233
|
+
try {
|
|
234
|
+
const b = bind(ompVault, true);
|
|
235
|
+
let answer;
|
|
236
|
+
const ctx = makeCtx({ input: () => new Promise((resolve) => (answer = resolve)) });
|
|
237
|
+
const pending = b.tool("bw_list", {}, ctx.ctx).then(
|
|
238
|
+
() => "resolved",
|
|
239
|
+
(error) => error.message,
|
|
240
|
+
);
|
|
241
|
+
for (let i = 0; i < 50 && !answer; i++) await new Promise((resolve) => setImmediate(resolve));
|
|
242
|
+
assert.equal(typeof answer, "function", "the password dialog opened");
|
|
243
|
+
|
|
244
|
+
await b.fire("session_switch", { reason: "new" }, ctx.ctx);
|
|
245
|
+
answer("testmaster");
|
|
246
|
+
assert.equal(await pending, "Cancelled.");
|
|
247
|
+
} finally {
|
|
248
|
+
process.env.DISPLAY = ":99";
|
|
249
|
+
}
|
|
250
|
+
});
|
|
251
|
+
|
|
252
|
+
test("bw_run stops buffering runaway output instead of growing without bound", async () => {
|
|
253
|
+
const b = bind(ompVault, true);
|
|
254
|
+
const result = await b.tool("bw_run", { item: "TestService", command: "head -c 10485760 /dev/zero | tr '\\0' x" });
|
|
255
|
+
assert.equal(result.details.truncated, true);
|
|
256
|
+
assert.match(textOf(result), /output past 8 MiB was dropped/);
|
|
257
|
+
});
|
|
258
|
+
|
|
259
|
+
test("a timed-out bw_run takes the processes it spawned down with it", async () => {
|
|
260
|
+
const b = bind(ompVault, true);
|
|
261
|
+
await assert.rejects(b.tool("bw_run", { item: "TestService", command: "sleep 987 & wait", timeout: 1 }), /timed out/);
|
|
262
|
+
await new Promise((resolve) => setTimeout(resolve, 200));
|
|
263
|
+
assert.equal(spawnSync("pgrep", ["-f", "sleep 987"]).status, 1, "the spawned sleep outlived the command");
|
|
264
|
+
});
|
|
265
|
+
|
|
266
|
+
test("bw_clipboard copies the value without it entering the result, and registers it for scrubbing", async () => {
|
|
267
|
+
delete process.env.DISPLAY;
|
|
268
|
+
process.env.WAYLAND_DISPLAY = "wayland-99";
|
|
269
|
+
// A custom field that no earlier test has put in the scrub list.
|
|
270
|
+
const CLIP = "hf_sk-abc987xyz456";
|
|
271
|
+
try {
|
|
272
|
+
const b = bind(ompVault, true);
|
|
273
|
+
const out = textOf(await b.tool("bw_clipboard", { item: "TestService", field: "field:API_KEY" }));
|
|
274
|
+
assert.match(out, /Copied "TestService" \(field:API_KEY\) to clipboard/);
|
|
275
|
+
assert.equal(out.includes(CLIP), false);
|
|
276
|
+
assert.equal(readFileSync(join(dir, "clipboard"), "utf8"), CLIP);
|
|
277
|
+
|
|
278
|
+
// `pbpaste`/`xclip -o`/`wl-paste` in bash can now read the value back,
|
|
279
|
+
// so its appearance in any tool result must be scrubbed.
|
|
280
|
+
const [scrubbed] = await b.fire("tool_result", {
|
|
281
|
+
toolName: "bash",
|
|
282
|
+
content: [{ type: "text", text: `clip=${CLIP}` }],
|
|
283
|
+
details: {},
|
|
284
|
+
});
|
|
285
|
+
assert.match(textOf(scrubbed), /\[BW_SCRUBBED:CLIPBOARD\]/);
|
|
286
|
+
assert.equal(textOf(scrubbed).includes(CLIP), false);
|
|
287
|
+
} finally {
|
|
288
|
+
delete process.env.WAYLAND_DISPLAY;
|
|
289
|
+
process.env.DISPLAY = ":99";
|
|
290
|
+
}
|
|
291
|
+
});
|
|
292
|
+
|
|
293
|
+
test("a lock that runs while a copy is in flight clears the value when it lands", async () => {
|
|
294
|
+
delete process.env.DISPLAY;
|
|
295
|
+
process.env.WAYLAND_DISPLAY = "wayland-99";
|
|
296
|
+
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
297
|
+
const hold = join(dir, "clipboard-hold");
|
|
298
|
+
const started = join(dir, "clipboard-started");
|
|
299
|
+
const clipboardText = () => (existsSync(join(dir, "clipboard")) ? readFileSync(join(dir, "clipboard"), "utf8") : "");
|
|
300
|
+
writeFileSync(hold, "");
|
|
301
|
+
try {
|
|
302
|
+
const b = bind(ompVault, true);
|
|
303
|
+
answers.master(dir, "testmaster");
|
|
304
|
+
answers.deny(dir, false);
|
|
305
|
+
const ctx = makeCtx();
|
|
306
|
+
const pending = b.tool("bw_clipboard", { item: "OtherService" }, ctx.ctx).then(
|
|
307
|
+
(result) => result,
|
|
308
|
+
(error) => error,
|
|
309
|
+
);
|
|
310
|
+
for (let i = 0; i < 200 && !existsSync(started); i++) await sleep(10);
|
|
311
|
+
assert.ok(existsSync(started), "the copy started");
|
|
312
|
+
|
|
313
|
+
await b.commands.get("bw").handler("lock", ctx.ctx);
|
|
314
|
+
const outcome = await pending;
|
|
315
|
+
assert.ok(outcome instanceof Error, "a copy that crossed a lock must not report success");
|
|
316
|
+
assert.match(outcome.message, /locked while copying/);
|
|
317
|
+
|
|
318
|
+
// The held copy lands the value only now; the delayed clear takes it away.
|
|
319
|
+
rmSync(hold, { force: true });
|
|
320
|
+
for (let i = 0; i < 300 && clipboardText() !== "other-pw-999"; i++) await sleep(10);
|
|
321
|
+
assert.equal(clipboardText(), "other-pw-999", "the held copy landed");
|
|
322
|
+
for (let i = 0; i < 300 && clipboardText() !== ""; i++) await sleep(10);
|
|
323
|
+
assert.equal(clipboardText(), "", "the clipboard kept the secret after the lock");
|
|
324
|
+
} finally {
|
|
325
|
+
rmSync(hold, { force: true });
|
|
326
|
+
rmSync(started, { force: true });
|
|
327
|
+
delete process.env.WAYLAND_DISPLAY;
|
|
328
|
+
process.env.DISPLAY = ":99";
|
|
329
|
+
}
|
|
330
|
+
});
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
// Shared setup for the ai-vault tests: a throwaway HOME and vault, a mock
|
|
2
|
+
// `bw` CLI, and a mock `zenity` that answers from queue files.
|
|
3
|
+
import { spawnSync } from "node:child_process";
|
|
4
|
+
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
5
|
+
import { tmpdir } from "node:os";
|
|
6
|
+
import { dirname, join } from "node:path";
|
|
7
|
+
import { fileURLToPath } from "node:url";
|
|
8
|
+
|
|
9
|
+
export const MOCKS = join(dirname(fileURLToPath(import.meta.url)), "mocks", "bin");
|
|
10
|
+
const ROOT = join(dirname(fileURLToPath(import.meta.url)), "..");
|
|
11
|
+
|
|
12
|
+
/** The Rust binary the extension calls: $AI_VAULT_BIN, else a local build. */
|
|
13
|
+
export function cliBinary() {
|
|
14
|
+
const explicit = process.env.AI_VAULT_BIN;
|
|
15
|
+
if (explicit) return explicit;
|
|
16
|
+
for (const profile of ["release", "debug"]) {
|
|
17
|
+
const candidate = join(ROOT, "target", profile, "ai-vault");
|
|
18
|
+
if (existsSync(candidate)) return candidate;
|
|
19
|
+
}
|
|
20
|
+
const built = spawnSync("cargo", ["build", "--release"], { cwd: ROOT, stdio: "inherit" });
|
|
21
|
+
if (built.status !== 0) throw new Error("cannot build the ai-vault CLI; run `cargo build --release`");
|
|
22
|
+
return join(ROOT, "target", "release", "ai-vault");
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Point the process at the mocks and at a private HOME, so nothing touches the
|
|
27
|
+
* user's real vault, Bitwarden config, or audit log. Call before importing
|
|
28
|
+
* anything under src/: module state is created at import time.
|
|
29
|
+
*/
|
|
30
|
+
export function useMocks() {
|
|
31
|
+
const dir = mkdtempSync(join(tmpdir(), "ai-vault-test-"));
|
|
32
|
+
mkdirSync(join(dir, "home"), { recursive: true });
|
|
33
|
+
process.env.HOME = join(dir, "home");
|
|
34
|
+
process.env.DISPLAY = ":99";
|
|
35
|
+
delete process.env.WAYLAND_DISPLAY;
|
|
36
|
+
process.env.PATH = `${MOCKS}:${process.env.PATH}`;
|
|
37
|
+
process.env.OMP_VAULT_BW_MOCK_DIR = dir;
|
|
38
|
+
process.env.OMP_VAULT_MOCK = dir;
|
|
39
|
+
process.env.AI_VAULT_DIR = join(dir, "vault");
|
|
40
|
+
process.env.AI_VAULT_BIN = cliBinary();
|
|
41
|
+
return dir;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Remove the throwaway directory when the process exits. Call after importing src/. */
|
|
45
|
+
export function cleanUpOnExit(dir) {
|
|
46
|
+
// Registered after the extension's own exit handler, so that handler still
|
|
47
|
+
// finds its mock clipboard and the directory goes last.
|
|
48
|
+
process.on("exit", () => rmSync(dir, { recursive: true, force: true }));
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Answers the mock dialogs give, in the order they are asked. Each call
|
|
53
|
+
* replaces its queue, so a prompt that never opened cannot leak into a later one.
|
|
54
|
+
*/
|
|
55
|
+
export const answers = {
|
|
56
|
+
/** Master-password dialogs, local or Bitwarden. */
|
|
57
|
+
master: (dir, ...lines) => writeFileSync(join(dir, "passwords"), lines.map((l) => `${l}\n`).join("")),
|
|
58
|
+
/** The dialog that types a new entry's password. */
|
|
59
|
+
entryPassword: (dir, password) => writeFileSync(join(dir, "entry-passwords"), `${password}\n`),
|
|
60
|
+
entries: (dir, ...lines) => writeFileSync(join(dir, "entries"), lines.map((l) => `${l}\n`).join("")),
|
|
61
|
+
deny: (dir, on = true) =>
|
|
62
|
+
on ? writeFileSync(join(dir, "deny"), "") : rmSync(join(dir, "deny"), { force: true }),
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
/** Every dialog the code opened, one line per call. */
|
|
66
|
+
export const dialogTrace = (dir) =>
|
|
67
|
+
existsSync(join(dir, "zenity.log")) ? readFileSync(join(dir, "zenity.log"), "utf8") : "";
|
|
68
|
+
export const passwordPrompts = (dir) => dialogTrace(dir).split("\n").filter((l) => l.startsWith("--password")).length;
|
|
69
|
+
|
|
70
|
+
let seq = 0;
|
|
71
|
+
const uuid = () => `${(0x10000000 + ++seq).toString(16)}-1111-4111-8111-111111111111`;
|
|
72
|
+
|
|
73
|
+
/** A host context. `input` and `confirm` replace the host dialog (used when no window can open). */
|
|
74
|
+
export function makeCtx({ sessionId, agent, hasUI = true, input, confirm } = {}) {
|
|
75
|
+
const notes = [];
|
|
76
|
+
const sid = sessionId ?? uuid();
|
|
77
|
+
const ctx = {
|
|
78
|
+
hasUI,
|
|
79
|
+
cwd: process.env.OMP_VAULT_BW_MOCK_DIR,
|
|
80
|
+
mode: "tui",
|
|
81
|
+
sessionManager: { getSessionId: () => sid },
|
|
82
|
+
agent,
|
|
83
|
+
model: { provider: "test-provider" },
|
|
84
|
+
ui: {
|
|
85
|
+
notify: (message, type = "info") => notes.push({ type, message }),
|
|
86
|
+
setStatus() {},
|
|
87
|
+
input: (title, placeholder) => (input ? input(title, placeholder) : Promise.resolve(undefined)),
|
|
88
|
+
confirm: (title, message) => (confirm ? confirm(title, message) : Promise.resolve(false)),
|
|
89
|
+
},
|
|
90
|
+
};
|
|
91
|
+
return {
|
|
92
|
+
ctx,
|
|
93
|
+
notes,
|
|
94
|
+
sid,
|
|
95
|
+
last: () => notes.at(-1),
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
const SUBAGENT = { kind: "sub", id: "0-Explore", name: "explore", depth: 0, parentId: "Main" };
|
|
100
|
+
export const subCtx = (options) => makeCtx({ agent: SUBAGENT, ...options });
|
|
101
|
+
|
|
102
|
+
/** Run the extension factory against a recording API. `omp: false` is upstream pi. */
|
|
103
|
+
export function bind(ompVault, omp = true) {
|
|
104
|
+
const tools = new Map();
|
|
105
|
+
const commands = new Map();
|
|
106
|
+
const handlers = new Map();
|
|
107
|
+
const api = {
|
|
108
|
+
registerTool: (tool) => tools.set(tool.name, tool),
|
|
109
|
+
registerCommand: (name, def) => commands.set(name, def),
|
|
110
|
+
on: (event, handler) => {
|
|
111
|
+
if (!handlers.has(event)) handlers.set(event, []);
|
|
112
|
+
handlers.get(event).push(handler);
|
|
113
|
+
return () => {};
|
|
114
|
+
},
|
|
115
|
+
};
|
|
116
|
+
if (omp) api.pi = {};
|
|
117
|
+
ompVault(api);
|
|
118
|
+
return {
|
|
119
|
+
tools,
|
|
120
|
+
commands,
|
|
121
|
+
has: (event) => handlers.has(event),
|
|
122
|
+
fire: (event, payload = {}, ctx = makeCtx().ctx) =>
|
|
123
|
+
Promise.all((handlers.get(event) ?? []).map((handler) => handler(payload, ctx))),
|
|
124
|
+
tool: (name, params, ctx = makeCtx().ctx) => tools.get(name).execute("call", params, undefined, undefined, ctx),
|
|
125
|
+
cmd: (args, ctx = makeCtx().ctx) => commands.get("vault").handler(args, ctx),
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
export const textOf = (result) => result.content.find((block) => block.type === "text")?.text ?? "";
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { test } from "node:test";
|
|
2
|
+
import assert from "node:assert/strict";
|
|
3
|
+
import { bitwardenLogins, filterLogins } from "../src/import-map.ts";
|
|
4
|
+
|
|
5
|
+
const item = (name, extra = {}) => ({
|
|
6
|
+
id: extra.id,
|
|
7
|
+
name,
|
|
8
|
+
login: { username: extra.username, password: extra.password ?? "pw-value-1", uris: extra.uri ? [{ uri: extra.uri }] : [] },
|
|
9
|
+
notes: extra.notes,
|
|
10
|
+
});
|
|
11
|
+
|
|
12
|
+
test("reads a Bitwarden export object and a raw array", () => {
|
|
13
|
+
const fromExport = bitwardenLogins({
|
|
14
|
+
items: [item("GitHub", { username: "me", uri: "https://github.com", notes: "n" })],
|
|
15
|
+
});
|
|
16
|
+
const fromArray = bitwardenLogins([item("GitHub", { username: "me", uri: "https://github.com", notes: "n" })]);
|
|
17
|
+
assert.equal(fromExport.length, 1);
|
|
18
|
+
assert.deepEqual(fromExport[0], {
|
|
19
|
+
name: "GitHub",
|
|
20
|
+
username: "me",
|
|
21
|
+
password: "pw-value-1",
|
|
22
|
+
uris: ["https://github.com"],
|
|
23
|
+
notes: "n",
|
|
24
|
+
});
|
|
25
|
+
assert.deepEqual(fromArray, fromExport);
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
test("each entry keeps the id of the Bitwarden item it came from", () => {
|
|
29
|
+
const [draft] = bitwardenLogins({ items: [item("Cloud", { id: "bw-1", username: "root" })] });
|
|
30
|
+
assert.deepEqual(draft.source, { kind: "bitwarden", id: "bw-1" });
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
test("an encrypted export is refused instead of importing nothing", () => {
|
|
34
|
+
assert.throws(
|
|
35
|
+
() => bitwardenLogins({ encrypted: true, encKeyValidation: "…", data: "2.0|…" }),
|
|
36
|
+
/encrypted Bitwarden export/,
|
|
37
|
+
);
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
test("a payload that is neither an export nor an item array is refused", () => {
|
|
41
|
+
assert.throws(() => bitwardenLogins({ hello: "world" }), /Not a Bitwarden export/);
|
|
42
|
+
assert.throws(() => bitwardenLogins(null), /Not a Bitwarden export/);
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
test("skips items with no login password and blank names", () => {
|
|
46
|
+
const drafts = bitwardenLogins({
|
|
47
|
+
items: [
|
|
48
|
+
{ name: "note-only", notes: "x" },
|
|
49
|
+
{ name: "empty-login", login: { username: "a", password: "" } },
|
|
50
|
+
{ name: " \n", login: { password: "pw-value-1" } },
|
|
51
|
+
],
|
|
52
|
+
});
|
|
53
|
+
assert.equal(drafts.length, 1);
|
|
54
|
+
assert.equal(drafts[0].name, "unnamed");
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
test("disambiguates duplicate names in a stable order", () => {
|
|
58
|
+
const drafts = bitwardenLogins([item("GitHub", { username: "b" }), item("GitHub", { username: "a" }), item("Other", { username: "z" })]);
|
|
59
|
+
assert.deepEqual(
|
|
60
|
+
drafts.map((d) => `${d.name}|${d.username}`),
|
|
61
|
+
["GitHub|a", "GitHub (2)|b", "Other|z"],
|
|
62
|
+
);
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
test("filter matches name, username, and uri", () => {
|
|
66
|
+
const drafts = bitwardenLogins([
|
|
67
|
+
item("GitHub", { username: "octo", uri: "https://github.com" }),
|
|
68
|
+
item("Mail", { username: "me", uri: "https://mail.example" }),
|
|
69
|
+
]);
|
|
70
|
+
assert.equal(filterLogins(drafts, "octo").length, 1);
|
|
71
|
+
assert.equal(filterLogins(drafts, "mail.example")[0].name, "Mail");
|
|
72
|
+
assert.equal(filterLogins(drafts, "nope").length, 0);
|
|
73
|
+
assert.equal(filterLogins(drafts, " ").length, 2);
|
|
74
|
+
});
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
#!/bin/bash
|
|
2
|
+
# Mock Bitwarden CLI for the omp-vault tests: two items, one session key.
|
|
3
|
+
# Controlled via env: OMP_VAULT_BW_MOCK_UNAUTH=1 (unauthenticated), OMP_VAULT_BW_MOCK_DIR (state dir).
|
|
4
|
+
MOCK_DIR="${OMP_VAULT_BW_MOCK_DIR:-/tmp/bw-mock-state}"
|
|
5
|
+
mkdir -p "$MOCK_DIR"
|
|
6
|
+
args="$*"
|
|
7
|
+
# One line per call, arguments only (a session key travels in the env, never here).
|
|
8
|
+
[[ "$1" == "--version" ]] || printf '%s\n' "$*" >> "$MOCK_DIR/bw.log"
|
|
9
|
+
if [[ "$1" == "--version" ]]; then echo "mock-1.0.0"; exit 0; fi
|
|
10
|
+
if [[ -f "$MOCK_DIR/locked" ]]; then
|
|
11
|
+
# Simulate an external lock (e.g. /bw lock in another pi session)
|
|
12
|
+
rm -f "$MOCK_DIR/locked"
|
|
13
|
+
fi
|
|
14
|
+
case "$args" in
|
|
15
|
+
"status --nointeraction")
|
|
16
|
+
if [[ "${OMP_VAULT_BW_MOCK_UNAUTH:-0}" == "1" ]]; then
|
|
17
|
+
echo '{"serverUrl":null,"lastSync":null,"status":"unauthenticated"}'
|
|
18
|
+
elif [[ "$BW_SESSION" == "GOOD_SESSION" ]]; then
|
|
19
|
+
echo '{"serverUrl":"https://vault.example.com","status":"unlocked","userEmail":"t@example.com"}'
|
|
20
|
+
else
|
|
21
|
+
echo '{"serverUrl":"https://vault.example.com","status":"locked","userEmail":"t@example.com"}'
|
|
22
|
+
fi ;;
|
|
23
|
+
"unlock --passwordenv BW_MASTER_PASSWORD --raw")
|
|
24
|
+
echo "$(( $(cat "$MOCK_DIR/unlocks" 2>/dev/null || echo 0) + 1 ))" > "$MOCK_DIR/unlocks"
|
|
25
|
+
if [[ "$BW_MASTER_PASSWORD" == "testmaster" ]]; then
|
|
26
|
+
touch "$MOCK_DIR/session"
|
|
27
|
+
echo "GOOD_SESSION"
|
|
28
|
+
else
|
|
29
|
+
echo "wrong pw" >&2; exit 1
|
|
30
|
+
fi ;;
|
|
31
|
+
"sync --nointeraction") exit 0 ;;
|
|
32
|
+
"list items --nointeraction")
|
|
33
|
+
echo '[{"id":"aaaa1111-1111-4111-8111-111111111111","name":"TestService","login":{"username":"alice","password":"supersecret-value-123","totp":null,"uris":[{"uri":"https://test.example.com"}]},"notes":"note-secret-abc","fields":[{"name":"API_KEY","value":"hf_sk-abc987xyz456","type":1}]},{"id":"bbbb2222-2222-4222-8222-222222222222","name":"OtherService","login":{"username":"bob","password":"other-pw-999","uris":[]},"fields":[]}]' ;;
|
|
34
|
+
"get item aaaa1111-1111-4111-8111-111111111111 --nointeraction")
|
|
35
|
+
echo '{"id":"aaaa1111-1111-4111-8111-111111111111","name":"TestService","login":{"username":"alice","password":"supersecret-value-123","uris":[]},"fields":[{"name":"API_KEY","value":"hf_sk-abc987xyz456","type":1}]}' ;;
|
|
36
|
+
"get item bbbb2222-2222-4222-8222-222222222222 --nointeraction")
|
|
37
|
+
echo '{"id":"bbbb2222-2222-4222-8222-222222222222","name":"OtherService","login":{"username":"bob","password":"other-pw-999","uris":[]},"fields":[]}' ;;
|
|
38
|
+
"lock --nointeraction") touch "$MOCK_DIR/locked"; exit 0 ;;
|
|
39
|
+
"get item "*" --nointeraction") echo "Not found." >&2; exit 1 ;;
|
|
40
|
+
*) echo "mock bw: unhandled: $args" >&2; exit 1 ;;
|
|
41
|
+
esac
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
#!/bin/bash
|
|
2
|
+
# Mock wl-copy: capture stdin into the mock clipboard file and keep a copy log
|
|
3
|
+
# (the real auto-clear wipes the clipboard, so tests assert on the copy log).
|
|
4
|
+
MOCK_DIR="${OMP_VAULT_BW_MOCK_DIR:-/tmp/bw-mock-state}"
|
|
5
|
+
mkdir -p "$MOCK_DIR"
|
|
6
|
+
if [[ "${1:-}" == "-c" ]]; then : > "$MOCK_DIR/clipboard"; exit 0; fi
|
|
7
|
+
# Test hook: while a `clipboard-hold` file exists, announce the copy and wait
|
|
8
|
+
# before taking the value, so a lock can run while the copy is in flight.
|
|
9
|
+
if [[ -f "$MOCK_DIR/clipboard-hold" ]]; then
|
|
10
|
+
: > "$MOCK_DIR/clipboard-started"
|
|
11
|
+
while [[ -f "$MOCK_DIR/clipboard-hold" ]]; do sleep 0.02; done
|
|
12
|
+
fi
|
|
13
|
+
cat > "$MOCK_DIR/clipboard"
|
|
14
|
+
cat "$MOCK_DIR/clipboard" >> "$MOCK_DIR/clipboard.copies"
|
|
15
|
+
printf '\n' >> "$MOCK_DIR/clipboard.copies"
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
#!/bin/bash
|
|
2
|
+
# Mock wl-paste: read the mock clipboard so auto-clear can verify ownership.
|
|
3
|
+
MOCK_DIR="${OMP_VAULT_BW_MOCK_DIR:-/tmp/bw-mock-state}"
|
|
4
|
+
if [[ "${1:-}" == "--no-newline" ]]; then
|
|
5
|
+
printf '%s' "$(cat "$MOCK_DIR/clipboard" 2>/dev/null)"
|
|
6
|
+
else
|
|
7
|
+
cat "$MOCK_DIR/clipboard" 2>/dev/null
|
|
8
|
+
fi
|
|
9
|
+
exit 0
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
#!/bin/bash
|
|
2
|
+
# Mock zenity for the ai-vault tests. Every call is one line in
|
|
3
|
+
# $OMP_VAULT_MOCK/zenity.log (newlines inside an argument show as ⏎).
|
|
4
|
+
# --password a master-password dialog (its title says 主密码) answers with
|
|
5
|
+
# the first line of $OMP_VAULT_MOCK/passwords, or "testmaster"
|
|
6
|
+
# when that file is missing or empty; any other password dialog
|
|
7
|
+
# answers with the first line of $OMP_VAULT_MOCK/entry-passwords
|
|
8
|
+
# --entry first line of $OMP_VAULT_MOCK/entries; empty when the file is gone
|
|
9
|
+
# --question allow, unless $OMP_VAULT_MOCK/deny exists (then exit 1)
|
|
10
|
+
DIR="${OMP_VAULT_MOCK:-/tmp/omp-vault-mock}"
|
|
11
|
+
mkdir -p "$DIR"
|
|
12
|
+
printf '%s\n' "${*//$'\n'/⏎}" >> "$DIR/zenity.log"
|
|
13
|
+
take_first() {
|
|
14
|
+
local first rest
|
|
15
|
+
first="$(head -n 1 "$1" 2>/dev/null)"
|
|
16
|
+
rest="$(tail -n +2 "$1" 2>/dev/null)"
|
|
17
|
+
# An exhausted queue is removed, not left as an empty line: the next dialog
|
|
18
|
+
# then falls back to its default instead of reading an empty answer.
|
|
19
|
+
if [[ -n "$rest" ]]; then printf '%s\n' "$rest" > "$1"; else rm -f "$1"; fi
|
|
20
|
+
printf '%s\n' "$first"
|
|
21
|
+
}
|
|
22
|
+
for arg in "$@"; do
|
|
23
|
+
case "$arg" in
|
|
24
|
+
--password)
|
|
25
|
+
kind="entry"
|
|
26
|
+
for a in "$@"; do [[ "$a" == --title=*主密码* || "$a" == --title=*解锁* || "$a" == --title=*创建* ]] && kind="master"; done
|
|
27
|
+
if [[ "$kind" == "master" ]]; then
|
|
28
|
+
if [[ -s "$DIR/passwords" ]]; then take_first "$DIR/passwords"; else echo "testmaster"; fi
|
|
29
|
+
elif [[ -f "$DIR/entry-passwords" ]]; then
|
|
30
|
+
take_first "$DIR/entry-passwords"
|
|
31
|
+
else
|
|
32
|
+
echo ""
|
|
33
|
+
fi
|
|
34
|
+
exit 0 ;;
|
|
35
|
+
--entry)
|
|
36
|
+
if [[ -f "$DIR/entries" ]]; then take_first "$DIR/entries"; else echo ""; fi
|
|
37
|
+
exit 0 ;;
|
|
38
|
+
--question)
|
|
39
|
+
[[ -f "$DIR/deny" ]] && exit 1
|
|
40
|
+
exit 0 ;;
|
|
41
|
+
esac
|
|
42
|
+
done
|
|
43
|
+
exit 0
|