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

http.test.ts

423 lines18.3 KB

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("closes guarded descriptors after full, HEAD, rejected, and cancelled responses", () =>
150 Effect.gen(function* () {
151 const fs = yield* FileSystem.FileSystem;
152 const path = yield* Path.Path;
153 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-guarded-cleanup-" });
154 const filePath = path.join(directory, "clip.mp4");
155 const bytes = new Uint8Array(1024 * 1024).fill(42);
156 yield* fs.writeFile(filePath, bytes);
157 const canonicalPath = yield* fs.realPath(filePath);
158 for (const mode of ["full", "HEAD", "rejected", "cancelled"] as const) {
159 const file = yield* Effect.scoped(
160 Effect.gen(function* () {
161 const file = yield* openMediaFile(canonicalPath);
162 if (!file) throw new Error("Expected an opened media file");
163 const response = HttpServerResponse.toWeb(
164 yield* assetFileResponse(
165 { path: canonicalPath, file, mimeType: "video/mp4" },
166 mode === "rejected" ? `bytes=${bytes.length}-` : "bytes=0-",
167 undefined,
168 mode === "HEAD" ? "HEAD" : "GET",
169 ),
170 );
171 if (mode === "HEAD") {
172 expect(response.status).toBe(200);
173 expect(response.headers.get("content-length")).toBe(String(bytes.length));
174 expect(response.headers.get("content-range")).toBeNull();
175 expect(yield* Effect.promise(() => response.text())).toBe("");
176 } else if (mode === "rejected") {
177 expect(response.status).toBe(416);
178 expect(yield* Effect.promise(() => response.text())).toBe("");
179 } else if (mode === "cancelled") {
180 const reader = response.body!.getReader();
181 const first = yield* Effect.promise(() => reader.read());
182 expect(first.done).toBe(false);
183 expect(first.value!.byteLength).toBeLessThan(bytes.length);
184 yield* Effect.promise(() => reader.cancel());
185 } else {
186 expect(yield* Effect.promise(() => response.arrayBuffer())).toEqual(bytes.buffer);
187 }
188 return file;
189 }),
190 );
191 expect(file.handle.fd).toBe(-1);
192 }
193 }).pipe(Effect.provide(fileResponseLayer)),
194 );
195​
196 it.effect("streams exactly the requested bytes and leaves full downloads intact", () =>
197 Effect.gen(function* () {
198 const fs = yield* FileSystem.FileSystem;
199 const path = yield* Path.Path;
200 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-video-range-" });
201 const file = path.join(directory, "clip.mp4");
202 yield* fs.writeFileString(file, "0123456789");
203 const asset = { path: file, mimeType: "video/mp4" };
204 for (const [header, expected, contentRange] of [
205 ["bytes=0-1", "01", "bytes 0-1/10"],
206 ["bytes=4-", "456789", "bytes 4-9/10"],
207 ["bytes=-3", "789", "bytes 7-9/10"],
208 ["bytes=-999999999999999999999999", "0123456789", "bytes 0-9/10"],
209 ["bytes=8-999999999999999999999999", "89", "bytes 8-9/10"],
210 ] as const) {
211 const response = HttpServerResponse.toWeb(yield* assetFileResponse(asset, header));
212 expect(response.status).toBe(206);
213 expect(response.headers.get("accept-ranges")).toBe("bytes");
214 expect(response.headers.get("content-range")).toBe(contentRange);
215 expect(response.headers.get("content-length")).toBe(String(expected.length));
216 expect(yield* Effect.promise(() => response.text())).toBe(expected);
217 }
218 for (const header of [
219 undefined,
220 "items=0-1",
221 "bytes=0-1,4-5",
222 "bytes=8-2",
223 "bytes=-",
224 "bytes=bad",
225 ]) {
226 const response = HttpServerResponse.toWeb(yield* assetFileResponse(asset, header));
227 expect(response.status).toBe(200);
228 expect(yield* Effect.promise(() => response.text())).toBe("0123456789");
229 }
230 const conditional = HttpServerResponse.toWeb(
231 yield* assetFileResponse(asset, "bytes=0-1", '"old-etag"'),
232 );
233 expect(conditional.status).toBe(200);
234 expect(yield* Effect.promise(() => conditional.text())).toBe("0123456789");
235 const uppercase = HttpServerResponse.toWeb(
236 yield* assetFileResponse({ ...asset, mimeType: "Video/MP4" }, "bytes=0-1"),
237 );
238 expect(uppercase.status).toBe(206);
239 expect(yield* Effect.promise(() => uppercase.text())).toBe("01");
240 const image = HttpServerResponse.toWeb(
241 yield* assetFileResponse({ path: file, mimeType: "image/png" }, "bytes=0-1"),
242 );
243 expect(image.status).toBe(200);
244 expect(image.headers.has("accept-ranges")).toBe(false);
245 expect(yield* Effect.promise(() => image.text())).toBe("0123456789");
246 }).pipe(Effect.provide(fileResponseLayer)),
247 );
248​
249 it.effect("rejects ranges outside the file, including empty files", () =>
250 Effect.gen(function* () {
251 const fs = yield* FileSystem.FileSystem;
252 const path = yield* Path.Path;
253 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-video-range-" });
254 const file = path.join(directory, "clip.mp4");
255 yield* fs.writeFileString(file, "0123456789");
256 for (const header of ["bytes=10-", "bytes=-0", "bytes=999999999999999999999999-"]) {
257 const response = HttpServerResponse.toWeb(
258 yield* assetFileResponse({ path: file, mimeType: "video/mp4" }, header),
259 );
260 expect(response.status).toBe(416);
261 expect(response.headers.get("content-range")).toBe("bytes */10");
262 expect(yield* Effect.promise(() => response.text())).toBe("");
263 }
264 yield* fs.writeFileString(file, "");
265 const empty = HttpServerResponse.toWeb(
266 yield* assetFileResponse({ path: file, mimeType: "video/mp4" }, "bytes=0-1"),
267 );
268 expect(empty.status).toBe(416);
269 expect(empty.headers.get("content-range")).toBe("bytes */0");
270 }).pipe(Effect.provide(fileResponseLayer)),
271 );
272});
273​
274describe("http dev routing", () => {
275 it("treats localhost and loopback addresses as local", () => {
276 expect(isLoopbackHostname("127.0.0.1")).toBe(true);
277 expect(isLoopbackHostname("localhost")).toBe(true);
278 expect(isLoopbackHostname("::1")).toBe(true);
279 expect(isLoopbackHostname("[::1]")).toBe(true);
280 });
281​
282 it("does not treat LAN addresses as local", () => {
283 expect(isLoopbackHostname("192.168.86.35")).toBe(false);
284 expect(isLoopbackHostname("10.0.0.24")).toBe(false);
285 expect(isLoopbackHostname("example.local")).toBe(false);
286 });
287​
288 it("preserves path and query when redirecting to the dev server", () => {
289 const devUrl = new URL("http://127.0.0.1:5173/");
290 const requestUrl = new URL("http://127.0.0.1:3774/pair?token=test-token");
291​
292 expect(resolveDevRedirectUrl(devUrl, requestUrl)).toBe(
293 "http://127.0.0.1:5173/pair?token=test-token",
294 );
295 });
296});
297​
298describe("assetResponseHeaders", () => {
299 it("sandboxes SVG assets", () => {
300 expect(assetResponseHeaders("/attachments/user-image.svg")).toMatchObject({
301 "Content-Security-Policy": "default-src 'none'; style-src 'unsafe-inline'; sandbox",
302 "X-Content-Type-Options": "nosniff",
303 });
304 expect(assetResponseHeaders("/attachments/user-image.SVG")).toHaveProperty(
305 "Content-Security-Policy",
306 );
307 });
308​
309 it("does not apply document policy to raster images", () => {
310 expect(assetResponseHeaders("/attachments/user-image.png")).toEqual({
311 "Cache-Control": "private, max-age=3600",
312 "X-Content-Type-Options": "nosniff",
313 });
314 });
315​
316 it("serves inline videos with their declared mime type", () => {
317 expect(
318 assetResponseHeaders("/attachments/demo.bin", {
319 mimeType: 'video/mp4; codecs="avc1.42E01E"',
320 }),
321 ).toEqual({
322 "Cache-Control": "private, max-age=3600",
323 "Content-Type": "video/mp4",
324 "X-Content-Type-Options": "nosniff",
325 });
326 });
327 it("serves inline attachment documents with their declared mime type", () => {
328 expect(
329 assetResponseHeaders("/attachments/upload.bin", { mimeType: "application/pdf" }),
330 ).toMatchObject({
331 "Content-Type": "application/pdf",
332 });
333 expect(
334 assetResponseHeaders("/attachments/upload.bin", { mimeType: "text/html" }),
335 ).toMatchObject({
336 "Content-Type": "text/html; charset=utf-8",
337 "Content-Security-Policy": "sandbox allow-scripts allow-forms allow-popups allow-modals",
338 });
339 });
340 it("serves HTML assets as utf-8 inside a sandboxed origin", () => {
341 for (const path of ["/workspace/page.html", "/workspace/PAGE.HTM", "/tmp/report.html"]) {
342 expect(assetResponseHeaders(path)).toMatchObject({
343 "Content-Type": "text/html; charset=utf-8",
344 "Content-Security-Policy": "sandbox allow-scripts allow-forms allow-popups allow-modals",
345 });
346 }
347 });
348​
349 it("downloads uploaded documents without executing their content", () => {
350 expect(assetResponseHeaders("/attachments/upload.html", { download: true })).toMatchObject({
351 "Content-Disposition": "attachment",
352 "Content-Security-Policy": "default-src 'none'; sandbox",
353 "Content-Type": "application/octet-stream",
354 });
355 });
356​
357 it("serves the real filename and mime type when the claims carry them", () => {
358 expect(
359 assetResponseHeaders("/attachments/thread-1-abc-pdf.pdf", {
360 download: true,
361 fileName: "Q3 report.pdf",
362 mimeType: "application/pdf",
363 }),
364 ).toMatchObject({
365 "Content-Disposition": 'attachment; filename="Q3 report.pdf"',
366 "Content-Security-Policy": "default-src 'none'; sandbox",
367 "Content-Type": "application/pdf",
368 });
369 });
370​
371 it("keeps renderable mime types as octet-stream downloads", () => {
372 for (const mimeType of [
373 "text/html",
374 "text/xml",
375 "image/svg+xml",
376 "application/xhtml+xml",
377 "application/rss+xml",
378 "APPLICATION/XML",
379 "IMAGE/SVG+XML",
380 "application/xml-dtd",
381 "application/xml-external-parsed-entity",
382 "not a mime",
383 ]) {
384 expect(
385 assetResponseHeaders("/attachments/upload.bin", { download: true, mimeType }),
386 ).toHaveProperty("Content-Type", "application/octet-stream");
387 }
388 });
389​
390 it("preserves official Office Open XML mime types", () => {
391 for (const mimeType of [
392 "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
393 "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
394 "application/vnd.openxmlformats-officedocument.presentationml.presentation",
395 ]) {
396 expect(
397 assetResponseHeaders("/attachments/upload.bin", { download: true, mimeType }),
398 ).toHaveProperty("Content-Type", mimeType);
399 }
400 });
401});
402​
403describe("downloadContentDisposition", () => {
404 it("quotes plain names and strips quotes and control characters", () => {
405 expect(downloadContentDisposition("report.pdf")).toBe('attachment; filename="report.pdf"');
406 expect(downloadContentDisposition('we"ird\n.pdf')).toBe('attachment; filename="we_ird_.pdf"');
407 });
408​
409 it("adds an RFC 5987 encoded name for non-ASCII filenames", () => {
410 expect(downloadContentDisposition("répört.pdf")).toBe(
411 `attachment; filename="r_p_rt.pdf"; filename*=UTF-8''r%C3%A9p%C3%B6rt.pdf`,
412 );
413 expect(downloadContentDisposition("résumé'(*).pdf")).toBe(
414 `attachment; filename="r_sum_'(*).pdf"; filename*=UTF-8''r%C3%A9sum%C3%A9%27%28%2A%29.pdf`,
415 );
416 });
417​
418 it("does not throw on unpaired surrogates in the filename", () => {
419 expect(downloadContentDisposition("bad\ud800name.pdf")).toBe(
420 `attachment; filename="bad_name.pdf"; filename*=UTF-8''bad%EF%BF%BDname.pdf`,
421 );
422 });
423});