@bolt-cli/cli 0.0.0-stage → 0.12.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/lib/api.js ADDED
@@ -0,0 +1,243 @@
1
+ "use strict";
2
+ // Minimal Bolt API client. Mirrors the web workspace prompt shape so the
3
+ // server-side agent loop (tools + arranged output) behaves identically.
4
+ const config = require("./config");
5
+ const cancel = require("./cancel");
6
+
7
+ // One transparent retry, capped: when OUR backend answers 429 it names a
8
+ // real wait (body.retryAfterSec, mirrored in the Retry-After header), so one
9
+ // advised wait-then-retry beats failing the run. Anything else — 402s,
10
+ // mid-stream errors, a second 429 — throws exactly as before.
11
+ const MAX_RETRY_WAIT_MS = 120_000;
12
+
13
+ /**
14
+ * Connection failures name the fix. The classic trap is a stale saved URL:
15
+ * ~/.bolt/config.json still points at localhost:3000 from local dev while
16
+ * the operator means production (or the reverse). fetch() throws a bare
17
+ * TypeError for refused connections, so every entry point translates it
18
+ * into the command that repairs it.
19
+ */
20
+ async function reachableFetch(url, init) {
21
+ let res;
22
+ try {
23
+ res = await fetch(url, init);
24
+ } catch (error) {
25
+ // Esc/Ctrl-C during a run aborts the fetch: surface it as a cancellation,
26
+ // never as a connectivity failure.
27
+ if ((error && error.name === "AbortError") || (init && init.signal && init.signal.aborted)) {
28
+ const cancelled = new Error("Cancelled — session saved. Press Esc during a run to stop it; close the terminal only to quit entirely.");
29
+ cancelled.code = "CANCELLED";
30
+ throw cancelled;
31
+ }
32
+ const message = (error && error.message) || "";
33
+ if (/fetch failed|ECONNREFUSED|ENOTFOUND|EHOSTUNREACH|ETIMEDOUT/i.test(message)) {
34
+ throw new Error(
35
+ `Cannot reach the Bolt backend at ${url}. ` +
36
+ `For production run: bolt login --url https://bolt.beerasafe.com (or set BOLT_URL). ` +
37
+ `For local dev, start the server first, then: bolt login --url http://localhost:3000.`,
38
+ );
39
+ }
40
+ throw error;
41
+ }
42
+ return res;
43
+ }
44
+
45
+ function authHeaders(token) {
46
+ return token ? { Authorization: `Bearer ${token}` } : {};
47
+ }
48
+
49
+ // Prompt blocks the web client would send for the same task: scope only when
50
+ // there is a network target, session/account context so "this session" and
51
+ // "my account" are answerable without tools, evidence, objective, plus
52
+ // optional project memory (BOLT.md context loaded by lib/memory.js - context
53
+ // only, explicit flags and prompt text win).
54
+ //
55
+ // Deliberately no hardcoded "Target type" or "Impact": the CLI used to send
56
+ // "Target type: web / Impact if confirmed: medium" on every run, including
57
+ // local tasks like "refactor src/auth.ts", and the model echoed the
58
+ // boilerplate back instead of answering the question. The server derives
59
+ // severity from the request text itself when it needs one.
60
+ function buildPrompt({ target, objective, evidence, history, memory, session, account }) {
61
+ const blocks = [];
62
+ if (target) {
63
+ blocks.push(`Target: ${target}`);
64
+ blocks.push(
65
+ "Rules of engagement:\n- The operator states this target is in scope under a signed authorization.\n- Testing is non-destructive. Do not run denial-of-service, data modification, persistence, or lockout techniques. Confirm impact with the least invasive proof available.",
66
+ );
67
+ } else {
68
+ blocks.push(
69
+ "Scope: a local working task in the operator's terminal (no network target for this request). Read and change only the project files at hand; shell commands stay inside the project directory.",
70
+ );
71
+ }
72
+ if (session || account) {
73
+ const who = [session ? `session ${session}` : "", account ? `signed in as ${account}` : ""].filter(Boolean).join(", ");
74
+ blocks.push(`Terminal context: ${who}. Use this when asked about the current session or account instead of claiming it is unavailable.`);
75
+ }
76
+ if (memory) blocks.push(`${memory}`);
77
+ if (history) blocks.push(`Session context:\n${history}`);
78
+ if (evidence) blocks.push(`Evidence:\n${evidence}`);
79
+ blocks.push(`Objective:\n${objective}`);
80
+ blocks.push(
81
+ "Answer what was asked, in the operator's language. Keep every claim tied to evidence you were given, and mark anything unverified as unverified.",
82
+ );
83
+ return blocks.join("\n\n");
84
+ }
85
+
86
+ async function getStats(url, token) {
87
+ const res = await reachableFetch(`${url}/api/dashboard/stats`, {
88
+ headers: { ...authHeaders(token) },
89
+ });
90
+ const data = await res.json().catch(() => ({}));
91
+ if (!res.ok) throw new Error(data.error || `Balance check failed (HTTP ${res.status}).`);
92
+ return data;
93
+ }
94
+
95
+ function topUpUrl(url) {
96
+ return `${String(url || "https://bolt.beerasafe.com").replace(/\/$/, "")}/pricing`;
97
+ }
98
+
99
+ // Streams SSE from /api/generate. Calls onToken(text) per chunk.
100
+ // `source` tags the run ("interactive" default, "watch" for Sentinel triage)
101
+ // so the server can meter background triage separately from live sessions.
102
+ // Resolves with { outputTokens, tokenCost, remainingTokens, truncated }.
103
+ // Throws errors with `.code`: INSUFFICIENT_TOKENS (402 or mid-stream
104
+ // exhaustion — stop and tell the operator to top up, never spin), CANCELLED
105
+ // (Esc/Ctrl-C abort), or the raw message for anything else.
106
+ async function streamGenerate({ url, token, prompt, mode, onToken, signal, source, _retried }) {
107
+ const fail = (message, code, extra) => {
108
+ const error = new Error(message);
109
+ if (code) error.code = code;
110
+ if (extra && typeof extra === "object") Object.assign(error, extra);
111
+ return error;
112
+ };
113
+ const retryAfterSecFrom = (res, data) => {
114
+ if (data && Number.isFinite(Number(data.retryAfterSec)) && Number(data.retryAfterSec) > 0) {
115
+ return Math.min(Number(data.retryAfterSec), MAX_RETRY_WAIT_MS / 1000);
116
+ }
117
+ const header = res && res.headers && typeof res.headers.get === "function" ? res.headers.get("retry-after") : null;
118
+ const n = Number(header);
119
+ if (Number.isFinite(n) && n > 0) return Math.min(n, MAX_RETRY_WAIT_MS / 1000);
120
+ return 0;
121
+ };
122
+ const throw402 = (data) => {
123
+ const balance = data && data.balance !== undefined ? data.balance : "0";
124
+ const need = data && data.inputTokens !== undefined ? ` (this run needs ~${data.inputTokens} input tokens)` : "";
125
+ throw fail(
126
+ `Out of tokens — balance ${balance}${need}. Top up at ${topUpUrl(url)} (or run bolt balance to confirm), then retry. Nothing was charged for this run.`,
127
+ "INSUFFICIENT_TOKENS",
128
+ { balance: data ? data.balance : undefined, inputTokens: data ? data.inputTokens : undefined },
129
+ );
130
+ };
131
+ let res;
132
+ try {
133
+ res = await reachableFetch(`${url}/api/generate`, {
134
+ method: "POST",
135
+ headers: { "Content-Type": "application/json", ...authHeaders(token) },
136
+ body: JSON.stringify(source ? { prompt, mode, source } : { prompt, mode }),
137
+ signal,
138
+ });
139
+ } catch (error) {
140
+ if (error && (error.code === "CANCELLED" || error.name === "AbortError" || (signal && signal.aborted))) {
141
+ throw fail("Cancelled — session saved. Press Esc during a run to stop it; close the terminal only to quit entirely.", "CANCELLED");
142
+ }
143
+ throw error;
144
+ }
145
+ if (!res.ok) {
146
+ const data = await res.json().catch(() => ({}));
147
+ if (res.status === 402) throw402(data);
148
+ // Single advised retry: our own 429 names its reset, so waiting it out
149
+ // once is strictly better than failing. `_retried` caps it at one:
150
+ // a second 429 throws with the advised wait attached instead of
151
+ // looping. Aborts during the wait cancel the run; anything without a
152
+ // named wait throws as before.
153
+ if (res.status === 429 && !_retried && !(signal && signal.aborted)) {
154
+ const waitSec = retryAfterSecFrom(res, data);
155
+ if (waitSec > 0) {
156
+ try {
157
+ if (process.stderr.isTTY) process.stderr.write(`Rate-limited — retrying in ~${Math.ceil(waitSec)}s…\n`);
158
+ await cancel.sleep(waitSec * 1000, { signal });
159
+ } catch (error) {
160
+ if (error && error.code === "CANCELLED") throw error;
161
+ }
162
+ if (!(signal && signal.aborted)) {
163
+ return streamGenerate({ url, token, prompt, mode, onToken, signal, source, _retried: true });
164
+ }
165
+ throw fail("Cancelled — session saved. Press Esc during a run to stop it; close the terminal only to quit entirely.", "CANCELLED");
166
+ }
167
+ }
168
+ if (res.status === 429 && data && data.retryAfterSec !== undefined) {
169
+ throw fail(`${data.error || `Run failed (HTTP ${res.status}).`} (retry in ~${data.retryAfterSec}s)`, undefined, { retryAfterSec: data.retryAfterSec });
170
+ }
171
+ throw new Error(`${data.error || `Run failed (HTTP ${res.status}).`}`);
172
+ }
173
+ if (!res.body) throw new Error("Empty response stream.");
174
+
175
+ const reader = res.body.getReader();
176
+ const decoder = new TextDecoder();
177
+ let buffer = "";
178
+ let full = "";
179
+ let doneInfo = null;
180
+
181
+ const handleEvent = (type, data) => {
182
+ if (type === "token" && data.text) {
183
+ full += data.text;
184
+ if (onToken) onToken(data.text);
185
+ } else if (type === "warn" && data.message) {
186
+ process.stderr.write(`\n[warn] ${data.message}\n`);
187
+ } else if (type === "error") {
188
+ // Mid-stream exhaustion carries no HTTP status, only this event: the
189
+ // response outgrew the remaining balance after the operator already saw
190
+ // partial output. Same treatment as a 402 — stop, say so, name the fix.
191
+ if (/balance/i.test(data.message || "")) {
192
+ throw fail(
193
+ `Out of tokens mid-run — kept what already streamed. Balance ${data.remainingTokens !== undefined ? data.remainingTokens : "exhausted"}. Top up at ${topUpUrl(url)}, then retry.`,
194
+ "INSUFFICIENT_TOKENS",
195
+ { remainingTokens: data.remainingTokens },
196
+ );
197
+ }
198
+ // Server-advised waits ride along untouched: when the backend names a
199
+ // retry time, the message carries it; otherwise the message is exactly
200
+ // what the server sent, as before.
201
+ const advised = data && Number.isFinite(Number(data.retryAfterSec)) && Number(data.retryAfterSec) > 0 ? Math.ceil(Number(data.retryAfterSec)) : 0;
202
+ throw fail(
203
+ `${data.message || "Run failed."}${data.code ? ` [${data.code}]` : ""}${advised ? ` (retry in ~${advised}s)` : ""}`,
204
+ data.code,
205
+ { remainingTokens: data.remainingTokens, ...(advised ? { retryAfterSec: advised } : {}) },
206
+ );
207
+ } else if (type === "done") {
208
+ doneInfo = data;
209
+ }
210
+ };
211
+
212
+ try {
213
+ while (true) {
214
+ const { value, done } = await reader.read();
215
+ if (done) break;
216
+ buffer += decoder.decode(value, { stream: true });
217
+ const events = buffer.split("\n\n");
218
+ buffer = events.pop() || "";
219
+ for (const event of events) {
220
+ const type = (event.match(/^event: (.+)$/m) || [])[1];
221
+ const raw = (event.match(/^data: (.+)$/m) || [])[1];
222
+ if (!raw) continue;
223
+ let data;
224
+ try {
225
+ data = JSON.parse(raw);
226
+ } catch {
227
+ continue; // ignore malformed keep-alive
228
+ }
229
+ // handleEvent throws on `error` events — that is a real run
230
+ // failure, so it propagates instead of being swallowed.
231
+ handleEvent(type, data);
232
+ }
233
+ }
234
+ } catch (error) {
235
+ if (error && (error.code === "CANCELLED" || error.name === "AbortError" || (signal && signal.aborted))) {
236
+ throw fail("Cancelled — session saved. Press Esc during a run to stop it; close the terminal only to quit entirely.", "CANCELLED");
237
+ }
238
+ throw error;
239
+ }
240
+ return { text: full, done: doneInfo };
241
+ }
242
+
243
+ module.exports = { buildPrompt, getStats, streamGenerate, topUpUrl, currentConfig: config.load };
@@ -0,0 +1,292 @@
1
+ "use strict";
2
+ // Secure tool bootstrap: maps common offensive/defensive/CTF tools to
3
+ // per-manager install commands, checks availability, and detects
4
+ // "command not found" failures so the agent loop can offer an install.
5
+ //
6
+ // Flow: bash fails with command-not-found (or the agent proposes a
7
+ // known-missing binary) -> executeCall returns
8
+ // {ok:false, needsInstall:{tool, manager, installCmd}} -> buildFollowup
9
+ // feeds it back -> the model proposes the install command -> checkApproval
10
+ // requires explicit operator approval -> asker prompts
11
+ // "Install <tool> via <manager>? [y/n]" -> never silent installs.
12
+ //
13
+ // Zero deps: node:child_process only. Installer strings are checked with
14
+ // the existing BLOCKED_COMMAND guard in lib/tools.js before use.
15
+
16
+ const TOOL_INSTALL_MAP = {
17
+ nmap: {
18
+ cmd: "nmap",
19
+ desc: "network scanner",
20
+ apt: "sudo apt install -y nmap",
21
+ dnf: "sudo dnf install -y nmap",
22
+ brew: "brew install nmap",
23
+ choco: "choco install nmap -y",
24
+ scoop: "scoop install nmap",
25
+ },
26
+ gobuster: {
27
+ cmd: "gobuster",
28
+ desc: "directory and DNS busting",
29
+ apt: "sudo apt install -y gobuster",
30
+ dnf: "sudo dnf install -y gobuster",
31
+ brew: "brew install gobuster",
32
+ choco: "choco install gobuster -y",
33
+ scoop: "scoop install gobuster",
34
+ },
35
+ ffuf: {
36
+ cmd: "ffuf",
37
+ desc: "fast web fuzzer",
38
+ apt: "sudo apt install -y ffuf",
39
+ dnf: "sudo dnf install -y ffuf",
40
+ brew: "brew install ffuf",
41
+ choco: "choco install ffuf -y",
42
+ scoop: "scoop install ffuf",
43
+ },
44
+ nikto: {
45
+ cmd: "nikto",
46
+ desc: "web server scanner",
47
+ apt: "sudo apt install -y nikto",
48
+ dnf: "sudo dnf install -y nikto",
49
+ brew: "brew install nikto",
50
+ choco: "choco install nikto -y",
51
+ scoop: "scoop install nikto",
52
+ },
53
+ sqlmap: {
54
+ cmd: "sqlmap",
55
+ desc: "SQL injection testing",
56
+ apt: "sudo apt install -y sqlmap",
57
+ dnf: "sudo dnf install -y sqlmap",
58
+ brew: "brew install sqlmap",
59
+ choco: "choco install sqlmap -y",
60
+ scoop: "scoop install sqlmap",
61
+ },
62
+ masscan: {
63
+ cmd: "masscan",
64
+ desc: "fast port scanner",
65
+ apt: "sudo apt install -y masscan",
66
+ dnf: "sudo dnf install -y masscan",
67
+ brew: "brew install masscan",
68
+ choco: "choco install masscan -y",
69
+ scoop: "scoop install masscan",
70
+ },
71
+ tshark: {
72
+ cmd: "tshark",
73
+ desc: "wireshark CLI packet capture",
74
+ apt: "sudo apt install -y tshark",
75
+ dnf: "sudo dnf install -y wireshark-cli",
76
+ brew: "brew install wireshark",
77
+ choco: "choco install wireshark -y",
78
+ scoop: "scoop install wireshark",
79
+ },
80
+ binutils: {
81
+ cmd: "objdump",
82
+ desc: "binary utils (strings, objdump, readelf)",
83
+ aliases: ["strings", "readelf"],
84
+ apt: "sudo apt install -y binutils",
85
+ dnf: "sudo dnf install -y binutils",
86
+ brew: "brew install binutils",
87
+ choco: "choco install mingw -y",
88
+ scoop: "scoop install mingw",
89
+ },
90
+ pwntools: {
91
+ cmd: "pwn",
92
+ desc: "CTF exploit toolkit (via pip)",
93
+ aliases: ["pwntools"],
94
+ apt: "pip install pwntools",
95
+ dnf: "pip install pwntools",
96
+ brew: "pip install pwntools",
97
+ choco: "pip install pwntools",
98
+ scoop: "pip install pwntools",
99
+ pip: "pip install pwntools",
100
+ },
101
+ steghide: {
102
+ cmd: "steghide",
103
+ desc: "steganography hiding and extraction",
104
+ apt: "sudo apt install -y steghide",
105
+ dnf: "sudo dnf install -y steghide",
106
+ brew: "brew install steghide",
107
+ choco: "choco install steghide -y",
108
+ scoop: "scoop install steghide",
109
+ },
110
+ exiftool: {
111
+ cmd: "exiftool",
112
+ desc: "image metadata reader",
113
+ aliases: ["exiftool"],
114
+ apt: "sudo apt install -y libimage-exiftool-perl",
115
+ dnf: "sudo dnf install -y perl-Image-ExifTool",
116
+ brew: "brew install exiftool",
117
+ choco: "choco install exiftool -y",
118
+ scoop: "scoop install exiftool",
119
+ },
120
+ john: {
121
+ cmd: "john",
122
+ desc: "password hash cracker",
123
+ aliases: ["john-the-ripper"],
124
+ apt: "sudo apt install -y john",
125
+ dnf: "sudo dnf install -y john",
126
+ brew: "brew install john",
127
+ choco: "choco install john -y",
128
+ scoop: "scoop install john",
129
+ },
130
+ hashcat: {
131
+ cmd: "hashcat",
132
+ desc: "GPU password recovery",
133
+ apt: "sudo apt install -y hashcat",
134
+ dnf: "sudo dnf install -y hashcat",
135
+ brew: "brew install hashcat",
136
+ choco: "choco install hashcat -y",
137
+ scoop: "scoop install hashcat",
138
+ },
139
+ metasploit: {
140
+ cmd: "msfconsole",
141
+ desc: "exploitation framework",
142
+ aliases: ["msfconsole", "msfvenom"],
143
+ apt: "sudo apt install -y metasploit-framework",
144
+ dnf: "sudo dnf install -y metasploit-framework",
145
+ brew: "brew install metasploit",
146
+ choco: "choco install metasploit -y",
147
+ scoop: "scoop install metasploit",
148
+ },
149
+ };
150
+
151
+ function defaultManager(platform) {
152
+ const p = platform || process.platform;
153
+ if (p === "win32") return "choco";
154
+ if (p === "darwin") return "brew";
155
+ return "apt";
156
+ }
157
+
158
+ // Find the map entry for a binary name. Matches the key, the cmd field,
159
+ // or any alias (e.g. msfconsole -> metasploit, strings -> binutils).
160
+ function findEntry(name) {
161
+ const key = String(name || "").trim().toLowerCase();
162
+ if (!key) return null;
163
+ if (TOOL_INSTALL_MAP[key]) return { name: key, entry: TOOL_INSTALL_MAP[key] };
164
+ for (const [pkg, entry] of Object.entries(TOOL_INSTALL_MAP)) {
165
+ if (String(entry.cmd || "").toLowerCase() === key) return { name: pkg, entry };
166
+ const aliases = entry.aliases || [];
167
+ if (aliases.some((a) => String(a).toLowerCase() === key)) return { name: pkg, entry };
168
+ }
169
+ return null;
170
+ }
171
+
172
+ function suggestInstall(toolName, manager) {
173
+ const found = findEntry(toolName);
174
+ if (!found) return null;
175
+ const wanted = manager || defaultManager();
176
+ const cmd = found.entry[wanted] || found.entry.apt || found.entry.brew || found.entry.choco || null;
177
+ if (!cmd) return null;
178
+ return { tool: found.name, manager: found.entry[wanted] ? wanted : "apt", installCmd: cmd };
179
+ }
180
+
181
+ // True when a bash command string exactly matches a known installer
182
+ // command (after trimming). Used to force the explicit install prompt.
183
+ // The WSL installer lives outside TOOL_INSTALL_MAP because it is a Windows
184
+ // feature enable, not a tool install: exact-match strings only, so a command
185
+ // that merely mentions wsl never trips it.
186
+ const WSL_INSTALL_COMMANDS = new Set([
187
+ "wsl.exe --install --norestart",
188
+ "wsl.exe --install",
189
+ "wsl --install --norestart",
190
+ "wsl --install",
191
+ ]);
192
+
193
+ const WSL_DEFAULT_INSTALL_CMD = "wsl.exe --install --norestart";
194
+
195
+ function isWSLInstallCommand(command) {
196
+ return WSL_INSTALL_COMMANDS.has(String(command || "").trim());
197
+ }
198
+
199
+ function isInstallCommand(command) {
200
+ const needle = String(command || "").trim();
201
+ if (!needle) return null;
202
+ if (isWSLInstallCommand(needle)) {
203
+ return { tool: "wsl", manager: "wsl", installCmd: needle === "wsl.exe --install --norestart" || needle === "wsl --install --norestart" ? WSL_DEFAULT_INSTALL_CMD : needle };
204
+ }
205
+ for (const [pkg, entry] of Object.entries(TOOL_INSTALL_MAP)) {
206
+ for (const mgr of ["apt", "dnf", "brew", "choco", "scoop", "pip"]) {
207
+ if (entry[mgr] && entry[mgr].trim() === needle) return { tool: pkg, manager: mgr, installCmd: entry[mgr] };
208
+ }
209
+ }
210
+ return null;
211
+ }
212
+
213
+ // Exact prompt text the asker must show. Kept here so tests and the CLI
214
+ // share one string. Plain hyphens only.
215
+ function installPromptText(tool, manager) {
216
+ return `Install ${tool} via ${manager}? [y/n]`;
217
+ }
218
+
219
+ function isValidBinary(name) {
220
+ return /^[A-Za-z0-9_][A-Za-z0-9_.~-]*$/.test(String(name || ""));
221
+ }
222
+
223
+ // Availability check: command -v on posix, where.exe on Windows.
224
+ // Sync and cached by callers only (no cache here - cheap enough per call
225
+ // and tests need deterministic results). opts.platform and opts.exec
226
+ // exist for tests: {platform, exec(cmd)} where exec throws on missing.
227
+ function isAvailable(cmd, opts = {}) {
228
+ const name = String(cmd || "").trim().split(/\s+/)[0] || "";
229
+ if (!isValidBinary(name)) return false;
230
+ const platform = opts.platform || process.platform;
231
+ try {
232
+ if (opts.exec) {
233
+ opts.exec(name, platform);
234
+ return true;
235
+ }
236
+ const { execSync } = require("node:child_process");
237
+ if (platform === "win32") {
238
+ execSync(`where.exe ${name}`, { stdio: "ignore", timeout: 5000, windowsHide: true });
239
+ } else {
240
+ execSync(`command -v ${name}`, { stdio: "ignore", timeout: 5000, shell: "/bin/sh" });
241
+ }
242
+ return true;
243
+ } catch {
244
+ return false;
245
+ }
246
+ }
247
+
248
+ // First word of a shell command, skipping a leading sudo. Returns "" when
249
+ // nothing parseable remains. Handles "sudo nmap -sV x" -> "nmap".
250
+ function extractToolFromCommand(command) {
251
+ const parts = String(command || "").trim().split(/\s+/).filter(Boolean);
252
+ if (!parts.length) return "";
253
+ let first = parts[0].replace(/^["']|["']$/g, "");
254
+ // Strip path: /usr/bin/nmap -> nmap
255
+ first = first.split(/[\\/]/).pop() || first;
256
+ if (first.toLowerCase() === "sudo" && parts.length > 1) {
257
+ let second = parts[1].replace(/^["']|["']$/g, "");
258
+ second = second.split(/[\\/]/).pop() || second;
259
+ return second.toLowerCase();
260
+ }
261
+ return first.toLowerCase();
262
+ }
263
+
264
+ function isMissingToolError(output) {
265
+ const s = String(output || "");
266
+ if (!s) return false;
267
+ return /command not found/i.test(s) || /is not recognized as an internal/i.test(s) || /:\s*not found\s*$/im.test(s) || /\bnot found\b.*\b(command|tool)\b/i.test(s);
268
+ }
269
+
270
+ // When bash output signals a missing binary and the binary is known,
271
+ // return {tool, manager, installCmd} for the default manager. Otherwise null.
272
+ function parseMissingTool(command, output, manager) {
273
+ if (!isMissingToolError(output)) return null;
274
+ const tool = extractToolFromCommand(command);
275
+ if (!tool) return null;
276
+ return suggestInstall(tool, manager);
277
+ }
278
+
279
+ module.exports = {
280
+ TOOL_INSTALL_MAP,
281
+ WSL_DEFAULT_INSTALL_CMD,
282
+ isWSLInstallCommand,
283
+ defaultManager,
284
+ findEntry,
285
+ suggestInstall,
286
+ isInstallCommand,
287
+ installPromptText,
288
+ isAvailable,
289
+ extractToolFromCommand,
290
+ isMissingToolError,
291
+ parseMissingTool,
292
+ };
package/lib/browser.js ADDED
@@ -0,0 +1,136 @@
1
+ "use strict";
2
+ // Browser hand-off for `bolt signin` via the RFC 8628 device authorization
3
+ // grant — the same flow `gh`, `vercel`, and `flyctl` use: the terminal shows
4
+ // a short code, the user approves it in the browser, the terminal polls for
5
+ // the token. No local HTTP server, no loopback navigation, no PKCE dance —
6
+ // nothing on the user's machine to block, and it works over SSH and in
7
+ // containers. Zero deps: node:child_process only.
8
+
9
+ const { spawn } = require("node:child_process");
10
+
11
+ const POLL_MAX_WAIT_MS = 10 * 60 * 1000;
12
+
13
+ /**
14
+ * Best-effort browser launch. Never throws and never blocks: on a headless box
15
+ * the URL and code are printed anyway, so the user can approve wherever they
16
+ * are. With `--no-browser` the caller skips this and prints only.
17
+ */
18
+ function openBrowser(url) {
19
+ try {
20
+ if (process.platform === "darwin") {
21
+ spawn("open", [url], { stdio: "ignore", detached: true }).unref();
22
+ return true;
23
+ }
24
+ if (process.platform === "win32") {
25
+ // rundll32's protocol handler takes the URL as a discrete argv entry, so
26
+ // nothing in it is re-parsed as a shell metacharacter. `cmd /c start`
27
+ // would need the URL quoted and still exposes it to cmd.exe parsing rules.
28
+ spawn("rundll32.exe", ["url.dll,FileProtocolHandler", url], { stdio: "ignore", detached: true }).unref();
29
+ return true;
30
+ }
31
+ spawn(process.env.BROWSER || "xdg-open", [url], { stdio: "ignore", detached: true }).unref();
32
+ return true;
33
+ } catch {
34
+ return false;
35
+ }
36
+ }
37
+
38
+ function sleep(ms) {
39
+ return new Promise((resolve) => setTimeout(resolve, ms));
40
+ }
41
+
42
+ /**
43
+ * Full device round trip: fetch a user code, show it, open the browser on
44
+ * the approval page, then poll until the grant is approved, denied, or
45
+ * expired. Resolves `{ token, expiresAt, email, balance }` and throws with an
46
+ * actionable message on every failure path.
47
+ *
48
+ * `spinner` is an optional progress handle with `start(msg)`/`stop()` (see
49
+ * `ui.createSpinner`). When provided, the wait animates in place instead of
50
+ * printing bare lines — the same treatment as every other long-running Bolt
51
+ * command.
52
+ */
53
+ async function signInWithBrowser({ url, open = true, log = () => {}, spinner = null }) {
54
+ // 1. A grant for this terminal: short code for the human, long secret for
55
+ // the polls. Neither is a credential yet — approval mints the token.
56
+ let grant;
57
+ try {
58
+ const res = await fetch(`${url}/api/cli/device/code`, { method: "POST" });
59
+ grant = await res.json().catch(() => ({}));
60
+ if (!res.ok || !grant.device_code || !grant.user_code) {
61
+ throw new Error((grant && grant.error) || `Sign-in server answered HTTP ${res.status}.`);
62
+ }
63
+ } catch (error) {
64
+ throw new Error(`Could not reach the sign-in server at ${url}. Check your connection, then run bolt signin again. (${error instanceof Error ? error.message : error})`);
65
+ }
66
+ const intervalMs = Math.min(Math.max((grant.interval || 5) * 1000, 2000), 30000);
67
+ const deadline = Date.now() + Math.min((grant.expires_in || 600) * 1000, POLL_MAX_WAIT_MS);
68
+
69
+ // 2. Show the code big and open the approval page with it prefilled.
70
+ const verificationUri = grant.verification_uri_complete || grant.verification_uri;
71
+ log("");
72
+ log("Sign in to continue:");
73
+ log(` Visit ${grant.verification_uri}`);
74
+ log(` Enter code ${grant.user_code}`);
75
+ log("");
76
+ const opened = open ? openBrowser(verificationUri) : false;
77
+ if (spinner && typeof spinner.start === "function") {
78
+ log(opened ? "Opening your browser — approve the request there, then return here." : "Open that link in your browser to finish signing in.");
79
+ log("");
80
+ spinner.start("Waiting for browser approval");
81
+ } else {
82
+ log(opened ? "Opening your browser. Waiting for approval…" : "Open that link in your browser to finish signing in.");
83
+ log("");
84
+ }
85
+
86
+ const stopSpinner = () => {
87
+ try {
88
+ if (spinner && typeof spinner.stop === "function") spinner.stop();
89
+ } catch {
90
+ // A progress-handle failure must never break sign-in.
91
+ }
92
+ };
93
+
94
+ // 3. Poll until the browser approves. Transient network failures are just
95
+ // missed rounds; terminal states throw with the exact next step.
96
+ let waitMs = intervalMs;
97
+ try {
98
+ for (;;) {
99
+ await sleep(waitMs);
100
+ if (Date.now() >= deadline) {
101
+ throw new Error("Timed out waiting for the browser. Run bolt signin again for a fresh code.");
102
+ }
103
+ let res;
104
+ try {
105
+ res = await fetch(`${url}/api/cli/device/token`, {
106
+ method: "POST",
107
+ headers: { "Content-Type": "application/json", Accept: "application/json" },
108
+ body: JSON.stringify({ device_code: grant.device_code }),
109
+ });
110
+ } catch {
111
+ continue;
112
+ }
113
+ const data = await res.json().catch(() => ({}));
114
+ if (res.ok && data && data.token) {
115
+ stopSpinner();
116
+ return data;
117
+ }
118
+ const code = data && data.error;
119
+ if (code === "authorization_pending") continue;
120
+ if (code === "slow_down") {
121
+ waitMs = Math.min(waitMs * 2, 30000);
122
+ continue;
123
+ }
124
+ stopSpinner();
125
+ if (code === "access_denied") {
126
+ throw new Error("Sign-in was declined in the browser. Run bolt signin again when you are ready.");
127
+ }
128
+ throw new Error("That sign-in request expired. Run bolt signin again for a fresh code.");
129
+ }
130
+ } catch (error) {
131
+ stopSpinner();
132
+ throw error;
133
+ }
134
+ }
135
+
136
+ module.exports = { openBrowser, signInWithBrowser };