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