The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 04:45 UTC
| 1 | // Carries a remote desktop's preview traffic to this machine's loopback ports, one TCP |
| 2 | // connection per WebSocket. Raw bytes, so pages keep their own origin, HMR sockets and TLS. |
| 3 | import * as NodeHttpServerRequest from "@effect/platform-node/NodeHttpServerRequest"; |
| 4 | import * as NodeSocket from "@effect/platform-node/NodeSocket"; |
| 5 | import { allowsPreviewTunnel, AuthTerminalOperateScope } from "@t3tools/contracts"; |
| 6 | import type * as NodeNet from "node:net"; |
| 7 | import * as Context from "effect/Context"; |
| 8 | import * as Effect from "effect/Effect"; |
| 9 | import * as Layer from "effect/Layer"; |
| 10 | import * as Option from "effect/Option"; |
| 11 | import * as Schema from "effect/Schema"; |
| 12 | import type * as Scope from "effect/Scope"; |
| 13 | import * as Stream from "effect/Stream"; |
| 14 | import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/http"; |
| 15 | import type * as Socket from "effect/socket/Socket"; |
| 16 | |
| 17 | import { authenticateMediaRequest } from "../auth/http.ts"; |
| 18 | import * as SessionStore from "../auth/SessionStore.ts"; |
| 19 | import { requestUrl } from "../requestUrl.ts"; |
| 20 | import { ServerSettingsService } from "../serverSettings.ts"; |
| 21 | |
| 22 | const PREVIEW_TUNNEL_ROUTE = "/api/preview/tunnel"; |
| 23 | /** |
| 24 | * Marks a refusal about the port itself, so a client can tell "nothing listens there" from a proxy |
| 25 | * in front of the environment answering 502 because the environment is down. |
| 26 | */ |
| 27 | export const PREVIEW_TUNNEL_PORT_REFUSED_HEADER = "x-t3-tunnel-port-refused"; |
| 28 | /** Marks a refusal because the tunnel is switched off here, by the setting or by policy. */ |
| 29 | export const PREVIEW_TUNNEL_DISABLED_HEADER = "x-t3-tunnel-disabled"; |
| 30 | |
| 31 | const CONNECT_TIMEOUT = "5 seconds"; |
| 32 | |
| 33 | export class PreviewTunnelPortRefusedError extends Schema.TaggedError<PreviewTunnelPortRefusedError>()( |
| 34 | "PreviewTunnelPortRefusedError", |
| 35 | { port: Schema.Number }, |
| 36 | ) { |
| 37 | override get message(): string { |
| 38 | return `Port ${this.port} is this T3 Code server's own port.`; |
| 39 | } |
| 40 | } |
| 41 | |
| 42 | export class PreviewTunnelDisabledError extends Schema.TaggedError<PreviewTunnelDisabledError>()( |
| 43 | "PreviewTunnelDisabledError", |
| 44 | {}, |
| 45 | ) { |
| 46 | override get message(): string { |
| 47 | return "The preview tunnel is turned off on this T3 Code server."; |
| 48 | } |
| 49 | } |
| 50 | |
| 51 | export class PreviewTunnelConnectError extends Schema.TaggedError<PreviewTunnelConnectError>()( |
| 52 | "PreviewTunnelConnectError", |
| 53 | { port: Schema.Number, cause: Schema.Defect() }, |
| 54 | ) { |
| 55 | override get message(): string { |
| 56 | return `Nothing accepted a connection on loopback port ${this.port}.`; |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | export class PreviewTunnel extends Context.Service< |
| 61 | PreviewTunnel, |
| 62 | { |
| 63 | /** Connects to a loopback port. `servedPort` is the port the request arrived on. */ |
| 64 | readonly connect: (input: { |
| 65 | readonly port: number; |
| 66 | readonly servedPort: number | undefined; |
| 67 | }) => Effect.Effect< |
| 68 | { readonly reader: Socket.Reader; readonly writer: Socket.Writer }, |
| 69 | PreviewTunnelDisabledError | PreviewTunnelPortRefusedError | PreviewTunnelConnectError, |
| 70 | Scope.Scope |
| 71 | >; |
| 72 | /** |
| 73 | * Subscribes now, before `connect` reads the setting, so a switch-off during dialling isn't |
| 74 | * missed. The returned effect completes once the tunnel is switched off. |
| 75 | */ |
| 76 | readonly watchTurnedOff: Effect.Effect<Effect.Effect<void>, never, Scope.Scope>; |
| 77 | } |
| 78 | >()("t3/preview/PreviewTunnel") {} |
| 79 | |
| 80 | const make = Effect.gen(function* () { |
| 81 | const serverSettings = yield* ServerSettingsService; |
| 82 | const managedPolicy = serverSettings.managedPolicy; |
| 83 | const allowedBy = (settings: { readonly enablePreviewTunnel: boolean }) => |
| 84 | allowsPreviewTunnel({ settings, managedPolicy }); |
| 85 | // Unreadable settings fail closed: the tunnel is raw TCP into the host. |
| 86 | const enabled = serverSettings.getSettings.pipe( |
| 87 | Effect.map(allowedBy), |
| 88 | Effect.orElseSucceed(() => false), |
| 89 | ); |
| 90 | const watchTurnedOff = serverSettings.subscribeChanges.pipe( |
| 91 | Effect.map((changes) => |
| 92 | changes.pipe( |
| 93 | Stream.filter((settings) => !allowedBy(settings)), |
| 94 | Stream.runHead, |
| 95 | // A change stream that ends without switching the tunnel off never does. |
| 96 | Effect.flatMap((change) => (Option.isSome(change) ? Effect.void : Effect.never)), |
| 97 | ), |
| 98 | ), |
| 99 | ); |
| 100 | |
| 101 | const dial = Effect.fnUntraced(function* (host: string, port: number) { |
| 102 | const socket = yield* NodeSocket.makeNet({ host, port, openTimeout: CONNECT_TIMEOUT }); |
| 103 | return { reader: yield* socket.reader, writer: yield* socket.writer }; |
| 104 | }); |
| 105 | |
| 106 | const connect: PreviewTunnel["Service"]["connect"] = Effect.fn("PreviewTunnel.connect")( |
| 107 | function* ({ port, servedPort }) { |
| 108 | yield* Effect.annotateCurrentSpan({ port }); |
| 109 | if (!(yield* enabled)) return yield* new PreviewTunnelDisabledError(); |
| 110 | // Tunnelling to this server would hand the page an unauthenticated loopback client. |
| 111 | if (port === servedPort) { |
| 112 | return yield* new PreviewTunnelPortRefusedError({ port }); |
| 113 | } |
| 114 | return yield* dial("127.0.0.1", port).pipe( |
| 115 | Effect.catch(() => dial("::1", port)), |
| 116 | Effect.mapError((cause) => new PreviewTunnelConnectError({ port, cause })), |
| 117 | ); |
| 118 | }, |
| 119 | ); |
| 120 | |
| 121 | return PreviewTunnel.of({ connect, watchTurnedOff }); |
| 122 | }); |
| 123 | |
| 124 | export const layer = Layer.effect(PreviewTunnel, make); |
| 125 | |
| 126 | const SEND_HIGH_WATER_BYTES = 1024 * 1024; |
| 127 | |
| 128 | // Effect's WebSocket writer never waits for its send buffer, so a slow client would queue a |
| 129 | // whole response in memory. `ws` writes its frames to the upgraded TCP socket; wait on that. |
| 130 | const drained = (connection: NodeNet.Socket) => |
| 131 | Effect.callback<void>((resume) => { |
| 132 | if (connection.writableLength <= SEND_HIGH_WATER_BYTES || connection.destroyed) { |
| 133 | return resume(Effect.void); |
| 134 | } |
| 135 | const stopWaiting = () => connection.off("drain", done).off("close", done); |
| 136 | const done = () => { |
| 137 | stopWaiting(); |
| 138 | resume(Effect.void); |
| 139 | }; |
| 140 | connection.on("drain", done).on("close", done); |
| 141 | return Effect.sync(stopWaiting); |
| 142 | }); |
| 143 | |
| 144 | const pump = |
| 145 | /* Runs for the life of the connection; a span per direction adds no diagnostic value. */ |
| 146 | Effect.fnUntraced(function* ( |
| 147 | reader: Socket.Reader, |
| 148 | writer: Socket.Writer, |
| 149 | backpressure: Effect.Effect<void> = Effect.void, |
| 150 | ) { |
| 151 | while (true) { |
| 152 | yield* writer.writeAll(yield* reader.pull); |
| 153 | yield* backpressure; |
| 154 | } |
| 155 | }); |
| 156 | |
| 157 | const handler = Effect.gen(function* () { |
| 158 | const request = yield* HttpServerRequest.HttpServerRequest; |
| 159 | const url = requestUrl(request); |
| 160 | const port = Number(Option.getOrUndefined(url)?.searchParams.get("port") ?? Number.NaN); |
| 161 | if ( |
| 162 | request.headers.upgrade?.toLowerCase() !== "websocket" || |
| 163 | !Number.isInteger(port) || |
| 164 | port < 1 || |
| 165 | port > 65_535 |
| 166 | ) { |
| 167 | return HttpServerResponse.text("Bad Request", { status: 400 }); |
| 168 | } |
| 169 | const session = yield* authenticateMediaRequest(AuthTerminalOperateScope); |
| 170 | const sessions = yield* SessionStore.SessionStore; |
| 171 | const tunnel = yield* PreviewTunnel; |
| 172 | const connection = NodeHttpServerRequest.toIncomingMessage(request).socket; |
| 173 | const servedPort = connection.localPort; |
| 174 | return yield* Effect.gen(function* () { |
| 175 | const turnedOff = yield* tunnel.watchTurnedOff; |
| 176 | // Dialled before the upgrade so a dead port fails the handshake instead of an open socket. |
| 177 | const upstream = yield* tunnel.connect({ port, servedPort }); |
| 178 | const client = yield* request.upgrade; |
| 179 | const clientReader = yield* client.reader; |
| 180 | const clientWriter = yield* client.writer; |
| 181 | // A tunnel is raw TCP into the host, so it closes with its session like the RPC socket. |
| 182 | // So does switching the tunnel off. |
| 183 | yield* Effect.raceFirst( |
| 184 | Effect.raceFirst( |
| 185 | pump(upstream.reader, clientWriter, drained(connection)), |
| 186 | pump(clientReader, upstream.writer), |
| 187 | ), |
| 188 | Effect.raceFirst( |
| 189 | sessions.awaitInvalidation(session.sessionId, session.proofKeyThumbprint), |
| 190 | turnedOff, |
| 191 | ), |
| 192 | ).pipe(Effect.ignoreCause); |
| 193 | return HttpServerResponse.empty(); |
| 194 | }).pipe( |
| 195 | Effect.scoped, |
| 196 | Effect.catchTags({ |
| 197 | PreviewTunnelDisabledError: (error) => |
| 198 | Effect.succeed( |
| 199 | HttpServerResponse.text(error.message, { status: 403, headers: DISABLED_HEADERS }), |
| 200 | ), |
| 201 | PreviewTunnelPortRefusedError: (error) => |
| 202 | Effect.succeed( |
| 203 | HttpServerResponse.text(error.message, { status: 403, headers: PORT_REFUSED_HEADERS }), |
| 204 | ), |
| 205 | // Not 502: Cloudflare, in front of T3 Connect, swaps an origin 502 for its own page. |
| 206 | PreviewTunnelConnectError: (error) => |
| 207 | Effect.succeed( |
| 208 | HttpServerResponse.text(error.message, { status: 403, headers: PORT_REFUSED_HEADERS }), |
| 209 | ), |
| 210 | }), |
| 211 | ); |
| 212 | }); |
| 213 | |
| 214 | const PORT_REFUSED_HEADERS = { [PREVIEW_TUNNEL_PORT_REFUSED_HEADER]: "1" }; |
| 215 | const DISABLED_HEADERS = { [PREVIEW_TUNNEL_DISABLED_HEADER]: "1" }; |
| 216 | |
| 217 | export const routeLayer = HttpRouter.add("GET", PREVIEW_TUNNEL_ROUTE, handler); |