Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

LoopbackTunnel.ts

709 lines29.2 KB

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