@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 03:37 UTC

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