Open History to see the last commit
1import { afterEach, describe, expect, it } from "vite-plus/test";
2import {
3 AuthOrchestrationReadScope,
4 AuthOrchestrationOperateScope,
5 AuthSessionId,
6 LOCAL_DEVICE_HOST_ID,
7 type AuthEnvironmentScope,
8} from "@t3tools/contracts";
9import * as Effect from "effect/Effect";
10import * as Layer from "effect/Layer";
11import { HttpClient, HttpClientResponse, HttpRouter } from "effect/http";
12import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
13import * as SessionStore from "../auth/SessionStore.ts";
14import type * as DeviceHost from "./DeviceHost.ts";
15import * as DeviceService from "./DeviceService.ts";
16import * as DeviceHubProxy from "./DeviceHubProxy.ts";
17
18const disposers: Array<() => Promise<void>> = [];
19afterEach(async () => {
20 for (const dispose of disposers.splice(0)) await dispose();
21});
22
23const fixture = (
24 scopes: ReadonlyArray<AuthEnvironmentScope>,
25 fail = false,
26 authError?: EnvironmentAuth.ServerAuthCredentialError | EnvironmentAuth.ServerAuthInternalError,
27 upstream?: DeviceHost.DeviceHostReady["upstream"],
28 stream?: ReadableStream<Uint8Array>,
29 invalidated?: Promise<void>,
30) => {
31 let finalized = 0;
32 const requests: string[] = [];
33 const screenshots: Array<Parameters<DeviceService.DeviceService["Service"]["screenshot"]>[0]> =
34 [];
35 const headers: Array<Readonly<Record<string, string>>> = [];
36 const unexpectedOperation = Effect.die("Unexpected device operation");
37 const client = HttpClient.make((request, _url, signal) =>
38 Effect.gen(function* () {
39 requests.push(request.url);
40 headers.push(request.headers);
41 signal.addEventListener("abort", () => {
42 finalized++;
43 });
44 if (fail) return yield* Effect.die(new Error("upstream failed"));
45 return HttpClientResponse.fromWeb(
46 request,
47 new Response(stream ?? "frame", {
48 headers: {
49 "set-cookie": "upstream=1",
50 "clear-site-data": '"*"',
51 "content-type": "text/html",
52 "content-security-policy": "script-src *",
53 },
54 }),
55 );
56 }),
57 );
58 const { handler, dispose } = HttpRouter.toWebHandler(
59 DeviceHubProxy.layer.pipe(
60 Layer.provideMerge(
61 Layer.mock(EnvironmentAuth.EnvironmentAuth)({
62 authenticateWebSocketUpgrade: () =>
63 authError
64 ? Effect.fail(authError)
65 : Effect.succeed({
66 sessionId: AuthSessionId.make("test"),
67 subject: "test",
68 method: "bearer-access-token",
69 scopes,
70 }),
71 }),
72 ),
73 Layer.provideMerge(
74 Layer.mock(DeviceService.DeviceService)({
75 currentReadiness: (hostId) =>
76 Effect.succeed({
77 hostId: hostId ?? LOCAL_DEVICE_HOST_ID,
78 nodePath: "node",
79 hub: { origin: "http://hub.test", token: "hub-token" },
80 devices: {
81 list: unexpectedOperation,
82 boot: () => unexpectedOperation,
83 attach: () => unexpectedOperation,
84 shutdown: () => unexpectedOperation,
85 screenshot: () => unexpectedOperation,
86 },
87 run: () => unexpectedOperation,
88 helpers: { serveSimAxSettings: null, serveSimCli: null },
89 ...(upstream ? { upstream } : {}),
90 }),
91 screenshot: (input) =>
92 Effect.sync(() => {
93 screenshots.push(input);
94 return {
95 device: {
96 hostId: input.hostId ?? LOCAL_DEVICE_HOST_ID,
97 id: input.deviceId,
98 platform: "ios",
99 name: "Phone",
100 version: "27.0",
101 booted: true,
102 physical: false,
103 },
104 png: new Uint8Array([137, 80, 78, 71]),
105 };
106 }),
107 }),
108 ),
109 Layer.provideMerge(Layer.succeed(HttpClient.HttpClient, client)),
110 Layer.provideMerge(
111 Layer.mock(SessionStore.SessionStore, {
112 cookieName: "test",
113 legacyCookieName: undefined,
114 awaitInvalidation: () => (invalidated ? Effect.promise(() => invalidated) : Effect.never),
115 }),
116 ),
117 ),
118 { disableLogger: true },
119 );
120 disposers.push(dispose);
121 return { handler, requests, screenshots, headers, finalized: () => finalized };
122};
123
124describe("device hub proxy", () => {
125 it("releases the upstream response after forwarding its body and strips tickets", async () => {
126 const { handler, requests, finalized } = fixture([AuthOrchestrationReadScope]);
127 const response = await handler(
128 new Request("http://t3.test/api/device-hub/api/devices?wsTicket=secret"),
129 );
130 expect(response.status).toBe(200);
131 expect(await response.text()).toBe("frame");
132 expect(response.headers.get("set-cookie")).toBeNull();
133 expect(response.headers.get("clear-site-data")).toBeNull();
134 // Opened as a page, a hub response gets an opaque origin and no script.
135 expect(response.headers.get("content-security-policy")).toBe("default-src 'none'; sandbox");
136 expect(response.headers.get("x-content-type-options")).toBe("nosniff");
137 expect(requests).toEqual(["http://hub.test/api/devices"]);
138 expect(finalized()).toBe(1);
139 });
140
141 it("stops an open HTTP stream and releases its upstream on session invalidation", async () => {
142 const invalidated = Promise.withResolvers<void>();
143 const stream = new ReadableStream<Uint8Array>({
144 start: (controller) => controller.enqueue(new Uint8Array([1])),
145 });
146 const { handler, finalized } = fixture(
147 [AuthOrchestrationReadScope],
148 false,
149 undefined,
150 undefined,
151 stream,
152 invalidated.promise,
153 );
154 const response = await handler(
155 new Request("http://t3.test/api/device-hub/vendor/serve-sim/helper/device/stream.avcc"),
156 );
157 expect(response.status).toBe(200);
158 const reader = response.body!.getReader();
159 expect(await reader.read()).toEqual({ done: false, value: new Uint8Array([1]) });
160 invalidated.resolve();
161 expect((await reader.read()).done).toBe(true);
162 expect(finalized()).toBe(1);
163 });
164
165 it.each(["/vendor/serve-sim/helper/ws", "/vendor/serve-emu/ws"])(
166 "rejects input socket %s for a read-only session",
167 async (path) => {
168 const { handler, requests } = fixture([AuthOrchestrationReadScope]);
169 const response = await handler(
170 new Request(`http://t3.test/api/device-hub${path}`, { headers: { upgrade: "websocket" } }),
171 );
172 expect(response.status).toBe(403);
173 expect(requests).toEqual([]);
174 },
175 );
176
177 it("requires operate scope for stream tuning", async () => {
178 const readOnly = fixture([AuthOrchestrationReadScope]);
179 const path = "http://t3.test/api/device-hub/vendor/serve-emu/api/stream-settings";
180 expect((await readOnly.handler(new Request(path, { method: "POST" }))).status).toBe(403);
181 const operator = fixture([AuthOrchestrationOperateScope]);
182 const response = await operator.handler(new Request(path, { method: "POST" }));
183 expect(response.status).toBe(200);
184 await response.text();
185 });
186
187 it("reads Android fold state but requires operate scope to change it", async () => {
188 const path = "http://t3.test/api/device-hub/vendor/serve-emu/api/fold?device=emulator-5554";
189 const reader = fixture([AuthOrchestrationReadScope]);
190 const read = await reader.handler(new Request(path));
191 expect(read.status).toBe(200);
192 await read.text();
193 expect(reader.requests).toEqual([
194 "http://hub.test/vendor/serve-emu/api/fold?device=emulator-5554",
195 ]);
196 const denied = await reader.handler(
197 new Request(path, { method: "POST", body: '{"posture":"closed"}' }),
198 );
199 expect(denied.status).toBe(403);
200 expect(reader.requests).toHaveLength(1);
201
202 const operator = fixture([AuthOrchestrationOperateScope]);
203 const changed = await operator.handler(
204 new Request(path, { method: "POST", body: '{"posture":"closed"}' }),
205 );
206 expect(changed.status).toBe(200);
207 await changed.text();
208 expect(operator.requests).toEqual([
209 "http://hub.test/vendor/serve-emu/api/fold?device=emulator-5554",
210 ]);
211 });
212
213 it("presents fold changes from an HTTPS client as same-origin hub requests", async () => {
214 const { handler, headers } = fixture([AuthOrchestrationOperateScope]);
215 const response = await handler(
216 new Request(
217 "https://relay.test/api/device-hub/vendor/serve-emu/api/fold?device=emulator-5554",
218 {
219 method: "POST",
220 headers: { origin: "https://relay.test", "x-forwarded-proto": "https" },
221 body: '{"posture":"opened"}',
222 },
223 ),
224 );
225 expect(response.status).toBe(200);
226 await response.text();
227 expect(headers).toHaveLength(1);
228 expect(headers[0]?.origin).toBe("http://hub.test");
229 expect(headers[0]?.authorization).toBe("Bearer hub-token");
230 expect(headers[0]).not.toHaveProperty("x-forwarded-proto");
231 });
232
233 it("lets a viewer negotiate a WebRTC stream with read scope", async () => {
234 const { handler, requests, headers } = fixture([AuthOrchestrationReadScope]);
235 const offer = await handler(
236 new Request("http://t3.test/api/device-hub/vendor/serve-sim/helper/udid-1/webrtc/offer", {
237 method: "POST",
238 headers: { "content-type": "application/json" },
239 body: '{"type":"offer"}',
240 }),
241 );
242 expect(offer.status).toBe(200);
243 await offer.text();
244 expect(requests).toEqual(["http://hub.test/vendor/serve-sim/helper/udid-1/webrtc/offer"]);
245 expect(headers[0]?.["content-type"]).toBe("application/json");
246 });
247
248 it("lets a viewer read Android stream capabilities and signal WebRTC with read scope", async () => {
249 const { handler, requests } = fixture([AuthOrchestrationReadScope]);
250 const hub = "http://t3.test/api/device-hub/vendor/serve-emu";
251 const api = await handler(new Request(`${hub}/api?device=session-1`));
252 expect(api.status).toBe(200);
253 await api.text();
254 for (const action of ["offer", "close"]) {
255 const signal = await handler(
256 new Request(`${hub}/webrtc/${action}?device=session-1`, {
257 method: "POST",
258 headers: { "content-type": "application/json" },
259 body: '{"sessionId":"viewer"}',
260 }),
261 );
262 expect(signal.status).toBe(200);
263 await signal.text();
264 }
265 expect(requests).toEqual([
266 "http://hub.test/vendor/serve-emu/api?device=session-1",
267 "http://hub.test/vendor/serve-emu/webrtc/offer?device=session-1",
268 "http://hub.test/vendor/serve-emu/webrtc/close?device=session-1",
269 ]);
270 expect((await handler(new Request(`${hub}/api`, { method: "POST" }))).status).toBe(405);
271 expect((await handler(new Request(`${hub}/webrtc/offer`))).status).toBe(405);
272 });
273
274 it("sends requests a host routes itself to its upstream with its credentials", async () => {
275 const { handler, requests, headers } = fixture(
276 [AuthOrchestrationReadScope],
277 false,
278 undefined,
279 (hubPath, search) =>
280 Effect.succeed(
281 hubPath === "/vendor/serve-sim/api"
282 ? {
283 url: `https://session.test${hubPath.slice("/vendor/serve-sim".length)}?${search}`,
284 headers: { authorization: "Bearer session-token" },
285 protocols: [],
286 }
287 : null,
288 ),
289 );
290 const routed = await handler(
291 new Request("http://t3.test/api/device-hub/vendor/serve-sim/api?device=udid-1&hostId=eas", {
292 headers: { authorization: "Bearer environment-token" },
293 }),
294 );
295 expect(routed.status).toBe(200);
296 expect(routed.headers.get("set-cookie")).toBeNull();
297 await routed.text();
298 expect(requests).toEqual(["https://session.test/api?device=udid-1"]);
299 expect(headers[0]?.authorization).toBe("Bearer session-token");
300 const unrouted = await handler(
301 new Request("http://t3.test/api/device-hub/vendor/serve-sim/helper/udid-2/stream.mjpeg"),
302 );
303 expect(unrouted.status).toBe(404);
304 expect(requests).toHaveLength(1);
305 });
306
307 it("never forwards the vendor shell endpoint", async () => {
308 const { handler, requests } = fixture([AuthOrchestrationOperateScope]);
309 expect(
310 (
311 await handler(
312 new Request("http://t3.test/api/device-hub/vendor/serve-sim/exec", { method: "POST" }),
313 )
314 ).status,
315 ).toBe(404);
316 expect(requests).toEqual([]);
317 });
318
319 it.each(["serve-sim", "serve-emu"])(
320 "captures %s screenshots through hosts with their own stream routing",
321 async (vendor) => {
322 const { handler, requests, screenshots } = fixture(
323 [AuthOrchestrationReadScope],
324 false,
325 undefined,
326 () => Effect.succeed(null),
327 );
328 const response = await handler(
329 new Request(
330 `http://t3.test/api/device-hub/vendor/${vendor}/api/screenshot?device=udid-1&hostId=pool`,
331 {
332 method: "POST",
333 },
334 ),
335 );
336 expect(response.status).toBe(200);
337 expect(response.headers.get("content-type")).toBe("image/png");
338 expect(new Uint8Array(await response.arrayBuffer())).toEqual(
339 new Uint8Array([137, 80, 78, 71]),
340 );
341 expect(requests).toEqual([]);
342 expect(screenshots).toEqual([{ hostId: "pool", deviceId: "udid-1" }]);
343 },
344 );
345});
346
347it.each([
348 [new EnvironmentAuth.ServerAuthMissingCredentialError({}), 401],
349 [
350 new EnvironmentAuth.ServerAuthSessionCredentialValidationError({
351 cause: new Error("private credential diagnostic"),
352 }),
353 500,
354 ],
355] as const)("translates authentication failure to HTTP %s", async (error, status) => {
356 const { handler, requests } = fixture([], false, error);
357 const response = await handler(new Request("http://t3.test/api/device-hub/api/devices"));
358 expect(response.status).toBe(status);
359 expect(await response.text()).not.toContain("private credential diagnostic");
360 expect(requests).toEqual([]);
361});
362
363it("rejects unsupported Duo routes", async () => {
364 const { handler, requests } = fixture([AuthOrchestrationReadScope]);
365 const response = await handler(
366 new Request("http://t3.test/api/device-hub/vendor/serve-sim/helper/duo/panel/1/webrtc/offer"),
367 );
368 expect(response.status).toBe(404);
369 expect(requests).toEqual([]);
370});