@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.
- package/Cargo.lock +784 -0
- package/Cargo.toml +8 -0
- package/LICENSE +21 -0
- package/README.md +244 -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 +1129 -0
- package/crates/ai-vault/src/config.rs +77 -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 +22 -0
- package/crates/ai-vault/src/paths.rs +68 -0
- package/crates/ai-vault/src/session.rs +280 -0
- package/crates/ai-vault/src/store.rs +219 -0
- package/install.sh +21 -0
- package/package.json +76 -5
- package/packages/pi-ai-vault/README.md +62 -0
- package/packages/pi-ai-vault/package.json +47 -0
- package/packages/pi-ai-vault/src/bitwarden.ts +1482 -0
- package/packages/pi-ai-vault/src/cli.ts +171 -0
- package/packages/pi-ai-vault/src/host.ts +76 -0
- package/packages/pi-ai-vault/src/import-map.ts +91 -0
- package/packages/pi-ai-vault/src/index.ts +976 -0
- package/packages/pi-ai-vault/src/prompt.ts +195 -0
- package/packages/pi-ai-vault/src/scrub.ts +157 -0
- package/test/cli.sh +135 -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 +131 -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 +51 -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 +217 -0
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Desktop dialogs, shared by the local vault and the Bitwarden tools.
|
|
3
|
+
*
|
|
4
|
+
* A display (X11 or Wayland) opens a zenity window. Cancel (exit 1) and our
|
|
5
|
+
* own timeout (exit 5) end the prompt there: they never fall through to a
|
|
6
|
+
* second, terminal prompt. When no window could open at all (zenity missing,
|
|
7
|
+
* an option it rejects, a display it cannot reach) the host dialog is used
|
|
8
|
+
* instead. Upstream pi shows typed text in the clear; OMP masks it.
|
|
9
|
+
*/
|
|
10
|
+
import { spawn, spawnSync } from "node:child_process";
|
|
11
|
+
import { existsSync } from "node:fs";
|
|
12
|
+
import { join } from "node:path";
|
|
13
|
+
|
|
14
|
+
const DIALOG_MS = 10 * 60_000;
|
|
15
|
+
const STDERR_CAP = 16_000;
|
|
16
|
+
|
|
17
|
+
export interface PromptHost {
|
|
18
|
+
hasUI: boolean;
|
|
19
|
+
ui: {
|
|
20
|
+
input(title: string, placeholder?: string, opts?: { timeout?: number; secret?: boolean }): Promise<string | undefined>;
|
|
21
|
+
confirm(title: string, message: string, opts?: { timeout?: number }): Promise<boolean>;
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function hasDisplay(): boolean {
|
|
26
|
+
return !!(process.env.DISPLAY || process.env.WAYLAND_DISPLAY);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
interface ZenityResult {
|
|
30
|
+
/** False when zenity could not be started. */
|
|
31
|
+
spawned: boolean;
|
|
32
|
+
code: number;
|
|
33
|
+
stdout: string;
|
|
34
|
+
stderr: string;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function zenity(args: string[], signal?: AbortSignal): Promise<ZenityResult> {
|
|
38
|
+
const closed: ZenityResult = { spawned: false, code: 1, stdout: "", stderr: "" };
|
|
39
|
+
if (signal?.aborted) return Promise.resolve(closed);
|
|
40
|
+
const { promise, resolve } = Promise.withResolvers<ZenityResult>();
|
|
41
|
+
const child = spawn("zenity", args, { stdio: ["ignore", "pipe", "pipe"] });
|
|
42
|
+
let out = "";
|
|
43
|
+
let err = "";
|
|
44
|
+
let settled = false;
|
|
45
|
+
const finish = (result: ZenityResult) => {
|
|
46
|
+
if (settled) return;
|
|
47
|
+
settled = true;
|
|
48
|
+
clearTimeout(timer);
|
|
49
|
+
signal?.removeEventListener("abort", onAbort);
|
|
50
|
+
resolve(result);
|
|
51
|
+
};
|
|
52
|
+
const onAbort = () => {
|
|
53
|
+
child.kill("SIGKILL");
|
|
54
|
+
finish({ spawned: true, code: 1, stdout: "", stderr: "" });
|
|
55
|
+
};
|
|
56
|
+
const timer = setTimeout(() => {
|
|
57
|
+
child.kill("SIGKILL");
|
|
58
|
+
finish({ spawned: true, code: 5, stdout: "", stderr: "" });
|
|
59
|
+
}, DIALOG_MS);
|
|
60
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
61
|
+
// Both pipes must be drained, or a chatty GTK fills one and blocks the dialog.
|
|
62
|
+
child.stdout?.on("data", (chunk: Buffer | string) => {
|
|
63
|
+
if (out.length < 256_000) out += chunk;
|
|
64
|
+
});
|
|
65
|
+
child.stderr?.on("data", (chunk: Buffer | string) => {
|
|
66
|
+
if (err.length < STDERR_CAP) err += chunk;
|
|
67
|
+
});
|
|
68
|
+
child.on("error", (e: NodeJS.ErrnoException) => {
|
|
69
|
+
// ENOENT or a failed spawn: the caller may use the host dialog.
|
|
70
|
+
finish({ spawned: false, code: e.code === "ENOENT" ? 127 : -1, stdout: "", stderr: "" });
|
|
71
|
+
});
|
|
72
|
+
child.on("close", (code) => finish({ spawned: true, code: code ?? -1, stdout: out, stderr: err }));
|
|
73
|
+
return promise;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* True when the configured display looks usable. Only consulted when zenity
|
|
78
|
+
* exits 1 with no output at all: that is either a cancel (display fine) or a
|
|
79
|
+
* silent start failure (display unreachable).
|
|
80
|
+
*/
|
|
81
|
+
function displayReachable(): boolean {
|
|
82
|
+
if (process.env.WAYLAND_DISPLAY) {
|
|
83
|
+
const runtime = process.env.XDG_RUNTIME_DIR;
|
|
84
|
+
return !!runtime && existsSync(join(runtime, process.env.WAYLAND_DISPLAY));
|
|
85
|
+
}
|
|
86
|
+
if (!process.env.DISPLAY) return false;
|
|
87
|
+
const probe = spawnSync("xdpyinfo", [], { stdio: "ignore", timeout: 1500 });
|
|
88
|
+
// If the probe itself cannot run, do not turn a normal cancel into a second prompt.
|
|
89
|
+
return probe.error ? true : probe.status === 0;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* True when no dialog ran. Exit 1 is ambiguous on some zenity builds (cancel
|
|
94
|
+
* and a failed start both use it), so stderr decides: GTK's own diagnostics
|
|
95
|
+
* carry a `(zenity:PID): Gtk-WARNING` prefix; any other line, or a display
|
|
96
|
+
* failure, means the window never opened. With no output at all, a display
|
|
97
|
+
* that cannot be reached is the one remaining signal; otherwise it is a cancel.
|
|
98
|
+
*/
|
|
99
|
+
function failedToOpen(result: ZenityResult): boolean {
|
|
100
|
+
if (!result.spawned) return true;
|
|
101
|
+
if (result.code === 0 || result.code === 5) return false;
|
|
102
|
+
if (result.code === 1 && result.stdout === "" && result.stderr === "") return !displayReachable();
|
|
103
|
+
if (/cannot open display|unable to (?:open|init)|failed to (?:open|init)/i.test(result.stderr)) return true;
|
|
104
|
+
const gtkDiagnostic = /^\**\s*\(\w+:\d+\):\s+[\w-]+-(?:WARNING|CRITICAL|MESSAGE|DEBUG)\b/;
|
|
105
|
+
return result.stderr.split(/\r?\n/).some((line) => line.trim() !== "" && !gtkDiagnostic.test(line));
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** Secret entry. Empty and cancel are both "no value". */
|
|
109
|
+
export async function promptSecret(
|
|
110
|
+
ctx: PromptHost | undefined,
|
|
111
|
+
title: string,
|
|
112
|
+
label: string,
|
|
113
|
+
signal?: AbortSignal,
|
|
114
|
+
): Promise<string | undefined> {
|
|
115
|
+
if (signal?.aborted) return undefined;
|
|
116
|
+
if (hasDisplay()) {
|
|
117
|
+
const result = await zenity(
|
|
118
|
+
["--password", `--title=${title} — ${label}`, "--width=420", `--timeout=${DIALOG_MS / 1000}`],
|
|
119
|
+
signal,
|
|
120
|
+
);
|
|
121
|
+
if (!failedToOpen(result)) {
|
|
122
|
+
const value = result.stdout.replace(/[\r\n]+$/, "");
|
|
123
|
+
return result.code === 0 && value ? value : undefined;
|
|
124
|
+
}
|
|
125
|
+
if (signal?.aborted) return undefined;
|
|
126
|
+
}
|
|
127
|
+
if (ctx?.hasUI) {
|
|
128
|
+
const value = await ctx.ui.input(title, label, { timeout: DIALOG_MS, secret: true });
|
|
129
|
+
if (signal?.aborted) return undefined;
|
|
130
|
+
return value && value.length > 0 ? value : undefined;
|
|
131
|
+
}
|
|
132
|
+
return undefined;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** Plain text entry. Cancel is undefined; confirming an empty field is "". */
|
|
136
|
+
export async function promptText(
|
|
137
|
+
ctx: PromptHost | undefined,
|
|
138
|
+
title: string,
|
|
139
|
+
label: string,
|
|
140
|
+
signal?: AbortSignal,
|
|
141
|
+
): Promise<string | undefined> {
|
|
142
|
+
if (signal?.aborted) return undefined;
|
|
143
|
+
if (hasDisplay()) {
|
|
144
|
+
const result = await zenity(
|
|
145
|
+
["--entry", `--title=${title}`, `--text=${label}`, "--width=480", "--no-markup", `--timeout=${DIALOG_MS / 1000}`],
|
|
146
|
+
signal,
|
|
147
|
+
);
|
|
148
|
+
if (!failedToOpen(result)) return result.code === 0 ? result.stdout.replace(/[\r\n]+$/, "") : undefined;
|
|
149
|
+
if (signal?.aborted) return undefined;
|
|
150
|
+
}
|
|
151
|
+
if (ctx?.hasUI) {
|
|
152
|
+
const value = await ctx.ui.input(title, label, { timeout: DIALOG_MS });
|
|
153
|
+
if (signal?.aborted) return undefined;
|
|
154
|
+
return value;
|
|
155
|
+
}
|
|
156
|
+
return undefined;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* Yes/no window. Deny and timeout are false and do not fall through.
|
|
161
|
+
* When no window could open, the host confirm dialog is asked instead.
|
|
162
|
+
*/
|
|
163
|
+
export async function confirmWindow(
|
|
164
|
+
ctx: PromptHost | undefined,
|
|
165
|
+
title: string,
|
|
166
|
+
message: string,
|
|
167
|
+
signal?: AbortSignal,
|
|
168
|
+
): Promise<boolean> {
|
|
169
|
+
if (signal?.aborted) return false;
|
|
170
|
+
if (hasDisplay()) {
|
|
171
|
+
const result = await zenity(
|
|
172
|
+
[
|
|
173
|
+
"--question",
|
|
174
|
+
`--title=${title}`,
|
|
175
|
+
"--text",
|
|
176
|
+
message,
|
|
177
|
+
"--no-markup",
|
|
178
|
+
"--width=520",
|
|
179
|
+
"--default-cancel",
|
|
180
|
+
"--ok-label=允许",
|
|
181
|
+
"--cancel-label=拒绝",
|
|
182
|
+
`--timeout=${DIALOG_MS / 1000}`,
|
|
183
|
+
],
|
|
184
|
+
signal,
|
|
185
|
+
);
|
|
186
|
+
if (!failedToOpen(result)) return result.code === 0;
|
|
187
|
+
if (signal?.aborted) return false;
|
|
188
|
+
}
|
|
189
|
+
if (ctx?.hasUI) {
|
|
190
|
+
const ok = await ctx.ui.confirm(title, message, { timeout: DIALOG_MS });
|
|
191
|
+
if (signal?.aborted) return false;
|
|
192
|
+
return ok === true;
|
|
193
|
+
}
|
|
194
|
+
return false;
|
|
195
|
+
}
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
/** Values the output scrubber must keep hiding. */
|
|
2
|
+
export type ScrubValue = { env: string; value: string };
|
|
3
|
+
|
|
4
|
+
const escapeRegExp = (input: string): string => input.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
5
|
+
|
|
6
|
+
/** `needle` with any whitespace allowed between characters (base64/xxd line wrapping). */
|
|
7
|
+
const spacedPattern = (needle: string, flags: string): RegExp =>
|
|
8
|
+
new RegExp(needle.split("").map(escapeRegExp).join("\\s*"), `${flags}g`);
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Replace a secret and its common encodings (base64, base64url, URL, hex) in
|
|
12
|
+
* text. A form shorter than 6 characters is deliberately skipped: replacing
|
|
13
|
+
* it would corrupt ordinary output more often than it protects anything.
|
|
14
|
+
*
|
|
15
|
+
* Encoded forms are matched both contiguously and with whitespace between
|
|
16
|
+
* characters: GNU `base64` wraps at 76 columns and `xxd`/`od` separate hex
|
|
17
|
+
* bytes, so a line-broken encoding must still be found.
|
|
18
|
+
*/
|
|
19
|
+
export function scrubText(input: string, values: Iterable<ScrubValue>): { text: string; changed: boolean } {
|
|
20
|
+
let text = input;
|
|
21
|
+
let changed = false;
|
|
22
|
+
// A whitespace-free copy makes the "is this encoding present?" check cheap;
|
|
23
|
+
// the regex below is only built when there is something to replace.
|
|
24
|
+
const compact = input.replace(/\s+/g, "");
|
|
25
|
+
const replace = (needle: string, label: string) => {
|
|
26
|
+
if (needle.length < 6 || !text.includes(needle)) return;
|
|
27
|
+
text = text.split(needle).join(label);
|
|
28
|
+
changed = true;
|
|
29
|
+
};
|
|
30
|
+
const replaceSpaced = (needle: string, label: string, flags = "") => {
|
|
31
|
+
if (needle.length < 6 || !compact.includes(needle)) return;
|
|
32
|
+
const next = text.replace(spacedPattern(needle, flags), label);
|
|
33
|
+
if (next !== text) {
|
|
34
|
+
text = next;
|
|
35
|
+
changed = true;
|
|
36
|
+
}
|
|
37
|
+
};
|
|
38
|
+
for (const { env, value } of values) {
|
|
39
|
+
replace(value, `[BW_SCRUBBED:${env}]`);
|
|
40
|
+
const b64 = Buffer.from(value, "utf-8").toString("base64");
|
|
41
|
+
const b64url = b64.replace(/=+$/, "").replace(/\+/g, "-").replace(/\//g, "_");
|
|
42
|
+
replace(b64, `[BW_SCRUBBED-B64:${env}]`);
|
|
43
|
+
replace(b64url, `[BW_SCRUBBED-B64URL:${env}]`);
|
|
44
|
+
replaceSpaced(b64, `[BW_SCRUBBED-B64:${env}]`);
|
|
45
|
+
replaceSpaced(b64url, `[BW_SCRUBBED-B64URL:${env}]`);
|
|
46
|
+
const url = encodeURIComponent(value);
|
|
47
|
+
if (url !== value) replace(url, `[BW_SCRUBBED-URL:${env}]`);
|
|
48
|
+
const hex = Buffer.from(value, "utf-8").toString("hex");
|
|
49
|
+
replace(hex, `[BW_SCRUBBED-HEX:${env}]`);
|
|
50
|
+
replaceSpaced(hex, `[BW_SCRUBBED-HEX:${env}]`, "i");
|
|
51
|
+
if (hex !== hex.toUpperCase()) {
|
|
52
|
+
replaceSpaced(hex.toUpperCase(), `[BW_SCRUBBED-HEX:${env}]`, "i");
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
return { text, changed };
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** A Buffer's text may hold a secret; only replace it when something changed. */
|
|
59
|
+
function scrubBuffer(value: Buffer, values: Iterable<ScrubValue>): { value: unknown; changed: boolean } {
|
|
60
|
+
const result = scrubText(value.toString("utf-8"), values);
|
|
61
|
+
return result.changed ? { value: Buffer.from(result.text, "utf-8"), changed: true } : { value, changed: false };
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Rebuild a Map/Set/Error only when a contained string changed, so identity is kept otherwise. */
|
|
65
|
+
function scrubMap(
|
|
66
|
+
value: Map<unknown, unknown>,
|
|
67
|
+
values: Iterable<ScrubValue>,
|
|
68
|
+
depth: number,
|
|
69
|
+
): { value: unknown; changed: boolean } {
|
|
70
|
+
let changed = false;
|
|
71
|
+
const next = new Map<unknown, unknown>();
|
|
72
|
+
for (const [key, entry] of value) {
|
|
73
|
+
const k = scrubDeep(key, values, depth + 1);
|
|
74
|
+
const v = scrubDeep(entry, values, depth + 1);
|
|
75
|
+
if (k.changed || v.changed) changed = true;
|
|
76
|
+
next.set(k.value, v.value);
|
|
77
|
+
}
|
|
78
|
+
return { value: changed ? next : value, changed };
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function scrubSet(
|
|
82
|
+
value: Set<unknown>,
|
|
83
|
+
values: Iterable<ScrubValue>,
|
|
84
|
+
depth: number,
|
|
85
|
+
): { value: unknown; changed: boolean } {
|
|
86
|
+
let changed = false;
|
|
87
|
+
const next = new Set<unknown>();
|
|
88
|
+
for (const entry of value) {
|
|
89
|
+
const result = scrubDeep(entry, values, depth + 1);
|
|
90
|
+
if (result.changed) changed = true;
|
|
91
|
+
next.add(result.value);
|
|
92
|
+
}
|
|
93
|
+
return { value: changed ? next : value, changed };
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function scrubError(
|
|
97
|
+
value: Error,
|
|
98
|
+
values: Iterable<ScrubValue>,
|
|
99
|
+
depth: number,
|
|
100
|
+
): { value: unknown; changed: boolean } {
|
|
101
|
+
const message = scrubText(value.message, values);
|
|
102
|
+
const stack = typeof value.stack === "string" ? scrubText(value.stack, values) : undefined;
|
|
103
|
+
const cause =
|
|
104
|
+
"cause" in value
|
|
105
|
+
? scrubDeep((value as Error & { cause?: unknown }).cause, values, depth + 1)
|
|
106
|
+
: undefined;
|
|
107
|
+
if (!message.changed && !stack?.changed && !cause?.changed) return { value, changed: false };
|
|
108
|
+
const copy = Object.create(Object.getPrototypeOf(value)) as Error;
|
|
109
|
+
Object.defineProperties(copy, Object.getOwnPropertyDescriptors(value));
|
|
110
|
+
if (message.changed) Object.defineProperty(copy, "message", { value: message.text, writable: true, configurable: true });
|
|
111
|
+
if (stack?.changed) Object.defineProperty(copy, "stack", { value: stack.text, writable: true, configurable: true });
|
|
112
|
+
if (cause?.changed) {
|
|
113
|
+
Object.defineProperty(copy, "cause", { value: cause.value, writable: true, configurable: true });
|
|
114
|
+
}
|
|
115
|
+
return { value: copy, changed: true };
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** OMP's bash `details.trace` can echo the sourced env file; scrub nested values. */
|
|
119
|
+
export function scrubDeep(
|
|
120
|
+
value: unknown,
|
|
121
|
+
values: Iterable<ScrubValue>,
|
|
122
|
+
depth = 0,
|
|
123
|
+
): { value: unknown; changed: boolean } {
|
|
124
|
+
if (depth > 12) return { value, changed: false };
|
|
125
|
+
if (typeof value === "string") {
|
|
126
|
+
const result = scrubText(value, values);
|
|
127
|
+
return { value: result.text, changed: result.changed };
|
|
128
|
+
}
|
|
129
|
+
if (Array.isArray(value)) {
|
|
130
|
+
let changed = false;
|
|
131
|
+
const next = value.map((entry) => {
|
|
132
|
+
const result = scrubDeep(entry, values, depth + 1);
|
|
133
|
+
if (result.changed) changed = true;
|
|
134
|
+
return result.value;
|
|
135
|
+
});
|
|
136
|
+
return { value: changed ? next : value, changed };
|
|
137
|
+
}
|
|
138
|
+
if (Buffer.isBuffer(value)) return scrubBuffer(value, values);
|
|
139
|
+
if (value instanceof Map) return scrubMap(value, values, depth);
|
|
140
|
+
if (value instanceof Set) return scrubSet(value, values, depth);
|
|
141
|
+
if (value instanceof Error) return scrubError(value, values, depth);
|
|
142
|
+
if (value && typeof value === "object") {
|
|
143
|
+
// Only plain data is rebuilt. A Date or another class instance keeps its
|
|
144
|
+
// prototype: it is returned as is instead of being turned into `{}`.
|
|
145
|
+
const proto = Object.getPrototypeOf(value);
|
|
146
|
+
if (proto !== Object.prototype && proto !== null) return { value, changed: false };
|
|
147
|
+
let changed = false;
|
|
148
|
+
const next: Record<string, unknown> = {};
|
|
149
|
+
for (const [key, entry] of Object.entries(value)) {
|
|
150
|
+
const result = scrubDeep(entry, values, depth + 1);
|
|
151
|
+
if (result.changed) changed = true;
|
|
152
|
+
next[key] = result.value;
|
|
153
|
+
}
|
|
154
|
+
return { value: changed ? next : value, changed };
|
|
155
|
+
}
|
|
156
|
+
return { value, changed: false };
|
|
157
|
+
}
|
package/test/cli.sh
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
#!/usr/bin/env bash
|
|
2
|
+
# End-to-end checks of the ai-vault binary alone: no desktop, no agent, no
|
|
3
|
+
# mocks. Every dialog is answered through the documented exit-code contract,
|
|
4
|
+
# which is exactly what a headless host does.
|
|
5
|
+
#
|
|
6
|
+
# bash test/cli.sh # uses target/release/ai-vault
|
|
7
|
+
# AI_VAULT_BIN=... bash test/cli.sh
|
|
8
|
+
set -uo pipefail
|
|
9
|
+
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
|
|
10
|
+
BIN="${AI_VAULT_BIN:-$ROOT/target/release/ai-vault}"
|
|
11
|
+
[[ -x "$BIN" ]] || { echo "no binary at $BIN — run: cargo build --release" >&2; exit 2; }
|
|
12
|
+
|
|
13
|
+
TMP="$(mktemp -d "/tmp/ai-vault-cli.XXXXXX")"
|
|
14
|
+
trap 'rm -rf "$TMP"' EXIT
|
|
15
|
+
export AI_VAULT_DIR="$TMP/store"
|
|
16
|
+
export XDG_RUNTIME_DIR="$TMP/runtime"
|
|
17
|
+
mkdir -p "$XDG_RUNTIME_DIR"
|
|
18
|
+
unset DISPLAY WAYLAND_DISPLAY
|
|
19
|
+
export HOME="$TMP/home"
|
|
20
|
+
mkdir -p "$HOME"
|
|
21
|
+
|
|
22
|
+
PASS=0
|
|
23
|
+
FAIL=0
|
|
24
|
+
ok() { printf ' PASS %s\n' "$*"; PASS=$((PASS + 1)); }
|
|
25
|
+
bad() { printf ' FAIL %s\n' "$*"; FAIL=$((FAIL + 1)); }
|
|
26
|
+
# check <description> <expected-exit> <command...>
|
|
27
|
+
check() {
|
|
28
|
+
local what="$1" want="$2"
|
|
29
|
+
shift 2
|
|
30
|
+
"$@" >"$TMP/out" 2>"$TMP/err"
|
|
31
|
+
local got=$?
|
|
32
|
+
if [[ "$got" == "$want" ]]; then ok "$what (exit $got)"; else
|
|
33
|
+
bad "$what: exit $got, wanted $want"
|
|
34
|
+
head -3 "$TMP/err" | sed 's/^/ /'
|
|
35
|
+
fi
|
|
36
|
+
}
|
|
37
|
+
out() { cat "$TMP/out"; }
|
|
38
|
+
json() { python3 -c "import json,sys;print(json.load(sys.stdin).get(\"$1\",\"\"))"; }
|
|
39
|
+
|
|
40
|
+
echo "== init =="
|
|
41
|
+
check "init without a window asks the host" 3 "$BIN" init
|
|
42
|
+
grep -q 'needs-ui: password' "$TMP/err" && ok "the needs-ui step is named" || bad "no needs-ui hint"
|
|
43
|
+
check "a short password is a usage error" 2 bash -c "printf 'short' | '$BIN' init --password-stdin"
|
|
44
|
+
check "init creates the store" 0 bash -c "printf 'correct horse' | '$BIN' init --password-stdin --requester cli"
|
|
45
|
+
[[ -f "$AI_VAULT_DIR/store.json" ]] && ok "store.json exists" || bad "store.json missing"
|
|
46
|
+
[[ "$(stat -c %a "$AI_VAULT_DIR/store.json")" == "600" ]] && ok "store.json is 0600" || bad "store.json is not 0600"
|
|
47
|
+
|
|
48
|
+
echo "== unlock =="
|
|
49
|
+
check "unlock without a window asks the host" 3 "$BIN" unlock
|
|
50
|
+
check "a wrong password is an auth failure" 5 bash -c "printf 'wrong password' | '$BIN' unlock --password-stdin"
|
|
51
|
+
check "the right password opens it" 0 bash -c "printf 'correct horse' | '$BIN' unlock --password-stdin --json"
|
|
52
|
+
TOKEN=$(printf 'correct horse' | "$BIN" unlock --password-stdin --json | json token)
|
|
53
|
+
[[ ${#TOKEN} -ge 32 ]] && ok "a session token is printed" || bad "no token"
|
|
54
|
+
SESS="$XDG_RUNTIME_DIR/ai-vault/sessions/$TOKEN.json"
|
|
55
|
+
[[ -f "$SESS" ]] && ok "the token file lives under XDG_RUNTIME_DIR" || bad "token file missing"
|
|
56
|
+
[[ "$(stat -c %a "$SESS")" == "600" ]] && ok "the token file is 0600" || bad "the token file is not 0600"
|
|
57
|
+
|
|
58
|
+
echo "== add / list =="
|
|
59
|
+
check "add needs a window for the password" 3 bash -c "'$BIN' add --name GitHub --username octo --token '$TOKEN'"
|
|
60
|
+
check "add with a typed password" 0 bash -c "printf 'p1ssw0rd' | '$BIN' add --name GitHub --username octo --uri https://github.com --password-stdin --yes --token '$TOKEN' --json"
|
|
61
|
+
"$BIN" list --token "$TOKEN" --json >"$TMP/list"
|
|
62
|
+
python3 - "$TMP/list" <<'PY' && ok "list shows metadata only" || bad "list output is wrong"
|
|
63
|
+
import json,sys
|
|
64
|
+
data = json.load(open(sys.argv[1]))
|
|
65
|
+
assert data["count"] == 1, data
|
|
66
|
+
assert data["items"][0]["name"] == "GitHub", data
|
|
67
|
+
assert "password" not in data["items"][0], data
|
|
68
|
+
PY
|
|
69
|
+
grep -q 'p1ssw0rd' "$AI_VAULT_DIR/store.json" && bad "the password is in plaintext on disk" || ok "the store is encrypted at rest"
|
|
70
|
+
|
|
71
|
+
echo "== read approval =="
|
|
72
|
+
check "get without a window asks the host" 3 bash -c "'$BIN' get GitHub --token '$TOKEN'"
|
|
73
|
+
check "a denied window is not a lock" 4 bash -c "printf 'n\n' | '$BIN' get GitHub --token '$TOKEN' --answer-stdin"
|
|
74
|
+
printf 'y\n' | "$BIN" get GitHub --token "$TOKEN" --answer-stdin --json >"$TMP/get" 2>"$TMP/err"
|
|
75
|
+
[[ $? -eq 0 ]] && ok "an approved window reveals the entry" || bad "an approved window failed"
|
|
76
|
+
python3 - "$TMP/get" <<'PY' && ok "the approved entry carries the password" || bad "get output is wrong"
|
|
77
|
+
import json,sys
|
|
78
|
+
item = json.load(open(sys.argv[1]))
|
|
79
|
+
assert item["password"] == "p1ssw0rd", item
|
|
80
|
+
assert item["via"] == "interactive-grant", item
|
|
81
|
+
PY
|
|
82
|
+
"$BIN" get GitHub --token "$TOKEN" --json >"$TMP/get2" 2>"$TMP/err2"
|
|
83
|
+
[[ $? -eq 0 ]] && ok "a live grant needs no window" || bad "the grant was not reused"
|
|
84
|
+
grep -q 'existing-grant' "$TMP/get2" && ok "the reuse is labelled" || bad "the reuse is not labelled"
|
|
85
|
+
check "a grant can be revoked" 0 "$BIN" revoke GitHub --token "$TOKEN" --json
|
|
86
|
+
check "remove needs a window to confirm" 3 "$BIN" remove GitHub --token "$TOKEN"
|
|
87
|
+
check "remove after approval" 0 "$BIN" remove GitHub --yes --token "$TOKEN" --json
|
|
88
|
+
|
|
89
|
+
echo "== import =="
|
|
90
|
+
cat >"$TMP/export.json" <<'JSON'
|
|
91
|
+
{ "items": [
|
|
92
|
+
{ "id": "abc", "name": "FromExport", "login": { "username": "u", "password": "exp-pass", "uris": [{ "uri": "https://e.example" }] } },
|
|
93
|
+
{ "id": "def", "name": "NoPassword", "login": { "username": "u" } }
|
|
94
|
+
] }
|
|
95
|
+
JSON
|
|
96
|
+
check "import without a window asks the host" 3 "$BIN" import "$TMP/export.json" --token "$TOKEN"
|
|
97
|
+
check "import after approval" 0 "$BIN" import "$TMP/export.json" --yes --token "$TOKEN" --json
|
|
98
|
+
grep -q 'exp-pass' "$AI_VAULT_DIR/store.json" && bad "an imported password is on disk in plaintext" || ok "the import is encrypted"
|
|
99
|
+
check "save requires the caller's --yes" 2 bash -c "printf '[]' | '$BIN' save --token '$TOKEN'"
|
|
100
|
+
check "save inserts drafts" 0 bash -c "printf '[{\"name\":\"Draft\",\"password\":\"dr-pw\",\"uris\":[\"https://d\"]}]' | '$BIN' save --yes --token '$TOKEN' --json"
|
|
101
|
+
|
|
102
|
+
echo "== lock / audit =="
|
|
103
|
+
check "lock drops the token" 0 "$BIN" lock --token "$TOKEN" --json
|
|
104
|
+
check "a dropped token no longer works" 5 "$BIN" list --token "$TOKEN"
|
|
105
|
+
"$BIN" audit 50 --json >"$TMP/audit"
|
|
106
|
+
python3 - "$TMP/audit" <<'PY' && ok "the audit log records events without values" || bad "audit output is wrong"
|
|
107
|
+
import json,sys
|
|
108
|
+
entries = json.load(open(sys.argv[1]))["entries"]
|
|
109
|
+
events = {e["event"] for e in entries}
|
|
110
|
+
for want in ("init", "unlock", "unlock_failed", "add", "grant", "read_deny", "read_allow", "remove", "import", "lock"):
|
|
111
|
+
assert want in events, (want, events)
|
|
112
|
+
assert not any("p1ssw0rd" in json.dumps(e) or "exp-pass" in json.dumps(e) for e in entries)
|
|
113
|
+
PY
|
|
114
|
+
grep -q 'p1ssw0rd' "$AI_VAULT_DIR/audit.log" && bad "a secret reached the audit log" || ok "no secret in audit.log"
|
|
115
|
+
|
|
116
|
+
echo "== unlock modes =="
|
|
117
|
+
check "mode get works without a token" 0 "$BIN" mode --json
|
|
118
|
+
check "switching the mode needs the password" 3 "$BIN" mode set never
|
|
119
|
+
check "a wrong password does not switch it" 5 bash -c "printf 'wrong password' | '$BIN' mode set never --password-stdin"
|
|
120
|
+
check "never mode is set with the password" 0 bash -c "printf 'correct horse' | '$BIN' mode set never --password-stdin --json"
|
|
121
|
+
check "never mode needs no token" 0 "$BIN" status --json
|
|
122
|
+
printf 'correct horse' | "$BIN" unlock --password-stdin --json >"$TMP/u2" 2>&1
|
|
123
|
+
python3 - "$TMP/u2" <<'PY' && ok "unlock reports the mode" || bad "unlock output is wrong"
|
|
124
|
+
import json,sys
|
|
125
|
+
d = json.load(open(sys.argv[1]))
|
|
126
|
+
assert d["mode"] == "never" and d["auto"] is True, d
|
|
127
|
+
PY
|
|
128
|
+
check "back to session mode" 0 bash -c "printf 'correct horse' | '$BIN' mode set session --password-stdin --json"
|
|
129
|
+
check "session mode needs a token again" 5 "$BIN" status
|
|
130
|
+
|
|
131
|
+
echo "== doctor =="
|
|
132
|
+
check "doctor runs" 0 "$BIN" doctor --json
|
|
133
|
+
|
|
134
|
+
printf '\nRESULT: %d passed, %d failed\n' "$PASS" "$FAIL"
|
|
135
|
+
[[ "$FAIL" -eq 0 ]]
|
package/test/npm.sh
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
#!/usr/bin/env bash
|
|
2
|
+
# Verify the npm packaging the way a user would consume it: pack both
|
|
3
|
+
# tarballs, install them into a throwaway prefix (no registry access), then
|
|
4
|
+
# run the installed `ai-vault` shim.
|
|
5
|
+
#
|
|
6
|
+
# bash test/npm.sh
|
|
7
|
+
set -uo pipefail
|
|
8
|
+
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
|
|
9
|
+
TMP="$(mktemp -d "/tmp/ai-vault-npm.XXXXXX")"
|
|
10
|
+
trap 'rm -rf "$TMP"' EXIT
|
|
11
|
+
# AI_VAULT_DIR below keeps the real ~/.ai-vault (and its migration) out of reach.
|
|
12
|
+
|
|
13
|
+
PASS=0
|
|
14
|
+
FAIL=0
|
|
15
|
+
ok() { printf ' PASS %s\n' "$*"; PASS=$((PASS + 1)); }
|
|
16
|
+
bad() { printf ' FAIL %s\n' "$*"; FAIL=$((FAIL + 1)); }
|
|
17
|
+
|
|
18
|
+
echo "== stage the platform package =="
|
|
19
|
+
bash "$ROOT/scripts/stage-npm.sh" >"$TMP/stage" 2>&1 || { cat "$TMP/stage"; exit 1; }
|
|
20
|
+
PLATFORM="$(cd "$ROOT/npm" && ls -d */ | head -1 | tr -d /)"
|
|
21
|
+
[[ -f "$ROOT/npm/$PLATFORM/bin/ai-vault" ]] && ok "staged $PLATFORM" || bad "nothing staged"
|
|
22
|
+
|
|
23
|
+
echo "== pack =="
|
|
24
|
+
mkdir -p "$TMP/tarballs"
|
|
25
|
+
(cd "$ROOT/npm/$PLATFORM" && npm pack --pack-destination "$TMP/tarballs" --silent >/dev/null) || bad "packing the platform package failed"
|
|
26
|
+
(cd "$ROOT" && npm pack --pack-destination "$TMP/tarballs" --silent >/dev/null) || bad "packing the root package failed"
|
|
27
|
+
ls "$TMP"/tarballs/*.tgz >/dev/null 2>&1 || { echo "no tarballs"; exit 1; }
|
|
28
|
+
PLATFORM_TGZ="$(ls "$TMP"/tarballs/*ai-vault-"$PLATFORM"*.tgz)"
|
|
29
|
+
ROOT_TGZ="$(ls "$TMP"/tarballs/*ai-vault-0*.tgz | grep -v -- "-$PLATFORM-" | head -1)"
|
|
30
|
+
[[ -n "$PLATFORM_TGZ" && -n "$ROOT_TGZ" ]] && ok "both tarballs exist" || bad "tarball names are wrong: $(ls "$TMP"/tarballs)"
|
|
31
|
+
|
|
32
|
+
# The platform package must not drag the JS extension along, and the root
|
|
33
|
+
# package must not drag a binary for every platform.
|
|
34
|
+
tar -tzf "$PLATFORM_TGZ" >"$TMP/platform.list"
|
|
35
|
+
tar -tzf "$ROOT_TGZ" >"$TMP/root.list"
|
|
36
|
+
grep -qx 'package/bin/ai-vault' "$TMP/platform.list" && ok "the platform tarball carries the binary" || bad "no binary in the platform tarball"
|
|
37
|
+
grep -q '^package/src/' "$TMP/platform.list" && bad "the platform tarball carries the extension" || ok "the platform tarball is binary-only"
|
|
38
|
+
grep -qx 'package/bin/ai-vault.cjs' "$TMP/root.list" && ok "the root tarball carries the shim" || bad "no shim in the root tarball"
|
|
39
|
+
|
|
40
|
+
echo "== install into a throwaway prefix =="
|
|
41
|
+
PREFIX="$TMP/prefix"
|
|
42
|
+
mkdir -p "$PREFIX"
|
|
43
|
+
if npm install -g --prefix "$PREFIX" --legacy-peer-deps --no-audit --no-fund "$ROOT_TGZ" "$PLATFORM_TGZ" >"$TMP/install" 2>&1; then
|
|
44
|
+
ok "npm install -g succeeded with both tarballs"
|
|
45
|
+
else
|
|
46
|
+
bad "npm install -g failed"
|
|
47
|
+
sed 's/^/ /' "$TMP/install" | tail -20
|
|
48
|
+
fi
|
|
49
|
+
|
|
50
|
+
BIN="$PREFIX/bin/ai-vault"
|
|
51
|
+
[[ -x "$BIN" ]] && ok "the shim is linked as ai-vault" || bad "no $BIN"
|
|
52
|
+
|
|
53
|
+
echo "== run through the shim =="
|
|
54
|
+
[[ "$("$BIN" --version 2>/dev/null)" == ai-vault* ]] && ok "the shim runs the real binary (--version)" || bad "the shim did not run the binary"
|
|
55
|
+
|
|
56
|
+
export AI_VAULT_DIR="$TMP/store"
|
|
57
|
+
export XDG_RUNTIME_DIR="$TMP/runtime"
|
|
58
|
+
mkdir -p "$XDG_RUNTIME_DIR"
|
|
59
|
+
unset DISPLAY WAYLAND_DISPLAY
|
|
60
|
+
"$BIN" init >"$TMP/out" 2>"$TMP/err"
|
|
61
|
+
[[ $? -eq 3 ]] && ok "exit code 3 (needs-ui) survives the shim" || bad "the shim rewrote the exit code"
|
|
62
|
+
grep -q 'needs-ui: password' "$TMP/err" && ok "stderr is passed through untouched" || bad "stderr was not passed through"
|
|
63
|
+
printf 'correct horse' | "$BIN" init --password-stdin --json >"$TMP/init" 2>&1
|
|
64
|
+
[[ $? -eq 0 ]] && ok "init works through the shim" || { bad "init failed through the shim"; cat "$TMP/init"; }
|
|
65
|
+
printf 'wrong password' | "$BIN" unlock --password-stdin >/dev/null 2>&1
|
|
66
|
+
[[ $? -eq 5 ]] && ok "exit code 5 (auth) survives the shim" || bad "auth exit code was lost"
|
|
67
|
+
[[ -f "$AI_VAULT_DIR/store.json" ]] && ok "the store landed in AI_VAULT_DIR" || bad "no store file"
|
|
68
|
+
|
|
69
|
+
printf '\nRESULT: %d passed, %d failed\n' "$PASS" "$FAIL"
|
|
70
|
+
[[ "$FAIL" -eq 0 ]]
|
package/test/smoke.sh
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
#!/usr/bin/env bash
|
|
2
|
+
# Manual, model-driven smoke check on a real host. `npm test` drives the tools
|
|
3
|
+
# through a fake host; this runs the extension inside an actual omp or pi
|
|
4
|
+
# session with the mock bw CLI, so host wiring is exercised too.
|
|
5
|
+
#
|
|
6
|
+
# OMP_MODEL=<provider/model> bash test/smoke.sh omp
|
|
7
|
+
# PI_MODEL=<provider/model> bash test/smoke.sh pi
|
|
8
|
+
#
|
|
9
|
+
# The host keeps the real HOME because it needs its own model credentials; the
|
|
10
|
+
# Bitwarden state (config + audit) is redirected into the throwaway directory
|
|
11
|
+
# instead, so nothing touches your real vault or logs.
|
|
12
|
+
set -uo pipefail
|
|
13
|
+
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
|
|
14
|
+
export AI_VAULT_BIN="${AI_VAULT_BIN:-$ROOT/target/release/ai-vault}"
|
|
15
|
+
HOST="${1:-omp}"
|
|
16
|
+
STATE="$(mktemp -d "/tmp/ai-vault-$HOST.XXXXXX")"
|
|
17
|
+
mkdir -p "$STATE/cwd" "$STATE/sessions" "$STATE/bw"
|
|
18
|
+
export OMP_VAULT_BW_MOCK_DIR="$STATE"
|
|
19
|
+
export OMP_VAULT_MOCK="$STATE"
|
|
20
|
+
export AI_VAULT_DIR="$STATE/vault"
|
|
21
|
+
export OMP_VAULT_BW_DIR="$STATE/bw"
|
|
22
|
+
export PATH="$ROOT/tests/mocks/bin:$PATH"
|
|
23
|
+
# The mock zenity still needs a display to be asked at all; it never opens a window.
|
|
24
|
+
export DISPLAY="${DISPLAY:-:99}"
|
|
25
|
+
|
|
26
|
+
PASS=0
|
|
27
|
+
FAIL=0
|
|
28
|
+
ok() { printf ' PASS %s\n' "$*"; PASS=$((PASS + 1)); }
|
|
29
|
+
bad() { printf ' FAIL %s\n' "$*"; FAIL=$((FAIL + 1)); }
|
|
30
|
+
|
|
31
|
+
PROMPT='Call the bw_run tool with item TestService, field password, and exactly this command (do not shorten it): echo LEN=${#VAULT_SECRET}; printf %s "$VAULT_SECRET" | base64; printenv VAULT_SECRET'
|
|
32
|
+
|
|
33
|
+
case "$HOST" in
|
|
34
|
+
omp)
|
|
35
|
+
MODEL_ARGS=()
|
|
36
|
+
[[ -n "${OMP_MODEL:-}" ]] && MODEL_ARGS=(--model "$OMP_MODEL")
|
|
37
|
+
(cd "$STATE/cwd" && timeout 300 omp --session-dir "$STATE/sessions" --no-extensions \
|
|
38
|
+
-e "$ROOT/packages/pi-ai-vault/src/index.ts" "${MODEL_ARGS[@]}" --auto-approve --mode json -p "$PROMPT" 2>&1) >"$STATE/events"
|
|
39
|
+
;;
|
|
40
|
+
pi)
|
|
41
|
+
MODEL_ARGS=()
|
|
42
|
+
[[ -n "${PI_MODEL:-}" ]] && MODEL_ARGS=(--model "$PI_MODEL")
|
|
43
|
+
(cd "$STATE/cwd" && timeout 300 pi --no-session --no-extensions \
|
|
44
|
+
-e "$ROOT/packages/pi-ai-vault/src/index.ts" "${MODEL_ARGS[@]}" --mode json -p "$PROMPT" 2>&1) >"$STATE/events"
|
|
45
|
+
;;
|
|
46
|
+
*)
|
|
47
|
+
echo "usage: $0 [omp|pi]" >&2
|
|
48
|
+
exit 2
|
|
49
|
+
;;
|
|
50
|
+
esac
|
|
51
|
+
|
|
52
|
+
if grep -q 'LEN=21' "$STATE/events"; then
|
|
53
|
+
ok "$HOST: bw_run saw the secret in the command environment (LEN=21)"
|
|
54
|
+
if grep -q 'c3VwZXJzZWNyZXQ' "$STATE/events"; then
|
|
55
|
+
bad "$HOST: the base64 form leaked"
|
|
56
|
+
elif grep -q 'BW_SCRUBBED-B64:VAULT_SECRET' "$STATE/events"; then
|
|
57
|
+
ok "$HOST: the base64 form was scrubbed"
|
|
58
|
+
else
|
|
59
|
+
printf ' INCONCLUSIVE: the model did not run base64; check %s/events\n' "$STATE"
|
|
60
|
+
fi
|
|
61
|
+
else
|
|
62
|
+
printf ' INCONCLUSIVE: bw_run did not run; events are in %s/events\n' "$STATE"
|
|
63
|
+
fi
|
|
64
|
+
if grep '"type":"tool_execution_end"' "$STATE/events" | grep -q 'supersecret-value-123'; then
|
|
65
|
+
bad "$HOST: the raw secret appeared in a final tool result"
|
|
66
|
+
else
|
|
67
|
+
ok "$HOST: the raw secret is absent from tool results"
|
|
68
|
+
fi
|
|
69
|
+
if grep -rqs 'supersecret-value-123' "$STATE/sessions" "$STATE/bw" "$STATE/vault" 2>/dev/null; then
|
|
70
|
+
bad "$HOST: the raw secret was written to disk"
|
|
71
|
+
else
|
|
72
|
+
ok "$HOST: the raw secret is absent from the session, the vault, and the audit log"
|
|
73
|
+
fi
|
|
74
|
+
|
|
75
|
+
printf '\nRESULT (%s): %d passed, %d failed (advisory)\n' "$HOST" "$PASS" "$FAIL"
|
|
76
|
+
[[ "$FAIL" -eq 0 ]] || echo "state kept for inspection: $STATE"
|
|
77
|
+
exit 0
|