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