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