@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
package/src/bitwarden.ts
ADDED
|
@@ -0,0 +1,1450 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Bitwarden half of ai-vault — deliver vault secrets to processes, not to the LLM.
|
|
3
|
+
*
|
|
4
|
+
* Security model
|
|
5
|
+
* ==============
|
|
6
|
+
* - Master password: asked in a desktop window, or the host's input dialog
|
|
7
|
+
* when no window can open (prompt.ts). Lives in memory only for the duration
|
|
8
|
+
* of one `bw unlock` call, passed via env var (never argv). The session key
|
|
9
|
+
* (BW_SESSION) stays in this process's memory: never on disk, never in the
|
|
10
|
+
* bash environment, never in logs or results.
|
|
11
|
+
* - One unlock per session or subagent: omp rebinds the extension for each, and
|
|
12
|
+
* every binding owns its session key. A subagent or a second session cannot
|
|
13
|
+
* use an unlock that is not its own.
|
|
14
|
+
* - bw_inject (pi only): fetches a secret and injects it as an env var into
|
|
15
|
+
* this binding's bash tool (createBashTool's spawnHook). The model never
|
|
16
|
+
* sees the value. A tool_result scrubber replaces every active secret
|
|
17
|
+
* (raw/base64/base64url/URL/hex, plus details/structuredContent) in ALL tool
|
|
18
|
+
* results before they reach the model (catches `echo $VAR`).
|
|
19
|
+
* - bw_run: runs one command with the secret in its environment. This is the
|
|
20
|
+
* OMP path (OMP discards spawnHook env), and also works on pi. Output is
|
|
21
|
+
* scrubbed; nothing is persisted after the command exits.
|
|
22
|
+
* - Every confirmation names the entry that was really matched, not the
|
|
23
|
+
* model's reference. Only the listing's metadata is used to build it; the
|
|
24
|
+
* entry's fields are fetched by id after the user has agreed.
|
|
25
|
+
* - bw_clipboard: copies a secret to the system clipboard, auto-cleared after
|
|
26
|
+
* the configured delay and on lock/exit (only if it still holds our value).
|
|
27
|
+
* The copied value also joins the scrub list, so reading it back with
|
|
28
|
+
* pbpaste/xclip/wl-paste in a later tool result does not leak it.
|
|
29
|
+
* - bw_reveal (off by default, per-call confirmation): returns a secret in
|
|
30
|
+
* plain text. The value then transits the LLM provider and the session file —
|
|
31
|
+
* that is inherent, hence every reveal needs explicit approval.
|
|
32
|
+
* - Auto-lock: configurable idle timeout (config.json, default: session-lifetime,
|
|
33
|
+
* i.e. unlock once per session); always on /bw lock and when the session is
|
|
34
|
+
* left (/new, /fork, exit; a /resume keeps it when keepOnResume is set).
|
|
35
|
+
* `bw lock` is global, so it runs only when the last binding releases its
|
|
36
|
+
* key; one session's lock cannot invalidate another session's unlock.
|
|
37
|
+
* - Audit log: ~/.bw/pi-extension/audit.log (timestamps, session/subagent
|
|
38
|
+
* labels, item names, env var names, allow/deny — never secret values;
|
|
39
|
+
* rotated at 1 MiB).
|
|
40
|
+
* - Config: ~/.bw/pi-extension/config.json (autoLockMinutes, keepOnResume,
|
|
41
|
+
* clipboardClearSeconds, allowReveal, maxInjectedEnv).
|
|
42
|
+
*
|
|
43
|
+
* Requires: bitwarden CLI (`bw`), logged in (`bw login`).
|
|
44
|
+
* Browser filling works via agent-browser: agent-browser fill @ref "$VAR"
|
|
45
|
+
* (the value never enters the conversation).
|
|
46
|
+
*/
|
|
47
|
+
|
|
48
|
+
import { spawn, spawnSync } from "node:child_process";
|
|
49
|
+
import { constants as fsConstants, accessSync, readFileSync, promises as fs } from "node:fs";
|
|
50
|
+
import { homedir, tmpdir } from "node:os";
|
|
51
|
+
import path from "node:path";
|
|
52
|
+
import type { ExtensionAPI, ExtensionContext, ToolDefinition, ToolResultEventResult } from "@earendil-works/pi-coding-agent";
|
|
53
|
+
import { createBashTool } from "@earendil-works/pi-coding-agent";
|
|
54
|
+
import { Type } from "typebox";
|
|
55
|
+
import { bitwardenLogins, filterLogins, type LoginDraft } from "./import-map.js";
|
|
56
|
+
import { onSessionLeave, sessionLabel, withTier } from "./host.js";
|
|
57
|
+
import { confirmWindow, hasDisplay, promptSecret } from "./prompt.js";
|
|
58
|
+
import { scrubDeep, scrubText } from "./scrub.js";
|
|
59
|
+
|
|
60
|
+
// ---------------------------------------------------------------------------
|
|
61
|
+
// Configuration (defaults overridable via ~/.bw/pi-extension/config.json)
|
|
62
|
+
// ---------------------------------------------------------------------------
|
|
63
|
+
const STATE_DIR = process.env.OMP_VAULT_BW_DIR ?? path.join(homedir(), ".bw", "pi-extension");
|
|
64
|
+
const CONFIG_PATH = path.join(STATE_DIR, "config.json");
|
|
65
|
+
|
|
66
|
+
const DEFAULTS = {
|
|
67
|
+
/** Idle minutes before the vault session and injected secrets drop.
|
|
68
|
+
* 0 = unlock lasts for the whole pi session (lock only on /bw lock or exit). */
|
|
69
|
+
autoLockMinutes: 0,
|
|
70
|
+
/** Keep the unlock state when switching sessions with /resume in the same pi process. */
|
|
71
|
+
keepOnResume: true,
|
|
72
|
+
/** Clipboard auto-clear delay. */
|
|
73
|
+
clipboardClearSeconds: 30,
|
|
74
|
+
/** Allow bw_reveal (plain-text secret to the model, per-call confirmation). */
|
|
75
|
+
allowReveal: false,
|
|
76
|
+
/** Upper bound on concurrently injected env vars. */
|
|
77
|
+
maxInjectedEnv: 12,
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
function loadConfig(): typeof DEFAULTS {
|
|
81
|
+
type Config = typeof DEFAULTS;
|
|
82
|
+
const fail = (key: keyof Config, expected: string, fallback: unknown) =>
|
|
83
|
+
process.stderr.write(
|
|
84
|
+
`pi-bitwarden: invalid ${key} in ${CONFIG_PATH} (expected ${expected}); using ${String(fallback)}\n`,
|
|
85
|
+
);
|
|
86
|
+
const int = (
|
|
87
|
+
raw: Record<string, unknown>,
|
|
88
|
+
key: keyof Config,
|
|
89
|
+
min: number,
|
|
90
|
+
max: number,
|
|
91
|
+
invalidFallback: number = DEFAULTS[key] as number,
|
|
92
|
+
): number => {
|
|
93
|
+
const value = raw[key];
|
|
94
|
+
if (value === undefined) return DEFAULTS[key] as number;
|
|
95
|
+
if (typeof value === "number" && Number.isInteger(value) && value >= min && value <= max) return value;
|
|
96
|
+
fail(key, `integer ${min}..${max}`, invalidFallback);
|
|
97
|
+
return invalidFallback;
|
|
98
|
+
};
|
|
99
|
+
const bool = (raw: Record<string, unknown>, key: keyof Config, invalidValue: boolean): boolean => {
|
|
100
|
+
const fallback = DEFAULTS[key] as boolean;
|
|
101
|
+
const value = raw[key];
|
|
102
|
+
if (value === undefined) return fallback;
|
|
103
|
+
if (typeof value === "boolean") return value;
|
|
104
|
+
// Explicit but wrong type: fail closed for security switches.
|
|
105
|
+
fail(key, "true or false", invalidValue);
|
|
106
|
+
return invalidValue;
|
|
107
|
+
};
|
|
108
|
+
|
|
109
|
+
let parsed: unknown;
|
|
110
|
+
try {
|
|
111
|
+
parsed = JSON.parse(readFileSync(CONFIG_PATH, "utf-8"));
|
|
112
|
+
} catch {
|
|
113
|
+
return { ...DEFAULTS };
|
|
114
|
+
}
|
|
115
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return { ...DEFAULTS };
|
|
116
|
+
const raw = parsed as Record<string, unknown>;
|
|
117
|
+
return {
|
|
118
|
+
autoLockMinutes: int(raw, "autoLockMinutes", 0, 10_080, 15),
|
|
119
|
+
keepOnResume: bool(raw, "keepOnResume", false),
|
|
120
|
+
clipboardClearSeconds: int(raw, "clipboardClearSeconds", 0, 3600),
|
|
121
|
+
allowReveal: bool(raw, "allowReveal", false),
|
|
122
|
+
maxInjectedEnv: int(raw, "maxInjectedEnv", 1, 64),
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
const CONFIG = loadConfig();
|
|
127
|
+
/** 0 = no idle lock (session-lifetime unlock). */
|
|
128
|
+
const autoLockMs = CONFIG.autoLockMinutes > 0 ? CONFIG.autoLockMinutes * 60_000 : 0;
|
|
129
|
+
const CLIPBOARD_CLEAR_TEXT =
|
|
130
|
+
CONFIG.clipboardClearSeconds > 0
|
|
131
|
+
? `auto-cleared after ${CONFIG.clipboardClearSeconds}s`
|
|
132
|
+
: "auto-clear disabled (lock/exit still clear)";
|
|
133
|
+
const BW_TIMEOUT_MS = 120_000;
|
|
134
|
+
|
|
135
|
+
/** Env names the model may never claim (shell/loader injection vectors + Bitwarden internals). */
|
|
136
|
+
const ENV_BLOCKLIST =
|
|
137
|
+
/^(PATH|HOME|SHELL|USER|LOGNAME|PWD|OLDPWD|IFS|PS1|PS2|PROMPT_COMMAND|BASH_ENV|BASH_FUNC_.+|BASH_LOADABLES_PATH|ENV|SHELLOPTS|BASHOPTS|LD_.+|DYLD_.+|PYTHONPATH|PYTHONSTARTUP|PERL5OPT|RUBYOPT|NODE_OPTIONS|NODE_PATH|GIT_CONFIG|GIT_CONFIG_GLOBAL|GIT_CONFIG_SYSTEM|GIT_SSH|GIT_SSH_COMMAND|GIT_ASKPASS|GIT_EDITOR|GIT_PAGER|GIT_EXTERNAL_DIFF|SSH_AUTH_SOCK|SSH_ASKPASS|SUDO_ASKPASS|LESSOPEN|LESSCLOSE|PAGER|MANPAGER|EDITOR|VISUAL|BROWSER|SSL_CERT_FILE|REQUESTS_CA_BUNDLE|CURL_HOME|CURL_CA_BUNDLE|http_proxy|https_proxy|all_proxy|no_proxy|PI_.+|BW_.+)$/i;
|
|
138
|
+
|
|
139
|
+
const FIELD_RE = /^(password|totp|code|notes|field:[\w.\- ]{1,64})$/;
|
|
140
|
+
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
141
|
+
|
|
142
|
+
const BW_LOGIN_HINT =
|
|
143
|
+
"Bitwarden CLI is not logged in. Run `bw login` in a terminal first " +
|
|
144
|
+
"(and `bw config --server <url>` if self-hosted), then retry. " +
|
|
145
|
+
"You can check with /bw status.";
|
|
146
|
+
|
|
147
|
+
// ---------------------------------------------------------------------------
|
|
148
|
+
// State (memory only)
|
|
149
|
+
// ---------------------------------------------------------------------------
|
|
150
|
+
type BwItem = {
|
|
151
|
+
id?: string;
|
|
152
|
+
name?: string;
|
|
153
|
+
notes?: string;
|
|
154
|
+
login?: { username?: string; password?: string; totp?: string; uris?: { uri?: string }[] };
|
|
155
|
+
fields?: { name?: string; value?: string }[];
|
|
156
|
+
};
|
|
157
|
+
/** Only metadata is cached; secrets stay in the vault process until needed. */
|
|
158
|
+
type LiteItem = { id: string; name: string; username: string; uri: string };
|
|
159
|
+
type InjectedSecret = { value: string; item: string; field: string; at: number };
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* One session or subagent. omp rebinds the extension factory for each, so the
|
|
163
|
+
* session key, the injected variables, and the item cache belong to the binding
|
|
164
|
+
* that unlocked them and are never shared with another.
|
|
165
|
+
*/
|
|
166
|
+
export interface BwState {
|
|
167
|
+
key?: string;
|
|
168
|
+
verifiedAt: number;
|
|
169
|
+
lastActivity: number;
|
|
170
|
+
inFlight?: Promise<string>;
|
|
171
|
+
/** Bumped by lock(): an unlock that started earlier is discarded. */
|
|
172
|
+
epoch: number;
|
|
173
|
+
/** Metadata only; an entry's fields are fetched by id, for an approved request. */
|
|
174
|
+
cache?: { at: number; items: LiteItem[] };
|
|
175
|
+
/** Audit label of the session or subagent this binding serves (set when it unlocks). */
|
|
176
|
+
sessionLabel?: string;
|
|
177
|
+
/** pi only: ENV -> injected secret, read by this binding's bash tool. */
|
|
178
|
+
injected: Map<string, InjectedSecret>;
|
|
179
|
+
lockTimer?: NodeJS.Timeout;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
export function newBwState(): BwState {
|
|
183
|
+
return { verifiedAt: 0, lastActivity: Date.now(), epoch: 0, injected: new Map() };
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/**
|
|
187
|
+
* Values the output scrubber must keep hiding, even after /bw clear or lock:
|
|
188
|
+
* a command may already have copied $VAR to a file, and a later `cat` would
|
|
189
|
+
* otherwise leak it. Keyed by ENV + value so replacements keep both.
|
|
190
|
+
*
|
|
191
|
+
* The list is bounded so a session that asks for many different values (every
|
|
192
|
+
* TOTP code is a new one) cannot grow it without end. It is kept large enough
|
|
193
|
+
* that an ordinary session never evicts a value that may still be on disk;
|
|
194
|
+
* past the bound, the least recently used value loses its protection.
|
|
195
|
+
*/
|
|
196
|
+
const scrubValues = new Map<string, { env: string; value: string }>();
|
|
197
|
+
const MAX_SCRUB_VALUES = 512;
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* Bindings in this process that still hold a Bitwarden session key.
|
|
201
|
+
*
|
|
202
|
+
* `bw lock` destroys every active session key, not just ours, so it must run
|
|
203
|
+
* only when the last binding lets go. A /new, /fork, idle lock or subagent
|
|
204
|
+
* shutdown in one session must not invalidate another session's unlock.
|
|
205
|
+
*/
|
|
206
|
+
let liveSessionKeys = 0;
|
|
207
|
+
|
|
208
|
+
function acquireSessionKey(): void {
|
|
209
|
+
liveSessionKeys++;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/** Returns true when this was the last key, i.e. a global `bw lock` is now safe. */
|
|
213
|
+
function releaseSessionKey(): boolean {
|
|
214
|
+
if (liveSessionKeys > 0) liveSessionKeys--;
|
|
215
|
+
return liveSessionKeys === 0;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
function rememberScrubValue(env: string, value: string): void {
|
|
219
|
+
const key = `${env}\u0000${value}`;
|
|
220
|
+
// Re-insert so a value that is still in use moves to the back: the oldest
|
|
221
|
+
// entry to drop is the one that has gone unused the longest.
|
|
222
|
+
scrubValues.delete(key);
|
|
223
|
+
scrubValues.set(key, { env, value });
|
|
224
|
+
while (scrubValues.size > MAX_SCRUB_VALUES) {
|
|
225
|
+
const oldest = scrubValues.keys().next();
|
|
226
|
+
if (oldest.done) break;
|
|
227
|
+
scrubValues.delete(oldest.value);
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
process.once("exit", () => {
|
|
232
|
+
clearClipboardSync();
|
|
233
|
+
});
|
|
234
|
+
|
|
235
|
+
// ---------------------------------------------------------------------------
|
|
236
|
+
// Small helpers
|
|
237
|
+
// ---------------------------------------------------------------------------
|
|
238
|
+
function safeStatus(ctx: ExtensionContext | undefined, text: string | undefined): void {
|
|
239
|
+
try {
|
|
240
|
+
ctx?.ui.setStatus("bitwarden", text);
|
|
241
|
+
} catch {
|
|
242
|
+
/* runner may be inactive */
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
function tail(s: string, n = 200): string {
|
|
247
|
+
const t = s.trim();
|
|
248
|
+
if (!t) return "";
|
|
249
|
+
return t.length > n ? t.slice(-n) : t;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/** Most output kept per stream; a runaway command must not exhaust memory. */
|
|
253
|
+
const OUTPUT_CAP = 8 * 1024 * 1024;
|
|
254
|
+
|
|
255
|
+
interface ExecOptions {
|
|
256
|
+
env?: Record<string, string>;
|
|
257
|
+
timeout?: number;
|
|
258
|
+
input?: string;
|
|
259
|
+
signal?: AbortSignal;
|
|
260
|
+
cwd?: string;
|
|
261
|
+
/** Run in its own process group, so a timeout also kills what it spawned. */
|
|
262
|
+
group?: boolean;
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
interface ExecResult {
|
|
266
|
+
stdout: string;
|
|
267
|
+
stderr: string;
|
|
268
|
+
code: number;
|
|
269
|
+
/** True when output past OUTPUT_CAP was dropped. */
|
|
270
|
+
truncated: boolean;
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/**
|
|
274
|
+
* Environment for a child process: the host's environment without any BW_*
|
|
275
|
+
* variables. The session key is passed explicitly per call (BW_SESSION for
|
|
276
|
+
* `bw`, BW_MASTER_PASSWORD for one unlock), so a key exported in the user's
|
|
277
|
+
* shell can never leak into bash or a bw_run command.
|
|
278
|
+
*/
|
|
279
|
+
function childEnv(extra?: Record<string, string>): NodeJS.ProcessEnv {
|
|
280
|
+
const env: NodeJS.ProcessEnv = {};
|
|
281
|
+
for (const [key, value] of Object.entries(process.env)) {
|
|
282
|
+
if (!key.startsWith("BW_")) env[key] = value;
|
|
283
|
+
}
|
|
284
|
+
if (extra) Object.assign(env, extra);
|
|
285
|
+
return env;
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
function exec(cmd: string, args: string[], opts: ExecOptions = {}): Promise<ExecResult> {
|
|
289
|
+
if (opts.signal?.aborted) return Promise.reject(new Error(`${cmd} cancelled`));
|
|
290
|
+
const { promise, resolve, reject } = Promise.withResolvers<ExecResult>();
|
|
291
|
+
const child = spawn(cmd, args, {
|
|
292
|
+
env: childEnv(opts.env),
|
|
293
|
+
cwd: opts.cwd,
|
|
294
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
295
|
+
detached: opts.group === true,
|
|
296
|
+
});
|
|
297
|
+
let out = "";
|
|
298
|
+
let err = "";
|
|
299
|
+
let truncated = false;
|
|
300
|
+
let settled = false;
|
|
301
|
+
const kill = () => {
|
|
302
|
+
if (opts.group && child.pid) {
|
|
303
|
+
try {
|
|
304
|
+
process.kill(-child.pid, "SIGKILL");
|
|
305
|
+
} catch {
|
|
306
|
+
/* the group is already gone */
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
child.kill("SIGKILL");
|
|
310
|
+
};
|
|
311
|
+
const cleanup = () => {
|
|
312
|
+
clearTimeout(timer);
|
|
313
|
+
opts.signal?.removeEventListener("abort", onAbort);
|
|
314
|
+
};
|
|
315
|
+
const finish = (fn: () => void) => {
|
|
316
|
+
if (settled) return;
|
|
317
|
+
settled = true;
|
|
318
|
+
cleanup();
|
|
319
|
+
fn();
|
|
320
|
+
};
|
|
321
|
+
const onAbort = () =>
|
|
322
|
+
finish(() => {
|
|
323
|
+
kill();
|
|
324
|
+
reject(new Error(`${cmd} cancelled`));
|
|
325
|
+
});
|
|
326
|
+
const timer = setTimeout(
|
|
327
|
+
() =>
|
|
328
|
+
finish(() => {
|
|
329
|
+
kill();
|
|
330
|
+
reject(new Error(`${cmd} timed out after ${opts.timeout ?? BW_TIMEOUT_MS}ms`));
|
|
331
|
+
}),
|
|
332
|
+
opts.timeout ?? BW_TIMEOUT_MS,
|
|
333
|
+
);
|
|
334
|
+
opts.signal?.addEventListener("abort", onAbort, { once: true });
|
|
335
|
+
if (opts.signal?.aborted) onAbort();
|
|
336
|
+
child.stdout?.on("data", (chunk: Buffer | string) => {
|
|
337
|
+
if (out.length < OUTPUT_CAP) out += chunk;
|
|
338
|
+
else truncated = true;
|
|
339
|
+
});
|
|
340
|
+
child.stderr?.on("data", (chunk: Buffer | string) => {
|
|
341
|
+
if (err.length < OUTPUT_CAP) err += chunk;
|
|
342
|
+
else truncated = true;
|
|
343
|
+
});
|
|
344
|
+
child.on("error", (e) => finish(() => reject(e)));
|
|
345
|
+
child.on("close", (code) => finish(() => resolve({ stdout: out, stderr: err, code: code ?? -1, truncated })));
|
|
346
|
+
child.stdin?.on("error", () => {}); // EPIPE when the child dies before reading input
|
|
347
|
+
if (opts.input !== undefined) child.stdin?.write(opts.input);
|
|
348
|
+
child.stdin?.end();
|
|
349
|
+
return promise;
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
const AUDIT_MAX_BYTES = 1024 * 1024;
|
|
353
|
+
let auditModeFixed = false;
|
|
354
|
+
|
|
355
|
+
/** One audit line per event. `session` is the binding's label, so a subagent's `bw_run` can be told from its parent's. */
|
|
356
|
+
async function audit(event: string, detail: string, session?: string): Promise<void> {
|
|
357
|
+
try {
|
|
358
|
+
await fs.mkdir(STATE_DIR, { recursive: true, mode: 0o700 });
|
|
359
|
+
const log = path.join(STATE_DIR, "audit.log");
|
|
360
|
+
if (!auditModeFixed) {
|
|
361
|
+
auditModeFixed = true;
|
|
362
|
+
await fs.chmod(STATE_DIR, 0o700).catch(() => {});
|
|
363
|
+
await fs.chmod(log, 0o600).catch(() => {});
|
|
364
|
+
}
|
|
365
|
+
try {
|
|
366
|
+
const stat = await fs.stat(log);
|
|
367
|
+
if (stat.size > AUDIT_MAX_BYTES) await fs.rename(log, `${log}.1`);
|
|
368
|
+
} catch {
|
|
369
|
+
/* first entry */
|
|
370
|
+
}
|
|
371
|
+
// Item names are model/vault supplied: keep one entry per line.
|
|
372
|
+
const safeDetail = detail.replace(/[\r\n]+/g, " ").slice(0, 500);
|
|
373
|
+
const safeSession = session?.replace(/[^\w./-]/g, "").slice(0, 48);
|
|
374
|
+
const line = `${new Date().toISOString()} ${event}${safeSession ? ` session=${safeSession}` : ""} ${safeDetail}\n`;
|
|
375
|
+
await fs.appendFile(log, line, { mode: 0o600 });
|
|
376
|
+
} catch {
|
|
377
|
+
/* best-effort */
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
// ---------------------------------------------------------------------------
|
|
382
|
+
// Bitwarden CLI plumbing (secrets only ever travel via env vars / pipes)
|
|
383
|
+
// ---------------------------------------------------------------------------
|
|
384
|
+
let bwBin: string | undefined;
|
|
385
|
+
|
|
386
|
+
async function resolveBw(): Promise<string> {
|
|
387
|
+
if (bwBin) return bwBin;
|
|
388
|
+
try {
|
|
389
|
+
await exec("bw", ["--version"], { timeout: 20_000 });
|
|
390
|
+
bwBin = "bw";
|
|
391
|
+
return bwBin;
|
|
392
|
+
} catch {
|
|
393
|
+
/* fall through to nvm scan */
|
|
394
|
+
}
|
|
395
|
+
try {
|
|
396
|
+
const nvmDir = path.join(homedir(), ".nvm", "versions", "node");
|
|
397
|
+
const versions = (await fs.readdir(nvmDir).catch(() => [] as string[]))
|
|
398
|
+
.filter((v) => /^\d+\.\d+\.\d+$/.test(v))
|
|
399
|
+
.sort((a, b) => a.localeCompare(b, undefined, { numeric: true }))
|
|
400
|
+
.reverse();
|
|
401
|
+
for (const v of versions) {
|
|
402
|
+
const p = path.join(nvmDir, v, "bin", "bw");
|
|
403
|
+
if (await fs.access(p).then(() => true, () => false)) {
|
|
404
|
+
bwBin = p;
|
|
405
|
+
return bwBin;
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
} catch {
|
|
409
|
+
/* ignore */
|
|
410
|
+
}
|
|
411
|
+
throw new Error("Bitwarden CLI (`bw`) not found in PATH or ~/.nvm. Install it, `bw login`, and retry.");
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
async function runBw(
|
|
415
|
+
args: string[],
|
|
416
|
+
opts: { session?: string; extraEnv?: Record<string, string>; signal?: AbortSignal } = {},
|
|
417
|
+
): Promise<string> {
|
|
418
|
+
const bin = await resolveBw();
|
|
419
|
+
const env: Record<string, string> = { ...opts.extraEnv };
|
|
420
|
+
if (opts.session) env.BW_SESSION = opts.session;
|
|
421
|
+
const r = await exec(bin, [...args, "--nointeraction"], { env, signal: opts.signal });
|
|
422
|
+
if (r.code !== 0) {
|
|
423
|
+
const hint = tail(r.stderr) || `exit ${r.code}`;
|
|
424
|
+
// Never include stdout in errors — some commands print secrets on success-ish paths.
|
|
425
|
+
throw new Error(`bw ${args.slice(0, 2).join(" ")} failed: ${hint}`);
|
|
426
|
+
}
|
|
427
|
+
return r.stdout;
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
async function runBwJson(args: string[], session?: string, signal?: AbortSignal): Promise<any> {
|
|
431
|
+
return JSON.parse(await runBw(args, { session, signal }));
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
let statusCache: { at: number; json: any } | undefined;
|
|
435
|
+
|
|
436
|
+
async function bwStatus(session?: string, signal?: AbortSignal): Promise<any> {
|
|
437
|
+
// With a session, this verifies that key. Without one it asks whether the CLI
|
|
438
|
+
// itself is locked; a stale BW_SESSION in the host env would make it exit
|
|
439
|
+
// non-zero, so the probe never inherits the env (see childEnv).
|
|
440
|
+
if (session) {
|
|
441
|
+
const r = await runBw(["status"], { session, signal });
|
|
442
|
+
return JSON.parse(r);
|
|
443
|
+
}
|
|
444
|
+
if (statusCache && Date.now() - statusCache.at < 3000) return statusCache.json;
|
|
445
|
+
const json = await runBwJson(["status"], undefined, signal);
|
|
446
|
+
statusCache = { at: Date.now(), json };
|
|
447
|
+
return json;
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
/** The Bitwarden master password, in a window or the host's input dialog. */
|
|
451
|
+
async function askMasterPassword(ctx: ExtensionContext | undefined, signal?: AbortSignal): Promise<string> {
|
|
452
|
+
const pw = await promptSecret(ctx, "Bitwarden · 主密码", "解锁 Bitwarden 保险库", signal);
|
|
453
|
+
if (pw) return pw;
|
|
454
|
+
if (signal?.aborted) throw new Error("Cancelled.");
|
|
455
|
+
if (!hasDisplay() && !ctx?.hasUI) {
|
|
456
|
+
throw new Error(
|
|
457
|
+
"No way to prompt for the master password (no desktop, no interactive UI). Run /bw unlock in an interactive session.",
|
|
458
|
+
);
|
|
459
|
+
}
|
|
460
|
+
throw new Error("Master password prompt cancelled.");
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
async function confirmAction(
|
|
464
|
+
ctx: ExtensionContext | undefined,
|
|
465
|
+
title: string,
|
|
466
|
+
message: string,
|
|
467
|
+
signal?: AbortSignal,
|
|
468
|
+
): Promise<boolean> {
|
|
469
|
+
const ok = await confirmWindow(ctx, title, message, signal);
|
|
470
|
+
if (signal?.aborted) throw new Error("Cancelled.");
|
|
471
|
+
return ok;
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
function touchActivity(st: BwState): void {
|
|
475
|
+
st.lastActivity = Date.now();
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
function startAutoLock(st: BwState, ctx: ExtensionContext | undefined): void {
|
|
479
|
+
st.lastActivity = Date.now();
|
|
480
|
+
if (st.lockTimer || !autoLockMs) return;
|
|
481
|
+
const tick = () => {
|
|
482
|
+
if (st.key && autoLockMs && Date.now() - st.lastActivity > autoLockMs) {
|
|
483
|
+
void lock(st, "auto-idle");
|
|
484
|
+
}
|
|
485
|
+
};
|
|
486
|
+
// A timer made through omp's context is cleared for us on session_shutdown.
|
|
487
|
+
const host = ctx as { setInterval?: (callback: () => void, ms?: number) => NodeJS.Timeout } | undefined;
|
|
488
|
+
st.lockTimer = host?.setInterval ? host.setInterval(tick, 30_000) : setInterval(tick, 30_000);
|
|
489
|
+
st.lockTimer.unref?.();
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
/** Drop this binding's session key and injected variables, and the clipboard. */
|
|
493
|
+
async function lock(st: BwState, reason: string): Promise<void> {
|
|
494
|
+
const hadSession = !!st.key;
|
|
495
|
+
st.epoch++;
|
|
496
|
+
st.key = undefined;
|
|
497
|
+
st.verifiedAt = 0;
|
|
498
|
+
st.cache = undefined;
|
|
499
|
+
st.injected.clear();
|
|
500
|
+
// An unlock that was waiting for its password window must not be reused;
|
|
501
|
+
// its epoch check already discards the result, and the next call asks again.
|
|
502
|
+
st.inFlight = undefined;
|
|
503
|
+
// From here on the clipboard is not ours to keep: a copy still in flight
|
|
504
|
+
// must clear again when it lands (see copyToClipboard).
|
|
505
|
+
clipboardDrops++;
|
|
506
|
+
await clearClipboardIfOwner();
|
|
507
|
+
if (st.lockTimer) {
|
|
508
|
+
clearInterval(st.lockTimer);
|
|
509
|
+
st.lockTimer = undefined;
|
|
510
|
+
}
|
|
511
|
+
if (hadSession) {
|
|
512
|
+
await audit("lock", `reason=${reason}`, st.sessionLabel);
|
|
513
|
+
if (!releaseSessionKey()) return; // another binding still uses its own key
|
|
514
|
+
try {
|
|
515
|
+
const bin = await resolveBw();
|
|
516
|
+
await exec(bin, ["lock", "--nointeraction"], { timeout: 15_000 });
|
|
517
|
+
} catch {
|
|
518
|
+
/* best-effort; dropping our session key is what matters */
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
async function ensureUnlocked(st: BwState, ctx: ExtensionContext | undefined, signal?: AbortSignal): Promise<string> {
|
|
524
|
+
touchActivity(st);
|
|
525
|
+
// Every audit line of this binding names the session or subagent that asked.
|
|
526
|
+
st.sessionLabel = sessionLabel(ctx);
|
|
527
|
+
if (signal?.aborted) throw new Error("Cancelled.");
|
|
528
|
+
if (st.key && Date.now() - st.verifiedAt < 30_000) return st.key;
|
|
529
|
+
if (st.key) {
|
|
530
|
+
try {
|
|
531
|
+
const status = await bwStatus(st.key, signal);
|
|
532
|
+
if (status?.status === "unlocked") {
|
|
533
|
+
st.verifiedAt = Date.now();
|
|
534
|
+
return st.key;
|
|
535
|
+
}
|
|
536
|
+
} catch {
|
|
537
|
+
if (signal?.aborted) throw new Error("Cancelled.");
|
|
538
|
+
/* stale session key */
|
|
539
|
+
}
|
|
540
|
+
st.key = undefined;
|
|
541
|
+
st.verifiedAt = 0;
|
|
542
|
+
releaseSessionKey();
|
|
543
|
+
}
|
|
544
|
+
if (st.inFlight) return st.inFlight;
|
|
545
|
+
|
|
546
|
+
const epoch = st.epoch;
|
|
547
|
+
const pending = (async () => {
|
|
548
|
+
const status = await bwStatus(undefined, signal); // no session env
|
|
549
|
+
if (status?.status === "unauthenticated") throw new Error(BW_LOGIN_HINT);
|
|
550
|
+
|
|
551
|
+
const pw = await askMasterPassword(ctx, signal);
|
|
552
|
+
const bin = await resolveBw();
|
|
553
|
+
const r = await exec(bin, ["unlock", "--passwordenv", "BW_MASTER_PASSWORD", "--raw"], {
|
|
554
|
+
env: { BW_MASTER_PASSWORD: pw },
|
|
555
|
+
timeout: 60_000,
|
|
556
|
+
signal,
|
|
557
|
+
});
|
|
558
|
+
if (r.code !== 0) {
|
|
559
|
+
await audit("unlock", "deny=bad-password", st.sessionLabel);
|
|
560
|
+
throw new Error(`Unlock failed (wrong master password or CLI error). ${tail(r.stderr, 120)}`);
|
|
561
|
+
}
|
|
562
|
+
const key = r.stdout.replace(/[\r\n]+$/, "");
|
|
563
|
+
if (!key) throw new Error("Unlock failed: empty session key.");
|
|
564
|
+
const verify = await bwStatus(key, signal);
|
|
565
|
+
if (verify?.status !== "unlocked") throw new Error("Unlock failed: session key not accepted.");
|
|
566
|
+
// /bw lock or a session switch ran while the password window was open.
|
|
567
|
+
if (epoch !== st.epoch || signal?.aborted) throw new Error("Cancelled.");
|
|
568
|
+
st.key = key;
|
|
569
|
+
st.verifiedAt = Date.now();
|
|
570
|
+
acquireSessionKey();
|
|
571
|
+
startAutoLock(st, ctx);
|
|
572
|
+
await audit("unlock", "ok", st.sessionLabel);
|
|
573
|
+
// Refresh in the background: a full sync can take seconds on large vaults.
|
|
574
|
+
const lastSync = Date.parse(status?.lastSync ?? "");
|
|
575
|
+
if (!Number.isFinite(lastSync) || Date.now() - lastSync > 15 * 60_000) {
|
|
576
|
+
void runBw(["sync"], { session: key }).catch(() => {
|
|
577
|
+
/* offline ok — cached vault */
|
|
578
|
+
});
|
|
579
|
+
}
|
|
580
|
+
return key;
|
|
581
|
+
})();
|
|
582
|
+
st.inFlight = pending;
|
|
583
|
+
// Only clear the slot if it still belongs to this attempt: a lock followed
|
|
584
|
+
// by a new unlock must not have its promise erased by the old one.
|
|
585
|
+
void pending.then(
|
|
586
|
+
() => {
|
|
587
|
+
if (st.inFlight === pending) st.inFlight = undefined;
|
|
588
|
+
},
|
|
589
|
+
() => {
|
|
590
|
+
if (st.inFlight === pending) st.inFlight = undefined;
|
|
591
|
+
},
|
|
592
|
+
);
|
|
593
|
+
return pending;
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
function toLite(raw: BwItem): LiteItem {
|
|
597
|
+
return {
|
|
598
|
+
id: raw.id ?? "",
|
|
599
|
+
name: raw.name ?? "",
|
|
600
|
+
username: raw.login?.username ?? "",
|
|
601
|
+
uri: raw.login?.uris?.[0]?.uri ?? "",
|
|
602
|
+
};
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
async function listItems(
|
|
606
|
+
st: BwState,
|
|
607
|
+
session: string,
|
|
608
|
+
signal?: AbortSignal,
|
|
609
|
+
opts: { fresh?: boolean } = {},
|
|
610
|
+
): Promise<LiteItem[]> {
|
|
611
|
+
if (!opts.fresh && st.cache && Date.now() - st.cache.at < 5 * 60_000) return st.cache.items;
|
|
612
|
+
const raw = (await runBwJson(["list", "items"], session, signal)) as BwItem[];
|
|
613
|
+
const items = raw.map(toLite);
|
|
614
|
+
st.cache = { at: Date.now(), items };
|
|
615
|
+
return items;
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
/** The whole entry, secret fields included. Called only for an entry the user already approved, by id. */
|
|
619
|
+
async function getItemById(session: string, id: string, signal?: AbortSignal): Promise<BwItem> {
|
|
620
|
+
try {
|
|
621
|
+
return (await runBwJson(["get", "item", id], session, signal)) as BwItem;
|
|
622
|
+
} catch (e) {
|
|
623
|
+
// Only a missing item is reported as such; a CLI or network error keeps its own message.
|
|
624
|
+
if (e instanceof Error && /not found/i.test(e.message)) throw new Error(`No Bitwarden item with id ${id}.`);
|
|
625
|
+
throw e;
|
|
626
|
+
}
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
function itemScore(item: LiteItem, query: string): number {
|
|
630
|
+
const haystack = `${item.name} ${item.username} ${item.uri}`.toLowerCase();
|
|
631
|
+
let score = 0;
|
|
632
|
+
for (const token of query.split(/\s+/).filter(Boolean)) {
|
|
633
|
+
if (haystack.includes(token)) score += 10;
|
|
634
|
+
else if (token.length > 3 && haystack.includes(token.slice(0, Math.max(3, token.length - 2)))) score += 3;
|
|
635
|
+
}
|
|
636
|
+
return score;
|
|
637
|
+
}
|
|
638
|
+
|
|
639
|
+
/**
|
|
640
|
+
* Resolve the model's reference to the entry it really names, as metadata.
|
|
641
|
+
* Asking the user only needs the name and username; the entry's fields are
|
|
642
|
+
* fetched by id in secretOf(), after the user has agreed.
|
|
643
|
+
*/
|
|
644
|
+
async function resolveItem(st: BwState, session: string, ref: string, signal?: AbortSignal): Promise<LiteItem> {
|
|
645
|
+
if (UUID_RE.test(ref)) {
|
|
646
|
+
let items = await listItems(st, session, signal);
|
|
647
|
+
// An item created after the cache was filled is missing from it: look once more.
|
|
648
|
+
if (!items.some((i) => i.id === ref)) items = await listItems(st, session, signal, { fresh: true });
|
|
649
|
+
const byId = items.find((i) => i.id === ref);
|
|
650
|
+
if (byId) return byId;
|
|
651
|
+
throw new Error(`No Bitwarden item with id ${ref}. Use bw_list to browse item ids.`);
|
|
652
|
+
}
|
|
653
|
+
|
|
654
|
+
const items = await listItems(st, session, signal);
|
|
655
|
+
const query = ref.trim().toLowerCase();
|
|
656
|
+
if (!query) throw new Error("Item reference is empty; pass an item name or id.");
|
|
657
|
+
const exact = items.filter((i) => i.name.toLowerCase() === query);
|
|
658
|
+
const partial = items.filter((i) =>
|
|
659
|
+
`${i.name}\n${i.username}\n${i.uri}`.toLowerCase().includes(query),
|
|
660
|
+
);
|
|
661
|
+
const hits = exact.length > 0 ? exact : partial;
|
|
662
|
+
const only = hits[0];
|
|
663
|
+
if (hits.length === 1 && only) return only;
|
|
664
|
+
|
|
665
|
+
const list = (items: LiteItem[]) =>
|
|
666
|
+
items
|
|
667
|
+
.slice(0, 10)
|
|
668
|
+
.map((i) => `- ${i.name || "?"} | user: ${i.username || "-"} | ${i.uri || "-"} | id: ${i.id}`)
|
|
669
|
+
.join("\n");
|
|
670
|
+
if (hits.length > 1) throw new Error(`Multiple Bitwarden items match "${ref}". Specify by id:\n${list(hits)}`);
|
|
671
|
+
|
|
672
|
+
const closest = items
|
|
673
|
+
.map((item) => ({ item, score: itemScore(item, query) }))
|
|
674
|
+
.filter((entry) => entry.score > 0)
|
|
675
|
+
.sort((a, b) => b.score - a.score)
|
|
676
|
+
.slice(0, 10)
|
|
677
|
+
.map((entry) => entry.item);
|
|
678
|
+
throw new Error(
|
|
679
|
+
closest.length > 0
|
|
680
|
+
? `No Bitwarden item matches "${ref}". Closest items:\n${list(closest)}`
|
|
681
|
+
: `No Bitwarden item matches "${ref}". Use bw_list to browse item names.`,
|
|
682
|
+
);
|
|
683
|
+
}
|
|
684
|
+
|
|
685
|
+
function extractSecret(item: BwItem, field: string): string {
|
|
686
|
+
let v: string | undefined;
|
|
687
|
+
if (field === "password") v = item.login?.password;
|
|
688
|
+
else if (field === "totp") v = item.login?.totp; // TOTP seed, not the rotating code
|
|
689
|
+
else if (field === "notes") v = item.notes;
|
|
690
|
+
else if (field.startsWith("field:")) {
|
|
691
|
+
const name = field.slice(6);
|
|
692
|
+
v = item.fields?.find((f) => f.name === name)?.value;
|
|
693
|
+
}
|
|
694
|
+
if (typeof v !== "string" || v.length === 0) {
|
|
695
|
+
throw new Error(`Field "${field}" is empty or missing on item "${item.name ?? "?"}".`);
|
|
696
|
+
}
|
|
697
|
+
return v;
|
|
698
|
+
}
|
|
699
|
+
|
|
700
|
+
/**
|
|
701
|
+
* Unlock, resolve the model's reference to the entry it really names, and ask
|
|
702
|
+
* the user about that entry. The window shows the resolved name and username,
|
|
703
|
+
* so a fuzzy or mistyped reference cannot be approved as some other entry.
|
|
704
|
+
* Only metadata is resolved here; the entry's fields are fetched after the
|
|
705
|
+
* user agrees, by the id that was shown.
|
|
706
|
+
*/
|
|
707
|
+
async function approveItem(
|
|
708
|
+
st: BwState,
|
|
709
|
+
ctx: ExtensionContext | undefined,
|
|
710
|
+
event: string,
|
|
711
|
+
title: string,
|
|
712
|
+
itemRef: string,
|
|
713
|
+
field: string,
|
|
714
|
+
detail: string,
|
|
715
|
+
signal?: AbortSignal,
|
|
716
|
+
): Promise<{ session: string; item: LiteItem } | undefined> {
|
|
717
|
+
const session = await ensureUnlocked(st, ctx, signal);
|
|
718
|
+
const item = await resolveItem(st, session, itemRef, signal);
|
|
719
|
+
const name = item.name || "?";
|
|
720
|
+
const user = item.username ? ` (user: ${item.username})` : "";
|
|
721
|
+
const ok = await confirmAction(ctx, title, `Item: ${name}${user}\nField: ${field}\n${detail}\n\nAllow?`, signal);
|
|
722
|
+
if (!ok) {
|
|
723
|
+
await audit(event, `deny item="${name}" field=${field}`, st.sessionLabel);
|
|
724
|
+
return undefined;
|
|
725
|
+
}
|
|
726
|
+
return { session, item };
|
|
727
|
+
}
|
|
728
|
+
|
|
729
|
+
/** Read one field of an entry the user has just approved: the entry is fetched now, by the id that was shown. */
|
|
730
|
+
async function secretOf(
|
|
731
|
+
session: string,
|
|
732
|
+
item: LiteItem,
|
|
733
|
+
field: string,
|
|
734
|
+
signal?: AbortSignal,
|
|
735
|
+
): Promise<{ value: string; itemId: string; itemName: string }> {
|
|
736
|
+
const itemName = item.name || "?";
|
|
737
|
+
if (!item.id) {
|
|
738
|
+
throw new Error(`Bitwarden item "${itemName}" has no id, so ${field === "code" ? "no TOTP code can be generated" : "its fields cannot be read"}.`);
|
|
739
|
+
}
|
|
740
|
+
if (field === "code") {
|
|
741
|
+
const code = (await runBw(["get", "totp", item.id], { session, signal })).trim();
|
|
742
|
+
if (!code) throw new Error(`No TOTP code available for item "${itemName}".`);
|
|
743
|
+
return { value: code, itemId: item.id, itemName };
|
|
744
|
+
}
|
|
745
|
+
const full = await getItemById(session, item.id, signal);
|
|
746
|
+
return { value: extractSecret(full, field), itemId: item.id, itemName };
|
|
747
|
+
}
|
|
748
|
+
|
|
749
|
+
export type BitwardenMeta = { id: string; name: string; username: string; uri: string };
|
|
750
|
+
|
|
751
|
+
/** Metadata only. Unlocks Bitwarden (master-password window) on first use. */
|
|
752
|
+
export async function queryBitwarden(
|
|
753
|
+
st: BwState,
|
|
754
|
+
ctx: ExtensionContext | undefined,
|
|
755
|
+
search: string | undefined,
|
|
756
|
+
signal?: AbortSignal,
|
|
757
|
+
): Promise<BitwardenMeta[]> {
|
|
758
|
+
const session = await ensureUnlocked(st, ctx, signal);
|
|
759
|
+
let items = await listItems(st, session, signal);
|
|
760
|
+
const query = (search ?? "").trim().toLowerCase();
|
|
761
|
+
if (query) {
|
|
762
|
+
items = items.filter((item) => `${item.name}\n${item.username}\n${item.uri}`.toLowerCase().includes(query));
|
|
763
|
+
}
|
|
764
|
+
return items.map((item) => ({ id: item.id, name: item.name, username: item.username, uri: item.uri }));
|
|
765
|
+
}
|
|
766
|
+
|
|
767
|
+
/**
|
|
768
|
+
* Login items that have a password, ready to store in the local vault.
|
|
769
|
+
* Call only after the user has agreed to the import — this reads secrets.
|
|
770
|
+
*/
|
|
771
|
+
export async function pullBitwardenLogins(
|
|
772
|
+
st: BwState,
|
|
773
|
+
ctx: ExtensionContext | undefined,
|
|
774
|
+
search: string | undefined,
|
|
775
|
+
signal?: AbortSignal,
|
|
776
|
+
): Promise<LoginDraft[]> {
|
|
777
|
+
const session = await ensureUnlocked(st, ctx, signal);
|
|
778
|
+
const raw: unknown = await runBwJson(["list", "items"], session, signal);
|
|
779
|
+
return filterLogins(bitwardenLogins(raw), search);
|
|
780
|
+
}
|
|
781
|
+
|
|
782
|
+
function normalizeEnvName(raw: string): string {
|
|
783
|
+
const name = raw.trim().toUpperCase();
|
|
784
|
+
if (!/^[A-Z_][A-Z0-9_]*$/.test(name)) {
|
|
785
|
+
throw new Error(`Invalid env var name "${raw}". Use letters, digits, underscores; must not start with a digit.`);
|
|
786
|
+
}
|
|
787
|
+
if (ENV_BLOCKLIST.test(name)) {
|
|
788
|
+
throw new Error(`Env var name "${name}" is blocked (shell/loader/Bitwarden internals). Pick a specific name like MYAPP_TOKEN.`);
|
|
789
|
+
}
|
|
790
|
+
return name;
|
|
791
|
+
}
|
|
792
|
+
|
|
793
|
+
function injectedListText(st: BwState): string {
|
|
794
|
+
if (st.injected.size === 0) return "(none)";
|
|
795
|
+
return [...st.injected.entries()].map(([env, r]) => `$${env} ← "${r.item}" (${r.field})`).join(", ");
|
|
796
|
+
}
|
|
797
|
+
|
|
798
|
+
// ---------------------------------------------------------------------------
|
|
799
|
+
// Clipboard
|
|
800
|
+
// ---------------------------------------------------------------------------
|
|
801
|
+
type ClipboardBackend = {
|
|
802
|
+
copy: [string, string[]];
|
|
803
|
+
clear: [string, string[]];
|
|
804
|
+
read: [string, string[]];
|
|
805
|
+
};
|
|
806
|
+
|
|
807
|
+
/** Whether an executable is on PATH, so a Wayland session can fall back to X11. */
|
|
808
|
+
function commandExists(command: string): boolean {
|
|
809
|
+
for (const dir of (process.env.PATH ?? "").split(path.delimiter)) {
|
|
810
|
+
if (!dir) continue;
|
|
811
|
+
try {
|
|
812
|
+
accessSync(path.join(dir, command), fsConstants.X_OK);
|
|
813
|
+
return true;
|
|
814
|
+
} catch {
|
|
815
|
+
/* not in this directory */
|
|
816
|
+
}
|
|
817
|
+
}
|
|
818
|
+
return false;
|
|
819
|
+
}
|
|
820
|
+
|
|
821
|
+
function clipboardBackend(): ClipboardBackend | undefined {
|
|
822
|
+
if (process.platform === "darwin") {
|
|
823
|
+
return { copy: ["pbcopy", []], clear: ["pbcopy", []], read: ["pbpaste", []] };
|
|
824
|
+
}
|
|
825
|
+
if (process.env.WAYLAND_DISPLAY && commandExists("wl-copy") && commandExists("wl-paste")) {
|
|
826
|
+
return {
|
|
827
|
+
copy: ["wl-copy", []],
|
|
828
|
+
clear: ["wl-copy", ["-c"]],
|
|
829
|
+
read: ["wl-paste", ["--no-newline"]],
|
|
830
|
+
};
|
|
831
|
+
}
|
|
832
|
+
if (process.env.DISPLAY && commandExists("xclip")) {
|
|
833
|
+
return {
|
|
834
|
+
copy: ["xclip", ["-selection", "clipboard"]],
|
|
835
|
+
clear: ["xclip", ["-selection", "clipboard", "/dev/null"]],
|
|
836
|
+
read: ["xclip", ["-selection", "clipboard", "-o"]],
|
|
837
|
+
};
|
|
838
|
+
}
|
|
839
|
+
return undefined;
|
|
840
|
+
}
|
|
841
|
+
|
|
842
|
+
let clipboardValue: string | undefined;
|
|
843
|
+
/** Set while a copy is in flight, so exit cleanup can still clear it. */
|
|
844
|
+
let clipboardPending: string | undefined;
|
|
845
|
+
let clipboardTimer: NodeJS.Timeout | undefined;
|
|
846
|
+
/**
|
|
847
|
+
* Bumped whenever the clipboard is dropped for good (a lock or an exit), not by
|
|
848
|
+
* the auto-clear timer. A copy that was in flight across a drop puts its value
|
|
849
|
+
* back afterwards, so it compares this and clears again instead of only
|
|
850
|
+
* arming its own timer.
|
|
851
|
+
*/
|
|
852
|
+
let clipboardDrops = 0;
|
|
853
|
+
|
|
854
|
+
function clipboardMatches(current: string, value: string): boolean {
|
|
855
|
+
return current === value || current.replace(/[\r\n]+$/, "") === value.replace(/[\r\n]+$/, "");
|
|
856
|
+
}
|
|
857
|
+
|
|
858
|
+
async function copyToClipboard(value: string): Promise<void> {
|
|
859
|
+
const backend = clipboardBackend();
|
|
860
|
+
if (!backend) throw new Error("No clipboard available (need Wayland, X11, or macOS).");
|
|
861
|
+
const drops = clipboardDrops;
|
|
862
|
+
const [cmd, args] = backend.copy;
|
|
863
|
+
const { promise, resolve, reject } = Promise.withResolvers<void>();
|
|
864
|
+
// wl-copy/xclip stay alive to own the selection; a quick clean exit also means success.
|
|
865
|
+
const child = spawn(cmd, args, { stdio: ["pipe", "ignore", "pipe"], detached: true, env: childEnv() });
|
|
866
|
+
let settled = false;
|
|
867
|
+
let stderr = "";
|
|
868
|
+
const finish = (err?: Error) => {
|
|
869
|
+
if (settled) return;
|
|
870
|
+
settled = true;
|
|
871
|
+
if (err) reject(err);
|
|
872
|
+
else {
|
|
873
|
+
child.unref();
|
|
874
|
+
resolve();
|
|
875
|
+
}
|
|
876
|
+
};
|
|
877
|
+
child.stderr?.on("data", (d) => (stderr += d));
|
|
878
|
+
child.on("error", finish);
|
|
879
|
+
child.on("exit", (code) => {
|
|
880
|
+
if (code === 0) finish();
|
|
881
|
+
else finish(new Error(`${cmd} exited with ${code}${stderr ? `: ${tail(stderr, 120)}` : ""}`));
|
|
882
|
+
});
|
|
883
|
+
child.stdin?.on("error", (e) => finish(e instanceof Error ? e : new Error(String(e))));
|
|
884
|
+
child.stdin?.write(value, (err) => {
|
|
885
|
+
if (err) {
|
|
886
|
+
finish(err);
|
|
887
|
+
return;
|
|
888
|
+
}
|
|
889
|
+
child.stdin?.end();
|
|
890
|
+
setTimeout(() => finish(), 500);
|
|
891
|
+
});
|
|
892
|
+
clipboardPending = value;
|
|
893
|
+
try {
|
|
894
|
+
await promise;
|
|
895
|
+
} catch (e) {
|
|
896
|
+
if (clipboardPending === value) clipboardPending = undefined;
|
|
897
|
+
throw e;
|
|
898
|
+
}
|
|
899
|
+
if (clipboardPending === value) clipboardPending = undefined;
|
|
900
|
+
clearTimeout(clipboardTimer);
|
|
901
|
+
clipboardValue = value;
|
|
902
|
+
clipboardTimer = undefined;
|
|
903
|
+
// A lock or an exit ran while this copy was in flight: the value is back in
|
|
904
|
+
// the clipboard, so it goes again, now and once more in case the copy
|
|
905
|
+
// command has not taken the selection yet.
|
|
906
|
+
if (drops !== clipboardDrops) {
|
|
907
|
+
await clearClipboardIfOwner();
|
|
908
|
+
clipboardValue = value;
|
|
909
|
+
clipboardTimer = setTimeout(() => void clearClipboardIfOwner(), 1000);
|
|
910
|
+
clipboardTimer.unref?.();
|
|
911
|
+
throw new Error("Bitwarden was locked while copying; the clipboard is being cleared.");
|
|
912
|
+
}
|
|
913
|
+
if (CONFIG.clipboardClearSeconds > 0) {
|
|
914
|
+
clipboardTimer = setTimeout(() => void clearClipboardIfOwner(), CONFIG.clipboardClearSeconds * 1000);
|
|
915
|
+
clipboardTimer.unref?.();
|
|
916
|
+
}
|
|
917
|
+
}
|
|
918
|
+
|
|
919
|
+
/** Clear only if the clipboard still holds our value (never wipe a newer user copy). */
|
|
920
|
+
async function clearClipboardIfOwner(): Promise<boolean> {
|
|
921
|
+
const value = clipboardValue ?? clipboardPending;
|
|
922
|
+
const backend = clipboardBackend();
|
|
923
|
+
clipboardValue = undefined;
|
|
924
|
+
clipboardPending = undefined;
|
|
925
|
+
if (clipboardTimer) {
|
|
926
|
+
clearTimeout(clipboardTimer);
|
|
927
|
+
clipboardTimer = undefined;
|
|
928
|
+
}
|
|
929
|
+
if (!value || !backend) return false;
|
|
930
|
+
try {
|
|
931
|
+
const r = await exec(backend.read[0], backend.read[1], { timeout: 3000 });
|
|
932
|
+
if (r.code === 0 && r.stdout.length > 0 && !clipboardMatches(r.stdout, value)) return false;
|
|
933
|
+
} catch {
|
|
934
|
+
/* unreadable clipboard: clear anyway (fail-safe) */
|
|
935
|
+
}
|
|
936
|
+
try {
|
|
937
|
+
await exec(backend.clear[0], backend.clear[1], { timeout: 5000, input: "" });
|
|
938
|
+
} catch {
|
|
939
|
+
/* best-effort */
|
|
940
|
+
}
|
|
941
|
+
return true;
|
|
942
|
+
}
|
|
943
|
+
|
|
944
|
+
/** Exit-path cleanup: timers never run after the process exits. */
|
|
945
|
+
function clearClipboardSync(): void {
|
|
946
|
+
clipboardDrops++;
|
|
947
|
+
const value = clipboardValue ?? clipboardPending;
|
|
948
|
+
const backend = clipboardBackend();
|
|
949
|
+
clipboardValue = undefined;
|
|
950
|
+
clipboardPending = undefined;
|
|
951
|
+
if (!value || !backend) return;
|
|
952
|
+
try {
|
|
953
|
+
const r = spawnSync(backend.read[0], backend.read[1], { encoding: "utf8", timeout: 1000, env: childEnv() });
|
|
954
|
+
if (r.status === 0 && typeof r.stdout === "string" && r.stdout.length > 0 && !clipboardMatches(r.stdout, value)) return;
|
|
955
|
+
} catch {
|
|
956
|
+
/* clear anyway */
|
|
957
|
+
}
|
|
958
|
+
try {
|
|
959
|
+
spawnSync(backend.clear[0], backend.clear[1], { input: "", timeout: 2000, env: childEnv() });
|
|
960
|
+
} catch {
|
|
961
|
+
/* best-effort */
|
|
962
|
+
}
|
|
963
|
+
}
|
|
964
|
+
|
|
965
|
+
/** The exact file shape pi's bash tool writes for truncated output. */
|
|
966
|
+
const ARTIFACT_RE = /^pi-bash-[0-9a-f]{16}\.log$/;
|
|
967
|
+
|
|
968
|
+
/** A path is only an output artifact if it is one of bash's files in the OS temp dir. */
|
|
969
|
+
function artifactPath(details: unknown): string | undefined {
|
|
970
|
+
if (!details || typeof details !== "object" || !("fullOutputPath" in details)) return undefined;
|
|
971
|
+
const file = (details as { fullOutputPath?: unknown }).fullOutputPath;
|
|
972
|
+
if (typeof file !== "string" || !file) return undefined;
|
|
973
|
+
const resolved = path.resolve(file);
|
|
974
|
+
if (path.dirname(resolved) !== path.resolve(tmpdir())) return undefined;
|
|
975
|
+
if (!ARTIFACT_RE.test(path.basename(resolved))) return undefined;
|
|
976
|
+
return resolved;
|
|
977
|
+
}
|
|
978
|
+
|
|
979
|
+
/**
|
|
980
|
+
* Bash truncation can leave the full output in a file; scrub that copy too.
|
|
981
|
+
* Only bash's own temp artifact is touched: a tool cannot use `fullOutputPath`
|
|
982
|
+
* to make the extension delete or rewrite an arbitrary file.
|
|
983
|
+
*/
|
|
984
|
+
async function scrubArtifact(toolName: string, details: unknown): Promise<void> {
|
|
985
|
+
if (toolName !== "bash") return;
|
|
986
|
+
const file = artifactPath(details);
|
|
987
|
+
if (!file) return;
|
|
988
|
+
let handle: Awaited<ReturnType<typeof fs.open>> | undefined;
|
|
989
|
+
try {
|
|
990
|
+
// O_NOFOLLOW: never read or rewrite through a symlink placed in the temp dir.
|
|
991
|
+
handle = await fs.open(file, fsConstants.O_RDWR | fsConstants.O_NOFOLLOW);
|
|
992
|
+
const stat = await handle.stat();
|
|
993
|
+
if (!stat.isFile()) return;
|
|
994
|
+
if (stat.size > OUTPUT_CAP) {
|
|
995
|
+
await fs.rm(file, { force: true });
|
|
996
|
+
return;
|
|
997
|
+
}
|
|
998
|
+
const raw = await handle.readFile({ encoding: "utf-8" });
|
|
999
|
+
const { text, changed } = scrubText(raw, scrubValues.values());
|
|
1000
|
+
if (changed) {
|
|
1001
|
+
await handle.truncate(0);
|
|
1002
|
+
await handle.write(text, 0, "utf-8");
|
|
1003
|
+
}
|
|
1004
|
+
} catch {
|
|
1005
|
+
/* artifact already gone, unreadable, or not a regular file */
|
|
1006
|
+
} finally {
|
|
1007
|
+
if (handle) await handle.close().catch(() => {});
|
|
1008
|
+
}
|
|
1009
|
+
}
|
|
1010
|
+
|
|
1011
|
+
// ---------------------------------------------------------------------------
|
|
1012
|
+
// Extension
|
|
1013
|
+
// ---------------------------------------------------------------------------
|
|
1014
|
+
const itemField = {
|
|
1015
|
+
item: Type.String({ description: "Item name or id (see bw_list)" }),
|
|
1016
|
+
field: Type.Optional(
|
|
1017
|
+
Type.String({
|
|
1018
|
+
description:
|
|
1019
|
+
"password | totp (seed) | code (rotating TOTP code) | notes | field:<customFieldName> (default: password)",
|
|
1020
|
+
}),
|
|
1021
|
+
),
|
|
1022
|
+
};
|
|
1023
|
+
const bwListParams = Type.Object({
|
|
1024
|
+
search: Type.Optional(Type.String({ description: "Substring filter on name, username, or URI" })),
|
|
1025
|
+
offset: Type.Optional(Type.Number({ description: "Rows to skip (default 0)" })),
|
|
1026
|
+
limit: Type.Optional(Type.Number({ description: "Rows to return (default 60, max 200)" })),
|
|
1027
|
+
});
|
|
1028
|
+
const bwInjectParams = Type.Object({
|
|
1029
|
+
...itemField,
|
|
1030
|
+
env: Type.String({ description: "Env var name for bash commands, e.g. MYAPP_TOKEN" }),
|
|
1031
|
+
});
|
|
1032
|
+
const bwRunParams = Type.Object({
|
|
1033
|
+
...itemField,
|
|
1034
|
+
env: Type.Optional(Type.String({ description: "Env var name available to the command (default VAULT_SECRET)" })),
|
|
1035
|
+
command: Type.String({ description: "Shell command; use $VAULT_SECRET for the value" }),
|
|
1036
|
+
cwd: Type.Optional(Type.String({ description: "Working directory (default: current session cwd)" })),
|
|
1037
|
+
timeout: Type.Optional(Type.Number({ description: "Seconds (default 120, max 600)" })),
|
|
1038
|
+
});
|
|
1039
|
+
const bwSecretParams = Type.Object(itemField);
|
|
1040
|
+
const bwRevealParams = Type.Object({
|
|
1041
|
+
...itemField,
|
|
1042
|
+
reason: Type.String({ description: "Why the plain-text value is needed (shown to the user)" }),
|
|
1043
|
+
});
|
|
1044
|
+
|
|
1045
|
+
/**
|
|
1046
|
+
* Register the Bitwarden tools for one binding. `st` is that binding's own
|
|
1047
|
+
* state (see BwState), so nothing here can reach another session's unlock.
|
|
1048
|
+
*/
|
|
1049
|
+
export function registerBitwarden(pi: ExtensionAPI, st: BwState, ompHost: boolean): void {
|
|
1050
|
+
// pi honors createBashTool's spawnHook. OMP already has its own bash tool and
|
|
1051
|
+
// discards that env, so registering another bash would only shadow it.
|
|
1052
|
+
if (!ompHost) {
|
|
1053
|
+
const bashTool = createBashTool(process.cwd(), {
|
|
1054
|
+
spawnHook: ({ command, cwd, env }) => {
|
|
1055
|
+
// A BW_SESSION exported in the user's shell must not reach bash.
|
|
1056
|
+
for (const name of Object.keys(env)) if (name.startsWith("BW_")) delete env[name];
|
|
1057
|
+
for (const [name, rec] of st.injected) env[name] = rec.value;
|
|
1058
|
+
return { command, cwd, env };
|
|
1059
|
+
},
|
|
1060
|
+
});
|
|
1061
|
+
pi.registerTool({ ...bashTool } as any);
|
|
1062
|
+
}
|
|
1063
|
+
|
|
1064
|
+
// Bash activity counts toward the idle auto-lock.
|
|
1065
|
+
pi.on("tool_call", async (event) => {
|
|
1066
|
+
if (event.toolName === "bash") touchActivity(st);
|
|
1067
|
+
return undefined;
|
|
1068
|
+
});
|
|
1069
|
+
|
|
1070
|
+
// --- bw_list: vault map without secrets ---
|
|
1071
|
+
const delivery = ompHost ? "bw_run" : "bw_inject";
|
|
1072
|
+
const bwList: ToolDefinition<typeof bwListParams> = {
|
|
1073
|
+
name: "bw_list",
|
|
1074
|
+
label: "Bitwarden list",
|
|
1075
|
+
description:
|
|
1076
|
+
"List Bitwarden vault items: name, username, URI, id. NEVER returns passwords, TOTP, notes or field values. " +
|
|
1077
|
+
"Search matches item name, username, or URI. Paginated with offset/limit. " +
|
|
1078
|
+
`First use in a session prompts for the Bitwarden master password (unlock). Use it to find item names/ids before ${delivery} or vault_import. ` +
|
|
1079
|
+
"This reads Bitwarden live; vault_list is the separate local ai-vault store.",
|
|
1080
|
+
promptSnippet: "List Bitwarden items (no secrets)",
|
|
1081
|
+
promptGuidelines: [
|
|
1082
|
+
`Use bw_list to find Bitwarden item names/ids, then ${delivery} to pass a credential to a command.`,
|
|
1083
|
+
],
|
|
1084
|
+
parameters: bwListParams,
|
|
1085
|
+
async execute(_id, params, signal, _onUpdate, ctx) {
|
|
1086
|
+
const session = await ensureUnlocked(st, ctx, signal);
|
|
1087
|
+
const offsetInput = params.offset;
|
|
1088
|
+
const limitInput = params.limit;
|
|
1089
|
+
const offset =
|
|
1090
|
+
typeof offsetInput === "number" && Number.isFinite(offsetInput)
|
|
1091
|
+
? Math.max(0, Math.trunc(offsetInput))
|
|
1092
|
+
: 0;
|
|
1093
|
+
const limit =
|
|
1094
|
+
typeof limitInput === "number" && Number.isFinite(limitInput)
|
|
1095
|
+
? Math.min(200, Math.max(1, Math.trunc(limitInput)))
|
|
1096
|
+
: 60;
|
|
1097
|
+
let items = [...(await listItems(st, session, signal))].sort((a, b) => a.name.localeCompare(b.name));
|
|
1098
|
+
const query = (params.search ?? "").trim().toLowerCase();
|
|
1099
|
+
if (query) {
|
|
1100
|
+
items = items.filter((i) => `${i.name}\n${i.username}\n${i.uri}`.toLowerCase().includes(query));
|
|
1101
|
+
}
|
|
1102
|
+
const page = items.slice(offset, offset + limit);
|
|
1103
|
+
const lines = page.map(
|
|
1104
|
+
(i) => `${i.name || "?"} | user: ${i.username || "-"} | uri: ${i.uri || "-"} | id: ${i.id}`,
|
|
1105
|
+
);
|
|
1106
|
+
const range = page.length > 0 ? `${offset + 1}-${offset + page.length} of ` : "0 of ";
|
|
1107
|
+
const more =
|
|
1108
|
+
offset + page.length < items.length
|
|
1109
|
+
? `\n... ${items.length - offset - page.length} more (use offset=${offset + page.length})`
|
|
1110
|
+
: "";
|
|
1111
|
+
const text =
|
|
1112
|
+
`${range}${items.length} item(s)${query ? ` matching "${params.search}"` : ""}:\n` +
|
|
1113
|
+
lines.join("\n") +
|
|
1114
|
+
more;
|
|
1115
|
+
return { content: [{ type: "text", text }], details: { count: items.length, offset, limit } };
|
|
1116
|
+
},
|
|
1117
|
+
};
|
|
1118
|
+
pi.registerTool(withTier(bwList, "read"));
|
|
1119
|
+
|
|
1120
|
+
// --- bw_inject: secret -> bash env, model never sees the value ---
|
|
1121
|
+
// OMP drops the bash spawnHook env, so there the tool is not offered at all.
|
|
1122
|
+
if (!ompHost) {
|
|
1123
|
+
const bwInject: ToolDefinition<typeof bwInjectParams> = {
|
|
1124
|
+
name: "bw_inject",
|
|
1125
|
+
label: "Bitwarden inject",
|
|
1126
|
+
description:
|
|
1127
|
+
"Fetch a Bitwarden secret and inject it as an environment variable into bash tool commands. " +
|
|
1128
|
+
"The VALUE IS NEVER SHOWN to you nor stored in the conversation; reference it as $VAR in later bash commands. " +
|
|
1129
|
+
"Requires user confirmation per injection. Use when a command needs a credential (API token, docker login, git push, ...). " +
|
|
1130
|
+
"Browser filling: agent-browser fill @ref \"$VAR\" types it into a form without the value entering the conversation. " +
|
|
1131
|
+
"Prefer this over bw_reveal. field: 'password' (default) | 'totp' (seed) | 'code' (rotating TOTP code) | 'notes' | 'field:<customFieldName>'.",
|
|
1132
|
+
promptSnippet: "Pass a Bitwarden secret to bash via env var (value hidden from model)",
|
|
1133
|
+
promptGuidelines: [
|
|
1134
|
+
"Use bw_inject when a bash command needs a Bitwarden credential; never ask the user to paste secrets into chat.",
|
|
1135
|
+
"To fill a browser login with agent-browser: bw_inject the secret, then run agent-browser fill @ref \"$VAR\" — the value stays out of the conversation.",
|
|
1136
|
+
"For repeated browser logins, import once with: printenv $VAR | agent-browser auth save <name> --username <user> --password-stdin — afterwards agent-browser auth login <name> needs no secret.",
|
|
1137
|
+
],
|
|
1138
|
+
parameters: bwInjectParams,
|
|
1139
|
+
async execute(_id, params, signal, _onUpdate, ctx) {
|
|
1140
|
+
const field = (params.field ?? "password").trim();
|
|
1141
|
+
if (!FIELD_RE.test(field)) {
|
|
1142
|
+
throw new Error(`Invalid field "${field}". Use password | totp | code | notes | field:<name>.`);
|
|
1143
|
+
}
|
|
1144
|
+
const envName = normalizeEnvName(params.env);
|
|
1145
|
+
if (!st.injected.has(envName) && st.injected.size >= CONFIG.maxInjectedEnv) {
|
|
1146
|
+
throw new Error(`Too many injected vars (max ${CONFIG.maxInjectedEnv}). Run /bw clear to drop some.`);
|
|
1147
|
+
}
|
|
1148
|
+
|
|
1149
|
+
const replaced = st.injected.get(envName);
|
|
1150
|
+
const approved = await approveItem(
|
|
1151
|
+
st,
|
|
1152
|
+
ctx,
|
|
1153
|
+
"inject",
|
|
1154
|
+
"Bitwarden: inject secret into AI bash environment",
|
|
1155
|
+
params.item,
|
|
1156
|
+
field,
|
|
1157
|
+
`Env: $${envName}` +
|
|
1158
|
+
(replaced ? `\nReplaces: "${replaced.item}" (${replaced.field})` : "") +
|
|
1159
|
+
`\n\nCommands run by the AI in this session will see $${envName}.` +
|
|
1160
|
+
`\nThe value itself is never shown to the AI nor stored in the chat.` +
|
|
1161
|
+
`\nDropped on ` +
|
|
1162
|
+
(autoLockMs ? `idle lock (${Math.round(autoLockMs / 60000)} min) or /bw lock` : `/bw lock or session end`) +
|
|
1163
|
+
`.`,
|
|
1164
|
+
signal,
|
|
1165
|
+
);
|
|
1166
|
+
if (!approved) throw new Error("User declined the injection.");
|
|
1167
|
+
|
|
1168
|
+
const { value, itemId, itemName } = await secretOf(approved.session, approved.item, field, signal);
|
|
1169
|
+
st.injected.set(envName, { value, item: itemName, field, at: Date.now() });
|
|
1170
|
+
rememberScrubValue(envName, value);
|
|
1171
|
+
await audit("inject", `allow env=${envName} item="${itemName}" (${itemId}) field=${field}`, st.sessionLabel);
|
|
1172
|
+
safeStatus(ctx, `🔓 bw: ${st.injected.size} env var(s)`);
|
|
1173
|
+
const weak =
|
|
1174
|
+
value.length < 6
|
|
1175
|
+
? " WARNING: this value is shorter than 6 characters, so tool output cannot be reliably scrubbed."
|
|
1176
|
+
: "";
|
|
1177
|
+
|
|
1178
|
+
return {
|
|
1179
|
+
content: [
|
|
1180
|
+
{
|
|
1181
|
+
type: "text",
|
|
1182
|
+
text:
|
|
1183
|
+
`Injected $${envName} (item "${itemName}", field ${field}) into the bash environment. ` +
|
|
1184
|
+
`Use $${envName} in bash commands. Do NOT try to print, echo, or exfiltrate it — output is scrubbed.${weak} ` +
|
|
1185
|
+
`Active injected vars: ${injectedListText(st)}`,
|
|
1186
|
+
},
|
|
1187
|
+
],
|
|
1188
|
+
details: { env: envName, item: itemName, field },
|
|
1189
|
+
};
|
|
1190
|
+
},
|
|
1191
|
+
};
|
|
1192
|
+
pi.registerTool(bwInject);
|
|
1193
|
+
}
|
|
1194
|
+
|
|
1195
|
+
// --- bw_run: one command with the secret in its env (works on OMP) ---
|
|
1196
|
+
const bwRun: ToolDefinition<typeof bwRunParams> = {
|
|
1197
|
+
name: "bw_run",
|
|
1198
|
+
label: "Bitwarden run",
|
|
1199
|
+
description:
|
|
1200
|
+
"Run a shell command with a Bitwarden secret in its environment as $VAULT_SECRET (or a chosen env name). " +
|
|
1201
|
+
"The value never enters the conversation; stdout/stderr are scrubbed. Requires confirmation per call. " +
|
|
1202
|
+
"Use this on OMP (where bw_inject is unavailable) or when the secret should live for exactly one command. " +
|
|
1203
|
+
"field: 'password' (default) | 'totp' (seed) | 'code' (rotating TOTP) | 'notes' | 'field:<customFieldName>'.",
|
|
1204
|
+
promptSnippet: "Run one command with a Bitwarden secret in its env (value hidden)",
|
|
1205
|
+
promptGuidelines: [
|
|
1206
|
+
"Use bw_run for a command that needs a Bitwarden credential; reference it as $VAULT_SECRET.",
|
|
1207
|
+
"Never print or echo the value; prefer piping it into the consumer (e.g. --password-stdin).",
|
|
1208
|
+
],
|
|
1209
|
+
parameters: bwRunParams,
|
|
1210
|
+
async execute(_id, params, signal, _onUpdate, ctx) {
|
|
1211
|
+
const field = (params.field ?? "password").trim();
|
|
1212
|
+
if (!FIELD_RE.test(field)) {
|
|
1213
|
+
throw new Error(`Invalid field "${field}". Use password | totp | code | notes | field:<name>.`);
|
|
1214
|
+
}
|
|
1215
|
+
if (!params.command.trim()) throw new Error("Command is empty.");
|
|
1216
|
+
const envName = normalizeEnvName(params.env ?? "VAULT_SECRET");
|
|
1217
|
+
const timeoutInput = params.timeout;
|
|
1218
|
+
const seconds =
|
|
1219
|
+
typeof timeoutInput === "number" && Number.isFinite(timeoutInput)
|
|
1220
|
+
? Math.min(600, Math.max(1, Math.trunc(timeoutInput)))
|
|
1221
|
+
: 120;
|
|
1222
|
+
const cwd = params.cwd?.trim() || ctx.cwd || process.cwd();
|
|
1223
|
+
const approved = await approveItem(
|
|
1224
|
+
st,
|
|
1225
|
+
ctx,
|
|
1226
|
+
"run",
|
|
1227
|
+
"Bitwarden: run command with secret",
|
|
1228
|
+
params.item,
|
|
1229
|
+
field,
|
|
1230
|
+
`Env: $${envName}\nCwd: ${cwd}\nCommand:\n${params.command}\n\n` +
|
|
1231
|
+
`The command runs once with $${envName} set. The value never enters the chat; output is scrubbed.`,
|
|
1232
|
+
signal,
|
|
1233
|
+
);
|
|
1234
|
+
if (!approved) throw new Error("User declined the command.");
|
|
1235
|
+
const { value, itemName } = await secretOf(approved.session, approved.item, field, signal);
|
|
1236
|
+
rememberScrubValue(envName, value);
|
|
1237
|
+
const r = await exec("bash", ["-c", params.command], {
|
|
1238
|
+
env: { [envName]: value },
|
|
1239
|
+
cwd,
|
|
1240
|
+
timeout: seconds * 1000,
|
|
1241
|
+
signal,
|
|
1242
|
+
group: true,
|
|
1243
|
+
});
|
|
1244
|
+
await audit("run", `allow env=${envName} item="${itemName}" field=${field} exit=${r.code}`, st.sessionLabel);
|
|
1245
|
+
const raw = [r.stdout, r.stderr].filter((s) => s.length > 0).join("\n");
|
|
1246
|
+
const scrubbed = scrubText(raw, scrubValues.values()).text;
|
|
1247
|
+
const output =
|
|
1248
|
+
scrubbed.length > 32_000
|
|
1249
|
+
? `... (truncated to the last 32000 chars)\n${scrubbed.slice(-32_000)}`
|
|
1250
|
+
: scrubbed;
|
|
1251
|
+
const dropped = r.truncated ? "(command output past 8 MiB was dropped)\n" : "";
|
|
1252
|
+
return {
|
|
1253
|
+
content: [
|
|
1254
|
+
{
|
|
1255
|
+
type: "text",
|
|
1256
|
+
text:
|
|
1257
|
+
`Ran with $${envName} (item "${itemName}", field ${field}); exit ${r.code}.\n${dropped}` +
|
|
1258
|
+
(output ? `--- output ---\n${output}` : "(no output)"),
|
|
1259
|
+
},
|
|
1260
|
+
],
|
|
1261
|
+
details: { item: itemName, field, env: envName, exit: r.code, truncated: r.truncated },
|
|
1262
|
+
};
|
|
1263
|
+
},
|
|
1264
|
+
};
|
|
1265
|
+
pi.registerTool(withTier(bwRun, "exec"));
|
|
1266
|
+
|
|
1267
|
+
// --- bw_clipboard: secret -> clipboard, auto-cleared ---
|
|
1268
|
+
const bwClipboard: ToolDefinition<typeof bwSecretParams> = {
|
|
1269
|
+
name: "bw_clipboard",
|
|
1270
|
+
label: "Bitwarden clipboard",
|
|
1271
|
+
description:
|
|
1272
|
+
"Copy a Bitwarden secret to the system clipboard; " +
|
|
1273
|
+
CLIPBOARD_CLEAR_TEXT +
|
|
1274
|
+
". The value never enters the conversation. Requires user confirmation. " +
|
|
1275
|
+
"field: 'password' (default) | 'totp' (seed) | 'code' (rotating TOTP code) | 'notes' | 'field:<customFieldName>'.",
|
|
1276
|
+
promptSnippet: "Copy a Bitwarden secret to clipboard (auto-clear)",
|
|
1277
|
+
parameters: bwSecretParams,
|
|
1278
|
+
async execute(_id, params, signal, _onUpdate, ctx) {
|
|
1279
|
+
const field = (params.field ?? "password").trim();
|
|
1280
|
+
if (!FIELD_RE.test(field)) throw new Error(`Invalid field "${field}".`);
|
|
1281
|
+
const approved = await approveItem(
|
|
1282
|
+
st,
|
|
1283
|
+
ctx,
|
|
1284
|
+
"clipboard",
|
|
1285
|
+
"Bitwarden: copy secret to clipboard",
|
|
1286
|
+
params.item,
|
|
1287
|
+
field,
|
|
1288
|
+
`The value is copied to the system clipboard; ${CLIPBOARD_CLEAR_TEXT}. It never enters the chat.`,
|
|
1289
|
+
signal,
|
|
1290
|
+
);
|
|
1291
|
+
if (!approved) throw new Error("User declined.");
|
|
1292
|
+
const { value, itemName } = await secretOf(approved.session, approved.item, field, signal);
|
|
1293
|
+
// The value is now in a place bash can read back (pbpaste/xclip -o),
|
|
1294
|
+
// so tool output carrying it must be scrubbed like an injected var.
|
|
1295
|
+
rememberScrubValue("CLIPBOARD", value);
|
|
1296
|
+
await copyToClipboard(value);
|
|
1297
|
+
await audit("clipboard", `allow item="${itemName}" field=${field}`, st.sessionLabel);
|
|
1298
|
+
const clears =
|
|
1299
|
+
CONFIG.clipboardClearSeconds > 0 ? `Clears in ${CONFIG.clipboardClearSeconds}s.` : "Auto-clear disabled.";
|
|
1300
|
+
return {
|
|
1301
|
+
content: [{ type: "text", text: `Copied "${itemName}" (${field}) to clipboard. ${clears}` }],
|
|
1302
|
+
details: { item: itemName, field },
|
|
1303
|
+
};
|
|
1304
|
+
},
|
|
1305
|
+
};
|
|
1306
|
+
pi.registerTool(withTier(bwClipboard, "write"));
|
|
1307
|
+
|
|
1308
|
+
// --- bw_reveal: plain text to the model, per-call confirmation ---
|
|
1309
|
+
const bwReveal: ToolDefinition<typeof bwRevealParams> = {
|
|
1310
|
+
name: "bw_reveal",
|
|
1311
|
+
label: "Bitwarden reveal (danger)",
|
|
1312
|
+
description:
|
|
1313
|
+
"Return a Bitwarden secret in PLAIN TEXT. DANGEROUS: the value will be sent to the LLM provider and stored in the session file. " +
|
|
1314
|
+
"Requires explicit user confirmation every single call, and is disabled unless allowReveal is set in the config. " +
|
|
1315
|
+
"Only use when bw_inject / bw_clipboard genuinely cannot do the job. " +
|
|
1316
|
+
"field: 'password' (default) | 'totp' (seed) | 'code' (rotating TOTP code) | 'notes' | 'field:<customFieldName>'.",
|
|
1317
|
+
promptSnippet: "Reveal a Bitwarden secret in plain text (per-call approval)",
|
|
1318
|
+
promptGuidelines: [
|
|
1319
|
+
"Use bw_reveal only as a last resort; prefer bw_inject (bash env) or bw_clipboard which keep the value out of the conversation.",
|
|
1320
|
+
],
|
|
1321
|
+
parameters: bwRevealParams,
|
|
1322
|
+
async execute(_id, params, signal, _onUpdate, ctx) {
|
|
1323
|
+
if (!CONFIG.allowReveal) {
|
|
1324
|
+
throw new Error("bw_reveal is disabled in this installation (set allowReveal in ~/.bw/pi-extension/config.json to enable it).");
|
|
1325
|
+
}
|
|
1326
|
+
const field = (params.field ?? "password").trim();
|
|
1327
|
+
if (!FIELD_RE.test(field)) throw new Error(`Invalid field "${field}".`);
|
|
1328
|
+
const provider = ctx?.model?.provider ?? "the LLM provider";
|
|
1329
|
+
const approved = await approveItem(
|
|
1330
|
+
st,
|
|
1331
|
+
ctx,
|
|
1332
|
+
"reveal",
|
|
1333
|
+
"⚠️ Bitwarden: reveal secret IN PLAIN TEXT",
|
|
1334
|
+
params.item,
|
|
1335
|
+
field,
|
|
1336
|
+
`Reason: ${params.reason}\n\n` +
|
|
1337
|
+
`The value will be shown to the AI, sent to ${provider}, and stored in the session file.`,
|
|
1338
|
+
signal,
|
|
1339
|
+
);
|
|
1340
|
+
if (!approved) throw new Error("User declined the reveal.");
|
|
1341
|
+
const { value, itemName } = await secretOf(approved.session, approved.item, field, signal);
|
|
1342
|
+
await audit("reveal", `allow item="${itemName}" field=${field}`, st.sessionLabel);
|
|
1343
|
+
return {
|
|
1344
|
+
content: [{ type: "text", text: `${itemName} (${field}):\n<secret>${value}</secret>` }],
|
|
1345
|
+
details: { item: itemName, field },
|
|
1346
|
+
};
|
|
1347
|
+
},
|
|
1348
|
+
};
|
|
1349
|
+
pi.registerTool(bwReveal);
|
|
1350
|
+
|
|
1351
|
+
// --- Scrubber: active secrets never reach the model via tool results ---
|
|
1352
|
+
pi.on("tool_result", async (event) => {
|
|
1353
|
+
// bw_reveal and vault_get are intentional, user-approved plain-text
|
|
1354
|
+
// reveals; scrubbing them would corrupt the value the user asked for.
|
|
1355
|
+
if (event.toolName === "bw_reveal" || event.toolName === "vault_get") return undefined;
|
|
1356
|
+
if (scrubValues.size === 0) return undefined;
|
|
1357
|
+
let changed = false;
|
|
1358
|
+
const content = event.content.map((block: any) => {
|
|
1359
|
+
if (block?.type !== "text" || typeof block.text !== "string") return block;
|
|
1360
|
+
const result = scrubText(block.text, scrubValues.values());
|
|
1361
|
+
if (result.changed) changed = true;
|
|
1362
|
+
return result.changed ? { ...block, text: result.text } : block;
|
|
1363
|
+
});
|
|
1364
|
+
// Host tool details can carry expanded command/env data; scrub them too.
|
|
1365
|
+
const details = scrubDeep(event.details, scrubValues.values());
|
|
1366
|
+
const structured = scrubDeep(event.structuredContent, scrubValues.values());
|
|
1367
|
+
if (details.changed || structured.changed) changed = true;
|
|
1368
|
+
await scrubArtifact(event.toolName, event.details);
|
|
1369
|
+
if (!changed) return undefined;
|
|
1370
|
+
const result: ToolResultEventResult = { content };
|
|
1371
|
+
if (details.changed) result.details = details.value;
|
|
1372
|
+
// The scrubbed tree is still JSON-shaped (strings, arrays, plain objects).
|
|
1373
|
+
if (structured.changed) result.structuredContent = structured.value as ToolResultEventResult["structuredContent"];
|
|
1374
|
+
return result;
|
|
1375
|
+
});
|
|
1376
|
+
|
|
1377
|
+
// --- /bw command ---
|
|
1378
|
+
pi.registerCommand("bw", {
|
|
1379
|
+
description: "Bitwarden: status | unlock | lock | clear [ENV]",
|
|
1380
|
+
handler: async (args: string, ctx) => {
|
|
1381
|
+
const parts = (args ?? "status").trim().split(/\s+/);
|
|
1382
|
+
const sub = (parts[0] || "status").toLowerCase();
|
|
1383
|
+
if (sub === "lock") {
|
|
1384
|
+
await lock(st, "user");
|
|
1385
|
+
safeStatus(ctx, undefined);
|
|
1386
|
+
ctx.ui.notify("Bitwarden: locked (session key + injected env dropped)", "info");
|
|
1387
|
+
return;
|
|
1388
|
+
}
|
|
1389
|
+
if (sub === "clear") {
|
|
1390
|
+
const target = parts[1];
|
|
1391
|
+
if (target) {
|
|
1392
|
+
let envName: string;
|
|
1393
|
+
try {
|
|
1394
|
+
envName = normalizeEnvName(target);
|
|
1395
|
+
} catch (e) {
|
|
1396
|
+
ctx.ui.notify(e instanceof Error ? e.message : String(e), "error");
|
|
1397
|
+
return;
|
|
1398
|
+
}
|
|
1399
|
+
const removed = st.injected.delete(envName);
|
|
1400
|
+
safeStatus(ctx, st.key ? `🔓 bw: ${st.injected.size} env var(s)` : undefined);
|
|
1401
|
+
ctx.ui.notify(
|
|
1402
|
+
removed ? `Bitwarden: dropped $${envName}` : `Bitwarden: $${envName} was not injected`,
|
|
1403
|
+
removed ? "info" : "warning",
|
|
1404
|
+
);
|
|
1405
|
+
return;
|
|
1406
|
+
}
|
|
1407
|
+
st.injected.clear();
|
|
1408
|
+
safeStatus(ctx, st.key ? `🔓 bw: 0 env var(s)` : undefined);
|
|
1409
|
+
ctx.ui.notify("Bitwarden: injected env vars cleared", "info");
|
|
1410
|
+
return;
|
|
1411
|
+
}
|
|
1412
|
+
if (sub === "unlock") {
|
|
1413
|
+
try {
|
|
1414
|
+
await ensureUnlocked(st, ctx);
|
|
1415
|
+
safeStatus(ctx, `🔓 bw: ${st.injected.size} env var(s)`);
|
|
1416
|
+
ctx.ui.notify("Bitwarden: unlocked", "info");
|
|
1417
|
+
} catch (e: unknown) {
|
|
1418
|
+
ctx.ui.notify(`Bitwarden unlock failed: ${e instanceof Error ? e.message : String(e)}`, "error");
|
|
1419
|
+
}
|
|
1420
|
+
return;
|
|
1421
|
+
}
|
|
1422
|
+
// status
|
|
1423
|
+
let cli = "unknown";
|
|
1424
|
+
try {
|
|
1425
|
+
const cliState = await bwStatus();
|
|
1426
|
+
cli = cliState?.status ?? "unknown";
|
|
1427
|
+
} catch (e: unknown) {
|
|
1428
|
+
cli = `error: ${tail(e instanceof Error ? e.message : String(e), 80)}`;
|
|
1429
|
+
}
|
|
1430
|
+
const ttl = st.key && autoLockMs ? Math.max(0, Math.round((autoLockMs - (Date.now() - st.lastActivity)) / 60000)) : 0;
|
|
1431
|
+
ctx.ui.notify(
|
|
1432
|
+
`bw CLI: ${cli}\n` +
|
|
1433
|
+
`extension: ${st.key ? (autoLockMs ? `unlocked (auto-lock in ${ttl} min)` : "unlocked (session-lifetime)") : "locked"}\n` +
|
|
1434
|
+
`injected env: ${injectedListText(st)}\n` +
|
|
1435
|
+
`bw_reveal: ${CONFIG.allowReveal ? "enabled" : "disabled"}`,
|
|
1436
|
+
"info",
|
|
1437
|
+
);
|
|
1438
|
+
},
|
|
1439
|
+
});
|
|
1440
|
+
|
|
1441
|
+
// --- Lifecycle ---
|
|
1442
|
+
// /new and /fork must not carry this unlock into the next transcript; a
|
|
1443
|
+
// /resume keeps it when keepOnResume is set. Which event reports that is
|
|
1444
|
+
// the host's business (see host.ts).
|
|
1445
|
+
onSessionLeave(pi, ompHost, async (reason, ctx) => {
|
|
1446
|
+
if (reason === "resume" && CONFIG.keepOnResume) return;
|
|
1447
|
+
await lock(st, `session-${reason}`);
|
|
1448
|
+
safeStatus(ctx, undefined);
|
|
1449
|
+
});
|
|
1450
|
+
}
|