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

DeviceHubProxy.ts

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