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

http.test.ts

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