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

http.test.ts

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