turno-browser 0.4.0 → 0.5.0
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/CHANGELOG.md +24 -0
- package/README.md +92 -149
- package/dist/act-model.js +4 -3
- package/dist/act.js +2 -1
- package/dist/api.d.ts +63 -2
- package/dist/api.js +14 -4
- package/dist/background-state.d.ts +54 -0
- package/dist/background-state.js +97 -0
- package/dist/background.d.ts +69 -0
- package/dist/background.js +458 -0
- package/dist/bin/mcp.js +48 -8
- package/dist/captcha.js +3 -2
- package/dist/cli/background.d.ts +11 -0
- package/dist/cli/background.js +132 -0
- package/dist/cli/commands.d.ts +16 -0
- package/dist/cli/commands.js +515 -0
- package/dist/cli/context.d.ts +75 -0
- package/dist/cli/context.js +44 -0
- package/dist/cli/do-background.d.ts +27 -0
- package/dist/cli/do-background.js +212 -0
- package/dist/cli/do.d.ts +85 -0
- package/dist/cli/do.js +558 -0
- package/dist/cli/flows.d.ts +28 -0
- package/dist/cli/flows.js +303 -0
- package/dist/cli/identity.d.ts +37 -0
- package/dist/cli/identity.js +906 -0
- package/dist/cli/live.d.ts +7 -0
- package/dist/cli/live.js +99 -0
- package/dist/cli/main.d.ts +16 -0
- package/dist/cli/main.js +171 -0
- package/dist/cli/secret.d.ts +4 -0
- package/dist/cli/secret.js +151 -0
- package/dist/cli/session.d.ts +6 -0
- package/dist/cli/session.js +106 -0
- package/dist/cli/setup.d.ts +7 -0
- package/dist/cli/setup.js +180 -0
- package/dist/cli/vault.d.ts +5 -0
- package/dist/cli/vault.js +192 -0
- package/dist/client.d.ts +82 -0
- package/dist/client.js +303 -0
- package/dist/doctor.js +34 -1
- package/dist/engine-camoufox.js +5 -4
- package/dist/engine-lightpanda.js +3 -2
- package/dist/engine.js +2 -1
- package/dist/health.js +2 -1
- package/dist/host.d.ts +21 -0
- package/dist/host.js +75 -15
- package/dist/human-input.js +7 -2
- package/dist/identities.js +2 -1
- package/dist/index.d.ts +5 -1
- package/dist/index.js +2 -0
- package/dist/lifecycle.d.ts +2 -0
- package/dist/lifecycle.js +2 -1
- package/dist/live-client.js +8 -6
- package/dist/live-page.d.ts +0 -7
- package/dist/live-page.js +3 -2
- package/dist/live-server.js +6 -3
- package/dist/live.js +2 -1
- package/dist/login-tool.js +3 -2
- package/dist/login.js +2 -1
- package/dist/names.d.ts +28 -0
- package/dist/names.js +25 -0
- package/dist/network.d.ts +1 -1
- package/dist/network.js +4 -3
- package/dist/opt-in-settings.js +3 -2
- package/dist/replay.js +4 -3
- package/dist/runtime-lock.js +3 -2
- package/dist/vault.js +5 -4
- package/npm-shrinkwrap.json +6 -5
- package/package.json +13 -7
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import { readFileSync, rmSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { pidAlive, readProcTable } from "turno-core/process";
|
|
4
|
+
import { IdentityError, identityStateDir } from "./ids.js";
|
|
5
|
+
export function backgroundDir(id, env = process.env) {
|
|
6
|
+
return join(identityStateDir(id, env), "background");
|
|
7
|
+
}
|
|
8
|
+
export function backgroundStatePath(id, env = process.env) {
|
|
9
|
+
return join(backgroundDir(id, env), "server.json");
|
|
10
|
+
}
|
|
11
|
+
export function backgroundSocketPath(id, env = process.env) {
|
|
12
|
+
return join(backgroundDir(id, env), "sock");
|
|
13
|
+
}
|
|
14
|
+
export function backgroundTokenPath(id, env = process.env) {
|
|
15
|
+
return join(backgroundDir(id, env), "token");
|
|
16
|
+
}
|
|
17
|
+
export function backgroundLogPath(id, env = process.env) {
|
|
18
|
+
return join(backgroundDir(id, env), "server.log");
|
|
19
|
+
}
|
|
20
|
+
function isState(v, id) {
|
|
21
|
+
const s = v;
|
|
22
|
+
if (typeof s !== "object" || s === null || s.v !== 1 || s.identity !== id)
|
|
23
|
+
return false;
|
|
24
|
+
if (typeof s.pid !== "number" || !Number.isSafeInteger(s.pid) || s.pid <= 0)
|
|
25
|
+
return false;
|
|
26
|
+
if (typeof s.startedAt !== "string" || typeof s.version !== "string" || typeof s.idleMs !== "number")
|
|
27
|
+
return false;
|
|
28
|
+
if (s.transport === "socket")
|
|
29
|
+
return typeof s.socket === "string";
|
|
30
|
+
if (s.transport === "tcp")
|
|
31
|
+
return typeof s.port === "number" && typeof s.tokenFile === "string";
|
|
32
|
+
return s.transport === undefined;
|
|
33
|
+
}
|
|
34
|
+
/** The state file's content, undefined when there is none or it is not one. */
|
|
35
|
+
export function readBackgroundState(id, env = process.env) {
|
|
36
|
+
try {
|
|
37
|
+
const v = JSON.parse(readFileSync(backgroundStatePath(id, env), "utf8"));
|
|
38
|
+
return isState(v, id) ? v : undefined;
|
|
39
|
+
}
|
|
40
|
+
catch {
|
|
41
|
+
return undefined;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* True while the state's process runs and, when the process table can be read, is a background
|
|
46
|
+
* server (a pid the system gave to another program after a kill is not one).
|
|
47
|
+
*/
|
|
48
|
+
export function backgroundAlive(state) {
|
|
49
|
+
if (state.pid === process.pid)
|
|
50
|
+
return true;
|
|
51
|
+
if (!pidAlive(state.pid))
|
|
52
|
+
return false;
|
|
53
|
+
const command = readProcTable()?.get(state.pid)?.command;
|
|
54
|
+
return command === undefined || command.includes("--background");
|
|
55
|
+
}
|
|
56
|
+
/** Removes what a background server that is gone left behind (state, socket, token). */
|
|
57
|
+
export function removeBackgroundFiles(id, env = process.env) {
|
|
58
|
+
for (const file of [backgroundStatePath(id, env), backgroundSocketPath(id, env), backgroundTokenPath(id, env)])
|
|
59
|
+
rmSync(file, { force: true });
|
|
60
|
+
}
|
|
61
|
+
/** The running background server of the identity, undefined when none runs (a stale state is removed). */
|
|
62
|
+
export function liveBackground(id, env = process.env) {
|
|
63
|
+
const state = readBackgroundState(id, env);
|
|
64
|
+
if (!state)
|
|
65
|
+
return undefined;
|
|
66
|
+
if (backgroundAlive(state))
|
|
67
|
+
return state;
|
|
68
|
+
if (readBackgroundState(id, env)?.pid === state.pid)
|
|
69
|
+
removeBackgroundFiles(id, env);
|
|
70
|
+
return undefined;
|
|
71
|
+
}
|
|
72
|
+
function duration(ms) {
|
|
73
|
+
if (ms % 3_600_000 === 0)
|
|
74
|
+
return `${ms / 3_600_000}h`;
|
|
75
|
+
if (ms % 60_000 === 0)
|
|
76
|
+
return `${ms / 60_000}m`;
|
|
77
|
+
return `${Math.round(ms / 1000)}s`;
|
|
78
|
+
}
|
|
79
|
+
/** Why a server other than the background one may not launch the identity's browser now. */
|
|
80
|
+
function backgroundOwnsMessage(id, state) {
|
|
81
|
+
const idle = state.idleMs > 0 ? `, or wait: it exits after ${duration(state.idleMs)} without a request` : "";
|
|
82
|
+
return (`browser identity "${id}" is served by its background server (pid ${state.pid}) since ${state.startedAt}, ` +
|
|
83
|
+
`which owns the identity's browser while it runs. Stop it with \`turno-browser background stop ${id}\` ` +
|
|
84
|
+
`(or \`kill ${state.pid}\`; it closes its Chrome first)${idle}; ` +
|
|
85
|
+
"then try again.");
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* Throws when another process runs the identity's background server: called before a server
|
|
89
|
+
* launches the identity's browser. The background server itself passes.
|
|
90
|
+
*/
|
|
91
|
+
export function refuseWhileBackground(identity) {
|
|
92
|
+
const state = readBackgroundState(identity.id, identity.env);
|
|
93
|
+
if (!state || state.pid === process.pid || !backgroundAlive(state))
|
|
94
|
+
return;
|
|
95
|
+
throw new IdentityError(backgroundOwnsMessage(identity.id, state));
|
|
96
|
+
}
|
|
97
|
+
//# sourceMappingURL=background-state.js.map
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { type BackgroundState } from "./background-state.js";
|
|
2
|
+
import type { IdentityRef } from "./engine.js";
|
|
3
|
+
import { type Host } from "./host.js";
|
|
4
|
+
import type { SharingMode } from "./sharing.js";
|
|
5
|
+
/**
|
|
6
|
+
* The background server of an identity: `turno-browser-mcp --identity <id> --background`.
|
|
7
|
+
*
|
|
8
|
+
* It serves the identity over MCP streamable HTTP, for shell use without turno's gateway
|
|
9
|
+
* (`client.ts` starts it, connects and calls tools). Only the user reaches it: a Unix socket in
|
|
10
|
+
* a folder only the user can enter, or, where a socket cannot be used (Windows, or a path longer
|
|
11
|
+
* than the system allows), a loopback port that asks for a random per-server bearer token kept
|
|
12
|
+
* in a file only the user can read. It writes `server.json` (pid, address, version) when it is
|
|
13
|
+
* ready and removes it when it exits.
|
|
14
|
+
*
|
|
15
|
+
* Every connection is one client session, and they all drive the identity's one browser
|
|
16
|
+
* (`shareHost`), as mcpd's sessions share one stdio server: with `"sharing": "tabs"` each session
|
|
17
|
+
* has its own tabs; with `"sharing": "session"` one session at a time holds the browser (a lease
|
|
18
|
+
* that ends with the session, when its owner process exits, or after `leaseMs` without a call),
|
|
19
|
+
* and another session's calls get an error that says so. A session continues across connections
|
|
20
|
+
* and processes: a client that sends its `Mcp-Session-Id` again keeps its session and its tab.
|
|
21
|
+
*
|
|
22
|
+
* It exits after `idleMs` without a request (default 15 minutes), on SIGTERM, SIGINT and SIGHUP,
|
|
23
|
+
* closing Chrome first. Coexistence with the stdio servers of the identity: `background-state.ts`.
|
|
24
|
+
*/
|
|
25
|
+
/** Exits after this long without a request, unless the flag or TURNO_BROWSER_BACKGROUND_IDLE says otherwise. */
|
|
26
|
+
export declare const DEFAULT_BACKGROUND_IDLE_MS: number;
|
|
27
|
+
/** The request header a client names the process its session belongs to with (as mcpd's). */
|
|
28
|
+
export declare const OWNER_HEADER = "x-turno-pid";
|
|
29
|
+
export declare class BackgroundError extends Error {
|
|
30
|
+
constructor(message: string);
|
|
31
|
+
}
|
|
32
|
+
export interface BackgroundFlags {
|
|
33
|
+
/** `--background`. */
|
|
34
|
+
background: boolean;
|
|
35
|
+
/** `--background-idle <duration>` or TURNO_BROWSER_BACKGROUND_IDLE, in ms; 0 never. */
|
|
36
|
+
idleMs: number;
|
|
37
|
+
rest: string[];
|
|
38
|
+
}
|
|
39
|
+
/** Removes `--background` and `--background-idle <duration>` from args and checks them. */
|
|
40
|
+
export declare function extractBackground(args: string[], env?: NodeJS.ProcessEnv): BackgroundFlags;
|
|
41
|
+
export interface BackgroundOptions {
|
|
42
|
+
identity: IdentityRef;
|
|
43
|
+
/** Exit after this long without a request; 0 never. */
|
|
44
|
+
idleMs: number;
|
|
45
|
+
/** The identity's sharing mode now (the flag, else identity.json, else "session"). */
|
|
46
|
+
sharing: () => SharingMode;
|
|
47
|
+
/** "auto" (default): a Unix socket where it can, else loopback with a token. */
|
|
48
|
+
transport?: "auto" | "socket" | "tcp";
|
|
49
|
+
/** With `"sharing": "session"`, how long an idle session keeps the browser. */
|
|
50
|
+
leaseMs?: number;
|
|
51
|
+
/** How often sessions whose owner exited are ended and the idle limit is checked. */
|
|
52
|
+
sweepMs?: number;
|
|
53
|
+
/** Runs once the server closed; default: exit the process. */
|
|
54
|
+
onClosed?: (reason: string) => void;
|
|
55
|
+
/** Answer SIGTERM, SIGINT and SIGHUP (default true; tests in process pass false). */
|
|
56
|
+
signals?: boolean;
|
|
57
|
+
log?: (line: string) => void;
|
|
58
|
+
}
|
|
59
|
+
export interface BackgroundServer {
|
|
60
|
+
state: BackgroundState;
|
|
61
|
+
/** Closes every session and the browser, removes the state file. */
|
|
62
|
+
close(reason?: string): Promise<void>;
|
|
63
|
+
/** Resolves once closed. */
|
|
64
|
+
closed: Promise<void>;
|
|
65
|
+
}
|
|
66
|
+
/** Serves `host` as the identity's background server until it closes. */
|
|
67
|
+
export declare function serveBackground(host: Host, options: BackgroundOptions): Promise<BackgroundServer>;
|
|
68
|
+
/** The identity's sharing mode for the lease: `--sharing`, else identity.json, else "session". */
|
|
69
|
+
export declare function sharingOf(flag: SharingMode | undefined, read: () => SharingMode | undefined): () => SharingMode;
|
|
@@ -0,0 +1,458 @@
|
|
|
1
|
+
import { randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
|
|
2
|
+
import { chmodSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { createServer } from "node:http";
|
|
4
|
+
import { fileURLToPath } from "node:url";
|
|
5
|
+
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
|
|
6
|
+
import { isInitializeRequest, isJSONRPCErrorResponse, isJSONRPCRequest, isJSONRPCResultResponse, } from "@modelcontextprotocol/sdk/types.js";
|
|
7
|
+
import { pidAlive } from "turno-core/process";
|
|
8
|
+
import { backgroundAlive, backgroundDir, backgroundSocketPath, backgroundStatePath, backgroundTokenPath, readBackgroundState, } from "./background-state.js";
|
|
9
|
+
import { shareHost } from "./host.js";
|
|
10
|
+
import { inUseMessage, readRuntimeLock, runtimeLockAlive } from "./runtime-lock.js";
|
|
11
|
+
import { SESSION_META_KEY } from "./session.js";
|
|
12
|
+
import { parseDuration } from "./units.js";
|
|
13
|
+
/**
|
|
14
|
+
* The background server of an identity: `turno-browser-mcp --identity <id> --background`.
|
|
15
|
+
*
|
|
16
|
+
* It serves the identity over MCP streamable HTTP, for shell use without turno's gateway
|
|
17
|
+
* (`client.ts` starts it, connects and calls tools). Only the user reaches it: a Unix socket in
|
|
18
|
+
* a folder only the user can enter, or, where a socket cannot be used (Windows, or a path longer
|
|
19
|
+
* than the system allows), a loopback port that asks for a random per-server bearer token kept
|
|
20
|
+
* in a file only the user can read. It writes `server.json` (pid, address, version) when it is
|
|
21
|
+
* ready and removes it when it exits.
|
|
22
|
+
*
|
|
23
|
+
* Every connection is one client session, and they all drive the identity's one browser
|
|
24
|
+
* (`shareHost`), as mcpd's sessions share one stdio server: with `"sharing": "tabs"` each session
|
|
25
|
+
* has its own tabs; with `"sharing": "session"` one session at a time holds the browser (a lease
|
|
26
|
+
* that ends with the session, when its owner process exits, or after `leaseMs` without a call),
|
|
27
|
+
* and another session's calls get an error that says so. A session continues across connections
|
|
28
|
+
* and processes: a client that sends its `Mcp-Session-Id` again keeps its session and its tab.
|
|
29
|
+
*
|
|
30
|
+
* It exits after `idleMs` without a request (default 15 minutes), on SIGTERM, SIGINT and SIGHUP,
|
|
31
|
+
* closing Chrome first. Coexistence with the stdio servers of the identity: `background-state.ts`.
|
|
32
|
+
*/
|
|
33
|
+
/** Exits after this long without a request, unless the flag or TURNO_BROWSER_BACKGROUND_IDLE says otherwise. */
|
|
34
|
+
export const DEFAULT_BACKGROUND_IDLE_MS = 15 * 60_000;
|
|
35
|
+
/** With `"sharing": "session"`: how long an idle session keeps the browser (mcpd's default lease). */
|
|
36
|
+
const DEFAULT_LEASE_MS = 5 * 60_000;
|
|
37
|
+
/** The flag that turns a server into the background server, and its idle limit. */
|
|
38
|
+
const BACKGROUND_FLAG = "--background";
|
|
39
|
+
const BACKGROUND_IDLE_FLAG = "--background-idle";
|
|
40
|
+
const BACKGROUND_IDLE_ENV = "TURNO_BROWSER_BACKGROUND_IDLE";
|
|
41
|
+
/** The request header a client names the process its session belongs to with (as mcpd's). */
|
|
42
|
+
export const OWNER_HEADER = "x-turno-pid";
|
|
43
|
+
/** Longest Unix socket path (macOS allows 103 bytes, Linux 107). */
|
|
44
|
+
const MAX_SOCKET_PATH = 103;
|
|
45
|
+
const PACKAGE_VERSION = JSON.parse(readFileSync(fileURLToPath(new URL("../package.json", import.meta.url)), "utf8")).version;
|
|
46
|
+
export class BackgroundError extends Error {
|
|
47
|
+
constructor(message) {
|
|
48
|
+
super(message);
|
|
49
|
+
this.name = "BackgroundError";
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
/** Removes `--background` and `--background-idle <duration>` from args and checks them. */
|
|
53
|
+
export function extractBackground(args, env = process.env) {
|
|
54
|
+
const rest = [];
|
|
55
|
+
let background = false;
|
|
56
|
+
let idle;
|
|
57
|
+
for (let i = 0; i < args.length; i++) {
|
|
58
|
+
const a = args[i];
|
|
59
|
+
if (a === BACKGROUND_FLAG)
|
|
60
|
+
background = true;
|
|
61
|
+
else if (a.startsWith(`${BACKGROUND_FLAG}=`))
|
|
62
|
+
throw new Error(`${BACKGROUND_FLAG} takes no value`);
|
|
63
|
+
else if (a === BACKGROUND_IDLE_FLAG) {
|
|
64
|
+
const v = args[i + 1];
|
|
65
|
+
if (v === undefined || v.startsWith("--"))
|
|
66
|
+
throw new Error(`${BACKGROUND_IDLE_FLAG} needs a duration`);
|
|
67
|
+
idle = v;
|
|
68
|
+
i++;
|
|
69
|
+
}
|
|
70
|
+
else if (a.startsWith(`${BACKGROUND_IDLE_FLAG}=`))
|
|
71
|
+
idle = a.slice(BACKGROUND_IDLE_FLAG.length + 1);
|
|
72
|
+
else
|
|
73
|
+
rest.push(a);
|
|
74
|
+
}
|
|
75
|
+
if (idle !== undefined && !background)
|
|
76
|
+
throw new Error(`${BACKGROUND_IDLE_FLAG} applies only with ${BACKGROUND_FLAG}`);
|
|
77
|
+
const source = idle ?? env[BACKGROUND_IDLE_ENV];
|
|
78
|
+
let idleMs = DEFAULT_BACKGROUND_IDLE_MS;
|
|
79
|
+
if (source !== undefined && source !== "") {
|
|
80
|
+
const ms = parseDuration(source);
|
|
81
|
+
if (ms === undefined)
|
|
82
|
+
throw new Error(`${idle !== undefined ? BACKGROUND_IDLE_FLAG : BACKGROUND_IDLE_ENV} must be a duration like "15m", "90s" or "0" (never), not "${source}"`);
|
|
83
|
+
idleMs = ms;
|
|
84
|
+
}
|
|
85
|
+
if (background) {
|
|
86
|
+
const http = rest.find((a) => ["--port", "--host"].some((f) => a === f || a.startsWith(`${f}=`)));
|
|
87
|
+
if (http)
|
|
88
|
+
throw new Error(`${BACKGROUND_FLAG} picks its own address: drop ${http.split("=")[0]}`);
|
|
89
|
+
}
|
|
90
|
+
return { background, idleMs, rest };
|
|
91
|
+
}
|
|
92
|
+
function writeState(file, state, flag) {
|
|
93
|
+
if (flag === "wx") {
|
|
94
|
+
writeFileSync(file, `${JSON.stringify(state)}\n`, { mode: 0o600, flag: "wx" });
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
97
|
+
const tmp = `${file}.${process.pid}.tmp`;
|
|
98
|
+
writeFileSync(tmp, `${JSON.stringify(state)}\n`, { mode: 0o600 });
|
|
99
|
+
renameSync(tmp, file);
|
|
100
|
+
}
|
|
101
|
+
/** The private folder of the identity's background server, 0700 even when it existed. */
|
|
102
|
+
function privateDir(id, env) {
|
|
103
|
+
const dir = backgroundDir(id, env);
|
|
104
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
105
|
+
chmodSync(dir, 0o700);
|
|
106
|
+
return dir;
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* Takes the identity's background slot: `server.json` is created exclusively, so two servers
|
|
110
|
+
* started at once never both run. Refuses while another background server runs, or while
|
|
111
|
+
* another process holds the identity's runtime lock (its Chrome is open).
|
|
112
|
+
*/
|
|
113
|
+
function claim(id, env, idleMs) {
|
|
114
|
+
privateDir(id, env);
|
|
115
|
+
const file = backgroundStatePath(id, env);
|
|
116
|
+
const state = {
|
|
117
|
+
v: 1,
|
|
118
|
+
pid: process.pid,
|
|
119
|
+
identity: id,
|
|
120
|
+
version: PACKAGE_VERSION,
|
|
121
|
+
startedAt: new Date().toISOString(),
|
|
122
|
+
idleMs,
|
|
123
|
+
};
|
|
124
|
+
for (let attempt = 0;; attempt++) {
|
|
125
|
+
try {
|
|
126
|
+
writeState(file, state, "wx");
|
|
127
|
+
break;
|
|
128
|
+
}
|
|
129
|
+
catch (err) {
|
|
130
|
+
if (err.code !== "EEXIST" || attempt >= 3)
|
|
131
|
+
throw err;
|
|
132
|
+
}
|
|
133
|
+
const other = readBackgroundState(id, env);
|
|
134
|
+
if (other && other.pid !== process.pid && backgroundAlive(other))
|
|
135
|
+
throw new BackgroundError(`the background server of browser identity "${id}" already runs (pid ${other.pid}, since ${other.startedAt})`);
|
|
136
|
+
rmSync(file, { force: true });
|
|
137
|
+
}
|
|
138
|
+
const lock = readRuntimeLock(id, env);
|
|
139
|
+
if (lock && lock.nodePid !== process.pid && runtimeLockAlive(lock)) {
|
|
140
|
+
rmSync(file, { force: true });
|
|
141
|
+
throw new BackgroundError(`${inUseMessage(id, lock)} The background server owns the identity's browser while it runs, so it starts only when no other process has it open.`);
|
|
142
|
+
}
|
|
143
|
+
return state;
|
|
144
|
+
}
|
|
145
|
+
function socketUsable(path, transport) {
|
|
146
|
+
if (transport === "tcp")
|
|
147
|
+
return false;
|
|
148
|
+
const fits = process.platform !== "win32" && Buffer.byteLength(path) <= MAX_SOCKET_PATH;
|
|
149
|
+
if (transport === "socket" && !fits)
|
|
150
|
+
throw new BackgroundError(`cannot use a Unix socket at ${path} on this system (path too long or no sockets)`);
|
|
151
|
+
return fits;
|
|
152
|
+
}
|
|
153
|
+
function listen(server, target) {
|
|
154
|
+
return new Promise((resolve, reject) => {
|
|
155
|
+
server.once("error", reject);
|
|
156
|
+
const done = () => {
|
|
157
|
+
server.off("error", reject);
|
|
158
|
+
resolve();
|
|
159
|
+
};
|
|
160
|
+
if (typeof target === "string")
|
|
161
|
+
server.listen(target, done);
|
|
162
|
+
else
|
|
163
|
+
server.listen(target.port, target.host, done);
|
|
164
|
+
});
|
|
165
|
+
}
|
|
166
|
+
async function readBody(req) {
|
|
167
|
+
const chunks = [];
|
|
168
|
+
let size = 0;
|
|
169
|
+
for await (const c of req) {
|
|
170
|
+
size += c.length;
|
|
171
|
+
if (size > 4 * 1024 * 1024)
|
|
172
|
+
throw new BackgroundError("request body too large");
|
|
173
|
+
chunks.push(c);
|
|
174
|
+
}
|
|
175
|
+
return JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
176
|
+
}
|
|
177
|
+
function reply(res, status, message, id = null) {
|
|
178
|
+
if (res.headersSent)
|
|
179
|
+
return;
|
|
180
|
+
res.writeHead(status, { "content-type": "application/json" });
|
|
181
|
+
res.end(JSON.stringify({ jsonrpc: "2.0", error: { code: -32000, message }, id }));
|
|
182
|
+
}
|
|
183
|
+
function clock(ms) {
|
|
184
|
+
return new Date(ms).toLocaleTimeString("en-US", { hour12: false });
|
|
185
|
+
}
|
|
186
|
+
function duration(ms) {
|
|
187
|
+
if (ms % 60_000 === 0)
|
|
188
|
+
return `${ms / 60_000}m`;
|
|
189
|
+
return `${Math.round(ms / 1000)}s`;
|
|
190
|
+
}
|
|
191
|
+
/** Serves `host` as the identity's background server until it closes. */
|
|
192
|
+
export async function serveBackground(host, options) {
|
|
193
|
+
const { identity, idleMs } = options;
|
|
194
|
+
const { id, env } = identity;
|
|
195
|
+
const log = options.log ?? ((line) => process.stderr.write(`turno-browser-mcp: ${line}\n`));
|
|
196
|
+
const leaseMs = options.leaseMs ?? DEFAULT_LEASE_MS;
|
|
197
|
+
const state = claim(id, env, idleMs);
|
|
198
|
+
const stateFile = backgroundStatePath(id, env);
|
|
199
|
+
const socketPath = backgroundSocketPath(id, env);
|
|
200
|
+
const tokenFile = backgroundTokenPath(id, env);
|
|
201
|
+
const useSocket = (() => {
|
|
202
|
+
try {
|
|
203
|
+
return socketUsable(socketPath, options.transport);
|
|
204
|
+
}
|
|
205
|
+
catch (error) {
|
|
206
|
+
rmSync(stateFile, { force: true });
|
|
207
|
+
throw error;
|
|
208
|
+
}
|
|
209
|
+
})();
|
|
210
|
+
const token = useSocket ? undefined : randomBytes(32).toString("base64url");
|
|
211
|
+
const shared = shareHost(host);
|
|
212
|
+
const sessions = new Map();
|
|
213
|
+
let holder;
|
|
214
|
+
let lastActivity = Date.now();
|
|
215
|
+
let active = 0;
|
|
216
|
+
let closing;
|
|
217
|
+
let resolveClosed;
|
|
218
|
+
const closed = new Promise((r) => {
|
|
219
|
+
resolveClosed = r;
|
|
220
|
+
});
|
|
221
|
+
// The files are this server's only while server.json names it.
|
|
222
|
+
const ours = () => readBackgroundState(id, env)?.pid === process.pid;
|
|
223
|
+
const removeFiles = () => {
|
|
224
|
+
if (!ours())
|
|
225
|
+
return;
|
|
226
|
+
rmSync(socketPath, { force: true });
|
|
227
|
+
rmSync(tokenFile, { force: true });
|
|
228
|
+
rmSync(stateFile, { force: true });
|
|
229
|
+
};
|
|
230
|
+
process.on("exit", removeFiles);
|
|
231
|
+
const endSession = async (s) => {
|
|
232
|
+
if (s.ended)
|
|
233
|
+
return;
|
|
234
|
+
s.ended = true;
|
|
235
|
+
sessions.delete(s.sid);
|
|
236
|
+
if (holder?.session === s)
|
|
237
|
+
holder = undefined;
|
|
238
|
+
await shared.endSession(s.key).catch(() => { });
|
|
239
|
+
};
|
|
240
|
+
/** With `"sharing": "session"`, why `s` may not call now, or undefined when it holds the browser. */
|
|
241
|
+
const leaseRefusal = (s) => {
|
|
242
|
+
if (options.sharing() === "tabs")
|
|
243
|
+
return undefined;
|
|
244
|
+
if (holder) {
|
|
245
|
+
const h = holder.session;
|
|
246
|
+
const gone = h.ended || (h.owner !== undefined && !pidAlive(h.owner));
|
|
247
|
+
const idle = h.inflight.size === 0 && Date.now() - h.lastSeen > leaseMs;
|
|
248
|
+
if (gone || idle)
|
|
249
|
+
holder = undefined;
|
|
250
|
+
}
|
|
251
|
+
if (holder && holder.session !== s) {
|
|
252
|
+
const h = holder.session;
|
|
253
|
+
return (`browser identity "${id}" is in use by another session of its background server` +
|
|
254
|
+
`${h.owner !== undefined ? ` (owner pid ${h.owner})` : ""} since ${clock(holder.since)}. ` +
|
|
255
|
+
`Try again when that session ends or after ${duration(leaseMs)} without a call from it, ` +
|
|
256
|
+
`or set "sharing": "tabs" in the identity's settings so that sessions share the browser in separate tabs.`);
|
|
257
|
+
}
|
|
258
|
+
if (!holder)
|
|
259
|
+
holder = { session: s, since: Date.now() };
|
|
260
|
+
return undefined;
|
|
261
|
+
};
|
|
262
|
+
/**
|
|
263
|
+
* Connects a new session: its calls carry its own client session in `_meta` (whatever the
|
|
264
|
+
* client put there), pass the lease, and count as in flight until their response leaves.
|
|
265
|
+
*/
|
|
266
|
+
const openSession = async (owner) => {
|
|
267
|
+
let session;
|
|
268
|
+
const transport = new StreamableHTTPServerTransport({
|
|
269
|
+
sessionIdGenerator: () => randomUUID(),
|
|
270
|
+
onsessioninitialized: (sid) => {
|
|
271
|
+
session = {
|
|
272
|
+
sid,
|
|
273
|
+
key: randomUUID(),
|
|
274
|
+
transport,
|
|
275
|
+
...(owner !== undefined ? { owner } : {}),
|
|
276
|
+
lastSeen: Date.now(),
|
|
277
|
+
inflight: new Set(),
|
|
278
|
+
ended: false,
|
|
279
|
+
};
|
|
280
|
+
sessions.set(sid, session);
|
|
281
|
+
},
|
|
282
|
+
onsessionclosed: async () => {
|
|
283
|
+
if (session)
|
|
284
|
+
await endSession(session);
|
|
285
|
+
},
|
|
286
|
+
});
|
|
287
|
+
await shared.connect(transport);
|
|
288
|
+
const deliver = transport.onmessage;
|
|
289
|
+
transport.onmessage = (message, extra) => {
|
|
290
|
+
const s = session;
|
|
291
|
+
if (s && isJSONRPCRequest(message) && message.method === "tools/call") {
|
|
292
|
+
s.lastSeen = Date.now();
|
|
293
|
+
const refusal = leaseRefusal(s);
|
|
294
|
+
if (refusal) {
|
|
295
|
+
const response = {
|
|
296
|
+
jsonrpc: "2.0",
|
|
297
|
+
id: message.id,
|
|
298
|
+
result: { content: [{ type: "text", text: `### Error\n${refusal}` }], isError: true },
|
|
299
|
+
};
|
|
300
|
+
void transport.send(response).catch(() => { });
|
|
301
|
+
return;
|
|
302
|
+
}
|
|
303
|
+
s.inflight.add(message.id);
|
|
304
|
+
const params = (message.params ?? {});
|
|
305
|
+
message.params = { ...params, _meta: { ...(params._meta ?? {}), [SESSION_META_KEY]: s.key } };
|
|
306
|
+
}
|
|
307
|
+
deliver(message, extra);
|
|
308
|
+
};
|
|
309
|
+
const send = transport.send.bind(transport);
|
|
310
|
+
transport.send = async (message, opts) => {
|
|
311
|
+
const s = session;
|
|
312
|
+
if (s && (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) && message.id !== undefined) {
|
|
313
|
+
if (s.inflight.delete(message.id))
|
|
314
|
+
s.lastSeen = Date.now();
|
|
315
|
+
}
|
|
316
|
+
return await send(message, opts);
|
|
317
|
+
};
|
|
318
|
+
return transport;
|
|
319
|
+
};
|
|
320
|
+
const authorized = (req, port) => {
|
|
321
|
+
if (!token)
|
|
322
|
+
return true;
|
|
323
|
+
// The Host check keeps a web page that rebinds a name to 127.0.0.1 out, with the token.
|
|
324
|
+
const hostHeader = req.headers.host ?? "";
|
|
325
|
+
if (hostHeader !== `127.0.0.1:${port}` && hostHeader !== `localhost:${port}`)
|
|
326
|
+
return false;
|
|
327
|
+
const auth = req.headers.authorization ?? "";
|
|
328
|
+
const given = Buffer.from(auth.startsWith("Bearer ") ? auth.slice(7) : "");
|
|
329
|
+
const expected = Buffer.from(token);
|
|
330
|
+
return given.length === expected.length && timingSafeEqual(given, expected);
|
|
331
|
+
};
|
|
332
|
+
const handle = async (req, res, port) => {
|
|
333
|
+
if (!authorized(req, port)) {
|
|
334
|
+
reply(res, 401, "unauthorized");
|
|
335
|
+
return;
|
|
336
|
+
}
|
|
337
|
+
if (new URL(req.url ?? "/", "http://localhost").pathname !== "/mcp") {
|
|
338
|
+
reply(res, 404, "not found");
|
|
339
|
+
return;
|
|
340
|
+
}
|
|
341
|
+
const sid = req.headers["mcp-session-id"];
|
|
342
|
+
if (typeof sid === "string") {
|
|
343
|
+
const s = sessions.get(sid);
|
|
344
|
+
if (!s) {
|
|
345
|
+
reply(res, 404, "Session not found");
|
|
346
|
+
return;
|
|
347
|
+
}
|
|
348
|
+
s.lastSeen = Date.now();
|
|
349
|
+
const body = req.method === "POST" ? await readBody(req) : undefined;
|
|
350
|
+
await s.transport.handleRequest(req, res, body);
|
|
351
|
+
return;
|
|
352
|
+
}
|
|
353
|
+
if (req.method !== "POST") {
|
|
354
|
+
reply(res, 400, "Bad Request: no session (Mcp-Session-Id)");
|
|
355
|
+
return;
|
|
356
|
+
}
|
|
357
|
+
const body = await readBody(req);
|
|
358
|
+
if (!isInitializeRequest(body)) {
|
|
359
|
+
reply(res, 400, "Bad Request: initialize first, or send the Mcp-Session-Id of a session");
|
|
360
|
+
return;
|
|
361
|
+
}
|
|
362
|
+
const raw = req.headers[OWNER_HEADER];
|
|
363
|
+
const owner = typeof raw === "string" && /^\d{1,10}$/.test(raw) && Number(raw) > 1 ? Number(raw) : undefined;
|
|
364
|
+
const transport = await openSession(owner);
|
|
365
|
+
await transport.handleRequest(req, res, body);
|
|
366
|
+
};
|
|
367
|
+
const http = createServer((req, res) => {
|
|
368
|
+
// A request in flight keeps the server up; an open event stream (GET) does not.
|
|
369
|
+
const counts = req.method !== "GET";
|
|
370
|
+
lastActivity = Date.now();
|
|
371
|
+
if (counts)
|
|
372
|
+
active++;
|
|
373
|
+
res.once("close", () => {
|
|
374
|
+
lastActivity = Date.now();
|
|
375
|
+
if (counts)
|
|
376
|
+
active--;
|
|
377
|
+
});
|
|
378
|
+
const port = http.address()?.port ?? 0;
|
|
379
|
+
handle(req, res, port).catch((error) => {
|
|
380
|
+
if (error instanceof SyntaxError)
|
|
381
|
+
reply(res, 400, "Parse error");
|
|
382
|
+
else
|
|
383
|
+
reply(res, 500, error.message);
|
|
384
|
+
});
|
|
385
|
+
});
|
|
386
|
+
// A tool call may take longer than Node's default request timeout of 5 minutes.
|
|
387
|
+
http.requestTimeout = 0;
|
|
388
|
+
try {
|
|
389
|
+
if (useSocket) {
|
|
390
|
+
rmSync(socketPath, { force: true });
|
|
391
|
+
await listen(http, socketPath);
|
|
392
|
+
chmodSync(socketPath, 0o600);
|
|
393
|
+
}
|
|
394
|
+
else {
|
|
395
|
+
await listen(http, { port: 0, host: "127.0.0.1" });
|
|
396
|
+
writeFileSync(tokenFile, `${token}\n`, { mode: 0o600 });
|
|
397
|
+
chmodSync(tokenFile, 0o600);
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
catch (error) {
|
|
401
|
+
removeFiles();
|
|
402
|
+
throw error;
|
|
403
|
+
}
|
|
404
|
+
const ready = useSocket
|
|
405
|
+
? { ...state, transport: "socket", socket: socketPath }
|
|
406
|
+
: { ...state, transport: "tcp", port: http.address().port, tokenFile };
|
|
407
|
+
writeState(stateFile, ready, "w");
|
|
408
|
+
const close = (reason = "closed") => {
|
|
409
|
+
closing ??= (async () => {
|
|
410
|
+
log(`background server of "${id}" stops: ${reason}`);
|
|
411
|
+
clearInterval(sweep);
|
|
412
|
+
http.close();
|
|
413
|
+
http.closeAllConnections();
|
|
414
|
+
for (const s of [...sessions.values()]) {
|
|
415
|
+
await endSession(s);
|
|
416
|
+
await s.transport.close().catch(() => { });
|
|
417
|
+
}
|
|
418
|
+
await shared.dispose().catch(() => { });
|
|
419
|
+
removeFiles();
|
|
420
|
+
process.off("exit", removeFiles);
|
|
421
|
+
resolveClosed();
|
|
422
|
+
(options.onClosed ?? (() => process.exit(0)))(reason);
|
|
423
|
+
})();
|
|
424
|
+
return closing;
|
|
425
|
+
};
|
|
426
|
+
const sweepMs = options.sweepMs ?? Math.min(15_000, Math.max(100, Math.floor((idleMs || 60_000) / 4)));
|
|
427
|
+
const sweep = setInterval(() => {
|
|
428
|
+
for (const s of [...sessions.values()])
|
|
429
|
+
if (s.owner !== undefined && s.inflight.size === 0 && !pidAlive(s.owner)) {
|
|
430
|
+
void endSession(s);
|
|
431
|
+
void s.transport.close().catch(() => { });
|
|
432
|
+
}
|
|
433
|
+
if (!ours())
|
|
434
|
+
void close("its state file was replaced or removed");
|
|
435
|
+
else if (idleMs > 0 && active === 0 && Date.now() - lastActivity >= idleMs)
|
|
436
|
+
void close(`no request for ${duration(idleMs)}`);
|
|
437
|
+
}, sweepMs);
|
|
438
|
+
if (options.signals !== false)
|
|
439
|
+
for (const signal of ["SIGTERM", "SIGINT", "SIGHUP"])
|
|
440
|
+
process.once(signal, () => void close(signal));
|
|
441
|
+
log(`background server of "${id}" ready on ${useSocket ? socketPath : `127.0.0.1:${ready.port} (token in ${tokenFile})`}` +
|
|
442
|
+
`${idleMs > 0 ? `; exits after ${duration(idleMs)} without a request` : ""}`);
|
|
443
|
+
return { state: ready, close, closed };
|
|
444
|
+
}
|
|
445
|
+
/** The identity's sharing mode for the lease: `--sharing`, else identity.json, else "session". */
|
|
446
|
+
export function sharingOf(flag, read) {
|
|
447
|
+
return () => {
|
|
448
|
+
if (flag)
|
|
449
|
+
return flag;
|
|
450
|
+
try {
|
|
451
|
+
return read() ?? "session";
|
|
452
|
+
}
|
|
453
|
+
catch {
|
|
454
|
+
return "session"; // a bad identity.json: the launch reports it
|
|
455
|
+
}
|
|
456
|
+
};
|
|
457
|
+
}
|
|
458
|
+
//# sourceMappingURL=background.js.map
|