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

http.test.ts

238 lines9.4 KB

1import { expect, it } from "@effect/vitest";
2import { describe } 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";
10​
11import {
12 assetResponseHeaders,
13 assetFileResponse,
14 downloadContentDisposition,
15 isLoopbackHostname,
16 resolveDevRedirectUrl,
17} from "./http.ts";
18​
19const fileResponseLayer = Layer.mergeAll(NodeHttpPlatform.layer, NodeServices.layer);
20​
21describe("video asset byte ranges", () => {
22 it.effect("streams exactly the requested bytes and leaves full downloads intact", () =>
23 Effect.gen(function* () {
24 const fs = yield* FileSystem.FileSystem;
25 const path = yield* Path.Path;
26 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-video-range-" });
27 const file = path.join(directory, "clip.mp4");
28 yield* fs.writeFileString(file, "0123456789");
29 const asset = { path: file, mimeType: "video/mp4" };
30 for (const [header, expected, contentRange] of [
31 ["bytes=0-1", "01", "bytes 0-1/10"],
32 ["bytes=4-", "456789", "bytes 4-9/10"],
33 ["bytes=-3", "789", "bytes 7-9/10"],
34 ["bytes=-999999999999999999999999", "0123456789", "bytes 0-9/10"],
35 ["bytes=8-999999999999999999999999", "89", "bytes 8-9/10"],
36 ] as const) {
37 const response = HttpServerResponse.toWeb(yield* assetFileResponse(asset, header));
38 expect(response.status).toBe(206);
39 expect(response.headers.get("accept-ranges")).toBe("bytes");
40 expect(response.headers.get("content-range")).toBe(contentRange);
41 expect(response.headers.get("content-length")).toBe(String(expected.length));
42 expect(yield* Effect.promise(() => response.text())).toBe(expected);
43 }
44 for (const header of [
45 undefined,
46 "items=0-1",
47 "bytes=0-1,4-5",
48 "bytes=8-2",
49 "bytes=-",
50 "bytes=bad",
51 ]) {
52 const response = HttpServerResponse.toWeb(yield* assetFileResponse(asset, header));
53 expect(response.status).toBe(200);
54 expect(yield* Effect.promise(() => response.text())).toBe("0123456789");
55 }
56 const conditional = HttpServerResponse.toWeb(
57 yield* assetFileResponse(asset, "bytes=0-1", '"old-etag"'),
58 );
59 expect(conditional.status).toBe(200);
60 expect(yield* Effect.promise(() => conditional.text())).toBe("0123456789");
61 const uppercase = HttpServerResponse.toWeb(
62 yield* assetFileResponse({ ...asset, mimeType: "Video/MP4" }, "bytes=0-1"),
63 );
64 expect(uppercase.status).toBe(206);
65 expect(yield* Effect.promise(() => uppercase.text())).toBe("01");
66 const image = HttpServerResponse.toWeb(
67 yield* assetFileResponse({ path: file, mimeType: "image/png" }, "bytes=0-1"),
68 );
69 expect(image.status).toBe(200);
70 expect(image.headers.has("accept-ranges")).toBe(false);
71 expect(yield* Effect.promise(() => image.text())).toBe("0123456789");
72 }).pipe(Effect.provide(fileResponseLayer)),
73 );
74​
75 it.effect("rejects ranges outside the file, including empty files", () =>
76 Effect.gen(function* () {
77 const fs = yield* FileSystem.FileSystem;
78 const path = yield* Path.Path;
79 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-video-range-" });
80 const file = path.join(directory, "clip.mp4");
81 yield* fs.writeFileString(file, "0123456789");
82 for (const header of ["bytes=10-", "bytes=-0", "bytes=999999999999999999999999-"]) {
83 const response = HttpServerResponse.toWeb(
84 yield* assetFileResponse({ path: file, mimeType: "video/mp4" }, header),
85 );
86 expect(response.status).toBe(416);
87 expect(response.headers.get("content-range")).toBe("bytes */10");
88 expect(yield* Effect.promise(() => response.text())).toBe("");
89 }
90 yield* fs.writeFileString(file, "");
91 const empty = HttpServerResponse.toWeb(
92 yield* assetFileResponse({ path: file, mimeType: "video/mp4" }, "bytes=0-1"),
93 );
94 expect(empty.status).toBe(416);
95 expect(empty.headers.get("content-range")).toBe("bytes */0");
96 }).pipe(Effect.provide(fileResponseLayer)),
97 );
98});
99​
100describe("http dev routing", () => {
101 it("treats localhost and loopback addresses as local", () => {
102 expect(isLoopbackHostname("127.0.0.1")).toBe(true);
103 expect(isLoopbackHostname("localhost")).toBe(true);
104 expect(isLoopbackHostname("::1")).toBe(true);
105 expect(isLoopbackHostname("[::1]")).toBe(true);
106 });
107​
108 it("does not treat LAN addresses as local", () => {
109 expect(isLoopbackHostname("192.168.86.35")).toBe(false);
110 expect(isLoopbackHostname("10.0.0.24")).toBe(false);
111 expect(isLoopbackHostname("example.local")).toBe(false);
112 });
113​
114 it("preserves path and query when redirecting to the dev server", () => {
115 const devUrl = new URL("http://127.0.0.1:5173/");
116 const requestUrl = new URL("http://127.0.0.1:3774/pair?token=test-token");
117​
118 expect(resolveDevRedirectUrl(devUrl, requestUrl)).toBe(
119 "http://127.0.0.1:5173/pair?token=test-token",
120 );
121 });
122});
123​
124describe("assetResponseHeaders", () => {
125 it("sandboxes SVG assets", () => {
126 expect(assetResponseHeaders("/attachments/user-image.svg")).toMatchObject({
127 "Content-Security-Policy": "default-src 'none'; style-src 'unsafe-inline'; sandbox",
128 "X-Content-Type-Options": "nosniff",
129 });
130 expect(assetResponseHeaders("/attachments/user-image.SVG")).toHaveProperty(
131 "Content-Security-Policy",
132 );
133 });
134​
135 it("does not apply document policy to raster images", () => {
136 expect(assetResponseHeaders("/attachments/user-image.png")).toEqual({
137 "Cache-Control": "private, max-age=3600",
138 "X-Content-Type-Options": "nosniff",
139 });
140 });
141​
142 it("serves inline videos with their declared mime type", () => {
143 expect(
144 assetResponseHeaders("/attachments/demo.bin", {
145 mimeType: 'video/mp4; codecs="avc1.42E01E"',
146 }),
147 ).toEqual({
148 "Cache-Control": "private, max-age=3600",
149 "Content-Type": "video/mp4",
150 "X-Content-Type-Options": "nosniff",
151 });
152 });
153 it("declares utf-8 for HTML assets so non-ASCII content renders correctly", () => {
154 expect(assetResponseHeaders("/workspace/page.html")).toHaveProperty(
155 "Content-Type",
156 "text/html; charset=utf-8",
157 );
158 expect(assetResponseHeaders("/workspace/PAGE.HTM")).toHaveProperty(
159 "Content-Type",
160 "text/html; charset=utf-8",
161 );
162 });
163​
164 it("downloads uploaded documents without executing their content", () => {
165 expect(assetResponseHeaders("/attachments/upload.html", { download: true })).toMatchObject({
166 "Content-Disposition": "attachment",
167 "Content-Security-Policy": "default-src 'none'; sandbox",
168 "Content-Type": "application/octet-stream",
169 });
170 });
171​
172 it("serves the real filename and mime type when the claims carry them", () => {
173 expect(
174 assetResponseHeaders("/attachments/thread-1-abc-pdf.pdf", {
175 download: true,
176 fileName: "Q3 report.pdf",
177 mimeType: "application/pdf",
178 }),
179 ).toMatchObject({
180 "Content-Disposition": 'attachment; filename="Q3 report.pdf"',
181 "Content-Security-Policy": "default-src 'none'; sandbox",
182 "Content-Type": "application/pdf",
183 });
184 });
185​
186 it("keeps renderable mime types as octet-stream downloads", () => {
187 for (const mimeType of [
188 "text/html",
189 "text/xml",
190 "image/svg+xml",
191 "application/xhtml+xml",
192 "application/rss+xml",
193 "APPLICATION/XML",
194 "IMAGE/SVG+XML",
195 "application/xml-dtd",
196 "application/xml-external-parsed-entity",
197 "not a mime",
198 ]) {
199 expect(
200 assetResponseHeaders("/attachments/upload.bin", { download: true, mimeType }),
201 ).toHaveProperty("Content-Type", "application/octet-stream");
202 }
203 });
204​
205 it("preserves official Office Open XML mime types", () => {
206 for (const mimeType of [
207 "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
208 "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
209 "application/vnd.openxmlformats-officedocument.presentationml.presentation",
210 ]) {
211 expect(
212 assetResponseHeaders("/attachments/upload.bin", { download: true, mimeType }),
213 ).toHaveProperty("Content-Type", mimeType);
214 }
215 });
216});
217​
218describe("downloadContentDisposition", () => {
219 it("quotes plain names and strips quotes and control characters", () => {
220 expect(downloadContentDisposition("report.pdf")).toBe('attachment; filename="report.pdf"');
221 expect(downloadContentDisposition('we"ird\n.pdf')).toBe('attachment; filename="we_ird_.pdf"');
222 });
223​
224 it("adds an RFC 5987 encoded name for non-ASCII filenames", () => {
225 expect(downloadContentDisposition("répört.pdf")).toBe(
226 `attachment; filename="r_p_rt.pdf"; filename*=UTF-8''r%C3%A9p%C3%B6rt.pdf`,
227 );
228 expect(downloadContentDisposition("résumé'(*).pdf")).toBe(
229 `attachment; filename="r_sum_'(*).pdf"; filename*=UTF-8''r%C3%A9sum%C3%A9%27%28%2A%29.pdf`,
230 );
231 });
232​
233 it("does not throw on unpaired surrogates in the filename", () => {
234 expect(downloadContentDisposition("bad\ud800name.pdf")).toBe(
235 `attachment; filename="bad_name.pdf"; filename*=UTF-8''bad%EF%BF%BDname.pdf`,
236 );
237 });
238});