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

http.test.ts

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