@devries-cameron20 / t3code-1 / commits / 0226239a41
Fork 0

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

feat(desktop): render other environments' localhost tabs locally (#37948)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Nov 18, 2026 at 17:49 UTC 0226239a41e1fd0649fdd2562421d8950db7f39c
29 files changed +919 -32
apps/desktop/src/app/DesktopApp.test.ts
+2
@@ -72,6 +72,7 @@ import * as ElectronShell from "../electron/ElectronShell.ts";
72 import * as ElectronTheme from "../electron/ElectronTheme.ts";
73 import * as ElectronWindow from "../electron/ElectronWindow.ts";
74 import * as MacPermissions from "../permissions/MacPermissions.ts";
75 +import * as LoopbackTunnel from "../preview/LoopbackTunnel.ts";
76 import * as PreviewManager from "../preview/Manager.ts";
77
78 interface StubbedDesktop {
@@ -232,6 +233,7 @@ const runStubbedDesktop = (stub: StubbedDesktop) =>
233 Layer.mock(ElectronTheme.ElectronTheme, {}),
234 Layer.mock(ElectronWindow.ElectronWindow, {}),
235 Layer.mock(MacPermissions.MacPermissions, {}),
236 + Layer.mock(LoopbackTunnel.LoopbackTunnel, {}),
237 Layer.mock(PreviewManager.PreviewManager, {
238 isBrowserPartition: () => {
239 throw new Error("unexpected browser partition lookup");
apps/desktop/src/ipc/channels.ts
+2
@@ -126,6 +126,8 @@ export const PREVIEW_STATE_CHANGE_CHANNEL = "desktop:preview-state-change";
126 export const PREVIEW_POINTER_EVENT_CHANNEL = "desktop:preview-pointer-event";
127 export const PREVIEW_OPEN_LINK_CHANNEL = "desktop:preview-open-link";
128 export const PREVIEW_FIND_RESULT_CHANNEL = "desktop:preview-find-result";
129 +export const PREVIEW_TUNNEL_ACCESS_REQUEST_CHANNEL = "desktop:preview-tunnel-access-request";
130 +export const PREVIEW_TUNNEL_ACCESS_RESOLVE_CHANNEL = "desktop:preview-tunnel-access-resolve";
131
132 export const MAC_PERMISSION_HELPER_CHANNEL = "desktop:mac-permission-helper";
133
apps/desktop/src/ipc/methods/preview.ts
+22 -2
@@ -22,6 +22,7 @@ import {
22 DesktopPreviewImportCookiesInputSchema,
23 DesktopPreviewCreateTabInputSchema,
24 DesktopPreviewTabInputSchema,
25 + DesktopPreviewTunnelAccessResolutionInputSchema,
26 DesktopPreviewWebviewConfigSchema,
27 PreviewAnnotationSubmissionResultSchema,
28 PreviewCaptureFailure,
@@ -37,6 +38,7 @@ import * as NodeURL from "node:url";
38
39 import * as ElectronWindow from "../../electron/ElectronWindow.ts";
40 import * as BrowserImport from "../../preview/BrowserImport/BrowserImport.ts";
41 +import * as LoopbackTunnel from "../../preview/LoopbackTunnel.ts";
42 import * as PreviewManager from "../../preview/Manager.ts";
43 import { normalizeCaptureFailure } from "../../preview/captureErrors.ts";
44 import * as DesktopClientSettings from "../../settings/DesktopClientSettings.ts";
@@ -347,11 +349,18 @@ const getPreviewConfig = DesktopIpc.makeIpcMethod({
349 channel: IpcChannels.PREVIEW_GET_CONFIG_CHANNEL,
350 payload: DesktopPreviewConfigInputSchema,
351 result: DesktopPreviewWebviewConfigSchema,
350 - handler: Effect.fn("desktop.ipc.preview.getConfig")(function* ({ environmentId, profileId }) {
352 + handler: Effect.fn("desktop.ipc.preview.getConfig")(function* ({
353 + environmentId,
354 + profileId,
355 + tunnelLoopback,
356 + }) {
357 const manager = yield* PreviewManager.PreviewManager;
358 + const tunnel = yield* LoopbackTunnel.LoopbackTunnel;
359 const { scope, persistent, namespace } = resolvePartitionScope(environmentId, profileId);
360 // Session creation installs UA and permission handlers before a guest can attach.
354 - yield* manager.getBrowserSession(scope, persistent, namespace);
361 + const session = yield* manager.getBrowserSession(scope, persistent, namespace);
362 + // Routed before the renderer learns the partition, so no guest loads loopback directly.
363 + yield* tunnel.route({ environmentId, session, tunnelled: tunnelLoopback === true });
364 return {
365 partition: yield* manager.getBrowserPartition(scope, persistent, namespace),
366 webPreferences: PREVIEW_WEBVIEW_PREFERENCES,
@@ -360,6 +369,16 @@ const getPreviewConfig = DesktopIpc.makeIpcMethod({
369 }),
370 });
371
372 +const resolveTunnelAccess = DesktopIpc.makeIpcMethod({
373 + channel: IpcChannels.PREVIEW_TUNNEL_ACCESS_RESOLVE_CHANNEL,
374 + payload: DesktopPreviewTunnelAccessResolutionInputSchema,
375 + result: Schema.Void,
376 + handler: Effect.fn("desktop.ipc.preview.resolveTunnelAccess")(function* (input) {
377 + const tunnel = yield* LoopbackTunnel.LoopbackTunnel;
378 + yield* tunnel.resolveAccess(input);
379 + }),
380 +});
381 +
382 export const listBrowserImportSources = DesktopIpc.makeIpcMethod({
383 channel: IpcChannels.PREVIEW_IMPORT_SOURCES_CHANNEL,
384 payload: Schema.Void,
@@ -503,6 +522,7 @@ export const methods = [
522 clearCookies,
523 clearCache,
524 getPreviewConfig,
525 + resolveTunnelAccess,
526 setAnnotationTheme,
527 setAnnotationSendEnabled,
528 pickElement,
apps/desktop/src/main.ts
+2
@@ -73,6 +73,7 @@ import * as BrowserImport from "./preview/BrowserImport/BrowserImport.ts";
73 import * as LinuxBrowserSecret from "./preview/BrowserImport/LinuxBrowserSecret.ts";
74 import * as BrowserSession from "./preview/BrowserSession.ts";
75 import * as DesktopBrowserHost from "./preview/DesktopBrowserHost.ts";
76 +import * as LoopbackTunnel from "./preview/LoopbackTunnel.ts";
77 import * as PreviewManager from "./preview/Manager.ts";
78 import * as PreviewPasskeys from "./preview/Passkeys.ts";
79 import * as DesktopWindow from "./window/DesktopWindow.ts";
@@ -167,6 +168,7 @@ const layerDesktopServerExposure = DesktopServerExposure.layer.pipe(
168 );
169
170 const layerDesktopPreview = PreviewManager.layer.pipe(
171 + Layer.provideMerge(LoopbackTunnel.layer),
172 Layer.provideMerge(DesktopBrowserHost.layer),
173 // IPC needs both services on the same BrowserSession.
174 Layer.provideMerge(BrowserImport.layer.pipe(Layer.provide(LinuxBrowserSecret.layer))),
apps/desktop/src/preload.ts
+20 -2
@@ -429,8 +429,26 @@ contextBridge.exposeInMainWorld("desktopBridge", {
429 ipcRenderer.invoke(IpcChannels.PREVIEW_CLEAR_COOKIES_CHANNEL, { environmentId, profileId }),
430 clearCache: (environmentId, profileId) =>
431 ipcRenderer.invoke(IpcChannels.PREVIEW_CLEAR_CACHE_CHANNEL, { environmentId, profileId }),
432 - getPreviewConfig: (environmentId, profileId) =>
433 - ipcRenderer.invoke(IpcChannels.PREVIEW_GET_CONFIG_CHANNEL, { environmentId, profileId }),
432 + getPreviewConfig: (environmentId, profileId, tunnelLoopback) =>
433 + ipcRenderer.invoke(IpcChannels.PREVIEW_GET_CONFIG_CHANNEL, {
434 + environmentId,
435 + profileId,
436 + tunnelLoopback,
437 + }),
438 + onTunnelAccessRequest: (listener) => {
439 + const wrappedListener = (_event: Electron.IpcRendererEvent, request: unknown) => {
440 + if (typeof request !== "object" || request === null) return;
441 + listener(request as Parameters<typeof listener>[0]);
442 + };
443 + ipcRenderer.on(IpcChannels.PREVIEW_TUNNEL_ACCESS_REQUEST_CHANNEL, wrappedListener);
444 + return () =>
445 + ipcRenderer.removeListener(
446 + IpcChannels.PREVIEW_TUNNEL_ACCESS_REQUEST_CHANNEL,
447 + wrappedListener,
448 + );
449 + },
450 + resolveTunnelAccess: (requestId, url) =>
451 + ipcRenderer.invoke(IpcChannels.PREVIEW_TUNNEL_ACCESS_RESOLVE_CHANNEL, { requestId, url }),
452 setAnnotationTheme: (theme) =>
453 ipcRenderer.invoke(IpcChannels.PREVIEW_SET_ANNOTATION_THEME_CHANNEL, { theme }),
454 setAnnotationSendEnabled: (tabId, enabled) =>
apps/desktop/src/preview/LoopbackTunnel.test.ts new
+286
@@ -0,0 +1,286 @@
1 +import * as NodeFileSystem from "@effect/platform-node/NodeFileSystem";
2 +import * as NodeWS from "@effect/platform-node/NodeWS";
3 +import * as HostProcess from "@t3tools/shared/HostProcess";
4 +import { expect, it } from "@effect/vitest";
5 +import * as NodeNet from "node:net";
6 +import * as Context from "effect/Context";
7 +import * as Effect from "effect/Effect";
8 +import * as FileSystem from "effect/FileSystem";
9 +import * as Layer from "effect/Layer";
10 +import * as Queue from "effect/Queue";
11 +
12 +import * as ElectronWindow from "../electron/ElectronWindow.ts";
13 +import * as LoopbackTunnel from "./LoopbackTunnel.ts";
14 +
15 +const addressPort = (server: NodeNet.Server | NodeWS.WebSocketServer) =>
16 + (server.address() as NodeNet.AddressInfo).port;
17 +
18 +const closeServer = (server: NodeNet.Server | NodeWS.WebSocketServer) =>
19 + Effect.promise(
20 + () =>
21 + new Promise<void>((resolve) => {
22 + if (server instanceof NodeWS.WebSocketServer) {
23 + for (const client of server.clients) client.terminate();
24 + }
25 + server.close(() => resolve());
26 + }),
27 + );
28 +
29 +/** A local listener that must never see a connection: the reviewer's own localhost server. */
30 +const listenDecoy = Effect.acquireRelease(
31 + Effect.promise(
32 + () =>
33 + new Promise<{ server: NodeNet.Server; connections: () => number }>((resolve) => {
34 + let connections = 0;
35 + const server = NodeNet.createServer((socket) => {
36 + connections++;
37 + socket.destroy();
38 + });
39 + server.listen(0, "127.0.0.1", () => resolve({ server, connections: () => connections }));
40 + }),
41 + ),
42 + ({ server }) => closeServer(server),
43 +);
44 +
45 +/** Stands in for the environment's /api/preview/tunnel: echoes each frame behind a 0xee byte. */
46 +const listenEndpoint = Effect.acquireRelease(
47 + Effect.promise(
48 + () =>
49 + new Promise<{ server: NodeWS.WebSocketServer; requests: string[] }>((resolve) => {
50 + const requests: string[] = [];
51 + const server: NodeWS.WebSocketServer = new NodeWS.WebSocketServer(
52 + { port: 0, host: "127.0.0.1" },
53 + () => resolve({ server, requests }),
54 + );
55 + server.on("connection", (socket: NodeWS.WebSocket, request: { url?: string }) => {
56 + requests.push(request.url ?? "");
57 + socket.on("message", (data: Buffer) =>
58 + socket.send(Buffer.concat([Uint8Array.of(0xee), data])),
59 + );
60 + });
61 + }),
62 + ),
63 + ({ server }) => closeServer(server),
64 +);
65 +
66 +const unusedPort = Effect.promise(
67 + () =>
68 + new Promise<number>((resolve) => {
69 + const server = NodeNet.createServer();
70 + server.listen(0, "127.0.0.1", () => {
71 + const port = addressPort(server);
72 + server.close(() => resolve(port));
73 + });
74 + }),
75 +);
76 +
77 +/** Routes a stand-in session through the tunnel and returns its SOCKS listener port. */
78 +const routeThroughTunnel = (
79 + tunnelUrl: string | null,
80 + host?: Layer.Layer<FileSystem.FileSystem> | Layer.Layer<never>,
81 +) =>
82 + Effect.gen(function* () {
83 + const accessRequests = yield* Queue.unbounded<string>();
84 + const window = {
85 + isDestroyed: () => false,
86 + webContents: {
87 + send: (_channel: string, request: { readonly requestId: string }) =>
88 + Queue.offerUnsafe(accessRequests, request.requestId),
89 + },
90 + };
91 + const services = yield* Layer.build(
92 + LoopbackTunnel.layer.pipe(
93 + Layer.provide(
94 + Layer.mergeAll(
95 + Layer.mock(ElectronWindow.ElectronWindow, {
96 + currentMainOrFirst: Effect.succeedSome(window as unknown as Electron.BrowserWindow),
97 + }),
98 + NodeFileSystem.layer,
99 + host ?? Layer.empty,
100 + ),
101 + ),
102 + ),
103 + );
104 + const tunnel = Context.get(services, LoopbackTunnel.LoopbackTunnel);
105 + yield* Queue.take(accessRequests).pipe(
106 + Effect.flatMap((requestId) => tunnel.resolveAccess({ requestId, url: tunnelUrl })),
107 + Effect.forever,
108 + Effect.forkScoped,
109 + );
110 + let proxyRules = "";
111 + const session = {
112 + setProxy: async (config: Electron.ProxyConfig) => {
113 + proxyRules = config.proxyRules ?? "";
114 + },
115 + closeAllConnections: async () => undefined,
116 + webRequest: { onBeforeRequest: () => undefined },
117 + };
118 + yield* tunnel.route({
119 + environmentId: "remote",
120 + session: session as unknown as Electron.Session,
121 + tunnelled: true,
122 + });
123 + return Number(/socks5:\/\/127\.0\.0\.1:(\d+)/.exec(proxyRules)![1]);
124 + });
125 +
126 +/**
127 + * The real TCP tables with 127.0.0.1 in one column rewritten to 127.0.0.2. The rows keep their
128 + * ports and owner, so only an address mismatch can refuse them.
129 + */
130 +const tcpTablesWithMovedAddress = (column: 1 | 2) =>
131 + Layer.effect(
132 + FileSystem.FileSystem,
133 + Effect.gen(function* () {
134 + const fileSystem = yield* FileSystem.FileSystem;
135 + const moveAddress = (line: string) => {
136 + const columns = line.trim().split(/\s+/);
137 + const address = columns[column];
138 + if (address === undefined || !/0100007F:/i.test(address)) return line;
139 + columns[column] = address.replace(/0100007F:/i, "0200007F:");
140 + return columns.join(" ");
141 + };
142 + return FileSystem.FileSystem.of({
143 + ...fileSystem,
144 + readFileString: (path, encoding) =>
145 + fileSystem
146 + .readFileString(path, encoding)
147 + .pipe(Effect.map((table) => table.split("\n").map(moveAddress).join("\n"))),
148 + });
149 + }),
150 + ).pipe(Layer.provide(NodeFileSystem.layer));
151 +
152 +/** Greets the SOCKS listener and sends a CONNECT for `host:port`; resolves with the reply. */
153 +const socksConnect = (proxyPort: number, host: string, port: number) =>
154 + Effect.acquireRelease(
155 + Effect.promise(
156 + () =>
157 + new Promise<{ socket: NodeNet.Socket; reply: Buffer }>((resolve, reject) => {
158 + const socket = NodeNet.connect(proxyPort, "127.0.0.1", () =>
159 + socket.write(Uint8Array.of(5, 1, 0)),
160 + );
161 + let received = Buffer.alloc(0);
162 + let greeted = false;
163 + const onData = (chunk: Buffer) => {
164 + received = Buffer.concat([received, chunk]);
165 + if (!greeted && received.length >= 2) {
166 + // A refused greeting is the whole answer.
167 + if (received[1] !== 0) return resolve({ socket, reply: received.subarray(0, 2) });
168 + greeted = true;
169 + received = received.subarray(2);
170 + const destination = Buffer.alloc(2);
171 + destination.writeUInt16BE(port);
172 + socket.write(
173 + Buffer.concat([
174 + Uint8Array.of(5, 1, 0, 3, host.length),
175 + Buffer.from(host, "latin1"),
176 + destination,
177 + ]),
178 + );
179 + }
180 + if (greeted && received.length >= 10) {
181 + socket.off("data", onData);
182 + resolve({ socket, reply: received.subarray(0, 10) });
183 + }
184 + };
185 + socket.on("data", onData);
186 + socket.on("error", reject);
187 + }),
188 + ),
189 + ({ socket }) => Effect.sync(() => socket.destroy()),
190 + );
191 +
192 +it.effect.each(["localhost", "localhost."])(
193 + "carries a loopback CONNECT for %s over the tunnel WebSocket, not to local listeners",
194 + (host) =>
195 + Effect.gen(function* () {
196 + const decoy = yield* listenDecoy;
197 + const endpoint = yield* listenEndpoint;
198 + const proxyPort = yield* routeThroughTunnel(
199 + `ws://127.0.0.1:${addressPort(endpoint.server)}/api/preview/tunnel?wsTicket=t`,
200 + );
201 + const { socket, reply } = yield* socksConnect(proxyPort, host, addressPort(decoy.server));
202 + expect(reply[1]).toBe(0);
203 + const echoed = yield* Effect.promise(
204 + () =>
205 + new Promise<number[]>((resolve) => {
206 + socket.once("data", (chunk) => resolve([...chunk]));
207 + socket.write(Uint8Array.of(1, 2, 3));
208 + }),
209 + );
210 + expect(echoed).toEqual([0xee, 1, 2, 3]);
211 + expect(endpoint.requests).toEqual([
212 + `/api/preview/tunnel?wsTicket=t&port=${addressPort(decoy.server)}`,
213 + ]);
214 + expect(decoy.connections()).toBe(0);
215 + }),
216 +);
217 +
218 +it.effect.each([
219 + { case: "a non-loopback destination", host: "192.168.1.20", tunnel: "endpoint" },
220 + { case: "no tunnel URL", host: "127.0.0.1", tunnel: "none" },
221 + { case: "an unreachable tunnel endpoint", host: "localhost", tunnel: "unreachable" },
222 + { case: "another OS user's client", host: "localhost", tunnel: "other-user" },
223 + { case: "a TCP row whose client address differs", host: "localhost", tunnel: "moved-client" },
224 + { case: "a TCP row whose listener address differs", host: "localhost", tunnel: "moved-listener" },
225 +] as const)("fails the SOCKS request for $case without dialling locally", ({ host, tunnel }) =>
226 + Effect.gen(function* () {
227 + const decoy = yield* listenDecoy;
228 + const endpoint = yield* listenEndpoint;
229 + const endpointPort =
230 + tunnel === "unreachable" ? yield* unusedPort : addressPort(endpoint.server);
231 + const proxyPort = yield* routeThroughTunnel(
232 + tunnel === "none" ? null : `ws://127.0.0.1:${endpointPort}/api/preview/tunnel`,
233 + // This process owns the client, so a different user id here makes it another user's.
234 + tunnel === "other-user"
235 + ? Layer.mergeAll(
236 + Layer.succeed(HostProcess.Platform, "linux"),
237 + Layer.succeed(HostProcess.UserId, (process.getuid?.() ?? 0) + 1),
238 + )
239 + : tunnel === "moved-client" || tunnel === "moved-listener"
240 + ? Layer.mergeAll(
241 + Layer.succeed(HostProcess.Platform, "linux"),
242 + tcpTablesWithMovedAddress(tunnel === "moved-client" ? 1 : 2),
243 + )
244 + : undefined,
245 + );
246 + const { reply } = yield* socksConnect(proxyPort, host, addressPort(decoy.server));
247 + expect(reply[1]).not.toBe(0);
248 + expect(endpoint.requests).toEqual([]);
249 + expect(decoy.connections()).toBe(0);
250 + }),
251 +);
252 +
253 +it.effect("connects straight to the environment's own forwarded origin port", () =>
254 + Effect.gen(function* () {
255 + // Over SSH the origin is a local forward, and signed file previews load from it.
256 + const received: number[] = [];
257 + const origin = yield* Effect.acquireRelease(
258 + Effect.promise(
259 + () =>
260 + new Promise<NodeNet.Server>((resolve) => {
261 + const server = NodeNet.createServer((socket) =>
262 + socket.on("data", (chunk) => {
263 + received.push(...chunk);
264 + socket.write(chunk);
265 + }),
266 + );
267 + server.listen(0, "127.0.0.1", () => resolve(server));
268 + }),
269 + ),
270 + closeServer,
271 + );
272 + const port = addressPort(origin);
273 + const proxyPort = yield* routeThroughTunnel(`ws://127.0.0.1:${port}/api/preview/tunnel`);
274 + const { socket, reply } = yield* socksConnect(proxyPort, "127.0.0.1", port);
275 + expect(reply[1]).toBe(0);
276 + const echoed = yield* Effect.promise(
277 + () =>
278 + new Promise<number[]>((resolve) => {
279 + socket.once("data", (chunk) => resolve([...chunk]));
280 + socket.write(Uint8Array.of(7, 8));
281 + }),
282 + );
283 + expect(echoed).toEqual([7, 8]);
284 + expect(received).toEqual([7, 8]);
285 + }),
286 +);
apps/desktop/src/preview/LoopbackTunnel.ts new
+381
@@ -0,0 +1,381 @@
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.
4 +import * as NodeSocket from "@effect/platform-node/NodeSocket";
5 +import * as NodeSocketServer from "@effect/platform-node/NodeSocketServer";
6 +import * as NodeWS from "@effect/platform-node/NodeWS";
7 +import type { DesktopPreviewTunnelAccessRequest } from "@t3tools/contracts";
8 +import * as HostProcess from "@t3tools/shared/HostProcess";
9 +import type { NonEmptyReadonlyArray } from "effect/Array";
10 +import * as Context from "effect/Context";
11 +import * as Deferred from "effect/Deferred";
12 +import * as Effect from "effect/Effect";
13 +import * as FileSystem from "effect/FileSystem";
14 +import * as Layer from "effect/Layer";
15 +import * as NetAddress from "effect/net/NetAddress";
16 +import * as Option from "effect/Option";
17 +import * as Result from "effect/Result";
18 +import * as Schema from "effect/Schema";
19 +import * as Scope from "effect/Scope";
20 +import * as Semaphore from "effect/Semaphore";
21 +import * as Socket from "effect/socket/Socket";
22 +
23 +import * as ElectronWindow from "../electron/ElectronWindow.ts";
24 +import { PREVIEW_TUNNEL_ACCESS_REQUEST_CHANNEL } from "../ipc/channels.ts";
25 +
26 +const ACCESS_TIMEOUT = "15 seconds";
27 +const CONNECT_TIMEOUT = "10 seconds";
28 +
29 +const REPLY_SUCCEEDED = 0;
30 +const REPLY_FAILURE = 1;
31 +const REPLY_NOT_ALLOWED = 2;
32 +const REPLY_COMMAND_NOT_SUPPORTED = 7;
33 +const REPLY_ADDRESS_NOT_SUPPORTED = 8;
34 +
35 +const 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.
39 +const 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.
52 +const UNSPECIFIED_ADDRESS_URLS = ["http", "https", "ws", "wss"].flatMap((scheme) => [
53 + `${scheme}://0.0.0.0/*`,
54 + `${scheme}://[::]/*`,
55 +]);
56 +
57 +const 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 +
68 +type SocksRequest = { readonly port: number } | { readonly refusal: number };
69 +
70 +/** Undefined until the whole request has arrived. */
71 +const 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. */
90 +const 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.
116 +const 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 +
124 +const 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. */
130 +const 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 +
167 +const 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.
171 +const 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. */
186 +const 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 +
207 +const 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 +
218 +export 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 +
227 +export 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 +
243 +const 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 +
381 +export const layer = Layer.effect(LoopbackTunnel, make);
apps/web/src/browser/ElectronBrowserHost.tsx
+6
@@ -22,6 +22,7 @@ import {
22 } from "~/previewStateStore";
23 import { appAtomRegistry } from "~/rpc/atomRegistry";
24 import { previewEnvironment } from "~/state/preview";
25 +import { readPreviewTunnelUrl } from "~/state/previewTunnel";
26 import { useEnvironmentScope } from "~/state/session";
27
28 import { readPreviewAnnotationTheme } from "./annotationTheme";
@@ -119,6 +120,11 @@ export function startElectronBrowserHost(): () => void {
120 useBrowserPointerStore.getState().apply(event);
121 }),
122 preview.onOpenLink(openLinkInPreview),
123 + preview.onTunnelAccessRequest(({ requestId, environmentId }) => {
124 + void readPreviewTunnelUrl(environmentId).then((url) =>
125 + preview.resolveTunnelAccess(requestId, url),
126 + );
127 + }),
128 ];
129 return () => {
130 for (const dispose of disposers) dispose();
apps/web/src/browser/browserTargetResolver.test.ts
+7 -2
@@ -40,7 +40,8 @@ describe("browser target resolver", () => {
40
41 it("keeps localhost for servers on the desktop's own WSL or primary backend", async () => {
42 // WSL NAT advertises a distro IP, but loopback-bound servers only answer on localhost.
43 - const { resolveDiscoveredServerUrl } = await import("./browserTargetResolver");
43 + const { resolveDiscoveredServerUrl, resolveExternalServerUrl } =
44 + await import("./browserTargetResolver");
45 env.isElectron = true;
46 try {
47 for (const target of [
@@ -56,9 +57,13 @@ describe("browser target resolver", () => {
57 httpBaseUrl: "http://192.168.1.25:3773",
58 target: { _tag: "BearerConnectionTarget", connectionId: "saved:remote" },
59 });
60 + // The webview's partition tunnels to the environment; the system browser has no tunnel.
61 expect(
62 resolveDiscoveredServerUrl(EnvironmentId.make("environment-1"), "localhost:3001/"),
61 - ).toBe("http://192.168.1.25:3001/");
63 + ).toBe("http://localhost:3001/");
64 + expect(resolveExternalServerUrl(EnvironmentId.make("environment-1"), "localhost:3001/")).toBe(
65 + "http://192.168.1.25:3001/",
66 + );
67 } finally {
68 env.isElectron = false;
69 }
apps/web/src/browser/browserTargetResolver.ts
+20 -4
@@ -58,16 +58,24 @@ const resolveEnvironmentPortTarget = (
58 };
59 };
60
61 -// Desktop renders primary and WSL tabs locally; loopback servers require localhost even for LAN backends.
61 +// Loopback servers on the desktop's own primary and WSL backends answer on this machine's localhost.
62 const reachesEnvironmentLoopback = (target: ConnectionTarget): boolean =>
63 isElectron &&
64 (target._tag === "PrimaryConnectionTarget" || isDesktopLocalConnectionTarget(target));
65
66 -export function resolveDiscoveredServerUrl(environmentId: EnvironmentId, rawUrl: string): string {
66 +/** Desktop carries every other environment's loopback traffic through the preview tunnel. */
67 +export const tunnelsEnvironmentLoopback = (target: ConnectionTarget | undefined): boolean =>
68 + isElectron && !(target !== undefined && reachesEnvironmentLoopback(target));
69 +
70 +const resolveLoopbackUrl = (
71 + environmentId: EnvironmentId,
72 + rawUrl: string,
73 + tunnelled: boolean,
74 +): string => {
75 try {
76 const normalizedUrl = normalizePreviewUrl(rawUrl);
77 const parsed = new URL(normalizedUrl);
70 - if (!isLoopbackHost(parsed.hostname)) return normalizedUrl;
78 + if (tunnelled || !isLoopbackHost(parsed.hostname)) return normalizedUrl;
79 const target = readPreparedConnection(environmentId)?.target;
80 if (target && reachesEnvironmentLoopback(target)) return normalizedUrl;
81 return resolveEnvironmentPortTarget(
@@ -85,4 +93,12 @@ export function resolveDiscoveredServerUrl(environmentId: EnvironmentId, rawUrl:
93 } catch {
94 return rawUrl;
95 }
88 -}
96 +};
97 +
98 +/** The URL an in-app tab loads. A desktop webview keeps localhost; its partition reaches the environment. */
99 +export const resolveDiscoveredServerUrl = (environmentId: EnvironmentId, rawUrl: string): string =>
100 + resolveLoopbackUrl(environmentId, rawUrl, isElectron);
101 +
102 +/** The URL for the system browser, which has no tunnel and needs an address it can reach itself. */
103 +export const resolveExternalServerUrl = (environmentId: EnvironmentId, rawUrl: string): string =>
104 + resolveLoopbackUrl(environmentId, rawUrl, false);
apps/web/src/browser/previewWebviewConfigState.ts
+16 -3
@@ -9,6 +9,9 @@ import * as Schema from "effect/Schema";
9 import { AsyncResult, Atom } from "effect/reactivity";
10
11 import { previewBridge } from "~/components/preview/previewBridge";
12 +import { environmentCatalog } from "~/connection/catalog";
13 +
14 +import { tunnelsEnvironmentLoopback } from "./browserTargetResolver";
15
16 const PREVIEW_CONFIG_STALE_TIME_MS = 5 * 60_000;
17 const PREVIEW_CONFIG_IDLE_TTL_MS = 10 * 60_000;
@@ -44,7 +47,8 @@ type PreviewConfigBridge = Pick<DesktopPreviewBridge, "getPreviewConfig">;
47
48 const loadPreviewWebviewConfig = (
49 environmentId: EnvironmentId,
47 - profileId?: string,
50 + profileId: string | undefined,
51 + tunnelLoopback: boolean,
52 bridge: PreviewConfigBridge | null = previewBridge,
53 ): Effect.Effect<DesktopPreviewWebviewConfig, PreviewWebviewConfigError> => {
54 if (bridge === null) {
@@ -52,7 +56,7 @@ const loadPreviewWebviewConfig = (
56 }
57
58 return Effect.tryPromise({
55 - try: () => bridge.getPreviewConfig(environmentId, profileId),
59 + try: () => bridge.getPreviewConfig(environmentId, profileId, tunnelLoopback),
60 catch: (cause) => new PreviewWebviewConfigLoadError({ environmentId, cause }),
61 });
62 };
@@ -75,7 +79,16 @@ const parseConfigKey = (key: string): { environmentId: EnvironmentId; profileId?
79
80 const previewWebviewConfigAtom = Atom.family((key: string) => {
81 const { environmentId, profileId } = parseConfigKey(key);
78 - return Atom.make(loadPreviewWebviewConfig(environmentId, profileId)).pipe(
82 + // The catalog knows the target before the environment connects, and a change re-routes the partition.
83 + return Atom.make((get) =>
84 + loadPreviewWebviewConfig(
85 + environmentId,
86 + profileId,
87 + tunnelsEnvironmentLoopback(
88 + get(environmentCatalog.catalogValueAtom).entries.get(environmentId)?.target,
89 + ),
90 + ),
91 + ).pipe(
92 Atom.swr({
93 staleTime: PREVIEW_CONFIG_STALE_TIME_MS,
94 revalidateOnMount: true,
apps/web/src/components/chat/ThreadServersPanel.tsx
+2 -2
@@ -16,7 +16,7 @@ import { m } from "~/i18n/messages";
16 import { GlobeIcon, SquareIcon, ChevronDownIcon, ChevronUpIcon } from "lucide-react";
17 import { type MouseEvent, useState } from "react";
18
19 -import { resolveDiscoveredServerUrl } from "../../browser/browserTargetResolver";
19 +import { resolveExternalServerUrl } from "../../browser/browserTargetResolver";
20 import { readLocalApi } from "../../localApi";
21 import { cn, isMacPlatform } from "../../lib/utils";
22 import { useThreadDiscoveredPorts } from "../../portDiscoveryState";
@@ -83,7 +83,7 @@ function ThreadServersList(props: ThreadServersPanelProps) {
83 // Like links: modified and middle clicks go to the system browser.
84 if (event.metaKey || event.ctrlKey || event.button === 1) {
85 event.preventDefault();
86 - const url = resolveDiscoveredServerUrl(props.environmentId, server.url);
86 + const url = resolveExternalServerUrl(props.environmentId, server.url);
87 await readLocalApi()
88 ?.shell.openExternal(url)
89 .catch((error: unknown) => reportFailure(gt("Unable to open in browser"), error));
apps/web/src/components/preview/PreviewView.tsx
+7 -2
@@ -46,7 +46,10 @@ import {
46 updatePreviewServerSnapshot,
47 useThreadPreviewState,
48 } from "~/previewStateStore";
49 -import { resolveDiscoveredServerUrl } from "~/browser/browserTargetResolver";
49 +import {
50 + resolveDiscoveredServerUrl,
51 + resolveExternalServerUrl,
52 +} from "~/browser/browserTargetResolver";
53 import { useEnvironmentSupportsServerBrowser } from "~/state/entities";
54 import {
55 useEnvironment,
@@ -451,7 +454,9 @@ export function PreviewView({
454
455 const handleOpenInBrowser = () => {
456 if (!localApi || !url) return;
454 - void localApi.shell.openExternal(url).catch(() => undefined);
457 + // A desktop tab's localhost is the environment's; the system browser needs its own route there.
458 + const externalUrl = isServerTab ? url : resolveExternalServerUrl(threadRef.environmentId, url);
459 + void localApi.shell.openExternal(externalUrl).catch(() => undefined);
460 };
461
462 const moveTarget = alternatePreviewRuntime(
apps/web/src/components/preview/previewConstants.ts
+2
@@ -6,6 +6,8 @@ export const PREVIEW_ERROR_CODE_MESSAGES: Readonly<Record<string, string>> = Obj
6 ERR_NAME_NOT_RESOLVED: msg("DNS address could not be found"),
7 ERR_NAME_RESOLUTION_FAILED: msg("DNS address could not be found"),
8 ERR_CONNECTION_REFUSED: msg("Connection refused"),
9 + // Another environment's localhost tab, when its tunnel or the port on that machine is unreachable.
10 + ERR_SOCKS_CONNECTION_FAILED: msg("Could not reach this port on the environment"),
11 ERR_CONNECTION_RESET: msg("Connection was reset"),
12 ERR_CONNECTION_CLOSED: msg("Connection was closed"),
13 ERR_CONNECTION_TIMED_OUT: msg("Connection timed out"),
apps/web/src/i18n/translations/de.json
+1
@@ -1,4 +1,5 @@
1 {
2 + "4052bd9a2478988d": "Could not reach this port on the environment",
3 "23be753133ae6950": "Thread",
4 "0001ae5846061bb6": "Thread auf {machine}",
5 "eef7f4dacbc3c3f2": "Rechner",
apps/web/src/i18n/translations/en.json
+1
@@ -1,4 +1,5 @@
1 {
2 + "4052bd9a2478988d": "Could not reach this port on the environment",
3 "23be753133ae6950": "Thread",
4 "0001ae5846061bb6": "Thread on {machine}",
5 "eef7f4dacbc3c3f2": "Machine",
apps/web/src/i18n/translations/es.json
+1
@@ -1,4 +1,5 @@
1 {
2 + "4052bd9a2478988d": "Could not reach this port on the environment",
3 "23be753133ae6950": "Hilo",
4 "0001ae5846061bb6": "Hilo en {machine}",
5 "eef7f4dacbc3c3f2": "Máquina",
apps/web/src/i18n/translations/fr.json
+1
@@ -1,4 +1,5 @@
1 {
2 + "4052bd9a2478988d": "Could not reach this port on the environment",
3 "23be753133ae6950": "Fil",
4 "0001ae5846061bb6": "Fil sur {machine}",
5 "eef7f4dacbc3c3f2": "Machine",
apps/web/src/i18n/translations/ja.json
+1
@@ -1,4 +1,5 @@
1 {
2 + "4052bd9a2478988d": "Could not reach this port on the environment",
3 "23be753133ae6950": "スレッド",
4 "0001ae5846061bb6": "{machine} 上のスレッド",
5 "eef7f4dacbc3c3f2": "マシン",
apps/web/src/i18n/translations/ko.json
+1
@@ -1,4 +1,5 @@
1 {
2 + "4052bd9a2478988d": "Could not reach this port on the environment",
3 "23be753133ae6950": "스레드",
4 "0001ae5846061bb6": "{machine}의 스레드",
5 "eef7f4dacbc3c3f2": "머신",
apps/web/src/i18n/translations/pt-BR.json
+1
@@ -1,4 +1,5 @@
1 {
2 + "4052bd9a2478988d": "Could not reach this port on the environment",
3 "23be753133ae6950": "Thread",
4 "0001ae5846061bb6": "Thread em {machine}",
5 "eef7f4dacbc3c3f2": "Máquina",
apps/web/src/i18n/translations/ru.json
+1
@@ -1,4 +1,5 @@
1 {
2 + "4052bd9a2478988d": "Could not reach this port on the environment",
3 "23be753133ae6950": "Тред",
4 "0001ae5846061bb6": "Тред на {machine}",
5 "eef7f4dacbc3c3f2": "Машина",
apps/web/src/i18n/translations/sv.json
+1
@@ -1,4 +1,5 @@
1 {
2 + "4052bd9a2478988d": "Could not reach this port on the environment",
3 "23be753133ae6950": "Tråd",
4 "0001ae5846061bb6": "Tråd på {machine}",
5 "eef7f4dacbc3c3f2": "Dator",
apps/web/src/i18n/translations/zh.json
+1
@@ -1,4 +1,5 @@
1 {
2 + "4052bd9a2478988d": "Could not reach this port on the environment",
3 "23be753133ae6950": "会话",
4 "0001ae5846061bb6": "{machine} 上的会话",
5 "eef7f4dacbc3c3f2": "机器",
apps/web/src/state/previewTunnel.ts new
+58
@@ -0,0 +1,58 @@
1 +import { environmentEndpointUrl } from "@t3tools/client-runtime/environment";
2 +import { mintMediaTicket } from "@t3tools/client-runtime/state/deviceHubAccess";
3 +import type { EnvironmentId } from "@t3tools/contracts";
4 +import * as DateTime from "effect/DateTime";
5 +import * as Effect from "effect/Effect";
6 +import * as Option from "effect/Option";
7 +import * as Redacted from "effect/Redacted";
8 +import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
9 +
10 +import { connectionAtomRuntime } from "../connection/runtime";
11 +import { appAtomRegistry } from "../rpc/atomRegistry";
12 +import { environmentSession } from "./session";
13 +
14 +const PREVIEW_TUNNEL_PATH = "/api/preview/tunnel";
15 +const TICKET_REFRESH_MARGIN_MS = 30_000;
16 +
17 +// Reading the prepared connection here re-mints for the route in use after a route switch.
18 +const previewTunnelAccessAtom = Atom.family((environmentId: EnvironmentId) =>
19 + connectionAtomRuntime
20 + .atom((get) => {
21 + const prepared = Option.getOrNull(
22 + get(environmentSession.preparedConnectionValueAtom(environmentId)),
23 + );
24 + // Desktop main cannot send this window's cookies, so only ticketed connections tunnel.
25 + if (prepared === null || prepared.httpAuthorization === null) return Effect.succeed(null);
26 + return mintMediaTicket(prepared).pipe(
27 + Effect.map((ticket) => {
28 + const url = new URL(
29 + environmentEndpointUrl(prepared.httpBaseUrl, PREVIEW_TUNNEL_PATH).replace(
30 + /^http/,
31 + "ws",
32 + ),
33 + );
34 + url.searchParams.set("wsTicket", Redacted.value(ticket.ticket));
35 + return { url: url.toString(), expiresAtMillis: DateTime.toEpochMillis(ticket.expiresAt) };
36 + }),
37 + );
38 + })
39 + .pipe(Atom.setIdleTTL(60_000), Atom.withLabel(`preview-tunnel-access:${environmentId}`)),
40 +);
41 +
42 +/** The environment's tunnel WebSocket URL with a live media ticket, or null when unreachable. */
43 +export function readPreviewTunnelUrl(environmentId: EnvironmentId): Promise<string | null> {
44 + const atom = previewTunnelAccessAtom(environmentId);
45 + const current = appAtomRegistry.get(atom);
46 + const reusable =
47 + AsyncResult.isSuccess(current) &&
48 + current.value !== null &&
49 + current.value.expiresAtMillis - Date.now() > TICKET_REFRESH_MARGIN_MS;
50 + if (!reusable && !current.waiting) appAtomRegistry.refresh(atom);
51 + return Effect.runPromise(
52 + AtomRegistry.getResult(appAtomRegistry, atom, { suspendOnWaiting: true }).pipe(
53 + Effect.map((access) => access?.url ?? null),
54 + Effect.timeout("10 seconds"),
55 + Effect.orElseSucceed(() => null),
56 + ),
57 + );
58 +}
docs/internals/remote.md
+24
@@ -158,6 +158,30 @@ of requests to the hosted origin. The browser exchanges the secret with the
158 environment and strips it from its history. Moving the token into a query
159 parameter would disclose it to the wrong origin.
160
161 +## Desktop previews tunnel loopback
162 +
163 +A desktop webview for another environment keeps `localhost` URLs and reaches the environment's
164 +loopback through `/api/preview/tunnel`, one WebSocket per TCP connection, on the same origin as
165 +every other request. That is why it works over any connection method. Four choices are easy to
166 +undo by accident:
167 +
168 +- **Fixed proxy, not PAC.** Chromium never consults a PAC script for loopback hosts, even with
169 + `<-loopback>`. The partition uses a fixed SOCKS5 proxy with the bypass list
170 + `*,<-loopback>,169.254.0.0/16,fe80::/10`, in that order, since the last matching rule wins:
171 + everything is direct except loopback. `<-loopback>` also takes link-local addresses, so the last
172 + two rules hand them back to the direct route. A fixed proxy also has no
173 + direct retry, so a failed tunnel is a connection error and never the reviewer's own localhost.
174 + The rule matches hostnames, not resolved addresses, so a custom name that resolves to loopback
175 + still goes direct.
176 +- **Media tickets.** Desktop main opens the tunnel but holds no environment credentials. Media
177 + tickets are not DPoP-bound, so the renderer can hand one over. Main asks it for a tunnel URL per
178 + connection, which also makes the tunnel follow a route switch.
179 +- **Owner check, not auth.** Chromium can't authenticate to a SOCKS proxy, so any local process
180 + can connect to the listener and ride this user's tunnel. On Linux the listener looks the client
181 + up in `/proc/net/tcp` and refuses other users. macOS and Windows have no such check yet.
182 +- **System browser links** have no tunnel. They keep the private-network rewrite in
183 + [`browserTargetResolver.ts`](../../apps/web/src/browser/browserTargetResolver.ts).
184 +
185 ## Access and process ownership are different
186
187 Tailscale supplies an endpoint for ordinary pairing, so it needs no separate
docs/user/remote-access.md
+11
@@ -280,6 +280,17 @@ directly. Every other device, and the desktop app for other environments,
280 streams them from the host. Agents keep using them while no device is
281 connected, and `localhost` addresses reach servers on the host.
282
283 +A tab you open yourself in the desktop app for another environment loads on
284 +your computer instead, so the element picker, screenshots, and annotations work
285 +as they do locally. Its `localhost` addresses still reach servers on the host,
286 +over the connection the app already has, whichever way you connected. If the
287 +host cannot be reached, the tab shows a connection error; a `localhost`,
288 +`127.0.0.1`, or `[::1]` address never opens a server on your own computer.
289 +Other names that point at your computer, such as `/etc/hosts` entries, still
290 +do. These tabs ignore your system proxy settings, so they can't reach a host
291 +you connect to only through a proxy or over HTTPS with a privately issued
292 +certificate. The web and mobile apps keep streaming.
293 +
294 The first tab downloads a headless Chrome, about 120 MB, into the T3 home. It
295 is the same browser [HTML renders](html-renders.md) use, so a host downloads it
296 only once. Some Linux hosts need [setup](#browser-host-setup) before it can
packages/client-runtime/src/state/deviceHubAccess.ts
+22 -15
@@ -20,6 +20,27 @@ export { type DeviceHubAccess, withDeviceHubQuery } from "../device/hubAccess.ts
20
21 const TICKET_TIMEOUT_MS = 8_000;
22
23 +/** Reusable across media requests until it expires; only for connections that send credentials. */
24 +export const mintMediaTicket = Effect.fn("clientRuntime.state.mintMediaTicket")(function* (
25 + prepared: PreparedConnection,
26 +) {
27 + const signer = yield* Effect.serviceOption(ManagedRelay.ManagedRelayDpopSigner);
28 + const remoteAuthorization = yield* Effect.serviceOption(
29 + RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization,
30 + );
31 + return yield* executeAuthenticatedEnvironmentHttpRequest({
32 + prepared,
33 + signer,
34 + remoteAuthorization,
35 + group: "auth",
36 + method: "POST",
37 + url: (urls) => urls.webSocketTicketFor({ params: { use: "media" } }),
38 + timeoutMs: TICKET_TIMEOUT_MS,
39 + request: ({ client, headers }) =>
40 + client.webSocketTicketFor({ headers, params: { use: "media" } }),
41 + });
42 +});
43 +
44 export const resolveDeviceHubAccess = Effect.fn("clientRuntime.state.resolveDeviceHubAccess")(
45 function* (input: {
46 readonly prepared: PreparedConnection;
@@ -30,21 +51,7 @@ export const resolveDeviceHubAccess = Effect.fn("clientRuntime.state.resolveDevi
51 if (input.prepared.httpAuthorization === null) {
52 return { httpBase, wsBase, query: {}, credentials: true };
53 }
33 - const signer = yield* Effect.serviceOption(ManagedRelay.ManagedRelayDpopSigner);
34 - const remoteAuthorization = yield* Effect.serviceOption(
35 - RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization,
36 - );
37 - const ticket = yield* executeAuthenticatedEnvironmentHttpRequest({
38 - prepared: input.prepared,
39 - signer,
40 - remoteAuthorization,
41 - group: "auth",
42 - method: "POST",
43 - url: (urls) => urls.webSocketTicketFor({ params: { use: "media" } }),
44 - timeoutMs: TICKET_TIMEOUT_MS,
45 - request: ({ client, headers }) =>
46 - client.webSocketTicketFor({ headers, params: { use: "media" } }),
47 - });
54 + const ticket = yield* mintMediaTicket(input.prepared);
55 return {
56 httpBase,
57 wsBase,
packages/contracts/src/ipc.ts
+19
@@ -987,6 +987,19 @@ export const DesktopPreviewConfigInputSchema = Schema.Struct({
987 environmentId: EnvironmentId,
988 /** Main must derive the partition to ensure its session has UA rewrites and permission handlers. */
989 profileId: Schema.optional(BrowserProfileId),
990 + /** Carry the partition's loopback traffic to the environment instead of this machine. */
991 + tunnelLoopback: Schema.optional(Schema.Boolean),
992 +});
993 +
994 +export interface DesktopPreviewTunnelAccessRequest {
995 + readonly requestId: string;
996 + readonly environmentId: EnvironmentId;
997 +}
998 +
999 +export const DesktopPreviewTunnelAccessResolutionInputSchema = Schema.Struct({
1000 + requestId: Schema.String,
1001 + /** The environment's tunnel WebSocket URL with its ticket, or null when it cannot be reached. */
1002 + url: Schema.NullOr(Schema.String),
1003 });
1004
1005 export const DesktopPreviewClearDataInputSchema = Schema.Struct({
@@ -1304,7 +1317,13 @@ export interface DesktopPreviewBridge {
1317 getPreviewConfig: (
1318 environmentId: EnvironmentId,
1319 profileId?: string,
1320 + tunnelLoopback?: boolean,
1321 ) => Promise<DesktopPreviewWebviewConfig>;
1322 + /** Main asks for an environment's tunnel URL once per connection a tunnelled page opens. */
1323 + onTunnelAccessRequest: (
1324 + listener: (request: DesktopPreviewTunnelAccessRequest) => void,
1325 + ) => () => void;
1326 + resolveTunnelAccess: (requestId: string, url: string | null) => Promise<void>;
1327 listBrowserImportSources: () => Promise<ReadonlyArray<BrowserImportSource>>;
1328 importBrowserCookies: (input: {
1329 readonly environmentId: EnvironmentId;