@ricsam/browser-mcp 0.0.0 → 0.3.4
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/LICENSE +14 -0
- package/README.md +51 -43
- package/THIRD_PARTY_NOTICES.md +17 -0
- package/dist/chunk-1sjcwr28.js +4 -0
- package/dist/chunk-2hzkme2s.js +41 -0
- package/dist/chunk-847prxk6.js +98 -0
- package/dist/chunk-cy1a8r79.js +255 -0
- package/dist/chunk-j6psfksr.js +52 -0
- package/dist/chunk-s1kjxpf5.js +5005 -0
- package/dist/chunk-swy0qtx0.js +60 -0
- package/dist/chunk-xgk37h9a.js +77 -0
- package/dist/main.js +36 -0
- package/package.json +10 -7
package/LICENSE
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
Browser MCP CLI Distribution License
|
|
2
|
+
Copyright (c) 2026 ricsam. All rights reserved.
|
|
3
|
+
|
|
4
|
+
Permission is granted to install and execute the published @ricsam/browser-mcp
|
|
5
|
+
CLI package, and to make copies reasonably necessary for those purposes.
|
|
6
|
+
This permission does not grant rights to publish the private source repository,
|
|
7
|
+
redistribute modified versions, sublicense the software, or distribute source
|
|
8
|
+
outside the published package. All rights not expressly granted are reserved.
|
|
9
|
+
Third-party dependencies retain their own licenses; see THIRD_PARTY_NOTICES.md.
|
|
10
|
+
|
|
11
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
12
|
+
IMPLIED, INCLUDING MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
|
13
|
+
NONINFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
|
|
14
|
+
CLAIM, DAMAGES OR OTHER LIABILITY ARISING FROM USE OF THE SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,45 +1,53 @@
|
|
|
1
1
|
# @ricsam/browser-mcp
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
3
|
+
Native Chrome companion, version 0.3.0. Requires Node >=22.14 and an installed
|
|
4
|
+
Google Chrome. No browser download or startup occurs during npm installation.
|
|
5
|
+
|
|
6
|
+
```sh
|
|
7
|
+
npx @ricsam/browser-mcp --help
|
|
8
|
+
npx @ricsam/browser-mcp browser start --server https://browser-mcp.click --profile work
|
|
9
|
+
browser-mcp browser status --profile work
|
|
10
|
+
browser-mcp browser pause --profile work
|
|
11
|
+
browser-mcp browser resume --profile work
|
|
12
|
+
browser-mcp browser stop --profile work
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
Approve the printed pairing link in your ordinary browser. Credentials are stored
|
|
16
|
+
in restrictive files under `~/.browser-mcp`; never pass them in command arguments.
|
|
17
|
+
Profiles are dedicated and persistent by default. `--ephemeral` is explicit.
|
|
18
|
+
`--chrome-path /absolute/path/to/chrome` selects an installed binary, never a
|
|
19
|
+
profile. Profile names cannot contain paths. Your daily-driver profile is never
|
|
20
|
+
opened, copied or attached. `--live-view` enables screenshot-based live view
|
|
21
|
+
locally (off by default); remote viewers cannot enable it.
|
|
22
|
+
|
|
23
|
+
Foreground pipe lifecycle: keep the CLI running. Ctrl-C, stop, or normal CLI exit
|
|
24
|
+
closes its Chrome. There is no detach or automatic CDP reattachment. Each launch
|
|
25
|
+
has a fresh instance identity. Relay reconnect does not replay admitted actions.
|
|
26
|
+
Crash locks are deliberately not removed automatically: verify the exact prior
|
|
27
|
+
owner and Chrome processes are stopped before operator recovery. Retained crash
|
|
28
|
+
files are not automatically scavenged. Never remove directories by name prefix.
|
|
29
|
+
|
|
30
|
+
Linux requires a graphical display and working Chrome sandbox (unprivileged
|
|
31
|
+
user namespaces or a vendor-supported sandbox). macOS discovery is implemented
|
|
32
|
+
but requires platform verification before release. Windows browser hosting is
|
|
33
|
+
explicitly unavailable pending private ACL/lifecycle verification. Agent-only
|
|
34
|
+
helpers do not load Playwright or require a display:
|
|
35
|
+
|
|
36
|
+
```sh
|
|
37
|
+
browser-mcp files --help
|
|
38
|
+
browser-mcp secrets --help
|
|
39
|
+
browser-mcp forward --help
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
Native file/secret capabilities use separate bounded HTTPS streams. Secret
|
|
43
|
+
exports require explicit safe output paths; they are never printed to stdout.
|
|
44
|
+
Do not source page-derived dotenv as shell code. Capability files are sensitive.
|
|
45
|
+
|
|
46
|
+
Password inputs are masked at observation source, including nested frames.
|
|
47
|
+
Snapshots require exactly Playwright 1.63.0. Screenshots/live view, arbitrary JS,
|
|
48
|
+
ordinary page text and hostile scripts are **not** universally redacted. Clipboard
|
|
49
|
+
requires explicit authority and browser permissions; permissions are not silently
|
|
50
|
+
granted. Control-plane and privileged frames are blocked. The runtime is not a
|
|
51
|
+
remote shell, public CDP endpoint or arbitrary host-filesystem server.
|
|
52
|
+
|
|
53
|
+
License: see LICENSE. Public dependency notices: THIRD_PARTY_NOTICES.md.
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
# Notices
|
|
2
|
+
|
|
3
|
+
Browser semantic/action, event, input and snapshot modules were adapted with the
|
|
4
|
+
owner's authorization from the private `ricsam/r5d-dev` project, package
|
|
5
|
+
`packages/r5d-browser`. That repository and its unpublished APIs are not runtime
|
|
6
|
+
dependencies. The snapshot adapter is specifically reconciled with Playwright
|
|
7
|
+
1.63.0 and fails closed on incompatible private snapshot APIs.
|
|
8
|
+
|
|
9
|
+
Public runtime dependencies installed alongside this package:
|
|
10
|
+
|
|
11
|
+
- `playwright-core` 1.63.0 — Microsoft Corporation, Apache License 2.0.
|
|
12
|
+
Its package includes LICENSE, NOTICE and ThirdPartyNotices.txt. Those notices
|
|
13
|
+
apply to its bundled third-party code. No browser binary is included here.
|
|
14
|
+
- `ws` 8.22.0 — Einar Otto Stangvik and contributors, MIT License.
|
|
15
|
+
See `ws/LICENSE` in the installed dependency.
|
|
16
|
+
|
|
17
|
+
Chrome is separately installed software governed by its vendor's terms.
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
// cli/src/agent/capability.ts
|
|
2
|
+
import { open, constants } from "node:fs/promises";
|
|
3
|
+
import { Readable } from "node:stream";
|
|
4
|
+
async function readCapability(path) {
|
|
5
|
+
let text = "";
|
|
6
|
+
if (path === "-") {
|
|
7
|
+
for await (const chunk of process.stdin) {
|
|
8
|
+
text += chunk;
|
|
9
|
+
if (Buffer.byteLength(text) > 16384)
|
|
10
|
+
throw new Error("Capability too large");
|
|
11
|
+
}
|
|
12
|
+
} else {
|
|
13
|
+
const file = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
14
|
+
try {
|
|
15
|
+
const s = await file.stat();
|
|
16
|
+
if (!s.isFile() || s.size > 16384 || process.platform !== "win32" && (s.mode & 63) !== 0)
|
|
17
|
+
throw new Error("Capability file must be private");
|
|
18
|
+
text = await file.readFile("utf8");
|
|
19
|
+
} finally {
|
|
20
|
+
await file.close();
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
const cap = JSON.parse(text);
|
|
24
|
+
const u = new URL(cap.url);
|
|
25
|
+
if (u.protocol !== "https:" || u.username || u.password || u.search || u.hash || !/^\/api\/native-data\/[a-zA-Z0-9-]+$/.test(u.pathname) || !["GET", "PUT"].includes(cap.method) || !/^Bearer [A-Za-z0-9_-]{43}$/.test(cap.headers.Authorization) || cap.expiresAt <= Date.now() || !Number.isSafeInteger(cap.limits.maxBytes) || cap.limits.maxBytes < 0 || cap.limits.maxBytes > 256 * 1024 * 1024)
|
|
26
|
+
throw new Error("Invalid capability");
|
|
27
|
+
return cap;
|
|
28
|
+
}
|
|
29
|
+
async function capabilityFetch(cap, body) {
|
|
30
|
+
const response = await fetch(cap.url, { method: cap.method, headers: { Authorization: cap.headers.Authorization }, body: body ? Readable.toWeb(body) : undefined, duplex: "half", redirect: "error", signal: AbortSignal.timeout(120000) });
|
|
31
|
+
if (!response.ok)
|
|
32
|
+
throw new Error("Capability transfer failed; do not automatically retry");
|
|
33
|
+
return response;
|
|
34
|
+
}
|
|
35
|
+
async function exclusiveOutput(path) {
|
|
36
|
+
if (process.platform === "win32")
|
|
37
|
+
throw new Error("Secret/file output on Windows requires ACL support; unavailable");
|
|
38
|
+
return open(path, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 384);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export { readCapability, capabilityFetch, exclusiveOutput };
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import {
|
|
2
|
+
parseSecrets,
|
|
3
|
+
serializeSecrets
|
|
4
|
+
} from "./chunk-j6psfksr.js";
|
|
5
|
+
import {
|
|
6
|
+
capabilityFetch,
|
|
7
|
+
exclusiveOutput,
|
|
8
|
+
readCapability
|
|
9
|
+
} from "./chunk-2hzkme2s.js";
|
|
10
|
+
import"./chunk-1sjcwr28.js";
|
|
11
|
+
|
|
12
|
+
// cli/src/agent/secrets.ts
|
|
13
|
+
import { spawn } from "node:child_process";
|
|
14
|
+
import { unlink } from "node:fs/promises";
|
|
15
|
+
async function receive(path, format) {
|
|
16
|
+
const cap = await readCapability(path);
|
|
17
|
+
if (cap.method !== "GET" || cap.limits.maxBytes > 1024 * 1024)
|
|
18
|
+
throw new Error("Secret export capability required");
|
|
19
|
+
const response = await capabilityFetch(cap);
|
|
20
|
+
if (!response.body)
|
|
21
|
+
throw new Error("Missing export body");
|
|
22
|
+
const reader = response.body.getReader();
|
|
23
|
+
const chunks = [];
|
|
24
|
+
let bytes = 0;
|
|
25
|
+
try {
|
|
26
|
+
for (;; ) {
|
|
27
|
+
const r = await reader.read();
|
|
28
|
+
if (r.done)
|
|
29
|
+
break;
|
|
30
|
+
bytes += r.value.length;
|
|
31
|
+
if (bytes > cap.limits.maxBytes)
|
|
32
|
+
throw new Error("Export limit");
|
|
33
|
+
chunks.push(r.value);
|
|
34
|
+
}
|
|
35
|
+
return parseSecrets(Buffer.concat(chunks).toString("utf8"), format);
|
|
36
|
+
} catch {
|
|
37
|
+
await reader.cancel().catch(() => {});
|
|
38
|
+
throw new Error("Secret export failed; request a new capability");
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
async function exportSecrets(capabilityPath, outputPath, format = "json") {
|
|
42
|
+
const file = await exclusiveOutput(outputPath);
|
|
43
|
+
let ok = false;
|
|
44
|
+
try {
|
|
45
|
+
const values = await receive(capabilityPath, format);
|
|
46
|
+
await file.writeFile(serializeSecrets(values, format));
|
|
47
|
+
await file.sync();
|
|
48
|
+
ok = true;
|
|
49
|
+
return { exported: true };
|
|
50
|
+
} finally {
|
|
51
|
+
await file.close();
|
|
52
|
+
if (!ok)
|
|
53
|
+
await unlink(outputPath).catch(() => {});
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
async function execSecrets(capabilityPath, command, args, format = "json") {
|
|
57
|
+
if (!command)
|
|
58
|
+
throw new Error("Executable required");
|
|
59
|
+
const values = await receive(capabilityPath, format);
|
|
60
|
+
if (Object.values(values).some((v) => v.includes("\x00")))
|
|
61
|
+
throw new Error("NUL is not supported in environment values");
|
|
62
|
+
return new Promise((resolve, reject) => {
|
|
63
|
+
const child = spawn(command, args, { shell: false, env: { ...process.env, ...values }, stdio: "inherit" });
|
|
64
|
+
child.once("error", () => reject(new Error("Secret child could not start")));
|
|
65
|
+
child.once("exit", (code) => resolve(code ?? 1));
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
async function runSecretsCommand(args) {
|
|
69
|
+
if (!args.length || args[0] === "--help" || args[0] === "help" || args.indexOf("--help") >= 0 && (args.indexOf("--") < 0 || args.indexOf("--help") < args.indexOf("--"))) {
|
|
70
|
+
console.log(`Usage: secrets export --capability private.json|- --format json|dotenv --output PATH
|
|
71
|
+
secrets exec --capability private.json|- --format json|dotenv -- executable args`);
|
|
72
|
+
return;
|
|
73
|
+
}
|
|
74
|
+
const [op, ...rest] = args;
|
|
75
|
+
const value = (flag) => {
|
|
76
|
+
const i = rest.indexOf(flag);
|
|
77
|
+
if (i < 0 || !rest[i + 1])
|
|
78
|
+
throw new Error(`Required ${flag}`);
|
|
79
|
+
return rest[i + 1];
|
|
80
|
+
};
|
|
81
|
+
const format = rest.includes("--format") ? value("--format") : "json";
|
|
82
|
+
if (format !== "json" && format !== "dotenv")
|
|
83
|
+
throw new Error("Invalid secret format");
|
|
84
|
+
if (op === "export")
|
|
85
|
+
return exportSecrets(value("--capability"), value("--output"), format);
|
|
86
|
+
if (op === "exec") {
|
|
87
|
+
const i = rest.indexOf("--");
|
|
88
|
+
if (i < 0)
|
|
89
|
+
throw new Error("Executable must follow --");
|
|
90
|
+
return execSecrets(value("--capability"), rest[i + 1] ?? "", rest.slice(i + 2), format);
|
|
91
|
+
}
|
|
92
|
+
throw new Error("Usage: secrets export|exec --capability private.json|- --format json|dotenv --output PATH | -- executable args");
|
|
93
|
+
}
|
|
94
|
+
export {
|
|
95
|
+
execSecrets,
|
|
96
|
+
exportSecrets,
|
|
97
|
+
runSecretsCommand
|
|
98
|
+
};
|
|
@@ -0,0 +1,255 @@
|
|
|
1
|
+
// cli/src/forward/connector.ts
|
|
2
|
+
import net from "node:net";
|
|
3
|
+
import WebSocket from "ws";
|
|
4
|
+
|
|
5
|
+
// shared/forwarding.ts
|
|
6
|
+
var FORWARD = { path: "/api/forward/v1", maxPayload: 16384, window: 65536, maxStreams: 32, maxBuffered: 2097152, maxLeases: 128, maxScopeLeases: 8, maxTtl: 900000, heartbeatMs: 1e4, deadMs: 35000 };
|
|
7
|
+
function frame(type, id = 0, data = new Uint8Array) {
|
|
8
|
+
const out = new Uint8Array(5 + data.length);
|
|
9
|
+
out[0] = type;
|
|
10
|
+
new DataView(out.buffer).setUint32(1, id);
|
|
11
|
+
out.set(data, 5);
|
|
12
|
+
return out;
|
|
13
|
+
}
|
|
14
|
+
function decode(bytes) {
|
|
15
|
+
if (bytes.length < 5 || bytes.length > FORWARD.maxPayload + 5)
|
|
16
|
+
throw new Error("invalid forwarding frame");
|
|
17
|
+
const type = bytes[0];
|
|
18
|
+
const id = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength).getUint32(1);
|
|
19
|
+
const data = bytes.subarray(5);
|
|
20
|
+
if (type < 1 /* Open */ || type > 8 /* Pong */ || (type === 2 /* Data */ ? !id || !data.length : type === 5 /* Credit */ ? !id || data.length !== 4 : data.length !== 0))
|
|
21
|
+
throw new Error("invalid forwarding frame");
|
|
22
|
+
if (type >= 6 /* Ready */ !== (id === 0))
|
|
23
|
+
throw new Error("invalid stream identity");
|
|
24
|
+
return { type, id, data };
|
|
25
|
+
}
|
|
26
|
+
function credit(id, n) {
|
|
27
|
+
const b = new Uint8Array(4);
|
|
28
|
+
new DataView(b.buffer).setUint32(0, n);
|
|
29
|
+
return frame(5 /* Credit */, id, b);
|
|
30
|
+
}
|
|
31
|
+
function sameScope(a, b) {
|
|
32
|
+
return a.browserId === b.browserId && a.tokenId === b.tokenId && a.sessionKey === b.sessionKey && a.instanceId === b.instanceId;
|
|
33
|
+
}
|
|
34
|
+
function loopback(value) {
|
|
35
|
+
if (value !== "127.0.0.1" && value !== "::1")
|
|
36
|
+
throw new Error("explicit loopback address required");
|
|
37
|
+
return value;
|
|
38
|
+
}
|
|
39
|
+
function port(value) {
|
|
40
|
+
if (!Number.isInteger(value) || Number(value) < 1 || Number(value) > 65535)
|
|
41
|
+
throw new Error("invalid TCP port");
|
|
42
|
+
return Number(value);
|
|
43
|
+
}
|
|
44
|
+
function validateCapability(c) {
|
|
45
|
+
if (!c || c.version !== 1 || typeof c.id !== "string" || !/^[0-9a-f-]{36}$/.test(c.id) || !["browser", "agent"].includes(c.role) || !c.headers || Object.keys(c.headers).length !== 1 || typeof c.headers.Authorization !== "string" || !/^Bearer [A-Za-z0-9_-]{43}$/.test(c.headers.Authorization) || !c.scope || Object.keys(c.scope).length !== 4 || ["browserId", "tokenId", "sessionKey", "instanceId"].some((k) => typeof c.scope[k] !== "string" || !c.scope[k] || c.scope[k].length > 512))
|
|
46
|
+
throw new Error("invalid forward capability");
|
|
47
|
+
const u = new URL(c.url);
|
|
48
|
+
if (u.protocol !== "wss:" || u.username || u.password || u.search || u.hash || u.pathname !== FORWARD.path)
|
|
49
|
+
throw new Error("forward requires credential-free WSS URL");
|
|
50
|
+
if (!Number.isFinite(c.expiresAt) || c.expiresAt <= Date.now() || c.expiresAt > Date.now() + FORWARD.maxTtl)
|
|
51
|
+
throw new Error("forward capability expired or too long");
|
|
52
|
+
loopback(c.browserHost);
|
|
53
|
+
loopback(c.targetHost);
|
|
54
|
+
port(c.browserPort);
|
|
55
|
+
port(c.targetPort);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// cli/src/forward/connector.ts
|
|
59
|
+
async function connectForward(cap) {
|
|
60
|
+
validateCapability(cap);
|
|
61
|
+
const ws = new WebSocket(cap.url, { headers: cap.headers, maxPayload: FORWARD.maxPayload + 5, perMessageDeflate: false, handshakeTimeout: 1e4 });
|
|
62
|
+
const streams = new Map;
|
|
63
|
+
let listener;
|
|
64
|
+
let ready = false;
|
|
65
|
+
let ended = false;
|
|
66
|
+
let lastError = null;
|
|
67
|
+
let nextId = 0;
|
|
68
|
+
let lastSeen = Date.now();
|
|
69
|
+
let resolveClosed;
|
|
70
|
+
const closed = new Promise((r) => resolveClosed = r);
|
|
71
|
+
let resolveOpen;
|
|
72
|
+
let rejectOpen;
|
|
73
|
+
const opened = new Promise((r, j) => {
|
|
74
|
+
resolveOpen = r;
|
|
75
|
+
rejectOpen = j;
|
|
76
|
+
});
|
|
77
|
+
function close(reason) {
|
|
78
|
+
if (ended)
|
|
79
|
+
return;
|
|
80
|
+
ended = true;
|
|
81
|
+
ready = false;
|
|
82
|
+
lastError = reason ?? null;
|
|
83
|
+
clearInterval(heartbeat);
|
|
84
|
+
clearTimeout(expiry);
|
|
85
|
+
listener?.close();
|
|
86
|
+
for (const s of streams.values())
|
|
87
|
+
s.socket.destroy();
|
|
88
|
+
streams.clear();
|
|
89
|
+
ws.terminate();
|
|
90
|
+
rejectOpen(new Error(reason ?? "forward closed"));
|
|
91
|
+
resolveClosed();
|
|
92
|
+
}
|
|
93
|
+
function send(bytes) {
|
|
94
|
+
if (ended || ws.readyState !== WebSocket.OPEN || ws.bufferedAmount + bytes.byteLength > FORWARD.maxBuffered) {
|
|
95
|
+
close("forward transport unavailable");
|
|
96
|
+
return false;
|
|
97
|
+
}
|
|
98
|
+
ws.send(bytes, { binary: true }, (error) => {
|
|
99
|
+
if (error)
|
|
100
|
+
close("forward transport failed");
|
|
101
|
+
});
|
|
102
|
+
return true;
|
|
103
|
+
}
|
|
104
|
+
function reset(id, notify = true) {
|
|
105
|
+
const s = streams.get(id);
|
|
106
|
+
if (!s)
|
|
107
|
+
return;
|
|
108
|
+
streams.delete(id);
|
|
109
|
+
s.socket.destroy();
|
|
110
|
+
if (notify)
|
|
111
|
+
send(frame(4 /* Reset */, id));
|
|
112
|
+
}
|
|
113
|
+
function pump(id) {
|
|
114
|
+
const s = streams.get(id);
|
|
115
|
+
if (!s)
|
|
116
|
+
return;
|
|
117
|
+
while (s.credit > 0) {
|
|
118
|
+
const n = Math.min(FORWARD.maxPayload, s.credit, s.socket.readableLength);
|
|
119
|
+
const b = s.socket.read(n);
|
|
120
|
+
if (!b)
|
|
121
|
+
break;
|
|
122
|
+
s.credit -= b.length;
|
|
123
|
+
if (!send(frame(2 /* Data */, id, b)))
|
|
124
|
+
return;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
function attach(id, socket) {
|
|
128
|
+
socket.setNoDelay(true);
|
|
129
|
+
socket.setTimeout(120000, () => reset(id));
|
|
130
|
+
const s = { socket, credit: 0, outstanding: FORWARD.window, localFin: false, remoteFin: false };
|
|
131
|
+
streams.set(id, s);
|
|
132
|
+
socket.on("readable", () => pump(id));
|
|
133
|
+
socket.on("end", () => {
|
|
134
|
+
if (!streams.has(id))
|
|
135
|
+
return;
|
|
136
|
+
s.localFin = true;
|
|
137
|
+
send(frame(3 /* Fin */, id));
|
|
138
|
+
if (s.remoteFin)
|
|
139
|
+
streams.delete(id);
|
|
140
|
+
});
|
|
141
|
+
socket.on("error", () => reset(id));
|
|
142
|
+
socket.on("close", () => {
|
|
143
|
+
if (streams.has(id))
|
|
144
|
+
reset(id);
|
|
145
|
+
});
|
|
146
|
+
send(credit(id, FORWARD.window));
|
|
147
|
+
}
|
|
148
|
+
const heartbeat = setInterval(() => {
|
|
149
|
+
if (Date.now() - lastSeen > FORWARD.deadMs)
|
|
150
|
+
close("heartbeat expired");
|
|
151
|
+
else
|
|
152
|
+
send(frame(7 /* Ping */));
|
|
153
|
+
}, FORWARD.heartbeatMs);
|
|
154
|
+
heartbeat.unref();
|
|
155
|
+
const expiry = setTimeout(() => close("forward expired"), Math.max(1, cap.expiresAt - Date.now()));
|
|
156
|
+
expiry.unref();
|
|
157
|
+
ws.on("open", () => {
|
|
158
|
+
if (cap.role === "agent") {
|
|
159
|
+
resolveOpen();
|
|
160
|
+
return;
|
|
161
|
+
}
|
|
162
|
+
listener = net.createServer({ allowHalfOpen: true, pauseOnConnect: true }, (socket) => {
|
|
163
|
+
if (!ready || streams.size >= FORWARD.maxStreams || nextId === 4294967295) {
|
|
164
|
+
socket.destroy();
|
|
165
|
+
return;
|
|
166
|
+
}
|
|
167
|
+
const id = ++nextId;
|
|
168
|
+
send(frame(1 /* Open */, id));
|
|
169
|
+
attach(id, socket);
|
|
170
|
+
});
|
|
171
|
+
listener.on("error", () => close("browser loopback port unavailable"));
|
|
172
|
+
listener.listen({ host: cap.browserHost, port: cap.browserPort, exclusive: true }, () => resolveOpen());
|
|
173
|
+
});
|
|
174
|
+
ws.on("error", () => close("forward connection failed"));
|
|
175
|
+
ws.on("close", () => close("forward disconnected"));
|
|
176
|
+
ws.on("message", (raw, isBinary) => {
|
|
177
|
+
try {
|
|
178
|
+
if (!isBinary)
|
|
179
|
+
throw new Error("text frame forbidden");
|
|
180
|
+
const bytes = raw instanceof ArrayBuffer ? new Uint8Array(raw) : Array.isArray(raw) ? Buffer.concat(raw) : raw;
|
|
181
|
+
const f = decode(bytes);
|
|
182
|
+
lastSeen = Date.now();
|
|
183
|
+
if (f.type === 7 /* Ping */) {
|
|
184
|
+
send(frame(8 /* Pong */));
|
|
185
|
+
return;
|
|
186
|
+
}
|
|
187
|
+
if (f.type === 8 /* Pong */)
|
|
188
|
+
return;
|
|
189
|
+
if (f.type === 6 /* Ready */) {
|
|
190
|
+
ready = true;
|
|
191
|
+
if (cap.role === "browser")
|
|
192
|
+
send(frame(6 /* Ready */));
|
|
193
|
+
return;
|
|
194
|
+
}
|
|
195
|
+
if (f.type === 1 /* Open */) {
|
|
196
|
+
if (cap.role !== "agent" || streams.has(f.id) || streams.size >= FORWARD.maxStreams)
|
|
197
|
+
throw new Error("invalid open");
|
|
198
|
+
const socket = net.createConnection({ host: cap.targetHost, port: cap.targetPort, allowHalfOpen: true });
|
|
199
|
+
attach(f.id, socket);
|
|
200
|
+
return;
|
|
201
|
+
}
|
|
202
|
+
const s = streams.get(f.id);
|
|
203
|
+
if (!s) {
|
|
204
|
+
if (f.type === 4 /* Reset */ || f.type === 5 /* Credit */)
|
|
205
|
+
return;
|
|
206
|
+
throw new Error("unknown stream");
|
|
207
|
+
}
|
|
208
|
+
if (f.type === 4 /* Reset */) {
|
|
209
|
+
reset(f.id, false);
|
|
210
|
+
return;
|
|
211
|
+
}
|
|
212
|
+
if (f.type === 5 /* Credit */) {
|
|
213
|
+
const n = new DataView(f.data.buffer, f.data.byteOffset, 4).getUint32(0);
|
|
214
|
+
if (!n || s.credit + n > FORWARD.window)
|
|
215
|
+
throw new Error("invalid credit");
|
|
216
|
+
s.credit += n;
|
|
217
|
+
pump(f.id);
|
|
218
|
+
return;
|
|
219
|
+
}
|
|
220
|
+
if (f.type === 2 /* Data */) {
|
|
221
|
+
if (s.remoteFin || f.data.length > s.outstanding)
|
|
222
|
+
throw new Error("flow budget exceeded");
|
|
223
|
+
s.outstanding -= f.data.length;
|
|
224
|
+
const n = f.data.length;
|
|
225
|
+
s.socket.write(f.data, (error) => {
|
|
226
|
+
if (error) {
|
|
227
|
+
reset(f.id);
|
|
228
|
+
return;
|
|
229
|
+
}
|
|
230
|
+
if (streams.has(f.id)) {
|
|
231
|
+
s.outstanding += n;
|
|
232
|
+
send(credit(f.id, n));
|
|
233
|
+
}
|
|
234
|
+
});
|
|
235
|
+
return;
|
|
236
|
+
}
|
|
237
|
+
if (f.type === 3 /* Fin */) {
|
|
238
|
+
if (s.remoteFin)
|
|
239
|
+
throw new Error("duplicate EOF");
|
|
240
|
+
s.remoteFin = true;
|
|
241
|
+
s.socket.end();
|
|
242
|
+
if (s.localFin)
|
|
243
|
+
streams.delete(f.id);
|
|
244
|
+
return;
|
|
245
|
+
}
|
|
246
|
+
throw new Error("invalid frame");
|
|
247
|
+
} catch {
|
|
248
|
+
close("forward protocol failure");
|
|
249
|
+
}
|
|
250
|
+
});
|
|
251
|
+
await opened;
|
|
252
|
+
return { closed, close: () => close(), status: () => ({ ready, activeConnections: streams.size, lastError }) };
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
export { FORWARD, sameScope, connectForward };
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
// cli/src/data/contracts.ts
|
|
2
|
+
var LIMITS = { file: 256 * 1024 * 1024, session: 512 * 1024 * 1024, browser: 1024 * 1024 * 1024, secret: 1024 * 1024, value: 65536, count: 128, ttl: 300000, duration: 120000 };
|
|
3
|
+
var sameScope = (a, b) => a.browserId === b.browserId && a.tokenId === b.tokenId && a.sessionKey === b.sessionKey && a.instanceId === b.instanceId;
|
|
4
|
+
var validName = (n) => /^[A-Za-z_][A-Za-z0-9_]*$/.test(n);
|
|
5
|
+
function secureDataUrl(u, allowInsecureLoopback = false) {
|
|
6
|
+
return u.protocol === "https:" || allowInsecureLoopback && u.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(u.hostname);
|
|
7
|
+
}
|
|
8
|
+
function validateGrant(g, origin, resourceId, allowInsecureLoopback = false) {
|
|
9
|
+
const u = new URL(g.url);
|
|
10
|
+
if (!secureDataUrl(u, allowInsecureLoopback) || u.origin !== new URL(origin).origin || u.username || u.password || u.search || u.hash || !/^\/api\/native-data\/[a-zA-Z0-9-]+\/runtime$/.test(u.pathname) || g.resourceId !== resourceId || g.expiresAt <= Date.now() || g.expiresAt > Date.now() + 65000 || !/^Bearer [A-Za-z0-9_-]{43}$/.test(g.headers.Authorization) || !Number.isSafeInteger(g.limits.maxBytes) || g.limits.maxBytes < 0 || g.limits.maxBytes > LIMITS.file)
|
|
11
|
+
throw new Error("Invalid data grant");
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
// cli/src/data/serialization.ts
|
|
15
|
+
function validateValues(input) {
|
|
16
|
+
if (!input || typeof input !== "object" || Array.isArray(input))
|
|
17
|
+
throw new Error("Invalid secret document");
|
|
18
|
+
const out = Object.create(null);
|
|
19
|
+
for (const [k, v] of Object.entries(input)) {
|
|
20
|
+
if (!validName(k) || typeof v !== "string")
|
|
21
|
+
throw new Error("Invalid secret document");
|
|
22
|
+
out[k] = v;
|
|
23
|
+
}
|
|
24
|
+
return out;
|
|
25
|
+
}
|
|
26
|
+
function serializeSecrets(values, format) {
|
|
27
|
+
validateValues(values);
|
|
28
|
+
return format === "json" ? JSON.stringify(values) : Object.entries(values).map(([k, v]) => `${k}=${JSON.stringify(v)}`).join(`
|
|
29
|
+
`) + `
|
|
30
|
+
`;
|
|
31
|
+
}
|
|
32
|
+
function parseSecrets(text, format) {
|
|
33
|
+
if (format === "json")
|
|
34
|
+
return validateValues(JSON.parse(text));
|
|
35
|
+
const result = Object.create(null);
|
|
36
|
+
for (const line of text.split(`
|
|
37
|
+
`)) {
|
|
38
|
+
if (!line)
|
|
39
|
+
continue;
|
|
40
|
+
const index = line.indexOf("=");
|
|
41
|
+
const key = line.slice(0, index);
|
|
42
|
+
if (index < 1 || !validName(key) || Object.hasOwn(result, key))
|
|
43
|
+
throw new Error("Invalid dotenv document");
|
|
44
|
+
const value = JSON.parse(line.slice(index + 1));
|
|
45
|
+
if (typeof value !== "string")
|
|
46
|
+
throw new Error("Invalid dotenv value");
|
|
47
|
+
result[key] = value;
|
|
48
|
+
}
|
|
49
|
+
return result;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export { LIMITS, sameScope, validName, secureDataUrl, validateGrant, serializeSecrets, parseSecrets };
|