Open History to see the last commit
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 isSafeInlineMediaMimeType = (mimeType: string): boolean =>
67 DOWNLOAD_MIME_TYPE_PATTERN.test(mimeType) && /^(?:audio|video)\//i.test(mimeType);
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 }`;
87}
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 && isSafeInlineMediaMimeType(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 };
133}
134
135/** A single byte range for native media 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 };
156}
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 isMedia = /^(?:audio|video)\//i.test(headers["Content-Type"] ?? "");
174 if (isMedia) {
175 // Host media can change in place. Do not invite conditional range requests
176 // with validators that cannot establish byte-for-byte identity. Attachment media
177 // carries no `file`, and must not outlive the signed URL that granted it either.
178 headers["Cache-Control"] = "private, no-store";
179 }
180 let status = 200;
181 let offset = 0n;
182 let bytesToRead: bigint | undefined;
183 if (isMedia) {
184 headers["Accept-Ranges"] = "bytes";
185 // If-Range requires a matching validator. A full response is safe when we cannot validate it.
186 if (method === "GET" && rangeHeader && ifRangeHeader === undefined) {
187 const fs = yield* FileSystem.FileSystem;
188 const info = mediaInfo ?? (yield* fs.stat(asset.path));
189 const range = assetByteRange(rangeHeader, info.size);
190 if (range?._tag === "Unsatisfiable") {
191 return HttpServerResponse.empty({
192 status: 416,
193 headers: { ...headers, "Content-Range": `bytes */${info.size}` },
194 });
195 }
196 if (range?._tag === "Range") {
197 status = 206;
198 offset = range.offset;
199 bytesToRead = range.bytesToRead;
200 headers["Content-Range"] = range.contentRange;
201 }
202 }
203 }
204 if (mediaFile && mediaInfo) {
205 const size = bytesToRead ?? mediaInfo.size;
206 headers["Content-Type"] ??= Mime.getType(asset.path) ?? "application/octet-stream";
207 headers["Content-Length"] = String(size);
208 if (!isMedia) {
209 headers["Last-Modified"] = mediaInfo.mtime.toUTCString();
210 headers.ETag = `W/"${mediaInfo.size.toString(16)}-${mediaInfo.mtimeMs.toString(16)}"`;
211 }
212 if (method === "HEAD" || size === 0n) {
213 return HttpServerResponse.empty({ status, headers });
214 }
215 const body = streamMediaFile(mediaFile, offset, size);
216 if (!body) {
217 return HttpServerResponse.text("File is too large to preview.", { status: 413 });
218 }
219 return HttpServerResponse.stream(body, {
220 status,
221 headers,
222 });
223 }
224 return yield* HttpServerResponse.file(asset.path, { status, offset, bytesToRead, headers });
225});
226
227export const httpCompressionLayer = HttpRouter.middleware(HttpMiddleware.compression(), {
228 global: true,
229});
230
231export const browserApiCorsLayer = Layer.unwrap(
232 Effect.gen(function* () {
233 const config = yield* ServerConfig.ServerConfig;
234 const devOrigin = config.devUrl?.origin;
235 // Dev uses credentialed requests from Vite or the Electron custom origin, so both must be
236 // explicit. Packaged desktop omits credentials and uses Effect's default wildcard origin.
237 //
238 // T3CODE_DEV_ALLOWED_ORIGINS covers dev servers reached from a second
239 // origin — a tailnet name, a LAN IP, a phone. Browser dev normally proxies
240 // through Vite and is same-origin (no preflight at all), so this is a
241 // safety net for the desktop renderer and any direct-to-backend caller.
242 return HttpRouter.cors({
243 ...(devOrigin
244 ? {
245 allowedOrigins: [devOrigin, ...DESKTOP_RENDERER_ORIGINS, ...config.devAllowedOrigins],
246 credentials: true,
247 }
248 : {}),
249 allowedMethods: browserApiCorsAllowedMethods,
250 allowedHeaders: browserApiCorsAllowedHeaders,
251 maxAge: 600,
252 });
253 }),
254);
255
256export function isLoopbackHostname(hostname: string): boolean {
257 const normalizedHostname = hostname
258 .trim()
259 .toLowerCase()
260 .replace(/^\[(.*)\]$/, "$1");
261 return LOOPBACK_HOSTNAMES.has(normalizedHostname);
262}
263
264export function resolveDevRedirectUrl(devUrl: URL, requestUrl: URL): string {
265 const redirectUrl = new URL(devUrl.toString());
266 redirectUrl.pathname = requestUrl.pathname;
267 redirectUrl.search = requestUrl.search;
268 redirectUrl.hash = requestUrl.hash;
269 return redirectUrl.toString();
270}
271
272const authenticateRawRouteWithScope = (
273 scope: typeof AuthOrchestrationReadScope | typeof AuthOrchestrationOperateScope,
274) =>
275 Effect.gen(function* () {
276 const request = yield* HttpServerRequest.HttpServerRequest;
277 const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
278 const session = yield* serverAuth.authenticateHttpRequest(request).pipe(
279 Effect.catchIf(EnvironmentAuth.isServerAuthCredentialError, (error) =>
280 failEnvironmentAuthInvalid(
281 EnvironmentAuth.serverAuthCredentialReason(error),
282 EnvironmentAuth.serverAuthDpopFailureReason(error),
283 ),
284 ),
285 Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
286 failEnvironmentInternal("internal_error", error),
287 ),
288 );
289 if (!session.scopes.includes(scope)) {
290 return yield* failEnvironmentScopeRequired(scope);
291 }
292 });
293
294export const serverEnvironmentHttpApiLayer = HttpApiBuilder.group(
295 EnvironmentHttpApi,
296 "metadata",
297 Effect.fnUntraced(function* (handlers) {
298 const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
299 return handlers.handle(
300 "descriptor",
301 Effect.fn("environment.metadata.descriptor")(function* (args) {
302 yield* annotateEnvironmentRequest(args.endpoint.name);
303 return yield* serverEnvironment.getDescriptor;
304 }, traceRelayRequest),
305 );
306 }),
307);
308
309class DecodeOtlpTraceRecordsError extends Data.TaggedError("DecodeOtlpTraceRecordsError")<{
310 readonly cause: unknown;
311 readonly bodyJson: OtlpTracer.TraceData;
312}> {}
313
314export const otlpTracesProxyRouteLayer = HttpRouter.add(
315 "POST",
316 OTLP_TRACES_PROXY_PATH,
317 Effect.gen(function* () {
318 yield* authenticateRawRouteWithScope(AuthOrchestrationOperateScope);
319 const request = yield* HttpServerRequest.HttpServerRequest;
320 const config = yield* ServerConfig.ServerConfig;
321 const otlpTracesUrl = config.otlpTracesUrl;
322 const browserTraceCollector = yield* BrowserTraceCollector.BrowserTraceCollector;
323 const httpClient = yield* HttpClient.HttpClient;
324 const bodyJson = cast<unknown, OtlpTracer.TraceData>(yield* request.json);
325
326 yield* Effect.try({
327 try: () => decodeOtlpTraceRecords(bodyJson),
328 catch: (cause) => new DecodeOtlpTraceRecordsError({ cause, bodyJson }),
329 }).pipe(
330 Effect.flatMap((records) => browserTraceCollector.record(records)),
331 Effect.catch((cause) =>
332 Effect.logWarning("Failed to decode browser OTLP traces", {
333 cause,
334 bodyJson,
335 }),
336 ),
337 );
338
339 if (otlpTracesUrl === undefined) {
340 return HttpServerResponse.empty({ status: 204 });
341 }
342
343 return yield* httpClient
344 .post(otlpTracesUrl, {
345 body: HttpBody.jsonUnsafe(bodyJson),
346 })
347 .pipe(
348 Effect.flatMap(HttpClientResponse.filterStatusOk),
349 Effect.as(HttpServerResponse.empty({ status: 204 })),
350 Effect.tapError((cause) =>
351 Effect.logWarning("Failed to export browser OTLP traces", {
352 cause,
353 otlpTracesUrl,
354 }),
355 ),
356 Effect.orElseSucceed(() =>
357 HttpServerResponse.text("Trace export failed.", { status: 502 }),
358 ),
359 );
360 }).pipe(
361 Effect.catchTags({
362 EnvironmentAuthInvalidError: HttpServerRespondable.toResponse,
363 EnvironmentInternalError: HttpServerRespondable.toResponse,
364 EnvironmentScopeRequiredError: HttpServerRespondable.toResponse,
365 }),
366 ),
367);
368
369export const assetRouteLayer = HttpRouter.add(
370 "GET",
371 `${ASSET_ROUTE_PREFIX}/*`,
372 Effect.gen(function* () {
373 const request = yield* HttpServerRequest.HttpServerRequest;
374 const url = HttpServerRequest.toURL(request);
375 if (Option.isNone(url)) {
376 return HttpServerResponse.text("Bad Request", { status: 400 });
377 }
378
379 const suffix = url.value.pathname.slice(`${ASSET_ROUTE_PREFIX}/`.length);
380 const separatorIndex = suffix.indexOf("/");
381 if (separatorIndex <= 0) {
382 return HttpServerResponse.text("Not Found", { status: 404 });
383 }
384
385 const asset = yield* resolveAsset(
386 suffix.slice(0, separatorIndex),
387 suffix.slice(separatorIndex + 1),
388 );
389 if (!asset) {
390 return HttpServerResponse.text("Not Found", { status: 404 });
391 }
392 return yield* assetFileResponse(
393 asset,
394 request.method === "GET" ? request.headers.range : undefined,
395 request.headers["if-range"],
396 request.method === "HEAD" ? "HEAD" : "GET",
397 ).pipe(
398 Effect.orElseSucceed(() => HttpServerResponse.text("Internal Server Error", { status: 500 })),
399 );
400 }),
401);
402
403export const attachmentUploadRouteLayer = HttpRouter.add(
404 "POST",
405 `${ATTACHMENT_UPLOAD_ROUTE_PREFIX}/*`,
406 Effect.gen(function* () {
407 const request = yield* HttpServerRequest.HttpServerRequest;
408 const url = HttpServerRequest.toURL(request);
409 if (Option.isNone(url)) {
410 return HttpServerResponse.text("Bad Request", { status: 400 });
411 }
412
413 const token = url.value.pathname.slice(`${ATTACHMENT_UPLOAD_ROUTE_PREFIX}/`.length);
414 if (!token) {
415 return HttpServerResponse.text("Not Found", { status: 404 });
416 }
417 const claims = yield* validateAttachmentUploadToken(token);
418 if (!claims) {
419 return HttpServerResponse.text("Not Found", { status: 404 });
420 }
421
422 const contentLengthHeader = request.headers["content-length"];
423 if (
424 contentLengthHeader !== undefined &&
425 (!Number.isInteger(Number(contentLengthHeader)) ||
426 Number(contentLengthHeader) !== claims.sizeBytes)
427 ) {
428 return HttpServerResponse.text("Content-Length must match the upload size.", {
429 status: 400,
430 });
431 }
432
433 // Keep the request stream in the route scope until the response is sent.
434 const bodyPull = yield* Stream.toPull(request.stream);
435 const stored = yield* storeAttachmentUpload(claims, Stream.fromPull(Effect.succeed(bodyPull)));
436 return stored.ok
437 ? HttpServerResponse.empty({ status: 204 })
438 : HttpServerResponse.text(stored.detail, { status: stored.status });
439 }),
440);
441
442const decodeBuildManifest = Schema.decodeUnknownEffect(
443 Schema.fromJsonString(
444 Schema.Record(
445 Schema.String,
446 Schema.Struct({
447 file: Schema.String,
448 css: Schema.optional(Schema.Array(Schema.String)),
449 assets: Schema.optional(Schema.Array(Schema.String)),
450 }),
451 ),
452 ),
453);
454
455const loadImmutableBuildAssets = Effect.gen(function* () {
456 const config = yield* ServerConfig.ServerConfig;
457 const staticDir =
458 config.staticDir ?? (config.devUrl ? yield* ServerConfig.resolveStaticDir() : undefined);
459 if (!staticDir) return new Set<string>();
460 const fileSystem = yield* FileSystem.FileSystem;
461 const path = yield* Path.Path;
462 return yield* fileSystem.readFileString(path.join(staticDir, ".vite", "manifest.json")).pipe(
463 Effect.flatMap(decodeBuildManifest),
464 Effect.map(
465 (manifest) =>
466 new Set(
467 Object.values(manifest).flatMap((entry) => [
468 entry.file,
469 ...(entry.css ?? []),
470 ...(entry.assets ?? []),
471 ]),
472 ),
473 ),
474 Effect.orElseSucceed(() => new Set<string>()),
475 );
476});
477
478const openStaticFile = Effect.fn("openStaticFile")(function* (filePath: string) {
479 const fileSystem = yield* FileSystem.FileSystem;
480 // Reject directories and special files before opening. Response metadata comes from the handle.
481 const pathInfo = yield* fileSystem.stat(filePath).pipe(Effect.orElseSucceed(() => null));
482 if (pathInfo?.type !== "File") return null;
483 const file = yield* fileSystem.open(filePath, { flag: "r" });
484 const info = yield* file.stat;
485 return info.type === "File" ? { file, info } : null;
486});
487
488const streamStaticFile = (file: FileSystem.File, size: bigint) =>
489 Stream.unfold(
490 0n,
491 Effect.fnUntraced(function* (offset: bigint) {
492 if (offset >= size) return;
493 const remaining = size - offset;
494 const bytes = yield* file.readAlloc(remaining < 65_536n ? remaining : 65_536n);
495 if (Option.isNone(bytes)) return;
496 return [bytes.value, offset + BigInt(bytes.value.byteLength)] as const;
497 }),
498 );
499
500const handleStaticAndDevRequest = Effect.fn("handleStaticAndDevRequest")(
501 function* (immutableBuildAssets: ReadonlySet<string>) {
502 const request = yield* HttpServerRequest.HttpServerRequest;
503 const url = HttpServerRequest.toURL(request);
504
505 if (Option.isNone(url)) {
506 return HttpServerResponse.text("Bad Request", { status: 400 });
507 }
508
509 const config = yield* ServerConfig.ServerConfig;
510 if (config.devUrl && isDevProxiedPath(url.value.pathname)) {
511 return HttpServerResponse.text("Not Found", { status: 404 });
512 }
513
514 if (config.devUrl && isLoopbackHostname(url.value.hostname)) {
515 return HttpServerResponse.redirect(resolveDevRedirectUrl(config.devUrl, url.value), {
516 status: 302,
517 });
518 }
519
520 const staticDir =
521 config.staticDir ?? (config.devUrl ? yield* ServerConfig.resolveStaticDir() : undefined);
522 if (!staticDir) {
523 return HttpServerResponse.text("No static directory configured and no dev URL set.", {
524 status: 503,
525 });
526 }
527
528 const path = yield* Path.Path;
529 const staticRoot = path.resolve(staticDir);
530 const staticRequestPath = url.value.pathname === "/" ? "/index.html" : url.value.pathname;
531 const rawStaticRelativePath = staticRequestPath.replace(/^[/\\]+/, "");
532 const hasRawLeadingParentSegment = rawStaticRelativePath.startsWith("..");
533 const staticRelativePath = path.normalize(rawStaticRelativePath).replace(/^[/\\]+/, "");
534 const hasPathTraversalSegment = staticRelativePath.startsWith("..");
535 if (
536 staticRelativePath.length === 0 ||
537 hasRawLeadingParentSegment ||
538 hasPathTraversalSegment ||
539 staticRelativePath.includes("\0")
540 ) {
541 return HttpServerResponse.text("Invalid static file path", { status: 400 });
542 }
543
544 const isWithinStaticRoot = (candidate: string) =>
545 candidate === staticRoot ||
546 candidate.startsWith(staticRoot.endsWith(path.sep) ? staticRoot : `${staticRoot}${path.sep}`);
547
548 let filePath = path.resolve(staticRoot, staticRelativePath);
549 if (!isWithinStaticRoot(filePath)) {
550 return HttpServerResponse.text("Invalid static file path", { status: 400 });
551 }
552
553 const ext = path.extname(filePath);
554 if (!ext) {
555 filePath = path.resolve(filePath, "index.html");
556 if (!isWithinStaticRoot(filePath)) {
557 return HttpServerResponse.text("Invalid static file path", { status: 400 });
558 }
559 }
560
561 let opened = yield* openStaticFile(filePath);
562 if (!opened) {
563 filePath = path.resolve(staticRoot, "index.html");
564 opened = yield* openStaticFile(filePath);
565 if (!opened) {
566 return HttpServerResponse.text("Not Found", { status: 404 });
567 }
568 }
569 const fileInfo = opened.info;
570 const mimeType = Mime.getType(filePath) ?? "application/octet-stream";
571 const isHtml = mimeType === "text/html";
572
573 // A hash-like name is not enough: custom static files can use the same naming pattern.
574 const relativePath = path.relative(staticRoot, filePath).replaceAll("\\", "/");
575 const immutable =
576 !isHtml &&
577 /^assets\/.+-[\w-]{8}\.[^/]+$/.test(relativePath) &&
578 immutableBuildAssets.has(relativePath);
579 const headers: Record<string, string> = {
580 "Cache-Control": immutable ? "public, max-age=31536000, immutable" : "no-cache",
581 };
582 // Deployments can preserve HTML size and mtime while changing its bundle URLs.
583 const modifiedAt = isHtml ? undefined : Option.getOrUndefined(fileInfo.mtime);
584 const etag = modifiedAt
585 ? `W/"${fileInfo.size.toString(16)}-${modifiedAt.getTime().toString(16)}"`
586 : undefined;
587 if (etag !== undefined && modifiedAt !== undefined) {
588 headers.ETag = etag;
589 headers["Last-Modified"] = modifiedAt.toUTCString();
590 }
591
592 // If-None-Match takes precedence over dates and uses weak comparison for
593 // GET/HEAD, including when compression changes the transferred bytes.
594 const ifNoneMatch = request.headers["if-none-match"];
595 const ifModifiedSince = request.headers["if-modified-since"];
596 const unchanged =
597 ifNoneMatch !== undefined
598 ? ifNoneMatch.split(",").some((value) => {
599 const candidate = value.trim();
600 return (
601 candidate === "*" ||
602 (etag !== undefined && candidate.replace(/^W\//i, "") === etag.slice(2))
603 );
604 })
605 : ifModifiedSince !== undefined &&
606 modifiedAt !== undefined &&
607 Date.parse(modifiedAt.toUTCString()) <= Date.parse(ifModifiedSince);
608 if (!isHtml && unchanged) {
609 return HttpServerResponse.empty({
610 status: 304,
611 headers: { ...headers, Vary: "Accept-Encoding" },
612 });
613 }
614
615 const contentType = isHtml ? "text/html; charset=utf-8" : mimeType;
616 // The request scope closes the handle for GET, HEAD, 304, errors, and cancellation.
617 // HEAD still passes through compression, which selects headers without reading the stream.
618 return HttpServerResponse.stream(streamStaticFile(opened.file, fileInfo.size), {
619 headers,
620 contentType,
621 contentLength: Number(fileInfo.size),
622 });
623 },
624 Effect.catchTags({
625 PlatformError: () =>
626 Effect.succeed(HttpServerResponse.text("Internal Server Error", { status: 500 })),
627 }),
628);
629
630// Read the installed build's manifest once. Unknown files use revalidation.
631export const staticAndDevRouteLayer = Layer.unwrap(
632 loadImmutableBuildAssets.pipe(
633 Effect.map((assets) => HttpRouter.add("GET", "*", handleStaticAndDevRequest(assets))),
634 ),
635);