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

http.test.ts

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