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