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