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

DeviceHubProxy.ts

235 lines8.9 KB

1/**
2 * Same-origin proxy in front of expo-device-hub.
3 *
4 * The hub binds loopback and is never reachable directly: serve-sim exposes a
5 * shell-exec route and serve-emu's action routes are unauthenticated, so the
6 * only way to a device stream is through this route, which requires an
7 * environment session with read scope (operate scope for input and tuning). Reusing the T3
8 * origin is also what makes remote connections work unchanged — Tailscale and
9 * T3 Connect already carry `/api/*` and WebSocket upgrades for the app itself.
10 *
11 * Only the routes the Device panel needs are forwarded. Anything under the
12 * hub's dashboard, exec, or WebRTC surface is rejected here.
13 */
14import {
15 AuthOrchestrationReadScope,
16 AuthOrchestrationOperateScope,
17 type AuthEnvironmentScope,
18} from "@t3tools/contracts";
19import * as Effect from "effect/Effect";
20import * as Option from "effect/Option";
21import {
22 HttpClient,
23 HttpClientRequest,
24 HttpRouter,
25 HttpServerRequest,
26 HttpServerResponse,
27} from "effect/unstable/http";
28import * as Socket from "effect/unstable/socket/Socket";
29import * as NodeSocket from "@effect/platform-node/NodeSocket";
30​
31import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
32import {
33 failEnvironmentAuthInvalid,
34 failEnvironmentInternal,
35 failEnvironmentScopeRequired,
36} from "../auth/http.ts";
37import * as DeviceService from "./DeviceService.ts";
38​
39const ALLOWED_PATHS: ReadonlyArray<RegExp> = [
40 /^\/api\/devices$/,
41 /^\/vendor\/serve-sim\/api$/,
42 /^\/vendor\/serve-sim\/api\/screenshot$/,
43 /^\/vendor\/serve-sim\/api\/event-log(\/events)?$/,
44 /^\/vendor\/serve-sim\/helper\/[^/]+\/(stream\.mjpeg|stream\.avcc|config|health|ax|foreground)$/,
45 /^\/vendor\/serve-sim\/appstate$/,
46 /^\/vendor\/serve-emu\/api\/(devices|screenshot|stream-mode|stream-settings|accessibility)$/,
47 /^\/vendor\/serve-emu\/health$/,
48];
49​
50/** Read paths are GET-only; only these accept other methods (screenshot captures, stream tuning). */
51const MUTABLE_PATHS: ReadonlyArray<RegExp> = [
52 /^\/vendor\/serve-sim\/api\/screenshot$/,
53 /^\/vendor\/serve-emu\/api\/(screenshot|stream-mode|stream-settings)$/,
54];
55​
56const ALLOWED_WS_PATHS: ReadonlyArray<RegExp> = [
57 /^\/api\/devices\/ws$/,
58 /^\/vendor\/serve-sim\/helper\/ws$/,
59 /^\/vendor\/serve-emu\/ws$/,
60];
61​
62/** Hop-by-hop and origin headers that must not cross the proxy. */
63const DROPPED_REQUEST_HEADERS = new Set([
64 "host",
65 "connection",
66 "upgrade",
67 "sec-websocket-key",
68 "sec-websocket-version",
69 "sec-websocket-extensions",
70 "sec-websocket-protocol",
71 "cookie",
72 "authorization",
73 "dpop",
74 "content-length",
75 "accept-encoding",
76]);
77​
78const isWebSocketUpgrade = (request: HttpServerRequest.HttpServerRequest) =>
79 request.headers.upgrade?.toLowerCase() === "websocket";
80​
81/**
82 * `<img>` and WebSocket cannot set headers, so every proxied request
83 * authenticates the way the `/ws` upgrade does: a cookie for browser
84 * sessions, or a short-lived `wsTicket` minted over authenticated HTTP for
85 * bearer and DPoP clients. The upgrade authenticator already implements that
86 * fallback order, so it is used for plain requests as well.
87 */
88const authenticate = (requiredScope: AuthEnvironmentScope) =>
89 Effect.gen(function* () {
90 const request = yield* HttpServerRequest.HttpServerRequest;
91 const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
92 const session = yield* serverAuth.authenticateWebSocketUpgrade(request).pipe(
93 Effect.catch((error) =>
94 Effect.gen(function* () {
95 if (EnvironmentAuth.isServerAuthCredentialError(error)) {
96 return yield* failEnvironmentAuthInvalid(
97 EnvironmentAuth.serverAuthCredentialReason(error),
98 EnvironmentAuth.serverAuthDpopFailureReason(error),
99 );
100 }
101 return yield* failEnvironmentInternal("internal_error", error);
102 }),
103 ),
104 );
105 if (!session.scopes.includes(requiredScope)) {
106 return yield* failEnvironmentScopeRequired(requiredScope);
107 }
108 });
109​
110const forwardHeaders = (request: HttpServerRequest.HttpServerRequest, origin: string) => {
111 const headers: Record<string, string> = {};
112 for (const [name, value] of Object.entries(request.headers)) {
113 if (DROPPED_REQUEST_HEADERS.has(name) || value === undefined) continue;
114 headers[name] = value;
115 }
116 // serve-emu refuses mutations whose Origin differs from the request origin.
117 if (request.headers.origin !== undefined) headers.origin = origin;
118 return headers;
119};
120​
121/**
122 * Pipe a client WebSocket to the hub's with no framing changes. Frames are
123 * opaque: H.264 access units one way, input packets the other.
124 */
125const proxyWebSocket = Effect.fn("DeviceHubProxy.proxyWebSocket")(function* (
126 request: HttpServerRequest.HttpServerRequest,
127 upstreamUrl: string,
128) {
129 const client = yield* request.upgrade;
130 const upstream = yield* Socket.makeWebSocket(upstreamUrl, {
131 openTimeout: "10 seconds",
132 }).pipe(Effect.provide(NodeSocket.layerWebSocketConstructor));
133 yield* Effect.scoped(
134 Effect.gen(function* () {
135 const writeToClient = yield* client.writer;
136 const writeToUpstream = yield* upstream.writer;
137 // Whichever side closes first ends the other via scope teardown: a close
138 // fails the pull with a SocketError, which loses the race.
139 return yield* Effect.raceFirst(
140 pumpFrames(upstream, writeToClient),
141 pumpFrames(client, writeToUpstream),
142 );
143 }),
144 ).pipe(Effect.catchCause(() => Effect.void));
145 return HttpServerResponse.empty();
146});
147​
148const pumpFrames = (source: Socket.Socket, sink: Socket.Writer) =>
149 Effect.gen(function* () {
150 const { pull } = yield* source.reader;
151 while (true) {
152 yield* sink.writeAll(yield* pull);
153 }
154 });
155​
156const proxyHttp = Effect.fn("DeviceHubProxy.proxyHttp")(function* (
157 request: HttpServerRequest.HttpServerRequest,
158 upstreamUrl: string,
159 hubOrigin: string,
160) {
161 const httpClient = HttpClient.withScope(yield* HttpClient.HttpClient);
162 const method = request.method;
163 const upstreamRequest = HttpClientRequest.make(method)(upstreamUrl).pipe(
164 HttpClientRequest.setHeaders(forwardHeaders(request, hubOrigin)),
165 method === "GET" || method === "HEAD"
166 ? (self) => self
167 : HttpClientRequest.bodyStream(request.stream),
168 );
169 const response = yield* httpClient.execute(upstreamRequest);
170 const headers: Record<string, string> = {};
171 for (const [name, value] of Object.entries(response.headers)) {
172 if (name === "content-encoding" || name === "transfer-encoding" || name === "connection") {
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 return HttpServerResponse.stream(response.stream, {
180 status: response.status,
181 headers,
182 ...(headers["content-type"] ? { contentType: headers["content-type"] } : {}),
183 });
184});
185​
186const handler = Effect.gen(function* () {
187 const request = yield* HttpServerRequest.HttpServerRequest;
188 const url = HttpServerRequest.toURL(request);
189 if (Option.isNone(url)) {
190 return HttpServerResponse.text("Bad Request", { status: 400 });
191 }
192 const hubPath = url.value.pathname.slice(DeviceService.DEVICE_HUB_ROUTE_PREFIX.length) || "/";
193 const upgrade = isWebSocketUpgrade(request);
194 const allowed = (upgrade ? ALLOWED_WS_PATHS : ALLOWED_PATHS).some((pattern) =>
195 pattern.test(hubPath),
196 );
197 if (!allowed) {
198 return HttpServerResponse.text("Not Found", { status: 404 });
199 }
200 const readOnly = request.method === "GET" || request.method === "HEAD";
201 if (!upgrade && !readOnly && !MUTABLE_PATHS.some((pattern) => pattern.test(hubPath))) {
202 return HttpServerResponse.text("Method Not Allowed", { status: 405 });
203 }
204 const controlsDevice =
205 (upgrade && hubPath !== "/api/devices/ws") ||
206 (!readOnly && /\/api\/stream-(mode|settings)$/.test(hubPath));
207 yield* authenticate(controlsDevice ? AuthOrchestrationOperateScope : AuthOrchestrationReadScope);
208 const devices = yield* DeviceService.DeviceService;
209 const ready = yield* devices.currentReadiness(url.value.searchParams.get("hostId") ?? undefined);
210 if (!ready) {
211 return HttpServerResponse.text("Device hub is not running", { status: 503 });
212 }
213 // The hub runs in standalone mode at its origin root; the panel builds every
214 // stream and socket URL itself, so nothing depends on the hub knowing the
215 // T3 prefix.
216 // The ticket authenticates here and must not travel on to the hub.
217 const upstreamSearch = new URLSearchParams(url.value.search);
218 upstreamSearch.delete("wsTicket");
219 upstreamSearch.delete("hostId");
220 const search = upstreamSearch.size > 0 ? `?${upstreamSearch.toString()}` : "";
221 const upstreamPath = `${hubPath}${search}`;
222 if (upgrade) {
223 return yield* proxyWebSocket(
224 request,
225 `${ready.hub.origin.replace(/^http/, "ws")}${upstreamPath}`,
226 );
227 }
228 return yield* proxyHttp(request, `${ready.hub.origin}${upstreamPath}`, ready.hub.origin);
229});
230​
231export const deviceHubProxyRouteLayer = HttpRouter.add(
232 "*",
233 `${DeviceService.DEVICE_HUB_ROUTE_PREFIX}/*`,
234 handler,
235);