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

DeviceHubProxy.ts

209 lines8.3 KB

1/**
2 * The hub binds loopback and is never reachable directly: serve-sim exposes a shell-exec route
3 * and serve-emu's action routes are unauthenticated, so the only way to a device stream is
4 * through this route, which requires an environment session with read scope (operate scope for
5 * input and tuning).
6 */
7import { AuthOrchestrationReadScope, AuthOrchestrationOperateScope } from "@t3tools/contracts";
8import * as Effect from "effect/Effect";
9import * as Option from "effect/Option";
10import {
11 HttpClient,
12 HttpClientRequest,
13 HttpRouter,
14 HttpServerRequest,
15 HttpServerResponse,
16} from "effect/http";
17import * as Socket from "effect/socket/Socket";
18import * as NodeSocket from "@effect/platform-node/NodeSocket";
19​
20import { authenticateMediaRequest } from "../auth/http.ts";
21import * as DeviceService from "./DeviceService.ts";
22import { repeatStillFrame } from "./mjpegStillFrame.ts";
23​
24const ALLOWED_PATHS: ReadonlyArray<RegExp> = [
25 /^\/api\/devices$/,
26 /^\/vendor\/serve-sim\/api$/,
27 /^\/vendor\/serve-sim\/api\/screenshot$/,
28 /^\/vendor\/serve-sim\/api\/event-log(\/events)?$/,
29 /^\/vendor\/serve-sim\/helper\/[^/]+\/(stream\.mjpeg|stream\.avcc|config|health|ax|foreground)$/,
30 /^\/vendor\/serve-sim\/helper\/[^/]+\/panel\/(1|3)\/stream\.avcc$/,
31 /^\/vendor\/serve-sim\/helper\/[^/]+\/webrtc\/(offer|close)$/,
32 /^\/vendor\/serve-sim\/appstate$/,
33 /^\/vendor\/serve-emu\/api\/(devices|screenshot|stream-mode|stream-settings|accessibility|fold)$/,
34 /^\/vendor\/serve-emu\/health$/,
35];
36​
37const MUTABLE_PATHS: ReadonlyArray<RegExp> = [
38 /^\/vendor\/serve-sim\/api\/screenshot$/,
39 // WebRTC signalling: opening and closing a view of the stream, so read scope.
40 /^\/vendor\/serve-sim\/helper\/[^/]+\/webrtc\/(offer|close)$/,
41 /^\/vendor\/serve-emu\/api\/(screenshot|stream-mode|stream-settings)$/,
42 /^\/vendor\/serve-emu\/api\/fold$/,
43];
44​
45const ALLOWED_WS_PATHS: ReadonlyArray<RegExp> = [
46 /^\/api\/devices\/ws$/,
47 /^\/vendor\/serve-sim\/helper\/ws$/,
48 /^\/vendor\/serve-emu\/ws$/,
49];
50​
51const DROPPED_REQUEST_HEADERS = new Set([
52 "host",
53 "connection",
54 "upgrade",
55 "sec-websocket-key",
56 "sec-websocket-version",
57 "sec-websocket-extensions",
58 "sec-websocket-protocol",
59 "cookie",
60 "authorization",
61 "dpop",
62 "content-length",
63 "accept-encoding",
64 // Describes the client's HTTPS hop to T3. The hub builds its own origin from it and then
65 // rejects the loopback Origin set below, so every mutation fails over T3 Connect.
66 "x-forwarded-proto",
67]);
68​
69const isWebSocketUpgrade = (request: HttpServerRequest.HttpServerRequest) =>
70 request.headers.upgrade?.toLowerCase() === "websocket";
71​
72const forwardHeaders = (request: HttpServerRequest.HttpServerRequest, origin: string) => {
73 const headers: Record<string, string> = {};
74 for (const [name, value] of Object.entries(request.headers)) {
75 if (DROPPED_REQUEST_HEADERS.has(name) || value === undefined) continue;
76 headers[name] = value;
77 }
78 // serve-emu refuses mutations whose Origin differs from the request origin.
79 if (request.headers.origin !== undefined) headers.origin = origin;
80 return headers;
81};
82​
83const proxyWebSocket = Effect.fn("DeviceHubProxy.proxyWebSocket")(function* (
84 request: HttpServerRequest.HttpServerRequest,
85 upstreamUrl: string,
86 protocols: ReadonlyArray<string> = [],
87) {
88 const client = yield* request.upgrade;
89 const upstream = yield* Socket.makeWebSocket(upstreamUrl, {
90 openTimeout: "10 seconds",
91 ...(protocols.length > 0 ? { protocols: [...protocols] } : {}),
92 }).pipe(Effect.provide(NodeSocket.layerWebSocketConstructor));
93 yield* Effect.scoped(
94 Effect.gen(function* () {
95 const writeToClient = yield* client.writer;
96 const writeToUpstream = yield* upstream.writer;
97 // Whichever side closes first ends the other via scope teardown: a close
98 // fails the pull with a SocketError, which loses the race.
99 return yield* Effect.raceFirst(
100 pumpFrames(upstream, writeToClient),
101 pumpFrames(client, writeToUpstream),
102 );
103 }),
104 ).pipe(Effect.ignoreCause);
105 return HttpServerResponse.empty();
106});
107​
108const pumpFrames =
109 /* Frame pumping runs continuously; a span per frame stream adds no diagnostic value. */
110 Effect.fnUntraced(function* (source: Socket.Socket, sink: Socket.Writer) {
111 const { pull } = yield* source.reader;
112 while (true) {
113 yield* sink.writeAll(yield* pull);
114 }
115 });
116​
117const proxyHttp = Effect.fn("DeviceHubProxy.proxyHttp")(function* (
118 request: HttpServerRequest.HttpServerRequest,
119 upstreamUrl: string,
120 extraHeaders: Readonly<Record<string, string>> = {},
121) {
122 const httpClient = HttpClient.withScope(yield* HttpClient.HttpClient);
123 const method = request.method;
124 const upstreamRequest = HttpClientRequest.make(method)(upstreamUrl).pipe(
125 HttpClientRequest.setHeaders({
126 ...forwardHeaders(request, new URL(upstreamUrl).origin),
127 ...extraHeaders,
128 }),
129 method === "GET" || method === "HEAD"
130 ? (self) => self
131 : // A bare stream body is sent as octet-stream; serve-sim refuses WebRTC
132 // offers that are not application/json.
133 HttpClientRequest.bodyStream(request.stream, {
134 contentType: request.headers["content-type"],
135 }),
136 );
137 const response = yield* httpClient.execute(upstreamRequest);
138 const headers: Record<string, string> = {};
139 for (const [name, value] of Object.entries(response.headers)) {
140 // A cookie from an upstream such as an EAS session's preview host would land on T3's origin.
141 if (
142 name === "content-encoding" ||
143 name === "transfer-encoding" ||
144 name === "connection" ||
145 name === "set-cookie"
146 ) {
147 continue;
148 }
149 if (value !== undefined) headers[name] = value;
150 }
151 // Long-lived MJPEG and AVCC responses must not be buffered by compression.
152 headers["cache-control"] = "no-store, no-transform";
153 const body = headers["content-type"]?.startsWith("multipart/x-mixed-replace")
154 ? repeatStillFrame(response.stream)
155 : response.stream;
156 return HttpServerResponse.stream(body, {
157 status: response.status,
158 headers,
159 ...(headers["content-type"] ? { contentType: headers["content-type"] } : {}),
160 });
161});
162​
163const handler = Effect.gen(function* () {
164 const request = yield* HttpServerRequest.HttpServerRequest;
165 const url = HttpServerRequest.toURL(request);
166 if (Option.isNone(url)) {
167 return HttpServerResponse.text("Bad Request", { status: 400 });
168 }
169 const hubPath = url.value.pathname.slice(DeviceService.DEVICE_HUB_ROUTE_PREFIX.length) || "/";
170 const upgrade = isWebSocketUpgrade(request);
171 const allowed = (upgrade ? ALLOWED_WS_PATHS : ALLOWED_PATHS).some((pattern) =>
172 pattern.test(hubPath),
173 );
174 if (!allowed) {
175 return HttpServerResponse.text("Not Found", { status: 404 });
176 }
177 const readOnly = request.method === "GET" || request.method === "HEAD";
178 if (!upgrade && !readOnly && !MUTABLE_PATHS.some((pattern) => pattern.test(hubPath))) {
179 return HttpServerResponse.text("Method Not Allowed", { status: 405 });
180 }
181 const controlsDevice =
182 (upgrade && hubPath !== "/api/devices/ws") ||
183 (!readOnly && /\/api\/(stream-(mode|settings)|fold)$/.test(hubPath));
184 yield* authenticateMediaRequest(
185 controlsDevice ? AuthOrchestrationOperateScope : AuthOrchestrationReadScope,
186 );
187 const devices = yield* DeviceService.DeviceService;
188 const ready = yield* devices.currentReadiness(url.value.searchParams.get("hostId") ?? undefined);
189 if (!ready) {
190 return HttpServerResponse.text("Device hub is not running", { status: 503 });
191 }
192 // The ticket authenticates here and must not travel on to the hub.
193 const upstreamSearch = new URLSearchParams(url.value.search);
194 upstreamSearch.delete("wsTicket");
195 upstreamSearch.delete("hostId");
196 const search = upstreamSearch.size > 0 ? `?${upstreamSearch.toString()}` : "";
197 // Hosts with several upstreams (one per cloud session) route and authenticate requests themselves.
198 const routed = ready.upstream ? yield* ready.upstream(hubPath, upstreamSearch) : undefined;
199 if (routed === null) {
200 return HttpServerResponse.text("Not Found", { status: 404 });
201 }
202 const upstreamUrl = routed?.url ?? `${ready.hub.origin}${hubPath}${search}`;
203 if (upgrade) {
204 return yield* proxyWebSocket(request, upstreamUrl.replace(/^http/, "ws"), routed?.protocols);
205 }
206 return yield* proxyHttp(request, upstreamUrl, routed?.headers);
207});
208​
209export const layer = HttpRouter.add("*", `${DeviceService.DEVICE_HUB_ROUTE_PREFIX}/*`, handler);