Open History to see the last commit
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.
4import * as NodeSocket from "@effect/platform-node/NodeSocket";
5import * as NodeSocketServer from "@effect/platform-node/NodeSocketServer";
6import * as NodeWS from "@effect/platform-node/NodeWS";
7import type { DesktopPreviewTunnelAccessRequest } from "@t3tools/contracts";
8import * as HostProcess from "@t3tools/shared/HostProcess";
9import type { NonEmptyReadonlyArray } from "effect/Array";
10import * as Context from "effect/Context";
11import * as Deferred from "effect/Deferred";
12import * as Effect from "effect/Effect";
13import * as FileSystem from "effect/FileSystem";
14import * as Layer from "effect/Layer";
15import * as NetAddress from "effect/net/NetAddress";
16import * as Option from "effect/Option";
17import * as Result from "effect/Result";
18import * as Schema from "effect/Schema";
19import * as Scope from "effect/Scope";
20import * as Semaphore from "effect/Semaphore";
21import * as Socket from "effect/socket/Socket";
22
23import * as ElectronWindow from "../electron/ElectronWindow.ts";
24import { PREVIEW_TUNNEL_ACCESS_REQUEST_CHANNEL } from "../ipc/channels.ts";
25
26const ACCESS_TIMEOUT = "15 seconds";
27const CONNECT_TIMEOUT = "10 seconds";
28
29const REPLY_SUCCEEDED = 0;
30const REPLY_FAILURE = 1;
31const REPLY_NOT_ALLOWED = 2;
32const REPLY_COMMAND_NOT_SUPPORTED = 7;
33const REPLY_ADDRESS_NOT_SUPPORTED = 8;
34
35const socksReply = (code: number) => Uint8Array.of(5, code, 0, 1, 0, 0, 0, 0, 0, 0);
36
37// Chromium names the host as typed, so IP literals also arrive as domain names, and a fully
38// qualified `localhost.` keeps its trailing dot.
39const isLoopbackName = (typed: string) => {
40 const name = typed.replace(/\.$/, "");
41 return (
42 name === "localhost" ||
43 name.endsWith(".localhost") ||
44 Result.match(NetAddress.ipFromString(name), {
45 onSuccess: NetAddress.isLoopback,
46 onFailure: () => false,
47 })
48 );
49};
50
51// `*://` matches only http and https, so WebSocket schemes are listed separately.
52const UNSPECIFIED_ADDRESS_URLS = ["http", "https", "ws", "wss"].flatMap((scheme) => [
53 `${scheme}://0.0.0.0/*`,
54 `${scheme}://[::]/*`,
55]);
56
57const sendUnspecifiedToLocalhost = (
58 details: Electron.OnBeforeRequestListenerDetails,
59 callback: (response: Electron.CallbackResponse) => void,
60) => {
61 const url = new URL(details.url);
62 // A WebSocket handshake can't be redirected.
63 if (url.protocol === "ws:" || url.protocol === "wss:") return callback({ cancel: true });
64 url.hostname = "localhost";
65 callback({ redirectURL: url.toString() });
66};
67
68type SocksRequest = { readonly port: number } | { readonly refusal: number };
69
70/** Undefined until the whole request has arrived. */
71const parseConnect = (data: Buffer): SocksRequest | undefined => {
72 if (data.length < 5) return undefined;
73 const addressType = data[3];
74 const hostLength =
75 addressType === 1 ? 4 : addressType === 4 ? 16 : addressType === 3 ? 1 + data[4]! : -1;
76 if (hostLength < 0) return { refusal: REPLY_ADDRESS_NOT_SUPPORTED };
77 if (data.length < 4 + hostLength + 2) return undefined;
78 if (data[0] !== 5 || data[1] !== 1) return { refusal: REPLY_COMMAND_NOT_SUPPORTED };
79 const host = data.subarray(4, 4 + hostLength);
80 const loopback =
81 addressType === 1
82 ? NetAddress.isLoopback(NetAddress.ipv4FromBytesUnsafe(host))
83 : addressType === 4
84 ? NetAddress.isLoopback(NetAddress.ipv6FromBytesUnsafe(host))
85 : isLoopbackName(host.subarray(1).toString("latin1").toLowerCase());
86 return loopback ? { port: data.readUInt16BE(4 + hostLength) } : { refusal: REPLY_NOT_ALLOWED };
87};
88
89/** Answers the greeting and reads the CONNECT; undefined when the client offers no usable auth. */
90const readSocksRequest = Effect.fn("LoopbackTunnel.readSocksRequest")(function* (
91 pull: Effect.Effect<NonEmptyReadonlyArray<Uint8Array>, Socket.SocketError>,
92 writer: Socket.Writer,
93) {
94 let received = Buffer.alloc(0);
95 let greeted = false;
96 while (true) {
97 received = Buffer.concat([received, ...(yield* pull)]);
98 if (!greeted) {
99 const methods = received[1];
100 if (methods === undefined || received.length < 2 + methods) continue;
101 if (received[0] !== 5 || !received.subarray(2, 2 + methods).includes(0)) {
102 yield* writer.write(Uint8Array.of(5, 0xff));
103 return undefined;
104 }
105 yield* writer.write(Uint8Array.of(5, 0));
106 received = received.subarray(2 + methods);
107 greeted = true;
108 }
109 const request = parseConnect(received);
110 if (request !== undefined) return request;
111 }
112});
113
114// Over an SSH forward the environment's own origin is a loopback port here, and signed asset
115// URLs point at it. That port is the environment, not one of its loopback servers.
116const tunnelEndpoint = (tunnelUrl: string) => {
117 const url = new URL(tunnelUrl);
118 return {
119 host: url.hostname.replace(/^\[|\]$/g, ""),
120 port: Number(url.port || (url.protocol === "wss:" ? 443 : 80)),
121 };
122};
123
124const isTunnelEndpoint = (tunnelUrl: string, port: number) => {
125 const endpoint = tunnelEndpoint(tunnelUrl);
126 return isLoopbackName(endpoint.host) && endpoint.port === port;
127};
128
129/** Opens a connection to the destination; `ws` pauses its socket, so a slow page slows the tunnel. */
130const dialDestination = Effect.fn("LoopbackTunnel.dialDestination")(function* (
131 tunnelUrl: string,
132 port: number,
133) {
134 if (isTunnelEndpoint(tunnelUrl, port)) {
135 const endpoint = yield* NodeSocket.makeNet({
136 ...tunnelEndpoint(tunnelUrl),
137 openTimeout: CONNECT_TIMEOUT,
138 });
139 return { pull: yield* Socket.readerBytes(endpoint), writer: yield* endpoint.writer };
140 }
141 const url = new URL(tunnelUrl);
142 url.searchParams.set("port", String(port));
143 const tunnel = yield* Effect.acquireRelease(
144 Effect.sync(() =>
145 // Closing before the handshake finishes emits an error after Socket's listeners are gone.
146 new NodeWS.WebSocket(url).on("error", () => undefined),
147 ),
148 (tunnel) => Effect.sync(() => tunnel.close()),
149 );
150 const socket = yield* Socket.fromWebSocket(Effect.succeed(tunnel), {
151 openTimeout: CONNECT_TIMEOUT,
152 });
153 // Effect's WebSocket writer never waits for the send buffer; `ws` calls back once it is written.
154 const sendAll = (chunks: NonEmptyReadonlyArray<Uint8Array>) =>
155 Effect.callback<void>((resume) => {
156 const last = chunks.length - 1;
157 chunks.forEach((chunk, index) =>
158 tunnel.send(chunk, index === last ? () => resume(Effect.void) : undefined),
159 );
160 });
161 return {
162 pull: yield* Socket.readerBytes(socket),
163 writer: { write: (chunk: Uint8Array) => sendAll([chunk]), writeAll: sendAll },
164 };
165});
166
167const TCP_TABLES = ["/proc/net/tcp", "/proc/net/tcp6"];
168
169// Rows read `sl local_address rem_address st queues timer retransmits uid ...`, with addresses
170// as HEXIP:HEXPORT and IPv4 bytes in little-endian order; tcp6 holds IPv4 as ::ffff:a.b.c.d.
171const procAddresses = (ip: string, port: number) => {
172 const octets = ip
173 .replace(/^::ffff:/i, "")
174 .split(".")
175 .map(Number);
176 const v4 = octets
177 .reverse()
178 .map((octet) => octet.toString(16).padStart(2, "0"))
179 .join("")
180 .toUpperCase();
181 const hexPort = port.toString(16).padStart(4, "0").toUpperCase();
182 return [`${v4}:${hexPort}`, `0000000000000000FFFF0000${v4}:${hexPort}`];
183};
184
185/** The owner of the row whose local end is the client and remote end is the listener. */
186const connectionOwner = (
187 tables: ReadonlyArray<string>,
188 client: { readonly address: string; readonly port: number },
189 listener: { readonly address: string; readonly port: number },
190) => {
191 const clientEnds = procAddresses(client.address, client.port);
192 const listenerEnds = procAddresses(listener.address, listener.port);
193 for (const line of tables.flatMap((table) => table.split("\n").slice(1))) {
194 const [, local, remote, , , , , uid] = line.trim().split(/\s+/);
195 if (
196 local !== undefined &&
197 remote !== undefined &&
198 clientEnds.includes(local.toUpperCase()) &&
199 listenerEnds.includes(remote.toUpperCase())
200 ) {
201 return Number(uid);
202 }
203 }
204 return undefined;
205};
206
207const pump =
208 /* Runs for the life of the connection; a span per direction adds no diagnostic value. */
209 Effect.fnUntraced(function* (
210 pull: Effect.Effect<NonEmptyReadonlyArray<Uint8Array>, Socket.SocketError>,
211 writeAll: (
212 chunks: NonEmptyReadonlyArray<Uint8Array>,
213 ) => Effect.Effect<void, Socket.SocketError>,
214 ) {
215 while (true) yield* writeAll(yield* pull);
216 });
217
218export class LoopbackTunnelRouteError extends Schema.TaggedError<LoopbackTunnelRouteError>()(
219 "LoopbackTunnelRouteError",
220 { environmentId: Schema.String, cause: Schema.Defect() },
221) {
222 override get message(): string {
223 return `Failed to route preview traffic for environment "${this.environmentId}".`;
224 }
225}
226
227export class LoopbackTunnel extends Context.Service<
228 LoopbackTunnel,
229 {
230 /** Sends a preview session's loopback traffic to its environment, or back to this machine. */
231 readonly route: (input: {
232 readonly environmentId: string;
233 readonly session: Electron.Session;
234 readonly tunnelled: boolean;
235 }) => Effect.Effect<void, LoopbackTunnelRouteError>;
236 readonly resolveAccess: (input: {
237 readonly requestId: string;
238 readonly url: string | null;
239 }) => Effect.Effect<void>;
240 }
241>()("@t3tools/desktop/preview/LoopbackTunnel") {}
242
243const make = Effect.gen(function* () {
244 const electronWindow = yield* ElectronWindow.ElectronWindow;
245 const fileSystem = yield* FileSystem.FileSystem;
246 const platform = yield* HostProcess.Platform;
247 const userId = yield* HostProcess.UserId;
248 const listenerScope = yield* Effect.scope;
249 const routing = yield* Semaphore.make(1);
250 const pending = new Map<string, Deferred.Deferred<string | null>>();
251 const listenerPorts = new Map<string, number>();
252 const routed = new WeakSet<Electron.Session>();
253 let requestCount = 0;
254
255 // The renderer owns environment credentials and the selected route, so it is asked per
256 // connection; it decides how long a ticket is reused.
257 const requestAccess = Effect.fn("LoopbackTunnel.requestAccess")(function* (
258 environmentId: string,
259 ) {
260 const window = yield* electronWindow.currentMainOrFirst;
261 if (Option.isNone(window) || window.value.isDestroyed()) return null;
262 const requestId = `preview-tunnel-${requestCount++}`;
263 const answer = yield* Deferred.make<string | null>();
264 pending.set(requestId, answer);
265 window.value.webContents.send(PREVIEW_TUNNEL_ACCESS_REQUEST_CHANNEL, {
266 requestId,
267 environmentId,
268 } as DesktopPreviewTunnelAccessRequest);
269 return yield* Deferred.await(answer).pipe(
270 Effect.timeoutOption(ACCESS_TIMEOUT),
271 Effect.map(Option.getOrNull),
272 Effect.ensuring(Effect.sync(() => pending.delete(requestId))),
273 );
274 });
275
276 // Chromium can't authenticate to a SOCKS proxy, so on Linux the listener checks that the
277 // client belongs to this OS user. Other users could otherwise ride this user's tunnel.
278 const isOwnConnection = Effect.fn("LoopbackTunnel.isOwnConnection")(function* () {
279 if (platform !== "linux") return true;
280 const connection = yield* Effect.serviceOption(NodeSocket.NetSocket);
281 if (Option.isNone(connection)) return false;
282 const { remoteAddress, remotePort, localAddress, localPort } = connection.value;
283 if (!remoteAddress || !remotePort || !localAddress || !localPort) return false;
284 const tables = yield* Effect.forEach(TCP_TABLES, (path) =>
285 fileSystem.readFileString(path).pipe(Effect.orElseSucceed(() => "")),
286 );
287 return (
288 connectionOwner(
289 tables,
290 { address: remoteAddress, port: remotePort },
291 { address: localAddress, port: localPort },
292 ) === userId
293 );
294 });
295
296 /** Serves one SOCKS connection; never falls back to a direct local connection. */
297 const serve = (environmentId: string) =>
298 Effect.fn("LoopbackTunnel.serve")(
299 function* (socket: Socket.Socket) {
300 const pull = yield* Socket.readerBytes(socket);
301 const writer = yield* socket.writer;
302 // "No acceptable methods": the only refusal a client gets before its request.
303 if (!(yield* isOwnConnection())) return yield* writer.write(Uint8Array.of(5, 0xff));
304 const request = yield* readSocksRequest(pull, writer);
305 if (request === undefined) return;
306 if ("refusal" in request) return yield* writer.write(socksReply(request.refusal));
307 const tunnelUrl = yield* requestAccess(environmentId);
308 if (tunnelUrl === null) return yield* writer.write(socksReply(REPLY_FAILURE));
309 const destination = yield* dialDestination(tunnelUrl, request.port).pipe(Effect.option);
310 if (Option.isNone(destination)) return yield* writer.write(socksReply(REPLY_FAILURE));
311 yield* writer.write(socksReply(REPLY_SUCCEEDED));
312 return yield* Effect.raceFirst(
313 pump(pull, destination.value.writer.writeAll),
314 pump(destination.value.pull, writer.writeAll),
315 );
316 },
317 Effect.scoped,
318 (effect) => Effect.ignoreCause(effect),
319 );
320
321 const listen = Effect.fn("LoopbackTunnel.listen")(function* (environmentId: string) {
322 const existing = listenerPorts.get(environmentId);
323 if (existing !== undefined) return existing;
324 // Listeners live as long as the app: a session can be routed back through at any time.
325 const server = yield* NodeSocketServer.make({ port: 0, host: "127.0.0.1" }).pipe(
326 Scope.provide(listenerScope),
327 Effect.mapError((cause) => new LoopbackTunnelRouteError({ environmentId, cause })),
328 );
329 yield* server.run(serve(environmentId)).pipe(Effect.forkIn(listenerScope));
330 const port = (server.address as NetAddress.InetAddress).port;
331 listenerPorts.set(environmentId, port);
332 return port;
333 });
334
335 const route: LoopbackTunnel["Service"]["route"] = Effect.fn("LoopbackTunnel.route")(function* ({
336 environmentId,
337 session,
338 tunnelled,
339 }) {
340 if (routed.has(session) === tunnelled) return;
341 const port = tunnelled ? yield* listen(environmentId) : null;
342 yield* Effect.tryPromise({
343 try: async () => {
344 await session.setProxy(
345 port === null
346 ? { mode: "system" }
347 : {
348 mode: "fixed_servers",
349 proxyRules: `socks5://127.0.0.1:${port}`,
350 // Chromium never asks a PAC script about loopback hosts, so the split is done
351 // here: `*` sends everything direct, and the later `<-loopback>` takes loopback
352 // back out of that bypass, along with link-local, which the CIDRs return. The
353 // last matching rule wins. A fixed proxy has no direct retry.
354 proxyBypassRules: "*,<-loopback>,169.254.0.0/16,fe80::/10",
355 },
356 );
357 // The bypass rules don't cover the unspecified address, so it would reach this machine.
358 if (port === null) session.webRequest.onBeforeRequest(null);
359 else {
360 session.webRequest.onBeforeRequest(
361 { urls: UNSPECIFIED_ADDRESS_URLS },
362 sendUnspecifiedToLocalhost,
363 );
364 }
365 await session.closeAllConnections();
366 },
367 catch: (cause) => new LoopbackTunnelRouteError({ environmentId, cause }),
368 });
369 if (tunnelled) routed.add(session);
370 else routed.delete(session);
371 }, routing.withPermits(1));
372
373 const resolveAccess: LoopbackTunnel["Service"]["resolveAccess"] = ({ requestId, url }) => {
374 const answer = pending.get(requestId);
375 return answer ? Deferred.succeed(answer, url).pipe(Effect.asVoid) : Effect.void;
376 };
377
378 return LoopbackTunnel.of({ route, resolveAccess });
379});
380
381export const layer = Layer.effect(LoopbackTunnel, make);