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