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