The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { requestUrl } from "../requestUrl.ts"; |
| 2 | // Loopback-only hubs expose shell execution or unauthenticated actions. |
| 3 | // Proxy with environment read scope for streams and operate scope for input and tuning. |
| 4 | import { AuthOrchestrationReadScope, AuthOrchestrationOperateScope } from "@t3tools/contracts"; |
| 5 | import * as Effect from "effect/Effect"; |
| 6 | import * as Layer from "effect/Layer"; |
| 7 | import * as Option from "effect/Option"; |
| 8 | import * as Stream from "effect/Stream"; |
| 9 | import { |
| 10 | HttpClient, |
| 11 | HttpClientRequest, |
| 12 | HttpMethod, |
| 13 | HttpRouter, |
| 14 | HttpServerRequest, |
| 15 | HttpServerResponse, |
| 16 | } from "effect/http"; |
| 17 | import * as Socket from "effect/socket/Socket"; |
| 18 | import * as NodeHttpServerRequest from "@effect/platform-node/NodeHttpServerRequest"; |
| 19 | import * as NodeSocket from "@effect/platform-node/NodeSocket"; |
| 20 | |
| 21 | import { authenticateMediaRequest, failEnvironmentInternal } from "../auth/http.ts"; |
| 22 | import * as SessionStore from "../auth/SessionStore.ts"; |
| 23 | import * as DeviceService from "./DeviceService.ts"; |
| 24 | import { repeatStillFrame } from "./mjpegStillFrame.ts"; |
| 25 | |
| 26 | const ALLOWED_PATHS: ReadonlyArray<RegExp> = [ |
| 27 | /^\/api\/devices$/, |
| 28 | /^\/vendor\/serve-sim\/api$/, |
| 29 | /^\/vendor\/serve-sim\/api\/screenshot$/, |
| 30 | /^\/vendor\/serve-sim\/api\/event-log(\/events)?$/, |
| 31 | /^\/vendor\/serve-sim\/helper\/[^/]+\/(stream\.mjpeg|stream\.avcc|config|health|ax|foreground)$/, |
| 32 | /^\/vendor\/serve-sim\/helper\/[^/]+\/panel\/(1|3)\/stream\.avcc$/, |
| 33 | /^\/vendor\/serve-sim\/helper\/[^/]+\/webrtc\/(offer|close)$/, |
| 34 | /^\/vendor\/serve-sim\/appstate$/, |
| 35 | /^\/vendor\/serve-emu\/api$/, |
| 36 | /^\/vendor\/serve-emu\/api\/(devices|screenshot|stream-mode|stream-settings|accessibility|fold)$/, |
| 37 | /^\/vendor\/serve-emu\/health$/, |
| 38 | ]; |
| 39 | |
| 40 | // Paths that take methods besides GET; one missing from ALLOWED_PATHS takes no GET. |
| 41 | const MUTABLE_PATHS: ReadonlyArray<RegExp> = [ |
| 42 | /^\/vendor\/serve-sim\/api\/screenshot$/, |
| 43 | // WebRTC signalling: opening and closing a view of the stream, so read scope. |
| 44 | /^\/vendor\/serve-sim\/helper\/[^/]+\/webrtc\/(offer|close)$/, |
| 45 | /^\/vendor\/serve-emu\/webrtc\/(offer|close)$/, |
| 46 | /^\/vendor\/serve-emu\/api\/(screenshot|stream-mode|stream-settings)$/, |
| 47 | /^\/vendor\/serve-emu\/api\/fold$/, |
| 48 | ]; |
| 49 | |
| 50 | const ALLOWED_WS_PATHS: ReadonlyArray<RegExp> = [ |
| 51 | /^\/api\/devices\/ws$/, |
| 52 | /^\/vendor\/serve-sim\/helper\/ws$/, |
| 53 | /^\/vendor\/serve-emu\/ws$/, |
| 54 | ]; |
| 55 | |
| 56 | const DROPPED_REQUEST_HEADERS = new Set([ |
| 57 | "host", |
| 58 | "connection", |
| 59 | "upgrade", |
| 60 | "sec-websocket-key", |
| 61 | "sec-websocket-version", |
| 62 | "sec-websocket-extensions", |
| 63 | "sec-websocket-protocol", |
| 64 | "cookie", |
| 65 | "authorization", |
| 66 | "dpop", |
| 67 | "content-length", |
| 68 | "accept-encoding", |
| 69 | // The client's HTTPS hop makes the hub reject our loopback Origin over T3 Connect. |
| 70 | "x-forwarded-proto", |
| 71 | ]); |
| 72 | |
| 73 | const isWebSocketUpgrade = (request: HttpServerRequest.HttpServerRequest) => |
| 74 | request.headers.upgrade?.toLowerCase() === "websocket"; |
| 75 | |
| 76 | const forwardHeaders = (request: HttpServerRequest.HttpServerRequest, origin: string) => { |
| 77 | const headers: Record<string, string> = {}; |
| 78 | for (const [name, value] of Object.entries(request.headers)) { |
| 79 | if (DROPPED_REQUEST_HEADERS.has(name) || value === undefined) continue; |
| 80 | headers[name] = value; |
| 81 | } |
| 82 | // serve-emu refuses mutations whose Origin differs from the request origin. |
| 83 | if (request.headers.origin !== undefined) headers.origin = origin; |
| 84 | return headers; |
| 85 | }; |
| 86 | |
| 87 | // Effect drops its listeners before closing a socket that is still connecting, and `ws` then |
| 88 | // emits an `error` nobody handles, which exits the server. |
| 89 | export const upstreamWebSocketConstructor = Layer.effect( |
| 90 | Socket.WebSocketConstructor, |
| 91 | Effect.gen(function* () { |
| 92 | const make = yield* Socket.WebSocketConstructor; |
| 93 | return (url, options) => { |
| 94 | const socket = make(url, options); |
| 95 | socket.addEventListener("error", () => undefined); |
| 96 | return socket; |
| 97 | }; |
| 98 | }), |
| 99 | ).pipe(Layer.provide(NodeSocket.layerWebSocketConstructor)); |
| 100 | |
| 101 | const proxyWebSocket = Effect.fn("DeviceHubProxy.proxyWebSocket")(function* ( |
| 102 | request: HttpServerRequest.HttpServerRequest, |
| 103 | upstreamUrl: string, |
| 104 | protocols: ReadonlyArray<string> = [], |
| 105 | headers: Readonly<Record<string, string>> = {}, |
| 106 | ) { |
| 107 | const transport = NodeHttpServerRequest.toIncomingMessage(request).socket; |
| 108 | const client = yield* request.upgrade; |
| 109 | const upstream = yield* Socket.makeWebSocket(upstreamUrl, { |
| 110 | openTimeout: "10 seconds", |
| 111 | ...(protocols.length > 0 ? { protocols: [...protocols] } : {}), |
| 112 | ...(Object.keys(headers).length > 0 ? { headers: { ...headers } } : {}), |
| 113 | }).pipe(Effect.provide(upstreamWebSocketConstructor)); |
| 114 | yield* Effect.scoped( |
| 115 | Effect.gen(function* () { |
| 116 | const writeToClient = yield* client.writer; |
| 117 | const writeToUpstream = yield* upstream.writer; |
| 118 | return yield* Effect.raceFirst( |
| 119 | pumpFrames(upstream, writeToClient), |
| 120 | pumpFrames(client, writeToUpstream), |
| 121 | ); |
| 122 | }), |
| 123 | ).pipe( |
| 124 | Effect.onInterrupt(() => Effect.sync(() => transport.destroy())), |
| 125 | Effect.ignoreCause, |
| 126 | ); |
| 127 | return HttpServerResponse.empty(); |
| 128 | }); |
| 129 | |
| 130 | const pumpFrames = |
| 131 | /* Frame pumping runs continuously; a span per frame stream adds no diagnostic value. */ |
| 132 | Effect.fnUntraced(function* (source: Socket.Socket, sink: Socket.Writer) { |
| 133 | const { pull } = yield* source.reader; |
| 134 | while (true) { |
| 135 | yield* sink.writeAll(yield* pull); |
| 136 | } |
| 137 | }); |
| 138 | |
| 139 | const proxyHttp = Effect.fn("DeviceHubProxy.proxyHttp")(function* ( |
| 140 | request: HttpServerRequest.HttpServerRequest, |
| 141 | upstreamUrl: string, |
| 142 | invalidated: Effect.Effect<void>, |
| 143 | extraHeaders: Readonly<Record<string, string>> = {}, |
| 144 | ) { |
| 145 | const httpClient = HttpClient.withScope(yield* HttpClient.HttpClient); |
| 146 | const method = request.method; |
| 147 | if (!HttpMethod.isHttpMethod(method)) { |
| 148 | return HttpServerResponse.text("Method Not Allowed", { status: 405 }); |
| 149 | } |
| 150 | const upstreamRequest = HttpClientRequest.make(method)(upstreamUrl).pipe( |
| 151 | HttpClientRequest.setHeaders({ |
| 152 | ...forwardHeaders(request, new URL(upstreamUrl).origin), |
| 153 | ...extraHeaders, |
| 154 | }), |
| 155 | method === "GET" || method === "HEAD" |
| 156 | ? (self) => self |
| 157 | : // A bare stream body is sent as octet-stream; serve-sim refuses WebRTC |
| 158 | // offers that are not application/json. |
| 159 | HttpClientRequest.bodyStream(request.stream, { |
| 160 | contentType: request.headers["content-type"], |
| 161 | }), |
| 162 | ); |
| 163 | const response = yield* httpClient.execute(upstreamRequest); |
| 164 | const headers: Record<string, string> = {}; |
| 165 | for (const [name, value] of Object.entries(response.headers)) { |
| 166 | // A cookie from an upstream such as an Expo Simulators session's preview host would land on T3's origin. |
| 167 | if ( |
| 168 | name === "content-encoding" || |
| 169 | name === "transfer-encoding" || |
| 170 | name === "connection" || |
| 171 | name === "set-cookie" |
| 172 | ) { |
| 173 | continue; |
| 174 | } |
| 175 | if (value !== undefined) headers[name] = value; |
| 176 | } |
| 177 | // Long-lived MJPEG and AVCC responses must not be buffered by compression. |
| 178 | headers["cache-control"] = "no-store, no-transform"; |
| 179 | const body = headers["content-type"]?.startsWith("multipart/x-mixed-replace") |
| 180 | ? repeatStillFrame(response.stream) |
| 181 | : response.stream; |
| 182 | return HttpServerResponse.stream(body.pipe(Stream.interruptWhen(invalidated)), { |
| 183 | status: response.status, |
| 184 | headers, |
| 185 | ...(headers["content-type"] ? { contentType: headers["content-type"] } : {}), |
| 186 | }); |
| 187 | }); |
| 188 | |
| 189 | const handler = Effect.gen(function* () { |
| 190 | const request = yield* HttpServerRequest.HttpServerRequest; |
| 191 | const url = requestUrl(request); |
| 192 | if (Option.isNone(url)) { |
| 193 | return HttpServerResponse.text("Bad Request", { status: 400 }); |
| 194 | } |
| 195 | const hubPath = url.value.pathname.slice(DeviceService.DEVICE_HUB_ROUTE_PREFIX.length) || "/"; |
| 196 | const upgrade = isWebSocketUpgrade(request); |
| 197 | const matches = (paths: ReadonlyArray<RegExp>) => paths.some((pattern) => pattern.test(hubPath)); |
| 198 | const allowed = upgrade |
| 199 | ? matches(ALLOWED_WS_PATHS) |
| 200 | : matches(ALLOWED_PATHS) || matches(MUTABLE_PATHS); |
| 201 | if (!allowed) { |
| 202 | return HttpServerResponse.text("Not Found", { status: 404 }); |
| 203 | } |
| 204 | const readOnly = request.method === "GET" || request.method === "HEAD"; |
| 205 | if (!upgrade && !matches(readOnly ? ALLOWED_PATHS : MUTABLE_PATHS)) { |
| 206 | return HttpServerResponse.text("Method Not Allowed", { status: 405 }); |
| 207 | } |
| 208 | const controlsDevice = |
| 209 | (upgrade && hubPath !== "/api/devices/ws") || |
| 210 | (!readOnly && /\/api\/(stream-(mode|settings)|fold)$/.test(hubPath)); |
| 211 | const session = yield* authenticateMediaRequest( |
| 212 | controlsDevice ? AuthOrchestrationOperateScope : AuthOrchestrationReadScope, |
| 213 | ); |
| 214 | const sessions = yield* SessionStore.SessionStore; |
| 215 | const invalidated = sessions.awaitInvalidation(session.sessionId).pipe( |
| 216 | Effect.catchTags({ |
| 217 | SessionCredentialVerificationError: (error) => |
| 218 | failEnvironmentInternal("internal_error", error).pipe(Effect.ignore), |
| 219 | }), |
| 220 | ); |
| 221 | const devices = yield* DeviceService.DeviceService; |
| 222 | const ready = yield* devices.currentReadiness(url.value.searchParams.get("hostId") ?? undefined); |
| 223 | if (!ready) { |
| 224 | return HttpServerResponse.text("Device hub is not running", { status: 503 }); |
| 225 | } |
| 226 | // Consume the auth ticket here; never forward it to the hub. |
| 227 | const upstreamSearch = new URLSearchParams(url.value.search); |
| 228 | upstreamSearch.delete("wsTicket"); |
| 229 | upstreamSearch.delete("hostId"); |
| 230 | const search = upstreamSearch.size > 0 ? `?${upstreamSearch.toString()}` : ""; |
| 231 | const screenshotDevice = upstreamSearch.get("device"); |
| 232 | if ( |
| 233 | screenshotDevice && |
| 234 | ["/vendor/serve-sim/api/screenshot", "/vendor/serve-emu/api/screenshot"].includes(hubPath) |
| 235 | ) { |
| 236 | const { png } = yield* devices.screenshot({ hostId: ready.hostId, deviceId: screenshotDevice }); |
| 237 | return HttpServerResponse.uint8Array(png, { |
| 238 | contentType: "image/png", |
| 239 | headers: { "cache-control": "no-store, no-transform" }, |
| 240 | }); |
| 241 | } |
| 242 | // Hosts with several upstreams (one per cloud session) route and authenticate requests themselves. |
| 243 | const routed = ready.upstream ? yield* ready.upstream(hubPath, upstreamSearch) : undefined; |
| 244 | if (routed === null) { |
| 245 | return HttpServerResponse.text("Not Found", { status: 404 }); |
| 246 | } |
| 247 | const upstreamUrl = routed?.url ?? `${ready.hub.origin}${hubPath}${search}`; |
| 248 | if (upgrade) { |
| 249 | return yield* Effect.raceFirst( |
| 250 | proxyWebSocket( |
| 251 | request, |
| 252 | upstreamUrl.replace(/^http/, "ws"), |
| 253 | routed?.protocols, |
| 254 | routed?.headers, |
| 255 | ), |
| 256 | invalidated.pipe(Effect.as(HttpServerResponse.empty())), |
| 257 | ); |
| 258 | } |
| 259 | return yield* proxyHttp(request, upstreamUrl, invalidated, routed?.headers); |
| 260 | }); |
| 261 | |
| 262 | export const layer = HttpRouter.add("*", `${DeviceService.DEVICE_HUB_ROUTE_PREFIX}/*`, handler); |