@ricsam/browser-mcp 0.3.7 → 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 +11 -2
- package/dist/{chunk-rshfr4hg.js → chunk-3f5mve2t.js} +394 -180
- package/dist/main.js +3 -3
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -4,7 +4,7 @@ Native Chrome companion. Requires Node >=22.14.0 and an installed
|
|
|
4
4
|
Google Chrome. No browser download or startup occurs during npm installation.
|
|
5
5
|
|
|
6
6
|
```sh
|
|
7
|
-
npm install -g @ricsam/browser-mcp@0.3.
|
|
7
|
+
npm install -g @ricsam/browser-mcp@0.3.10
|
|
8
8
|
browser-mcp browser start --server https://browser-mcp.click --profile work
|
|
9
9
|
browser-mcp browser status --profile work
|
|
10
10
|
browser-mcp browser pause --profile work
|
|
@@ -20,7 +20,7 @@ profile. Profile names cannot contain paths. Your daily-driver profile is never
|
|
|
20
20
|
opened, copied or attached. `--live-view` enables screenshot-based live view
|
|
21
21
|
locally (off by default); remote viewers cannot enable it.
|
|
22
22
|
|
|
23
|
-
Foreground
|
|
23
|
+
Foreground lifecycle: keep the CLI running. Ctrl-C, stop, or normal CLI exit
|
|
24
24
|
closes its Chrome. There is no detach or automatic CDP reattachment. Each launch
|
|
25
25
|
has a fresh instance identity. Relay reconnect does not replay admitted actions.
|
|
26
26
|
Signals received during launch cancel further startup and wait for the bounded
|
|
@@ -28,6 +28,15 @@ Chrome launch (up to 30 seconds) before closing acquired resources. Repeated
|
|
|
28
28
|
signals wait for that same cleanup. Pairing waits are cancelled too. A cleanup
|
|
29
29
|
error is reported after the other safe cleanup stages have been attempted.
|
|
30
30
|
|
|
31
|
+
Chrome runs headed, without `--enable-automation`, `--headless`,
|
|
32
|
+
`--remote-debugging-pipe` or `--remote-debugging-port=0`, so its native
|
|
33
|
+
`navigator.webdriver` stays false (no getter override or stealth script).
|
|
34
|
+
Control uses a fresh nonzero loopback CDP port for each launch. The CLI connects
|
|
35
|
+
only to the endpoint announced by its own Chrome child, never a pre-existing
|
|
36
|
+
browser. This local listener is unauthenticated: other local processes can
|
|
37
|
+
control the profile outside MCP authorization and pause controls. Do not expose
|
|
38
|
+
or forward it; use a trusted host, not an untrusted multi-user machine.
|
|
39
|
+
|
|
31
40
|
Crash locks are deliberately not removed automatically: verify the exact prior
|
|
32
41
|
owner and Chrome processes are stopped before operator recovery. Retained crash
|
|
33
42
|
files are not automatically scavenged. Never remove directories by name prefix.
|
|
@@ -14,16 +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
20
|
import { setMaxListeners } from "node:events";
|
|
21
21
|
|
|
22
22
|
// cli/src/browser/lifecycle.ts
|
|
23
|
-
import
|
|
24
|
-
import
|
|
23
|
+
import fs3 from "node:fs/promises";
|
|
24
|
+
import path3 from "node:path";
|
|
25
25
|
import os2 from "node:os";
|
|
26
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";
|
|
27
33
|
import { chromium } from "playwright-core";
|
|
28
34
|
|
|
29
35
|
// cli/src/browser/cleanup.ts
|
|
@@ -45,41 +51,246 @@ function onceAsync(action) {
|
|
|
45
51
|
return () => result ??= Promise.resolve().then(action);
|
|
46
52
|
}
|
|
47
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
|
+
|
|
48
259
|
// cli/src/browser/recovery.ts
|
|
49
|
-
import
|
|
260
|
+
import fs2 from "node:fs/promises";
|
|
50
261
|
import { constants } from "node:fs";
|
|
51
|
-
import
|
|
262
|
+
import path2 from "node:path";
|
|
52
263
|
import os from "node:os";
|
|
53
|
-
import
|
|
264
|
+
import net2 from "node:net";
|
|
54
265
|
import { createHash } from "node:crypto";
|
|
55
266
|
import { execFile } from "node:child_process";
|
|
56
267
|
import { promisify } from "node:util";
|
|
57
268
|
function controlSocketPath(root, profile) {
|
|
58
|
-
return
|
|
269
|
+
return path2.join(root, `control-${createHash("sha256").update(profile).digest("hex").slice(0, 16)}.sock`);
|
|
59
270
|
}
|
|
60
271
|
var code = (e) => e.code;
|
|
61
272
|
var fail = (file, reason) => {
|
|
62
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.`);
|
|
63
274
|
};
|
|
64
275
|
async function directories(directory) {
|
|
65
|
-
let cursor =
|
|
66
|
-
for (const part of directory.slice(cursor.length).split(
|
|
67
|
-
cursor =
|
|
68
|
-
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);
|
|
69
280
|
if (!s.isDirectory() || s.isSymbolicLink())
|
|
70
281
|
fail(cursor, "unsafe directory ancestor");
|
|
71
282
|
}
|
|
72
283
|
}
|
|
73
284
|
async function privateDir(directory) {
|
|
74
285
|
await directories(directory);
|
|
75
|
-
const s = await
|
|
286
|
+
const s = await fs2.lstat(directory);
|
|
76
287
|
if (s.uid !== process.getuid?.() || (s.mode & 511) !== 448)
|
|
77
288
|
fail(directory, "directory must be owned by current user with mode 0700");
|
|
78
289
|
}
|
|
79
290
|
async function artifact(file, socket = false) {
|
|
80
291
|
let s;
|
|
81
292
|
try {
|
|
82
|
-
s = await
|
|
293
|
+
s = await fs2.lstat(file);
|
|
83
294
|
} catch (e) {
|
|
84
295
|
if (code(e) === "ENOENT")
|
|
85
296
|
return;
|
|
@@ -116,10 +327,10 @@ async function assertProfileStopped(profile) {
|
|
|
116
327
|
fail(profile, `possible surviving profile process: PID ${pid}`);
|
|
117
328
|
}
|
|
118
329
|
}
|
|
119
|
-
const singleton =
|
|
330
|
+
const singleton = path2.join(profile, "SingletonLock");
|
|
120
331
|
let s;
|
|
121
332
|
try {
|
|
122
|
-
s = await
|
|
333
|
+
s = await fs2.lstat(singleton);
|
|
123
334
|
} catch (e) {
|
|
124
335
|
if (code(e) === "ENOENT")
|
|
125
336
|
return;
|
|
@@ -127,14 +338,14 @@ async function assertProfileStopped(profile) {
|
|
|
127
338
|
}
|
|
128
339
|
if (!s.isSymbolicLink() || s.uid !== process.getuid?.())
|
|
129
340
|
fail(singleton, "unrecognized Chromium singleton lock");
|
|
130
|
-
const target = await
|
|
341
|
+
const target = await fs2.readlink(singleton), match = /^(.*)-(\d+)$/.exec(target);
|
|
131
342
|
if (!match || match[1] !== os.hostname() || !Number.isSafeInteger(Number(match[2])) || Number(match[2]) <= 0)
|
|
132
343
|
fail(singleton, "foreign or unrecognized Chromium owner");
|
|
133
344
|
dead(Number(match[2]), singleton);
|
|
134
345
|
}
|
|
135
346
|
async function refusedSocket(file) {
|
|
136
347
|
await new Promise((resolve, reject) => {
|
|
137
|
-
const socket =
|
|
348
|
+
const socket = net2.createConnection(file);
|
|
138
349
|
const finish = (error) => {
|
|
139
350
|
socket.destroy();
|
|
140
351
|
error ? reject(error) : resolve();
|
|
@@ -152,11 +363,11 @@ async function recoverProfile(root, name) {
|
|
|
152
363
|
throw new Error("Recovery is supported only on Linux and macOS");
|
|
153
364
|
if (!/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,47}$/.test(name))
|
|
154
365
|
throw new Error("Profile must be a simple name, not a path");
|
|
155
|
-
root =
|
|
156
|
-
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);
|
|
157
368
|
try {
|
|
158
369
|
await privateDir(root);
|
|
159
|
-
await privateDir(
|
|
370
|
+
await privateDir(path2.join(root, "profiles"));
|
|
160
371
|
await privateDir(profile);
|
|
161
372
|
const original = await artifact(lock), originalSocket = await artifact(socket, true);
|
|
162
373
|
if (!original) {
|
|
@@ -166,7 +377,7 @@ async function recoverProfile(root, name) {
|
|
|
166
377
|
}
|
|
167
378
|
if (original.size > 16384)
|
|
168
379
|
fail(lock, "oversized lock");
|
|
169
|
-
const handle = await
|
|
380
|
+
const handle = await fs2.open(lock, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
170
381
|
try {
|
|
171
382
|
if (!same(original, await handle.stat()))
|
|
172
383
|
fail(lock, "lock changed while opening");
|
|
@@ -181,11 +392,11 @@ async function recoverProfile(root, name) {
|
|
|
181
392
|
fail(lock, "invalid lock schema or mismatched exact profile (legacy 0.3.5 fields required)");
|
|
182
393
|
const validate = async () => {
|
|
183
394
|
await privateDir(root);
|
|
184
|
-
await privateDir(
|
|
395
|
+
await privateDir(path2.join(root, "profiles"));
|
|
185
396
|
await privateDir(profile);
|
|
186
397
|
dead(owner.pid, lock);
|
|
187
398
|
await assertProfileStopped(profile);
|
|
188
|
-
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)))
|
|
189
400
|
fail(lock, `artifact identity changed (socket ${socket})`);
|
|
190
401
|
if (originalSocket)
|
|
191
402
|
await refusedSocket(socket);
|
|
@@ -195,11 +406,11 @@ async function recoverProfile(root, name) {
|
|
|
195
406
|
};
|
|
196
407
|
await validate();
|
|
197
408
|
if (originalSocket)
|
|
198
|
-
await
|
|
409
|
+
await fs2.unlink(socket);
|
|
199
410
|
dead(owner.pid, lock);
|
|
200
411
|
if (!same(original, await handle.stat()) || !same(original, await artifact(lock)))
|
|
201
412
|
fail(lock, "lock changed before unlink");
|
|
202
|
-
await
|
|
413
|
+
await fs2.unlink(lock);
|
|
203
414
|
} finally {
|
|
204
415
|
await handle.close();
|
|
205
416
|
}
|
|
@@ -210,38 +421,38 @@ async function recoverProfile(root, name) {
|
|
|
210
421
|
|
|
211
422
|
// cli/src/browser/lifecycle.ts
|
|
212
423
|
function installationRoot() {
|
|
213
|
-
return
|
|
424
|
+
return path3.join(os2.homedir(), ".browser-mcp");
|
|
214
425
|
}
|
|
215
426
|
async function privateDirectory(directory) {
|
|
216
|
-
const absolute =
|
|
217
|
-
let cursor =
|
|
218
|
-
for (const piece of absolute.slice(cursor.length).split(
|
|
219
|
-
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);
|
|
220
431
|
try {
|
|
221
|
-
await
|
|
432
|
+
await fs3.mkdir(cursor, { mode: 448 });
|
|
222
433
|
} catch (e) {
|
|
223
434
|
if (e.code !== "EEXIST")
|
|
224
435
|
throw e;
|
|
225
436
|
}
|
|
226
|
-
const stat2 = await
|
|
437
|
+
const stat2 = await fs3.lstat(cursor);
|
|
227
438
|
if (stat2.isSymbolicLink() || !stat2.isDirectory())
|
|
228
439
|
throw new Error("Unsafe directory path");
|
|
229
440
|
}
|
|
230
|
-
const stat = await
|
|
441
|
+
const stat = await fs3.stat(absolute);
|
|
231
442
|
if (process.platform !== "win32" && ((stat.mode & 63) !== 0 || stat.uid !== process.getuid?.()))
|
|
232
443
|
throw new Error("Private directory must be owned by current user with mode 0700");
|
|
233
444
|
return absolute;
|
|
234
445
|
}
|
|
235
446
|
async function discoverChrome(override) {
|
|
236
|
-
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"];
|
|
237
448
|
for (const candidate of candidates) {
|
|
238
|
-
if (!
|
|
449
|
+
if (!path3.isAbsolute(candidate))
|
|
239
450
|
throw new Error("Chrome override must be an absolute executable path");
|
|
240
451
|
try {
|
|
241
|
-
const real = await
|
|
452
|
+
const real = await fs3.realpath(candidate), stat = await fs3.stat(real);
|
|
242
453
|
if (!stat.isFile())
|
|
243
454
|
continue;
|
|
244
|
-
await
|
|
455
|
+
await fs3.access(real, fs3.constants.X_OK);
|
|
245
456
|
return real;
|
|
246
457
|
} catch {}
|
|
247
458
|
}
|
|
@@ -254,37 +465,38 @@ async function launchDedicated(options = {}) {
|
|
|
254
465
|
if (!/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,47}$/.test(name))
|
|
255
466
|
throw new Error("Profile must be a simple name, not a path");
|
|
256
467
|
const root = await privateDirectory(options.root ?? installationRoot());
|
|
257
|
-
const profiles = await privateDirectory(
|
|
258
|
-
const profile =
|
|
468
|
+
const profiles = await privateDirectory(path3.join(root, "profiles"));
|
|
469
|
+
const profile = path3.join(profiles, options.ephemeral ? `ephemeral-${randomUUID()}` : name);
|
|
259
470
|
await privateDirectory(profile);
|
|
260
|
-
const profileStat = await
|
|
471
|
+
const profileStat = await fs3.lstat(profile);
|
|
261
472
|
options.signal?.throwIfAborted();
|
|
262
|
-
const lockPath =
|
|
473
|
+
const lockPath = path3.join(profile, "runtime.lock"), nonce = randomUUID(), instanceId = randomUUID();
|
|
263
474
|
let lock;
|
|
264
475
|
try {
|
|
265
|
-
lock = await
|
|
476
|
+
lock = await fs3.open(lockPath, "wx", 384);
|
|
266
477
|
} catch (error) {
|
|
267
478
|
if (error.code !== "EEXIST")
|
|
268
479
|
throw error;
|
|
269
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.`);
|
|
270
481
|
}
|
|
271
482
|
const lockStat = await lock.stat();
|
|
272
|
-
const runPath =
|
|
483
|
+
const runPath = path3.join(profile, `run-${instanceId}`);
|
|
273
484
|
const manifest = { instanceId, profile, runPath, lockPath, ephemeral: !!options.ephemeral, ownedPaths: [runPath, ...options.ephemeral ? [profile] : []] };
|
|
274
485
|
let context, launched = false, lockWritten = false;
|
|
486
|
+
let chrome;
|
|
275
487
|
let runStat;
|
|
276
488
|
const verifyProfile = async () => {
|
|
277
|
-
const stat = await
|
|
278
|
-
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)
|
|
279
491
|
throw new Error("Profile directory ownership changed; retained owned paths");
|
|
280
492
|
};
|
|
281
493
|
const verifyLock = async () => {
|
|
282
494
|
await verifyProfile();
|
|
283
|
-
const stat = await
|
|
495
|
+
const stat = await fs3.lstat(lockPath);
|
|
284
496
|
if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1 || stat.dev !== lockStat.dev || stat.ino !== lockStat.ino || stat.uid !== lockStat.uid || stat.mode & 63)
|
|
285
497
|
throw new Error("Profile lock ownership changed; retained owned paths");
|
|
286
498
|
if (lockWritten) {
|
|
287
|
-
const stored = JSON.parse(await
|
|
499
|
+
const stored = JSON.parse(await fs3.readFile(lockPath, "utf8"));
|
|
288
500
|
if (stored.nonce !== nonce || stored.instanceId !== instanceId || stored.pid !== process.pid || stored.profile !== profile)
|
|
289
501
|
throw new Error("Profile lock ownership changed; retained owned paths");
|
|
290
502
|
}
|
|
@@ -294,8 +506,9 @@ async function launchDedicated(options = {}) {
|
|
|
294
506
|
try {
|
|
295
507
|
await cleanupSteps([
|
|
296
508
|
["Chrome close", async () => {
|
|
297
|
-
if (
|
|
298
|
-
await
|
|
509
|
+
if (chrome) {
|
|
510
|
+
await chrome.close();
|
|
511
|
+
await assertProfileStopped(profile);
|
|
299
512
|
stopped = true;
|
|
300
513
|
}
|
|
301
514
|
}],
|
|
@@ -307,19 +520,19 @@ async function launchDedicated(options = {}) {
|
|
|
307
520
|
["Run directory", async () => {
|
|
308
521
|
if (!runStat)
|
|
309
522
|
return;
|
|
310
|
-
const stat = await
|
|
523
|
+
const stat = await fs3.lstat(runPath);
|
|
311
524
|
if (!stat.isDirectory() || stat.isSymbolicLink() || stat.dev !== runStat.dev || stat.ino !== runStat.ino || stat.uid !== runStat.uid)
|
|
312
525
|
throw new Error("Run directory ownership changed; retained path");
|
|
313
|
-
await
|
|
526
|
+
await fs3.rm(runPath, { recursive: true, force: true });
|
|
314
527
|
}],
|
|
315
528
|
["Profile lock", async () => {
|
|
316
529
|
await verifyLock();
|
|
317
|
-
await
|
|
530
|
+
await fs3.unlink(lockPath);
|
|
318
531
|
}]
|
|
319
532
|
]);
|
|
320
533
|
if (options.ephemeral) {
|
|
321
534
|
await verifyProfile();
|
|
322
|
-
await
|
|
535
|
+
await fs3.rm(profile, { recursive: true, force: true });
|
|
323
536
|
}
|
|
324
537
|
}]
|
|
325
538
|
]);
|
|
@@ -330,14 +543,15 @@ async function launchDedicated(options = {}) {
|
|
|
330
543
|
try {
|
|
331
544
|
await lock.writeFile(JSON.stringify({ pid: process.pid, nonce, instanceId, profile, ephemeral: !!options.ephemeral }));
|
|
332
545
|
lockWritten = true;
|
|
333
|
-
await
|
|
334
|
-
runStat = await
|
|
335
|
-
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 });
|
|
336
549
|
options.signal?.throwIfAborted();
|
|
337
550
|
const executablePath = await discoverChrome(options.chromePath);
|
|
338
551
|
options.signal?.throwIfAborted();
|
|
339
552
|
launched = true;
|
|
340
|
-
|
|
553
|
+
chrome = await launchOwnedChrome({ executablePath, profile, runPath, signal: options.signal });
|
|
554
|
+
context = chrome.context;
|
|
341
555
|
options.signal?.throwIfAborted();
|
|
342
556
|
return { context, instanceId, profile, runPath, close, manifest };
|
|
343
557
|
} catch (error) {
|
|
@@ -352,12 +566,12 @@ ${cleanupError instanceof Error ? cleanupError.message : cleanupError}`);
|
|
|
352
566
|
}
|
|
353
567
|
|
|
354
568
|
// cli/src/browser/control.ts
|
|
355
|
-
import
|
|
356
|
-
import
|
|
569
|
+
import fs4 from "node:fs/promises";
|
|
570
|
+
import path4 from "node:path";
|
|
357
571
|
async function listenControl(server, root, controlPath) {
|
|
358
|
-
const rootStat = await
|
|
359
|
-
const directory = await
|
|
360
|
-
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");
|
|
361
575
|
let socketStat, published = false;
|
|
362
576
|
const close = onceAsync(() => cleanupSteps([
|
|
363
577
|
["Control listener", async () => {
|
|
@@ -367,10 +581,10 @@ async function listenControl(server, root, controlPath) {
|
|
|
367
581
|
["Control pathname", async () => {
|
|
368
582
|
if (!published)
|
|
369
583
|
return;
|
|
370
|
-
const parent = await
|
|
371
|
-
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)
|
|
372
586
|
throw new Error(`Control root ownership changed; retained ${controlPath}`);
|
|
373
|
-
const stat = await
|
|
587
|
+
const stat = await fs4.lstat(controlPath).catch((error) => {
|
|
374
588
|
if (error.code !== "ENOENT")
|
|
375
589
|
throw error;
|
|
376
590
|
});
|
|
@@ -378,28 +592,28 @@ async function listenControl(server, root, controlPath) {
|
|
|
378
592
|
return;
|
|
379
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)
|
|
380
594
|
throw new Error(`Control socket ownership changed; retained ${controlPath}`);
|
|
381
|
-
await
|
|
595
|
+
await fs4.unlink(controlPath);
|
|
382
596
|
}],
|
|
383
597
|
["Private control directory", async () => {
|
|
384
|
-
const stat = await
|
|
385
|
-
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)
|
|
386
600
|
throw new Error(`Control directory ownership changed; retained ${directory}`);
|
|
387
|
-
await
|
|
388
|
-
await
|
|
601
|
+
await fs4.unlink(path4.join(directory, "ownership.json"));
|
|
602
|
+
await fs4.rmdir(directory);
|
|
389
603
|
}]
|
|
390
604
|
]));
|
|
391
605
|
try {
|
|
392
|
-
await
|
|
606
|
+
await fs4.writeFile(path4.join(directory, "ownership.json"), JSON.stringify({ pid: process.pid, controlPath, ownedPaths: [directory, boundPath] }), { mode: 384, flag: "wx" });
|
|
393
607
|
await new Promise((resolve, reject) => {
|
|
394
608
|
server.once("error", reject);
|
|
395
609
|
server.listen(boundPath, resolve);
|
|
396
610
|
});
|
|
397
|
-
socketStat = await
|
|
398
|
-
await
|
|
399
|
-
await
|
|
611
|
+
socketStat = await fs4.lstat(boundPath);
|
|
612
|
+
await fs4.chmod(boundPath, 384);
|
|
613
|
+
await fs4.link(boundPath, controlPath);
|
|
400
614
|
published = true;
|
|
401
|
-
await
|
|
402
|
-
socketStat = await
|
|
615
|
+
await fs4.unlink(boundPath);
|
|
616
|
+
socketStat = await fs4.lstat(controlPath);
|
|
403
617
|
return close;
|
|
404
618
|
} catch (error) {
|
|
405
619
|
try {
|
|
@@ -413,8 +627,8 @@ ${cleanupError}`);
|
|
|
413
627
|
}
|
|
414
628
|
|
|
415
629
|
// cli/src/browser/pairing.ts
|
|
416
|
-
import
|
|
417
|
-
import
|
|
630
|
+
import fs5 from "node:fs/promises";
|
|
631
|
+
import path5 from "node:path";
|
|
418
632
|
import { randomBytes, createHash as createHash2 } from "node:crypto";
|
|
419
633
|
import { setTimeout as delay } from "node:timers/promises";
|
|
420
634
|
function serverURL(raw) {
|
|
@@ -427,13 +641,13 @@ function serverURL(raw) {
|
|
|
427
641
|
}
|
|
428
642
|
async function credential(root, server, profile, signal) {
|
|
429
643
|
signal?.throwIfAborted();
|
|
430
|
-
const filename =
|
|
644
|
+
const filename = path5.join(root, `credential-${createHash2("sha256").update(`${server}
|
|
431
645
|
${profile}`).digest("hex").slice(0, 24)}.json`);
|
|
432
646
|
try {
|
|
433
|
-
const stat = await
|
|
647
|
+
const stat = await fs5.lstat(filename);
|
|
434
648
|
if (!stat.isFile() || stat.isSymbolicLink() || process.platform !== "win32" && stat.mode & 63)
|
|
435
649
|
throw new Error("Unsafe credential file");
|
|
436
|
-
const value = JSON.parse(await
|
|
650
|
+
const value = JSON.parse(await fs5.readFile(filename, "utf8"));
|
|
437
651
|
if (value.server !== server || !/^br_[\w-]+$/.test(value.token))
|
|
438
652
|
throw new Error("Invalid credential file");
|
|
439
653
|
return value.token;
|
|
@@ -463,7 +677,7 @@ ${profile}`).digest("hex").slice(0, 24)}.json`);
|
|
|
463
677
|
if (typeof token !== "string" || !/^br_[\w-]+$/.test(token))
|
|
464
678
|
throw new Error("Pairing did not return a browser credential");
|
|
465
679
|
signal?.throwIfAborted();
|
|
466
|
-
await
|
|
680
|
+
await fs5.writeFile(filename, JSON.stringify({ server, token }), { mode: 384, flag: "wx" });
|
|
467
681
|
return token;
|
|
468
682
|
}
|
|
469
683
|
throw new Error("Pairing expired");
|
|
@@ -528,8 +742,8 @@ function screenshotPoint(transform, current, delivered, point) {
|
|
|
528
742
|
}
|
|
529
743
|
|
|
530
744
|
// cli/src/browser/browser-runtime.ts
|
|
531
|
-
import
|
|
532
|
-
import
|
|
745
|
+
import fs8 from "node:fs";
|
|
746
|
+
import path7 from "node:path";
|
|
533
747
|
|
|
534
748
|
// cli/src/browser/upload-input.ts
|
|
535
749
|
var BROWSER_UPLOAD_CHUNK_BYTES = 1024 * 1024;
|
|
@@ -1031,8 +1245,8 @@ function preflightBrowserInput(action, raw) {
|
|
|
1031
1245
|
}
|
|
1032
1246
|
|
|
1033
1247
|
// cli/src/browser/upload-store.ts
|
|
1034
|
-
import
|
|
1035
|
-
import
|
|
1248
|
+
import fs6 from "node:fs";
|
|
1249
|
+
import path6 from "node:path";
|
|
1036
1250
|
import { createHash as createHash3 } from "node:crypto";
|
|
1037
1251
|
class BrowserUploadStore {
|
|
1038
1252
|
releaseTarget;
|
|
@@ -1042,8 +1256,8 @@ class BrowserUploadStore {
|
|
|
1042
1256
|
return;
|
|
1043
1257
|
}) {
|
|
1044
1258
|
this.releaseTarget = releaseTarget;
|
|
1045
|
-
|
|
1046
|
-
this.directory =
|
|
1259
|
+
fs6.mkdirSync(root, { recursive: true, mode: 448 });
|
|
1260
|
+
this.directory = fs6.mkdtempSync(path6.join(root, "run-"));
|
|
1047
1261
|
}
|
|
1048
1262
|
begin(id, tabId, files, target2) {
|
|
1049
1263
|
if (typeof id !== "string" || !/^[a-f0-9-]{36}$/.test(id) || this.uploads.has(id))
|
|
@@ -1051,20 +1265,20 @@ class BrowserUploadStore {
|
|
|
1051
1265
|
if (!Array.isArray(files) || files.length === 0 || files.length > 100)
|
|
1052
1266
|
throw new Error("Upload requires between 1 and 100 files.");
|
|
1053
1267
|
const metadata = files.map(validateUploadFile);
|
|
1054
|
-
const directory =
|
|
1268
|
+
const directory = fs6.mkdtempSync(path6.join(this.directory, "upload-"));
|
|
1055
1269
|
try {
|
|
1056
1270
|
const staged = metadata.map((file, index) => {
|
|
1057
|
-
const parent =
|
|
1058
|
-
|
|
1059
|
-
const filePath =
|
|
1060
|
-
|
|
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));
|
|
1061
1275
|
return { ...file, path: filePath, offset: 0, hash: createHash3("sha256") };
|
|
1062
1276
|
});
|
|
1063
1277
|
const timer = setTimeout(() => this.abort(id, tabId), 5 * 60 * 1000);
|
|
1064
1278
|
timer.unref();
|
|
1065
1279
|
this.uploads.set(id, { tabId, directory, files: staged, target: target2, attached: false, timer });
|
|
1066
1280
|
} catch (error) {
|
|
1067
|
-
|
|
1281
|
+
fs6.rmSync(directory, { recursive: true, force: true });
|
|
1068
1282
|
throw error;
|
|
1069
1283
|
}
|
|
1070
1284
|
}
|
|
@@ -1085,17 +1299,17 @@ class BrowserUploadStore {
|
|
|
1085
1299
|
const bytes = decodeUploadChunk(base64);
|
|
1086
1300
|
if (bytes.length === 0 || file.offset + bytes.length > file.size)
|
|
1087
1301
|
throw new Error("Upload chunk does not match the declared file size.");
|
|
1088
|
-
const fd =
|
|
1302
|
+
const fd = fs6.openSync(file.path, fs6.constants.O_WRONLY | fs6.constants.O_NOFOLLOW);
|
|
1089
1303
|
try {
|
|
1090
1304
|
let written = 0;
|
|
1091
1305
|
while (written < bytes.length) {
|
|
1092
|
-
const count =
|
|
1306
|
+
const count = fs6.writeSync(fd, bytes, written, bytes.length - written, file.offset + written);
|
|
1093
1307
|
if (!count)
|
|
1094
1308
|
throw new Error("Could not write upload chunk.");
|
|
1095
1309
|
written += count;
|
|
1096
1310
|
}
|
|
1097
1311
|
} finally {
|
|
1098
|
-
|
|
1312
|
+
fs6.closeSync(fd);
|
|
1099
1313
|
}
|
|
1100
1314
|
file.hash.update(bytes);
|
|
1101
1315
|
file.offset += bytes.length;
|
|
@@ -1129,7 +1343,7 @@ class BrowserUploadStore {
|
|
|
1129
1343
|
clearTimeout(upload.timer);
|
|
1130
1344
|
this.uploads.delete(id);
|
|
1131
1345
|
this.releaseTarget(upload.target);
|
|
1132
|
-
|
|
1346
|
+
fs6.rmSync(upload.directory, { recursive: true, force: true });
|
|
1133
1347
|
}
|
|
1134
1348
|
closeTab(tabId) {
|
|
1135
1349
|
for (const [id, upload] of this.uploads)
|
|
@@ -1139,7 +1353,7 @@ class BrowserUploadStore {
|
|
|
1139
1353
|
close() {
|
|
1140
1354
|
for (const [id, upload] of this.uploads)
|
|
1141
1355
|
this.remove(id, upload);
|
|
1142
|
-
|
|
1356
|
+
fs6.rmSync(this.directory, { recursive: true, force: true });
|
|
1143
1357
|
}
|
|
1144
1358
|
}
|
|
1145
1359
|
|
|
@@ -1317,7 +1531,7 @@ async function passwordSafeAriaSnapshot(page, options = {}) {
|
|
|
1317
1531
|
};
|
|
1318
1532
|
const document2 = { text: "", priorityRefs: [], matchRefs: [], matchCount: 0, frames: [], unavailableFrames: [] };
|
|
1319
1533
|
const timeoutError = () => new Error(`Timeout ${timeout2}ms exceeded building a password-safe browser snapshot.`);
|
|
1320
|
-
const
|
|
1534
|
+
const bounded2 = async (operation) => {
|
|
1321
1535
|
let timer;
|
|
1322
1536
|
try {
|
|
1323
1537
|
return await Promise.race([
|
|
@@ -1335,7 +1549,7 @@ async function passwordSafeAriaSnapshot(page, options = {}) {
|
|
|
1335
1549
|
throw new Error(UNAVAILABLE);
|
|
1336
1550
|
if (Date.now() >= deadline)
|
|
1337
1551
|
throw timeoutError();
|
|
1338
|
-
const captured = await
|
|
1552
|
+
const captured = await bounded2(currentFrame.selectors.callOnSelector(selector, { strict: true }, captureInUtilityWorld, frameOptions));
|
|
1339
1553
|
if (!captured) {
|
|
1340
1554
|
if (!isMainFrame) {
|
|
1341
1555
|
document2.unavailableFrames.push(framePath.at(-1));
|
|
@@ -1347,7 +1561,7 @@ async function passwordSafeAriaSnapshot(page, options = {}) {
|
|
|
1347
1561
|
}
|
|
1348
1562
|
if (options.frames?.length)
|
|
1349
1563
|
throw new Error("Snapshot frame selection failed. Each frames selector must match exactly one iframe with a loaded document.");
|
|
1350
|
-
await
|
|
1564
|
+
await bounded2(new Promise((resolve) => setTimeout(resolve, 50)));
|
|
1351
1565
|
return captureFrame(currentFrame, selector, frameOptions, true);
|
|
1352
1566
|
}
|
|
1353
1567
|
if (captured.info?.world !== "utility" || !isServerFrame(captured.frame))
|
|
@@ -1537,7 +1751,7 @@ async function openBackgroundTab(context, newWindow, timeoutMs = 1e4) {
|
|
|
1537
1751
|
const deadline = Date.now() + timeoutMs;
|
|
1538
1752
|
const sessions = new Set;
|
|
1539
1753
|
let stopped = false;
|
|
1540
|
-
const
|
|
1754
|
+
const bounded2 = async (operation) => {
|
|
1541
1755
|
let timer;
|
|
1542
1756
|
try {
|
|
1543
1757
|
return await Promise.race([
|
|
@@ -1584,9 +1798,9 @@ async function openBackgroundTab(context, newWindow, timeoutMs = 1e4) {
|
|
|
1584
1798
|
};
|
|
1585
1799
|
const onPage = (page) => {
|
|
1586
1800
|
(async () => {
|
|
1587
|
-
const session = await
|
|
1801
|
+
const session = await bounded2(attach(page));
|
|
1588
1802
|
try {
|
|
1589
|
-
const { targetInfo } = await
|
|
1803
|
+
const { targetInfo } = await bounded2(session.send("Target.getTargetInfo"));
|
|
1590
1804
|
if (!stopped && !page.isClosed()) {
|
|
1591
1805
|
candidates.set(targetInfo.targetId, page);
|
|
1592
1806
|
select();
|
|
@@ -1604,10 +1818,10 @@ async function openBackgroundTab(context, newWindow, timeoutMs = 1e4) {
|
|
|
1604
1818
|
try {
|
|
1605
1819
|
const previous = context.pages().findLast((page) => !page.isClosed());
|
|
1606
1820
|
if (!previous)
|
|
1607
|
-
return await
|
|
1608
|
-
const controller = await
|
|
1609
|
-
const { targetInfo } = await
|
|
1610
|
-
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", {
|
|
1611
1825
|
url: "about:blank",
|
|
1612
1826
|
background: true,
|
|
1613
1827
|
newWindow,
|
|
@@ -1616,12 +1830,12 @@ async function openBackgroundTab(context, newWindow, timeoutMs = 1e4) {
|
|
|
1616
1830
|
}));
|
|
1617
1831
|
targetId = created.targetId;
|
|
1618
1832
|
select();
|
|
1619
|
-
return await
|
|
1833
|
+
return await bounded2(found);
|
|
1620
1834
|
} finally {
|
|
1621
1835
|
stopped = true;
|
|
1622
1836
|
context.off("page", onPage);
|
|
1623
1837
|
context.off("close", onClose);
|
|
1624
|
-
await
|
|
1838
|
+
await bounded2(Promise.allSettled([...sessions].map(detach))).catch(() => {
|
|
1625
1839
|
return;
|
|
1626
1840
|
});
|
|
1627
1841
|
}
|
|
@@ -1697,7 +1911,7 @@ async function waitForBrowserCondition(page, input) {
|
|
|
1697
1911
|
code: "invalid_wait_target",
|
|
1698
1912
|
error: "Cannot resolve the wait target. Check target, scope and frame selectors with browser_read_page."
|
|
1699
1913
|
});
|
|
1700
|
-
const
|
|
1914
|
+
const bounded2 = async (promise) => {
|
|
1701
1915
|
let timer;
|
|
1702
1916
|
try {
|
|
1703
1917
|
return await Promise.race([
|
|
@@ -1737,7 +1951,7 @@ async function waitForBrowserCondition(page, input) {
|
|
|
1737
1951
|
if (page.isClosed())
|
|
1738
1952
|
return result(false, { code: "wait_tab_closed", error: "The tab closed before the condition matched." });
|
|
1739
1953
|
try {
|
|
1740
|
-
const observed = await
|
|
1954
|
+
const observed = await bounded2((async () => {
|
|
1741
1955
|
let handle = null;
|
|
1742
1956
|
let frameHandle = null;
|
|
1743
1957
|
let elements = [];
|
|
@@ -2576,13 +2790,13 @@ async function exportDocument(page, format) {
|
|
|
2576
2790
|
}
|
|
2577
2791
|
}
|
|
2578
2792
|
const text = await page.evaluate((format2) => {
|
|
2579
|
-
const
|
|
2793
|
+
const bounded2 = (text2) => {
|
|
2580
2794
|
if (text2.length > 20 * 1024 * 1024 || new TextEncoder().encode(text2).length > 20 * 1024 * 1024)
|
|
2581
2795
|
throw new Error("Document export exceeds 20 MiB.");
|
|
2582
2796
|
return text2;
|
|
2583
2797
|
};
|
|
2584
2798
|
if (format2 === "text")
|
|
2585
|
-
return
|
|
2799
|
+
return bounded2(document.body.innerText);
|
|
2586
2800
|
const clone = document.documentElement.cloneNode(true);
|
|
2587
2801
|
for (const el of clone.querySelectorAll('input[type="password"]'))
|
|
2588
2802
|
el.setAttribute("value", "[password]");
|
|
@@ -2592,7 +2806,7 @@ async function exportDocument(page, format) {
|
|
|
2592
2806
|
for (const attr of [...el.attributes])
|
|
2593
2807
|
if (/^on/i.test(attr.name) || attr.name === "srcdoc" || /^[\s\u0000-\u0020]*(javascript|vbscript):/i.test(attr.value))
|
|
2594
2808
|
el.removeAttribute(attr.name);
|
|
2595
|
-
return
|
|
2809
|
+
return bounded2(`<!doctype html>
|
|
2596
2810
|
` + clone.outerHTML);
|
|
2597
2811
|
}, format);
|
|
2598
2812
|
return {
|
|
@@ -2603,7 +2817,7 @@ async function exportDocument(page, format) {
|
|
|
2603
2817
|
}
|
|
2604
2818
|
|
|
2605
2819
|
// cli/src/browser/browser-tab-state.ts
|
|
2606
|
-
import
|
|
2820
|
+
import fs7 from "node:fs";
|
|
2607
2821
|
|
|
2608
2822
|
class BrowserTabState {
|
|
2609
2823
|
context;
|
|
@@ -2614,8 +2828,8 @@ class BrowserTabState {
|
|
|
2614
2828
|
constructor(context, filename) {
|
|
2615
2829
|
this.context = context;
|
|
2616
2830
|
this.filename = filename;
|
|
2617
|
-
if (
|
|
2618
|
-
const value = JSON.parse(
|
|
2831
|
+
if (fs7.existsSync(filename)) {
|
|
2832
|
+
const value = JSON.parse(fs7.readFileSync(filename, "utf8"));
|
|
2619
2833
|
if (value.version !== 1 || !value.targets || typeof value.targets !== "object")
|
|
2620
2834
|
throw new Error("Invalid browser tab state.");
|
|
2621
2835
|
this.stored = value.targets;
|
|
@@ -2623,8 +2837,8 @@ class BrowserTabState {
|
|
|
2623
2837
|
}
|
|
2624
2838
|
save() {
|
|
2625
2839
|
const tmp = `${this.filename}.${crypto.randomUUID()}.tmp`;
|
|
2626
|
-
|
|
2627
|
-
|
|
2840
|
+
fs7.writeFileSync(tmp, JSON.stringify({ version: 1, targets: this.stored }), { mode: 384, flag: "wx" });
|
|
2841
|
+
fs7.renameSync(tmp, this.filename);
|
|
2628
2842
|
}
|
|
2629
2843
|
resolve(page) {
|
|
2630
2844
|
let pending = this.pages.get(page);
|
|
@@ -2736,7 +2950,7 @@ class BrowserRuntime {
|
|
|
2736
2950
|
return;
|
|
2737
2951
|
});
|
|
2738
2952
|
});
|
|
2739
|
-
|
|
2953
|
+
fs8.mkdirSync(downloadsPath, { recursive: true });
|
|
2740
2954
|
this.tabState = new BrowserTabState(context, `${downloadsPath}.tabs.json`);
|
|
2741
2955
|
for (const page of context.pages())
|
|
2742
2956
|
this.track(page);
|
|
@@ -2795,23 +3009,23 @@ class BrowserRuntime {
|
|
|
2795
3009
|
return id;
|
|
2796
3010
|
}
|
|
2797
3011
|
safeDownloadFilename(suggestedFilename) {
|
|
2798
|
-
const basename =
|
|
3012
|
+
const basename = path7.basename(suggestedFilename).replace(/[\\/\0]/g, "-").trim();
|
|
2799
3013
|
if (!basename || basename === "." || basename === "..")
|
|
2800
3014
|
return "download";
|
|
2801
|
-
const extension =
|
|
2802
|
-
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";
|
|
2803
3017
|
while (Buffer.byteLength(`${stem}${extension}`) > 200)
|
|
2804
3018
|
stem = stem.slice(0, -1);
|
|
2805
3019
|
return `${stem || "download"}${extension}`;
|
|
2806
3020
|
}
|
|
2807
3021
|
availableDownloadPath(suggestedFilename) {
|
|
2808
3022
|
const filename = this.safeDownloadFilename(suggestedFilename);
|
|
2809
|
-
const extension =
|
|
3023
|
+
const extension = path7.extname(filename);
|
|
2810
3024
|
const stem = filename.slice(0, filename.length - extension.length) || "download";
|
|
2811
3025
|
for (let suffix = 1;; suffix += 1) {
|
|
2812
3026
|
const candidate = suffix === 1 ? filename : `${stem}-${suffix}${extension}`;
|
|
2813
|
-
const candidatePath =
|
|
2814
|
-
if (!
|
|
3027
|
+
const candidatePath = path7.join(this.downloadsPath, candidate);
|
|
3028
|
+
if (!fs8.existsSync(candidatePath))
|
|
2815
3029
|
return candidatePath;
|
|
2816
3030
|
}
|
|
2817
3031
|
}
|
|
@@ -2819,18 +3033,18 @@ class BrowserRuntime {
|
|
|
2819
3033
|
const failure = await download.failure();
|
|
2820
3034
|
if (failure)
|
|
2821
3035
|
throw new Error(failure);
|
|
2822
|
-
const temporary =
|
|
3036
|
+
const temporary = path7.join(this.downloadsPath, `.${crypto.randomUUID()}.download`);
|
|
2823
3037
|
let targetPath;
|
|
2824
3038
|
try {
|
|
2825
3039
|
await download.saveAs(temporary);
|
|
2826
3040
|
targetPath = this.availableDownloadPath(download.suggestedFilename());
|
|
2827
|
-
|
|
3041
|
+
fs8.renameSync(temporary, targetPath);
|
|
2828
3042
|
} finally {
|
|
2829
|
-
|
|
3043
|
+
fs8.rmSync(temporary, { force: true });
|
|
2830
3044
|
}
|
|
2831
|
-
process.stdout.write(`[r5d-browser] downloaded ${
|
|
3045
|
+
process.stdout.write(`[r5d-browser] downloaded ${path7.basename(targetPath)}
|
|
2832
3046
|
`);
|
|
2833
|
-
return { downloadId: this.downloadId(
|
|
3047
|
+
return { downloadId: this.downloadId(path7.basename(targetPath)) };
|
|
2834
3048
|
}
|
|
2835
3049
|
downloadId(filename) {
|
|
2836
3050
|
return Buffer.from(filename, "utf8").toString("base64url");
|
|
@@ -2839,13 +3053,13 @@ class BrowserRuntime {
|
|
|
2839
3053
|
if (typeof downloadId !== "string" || !downloadId)
|
|
2840
3054
|
throw new Error("downloadId is required.");
|
|
2841
3055
|
const filename = Buffer.from(downloadId, "base64url").toString("utf8");
|
|
2842
|
-
if (this.downloadId(filename) !== downloadId || filename !==
|
|
3056
|
+
if (this.downloadId(filename) !== downloadId || filename !== path7.basename(filename) || filename.includes("\x00")) {
|
|
2843
3057
|
throw new Error("Invalid downloadId.");
|
|
2844
3058
|
}
|
|
2845
|
-
const filePath =
|
|
3059
|
+
const filePath = path7.join(this.downloadsPath, filename);
|
|
2846
3060
|
let stats;
|
|
2847
3061
|
try {
|
|
2848
|
-
stats =
|
|
3062
|
+
stats = fs8.lstatSync(filePath);
|
|
2849
3063
|
} catch {
|
|
2850
3064
|
throw new Error(`Browser download ${downloadId} no longer exists.`);
|
|
2851
3065
|
}
|
|
@@ -2854,7 +3068,7 @@ class BrowserRuntime {
|
|
|
2854
3068
|
return { filename, filePath, stats };
|
|
2855
3069
|
}
|
|
2856
3070
|
async listDownloads() {
|
|
2857
|
-
return
|
|
3071
|
+
return fs8.readdirSync(this.downloadsPath, { withFileTypes: true }).flatMap((entry) => {
|
|
2858
3072
|
if (!entry.isFile() || entry.name.startsWith("."))
|
|
2859
3073
|
return [];
|
|
2860
3074
|
const { filename, stats } = this.resolveDownload(this.downloadId(entry.name));
|
|
@@ -2878,20 +3092,20 @@ class BrowserRuntime {
|
|
|
2878
3092
|
throw new Error("Invalid download chunk size.");
|
|
2879
3093
|
const chunkSize = Math.min(requestedBytes, MAX_DOWNLOAD_CHUNK_BYTES, stats.size - offset);
|
|
2880
3094
|
const bytes = Buffer.alloc(chunkSize);
|
|
2881
|
-
const handle =
|
|
3095
|
+
const handle = fs8.openSync(filePath, fs8.constants.O_RDONLY | fs8.constants.O_NOFOLLOW);
|
|
2882
3096
|
let bytesRead = 0;
|
|
2883
3097
|
try {
|
|
2884
|
-
const openedStats =
|
|
3098
|
+
const openedStats = fs8.fstatSync(handle);
|
|
2885
3099
|
if (!openedStats.isFile() || openedStats.dev !== stats.dev || openedStats.ino !== stats.ino) {
|
|
2886
3100
|
throw new Error("Browser download changed before it could be read.");
|
|
2887
3101
|
}
|
|
2888
|
-
bytesRead =
|
|
2889
|
-
const completedStats =
|
|
3102
|
+
bytesRead = fs8.readSync(handle, bytes, 0, chunkSize, offset);
|
|
3103
|
+
const completedStats = fs8.fstatSync(handle);
|
|
2890
3104
|
if (completedStats.size !== stats.size || completedStats.mtimeMs !== stats.mtimeMs) {
|
|
2891
3105
|
throw new Error("Browser download changed while it was being read.");
|
|
2892
3106
|
}
|
|
2893
3107
|
} finally {
|
|
2894
|
-
|
|
3108
|
+
fs8.closeSync(handle);
|
|
2895
3109
|
}
|
|
2896
3110
|
const nextOffset = offset + bytesRead;
|
|
2897
3111
|
return {
|
|
@@ -3313,9 +3527,9 @@ class BrowserRuntime {
|
|
|
3313
3527
|
return { tabId, exported: false, code: "export_too_large" };
|
|
3314
3528
|
const exports = files.map((file) => {
|
|
3315
3529
|
const target2 = this.availableDownloadPath(`${crypto.randomUUID()}-${file.filename}`);
|
|
3316
|
-
|
|
3530
|
+
fs8.writeFileSync(target2, file.bytes, { flag: "wx", mode: 384 });
|
|
3317
3531
|
return {
|
|
3318
|
-
downloadId: this.downloadId(
|
|
3532
|
+
downloadId: this.downloadId(path7.basename(target2)),
|
|
3319
3533
|
filename: file.filename,
|
|
3320
3534
|
size: file.bytes.length,
|
|
3321
3535
|
mimeType: file.mimeType
|
|
@@ -4050,8 +4264,8 @@ class NativeRuntime {
|
|
|
4050
4264
|
// cli/src/runtime/relay.ts
|
|
4051
4265
|
import WebSocket2 from "ws";
|
|
4052
4266
|
import { createHash as createHash5, randomUUID as randomUUID2 } from "node:crypto";
|
|
4053
|
-
import
|
|
4054
|
-
import
|
|
4267
|
+
import fs9 from "node:fs/promises";
|
|
4268
|
+
import path8 from "node:path";
|
|
4055
4269
|
|
|
4056
4270
|
// cli/src/live/producer.ts
|
|
4057
4271
|
import WebSocket from "ws";
|
|
@@ -4151,7 +4365,7 @@ class CaptureTimeout extends Error {
|
|
|
4151
4365
|
this.stage = stage;
|
|
4152
4366
|
}
|
|
4153
4367
|
}
|
|
4154
|
-
async function
|
|
4368
|
+
async function bounded2(stage, operation) {
|
|
4155
4369
|
let timer;
|
|
4156
4370
|
try {
|
|
4157
4371
|
return await Promise.race([operation, new Promise((_, reject) => {
|
|
@@ -4257,8 +4471,8 @@ class NativeLiveProducer {
|
|
|
4257
4471
|
const cdp = this.cdp;
|
|
4258
4472
|
this.cdp = undefined;
|
|
4259
4473
|
if (cdp) {
|
|
4260
|
-
await
|
|
4261
|
-
await
|
|
4474
|
+
await bounded2("stop_screencast", cdp.send("Page.stopScreencast")).catch(() => {});
|
|
4475
|
+
await bounded2("detach", cdp.detach()).catch(() => {});
|
|
4262
4476
|
}
|
|
4263
4477
|
}
|
|
4264
4478
|
async reconcile(generation) {
|
|
@@ -4287,7 +4501,7 @@ class NativeLiveProducer {
|
|
|
4287
4501
|
const initialNav = this.navSeq;
|
|
4288
4502
|
let authorized = false;
|
|
4289
4503
|
try {
|
|
4290
|
-
authorized = await
|
|
4504
|
+
authorized = await bounded2("authorize", this.options.authorizePage(page));
|
|
4291
4505
|
} catch (error) {
|
|
4292
4506
|
await this.teardown();
|
|
4293
4507
|
if (generation === this.generation)
|
|
@@ -4350,12 +4564,12 @@ class NativeLiveProducer {
|
|
|
4350
4564
|
let abandoned = false;
|
|
4351
4565
|
const attaching = this.options.context.newCDPSession(page).then((session) => {
|
|
4352
4566
|
if (abandoned)
|
|
4353
|
-
|
|
4567
|
+
bounded2("detach", session.detach()).catch(() => {});
|
|
4354
4568
|
return session;
|
|
4355
4569
|
});
|
|
4356
4570
|
let cdp;
|
|
4357
4571
|
try {
|
|
4358
|
-
cdp = await
|
|
4572
|
+
cdp = await bounded2("attach", attaching);
|
|
4359
4573
|
} catch (error) {
|
|
4360
4574
|
abandoned = true;
|
|
4361
4575
|
throw error;
|
|
@@ -4389,7 +4603,7 @@ class NativeLiveProducer {
|
|
|
4389
4603
|
const nav = this.navSeq;
|
|
4390
4604
|
(async () => {
|
|
4391
4605
|
try {
|
|
4392
|
-
const allowed2 = await
|
|
4606
|
+
const allowed2 = await bounded2("frame_authorize", this.options.authorizePage(page));
|
|
4393
4607
|
if (generation !== this.generation || nav !== this.navSeq || this.closed || !this.enabled || !this.active || this.socket !== ws || ws.readyState !== WebSocket.OPEN)
|
|
4394
4608
|
return;
|
|
4395
4609
|
if (!allowed2 || this.options.getPage(tab) !== page) {
|
|
@@ -4405,11 +4619,11 @@ class NativeLiveProducer {
|
|
|
4405
4619
|
})();
|
|
4406
4620
|
});
|
|
4407
4621
|
const startNav = this.navSeq;
|
|
4408
|
-
if (!await
|
|
4622
|
+
if (!await bounded2("authorize", this.options.authorizePage(page)) || generation !== this.generation || startNav !== this.navSeq) {
|
|
4409
4623
|
await this.teardown();
|
|
4410
4624
|
return;
|
|
4411
4625
|
}
|
|
4412
|
-
await
|
|
4626
|
+
await bounded2("start_screencast", cdp.send("Page.startScreencast", { format: "jpeg", quality: 60, maxWidth: 1600, maxHeight: 1000, everyNthFrame: 1 }));
|
|
4413
4627
|
if (generation !== this.generation) {
|
|
4414
4628
|
await this.teardown();
|
|
4415
4629
|
return;
|
|
@@ -4515,7 +4729,7 @@ class Relay {
|
|
|
4515
4729
|
heartbeat.unref();
|
|
4516
4730
|
socket.once("open", () => {
|
|
4517
4731
|
this.state = "authenticating";
|
|
4518
|
-
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 } } }));
|
|
4519
4733
|
});
|
|
4520
4734
|
socket.on("message", (bytes, binary) => {
|
|
4521
4735
|
if (binary || Buffer.byteLength(bytes.toString()) > LIMIT) {
|
|
@@ -4634,20 +4848,20 @@ class Relay {
|
|
|
4634
4848
|
if (message.op === "export_page" && Array.isArray(result?.exports))
|
|
4635
4849
|
for (const item of result.exports) {
|
|
4636
4850
|
const filename = Buffer.from(item.downloadId, "base64url").toString("utf8");
|
|
4637
|
-
if (
|
|
4851
|
+
if (path8.basename(filename) !== filename)
|
|
4638
4852
|
throw new Error("Invalid export file");
|
|
4639
|
-
const filenamePath =
|
|
4640
|
-
const stat = await
|
|
4853
|
+
const filenamePath = path8.join(this.previewDirectory, filename);
|
|
4854
|
+
const stat = await fs9.lstat(filenamePath);
|
|
4641
4855
|
if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 20 * 1024 * 1024)
|
|
4642
4856
|
throw new Error("Invalid export file");
|
|
4643
|
-
blobs.push(await this.upload(await
|
|
4644
|
-
await
|
|
4857
|
+
blobs.push(await this.upload(await fs9.readFile(filenamePath), "export", item.filename, item.mimeType));
|
|
4858
|
+
await fs9.unlink(filenamePath);
|
|
4645
4859
|
delete item.downloadId;
|
|
4646
4860
|
}
|
|
4647
4861
|
if (message.op === "run_js" && Array.isArray(result?.artifacts)) {
|
|
4648
4862
|
for (const artifact2 of result.artifacts)
|
|
4649
|
-
blobs.push(await this.upload(Buffer.from(artifact2.content), "artifact",
|
|
4650
|
-
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) }));
|
|
4651
4865
|
}
|
|
4652
4866
|
if (Buffer.byteLength(JSON.stringify(result)) > 1800000)
|
|
4653
4867
|
throw new Error("Result budget exceeded");
|
|
@@ -5038,9 +5252,9 @@ async function createDataPlugin(access, options) {
|
|
|
5038
5252
|
r = create(scope, "download", LIMITS.file, download.suggestedFilename());
|
|
5039
5253
|
r.tabId = tabId;
|
|
5040
5254
|
r.generation = generation;
|
|
5041
|
-
const
|
|
5042
|
-
r.path =
|
|
5043
|
-
owned.add(
|
|
5255
|
+
const path9 = join(options.directory, r.id);
|
|
5256
|
+
r.path = path9;
|
|
5257
|
+
owned.add(path9);
|
|
5044
5258
|
const source = await download.createReadStream();
|
|
5045
5259
|
if (!source)
|
|
5046
5260
|
throw new Error("Download unavailable");
|
|
@@ -5054,17 +5268,17 @@ async function createDataPlugin(access, options) {
|
|
|
5054
5268
|
const timeout2 = setTimeout(() => r.abort.abort(), LIMITS.duration);
|
|
5055
5269
|
timeout2.unref?.();
|
|
5056
5270
|
try {
|
|
5057
|
-
await pipeline(source, bound, createWriteStream(
|
|
5271
|
+
await pipeline(source, bound, createWriteStream(path9, { flags: "wx", mode: 384 }), { signal: r.abort.signal });
|
|
5058
5272
|
} finally {
|
|
5059
5273
|
clearTimeout(timeout2);
|
|
5060
5274
|
}
|
|
5061
|
-
await chmod(
|
|
5062
|
-
const stat = await lstat(
|
|
5275
|
+
await chmod(path9, 384);
|
|
5276
|
+
const stat = await lstat(path9);
|
|
5063
5277
|
if (!stat.isFile() || stat.size > LIMITS.file)
|
|
5064
5278
|
throw new Error("Download limit");
|
|
5065
5279
|
r.size = stat.size;
|
|
5066
5280
|
const hash = createHash6("sha256");
|
|
5067
|
-
for await (const chunk of createReadStream(
|
|
5281
|
+
for await (const chunk of createReadStream(path9))
|
|
5068
5282
|
hash.update(chunk);
|
|
5069
5283
|
r.hash = hash.digest("hex");
|
|
5070
5284
|
if (r.abort.signal.aborted)
|
|
@@ -5204,7 +5418,7 @@ async function runBrowser(args) {
|
|
|
5204
5418
|
console.log(`browser-mcp browser start [--server https://browser-mcp.click] [--profile work] [--profile personal ...] [--ephemeral] [--chrome-path /path/to/chrome] [--live-view]
|
|
5205
5419
|
browser-mcp browser status|pause|resume|stop|recover [--profile work]
|
|
5206
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.
|
|
5207
|
-
Dedicated Chrome only. Foreground
|
|
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.`);
|
|
5208
5422
|
return;
|
|
5209
5423
|
}
|
|
5210
5424
|
if (!["start", "status", "pause", "resume", "stop", "recover"].includes(command))
|
|
@@ -5234,7 +5448,7 @@ Dedicated Chrome only. Foreground pipe lifecycle: stopping the CLI closes Chrome
|
|
|
5234
5448
|
return;
|
|
5235
5449
|
}
|
|
5236
5450
|
await new Promise((resolve, reject) => {
|
|
5237
|
-
const socket =
|
|
5451
|
+
const socket = net3.connect(controlPath);
|
|
5238
5452
|
socket.setTimeout(5000, () => socket.destroy(new Error("Local control timeout")));
|
|
5239
5453
|
socket.once("connect", () => socket.write(JSON.stringify({ command }) + `
|
|
5240
5454
|
`));
|
|
@@ -5251,7 +5465,7 @@ Dedicated Chrome only. Foreground pipe lifecycle: stopping the CLI closes Chrome
|
|
|
5251
5465
|
const server = serverURL(options.server ?? "https://browser-mcp.click");
|
|
5252
5466
|
for (const profile of profiles) {
|
|
5253
5467
|
const controlPath = controlSocketPath(root, profile);
|
|
5254
|
-
const previousSocket = await
|
|
5468
|
+
const previousSocket = await fs10.lstat(controlPath).catch((error) => {
|
|
5255
5469
|
if (error.code !== "ENOENT")
|
|
5256
5470
|
throw error;
|
|
5257
5471
|
});
|
|
@@ -5321,13 +5535,13 @@ async function startProfile(root, server, profile, options, groupSignal) {
|
|
|
5321
5535
|
session = await launchDedicated({ root, profile, ephemeral: !!options.ephemeral, chromePath: options["chrome-path"], signal: abort.signal });
|
|
5322
5536
|
session.context.once("close", requestStop);
|
|
5323
5537
|
abort.signal.throwIfAborted();
|
|
5324
|
-
stopQuota = await enforceDownloadQuota(session.context,
|
|
5538
|
+
stopQuota = await enforceDownloadQuota(session.context, path9.join(session.runPath, "chrome-downloads"));
|
|
5325
5539
|
abort.signal.throwIfAborted();
|
|
5326
5540
|
const token = await credential(root, server, profile, abort.signal);
|
|
5327
5541
|
abort.signal.throwIfAborted();
|
|
5328
|
-
const previews =
|
|
5542
|
+
const previews = path9.join(session.runPath, "previews");
|
|
5329
5543
|
runtime = new NativeRuntime(session.context, session.instanceId, previews, server);
|
|
5330
|
-
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:" }));
|
|
5331
5545
|
abort.signal.throwIfAborted();
|
|
5332
5546
|
runtime.plugins.push(createForwardPlugin({ serverUrl: server }));
|
|
5333
5547
|
relay = new Relay(runtime, server, token, previews, !!options.liveView);
|
|
@@ -5338,7 +5552,7 @@ async function startProfile(root, server, profile, options, groupSignal) {
|
|
|
5338
5552
|
await route.continue();
|
|
5339
5553
|
});
|
|
5340
5554
|
abort.signal.throwIfAborted();
|
|
5341
|
-
local =
|
|
5555
|
+
local = net3.createServer((socket) => {
|
|
5342
5556
|
clients.add(socket);
|
|
5343
5557
|
socket.once("close", () => clients.delete(socket));
|
|
5344
5558
|
socket.setTimeout(2000, () => socket.destroy());
|
|
@@ -5368,7 +5582,7 @@ async function startProfile(root, server, profile, options, groupSignal) {
|
|
|
5368
5582
|
return;
|
|
5369
5583
|
} else if (cmd !== "status")
|
|
5370
5584
|
throw new Error("Invalid command");
|
|
5371
|
-
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 }) + `
|
|
5372
5586
|
`);
|
|
5373
5587
|
})().catch(() => socket.destroy());
|
|
5374
5588
|
});
|
package/dist/main.js
CHANGED
|
@@ -8,7 +8,7 @@ var args = process.argv.slice(2);
|
|
|
8
8
|
var command = args.shift();
|
|
9
9
|
async function main() {
|
|
10
10
|
if (!command || command === "--help" || command === "help") {
|
|
11
|
-
console.log(`@ricsam/browser-mcp 0.3.
|
|
11
|
+
console.log(`@ricsam/browser-mcp 0.3.10
|
|
12
12
|
Usage: browser-mcp browser start|status|pause|resume|stop|recover [options]
|
|
13
13
|
browser-mcp files upload|download [options]
|
|
14
14
|
browser-mcp secrets export|exec [options]
|
|
@@ -18,11 +18,11 @@ Browser dependencies load only for browser commands. No automatic Chrome downloa
|
|
|
18
18
|
return;
|
|
19
19
|
}
|
|
20
20
|
if (command === "--version") {
|
|
21
|
-
console.log("0.3.
|
|
21
|
+
console.log("0.3.10");
|
|
22
22
|
return;
|
|
23
23
|
}
|
|
24
24
|
if (command === "browser")
|
|
25
|
-
return (await import("./chunk-
|
|
25
|
+
return (await import("./chunk-3f5mve2t.js")).runBrowser(args);
|
|
26
26
|
if (command === "files")
|
|
27
27
|
return (await import("./chunk-xgk37h9a.js")).runFilesCommand(args);
|
|
28
28
|
if (command === "secrets")
|