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

LoopbackTunnel.ts

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