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

http.test.ts

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