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

http.test.ts

782 lines33.4 KB

1import { expect, it } from "@effect/vitest";
2import { describe, vi } from "vite-plus/test";
3import * as NodeHttpPlatform from "@effect/platform-node/NodeHttpPlatform";
4import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
5import * as NodeServices from "@effect/platform-node/NodeServices";
6import * as Context from "effect/Context";
7import * as DateTime from "effect/DateTime";
8import * as Deferred from "effect/Deferred";
9import * as Effect from "effect/Effect";
10import * as Fiber from "effect/Fiber";
11import * as FileSystem from "effect/FileSystem";
12import * as Layer from "effect/Layer";
13import * as Path from "effect/Path";
14import * as PlatformError from "effect/PlatformError";
15import * as Queue from "effect/Queue";
16import { HttpClient, HttpClientRequest, HttpRouter, HttpServerResponse } from "effect/http";
17import { openMediaFile } from "./assets/MediaFile.ts";
18​
19import {
20 injectMcpAppCsp,
21 injectMcpAppCookieBootstrap,
22 injectMcpAppThemeBootstrap,
23 MCP_APP_MAX_HTML_BYTES,
24} from "@t3tools/shared/mcpApp";
25import { ORCHESTRATION_PROTOCOL_HEADER } from "@t3tools/contracts";
26​
27import * as ServerConfig from "./config.ts";
28​
29import { assetResponseHeaders, assetFileResponse, downloadContentDisposition } from "./http.ts";
30import * as ServerHttp from "./http.ts";
31​
32describe("MCP app asset responses", () => {
33 it.effect(
34 "transforms existing snapshots only with explicit render intent and fresh metadata",
35 () =>
36 Effect.gen(function* () {
37 const fs = yield* FileSystem.FileSystem;
38 const path = yield* Path.Path;
39 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-mcp-theme-" });
40 const file = path.join(directory, "app.html");
41 const html = injectMcpAppCsp(
42 "<html><head><script>vendor()</script></head><body>☃</body></html>",
43 undefined,
44 );
45 yield* fs.writeFileString(file, html);
46 for (const method of ["GET", "HEAD"] as const) {
47 const response = HttpServerResponse.toWeb(
48 yield* assetFileResponse(
49 { path: file, mimeType: "text/html", renderIntent: "mcp-app" },
50 "bytes=0-1",
51 undefined,
52 method,
53 ),
54 );
55 const expected = injectMcpAppCookieBootstrap(injectMcpAppThemeBootstrap(html));
56 expect(response.status).toBe(200);
57 expect(response.headers.get("content-length")).toBe(
58 String(new TextEncoder().encode(expected).byteLength),
59 );
60 expect(response.headers.get("etag")).toBeNull();
61 expect(response.headers.get("last-modified")).toBeNull();
62 expect(response.headers.get("content-security-policy")).toBe(
63 "sandbox allow-scripts allow-forms allow-popups allow-downloads",
64 );
65 expect(yield* Effect.promise(() => response.text())).toBe(
66 method === "HEAD" ? "" : expected,
67 );
68 }
69 for (const download of [false, true]) {
70 const response = HttpServerResponse.toWeb(
71 yield* assetFileResponse({
72 path: file,
73 mimeType: "text/html",
74 download,
75 ...(download ? { renderIntent: "mcp-app" as const } : {}),
76 }),
77 );
78 expect(yield* Effect.promise(() => response.text())).toBe(html);
79 }
80 }).pipe(Effect.provide(layerFileResponse)),
81 );
82​
83 it.effect("rejects oversized captures before transforming them", () =>
84 Effect.gen(function* () {
85 const fs = yield* FileSystem.FileSystem;
86 const path = yield* Path.Path;
87 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-mcp-theme-size-" });
88 const file = path.join(directory, "app.html");
89 yield* fs.writeFileString(file, "x".repeat(MCP_APP_MAX_HTML_BYTES + 128 * 1024 + 1));
90 const response = yield* assetFileResponse({ path: file, renderIntent: "mcp-app" });
91 expect(response.status).toBe(413);
92 }).pipe(Effect.provide(layerFileResponse)),
93 );
94});
95​
96describe("browser API CORS", () => {
97 it("accepts protocol negotiation with authenticated browser headers", async () => {
98 const layerRoute = Layer.effectDiscard(
99 Effect.gen(function* () {
100 const router = yield* HttpRouter.HttpRouter;
101 yield* router.add("GET", "/api/environment", HttpServerResponse.empty());
102 }),
103 );
104 const layerApp = Layer.merge(layerRoute, ServerHttp.layerBrowserApiCors).pipe(
105 Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "http-cors-test-" })),
106 Layer.provide(NodeServices.layer),
107 );
108 const { handler, dispose } = HttpRouter.toWebHandler(layerApp, { disableLogger: true });
109​
110 try {
111 const response = await handler(
112 new Request("https://backend.example/api/environment", {
113 method: "OPTIONS",
114 headers: {
115 origin: "https://app.t3.codes",
116 "access-control-request-method": "GET",
117 "access-control-request-headers": [
118 ORCHESTRATION_PROTOCOL_HEADER,
119 "authorization",
120 "dpop",
121 ].join(", "),
122 },
123 }),
124 );
125​
126 expect(response.status).toBe(204);
127 expect(response.headers.get("access-control-allow-origin")).toBe("*");
128 const allowedHeaders = new Set(
129 (response.headers.get("access-control-allow-headers") ?? "")
130 .split(",")
131 .map((header) => header.trim().toLowerCase()),
132 );
133 expect(allowedHeaders.has(ORCHESTRATION_PROTOCOL_HEADER)).toBe(true);
134 expect(allowedHeaders.has("authorization")).toBe(true);
135 expect(allowedHeaders.has("dpop")).toBe(true);
136 } finally {
137 await dispose();
138 }
139 });
140});
141​
142const layerFileResponse = Layer.mergeAll(NodeHttpPlatform.layer, NodeServices.layer);
143​
144const makeStaticRequest = Effect.fn("HttpTest.makeStaticRequest")(function* (staticDir: string) {
145 const config = yield* ServerConfig.ServerConfig;
146 const fileSystem = yield* FileSystem.FileSystem;
147 const layerApp = Layer.merge(
148 ServerHttp.layerStaticAndDevRoute,
149 ServerHttp.layerHttpCompression,
150 ).pipe(Layer.provideMerge(NodeHttpPlatform.layer));
151 // HttpRouter.serve reuses services from the layers around it before the
152 // app's own, and NodeHttpServer.layerTest brings a real FileSystem, so the
153 // caller's FileSystem and static directory go between the two.
154 const services = yield* Layer.build(
155 HttpRouter.serve(layerApp, { disableListenLog: true }).pipe(
156 Layer.provideMerge(ServerConfig.layer({ ...config, staticDir })),
157 Layer.provideMerge(Layer.succeed(FileSystem.FileSystem, fileSystem)),
158 Layer.provideMerge(NodeHttpServer.layerTest),
159 ),
160 );
161 const client = Context.get(services, HttpClient.HttpClient);
162 return (resource: string, options?: HttpClientRequest.Options) =>
163 client.execute(HttpClientRequest.make(options?.method ?? "GET")(resource, options));
164});
165​
166it.layer(
167 ServerConfig.layerTest(process.cwd(), { prefix: "t3-static-http-test-" }).pipe(
168 Layer.provideMerge(NodeServices.layer),
169 ),
170)("static HTTP responses", (it) => {
171 it.effect("revalidates non-HTML files and returns changed contents", () =>
172 Effect.gen(function* () {
173 const fs = yield* FileSystem.FileSystem;
174 const path = yield* Path.Path;
175 const staticDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-static-cache-" });
176 const assetPath = path.join(staticDir, "app.js");
177 yield* fs.writeFileString(assetPath, 'export const build = "first";');
178 const request = yield* makeStaticRequest(staticDir);
179​
180 const initial = yield* request("/app.js");
181 expect(initial.status).toBe(200);
182 expect(yield* initial.text).toContain("first");
183 const etag = initial.headers["etag"]!;
184 const lastModified = initial.headers["last-modified"]!;
185 expect(etag).toBeTruthy();
186 expect(lastModified).toBeTruthy();
187 for (const headers of [
188 { "if-none-match": etag },
189 { "if-none-match": etag.replace(/^W\//, "") },
190 { "if-none-match": `"other", ${etag}` },
191 { "if-none-match": "*" },
192 { "if-modified-since": lastModified },
193 ]) {
194 const response = yield* request("/app.js", { headers });
195 expect(response.status).toBe(304);
196 expect(response.headers["etag"]).toBe(etag);
197 expect(response.headers["cache-control"]).toBe("no-cache");
198 expect(yield* response.text).toBe("");
199 }
200 const mismatched = yield* request("/app.js", {
201 headers: { "if-none-match": '"another-build"', "if-modified-since": lastModified },
202 });
203 expect(mismatched.status).toBe(200);
204 expect(yield* mismatched.text).toContain("first");
205​
206 yield* fs.writeFileString(assetPath, 'export const build = "the next build";');
207 const changed = yield* request("/app.js", { headers: { "if-none-match": etag } });
208 expect(changed.status).toBe(200);
209 expect(changed.headers["etag"]).not.toBe(etag);
210 expect(yield* changed.text).toContain("next build");
211 }),
212 );
213​
214 it.effect("serves static files without handles and skips fallback reads for HEAD and 304", () =>
215 Effect.gen(function* () {
216 const fs = yield* FileSystem.FileSystem;
217 const path = yield* Path.Path;
218 const staticDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-static-no-open-" });
219 const filePath = path.join(staticDir, "app.txt");
220 const body = "packaged asset";
221 yield* fs.writeFileString(filePath, body);
222 let reads = 0;
223 // Electron asar files can be statted and read even when opening a handle fails.
224 const fileSystem = FileSystem.FileSystem.of({
225 ...fs,
226 open: (candidate, options) =>
227 candidate === filePath
228 ? Effect.fail(
229 PlatformError.systemError({
230 _tag: "NotFound",
231 module: "FileSystem",
232 method: "open",
233 pathOrDescriptor: candidate,
234 }),
235 )
236 : fs.open(candidate, options),
237 readFile: (candidate) =>
238 Effect.gen(function* () {
239 if (candidate === filePath) reads += 1;
240 return yield* fs.readFile(candidate);
241 }),
242 });
243 const request = yield* makeStaticRequest(staticDir).pipe(
244 Effect.provideService(FileSystem.FileSystem, fileSystem),
245 );
246​
247 const get = yield* request("/app.txt");
248 expect(get.status).toBe(200);
249 expect(yield* get.text).toBe(body);
250 expect(reads).toBeGreaterThan(0);
251 const readsAfterGet = reads;
252 const head = yield* request("/app.txt", { method: "HEAD" });
253 expect(head.status).toBe(200);
254 expect(yield* head.text).toBe("");
255 expect(reads).toBe(readsAfterGet);
256 const unchanged = yield* request("/app.txt", {
257 headers: { "if-none-match": get.headers["etag"]! },
258 });
259 expect(unchanged.status).toBe(304);
260 expect(yield* unchanged.text).toBe("");
261 expect(reads).toBe(readsAfterGet);
262 }),
263 );
264​
265 it.effect("serves replacement bytes with matching static fallback length and validators", () =>
266 Effect.gen(function* () {
267 const fs = yield* FileSystem.FileSystem;
268 const path = yield* Path.Path;
269 const staticDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-static-replaced-" });
270 const filePath = path.join(staticDir, "app.txt");
271 const before = DateTime.toDateUtc(DateTime.makeUnsafe("1985-10-26T08:15:00.000Z"));
272 const after = DateTime.toDateUtc(DateTime.makeUnsafe("2015-10-21T16:29:00.000Z"));
273 const replacement = "the replacement asset";
274 const replacementPath = path.join(staticDir, "replacement.txt");
275 yield* fs.writeFileString(filePath, "old");
276 yield* fs.utimes(filePath, before, before);
277 yield* fs.writeFileString(replacementPath, replacement);
278 yield* fs.utimes(replacementPath, after, after);
279 let replaceOnOpen = false;
280 const fileSystem = FileSystem.FileSystem.of({
281 ...fs,
282 open: (candidate, options) =>
283 Effect.gen(function* () {
284 if (candidate !== filePath) return yield* fs.open(candidate, options);
285 if (replaceOnOpen) {
286 yield* fs.rename(replacementPath, filePath);
287 replaceOnOpen = false;
288 }
289 return yield* PlatformError.systemError({
290 _tag: "NotFound",
291 module: "FileSystem",
292 method: "open",
293 pathOrDescriptor: candidate,
294 });
295 }),
296 });
297 const request = yield* makeStaticRequest(staticDir).pipe(
298 Effect.provideService(FileSystem.FileSystem, fileSystem),
299 );
300 const initial = yield* request("/app.txt", { headers: { "accept-encoding": "identity" } });
301 expect(yield* initial.text).toBe("old");
302​
303 replaceOnOpen = true;
304 const response = yield* request("/app.txt", { headers: { "accept-encoding": "identity" } });
305 expect(response.status).toBe(200);
306 expect(response.headers).toMatchObject({
307 "content-length": String(Buffer.byteLength(replacement)),
308 "last-modified": after.toUTCString(),
309 });
310 expect(response.headers["etag"]).not.toBe(initial.headers["etag"]);
311 expect(yield* response.text).toBe(replacement);
312 }),
313 );
314​
315 it.effect("serves changed HTML when deployments preserve its size and timestamp", () =>
316 Effect.gen(function* () {
317 const fs = yield* FileSystem.FileSystem;
318 const path = yield* Path.Path;
319 const staticDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-static-html-" });
320 const indexPath = path.join(staticDir, "index.html");
321 const modifiedAt = DateTime.toDateUtc(DateTime.makeUnsafe("1985-10-26T08:15:00.000Z"));
322 yield* fs.writeFileString(indexPath, "<html>old build</html>");
323 yield* fs.utimes(indexPath, modifiedAt, modifiedAt);
324 const request = yield* makeStaticRequest(staticDir);
325 const initial = yield* request("/");
326 expect(yield* initial.text).toBe("<html>old build</html>");
327 const previousEtag = initial.headers["etag"] ?? '"previous-html"';
328 const nextHtml = "<html>new build</html>";
329 yield* fs.writeFileString(indexPath, nextHtml);
330 yield* fs.utimes(indexPath, modifiedAt, modifiedAt);
331​
332 for (const [resource, headers] of [
333 ["/", { "if-none-match": previousEtag }],
334 ["/threads/example", { "if-modified-since": modifiedAt.toUTCString() }],
335 ["/", { "if-none-match": "*" }],
336 ] as const) {
337 const response = yield* request(resource, { headers });
338 expect(response.status).toBe(200);
339 expect(yield* response.text).toBe(nextHtml);
340 expect(response.headers["cache-control"]).toBe("no-cache");
341 expect(response.headers["etag"]).toBeUndefined();
342 expect(response.headers["last-modified"]).toBeUndefined();
343 }
344 const head = yield* request("/", {
345 method: "HEAD",
346 headers: { "if-none-match": previousEtag, "accept-encoding": "identity" },
347 });
348 expect(head.status).toBe(200);
349 expect(head.headers["content-length"]).toBe(String(Buffer.byteLength(nextHtml)));
350 expect(yield* head.text).toBe("");
351 }),
352 );
353​
354 it.effect("closes static descriptors after GET, HEAD, 304, and request cancellation", () =>
355 Effect.gen(function* () {
356 const fs = yield* FileSystem.FileSystem;
357 const path = yield* Path.Path;
358 const staticDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-static-close-" });
359 const filePath = path.join(staticDir, "app.txt");
360 const body = "file content\n".repeat(1024);
361 yield* fs.writeFileString(filePath, body);
362 const closed = yield* Queue.unbounded<FileSystem.File>();
363 const blocked = yield* Deferred.make<void>();
364 const active = new Set<FileSystem.File>();
365 let blockAfterOpen = false;
366 let bodyReads = 0;
367 const trackedFileSystem = FileSystem.FileSystem.of({
368 ...fs,
369 open: (candidate, options) =>
370 Effect.gen(function* () {
371 if (candidate !== filePath) return yield* fs.open(candidate, options);
372 let opened: FileSystem.File | undefined;
373 yield* Effect.addFinalizer(() =>
374 Effect.gen(function* () {
375 if (opened === undefined) return;
376 active.delete(opened);
377 yield* Queue.offer(closed, opened);
378 }),
379 );
380 const file = yield* fs.open(candidate, options);
381 opened = file;
382 active.add(file);
383 if (blockAfterOpen) {
384 yield* Deferred.succeed(blocked, undefined);
385 return yield* Effect.never;
386 }
387 return new Proxy(file, {
388 get(target, key) {
389 if (key === "readAlloc") {
390 return (size: number) => {
391 bodyReads += 1;
392 return target.readAlloc(size);
393 };
394 }
395 return Reflect.get(target, key, target);
396 },
397 });
398 }),
399 });
400 const request = yield* makeStaticRequest(staticDir).pipe(
401 Effect.provideService(FileSystem.FileSystem, trackedFileSystem),
402 );
403​
404 const get = yield* request("/app.txt");
405 expect(yield* get.text).toBe(body);
406 yield* Queue.take(closed);
407 expect(active.size).toBe(0);
408 expect(bodyReads).toBeGreaterThan(0);
409 const readsAfterGet = bodyReads;
410 const head = yield* request("/app.txt", {
411 method: "HEAD",
412 headers: { "accept-encoding": "gzip" },
413 });
414 expect(head.status).toBe(200);
415 expect(head.headers["content-encoding"]).toBe("gzip");
416 expect(yield* head.text).toBe("");
417 yield* Queue.take(closed);
418 expect(active.size).toBe(0);
419 expect(bodyReads).toBe(readsAfterGet);
420 const unchanged = yield* request("/app.txt", {
421 headers: { "if-none-match": get.headers["etag"]! },
422 });
423 expect(unchanged.status).toBe(304);
424 yield* Queue.take(closed);
425 expect(active.size).toBe(0);
426 expect(bodyReads).toBe(readsAfterGet);
427​
428 blockAfterOpen = true;
429 const cancelled = yield* request("/app.txt").pipe(Effect.forkChild);
430 yield* Deferred.await(blocked);
431 expect(active.size).toBe(1);
432 yield* Fiber.interrupt(cancelled);
433 yield* Queue.take(closed);
434 expect(active.size).toBe(0);
435 }),
436 );
437});
438​
439describe("video asset byte ranges", () => {
440 it.effect("uses current descriptor metadata after an in-place truncate or extension", () =>
441 Effect.gen(function* () {
442 const fs = yield* FileSystem.FileSystem;
443 const path = yield* Path.Path;
444 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-guarded-current-stat-" });
445 const filePath = path.join(directory, "clip.mp4");
446 for (const [contents, range, method, expected, status, contentRange] of [
447 ["1234", undefined, "GET", "1234", 200, null],
448 ["0123456789abcdef", undefined, "GET", "0123456789abcdef", 200, null],
449 ["1234", "bytes=4-", "GET", "", 416, "bytes */4"],
450 ["1234", "bytes=1-20", "GET", "234", 206, "bytes 1-3/4"],
451 ["0123456789abcdef", "bytes=10-", "GET", "abcdef", 206, "bytes 10-15/16"],
452 ["0123456789abcdef", undefined, "HEAD", "", 200, null],
453 ["", undefined, "GET", "", 200, null],
454 ["", "bytes=0-1", "GET", "", 416, "bytes */0"],
455 ] as const) {
456 yield* fs.writeFileString(filePath, "0123456789");
457 const canonicalPath = yield* fs.realPath(filePath);
458 const file = yield* openMediaFile(canonicalPath);
459 if (!file) throw new Error("Expected an opened media file");
460 yield* fs.writeFileString(filePath, contents);
461 const response = HttpServerResponse.toWeb(
462 yield* assetFileResponse(
463 { path: canonicalPath, file, mimeType: "video/mp4" },
464 range,
465 undefined,
466 method,
467 ),
468 );
469 expect(response.status).toBe(status);
470 expect(response.headers.get("content-range")).toBe(contentRange);
471 if (status !== 416) {
472 expect(response.headers.get("content-length")).toBe(
473 String(method === "HEAD" ? contents.length : expected.length),
474 );
475 }
476 expect(yield* Effect.promise(() => response.text())).toBe(expected);
477 }
478 }).pipe(Effect.provide(layerFileResponse)),
479 );
480​
481 it.effect(
482 "rejects unaddressable ranges before streaming and preserves small ranges on large files",
483 () =>
484 Effect.gen(function* () {
485 const fs = yield* FileSystem.FileSystem;
486 const path = yield* Path.Path;
487 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-guarded-offset-limit-" });
488 const filePath = path.join(directory, "clip.mp4");
489 yield* fs.writeFileString(filePath, "0123456789");
490 const canonicalPath = yield* fs.realPath(filePath);
491 const unsafeOffset = BigInt(Number.MAX_SAFE_INTEGER) + 1n;
492 const size = unsafeOffset + 32n;
493 for (const [range, status] of [
494 [`bytes=${unsafeOffset}-${unsafeOffset}`, 416],
495 [`bytes=0-${unsafeOffset}`, 416],
496 ["bytes=-1", 416],
497 [undefined, 413],
498 ["bytes=0-1", 206],
499 ] as const) {
500 const file = yield* openMediaFile(canonicalPath);
501 if (!file) throw new Error("Expected an opened media file");
502 const info = yield* Effect.promise(() => file.handle.stat({ bigint: true }));
503 info.size = size;
504 const statSpy = vi.spyOn(file.handle, "stat").mockResolvedValue(info);
505 yield* Effect.addFinalizer(() => Effect.sync(() => statSpy.mockRestore()));
506 const response = HttpServerResponse.toWeb(
507 yield* assetFileResponse({ path: canonicalPath, file, mimeType: "video/mp4" }, range),
508 );
509 expect(response.status).toBe(status);
510 if (status === 416) {
511 expect(response.headers.get("content-range")).toBe(`bytes */${size}`);
512 expect(yield* Effect.promise(() => response.text())).toBe("");
513 } else if (status === 206) {
514 expect(response.headers.get("content-range")).toBe(`bytes 0-1/${size}`);
515 expect(yield* Effect.promise(() => response.text())).toBe("01");
516 } else {
517 expect(yield* Effect.promise(() => response.text())).toBe(
518 "File is too large to preview.",
519 );
520 }
521 }
522 }).pipe(Effect.provide(layerFileResponse)),
523 );
524​
525 it.effect("keeps attachment media out of the cache once its signed URL expires", () =>
526 Effect.gen(function* () {
527 const fs = yield* FileSystem.FileSystem;
528 const path = yield* Path.Path;
529 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-attachment-media-" });
530 const filePath = path.join(directory, "audio.wav");
531 yield* fs.writeFileString(filePath, "RIFF");
532 const canonicalPath = yield* fs.realPath(filePath);
533 const response = HttpServerResponse.toWeb(
534 yield* assetFileResponse({ path: canonicalPath, mimeType: "audio/wav" }),
535 );
536 expect(response.headers.get("cache-control")).toBe("private, no-store");
537 expect(response.headers.get("accept-ranges")).toBe("bytes");
538 }).pipe(Effect.provide(layerFileResponse)),
539 );
540​
541 it.effect("closes guarded descriptors after full, HEAD, rejected, and cancelled responses", () =>
542 Effect.gen(function* () {
543 const fs = yield* FileSystem.FileSystem;
544 const path = yield* Path.Path;
545 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-guarded-cleanup-" });
546 const filePath = path.join(directory, "clip.mp4");
547 const bytes = new Uint8Array(1024 * 1024).fill(42);
548 yield* fs.writeFile(filePath, bytes);
549 const canonicalPath = yield* fs.realPath(filePath);
550 for (const mode of ["full", "HEAD", "rejected", "cancelled"] as const) {
551 const file = yield* Effect.scoped(
552 Effect.gen(function* () {
553 const file = yield* openMediaFile(canonicalPath);
554 if (!file) throw new Error("Expected an opened media file");
555 const response = HttpServerResponse.toWeb(
556 yield* assetFileResponse(
557 { path: canonicalPath, file, mimeType: "video/mp4" },
558 mode === "rejected" ? `bytes=${bytes.length}-` : "bytes=0-",
559 undefined,
560 mode === "HEAD" ? "HEAD" : "GET",
561 ),
562 );
563 if (mode === "HEAD") {
564 expect(response.status).toBe(200);
565 expect(response.headers.get("content-length")).toBe(String(bytes.length));
566 expect(response.headers.get("content-range")).toBeNull();
567 expect(yield* Effect.promise(() => response.text())).toBe("");
568 } else if (mode === "rejected") {
569 expect(response.status).toBe(416);
570 expect(yield* Effect.promise(() => response.text())).toBe("");
571 } else if (mode === "cancelled") {
572 const reader = response.body!.getReader();
573 const first = yield* Effect.promise(() => reader.read());
574 expect(first.done).toBe(false);
575 expect(first.value!.byteLength).toBeLessThan(bytes.length);
576 yield* Effect.promise(() => reader.cancel());
577 } else {
578 expect(yield* Effect.promise(() => response.arrayBuffer())).toEqual(bytes.buffer);
579 }
580 return file;
581 }),
582 );
583 expect(file.handle.fd).toBe(-1);
584 }
585 }).pipe(Effect.provide(layerFileResponse)),
586 );
587​
588 it.effect("streams exactly the requested bytes and leaves full downloads intact", () =>
589 Effect.gen(function* () {
590 const fs = yield* FileSystem.FileSystem;
591 const path = yield* Path.Path;
592 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-video-range-" });
593 const file = path.join(directory, "clip.mp4");
594 yield* fs.writeFileString(file, "0123456789");
595 const asset = { path: file, mimeType: "video/mp4" };
596 for (const [header, expected, contentRange] of [
597 ["bytes=0-1", "01", "bytes 0-1/10"],
598 ["bytes=4-", "456789", "bytes 4-9/10"],
599 ["bytes=-3", "789", "bytes 7-9/10"],
600 ["bytes=-999999999999999999999999", "0123456789", "bytes 0-9/10"],
601 ["bytes=8-999999999999999999999999", "89", "bytes 8-9/10"],
602 ] as const) {
603 const response = HttpServerResponse.toWeb(yield* assetFileResponse(asset, header));
604 expect(response.status).toBe(206);
605 expect(response.headers.get("accept-ranges")).toBe("bytes");
606 expect(response.headers.get("content-range")).toBe(contentRange);
607 expect(response.headers.get("content-length")).toBe(String(expected.length));
608 expect(yield* Effect.promise(() => response.text())).toBe(expected);
609 }
610 for (const header of [
611 undefined,
612 "items=0-1",
613 "bytes=0-1,4-5",
614 "bytes=8-2",
615 "bytes=-",
616 "bytes=bad",
617 ]) {
618 const response = HttpServerResponse.toWeb(yield* assetFileResponse(asset, header));
619 expect(response.status).toBe(200);
620 expect(yield* Effect.promise(() => response.text())).toBe("0123456789");
621 }
622 const conditional = HttpServerResponse.toWeb(
623 yield* assetFileResponse(asset, "bytes=0-1", '"old-etag"'),
624 );
625 expect(conditional.status).toBe(200);
626 expect(yield* Effect.promise(() => conditional.text())).toBe("0123456789");
627 const uppercase = HttpServerResponse.toWeb(
628 yield* assetFileResponse({ ...asset, mimeType: "Video/MP4" }, "bytes=0-1"),
629 );
630 expect(uppercase.status).toBe(206);
631 expect(yield* Effect.promise(() => uppercase.text())).toBe("01");
632 const image = HttpServerResponse.toWeb(
633 yield* assetFileResponse({ path: file, mimeType: "image/png" }, "bytes=0-1"),
634 );
635 expect(image.status).toBe(200);
636 expect(image.headers.has("accept-ranges")).toBe(false);
637 expect(yield* Effect.promise(() => image.text())).toBe("0123456789");
638 }).pipe(Effect.provide(layerFileResponse)),
639 );
640​
641 it.effect(
642 "supports native audio header probes and seeking without changing explicit downloads",
643 () =>
644 Effect.gen(function* () {
645 const fs = yield* FileSystem.FileSystem;
646 const path = yield* Path.Path;
647 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-audio-range-" });
648 const file = path.join(directory, "recording.wav");
649 yield* fs.writeFileString(file, "0123456789");
650 const asset = { path: file, mimeType: "audio/wav" };
651 for (const [header, expected] of [
652 ["bytes=0-1", "01"],
653 ["bytes=5-", "56789"],
654 ] as const) {
655 const response = HttpServerResponse.toWeb(yield* assetFileResponse(asset, header));
656 expect(response.status).toBe(206);
657 expect(response.headers.get("content-type")).toBe("audio/wav");
658 expect(response.headers.get("accept-ranges")).toBe("bytes");
659 expect(response.headers.get("content-length")).toBe(String(expected.length));
660 expect(yield* Effect.promise(() => response.text())).toBe(expected);
661 }
662 const download = HttpServerResponse.toWeb(
663 yield* assetFileResponse({ ...asset, download: true, fileName: "recording.wav" }),
664 );
665 expect(download.status).toBe(200);
666 expect(download.headers.get("content-disposition")).toContain("attachment;");
667 expect(yield* Effect.promise(() => download.text())).toBe("0123456789");
668 }).pipe(Effect.provide(layerFileResponse)),
669 );
670​
671 it.effect("rejects ranges outside the file, including empty files", () =>
672 Effect.gen(function* () {
673 const fs = yield* FileSystem.FileSystem;
674 const path = yield* Path.Path;
675 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-video-range-" });
676 const file = path.join(directory, "clip.mp4");
677 yield* fs.writeFileString(file, "0123456789");
678 for (const header of ["bytes=10-", "bytes=-0", "bytes=999999999999999999999999-"]) {
679 const response = HttpServerResponse.toWeb(
680 yield* assetFileResponse({ path: file, mimeType: "video/mp4" }, header),
681 );
682 expect(response.status).toBe(416);
683 expect(response.headers.get("content-range")).toBe("bytes */10");
684 expect(yield* Effect.promise(() => response.text())).toBe("");
685 }
686 yield* fs.writeFileString(file, "");
687 const empty = HttpServerResponse.toWeb(
688 yield* assetFileResponse({ path: file, mimeType: "video/mp4" }, "bytes=0-1"),
689 );
690 expect(empty.status).toBe(416);
691 expect(empty.headers.get("content-range")).toBe("bytes */0");
692 }).pipe(Effect.provide(layerFileResponse)),
693 );
694});
695​
696describe("assetResponseHeaders", () => {
697 it("sandboxes SVG assets", () => {
698 expect(assetResponseHeaders("/attachments/user-image.svg")).toMatchObject({
699 "Content-Security-Policy": "default-src 'none'; style-src 'unsafe-inline'; sandbox",
700 "X-Content-Type-Options": "nosniff",
701 });
702 expect(assetResponseHeaders("/attachments/user-image.SVG")).toHaveProperty(
703 "Content-Security-Policy",
704 );
705 });
706 it("serves inline attachment documents with their declared mime type", () => {
707 expect(
708 assetResponseHeaders("/attachments/upload.bin", { mimeType: "application/pdf" }),
709 ).toMatchObject({
710 "Content-Type": "application/pdf",
711 });
712 expect(
713 assetResponseHeaders("/attachments/upload.bin", { mimeType: "text/html" }),
714 ).toMatchObject({
715 "Content-Type": "text/html; charset=utf-8",
716 "Content-Security-Policy": "sandbox allow-scripts allow-forms allow-popups allow-downloads",
717 });
718 });
719​
720 it("downloads uploaded documents without executing their content", () => {
721 expect(assetResponseHeaders("/attachments/upload.html", { download: true })).toMatchObject({
722 "Content-Disposition": "attachment",
723 "Content-Security-Policy": "default-src 'none'; sandbox",
724 "Content-Type": "application/octet-stream",
725 });
726 });
727​
728 it("serves the real filename and mime type when the claims carry them", () => {
729 expect(
730 assetResponseHeaders("/attachments/thread-1-abc-pdf.pdf", {
731 download: true,
732 fileName: "Q3 report.pdf",
733 mimeType: "application/pdf",
734 }),
735 ).toMatchObject({
736 "Content-Disposition": 'attachment; filename="Q3 report.pdf"',
737 "Content-Security-Policy": "default-src 'none'; sandbox",
738 "Content-Type": "application/pdf",
739 });
740 });
741​
742 it("keeps renderable mime types as octet-stream downloads", () => {
743 for (const mimeType of [
744 "text/html",
745 "text/xml",
746 "image/svg+xml",
747 "application/xhtml+xml",
748 "application/rss+xml",
749 "APPLICATION/XML",
750 "IMAGE/SVG+XML",
751 "application/xml-dtd",
752 "application/xml-external-parsed-entity",
753 "not a mime",
754 ]) {
755 expect(
756 assetResponseHeaders("/attachments/upload.bin", { download: true, mimeType }),
757 ).toHaveProperty("Content-Type", "application/octet-stream");
758 }
759 });
760});
761​
762describe("downloadContentDisposition", () => {
763 it("quotes plain names and strips quotes and control characters", () => {
764 expect(downloadContentDisposition("report.pdf")).toBe('attachment; filename="report.pdf"');
765 expect(downloadContentDisposition('we"ird\n.pdf')).toBe('attachment; filename="we_ird_.pdf"');
766 });
767​
768 it("adds an RFC 5987 encoded name for non-ASCII filenames", () => {
769 expect(downloadContentDisposition("répört.pdf")).toBe(
770 `attachment; filename="r_p_rt.pdf"; filename*=UTF-8''r%C3%A9p%C3%B6rt.pdf`,
771 );
772 expect(downloadContentDisposition("résumé'(*).pdf")).toBe(
773 `attachment; filename="r_sum_'(*).pdf"; filename*=UTF-8''r%C3%A9sum%C3%A9%27%28%2A%29.pdf`,
774 );
775 });
776​
777 it("does not throw on unpaired surrogates in the filename", () => {
778 expect(downloadContentDisposition("bad\ud800name.pdf")).toBe(
779 `attachment; filename="bad_name.pdf"; filename*=UTF-8''bad%EF%BF%BDname.pdf`,
780 );
781 });
782});