Open History to see the last commit
1// Loopback-only hubs expose shell execution or unauthenticated actions.
2// Proxy with environment read scope for streams and operate scope for input and tuning.
3import { AuthOrchestrationReadScope, AuthOrchestrationOperateScope } from "@t3tools/contracts";
4import * as Effect from "effect/Effect";
5import * as Option from "effect/Option";
6import {
7 HttpClient,
8 HttpClientRequest,
9 HttpRouter,
10 HttpServerRequest,
11 HttpServerResponse,
12} from "effect/http";
13import * as Socket from "effect/socket/Socket";
14import * as NodeSocket from "@effect/platform-node/NodeSocket";
15
16import { authenticateMediaRequest } from "../auth/http.ts";
17import * as DeviceService from "./DeviceService.ts";
18import { repeatStillFrame } from "./mjpegStillFrame.ts";
19
20const ALLOWED_PATHS: ReadonlyArray<RegExp> = [
21 /^\/api\/devices$/,
22 /^\/vendor\/serve-sim\/api$/,
23 /^\/vendor\/serve-sim\/api\/screenshot$/,
24 /^\/vendor\/serve-sim\/api\/event-log(\/events)?$/,
25 /^\/vendor\/serve-sim\/helper\/[^/]+\/(stream\.mjpeg|stream\.avcc|config|health|ax|foreground)$/,
26 /^\/vendor\/serve-sim\/helper\/[^/]+\/panel\/(1|3)\/stream\.avcc$/,
27 /^\/vendor\/serve-sim\/helper\/[^/]+\/webrtc\/(offer|close)$/,
28 /^\/vendor\/serve-sim\/appstate$/,
29 /^\/vendor\/serve-emu\/api\/(devices|screenshot|stream-mode|stream-settings|accessibility|fold)$/,
30 /^\/vendor\/serve-emu\/health$/,
31];
32
33const MUTABLE_PATHS: ReadonlyArray<RegExp> = [
34 /^\/vendor\/serve-sim\/api\/screenshot$/,
35 // WebRTC signalling: opening and closing a view of the stream, so read scope.
36 /^\/vendor\/serve-sim\/helper\/[^/]+\/webrtc\/(offer|close)$/,
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 // The client's HTTPS hop makes the hub reject our loopback Origin over T3 Connect.
61 "x-forwarded-proto",
62]);
63
64const isWebSocketUpgrade = (request: HttpServerRequest.HttpServerRequest) =>
65 request.headers.upgrade?.toLowerCase() === "websocket";
66
67const forwardHeaders = (request: HttpServerRequest.HttpServerRequest, origin: string) => {
68 const headers: Record<string, string> = {};
69 for (const [name, value] of Object.entries(request.headers)) {
70 if (DROPPED_REQUEST_HEADERS.has(name) || value === undefined) continue;
71 headers[name] = value;
72 }
73 // serve-emu refuses mutations whose Origin differs from the request origin.
74 if (request.headers.origin !== undefined) headers.origin = origin;
75 return headers;
76};
77
78const proxyWebSocket = Effect.fn("DeviceHubProxy.proxyWebSocket")(function* (
79 request: HttpServerRequest.HttpServerRequest,
80 upstreamUrl: string,
81 protocols: ReadonlyArray<string> = [],
82) {
83 const client = yield* request.upgrade;
84 const upstream = yield* Socket.makeWebSocket(upstreamUrl, {
85 openTimeout: "10 seconds",
86 ...(protocols.length > 0 ? { protocols: [...protocols] } : {}),
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 return yield* Effect.raceFirst(
93 pumpFrames(upstream, writeToClient),
94 pumpFrames(client, writeToUpstream),
95 );
96 }),
97 ).pipe(Effect.ignoreCause);
98 return HttpServerResponse.empty();
99});
100
101const pumpFrames =
102 /* Frame pumping runs continuously; a span per frame stream adds no diagnostic value. */
103 Effect.fnUntraced(function* (source: Socket.Socket, sink: Socket.Writer) {
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 extraHeaders: Readonly<Record<string, 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({
119 ...forwardHeaders(request, new URL(upstreamUrl).origin),
120 ...extraHeaders,
121 }),
122 method === "GET" || method === "HEAD"
123 ? (self) => self
124 : // A bare stream body is sent as octet-stream; serve-sim refuses WebRTC
125 // offers that are not application/json.
126 HttpClientRequest.bodyStream(request.stream, {
127 contentType: request.headers["content-type"],
128 }),
129 );
130 const response = yield* httpClient.execute(upstreamRequest);
131 const headers: Record<string, string> = {};
132 for (const [name, value] of Object.entries(response.headers)) {
133 // A cookie from an upstream such as an EAS session's preview host would land on T3's origin.
134 if (
135 name === "content-encoding" ||
136 name === "transfer-encoding" ||
137 name === "connection" ||
138 name === "set-cookie"
139 ) {
140 continue;
141 }
142 if (value !== undefined) headers[name] = value;
143 }
144 // Long-lived MJPEG and AVCC responses must not be buffered by compression.
145 headers["cache-control"] = "no-store, no-transform";
146 const body = headers["content-type"]?.startsWith("multipart/x-mixed-replace")
147 ? repeatStillFrame(response.stream)
148 : response.stream;
149 return HttpServerResponse.stream(body, {
150 status: response.status,
151 headers,
152 ...(headers["content-type"] ? { contentType: headers["content-type"] } : {}),
153 });
154});
155
156const handler = Effect.gen(function* () {
157 const request = yield* HttpServerRequest.HttpServerRequest;
158 const url = HttpServerRequest.toURL(request);
159 if (Option.isNone(url)) {
160 return HttpServerResponse.text("Bad Request", { status: 400 });
161 }
162 const hubPath = url.value.pathname.slice(DeviceService.DEVICE_HUB_ROUTE_PREFIX.length) || "/";
163 const upgrade = isWebSocketUpgrade(request);
164 const allowed = (upgrade ? ALLOWED_WS_PATHS : ALLOWED_PATHS).some((pattern) =>
165 pattern.test(hubPath),
166 );
167 if (!allowed) {
168 return HttpServerResponse.text("Not Found", { status: 404 });
169 }
170 const readOnly = request.method === "GET" || request.method === "HEAD";
171 if (!upgrade && !readOnly && !MUTABLE_PATHS.some((pattern) => pattern.test(hubPath))) {
172 return HttpServerResponse.text("Method Not Allowed", { status: 405 });
173 }
174 const controlsDevice =
175 (upgrade && hubPath !== "/api/devices/ws") ||
176 (!readOnly && /\/api\/(stream-(mode|settings)|fold)$/.test(hubPath));
177 yield* authenticateMediaRequest(
178 controlsDevice ? AuthOrchestrationOperateScope : AuthOrchestrationReadScope,
179 );
180 const devices = yield* DeviceService.DeviceService;
181 const ready = yield* devices.currentReadiness(url.value.searchParams.get("hostId") ?? undefined);
182 if (!ready) {
183 return HttpServerResponse.text("Device hub is not running", { status: 503 });
184 }
185 // Consume the auth ticket here; never forward it to the hub.
186 const upstreamSearch = new URLSearchParams(url.value.search);
187 upstreamSearch.delete("wsTicket");
188 upstreamSearch.delete("hostId");
189 const search = upstreamSearch.size > 0 ? `?${upstreamSearch.toString()}` : "";
190 // Hosts with several upstreams (one per cloud session) route and authenticate requests themselves.
191 const routed = ready.upstream ? yield* ready.upstream(hubPath, upstreamSearch) : undefined;
192 if (routed === null) {
193 return HttpServerResponse.text("Not Found", { status: 404 });
194 }
195 const upstreamUrl = routed?.url ?? `${ready.hub.origin}${hubPath}${search}`;
196 if (upgrade) {
197 return yield* proxyWebSocket(request, upstreamUrl.replace(/^http/, "ws"), routed?.protocols);
198 }
199 return yield* proxyHttp(request, upstreamUrl, routed?.headers);
200});
201
202export const layer = HttpRouter.add("*", `${DeviceService.DEVICE_HUB_ROUTE_PREFIX}/*`, handler);