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 DeviceService from "./DeviceService.ts";
14import * as DeviceHubProxy from "./DeviceHubProxy.ts";
15
16const disposers: Array<() => Promise<void>> = [];
17afterEach(async () => {
18 for (const dispose of disposers.splice(0)) await dispose();
19});
20
21const fixture = (
22 scopes: ReadonlyArray<AuthEnvironmentScope>,
23 fail = false,
24 authError?: EnvironmentAuth.ServerAuthCredentialError | EnvironmentAuth.ServerAuthInternalError,
25) => {
26 let finalized = 0;
27 const requests: string[] = [];
28 const headers: Array<Readonly<Record<string, string>>> = [];
29 const client = HttpClient.make((request, _url, signal) =>
30 Effect.gen(function* () {
31 requests.push(request.url);
32 headers.push(request.headers);
33 signal.addEventListener("abort", () => {
34 finalized++;
35 });
36 if (fail) return yield* Effect.die(new Error("upstream failed"));
37 return HttpClientResponse.fromWeb(request, new Response("frame"));
38 }),
39 );
40 const { handler, dispose } = HttpRouter.toWebHandler(
41 DeviceHubProxy.layer.pipe(
42 Layer.provideMerge(
43 Layer.succeed(EnvironmentAuth.EnvironmentAuth, {
44 authenticateWebSocketUpgrade: () =>
45 authError
46 ? Effect.fail(authError)
47 : Effect.succeed({
48 sessionId: AuthSessionId.make("test"),
49 subject: "test",
50 method: "bearer-access-token",
51 scopes,
52 }),
53 } as unknown as EnvironmentAuth.EnvironmentAuth["Service"]),
54 ),
55 Layer.provideMerge(
56 Layer.succeed(DeviceService.DeviceService, {
57 currentReadiness: () =>
58 Effect.succeed({ hostId: LOCAL_DEVICE_HOST_ID, hub: { origin: "http://hub.test" } }),
59 } as DeviceService.DeviceService["Service"]),
60 ),
61 Layer.provideMerge(Layer.succeed(HttpClient.HttpClient, client)),
62 ),
63 { disableLogger: true },
64 );
65 disposers.push(dispose);
66 return { handler, requests, headers, finalized: () => finalized };
67};
68
69describe("device hub proxy", () => {
70 it("releases the upstream response after forwarding its body and strips tickets", async () => {
71 const { handler, requests, finalized } = fixture([AuthOrchestrationReadScope]);
72 const response = await handler(
73 new Request("http://t3.test/api/device-hub/api/devices?wsTicket=secret"),
74 );
75 expect(response.status).toBe(200);
76 expect(await response.text()).toBe("frame");
77 expect(requests).toEqual(["http://hub.test/api/devices"]);
78 expect(finalized()).toBe(1);
79 });
80
81 it("releases resources when upstream acquisition fails", async () => {
82 const { handler, finalized } = fixture([AuthOrchestrationReadScope], true);
83 const response = await handler(new Request("http://t3.test/api/device-hub/api/devices"));
84 expect(response.status).toBe(500);
85 expect(finalized()).toBe(1);
86 });
87
88 it.each(["/vendor/serve-sim/helper/ws", "/vendor/serve-emu/ws"])(
89 "rejects input socket %s for a read-only session",
90 async (path) => {
91 const { handler, requests } = fixture([AuthOrchestrationReadScope]);
92 const response = await handler(
93 new Request(`http://t3.test/api/device-hub${path}`, { headers: { upgrade: "websocket" } }),
94 );
95 expect(response.status).toBe(403);
96 expect(requests).toEqual([]);
97 },
98 );
99
100 it("requires operate scope for stream tuning", async () => {
101 const readOnly = fixture([AuthOrchestrationReadScope]);
102 const path = "http://t3.test/api/device-hub/vendor/serve-emu/api/stream-settings";
103 expect((await readOnly.handler(new Request(path, { method: "POST" }))).status).toBe(403);
104 const operator = fixture([AuthOrchestrationOperateScope]);
105 const response = await operator.handler(new Request(path, { method: "POST" }));
106 expect(response.status).toBe(200);
107 await response.text();
108 });
109
110 it("reads Android fold state but requires operate scope to change it", async () => {
111 const path = "http://t3.test/api/device-hub/vendor/serve-emu/api/fold?device=emulator-5554";
112 const reader = fixture([AuthOrchestrationReadScope]);
113 const read = await reader.handler(new Request(path));
114 expect(read.status).toBe(200);
115 await read.text();
116 expect(reader.requests).toEqual([
117 "http://hub.test/vendor/serve-emu/api/fold?device=emulator-5554",
118 ]);
119 const denied = await reader.handler(
120 new Request(path, { method: "POST", body: '{"posture":"closed"}' }),
121 );
122 expect(denied.status).toBe(403);
123 expect(reader.requests).toHaveLength(1);
124
125 const operator = fixture([AuthOrchestrationOperateScope]);
126 const changed = await operator.handler(
127 new Request(path, { method: "POST", body: '{"posture":"closed"}' }),
128 );
129 expect(changed.status).toBe(200);
130 await changed.text();
131 expect(operator.requests).toEqual([
132 "http://hub.test/vendor/serve-emu/api/fold?device=emulator-5554",
133 ]);
134 });
135
136 it("presents fold changes from an HTTPS client as same-origin hub requests", async () => {
137 const { handler, headers } = fixture([AuthOrchestrationOperateScope]);
138 const response = await handler(
139 new Request(
140 "https://relay.test/api/device-hub/vendor/serve-emu/api/fold?device=emulator-5554",
141 {
142 method: "POST",
143 headers: { origin: "https://relay.test", "x-forwarded-proto": "https" },
144 body: '{"posture":"opened"}',
145 },
146 ),
147 );
148 expect(response.status).toBe(200);
149 await response.text();
150 expect(headers).toHaveLength(1);
151 expect(headers[0]?.origin).toBe("http://hub.test");
152 expect(headers[0]).not.toHaveProperty("x-forwarded-proto");
153 });
154
155 it("never forwards the vendor shell endpoint", async () => {
156 const { handler, requests } = fixture([AuthOrchestrationOperateScope]);
157 expect(
158 (
159 await handler(
160 new Request("http://t3.test/api/device-hub/vendor/serve-sim/exec", { method: "POST" }),
161 )
162 ).status,
163 ).toBe(404);
164 expect(requests).toEqual([]);
165 });
166});
167
168it.each([
169 [new EnvironmentAuth.ServerAuthMissingCredentialError({}), 401],
170 [
171 new EnvironmentAuth.ServerAuthSessionCredentialValidationError({
172 cause: new Error("private credential diagnostic"),
173 }),
174 500,
175 ],
176] as const)("translates authentication failure to HTTP %s", async (error, status) => {
177 const { handler, requests } = fixture([], false, error);
178 const response = await handler(new Request("http://t3.test/api/device-hub/api/devices"));
179 expect(response.status).toBe(status);
180 expect(await response.text()).not.toContain("private credential diagnostic");
181 expect(requests).toEqual([]);
182});
183
184it.each([1, 3])(
185 "forwards fixed Duo display %s through the authenticated read proxy",
186 async (panel) => {
187 const { handler, requests } = fixture([AuthOrchestrationReadScope]);
188 const route = `/vendor/serve-sim/helper/duo/panel/${panel}/stream.avcc`;
189 const response = await handler(
190 new Request(`http://t3.test/api/device-hub${route}?wsTicket=secret`),
191 );
192 expect(response.status).toBe(200);
193 await response.text();
194 expect(requests).toEqual([`http://hub.test${route}`]);
195 },
196);
197
198it.each(["/panel/2/stream.avcc", "/panel/1/webrtc/offer", "/panel/3/exec"])(
199 "rejects unsupported Duo route %s",
200 async (route) => {
201 const { handler, requests } = fixture([AuthOrchestrationReadScope]);
202 const response = await handler(
203 new Request(`http://t3.test/api/device-hub/vendor/serve-sim/helper/duo${route}`),
204 );
205 expect(response.status).toBe(404);
206 expect(requests).toEqual([]);
207 },
208);