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 HttpClient,
20 HttpClientResponse,
21 HttpMiddleware,
22 HttpRouter,
23 HttpServerResponse,
24 HttpServerRequest,
25 HttpServerRespondable,
26} from "effect/unstable/http";
27import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder";
28import { OtlpTracer, OtlpSerialization } from "effect/unstable/observability";
29
30import * as ServerConfig from "./config.ts";
31import { ASSET_ROUTE_PREFIX, resolveAsset } from "./assets/AssetAccess.ts";
32import { githubMediaResponse } from "./assets/GitHubMediaFetch.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 otlpHeaders = config.otlpHeaders;
323 const browserTraceCollector = yield* BrowserTraceCollector.BrowserTraceCollector;
324 const httpClient = yield* HttpClient.HttpClient;
325 const serialization = yield* OtlpSerialization.OtlpSerialization;
326 const bodyJson = cast<unknown, OtlpTracer.TraceData>(yield* request.json);
327
328 yield* Effect.try({
329 try: () => decodeOtlpTraceRecords(bodyJson),
330 catch: (cause) => new DecodeOtlpTraceRecordsError({ cause, bodyJson }),
331 }).pipe(
332 Effect.flatMap((records) => browserTraceCollector.record(records)),
333 Effect.catch((cause) =>
334 Effect.logWarning("Failed to decode browser OTLP traces", {
335 cause,
336 bodyJson,
337 }),
338 ),
339 );
340
341 if (otlpTracesUrl === undefined) {
342 return HttpServerResponse.empty({ status: 204 });
343 }
344
345 return yield* httpClient
346 .post(otlpTracesUrl, {
347 body: serialization.traces(bodyJson),
348 headers: otlpHeaders,
349 })
350 .pipe(
351 Effect.flatMap(HttpClientResponse.filterStatusOk),
352 Effect.as(HttpServerResponse.empty({ status: 204 })),
353 Effect.tapError((cause) =>
354 Effect.logWarning("Failed to export browser OTLP traces", {
355 cause,
356 otlpTracesUrl,
357 }),
358 ),
359 Effect.orElseSucceed(() =>
360 HttpServerResponse.text("Trace export failed.", { status: 502 }),
361 ),
362 );
363 }).pipe(
364 Effect.catchTags({
365 EnvironmentAuthInvalidError: HttpServerRespondable.toResponse,
366 EnvironmentInternalError: HttpServerRespondable.toResponse,
367 EnvironmentScopeRequiredError: HttpServerRespondable.toResponse,
368 }),
369 ),
370);
371
372export const assetRouteLayer = HttpRouter.add(
373 "GET",
374 `${ASSET_ROUTE_PREFIX}/*`,
375 Effect.gen(function* () {
376 const request = yield* HttpServerRequest.HttpServerRequest;
377 const url = HttpServerRequest.toURL(request);
378 if (Option.isNone(url)) {
379 return HttpServerResponse.text("Bad Request", { status: 400 });
380 }
381
382 const suffix = url.value.pathname.slice(`${ASSET_ROUTE_PREFIX}/`.length);
383 const separatorIndex = suffix.indexOf("/");
384 if (separatorIndex <= 0) {
385 return HttpServerResponse.text("Not Found", { status: 404 });
386 }
387
388 const asset = yield* resolveAsset(
389 suffix.slice(0, separatorIndex),
390 suffix.slice(separatorIndex + 1),
391 );
392 if (!asset) {
393 return HttpServerResponse.text("Not Found", { status: 404 });
394 }
395 if (asset.kind === "github-media") {
396 return yield* githubMediaResponse(asset, request.headers).pipe(
397 Effect.tapError((cause) =>
398 Effect.logWarning("Failed to fetch GitHub media.", { url: asset.url, cause }),
399 ),
400 Effect.orElseSucceed(() =>
401 HttpServerResponse.empty({
402 status: 502,
403 headers: { "cache-control": "private, no-store", "x-content-type-options": "nosniff" },
404 }),
405 ),
406 );
407 }
408 return yield* assetFileResponse(
409 asset,
410 request.method === "GET" ? request.headers.range : undefined,
411 request.headers["if-range"],
412 request.method === "HEAD" ? "HEAD" : "GET",
413 ).pipe(
414 Effect.orElseSucceed(() => HttpServerResponse.text("Internal Server Error", { status: 500 })),
415 );
416 }),
417);
418
419export const attachmentUploadRouteLayer = HttpRouter.add(
420 "POST",
421 `${ATTACHMENT_UPLOAD_ROUTE_PREFIX}/*`,
422 Effect.gen(function* () {
423 const request = yield* HttpServerRequest.HttpServerRequest;
424 const url = HttpServerRequest.toURL(request);
425 if (Option.isNone(url)) {
426 return HttpServerResponse.text("Bad Request", { status: 400 });
427 }
428
429 const token = url.value.pathname.slice(`${ATTACHMENT_UPLOAD_ROUTE_PREFIX}/`.length);
430 if (!token) {
431 return HttpServerResponse.text("Not Found", { status: 404 });
432 }
433 const claims = yield* validateAttachmentUploadToken(token);
434 if (!claims) {
435 return HttpServerResponse.text("Not Found", { status: 404 });
436 }
437
438 const contentLengthHeader = request.headers["content-length"];
439 if (
440 contentLengthHeader !== undefined &&
441 (!Number.isInteger(Number(contentLengthHeader)) ||
442 Number(contentLengthHeader) !== claims.sizeBytes)
443 ) {
444 return HttpServerResponse.text("Content-Length must match the upload size.", {
445 status: 400,
446 });
447 }
448
449 // Keep the request stream in the route scope until the response is sent.
450 const bodyPull = yield* Stream.toPull(request.stream);
451 const stored = yield* storeAttachmentUpload(claims, Stream.fromPull(Effect.succeed(bodyPull)));
452 return stored.ok
453 ? HttpServerResponse.empty({ status: 204 })
454 : HttpServerResponse.text(stored.detail, { status: stored.status });
455 }),
456);
457
458const decodeBuildManifest = Schema.decodeUnknownEffect(
459 Schema.fromJsonString(
460 Schema.Record(
461 Schema.String,
462 Schema.Struct({
463 file: Schema.String,
464 css: Schema.optional(Schema.Array(Schema.String)),
465 assets: Schema.optional(Schema.Array(Schema.String)),
466 }),
467 ),
468 ),
469);
470
471const loadImmutableBuildAssets = Effect.gen(function* () {
472 const config = yield* ServerConfig.ServerConfig;
473 const staticDir =
474 config.staticDir ?? (config.devUrl ? yield* ServerConfig.resolveStaticDir() : undefined);
475 if (!staticDir) return new Set<string>();
476 const fileSystem = yield* FileSystem.FileSystem;
477 const path = yield* Path.Path;
478 return yield* fileSystem.readFileString(path.join(staticDir, ".vite", "manifest.json")).pipe(
479 Effect.flatMap(decodeBuildManifest),
480 Effect.map(
481 (manifest) =>
482 new Set(
483 Object.values(manifest).flatMap((entry) => [
484 entry.file,
485 ...(entry.css ?? []),
486 ...(entry.assets ?? []),
487 ]),
488 ),
489 ),
490 Effect.orElseSucceed(() => new Set<string>()),
491 );
492});
493
494const openStaticFile = Effect.fn("openStaticFile")(function* (filePath: string) {
495 const fileSystem = yield* FileSystem.FileSystem;
496 // Reject directories and special files before opening. Response metadata comes from the handle.
497 const pathInfo = yield* fileSystem.stat(filePath).pipe(Effect.orElseSucceed(() => null));
498 if (pathInfo?.type !== "File") return null;
499 const file = yield* fileSystem.open(filePath, { flag: "r" });
500 const info = yield* file.stat;
501 return info.type === "File" ? { file, info } : null;
502});
503
504const streamStaticFile = (file: FileSystem.File, size: bigint) =>
505 Stream.unfold(
506 0n,
507 Effect.fnUntraced(function* (offset: bigint) {
508 if (offset >= size) return;
509 const remaining = size - offset;
510 const bytes = yield* file.readAlloc(remaining < 65_536n ? remaining : 65_536n);
511 if (Option.isNone(bytes)) return;
512 return [bytes.value, offset + BigInt(bytes.value.byteLength)] as const;
513 }),
514 );
515
516const handleStaticAndDevRequest = Effect.fn("handleStaticAndDevRequest")(
517 function* (immutableBuildAssets: ReadonlySet<string>) {
518 const request = yield* HttpServerRequest.HttpServerRequest;
519 const url = HttpServerRequest.toURL(request);
520
521 if (Option.isNone(url)) {
522 return HttpServerResponse.text("Bad Request", { status: 400 });
523 }
524
525 const config = yield* ServerConfig.ServerConfig;
526 if (config.devUrl && isDevProxiedPath(url.value.pathname)) {
527 return HttpServerResponse.text("Not Found", { status: 404 });
528 }
529
530 if (config.devUrl && isLoopbackHostname(url.value.hostname)) {
531 return HttpServerResponse.redirect(resolveDevRedirectUrl(config.devUrl, url.value), {
532 status: 302,
533 });
534 }
535
536 const staticDir =
537 config.staticDir ?? (config.devUrl ? yield* ServerConfig.resolveStaticDir() : undefined);
538 if (!staticDir) {
539 return HttpServerResponse.text("No static directory configured and no dev URL set.", {
540 status: 503,
541 });
542 }
543
544 const path = yield* Path.Path;
545 const staticRoot = path.resolve(staticDir);
546 const staticRequestPath = url.value.pathname === "/" ? "/index.html" : url.value.pathname;
547 const rawStaticRelativePath = staticRequestPath.replace(/^[/\\]+/, "");
548 const hasRawLeadingParentSegment = rawStaticRelativePath.startsWith("..");
549 const staticRelativePath = path.normalize(rawStaticRelativePath).replace(/^[/\\]+/, "");
550 const hasPathTraversalSegment = staticRelativePath.startsWith("..");
551 if (
552 staticRelativePath.length === 0 ||
553 hasRawLeadingParentSegment ||
554 hasPathTraversalSegment ||
555 staticRelativePath.includes("\0")
556 ) {
557 return HttpServerResponse.text("Invalid static file path", { status: 400 });
558 }
559
560 const isWithinStaticRoot = (candidate: string) =>
561 candidate === staticRoot ||
562 candidate.startsWith(staticRoot.endsWith(path.sep) ? staticRoot : `${staticRoot}${path.sep}`);
563
564 let filePath = path.resolve(staticRoot, staticRelativePath);
565 if (!isWithinStaticRoot(filePath)) {
566 return HttpServerResponse.text("Invalid static file path", { status: 400 });
567 }
568
569 const ext = path.extname(filePath);
570 if (!ext) {
571 filePath = path.resolve(filePath, "index.html");
572 if (!isWithinStaticRoot(filePath)) {
573 return HttpServerResponse.text("Invalid static file path", { status: 400 });
574 }
575 }
576
577 let opened = yield* openStaticFile(filePath);
578 if (!opened) {
579 filePath = path.resolve(staticRoot, "index.html");
580 opened = yield* openStaticFile(filePath);
581 if (!opened) {
582 return HttpServerResponse.text("Not Found", { status: 404 });
583 }
584 }
585 const fileInfo = opened.info;
586 const mimeType = Mime.getType(filePath) ?? "application/octet-stream";
587 const isHtml = mimeType === "text/html";
588
589 // A hash-like name is not enough: custom static files can use the same naming pattern.
590 const relativePath = path.relative(staticRoot, filePath).replaceAll("\\", "/");
591 const immutable =
592 !isHtml &&
593 /^assets\/.+-[\w-]{8}\.[^/]+$/.test(relativePath) &&
594 immutableBuildAssets.has(relativePath);
595 const headers: Record<string, string> = {
596 "Cache-Control": immutable ? "public, max-age=31536000, immutable" : "no-cache",
597 };
598 // Deployments can preserve HTML size and mtime while changing its bundle URLs.
599 const modifiedAt = isHtml ? undefined : Option.getOrUndefined(fileInfo.mtime);
600 const etag = modifiedAt
601 ? `W/"${fileInfo.size.toString(16)}-${modifiedAt.getTime().toString(16)}"`
602 : undefined;
603 if (etag !== undefined && modifiedAt !== undefined) {
604 headers.ETag = etag;
605 headers["Last-Modified"] = modifiedAt.toUTCString();
606 }
607
608 // If-None-Match takes precedence over dates and uses weak comparison for
609 // GET/HEAD, including when compression changes the transferred bytes.
610 const ifNoneMatch = request.headers["if-none-match"];
611 const ifModifiedSince = request.headers["if-modified-since"];
612 const unchanged =
613 ifNoneMatch !== undefined
614 ? ifNoneMatch.split(",").some((value) => {
615 const candidate = value.trim();
616 return (
617 candidate === "*" ||
618 (etag !== undefined && candidate.replace(/^W\//i, "") === etag.slice(2))
619 );
620 })
621 : ifModifiedSince !== undefined &&
622 modifiedAt !== undefined &&
623 Date.parse(modifiedAt.toUTCString()) <= Date.parse(ifModifiedSince);
624 if (!isHtml && unchanged) {
625 return HttpServerResponse.empty({
626 status: 304,
627 headers: { ...headers, Vary: "Accept-Encoding" },
628 });
629 }
630
631 const contentType = isHtml ? "text/html; charset=utf-8" : mimeType;
632 // The request scope closes the handle for GET, HEAD, 304, errors, and cancellation.
633 // HEAD still passes through compression, which selects headers without reading the stream.
634 return HttpServerResponse.stream(streamStaticFile(opened.file, fileInfo.size), {
635 headers,
636 contentType,
637 contentLength: Number(fileInfo.size),
638 });
639 },
640 Effect.catchTags({
641 PlatformError: () =>
642 Effect.succeed(HttpServerResponse.text("Internal Server Error", { status: 500 })),
643 }),
644);
645
646// Read the installed build's manifest once. Unknown files use revalidation.
647export const staticAndDevRouteLayer = Layer.unwrap(
648 loadImmutableBuildAssets.pipe(
649 Effect.map((assets) => HttpRouter.add("GET", "*", handleStaticAndDevRequest(assets))),
650 ),
651);