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

DeviceHubProxy.ts

185 lines7.1 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";
22​
23const ALLOWED_PATHS: ReadonlyArray<RegExp> = [
24 /^\/api\/devices$/,
25 /^\/vendor\/serve-sim\/api$/,
26 /^\/vendor\/serve-sim\/api\/screenshot$/,
27 /^\/vendor\/serve-sim\/api\/event-log(\/events)?$/,
28 /^\/vendor\/serve-sim\/helper\/[^/]+\/(stream\.mjpeg|stream\.avcc|config|health|ax|foreground)$/,
29 /^\/vendor\/serve-sim\/helper\/[^/]+\/panel\/(1|3)\/stream\.avcc$/,
30 /^\/vendor\/serve-sim\/appstate$/,
31 /^\/vendor\/serve-emu\/api\/(devices|screenshot|stream-mode|stream-settings|accessibility|fold)$/,
32 /^\/vendor\/serve-emu\/health$/,
33];
34​
35const MUTABLE_PATHS: ReadonlyArray<RegExp> = [
36 /^\/vendor\/serve-sim\/api\/screenshot$/,
37 /^\/vendor\/serve-emu\/api\/(screenshot|stream-mode|stream-settings)$/,
38 /^\/vendor\/serve-emu\/api\/fold$/,
39];
40​
41const ALLOWED_WS_PATHS: ReadonlyArray<RegExp> = [
42 /^\/api\/devices\/ws$/,
43 /^\/vendor\/serve-sim\/helper\/ws$/,
44 /^\/vendor\/serve-emu\/ws$/,
45];
46​
47const DROPPED_REQUEST_HEADERS = new Set([
48 "host",
49 "connection",
50 "upgrade",
51 "sec-websocket-key",
52 "sec-websocket-version",
53 "sec-websocket-extensions",
54 "sec-websocket-protocol",
55 "cookie",
56 "authorization",
57 "dpop",
58 "content-length",
59 "accept-encoding",
60 // Describes the client's HTTPS hop to T3. The hub builds its own origin from it and then
61 // rejects the loopback Origin set below, so every mutation fails over T3 Connect.
62 "x-forwarded-proto",
63]);
64​
65const isWebSocketUpgrade = (request: HttpServerRequest.HttpServerRequest) =>
66 request.headers.upgrade?.toLowerCase() === "websocket";
67​
68const forwardHeaders = (request: HttpServerRequest.HttpServerRequest, origin: string) => {
69 const headers: Record<string, string> = {};
70 for (const [name, value] of Object.entries(request.headers)) {
71 if (DROPPED_REQUEST_HEADERS.has(name) || value === undefined) continue;
72 headers[name] = value;
73 }
74 // serve-emu refuses mutations whose Origin differs from the request origin.
75 if (request.headers.origin !== undefined) headers.origin = origin;
76 return headers;
77};
78​
79const proxyWebSocket = Effect.fn("DeviceHubProxy.proxyWebSocket")(function* (
80 request: HttpServerRequest.HttpServerRequest,
81 upstreamUrl: string,
82) {
83 const client = yield* request.upgrade;
84 const upstream = yield* Socket.makeWebSocket(upstreamUrl, {
85 openTimeout: "10 seconds",
86 }).pipe(Effect.provide(NodeSocket.layerWebSocketConstructor));
87 yield* Effect.scoped(
88 Effect.gen(function* () {
89 const writeToClient = yield* client.writer;
90 const writeToUpstream = yield* upstream.writer;
91 // Whichever side closes first ends the other via scope teardown: a close
92 // fails the pull with a SocketError, which loses the race.
93 return yield* Effect.raceFirst(
94 pumpFrames(upstream, writeToClient),
95 pumpFrames(client, writeToUpstream),
96 );
97 }),
98 ).pipe(Effect.ignoreCause);
99 return HttpServerResponse.empty();
100});
101​
102const pumpFrames =
103 /* Frame pumping runs continuously; a span per frame stream adds no diagnostic value. */
104 Effect.fnUntraced(function* (source: Socket.Socket, sink: Socket.Writer) {
105 const { pull } = yield* source.reader;
106 while (true) {
107 yield* sink.writeAll(yield* pull);
108 }
109 });
110​
111const proxyHttp = Effect.fn("DeviceHubProxy.proxyHttp")(function* (
112 request: HttpServerRequest.HttpServerRequest,
113 upstreamUrl: string,
114 hubOrigin: string,
115) {
116 const httpClient = HttpClient.withScope(yield* HttpClient.HttpClient);
117 const method = request.method;
118 const upstreamRequest = HttpClientRequest.make(method)(upstreamUrl).pipe(
119 HttpClientRequest.setHeaders(forwardHeaders(request, hubOrigin)),
120 method === "GET" || method === "HEAD"
121 ? (self) => self
122 : HttpClientRequest.bodyStream(request.stream),
123 );
124 const response = yield* httpClient.execute(upstreamRequest);
125 const headers: Record<string, string> = {};
126 for (const [name, value] of Object.entries(response.headers)) {
127 if (name === "content-encoding" || name === "transfer-encoding" || name === "connection") {
128 continue;
129 }
130 if (value !== undefined) headers[name] = value;
131 }
132 // Long-lived MJPEG and AVCC responses must not be buffered by compression.
133 headers["cache-control"] = "no-store, no-transform";
134 return HttpServerResponse.stream(response.stream, {
135 status: response.status,
136 headers,
137 ...(headers["content-type"] ? { contentType: headers["content-type"] } : {}),
138 });
139});
140​
141const handler = Effect.gen(function* () {
142 const request = yield* HttpServerRequest.HttpServerRequest;
143 const url = HttpServerRequest.toURL(request);
144 if (Option.isNone(url)) {
145 return HttpServerResponse.text("Bad Request", { status: 400 });
146 }
147 const hubPath = url.value.pathname.slice(DeviceService.DEVICE_HUB_ROUTE_PREFIX.length) || "/";
148 const upgrade = isWebSocketUpgrade(request);
149 const allowed = (upgrade ? ALLOWED_WS_PATHS : ALLOWED_PATHS).some((pattern) =>
150 pattern.test(hubPath),
151 );
152 if (!allowed) {
153 return HttpServerResponse.text("Not Found", { status: 404 });
154 }
155 const readOnly = request.method === "GET" || request.method === "HEAD";
156 if (!upgrade && !readOnly && !MUTABLE_PATHS.some((pattern) => pattern.test(hubPath))) {
157 return HttpServerResponse.text("Method Not Allowed", { status: 405 });
158 }
159 const controlsDevice =
160 (upgrade && hubPath !== "/api/devices/ws") ||
161 (!readOnly && /\/api\/(stream-(mode|settings)|fold)$/.test(hubPath));
162 yield* authenticateMediaRequest(
163 controlsDevice ? AuthOrchestrationOperateScope : AuthOrchestrationReadScope,
164 );
165 const devices = yield* DeviceService.DeviceService;
166 const ready = yield* devices.currentReadiness(url.value.searchParams.get("hostId") ?? undefined);
167 if (!ready) {
168 return HttpServerResponse.text("Device hub is not running", { status: 503 });
169 }
170 // The ticket authenticates here and must not travel on to the hub.
171 const upstreamSearch = new URLSearchParams(url.value.search);
172 upstreamSearch.delete("wsTicket");
173 upstreamSearch.delete("hostId");
174 const search = upstreamSearch.size > 0 ? `?${upstreamSearch.toString()}` : "";
175 const upstreamPath = `${hubPath}${search}`;
176 if (upgrade) {
177 return yield* proxyWebSocket(
178 request,
179 `${ready.hub.origin.replace(/^http/, "ws")}${upstreamPath}`,
180 );
181 }
182 return yield* proxyHttp(request, `${ready.hub.origin}${upstreamPath}`, ready.hub.origin);
183});
184​
185export const layer = HttpRouter.add("*", `${DeviceService.DEVICE_HUB_ROUTE_PREFIX}/*`, handler);