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

DeviceHubProxy.ts

184 lines7.0 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 = (source: Socket.Socket, sink: Socket.Writer) =>
103 Effect.gen(function* () {
104 const { pull } = yield* source.reader;
105 while (true) {
106 yield* sink.writeAll(yield* pull);
107 }
108 });
109​
110const proxyHttp = Effect.fn("DeviceHubProxy.proxyHttp")(function* (
111 request: HttpServerRequest.HttpServerRequest,
112 upstreamUrl: string,
113 hubOrigin: string,
114) {
115 const httpClient = HttpClient.withScope(yield* HttpClient.HttpClient);
116 const method = request.method;
117 const upstreamRequest = HttpClientRequest.make(method)(upstreamUrl).pipe(
118 HttpClientRequest.setHeaders(forwardHeaders(request, hubOrigin)),
119 method === "GET" || method === "HEAD"
120 ? (self) => self
121 : HttpClientRequest.bodyStream(request.stream),
122 );
123 const response = yield* httpClient.execute(upstreamRequest);
124 const headers: Record<string, string> = {};
125 for (const [name, value] of Object.entries(response.headers)) {
126 if (name === "content-encoding" || name === "transfer-encoding" || name === "connection") {
127 continue;
128 }
129 if (value !== undefined) headers[name] = value;
130 }
131 // Long-lived MJPEG and AVCC responses must not be buffered by compression.
132 headers["cache-control"] = "no-store, no-transform";
133 return HttpServerResponse.stream(response.stream, {
134 status: response.status,
135 headers,
136 ...(headers["content-type"] ? { contentType: headers["content-type"] } : {}),
137 });
138});
139​
140const handler = Effect.gen(function* () {
141 const request = yield* HttpServerRequest.HttpServerRequest;
142 const url = HttpServerRequest.toURL(request);
143 if (Option.isNone(url)) {
144 return HttpServerResponse.text("Bad Request", { status: 400 });
145 }
146 const hubPath = url.value.pathname.slice(DeviceService.DEVICE_HUB_ROUTE_PREFIX.length) || "/";
147 const upgrade = isWebSocketUpgrade(request);
148 const allowed = (upgrade ? ALLOWED_WS_PATHS : ALLOWED_PATHS).some((pattern) =>
149 pattern.test(hubPath),
150 );
151 if (!allowed) {
152 return HttpServerResponse.text("Not Found", { status: 404 });
153 }
154 const readOnly = request.method === "GET" || request.method === "HEAD";
155 if (!upgrade && !readOnly && !MUTABLE_PATHS.some((pattern) => pattern.test(hubPath))) {
156 return HttpServerResponse.text("Method Not Allowed", { status: 405 });
157 }
158 const controlsDevice =
159 (upgrade && hubPath !== "/api/devices/ws") ||
160 (!readOnly && /\/api\/(stream-(mode|settings)|fold)$/.test(hubPath));
161 yield* authenticateMediaRequest(
162 controlsDevice ? AuthOrchestrationOperateScope : AuthOrchestrationReadScope,
163 );
164 const devices = yield* DeviceService.DeviceService;
165 const ready = yield* devices.currentReadiness(url.value.searchParams.get("hostId") ?? undefined);
166 if (!ready) {
167 return HttpServerResponse.text("Device hub is not running", { status: 503 });
168 }
169 // The ticket authenticates here and must not travel on to the hub.
170 const upstreamSearch = new URLSearchParams(url.value.search);
171 upstreamSearch.delete("wsTicket");
172 upstreamSearch.delete("hostId");
173 const search = upstreamSearch.size > 0 ? `?${upstreamSearch.toString()}` : "";
174 const upstreamPath = `${hubPath}${search}`;
175 if (upgrade) {
176 return yield* proxyWebSocket(
177 request,
178 `${ready.hub.origin.replace(/^http/, "ws")}${upstreamPath}`,
179 );
180 }
181 return yield* proxyHttp(request, `${ready.hub.origin}${upstreamPath}`, ready.hub.origin);
182});
183​
184export const layer = HttpRouter.add("*", `${DeviceService.DEVICE_HUB_ROUTE_PREFIX}/*`, handler);