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

http.ts

632 lines23.9 KB

1import Mime from "@effect/platform-node/Mime";
2import {
3 AuthOrchestrationOperateScope,
4 AuthOrchestrationReadScope,
5 EnvironmentHttpApi,
6} from "@t3tools/contracts";
7import { isDevProxiedPath } from "@t3tools/shared/devProxy";
8import { decodeOtlpTraceRecords } from "@t3tools/shared/observability";
9import * as Data from "effect/Data";
10import * as Effect from "effect/Effect";
11import * as FileSystem from "effect/FileSystem";
12import * as Layer from "effect/Layer";
13import * as Option from "effect/Option";
14import * as Path from "effect/Path";
15import * as Schema from "effect/Schema";
16import * as Stream from "effect/Stream";
17import { cast } from "effect/Function";
18import {
19 HttpBody,
20 HttpClient,
21 HttpClientResponse,
22 HttpMiddleware,
23 HttpRouter,
24 HttpServerResponse,
25 HttpServerRequest,
26 HttpServerRespondable,
27} from "effect/unstable/http";
28import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder";
29import { OtlpTracer } from "effect/unstable/observability";
30​
31import * as ServerConfig from "./config.ts";
32import { ASSET_ROUTE_PREFIX, resolveAsset } from "./assets/AssetAccess.ts";
33import { statMediaFile, streamMediaFile, type OpenMediaFile } from "./assets/MediaFile.ts";
34import {
35 ATTACHMENT_UPLOAD_ROUTE_PREFIX,
36 storeAttachmentUpload,
37 validateAttachmentUploadToken,
38} from "./assets/AttachmentUpload.ts";
39import * as BrowserTraceCollector from "./observability/BrowserTraceCollector.ts";
40import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
41import { traceRelayRequest } from "./cloud/traceRelayRequest.ts";
42import {
43 annotateEnvironmentRequest,
44 failEnvironmentScopeRequired,
45 failEnvironmentAuthInvalid,
46 failEnvironmentInternal,
47} from "./auth/http.ts";
48import * as ServerEnvironment from "./environment/ServerEnvironment.ts";
49import { browserApiCorsAllowedHeaders, browserApiCorsAllowedMethods } from "./httpCors.ts";
50​
51const OTLP_TRACES_PROXY_PATH = "/api/observability/v1/traces";
52const LOOPBACK_HOSTNAMES = new Set(["127.0.0.1", "::1", "localhost"]);
53const DESKTOP_RENDERER_ORIGINS = ["t3code://app", "t3code-dev://app"];
54const SVG_CONTENT_SECURITY_POLICY = "default-src 'none'; style-src 'unsafe-inline'; sandbox";
55// HTML previews are agent output, not the app. The sandbox gives the document an
56// opaque origin: scripts run, but same-origin cookies, storage, and API calls are
57// out of reach. Relative sibling assets still load through their signed URLs.
58const HTML_CONTENT_SECURITY_POLICY = "sandbox allow-scripts allow-forms allow-popups allow-modals";
59​
60// Types a browser may render as a document if a proxy strips the disposition
61// header. Downloads of these fall back to octet-stream.
62const DOWNLOAD_MIME_TYPE_PATTERN = /^[\w!#$&^.+-]+\/[\w!#$&^.+-]+$/;
63const isSafeDownloadMimeType = (mimeType: string): boolean =>
64 DOWNLOAD_MIME_TYPE_PATTERN.test(mimeType) &&
65 !/(?:^text\/html$|\/xml(?:$|-)|\+xml$)/i.test(mimeType.trim().toLowerCase());
66const isSafeInlineVideoMimeType = (mimeType: string): boolean =>
67 DOWNLOAD_MIME_TYPE_PATTERN.test(mimeType) && mimeType.toLowerCase().startsWith("video/");
68const isSafeInlineDocumentMimeType = (mimeType: string): boolean =>
69 mimeType.toLowerCase() === "application/pdf" || mimeType.toLowerCase() === "text/html";
70​
71/** RFC 6266 disposition with an ASCII fallback name plus a UTF-8 `filename*`. */
72export function downloadContentDisposition(fileName?: string): string {
73 if (fileName === undefined) {
74 return "attachment";
75 }
76 // toWellFormed: encodeURIComponent throws URIError on unpaired surrogates.
77 const sanitized = fileName.toWellFormed().replace(/[\p{Cc}"\\]/gu, "_");
78 const asciiFallback = sanitized.replace(/[^\u0020-\u007e]/g, "_");
79 const needsExtended = asciiFallback !== sanitized;
80 const extendedName = encodeURIComponent(sanitized).replace(
81 /['()*]/g,
82 (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`,
83 );
84 return `attachment; filename="${asciiFallback}"${
85 needsExtended ? `; filename*=UTF-8''${extendedName}` : ""
86 }`;
88​
89export function assetResponseHeaders(
90 filePath: string,
91 options?: {
92 readonly download?: boolean;
93 readonly fileName?: string;
94 readonly mimeType?: string;
95 },
96): Record<string, string> {
97 const lowerPath = filePath.toLowerCase();
98 const inlineMimeType = options?.mimeType?.split(";", 1)[0]?.trim();
99 return {
100 "Cache-Control": "private, max-age=3600",
101 "X-Content-Type-Options": "nosniff",
102 ...(options?.download
103 ? {
104 "Content-Disposition": downloadContentDisposition(options.fileName),
105 "Content-Security-Policy": "default-src 'none'; sandbox",
106 "Content-Type":
107 options.mimeType !== undefined && isSafeDownloadMimeType(options.mimeType)
108 ? options.mimeType
109 : "application/octet-stream",
110 }
111 : inlineMimeType !== undefined && isSafeInlineVideoMimeType(inlineMimeType)
112 ? { "Content-Type": inlineMimeType }
113 : inlineMimeType !== undefined && isSafeInlineDocumentMimeType(inlineMimeType)
114 ? {
115 "Content-Type":
116 inlineMimeType.toLowerCase() === "text/html"
117 ? "text/html; charset=utf-8"
118 : "application/pdf",
119 ...(inlineMimeType.toLowerCase() === "text/html"
120 ? { "Content-Security-Policy": HTML_CONTENT_SECURITY_POLICY }
121 : {}),
122 }
123 : lowerPath.endsWith(".html") || lowerPath.endsWith(".htm")
124 ? {
125 "Content-Type": "text/html; charset=utf-8",
126 "Content-Security-Policy": HTML_CONTENT_SECURITY_POLICY,
127 }
128 : {}),
129 ...(!options?.download && lowerPath.endsWith(".svg")
130 ? { "Content-Security-Policy": SVG_CONTENT_SECURITY_POLICY }
131 : {}),
132 };
134​
135/** A single byte range for native video readers; unsupported range syntax uses the full file. */
136function assetByteRange(header: string, size: bigint) {
137 const match = /^bytes=(\d*)-(\d*)$/i.exec(header.trim());
138 if (!match || (!match[1] && !match[2])) return null;
139 const first = match[1] ? BigInt(match[1]) : null;
140 const last = match[2] ? BigInt(match[2]) : null;
141 if (first !== null && last !== null && last < first) return null;
142 if (size === 0n || (first !== null && first >= size) || (first === null && last === 0n)) {
143 return { _tag: "Unsatisfiable" as const };
144 }
145 const start = first ?? (last! >= size ? 0n : size - last!);
146 const end = first === null || last === null || last >= size ? size - 1n : last;
147 if (!Number.isSafeInteger(Number(start)) || !Number.isSafeInteger(Number(end))) {
148 return { _tag: "Unsatisfiable" as const };
149 }
150 return {
151 _tag: "Range" as const,
152 offset: start,
153 bytesToRead: end - start + 1n,
154 contentRange: `bytes ${start}-${end}/${size}`,
155 };
157​
158export const assetFileResponse = Effect.fn("assetFileResponse")(function* (
159 asset: {
160 readonly path: string;
161 readonly download?: boolean;
162 readonly fileName?: string;
163 readonly mimeType?: string;
164 readonly file?: OpenMediaFile;
165 },
166 rangeHeader?: string,
167 ifRangeHeader?: string,
168 method: "GET" | "HEAD" = "GET",
169) {
170 const headers = assetResponseHeaders(asset.path, asset);
171 const mediaFile = asset.file;
172 const mediaInfo = mediaFile ? yield* statMediaFile(asset.path, mediaFile) : undefined;
173 const isVideo = headers["Content-Type"]?.toLowerCase().startsWith("video/") === true;
174 if (mediaFile && isVideo) {
175 // Host videos can change in place. Do not invite conditional range requests
176 // with validators that cannot establish byte-for-byte identity.
177 headers["Cache-Control"] = "private, no-store";
178 }
179 let status = 200;
180 let offset = 0n;
181 let bytesToRead: bigint | undefined;
182 if (isVideo) {
183 headers["Accept-Ranges"] = "bytes";
184 // If-Range requires a matching validator. A full response is safe when we cannot validate it.
185 if (method === "GET" && rangeHeader && ifRangeHeader === undefined) {
186 const fs = yield* FileSystem.FileSystem;
187 const info = mediaInfo ?? (yield* fs.stat(asset.path));
188 const range = assetByteRange(rangeHeader, info.size);
189 if (range?._tag === "Unsatisfiable") {
190 return HttpServerResponse.empty({
191 status: 416,
192 headers: { ...headers, "Content-Range": `bytes */${info.size}` },
193 });
194 }
195 if (range?._tag === "Range") {
196 status = 206;
197 offset = range.offset;
198 bytesToRead = range.bytesToRead;
199 headers["Content-Range"] = range.contentRange;
200 }
201 }
202 }
203 if (mediaFile && mediaInfo) {
204 const size = bytesToRead ?? mediaInfo.size;
205 headers["Content-Type"] ??= Mime.getType(asset.path) ?? "application/octet-stream";
206 headers["Content-Length"] = String(size);
207 if (!isVideo) {
208 headers["Last-Modified"] = mediaInfo.mtime.toUTCString();
209 headers.ETag = `W/"${mediaInfo.size.toString(16)}-${mediaInfo.mtimeMs.toString(16)}"`;
210 }
211 if (method === "HEAD" || size === 0n) {
212 return HttpServerResponse.empty({ status, headers });
213 }
214 const body = streamMediaFile(mediaFile, offset, size);
215 if (!body) {
216 return HttpServerResponse.text("File is too large to preview.", { status: 413 });
217 }
218 return HttpServerResponse.stream(body, {
219 status,
220 headers,
221 });
222 }
223 return yield* HttpServerResponse.file(asset.path, { status, offset, bytesToRead, headers });
224});
225​
226export const httpCompressionLayer = HttpRouter.middleware(HttpMiddleware.compression(), {
227 global: true,
228});
229​
230export const browserApiCorsLayer = Layer.unwrap(
231 Effect.gen(function* () {
232 const config = yield* ServerConfig.ServerConfig;
233 const devOrigin = config.devUrl?.origin;
234 // Dev uses credentialed requests from Vite or the Electron custom origin, so both must be
235 // explicit. Packaged desktop omits credentials and uses Effect's default wildcard origin.
236 //
237 // T3CODE_DEV_ALLOWED_ORIGINS covers dev servers reached from a second
238 // origin — a tailnet name, a LAN IP, a phone. Browser dev normally proxies
239 // through Vite and is same-origin (no preflight at all), so this is a
240 // safety net for the desktop renderer and any direct-to-backend caller.
241 return HttpRouter.cors({
242 ...(devOrigin
243 ? {
244 allowedOrigins: [devOrigin, ...DESKTOP_RENDERER_ORIGINS, ...config.devAllowedOrigins],
245 credentials: true,
246 }
247 : {}),
248 allowedMethods: browserApiCorsAllowedMethods,
249 allowedHeaders: browserApiCorsAllowedHeaders,
250 maxAge: 600,
251 });
252 }),
253);
254​
255export function isLoopbackHostname(hostname: string): boolean {
256 const normalizedHostname = hostname
257 .trim()
258 .toLowerCase()
259 .replace(/^\[(.*)\]$/, "$1");
260 return LOOPBACK_HOSTNAMES.has(normalizedHostname);
262​
263export function resolveDevRedirectUrl(devUrl: URL, requestUrl: URL): string {
264 const redirectUrl = new URL(devUrl.toString());
265 redirectUrl.pathname = requestUrl.pathname;
266 redirectUrl.search = requestUrl.search;
267 redirectUrl.hash = requestUrl.hash;
268 return redirectUrl.toString();
270​
271const authenticateRawRouteWithScope = (
272 scope: typeof AuthOrchestrationReadScope | typeof AuthOrchestrationOperateScope,
273) =>
274 Effect.gen(function* () {
275 const request = yield* HttpServerRequest.HttpServerRequest;
276 const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
277 const session = yield* serverAuth.authenticateHttpRequest(request).pipe(
278 Effect.catchIf(EnvironmentAuth.isServerAuthCredentialError, (error) =>
279 failEnvironmentAuthInvalid(
280 EnvironmentAuth.serverAuthCredentialReason(error),
281 EnvironmentAuth.serverAuthDpopFailureReason(error),
282 ),
283 ),
284 Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
285 failEnvironmentInternal("internal_error", error),
286 ),
287 );
288 if (!session.scopes.includes(scope)) {
289 return yield* failEnvironmentScopeRequired(scope);
290 }
291 });
292​
293export const serverEnvironmentHttpApiLayer = HttpApiBuilder.group(
294 EnvironmentHttpApi,
295 "metadata",
296 Effect.fnUntraced(function* (handlers) {
297 const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
298 return handlers.handle(
299 "descriptor",
300 Effect.fn("environment.metadata.descriptor")(function* (args) {
301 yield* annotateEnvironmentRequest(args.endpoint.name);
302 return yield* serverEnvironment.getDescriptor;
303 }, traceRelayRequest),
304 );
305 }),
306);
307​
308class DecodeOtlpTraceRecordsError extends Data.TaggedError("DecodeOtlpTraceRecordsError")<{
309 readonly cause: unknown;
310 readonly bodyJson: OtlpTracer.TraceData;
311}> {}
312​
313export const otlpTracesProxyRouteLayer = HttpRouter.add(
314 "POST",
315 OTLP_TRACES_PROXY_PATH,
316 Effect.gen(function* () {
317 yield* authenticateRawRouteWithScope(AuthOrchestrationOperateScope);
318 const request = yield* HttpServerRequest.HttpServerRequest;
319 const config = yield* ServerConfig.ServerConfig;
320 const otlpTracesUrl = config.otlpTracesUrl;
321 const browserTraceCollector = yield* BrowserTraceCollector.BrowserTraceCollector;
322 const httpClient = yield* HttpClient.HttpClient;
323 const bodyJson = cast<unknown, OtlpTracer.TraceData>(yield* request.json);
324​
325 yield* Effect.try({
326 try: () => decodeOtlpTraceRecords(bodyJson),
327 catch: (cause) => new DecodeOtlpTraceRecordsError({ cause, bodyJson }),
328 }).pipe(
329 Effect.flatMap((records) => browserTraceCollector.record(records)),
330 Effect.catch((cause) =>
331 Effect.logWarning("Failed to decode browser OTLP traces", {
332 cause,
333 bodyJson,
334 }),
335 ),
336 );
337​
338 if (otlpTracesUrl === undefined) {
339 return HttpServerResponse.empty({ status: 204 });
340 }
341​
342 return yield* httpClient
343 .post(otlpTracesUrl, {
344 body: HttpBody.jsonUnsafe(bodyJson),
345 })
346 .pipe(
347 Effect.flatMap(HttpClientResponse.filterStatusOk),
348 Effect.as(HttpServerResponse.empty({ status: 204 })),
349 Effect.tapError((cause) =>
350 Effect.logWarning("Failed to export browser OTLP traces", {
351 cause,
352 otlpTracesUrl,
353 }),
354 ),
355 Effect.orElseSucceed(() =>
356 HttpServerResponse.text("Trace export failed.", { status: 502 }),
357 ),
358 );
359 }).pipe(
360 Effect.catchTags({
361 EnvironmentAuthInvalidError: HttpServerRespondable.toResponse,
362 EnvironmentInternalError: HttpServerRespondable.toResponse,
363 EnvironmentScopeRequiredError: HttpServerRespondable.toResponse,
364 }),
365 ),
366);
367​
368export const assetRouteLayer = HttpRouter.add(
369 "GET",
370 `${ASSET_ROUTE_PREFIX}/*`,
371 Effect.gen(function* () {
372 const request = yield* HttpServerRequest.HttpServerRequest;
373 const url = HttpServerRequest.toURL(request);
374 if (Option.isNone(url)) {
375 return HttpServerResponse.text("Bad Request", { status: 400 });
376 }
377​
378 const suffix = url.value.pathname.slice(`${ASSET_ROUTE_PREFIX}/`.length);
379 const separatorIndex = suffix.indexOf("/");
380 if (separatorIndex <= 0) {
381 return HttpServerResponse.text("Not Found", { status: 404 });
382 }
383​
384 const asset = yield* resolveAsset(
385 suffix.slice(0, separatorIndex),
386 suffix.slice(separatorIndex + 1),
387 );
388 if (!asset) {
389 return HttpServerResponse.text("Not Found", { status: 404 });
390 }
391 return yield* assetFileResponse(
392 asset,
393 request.method === "GET" ? request.headers.range : undefined,
394 request.headers["if-range"],
395 request.method === "HEAD" ? "HEAD" : "GET",
396 ).pipe(
397 Effect.orElseSucceed(() => HttpServerResponse.text("Internal Server Error", { status: 500 })),
398 );
399 }),
400);
401​
402export const attachmentUploadRouteLayer = HttpRouter.add(
403 "POST",
404 `${ATTACHMENT_UPLOAD_ROUTE_PREFIX}/*`,
405 Effect.gen(function* () {
406 const request = yield* HttpServerRequest.HttpServerRequest;
407 const url = HttpServerRequest.toURL(request);
408 if (Option.isNone(url)) {
409 return HttpServerResponse.text("Bad Request", { status: 400 });
410 }
411​
412 const token = url.value.pathname.slice(`${ATTACHMENT_UPLOAD_ROUTE_PREFIX}/`.length);
413 if (!token) {
414 return HttpServerResponse.text("Not Found", { status: 404 });
415 }
416 const claims = yield* validateAttachmentUploadToken(token);
417 if (!claims) {
418 return HttpServerResponse.text("Not Found", { status: 404 });
419 }
420​
421 const contentLengthHeader = request.headers["content-length"];
422 if (
423 contentLengthHeader !== undefined &&
424 (!Number.isInteger(Number(contentLengthHeader)) ||
425 Number(contentLengthHeader) !== claims.sizeBytes)
426 ) {
427 return HttpServerResponse.text("Content-Length must match the upload size.", {
428 status: 400,
429 });
430 }
431​
432 // Keep the request stream in the route scope until the response is sent.
433 const bodyPull = yield* Stream.toPull(request.stream);
434 const stored = yield* storeAttachmentUpload(claims, Stream.fromPull(Effect.succeed(bodyPull)));
435 return stored.ok
436 ? HttpServerResponse.empty({ status: 204 })
437 : HttpServerResponse.text(stored.detail, { status: stored.status });
438 }),
439);
440​
441const decodeBuildManifest = Schema.decodeUnknownEffect(
442 Schema.fromJsonString(
443 Schema.Record(
444 Schema.String,
445 Schema.Struct({
446 file: Schema.String,
447 css: Schema.optional(Schema.Array(Schema.String)),
448 assets: Schema.optional(Schema.Array(Schema.String)),
449 }),
450 ),
451 ),
452);
453​
454const loadImmutableBuildAssets = Effect.gen(function* () {
455 const config = yield* ServerConfig.ServerConfig;
456 const staticDir =
457 config.staticDir ?? (config.devUrl ? yield* ServerConfig.resolveStaticDir() : undefined);
458 if (!staticDir) return new Set<string>();
459 const fileSystem = yield* FileSystem.FileSystem;
460 const path = yield* Path.Path;
461 return yield* fileSystem.readFileString(path.join(staticDir, ".vite", "manifest.json")).pipe(
462 Effect.flatMap(decodeBuildManifest),
463 Effect.map(
464 (manifest) =>
465 new Set(
466 Object.values(manifest).flatMap((entry) => [
467 entry.file,
468 ...(entry.css ?? []),
469 ...(entry.assets ?? []),
470 ]),
471 ),
472 ),
473 Effect.orElseSucceed(() => new Set<string>()),
474 );
475});
476​
477const openStaticFile = Effect.fn("openStaticFile")(function* (filePath: string) {
478 const fileSystem = yield* FileSystem.FileSystem;
479 // Reject directories and special files before opening. Response metadata comes from the handle.
480 const pathInfo = yield* fileSystem.stat(filePath).pipe(Effect.orElseSucceed(() => null));
481 if (pathInfo?.type !== "File") return null;
482 const file = yield* fileSystem.open(filePath, { flag: "r" });
483 const info = yield* file.stat;
484 return info.type === "File" ? { file, info } : null;
485});
486​
487const streamStaticFile = (file: FileSystem.File, size: bigint) =>
488 Stream.unfold(
489 0n,
490 Effect.fnUntraced(function* (offset: bigint) {
491 if (offset >= size) return;
492 const remaining = size - offset;
493 const bytes = yield* file.readAlloc(remaining < 65_536n ? remaining : 65_536n);
494 if (Option.isNone(bytes)) return;
495 return [bytes.value, offset + BigInt(bytes.value.byteLength)] as const;
496 }),
497 );
498​
499const handleStaticAndDevRequest = Effect.fn("handleStaticAndDevRequest")(
500 function* (immutableBuildAssets: ReadonlySet<string>) {
501 const request = yield* HttpServerRequest.HttpServerRequest;
502 const url = HttpServerRequest.toURL(request);
503​
504 if (Option.isNone(url)) {
505 return HttpServerResponse.text("Bad Request", { status: 400 });
506 }
507​
508 const config = yield* ServerConfig.ServerConfig;
509 if (config.devUrl && isDevProxiedPath(url.value.pathname)) {
510 return HttpServerResponse.text("Not Found", { status: 404 });
511 }
512​
513 if (config.devUrl && isLoopbackHostname(url.value.hostname)) {
514 return HttpServerResponse.redirect(resolveDevRedirectUrl(config.devUrl, url.value), {
515 status: 302,
516 });
517 }
518​
519 const staticDir =
520 config.staticDir ?? (config.devUrl ? yield* ServerConfig.resolveStaticDir() : undefined);
521 if (!staticDir) {
522 return HttpServerResponse.text("No static directory configured and no dev URL set.", {
523 status: 503,
524 });
525 }
526​
527 const path = yield* Path.Path;
528 const staticRoot = path.resolve(staticDir);
529 const staticRequestPath = url.value.pathname === "/" ? "/index.html" : url.value.pathname;
530 const rawStaticRelativePath = staticRequestPath.replace(/^[/\\]+/, "");
531 const hasRawLeadingParentSegment = rawStaticRelativePath.startsWith("..");
532 const staticRelativePath = path.normalize(rawStaticRelativePath).replace(/^[/\\]+/, "");
533 const hasPathTraversalSegment = staticRelativePath.startsWith("..");
534 if (
535 staticRelativePath.length === 0 ||
536 hasRawLeadingParentSegment ||
537 hasPathTraversalSegment ||
538 staticRelativePath.includes("\0")
539 ) {
540 return HttpServerResponse.text("Invalid static file path", { status: 400 });
541 }
542​
543 const isWithinStaticRoot = (candidate: string) =>
544 candidate === staticRoot ||
545 candidate.startsWith(staticRoot.endsWith(path.sep) ? staticRoot : `${staticRoot}${path.sep}`);
546​
547 let filePath = path.resolve(staticRoot, staticRelativePath);
548 if (!isWithinStaticRoot(filePath)) {
549 return HttpServerResponse.text("Invalid static file path", { status: 400 });
550 }
551​
552 const ext = path.extname(filePath);
553 if (!ext) {
554 filePath = path.resolve(filePath, "index.html");
555 if (!isWithinStaticRoot(filePath)) {
556 return HttpServerResponse.text("Invalid static file path", { status: 400 });
557 }
558 }
559​
560 let opened = yield* openStaticFile(filePath);
561 if (!opened) {
562 filePath = path.resolve(staticRoot, "index.html");
563 opened = yield* openStaticFile(filePath);
564 if (!opened) {
565 return HttpServerResponse.text("Not Found", { status: 404 });
566 }
567 }
568 const fileInfo = opened.info;
569​
570 // A hash-like name is not enough: custom static files can use the same naming pattern.
571 const relativePath = path.relative(staticRoot, filePath).replaceAll("\\", "/");
572 const immutable =
573 /^assets\/.+-[\w-]{8}\.[^/]+$/.test(relativePath) && immutableBuildAssets.has(relativePath);
574 const headers: Record<string, string> = {
575 "Cache-Control": immutable ? "public, max-age=31536000, immutable" : "no-cache",
576 };
577 const modifiedAt = Option.getOrUndefined(fileInfo.mtime);
578 const etag = modifiedAt
579 ? `W/"${fileInfo.size.toString(16)}-${modifiedAt.getTime().toString(16)}"`
580 : undefined;
581 if (etag !== undefined && modifiedAt !== undefined) {
582 headers.ETag = etag;
583 headers["Last-Modified"] = modifiedAt.toUTCString();
584 }
585​
586 // If-None-Match takes precedence over dates and uses weak comparison for
587 // GET/HEAD, including when compression changes the transferred bytes.
588 const ifNoneMatch = request.headers["if-none-match"];
589 const ifModifiedSince = request.headers["if-modified-since"];
590 const unchanged =
591 ifNoneMatch !== undefined
592 ? ifNoneMatch.split(",").some((value) => {
593 const candidate = value.trim();
594 return (
595 candidate === "*" ||
596 (etag !== undefined && candidate.replace(/^W\//i, "") === etag.slice(2))
597 );
598 })
599 : ifModifiedSince !== undefined &&
600 modifiedAt !== undefined &&
601 Date.parse(modifiedAt.toUTCString()) <= Date.parse(ifModifiedSince);
602 if (unchanged) {
603 return HttpServerResponse.empty({
604 status: 304,
605 headers: { ...headers, Vary: "Accept-Encoding" },
606 });
607 }
608​
609 const contentType =
610 path.extname(filePath) === ".html"
611 ? "text/html; charset=utf-8"
612 : (Mime.getType(filePath) ?? "application/octet-stream");
613 // The request scope closes the handle for GET, HEAD, 304, errors, and cancellation.
614 // HEAD still passes through compression, which selects headers without reading the stream.
615 return HttpServerResponse.stream(streamStaticFile(opened.file, fileInfo.size), {
616 headers,
617 contentType,
618 contentLength: Number(fileInfo.size),
619 });
620 },
621 Effect.catchTags({
622 PlatformError: () =>
623 Effect.succeed(HttpServerResponse.text("Internal Server Error", { status: 500 })),
624 }),
625);
626​
627// Read the installed build's manifest once. Unknown files use revalidation.
628export const staticAndDevRouteLayer = Layer.unwrap(
629 loadImmutableBuildAssets.pipe(
630 Effect.map((assets) => HttpRouter.add("GET", "*", handleStaticAndDevRequest(assets))),
631 ),
632);