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

http.test.ts

899 lines38.4 KB

1import { expect, it } from "@effect/vitest";
2import { describe, vi } from "vite-plus/test";
3import * as NodeZlib from "node:zlib";
4import * as NodeHttpPlatform from "@effect/platform-node/NodeHttpPlatform";
5import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
6import * as NodeServices from "@effect/platform-node/NodeServices";
7import * as Context from "effect/Context";
8import * as DateTime from "effect/DateTime";
9import * as Deferred from "effect/Deferred";
10import * as Effect from "effect/Effect";
11import * as Fiber from "effect/Fiber";
12import * as FileSystem from "effect/FileSystem";
13import * as Layer from "effect/Layer";
14import * as Path from "effect/Path";
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("serves precompressed manifest assets and revalidates other files", () =>
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-compressed-" });
223 yield* fs.makeDirectory(path.join(staticDir, "assets"));
224 const body = 'export const build = "precompressed";\n'.repeat(100);
225 const asset = "assets/app-1234abcd.js";
226 const br = NodeZlib.brotliCompressSync(body);
227 const gz = NodeZlib.gzipSync(body);
228 yield* fs.writeFileString(path.join(staticDir, asset), body);
229 yield* fs.writeFile(path.join(staticDir, `${asset}.br`), br);
230 yield* fs.writeFile(path.join(staticDir, `${asset}.gz`), gz);
231 yield* fs.writeFileString(
232 path.join(staticDir, "vite-manifest.json"),
233 JSON.stringify({ "src/app.ts": { file: asset, isEntry: true } }),
234 );
235 // A hash-like filename and a compressed copy alone cannot make a custom file immutable.
236 const custom = "assets/custom-1234abcd.js";
237 yield* fs.writeFileString(path.join(staticDir, custom), body);
238 yield* fs.writeFile(path.join(staticDir, `${custom}.br`), br);
239 const request = yield* makeStaticRequest(staticDir);
240​
241 for (const [acceptEncoding, encoding, length] of [
242 ["br, gzip", "br", br.byteLength],
243 ["br;q=0, gzip", "gzip", gz.byteLength],
244 ["identity", undefined, Buffer.byteLength(body)],
245 ] as const) {
246 const response = yield* request(`/${asset}`, {
247 headers: { "accept-encoding": acceptEncoding },
248 });
249 expect(response.status).toBe(200);
250 expect(response.headers["content-encoding"]).toBe(encoding);
251 expect(response.headers["content-length"]).toBe(String(length));
252 expect(response.headers["content-type"]).toContain("javascript");
253 expect(response.headers["cache-control"]).toBe("public, max-age=31536000, immutable");
254 expect(response.headers["vary"]).toBe("Accept-Encoding");
255 expect(yield* response.text).toBe(body);
256 const head = yield* request(`/${asset}`, {
257 method: "HEAD",
258 headers: { "accept-encoding": acceptEncoding },
259 });
260 expect(head.headers["content-encoding"]).toBe(encoding);
261 expect(head.headers["content-length"]).toBe(String(length));
262 expect(yield* head.text).toBe("");
263 const unchanged = yield* request(`/${asset}`, {
264 headers: {
265 "accept-encoding": acceptEncoding,
266 "if-none-match": response.headers["etag"]!,
267 },
268 });
269 expect(unchanged.status).toBe(304);
270 expect(unchanged.headers["vary"]).toBe("Accept-Encoding");
271 expect(yield* unchanged.text).toBe("");
272 }
273 const unlisted = yield* request(`/${custom}`, { headers: { "accept-encoding": "br" } });
274 expect(unlisted.headers["cache-control"]).toBe("no-cache");
275 expect(unlisted.headers["content-length"]).toBeUndefined();
276 expect(yield* unlisted.text).toBe(body);
277​
278 yield* fs.remove(path.join(staticDir, `${asset}.br`));
279 const fallback = yield* request(`/${asset}`, { headers: { "accept-encoding": "br, gzip" } });
280 expect(fallback.headers["content-encoding"]).toBe("gzip");
281 expect(fallback.headers["content-length"]).toBe(String(gz.byteLength));
282 expect(yield* fallback.text).toBe(body);
283 }),
284 );
285​
286 it.effect("revalidates non-HTML files and returns changed contents", () =>
287 Effect.gen(function* () {
288 const fs = yield* FileSystem.FileSystem;
289 const path = yield* Path.Path;
290 const staticDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-static-cache-" });
291 const assetPath = path.join(staticDir, "app.js");
292 yield* fs.writeFileString(assetPath, 'export const build = "first";');
293 const request = yield* makeStaticRequest(staticDir);
294​
295 const initial = yield* request("/app.js");
296 expect(initial.status).toBe(200);
297 expect(yield* initial.text).toContain("first");
298 const etag = initial.headers["etag"]!;
299 const lastModified = initial.headers["last-modified"]!;
300 expect(etag).toBeTruthy();
301 expect(lastModified).toBeTruthy();
302 for (const headers of [
303 { "if-none-match": etag },
304 { "if-none-match": etag.replace(/^W\//, "") },
305 { "if-none-match": `"other", ${etag}` },
306 { "if-none-match": "*" },
307 { "if-modified-since": lastModified },
308 ]) {
309 const response = yield* request("/app.js", { headers });
310 expect(response.status).toBe(304);
311 expect(response.headers["etag"]).toBe(etag);
312 expect(response.headers["cache-control"]).toBe("no-cache");
313 expect(yield* response.text).toBe("");
314 }
315 const mismatched = yield* request("/app.js", {
316 headers: { "if-none-match": '"another-build"', "if-modified-since": lastModified },
317 });
318 expect(mismatched.status).toBe(200);
319 expect(yield* mismatched.text).toContain("first");
320​
321 yield* fs.writeFileString(assetPath, 'export const build = "the next build";');
322 const changed = yield* request("/app.js", { headers: { "if-none-match": etag } });
323 expect(changed.status).toBe(200);
324 expect(changed.headers["etag"]).not.toBe(etag);
325 expect(yield* changed.text).toContain("next build");
326 }),
327 );
328​
329 it.effect("serves changed HTML when deployments preserve its size and timestamp", () =>
330 Effect.gen(function* () {
331 const fs = yield* FileSystem.FileSystem;
332 const path = yield* Path.Path;
333 const staticDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-static-html-" });
334 const indexPath = path.join(staticDir, "index.html");
335 const modifiedAt = DateTime.toDateUtc(DateTime.makeUnsafe("1985-10-26T08:15:00.000Z"));
336 yield* fs.writeFileString(indexPath, "<html>old build</html>");
337 yield* fs.utimes(indexPath, modifiedAt, modifiedAt);
338 const request = yield* makeStaticRequest(staticDir);
339 const initial = yield* request("/");
340 expect(yield* initial.text).toBe("<html>old build</html>");
341 const previousEtag = initial.headers["etag"] ?? '"previous-html"';
342 const nextHtml = "<html>new build</html>";
343 yield* fs.writeFileString(indexPath, nextHtml);
344 yield* fs.utimes(indexPath, modifiedAt, modifiedAt);
345​
346 for (const [resource, headers] of [
347 ["/", { "if-none-match": previousEtag }],
348 ["/threads/example", { "if-modified-since": modifiedAt.toUTCString() }],
349 ["/", { "if-none-match": "*" }],
350 ] as const) {
351 const response = yield* request(resource, { headers });
352 expect(response.status).toBe(200);
353 expect(yield* response.text).toBe(nextHtml);
354 expect(response.headers["cache-control"]).toBe("no-cache");
355 expect(response.headers["etag"]).toBeUndefined();
356 expect(response.headers["last-modified"]).toBeUndefined();
357 }
358 const head = yield* request("/", {
359 method: "HEAD",
360 headers: { "if-none-match": previousEtag, "accept-encoding": "identity" },
361 });
362 expect(head.status).toBe(200);
363 expect(head.headers["content-length"]).toBe(String(Buffer.byteLength(nextHtml)));
364 expect(yield* head.text).toBe("");
365 }),
366 );
367​
368 it.effect("closes static descriptors after GET, HEAD, 304, and request cancellation", () =>
369 Effect.gen(function* () {
370 const fs = yield* FileSystem.FileSystem;
371 const path = yield* Path.Path;
372 const staticDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-static-close-" });
373 const filePath = path.join(staticDir, "app.txt");
374 const body = "file content\n".repeat(1024);
375 yield* fs.writeFileString(filePath, body);
376 const closed = yield* Queue.unbounded<FileSystem.File>();
377 const blocked = yield* Deferred.make<void>();
378 const active = new Set<FileSystem.File>();
379 let blockAfterOpen = false;
380 let bodyReads = 0;
381 const trackedFileSystem = FileSystem.FileSystem.of({
382 ...fs,
383 open: (candidate, options) =>
384 Effect.gen(function* () {
385 if (candidate !== filePath) return yield* fs.open(candidate, options);
386 let opened: FileSystem.File | undefined;
387 yield* Effect.addFinalizer(() =>
388 Effect.gen(function* () {
389 if (opened === undefined) return;
390 active.delete(opened);
391 yield* Queue.offer(closed, opened);
392 }),
393 );
394 const file = yield* fs.open(candidate, options);
395 opened = file;
396 active.add(file);
397 if (blockAfterOpen) {
398 yield* Deferred.succeed(blocked, undefined);
399 return yield* Effect.never;
400 }
401 return new Proxy(file, {
402 get(target, key) {
403 if (key === "readAlloc") {
404 return (size: number) => {
405 bodyReads += 1;
406 return target.readAlloc(size);
407 };
408 }
409 return Reflect.get(target, key, target);
410 },
411 });
412 }),
413 });
414 const request = yield* makeStaticRequest(staticDir).pipe(
415 Effect.provideService(FileSystem.FileSystem, trackedFileSystem),
416 );
417​
418 const get = yield* request("/app.txt");
419 expect(yield* get.text).toBe(body);
420 yield* Queue.take(closed);
421 expect(active.size).toBe(0);
422 expect(bodyReads).toBeGreaterThan(0);
423 const readsAfterGet = bodyReads;
424 const head = yield* request("/app.txt", {
425 method: "HEAD",
426 headers: { "accept-encoding": "gzip" },
427 });
428 expect(head.status).toBe(200);
429 expect(head.headers["content-encoding"]).toBe("gzip");
430 expect(yield* head.text).toBe("");
431 yield* Queue.take(closed);
432 expect(active.size).toBe(0);
433 expect(bodyReads).toBe(readsAfterGet);
434 const unchanged = yield* request("/app.txt", {
435 headers: { "if-none-match": get.headers["etag"]! },
436 });
437 expect(unchanged.status).toBe(304);
438 yield* Queue.take(closed);
439 expect(active.size).toBe(0);
440 expect(bodyReads).toBe(readsAfterGet);
441​
442 blockAfterOpen = true;
443 const cancelled = yield* request("/app.txt").pipe(Effect.forkChild);
444 yield* Deferred.await(blocked);
445 expect(active.size).toBe(1);
446 yield* Fiber.interrupt(cancelled);
447 yield* Queue.take(closed);
448 expect(active.size).toBe(0);
449 }),
450 );
451});
452​
453describe("video asset byte ranges", () => {
454 it.effect("uses current descriptor metadata after an in-place truncate or extension", () =>
455 Effect.gen(function* () {
456 const fs = yield* FileSystem.FileSystem;
457 const path = yield* Path.Path;
458 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-guarded-current-stat-" });
459 const filePath = path.join(directory, "clip.mp4");
460 for (const [contents, range, method, expected, status, contentRange] of [
461 ["1234", undefined, "GET", "1234", 200, null],
462 ["0123456789abcdef", undefined, "GET", "0123456789abcdef", 200, null],
463 ["1234", "bytes=4-", "GET", "", 416, "bytes */4"],
464 ["1234", "bytes=1-20", "GET", "234", 206, "bytes 1-3/4"],
465 ["0123456789abcdef", "bytes=10-", "GET", "abcdef", 206, "bytes 10-15/16"],
466 ["0123456789abcdef", undefined, "HEAD", "", 200, null],
467 ["", undefined, "GET", "", 200, null],
468 ["", "bytes=0-1", "GET", "", 416, "bytes */0"],
469 ] as const) {
470 yield* fs.writeFileString(filePath, "0123456789");
471 const canonicalPath = yield* fs.realPath(filePath);
472 const file = yield* openMediaFile(canonicalPath);
473 if (!file) throw new Error("Expected an opened media file");
474 yield* fs.writeFileString(filePath, contents);
475 const response = HttpServerResponse.toWeb(
476 yield* assetFileResponse(
477 { path: canonicalPath, file, mimeType: "video/mp4" },
478 range,
479 undefined,
480 method,
481 ),
482 );
483 expect(response.status).toBe(status);
484 expect(response.headers.get("content-range")).toBe(contentRange);
485 if (status !== 416) {
486 expect(response.headers.get("content-length")).toBe(
487 String(method === "HEAD" ? contents.length : expected.length),
488 );
489 }
490 expect(yield* Effect.promise(() => response.text())).toBe(expected);
491 }
492 }).pipe(Effect.provide(layerFileResponse)),
493 );
494​
495 it.effect(
496 "rejects unaddressable ranges before streaming and preserves small ranges on large files",
497 () =>
498 Effect.gen(function* () {
499 const fs = yield* FileSystem.FileSystem;
500 const path = yield* Path.Path;
501 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-guarded-offset-limit-" });
502 const filePath = path.join(directory, "clip.mp4");
503 yield* fs.writeFileString(filePath, "0123456789");
504 const canonicalPath = yield* fs.realPath(filePath);
505 const unsafeOffset = BigInt(Number.MAX_SAFE_INTEGER) + 1n;
506 const size = unsafeOffset + 32n;
507 for (const [range, status] of [
508 [`bytes=${unsafeOffset}-${unsafeOffset}`, 416],
509 [`bytes=0-${unsafeOffset}`, 416],
510 ["bytes=-1", 416],
511 [undefined, 413],
512 ["bytes=0-1", 206],
513 ] as const) {
514 const file = yield* openMediaFile(canonicalPath);
515 if (!file) throw new Error("Expected an opened media file");
516 const info = yield* Effect.promise(() => file.handle.stat({ bigint: true }));
517 info.size = size;
518 const statSpy = vi.spyOn(file.handle, "stat").mockResolvedValue(info);
519 yield* Effect.addFinalizer(() => Effect.sync(() => statSpy.mockRestore()));
520 const response = HttpServerResponse.toWeb(
521 yield* assetFileResponse({ path: canonicalPath, file, mimeType: "video/mp4" }, range),
522 );
523 expect(response.status).toBe(status);
524 if (status === 416) {
525 expect(response.headers.get("content-range")).toBe(`bytes */${size}`);
526 expect(yield* Effect.promise(() => response.text())).toBe("");
527 } else if (status === 206) {
528 expect(response.headers.get("content-range")).toBe(`bytes 0-1/${size}`);
529 expect(yield* Effect.promise(() => response.text())).toBe("01");
530 } else {
531 expect(yield* Effect.promise(() => response.text())).toBe(
532 "File is too large to preview.",
533 );
534 }
535 }
536 }).pipe(Effect.provide(layerFileResponse)),
537 );
538​
539 it.effect("streams guarded file ranges, including suffixes and conditional requests", () =>
540 Effect.gen(function* () {
541 const fs = yield* FileSystem.FileSystem;
542 const path = yield* Path.Path;
543 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-guarded-range-" });
544 const filePath = path.join(directory, "clip.mp4");
545 yield* fs.writeFileString(filePath, "0123456789");
546 const canonicalPath = yield* fs.realPath(filePath);
547 for (const [range, ifRange, expected, status, contentRange] of [
548 [undefined, undefined, "0123456789", 200, null],
549 ["bytes=0-1", undefined, "01", 206, "bytes 0-1/10"],
550 ["bytes=4-", undefined, "456789", 206, "bytes 4-9/10"],
551 ["bytes=-3", undefined, "789", 206, "bytes 7-9/10"],
552 ["bytes=-999999999999999999999999", undefined, "0123456789", 206, "bytes 0-9/10"],
553 ["bytes=10-", undefined, "", 416, "bytes */10"],
554 ["bytes=0-1", '"old-etag"', "0123456789", 200, null],
555 ["bytes=0-1", "", "0123456789", 200, null],
556 ] as const) {
557 const file = yield* openMediaFile(canonicalPath);
558 if (!file) throw new Error("Expected an opened media file");
559 const response = HttpServerResponse.toWeb(
560 yield* assetFileResponse(
561 { path: canonicalPath, file, mimeType: "video/mp4" },
562 range,
563 ifRange,
564 ),
565 );
566 expect(response.status).toBe(status);
567 expect(response.headers.get("accept-ranges")).toBe("bytes");
568 expect(response.headers.get("content-range")).toBe(contentRange);
569 expect(response.headers.get("cache-control")).toBe("private, no-store");
570 expect(response.headers.get("etag")).toBeNull();
571 expect(response.headers.get("last-modified")).toBeNull();
572 if (status !== 416)
573 expect(response.headers.get("content-length")).toBe(String(expected.length));
574 expect(yield* Effect.promise(() => response.text())).toBe(expected);
575 }
576 }).pipe(Effect.provide(layerFileResponse)),
577 );
578​
579 it.effect("keeps attachment media out of the cache once its signed URL expires", () =>
580 Effect.gen(function* () {
581 const fs = yield* FileSystem.FileSystem;
582 const path = yield* Path.Path;
583 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-attachment-media-" });
584 const filePath = path.join(directory, "audio.wav");
585 yield* fs.writeFileString(filePath, "RIFF");
586 const canonicalPath = yield* fs.realPath(filePath);
587 const response = HttpServerResponse.toWeb(
588 yield* assetFileResponse({ path: canonicalPath, mimeType: "audio/wav" }),
589 );
590 expect(response.headers.get("cache-control")).toBe("private, no-store");
591 expect(response.headers.get("accept-ranges")).toBe("bytes");
592 }).pipe(Effect.provide(layerFileResponse)),
593 );
594​
595 it.effect("closes guarded descriptors after full, HEAD, rejected, and cancelled responses", () =>
596 Effect.gen(function* () {
597 const fs = yield* FileSystem.FileSystem;
598 const path = yield* Path.Path;
599 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-guarded-cleanup-" });
600 const filePath = path.join(directory, "clip.mp4");
601 const bytes = new Uint8Array(1024 * 1024).fill(42);
602 yield* fs.writeFile(filePath, bytes);
603 const canonicalPath = yield* fs.realPath(filePath);
604 for (const mode of ["full", "HEAD", "rejected", "cancelled"] as const) {
605 const file = yield* Effect.scoped(
606 Effect.gen(function* () {
607 const file = yield* openMediaFile(canonicalPath);
608 if (!file) throw new Error("Expected an opened media file");
609 const response = HttpServerResponse.toWeb(
610 yield* assetFileResponse(
611 { path: canonicalPath, file, mimeType: "video/mp4" },
612 mode === "rejected" ? `bytes=${bytes.length}-` : "bytes=0-",
613 undefined,
614 mode === "HEAD" ? "HEAD" : "GET",
615 ),
616 );
617 if (mode === "HEAD") {
618 expect(response.status).toBe(200);
619 expect(response.headers.get("content-length")).toBe(String(bytes.length));
620 expect(response.headers.get("content-range")).toBeNull();
621 expect(yield* Effect.promise(() => response.text())).toBe("");
622 } else if (mode === "rejected") {
623 expect(response.status).toBe(416);
624 expect(yield* Effect.promise(() => response.text())).toBe("");
625 } else if (mode === "cancelled") {
626 const reader = response.body!.getReader();
627 const first = yield* Effect.promise(() => reader.read());
628 expect(first.done).toBe(false);
629 expect(first.value!.byteLength).toBeLessThan(bytes.length);
630 yield* Effect.promise(() => reader.cancel());
631 } else {
632 expect(yield* Effect.promise(() => response.arrayBuffer())).toEqual(bytes.buffer);
633 }
634 return file;
635 }),
636 );
637 expect(file.handle.fd).toBe(-1);
638 }
639 }).pipe(Effect.provide(layerFileResponse)),
640 );
641​
642 it.effect("streams exactly the requested bytes and leaves full downloads intact", () =>
643 Effect.gen(function* () {
644 const fs = yield* FileSystem.FileSystem;
645 const path = yield* Path.Path;
646 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-video-range-" });
647 const file = path.join(directory, "clip.mp4");
648 yield* fs.writeFileString(file, "0123456789");
649 const asset = { path: file, mimeType: "video/mp4" };
650 for (const [header, expected, contentRange] of [
651 ["bytes=0-1", "01", "bytes 0-1/10"],
652 ["bytes=4-", "456789", "bytes 4-9/10"],
653 ["bytes=-3", "789", "bytes 7-9/10"],
654 ["bytes=-999999999999999999999999", "0123456789", "bytes 0-9/10"],
655 ["bytes=8-999999999999999999999999", "89", "bytes 8-9/10"],
656 ] as const) {
657 const response = HttpServerResponse.toWeb(yield* assetFileResponse(asset, header));
658 expect(response.status).toBe(206);
659 expect(response.headers.get("accept-ranges")).toBe("bytes");
660 expect(response.headers.get("content-range")).toBe(contentRange);
661 expect(response.headers.get("content-length")).toBe(String(expected.length));
662 expect(yield* Effect.promise(() => response.text())).toBe(expected);
663 }
664 for (const header of [
665 undefined,
666 "items=0-1",
667 "bytes=0-1,4-5",
668 "bytes=8-2",
669 "bytes=-",
670 "bytes=bad",
671 ]) {
672 const response = HttpServerResponse.toWeb(yield* assetFileResponse(asset, header));
673 expect(response.status).toBe(200);
674 expect(yield* Effect.promise(() => response.text())).toBe("0123456789");
675 }
676 const conditional = HttpServerResponse.toWeb(
677 yield* assetFileResponse(asset, "bytes=0-1", '"old-etag"'),
678 );
679 expect(conditional.status).toBe(200);
680 expect(yield* Effect.promise(() => conditional.text())).toBe("0123456789");
681 const uppercase = HttpServerResponse.toWeb(
682 yield* assetFileResponse({ ...asset, mimeType: "Video/MP4" }, "bytes=0-1"),
683 );
684 expect(uppercase.status).toBe(206);
685 expect(yield* Effect.promise(() => uppercase.text())).toBe("01");
686 const image = HttpServerResponse.toWeb(
687 yield* assetFileResponse({ path: file, mimeType: "image/png" }, "bytes=0-1"),
688 );
689 expect(image.status).toBe(200);
690 expect(image.headers.has("accept-ranges")).toBe(false);
691 expect(yield* Effect.promise(() => image.text())).toBe("0123456789");
692 }).pipe(Effect.provide(layerFileResponse)),
693 );
694​
695 it.effect(
696 "supports native audio header probes and seeking without changing explicit downloads",
697 () =>
698 Effect.gen(function* () {
699 const fs = yield* FileSystem.FileSystem;
700 const path = yield* Path.Path;
701 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-audio-range-" });
702 const file = path.join(directory, "recording.wav");
703 yield* fs.writeFileString(file, "0123456789");
704 const asset = { path: file, mimeType: "audio/wav" };
705 for (const [header, expected] of [
706 ["bytes=0-1", "01"],
707 ["bytes=5-", "56789"],
708 ] as const) {
709 const response = HttpServerResponse.toWeb(yield* assetFileResponse(asset, header));
710 expect(response.status).toBe(206);
711 expect(response.headers.get("content-type")).toBe("audio/wav");
712 expect(response.headers.get("accept-ranges")).toBe("bytes");
713 expect(response.headers.get("content-length")).toBe(String(expected.length));
714 expect(yield* Effect.promise(() => response.text())).toBe(expected);
715 }
716 const download = HttpServerResponse.toWeb(
717 yield* assetFileResponse({ ...asset, download: true, fileName: "recording.wav" }),
718 );
719 expect(download.status).toBe(200);
720 expect(download.headers.get("content-disposition")).toContain("attachment;");
721 expect(yield* Effect.promise(() => download.text())).toBe("0123456789");
722 }).pipe(Effect.provide(layerFileResponse)),
723 );
724​
725 it.effect("rejects ranges outside the file, including empty files", () =>
726 Effect.gen(function* () {
727 const fs = yield* FileSystem.FileSystem;
728 const path = yield* Path.Path;
729 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-video-range-" });
730 const file = path.join(directory, "clip.mp4");
731 yield* fs.writeFileString(file, "0123456789");
732 for (const header of ["bytes=10-", "bytes=-0", "bytes=999999999999999999999999-"]) {
733 const response = HttpServerResponse.toWeb(
734 yield* assetFileResponse({ path: file, mimeType: "video/mp4" }, header),
735 );
736 expect(response.status).toBe(416);
737 expect(response.headers.get("content-range")).toBe("bytes */10");
738 expect(yield* Effect.promise(() => response.text())).toBe("");
739 }
740 yield* fs.writeFileString(file, "");
741 const empty = HttpServerResponse.toWeb(
742 yield* assetFileResponse({ path: file, mimeType: "video/mp4" }, "bytes=0-1"),
743 );
744 expect(empty.status).toBe(416);
745 expect(empty.headers.get("content-range")).toBe("bytes */0");
746 }).pipe(Effect.provide(layerFileResponse)),
747 );
748});
749​
750describe("http dev routing", () => {
751 it("treats localhost and loopback addresses as local", () => {
752 expect(isLoopbackHostname("127.0.0.1")).toBe(true);
753 expect(isLoopbackHostname("localhost")).toBe(true);
754 expect(isLoopbackHostname("::1")).toBe(true);
755 expect(isLoopbackHostname("[::1]")).toBe(true);
756 });
757​
758 it("does not treat LAN addresses as local", () => {
759 expect(isLoopbackHostname("192.168.86.35")).toBe(false);
760 expect(isLoopbackHostname("10.0.0.24")).toBe(false);
761 expect(isLoopbackHostname("example.local")).toBe(false);
762 });
763​
764 it("preserves path and query when redirecting to the dev server", () => {
765 const devUrl = new URL("http://127.0.0.1:5173/");
766 const requestUrl = new URL("http://127.0.0.1:3774/pair?token=test-token");
767​
768 expect(resolveDevRedirectUrl(devUrl, requestUrl)).toBe(
769 "http://127.0.0.1:5173/pair?token=test-token",
770 );
771 });
772});
773​
774describe("assetResponseHeaders", () => {
775 it("sandboxes SVG assets", () => {
776 expect(assetResponseHeaders("/attachments/user-image.svg")).toMatchObject({
777 "Content-Security-Policy": "default-src 'none'; style-src 'unsafe-inline'; sandbox",
778 "X-Content-Type-Options": "nosniff",
779 });
780 expect(assetResponseHeaders("/attachments/user-image.SVG")).toHaveProperty(
781 "Content-Security-Policy",
782 );
783 });
784​
785 it("does not apply document policy to raster images", () => {
786 expect(assetResponseHeaders("/attachments/user-image.png")).toEqual({
787 "Cache-Control": "private, max-age=3600",
788 "X-Content-Type-Options": "nosniff",
789 });
790 });
791​
792 it("serves inline videos with their declared mime type", () => {
793 expect(
794 assetResponseHeaders("/attachments/demo.bin", {
795 mimeType: 'video/mp4; codecs="avc1.42E01E"',
796 }),
797 ).toEqual({
798 "Cache-Control": "private, max-age=3600",
799 "Content-Type": "video/mp4",
800 "X-Content-Type-Options": "nosniff",
801 });
802 });
803 it("serves inline attachment documents with their declared mime type", () => {
804 expect(
805 assetResponseHeaders("/attachments/upload.bin", { mimeType: "application/pdf" }),
806 ).toMatchObject({
807 "Content-Type": "application/pdf",
808 });
809 expect(
810 assetResponseHeaders("/attachments/upload.bin", { mimeType: "text/html" }),
811 ).toMatchObject({
812 "Content-Type": "text/html; charset=utf-8",
813 "Content-Security-Policy": "sandbox allow-scripts allow-forms allow-popups allow-downloads",
814 });
815 });
816 it("serves HTML assets as utf-8 inside a sandboxed origin", () => {
817 for (const path of ["/workspace/page.html", "/workspace/PAGE.HTM", "/tmp/report.html"]) {
818 expect(assetResponseHeaders(path)).toMatchObject({
819 "Content-Type": "text/html; charset=utf-8",
820 "Content-Security-Policy": "sandbox allow-scripts allow-forms allow-popups allow-downloads",
821 });
822 }
823 });
824​
825 it("downloads uploaded documents without executing their content", () => {
826 expect(assetResponseHeaders("/attachments/upload.html", { download: true })).toMatchObject({
827 "Content-Disposition": "attachment",
828 "Content-Security-Policy": "default-src 'none'; sandbox",
829 "Content-Type": "application/octet-stream",
830 });
831 });
832​
833 it("serves the real filename and mime type when the claims carry them", () => {
834 expect(
835 assetResponseHeaders("/attachments/thread-1-abc-pdf.pdf", {
836 download: true,
837 fileName: "Q3 report.pdf",
838 mimeType: "application/pdf",
839 }),
840 ).toMatchObject({
841 "Content-Disposition": 'attachment; filename="Q3 report.pdf"',
842 "Content-Security-Policy": "default-src 'none'; sandbox",
843 "Content-Type": "application/pdf",
844 });
845 });
846​
847 it("keeps renderable mime types as octet-stream downloads", () => {
848 for (const mimeType of [
849 "text/html",
850 "text/xml",
851 "image/svg+xml",
852 "application/xhtml+xml",
853 "application/rss+xml",
854 "APPLICATION/XML",
855 "IMAGE/SVG+XML",
856 "application/xml-dtd",
857 "application/xml-external-parsed-entity",
858 "not a mime",
859 ]) {
860 expect(
861 assetResponseHeaders("/attachments/upload.bin", { download: true, mimeType }),
862 ).toHaveProperty("Content-Type", "application/octet-stream");
863 }
864 });
865​
866 it("preserves official Office Open XML mime types", () => {
867 for (const mimeType of [
868 "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
869 "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
870 "application/vnd.openxmlformats-officedocument.presentationml.presentation",
871 ]) {
872 expect(
873 assetResponseHeaders("/attachments/upload.bin", { download: true, mimeType }),
874 ).toHaveProperty("Content-Type", mimeType);
875 }
876 });
877});
878​
879describe("downloadContentDisposition", () => {
880 it("quotes plain names and strips quotes and control characters", () => {
881 expect(downloadContentDisposition("report.pdf")).toBe('attachment; filename="report.pdf"');
882 expect(downloadContentDisposition('we"ird\n.pdf')).toBe('attachment; filename="we_ird_.pdf"');
883 });
884​
885 it("adds an RFC 5987 encoded name for non-ASCII filenames", () => {
886 expect(downloadContentDisposition("répört.pdf")).toBe(
887 `attachment; filename="r_p_rt.pdf"; filename*=UTF-8''r%C3%A9p%C3%B6rt.pdf`,
888 );
889 expect(downloadContentDisposition("résumé'(*).pdf")).toBe(
890 `attachment; filename="r_sum_'(*).pdf"; filename*=UTF-8''r%C3%A9sum%C3%A9%27%28%2A%29.pdf`,
891 );
892 });
893​
894 it("does not throw on unpaired surrogates in the filename", () => {
895 expect(downloadContentDisposition("bad\ud800name.pdf")).toBe(
896 `attachment; filename="bad_name.pdf"; filename*=UTF-8''bad%EF%BF%BDname.pdf`,
897 );
898 });
899});