@radheim/plugin-browser 0.0.0-stage → 2.4.3

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/dist/proxy.js ADDED
@@ -0,0 +1,438 @@
1
+ export * as BrowserProxy from "./proxy.js";
2
+ import { randomBytes, timingSafeEqual } from "node:crypto";
3
+ import { Agent, createServer, request, } from "node:http";
4
+ import { Duplex } from "node:stream";
5
+ import { Schema } from "effect";
6
+ import { BrowserProxyMachine } from "./proxy-machine.js";
7
+ import { Browser } from "./rpc.js";
8
+ const MAX_POOLED_ORIGINS = 64;
9
+ const MAX_SOCKETS_PER_ORIGIN = 8;
10
+ const MAX_FREE_SOCKETS_PER_ORIGIN = 6;
11
+ const IDLE_POOL_SOCKET_TIMEOUT_MS = 30_000;
12
+ function isStreamTransport(transport) {
13
+ return "openStream" in transport;
14
+ }
15
+ // Desktop-only leaf. This listener is never loaded by the server plugin.
16
+ export async function make(transport) {
17
+ const username = randomBytes(16).toString("hex");
18
+ const password = randomBytes(32).toString("hex");
19
+ const expected = Buffer.from(`Basic ${Buffer.from(`${username}:${password}`).toString("base64")}`);
20
+ const clients = new Set();
21
+ const tunnels = new Set();
22
+ const pending = new Set();
23
+ const originPools = new Map();
24
+ const closed = Promise.withResolvers();
25
+ let state = BrowserProxyMachine.initial;
26
+ const authorized = (value) => {
27
+ if (!value)
28
+ return false;
29
+ const actual = Buffer.from(value);
30
+ return actual.length === expected.length && timingSafeEqual(actual, expected);
31
+ };
32
+ const connect = async (destination, signal) => {
33
+ if (!BrowserProxyMachine.admits(state))
34
+ throw new Error("Browser proxy is closed");
35
+ const abort = new AbortController();
36
+ const cancel = () => abort.abort();
37
+ signal.addEventListener("abort", cancel, { once: true });
38
+ if (signal.aborted)
39
+ cancel();
40
+ pending.add(abort);
41
+ try {
42
+ const socket = isStreamTransport(transport)
43
+ ? await transport.openStream(destination, abort.signal)
44
+ : new TunnelSocket(transport, await transport.open(destination, abort.signal));
45
+ if (!BrowserProxyMachine.admits(state) || abort.signal.aborted) {
46
+ socket.destroy();
47
+ throw new Error("Browser proxy connection was cancelled");
48
+ }
49
+ tunnels.add(socket);
50
+ socket.once("close", () => tunnels.delete(socket));
51
+ return socket;
52
+ }
53
+ finally {
54
+ pending.delete(abort);
55
+ signal.removeEventListener("abort", cancel);
56
+ }
57
+ };
58
+ const clearPools = () => {
59
+ for (const agent of originPools.values())
60
+ agent.destroy();
61
+ originPools.clear();
62
+ };
63
+ const offReset = isStreamTransport(transport) ? transport.onReset?.(clearPools) : undefined;
64
+ /**
65
+ * Returns a per-origin HTTP/1.1 keep-alive Agent scoped strictly to this attachment's proxy.
66
+ * Each origin key is canonicalized `host:port`; sockets are never shared across origins or attachments.
67
+ */
68
+ const agentForOrigin = (destination) => {
69
+ const key = `${destination.host.toLowerCase()}:${destination.port}`;
70
+ const existing = originPools.get(key);
71
+ if (existing) {
72
+ // Refresh LRU order.
73
+ originPools.delete(key);
74
+ originPools.set(key, existing);
75
+ return existing;
76
+ }
77
+ if (originPools.size >= MAX_POOLED_ORIGINS) {
78
+ const oldest = originPools.keys().next().value;
79
+ if (oldest !== undefined) {
80
+ originPools.get(oldest)?.destroy();
81
+ originPools.delete(oldest);
82
+ }
83
+ }
84
+ const agent = new Agent({
85
+ keepAlive: true,
86
+ keepAliveMsecs: 15_000,
87
+ maxSockets: MAX_SOCKETS_PER_ORIGIN,
88
+ maxFreeSockets: MAX_FREE_SOCKETS_PER_ORIGIN,
89
+ timeout: IDLE_POOL_SOCKET_TIMEOUT_MS,
90
+ scheduling: "lifo",
91
+ });
92
+ // Intercept async socket creation so each pooled socket dials through the attachment's tunnel.
93
+ const createConnection = (_options, callback) => {
94
+ const abort = new AbortController();
95
+ if (!callback)
96
+ throw new Error("Browser proxy pool requires async createConnection callback");
97
+ void connect(destination, abort.signal).then((socket) => {
98
+ // Keep an error sink on pooled sockets so an async nextTick error after `agent.destroy()`
99
+ // removes http.Agent's own listener cannot surface as an uncaught exception; active
100
+ // ClientRequests still receive the same error via their own socket error listener.
101
+ socket.on("error", () => {
102
+ if (!socket.destroyed)
103
+ socket.destroy();
104
+ });
105
+ // Half-open sockets whose upstream server closes them while idle must leave the pool immediately.
106
+ socket.once("end", () => {
107
+ if (!socket.destroyed)
108
+ socket.destroy();
109
+ });
110
+ callback(null, socket);
111
+ }, (error) => callback(asError(error)));
112
+ return undefined;
113
+ };
114
+ // SAFETY: Node's http.Agent invokes `createConnection(options, callback)` when a callback is accepted.
115
+ // oxlint-disable-next-line typescript-eslint/no-unsafe-type-assertion
116
+ agent.createConnection = createConnection;
117
+ originPools.set(key, agent);
118
+ return agent;
119
+ };
120
+ const server = createServer({ maxHeaderSize: 64 * 1024 }, (incoming, response) => {
121
+ void forward(incoming, response, agentForOrigin, authorized).catch((error) => {
122
+ if (!response.headersSent) {
123
+ const body = error instanceof Error ? error.message.slice(0, 256) : "Bad Gateway";
124
+ response.writeHead(502, {
125
+ connection: "close",
126
+ "content-type": "text/plain; charset=utf-8",
127
+ "content-length": String(Buffer.byteLength(body)),
128
+ });
129
+ response.end(body);
130
+ return;
131
+ }
132
+ response.destroy();
133
+ });
134
+ });
135
+ server.requestTimeout = 30_000;
136
+ server.headersTimeout = 10_000;
137
+ server.keepAliveTimeout = 30_000;
138
+ server.on("connection", (socket) => {
139
+ // A backlog connection can surface while the server drains after `close()`.
140
+ if (!BrowserProxyMachine.admits(state)) {
141
+ socket.destroy();
142
+ return;
143
+ }
144
+ clients.add(socket);
145
+ socket.setNoDelay(true);
146
+ socket.on("error", () => socket.destroy());
147
+ socket.once("close", () => clients.delete(socket));
148
+ });
149
+ const upgrade = (incoming, socket, head, connectMethod) => {
150
+ // Setup can throw before the close listeners pair the tunnel with the client socket.
151
+ let opened;
152
+ void (async () => {
153
+ if (!authorized(incoming.headers["proxy-authorization"])) {
154
+ socket.end('HTTP/1.1 407 Proxy Authentication Required\r\nProxy-Authenticate: Basic realm="OpenCode Browser Proxy"\r\nContent-Length: 0\r\nConnection: close\r\n\r\n');
155
+ return;
156
+ }
157
+ const url = parseURL(connectMethod ? `https://${incoming.url ?? ""}` : incoming.url);
158
+ if (!url || (!connectMethod && incoming.headers.upgrade?.toLowerCase() !== "websocket")) {
159
+ socket.end("HTTP/1.1 400 Bad Request\r\nContent-Length: 0\r\nConnection: close\r\n\r\n");
160
+ return;
161
+ }
162
+ const abort = new AbortController();
163
+ const cancel = () => abort.abort();
164
+ socket.once("close", cancel);
165
+ socket.pause();
166
+ try {
167
+ const tunnel = await connect(target(url), abort.signal);
168
+ opened = tunnel;
169
+ if (socket.destroyed) {
170
+ tunnel.destroy();
171
+ return;
172
+ }
173
+ if (connectMethod)
174
+ socket.write("HTTP/1.1 200 Connection Established\r\n\r\n");
175
+ if (!connectMethod) {
176
+ const headers = forwardedHeaders(incoming.headers);
177
+ headers.host = url.host;
178
+ headers.connection = "Upgrade";
179
+ headers.upgrade = "websocket";
180
+ tunnel.write(`${incoming.method} ${url.pathname}${url.search} HTTP/1.1\r\n${Object.entries(headers)
181
+ .flatMap(([key, value]) => value === undefined
182
+ ? []
183
+ : (Array.isArray(value) ? value : [value]).map((item) => `${key}: ${item}\r\n`))
184
+ .join("")}\r\n`);
185
+ }
186
+ if (head.byteLength)
187
+ tunnel.write(head);
188
+ // Attach explicit error handlers before `pipe()` so Node's pipe error handler never rethrows on teardown.
189
+ socket.on("error", () => tunnel.destroy());
190
+ tunnel.on("error", () => socket.destroy());
191
+ socket.once("close", () => tunnel.destroy());
192
+ tunnel.once("close", () => socket.destroy());
193
+ socket.pipe(tunnel);
194
+ tunnel.pipe(socket);
195
+ socket.resume();
196
+ }
197
+ finally {
198
+ socket.off("close", cancel);
199
+ }
200
+ })().catch(() => {
201
+ opened?.destroy();
202
+ if (!socket.destroyed)
203
+ socket.end("HTTP/1.1 502 Bad Gateway\r\nContent-Length: 0\r\nConnection: close\r\n\r\n");
204
+ });
205
+ };
206
+ server.on("connect", (incoming, socket, head) => upgrade(incoming, socket, head, true));
207
+ server.on("upgrade", (incoming, socket, head) => upgrade(incoming, socket, head, false));
208
+ server.on("clientError", (_error, socket) => {
209
+ if (!socket.destroyed)
210
+ socket.end("HTTP/1.1 400 Bad Request\r\nConnection: close\r\n\r\n");
211
+ });
212
+ await new Promise((resolve, reject) => {
213
+ server.once("error", reject);
214
+ server.listen(0, "127.0.0.1", () => {
215
+ server.off("error", reject);
216
+ resolve();
217
+ });
218
+ });
219
+ const address = server.address();
220
+ if (!address || typeof address === "string")
221
+ throw new Error("Browser proxy did not bind a TCP address");
222
+ return {
223
+ url: `http://127.0.0.1:${address.port}`,
224
+ host: "127.0.0.1",
225
+ port: address.port,
226
+ credentials: { username, password },
227
+ resetPools: clearPools,
228
+ close() {
229
+ const next = BrowserProxyMachine.transition(state, { type: "close" });
230
+ state = next.state;
231
+ next.effects.forEach(() => {
232
+ offReset?.();
233
+ clearPools();
234
+ pending.forEach((abort) => abort.abort());
235
+ tunnels.forEach((socket) => socket.destroy());
236
+ clients.forEach((socket) => socket.destroy());
237
+ server.close(() => closed.resolve());
238
+ });
239
+ return closed.promise;
240
+ },
241
+ };
242
+ }
243
+ async function forward(incoming, response, agentForOrigin, authorized) {
244
+ if (!authorized(incoming.headers["proxy-authorization"])) {
245
+ response.writeHead(407, {
246
+ "Proxy-Authenticate": 'Basic realm="OpenCode Browser Proxy"',
247
+ "Content-Length": "0",
248
+ Connection: "close",
249
+ });
250
+ response.end();
251
+ return;
252
+ }
253
+ const url = parseURL(incoming.url);
254
+ if (!url || url.protocol !== "http:") {
255
+ response.writeHead(400, { "Content-Length": "0", Connection: "close" });
256
+ response.end();
257
+ return;
258
+ }
259
+ const destination = target(url);
260
+ const agent = agentForOrigin(destination);
261
+ const abort = new AbortController();
262
+ let finished = false;
263
+ const cancel = () => {
264
+ if (!finished)
265
+ abort.abort();
266
+ };
267
+ incoming.once("aborted", cancel);
268
+ response.once("close", cancel);
269
+ const headers = forwardedHeaders(incoming.headers);
270
+ headers.host = url.host;
271
+ // Keep upstream HTTP/1.1 connections warm per origin/attachment; Node's Agent honours upstream `Connection: close`.
272
+ headers.connection = "keep-alive";
273
+ const clientWantsClose = incoming.httpVersion === "1.0" ||
274
+ /\bclose\b/i.test(incoming.headers.connection ?? "") ||
275
+ /\bclose\b/i.test(String(incoming.headers["proxy-connection"] ?? ""));
276
+ try {
277
+ await new Promise((resolve, reject) => {
278
+ const upstream = request({
279
+ agent,
280
+ hostname: url.hostname,
281
+ port: destination.port,
282
+ path: `${url.pathname}${url.search}`,
283
+ method: incoming.method,
284
+ headers,
285
+ signal: abort.signal,
286
+ }, (result) => {
287
+ const status = result.statusCode ?? 502;
288
+ const bodyless = status === 204 || status === 304 || incoming.method === "HEAD";
289
+ const explicitLength = result.headers["content-length"] !== undefined || result.headers["transfer-encoding"] !== undefined;
290
+ const responseHeaders = forwardedHeaders(result.headers);
291
+ // Keep the local Chromium <-> proxy connection alive whenever framing is explicit and client allows it.
292
+ if (clientWantsClose || (!bodyless && !explicitLength)) {
293
+ responseHeaders.connection = "close";
294
+ }
295
+ else {
296
+ responseHeaders.connection = "keep-alive";
297
+ }
298
+ response.writeHead(status, result.statusMessage, responseHeaders);
299
+ result.once("error", (error) => {
300
+ upstream.destroy();
301
+ reject(error);
302
+ });
303
+ response.once("finish", () => {
304
+ finished = true;
305
+ resolve();
306
+ });
307
+ result.pipe(response);
308
+ });
309
+ upstream.once("error", reject);
310
+ incoming.pipe(upstream);
311
+ });
312
+ }
313
+ finally {
314
+ incoming.off("aborted", cancel);
315
+ response.off("close", cancel);
316
+ }
317
+ }
318
+ function forwardedHeaders(input) {
319
+ const headers = { ...input };
320
+ headers.connection?.split(",").forEach((name) => delete headers[name.trim().toLowerCase()]);
321
+ [
322
+ "connection",
323
+ "keep-alive",
324
+ "proxy-authenticate",
325
+ "proxy-authorization",
326
+ "proxy-connection",
327
+ "te",
328
+ "trailer",
329
+ "transfer-encoding",
330
+ "upgrade",
331
+ ].forEach((name) => delete headers[name]);
332
+ return headers;
333
+ }
334
+ function parseURL(value) {
335
+ if (!value || !URL.canParse(value))
336
+ return;
337
+ const url = new URL(value);
338
+ if (!["http:", "https:", "ws:", "wss:"].includes(url.protocol) || url.username || url.password)
339
+ return;
340
+ return url;
341
+ }
342
+ function target(url) {
343
+ return Schema.decodeUnknownSync(Browser.TunnelTarget)({
344
+ host: url.hostname.replace(/^\[|\]$/g, ""),
345
+ port: url.port ? Number(url.port) : url.protocol === "https:" || url.protocol === "wss:" ? 443 : 80,
346
+ });
347
+ }
348
+ class TunnelSocket extends Duplex {
349
+ transport;
350
+ id;
351
+ connecting = false;
352
+ abort = new AbortController();
353
+ reads = "idle";
354
+ idleTimer;
355
+ constructor(transport, id) {
356
+ super({ highWaterMark: Browser.TUNNEL_CHUNK_BYTES, allowHalfOpen: true });
357
+ this.transport = transport;
358
+ this.id = id;
359
+ this.on("error", () => this.destroy());
360
+ }
361
+ _read() {
362
+ if (!this.advance("pull"))
363
+ return;
364
+ void this.transport.read(this.id, this.abort.signal).then((result) => {
365
+ if (!this.advance(result.eof ? "eof" : "chunk"))
366
+ return;
367
+ if (result.eof) {
368
+ this.push(null);
369
+ return;
370
+ }
371
+ if (this.push(result.data))
372
+ this._read();
373
+ }, (error) => this.destroy(asError(error)));
374
+ }
375
+ advance(event) {
376
+ const next = BrowserProxyMachine.transitionRead(this.reads, event);
377
+ if (next === this.reads)
378
+ return false;
379
+ this.reads = next;
380
+ return true;
381
+ }
382
+ _write(chunk, encoding, callback) {
383
+ const data = typeof chunk === "string" ? Buffer.from(chunk, encoding) : chunk;
384
+ void (async () => {
385
+ for (let offset = 0; offset < data.byteLength; offset += Browser.TUNNEL_CHUNK_BYTES)
386
+ await this.transport.write(this.id, data.subarray(offset, offset + Browser.TUNNEL_CHUNK_BYTES), false, this.abort.signal);
387
+ })().then(() => callback(), (error) => callback(asError(error)));
388
+ }
389
+ _final(callback) {
390
+ void this.transport.write(this.id, new Uint8Array(), true, this.abort.signal).then(() => callback(), (error) => callback(asError(error)));
391
+ }
392
+ _destroy(error, callback) {
393
+ if (this.idleTimer) {
394
+ clearTimeout(this.idleTimer);
395
+ this.idleTimer = undefined;
396
+ }
397
+ this.advance("destroyed");
398
+ this.abort.abort();
399
+ void this.transport
400
+ .close(this.id)
401
+ .catch(() => undefined)
402
+ .then(() => callback(error));
403
+ }
404
+ setKeepAlive() {
405
+ return this;
406
+ }
407
+ setNoDelay() {
408
+ return this;
409
+ }
410
+ setTimeout(timeout, callback) {
411
+ if (this.idleTimer) {
412
+ clearTimeout(this.idleTimer);
413
+ this.idleTimer = undefined;
414
+ }
415
+ if (timeout === 0) {
416
+ if (callback)
417
+ this.off("timeout", callback);
418
+ return this;
419
+ }
420
+ if (callback)
421
+ this.once("timeout", callback);
422
+ this.idleTimer = setTimeout(() => {
423
+ this.idleTimer = undefined;
424
+ this.emit("timeout");
425
+ }, timeout);
426
+ this.idleTimer.unref?.();
427
+ return this;
428
+ }
429
+ ref() {
430
+ return this;
431
+ }
432
+ unref() {
433
+ return this;
434
+ }
435
+ }
436
+ function asError(error) {
437
+ return error instanceof Error ? error : new Error(String(error));
438
+ }