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