The best way to control Claude Code, Codex and more from any computer or phone

main
ts 623 lines 25.2 KB
Raw
1 // Renders another environment's localhost pages in a local webview: the partition's loopback
2 // traffic goes to a SOCKS5 listener here, and each connection rides one WebSocket to the
3 // environment's /api/preview/tunnel. The page keeps its localhost origin. Forwarded ports take
4 // the same route from a plain listener, for any client on this machine.
5 import * as NodeSocket from "@effect/platform-node/NodeSocket";
6 import * as NodeSocketServer from "@effect/platform-node/NodeSocketServer";
7 import * as NodeWS from "@effect/platform-node/NodeWS";
8 import type {
9 DesktopPortForward,
10 DesktopPreviewTunnelAccessRequest,
11 EnvironmentId,
12 } from "@t3tools/contracts";
13 import * as HostProcess from "@t3tools/shared/HostProcess";
14 import type { NonEmptyReadonlyArray } from "effect/Array";
15 import * as Context from "effect/Context";
16 import * as Deferred from "effect/Deferred";
17 import * as Effect from "effect/Effect";
18 import * as Exit from "effect/Exit";
19 import * as FileSystem from "effect/FileSystem";
20 import * as Layer from "effect/Layer";
21 import * as NetAddress from "effect/net/NetAddress";
22 import * as Option from "effect/Option";
23 import * as Result from "effect/Result";
24 import * as Schema from "effect/Schema";
25 import * as SecureRandom from "effect/crypto/SecureRandom";
26 import * as Scope from "effect/Scope";
27 import * as Semaphore from "effect/Semaphore";
28 import * as Socket from "effect/socket/Socket";
29
30 import * as ElectronWindow from "../electron/ElectronWindow.ts";
31 import { PREVIEW_TUNNEL_ACCESS_REQUEST_CHANNEL } from "../ipc/channels.ts";
32
33 const ACCESS_TIMEOUT = "15 seconds";
34 const PROBE_TIMEOUT = "3 seconds";
35 const MAX_FORWARD_CONNECTIONS = 64;
36 const CONNECT_TIMEOUT = "10 seconds";
37
38 const REPLY_SUCCEEDED = 0;
39 const REPLY_FAILURE = 1;
40 const REPLY_NOT_ALLOWED = 2;
41 const REPLY_COMMAND_NOT_SUPPORTED = 7;
42 const REPLY_ADDRESS_NOT_SUPPORTED = 8;
43
44 const socksReply = (code: number) => Uint8Array.of(5, code, 0, 1, 0, 0, 0, 0, 0, 0);
45
46 // Chromium names the host as typed, so IP literals also arrive as domain names, and a fully
47 // qualified `localhost.` keeps its trailing dot.
48 const isLoopbackName = (typed: string) => {
49 const name = typed.replace(/\.$/, "");
50 return (
51 name === "localhost" ||
52 name.endsWith(".localhost") ||
53 Result.match(NetAddress.ipFromString(name), {
54 onSuccess: NetAddress.isLoopback,
55 onFailure: () => false,
56 })
57 );
58 };
59
60 // `*://` matches only http and https, so WebSocket schemes are listed separately.
61 const UNSPECIFIED_ADDRESS_URLS = ["http", "https", "ws", "wss"].flatMap((scheme) => [
62 `${scheme}://0.0.0.0/*`,
63 `${scheme}://[::]/*`,
64 ]);
65
66 const sendUnspecifiedToLocalhost = (
67 details: Electron.OnBeforeRequestListenerDetails,
68 callback: (response: Electron.CallbackResponse) => void,
69 ) => {
70 const url = new URL(details.url);
71 // A WebSocket handshake can't be redirected.
72 if (url.protocol === "ws:" || url.protocol === "wss:") return callback({ cancel: true });
73 url.hostname = "localhost";
74 callback({ redirectURL: url.toString() });
75 };
76
77 type SocksRequest = { readonly port: number } | { readonly refusal: number };
78
79 /** Undefined until the whole request has arrived. */
80 const parseConnect = (data: Buffer): SocksRequest | undefined => {
81 if (data.length < 5) return undefined;
82 const addressType = data[3];
83 const hostLength =
84 addressType === 1 ? 4 : addressType === 4 ? 16 : addressType === 3 ? 1 + data[4]! : -1;
85 if (hostLength < 0) return { refusal: REPLY_ADDRESS_NOT_SUPPORTED };
86 if (data.length < 4 + hostLength + 2) return undefined;
87 if (data[0] !== 5 || data[1] !== 1) return { refusal: REPLY_COMMAND_NOT_SUPPORTED };
88 const host = data.subarray(4, 4 + hostLength);
89 const loopback =
90 addressType === 1
91 ? NetAddress.isLoopback(NetAddress.ipv4FromBytesUnsafe(host))
92 : addressType === 4
93 ? NetAddress.isLoopback(NetAddress.ipv6FromBytesUnsafe(host))
94 : isLoopbackName(host.subarray(1).toString("latin1").toLowerCase());
95 return loopback ? { port: data.readUInt16BE(4 + hostLength) } : { refusal: REPLY_NOT_ALLOWED };
96 };
97
98 /** Answers the greeting and reads the CONNECT; undefined when the client offers no usable auth. */
99 const readSocksRequest = Effect.fn("LoopbackTunnel.readSocksRequest")(function* (
100 pull: Effect.Effect<NonEmptyReadonlyArray<Uint8Array>, Socket.SocketError>,
101 writer: Socket.Writer,
102 ) {
103 let received = Buffer.alloc(0);
104 let greeted = false;
105 while (true) {
106 received = Buffer.concat([received, ...(yield* pull)]);
107 if (!greeted) {
108 const methods = received[1];
109 if (methods === undefined || received.length < 2 + methods) continue;
110 if (received[0] !== 5 || !received.subarray(2, 2 + methods).includes(0)) {
111 yield* writer.write(Uint8Array.of(5, 0xff));
112 return undefined;
113 }
114 yield* writer.write(Uint8Array.of(5, 0));
115 received = received.subarray(2 + methods);
116 greeted = true;
117 }
118 const request = parseConnect(received);
119 if (request !== undefined) return request;
120 }
121 });
122
123 // Over an SSH forward the environment's own origin is a loopback port here, and signed asset
124 // URLs point at it. That port is the environment, not one of its loopback servers.
125 const tunnelEndpoint = (tunnelUrl: string) => {
126 const url = new URL(tunnelUrl);
127 return {
128 host: url.hostname.replace(/^\[|\]$/g, ""),
129 port: Number(url.port || (url.protocol === "wss:" ? 443 : 80)),
130 };
131 };
132
133 const isTunnelEndpoint = (tunnelUrl: string, port: number) => {
134 const endpoint = tunnelEndpoint(tunnelUrl);
135 return isLoopbackName(endpoint.host) && endpoint.port === port;
136 };
137
138 /** Opens a connection to the destination; `ws` pauses its socket, so a slow page slows the tunnel. */
139 /** Set by the environment's /api/preview/tunnel when it reached the port and nothing listens. */
140 const PORT_REFUSED_HEADER = "x-t3-tunnel-port-refused";
141
142 const dialDestination = Effect.fn("LoopbackTunnel.dialDestination")(function* (
143 tunnelUrl: string,
144 port: number,
145 onPortRefused?: () => void,
146 ) {
147 if (isTunnelEndpoint(tunnelUrl, port)) {
148 const endpoint = yield* NodeSocket.makeNet({
149 ...tunnelEndpoint(tunnelUrl),
150 openTimeout: CONNECT_TIMEOUT,
151 });
152 return { pull: yield* Socket.readerBytes(endpoint), writer: yield* endpoint.writer };
153 }
154 const url = new URL(tunnelUrl);
155 url.searchParams.set("port", String(port));
156 const tunnel = yield* Effect.acquireRelease(
157 Effect.sync(() => {
158 // Closing before the handshake finishes emits an error after Socket's listeners are gone.
159 const tunnel = new NodeWS.WebSocket(url).on("error", () => undefined);
160 if (onPortRefused) {
161 tunnel.on("unexpected-response", (_request, response) => {
162 if (response.headers[PORT_REFUSED_HEADER] !== undefined) onPortRefused();
163 // Handled here, so `ws` leaves aborting the handshake to us.
164 tunnel.terminate();
165 });
166 }
167 return tunnel;
168 }),
169 (tunnel) => Effect.sync(() => tunnel.close()),
170 );
171 const socket = yield* Socket.fromWebSocket(Effect.succeed(tunnel), {
172 openTimeout: CONNECT_TIMEOUT,
173 });
174 // Effect's WebSocket writer never waits for the send buffer; `ws` calls back once it is written.
175 const sendAll = (chunks: NonEmptyReadonlyArray<Uint8Array>) =>
176 Effect.callback<void>((resume) => {
177 const last = chunks.length - 1;
178 chunks.forEach((chunk, index) =>
179 tunnel.send(chunk, index === last ? () => resume(Effect.void) : undefined),
180 );
181 });
182 return {
183 pull: yield* Socket.readerBytes(socket),
184 writer: { write: (chunk: Uint8Array) => sendAll([chunk]), writeAll: sendAll },
185 };
186 });
187
188 const TCP_TABLES = ["/proc/net/tcp", "/proc/net/tcp6"];
189
190 // Rows read `sl local_address rem_address st queues timer retransmits uid ...`, with addresses
191 // as HEXIP:HEXPORT and IPv4 bytes in little-endian order; tcp6 holds IPv4 as ::ffff:a.b.c.d.
192 const procAddresses = (ip: string, port: number) => {
193 const octets = ip
194 .replace(/^::ffff:/i, "")
195 .split(".")
196 .map(Number);
197 const v4 = octets
198 .reverse()
199 .map((octet) => octet.toString(16).padStart(2, "0"))
200 .join("")
201 .toUpperCase();
202 const hexPort = port.toString(16).padStart(4, "0").toUpperCase();
203 return [`${v4}:${hexPort}`, `0000000000000000FFFF0000${v4}:${hexPort}`];
204 };
205
206 /** The owner of the row whose local end is the client and remote end is the listener. */
207 const connectionOwner = (
208 tables: ReadonlyArray<string>,
209 client: { readonly address: string; readonly port: number },
210 listener: { readonly address: string; readonly port: number },
211 ) => {
212 const clientEnds = procAddresses(client.address, client.port);
213 const listenerEnds = procAddresses(listener.address, listener.port);
214 for (const line of tables.flatMap((table) => table.split("\n").slice(1))) {
215 const [, local, remote, , , , , uid] = line.trim().split(/\s+/);
216 if (
217 local !== undefined &&
218 remote !== undefined &&
219 clientEnds.includes(local.toUpperCase()) &&
220 listenerEnds.includes(remote.toUpperCase())
221 ) {
222 return Number(uid);
223 }
224 }
225 return undefined;
226 };
227
228 const pump =
229 /* Runs for the life of the connection; a span per direction adds no diagnostic value. */
230 Effect.fnUntraced(function* (
231 pull: Effect.Effect<NonEmptyReadonlyArray<Uint8Array>, Socket.SocketError>,
232 writeAll: (
233 chunks: NonEmptyReadonlyArray<Uint8Array>,
234 ) => Effect.Effect<void, Socket.SocketError>,
235 ) {
236 while (true) yield* writeAll(yield* pull);
237 });
238
239 export class LoopbackTunnelRouteError extends Schema.TaggedError<LoopbackTunnelRouteError>()(
240 "LoopbackTunnelRouteError",
241 { environmentId: Schema.String, cause: Schema.Defect() },
242 ) {
243 override get message(): string {
244 return `Failed to route preview traffic for environment "${this.environmentId}".`;
245 }
246 }
247
248 export class LoopbackTunnelForwardError extends Schema.TaggedError<LoopbackTunnelForwardError>()(
249 "LoopbackTunnelForwardError",
250 { environmentId: Schema.String, port: Schema.Number, cause: Schema.Defect() },
251 ) {
252 override get message(): string {
253 return `Failed to forward port ${this.port} of environment "${this.environmentId}".`;
254 }
255 }
256
257 export class LoopbackTunnelUnavailableError extends Schema.TaggedError<LoopbackTunnelUnavailableError>()(
258 "LoopbackTunnelUnavailableError",
259 { environmentId: Schema.String },
260 ) {
261 override get message(): string {
262 return `Environment "${this.environmentId}" can't be reached through the tunnel right now.`;
263 }
264 }
265
266 export class LoopbackTunnelSameMachineError extends Schema.TaggedError<LoopbackTunnelSameMachineError>()(
267 "LoopbackTunnelSameMachineError",
268 { environmentId: Schema.String, port: Schema.Number },
269 ) {
270 override get message(): string {
271 return `This environment runs on this computer, so localhost:${this.port} already reaches it.`;
272 }
273 }
274
275 export class LoopbackTunnel extends Context.Service<
276 LoopbackTunnel,
277 {
278 /** Sends a preview session's loopback traffic to its environment, or back to this machine. */
279 readonly route: (input: {
280 readonly environmentId: string;
281 readonly session: Electron.Session;
282 readonly tunnelled: boolean;
283 }) => Effect.Effect<void, LoopbackTunnelRouteError>;
284 readonly resolveAccess: (input: {
285 readonly requestId: string;
286 readonly url: string | null;
287 }) => Effect.Effect<void>;
288 /** Listens on this machine's loopback, on the same port when it is free. */
289 readonly forward: (input: {
290 readonly environmentId: EnvironmentId;
291 readonly remotePort: number;
292 }) => Effect.Effect<
293 DesktopPortForward,
294 LoopbackTunnelForwardError | LoopbackTunnelSameMachineError | LoopbackTunnelUnavailableError
295 >;
296 readonly stopForward: (input: {
297 readonly environmentId: EnvironmentId;
298 readonly remotePort: number;
299 }) => Effect.Effect<void>;
300 readonly forwards: Effect.Effect<ReadonlyArray<DesktopPortForward>>;
301 /** Whether the environment's loopback is this machine's, so forwarding would only loop. */
302 readonly sharesLoopback: (
303 environmentId: EnvironmentId,
304 ) => Effect.Effect<boolean, LoopbackTunnelUnavailableError>;
305 readonly subscribeForwards: (
306 listener: (forwards: ReadonlyArray<DesktopPortForward>) => Effect.Effect<void>,
307 ) => Effect.Effect<void, never, Scope.Scope>;
308 }
309 >()("@t3tools/desktop/preview/LoopbackTunnel") {}
310
311 const make = Effect.gen(function* () {
312 const electronWindow = yield* ElectronWindow.ElectronWindow;
313 const fileSystem = yield* FileSystem.FileSystem;
314 const platform = yield* HostProcess.Platform;
315 const userId = yield* HostProcess.UserId;
316 const random = yield* SecureRandom.SecureRandom;
317 const listenerScope = yield* Effect.scope;
318 const routing = yield* Semaphore.make(1);
319 const forwarding = yield* Semaphore.make(1);
320 const forwarded = new Map<
321 string,
322 { readonly forward: DesktopPortForward; readonly scope: Scope.Closeable }
323 >();
324 const forwardListeners = new Set<
325 (forwards: ReadonlyArray<DesktopPortForward>) => Effect.Effect<void>
326 >();
327 const pending = new Map<string, Deferred.Deferred<string | null>>();
328 const listenerPorts = new Map<string, number>();
329 const routed = new WeakSet<Electron.Session>();
330 let requestCount = 0;
331
332 // The renderer owns environment credentials and the selected route, so it is asked per
333 // connection; it decides how long a ticket is reused.
334 const requestAccess = Effect.fn("LoopbackTunnel.requestAccess")(function* (
335 environmentId: string,
336 ) {
337 const window = yield* electronWindow.currentMainOrFirst;
338 if (Option.isNone(window) || window.value.isDestroyed()) return null;
339 const requestId = `preview-tunnel-${requestCount++}`;
340 const answer = yield* Deferred.make<string | null>();
341 pending.set(requestId, answer);
342 window.value.webContents.send(PREVIEW_TUNNEL_ACCESS_REQUEST_CHANNEL, {
343 requestId,
344 environmentId,
345 } as DesktopPreviewTunnelAccessRequest);
346 return yield* Deferred.await(answer).pipe(
347 Effect.timeoutOption(ACCESS_TIMEOUT),
348 Effect.map(Option.getOrNull),
349 Effect.ensuring(Effect.sync(() => pending.delete(requestId))),
350 );
351 });
352
353 // Chromium can't authenticate to a SOCKS proxy, so on Linux the listener checks that the
354 // client belongs to this OS user. Other users could otherwise ride this user's tunnel.
355 const isOwnConnection = Effect.fn("LoopbackTunnel.isOwnConnection")(function* () {
356 if (platform !== "linux") return true;
357 const connection = yield* Effect.serviceOption(NodeSocket.NetSocket);
358 if (Option.isNone(connection)) return false;
359 const { remoteAddress, remotePort, localAddress, localPort } = connection.value;
360 if (!remoteAddress || !remotePort || !localAddress || !localPort) return false;
361 const tables = yield* Effect.forEach(TCP_TABLES, (path) =>
362 fileSystem.readFileString(path).pipe(Effect.orElseSucceed(() => "")),
363 );
364 return (
365 connectionOwner(
366 tables,
367 { address: remoteAddress, port: remotePort },
368 { address: localAddress, port: localPort },
369 ) === userId
370 );
371 });
372
373 /** Serves one SOCKS connection; never falls back to a direct local connection. */
374 const serve = (environmentId: string) =>
375 Effect.fn("LoopbackTunnel.serve")(
376 function* (socket: Socket.Socket) {
377 const pull = yield* Socket.readerBytes(socket);
378 const writer = yield* socket.writer;
379 // "No acceptable methods": the only refusal a client gets before its request.
380 if (!(yield* isOwnConnection())) return yield* writer.write(Uint8Array.of(5, 0xff));
381 const request = yield* readSocksRequest(pull, writer);
382 if (request === undefined) return;
383 if ("refusal" in request) return yield* writer.write(socksReply(request.refusal));
384 const tunnelUrl = yield* requestAccess(environmentId);
385 if (tunnelUrl === null) return yield* writer.write(socksReply(REPLY_FAILURE));
386 const destination = yield* dialDestination(tunnelUrl, request.port).pipe(Effect.option);
387 if (Option.isNone(destination)) return yield* writer.write(socksReply(REPLY_FAILURE));
388 yield* writer.write(socksReply(REPLY_SUCCEEDED));
389 return yield* Effect.raceFirst(
390 pump(pull, destination.value.writer.writeAll),
391 pump(destination.value.pull, writer.writeAll),
392 );
393 },
394 Effect.scoped,
395 (effect) => Effect.ignoreCause(effect),
396 );
397
398 /** Serves one connection to a forwarded port; closes it when the environment is out of reach. */
399 const serveForward = (environmentId: string, port: number) => {
400 let active = 0;
401 return Effect.fn("LoopbackTunnel.serveForward")(
402 function* (socket: Socket.Socket) {
403 // Acquiring the socket ties it to this scope, so returning early closes it.
404 const pull = yield* Socket.readerBytes(socket);
405 const writer = yield* socket.writer;
406 // Closed at once, so a page hammering the port can't queue tunnels and access requests.
407 if (active >= MAX_FORWARD_CONNECTIONS) return;
408 active++;
409 yield* Effect.addFinalizer(() => Effect.sync(() => active--));
410 if (!(yield* isOwnConnection())) return;
411 const tunnelUrl = yield* requestAccess(environmentId);
412 if (tunnelUrl === null) return;
413 const destination = yield* dialDestination(tunnelUrl, port);
414 return yield* Effect.raceFirst(
415 pump(pull, destination.writer.writeAll),
416 pump(destination.pull, writer.writeAll),
417 );
418 },
419 Effect.scoped,
420 (effect) => Effect.ignoreCause(effect),
421 );
422 };
423
424 /**
425 * Whether the environment's loopback is this machine's, by tunnelling a nonce to a local probe.
426 * A forward there would accept the environment's own dials and loop through the tunnel.
427 */
428 const sharesLoopback = Effect.fn("LoopbackTunnel.sharesLoopback")(function* (
429 environmentId: string,
430 ) {
431 const tunnelUrl = yield* requestAccess(environmentId);
432 // Without access the answer is unknown, not "another machine": a forward could loop later.
433 if (tunnelUrl === null) return yield* new LoopbackTunnelUnavailableError({ environmentId });
434 return yield* probeLoopback(environmentId, tunnelUrl);
435 });
436
437 /**
438 * True only when the nonce reaches this machine's probe; false only on proof the environment
439 * was reached and nothing listens on the probe port there. Anything else is unknown.
440 */
441 const probeLoopback = Effect.fn("LoopbackTunnel.probeLoopback")(
442 function* (environmentId: string, tunnelUrl: string) {
443 const unavailable = new LoopbackTunnelUnavailableError({ environmentId });
444 const nonce = new TextEncoder().encode(yield* random.uuidV4());
445 const arrived = yield* Deferred.make<void>();
446 const probe = yield* NodeSocketServer.make({ port: 0, host: "127.0.0.1" });
447 yield* probe
448 .run(
449 Effect.fnUntraced(
450 function* (socket: Socket.Socket) {
451 const pull = yield* Socket.readerBytes(socket);
452 let received = Buffer.alloc(0);
453 while (received.length < nonce.length) {
454 received = Buffer.concat([received, ...(yield* pull)]);
455 }
456 if (received.subarray(0, nonce.length).equals(nonce)) {
457 yield* Deferred.succeed(arrived, undefined);
458 }
459 },
460 Effect.scoped,
461 (effect) => Effect.ignoreCause(effect),
462 ),
463 )
464 .pipe(Effect.forkScoped);
465 let portRefused = false;
466 const destination = yield* dialDestination(
467 tunnelUrl,
468 (probe.address as NetAddress.InetAddress).port,
469 () => {
470 portRefused = true;
471 },
472 ).pipe(Effect.option);
473 if (Option.isNone(destination)) {
474 if (portRefused) return false;
475 return yield* unavailable;
476 }
477 yield* destination.value.writer.write(nonce);
478 // An answer or a close means a service on another machine took the connection.
479 const answer = yield* Effect.raceFirst(
480 Deferred.await(arrived).pipe(Effect.as(true)),
481 destination.value.pull.pipe(Effect.as(false)),
482 ).pipe(Effect.timeoutOption(PROBE_TIMEOUT));
483 if (Option.isNone(answer)) return yield* unavailable;
484 return answer.value;
485 },
486 Effect.scoped,
487 (effect, environmentId) =>
488 effect.pipe(
489 Effect.mapError((error) =>
490 error._tag === "LoopbackTunnelUnavailableError"
491 ? error
492 : new LoopbackTunnelUnavailableError({ environmentId }),
493 ),
494 ),
495 );
496
497 const forwardKey = (environmentId: string, port: number) => `${environmentId}:${port}`;
498 const currentForwards = () => [...forwarded.values()].map(({ forward }) => forward);
499 const announceForwards = Effect.suspend(() => {
500 const forwards = currentForwards();
501 return Effect.forEach([...forwardListeners], (listener) => listener(forwards), {
502 discard: true,
503 });
504 });
505
506 const forward: LoopbackTunnel["Service"]["forward"] = Effect.fn("LoopbackTunnel.forward")(
507 function* ({ environmentId, remotePort }) {
508 const existing = forwarded.get(forwardKey(environmentId, remotePort));
509 if (existing) return existing.forward;
510 if (yield* sharesLoopback(environmentId)) {
511 return yield* new LoopbackTunnelSameMachineError({ environmentId, port: remotePort });
512 }
513 const scope = yield* Scope.fork(listenerScope);
514 const bind = (port: number) =>
515 NodeSocketServer.make({ port, host: "127.0.0.1" }).pipe(Scope.provide(scope));
516 const server = yield* bind(remotePort).pipe(
517 // Taken here, or privileged: any free port still reaches the environment's.
518 Effect.catch(() => bind(0)),
519 Effect.onError(() => Scope.close(scope, Exit.void)),
520 Effect.mapError(
521 (cause) => new LoopbackTunnelForwardError({ environmentId, port: remotePort, cause }),
522 ),
523 );
524 yield* server.run(serveForward(environmentId, remotePort)).pipe(Effect.forkIn(scope));
525 const forward = {
526 environmentId,
527 remotePort,
528 localPort: (server.address as NetAddress.InetAddress).port,
529 };
530 forwarded.set(forwardKey(environmentId, remotePort), { forward, scope });
531 yield* announceForwards;
532 return forward;
533 },
534 forwarding.withPermits(1),
535 );
536
537 const stopForward: LoopbackTunnel["Service"]["stopForward"] = Effect.fn(
538 "LoopbackTunnel.stopForward",
539 )(function* ({ environmentId, remotePort }) {
540 const key = forwardKey(environmentId, remotePort);
541 const existing = forwarded.get(key);
542 if (!existing) return;
543 forwarded.delete(key);
544 // Closing the scope also ends the connections it carries.
545 yield* Scope.close(existing.scope, Exit.void);
546 yield* announceForwards;
547 }, forwarding.withPermits(1));
548
549 const subscribeForwards: LoopbackTunnel["Service"]["subscribeForwards"] = (listener) =>
550 Effect.acquireRelease(
551 Effect.sync(() => forwardListeners.add(listener)),
552 () => Effect.sync(() => forwardListeners.delete(listener)),
553 ).pipe(Effect.asVoid);
554
555 const listen = Effect.fn("LoopbackTunnel.listen")(function* (environmentId: string) {
556 const existing = listenerPorts.get(environmentId);
557 if (existing !== undefined) return existing;
558 // Listeners live as long as the app: a session can be routed back through at any time.
559 const server = yield* NodeSocketServer.make({ port: 0, host: "127.0.0.1" }).pipe(
560 Scope.provide(listenerScope),
561 Effect.mapError((cause) => new LoopbackTunnelRouteError({ environmentId, cause })),
562 );
563 yield* server.run(serve(environmentId)).pipe(Effect.forkIn(listenerScope));
564 const port = (server.address as NetAddress.InetAddress).port;
565 listenerPorts.set(environmentId, port);
566 return port;
567 });
568
569 const route: LoopbackTunnel["Service"]["route"] = Effect.fn("LoopbackTunnel.route")(function* ({
570 environmentId,
571 session,
572 tunnelled,
573 }) {
574 if (routed.has(session) === tunnelled) return;
575 const port = tunnelled ? yield* listen(environmentId) : null;
576 yield* Effect.tryPromise({
577 try: async () => {
578 await session.setProxy(
579 port === null
580 ? { mode: "system" }
581 : {
582 mode: "fixed_servers",
583 proxyRules: `socks5://127.0.0.1:${port}`,
584 // Chromium never asks a PAC script about loopback hosts, so the split is done
585 // here: `*` sends everything direct, and the later `<-loopback>` takes loopback
586 // back out of that bypass, along with link-local, which the CIDRs return. The
587 // last matching rule wins. A fixed proxy has no direct retry.
588 proxyBypassRules: "*,<-loopback>,169.254.0.0/16,fe80::/10",
589 },
590 );
591 // The bypass rules don't cover the unspecified address, so it would reach this machine.
592 if (port === null) session.webRequest.onBeforeRequest(null);
593 else {
594 session.webRequest.onBeforeRequest(
595 { urls: UNSPECIFIED_ADDRESS_URLS },
596 sendUnspecifiedToLocalhost,
597 );
598 }
599 await session.closeAllConnections();
600 },
601 catch: (cause) => new LoopbackTunnelRouteError({ environmentId, cause }),
602 });
603 if (tunnelled) routed.add(session);
604 else routed.delete(session);
605 }, routing.withPermits(1));
606
607 const resolveAccess: LoopbackTunnel["Service"]["resolveAccess"] = ({ requestId, url }) => {
608 const answer = pending.get(requestId);
609 return answer ? Deferred.succeed(answer, url).pipe(Effect.asVoid) : Effect.void;
610 };
611
612 return LoopbackTunnel.of({
613 route,
614 resolveAccess,
615 forward,
616 stopForward,
617 forwards: Effect.sync(currentForwards),
618 sharesLoopback,
619 subscribeForwards,
620 });
621 });
622
623 export const layer = Layer.effect(LoopbackTunnel, make);