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 NodeServices from "@effect/platform-node/NodeServices";
5import * as Effect from "effect/Effect";
6import * as FileSystem from "effect/FileSystem";
7import * as Layer from "effect/Layer";
8import * as Path from "effect/Path";
9import { HttpServerResponse } from "effect/unstable/http";
10import { openMediaFile } from "./assets/MediaFile.ts";
11
12import {
13 assetResponseHeaders,
14 assetFileResponse,
15 downloadContentDisposition,
16 isLoopbackHostname,
17 resolveDevRedirectUrl,
18} from "./http.ts";
19
20const fileResponseLayer = Layer.mergeAll(NodeHttpPlatform.layer, NodeServices.layer);
21
22describe("video asset byte ranges", () => {
23 it.effect("uses current descriptor metadata after an in-place truncate or extension", () =>
24 Effect.gen(function* () {
25 const fs = yield* FileSystem.FileSystem;
26 const path = yield* Path.Path;
27 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-guarded-current-stat-" });
28 const filePath = path.join(directory, "clip.mp4");
29 for (const [contents, range, method, expected, status, contentRange] of [
30 ["1234", undefined, "GET", "1234", 200, null],
31 ["0123456789abcdef", undefined, "GET", "0123456789abcdef", 200, null],
32 ["1234", "bytes=4-", "GET", "", 416, "bytes */4"],
33 ["1234", "bytes=1-20", "GET", "234", 206, "bytes 1-3/4"],
34 ["0123456789abcdef", "bytes=10-", "GET", "abcdef", 206, "bytes 10-15/16"],
35 ["0123456789abcdef", undefined, "HEAD", "", 200, null],
36 ["", undefined, "GET", "", 200, null],
37 ["", "bytes=0-1", "GET", "", 416, "bytes */0"],
38 ] as const) {
39 yield* fs.writeFileString(filePath, "0123456789");
40 const canonicalPath = yield* fs.realPath(filePath);
41 const file = yield* openMediaFile(canonicalPath);
42 if (!file) throw new Error("Expected an opened media file");
43 yield* fs.writeFileString(filePath, contents);
44 const response = HttpServerResponse.toWeb(
45 yield* assetFileResponse(
46 { path: canonicalPath, file, mimeType: "video/mp4" },
47 range,
48 undefined,
49 method,
50 ),
51 );
52 expect(response.status).toBe(status);
53 expect(response.headers.get("content-range")).toBe(contentRange);
54 if (status !== 416) {
55 expect(response.headers.get("content-length")).toBe(
56 String(method === "HEAD" ? contents.length : expected.length),
57 );
58 }
59 expect(yield* Effect.promise(() => response.text())).toBe(expected);
60 }
61 }).pipe(Effect.provide(fileResponseLayer)),
62 );
63
64 it.effect(
65 "rejects unaddressable ranges before streaming and preserves small ranges on large files",
66 () =>
67 Effect.gen(function* () {
68 const fs = yield* FileSystem.FileSystem;
69 const path = yield* Path.Path;
70 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-guarded-offset-limit-" });
71 const filePath = path.join(directory, "clip.mp4");
72 yield* fs.writeFileString(filePath, "0123456789");
73 const canonicalPath = yield* fs.realPath(filePath);
74 const unsafeOffset = BigInt(Number.MAX_SAFE_INTEGER) + 1n;
75 const size = unsafeOffset + 32n;
76 for (const [range, status] of [
77 [`bytes=${unsafeOffset}-${unsafeOffset}`, 416],
78 [`bytes=0-${unsafeOffset}`, 416],
79 ["bytes=-1", 416],
80 [undefined, 413],
81 ["bytes=0-1", 206],
82 ] as const) {
83 const file = yield* openMediaFile(canonicalPath);
84 if (!file) throw new Error("Expected an opened media file");
85 // Model a sparse file beyond the native stream's numeric addressing limit.
86 const info = yield* Effect.promise(() => file.handle.stat({ bigint: true }));
87 info.size = size;
88 const statSpy = vi.spyOn(file.handle, "stat").mockResolvedValue(info);
89 yield* Effect.addFinalizer(() => Effect.sync(() => statSpy.mockRestore()));
90 const response = HttpServerResponse.toWeb(
91 yield* assetFileResponse({ path: canonicalPath, file, mimeType: "video/mp4" }, range),
92 );
93 expect(response.status).toBe(status);
94 if (status === 416) {
95 expect(response.headers.get("content-range")).toBe(`bytes */${size}`);
96 expect(yield* Effect.promise(() => response.text())).toBe("");
97 } else if (status === 206) {
98 expect(response.headers.get("content-range")).toBe(`bytes 0-1/${size}`);
99 expect(yield* Effect.promise(() => response.text())).toBe("01");
100 } else {
101 expect(yield* Effect.promise(() => response.text())).toBe(
102 "File is too large to preview.",
103 );
104 }
105 }
106 }).pipe(Effect.provide(fileResponseLayer)),
107 );
108
109 it.effect("streams guarded file ranges, including suffixes and conditional requests", () =>
110 Effect.gen(function* () {
111 const fs = yield* FileSystem.FileSystem;
112 const path = yield* Path.Path;
113 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-guarded-range-" });
114 const filePath = path.join(directory, "clip.mp4");
115 yield* fs.writeFileString(filePath, "0123456789");
116 const canonicalPath = yield* fs.realPath(filePath);
117 for (const [range, ifRange, expected, status, contentRange] of [
118 [undefined, undefined, "0123456789", 200, null],
119 ["bytes=0-1", undefined, "01", 206, "bytes 0-1/10"],
120 ["bytes=4-", undefined, "456789", 206, "bytes 4-9/10"],
121 ["bytes=-3", undefined, "789", 206, "bytes 7-9/10"],
122 ["bytes=-999999999999999999999999", undefined, "0123456789", 206, "bytes 0-9/10"],
123 ["bytes=10-", undefined, "", 416, "bytes */10"],
124 ["bytes=0-1", '"old-etag"', "0123456789", 200, null],
125 ["bytes=0-1", "", "0123456789", 200, null],
126 ] as const) {
127 const file = yield* openMediaFile(canonicalPath);
128 if (!file) throw new Error("Expected an opened media file");
129 const response = HttpServerResponse.toWeb(
130 yield* assetFileResponse(
131 { path: canonicalPath, file, mimeType: "video/mp4" },
132 range,
133 ifRange,
134 ),
135 );
136 expect(response.status).toBe(status);
137 expect(response.headers.get("accept-ranges")).toBe("bytes");
138 expect(response.headers.get("content-range")).toBe(contentRange);
139 expect(response.headers.get("cache-control")).toBe("private, no-store");
140 expect(response.headers.get("etag")).toBeNull();
141 expect(response.headers.get("last-modified")).toBeNull();
142 if (status !== 416)
143 expect(response.headers.get("content-length")).toBe(String(expected.length));
144 expect(yield* Effect.promise(() => response.text())).toBe(expected);
145 }
146 }).pipe(Effect.provide(fileResponseLayer)),
147 );
148
149 it.effect("keeps attachment media out of the cache once its signed URL expires", () =>
150 Effect.gen(function* () {
151 const fs = yield* FileSystem.FileSystem;
152 const path = yield* Path.Path;
153 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-attachment-media-" });
154 const filePath = path.join(directory, "audio.wav");
155 yield* fs.writeFileString(filePath, "RIFF");
156 const canonicalPath = yield* fs.realPath(filePath);
157 // An attachment is read straight from disk, so it carries no opened host file. Its URL is
158 // signed and short-lived; a cached copy would outlive the grant that served it.
159 const response = HttpServerResponse.toWeb(
160 yield* assetFileResponse({ path: canonicalPath, mimeType: "audio/wav" }),
161 );
162 expect(response.headers.get("cache-control")).toBe("private, no-store");
163 expect(response.headers.get("accept-ranges")).toBe("bytes");
164 }).pipe(Effect.provide(fileResponseLayer)),
165 );
166
167 it.effect("closes guarded descriptors after full, HEAD, rejected, and cancelled responses", () =>
168 Effect.gen(function* () {
169 const fs = yield* FileSystem.FileSystem;
170 const path = yield* Path.Path;
171 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-guarded-cleanup-" });
172 const filePath = path.join(directory, "clip.mp4");
173 const bytes = new Uint8Array(1024 * 1024).fill(42);
174 yield* fs.writeFile(filePath, bytes);
175 const canonicalPath = yield* fs.realPath(filePath);
176 for (const mode of ["full", "HEAD", "rejected", "cancelled"] as const) {
177 const file = yield* Effect.scoped(
178 Effect.gen(function* () {
179 const file = yield* openMediaFile(canonicalPath);
180 if (!file) throw new Error("Expected an opened media file");
181 const response = HttpServerResponse.toWeb(
182 yield* assetFileResponse(
183 { path: canonicalPath, file, mimeType: "video/mp4" },
184 mode === "rejected" ? `bytes=${bytes.length}-` : "bytes=0-",
185 undefined,
186 mode === "HEAD" ? "HEAD" : "GET",
187 ),
188 );
189 if (mode === "HEAD") {
190 expect(response.status).toBe(200);
191 expect(response.headers.get("content-length")).toBe(String(bytes.length));
192 expect(response.headers.get("content-range")).toBeNull();
193 expect(yield* Effect.promise(() => response.text())).toBe("");
194 } else if (mode === "rejected") {
195 expect(response.status).toBe(416);
196 expect(yield* Effect.promise(() => response.text())).toBe("");
197 } else if (mode === "cancelled") {
198 const reader = response.body!.getReader();
199 const first = yield* Effect.promise(() => reader.read());
200 expect(first.done).toBe(false);
201 expect(first.value!.byteLength).toBeLessThan(bytes.length);
202 yield* Effect.promise(() => reader.cancel());
203 } else {
204 expect(yield* Effect.promise(() => response.arrayBuffer())).toEqual(bytes.buffer);
205 }
206 return file;
207 }),
208 );
209 expect(file.handle.fd).toBe(-1);
210 }
211 }).pipe(Effect.provide(fileResponseLayer)),
212 );
213
214 it.effect("streams exactly the requested bytes and leaves full downloads intact", () =>
215 Effect.gen(function* () {
216 const fs = yield* FileSystem.FileSystem;
217 const path = yield* Path.Path;
218 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-video-range-" });
219 const file = path.join(directory, "clip.mp4");
220 yield* fs.writeFileString(file, "0123456789");
221 const asset = { path: file, mimeType: "video/mp4" };
222 for (const [header, expected, contentRange] of [
223 ["bytes=0-1", "01", "bytes 0-1/10"],
224 ["bytes=4-", "456789", "bytes 4-9/10"],
225 ["bytes=-3", "789", "bytes 7-9/10"],
226 ["bytes=-999999999999999999999999", "0123456789", "bytes 0-9/10"],
227 ["bytes=8-999999999999999999999999", "89", "bytes 8-9/10"],
228 ] as const) {
229 const response = HttpServerResponse.toWeb(yield* assetFileResponse(asset, header));
230 expect(response.status).toBe(206);
231 expect(response.headers.get("accept-ranges")).toBe("bytes");
232 expect(response.headers.get("content-range")).toBe(contentRange);
233 expect(response.headers.get("content-length")).toBe(String(expected.length));
234 expect(yield* Effect.promise(() => response.text())).toBe(expected);
235 }
236 for (const header of [
237 undefined,
238 "items=0-1",
239 "bytes=0-1,4-5",
240 "bytes=8-2",
241 "bytes=-",
242 "bytes=bad",
243 ]) {
244 const response = HttpServerResponse.toWeb(yield* assetFileResponse(asset, header));
245 expect(response.status).toBe(200);
246 expect(yield* Effect.promise(() => response.text())).toBe("0123456789");
247 }
248 const conditional = HttpServerResponse.toWeb(
249 yield* assetFileResponse(asset, "bytes=0-1", '"old-etag"'),
250 );
251 expect(conditional.status).toBe(200);
252 expect(yield* Effect.promise(() => conditional.text())).toBe("0123456789");
253 const uppercase = HttpServerResponse.toWeb(
254 yield* assetFileResponse({ ...asset, mimeType: "Video/MP4" }, "bytes=0-1"),
255 );
256 expect(uppercase.status).toBe(206);
257 expect(yield* Effect.promise(() => uppercase.text())).toBe("01");
258 const image = HttpServerResponse.toWeb(
259 yield* assetFileResponse({ path: file, mimeType: "image/png" }, "bytes=0-1"),
260 );
261 expect(image.status).toBe(200);
262 expect(image.headers.has("accept-ranges")).toBe(false);
263 expect(yield* Effect.promise(() => image.text())).toBe("0123456789");
264 }).pipe(Effect.provide(fileResponseLayer)),
265 );
266
267 it.effect(
268 "supports native audio header probes and seeking without changing explicit downloads",
269 () =>
270 Effect.gen(function* () {
271 const fs = yield* FileSystem.FileSystem;
272 const path = yield* Path.Path;
273 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-audio-range-" });
274 const file = path.join(directory, "recording.wav");
275 yield* fs.writeFileString(file, "0123456789");
276 const asset = { path: file, mimeType: "audio/wav" };
277 for (const [header, expected] of [
278 ["bytes=0-1", "01"],
279 ["bytes=5-", "56789"],
280 ] as const) {
281 const response = HttpServerResponse.toWeb(yield* assetFileResponse(asset, header));
282 expect(response.status).toBe(206);
283 expect(response.headers.get("content-type")).toBe("audio/wav");
284 expect(response.headers.get("accept-ranges")).toBe("bytes");
285 expect(response.headers.get("content-length")).toBe(String(expected.length));
286 expect(yield* Effect.promise(() => response.text())).toBe(expected);
287 }
288 const download = HttpServerResponse.toWeb(
289 yield* assetFileResponse({ ...asset, download: true, fileName: "recording.wav" }),
290 );
291 expect(download.status).toBe(200);
292 expect(download.headers.get("content-disposition")).toContain("attachment;");
293 expect(yield* Effect.promise(() => download.text())).toBe("0123456789");
294 }).pipe(Effect.provide(fileResponseLayer)),
295 );
296
297 it.effect("rejects ranges outside the file, including empty files", () =>
298 Effect.gen(function* () {
299 const fs = yield* FileSystem.FileSystem;
300 const path = yield* Path.Path;
301 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-video-range-" });
302 const file = path.join(directory, "clip.mp4");
303 yield* fs.writeFileString(file, "0123456789");
304 for (const header of ["bytes=10-", "bytes=-0", "bytes=999999999999999999999999-"]) {
305 const response = HttpServerResponse.toWeb(
306 yield* assetFileResponse({ path: file, mimeType: "video/mp4" }, header),
307 );
308 expect(response.status).toBe(416);
309 expect(response.headers.get("content-range")).toBe("bytes */10");
310 expect(yield* Effect.promise(() => response.text())).toBe("");
311 }
312 yield* fs.writeFileString(file, "");
313 const empty = HttpServerResponse.toWeb(
314 yield* assetFileResponse({ path: file, mimeType: "video/mp4" }, "bytes=0-1"),
315 );
316 expect(empty.status).toBe(416);
317 expect(empty.headers.get("content-range")).toBe("bytes */0");
318 }).pipe(Effect.provide(fileResponseLayer)),
319 );
320});
321
322describe("http dev routing", () => {
323 it("treats localhost and loopback addresses as local", () => {
324 expect(isLoopbackHostname("127.0.0.1")).toBe(true);
325 expect(isLoopbackHostname("localhost")).toBe(true);
326 expect(isLoopbackHostname("::1")).toBe(true);
327 expect(isLoopbackHostname("[::1]")).toBe(true);
328 });
329
330 it("does not treat LAN addresses as local", () => {
331 expect(isLoopbackHostname("192.168.86.35")).toBe(false);
332 expect(isLoopbackHostname("10.0.0.24")).toBe(false);
333 expect(isLoopbackHostname("example.local")).toBe(false);
334 });
335
336 it("preserves path and query when redirecting to the dev server", () => {
337 const devUrl = new URL("http://127.0.0.1:5173/");
338 const requestUrl = new URL("http://127.0.0.1:3774/pair?token=test-token");
339
340 expect(resolveDevRedirectUrl(devUrl, requestUrl)).toBe(
341 "http://127.0.0.1:5173/pair?token=test-token",
342 );
343 });
344});
345
346describe("assetResponseHeaders", () => {
347 it("sandboxes SVG assets", () => {
348 expect(assetResponseHeaders("/attachments/user-image.svg")).toMatchObject({
349 "Content-Security-Policy": "default-src 'none'; style-src 'unsafe-inline'; sandbox",
350 "X-Content-Type-Options": "nosniff",
351 });
352 expect(assetResponseHeaders("/attachments/user-image.SVG")).toHaveProperty(
353 "Content-Security-Policy",
354 );
355 });
356
357 it("does not apply document policy to raster images", () => {
358 expect(assetResponseHeaders("/attachments/user-image.png")).toEqual({
359 "Cache-Control": "private, max-age=3600",
360 "X-Content-Type-Options": "nosniff",
361 });
362 });
363
364 it("serves inline videos with their declared mime type", () => {
365 expect(
366 assetResponseHeaders("/attachments/demo.bin", {
367 mimeType: 'video/mp4; codecs="avc1.42E01E"',
368 }),
369 ).toEqual({
370 "Cache-Control": "private, max-age=3600",
371 "Content-Type": "video/mp4",
372 "X-Content-Type-Options": "nosniff",
373 });
374 });
375 it("serves inline attachment documents with their declared mime type", () => {
376 expect(
377 assetResponseHeaders("/attachments/upload.bin", { mimeType: "application/pdf" }),
378 ).toMatchObject({
379 "Content-Type": "application/pdf",
380 });
381 expect(
382 assetResponseHeaders("/attachments/upload.bin", { mimeType: "text/html" }),
383 ).toMatchObject({
384 "Content-Type": "text/html; charset=utf-8",
385 "Content-Security-Policy": "sandbox allow-scripts allow-forms allow-popups allow-modals",
386 });
387 });
388 it("serves HTML assets as utf-8 inside a sandboxed origin", () => {
389 for (const path of ["/workspace/page.html", "/workspace/PAGE.HTM", "/tmp/report.html"]) {
390 expect(assetResponseHeaders(path)).toMatchObject({
391 "Content-Type": "text/html; charset=utf-8",
392 "Content-Security-Policy": "sandbox allow-scripts allow-forms allow-popups allow-modals",
393 });
394 }
395 });
396
397 it("downloads uploaded documents without executing their content", () => {
398 expect(assetResponseHeaders("/attachments/upload.html", { download: true })).toMatchObject({
399 "Content-Disposition": "attachment",
400 "Content-Security-Policy": "default-src 'none'; sandbox",
401 "Content-Type": "application/octet-stream",
402 });
403 });
404
405 it("serves the real filename and mime type when the claims carry them", () => {
406 expect(
407 assetResponseHeaders("/attachments/thread-1-abc-pdf.pdf", {
408 download: true,
409 fileName: "Q3 report.pdf",
410 mimeType: "application/pdf",
411 }),
412 ).toMatchObject({
413 "Content-Disposition": 'attachment; filename="Q3 report.pdf"',
414 "Content-Security-Policy": "default-src 'none'; sandbox",
415 "Content-Type": "application/pdf",
416 });
417 });
418
419 it("keeps renderable mime types as octet-stream downloads", () => {
420 for (const mimeType of [
421 "text/html",
422 "text/xml",
423 "image/svg+xml",
424 "application/xhtml+xml",
425 "application/rss+xml",
426 "APPLICATION/XML",
427 "IMAGE/SVG+XML",
428 "application/xml-dtd",
429 "application/xml-external-parsed-entity",
430 "not a mime",
431 ]) {
432 expect(
433 assetResponseHeaders("/attachments/upload.bin", { download: true, mimeType }),
434 ).toHaveProperty("Content-Type", "application/octet-stream");
435 }
436 });
437
438 it("preserves official Office Open XML mime types", () => {
439 for (const mimeType of [
440 "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
441 "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
442 "application/vnd.openxmlformats-officedocument.presentationml.presentation",
443 ]) {
444 expect(
445 assetResponseHeaders("/attachments/upload.bin", { download: true, mimeType }),
446 ).toHaveProperty("Content-Type", mimeType);
447 }
448 });
449});
450
451describe("downloadContentDisposition", () => {
452 it("quotes plain names and strips quotes and control characters", () => {
453 expect(downloadContentDisposition("report.pdf")).toBe('attachment; filename="report.pdf"');
454 expect(downloadContentDisposition('we"ird\n.pdf')).toBe('attachment; filename="we_ird_.pdf"');
455 });
456
457 it("adds an RFC 5987 encoded name for non-ASCII filenames", () => {
458 expect(downloadContentDisposition("répört.pdf")).toBe(
459 `attachment; filename="r_p_rt.pdf"; filename*=UTF-8''r%C3%A9p%C3%B6rt.pdf`,
460 );
461 expect(downloadContentDisposition("résumé'(*).pdf")).toBe(
462 `attachment; filename="r_sum_'(*).pdf"; filename*=UTF-8''r%C3%A9sum%C3%A9%27%28%2A%29.pdf`,
463 );
464 });
465
466 it("does not throw on unpaired surrogates in the filename", () => {
467 expect(downloadContentDisposition("bad\ud800name.pdf")).toBe(
468 `attachment; filename="bad_name.pdf"; filename*=UTF-8''bad%EF%BF%BDname.pdf`,
469 );
470 });
471});