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

LoopbackTunnel.ts

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