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

DeviceHubProxy.ts

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