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

DeviceHubProxy.ts

225 lines8.7 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 const downstream = upstream.runRaw((data) => writeToClient(data));
138 const upstreamPump = client.runRaw((data) => writeToUpstream(data));
139 // Whichever side closes first ends the other via scope teardown.
140 yield* Effect.raceFirst(downstream, upstreamPump);
141 }),
142 ).pipe(Effect.catchCause(() => Effect.void));
143 return HttpServerResponse.empty();
144});
145​
146const proxyHttp = Effect.fn("DeviceHubProxy.proxyHttp")(function* (
147 request: HttpServerRequest.HttpServerRequest,
148 upstreamUrl: string,
149 hubOrigin: string,
150) {
151 const httpClient = HttpClient.withScope(yield* HttpClient.HttpClient);
152 const method = request.method;
153 const upstreamRequest = HttpClientRequest.make(method)(upstreamUrl).pipe(
154 HttpClientRequest.setHeaders(forwardHeaders(request, hubOrigin)),
155 method === "GET" || method === "HEAD"
156 ? (self) => self
157 : HttpClientRequest.bodyStream(request.stream),
158 );
159 const response = yield* httpClient.execute(upstreamRequest);
160 const headers: Record<string, string> = {};
161 for (const [name, value] of Object.entries(response.headers)) {
162 if (name === "content-encoding" || name === "transfer-encoding" || name === "connection") {
163 continue;
164 }
165 if (value !== undefined) headers[name] = value;
166 }
167 // Long-lived MJPEG and AVCC responses must not be buffered by compression.
168 headers["cache-control"] = "no-store, no-transform";
169 return HttpServerResponse.stream(response.stream, {
170 status: response.status,
171 headers,
172 ...(headers["content-type"] ? { contentType: headers["content-type"] } : {}),
173 });
174});
175​
176const handler = Effect.gen(function* () {
177 const request = yield* HttpServerRequest.HttpServerRequest;
178 const url = HttpServerRequest.toURL(request);
179 if (Option.isNone(url)) {
180 return HttpServerResponse.text("Bad Request", { status: 400 });
181 }
182 const hubPath = url.value.pathname.slice(DeviceService.DEVICE_HUB_ROUTE_PREFIX.length) || "/";
183 const upgrade = isWebSocketUpgrade(request);
184 const allowed = (upgrade ? ALLOWED_WS_PATHS : ALLOWED_PATHS).some((pattern) =>
185 pattern.test(hubPath),
186 );
187 if (!allowed) {
188 return HttpServerResponse.text("Not Found", { status: 404 });
189 }
190 const readOnly = request.method === "GET" || request.method === "HEAD";
191 if (!upgrade && !readOnly && !MUTABLE_PATHS.some((pattern) => pattern.test(hubPath))) {
192 return HttpServerResponse.text("Method Not Allowed", { status: 405 });
193 }
194 const controlsDevice =
195 (upgrade && hubPath !== "/api/devices/ws") ||
196 (!readOnly && /\/api\/stream-(mode|settings)$/.test(hubPath));
197 yield* authenticate(controlsDevice ? AuthOrchestrationOperateScope : AuthOrchestrationReadScope);
198 const devices = yield* DeviceService.DeviceService;
199 const ready = yield* devices.currentReadiness(url.value.searchParams.get("hostId") ?? undefined);
200 if (!ready) {
201 return HttpServerResponse.text("Device hub is not running", { status: 503 });
202 }
203 // The hub runs in standalone mode at its origin root; the panel builds every
204 // stream and socket URL itself, so nothing depends on the hub knowing the
205 // T3 prefix.
206 // The ticket authenticates here and must not travel on to the hub.
207 const upstreamSearch = new URLSearchParams(url.value.search);
208 upstreamSearch.delete("wsTicket");
209 upstreamSearch.delete("hostId");
210 const search = upstreamSearch.size > 0 ? `?${upstreamSearch.toString()}` : "";
211 const upstreamPath = `${hubPath}${search}`;
212 if (upgrade) {
213 return yield* proxyWebSocket(
214 request,
215 `${ready.hub.origin.replace(/^http/, "ws")}${upstreamPath}`,
216 );
217 }
218 return yield* proxyHttp(request, `${ready.hub.origin}${upstreamPath}`, ready.hub.origin);
219});
220​
221export const deviceHubProxyRouteLayer = HttpRouter.add(
222 "*",
223 `${DeviceService.DEVICE_HUB_ROUTE_PREFIX}/*`,
224 handler,
225);