@ricsam/browser-mcp 0.3.5 → 0.3.7
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 +81 -1
- package/dist/{chunk-jdnp1ajq.js → chunk-rshfr4hg.js} +599 -206
- package/dist/main.js +5 -4
- package/package.json +1 -1
|
@@ -14,50 +14,234 @@ import {
|
|
|
14
14
|
import"./chunk-1sjcwr28.js";
|
|
15
15
|
|
|
16
16
|
// cli/src/browser/main.ts
|
|
17
|
-
import
|
|
18
|
-
import
|
|
19
|
-
import
|
|
20
|
-
import {
|
|
17
|
+
import fs9 from "node:fs/promises";
|
|
18
|
+
import path8 from "node:path";
|
|
19
|
+
import net2 from "node:net";
|
|
20
|
+
import { setMaxListeners } from "node:events";
|
|
21
21
|
|
|
22
22
|
// cli/src/browser/lifecycle.ts
|
|
23
|
+
import fs2 from "node:fs/promises";
|
|
24
|
+
import path2 from "node:path";
|
|
25
|
+
import os2 from "node:os";
|
|
26
|
+
import { randomUUID } from "node:crypto";
|
|
27
|
+
import { chromium } from "playwright-core";
|
|
28
|
+
|
|
29
|
+
// cli/src/browser/cleanup.ts
|
|
30
|
+
async function cleanupSteps(steps) {
|
|
31
|
+
const errors = [];
|
|
32
|
+
for (const [name, step] of steps) {
|
|
33
|
+
try {
|
|
34
|
+
await step();
|
|
35
|
+
} catch (cause) {
|
|
36
|
+
errors.push(new Error(`${name}: ${cause instanceof Error ? cause.message : String(cause)}`, { cause }));
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
if (errors.length)
|
|
40
|
+
throw new AggregateError(errors, errors.map((error) => error.message).join(`
|
|
41
|
+
`));
|
|
42
|
+
}
|
|
43
|
+
function onceAsync(action) {
|
|
44
|
+
let result;
|
|
45
|
+
return () => result ??= Promise.resolve().then(action);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// cli/src/browser/recovery.ts
|
|
23
49
|
import fs from "node:fs/promises";
|
|
50
|
+
import { constants } from "node:fs";
|
|
24
51
|
import path from "node:path";
|
|
25
52
|
import os from "node:os";
|
|
26
|
-
import
|
|
27
|
-
import {
|
|
53
|
+
import net from "node:net";
|
|
54
|
+
import { createHash } from "node:crypto";
|
|
55
|
+
import { execFile } from "node:child_process";
|
|
56
|
+
import { promisify } from "node:util";
|
|
57
|
+
function controlSocketPath(root, profile) {
|
|
58
|
+
return path.join(root, `control-${createHash("sha256").update(profile).digest("hex").slice(0, 16)}.sock`);
|
|
59
|
+
}
|
|
60
|
+
var code = (e) => e.code;
|
|
61
|
+
var fail = (file, reason) => {
|
|
62
|
+
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
|
+
};
|
|
64
|
+
async function directories(directory) {
|
|
65
|
+
let cursor = path.parse(directory).root;
|
|
66
|
+
for (const part of directory.slice(cursor.length).split(path.sep).filter(Boolean)) {
|
|
67
|
+
cursor = path.join(cursor, part);
|
|
68
|
+
const s = await fs.lstat(cursor);
|
|
69
|
+
if (!s.isDirectory() || s.isSymbolicLink())
|
|
70
|
+
fail(cursor, "unsafe directory ancestor");
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
async function privateDir(directory) {
|
|
74
|
+
await directories(directory);
|
|
75
|
+
const s = await fs.lstat(directory);
|
|
76
|
+
if (s.uid !== process.getuid?.() || (s.mode & 511) !== 448)
|
|
77
|
+
fail(directory, "directory must be owned by current user with mode 0700");
|
|
78
|
+
}
|
|
79
|
+
async function artifact(file, socket = false) {
|
|
80
|
+
let s;
|
|
81
|
+
try {
|
|
82
|
+
s = await fs.lstat(file);
|
|
83
|
+
} catch (e) {
|
|
84
|
+
if (code(e) === "ENOENT")
|
|
85
|
+
return;
|
|
86
|
+
throw e;
|
|
87
|
+
}
|
|
88
|
+
if (s.isSymbolicLink() || !(socket ? s.isSocket() : s.isFile()) || s.nlink !== 1 || s.uid !== process.getuid?.() || (s.mode & 63) !== 0)
|
|
89
|
+
fail(file, "unsafe artifact type, links, owner or permissions");
|
|
90
|
+
return s;
|
|
91
|
+
}
|
|
92
|
+
function dead(pid, file) {
|
|
93
|
+
try {
|
|
94
|
+
process.kill(pid, 0);
|
|
95
|
+
} catch (e) {
|
|
96
|
+
if (code(e) === "ESRCH")
|
|
97
|
+
return;
|
|
98
|
+
fail(file, `cannot prove PID ${pid} absent (${code(e)})`);
|
|
99
|
+
}
|
|
100
|
+
fail(file, `PID ${pid} exists (including possible PID reuse)`);
|
|
101
|
+
}
|
|
102
|
+
async function assertProfileStopped(profile) {
|
|
103
|
+
let stdout;
|
|
104
|
+
try {
|
|
105
|
+
({ stdout } = await promisify(execFile)("ps", ["-axww", "-o", "pid=,command="], { timeout: 5000, maxBuffer: 16 * 1024 * 1024, env: { ...process.env, LC_ALL: "C" } }));
|
|
106
|
+
} catch {
|
|
107
|
+
return fail(profile, "process scan failed or was truncated");
|
|
108
|
+
}
|
|
109
|
+
const lines = stdout.trim().split(`
|
|
110
|
+
`);
|
|
111
|
+
if (!lines.length || lines.some((line) => !/^\s*\d+\s+\S/.test(line)))
|
|
112
|
+
fail(profile, "uncertain process scan");
|
|
113
|
+
for (const line of lines) {
|
|
114
|
+
const pid = Number(line.trim().split(/\s+/, 1)[0]);
|
|
115
|
+
if (pid !== process.pid && (line.includes(profile) || /(?:chrome|chromium)/i.test(line) && /--user-data-dir(?:\s|=)/.test(line) && !line.includes("--user-data-dir=/"))) {
|
|
116
|
+
fail(profile, `possible surviving profile process: PID ${pid}`);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
const singleton = path.join(profile, "SingletonLock");
|
|
120
|
+
let s;
|
|
121
|
+
try {
|
|
122
|
+
s = await fs.lstat(singleton);
|
|
123
|
+
} catch (e) {
|
|
124
|
+
if (code(e) === "ENOENT")
|
|
125
|
+
return;
|
|
126
|
+
throw e;
|
|
127
|
+
}
|
|
128
|
+
if (!s.isSymbolicLink() || s.uid !== process.getuid?.())
|
|
129
|
+
fail(singleton, "unrecognized Chromium singleton lock");
|
|
130
|
+
const target = await fs.readlink(singleton), match = /^(.*)-(\d+)$/.exec(target);
|
|
131
|
+
if (!match || match[1] !== os.hostname() || !Number.isSafeInteger(Number(match[2])) || Number(match[2]) <= 0)
|
|
132
|
+
fail(singleton, "foreign or unrecognized Chromium owner");
|
|
133
|
+
dead(Number(match[2]), singleton);
|
|
134
|
+
}
|
|
135
|
+
async function refusedSocket(file) {
|
|
136
|
+
await new Promise((resolve, reject) => {
|
|
137
|
+
const socket = net.createConnection(file);
|
|
138
|
+
const finish = (error) => {
|
|
139
|
+
socket.destroy();
|
|
140
|
+
error ? reject(error) : resolve();
|
|
141
|
+
};
|
|
142
|
+
socket.setTimeout(1000, () => finish(new Error(`Recovery refused: socket probe timed out: ${file}`)));
|
|
143
|
+
socket.once("connect", () => finish(new Error(`Recovery refused: live control listener: ${file}`)));
|
|
144
|
+
socket.once("error", (e) => code(e) === "ECONNREFUSED" ? finish() : finish(new Error(`Recovery refused: uncertain socket probe (${code(e)}): ${file}`)));
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
function same(a, b) {
|
|
148
|
+
return a === undefined ? b === undefined : b !== undefined && a.dev === b.dev && a.ino === b.ino && a.ctimeMs === b.ctimeMs && a.size === b.size && a.mode === b.mode && a.uid === b.uid;
|
|
149
|
+
}
|
|
150
|
+
async function recoverProfile(root, name) {
|
|
151
|
+
if (!["linux", "darwin"].includes(process.platform))
|
|
152
|
+
throw new Error("Recovery is supported only on Linux and macOS");
|
|
153
|
+
if (!/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,47}$/.test(name))
|
|
154
|
+
throw new Error("Profile must be a simple name, not a path");
|
|
155
|
+
root = path.resolve(root);
|
|
156
|
+
const profile = path.join(root, "profiles", name), lock = path.join(profile, "runtime.lock"), socket = controlSocketPath(root, name);
|
|
157
|
+
try {
|
|
158
|
+
await privateDir(root);
|
|
159
|
+
await privateDir(path.join(root, "profiles"));
|
|
160
|
+
await privateDir(profile);
|
|
161
|
+
const original = await artifact(lock), originalSocket = await artifact(socket, true);
|
|
162
|
+
if (!original) {
|
|
163
|
+
if (originalSocket)
|
|
164
|
+
fail(socket, `socket has no provenance because ${lock} is absent`);
|
|
165
|
+
return;
|
|
166
|
+
}
|
|
167
|
+
if (original.size > 16384)
|
|
168
|
+
fail(lock, "oversized lock");
|
|
169
|
+
const handle = await fs.open(lock, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
170
|
+
try {
|
|
171
|
+
if (!same(original, await handle.stat()))
|
|
172
|
+
fail(lock, "lock changed while opening");
|
|
173
|
+
const raw = await handle.readFile("utf8");
|
|
174
|
+
let owner;
|
|
175
|
+
try {
|
|
176
|
+
owner = JSON.parse(raw);
|
|
177
|
+
} catch {
|
|
178
|
+
fail(lock, "invalid lock JSON");
|
|
179
|
+
}
|
|
180
|
+
if (!owner || typeof owner !== "object" || !Number.isSafeInteger(owner.pid) || owner.pid <= 0 || owner.profile !== profile || typeof owner.ephemeral !== "boolean" || !["nonce", "instanceId"].every((k) => typeof owner[k] === "string" && /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(owner[k])))
|
|
181
|
+
fail(lock, "invalid lock schema or mismatched exact profile (legacy 0.3.5 fields required)");
|
|
182
|
+
const validate = async () => {
|
|
183
|
+
await privateDir(root);
|
|
184
|
+
await privateDir(path.join(root, "profiles"));
|
|
185
|
+
await privateDir(profile);
|
|
186
|
+
dead(owner.pid, lock);
|
|
187
|
+
await assertProfileStopped(profile);
|
|
188
|
+
if (!same(original, await artifact(lock)) || await fs.readFile(lock, "utf8") !== raw || !same(originalSocket, await artifact(socket, true)))
|
|
189
|
+
fail(lock, `artifact identity changed (socket ${socket})`);
|
|
190
|
+
if (originalSocket)
|
|
191
|
+
await refusedSocket(socket);
|
|
192
|
+
dead(owner.pid, lock);
|
|
193
|
+
if (!same(original, await handle.stat()) || !same(original, await artifact(lock)) || !same(originalSocket, await artifact(socket, true)))
|
|
194
|
+
fail(lock, "artifact identity changed during liveness probe");
|
|
195
|
+
};
|
|
196
|
+
await validate();
|
|
197
|
+
if (originalSocket)
|
|
198
|
+
await fs.unlink(socket);
|
|
199
|
+
dead(owner.pid, lock);
|
|
200
|
+
if (!same(original, await handle.stat()) || !same(original, await artifact(lock)))
|
|
201
|
+
fail(lock, "lock changed before unlink");
|
|
202
|
+
await fs.unlink(lock);
|
|
203
|
+
} finally {
|
|
204
|
+
await handle.close();
|
|
205
|
+
}
|
|
206
|
+
} catch (e) {
|
|
207
|
+
throw new Error(`Cannot recover profile ${profile} (lock ${lock}, socket ${socket}): ${e.message}`);
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
// cli/src/browser/lifecycle.ts
|
|
28
212
|
function installationRoot() {
|
|
29
|
-
return
|
|
213
|
+
return path2.join(os2.homedir(), ".browser-mcp");
|
|
30
214
|
}
|
|
31
215
|
async function privateDirectory(directory) {
|
|
32
|
-
const absolute =
|
|
33
|
-
let cursor =
|
|
34
|
-
for (const piece of absolute.slice(cursor.length).split(
|
|
35
|
-
cursor =
|
|
216
|
+
const absolute = path2.resolve(directory);
|
|
217
|
+
let cursor = path2.parse(absolute).root;
|
|
218
|
+
for (const piece of absolute.slice(cursor.length).split(path2.sep)) {
|
|
219
|
+
cursor = path2.join(cursor, piece);
|
|
36
220
|
try {
|
|
37
|
-
await
|
|
221
|
+
await fs2.mkdir(cursor, { mode: 448 });
|
|
38
222
|
} catch (e) {
|
|
39
223
|
if (e.code !== "EEXIST")
|
|
40
224
|
throw e;
|
|
41
225
|
}
|
|
42
|
-
const stat2 = await
|
|
226
|
+
const stat2 = await fs2.lstat(cursor);
|
|
43
227
|
if (stat2.isSymbolicLink() || !stat2.isDirectory())
|
|
44
228
|
throw new Error("Unsafe directory path");
|
|
45
229
|
}
|
|
46
|
-
const stat = await
|
|
230
|
+
const stat = await fs2.stat(absolute);
|
|
47
231
|
if (process.platform !== "win32" && ((stat.mode & 63) !== 0 || stat.uid !== process.getuid?.()))
|
|
48
232
|
throw new Error("Private directory must be owned by current user with mode 0700");
|
|
49
233
|
return absolute;
|
|
50
234
|
}
|
|
51
235
|
async function discoverChrome(override) {
|
|
52
|
-
const candidates = override ? [override] : process.platform === "darwin" ? ["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
|
|
236
|
+
const candidates = override ? [override] : process.platform === "darwin" ? ["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome", path2.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) => path2.join(p, "Google", "Chrome", "Application", "chrome.exe")) : ["/usr/bin/google-chrome-stable", "/usr/bin/google-chrome", "/opt/google/chrome/chrome"];
|
|
53
237
|
for (const candidate of candidates) {
|
|
54
|
-
if (!
|
|
238
|
+
if (!path2.isAbsolute(candidate))
|
|
55
239
|
throw new Error("Chrome override must be an absolute executable path");
|
|
56
240
|
try {
|
|
57
|
-
const real = await
|
|
241
|
+
const real = await fs2.realpath(candidate), stat = await fs2.stat(real);
|
|
58
242
|
if (!stat.isFile())
|
|
59
243
|
continue;
|
|
60
|
-
await
|
|
244
|
+
await fs2.access(real, fs2.constants.X_OK);
|
|
61
245
|
return real;
|
|
62
246
|
} catch {}
|
|
63
247
|
}
|
|
@@ -70,49 +254,169 @@ async function launchDedicated(options = {}) {
|
|
|
70
254
|
if (!/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,47}$/.test(name))
|
|
71
255
|
throw new Error("Profile must be a simple name, not a path");
|
|
72
256
|
const root = await privateDirectory(options.root ?? installationRoot());
|
|
73
|
-
const profiles = await privateDirectory(
|
|
74
|
-
const profile =
|
|
257
|
+
const profiles = await privateDirectory(path2.join(root, "profiles"));
|
|
258
|
+
const profile = path2.join(profiles, options.ephemeral ? `ephemeral-${randomUUID()}` : name);
|
|
75
259
|
await privateDirectory(profile);
|
|
76
|
-
const
|
|
260
|
+
const profileStat = await fs2.lstat(profile);
|
|
261
|
+
options.signal?.throwIfAborted();
|
|
262
|
+
const lockPath = path2.join(profile, "runtime.lock"), nonce = randomUUID(), instanceId = randomUUID();
|
|
77
263
|
let lock;
|
|
78
264
|
try {
|
|
79
|
-
lock = await
|
|
80
|
-
} catch {
|
|
81
|
-
|
|
265
|
+
lock = await fs2.open(lockPath, "wx", 384);
|
|
266
|
+
} catch (error) {
|
|
267
|
+
if (error.code !== "EEXIST")
|
|
268
|
+
throw error;
|
|
269
|
+
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.`);
|
|
82
270
|
}
|
|
83
|
-
await lock.
|
|
84
|
-
|
|
85
|
-
const runPath = await privateDirectory(path.join(profile, `run-${instanceId}`));
|
|
271
|
+
const lockStat = await lock.stat();
|
|
272
|
+
const runPath = path2.join(profile, `run-${instanceId}`);
|
|
86
273
|
const manifest = { instanceId, profile, runPath, lockPath, ephemeral: !!options.ephemeral, ownedPaths: [runPath, ...options.ephemeral ? [profile] : []] };
|
|
87
|
-
|
|
88
|
-
let
|
|
89
|
-
const
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
274
|
+
let context, launched = false, lockWritten = false;
|
|
275
|
+
let runStat;
|
|
276
|
+
const verifyProfile = async () => {
|
|
277
|
+
const stat = await fs2.lstat(profile);
|
|
278
|
+
if (await fs2.realpath(profile) !== profile || !stat.isDirectory() || stat.isSymbolicLink() || stat.dev !== profileStat.dev || stat.ino !== profileStat.ino || stat.uid !== profileStat.uid || stat.mode & 63)
|
|
279
|
+
throw new Error("Profile directory ownership changed; retained owned paths");
|
|
280
|
+
};
|
|
281
|
+
const verifyLock = async () => {
|
|
282
|
+
await verifyProfile();
|
|
283
|
+
const stat = await fs2.lstat(lockPath);
|
|
284
|
+
if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1 || stat.dev !== lockStat.dev || stat.ino !== lockStat.ino || stat.uid !== lockStat.uid || stat.mode & 63)
|
|
96
285
|
throw new Error("Profile lock ownership changed; retained owned paths");
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
286
|
+
if (lockWritten) {
|
|
287
|
+
const stored = JSON.parse(await fs2.readFile(lockPath, "utf8"));
|
|
288
|
+
if (stored.nonce !== nonce || stored.instanceId !== instanceId || stored.pid !== process.pid || stored.profile !== profile)
|
|
289
|
+
throw new Error("Profile lock ownership changed; retained owned paths");
|
|
290
|
+
}
|
|
101
291
|
};
|
|
292
|
+
const close = onceAsync(async () => {
|
|
293
|
+
let stopped = !launched;
|
|
294
|
+
try {
|
|
295
|
+
await cleanupSteps([
|
|
296
|
+
["Chrome close", async () => {
|
|
297
|
+
if (context) {
|
|
298
|
+
await context.close();
|
|
299
|
+
stopped = true;
|
|
300
|
+
}
|
|
301
|
+
}],
|
|
302
|
+
["Owned profile cleanup", async () => {
|
|
303
|
+
if (!stopped)
|
|
304
|
+
await assertProfileStopped(profile);
|
|
305
|
+
await verifyLock();
|
|
306
|
+
await cleanupSteps([
|
|
307
|
+
["Run directory", async () => {
|
|
308
|
+
if (!runStat)
|
|
309
|
+
return;
|
|
310
|
+
const stat = await fs2.lstat(runPath);
|
|
311
|
+
if (!stat.isDirectory() || stat.isSymbolicLink() || stat.dev !== runStat.dev || stat.ino !== runStat.ino || stat.uid !== runStat.uid)
|
|
312
|
+
throw new Error("Run directory ownership changed; retained path");
|
|
313
|
+
await fs2.rm(runPath, { recursive: true, force: true });
|
|
314
|
+
}],
|
|
315
|
+
["Profile lock", async () => {
|
|
316
|
+
await verifyLock();
|
|
317
|
+
await fs2.unlink(lockPath);
|
|
318
|
+
}]
|
|
319
|
+
]);
|
|
320
|
+
if (options.ephemeral) {
|
|
321
|
+
await verifyProfile();
|
|
322
|
+
await fs2.rm(profile, { recursive: true, force: true });
|
|
323
|
+
}
|
|
324
|
+
}]
|
|
325
|
+
]);
|
|
326
|
+
} finally {
|
|
327
|
+
await lock.close();
|
|
328
|
+
}
|
|
329
|
+
});
|
|
102
330
|
try {
|
|
331
|
+
await lock.writeFile(JSON.stringify({ pid: process.pid, nonce, instanceId, profile, ephemeral: !!options.ephemeral }));
|
|
332
|
+
lockWritten = true;
|
|
333
|
+
await fs2.mkdir(runPath, { mode: 448 });
|
|
334
|
+
runStat = await fs2.lstat(runPath);
|
|
335
|
+
await fs2.writeFile(path2.join(runPath, "ownership.json"), JSON.stringify(manifest), { flag: "wx", mode: 384 });
|
|
336
|
+
options.signal?.throwIfAborted();
|
|
103
337
|
const executablePath = await discoverChrome(options.chromePath);
|
|
104
|
-
|
|
338
|
+
options.signal?.throwIfAborted();
|
|
339
|
+
launched = true;
|
|
340
|
+
context = await chromium.launchPersistentContext(profile, { executablePath, headless: options.headless ?? false, chromiumSandbox: true, timeout: 30000, handleSIGINT: false, handleSIGTERM: false, handleSIGHUP: false, ignoreDefaultArgs: ["--password-store=basic", "--use-mock-keychain"], acceptDownloads: true, downloadsPath: path2.join(runPath, "chrome-downloads"), viewport: null, serviceWorkers: "block", args: ["--no-first-run", "--no-default-browser-check"] });
|
|
341
|
+
options.signal?.throwIfAborted();
|
|
105
342
|
return { context, instanceId, profile, runPath, close, manifest };
|
|
106
|
-
} catch (
|
|
107
|
-
|
|
108
|
-
|
|
343
|
+
} catch (error) {
|
|
344
|
+
try {
|
|
345
|
+
await close();
|
|
346
|
+
} catch (cleanupError) {
|
|
347
|
+
throw new AggregateError([error, cleanupError], `${error instanceof Error ? error.message : error}
|
|
348
|
+
${cleanupError instanceof Error ? cleanupError.message : cleanupError}`);
|
|
349
|
+
}
|
|
350
|
+
throw error;
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
// cli/src/browser/control.ts
|
|
355
|
+
import fs3 from "node:fs/promises";
|
|
356
|
+
import path3 from "node:path";
|
|
357
|
+
async function listenControl(server, root, controlPath) {
|
|
358
|
+
const rootStat = await fs3.lstat(root);
|
|
359
|
+
const directory = await fs3.mkdtemp(path3.join(root, "c-"));
|
|
360
|
+
const dirStat = await fs3.lstat(directory), boundPath = path3.join(directory, "s");
|
|
361
|
+
let socketStat, published = false;
|
|
362
|
+
const close = onceAsync(() => cleanupSteps([
|
|
363
|
+
["Control listener", async () => {
|
|
364
|
+
if (server.listening)
|
|
365
|
+
await new Promise((resolve, reject) => server.close((error) => error ? reject(error) : resolve()));
|
|
366
|
+
}],
|
|
367
|
+
["Control pathname", async () => {
|
|
368
|
+
if (!published)
|
|
369
|
+
return;
|
|
370
|
+
const parent = await fs3.lstat(root);
|
|
371
|
+
if (await fs3.realpath(root) !== root || !parent.isDirectory() || parent.isSymbolicLink() || parent.dev !== rootStat.dev || parent.ino !== rootStat.ino || parent.uid !== rootStat.uid)
|
|
372
|
+
throw new Error(`Control root ownership changed; retained ${controlPath}`);
|
|
373
|
+
const stat = await fs3.lstat(controlPath).catch((error) => {
|
|
374
|
+
if (error.code !== "ENOENT")
|
|
375
|
+
throw error;
|
|
376
|
+
});
|
|
377
|
+
if (!stat)
|
|
378
|
+
return;
|
|
379
|
+
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
|
+
throw new Error(`Control socket ownership changed; retained ${controlPath}`);
|
|
381
|
+
await fs3.unlink(controlPath);
|
|
382
|
+
}],
|
|
383
|
+
["Private control directory", async () => {
|
|
384
|
+
const stat = await fs3.lstat(directory);
|
|
385
|
+
if (await fs3.realpath(directory) !== directory || !stat.isDirectory() || stat.isSymbolicLink() || stat.dev !== dirStat.dev || stat.ino !== dirStat.ino || stat.uid !== dirStat.uid)
|
|
386
|
+
throw new Error(`Control directory ownership changed; retained ${directory}`);
|
|
387
|
+
await fs3.unlink(path3.join(directory, "ownership.json"));
|
|
388
|
+
await fs3.rmdir(directory);
|
|
389
|
+
}]
|
|
390
|
+
]));
|
|
391
|
+
try {
|
|
392
|
+
await fs3.writeFile(path3.join(directory, "ownership.json"), JSON.stringify({ pid: process.pid, controlPath, ownedPaths: [directory, boundPath] }), { mode: 384, flag: "wx" });
|
|
393
|
+
await new Promise((resolve, reject) => {
|
|
394
|
+
server.once("error", reject);
|
|
395
|
+
server.listen(boundPath, resolve);
|
|
396
|
+
});
|
|
397
|
+
socketStat = await fs3.lstat(boundPath);
|
|
398
|
+
await fs3.chmod(boundPath, 384);
|
|
399
|
+
await fs3.link(boundPath, controlPath);
|
|
400
|
+
published = true;
|
|
401
|
+
await fs3.unlink(boundPath);
|
|
402
|
+
socketStat = await fs3.lstat(controlPath);
|
|
403
|
+
return close;
|
|
404
|
+
} catch (error) {
|
|
405
|
+
try {
|
|
406
|
+
await close();
|
|
407
|
+
} catch (cleanupError) {
|
|
408
|
+
throw new AggregateError([error, cleanupError], `${error}
|
|
409
|
+
${cleanupError}`);
|
|
410
|
+
}
|
|
411
|
+
throw error;
|
|
109
412
|
}
|
|
110
413
|
}
|
|
111
414
|
|
|
112
415
|
// cli/src/browser/pairing.ts
|
|
113
|
-
import
|
|
114
|
-
import
|
|
115
|
-
import { randomBytes, createHash } from "node:crypto";
|
|
416
|
+
import fs4 from "node:fs/promises";
|
|
417
|
+
import path4 from "node:path";
|
|
418
|
+
import { randomBytes, createHash as createHash2 } from "node:crypto";
|
|
419
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
116
420
|
function serverURL(raw) {
|
|
117
421
|
const u = new URL(raw);
|
|
118
422
|
if (u.protocol !== "https:" && !(u.protocol === "http:" && ["127.0.0.1", "localhost", "[::1]"].includes(u.hostname)))
|
|
@@ -121,14 +425,15 @@ function serverURL(raw) {
|
|
|
121
425
|
throw new Error("Server must be a canonical origin");
|
|
122
426
|
return u.origin;
|
|
123
427
|
}
|
|
124
|
-
async function credential(root, server, profile) {
|
|
125
|
-
|
|
428
|
+
async function credential(root, server, profile, signal) {
|
|
429
|
+
signal?.throwIfAborted();
|
|
430
|
+
const filename = path4.join(root, `credential-${createHash2("sha256").update(`${server}
|
|
126
431
|
${profile}`).digest("hex").slice(0, 24)}.json`);
|
|
127
432
|
try {
|
|
128
|
-
const stat = await
|
|
433
|
+
const stat = await fs4.lstat(filename);
|
|
129
434
|
if (!stat.isFile() || stat.isSymbolicLink() || process.platform !== "win32" && stat.mode & 63)
|
|
130
435
|
throw new Error("Unsafe credential file");
|
|
131
|
-
const value = JSON.parse(await
|
|
436
|
+
const value = JSON.parse(await fs4.readFile(filename, "utf8"));
|
|
132
437
|
if (value.server !== server || !/^br_[\w-]+$/.test(value.token))
|
|
133
438
|
throw new Error("Invalid credential file");
|
|
134
439
|
return value.token;
|
|
@@ -137,27 +442,28 @@ ${profile}`).digest("hex").slice(0, 24)}.json`);
|
|
|
137
442
|
throw e;
|
|
138
443
|
}
|
|
139
444
|
const post = async (route, body) => {
|
|
140
|
-
const response = await fetch(server + route, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body), redirect: "error", signal: AbortSignal.timeout(15000) });
|
|
445
|
+
const response = await fetch(server + route, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body), redirect: "error", signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(15000)]) : AbortSignal.timeout(15000) });
|
|
141
446
|
if (!response.ok)
|
|
142
447
|
throw new Error(`Pairing rejected (${response.status})`);
|
|
143
448
|
return await response.json();
|
|
144
449
|
};
|
|
145
|
-
const verifier = randomBytes(32).toString("base64url"), challenge =
|
|
450
|
+
const verifier = randomBytes(32).toString("base64url"), challenge = createHash2("sha256").update(verifier).digest("hex");
|
|
146
451
|
const grant = await post("/api/device/start", { name: `Native Chrome (${profile})`, challenge });
|
|
147
452
|
const verification = new URL(grant.verificationUrl);
|
|
148
453
|
if (verification.origin !== server)
|
|
149
454
|
throw new Error("Pairing origin mismatch");
|
|
150
|
-
console.error(`Approve this dedicated browser: ${verification.href}`);
|
|
455
|
+
console.error(`Approve this dedicated browser (${profile}): ${verification.href}`);
|
|
151
456
|
const deadline = Date.now() + Math.min(600, Number(grant.expiresIn)) * 1000;
|
|
152
457
|
while (Date.now() < deadline) {
|
|
153
|
-
await
|
|
458
|
+
await delay(Math.max(3, Number(grant.interval)) * 1000, undefined, { signal });
|
|
154
459
|
const result = await post("/api/device/poll", { deviceCode: grant.deviceCode, verifier });
|
|
155
460
|
if (result.status === "pending")
|
|
156
461
|
continue;
|
|
157
462
|
const token = result.connectionToken;
|
|
158
463
|
if (typeof token !== "string" || !/^br_[\w-]+$/.test(token))
|
|
159
464
|
throw new Error("Pairing did not return a browser credential");
|
|
160
|
-
|
|
465
|
+
signal?.throwIfAborted();
|
|
466
|
+
await fs4.writeFile(filename, JSON.stringify({ server, token }), { mode: 384, flag: "wx" });
|
|
161
467
|
return token;
|
|
162
468
|
}
|
|
163
469
|
throw new Error("Pairing expired");
|
|
@@ -222,8 +528,8 @@ function screenshotPoint(transform, current, delivered, point) {
|
|
|
222
528
|
}
|
|
223
529
|
|
|
224
530
|
// cli/src/browser/browser-runtime.ts
|
|
225
|
-
import
|
|
226
|
-
import
|
|
531
|
+
import fs7 from "node:fs";
|
|
532
|
+
import path6 from "node:path";
|
|
227
533
|
|
|
228
534
|
// cli/src/browser/upload-input.ts
|
|
229
535
|
var BROWSER_UPLOAD_CHUNK_BYTES = 1024 * 1024;
|
|
@@ -725,9 +1031,9 @@ function preflightBrowserInput(action, raw) {
|
|
|
725
1031
|
}
|
|
726
1032
|
|
|
727
1033
|
// cli/src/browser/upload-store.ts
|
|
728
|
-
import
|
|
729
|
-
import
|
|
730
|
-
import { createHash as
|
|
1034
|
+
import fs5 from "node:fs";
|
|
1035
|
+
import path5 from "node:path";
|
|
1036
|
+
import { createHash as createHash3 } from "node:crypto";
|
|
731
1037
|
class BrowserUploadStore {
|
|
732
1038
|
releaseTarget;
|
|
733
1039
|
directory;
|
|
@@ -736,8 +1042,8 @@ class BrowserUploadStore {
|
|
|
736
1042
|
return;
|
|
737
1043
|
}) {
|
|
738
1044
|
this.releaseTarget = releaseTarget;
|
|
739
|
-
|
|
740
|
-
this.directory =
|
|
1045
|
+
fs5.mkdirSync(root, { recursive: true, mode: 448 });
|
|
1046
|
+
this.directory = fs5.mkdtempSync(path5.join(root, "run-"));
|
|
741
1047
|
}
|
|
742
1048
|
begin(id, tabId, files, target2) {
|
|
743
1049
|
if (typeof id !== "string" || !/^[a-f0-9-]{36}$/.test(id) || this.uploads.has(id))
|
|
@@ -745,20 +1051,20 @@ class BrowserUploadStore {
|
|
|
745
1051
|
if (!Array.isArray(files) || files.length === 0 || files.length > 100)
|
|
746
1052
|
throw new Error("Upload requires between 1 and 100 files.");
|
|
747
1053
|
const metadata = files.map(validateUploadFile);
|
|
748
|
-
const directory =
|
|
1054
|
+
const directory = fs5.mkdtempSync(path5.join(this.directory, "upload-"));
|
|
749
1055
|
try {
|
|
750
1056
|
const staged = metadata.map((file, index) => {
|
|
751
|
-
const parent =
|
|
752
|
-
|
|
753
|
-
const filePath =
|
|
754
|
-
|
|
755
|
-
return { ...file, path: filePath, offset: 0, hash:
|
|
1057
|
+
const parent = path5.join(directory, String(index));
|
|
1058
|
+
fs5.mkdirSync(parent, { mode: 448 });
|
|
1059
|
+
const filePath = path5.join(parent, file.filename);
|
|
1060
|
+
fs5.closeSync(fs5.openSync(filePath, "wx", 384));
|
|
1061
|
+
return { ...file, path: filePath, offset: 0, hash: createHash3("sha256") };
|
|
756
1062
|
});
|
|
757
1063
|
const timer = setTimeout(() => this.abort(id, tabId), 5 * 60 * 1000);
|
|
758
1064
|
timer.unref();
|
|
759
1065
|
this.uploads.set(id, { tabId, directory, files: staged, target: target2, attached: false, timer });
|
|
760
1066
|
} catch (error) {
|
|
761
|
-
|
|
1067
|
+
fs5.rmSync(directory, { recursive: true, force: true });
|
|
762
1068
|
throw error;
|
|
763
1069
|
}
|
|
764
1070
|
}
|
|
@@ -779,17 +1085,17 @@ class BrowserUploadStore {
|
|
|
779
1085
|
const bytes = decodeUploadChunk(base64);
|
|
780
1086
|
if (bytes.length === 0 || file.offset + bytes.length > file.size)
|
|
781
1087
|
throw new Error("Upload chunk does not match the declared file size.");
|
|
782
|
-
const fd =
|
|
1088
|
+
const fd = fs5.openSync(file.path, fs5.constants.O_WRONLY | fs5.constants.O_NOFOLLOW);
|
|
783
1089
|
try {
|
|
784
1090
|
let written = 0;
|
|
785
1091
|
while (written < bytes.length) {
|
|
786
|
-
const count =
|
|
1092
|
+
const count = fs5.writeSync(fd, bytes, written, bytes.length - written, file.offset + written);
|
|
787
1093
|
if (!count)
|
|
788
1094
|
throw new Error("Could not write upload chunk.");
|
|
789
1095
|
written += count;
|
|
790
1096
|
}
|
|
791
1097
|
} finally {
|
|
792
|
-
|
|
1098
|
+
fs5.closeSync(fd);
|
|
793
1099
|
}
|
|
794
1100
|
file.hash.update(bytes);
|
|
795
1101
|
file.offset += bytes.length;
|
|
@@ -823,7 +1129,7 @@ class BrowserUploadStore {
|
|
|
823
1129
|
clearTimeout(upload.timer);
|
|
824
1130
|
this.uploads.delete(id);
|
|
825
1131
|
this.releaseTarget(upload.target);
|
|
826
|
-
|
|
1132
|
+
fs5.rmSync(upload.directory, { recursive: true, force: true });
|
|
827
1133
|
}
|
|
828
1134
|
closeTab(tabId) {
|
|
829
1135
|
for (const [id, upload] of this.uploads)
|
|
@@ -833,7 +1139,7 @@ class BrowserUploadStore {
|
|
|
833
1139
|
close() {
|
|
834
1140
|
for (const [id, upload] of this.uploads)
|
|
835
1141
|
this.remove(id, upload);
|
|
836
|
-
|
|
1142
|
+
fs5.rmSync(this.directory, { recursive: true, force: true });
|
|
837
1143
|
}
|
|
838
1144
|
}
|
|
839
1145
|
|
|
@@ -1085,7 +1391,7 @@ async function passwordSafeAriaSnapshot(page, options = {}) {
|
|
|
1085
1391
|
}
|
|
1086
1392
|
|
|
1087
1393
|
// cli/src/browser/snapshot-outline.ts
|
|
1088
|
-
import { createHash as
|
|
1394
|
+
import { createHash as createHash4 } from "node:crypto";
|
|
1089
1395
|
function outline(document2) {
|
|
1090
1396
|
const roots = [], stack = [], refs = new Map;
|
|
1091
1397
|
const frames = new Map(document2.frames.map((frame) => [frame.ref, frame.path]));
|
|
@@ -1114,7 +1420,7 @@ function outline(document2) {
|
|
|
1114
1420
|
function renderSnapshot(document2, input) {
|
|
1115
1421
|
const { roots, refs } = outline(document2);
|
|
1116
1422
|
const canonicalTarget = (target2) => target2 && Object.fromEntries(Object.entries({ exact: true, ...target2 }).sort(([a], [b]) => a.localeCompare(b)));
|
|
1117
|
-
const snapshotId =
|
|
1423
|
+
const snapshotId = createHash4("sha256").update(JSON.stringify({
|
|
1118
1424
|
text: document2.text,
|
|
1119
1425
|
scope: canonicalTarget(input.scope),
|
|
1120
1426
|
query: canonicalTarget(input.query),
|
|
@@ -1519,7 +1825,7 @@ function observeNavigation(page, input) {
|
|
|
1519
1825
|
const result = new Promise((done) => {
|
|
1520
1826
|
resolve = done;
|
|
1521
1827
|
});
|
|
1522
|
-
const finish = (matched,
|
|
1828
|
+
const finish = (matched, code2, error) => {
|
|
1523
1829
|
if (settled)
|
|
1524
1830
|
return;
|
|
1525
1831
|
settled = true;
|
|
@@ -1527,7 +1833,7 @@ function observeNavigation(page, input) {
|
|
|
1527
1833
|
page.off("framenavigated", onNavigation);
|
|
1528
1834
|
page.off("close", onClose);
|
|
1529
1835
|
page.off("crash", onClose);
|
|
1530
|
-
resolve({ matched, url: page.url(), elapsedMs: Date.now() - started, waitUntil: input.waitUntil, ...
|
|
1836
|
+
resolve({ matched, url: page.url(), elapsedMs: Date.now() - started, waitUntil: input.waitUntil, ...code2 ? { code: code2, error } : {} });
|
|
1531
1837
|
};
|
|
1532
1838
|
const onClose = () => finish(false, "navigation_tab_closed", "The tab closed before navigation was observed. Inspect tabs before another action.");
|
|
1533
1839
|
const onNavigation = (frame) => {
|
|
@@ -2297,7 +2603,7 @@ async function exportDocument(page, format) {
|
|
|
2297
2603
|
}
|
|
2298
2604
|
|
|
2299
2605
|
// cli/src/browser/browser-tab-state.ts
|
|
2300
|
-
import
|
|
2606
|
+
import fs6 from "node:fs";
|
|
2301
2607
|
|
|
2302
2608
|
class BrowserTabState {
|
|
2303
2609
|
context;
|
|
@@ -2308,8 +2614,8 @@ class BrowserTabState {
|
|
|
2308
2614
|
constructor(context, filename) {
|
|
2309
2615
|
this.context = context;
|
|
2310
2616
|
this.filename = filename;
|
|
2311
|
-
if (
|
|
2312
|
-
const value = JSON.parse(
|
|
2617
|
+
if (fs6.existsSync(filename)) {
|
|
2618
|
+
const value = JSON.parse(fs6.readFileSync(filename, "utf8"));
|
|
2313
2619
|
if (value.version !== 1 || !value.targets || typeof value.targets !== "object")
|
|
2314
2620
|
throw new Error("Invalid browser tab state.");
|
|
2315
2621
|
this.stored = value.targets;
|
|
@@ -2317,8 +2623,8 @@ class BrowserTabState {
|
|
|
2317
2623
|
}
|
|
2318
2624
|
save() {
|
|
2319
2625
|
const tmp = `${this.filename}.${crypto.randomUUID()}.tmp`;
|
|
2320
|
-
|
|
2321
|
-
|
|
2626
|
+
fs6.writeFileSync(tmp, JSON.stringify({ version: 1, targets: this.stored }), { mode: 384, flag: "wx" });
|
|
2627
|
+
fs6.renameSync(tmp, this.filename);
|
|
2322
2628
|
}
|
|
2323
2629
|
resolve(page) {
|
|
2324
2630
|
let pending = this.pages.get(page);
|
|
@@ -2430,7 +2736,7 @@ class BrowserRuntime {
|
|
|
2430
2736
|
return;
|
|
2431
2737
|
});
|
|
2432
2738
|
});
|
|
2433
|
-
|
|
2739
|
+
fs7.mkdirSync(downloadsPath, { recursive: true });
|
|
2434
2740
|
this.tabState = new BrowserTabState(context, `${downloadsPath}.tabs.json`);
|
|
2435
2741
|
for (const page of context.pages())
|
|
2436
2742
|
this.track(page);
|
|
@@ -2489,23 +2795,23 @@ class BrowserRuntime {
|
|
|
2489
2795
|
return id;
|
|
2490
2796
|
}
|
|
2491
2797
|
safeDownloadFilename(suggestedFilename) {
|
|
2492
|
-
const basename =
|
|
2798
|
+
const basename = path6.basename(suggestedFilename).replace(/[\\/\0]/g, "-").trim();
|
|
2493
2799
|
if (!basename || basename === "." || basename === "..")
|
|
2494
2800
|
return "download";
|
|
2495
|
-
const extension =
|
|
2496
|
-
let stem = basename.slice(0, basename.length -
|
|
2801
|
+
const extension = path6.extname(basename).slice(0, 30);
|
|
2802
|
+
let stem = basename.slice(0, basename.length - path6.extname(basename).length) || "download";
|
|
2497
2803
|
while (Buffer.byteLength(`${stem}${extension}`) > 200)
|
|
2498
2804
|
stem = stem.slice(0, -1);
|
|
2499
2805
|
return `${stem || "download"}${extension}`;
|
|
2500
2806
|
}
|
|
2501
2807
|
availableDownloadPath(suggestedFilename) {
|
|
2502
2808
|
const filename = this.safeDownloadFilename(suggestedFilename);
|
|
2503
|
-
const extension =
|
|
2809
|
+
const extension = path6.extname(filename);
|
|
2504
2810
|
const stem = filename.slice(0, filename.length - extension.length) || "download";
|
|
2505
2811
|
for (let suffix = 1;; suffix += 1) {
|
|
2506
2812
|
const candidate = suffix === 1 ? filename : `${stem}-${suffix}${extension}`;
|
|
2507
|
-
const candidatePath =
|
|
2508
|
-
if (!
|
|
2813
|
+
const candidatePath = path6.join(this.downloadsPath, candidate);
|
|
2814
|
+
if (!fs7.existsSync(candidatePath))
|
|
2509
2815
|
return candidatePath;
|
|
2510
2816
|
}
|
|
2511
2817
|
}
|
|
@@ -2513,18 +2819,18 @@ class BrowserRuntime {
|
|
|
2513
2819
|
const failure = await download.failure();
|
|
2514
2820
|
if (failure)
|
|
2515
2821
|
throw new Error(failure);
|
|
2516
|
-
const temporary =
|
|
2822
|
+
const temporary = path6.join(this.downloadsPath, `.${crypto.randomUUID()}.download`);
|
|
2517
2823
|
let targetPath;
|
|
2518
2824
|
try {
|
|
2519
2825
|
await download.saveAs(temporary);
|
|
2520
2826
|
targetPath = this.availableDownloadPath(download.suggestedFilename());
|
|
2521
|
-
|
|
2827
|
+
fs7.renameSync(temporary, targetPath);
|
|
2522
2828
|
} finally {
|
|
2523
|
-
|
|
2829
|
+
fs7.rmSync(temporary, { force: true });
|
|
2524
2830
|
}
|
|
2525
|
-
process.stdout.write(`[r5d-browser] downloaded ${
|
|
2831
|
+
process.stdout.write(`[r5d-browser] downloaded ${path6.basename(targetPath)}
|
|
2526
2832
|
`);
|
|
2527
|
-
return { downloadId: this.downloadId(
|
|
2833
|
+
return { downloadId: this.downloadId(path6.basename(targetPath)) };
|
|
2528
2834
|
}
|
|
2529
2835
|
downloadId(filename) {
|
|
2530
2836
|
return Buffer.from(filename, "utf8").toString("base64url");
|
|
@@ -2533,13 +2839,13 @@ class BrowserRuntime {
|
|
|
2533
2839
|
if (typeof downloadId !== "string" || !downloadId)
|
|
2534
2840
|
throw new Error("downloadId is required.");
|
|
2535
2841
|
const filename = Buffer.from(downloadId, "base64url").toString("utf8");
|
|
2536
|
-
if (this.downloadId(filename) !== downloadId || filename !==
|
|
2842
|
+
if (this.downloadId(filename) !== downloadId || filename !== path6.basename(filename) || filename.includes("\x00")) {
|
|
2537
2843
|
throw new Error("Invalid downloadId.");
|
|
2538
2844
|
}
|
|
2539
|
-
const filePath =
|
|
2845
|
+
const filePath = path6.join(this.downloadsPath, filename);
|
|
2540
2846
|
let stats;
|
|
2541
2847
|
try {
|
|
2542
|
-
stats =
|
|
2848
|
+
stats = fs7.lstatSync(filePath);
|
|
2543
2849
|
} catch {
|
|
2544
2850
|
throw new Error(`Browser download ${downloadId} no longer exists.`);
|
|
2545
2851
|
}
|
|
@@ -2548,7 +2854,7 @@ class BrowserRuntime {
|
|
|
2548
2854
|
return { filename, filePath, stats };
|
|
2549
2855
|
}
|
|
2550
2856
|
async listDownloads() {
|
|
2551
|
-
return
|
|
2857
|
+
return fs7.readdirSync(this.downloadsPath, { withFileTypes: true }).flatMap((entry) => {
|
|
2552
2858
|
if (!entry.isFile() || entry.name.startsWith("."))
|
|
2553
2859
|
return [];
|
|
2554
2860
|
const { filename, stats } = this.resolveDownload(this.downloadId(entry.name));
|
|
@@ -2572,20 +2878,20 @@ class BrowserRuntime {
|
|
|
2572
2878
|
throw new Error("Invalid download chunk size.");
|
|
2573
2879
|
const chunkSize = Math.min(requestedBytes, MAX_DOWNLOAD_CHUNK_BYTES, stats.size - offset);
|
|
2574
2880
|
const bytes = Buffer.alloc(chunkSize);
|
|
2575
|
-
const handle =
|
|
2881
|
+
const handle = fs7.openSync(filePath, fs7.constants.O_RDONLY | fs7.constants.O_NOFOLLOW);
|
|
2576
2882
|
let bytesRead = 0;
|
|
2577
2883
|
try {
|
|
2578
|
-
const openedStats =
|
|
2884
|
+
const openedStats = fs7.fstatSync(handle);
|
|
2579
2885
|
if (!openedStats.isFile() || openedStats.dev !== stats.dev || openedStats.ino !== stats.ino) {
|
|
2580
2886
|
throw new Error("Browser download changed before it could be read.");
|
|
2581
2887
|
}
|
|
2582
|
-
bytesRead =
|
|
2583
|
-
const completedStats =
|
|
2888
|
+
bytesRead = fs7.readSync(handle, bytes, 0, chunkSize, offset);
|
|
2889
|
+
const completedStats = fs7.fstatSync(handle);
|
|
2584
2890
|
if (completedStats.size !== stats.size || completedStats.mtimeMs !== stats.mtimeMs) {
|
|
2585
2891
|
throw new Error("Browser download changed while it was being read.");
|
|
2586
2892
|
}
|
|
2587
2893
|
} finally {
|
|
2588
|
-
|
|
2894
|
+
fs7.closeSync(handle);
|
|
2589
2895
|
}
|
|
2590
2896
|
const nextOffset = offset + bytesRead;
|
|
2591
2897
|
return {
|
|
@@ -3007,9 +3313,9 @@ class BrowserRuntime {
|
|
|
3007
3313
|
return { tabId, exported: false, code: "export_too_large" };
|
|
3008
3314
|
const exports = files.map((file) => {
|
|
3009
3315
|
const target2 = this.availableDownloadPath(`${crypto.randomUUID()}-${file.filename}`);
|
|
3010
|
-
|
|
3316
|
+
fs7.writeFileSync(target2, file.bytes, { flag: "wx", mode: 384 });
|
|
3011
3317
|
return {
|
|
3012
|
-
downloadId: this.downloadId(
|
|
3318
|
+
downloadId: this.downloadId(path6.basename(target2)),
|
|
3013
3319
|
filename: file.filename,
|
|
3014
3320
|
size: file.bytes.length,
|
|
3015
3321
|
mimeType: file.mimeType
|
|
@@ -3350,11 +3656,11 @@ class BrowserRuntime {
|
|
|
3350
3656
|
if (input.text.length > MAX_TYPED_KEYS_CHARS) {
|
|
3351
3657
|
throw new Error(`keyboard_type mode "keys" is limited to ${MAX_TYPED_KEYS_CHARS} characters per call; split the text or use the default insert mode.`);
|
|
3352
3658
|
}
|
|
3353
|
-
const
|
|
3354
|
-
if (input.text.length *
|
|
3659
|
+
const delay2 = clampInt(input.delayMs, 0, 100, 20);
|
|
3660
|
+
if (input.text.length * delay2 > MAX_TYPED_KEYS_TOTAL_MS) {
|
|
3355
3661
|
throw new Error(`text.length x delayMs must stay at or below ${MAX_TYPED_KEYS_TOTAL_MS}ms; lower delayMs or split the text.`);
|
|
3356
3662
|
}
|
|
3357
|
-
await page.keyboard.type(input.text, { delay });
|
|
3663
|
+
await page.keyboard.type(input.text, { delay: delay2 });
|
|
3358
3664
|
return { tabId, characters: input.text.length, mode: "keys" };
|
|
3359
3665
|
}
|
|
3360
3666
|
await page.keyboard.insertText(input.text);
|
|
@@ -3365,7 +3671,7 @@ class BrowserRuntime {
|
|
|
3365
3671
|
throw new Error("run_js requires code.");
|
|
3366
3672
|
let evaluated;
|
|
3367
3673
|
try {
|
|
3368
|
-
evaluated = await page.evaluate(async ({ code, maxBytes, maxCount }) => {
|
|
3674
|
+
evaluated = await page.evaluate(async ({ code: code2, maxBytes, maxCount }) => {
|
|
3369
3675
|
const artifacts = [];
|
|
3370
3676
|
let totalBytes = 0;
|
|
3371
3677
|
const r5dCreateArtifact = (filename, content) => {
|
|
@@ -3386,7 +3692,7 @@ class BrowserRuntime {
|
|
|
3386
3692
|
return filename;
|
|
3387
3693
|
};
|
|
3388
3694
|
const invoke = new Function("r5dCreateArtifact", `"use strict"; return (async () => {
|
|
3389
|
-
${
|
|
3695
|
+
${code2}
|
|
3390
3696
|
})()`);
|
|
3391
3697
|
try {
|
|
3392
3698
|
return { result: await invoke(r5dCreateArtifact), artifacts };
|
|
@@ -3743,9 +4049,9 @@ class NativeRuntime {
|
|
|
3743
4049
|
|
|
3744
4050
|
// cli/src/runtime/relay.ts
|
|
3745
4051
|
import WebSocket2 from "ws";
|
|
3746
|
-
import { createHash as
|
|
3747
|
-
import
|
|
3748
|
-
import
|
|
4052
|
+
import { createHash as createHash5, randomUUID as randomUUID2 } from "node:crypto";
|
|
4053
|
+
import fs8 from "node:fs/promises";
|
|
4054
|
+
import path7 from "node:path";
|
|
3749
4055
|
|
|
3750
4056
|
// cli/src/live/producer.ts
|
|
3751
4057
|
import WebSocket from "ws";
|
|
@@ -4209,7 +4515,7 @@ class Relay {
|
|
|
4209
4515
|
heartbeat.unref();
|
|
4210
4516
|
socket.once("open", () => {
|
|
4211
4517
|
this.state = "authenticating";
|
|
4212
|
-
socket.send(JSON.stringify({ type: "auth", token: this.token, client: { protocol: 3, version: "0.3.
|
|
4518
|
+
socket.send(JSON.stringify({ type: "auth", token: this.token, client: { protocol: 3, version: "0.3.7", 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 } } }));
|
|
4213
4519
|
});
|
|
4214
4520
|
socket.on("message", (bytes, binary) => {
|
|
4215
4521
|
if (binary || Buffer.byteLength(bytes.toString()) > LIMIT) {
|
|
@@ -4328,20 +4634,20 @@ class Relay {
|
|
|
4328
4634
|
if (message.op === "export_page" && Array.isArray(result?.exports))
|
|
4329
4635
|
for (const item of result.exports) {
|
|
4330
4636
|
const filename = Buffer.from(item.downloadId, "base64url").toString("utf8");
|
|
4331
|
-
if (
|
|
4637
|
+
if (path7.basename(filename) !== filename)
|
|
4332
4638
|
throw new Error("Invalid export file");
|
|
4333
|
-
const filenamePath =
|
|
4334
|
-
const stat = await
|
|
4639
|
+
const filenamePath = path7.join(this.previewDirectory, filename);
|
|
4640
|
+
const stat = await fs8.lstat(filenamePath);
|
|
4335
4641
|
if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 20 * 1024 * 1024)
|
|
4336
4642
|
throw new Error("Invalid export file");
|
|
4337
|
-
blobs.push(await this.upload(await
|
|
4338
|
-
await
|
|
4643
|
+
blobs.push(await this.upload(await fs8.readFile(filenamePath), "export", item.filename, item.mimeType));
|
|
4644
|
+
await fs8.unlink(filenamePath);
|
|
4339
4645
|
delete item.downloadId;
|
|
4340
4646
|
}
|
|
4341
4647
|
if (message.op === "run_js" && Array.isArray(result?.artifacts)) {
|
|
4342
|
-
for (const
|
|
4343
|
-
blobs.push(await this.upload(Buffer.from(
|
|
4344
|
-
result.artifacts = result.artifacts.map((a) => ({ filename:
|
|
4648
|
+
for (const artifact2 of result.artifacts)
|
|
4649
|
+
blobs.push(await this.upload(Buffer.from(artifact2.content), "artifact", path7.basename(artifact2.filename), "text/plain"));
|
|
4650
|
+
result.artifacts = result.artifacts.map((a) => ({ filename: path7.basename(a.filename) }));
|
|
4345
4651
|
}
|
|
4346
4652
|
if (Buffer.byteLength(JSON.stringify(result)) > 1800000)
|
|
4347
4653
|
throw new Error("Result budget exceeded");
|
|
@@ -4356,7 +4662,7 @@ class Relay {
|
|
|
4356
4662
|
async upload(bytes, role, name, mimeType) {
|
|
4357
4663
|
if (bytes.length > 20 * 1024 * 1024)
|
|
4358
4664
|
throw new Error("Preview exceeds 20 MiB");
|
|
4359
|
-
const blobId = randomUUID2(), sha256 =
|
|
4665
|
+
const blobId = randomUUID2(), sha256 = createHash5("sha256").update(bytes).digest("hex");
|
|
4360
4666
|
const response = await fetch(new URL(`/api/runtime/blobs/${blobId}`, this.server), { method: "PUT", headers: { Authorization: `Bearer ${this.token}`, "Content-Type": "application/octet-stream", "X-Runtime-Instance": this.runtime.instanceId, "X-Content-SHA256": sha256 }, body: bytes, redirect: "error", signal: AbortSignal.timeout(30000) });
|
|
4361
4667
|
if (!response.ok)
|
|
4362
4668
|
throw new Error("Preview upload failed");
|
|
@@ -4383,7 +4689,7 @@ class Relay {
|
|
|
4383
4689
|
// cli/src/data/index.ts
|
|
4384
4690
|
import { mkdir, open, rename, unlink, rmdir, chmod, lstat } from "node:fs/promises";
|
|
4385
4691
|
import { createReadStream, createWriteStream } from "node:fs";
|
|
4386
|
-
import { randomUUID as randomUUID4, createHash as
|
|
4692
|
+
import { randomUUID as randomUUID4, createHash as createHash6 } from "node:crypto";
|
|
4387
4693
|
import { join, basename } from "node:path";
|
|
4388
4694
|
import { Readable, Transform } from "node:stream";
|
|
4389
4695
|
import { pipeline } from "node:stream/promises";
|
|
@@ -4405,13 +4711,13 @@ class SecretVault {
|
|
|
4405
4711
|
metadata(e) {
|
|
4406
4712
|
return { vaultId: e.id, names: Object.keys(e.values), count: Object.keys(e.values).length, expiresAt: e.expiresAt, tabId: e.tabId, generation: e.generation };
|
|
4407
4713
|
}
|
|
4408
|
-
async capture(scope, tabId,
|
|
4409
|
-
if (
|
|
4714
|
+
async capture(scope, tabId, code2, frames) {
|
|
4715
|
+
if (code2.length > 65536)
|
|
4410
4716
|
throw new Error("Capture rejected");
|
|
4411
4717
|
const epoch = this.epoch, target2 = await this.access.resolveTarget(tabId, scope, frames);
|
|
4412
4718
|
try {
|
|
4413
4719
|
let timer;
|
|
4414
|
-
const values = await Promise.race([this.access.suppressDiagnostics(tabId, () => target2.frame.evaluate(async ({ code:
|
|
4720
|
+
const values = await Promise.race([this.access.suppressDiagnostics(tabId, () => target2.frame.evaluate(async ({ code: code3, limits }) => {
|
|
4415
4721
|
const values2 = Object.create(null);
|
|
4416
4722
|
let bytes = 0;
|
|
4417
4723
|
const helper = Object.freeze({ secrets: Object.freeze({ set: async (name, value) => {
|
|
@@ -4424,12 +4730,12 @@ class SecretVault {
|
|
|
4424
4730
|
} }) });
|
|
4425
4731
|
const AsyncFunction = Object.getPrototypeOf(async function() {}).constructor;
|
|
4426
4732
|
try {
|
|
4427
|
-
await new AsyncFunction("browserMcp",
|
|
4733
|
+
await new AsyncFunction("browserMcp", code3)(helper);
|
|
4428
4734
|
return values2;
|
|
4429
4735
|
} catch {
|
|
4430
4736
|
throw new Error("Capture failed");
|
|
4431
4737
|
}
|
|
4432
|
-
}, { code, limits: LIMITS })), new Promise((_resolve, reject) => {
|
|
4738
|
+
}, { code: code2, limits: LIMITS })), new Promise((_resolve, reject) => {
|
|
4433
4739
|
timer = setTimeout(() => reject(new Error("Capture timeout")), 15000);
|
|
4434
4740
|
timer.unref?.();
|
|
4435
4741
|
})]).finally(() => {
|
|
@@ -4577,7 +4883,7 @@ async function createDataPlugin(access, options) {
|
|
|
4577
4883
|
owned.add(part);
|
|
4578
4884
|
r.path = part;
|
|
4579
4885
|
let size = 0;
|
|
4580
|
-
const hash =
|
|
4886
|
+
const hash = createHash6("sha256");
|
|
4581
4887
|
const check = new Transform({ transform(chunk, _enc, cb) {
|
|
4582
4888
|
size += chunk.length;
|
|
4583
4889
|
if (size > r.size)
|
|
@@ -4732,9 +5038,9 @@ async function createDataPlugin(access, options) {
|
|
|
4732
5038
|
r = create(scope, "download", LIMITS.file, download.suggestedFilename());
|
|
4733
5039
|
r.tabId = tabId;
|
|
4734
5040
|
r.generation = generation;
|
|
4735
|
-
const
|
|
4736
|
-
r.path =
|
|
4737
|
-
owned.add(
|
|
5041
|
+
const path8 = join(options.directory, r.id);
|
|
5042
|
+
r.path = path8;
|
|
5043
|
+
owned.add(path8);
|
|
4738
5044
|
const source = await download.createReadStream();
|
|
4739
5045
|
if (!source)
|
|
4740
5046
|
throw new Error("Download unavailable");
|
|
@@ -4748,17 +5054,17 @@ async function createDataPlugin(access, options) {
|
|
|
4748
5054
|
const timeout2 = setTimeout(() => r.abort.abort(), LIMITS.duration);
|
|
4749
5055
|
timeout2.unref?.();
|
|
4750
5056
|
try {
|
|
4751
|
-
await pipeline(source, bound, createWriteStream(
|
|
5057
|
+
await pipeline(source, bound, createWriteStream(path8, { flags: "wx", mode: 384 }), { signal: r.abort.signal });
|
|
4752
5058
|
} finally {
|
|
4753
5059
|
clearTimeout(timeout2);
|
|
4754
5060
|
}
|
|
4755
|
-
await chmod(
|
|
4756
|
-
const stat = await lstat(
|
|
5061
|
+
await chmod(path8, 384);
|
|
5062
|
+
const stat = await lstat(path8);
|
|
4757
5063
|
if (!stat.isFile() || stat.size > LIMITS.file)
|
|
4758
5064
|
throw new Error("Download limit");
|
|
4759
5065
|
r.size = stat.size;
|
|
4760
|
-
const hash =
|
|
4761
|
-
for await (const chunk of createReadStream(
|
|
5066
|
+
const hash = createHash6("sha256");
|
|
5067
|
+
for await (const chunk of createReadStream(path8))
|
|
4762
5068
|
hash.update(chunk);
|
|
4763
5069
|
r.hash = hash.digest("hex");
|
|
4764
5070
|
if (r.abort.signal.aborted)
|
|
@@ -4872,82 +5178,158 @@ function createForwardPlugin(options) {
|
|
|
4872
5178
|
|
|
4873
5179
|
// cli/src/browser/main.ts
|
|
4874
5180
|
function parse(args) {
|
|
4875
|
-
const options = {};
|
|
5181
|
+
const options = { profiles: [] };
|
|
4876
5182
|
for (let i = 0;i < args.length; i++) {
|
|
4877
5183
|
const key = args[i];
|
|
4878
5184
|
if (key === "--ephemeral")
|
|
4879
5185
|
options.ephemeral = true;
|
|
4880
5186
|
else if (key === "--live-view")
|
|
4881
5187
|
options.liveView = true;
|
|
4882
|
-
else if (
|
|
5188
|
+
else if (key === "--profile" || key === "--server" || key === "--chrome-path") {
|
|
4883
5189
|
if (!args[i + 1] || args[i + 1].startsWith("--"))
|
|
4884
5190
|
throw new Error(`Missing ${key} value`);
|
|
4885
|
-
|
|
5191
|
+
const value = args[++i];
|
|
5192
|
+
if (key === "--profile")
|
|
5193
|
+
options.profiles.push(value);
|
|
5194
|
+
else
|
|
5195
|
+
options[key === "--server" ? "server" : "chrome-path"] = value;
|
|
4886
5196
|
} else
|
|
4887
5197
|
throw new Error(`Unknown browser option ${key}`);
|
|
4888
5198
|
}
|
|
4889
5199
|
return options;
|
|
4890
5200
|
}
|
|
4891
|
-
function socketPath(root, profile) {
|
|
4892
|
-
return path6.join(root, `control-${createHash6("sha256").update(profile).digest("hex").slice(0, 16)}.sock`);
|
|
4893
|
-
}
|
|
4894
5201
|
async function runBrowser(args) {
|
|
4895
5202
|
const command = args.shift() ?? "help";
|
|
4896
5203
|
if (command === "help" || command === "--help" || args.includes("--help")) {
|
|
4897
|
-
console.log(`browser-mcp browser start [--server https://browser-mcp.click] [--profile work] [--ephemeral] [--chrome-path /path/to/chrome]
|
|
4898
|
-
browser-mcp browser status|pause|resume|stop [--profile work]
|
|
4899
|
-
|
|
5204
|
+
console.log(`browser-mcp browser start [--server https://browser-mcp.click] [--profile work] [--profile personal ...] [--ephemeral] [--chrome-path /path/to/chrome] [--live-view]
|
|
5205
|
+
browser-mcp browser status|pause|resume|stop|recover [--profile work]
|
|
5206
|
+
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 pipe lifecycle: 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.`);
|
|
4900
5208
|
return;
|
|
4901
5209
|
}
|
|
4902
|
-
|
|
4903
|
-
|
|
4904
|
-
|
|
4905
|
-
|
|
4906
|
-
|
|
4907
|
-
|
|
4908
|
-
|
|
4909
|
-
|
|
4910
|
-
|
|
4911
|
-
|
|
4912
|
-
|
|
5210
|
+
if (!["start", "status", "pause", "resume", "stop", "recover"].includes(command))
|
|
5211
|
+
throw new Error("Unknown browser command");
|
|
5212
|
+
const options = parse(args), profiles = options.profiles.length ? options.profiles : ["default"];
|
|
5213
|
+
for (const profile of profiles)
|
|
5214
|
+
if (!/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,47}$/.test(profile))
|
|
5215
|
+
throw new Error("Invalid profile name");
|
|
5216
|
+
if (new Set(profiles).size !== profiles.length)
|
|
5217
|
+
throw new Error("Duplicate profile names: use a different --profile for each browser");
|
|
5218
|
+
if (command !== "start" && profiles.length !== 1)
|
|
5219
|
+
throw new Error(`${command} accepts one --profile; run local controls separately for each browser`);
|
|
5220
|
+
const abort = new AbortController;
|
|
5221
|
+
setMaxListeners(0, abort.signal);
|
|
5222
|
+
const requestStop = () => abort.abort(new Error("Browser startup interrupted"));
|
|
5223
|
+
const signals = ["SIGINT", "SIGTERM", "SIGHUP"];
|
|
5224
|
+
if (command === "start")
|
|
5225
|
+
for (const signal of signals)
|
|
5226
|
+
process.on(signal, requestStop);
|
|
5227
|
+
try {
|
|
5228
|
+
const root = await privateDirectory(installationRoot());
|
|
5229
|
+
if (command !== "start") {
|
|
5230
|
+
const profile = profiles[0], controlPath = controlSocketPath(root, profile);
|
|
5231
|
+
if (command === "recover") {
|
|
5232
|
+
await recoverProfile(root, profile);
|
|
5233
|
+
console.log(`Verified stale lock/socket cleanup complete for profile ${profile}; profile data retained.`);
|
|
5234
|
+
return;
|
|
5235
|
+
}
|
|
5236
|
+
await new Promise((resolve, reject) => {
|
|
5237
|
+
const socket = net2.connect(controlPath);
|
|
5238
|
+
socket.setTimeout(5000, () => socket.destroy(new Error("Local control timeout")));
|
|
5239
|
+
socket.once("connect", () => socket.write(JSON.stringify({ command }) + `
|
|
4913
5240
|
`));
|
|
4914
|
-
|
|
4915
|
-
|
|
4916
|
-
|
|
4917
|
-
|
|
5241
|
+
socket.once("data", (data) => {
|
|
5242
|
+
console.log(data.toString().trim());
|
|
5243
|
+
socket.end();
|
|
5244
|
+
resolve();
|
|
5245
|
+
});
|
|
5246
|
+
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}.`)));
|
|
4918
5247
|
});
|
|
4919
|
-
|
|
4920
|
-
}
|
|
4921
|
-
|
|
5248
|
+
return;
|
|
5249
|
+
}
|
|
5250
|
+
abort.signal.throwIfAborted();
|
|
5251
|
+
const server = serverURL(options.server ?? "https://browser-mcp.click");
|
|
5252
|
+
for (const profile of profiles) {
|
|
5253
|
+
const controlPath = controlSocketPath(root, profile);
|
|
5254
|
+
const previousSocket = await fs9.lstat(controlPath).catch((error) => {
|
|
5255
|
+
if (error.code !== "ENOENT")
|
|
5256
|
+
throw error;
|
|
5257
|
+
});
|
|
5258
|
+
if (previousSocket)
|
|
5259
|
+
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.`);
|
|
5260
|
+
abort.signal.throwIfAborted();
|
|
5261
|
+
}
|
|
5262
|
+
const results = await Promise.allSettled(profiles.map(async (profile) => {
|
|
5263
|
+
try {
|
|
5264
|
+
await startProfile(root, server, profile, options, abort.signal);
|
|
5265
|
+
} catch (cause) {
|
|
5266
|
+
requestStop();
|
|
5267
|
+
throw new Error(`Profile ${profile}: ${cause instanceof Error ? cause.message : cause}`, { cause });
|
|
5268
|
+
}
|
|
5269
|
+
}));
|
|
5270
|
+
const errors = results.flatMap((result) => result.status === "rejected" ? [result.reason] : []);
|
|
5271
|
+
if (errors.length)
|
|
5272
|
+
throw new AggregateError(errors, errors.map((error) => error.message).join(`
|
|
5273
|
+
`));
|
|
5274
|
+
} catch (error) {
|
|
5275
|
+
if (error !== abort.signal.reason)
|
|
5276
|
+
throw error;
|
|
5277
|
+
} finally {
|
|
5278
|
+
if (command === "start")
|
|
5279
|
+
for (const signal of signals)
|
|
5280
|
+
process.removeListener(signal, requestStop);
|
|
4922
5281
|
}
|
|
4923
|
-
|
|
4924
|
-
|
|
4925
|
-
|
|
5282
|
+
}
|
|
5283
|
+
async function startProfile(root, server, profile, options, groupSignal) {
|
|
5284
|
+
const abort = new AbortController;
|
|
5285
|
+
let starting = true;
|
|
5286
|
+
let session;
|
|
5287
|
+
let runtime, relay, local;
|
|
4926
5288
|
let stopQuota;
|
|
4927
|
-
const
|
|
4928
|
-
|
|
4929
|
-
|
|
4930
|
-
|
|
4931
|
-
|
|
4932
|
-
|
|
4933
|
-
|
|
4934
|
-
|
|
4935
|
-
|
|
4936
|
-
|
|
4937
|
-
|
|
5289
|
+
const controlPath = controlSocketPath(root, profile);
|
|
5290
|
+
let stopControl;
|
|
5291
|
+
const clients = new Set;
|
|
5292
|
+
const close = onceAsync(() => cleanupSteps([
|
|
5293
|
+
["Relay", async () => {
|
|
5294
|
+
await relay?.stop();
|
|
5295
|
+
}],
|
|
5296
|
+
["Download quota", async () => {
|
|
5297
|
+
await stopQuota?.();
|
|
5298
|
+
}],
|
|
5299
|
+
["Runtime", async () => {
|
|
5300
|
+
await runtime?.shutdown();
|
|
5301
|
+
}],
|
|
5302
|
+
["Local control", async () => {
|
|
5303
|
+
for (const client of clients)
|
|
5304
|
+
client.destroy();
|
|
5305
|
+
await stopControl?.();
|
|
5306
|
+
}],
|
|
5307
|
+
["Browser session", async () => {
|
|
5308
|
+
await session?.close();
|
|
5309
|
+
}]
|
|
5310
|
+
]));
|
|
5311
|
+
const requestStop = () => {
|
|
5312
|
+
abort.abort(new Error("Browser startup interrupted"));
|
|
5313
|
+
if (!starting)
|
|
5314
|
+
close().catch(() => {});
|
|
4938
5315
|
};
|
|
4939
|
-
|
|
4940
|
-
|
|
4941
|
-
|
|
4942
|
-
process.once("SIGTERM", () => {
|
|
4943
|
-
close();
|
|
4944
|
-
});
|
|
5316
|
+
groupSignal.addEventListener("abort", requestStop, { once: true });
|
|
5317
|
+
if (groupSignal.aborted)
|
|
5318
|
+
requestStop();
|
|
4945
5319
|
try {
|
|
4946
|
-
|
|
4947
|
-
|
|
4948
|
-
|
|
5320
|
+
abort.signal.throwIfAborted();
|
|
5321
|
+
session = await launchDedicated({ root, profile, ephemeral: !!options.ephemeral, chromePath: options["chrome-path"], signal: abort.signal });
|
|
5322
|
+
session.context.once("close", requestStop);
|
|
5323
|
+
abort.signal.throwIfAborted();
|
|
5324
|
+
stopQuota = await enforceDownloadQuota(session.context, path8.join(session.runPath, "chrome-downloads"));
|
|
5325
|
+
abort.signal.throwIfAborted();
|
|
5326
|
+
const token = await credential(root, server, profile, abort.signal);
|
|
5327
|
+
abort.signal.throwIfAborted();
|
|
5328
|
+
const previews = path8.join(session.runPath, "previews");
|
|
4949
5329
|
runtime = new NativeRuntime(session.context, session.instanceId, previews, server);
|
|
4950
|
-
runtime.plugins.push(await createDataPlugin(runtime, { directory:
|
|
5330
|
+
runtime.plugins.push(await createDataPlugin(runtime, { directory: path8.join(session.runPath, "data"), serverOrigin: server, allowInsecureLoopback: new URL(server).protocol === "http:" }));
|
|
5331
|
+
abort.signal.throwIfAborted();
|
|
5332
|
+
runtime.plugins.push(createForwardPlugin({ serverUrl: server }));
|
|
4951
5333
|
relay = new Relay(runtime, server, token, previews, !!options.liveView);
|
|
4952
5334
|
await session.context.route("**/*", async (route) => {
|
|
4953
5335
|
if (!runtime.allowURL(route.request().url()))
|
|
@@ -4955,10 +5337,15 @@ Dedicated Chrome only. Foreground pipe lifecycle: stopping the CLI closes Chrome
|
|
|
4955
5337
|
else
|
|
4956
5338
|
await route.continue();
|
|
4957
5339
|
});
|
|
4958
|
-
|
|
5340
|
+
abort.signal.throwIfAborted();
|
|
5341
|
+
local = net2.createServer((socket) => {
|
|
5342
|
+
clients.add(socket);
|
|
5343
|
+
socket.once("close", () => clients.delete(socket));
|
|
4959
5344
|
socket.setTimeout(2000, () => socket.destroy());
|
|
4960
|
-
let data = "";
|
|
5345
|
+
let data = "", handled = false;
|
|
4961
5346
|
socket.on("data", (chunk) => {
|
|
5347
|
+
if (handled)
|
|
5348
|
+
return;
|
|
4962
5349
|
data += chunk.toString();
|
|
4963
5350
|
if (data.length > 1024) {
|
|
4964
5351
|
socket.destroy();
|
|
@@ -4967,6 +5354,7 @@ Dedicated Chrome only. Foreground pipe lifecycle: stopping the CLI closes Chrome
|
|
|
4967
5354
|
if (!data.includes(`
|
|
4968
5355
|
`))
|
|
4969
5356
|
return;
|
|
5357
|
+
handled = true;
|
|
4970
5358
|
(async () => {
|
|
4971
5359
|
const cmd = JSON.parse(data).command;
|
|
4972
5360
|
if (cmd === "pause")
|
|
@@ -4976,28 +5364,33 @@ Dedicated Chrome only. Foreground pipe lifecycle: stopping the CLI closes Chrome
|
|
|
4976
5364
|
else if (cmd === "stop") {
|
|
4977
5365
|
socket.end(`{"state":"stopping"}
|
|
4978
5366
|
`);
|
|
4979
|
-
|
|
5367
|
+
requestStop();
|
|
4980
5368
|
return;
|
|
4981
5369
|
} else if (cmd !== "status")
|
|
4982
5370
|
throw new Error("Invalid command");
|
|
4983
|
-
socket.end(JSON.stringify({ state: relay.state, paused: relay.paused, instanceId: session.instanceId, profile, version: "0.3.
|
|
5371
|
+
socket.end(JSON.stringify({ state: relay.state, paused: relay.paused, instanceId: session.instanceId, profile, version: "0.3.7", protocol: 3 }) + `
|
|
4984
5372
|
`);
|
|
4985
5373
|
})().catch(() => socket.destroy());
|
|
4986
5374
|
});
|
|
4987
5375
|
});
|
|
4988
|
-
|
|
4989
|
-
local
|
|
4990
|
-
|
|
4991
|
-
|
|
4992
|
-
|
|
4993
|
-
|
|
4994
|
-
|
|
4995
|
-
|
|
4996
|
-
});
|
|
4997
|
-
console.error(`Dedicated Chrome running. Local controls: browser-mcp browser pause|status|stop --profile ${profile}. Ctrl-C closes Chrome.`);
|
|
5376
|
+
try {
|
|
5377
|
+
stopControl = await listenControl(local, root, controlPath);
|
|
5378
|
+
} catch (error) {
|
|
5379
|
+
throw new Error(`Cannot bind local control socket ${controlPath}: ${error instanceof Error ? error.message : error}. No existing socket was removed. Stop the previous owner and run browser-mcp browser recover --profile ${profile}; see the recovery documentation if ownership cannot be verified.`);
|
|
5380
|
+
}
|
|
5381
|
+
abort.signal.throwIfAborted();
|
|
5382
|
+
starting = false;
|
|
5383
|
+
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.`);
|
|
4998
5384
|
await relay.start();
|
|
5385
|
+
} catch (error) {
|
|
5386
|
+
if (error !== abort.signal.reason && !(abort.signal.aborted && error instanceof Error && error.name === "AbortError"))
|
|
5387
|
+
throw error;
|
|
4999
5388
|
} finally {
|
|
5000
|
-
|
|
5389
|
+
try {
|
|
5390
|
+
await close();
|
|
5391
|
+
} finally {
|
|
5392
|
+
groupSignal.removeEventListener("abort", requestStop);
|
|
5393
|
+
}
|
|
5001
5394
|
}
|
|
5002
5395
|
}
|
|
5003
5396
|
export {
|