Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ServerBrowserStream.test.ts

436 lines16.8 KB

1import * as NodeHttpPlatform from "@effect/platform-node/NodeHttpPlatform";
2import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
3import * as NodeServices from "@effect/platform-node/NodeServices";
4import { expect, it } from "@effect/vitest";
5import {
6 AuthOrchestrationOperateScope,
7 AuthOrchestrationReadScope,
8 AuthPreviewOperateScope,
9 AuthSessionId,
10 PREVIEW_STREAM_HOST_SETUP_CLOSE_CODE,
11 PreviewStreamHostSetup,
12 type AuthEnvironmentScope,
13} from "@t3tools/contracts";
14import * as Context from "effect/Context";
15import * as Effect from "effect/Effect";
16import * as FileSystem from "effect/FileSystem";
17import * as Layer from "effect/Layer";
18import * as Option from "effect/Option";
19import * as Queue from "effect/Queue";
20import * as Schema from "effect/Schema";
21import { HttpRouter, HttpServer } from "effect/http";
22​
23import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
24import * as PreviewBrowserHost from "./PreviewBrowserHost.ts";
25import * as ServerBrowser from "./ServerBrowser.ts";
26import { routeLayer } from "./ServerBrowserStream.ts";
27​
28const platformLayer = NodeHttpPlatform.layer.pipe(Layer.provideMerge(NodeServices.layer));
29​
30const makeAuth = (
31 scopes: ReadonlyArray<AuthEnvironmentScope>,
32 error?: EnvironmentAuth.ServerAuthCredentialError,
33) => {
34 const requests: string[] = [];
35 const layer = Layer.mock(EnvironmentAuth.EnvironmentAuth, {
36 authenticateWebSocketUpgrade: (request) => {
37 requests.push(request.originalUrl);
38 return error
39 ? Effect.fail(error)
40 : Effect.succeed({
41 sessionId: AuthSessionId.make("stream-test"),
42 subject: "stream-test",
43 method: "bearer-access-token",
44 scopes,
45 });
46 },
47 });
48 return { layer, requests };
49};
50​
51const mutations = [
52 { type: "resize", width: 390, height: 844 },
53 { type: "mouse", action: "down", x: 10, y: 10, button: "left", buttons: 1 },
54 { type: "key", action: "down", key: "Enter" },
55 { type: "text", text: "reader must not type" },
56 { type: "wheel", deltaY: 100 },
57 { type: "navigate", url: "https://example.com" },
58 { type: "history", delta: -1 },
59 { type: "reload" },
60 { type: "probe", x: 10, y: 10 },
61 { type: "takeControl" },
62 { type: "releaseControl" },
63 { type: "dialog", accept: true },
64 { type: "viewport", setting: { _tag: "fill" } },
65];
66​
67it.effect.each([
68 { hasOperateScope: false, interactive: true },
69 { hasOperateScope: true, interactive: true },
70 { hasOperateScope: true, interactive: false },
71])("streams frames and acks while gating page mutations (%s)", ({ hasOperateScope, interactive }) =>
72 Effect.gen(function* () {
73 const canOperate = hasOperateScope && interactive;
74 const scopes = hasOperateScope
75 ? [AuthOrchestrationReadScope, AuthPreviewOperateScope]
76 : [AuthOrchestrationReadScope];
77 const auth = makeAuth(scopes);
78 const inputs: unknown[] = [];
79 const attachments: Parameters<ServerBrowser.ServerBrowser["Service"]["attachViewer"]>[0][] = [];
80 const acked = Promise.withResolvers<void>();
81 const frame = new Uint8Array([255, 216, 255, 217]);
82 const output = yield* Queue.make<ServerBrowser.ServerBrowserViewerOutput>();
83 yield* Queue.offer(output, { _tag: "viewport", width: 1280, height: 800 });
84 yield* Queue.offer(output, {
85 _tag: "frame",
86 data: frame,
87 ack: Effect.sync(() => acked.resolve()),
88 });
89 const browser = ServerBrowser.ServerBrowser.of({
90 clearProfile: () => Effect.void,
91 reportProfiles: () => Effect.void,
92 openDownload: () => Effect.succeedNone,
93 answerFileChooser: () => Effect.succeed(false),
94 attachViewer: (input) =>
95 Effect.sync(() => {
96 attachments.push(input);
97 return {
98 output,
99 input: (message) => Effect.sync(() => void inputs.push(message)),
100 };
101 }),
102 });
103 const services = yield* Layer.build(
104 HttpRouter.serve(
105 routeLayer.pipe(
106 Layer.provide(Layer.succeed(ServerBrowser.ServerBrowser, browser)),
107 Layer.provide(platformLayer),
108 ),
109 { disableListenLog: true },
110 ).pipe(Layer.provideMerge(NodeHttpServer.layerTest), Layer.provide(auth.layer)),
111 );
112 const server = Context.get(services, HttpServer.HttpServer);
113 const origin = HttpServer.formatAddress(server.address).replace(/^http/, "ws");
114 const resource = `/api/preview-stream/ws?threadId=thread&tabId=tab&wsTicket=one-use-ticket${interactive ? "" : "&interactive=false"}`;
115 const received = Promise.withResolvers<void>();
116 const socket = yield* Effect.acquireRelease(
117 Effect.sync(() => new WebSocket(`${origin}${resource}`)),
118 (socket) => Effect.sync(() => socket.close()),
119 );
120 socket.binaryType = "arraybuffer";
121 const viewports: unknown[] = [];
122 const frames: Uint8Array[] = [];
123 socket.addEventListener("error", () => received.reject(new Error("stream failed")));
124 socket.addEventListener("message", (event) => {
125 if (typeof event.data === "string") {
126 viewports.push(JSON.parse(event.data));
127 return;
128 }
129 frames.push(new Uint8Array(event.data as ArrayBuffer));
130 for (const message of mutations) socket.send(JSON.stringify(message));
131 socket.send("malformed input");
132 socket.send(JSON.stringify({ type: "ack" }));
133 received.resolve();
134 });
135 yield* Effect.promise(() => received.promise);
136 // The ack follows every mutation on the socket, so this is also a barrier
137 // proving all preceding inputs were processed, without a timing sleep.
138 yield* Effect.promise(() => acked.promise);
139 expect(frames).toEqual([frame]);
140 expect(viewports).toEqual([{ type: "viewport", width: 1280, height: 800 }]);
141 expect(inputs).toEqual(canOperate ? [...mutations, null] : []);
142 expect(attachments).toEqual([
143 {
144 threadId: "thread",
145 tabId: "tab",
146 maxWidth: 1280,
147 maxHeight: 800,
148 quality: 70,
149 canOperate,
150 },
151 ]);
152 expect(auth.requests).toEqual([resource]);
153 }).pipe(Effect.scoped),
154);
155​
156it.effect("sends replies ahead of stale frames and only the newest frame after an ack", () =>
157 Effect.gen(function* () {
158 const output = yield* Queue.make<ServerBrowser.ServerBrowserViewerOutput>();
159 const released: number[] = [];
160 const frame = (id: number): ServerBrowser.ServerBrowserViewerOutput => ({
161 _tag: "frame",
162 data: new Uint8Array([id]),
163 ack: Effect.sync(() => void released.push(id)),
164 });
165 const browser = ServerBrowser.ServerBrowser.of({
166 clearProfile: () => Effect.void,
167 reportProfiles: () => Effect.void,
168 openDownload: () => Effect.succeedNone,
169 answerFileChooser: () => Effect.succeed(false),
170 attachViewer: () => Effect.succeed({ output, input: () => Effect.void }),
171 });
172 const services = yield* Layer.build(
173 HttpRouter.serve(
174 routeLayer.pipe(
175 Layer.provide(Layer.succeed(ServerBrowser.ServerBrowser, browser)),
176 Layer.provide(platformLayer),
177 ),
178 { disableListenLog: true },
179 ).pipe(
180 Layer.provideMerge(NodeHttpServer.layerTest),
181 Layer.provide(makeAuth([AuthOrchestrationReadScope]).layer),
182 ),
183 );
184 const server = Context.get(services, HttpServer.HttpServer);
185 const origin = HttpServer.formatAddress(server.address).replace(/^http/, "ws");
186 const received: Array<number | string> = [];
187 let next = Promise.withResolvers<void>();
188 const socket = yield* Effect.acquireRelease(
189 Effect.sync(
190 () =>
191 new WebSocket(
192 `${origin}/api/preview-stream/ws?threadId=thread&tabId=tab&wsTicket=one-use-ticket`,
193 ),
194 ),
195 (socket) => Effect.sync(() => socket.close()),
196 );
197 socket.binaryType = "arraybuffer";
198 socket.addEventListener("message", (event) => {
199 received.push(
200 typeof event.data === "string"
201 ? JSON.parse(event.data).type
202 : new Uint8Array(event.data as ArrayBuffer)[0]!,
203 );
204 next.resolve();
205 });
206​
207 yield* Queue.offer(output, frame(1));
208 yield* Effect.promise(() => next.promise);
209 next = Promise.withResolvers();
210 yield* Queue.offerAll(output, [
211 frame(2),
212 frame(3),
213 frame(4),
214 { _tag: "probe", x: 0, y: 0, editable: false },
215 ]);
216 yield* Effect.promise(() => next.promise);
217 expect(received).toEqual([1, "probe"]);
218 // Frames 2 and 3 were superseded before they could be sent.
219 expect(released).toEqual([2, 3]);
220​
221 next = Promise.withResolvers();
222 socket.send(JSON.stringify({ type: "ack" }));
223 yield* Effect.promise(() => next.promise);
224 expect(received).toEqual([1, "probe", 4]);
225 expect(released).toEqual([2, 3, 1]);
226 }).pipe(Effect.scoped),
227);
228​
229it.effect.each([
230 { scopes: [], error: undefined, status: 403 },
231 { scopes: [AuthOrchestrationOperateScope], error: undefined, status: 403 },
232 { scopes: [], error: new EnvironmentAuth.ServerAuthMissingCredentialError({}), status: 401 },
233])("rejects unauthorized stream connections before attaching a viewer (%s)", (testCase) =>
234 Effect.gen(function* () {
235 const auth = makeAuth(testCase.scopes, testCase.error);
236 let attachments = 0;
237 const browser = ServerBrowser.ServerBrowser.of({
238 clearProfile: () => Effect.void,
239 reportProfiles: () => Effect.void,
240 openDownload: () => Effect.succeedNone,
241 answerFileChooser: () => Effect.succeed(false),
242 attachViewer: () => {
243 attachments++;
244 return Effect.die("unauthorized viewer must not attach");
245 },
246 });
247 const handler = yield* Effect.acquireRelease(
248 Effect.sync(() =>
249 HttpRouter.toWebHandler(
250 routeLayer.pipe(
251 Layer.provide(Layer.succeed(ServerBrowser.ServerBrowser, browser)),
252 Layer.provide(platformLayer),
253 Layer.provideMerge(auth.layer),
254 ),
255 { disableLogger: true },
256 ),
257 ),
258 ({ dispose }) => Effect.promise(dispose),
259 );
260 const response = yield* Effect.promise(() =>
261 handler.handler(
262 new Request("http://t3.test/api/preview-stream/ws?threadId=thread&tabId=tab", {
263 headers: { upgrade: "websocket" },
264 }),
265 ),
266 );
267 expect(response.status).toBe(testCase.status);
268 expect(attachments).toBe(0);
269 }).pipe(Effect.scoped),
270);
271​
272it.effect("serves a tab's download only to an authorized session", () =>
273 Effect.gen(function* () {
274 const fs = yield* FileSystem.FileSystem;
275 const path = `${yield* fs.makeTempDirectoryScoped({ prefix: "t3-download-" })}/file`;
276 yield* fs.writeFileString(path, "report contents");
277 const requests: Array<unknown> = [];
278 const browser = ServerBrowser.ServerBrowser.of({
279 clearProfile: () => Effect.void,
280 reportProfiles: () => Effect.void,
281 openDownload: (input) =>
282 Effect.sync(() => {
283 requests.push(input);
284 return input.downloadId === "download-1"
285 ? Option.some({ path, fileName: "Q3 report.csv" })
286 : Option.none();
287 }),
288 answerFileChooser: () => Effect.succeed(false),
289 attachViewer: () => Effect.die("unused"),
290 });
291 const serve = (scopes: ReadonlyArray<AuthEnvironmentScope>, url: string) =>
292 Effect.gen(function* () {
293 const handler = yield* Effect.acquireRelease(
294 Effect.sync(() =>
295 HttpRouter.toWebHandler(
296 routeLayer.pipe(
297 Layer.provide(Layer.succeed(ServerBrowser.ServerBrowser, browser)),
298 Layer.provide(platformLayer),
299 Layer.provideMerge(makeAuth(scopes, undefined).layer),
300 ),
301 { disableLogger: true },
302 ),
303 ),
304 ({ dispose }) => Effect.promise(dispose),
305 );
306 return yield* Effect.promise(() => handler.handler(new Request(url)));
307 });
308 const base = "http://t3.test/api/preview-stream/download?threadId=thread&tabId=tab";
309 const denied = yield* serve([], `${base}&id=download-1`);
310 expect(denied.status).toBe(403);
311 expect(requests).toEqual([]);
312 const response = yield* serve([AuthOrchestrationReadScope], `${base}&id=download-1`);
313 expect(response.status).toBe(200);
314 expect(response.headers.get("content-disposition")).toBe(
315 'attachment; filename="Q3 report.csv"',
316 );
317 expect(yield* Effect.promise(() => response.text())).toBe("report contents");
318 const missing = yield* serve([AuthOrchestrationReadScope], `${base}&id=other`);
319 expect(missing.status).toBe(404);
320 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
321);
322​
323it.effect("passes uploaded files to the page's open picker and needs operate scope", () =>
324 Effect.gen(function* () {
325 const answers: Array<{ chooserId: string; files: Array<{ name: string; text: string }> }> = [];
326 const browser = ServerBrowser.ServerBrowser.of({
327 clearProfile: () => Effect.void,
328 reportProfiles: () => Effect.void,
329 openDownload: () => Effect.succeedNone,
330 answerFileChooser: (input) =>
331 Effect.sync(() => {
332 answers.push({
333 chooserId: input.chooserId,
334 files: input.files.map((file) => ({ name: file.name, text: file.buffer.toString() })),
335 });
336 return input.chooserId === "chooser-1";
337 }),
338 attachViewer: () => Effect.die("unused"),
339 });
340 const upload = (scopes: ReadonlyArray<AuthEnvironmentScope>, chooser: string) =>
341 Effect.gen(function* () {
342 const handler = yield* Effect.acquireRelease(
343 Effect.sync(() =>
344 HttpRouter.toWebHandler(
345 routeLayer.pipe(
346 Layer.provide(Layer.succeed(ServerBrowser.ServerBrowser, browser)),
347 Layer.provide(platformLayer),
348 Layer.provideMerge(makeAuth(scopes, undefined).layer),
349 ),
350 { disableLogger: true },
351 ),
352 ),
353 ({ dispose }) => Effect.promise(dispose),
354 );
355 const body = new FormData();
356 body.append("file", new File(["hello"], "notes.txt", { type: "text/plain" }));
357 return yield* Effect.promise(() =>
358 handler.handler(
359 new Request(
360 `http://t3.test/api/preview-stream/upload?threadId=thread&tabId=tab&chooser=${chooser}`,
361 { method: "POST", body },
362 ),
363 ),
364 );
365 });
366 expect((yield* upload([AuthOrchestrationReadScope], "chooser-1")).status).toBe(403);
367 expect(answers).toEqual([]);
368 expect((yield* upload([AuthOrchestrationOperateScope], "chooser-1")).status).toBe(403);
369 expect((yield* upload([AuthPreviewOperateScope], "chooser-1")).status).toBe(204);
370 expect(answers).toEqual([
371 { chooserId: "chooser-1", files: [{ name: "notes.txt", text: "hello" }] },
372 ]);
373 expect((yield* upload([AuthPreviewOperateScope], "stale")).status).toBe(409);
374 }).pipe(Effect.scoped),
375);
376​
377const decodeHostSetup = Schema.decodeUnknownEffect(Schema.fromJsonString(PreviewStreamHostSetup));
378​
379it.effect.each([
380 {
381 error: new PreviewBrowserHost.PreviewBrowserSandboxError({
382 setupCommand: "sudo t3 browser setup",
383 }),
384 need: "sandbox",
385 },
386 {
387 error: new PreviewBrowserHost.PreviewBrowserLibrariesError({
388 setupCommand: "sudo t3 browser setup",
389 libraries: ["libnss3.so"],
390 }),
391 need: "libraries",
392 },
393])("tells viewers the command that sets up the host ($need)", ({ error, need }) =>
394 Effect.gen(function* () {
395 const browser = ServerBrowser.ServerBrowser.of({
396 clearProfile: () => Effect.void,
397 reportProfiles: () => Effect.void,
398 openDownload: () => Effect.succeedNone,
399 answerFileChooser: () => Effect.succeed(false),
400 attachViewer: () => Effect.fail(new ServerBrowser.ServerBrowserLaunchError({ cause: error })),
401 });
402 const services = yield* Layer.build(
403 HttpRouter.serve(
404 routeLayer.pipe(
405 Layer.provide(Layer.succeed(ServerBrowser.ServerBrowser, browser)),
406 Layer.provide(platformLayer),
407 ),
408 { disableListenLog: true },
409 ).pipe(
410 Layer.provideMerge(NodeHttpServer.layerTest),
411 Layer.provide(makeAuth([AuthOrchestrationReadScope]).layer),
412 ),
413 );
414 const server = Context.get(services, HttpServer.HttpServer);
415 const origin = HttpServer.formatAddress(server.address).replace(/^http/, "ws");
416 const closed = Promise.withResolvers<{ code: number; reason: string }>();
417 yield* Effect.acquireRelease(
418 Effect.sync(() => {
419 const socket = new WebSocket(
420 `${origin}/api/preview-stream/ws?threadId=thread&tabId=tab&wsTicket=one-use-ticket`,
421 );
422 socket.addEventListener("close", (event) =>
423 closed.resolve({ code: event.code, reason: event.reason }),
424 );
425 return socket;
426 }),
427 (socket) => Effect.sync(() => socket.close()),
428 );
429 const { code, reason } = yield* Effect.promise(() => closed.promise);
430 expect(code).toBe(PREVIEW_STREAM_HOST_SETUP_CLOSE_CODE);
431 expect(yield* decodeHostSetup(reason)).toEqual({
432 need,
433 command: "sudo t3 browser setup",
434 });
435 }).pipe(Effect.scoped),
436);