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