@ricsam/browser-mcp 0.3.6 → 0.3.10
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/README.md +42 -2
- package/dist/{chunk-9kd368ja.js → chunk-3f5mve2t.js} +485 -227
- package/dist/main.js +4 -3
- package/package.json +1 -1
|
@@ -14,15 +14,22 @@ import {
|
|
|
14
14
|
import"./chunk-1sjcwr28.js";
|
|
15
15
|
|
|
16
16
|
// cli/src/browser/main.ts
|
|
17
|
-
import
|
|
18
|
-
import
|
|
19
|
-
import
|
|
17
|
+
import fs10 from "node:fs/promises";
|
|
18
|
+
import path9 from "node:path";
|
|
19
|
+
import net3 from "node:net";
|
|
20
|
+
import { setMaxListeners } from "node:events";
|
|
20
21
|
|
|
21
22
|
// cli/src/browser/lifecycle.ts
|
|
22
|
-
import
|
|
23
|
-
import
|
|
23
|
+
import fs3 from "node:fs/promises";
|
|
24
|
+
import path3 from "node:path";
|
|
24
25
|
import os2 from "node:os";
|
|
25
26
|
import { randomUUID } from "node:crypto";
|
|
27
|
+
|
|
28
|
+
// cli/src/browser/owned-chrome.ts
|
|
29
|
+
import { spawn } from "node:child_process";
|
|
30
|
+
import net from "node:net";
|
|
31
|
+
import fs from "node:fs/promises";
|
|
32
|
+
import path from "node:path";
|
|
26
33
|
import { chromium } from "playwright-core";
|
|
27
34
|
|
|
28
35
|
// cli/src/browser/cleanup.ts
|
|
@@ -44,41 +51,246 @@ function onceAsync(action) {
|
|
|
44
51
|
return () => result ??= Promise.resolve().then(action);
|
|
45
52
|
}
|
|
46
53
|
|
|
54
|
+
// cli/src/browser/owned-chrome.ts
|
|
55
|
+
var STARTUP_MS = 30000;
|
|
56
|
+
var CLOSE_MS = 2000;
|
|
57
|
+
var GRACEFUL_EXIT_MS = 30000;
|
|
58
|
+
async function allocateChromePort() {
|
|
59
|
+
return new Promise((resolve, reject) => {
|
|
60
|
+
const server = net.createServer();
|
|
61
|
+
const timer = setTimeout(() => {
|
|
62
|
+
server.close();
|
|
63
|
+
reject(new Error("Chrome port allocation timed out"));
|
|
64
|
+
}, STARTUP_MS);
|
|
65
|
+
server.once("error", (error) => {
|
|
66
|
+
clearTimeout(timer);
|
|
67
|
+
reject(error);
|
|
68
|
+
});
|
|
69
|
+
server.listen(0, "127.0.0.1", () => {
|
|
70
|
+
const address = server.address();
|
|
71
|
+
server.close((error) => {
|
|
72
|
+
clearTimeout(timer);
|
|
73
|
+
if (error)
|
|
74
|
+
reject(error);
|
|
75
|
+
else if (!address || typeof address === "string" || !address.port)
|
|
76
|
+
reject(new Error("Invalid Chrome port allocation"));
|
|
77
|
+
else
|
|
78
|
+
resolve(address.port);
|
|
79
|
+
});
|
|
80
|
+
});
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
function ownedChromeArgs(profile, port) {
|
|
84
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535)
|
|
85
|
+
throw new Error("Chrome requires a nonzero TCP port");
|
|
86
|
+
return [
|
|
87
|
+
`--user-data-dir=${profile}`,
|
|
88
|
+
"--remote-debugging-address=127.0.0.1",
|
|
89
|
+
`--remote-debugging-port=${port}`,
|
|
90
|
+
"--no-first-run",
|
|
91
|
+
"--no-default-browser-check",
|
|
92
|
+
"--disable-extensions",
|
|
93
|
+
"--disable-component-extensions-with-background-pages",
|
|
94
|
+
"--disable-sync",
|
|
95
|
+
"about:blank"
|
|
96
|
+
];
|
|
97
|
+
}
|
|
98
|
+
function chromeEndpointFromLine(line, port) {
|
|
99
|
+
const match = /^DevTools listening on (ws:\/\/127\.0\.0\.1:([1-9][0-9]*)\/devtools\/browser\/[a-zA-Z0-9-]+)\r?$/.exec(line);
|
|
100
|
+
return match && Number(match[2]) === port ? match[1] : undefined;
|
|
101
|
+
}
|
|
102
|
+
async function bounded(promise, ms) {
|
|
103
|
+
let timer;
|
|
104
|
+
try {
|
|
105
|
+
return await Promise.race([promise, new Promise((_, reject) => {
|
|
106
|
+
timer = setTimeout(() => reject(new Error("Owned Chrome operation timed out")), ms);
|
|
107
|
+
})]);
|
|
108
|
+
} finally {
|
|
109
|
+
clearTimeout(timer);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
async function launchOwnedChrome(options) {
|
|
113
|
+
options.signal?.throwIfAborted();
|
|
114
|
+
const artifactsDir = path.join(options.runPath, "chrome-downloads");
|
|
115
|
+
await fs.mkdir(artifactsDir, { mode: 448 });
|
|
116
|
+
options.signal?.throwIfAborted();
|
|
117
|
+
const port = await allocateChromePort();
|
|
118
|
+
options.signal?.throwIfAborted();
|
|
119
|
+
const child = spawn(options.executablePath, ownedChromeArgs(options.profile, port), {
|
|
120
|
+
stdio: ["ignore", "ignore", "pipe"]
|
|
121
|
+
});
|
|
122
|
+
let exited = false;
|
|
123
|
+
let browser;
|
|
124
|
+
let closing = false;
|
|
125
|
+
let resolveExit;
|
|
126
|
+
const exit = new Promise((resolve) => {
|
|
127
|
+
resolveExit = resolve;
|
|
128
|
+
});
|
|
129
|
+
let rejectStartup;
|
|
130
|
+
const failed = new Promise((_, reject) => {
|
|
131
|
+
rejectStartup = reject;
|
|
132
|
+
});
|
|
133
|
+
child.once("exit", () => {
|
|
134
|
+
exited = true;
|
|
135
|
+
resolveExit();
|
|
136
|
+
rejectStartup(new Error("Owned Chrome exited before startup completed"));
|
|
137
|
+
});
|
|
138
|
+
child.on("error", () => {
|
|
139
|
+
if (!child.pid) {
|
|
140
|
+
exited = true;
|
|
141
|
+
resolveExit();
|
|
142
|
+
}
|
|
143
|
+
rejectStartup(new Error("Could not start owned Chrome process"));
|
|
144
|
+
});
|
|
145
|
+
failed.catch(() => {});
|
|
146
|
+
const alive = () => !exited && child.exitCode === null && child.signalCode === null && !!child.pid;
|
|
147
|
+
const signalChild = (signal) => {
|
|
148
|
+
if (alive())
|
|
149
|
+
child.kill(signal);
|
|
150
|
+
};
|
|
151
|
+
const close = onceAsync(async () => {
|
|
152
|
+
closing = true;
|
|
153
|
+
const requestedClose = !!browser?.isConnected() && alive();
|
|
154
|
+
if (requestedClose) {
|
|
155
|
+
try {
|
|
156
|
+
await bounded((async () => {
|
|
157
|
+
const session = await browser.newBrowserCDPSession();
|
|
158
|
+
try {
|
|
159
|
+
await session.send("Browser.close");
|
|
160
|
+
} finally {
|
|
161
|
+
await session.detach().catch(() => {});
|
|
162
|
+
}
|
|
163
|
+
})(), CLOSE_MS);
|
|
164
|
+
} catch {}
|
|
165
|
+
}
|
|
166
|
+
try {
|
|
167
|
+
if (requestedClose && alive())
|
|
168
|
+
await bounded(exit, GRACEFUL_EXIT_MS).catch(() => {});
|
|
169
|
+
if (alive()) {
|
|
170
|
+
signalChild("SIGTERM");
|
|
171
|
+
try {
|
|
172
|
+
await bounded(exit, CLOSE_MS);
|
|
173
|
+
} catch {
|
|
174
|
+
signalChild("SIGKILL");
|
|
175
|
+
await bounded(exit, CLOSE_MS);
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
} finally {
|
|
179
|
+
if (browser)
|
|
180
|
+
await bounded(browser.close(), CLOSE_MS).catch(() => {});
|
|
181
|
+
child.stderr?.destroy();
|
|
182
|
+
}
|
|
183
|
+
if (alive())
|
|
184
|
+
throw new Error("Owned Chrome did not exit; retain profile ownership");
|
|
185
|
+
});
|
|
186
|
+
let lineBuffer = "";
|
|
187
|
+
let resolveEndpoint;
|
|
188
|
+
const endpoint = new Promise((resolve) => {
|
|
189
|
+
resolveEndpoint = resolve;
|
|
190
|
+
});
|
|
191
|
+
const onData = (chunk) => {
|
|
192
|
+
lineBuffer += chunk;
|
|
193
|
+
let newline;
|
|
194
|
+
while ((newline = lineBuffer.indexOf(`
|
|
195
|
+
`)) !== -1) {
|
|
196
|
+
const line = lineBuffer.slice(0, newline);
|
|
197
|
+
lineBuffer = lineBuffer.slice(newline + 1);
|
|
198
|
+
const url = chromeEndpointFromLine(line, port);
|
|
199
|
+
if (url)
|
|
200
|
+
resolveEndpoint(url);
|
|
201
|
+
else if (line.startsWith("DevTools listening on "))
|
|
202
|
+
rejectStartup(new Error("Owned Chrome announced an unexpected debugging endpoint"));
|
|
203
|
+
}
|
|
204
|
+
if (lineBuffer.length > 16384)
|
|
205
|
+
lineBuffer = "";
|
|
206
|
+
};
|
|
207
|
+
child.stderr?.setEncoding("utf8");
|
|
208
|
+
child.stderr?.on("data", onData);
|
|
209
|
+
const onAbort = () => rejectStartup(new Error("Owned Chrome startup aborted"));
|
|
210
|
+
options.signal?.addEventListener("abort", onAbort, { once: true });
|
|
211
|
+
if (options.signal?.aborted)
|
|
212
|
+
onAbort();
|
|
213
|
+
const deadline = Date.now() + STARTUP_MS;
|
|
214
|
+
const stage = (work) => bounded(Promise.race([work, failed]), Math.max(1, deadline - Date.now()));
|
|
215
|
+
try {
|
|
216
|
+
const url = await stage(endpoint);
|
|
217
|
+
const connection = chromium.connectOverCDP(url, {
|
|
218
|
+
isLocal: true,
|
|
219
|
+
artifactsDir,
|
|
220
|
+
timeout: Math.max(1, deadline - Date.now())
|
|
221
|
+
}).then(async (connected) => {
|
|
222
|
+
browser = connected;
|
|
223
|
+
if (closing) {
|
|
224
|
+
await connected.close();
|
|
225
|
+
throw new Error("Owned Chrome startup cancelled");
|
|
226
|
+
}
|
|
227
|
+
return connected;
|
|
228
|
+
});
|
|
229
|
+
await stage(connection);
|
|
230
|
+
const context = browser.contexts()[0];
|
|
231
|
+
if (!context)
|
|
232
|
+
throw new Error("Owned Chrome has no default context");
|
|
233
|
+
await stage(context.addInitScript("if (navigator.serviceWorker) navigator.serviceWorker.register = async () => { console.warn('Service Worker registration blocked by Playwright'); };"));
|
|
234
|
+
const page = context.pages().find((page2) => page2.url() === "about:blank");
|
|
235
|
+
if (!page)
|
|
236
|
+
throw new Error("Owned Chrome did not open the initial blank page");
|
|
237
|
+
if (await stage(page.evaluate(() => navigator.webdriver)) !== false) {
|
|
238
|
+
throw new Error("Owned Chrome unexpectedly exposes navigator.webdriver=true");
|
|
239
|
+
}
|
|
240
|
+
options.signal?.throwIfAborted();
|
|
241
|
+
if (!alive())
|
|
242
|
+
throw new Error("Owned Chrome exited during startup");
|
|
243
|
+
return { context, close };
|
|
244
|
+
} catch {
|
|
245
|
+
try {
|
|
246
|
+
await close();
|
|
247
|
+
} catch {
|
|
248
|
+
throw new Error("Owned Chrome startup and cleanup failed; retain profile ownership");
|
|
249
|
+
}
|
|
250
|
+
options.signal?.throwIfAborted();
|
|
251
|
+
throw new Error("Owned Chrome startup failed (process, endpoint, connection, or webdriver verification)");
|
|
252
|
+
} finally {
|
|
253
|
+
options.signal?.removeEventListener("abort", onAbort);
|
|
254
|
+
child.stderr?.off("data", onData);
|
|
255
|
+
child.stderr?.resume();
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
|
|
47
259
|
// cli/src/browser/recovery.ts
|
|
48
|
-
import
|
|
260
|
+
import fs2 from "node:fs/promises";
|
|
49
261
|
import { constants } from "node:fs";
|
|
50
|
-
import
|
|
262
|
+
import path2 from "node:path";
|
|
51
263
|
import os from "node:os";
|
|
52
|
-
import
|
|
264
|
+
import net2 from "node:net";
|
|
53
265
|
import { createHash } from "node:crypto";
|
|
54
266
|
import { execFile } from "node:child_process";
|
|
55
267
|
import { promisify } from "node:util";
|
|
56
268
|
function controlSocketPath(root, profile) {
|
|
57
|
-
return
|
|
269
|
+
return path2.join(root, `control-${createHash("sha256").update(profile).digest("hex").slice(0, 16)}.sock`);
|
|
58
270
|
}
|
|
59
271
|
var code = (e) => e.code;
|
|
60
272
|
var fail = (file, reason) => {
|
|
61
273
|
throw new Error(`Recovery refused: ${reason}: ${file}. Stop the prior host and Chrome, verify ownership and retry browser recover; do not blindly delete artifacts.`);
|
|
62
274
|
};
|
|
63
275
|
async function directories(directory) {
|
|
64
|
-
let cursor =
|
|
65
|
-
for (const part of directory.slice(cursor.length).split(
|
|
66
|
-
cursor =
|
|
67
|
-
const s = await
|
|
276
|
+
let cursor = path2.parse(directory).root;
|
|
277
|
+
for (const part of directory.slice(cursor.length).split(path2.sep).filter(Boolean)) {
|
|
278
|
+
cursor = path2.join(cursor, part);
|
|
279
|
+
const s = await fs2.lstat(cursor);
|
|
68
280
|
if (!s.isDirectory() || s.isSymbolicLink())
|
|
69
281
|
fail(cursor, "unsafe directory ancestor");
|
|
70
282
|
}
|
|
71
283
|
}
|
|
72
284
|
async function privateDir(directory) {
|
|
73
285
|
await directories(directory);
|
|
74
|
-
const s = await
|
|
286
|
+
const s = await fs2.lstat(directory);
|
|
75
287
|
if (s.uid !== process.getuid?.() || (s.mode & 511) !== 448)
|
|
76
288
|
fail(directory, "directory must be owned by current user with mode 0700");
|
|
77
289
|
}
|
|
78
290
|
async function artifact(file, socket = false) {
|
|
79
291
|
let s;
|
|
80
292
|
try {
|
|
81
|
-
s = await
|
|
293
|
+
s = await fs2.lstat(file);
|
|
82
294
|
} catch (e) {
|
|
83
295
|
if (code(e) === "ENOENT")
|
|
84
296
|
return;
|
|
@@ -115,10 +327,10 @@ async function assertProfileStopped(profile) {
|
|
|
115
327
|
fail(profile, `possible surviving profile process: PID ${pid}`);
|
|
116
328
|
}
|
|
117
329
|
}
|
|
118
|
-
const singleton =
|
|
330
|
+
const singleton = path2.join(profile, "SingletonLock");
|
|
119
331
|
let s;
|
|
120
332
|
try {
|
|
121
|
-
s = await
|
|
333
|
+
s = await fs2.lstat(singleton);
|
|
122
334
|
} catch (e) {
|
|
123
335
|
if (code(e) === "ENOENT")
|
|
124
336
|
return;
|
|
@@ -126,14 +338,14 @@ async function assertProfileStopped(profile) {
|
|
|
126
338
|
}
|
|
127
339
|
if (!s.isSymbolicLink() || s.uid !== process.getuid?.())
|
|
128
340
|
fail(singleton, "unrecognized Chromium singleton lock");
|
|
129
|
-
const target = await
|
|
341
|
+
const target = await fs2.readlink(singleton), match = /^(.*)-(\d+)$/.exec(target);
|
|
130
342
|
if (!match || match[1] !== os.hostname() || !Number.isSafeInteger(Number(match[2])) || Number(match[2]) <= 0)
|
|
131
343
|
fail(singleton, "foreign or unrecognized Chromium owner");
|
|
132
344
|
dead(Number(match[2]), singleton);
|
|
133
345
|
}
|
|
134
346
|
async function refusedSocket(file) {
|
|
135
347
|
await new Promise((resolve, reject) => {
|
|
136
|
-
const socket =
|
|
348
|
+
const socket = net2.createConnection(file);
|
|
137
349
|
const finish = (error) => {
|
|
138
350
|
socket.destroy();
|
|
139
351
|
error ? reject(error) : resolve();
|
|
@@ -151,11 +363,11 @@ async function recoverProfile(root, name) {
|
|
|
151
363
|
throw new Error("Recovery is supported only on Linux and macOS");
|
|
152
364
|
if (!/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,47}$/.test(name))
|
|
153
365
|
throw new Error("Profile must be a simple name, not a path");
|
|
154
|
-
root =
|
|
155
|
-
const profile =
|
|
366
|
+
root = path2.resolve(root);
|
|
367
|
+
const profile = path2.join(root, "profiles", name), lock = path2.join(profile, "runtime.lock"), socket = controlSocketPath(root, name);
|
|
156
368
|
try {
|
|
157
369
|
await privateDir(root);
|
|
158
|
-
await privateDir(
|
|
370
|
+
await privateDir(path2.join(root, "profiles"));
|
|
159
371
|
await privateDir(profile);
|
|
160
372
|
const original = await artifact(lock), originalSocket = await artifact(socket, true);
|
|
161
373
|
if (!original) {
|
|
@@ -165,7 +377,7 @@ async function recoverProfile(root, name) {
|
|
|
165
377
|
}
|
|
166
378
|
if (original.size > 16384)
|
|
167
379
|
fail(lock, "oversized lock");
|
|
168
|
-
const handle = await
|
|
380
|
+
const handle = await fs2.open(lock, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
169
381
|
try {
|
|
170
382
|
if (!same(original, await handle.stat()))
|
|
171
383
|
fail(lock, "lock changed while opening");
|
|
@@ -180,11 +392,11 @@ async function recoverProfile(root, name) {
|
|
|
180
392
|
fail(lock, "invalid lock schema or mismatched exact profile (legacy 0.3.5 fields required)");
|
|
181
393
|
const validate = async () => {
|
|
182
394
|
await privateDir(root);
|
|
183
|
-
await privateDir(
|
|
395
|
+
await privateDir(path2.join(root, "profiles"));
|
|
184
396
|
await privateDir(profile);
|
|
185
397
|
dead(owner.pid, lock);
|
|
186
398
|
await assertProfileStopped(profile);
|
|
187
|
-
if (!same(original, await artifact(lock)) || await
|
|
399
|
+
if (!same(original, await artifact(lock)) || await fs2.readFile(lock, "utf8") !== raw || !same(originalSocket, await artifact(socket, true)))
|
|
188
400
|
fail(lock, `artifact identity changed (socket ${socket})`);
|
|
189
401
|
if (originalSocket)
|
|
190
402
|
await refusedSocket(socket);
|
|
@@ -194,11 +406,11 @@ async function recoverProfile(root, name) {
|
|
|
194
406
|
};
|
|
195
407
|
await validate();
|
|
196
408
|
if (originalSocket)
|
|
197
|
-
await
|
|
409
|
+
await fs2.unlink(socket);
|
|
198
410
|
dead(owner.pid, lock);
|
|
199
411
|
if (!same(original, await handle.stat()) || !same(original, await artifact(lock)))
|
|
200
412
|
fail(lock, "lock changed before unlink");
|
|
201
|
-
await
|
|
413
|
+
await fs2.unlink(lock);
|
|
202
414
|
} finally {
|
|
203
415
|
await handle.close();
|
|
204
416
|
}
|
|
@@ -209,38 +421,38 @@ async function recoverProfile(root, name) {
|
|
|
209
421
|
|
|
210
422
|
// cli/src/browser/lifecycle.ts
|
|
211
423
|
function installationRoot() {
|
|
212
|
-
return
|
|
424
|
+
return path3.join(os2.homedir(), ".browser-mcp");
|
|
213
425
|
}
|
|
214
426
|
async function privateDirectory(directory) {
|
|
215
|
-
const absolute =
|
|
216
|
-
let cursor =
|
|
217
|
-
for (const piece of absolute.slice(cursor.length).split(
|
|
218
|
-
cursor =
|
|
427
|
+
const absolute = path3.resolve(directory);
|
|
428
|
+
let cursor = path3.parse(absolute).root;
|
|
429
|
+
for (const piece of absolute.slice(cursor.length).split(path3.sep)) {
|
|
430
|
+
cursor = path3.join(cursor, piece);
|
|
219
431
|
try {
|
|
220
|
-
await
|
|
432
|
+
await fs3.mkdir(cursor, { mode: 448 });
|
|
221
433
|
} catch (e) {
|
|
222
434
|
if (e.code !== "EEXIST")
|
|
223
435
|
throw e;
|
|
224
436
|
}
|
|
225
|
-
const stat2 = await
|
|
437
|
+
const stat2 = await fs3.lstat(cursor);
|
|
226
438
|
if (stat2.isSymbolicLink() || !stat2.isDirectory())
|
|
227
439
|
throw new Error("Unsafe directory path");
|
|
228
440
|
}
|
|
229
|
-
const stat = await
|
|
441
|
+
const stat = await fs3.stat(absolute);
|
|
230
442
|
if (process.platform !== "win32" && ((stat.mode & 63) !== 0 || stat.uid !== process.getuid?.()))
|
|
231
443
|
throw new Error("Private directory must be owned by current user with mode 0700");
|
|
232
444
|
return absolute;
|
|
233
445
|
}
|
|
234
446
|
async function discoverChrome(override) {
|
|
235
|
-
const candidates = override ? [override] : process.platform === "darwin" ? ["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
|
|
447
|
+
const candidates = override ? [override] : process.platform === "darwin" ? ["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome", path3.join(os2.homedir(), "Applications/Google Chrome.app/Contents/MacOS/Google Chrome")] : process.platform === "win32" ? [process.env.PROGRAMFILES, process.env["PROGRAMFILES(X86)"], process.env.LOCALAPPDATA].filter(Boolean).map((p) => path3.join(p, "Google", "Chrome", "Application", "chrome.exe")) : ["/usr/bin/google-chrome-stable", "/usr/bin/google-chrome", "/opt/google/chrome/chrome"];
|
|
236
448
|
for (const candidate of candidates) {
|
|
237
|
-
if (!
|
|
449
|
+
if (!path3.isAbsolute(candidate))
|
|
238
450
|
throw new Error("Chrome override must be an absolute executable path");
|
|
239
451
|
try {
|
|
240
|
-
const real = await
|
|
452
|
+
const real = await fs3.realpath(candidate), stat = await fs3.stat(real);
|
|
241
453
|
if (!stat.isFile())
|
|
242
454
|
continue;
|
|
243
|
-
await
|
|
455
|
+
await fs3.access(real, fs3.constants.X_OK);
|
|
244
456
|
return real;
|
|
245
457
|
} catch {}
|
|
246
458
|
}
|
|
@@ -253,37 +465,38 @@ async function launchDedicated(options = {}) {
|
|
|
253
465
|
if (!/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,47}$/.test(name))
|
|
254
466
|
throw new Error("Profile must be a simple name, not a path");
|
|
255
467
|
const root = await privateDirectory(options.root ?? installationRoot());
|
|
256
|
-
const profiles = await privateDirectory(
|
|
257
|
-
const profile =
|
|
468
|
+
const profiles = await privateDirectory(path3.join(root, "profiles"));
|
|
469
|
+
const profile = path3.join(profiles, options.ephemeral ? `ephemeral-${randomUUID()}` : name);
|
|
258
470
|
await privateDirectory(profile);
|
|
259
|
-
const profileStat = await
|
|
471
|
+
const profileStat = await fs3.lstat(profile);
|
|
260
472
|
options.signal?.throwIfAborted();
|
|
261
|
-
const lockPath =
|
|
473
|
+
const lockPath = path3.join(profile, "runtime.lock"), nonce = randomUUID(), instanceId = randomUUID();
|
|
262
474
|
let lock;
|
|
263
475
|
try {
|
|
264
|
-
lock = await
|
|
476
|
+
lock = await fs3.open(lockPath, "wx", 384);
|
|
265
477
|
} catch (error) {
|
|
266
478
|
if (error.code !== "EEXIST")
|
|
267
479
|
throw error;
|
|
268
|
-
throw new Error(`Profile already locked: ${lockPath}. After stopping the previous CLI and Chrome, run browser-mcp browser recover --profile ${name}. Recovery refuses live or uncertain owners; never blindly remove locks or sockets.`);
|
|
480
|
+
throw new Error(`Profile already locked: ${lockPath}. Use a different --profile to launch another browser. After stopping the previous CLI and Chrome, run browser-mcp browser recover --profile ${name}. Recovery refuses live or uncertain owners; never blindly remove locks or sockets.`);
|
|
269
481
|
}
|
|
270
482
|
const lockStat = await lock.stat();
|
|
271
|
-
const runPath =
|
|
483
|
+
const runPath = path3.join(profile, `run-${instanceId}`);
|
|
272
484
|
const manifest = { instanceId, profile, runPath, lockPath, ephemeral: !!options.ephemeral, ownedPaths: [runPath, ...options.ephemeral ? [profile] : []] };
|
|
273
485
|
let context, launched = false, lockWritten = false;
|
|
486
|
+
let chrome;
|
|
274
487
|
let runStat;
|
|
275
488
|
const verifyProfile = async () => {
|
|
276
|
-
const stat = await
|
|
277
|
-
if (await
|
|
489
|
+
const stat = await fs3.lstat(profile);
|
|
490
|
+
if (await fs3.realpath(profile) !== profile || !stat.isDirectory() || stat.isSymbolicLink() || stat.dev !== profileStat.dev || stat.ino !== profileStat.ino || stat.uid !== profileStat.uid || stat.mode & 63)
|
|
278
491
|
throw new Error("Profile directory ownership changed; retained owned paths");
|
|
279
492
|
};
|
|
280
493
|
const verifyLock = async () => {
|
|
281
494
|
await verifyProfile();
|
|
282
|
-
const stat = await
|
|
495
|
+
const stat = await fs3.lstat(lockPath);
|
|
283
496
|
if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1 || stat.dev !== lockStat.dev || stat.ino !== lockStat.ino || stat.uid !== lockStat.uid || stat.mode & 63)
|
|
284
497
|
throw new Error("Profile lock ownership changed; retained owned paths");
|
|
285
498
|
if (lockWritten) {
|
|
286
|
-
const stored = JSON.parse(await
|
|
499
|
+
const stored = JSON.parse(await fs3.readFile(lockPath, "utf8"));
|
|
287
500
|
if (stored.nonce !== nonce || stored.instanceId !== instanceId || stored.pid !== process.pid || stored.profile !== profile)
|
|
288
501
|
throw new Error("Profile lock ownership changed; retained owned paths");
|
|
289
502
|
}
|
|
@@ -293,8 +506,9 @@ async function launchDedicated(options = {}) {
|
|
|
293
506
|
try {
|
|
294
507
|
await cleanupSteps([
|
|
295
508
|
["Chrome close", async () => {
|
|
296
|
-
if (
|
|
297
|
-
await
|
|
509
|
+
if (chrome) {
|
|
510
|
+
await chrome.close();
|
|
511
|
+
await assertProfileStopped(profile);
|
|
298
512
|
stopped = true;
|
|
299
513
|
}
|
|
300
514
|
}],
|
|
@@ -306,19 +520,19 @@ async function launchDedicated(options = {}) {
|
|
|
306
520
|
["Run directory", async () => {
|
|
307
521
|
if (!runStat)
|
|
308
522
|
return;
|
|
309
|
-
const stat = await
|
|
523
|
+
const stat = await fs3.lstat(runPath);
|
|
310
524
|
if (!stat.isDirectory() || stat.isSymbolicLink() || stat.dev !== runStat.dev || stat.ino !== runStat.ino || stat.uid !== runStat.uid)
|
|
311
525
|
throw new Error("Run directory ownership changed; retained path");
|
|
312
|
-
await
|
|
526
|
+
await fs3.rm(runPath, { recursive: true, force: true });
|
|
313
527
|
}],
|
|
314
528
|
["Profile lock", async () => {
|
|
315
529
|
await verifyLock();
|
|
316
|
-
await
|
|
530
|
+
await fs3.unlink(lockPath);
|
|
317
531
|
}]
|
|
318
532
|
]);
|
|
319
533
|
if (options.ephemeral) {
|
|
320
534
|
await verifyProfile();
|
|
321
|
-
await
|
|
535
|
+
await fs3.rm(profile, { recursive: true, force: true });
|
|
322
536
|
}
|
|
323
537
|
}]
|
|
324
538
|
]);
|
|
@@ -329,14 +543,15 @@ async function launchDedicated(options = {}) {
|
|
|
329
543
|
try {
|
|
330
544
|
await lock.writeFile(JSON.stringify({ pid: process.pid, nonce, instanceId, profile, ephemeral: !!options.ephemeral }));
|
|
331
545
|
lockWritten = true;
|
|
332
|
-
await
|
|
333
|
-
runStat = await
|
|
334
|
-
await
|
|
546
|
+
await fs3.mkdir(runPath, { mode: 448 });
|
|
547
|
+
runStat = await fs3.lstat(runPath);
|
|
548
|
+
await fs3.writeFile(path3.join(runPath, "ownership.json"), JSON.stringify(manifest), { flag: "wx", mode: 384 });
|
|
335
549
|
options.signal?.throwIfAborted();
|
|
336
550
|
const executablePath = await discoverChrome(options.chromePath);
|
|
337
551
|
options.signal?.throwIfAborted();
|
|
338
552
|
launched = true;
|
|
339
|
-
|
|
553
|
+
chrome = await launchOwnedChrome({ executablePath, profile, runPath, signal: options.signal });
|
|
554
|
+
context = chrome.context;
|
|
340
555
|
options.signal?.throwIfAborted();
|
|
341
556
|
return { context, instanceId, profile, runPath, close, manifest };
|
|
342
557
|
} catch (error) {
|
|
@@ -351,12 +566,12 @@ ${cleanupError instanceof Error ? cleanupError.message : cleanupError}`);
|
|
|
351
566
|
}
|
|
352
567
|
|
|
353
568
|
// cli/src/browser/control.ts
|
|
354
|
-
import
|
|
355
|
-
import
|
|
569
|
+
import fs4 from "node:fs/promises";
|
|
570
|
+
import path4 from "node:path";
|
|
356
571
|
async function listenControl(server, root, controlPath) {
|
|
357
|
-
const rootStat = await
|
|
358
|
-
const directory = await
|
|
359
|
-
const dirStat = await
|
|
572
|
+
const rootStat = await fs4.lstat(root);
|
|
573
|
+
const directory = await fs4.mkdtemp(path4.join(root, "c-"));
|
|
574
|
+
const dirStat = await fs4.lstat(directory), boundPath = path4.join(directory, "s");
|
|
360
575
|
let socketStat, published = false;
|
|
361
576
|
const close = onceAsync(() => cleanupSteps([
|
|
362
577
|
["Control listener", async () => {
|
|
@@ -366,10 +581,10 @@ async function listenControl(server, root, controlPath) {
|
|
|
366
581
|
["Control pathname", async () => {
|
|
367
582
|
if (!published)
|
|
368
583
|
return;
|
|
369
|
-
const parent = await
|
|
370
|
-
if (await
|
|
584
|
+
const parent = await fs4.lstat(root);
|
|
585
|
+
if (await fs4.realpath(root) !== root || !parent.isDirectory() || parent.isSymbolicLink() || parent.dev !== rootStat.dev || parent.ino !== rootStat.ino || parent.uid !== rootStat.uid)
|
|
371
586
|
throw new Error(`Control root ownership changed; retained ${controlPath}`);
|
|
372
|
-
const stat = await
|
|
587
|
+
const stat = await fs4.lstat(controlPath).catch((error) => {
|
|
373
588
|
if (error.code !== "ENOENT")
|
|
374
589
|
throw error;
|
|
375
590
|
});
|
|
@@ -377,28 +592,28 @@ async function listenControl(server, root, controlPath) {
|
|
|
377
592
|
return;
|
|
378
593
|
if (!stat.isSocket() || !socketStat || stat.nlink !== 1 || stat.dev !== socketStat.dev || stat.ino !== socketStat.ino || stat.ctimeMs !== socketStat.ctimeMs || stat.mode !== socketStat.mode || stat.uid !== socketStat.uid)
|
|
379
594
|
throw new Error(`Control socket ownership changed; retained ${controlPath}`);
|
|
380
|
-
await
|
|
595
|
+
await fs4.unlink(controlPath);
|
|
381
596
|
}],
|
|
382
597
|
["Private control directory", async () => {
|
|
383
|
-
const stat = await
|
|
384
|
-
if (await
|
|
598
|
+
const stat = await fs4.lstat(directory);
|
|
599
|
+
if (await fs4.realpath(directory) !== directory || !stat.isDirectory() || stat.isSymbolicLink() || stat.dev !== dirStat.dev || stat.ino !== dirStat.ino || stat.uid !== dirStat.uid)
|
|
385
600
|
throw new Error(`Control directory ownership changed; retained ${directory}`);
|
|
386
|
-
await
|
|
387
|
-
await
|
|
601
|
+
await fs4.unlink(path4.join(directory, "ownership.json"));
|
|
602
|
+
await fs4.rmdir(directory);
|
|
388
603
|
}]
|
|
389
604
|
]));
|
|
390
605
|
try {
|
|
391
|
-
await
|
|
606
|
+
await fs4.writeFile(path4.join(directory, "ownership.json"), JSON.stringify({ pid: process.pid, controlPath, ownedPaths: [directory, boundPath] }), { mode: 384, flag: "wx" });
|
|
392
607
|
await new Promise((resolve, reject) => {
|
|
393
608
|
server.once("error", reject);
|
|
394
609
|
server.listen(boundPath, resolve);
|
|
395
610
|
});
|
|
396
|
-
socketStat = await
|
|
397
|
-
await
|
|
398
|
-
await
|
|
611
|
+
socketStat = await fs4.lstat(boundPath);
|
|
612
|
+
await fs4.chmod(boundPath, 384);
|
|
613
|
+
await fs4.link(boundPath, controlPath);
|
|
399
614
|
published = true;
|
|
400
|
-
await
|
|
401
|
-
socketStat = await
|
|
615
|
+
await fs4.unlink(boundPath);
|
|
616
|
+
socketStat = await fs4.lstat(controlPath);
|
|
402
617
|
return close;
|
|
403
618
|
} catch (error) {
|
|
404
619
|
try {
|
|
@@ -412,8 +627,8 @@ ${cleanupError}`);
|
|
|
412
627
|
}
|
|
413
628
|
|
|
414
629
|
// cli/src/browser/pairing.ts
|
|
415
|
-
import
|
|
416
|
-
import
|
|
630
|
+
import fs5 from "node:fs/promises";
|
|
631
|
+
import path5 from "node:path";
|
|
417
632
|
import { randomBytes, createHash as createHash2 } from "node:crypto";
|
|
418
633
|
import { setTimeout as delay } from "node:timers/promises";
|
|
419
634
|
function serverURL(raw) {
|
|
@@ -426,13 +641,13 @@ function serverURL(raw) {
|
|
|
426
641
|
}
|
|
427
642
|
async function credential(root, server, profile, signal) {
|
|
428
643
|
signal?.throwIfAborted();
|
|
429
|
-
const filename =
|
|
644
|
+
const filename = path5.join(root, `credential-${createHash2("sha256").update(`${server}
|
|
430
645
|
${profile}`).digest("hex").slice(0, 24)}.json`);
|
|
431
646
|
try {
|
|
432
|
-
const stat = await
|
|
647
|
+
const stat = await fs5.lstat(filename);
|
|
433
648
|
if (!stat.isFile() || stat.isSymbolicLink() || process.platform !== "win32" && stat.mode & 63)
|
|
434
649
|
throw new Error("Unsafe credential file");
|
|
435
|
-
const value = JSON.parse(await
|
|
650
|
+
const value = JSON.parse(await fs5.readFile(filename, "utf8"));
|
|
436
651
|
if (value.server !== server || !/^br_[\w-]+$/.test(value.token))
|
|
437
652
|
throw new Error("Invalid credential file");
|
|
438
653
|
return value.token;
|
|
@@ -451,7 +666,7 @@ ${profile}`).digest("hex").slice(0, 24)}.json`);
|
|
|
451
666
|
const verification = new URL(grant.verificationUrl);
|
|
452
667
|
if (verification.origin !== server)
|
|
453
668
|
throw new Error("Pairing origin mismatch");
|
|
454
|
-
console.error(`Approve this dedicated browser: ${verification.href}`);
|
|
669
|
+
console.error(`Approve this dedicated browser (${profile}): ${verification.href}`);
|
|
455
670
|
const deadline = Date.now() + Math.min(600, Number(grant.expiresIn)) * 1000;
|
|
456
671
|
while (Date.now() < deadline) {
|
|
457
672
|
await delay(Math.max(3, Number(grant.interval)) * 1000, undefined, { signal });
|
|
@@ -462,7 +677,7 @@ ${profile}`).digest("hex").slice(0, 24)}.json`);
|
|
|
462
677
|
if (typeof token !== "string" || !/^br_[\w-]+$/.test(token))
|
|
463
678
|
throw new Error("Pairing did not return a browser credential");
|
|
464
679
|
signal?.throwIfAborted();
|
|
465
|
-
await
|
|
680
|
+
await fs5.writeFile(filename, JSON.stringify({ server, token }), { mode: 384, flag: "wx" });
|
|
466
681
|
return token;
|
|
467
682
|
}
|
|
468
683
|
throw new Error("Pairing expired");
|
|
@@ -527,8 +742,8 @@ function screenshotPoint(transform, current, delivered, point) {
|
|
|
527
742
|
}
|
|
528
743
|
|
|
529
744
|
// cli/src/browser/browser-runtime.ts
|
|
530
|
-
import
|
|
531
|
-
import
|
|
745
|
+
import fs8 from "node:fs";
|
|
746
|
+
import path7 from "node:path";
|
|
532
747
|
|
|
533
748
|
// cli/src/browser/upload-input.ts
|
|
534
749
|
var BROWSER_UPLOAD_CHUNK_BYTES = 1024 * 1024;
|
|
@@ -1030,8 +1245,8 @@ function preflightBrowserInput(action, raw) {
|
|
|
1030
1245
|
}
|
|
1031
1246
|
|
|
1032
1247
|
// cli/src/browser/upload-store.ts
|
|
1033
|
-
import
|
|
1034
|
-
import
|
|
1248
|
+
import fs6 from "node:fs";
|
|
1249
|
+
import path6 from "node:path";
|
|
1035
1250
|
import { createHash as createHash3 } from "node:crypto";
|
|
1036
1251
|
class BrowserUploadStore {
|
|
1037
1252
|
releaseTarget;
|
|
@@ -1041,8 +1256,8 @@ class BrowserUploadStore {
|
|
|
1041
1256
|
return;
|
|
1042
1257
|
}) {
|
|
1043
1258
|
this.releaseTarget = releaseTarget;
|
|
1044
|
-
|
|
1045
|
-
this.directory =
|
|
1259
|
+
fs6.mkdirSync(root, { recursive: true, mode: 448 });
|
|
1260
|
+
this.directory = fs6.mkdtempSync(path6.join(root, "run-"));
|
|
1046
1261
|
}
|
|
1047
1262
|
begin(id, tabId, files, target2) {
|
|
1048
1263
|
if (typeof id !== "string" || !/^[a-f0-9-]{36}$/.test(id) || this.uploads.has(id))
|
|
@@ -1050,20 +1265,20 @@ class BrowserUploadStore {
|
|
|
1050
1265
|
if (!Array.isArray(files) || files.length === 0 || files.length > 100)
|
|
1051
1266
|
throw new Error("Upload requires between 1 and 100 files.");
|
|
1052
1267
|
const metadata = files.map(validateUploadFile);
|
|
1053
|
-
const directory =
|
|
1268
|
+
const directory = fs6.mkdtempSync(path6.join(this.directory, "upload-"));
|
|
1054
1269
|
try {
|
|
1055
1270
|
const staged = metadata.map((file, index) => {
|
|
1056
|
-
const parent =
|
|
1057
|
-
|
|
1058
|
-
const filePath =
|
|
1059
|
-
|
|
1271
|
+
const parent = path6.join(directory, String(index));
|
|
1272
|
+
fs6.mkdirSync(parent, { mode: 448 });
|
|
1273
|
+
const filePath = path6.join(parent, file.filename);
|
|
1274
|
+
fs6.closeSync(fs6.openSync(filePath, "wx", 384));
|
|
1060
1275
|
return { ...file, path: filePath, offset: 0, hash: createHash3("sha256") };
|
|
1061
1276
|
});
|
|
1062
1277
|
const timer = setTimeout(() => this.abort(id, tabId), 5 * 60 * 1000);
|
|
1063
1278
|
timer.unref();
|
|
1064
1279
|
this.uploads.set(id, { tabId, directory, files: staged, target: target2, attached: false, timer });
|
|
1065
1280
|
} catch (error) {
|
|
1066
|
-
|
|
1281
|
+
fs6.rmSync(directory, { recursive: true, force: true });
|
|
1067
1282
|
throw error;
|
|
1068
1283
|
}
|
|
1069
1284
|
}
|
|
@@ -1084,17 +1299,17 @@ class BrowserUploadStore {
|
|
|
1084
1299
|
const bytes = decodeUploadChunk(base64);
|
|
1085
1300
|
if (bytes.length === 0 || file.offset + bytes.length > file.size)
|
|
1086
1301
|
throw new Error("Upload chunk does not match the declared file size.");
|
|
1087
|
-
const fd =
|
|
1302
|
+
const fd = fs6.openSync(file.path, fs6.constants.O_WRONLY | fs6.constants.O_NOFOLLOW);
|
|
1088
1303
|
try {
|
|
1089
1304
|
let written = 0;
|
|
1090
1305
|
while (written < bytes.length) {
|
|
1091
|
-
const count =
|
|
1306
|
+
const count = fs6.writeSync(fd, bytes, written, bytes.length - written, file.offset + written);
|
|
1092
1307
|
if (!count)
|
|
1093
1308
|
throw new Error("Could not write upload chunk.");
|
|
1094
1309
|
written += count;
|
|
1095
1310
|
}
|
|
1096
1311
|
} finally {
|
|
1097
|
-
|
|
1312
|
+
fs6.closeSync(fd);
|
|
1098
1313
|
}
|
|
1099
1314
|
file.hash.update(bytes);
|
|
1100
1315
|
file.offset += bytes.length;
|
|
@@ -1128,7 +1343,7 @@ class BrowserUploadStore {
|
|
|
1128
1343
|
clearTimeout(upload.timer);
|
|
1129
1344
|
this.uploads.delete(id);
|
|
1130
1345
|
this.releaseTarget(upload.target);
|
|
1131
|
-
|
|
1346
|
+
fs6.rmSync(upload.directory, { recursive: true, force: true });
|
|
1132
1347
|
}
|
|
1133
1348
|
closeTab(tabId) {
|
|
1134
1349
|
for (const [id, upload] of this.uploads)
|
|
@@ -1138,7 +1353,7 @@ class BrowserUploadStore {
|
|
|
1138
1353
|
close() {
|
|
1139
1354
|
for (const [id, upload] of this.uploads)
|
|
1140
1355
|
this.remove(id, upload);
|
|
1141
|
-
|
|
1356
|
+
fs6.rmSync(this.directory, { recursive: true, force: true });
|
|
1142
1357
|
}
|
|
1143
1358
|
}
|
|
1144
1359
|
|
|
@@ -1316,7 +1531,7 @@ async function passwordSafeAriaSnapshot(page, options = {}) {
|
|
|
1316
1531
|
};
|
|
1317
1532
|
const document2 = { text: "", priorityRefs: [], matchRefs: [], matchCount: 0, frames: [], unavailableFrames: [] };
|
|
1318
1533
|
const timeoutError = () => new Error(`Timeout ${timeout2}ms exceeded building a password-safe browser snapshot.`);
|
|
1319
|
-
const
|
|
1534
|
+
const bounded2 = async (operation) => {
|
|
1320
1535
|
let timer;
|
|
1321
1536
|
try {
|
|
1322
1537
|
return await Promise.race([
|
|
@@ -1334,7 +1549,7 @@ async function passwordSafeAriaSnapshot(page, options = {}) {
|
|
|
1334
1549
|
throw new Error(UNAVAILABLE);
|
|
1335
1550
|
if (Date.now() >= deadline)
|
|
1336
1551
|
throw timeoutError();
|
|
1337
|
-
const captured = await
|
|
1552
|
+
const captured = await bounded2(currentFrame.selectors.callOnSelector(selector, { strict: true }, captureInUtilityWorld, frameOptions));
|
|
1338
1553
|
if (!captured) {
|
|
1339
1554
|
if (!isMainFrame) {
|
|
1340
1555
|
document2.unavailableFrames.push(framePath.at(-1));
|
|
@@ -1346,7 +1561,7 @@ async function passwordSafeAriaSnapshot(page, options = {}) {
|
|
|
1346
1561
|
}
|
|
1347
1562
|
if (options.frames?.length)
|
|
1348
1563
|
throw new Error("Snapshot frame selection failed. Each frames selector must match exactly one iframe with a loaded document.");
|
|
1349
|
-
await
|
|
1564
|
+
await bounded2(new Promise((resolve) => setTimeout(resolve, 50)));
|
|
1350
1565
|
return captureFrame(currentFrame, selector, frameOptions, true);
|
|
1351
1566
|
}
|
|
1352
1567
|
if (captured.info?.world !== "utility" || !isServerFrame(captured.frame))
|
|
@@ -1536,7 +1751,7 @@ async function openBackgroundTab(context, newWindow, timeoutMs = 1e4) {
|
|
|
1536
1751
|
const deadline = Date.now() + timeoutMs;
|
|
1537
1752
|
const sessions = new Set;
|
|
1538
1753
|
let stopped = false;
|
|
1539
|
-
const
|
|
1754
|
+
const bounded2 = async (operation) => {
|
|
1540
1755
|
let timer;
|
|
1541
1756
|
try {
|
|
1542
1757
|
return await Promise.race([
|
|
@@ -1583,9 +1798,9 @@ async function openBackgroundTab(context, newWindow, timeoutMs = 1e4) {
|
|
|
1583
1798
|
};
|
|
1584
1799
|
const onPage = (page) => {
|
|
1585
1800
|
(async () => {
|
|
1586
|
-
const session = await
|
|
1801
|
+
const session = await bounded2(attach(page));
|
|
1587
1802
|
try {
|
|
1588
|
-
const { targetInfo } = await
|
|
1803
|
+
const { targetInfo } = await bounded2(session.send("Target.getTargetInfo"));
|
|
1589
1804
|
if (!stopped && !page.isClosed()) {
|
|
1590
1805
|
candidates.set(targetInfo.targetId, page);
|
|
1591
1806
|
select();
|
|
@@ -1603,10 +1818,10 @@ async function openBackgroundTab(context, newWindow, timeoutMs = 1e4) {
|
|
|
1603
1818
|
try {
|
|
1604
1819
|
const previous = context.pages().findLast((page) => !page.isClosed());
|
|
1605
1820
|
if (!previous)
|
|
1606
|
-
return await
|
|
1607
|
-
const controller = await
|
|
1608
|
-
const { targetInfo } = await
|
|
1609
|
-
const created = await
|
|
1821
|
+
return await bounded2(context.newPage());
|
|
1822
|
+
const controller = await bounded2(attach(previous));
|
|
1823
|
+
const { targetInfo } = await bounded2(controller.send("Target.getTargetInfo"));
|
|
1824
|
+
const created = await bounded2(controller.send("Target.createTarget", {
|
|
1610
1825
|
url: "about:blank",
|
|
1611
1826
|
background: true,
|
|
1612
1827
|
newWindow,
|
|
@@ -1615,12 +1830,12 @@ async function openBackgroundTab(context, newWindow, timeoutMs = 1e4) {
|
|
|
1615
1830
|
}));
|
|
1616
1831
|
targetId = created.targetId;
|
|
1617
1832
|
select();
|
|
1618
|
-
return await
|
|
1833
|
+
return await bounded2(found);
|
|
1619
1834
|
} finally {
|
|
1620
1835
|
stopped = true;
|
|
1621
1836
|
context.off("page", onPage);
|
|
1622
1837
|
context.off("close", onClose);
|
|
1623
|
-
await
|
|
1838
|
+
await bounded2(Promise.allSettled([...sessions].map(detach))).catch(() => {
|
|
1624
1839
|
return;
|
|
1625
1840
|
});
|
|
1626
1841
|
}
|
|
@@ -1696,7 +1911,7 @@ async function waitForBrowserCondition(page, input) {
|
|
|
1696
1911
|
code: "invalid_wait_target",
|
|
1697
1912
|
error: "Cannot resolve the wait target. Check target, scope and frame selectors with browser_read_page."
|
|
1698
1913
|
});
|
|
1699
|
-
const
|
|
1914
|
+
const bounded2 = async (promise) => {
|
|
1700
1915
|
let timer;
|
|
1701
1916
|
try {
|
|
1702
1917
|
return await Promise.race([
|
|
@@ -1736,7 +1951,7 @@ async function waitForBrowserCondition(page, input) {
|
|
|
1736
1951
|
if (page.isClosed())
|
|
1737
1952
|
return result(false, { code: "wait_tab_closed", error: "The tab closed before the condition matched." });
|
|
1738
1953
|
try {
|
|
1739
|
-
const observed = await
|
|
1954
|
+
const observed = await bounded2((async () => {
|
|
1740
1955
|
let handle = null;
|
|
1741
1956
|
let frameHandle = null;
|
|
1742
1957
|
let elements = [];
|
|
@@ -2575,13 +2790,13 @@ async function exportDocument(page, format) {
|
|
|
2575
2790
|
}
|
|
2576
2791
|
}
|
|
2577
2792
|
const text = await page.evaluate((format2) => {
|
|
2578
|
-
const
|
|
2793
|
+
const bounded2 = (text2) => {
|
|
2579
2794
|
if (text2.length > 20 * 1024 * 1024 || new TextEncoder().encode(text2).length > 20 * 1024 * 1024)
|
|
2580
2795
|
throw new Error("Document export exceeds 20 MiB.");
|
|
2581
2796
|
return text2;
|
|
2582
2797
|
};
|
|
2583
2798
|
if (format2 === "text")
|
|
2584
|
-
return
|
|
2799
|
+
return bounded2(document.body.innerText);
|
|
2585
2800
|
const clone = document.documentElement.cloneNode(true);
|
|
2586
2801
|
for (const el of clone.querySelectorAll('input[type="password"]'))
|
|
2587
2802
|
el.setAttribute("value", "[password]");
|
|
@@ -2591,7 +2806,7 @@ async function exportDocument(page, format) {
|
|
|
2591
2806
|
for (const attr of [...el.attributes])
|
|
2592
2807
|
if (/^on/i.test(attr.name) || attr.name === "srcdoc" || /^[\s\u0000-\u0020]*(javascript|vbscript):/i.test(attr.value))
|
|
2593
2808
|
el.removeAttribute(attr.name);
|
|
2594
|
-
return
|
|
2809
|
+
return bounded2(`<!doctype html>
|
|
2595
2810
|
` + clone.outerHTML);
|
|
2596
2811
|
}, format);
|
|
2597
2812
|
return {
|
|
@@ -2602,7 +2817,7 @@ async function exportDocument(page, format) {
|
|
|
2602
2817
|
}
|
|
2603
2818
|
|
|
2604
2819
|
// cli/src/browser/browser-tab-state.ts
|
|
2605
|
-
import
|
|
2820
|
+
import fs7 from "node:fs";
|
|
2606
2821
|
|
|
2607
2822
|
class BrowserTabState {
|
|
2608
2823
|
context;
|
|
@@ -2613,8 +2828,8 @@ class BrowserTabState {
|
|
|
2613
2828
|
constructor(context, filename) {
|
|
2614
2829
|
this.context = context;
|
|
2615
2830
|
this.filename = filename;
|
|
2616
|
-
if (
|
|
2617
|
-
const value = JSON.parse(
|
|
2831
|
+
if (fs7.existsSync(filename)) {
|
|
2832
|
+
const value = JSON.parse(fs7.readFileSync(filename, "utf8"));
|
|
2618
2833
|
if (value.version !== 1 || !value.targets || typeof value.targets !== "object")
|
|
2619
2834
|
throw new Error("Invalid browser tab state.");
|
|
2620
2835
|
this.stored = value.targets;
|
|
@@ -2622,8 +2837,8 @@ class BrowserTabState {
|
|
|
2622
2837
|
}
|
|
2623
2838
|
save() {
|
|
2624
2839
|
const tmp = `${this.filename}.${crypto.randomUUID()}.tmp`;
|
|
2625
|
-
|
|
2626
|
-
|
|
2840
|
+
fs7.writeFileSync(tmp, JSON.stringify({ version: 1, targets: this.stored }), { mode: 384, flag: "wx" });
|
|
2841
|
+
fs7.renameSync(tmp, this.filename);
|
|
2627
2842
|
}
|
|
2628
2843
|
resolve(page) {
|
|
2629
2844
|
let pending = this.pages.get(page);
|
|
@@ -2735,7 +2950,7 @@ class BrowserRuntime {
|
|
|
2735
2950
|
return;
|
|
2736
2951
|
});
|
|
2737
2952
|
});
|
|
2738
|
-
|
|
2953
|
+
fs8.mkdirSync(downloadsPath, { recursive: true });
|
|
2739
2954
|
this.tabState = new BrowserTabState(context, `${downloadsPath}.tabs.json`);
|
|
2740
2955
|
for (const page of context.pages())
|
|
2741
2956
|
this.track(page);
|
|
@@ -2794,23 +3009,23 @@ class BrowserRuntime {
|
|
|
2794
3009
|
return id;
|
|
2795
3010
|
}
|
|
2796
3011
|
safeDownloadFilename(suggestedFilename) {
|
|
2797
|
-
const basename =
|
|
3012
|
+
const basename = path7.basename(suggestedFilename).replace(/[\\/\0]/g, "-").trim();
|
|
2798
3013
|
if (!basename || basename === "." || basename === "..")
|
|
2799
3014
|
return "download";
|
|
2800
|
-
const extension =
|
|
2801
|
-
let stem = basename.slice(0, basename.length -
|
|
3015
|
+
const extension = path7.extname(basename).slice(0, 30);
|
|
3016
|
+
let stem = basename.slice(0, basename.length - path7.extname(basename).length) || "download";
|
|
2802
3017
|
while (Buffer.byteLength(`${stem}${extension}`) > 200)
|
|
2803
3018
|
stem = stem.slice(0, -1);
|
|
2804
3019
|
return `${stem || "download"}${extension}`;
|
|
2805
3020
|
}
|
|
2806
3021
|
availableDownloadPath(suggestedFilename) {
|
|
2807
3022
|
const filename = this.safeDownloadFilename(suggestedFilename);
|
|
2808
|
-
const extension =
|
|
3023
|
+
const extension = path7.extname(filename);
|
|
2809
3024
|
const stem = filename.slice(0, filename.length - extension.length) || "download";
|
|
2810
3025
|
for (let suffix = 1;; suffix += 1) {
|
|
2811
3026
|
const candidate = suffix === 1 ? filename : `${stem}-${suffix}${extension}`;
|
|
2812
|
-
const candidatePath =
|
|
2813
|
-
if (!
|
|
3027
|
+
const candidatePath = path7.join(this.downloadsPath, candidate);
|
|
3028
|
+
if (!fs8.existsSync(candidatePath))
|
|
2814
3029
|
return candidatePath;
|
|
2815
3030
|
}
|
|
2816
3031
|
}
|
|
@@ -2818,18 +3033,18 @@ class BrowserRuntime {
|
|
|
2818
3033
|
const failure = await download.failure();
|
|
2819
3034
|
if (failure)
|
|
2820
3035
|
throw new Error(failure);
|
|
2821
|
-
const temporary =
|
|
3036
|
+
const temporary = path7.join(this.downloadsPath, `.${crypto.randomUUID()}.download`);
|
|
2822
3037
|
let targetPath;
|
|
2823
3038
|
try {
|
|
2824
3039
|
await download.saveAs(temporary);
|
|
2825
3040
|
targetPath = this.availableDownloadPath(download.suggestedFilename());
|
|
2826
|
-
|
|
3041
|
+
fs8.renameSync(temporary, targetPath);
|
|
2827
3042
|
} finally {
|
|
2828
|
-
|
|
3043
|
+
fs8.rmSync(temporary, { force: true });
|
|
2829
3044
|
}
|
|
2830
|
-
process.stdout.write(`[r5d-browser] downloaded ${
|
|
3045
|
+
process.stdout.write(`[r5d-browser] downloaded ${path7.basename(targetPath)}
|
|
2831
3046
|
`);
|
|
2832
|
-
return { downloadId: this.downloadId(
|
|
3047
|
+
return { downloadId: this.downloadId(path7.basename(targetPath)) };
|
|
2833
3048
|
}
|
|
2834
3049
|
downloadId(filename) {
|
|
2835
3050
|
return Buffer.from(filename, "utf8").toString("base64url");
|
|
@@ -2838,13 +3053,13 @@ class BrowserRuntime {
|
|
|
2838
3053
|
if (typeof downloadId !== "string" || !downloadId)
|
|
2839
3054
|
throw new Error("downloadId is required.");
|
|
2840
3055
|
const filename = Buffer.from(downloadId, "base64url").toString("utf8");
|
|
2841
|
-
if (this.downloadId(filename) !== downloadId || filename !==
|
|
3056
|
+
if (this.downloadId(filename) !== downloadId || filename !== path7.basename(filename) || filename.includes("\x00")) {
|
|
2842
3057
|
throw new Error("Invalid downloadId.");
|
|
2843
3058
|
}
|
|
2844
|
-
const filePath =
|
|
3059
|
+
const filePath = path7.join(this.downloadsPath, filename);
|
|
2845
3060
|
let stats;
|
|
2846
3061
|
try {
|
|
2847
|
-
stats =
|
|
3062
|
+
stats = fs8.lstatSync(filePath);
|
|
2848
3063
|
} catch {
|
|
2849
3064
|
throw new Error(`Browser download ${downloadId} no longer exists.`);
|
|
2850
3065
|
}
|
|
@@ -2853,7 +3068,7 @@ class BrowserRuntime {
|
|
|
2853
3068
|
return { filename, filePath, stats };
|
|
2854
3069
|
}
|
|
2855
3070
|
async listDownloads() {
|
|
2856
|
-
return
|
|
3071
|
+
return fs8.readdirSync(this.downloadsPath, { withFileTypes: true }).flatMap((entry) => {
|
|
2857
3072
|
if (!entry.isFile() || entry.name.startsWith("."))
|
|
2858
3073
|
return [];
|
|
2859
3074
|
const { filename, stats } = this.resolveDownload(this.downloadId(entry.name));
|
|
@@ -2877,20 +3092,20 @@ class BrowserRuntime {
|
|
|
2877
3092
|
throw new Error("Invalid download chunk size.");
|
|
2878
3093
|
const chunkSize = Math.min(requestedBytes, MAX_DOWNLOAD_CHUNK_BYTES, stats.size - offset);
|
|
2879
3094
|
const bytes = Buffer.alloc(chunkSize);
|
|
2880
|
-
const handle =
|
|
3095
|
+
const handle = fs8.openSync(filePath, fs8.constants.O_RDONLY | fs8.constants.O_NOFOLLOW);
|
|
2881
3096
|
let bytesRead = 0;
|
|
2882
3097
|
try {
|
|
2883
|
-
const openedStats =
|
|
3098
|
+
const openedStats = fs8.fstatSync(handle);
|
|
2884
3099
|
if (!openedStats.isFile() || openedStats.dev !== stats.dev || openedStats.ino !== stats.ino) {
|
|
2885
3100
|
throw new Error("Browser download changed before it could be read.");
|
|
2886
3101
|
}
|
|
2887
|
-
bytesRead =
|
|
2888
|
-
const completedStats =
|
|
3102
|
+
bytesRead = fs8.readSync(handle, bytes, 0, chunkSize, offset);
|
|
3103
|
+
const completedStats = fs8.fstatSync(handle);
|
|
2889
3104
|
if (completedStats.size !== stats.size || completedStats.mtimeMs !== stats.mtimeMs) {
|
|
2890
3105
|
throw new Error("Browser download changed while it was being read.");
|
|
2891
3106
|
}
|
|
2892
3107
|
} finally {
|
|
2893
|
-
|
|
3108
|
+
fs8.closeSync(handle);
|
|
2894
3109
|
}
|
|
2895
3110
|
const nextOffset = offset + bytesRead;
|
|
2896
3111
|
return {
|
|
@@ -3312,9 +3527,9 @@ class BrowserRuntime {
|
|
|
3312
3527
|
return { tabId, exported: false, code: "export_too_large" };
|
|
3313
3528
|
const exports = files.map((file) => {
|
|
3314
3529
|
const target2 = this.availableDownloadPath(`${crypto.randomUUID()}-${file.filename}`);
|
|
3315
|
-
|
|
3530
|
+
fs8.writeFileSync(target2, file.bytes, { flag: "wx", mode: 384 });
|
|
3316
3531
|
return {
|
|
3317
|
-
downloadId: this.downloadId(
|
|
3532
|
+
downloadId: this.downloadId(path7.basename(target2)),
|
|
3318
3533
|
filename: file.filename,
|
|
3319
3534
|
size: file.bytes.length,
|
|
3320
3535
|
mimeType: file.mimeType
|
|
@@ -4049,8 +4264,8 @@ class NativeRuntime {
|
|
|
4049
4264
|
// cli/src/runtime/relay.ts
|
|
4050
4265
|
import WebSocket2 from "ws";
|
|
4051
4266
|
import { createHash as createHash5, randomUUID as randomUUID2 } from "node:crypto";
|
|
4052
|
-
import
|
|
4053
|
-
import
|
|
4267
|
+
import fs9 from "node:fs/promises";
|
|
4268
|
+
import path8 from "node:path";
|
|
4054
4269
|
|
|
4055
4270
|
// cli/src/live/producer.ts
|
|
4056
4271
|
import WebSocket from "ws";
|
|
@@ -4150,7 +4365,7 @@ class CaptureTimeout extends Error {
|
|
|
4150
4365
|
this.stage = stage;
|
|
4151
4366
|
}
|
|
4152
4367
|
}
|
|
4153
|
-
async function
|
|
4368
|
+
async function bounded2(stage, operation) {
|
|
4154
4369
|
let timer;
|
|
4155
4370
|
try {
|
|
4156
4371
|
return await Promise.race([operation, new Promise((_, reject) => {
|
|
@@ -4256,8 +4471,8 @@ class NativeLiveProducer {
|
|
|
4256
4471
|
const cdp = this.cdp;
|
|
4257
4472
|
this.cdp = undefined;
|
|
4258
4473
|
if (cdp) {
|
|
4259
|
-
await
|
|
4260
|
-
await
|
|
4474
|
+
await bounded2("stop_screencast", cdp.send("Page.stopScreencast")).catch(() => {});
|
|
4475
|
+
await bounded2("detach", cdp.detach()).catch(() => {});
|
|
4261
4476
|
}
|
|
4262
4477
|
}
|
|
4263
4478
|
async reconcile(generation) {
|
|
@@ -4286,7 +4501,7 @@ class NativeLiveProducer {
|
|
|
4286
4501
|
const initialNav = this.navSeq;
|
|
4287
4502
|
let authorized = false;
|
|
4288
4503
|
try {
|
|
4289
|
-
authorized = await
|
|
4504
|
+
authorized = await bounded2("authorize", this.options.authorizePage(page));
|
|
4290
4505
|
} catch (error) {
|
|
4291
4506
|
await this.teardown();
|
|
4292
4507
|
if (generation === this.generation)
|
|
@@ -4349,12 +4564,12 @@ class NativeLiveProducer {
|
|
|
4349
4564
|
let abandoned = false;
|
|
4350
4565
|
const attaching = this.options.context.newCDPSession(page).then((session) => {
|
|
4351
4566
|
if (abandoned)
|
|
4352
|
-
|
|
4567
|
+
bounded2("detach", session.detach()).catch(() => {});
|
|
4353
4568
|
return session;
|
|
4354
4569
|
});
|
|
4355
4570
|
let cdp;
|
|
4356
4571
|
try {
|
|
4357
|
-
cdp = await
|
|
4572
|
+
cdp = await bounded2("attach", attaching);
|
|
4358
4573
|
} catch (error) {
|
|
4359
4574
|
abandoned = true;
|
|
4360
4575
|
throw error;
|
|
@@ -4388,7 +4603,7 @@ class NativeLiveProducer {
|
|
|
4388
4603
|
const nav = this.navSeq;
|
|
4389
4604
|
(async () => {
|
|
4390
4605
|
try {
|
|
4391
|
-
const allowed2 = await
|
|
4606
|
+
const allowed2 = await bounded2("frame_authorize", this.options.authorizePage(page));
|
|
4392
4607
|
if (generation !== this.generation || nav !== this.navSeq || this.closed || !this.enabled || !this.active || this.socket !== ws || ws.readyState !== WebSocket.OPEN)
|
|
4393
4608
|
return;
|
|
4394
4609
|
if (!allowed2 || this.options.getPage(tab) !== page) {
|
|
@@ -4404,11 +4619,11 @@ class NativeLiveProducer {
|
|
|
4404
4619
|
})();
|
|
4405
4620
|
});
|
|
4406
4621
|
const startNav = this.navSeq;
|
|
4407
|
-
if (!await
|
|
4622
|
+
if (!await bounded2("authorize", this.options.authorizePage(page)) || generation !== this.generation || startNav !== this.navSeq) {
|
|
4408
4623
|
await this.teardown();
|
|
4409
4624
|
return;
|
|
4410
4625
|
}
|
|
4411
|
-
await
|
|
4626
|
+
await bounded2("start_screencast", cdp.send("Page.startScreencast", { format: "jpeg", quality: 60, maxWidth: 1600, maxHeight: 1000, everyNthFrame: 1 }));
|
|
4412
4627
|
if (generation !== this.generation) {
|
|
4413
4628
|
await this.teardown();
|
|
4414
4629
|
return;
|
|
@@ -4514,7 +4729,7 @@ class Relay {
|
|
|
4514
4729
|
heartbeat.unref();
|
|
4515
4730
|
socket.once("open", () => {
|
|
4516
4731
|
this.state = "authenticating";
|
|
4517
|
-
socket.send(JSON.stringify({ type: "auth", token: this.token, client: { protocol: 3, version: "0.3.
|
|
4732
|
+
socket.send(JSON.stringify({ type: "auth", token: this.token, client: { protocol: 3, version: "0.3.10", instanceId: this.runtime.instanceId, operations: [...BROWSER_OPERATIONS, ...this.runtime.plugins.flatMap((p) => p.operations), "session_end", "release_tab"], capabilities: ["browser-controls.v1", "screenshot-ids.v1", "webmcp.page-context.v1", "clipboard.native.v1", "native-transfers.v1", "secrets.v1", "forwarding.v1", "live-view.v1"], liveView: { enabled: this.liveEnabled } } }));
|
|
4518
4733
|
});
|
|
4519
4734
|
socket.on("message", (bytes, binary) => {
|
|
4520
4735
|
if (binary || Buffer.byteLength(bytes.toString()) > LIMIT) {
|
|
@@ -4633,20 +4848,20 @@ class Relay {
|
|
|
4633
4848
|
if (message.op === "export_page" && Array.isArray(result?.exports))
|
|
4634
4849
|
for (const item of result.exports) {
|
|
4635
4850
|
const filename = Buffer.from(item.downloadId, "base64url").toString("utf8");
|
|
4636
|
-
if (
|
|
4851
|
+
if (path8.basename(filename) !== filename)
|
|
4637
4852
|
throw new Error("Invalid export file");
|
|
4638
|
-
const filenamePath =
|
|
4639
|
-
const stat = await
|
|
4853
|
+
const filenamePath = path8.join(this.previewDirectory, filename);
|
|
4854
|
+
const stat = await fs9.lstat(filenamePath);
|
|
4640
4855
|
if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 20 * 1024 * 1024)
|
|
4641
4856
|
throw new Error("Invalid export file");
|
|
4642
|
-
blobs.push(await this.upload(await
|
|
4643
|
-
await
|
|
4857
|
+
blobs.push(await this.upload(await fs9.readFile(filenamePath), "export", item.filename, item.mimeType));
|
|
4858
|
+
await fs9.unlink(filenamePath);
|
|
4644
4859
|
delete item.downloadId;
|
|
4645
4860
|
}
|
|
4646
4861
|
if (message.op === "run_js" && Array.isArray(result?.artifacts)) {
|
|
4647
4862
|
for (const artifact2 of result.artifacts)
|
|
4648
|
-
blobs.push(await this.upload(Buffer.from(artifact2.content), "artifact",
|
|
4649
|
-
result.artifacts = result.artifacts.map((a) => ({ filename:
|
|
4863
|
+
blobs.push(await this.upload(Buffer.from(artifact2.content), "artifact", path8.basename(artifact2.filename), "text/plain"));
|
|
4864
|
+
result.artifacts = result.artifacts.map((a) => ({ filename: path8.basename(a.filename) }));
|
|
4650
4865
|
}
|
|
4651
4866
|
if (Buffer.byteLength(JSON.stringify(result)) > 1800000)
|
|
4652
4867
|
throw new Error("Result budget exceeded");
|
|
@@ -5037,9 +5252,9 @@ async function createDataPlugin(access, options) {
|
|
|
5037
5252
|
r = create(scope, "download", LIMITS.file, download.suggestedFilename());
|
|
5038
5253
|
r.tabId = tabId;
|
|
5039
5254
|
r.generation = generation;
|
|
5040
|
-
const
|
|
5041
|
-
r.path =
|
|
5042
|
-
owned.add(
|
|
5255
|
+
const path9 = join(options.directory, r.id);
|
|
5256
|
+
r.path = path9;
|
|
5257
|
+
owned.add(path9);
|
|
5043
5258
|
const source = await download.createReadStream();
|
|
5044
5259
|
if (!source)
|
|
5045
5260
|
throw new Error("Download unavailable");
|
|
@@ -5053,17 +5268,17 @@ async function createDataPlugin(access, options) {
|
|
|
5053
5268
|
const timeout2 = setTimeout(() => r.abort.abort(), LIMITS.duration);
|
|
5054
5269
|
timeout2.unref?.();
|
|
5055
5270
|
try {
|
|
5056
|
-
await pipeline(source, bound, createWriteStream(
|
|
5271
|
+
await pipeline(source, bound, createWriteStream(path9, { flags: "wx", mode: 384 }), { signal: r.abort.signal });
|
|
5057
5272
|
} finally {
|
|
5058
5273
|
clearTimeout(timeout2);
|
|
5059
5274
|
}
|
|
5060
|
-
await chmod(
|
|
5061
|
-
const stat = await lstat(
|
|
5275
|
+
await chmod(path9, 384);
|
|
5276
|
+
const stat = await lstat(path9);
|
|
5062
5277
|
if (!stat.isFile() || stat.size > LIMITS.file)
|
|
5063
5278
|
throw new Error("Download limit");
|
|
5064
5279
|
r.size = stat.size;
|
|
5065
5280
|
const hash = createHash6("sha256");
|
|
5066
|
-
for await (const chunk of createReadStream(
|
|
5281
|
+
for await (const chunk of createReadStream(path9))
|
|
5067
5282
|
hash.update(chunk);
|
|
5068
5283
|
r.hash = hash.digest("hex");
|
|
5069
5284
|
if (r.abort.signal.aborted)
|
|
@@ -5177,17 +5392,21 @@ function createForwardPlugin(options) {
|
|
|
5177
5392
|
|
|
5178
5393
|
// cli/src/browser/main.ts
|
|
5179
5394
|
function parse(args) {
|
|
5180
|
-
const options = {};
|
|
5395
|
+
const options = { profiles: [] };
|
|
5181
5396
|
for (let i = 0;i < args.length; i++) {
|
|
5182
5397
|
const key = args[i];
|
|
5183
5398
|
if (key === "--ephemeral")
|
|
5184
5399
|
options.ephemeral = true;
|
|
5185
5400
|
else if (key === "--live-view")
|
|
5186
5401
|
options.liveView = true;
|
|
5187
|
-
else if (
|
|
5402
|
+
else if (key === "--profile" || key === "--server" || key === "--chrome-path") {
|
|
5188
5403
|
if (!args[i + 1] || args[i + 1].startsWith("--"))
|
|
5189
5404
|
throw new Error(`Missing ${key} value`);
|
|
5190
|
-
|
|
5405
|
+
const value = args[++i];
|
|
5406
|
+
if (key === "--profile")
|
|
5407
|
+
options.profiles.push(value);
|
|
5408
|
+
else
|
|
5409
|
+
options[key === "--server" ? "server" : "chrome-path"] = value;
|
|
5191
5410
|
} else
|
|
5192
5411
|
throw new Error(`Unknown browser option ${key}`);
|
|
5193
5412
|
}
|
|
@@ -5196,20 +5415,93 @@ function parse(args) {
|
|
|
5196
5415
|
async function runBrowser(args) {
|
|
5197
5416
|
const command = args.shift() ?? "help";
|
|
5198
5417
|
if (command === "help" || command === "--help" || args.includes("--help")) {
|
|
5199
|
-
console.log(`browser-mcp browser start [--server https://browser-mcp.click] [--profile work] [--ephemeral] [--chrome-path /path/to/chrome] [--live-view]
|
|
5418
|
+
console.log(`browser-mcp browser start [--server https://browser-mcp.click] [--profile work] [--profile personal ...] [--ephemeral] [--chrome-path /path/to/chrome] [--live-view]
|
|
5200
5419
|
browser-mcp browser status|pause|resume|stop|recover [--profile work]
|
|
5201
|
-
|
|
5420
|
+
Repeat --profile to launch multiple isolated browsers. Without --profile, uses default. Approve each new profile separately. Local controls target one profile; Ctrl-C closes all browsers started by this command. A launch/runtime failure stops the group.
|
|
5421
|
+
Dedicated Chrome only. Foreground lifecycle with loopback CDP: stopping the CLI closes Chrome; no detach/reattach. recover removes only verified stale lock/socket artifacts, never profile data. Live view requires local --live-view opt-in (screenshots may expose secrets). Windows browser host is not yet supported.`);
|
|
5202
5422
|
return;
|
|
5203
5423
|
}
|
|
5204
|
-
|
|
5205
|
-
|
|
5206
|
-
|
|
5424
|
+
if (!["start", "status", "pause", "resume", "stop", "recover"].includes(command))
|
|
5425
|
+
throw new Error("Unknown browser command");
|
|
5426
|
+
const options = parse(args), profiles = options.profiles.length ? options.profiles : ["default"];
|
|
5427
|
+
for (const profile of profiles)
|
|
5428
|
+
if (!/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,47}$/.test(profile))
|
|
5429
|
+
throw new Error("Invalid profile name");
|
|
5430
|
+
if (new Set(profiles).size !== profiles.length)
|
|
5431
|
+
throw new Error("Duplicate profile names: use a different --profile for each browser");
|
|
5432
|
+
if (command !== "start" && profiles.length !== 1)
|
|
5433
|
+
throw new Error(`${command} accepts one --profile; run local controls separately for each browser`);
|
|
5434
|
+
const abort = new AbortController;
|
|
5435
|
+
setMaxListeners(0, abort.signal);
|
|
5436
|
+
const requestStop = () => abort.abort(new Error("Browser startup interrupted"));
|
|
5437
|
+
const signals = ["SIGINT", "SIGTERM", "SIGHUP"];
|
|
5438
|
+
if (command === "start")
|
|
5439
|
+
for (const signal of signals)
|
|
5440
|
+
process.on(signal, requestStop);
|
|
5441
|
+
try {
|
|
5442
|
+
const root = await privateDirectory(installationRoot());
|
|
5443
|
+
if (command !== "start") {
|
|
5444
|
+
const profile = profiles[0], controlPath = controlSocketPath(root, profile);
|
|
5445
|
+
if (command === "recover") {
|
|
5446
|
+
await recoverProfile(root, profile);
|
|
5447
|
+
console.log(`Verified stale lock/socket cleanup complete for profile ${profile}; profile data retained.`);
|
|
5448
|
+
return;
|
|
5449
|
+
}
|
|
5450
|
+
await new Promise((resolve, reject) => {
|
|
5451
|
+
const socket = net3.connect(controlPath);
|
|
5452
|
+
socket.setTimeout(5000, () => socket.destroy(new Error("Local control timeout")));
|
|
5453
|
+
socket.once("connect", () => socket.write(JSON.stringify({ command }) + `
|
|
5454
|
+
`));
|
|
5455
|
+
socket.once("data", (data) => {
|
|
5456
|
+
console.log(data.toString().trim());
|
|
5457
|
+
socket.end();
|
|
5458
|
+
resolve();
|
|
5459
|
+
});
|
|
5460
|
+
socket.once("error", (error) => reject(new Error(`${error.message}. If the CLI has exited, run browser-mcp browser recover --profile ${profile} to check the profile lock and ${controlPath}.`)));
|
|
5461
|
+
});
|
|
5462
|
+
return;
|
|
5463
|
+
}
|
|
5464
|
+
abort.signal.throwIfAborted();
|
|
5465
|
+
const server = serverURL(options.server ?? "https://browser-mcp.click");
|
|
5466
|
+
for (const profile of profiles) {
|
|
5467
|
+
const controlPath = controlSocketPath(root, profile);
|
|
5468
|
+
const previousSocket = await fs10.lstat(controlPath).catch((error) => {
|
|
5469
|
+
if (error.code !== "ENOENT")
|
|
5470
|
+
throw error;
|
|
5471
|
+
});
|
|
5472
|
+
if (previousSocket)
|
|
5473
|
+
throw new Error(`Local control path already exists: ${controlPath}. Use a different --profile to launch another browser. If the prior host has stopped, run browser-mcp browser recover --profile ${profile}. Recovery verifies both runtime.lock and the socket; never blindly unlink either.`);
|
|
5474
|
+
abort.signal.throwIfAborted();
|
|
5475
|
+
}
|
|
5476
|
+
const results = await Promise.allSettled(profiles.map(async (profile) => {
|
|
5477
|
+
try {
|
|
5478
|
+
await startProfile(root, server, profile, options, abort.signal);
|
|
5479
|
+
} catch (cause) {
|
|
5480
|
+
requestStop();
|
|
5481
|
+
throw new Error(`Profile ${profile}: ${cause instanceof Error ? cause.message : cause}`, { cause });
|
|
5482
|
+
}
|
|
5483
|
+
}));
|
|
5484
|
+
const errors = results.flatMap((result) => result.status === "rejected" ? [result.reason] : []);
|
|
5485
|
+
if (errors.length)
|
|
5486
|
+
throw new AggregateError(errors, errors.map((error) => error.message).join(`
|
|
5487
|
+
`));
|
|
5488
|
+
} catch (error) {
|
|
5489
|
+
if (error !== abort.signal.reason)
|
|
5490
|
+
throw error;
|
|
5491
|
+
} finally {
|
|
5492
|
+
if (command === "start")
|
|
5493
|
+
for (const signal of signals)
|
|
5494
|
+
process.removeListener(signal, requestStop);
|
|
5495
|
+
}
|
|
5496
|
+
}
|
|
5497
|
+
async function startProfile(root, server, profile, options, groupSignal) {
|
|
5207
5498
|
const abort = new AbortController;
|
|
5208
5499
|
let starting = true;
|
|
5209
5500
|
let session;
|
|
5210
5501
|
let runtime, relay, local;
|
|
5211
5502
|
let stopQuota;
|
|
5212
|
-
|
|
5503
|
+
const controlPath = controlSocketPath(root, profile);
|
|
5504
|
+
let stopControl;
|
|
5213
5505
|
const clients = new Set;
|
|
5214
5506
|
const close = onceAsync(() => cleanupSteps([
|
|
5215
5507
|
["Relay", async () => {
|
|
@@ -5235,53 +5527,21 @@ Dedicated Chrome only. Foreground pipe lifecycle: stopping the CLI closes Chrome
|
|
|
5235
5527
|
if (!starting)
|
|
5236
5528
|
close().catch(() => {});
|
|
5237
5529
|
};
|
|
5238
|
-
|
|
5239
|
-
if (
|
|
5240
|
-
|
|
5241
|
-
process.on(signal, requestStop);
|
|
5530
|
+
groupSignal.addEventListener("abort", requestStop, { once: true });
|
|
5531
|
+
if (groupSignal.aborted)
|
|
5532
|
+
requestStop();
|
|
5242
5533
|
try {
|
|
5243
|
-
const root = await privateDirectory(installationRoot());
|
|
5244
|
-
controlPath = controlSocketPath(root, profile);
|
|
5245
|
-
if (command === "recover") {
|
|
5246
|
-
await recoverProfile(root, profile);
|
|
5247
|
-
console.log(`Verified stale lock/socket cleanup complete for profile ${profile}; profile data retained.`);
|
|
5248
|
-
return;
|
|
5249
|
-
}
|
|
5250
|
-
if (command !== "start") {
|
|
5251
|
-
if (!["status", "pause", "resume", "stop"].includes(command))
|
|
5252
|
-
throw new Error("Unknown browser command");
|
|
5253
|
-
await new Promise((resolve, reject) => {
|
|
5254
|
-
const socket = net2.connect(controlPath);
|
|
5255
|
-
socket.setTimeout(5000, () => socket.destroy(new Error("Local control timeout")));
|
|
5256
|
-
socket.once("connect", () => socket.write(JSON.stringify({ command }) + `
|
|
5257
|
-
`));
|
|
5258
|
-
socket.once("data", (data) => {
|
|
5259
|
-
console.log(data.toString().trim());
|
|
5260
|
-
socket.end();
|
|
5261
|
-
resolve();
|
|
5262
|
-
});
|
|
5263
|
-
socket.once("error", (error) => reject(new Error(`${error.message}. If the CLI has exited, run browser-mcp browser recover --profile ${profile} to check the profile lock and ${controlPath}.`)));
|
|
5264
|
-
});
|
|
5265
|
-
return;
|
|
5266
|
-
}
|
|
5267
5534
|
abort.signal.throwIfAborted();
|
|
5268
|
-
const server = serverURL(String(options.server ?? "https://browser-mcp.click"));
|
|
5269
|
-
const previousSocket = await fs9.lstat(controlPath).catch((error) => {
|
|
5270
|
-
if (error.code !== "ENOENT")
|
|
5271
|
-
throw error;
|
|
5272
|
-
});
|
|
5273
|
-
if (previousSocket)
|
|
5274
|
-
throw new Error(`Local control path already exists: ${controlPath}. If the prior host has stopped, run browser-mcp browser recover --profile ${profile}. Recovery verifies both runtime.lock and the socket; never blindly unlink either.`);
|
|
5275
5535
|
session = await launchDedicated({ root, profile, ephemeral: !!options.ephemeral, chromePath: options["chrome-path"], signal: abort.signal });
|
|
5276
5536
|
session.context.once("close", requestStop);
|
|
5277
5537
|
abort.signal.throwIfAborted();
|
|
5278
|
-
stopQuota = await enforceDownloadQuota(session.context,
|
|
5538
|
+
stopQuota = await enforceDownloadQuota(session.context, path9.join(session.runPath, "chrome-downloads"));
|
|
5279
5539
|
abort.signal.throwIfAborted();
|
|
5280
5540
|
const token = await credential(root, server, profile, abort.signal);
|
|
5281
5541
|
abort.signal.throwIfAborted();
|
|
5282
|
-
const previews =
|
|
5542
|
+
const previews = path9.join(session.runPath, "previews");
|
|
5283
5543
|
runtime = new NativeRuntime(session.context, session.instanceId, previews, server);
|
|
5284
|
-
runtime.plugins.push(await createDataPlugin(runtime, { directory:
|
|
5544
|
+
runtime.plugins.push(await createDataPlugin(runtime, { directory: path9.join(session.runPath, "data"), serverOrigin: server, allowInsecureLoopback: new URL(server).protocol === "http:" }));
|
|
5285
5545
|
abort.signal.throwIfAborted();
|
|
5286
5546
|
runtime.plugins.push(createForwardPlugin({ serverUrl: server }));
|
|
5287
5547
|
relay = new Relay(runtime, server, token, previews, !!options.liveView);
|
|
@@ -5292,7 +5552,7 @@ Dedicated Chrome only. Foreground pipe lifecycle: stopping the CLI closes Chrome
|
|
|
5292
5552
|
await route.continue();
|
|
5293
5553
|
});
|
|
5294
5554
|
abort.signal.throwIfAborted();
|
|
5295
|
-
local =
|
|
5555
|
+
local = net3.createServer((socket) => {
|
|
5296
5556
|
clients.add(socket);
|
|
5297
5557
|
socket.once("close", () => clients.delete(socket));
|
|
5298
5558
|
socket.setTimeout(2000, () => socket.destroy());
|
|
@@ -5322,7 +5582,7 @@ Dedicated Chrome only. Foreground pipe lifecycle: stopping the CLI closes Chrome
|
|
|
5322
5582
|
return;
|
|
5323
5583
|
} else if (cmd !== "status")
|
|
5324
5584
|
throw new Error("Invalid command");
|
|
5325
|
-
socket.end(JSON.stringify({ state: relay.state, paused: relay.paused, instanceId: session.instanceId, profile, version: "0.3.
|
|
5585
|
+
socket.end(JSON.stringify({ state: relay.state, paused: relay.paused, instanceId: session.instanceId, profile, version: "0.3.10", protocol: 3 }) + `
|
|
5326
5586
|
`);
|
|
5327
5587
|
})().catch(() => socket.destroy());
|
|
5328
5588
|
});
|
|
@@ -5334,7 +5594,7 @@ Dedicated Chrome only. Foreground pipe lifecycle: stopping the CLI closes Chrome
|
|
|
5334
5594
|
}
|
|
5335
5595
|
abort.signal.throwIfAborted();
|
|
5336
5596
|
starting = false;
|
|
5337
|
-
console.error(`Dedicated Chrome running. Local controls: browser-mcp browser pause|status|stop --profile ${profile}. Ctrl-C closes
|
|
5597
|
+
console.error(`Dedicated Chrome running (${profile}). Local controls: browser-mcp browser pause|resume|status|stop --profile ${profile}. Ctrl-C closes all browsers started by this command.`);
|
|
5338
5598
|
await relay.start();
|
|
5339
5599
|
} catch (error) {
|
|
5340
5600
|
if (error !== abort.signal.reason && !(abort.signal.aborted && error instanceof Error && error.name === "AbortError"))
|
|
@@ -5343,9 +5603,7 @@ Dedicated Chrome only. Foreground pipe lifecycle: stopping the CLI closes Chrome
|
|
|
5343
5603
|
try {
|
|
5344
5604
|
await close();
|
|
5345
5605
|
} finally {
|
|
5346
|
-
|
|
5347
|
-
for (const signal of signals)
|
|
5348
|
-
process.removeListener(signal, requestStop);
|
|
5606
|
+
groupSignal.removeEventListener("abort", requestStop);
|
|
5349
5607
|
}
|
|
5350
5608
|
}
|
|
5351
5609
|
}
|