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

http.test.ts

1,010 lines42.7 KB

1import { expect, it } from "@effect/vitest";
2import { describe, vi } from "vite-plus/test";
3import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
4import * as NodeHttpPlatform from "@effect/platform-node/NodeHttpPlatform";
5import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
6import * as NodeServices from "@effect/platform-node/NodeServices";
7import * as Context from "effect/Context";
8import * as DateTime from "effect/DateTime";
9import * as Deferred from "effect/Deferred";
10import * as Effect from "effect/Effect";
11import * as Fiber from "effect/Fiber";
12import * as FileSystem from "effect/FileSystem";
13import * as Layer from "effect/Layer";
14import * as Path from "effect/Path";
15import * as PlatformError from "effect/PlatformError";
16import * as Queue from "effect/Queue";
17import * as Tracer from "effect/Tracer";
18import { HttpClient, HttpClientRequest, HttpRouter, HttpServerResponse } from "effect/http";
19import { openMediaFile } from "./assets/MediaFile.ts";
20​
21import {
22 injectMcpAppCsp,
23 injectMcpAppCookieBootstrap,
24 injectMcpAppDocumentBootstrap,
25 injectMcpAppThemeBootstrap,
26 MCP_APP_MAX_HTML_BYTES,
27} from "@t3tools/shared/mcpApp";
28import { ORCHESTRATION_PROTOCOL_HEADER } from "@t3tools/contracts";
29import {
30 DESKTOP_READINESS_PROOF_PATH,
31 isValidDesktopReadinessProof,
32} from "@t3tools/shared/desktopReadinessProof";
33import { FILE_PREVIEW_SCROLL_SCRIPT } from "@t3tools/shared/htmlRender";
34​
35import * as ServerConfig from "./config.ts";
36​
37import { assetResponseHeaders, assetFileResponse, downloadContentDisposition } from "./http.ts";
38import * as ServerHttp from "./http.ts";
39​
40describe("MCP app asset responses", () => {
41 it.effect(
42 "transforms existing snapshots only with explicit render intent and fresh metadata",
43 () =>
44 Effect.gen(function* () {
45 const fs = yield* FileSystem.FileSystem;
46 const path = yield* Path.Path;
47 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-mcp-theme-" });
48 const file = path.join(directory, "app.html");
49 const html = injectMcpAppCsp(
50 "<html><head><script>vendor()</script></head><body>☃</body></html>",
51 undefined,
52 );
53 yield* fs.writeFileString(file, html);
54 for (const method of ["GET", "HEAD"] as const) {
55 const response = HttpServerResponse.toWeb(
56 yield* assetFileResponse(
57 { path: file, mimeType: "text/html", renderIntent: "mcp-app" },
58 "bytes=0-1",
59 undefined,
60 method,
61 ),
62 );
63 const expected = injectMcpAppDocumentBootstrap(
64 injectMcpAppCookieBootstrap(injectMcpAppThemeBootstrap(html)),
65 );
66 expect(response.status).toBe(200);
67 expect(response.headers.get("content-length")).toBe(
68 String(new TextEncoder().encode(expected).byteLength),
69 );
70 expect(response.headers.get("etag")).toBeNull();
71 expect(response.headers.get("last-modified")).toBeNull();
72 expect(response.headers.get("content-security-policy")).toBe(
73 "sandbox allow-scripts allow-forms allow-popups allow-downloads",
74 );
75 expect(yield* Effect.promise(() => response.text())).toBe(
76 method === "HEAD" ? "" : expected,
77 );
78 }
79 for (const download of [false, true]) {
80 const response = HttpServerResponse.toWeb(
81 yield* assetFileResponse({
82 path: file,
83 mimeType: "text/html",
84 download,
85 ...(download ? { renderIntent: "mcp-app" as const } : {}),
86 }),
87 );
88 expect(yield* Effect.promise(() => response.text())).toBe(html);
89 }
90 }).pipe(Effect.provide(layerFileResponse)),
91 );
92​
93 it.effect("rejects oversized captures before transforming them", () =>
94 Effect.gen(function* () {
95 const fs = yield* FileSystem.FileSystem;
96 const path = yield* Path.Path;
97 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-mcp-theme-size-" });
98 const file = path.join(directory, "app.html");
99 yield* fs.writeFileString(file, "x".repeat(MCP_APP_MAX_HTML_BYTES + 128 * 1024 + 1));
100 const response = yield* assetFileResponse({ path: file, renderIntent: "mcp-app" });
101 expect(response.status).toBe(413);
102 }).pipe(Effect.provide(layerFileResponse)),
103 );
104});
105​
106describe("workspace page preview responses", () => {
107 it.effect("append the scroll script only to inline HTML previews", () =>
108 Effect.gen(function* () {
109 const fs = yield* FileSystem.FileSystem;
110 const path = yield* Path.Path;
111 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-file-preview-" });
112 const page = path.join(directory, "report.html");
113 const style = path.join(directory, "report.css");
114 const html = "<!doctype html><html><body>☃</body></html>";
115 yield* fs.writeFileString(page, html);
116 yield* fs.writeFileString(style, "body{}");
117 const read = (asset: Parameters<typeof assetFileResponse>[0]) =>
118 assetFileResponse(asset).pipe(
119 Effect.flatMap((response) =>
120 Effect.promise(() => HttpServerResponse.toWeb(response).text()),
121 ),
122 );
123 const response = HttpServerResponse.toWeb(
124 yield* assetFileResponse({ path: page, renderIntent: "file-preview" }, "bytes=0-1"),
125 );
126 const expected = html + FILE_PREVIEW_SCROLL_SCRIPT;
127 expect(response.status).toBe(200);
128 expect(response.headers.get("content-length")).toBe(
129 String(new TextEncoder().encode(expected).byteLength),
130 );
131 expect(yield* Effect.promise(() => response.text())).toBe(expected);
132 expect(yield* read({ path: page, renderIntent: "file-preview", download: true })).toBe(html);
133 expect(yield* read({ path: page })).toBe(html);
134 expect(yield* read({ path: style, renderIntent: "file-preview" })).toBe("body{}");
135 }).pipe(Effect.provide(layerFileResponse)),
136 );
137});
138​
139describe("browser API CORS", () => {
140 it("accepts protocol negotiation with authenticated browser headers", async () => {
141 const layerRoute = Layer.effectDiscard(
142 Effect.gen(function* () {
143 const router = yield* HttpRouter.HttpRouter;
144 yield* router.add("GET", "/api/environment", HttpServerResponse.empty());
145 }),
146 );
147 const layerApp = Layer.merge(layerRoute, ServerHttp.layerBrowserApiCors).pipe(
148 Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "http-cors-test-" })),
149 Layer.provide(NodeServices.layer),
150 );
151 const { handler, dispose } = HttpRouter.toWebHandler(layerApp, { disableLogger: true });
152​
153 try {
154 const response = await handler(
155 new Request("https://backend.example/api/environment", {
156 method: "OPTIONS",
157 headers: {
158 origin: "https://app.t3.codes",
159 "access-control-request-method": "GET",
160 "access-control-request-headers": [
161 ORCHESTRATION_PROTOCOL_HEADER,
162 "authorization",
163 "dpop",
164 ].join(", "),
165 },
166 }),
167 );
168​
169 expect(response.status).toBe(204);
170 expect(response.headers.get("access-control-allow-origin")).toBe("*");
171 const allowedHeaders = new Set(
172 (response.headers.get("access-control-allow-headers") ?? "")
173 .split(",")
174 .map((header) => header.trim().toLowerCase()),
175 );
176 expect(allowedHeaders.has(ORCHESTRATION_PROTOCOL_HEADER)).toBe(true);
177 expect(allowedHeaders.has("authorization")).toBe(true);
178 expect(allowedHeaders.has("dpop")).toBe(true);
179 } finally {
180 await dispose();
181 }
182 });
183​
184 it("allows originless desktop requests in dev mode while still rejecting disallowed browser origins", async () => {
185 const layerRoute = Layer.effectDiscard(
186 Effect.gen(function* () {
187 const router = yield* HttpRouter.HttpRouter;
188 yield* router.add(
189 "GET",
190 "/api/environment",
191 HttpServerResponse.empty({ headers: { vary: "Accept-Encoding" } }),
192 );
193 }),
194 );
195 const layerDevConfig = Layer.effect(
196 ServerConfig.ServerConfig,
197 Effect.map(ServerConfig.ServerConfig, (config) => ({
198 ...config,
199 devUrl: new URL("http://127.0.0.1:5733"),
200 })),
201 ).pipe(Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "http-dev-cors-test-" })));
202 const layerApp = Layer.merge(layerRoute, ServerHttp.layerBrowserApiCors).pipe(
203 Layer.provide(layerDevConfig),
204 Layer.provide(NodeServices.layer),
205 );
206 const { handler, dispose } = HttpRouter.toWebHandler(layerApp, { disableLogger: true });
207​
208 try {
209 const originless = await handler(
210 new Request("https://dev.example/api/environment", { method: "GET" }),
211 );
212 expect(originless.headers.get("access-control-allow-origin")).toBe("*");
213 expect(originless.headers.get("access-control-allow-credentials")).toBeNull();
214 expect(originless.headers.get("vary")).toBe("Accept-Encoding, Origin");
215​
216 const originlessPreflight = await handler(
217 new Request("https://dev.example/api/environment", { method: "OPTIONS" }),
218 );
219 expect(originlessPreflight.status).toBe(204);
220 expect(originlessPreflight.headers.get("access-control-allow-origin")).toBe("*");
221 expect(originlessPreflight.headers.get("vary")).toBe("Origin");
222​
223 const allowed = await handler(
224 new Request("https://dev.example/api/environment", {
225 method: "GET",
226 headers: { origin: "http://127.0.0.1:5733" },
227 }),
228 );
229 expect(allowed.headers.get("access-control-allow-origin")).toBe("http://127.0.0.1:5733");
230 expect(allowed.headers.get("access-control-allow-credentials")).toBe("true");
231​
232 const disallowed = await handler(
233 new Request("https://dev.example/api/environment", {
234 method: "GET",
235 headers: { origin: "https://evil.example" },
236 }),
237 );
238 expect(disallowed.headers.get("access-control-allow-origin")).toBeNull();
239 } finally {
240 await dispose();
241 }
242 });
243});
244​
245describe("desktop readiness proof", () => {
246 // Request handlers read these from the app's own context.
247 const serveRoute = (overrides: Partial<ServerConfig.ServerConfig["Service"]>) =>
248 Effect.acquireRelease(
249 Effect.sync(() =>
250 HttpRouter.toWebHandler(
251 ServerHttp.layerDesktopReadinessProofRoute.pipe(
252 Layer.provideMerge(
253 Layer.effect(
254 ServerConfig.ServerConfig,
255 Effect.map(ServerConfig.ServerConfig, (config) => ({ ...config, ...overrides })),
256 ).pipe(
257 Layer.provide(
258 ServerConfig.layerTest(process.cwd(), { prefix: "http-readiness-test-" }),
259 ),
260 ),
261 ),
262 Layer.provideMerge(NodeCrypto.layerMac),
263 Layer.provide(NodeServices.layer),
264 ),
265 { disableLogger: true },
266 ),
267 ),
268 ({ dispose }) => Effect.promise(() => dispose()),
269 ).pipe(
270 Effect.map(
271 ({ handler }) =>
272 (query: string) =>
273 Effect.promise(() =>
274 handler(
275 new Request(`http://172.20.84.98:3773${DESKTOP_READINESS_PROOF_PATH}${query}`),
276 ),
277 ),
278 ),
279 );
280​
281 it.effect("answers a challenge with a proof bound to the launch's readiness secret", () =>
282 Effect.gen(function* () {
283 const get = yield* serveRoute({ desktopReadinessSecret: "launch-secret" });
284​
285 const response = yield* get("?challenge=abc123");
286 const proof = yield* Effect.promise(() => response.text());
287​
288 expect(response.status).toBe(200);
289 expect(yield* isValidDesktopReadinessProof("launch-secret", "abc123", proof)).toBe(true);
290 expect(yield* isValidDesktopReadinessProof("launch-secret", "other", proof)).toBe(false);
291 expect(yield* isValidDesktopReadinessProof("another-launch", "abc123", proof)).toBe(false);
292 expect(proof).not.toContain("launch-secret");
293​
294 expect((yield* get("")).status).toBe(404);
295 expect((yield* get(`?challenge=${"a".repeat(129)}`)).status).toBe(404);
296 }).pipe(Effect.scoped, Effect.provide(NodeCrypto.layerMac)),
297 );
298​
299 it.effect("does not answer on a server launched without a readiness secret", () =>
300 Effect.gen(function* () {
301 const get = yield* serveRoute({});
302​
303 expect((yield* get("?challenge=abc123")).status).toBe(404);
304 }).pipe(Effect.scoped),
305 );
306});
307​
308describe("untraced requests", () => {
309 it.effect("starts a separate trace for each request, not the server's lifetime trace", () =>
310 Effect.gen(function* () {
311 const requestSpans: Array<Tracer.NativeSpan> = [];
312 const layerTracer = Layer.succeed(
313 Tracer.Tracer,
314 Tracer.make({
315 span: (options) => {
316 const span = new Tracer.NativeSpan(options);
317 if (options.kind === "server") requestSpans.push(span);
318 return span;
319 },
320 }),
321 );
322 const layerRoutes = Layer.effectDiscard(
323 Effect.gen(function* () {
324 const router = yield* HttpRouter.HttpRouter;
325 yield* router.add("GET", "/api/environment", HttpServerResponse.empty());
326 }),
327 );
328 const services = yield* Layer.build(
329 HttpRouter.serve(layerRoutes, { disableListenLog: true, disableLogger: true }).pipe(
330 ServerHttp.withRootRequestSpans,
331 Layer.provideMerge(NodeHttpServer.layerTest),
332 ),
333 ).pipe(Effect.withSpan("server.lifetime"), Effect.provide(layerTracer));
334 // Without a traceparent header, the server alone decides each request's parent.
335 const client = Context.get(services, HttpClient.HttpClient);
336​
337 for (let i = 0; i < 2; i++) {
338 yield* client
339 .execute(HttpClientRequest.get("/api/environment"))
340 .pipe(Effect.provideService(HttpClient.TracerPropagationEnabled, false));
341 }
342 expect(requestSpans.map((span) => span.parent._tag)).toEqual(["None", "None"]);
343 expect(new Set(requestSpans.map((span) => span.traceId)).size).toBe(2);
344 }).pipe(Effect.provide(NodeServices.layer)),
345 );
346});
347​
348const layerFileResponse = Layer.mergeAll(NodeHttpPlatform.layer, NodeServices.layer);
349​
350const makeStaticRequest = Effect.fn("HttpTest.makeStaticRequest")(function* (staticDir: string) {
351 const config = yield* ServerConfig.ServerConfig;
352 const fileSystem = yield* FileSystem.FileSystem;
353 const layerApp = Layer.merge(
354 ServerHttp.layerStaticAndDevRoute,
355 ServerHttp.layerHttpCompression,
356 ).pipe(Layer.provideMerge(NodeHttpPlatform.layer));
357 // HttpRouter.serve prefers outer services; inject the test FileSystem between it and NodeHttpServer.layerTest.
358 const services = yield* Layer.build(
359 HttpRouter.serve(layerApp, { disableListenLog: true }).pipe(
360 Layer.provideMerge(ServerConfig.layer({ ...config, staticDir })),
361 Layer.provideMerge(Layer.succeed(FileSystem.FileSystem, fileSystem)),
362 Layer.provideMerge(NodeHttpServer.layerTest),
363 ),
364 );
365 const client = Context.get(services, HttpClient.HttpClient);
366 return (resource: string, options?: HttpClientRequest.Options) =>
367 client.execute(HttpClientRequest.make(options?.method ?? "GET")(resource, options));
368});
369​
370it.layer(
371 ServerConfig.layerTest(process.cwd(), { prefix: "t3-static-http-test-" }).pipe(
372 Layer.provideMerge(NodeServices.layer),
373 ),
374)("static HTTP responses", (it) => {
375 it.effect("revalidates non-HTML files and returns changed contents", () =>
376 Effect.gen(function* () {
377 const fs = yield* FileSystem.FileSystem;
378 const path = yield* Path.Path;
379 const staticDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-static-cache-" });
380 const assetPath = path.join(staticDir, "app.js");
381 yield* fs.writeFileString(assetPath, 'export const build = "first";');
382 const request = yield* makeStaticRequest(staticDir);
383​
384 const initial = yield* request("/app.js");
385 expect(initial.status).toBe(200);
386 expect(yield* initial.text).toContain("first");
387 const etag = initial.headers["etag"]!;
388 const lastModified = initial.headers["last-modified"]!;
389 expect(etag).toBeTruthy();
390 expect(lastModified).toBeTruthy();
391 for (const headers of [
392 { "if-none-match": etag },
393 { "if-none-match": etag.replace(/^W\//, "") },
394 { "if-none-match": `"other", ${etag}` },
395 { "if-none-match": "*" },
396 { "if-modified-since": lastModified },
397 ]) {
398 const response = yield* request("/app.js", { headers });
399 expect(response.status).toBe(304);
400 expect(response.headers["etag"]).toBe(etag);
401 expect(response.headers["cache-control"]).toBe("no-cache");
402 expect(yield* response.text).toBe("");
403 }
404 const mismatched = yield* request("/app.js", {
405 headers: { "if-none-match": '"another-build"', "if-modified-since": lastModified },
406 });
407 expect(mismatched.status).toBe(200);
408 expect(yield* mismatched.text).toContain("first");
409​
410 yield* fs.writeFileString(assetPath, 'export const build = "the next build";');
411 const changed = yield* request("/app.js", { headers: { "if-none-match": etag } });
412 expect(changed.status).toBe(200);
413 expect(changed.headers["etag"]).not.toBe(etag);
414 expect(yield* changed.text).toContain("next build");
415 }),
416 );
417​
418 it.effect("serves static files without handles and skips fallback reads for HEAD and 304", () =>
419 Effect.gen(function* () {
420 const fs = yield* FileSystem.FileSystem;
421 const path = yield* Path.Path;
422 const staticDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-static-no-open-" });
423 const filePath = path.join(staticDir, "app.txt");
424 const body = "packaged asset";
425 yield* fs.writeFileString(filePath, body);
426 let reads = 0;
427 // Electron asar files can be statted and read even when opening a handle fails.
428 const fileSystem = FileSystem.FileSystem.of({
429 ...fs,
430 open: (candidate, options) =>
431 candidate === filePath
432 ? Effect.fail(
433 PlatformError.systemError({
434 _tag: "NotFound",
435 module: "FileSystem",
436 method: "open",
437 pathOrDescriptor: candidate,
438 }),
439 )
440 : fs.open(candidate, options),
441 readFile: (candidate) =>
442 Effect.gen(function* () {
443 if (candidate === filePath) reads += 1;
444 return yield* fs.readFile(candidate);
445 }),
446 });
447 const request = yield* makeStaticRequest(staticDir).pipe(
448 Effect.provideService(FileSystem.FileSystem, fileSystem),
449 );
450​
451 const get = yield* request("/app.txt");
452 expect(get.status).toBe(200);
453 expect(yield* get.text).toBe(body);
454 expect(reads).toBeGreaterThan(0);
455 const readsAfterGet = reads;
456 const head = yield* request("/app.txt", { method: "HEAD" });
457 expect(head.status).toBe(200);
458 expect(yield* head.text).toBe("");
459 expect(reads).toBe(readsAfterGet);
460 const unchanged = yield* request("/app.txt", {
461 headers: { "if-none-match": get.headers["etag"]! },
462 });
463 expect(unchanged.status).toBe(304);
464 expect(yield* unchanged.text).toBe("");
465 expect(reads).toBe(readsAfterGet);
466 }),
467 );
468​
469 it.effect("serves replacement bytes with matching static fallback length and validators", () =>
470 Effect.gen(function* () {
471 const fs = yield* FileSystem.FileSystem;
472 const path = yield* Path.Path;
473 const staticDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-static-replaced-" });
474 const filePath = path.join(staticDir, "app.txt");
475 const before = DateTime.toDateUtc(DateTime.makeUnsafe("1985-10-26T08:15:00.000Z"));
476 const after = DateTime.toDateUtc(DateTime.makeUnsafe("2015-10-21T16:29:00.000Z"));
477 const replacement = "the replacement asset";
478 const replacementPath = path.join(staticDir, "replacement.txt");
479 yield* fs.writeFileString(filePath, "old");
480 yield* fs.utimes(filePath, before, before);
481 yield* fs.writeFileString(replacementPath, replacement);
482 yield* fs.utimes(replacementPath, after, after);
483 let replaceOnOpen = false;
484 const fileSystem = FileSystem.FileSystem.of({
485 ...fs,
486 open: (candidate, options) =>
487 Effect.gen(function* () {
488 if (candidate !== filePath) return yield* fs.open(candidate, options);
489 if (replaceOnOpen) {
490 yield* fs.rename(replacementPath, filePath);
491 replaceOnOpen = false;
492 }
493 return yield* PlatformError.systemError({
494 _tag: "NotFound",
495 module: "FileSystem",
496 method: "open",
497 pathOrDescriptor: candidate,
498 });
499 }),
500 });
501 const request = yield* makeStaticRequest(staticDir).pipe(
502 Effect.provideService(FileSystem.FileSystem, fileSystem),
503 );
504 const initial = yield* request("/app.txt", { headers: { "accept-encoding": "identity" } });
505 expect(yield* initial.text).toBe("old");
506​
507 replaceOnOpen = true;
508 const response = yield* request("/app.txt", { headers: { "accept-encoding": "identity" } });
509 expect(response.status).toBe(200);
510 expect(response.headers).toMatchObject({
511 "content-length": String(Buffer.byteLength(replacement)),
512 "last-modified": after.toUTCString(),
513 });
514 expect(response.headers["etag"]).not.toBe(initial.headers["etag"]);
515 expect(yield* response.text).toBe(replacement);
516 }),
517 );
518​
519 it.effect("serves changed HTML when deployments preserve its size and timestamp", () =>
520 Effect.gen(function* () {
521 const fs = yield* FileSystem.FileSystem;
522 const path = yield* Path.Path;
523 const staticDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-static-html-" });
524 const indexPath = path.join(staticDir, "index.html");
525 const modifiedAt = DateTime.toDateUtc(DateTime.makeUnsafe("1985-10-26T08:15:00.000Z"));
526 yield* fs.writeFileString(indexPath, "<html>old build</html>");
527 yield* fs.utimes(indexPath, modifiedAt, modifiedAt);
528 const request = yield* makeStaticRequest(staticDir);
529 const initial = yield* request("/");
530 expect(yield* initial.text).toBe("<html>old build</html>");
531 const previousEtag = initial.headers["etag"] ?? '"previous-html"';
532 const nextHtml = "<html>new build</html>";
533 yield* fs.writeFileString(indexPath, nextHtml);
534 yield* fs.utimes(indexPath, modifiedAt, modifiedAt);
535​
536 for (const [resource, headers] of [
537 ["/", { "if-none-match": previousEtag }],
538 ["/threads/example", { "if-modified-since": modifiedAt.toUTCString() }],
539 ["/", { "if-none-match": "*" }],
540 ] as const) {
541 const response = yield* request(resource, { headers });
542 expect(response.status).toBe(200);
543 expect(yield* response.text).toBe(nextHtml);
544 expect(response.headers["cache-control"]).toBe("no-cache");
545 expect(response.headers["content-security-policy"]).toBe("frame-ancestors 'none'");
546 expect(response.headers["x-frame-options"]).toBe("DENY");
547 expect(response.headers["etag"]).toBeUndefined();
548 expect(response.headers["last-modified"]).toBeUndefined();
549 }
550 const head = yield* request("/", {
551 method: "HEAD",
552 headers: { "if-none-match": previousEtag, "accept-encoding": "identity" },
553 });
554 expect(head.status).toBe(200);
555 expect(head.headers["content-length"]).toBe(String(Buffer.byteLength(nextHtml)));
556 expect(yield* head.text).toBe("");
557 }),
558 );
559​
560 it.effect("closes static descriptors after GET, HEAD, 304, and request cancellation", () =>
561 Effect.gen(function* () {
562 const fs = yield* FileSystem.FileSystem;
563 const path = yield* Path.Path;
564 const staticDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-static-close-" });
565 const filePath = path.join(staticDir, "app.txt");
566 const body = "file content\n".repeat(1024);
567 yield* fs.writeFileString(filePath, body);
568 const closed = yield* Queue.unbounded<FileSystem.File>();
569 const blocked = yield* Deferred.make<void>();
570 const active = new Set<FileSystem.File>();
571 let blockAfterOpen = false;
572 let bodyReads = 0;
573 const trackedFileSystem = FileSystem.FileSystem.of({
574 ...fs,
575 open: (candidate, options) =>
576 Effect.gen(function* () {
577 if (candidate !== filePath) return yield* fs.open(candidate, options);
578 let opened: FileSystem.File | undefined;
579 yield* Effect.addFinalizer(() =>
580 Effect.gen(function* () {
581 if (opened === undefined) return;
582 active.delete(opened);
583 yield* Queue.offer(closed, opened);
584 }),
585 );
586 const file = yield* fs.open(candidate, options);
587 opened = file;
588 active.add(file);
589 if (blockAfterOpen) {
590 yield* Deferred.succeed(blocked, undefined);
591 return yield* Effect.never;
592 }
593 return new Proxy(file, {
594 get(target, key) {
595 if (key === "readAlloc") {
596 return (size: number) => {
597 bodyReads += 1;
598 return target.readAlloc(size);
599 };
600 }
601 return Reflect.get(target, key, target);
602 },
603 });
604 }),
605 });
606 const request = yield* makeStaticRequest(staticDir).pipe(
607 Effect.provideService(FileSystem.FileSystem, trackedFileSystem),
608 );
609​
610 const get = yield* request("/app.txt");
611 expect(yield* get.text).toBe(body);
612 yield* Queue.take(closed);
613 expect(active.size).toBe(0);
614 expect(bodyReads).toBeGreaterThan(0);
615 const readsAfterGet = bodyReads;
616 const head = yield* request("/app.txt", {
617 method: "HEAD",
618 headers: { "accept-encoding": "gzip" },
619 });
620 expect(head.status).toBe(200);
621 expect(head.headers["content-encoding"]).toBe("gzip");
622 expect(yield* head.text).toBe("");
623 yield* Queue.take(closed);
624 expect(active.size).toBe(0);
625 expect(bodyReads).toBe(readsAfterGet);
626 const unchanged = yield* request("/app.txt", {
627 headers: { "if-none-match": get.headers["etag"]! },
628 });
629 expect(unchanged.status).toBe(304);
630 yield* Queue.take(closed);
631 expect(active.size).toBe(0);
632 expect(bodyReads).toBe(readsAfterGet);
633​
634 blockAfterOpen = true;
635 const cancelled = yield* request("/app.txt").pipe(Effect.forkChild);
636 yield* Deferred.await(blocked);
637 expect(active.size).toBe(1);
638 yield* Fiber.interrupt(cancelled);
639 yield* Queue.take(closed);
640 expect(active.size).toBe(0);
641 }),
642 );
643});
644​
645describe("video asset byte ranges", () => {
646 it.effect("uses current descriptor metadata after an in-place truncate or extension", () =>
647 Effect.gen(function* () {
648 const fs = yield* FileSystem.FileSystem;
649 const path = yield* Path.Path;
650 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-guarded-current-stat-" });
651 const filePath = path.join(directory, "clip.mp4");
652 for (const [contents, range, method, expected, status, contentRange] of [
653 ["1234", undefined, "GET", "1234", 200, null],
654 ["0123456789abcdef", undefined, "GET", "0123456789abcdef", 200, null],
655 ["1234", "bytes=4-", "GET", "", 416, "bytes */4"],
656 ["1234", "bytes=1-20", "GET", "234", 206, "bytes 1-3/4"],
657 ["0123456789abcdef", "bytes=10-", "GET", "abcdef", 206, "bytes 10-15/16"],
658 ["0123456789abcdef", undefined, "HEAD", "", 200, null],
659 ["", undefined, "GET", "", 200, null],
660 ["", "bytes=0-1", "GET", "", 416, "bytes */0"],
661 ] as const) {
662 yield* fs.writeFileString(filePath, "0123456789");
663 const canonicalPath = yield* fs.realPath(filePath);
664 const file = yield* openMediaFile(canonicalPath);
665 if (!file) throw new Error("Expected an opened media file");
666 yield* fs.writeFileString(filePath, contents);
667 const response = HttpServerResponse.toWeb(
668 yield* assetFileResponse(
669 { path: canonicalPath, file, mimeType: "video/mp4" },
670 range,
671 undefined,
672 method,
673 ),
674 );
675 expect(response.status).toBe(status);
676 expect(response.headers.get("content-range")).toBe(contentRange);
677 if (status !== 416) {
678 expect(response.headers.get("content-length")).toBe(
679 String(method === "HEAD" ? contents.length : expected.length),
680 );
681 }
682 expect(yield* Effect.promise(() => response.text())).toBe(expected);
683 }
684 }).pipe(Effect.provide(layerFileResponse)),
685 );
686​
687 it.effect(
688 "rejects unaddressable ranges before streaming and preserves small ranges on large files",
689 () =>
690 Effect.gen(function* () {
691 const fs = yield* FileSystem.FileSystem;
692 const path = yield* Path.Path;
693 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-guarded-offset-limit-" });
694 const filePath = path.join(directory, "clip.mp4");
695 yield* fs.writeFileString(filePath, "0123456789");
696 const canonicalPath = yield* fs.realPath(filePath);
697 const unsafeOffset = BigInt(Number.MAX_SAFE_INTEGER) + 1n;
698 const size = unsafeOffset + 32n;
699 for (const [range, status] of [
700 [`bytes=${unsafeOffset}-${unsafeOffset}`, 416],
701 [`bytes=0-${unsafeOffset}`, 416],
702 ["bytes=-1", 416],
703 [undefined, 413],
704 ["bytes=0-1", 206],
705 ] as const) {
706 const file = yield* openMediaFile(canonicalPath);
707 if (!file) throw new Error("Expected an opened media file");
708 const info = yield* Effect.promise(() => file.handle.stat({ bigint: true }));
709 info.size = size;
710 const statSpy = vi.spyOn(file.handle, "stat").mockResolvedValue(info);
711 yield* Effect.addFinalizer(() => Effect.sync(() => statSpy.mockRestore()));
712 const response = HttpServerResponse.toWeb(
713 yield* assetFileResponse({ path: canonicalPath, file, mimeType: "video/mp4" }, range),
714 );
715 expect(response.status).toBe(status);
716 if (status === 416) {
717 expect(response.headers.get("content-range")).toBe(`bytes */${size}`);
718 expect(yield* Effect.promise(() => response.text())).toBe("");
719 } else if (status === 206) {
720 expect(response.headers.get("content-range")).toBe(`bytes 0-1/${size}`);
721 expect(yield* Effect.promise(() => response.text())).toBe("01");
722 } else {
723 expect(yield* Effect.promise(() => response.text())).toBe(
724 "File is too large to preview.",
725 );
726 }
727 }
728 }).pipe(Effect.provide(layerFileResponse)),
729 );
730​
731 it.effect("keeps attachment media out of the cache once its signed URL expires", () =>
732 Effect.gen(function* () {
733 const fs = yield* FileSystem.FileSystem;
734 const path = yield* Path.Path;
735 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-attachment-media-" });
736 const filePath = path.join(directory, "audio.wav");
737 yield* fs.writeFileString(filePath, "RIFF");
738 const canonicalPath = yield* fs.realPath(filePath);
739 const response = HttpServerResponse.toWeb(
740 yield* assetFileResponse({ path: canonicalPath, mimeType: "audio/wav" }),
741 );
742 expect(response.headers.get("cache-control")).toBe("private, no-store");
743 expect(response.headers.get("accept-ranges")).toBe("bytes");
744 }).pipe(Effect.provide(layerFileResponse)),
745 );
746​
747 it.effect("closes guarded descriptors after full, HEAD, rejected, and cancelled responses", () =>
748 Effect.gen(function* () {
749 const fs = yield* FileSystem.FileSystem;
750 const path = yield* Path.Path;
751 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-guarded-cleanup-" });
752 const filePath = path.join(directory, "clip.mp4");
753 const bytes = new Uint8Array(1024 * 1024).fill(42);
754 yield* fs.writeFile(filePath, bytes);
755 const canonicalPath = yield* fs.realPath(filePath);
756 for (const mode of ["full", "HEAD", "rejected", "cancelled"] as const) {
757 const file = yield* Effect.scoped(
758 Effect.gen(function* () {
759 const file = yield* openMediaFile(canonicalPath);
760 if (!file) throw new Error("Expected an opened media file");
761 const response = HttpServerResponse.toWeb(
762 yield* assetFileResponse(
763 { path: canonicalPath, file, mimeType: "video/mp4" },
764 mode === "rejected" ? `bytes=${bytes.length}-` : "bytes=0-",
765 undefined,
766 mode === "HEAD" ? "HEAD" : "GET",
767 ),
768 );
769 if (mode === "HEAD") {
770 expect(response.status).toBe(200);
771 expect(response.headers.get("content-length")).toBe(String(bytes.length));
772 expect(response.headers.get("content-range")).toBeNull();
773 expect(yield* Effect.promise(() => response.text())).toBe("");
774 } else if (mode === "rejected") {
775 expect(response.status).toBe(416);
776 expect(yield* Effect.promise(() => response.text())).toBe("");
777 } else if (mode === "cancelled") {
778 const reader = response.body!.getReader();
779 const first = yield* Effect.promise(() => reader.read());
780 expect(first.done).toBe(false);
781 expect(first.value!.byteLength).toBeLessThan(bytes.length);
782 yield* Effect.promise(() => reader.cancel());
783 } else {
784 expect(yield* Effect.promise(() => response.arrayBuffer())).toEqual(bytes.buffer);
785 }
786 return file;
787 }),
788 );
789 expect(file.handle.fd).toBe(-1);
790 }
791 }).pipe(Effect.provide(layerFileResponse)),
792 );
793​
794 it.effect("streams exactly the requested bytes and leaves full downloads intact", () =>
795 Effect.gen(function* () {
796 const fs = yield* FileSystem.FileSystem;
797 const path = yield* Path.Path;
798 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-video-range-" });
799 const file = path.join(directory, "clip.mp4");
800 yield* fs.writeFileString(file, "0123456789");
801 const asset = { path: file, mimeType: "video/mp4" };
802 for (const [header, expected, contentRange] of [
803 ["bytes=0-1", "01", "bytes 0-1/10"],
804 ["bytes=4-", "456789", "bytes 4-9/10"],
805 ["bytes=-3", "789", "bytes 7-9/10"],
806 ["bytes=-999999999999999999999999", "0123456789", "bytes 0-9/10"],
807 ["bytes=8-999999999999999999999999", "89", "bytes 8-9/10"],
808 ] as const) {
809 const response = HttpServerResponse.toWeb(yield* assetFileResponse(asset, header));
810 expect(response.status).toBe(206);
811 expect(response.headers.get("accept-ranges")).toBe("bytes");
812 expect(response.headers.get("content-range")).toBe(contentRange);
813 expect(response.headers.get("content-length")).toBe(String(expected.length));
814 expect(yield* Effect.promise(() => response.text())).toBe(expected);
815 }
816 for (const header of [
817 undefined,
818 "items=0-1",
819 "bytes=0-1,4-5",
820 "bytes=8-2",
821 "bytes=-",
822 "bytes=bad",
823 ]) {
824 const response = HttpServerResponse.toWeb(yield* assetFileResponse(asset, header));
825 expect(response.status).toBe(200);
826 expect(yield* Effect.promise(() => response.text())).toBe("0123456789");
827 }
828 const conditional = HttpServerResponse.toWeb(
829 yield* assetFileResponse(asset, "bytes=0-1", '"old-etag"'),
830 );
831 expect(conditional.status).toBe(200);
832 expect(yield* Effect.promise(() => conditional.text())).toBe("0123456789");
833 const uppercase = HttpServerResponse.toWeb(
834 yield* assetFileResponse({ ...asset, mimeType: "Video/MP4" }, "bytes=0-1"),
835 );
836 expect(uppercase.status).toBe(206);
837 expect(yield* Effect.promise(() => uppercase.text())).toBe("01");
838 const image = HttpServerResponse.toWeb(
839 yield* assetFileResponse({ path: file, mimeType: "image/png" }, "bytes=0-1"),
840 );
841 expect(image.status).toBe(206);
842 expect(image.headers.get("accept-ranges")).toBe("bytes");
843 expect(yield* Effect.promise(() => image.text())).toBe("01");
844 for (const mimeType of ["text/plain", "text/csv", "application/octet-stream"]) {
845 for (const [range, expected, status] of [
846 ["bytes=2-5", "2345", 206],
847 ["bytes=-3", "789", 206],
848 ["bytes=10-", "", 416],
849 ] as const) {
850 const result = HttpServerResponse.toWeb(
851 yield* assetFileResponse({ path: file, mimeType }, range),
852 );
853 expect(result.status).toBe(status);
854 expect(yield* Effect.promise(() => result.text())).toBe(expected);
855 }
856 }
857 }).pipe(Effect.provide(layerFileResponse)),
858 );
859​
860 it.effect(
861 "supports native audio header probes and seeking without changing explicit downloads",
862 () =>
863 Effect.gen(function* () {
864 const fs = yield* FileSystem.FileSystem;
865 const path = yield* Path.Path;
866 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-audio-range-" });
867 const file = path.join(directory, "recording.wav");
868 yield* fs.writeFileString(file, "0123456789");
869 const asset = { path: file, mimeType: "audio/wav" };
870 for (const [header, expected] of [
871 ["bytes=0-1", "01"],
872 ["bytes=5-", "56789"],
873 ] as const) {
874 const response = HttpServerResponse.toWeb(yield* assetFileResponse(asset, header));
875 expect(response.status).toBe(206);
876 expect(response.headers.get("content-type")).toBe("audio/wav");
877 expect(response.headers.get("accept-ranges")).toBe("bytes");
878 expect(response.headers.get("content-length")).toBe(String(expected.length));
879 expect(yield* Effect.promise(() => response.text())).toBe(expected);
880 }
881 const download = HttpServerResponse.toWeb(
882 yield* assetFileResponse({ ...asset, download: true, fileName: "recording.wav" }),
883 );
884 expect(download.status).toBe(200);
885 expect(download.headers.get("content-disposition")).toContain("attachment;");
886 expect(yield* Effect.promise(() => download.text())).toBe("0123456789");
887 }).pipe(Effect.provide(layerFileResponse)),
888 );
889​
890 it.effect("rejects ranges outside the file, including empty files", () =>
891 Effect.gen(function* () {
892 const fs = yield* FileSystem.FileSystem;
893 const path = yield* Path.Path;
894 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-video-range-" });
895 const file = path.join(directory, "clip.mp4");
896 yield* fs.writeFileString(file, "0123456789");
897 for (const header of ["bytes=10-", "bytes=-0", "bytes=999999999999999999999999-"]) {
898 const response = HttpServerResponse.toWeb(
899 yield* assetFileResponse({ path: file, mimeType: "video/mp4" }, header),
900 );
901 expect(response.status).toBe(416);
902 expect(response.headers.get("content-range")).toBe("bytes */10");
903 expect(yield* Effect.promise(() => response.text())).toBe("");
904 }
905 yield* fs.writeFileString(file, "");
906 const empty = HttpServerResponse.toWeb(
907 yield* assetFileResponse({ path: file, mimeType: "video/mp4" }, "bytes=0-1"),
908 );
909 expect(empty.status).toBe(416);
910 expect(empty.headers.get("content-range")).toBe("bytes */0");
911 }).pipe(Effect.provide(layerFileResponse)),
912 );
913});
914​
915describe("assetResponseHeaders", () => {
916 it("sandboxes SVG and other XML assets", () => {
917 expect(assetResponseHeaders("/attachments/user-image.svg")).toMatchObject({
918 "Content-Security-Policy": "default-src 'none'; style-src 'unsafe-inline'; sandbox",
919 "X-Content-Type-Options": "nosniff",
920 });
921 expect(assetResponseHeaders("/attachments/user-image.SVG")).toHaveProperty(
922 "Content-Security-Policy",
923 );
924 for (const name of ["page.xhtml", "page.XHT", "feed.xml", "sheet.xsl", "feed.rss"]) {
925 expect(assetResponseHeaders(`/workspace/${name}`)).toHaveProperty(
926 "Content-Security-Policy",
927 "default-src 'none'; style-src 'unsafe-inline'; sandbox",
928 );
929 }
930 expect(assetResponseHeaders("/workspace/photo.png")).not.toHaveProperty(
931 "Content-Security-Policy",
932 );
933 });
934 it("serves inline attachment documents with their declared mime type", () => {
935 expect(
936 assetResponseHeaders("/attachments/upload.bin", { mimeType: "application/pdf" }),
937 ).toMatchObject({
938 "Content-Type": "application/pdf",
939 });
940 expect(
941 assetResponseHeaders("/attachments/upload.bin", { mimeType: "text/html" }),
942 ).toMatchObject({
943 "Content-Type": "text/html; charset=utf-8",
944 "Content-Security-Policy": "sandbox allow-scripts allow-forms allow-popups allow-downloads",
945 });
946 });
947​
948 it("downloads uploaded documents without executing their content", () => {
949 expect(assetResponseHeaders("/attachments/upload.html", { download: true })).toMatchObject({
950 "Content-Disposition": "attachment",
951 "Content-Security-Policy": "default-src 'none'; sandbox",
952 "Content-Type": "application/octet-stream",
953 });
954 });
955​
956 it("serves the real filename and mime type when the claims carry them", () => {
957 expect(
958 assetResponseHeaders("/attachments/thread-1-abc-pdf.pdf", {
959 download: true,
960 fileName: "Q3 report.pdf",
961 mimeType: "application/pdf",
962 }),
963 ).toMatchObject({
964 "Content-Disposition": 'attachment; filename="Q3 report.pdf"',
965 "Content-Security-Policy": "default-src 'none'; sandbox",
966 "Content-Type": "application/pdf",
967 });
968 });
969​
970 it("keeps renderable mime types as octet-stream downloads", () => {
971 for (const mimeType of [
972 "text/html",
973 "text/xml",
974 "image/svg+xml",
975 "application/xhtml+xml",
976 "application/rss+xml",
977 "APPLICATION/XML",
978 "IMAGE/SVG+XML",
979 "application/xml-dtd",
980 "application/xml-external-parsed-entity",
981 "not a mime",
982 ]) {
983 expect(
984 assetResponseHeaders("/attachments/upload.bin", { download: true, mimeType }),
985 ).toHaveProperty("Content-Type", "application/octet-stream");
986 }
987 });
988});
989​
990describe("downloadContentDisposition", () => {
991 it("quotes plain names and strips quotes and control characters", () => {
992 expect(downloadContentDisposition("report.pdf")).toBe('attachment; filename="report.pdf"');
993 expect(downloadContentDisposition('we"ird\n.pdf')).toBe('attachment; filename="we_ird_.pdf"');
994 });
995​
996 it("adds an RFC 5987 encoded name for non-ASCII filenames", () => {
997 expect(downloadContentDisposition("répört.pdf")).toBe(
998 `attachment; filename="r_p_rt.pdf"; filename*=UTF-8''r%C3%A9p%C3%B6rt.pdf`,
999 );
1000 expect(downloadContentDisposition("résumé'(*).pdf")).toBe(
1001 `attachment; filename="r_sum_'(*).pdf"; filename*=UTF-8''r%C3%A9sum%C3%A9%27%28%2A%29.pdf`,
1002 );
1003 });
1004​
1005 it("does not throw on unpaired surrogates in the filename", () => {
1006 expect(downloadContentDisposition("bad\ud800name.pdf")).toBe(
1007 `attachment; filename="bad_name.pdf"; filename*=UTF-8''bad%EF%BF%BDname.pdf`,
1008 );
1009 });
1010});