Repository navigation
Expand file tree
/
Copy pathDeviceHubProxy.ts
More file actions
244 lines (231 loc) · 9.49 KB
/
Copy pathDeviceHubProxy.ts
File metadata and controls
244 lines (231 loc) · 9.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
import { requestUrl } from "../requestUrl.ts";
// Loopback-only hubs expose shell execution or unauthenticated actions.
// Proxy with environment read scope for streams and operate scope for input and tuning.
import { AuthOrchestrationReadScope, AuthOrchestrationOperateScope } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import {
HttpClient,
HttpClientRequest,
HttpMethod,
HttpRouter,
HttpServerRequest,
HttpServerResponse,
} from "effect/http";
import * as Socket from "effect/socket/Socket";
import * as NodeSocket from "@effect/platform-node/NodeSocket";
import { authenticateMediaRequest } from "../auth/http.ts";
import * as DeviceService from "./DeviceService.ts";
import { repeatStillFrame } from "./mjpegStillFrame.ts";
const ALLOWED_PATHS: ReadonlyArray<RegExp> = [
/^\/api\/devices$/,
/^\/vendor\/serve-sim\/api$/,
/^\/vendor\/serve-sim\/api\/screenshot$/,
/^\/vendor\/serve-sim\/api\/event-log(\/events)?$/,
/^\/vendor\/serve-sim\/helper\/[^/]+\/(stream\.mjpeg|stream\.avcc|config|health|ax|foreground)$/,
/^\/vendor\/serve-sim\/helper\/[^/]+\/panel\/(1|3)\/stream\.avcc$/,
/^\/vendor\/serve-sim\/helper\/[^/]+\/webrtc\/(offer|close)$/,
/^\/vendor\/serve-sim\/appstate$/,
/^\/vendor\/serve-emu\/api$/,
/^\/vendor\/serve-emu\/api\/(devices|screenshot|stream-mode|stream-settings|accessibility|fold)$/,
/^\/vendor\/serve-emu\/health$/,
];
// Paths that take methods besides GET; one missing from ALLOWED_PATHS takes no GET.
const MUTABLE_PATHS: ReadonlyArray<RegExp> = [
/^\/vendor\/serve-sim\/api\/screenshot$/,
// WebRTC signalling: opening and closing a view of the stream, so read scope.
/^\/vendor\/serve-sim\/helper\/[^/]+\/webrtc\/(offer|close)$/,
/^\/vendor\/serve-emu\/webrtc\/(offer|close)$/,
/^\/vendor\/serve-emu\/api\/(screenshot|stream-mode|stream-settings)$/,
/^\/vendor\/serve-emu\/api\/fold$/,
];
const ALLOWED_WS_PATHS: ReadonlyArray<RegExp> = [
/^\/api\/devices\/ws$/,
/^\/vendor\/serve-sim\/helper\/ws$/,
/^\/vendor\/serve-emu\/ws$/,
];
const DROPPED_REQUEST_HEADERS = new Set([
"host",
"connection",
"upgrade",
"sec-websocket-key",
"sec-websocket-version",
"sec-websocket-extensions",
"sec-websocket-protocol",
"cookie",
"authorization",
"dpop",
"content-length",
"accept-encoding",
// The client's HTTPS hop makes the hub reject our loopback Origin over T3 Connect.
"x-forwarded-proto",
]);
const isWebSocketUpgrade = (request: HttpServerRequest.HttpServerRequest) =>
request.headers.upgrade?.toLowerCase() === "websocket";
const forwardHeaders = (request: HttpServerRequest.HttpServerRequest, origin: string) => {
const headers: Record<string, string> = {};
for (const [name, value] of Object.entries(request.headers)) {
if (DROPPED_REQUEST_HEADERS.has(name) || value === undefined) continue;
headers[name] = value;
}
// serve-emu refuses mutations whose Origin differs from the request origin.
if (request.headers.origin !== undefined) headers.origin = origin;
return headers;
};
// Effect drops its listeners before closing a socket that is still connecting, and `ws` then
// emits an `error` nobody handles, which exits the server.
export const upstreamWebSocketConstructor = Layer.effect(
Socket.WebSocketConstructor,
Effect.gen(function* () {
const make = yield* Socket.WebSocketConstructor;
return (url, options) => {
const socket = make(url, options);
socket.addEventListener("error", () => undefined);
return socket;
};
}),
).pipe(Layer.provide(NodeSocket.layerWebSocketConstructor));
const proxyWebSocket = Effect.fn("DeviceHubProxy.proxyWebSocket")(function* (
request: HttpServerRequest.HttpServerRequest,
upstreamUrl: string,
protocols: ReadonlyArray<string> = [],
headers: Readonly<Record<string, string>> = {},
) {
const client = yield* request.upgrade;
const upstream = yield* Socket.makeWebSocket(upstreamUrl, {
openTimeout: "10 seconds",
...(protocols.length > 0 ? { protocols: [...protocols] } : {}),
...(Object.keys(headers).length > 0 ? { headers: { ...headers } } : {}),
}).pipe(Effect.provide(upstreamWebSocketConstructor));
yield* Effect.scoped(
Effect.gen(function* () {
const writeToClient = yield* client.writer;
const writeToUpstream = yield* upstream.writer;
return yield* Effect.raceFirst(
pumpFrames(upstream, writeToClient),
pumpFrames(client, writeToUpstream),
);
}),
).pipe(Effect.ignoreCause);
return HttpServerResponse.empty();
});
const pumpFrames =
/* Frame pumping runs continuously; a span per frame stream adds no diagnostic value. */
Effect.fnUntraced(function* (source: Socket.Socket, sink: Socket.Writer) {
const { pull } = yield* source.reader;
while (true) {
yield* sink.writeAll(yield* pull);
}
});
const proxyHttp = Effect.fn("DeviceHubProxy.proxyHttp")(function* (
request: HttpServerRequest.HttpServerRequest,
upstreamUrl: string,
extraHeaders: Readonly<Record<string, string>> = {},
) {
const httpClient = HttpClient.withScope(yield* HttpClient.HttpClient);
const method = request.method;
if (!HttpMethod.isHttpMethod(method)) {
return HttpServerResponse.text("Method Not Allowed", { status: 405 });
}
const upstreamRequest = HttpClientRequest.make(method)(upstreamUrl).pipe(
HttpClientRequest.setHeaders({
...forwardHeaders(request, new URL(upstreamUrl).origin),
...extraHeaders,
}),
method === "GET" || method === "HEAD"
? (self) => self
: // A bare stream body is sent as octet-stream; serve-sim refuses WebRTC
// offers that are not application/json.
HttpClientRequest.bodyStream(request.stream, {
contentType: request.headers["content-type"],
}),
);
const response = yield* httpClient.execute(upstreamRequest);
const headers: Record<string, string> = {};
for (const [name, value] of Object.entries(response.headers)) {
// A cookie from an upstream such as an Expo Simulators session's preview host would land on T3's origin.
if (
name === "content-encoding" ||
name === "transfer-encoding" ||
name === "connection" ||
name === "set-cookie"
) {
continue;
}
if (value !== undefined) headers[name] = value;
}
// Long-lived MJPEG and AVCC responses must not be buffered by compression.
headers["cache-control"] = "no-store, no-transform";
const body = headers["content-type"]?.startsWith("multipart/x-mixed-replace")
? repeatStillFrame(response.stream)
: response.stream;
return HttpServerResponse.stream(body, {
status: response.status,
headers,
...(headers["content-type"] ? { contentType: headers["content-type"] } : {}),
});
});
const handler = Effect.gen(function* () {
const request = yield* HttpServerRequest.HttpServerRequest;
const url = requestUrl(request);
if (Option.isNone(url)) {
return HttpServerResponse.text("Bad Request", { status: 400 });
}
const hubPath = url.value.pathname.slice(DeviceService.DEVICE_HUB_ROUTE_PREFIX.length) || "/";
const upgrade = isWebSocketUpgrade(request);
const matches = (paths: ReadonlyArray<RegExp>) => paths.some((pattern) => pattern.test(hubPath));
const allowed = upgrade
? matches(ALLOWED_WS_PATHS)
: matches(ALLOWED_PATHS) || matches(MUTABLE_PATHS);
if (!allowed) {
return HttpServerResponse.text("Not Found", { status: 404 });
}
const readOnly = request.method === "GET" || request.method === "HEAD";
if (!upgrade && !matches(readOnly ? ALLOWED_PATHS : MUTABLE_PATHS)) {
return HttpServerResponse.text("Method Not Allowed", { status: 405 });
}
const controlsDevice =
(upgrade && hubPath !== "/api/devices/ws") ||
(!readOnly && /\/api\/(stream-(mode|settings)|fold)$/.test(hubPath));
yield* authenticateMediaRequest(
controlsDevice ? AuthOrchestrationOperateScope : AuthOrchestrationReadScope,
);
const devices = yield* DeviceService.DeviceService;
const ready = yield* devices.currentReadiness(url.value.searchParams.get("hostId") ?? undefined);
if (!ready) {
return HttpServerResponse.text("Device hub is not running", { status: 503 });
}
// Consume the auth ticket here; never forward it to the hub.
const upstreamSearch = new URLSearchParams(url.value.search);
upstreamSearch.delete("wsTicket");
upstreamSearch.delete("hostId");
const search = upstreamSearch.size > 0 ? `?${upstreamSearch.toString()}` : "";
const screenshotDevice = upstreamSearch.get("device");
if (
screenshotDevice &&
["/vendor/serve-sim/api/screenshot", "/vendor/serve-emu/api/screenshot"].includes(hubPath)
) {
const { png } = yield* devices.screenshot({ hostId: ready.hostId, deviceId: screenshotDevice });
return HttpServerResponse.uint8Array(png, {
contentType: "image/png",
headers: { "cache-control": "no-store, no-transform" },
});
}
// Hosts with several upstreams (one per cloud session) route and authenticate requests themselves.
const routed = ready.upstream ? yield* ready.upstream(hubPath, upstreamSearch) : undefined;
if (routed === null) {
return HttpServerResponse.text("Not Found", { status: 404 });
}
const upstreamUrl = routed?.url ?? `${ready.hub.origin}${hubPath}${search}`;
if (upgrade) {
return yield* proxyWebSocket(
request,
upstreamUrl.replace(/^http/, "ws"),
routed?.protocols,
routed?.headers,
);
}
return yield* proxyHttp(request, upstreamUrl, routed?.headers);
});
export const layer = HttpRouter.add("*", `${DeviceService.DEVICE_HUB_ROUTE_PREFIX}/*`, handler);