@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

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