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

http.ts

637 lines24.3 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 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 { statMediaFile, streamMediaFile, type OpenMediaFile } from "./assets/MediaFile.ts";
33import {
34 ATTACHMENT_UPLOAD_ROUTE_PREFIX,
35 storeAttachmentUpload,
36 validateAttachmentUploadToken,
37} from "./assets/AttachmentUpload.ts";
38import * as BrowserTraceCollector from "./observability/BrowserTraceCollector.ts";
39import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
40import { traceRelayRequest } from "./cloud/traceRelayRequest.ts";
41import {
42 annotateEnvironmentRequest,
43 failEnvironmentScopeRequired,
44 failEnvironmentAuthInvalid,
45 failEnvironmentInternal,
46} from "./auth/http.ts";
47import * as ServerEnvironment from "./environment/ServerEnvironment.ts";
48import { browserApiCorsAllowedHeaders, browserApiCorsAllowedMethods } from "./httpCors.ts";
49​
50const OTLP_TRACES_PROXY_PATH = "/api/observability/v1/traces";
51const LOOPBACK_HOSTNAMES = new Set(["127.0.0.1", "::1", "localhost"]);
52const DESKTOP_RENDERER_ORIGINS = ["t3code://app", "t3code-dev://app"];
53const SVG_CONTENT_SECURITY_POLICY = "default-src 'none'; style-src 'unsafe-inline'; sandbox";
54// HTML previews are agent output, not the app. The sandbox gives the document an
55// opaque origin: scripts run, but same-origin cookies, storage, and API calls are
56// out of reach. Relative sibling assets still load through their signed URLs.
57const HTML_CONTENT_SECURITY_POLICY = "sandbox allow-scripts allow-forms allow-popups allow-modals";
58​
59// Types a browser may render as a document if a proxy strips the disposition
60// header. Downloads of these fall back to octet-stream.
61const DOWNLOAD_MIME_TYPE_PATTERN = /^[\w!#$&^.+-]+\/[\w!#$&^.+-]+$/;
62const isSafeDownloadMimeType = (mimeType: string): boolean =>
63 DOWNLOAD_MIME_TYPE_PATTERN.test(mimeType) &&
64 !/(?:^text\/html$|\/xml(?:$|-)|\+xml$)/i.test(mimeType.trim().toLowerCase());
65const isSafeInlineMediaMimeType = (mimeType: string): boolean =>
66 DOWNLOAD_MIME_TYPE_PATTERN.test(mimeType) && /^(?:audio|video)\//i.test(mimeType);
67const isSafeInlineDocumentMimeType = (mimeType: string): boolean =>
68 mimeType.toLowerCase() === "application/pdf" || mimeType.toLowerCase() === "text/html";
69​
70/** RFC 6266 disposition with an ASCII fallback name plus a UTF-8 `filename*`. */
71export function downloadContentDisposition(fileName?: string): string {
72 if (fileName === undefined) {
73 return "attachment";
74 }
75 // toWellFormed: encodeURIComponent throws URIError on unpaired surrogates.
76 const sanitized = fileName.toWellFormed().replace(/[\p{Cc}"\\]/gu, "_");
77 const asciiFallback = sanitized.replace(/[^\u0020-\u007e]/g, "_");
78 const needsExtended = asciiFallback !== sanitized;
79 const extendedName = encodeURIComponent(sanitized).replace(
80 /['()*]/g,
81 (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`,
82 );
83 return `attachment; filename="${asciiFallback}"${
84 needsExtended ? `; filename*=UTF-8''${extendedName}` : ""
85 }`;
87​
88export function assetResponseHeaders(
89 filePath: string,
90 options?: {
91 readonly download?: boolean;
92 readonly fileName?: string;
93 readonly mimeType?: string;
94 },
95): Record<string, string> {
96 const lowerPath = filePath.toLowerCase();
97 const inlineMimeType = options?.mimeType?.split(";", 1)[0]?.trim();
98 return {
99 "Cache-Control": "private, max-age=3600",
100 "X-Content-Type-Options": "nosniff",
101 ...(options?.download
102 ? {
103 "Content-Disposition": downloadContentDisposition(options.fileName),
104 "Content-Security-Policy": "default-src 'none'; sandbox",
105 "Content-Type":
106 options.mimeType !== undefined && isSafeDownloadMimeType(options.mimeType)
107 ? options.mimeType
108 : "application/octet-stream",
109 }
110 : inlineMimeType !== undefined && isSafeInlineMediaMimeType(inlineMimeType)
111 ? { "Content-Type": inlineMimeType }
112 : inlineMimeType !== undefined && isSafeInlineDocumentMimeType(inlineMimeType)
113 ? {
114 "Content-Type":
115 inlineMimeType.toLowerCase() === "text/html"
116 ? "text/html; charset=utf-8"
117 : "application/pdf",
118 ...(inlineMimeType.toLowerCase() === "text/html"
119 ? { "Content-Security-Policy": HTML_CONTENT_SECURITY_POLICY }
120 : {}),
121 }
122 : lowerPath.endsWith(".html") || lowerPath.endsWith(".htm")
123 ? {
124 "Content-Type": "text/html; charset=utf-8",
125 "Content-Security-Policy": HTML_CONTENT_SECURITY_POLICY,
126 }
127 : {}),
128 ...(!options?.download && lowerPath.endsWith(".svg")
129 ? { "Content-Security-Policy": SVG_CONTENT_SECURITY_POLICY }
130 : {}),
131 };
133​
134/** A single byte range for native media readers; unsupported range syntax uses the full file. */
135function assetByteRange(header: string, size: bigint) {
136 const match = /^bytes=(\d*)-(\d*)$/i.exec(header.trim());
137 if (!match || (!match[1] && !match[2])) return null;
138 const first = match[1] ? BigInt(match[1]) : null;
139 const last = match[2] ? BigInt(match[2]) : null;
140 if (first !== null && last !== null && last < first) return null;
141 if (size === 0n || (first !== null && first >= size) || (first === null && last === 0n)) {
142 return { _tag: "Unsatisfiable" as const };
143 }
144 const start = first ?? (last! >= size ? 0n : size - last!);
145 const end = first === null || last === null || last >= size ? size - 1n : last;
146 if (!Number.isSafeInteger(Number(start)) || !Number.isSafeInteger(Number(end))) {
147 return { _tag: "Unsatisfiable" as const };
148 }
149 return {
150 _tag: "Range" as const,
151 offset: start,
152 bytesToRead: end - start + 1n,
153 contentRange: `bytes ${start}-${end}/${size}`,
154 };
156​
157export const assetFileResponse = Effect.fn("assetFileResponse")(function* (
158 asset: {
159 readonly path: string;
160 readonly download?: boolean;
161 readonly fileName?: string;
162 readonly mimeType?: string;
163 readonly file?: OpenMediaFile;
164 },
165 rangeHeader?: string,
166 ifRangeHeader?: string,
167 method: "GET" | "HEAD" = "GET",
168) {
169 const headers = assetResponseHeaders(asset.path, asset);
170 const mediaFile = asset.file;
171 const mediaInfo = mediaFile ? yield* statMediaFile(asset.path, mediaFile) : undefined;
172 const isMedia = /^(?:audio|video)\//i.test(headers["Content-Type"] ?? "");
173 if (isMedia) {
174 // Host media can change in place. Do not invite conditional range requests
175 // with validators that cannot establish byte-for-byte identity. Attachment media
176 // carries no `file`, and must not outlive the signed URL that granted it either.
177 headers["Cache-Control"] = "private, no-store";
178 }
179 let status = 200;
180 let offset = 0n;
181 let bytesToRead: bigint | undefined;
182 if (isMedia) {
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 (!isMedia) {
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 otlpHeaders = config.otlpHeaders;
322 const browserTraceCollector = yield* BrowserTraceCollector.BrowserTraceCollector;
323 const httpClient = yield* HttpClient.HttpClient;
324 const serialization = yield* OtlpSerialization.OtlpSerialization;
325 const bodyJson = cast<unknown, OtlpTracer.TraceData>(yield* request.json);
326​
327 yield* Effect.try({
328 try: () => decodeOtlpTraceRecords(bodyJson),
329 catch: (cause) => new DecodeOtlpTraceRecordsError({ cause, bodyJson }),
330 }).pipe(
331 Effect.flatMap((records) => browserTraceCollector.record(records)),
332 Effect.catch((cause) =>
333 Effect.logWarning("Failed to decode browser OTLP traces", {
334 cause,
335 bodyJson,
336 }),
337 ),
338 );
339​
340 if (otlpTracesUrl === undefined) {
341 return HttpServerResponse.empty({ status: 204 });
342 }
343​
344 return yield* httpClient
345 .post(otlpTracesUrl, {
346 body: serialization.traces(bodyJson),
347 headers: otlpHeaders,
348 })
349 .pipe(
350 Effect.flatMap(HttpClientResponse.filterStatusOk),
351 Effect.as(HttpServerResponse.empty({ status: 204 })),
352 Effect.tapError((cause) =>
353 Effect.logWarning("Failed to export browser OTLP traces", {
354 cause,
355 otlpTracesUrl,
356 }),
357 ),
358 Effect.orElseSucceed(() =>
359 HttpServerResponse.text("Trace export failed.", { status: 502 }),
360 ),
361 );
362 }).pipe(
363 Effect.catchTags({
364 EnvironmentAuthInvalidError: HttpServerRespondable.toResponse,
365 EnvironmentInternalError: HttpServerRespondable.toResponse,
366 EnvironmentScopeRequiredError: HttpServerRespondable.toResponse,
367 }),
368 ),
369);
370​
371export const assetRouteLayer = HttpRouter.add(
372 "GET",
373 `${ASSET_ROUTE_PREFIX}/*`,
374 Effect.gen(function* () {
375 const request = yield* HttpServerRequest.HttpServerRequest;
376 const url = HttpServerRequest.toURL(request);
377 if (Option.isNone(url)) {
378 return HttpServerResponse.text("Bad Request", { status: 400 });
379 }
380​
381 const suffix = url.value.pathname.slice(`${ASSET_ROUTE_PREFIX}/`.length);
382 const separatorIndex = suffix.indexOf("/");
383 if (separatorIndex <= 0) {
384 return HttpServerResponse.text("Not Found", { status: 404 });
385 }
386​
387 const asset = yield* resolveAsset(
388 suffix.slice(0, separatorIndex),
389 suffix.slice(separatorIndex + 1),
390 );
391 if (!asset) {
392 return HttpServerResponse.text("Not Found", { status: 404 });
393 }
394 return yield* assetFileResponse(
395 asset,
396 request.method === "GET" ? request.headers.range : undefined,
397 request.headers["if-range"],
398 request.method === "HEAD" ? "HEAD" : "GET",
399 ).pipe(
400 Effect.orElseSucceed(() => HttpServerResponse.text("Internal Server Error", { status: 500 })),
401 );
402 }),
403);
404​
405export const attachmentUploadRouteLayer = HttpRouter.add(
406 "POST",
407 `${ATTACHMENT_UPLOAD_ROUTE_PREFIX}/*`,
408 Effect.gen(function* () {
409 const request = yield* HttpServerRequest.HttpServerRequest;
410 const url = HttpServerRequest.toURL(request);
411 if (Option.isNone(url)) {
412 return HttpServerResponse.text("Bad Request", { status: 400 });
413 }
414​
415 const token = url.value.pathname.slice(`${ATTACHMENT_UPLOAD_ROUTE_PREFIX}/`.length);
416 if (!token) {
417 return HttpServerResponse.text("Not Found", { status: 404 });
418 }
419 const claims = yield* validateAttachmentUploadToken(token);
420 if (!claims) {
421 return HttpServerResponse.text("Not Found", { status: 404 });
422 }
423​
424 const contentLengthHeader = request.headers["content-length"];
425 if (
426 contentLengthHeader !== undefined &&
427 (!Number.isInteger(Number(contentLengthHeader)) ||
428 Number(contentLengthHeader) !== claims.sizeBytes)
429 ) {
430 return HttpServerResponse.text("Content-Length must match the upload size.", {
431 status: 400,
432 });
433 }
434​
435 // Keep the request stream in the route scope until the response is sent.
436 const bodyPull = yield* Stream.toPull(request.stream);
437 const stored = yield* storeAttachmentUpload(claims, Stream.fromPull(Effect.succeed(bodyPull)));
438 return stored.ok
439 ? HttpServerResponse.empty({ status: 204 })
440 : HttpServerResponse.text(stored.detail, { status: stored.status });
441 }),
442);
443​
444const decodeBuildManifest = Schema.decodeUnknownEffect(
445 Schema.fromJsonString(
446 Schema.Record(
447 Schema.String,
448 Schema.Struct({
449 file: Schema.String,
450 css: Schema.optional(Schema.Array(Schema.String)),
451 assets: Schema.optional(Schema.Array(Schema.String)),
452 }),
453 ),
454 ),
455);
456​
457const loadImmutableBuildAssets = Effect.gen(function* () {
458 const config = yield* ServerConfig.ServerConfig;
459 const staticDir =
460 config.staticDir ?? (config.devUrl ? yield* ServerConfig.resolveStaticDir() : undefined);
461 if (!staticDir) return new Set<string>();
462 const fileSystem = yield* FileSystem.FileSystem;
463 const path = yield* Path.Path;
464 return yield* fileSystem.readFileString(path.join(staticDir, ".vite", "manifest.json")).pipe(
465 Effect.flatMap(decodeBuildManifest),
466 Effect.map(
467 (manifest) =>
468 new Set(
469 Object.values(manifest).flatMap((entry) => [
470 entry.file,
471 ...(entry.css ?? []),
472 ...(entry.assets ?? []),
473 ]),
474 ),
475 ),
476 Effect.orElseSucceed(() => new Set<string>()),
477 );
478});
479​
480const openStaticFile = Effect.fn("openStaticFile")(function* (filePath: string) {
481 const fileSystem = yield* FileSystem.FileSystem;
482 // Reject directories and special files before opening. Response metadata comes from the handle.
483 const pathInfo = yield* fileSystem.stat(filePath).pipe(Effect.orElseSucceed(() => null));
484 if (pathInfo?.type !== "File") return null;
485 const file = yield* fileSystem.open(filePath, { flag: "r" });
486 const info = yield* file.stat;
487 return info.type === "File" ? { file, info } : null;
488});
489​
490const streamStaticFile = (file: FileSystem.File, size: bigint) =>
491 Stream.unfold(
492 0n,
493 Effect.fnUntraced(function* (offset: bigint) {
494 if (offset >= size) return;
495 const remaining = size - offset;
496 const bytes = yield* file.readAlloc(remaining < 65_536n ? remaining : 65_536n);
497 if (Option.isNone(bytes)) return;
498 return [bytes.value, offset + BigInt(bytes.value.byteLength)] as const;
499 }),
500 );
501​
502const handleStaticAndDevRequest = Effect.fn("handleStaticAndDevRequest")(
503 function* (immutableBuildAssets: ReadonlySet<string>) {
504 const request = yield* HttpServerRequest.HttpServerRequest;
505 const url = HttpServerRequest.toURL(request);
506​
507 if (Option.isNone(url)) {
508 return HttpServerResponse.text("Bad Request", { status: 400 });
509 }
510​
511 const config = yield* ServerConfig.ServerConfig;
512 if (config.devUrl && isDevProxiedPath(url.value.pathname)) {
513 return HttpServerResponse.text("Not Found", { status: 404 });
514 }
515​
516 if (config.devUrl && isLoopbackHostname(url.value.hostname)) {
517 return HttpServerResponse.redirect(resolveDevRedirectUrl(config.devUrl, url.value), {
518 status: 302,
519 });
520 }
521​
522 const staticDir =
523 config.staticDir ?? (config.devUrl ? yield* ServerConfig.resolveStaticDir() : undefined);
524 if (!staticDir) {
525 return HttpServerResponse.text("No static directory configured and no dev URL set.", {
526 status: 503,
527 });
528 }
529​
530 const path = yield* Path.Path;
531 const staticRoot = path.resolve(staticDir);
532 const staticRequestPath = url.value.pathname === "/" ? "/index.html" : url.value.pathname;
533 const rawStaticRelativePath = staticRequestPath.replace(/^[/\\]+/, "");
534 const hasRawLeadingParentSegment = rawStaticRelativePath.startsWith("..");
535 const staticRelativePath = path.normalize(rawStaticRelativePath).replace(/^[/\\]+/, "");
536 const hasPathTraversalSegment = staticRelativePath.startsWith("..");
537 if (
538 staticRelativePath.length === 0 ||
539 hasRawLeadingParentSegment ||
540 hasPathTraversalSegment ||
541 staticRelativePath.includes("\0")
542 ) {
543 return HttpServerResponse.text("Invalid static file path", { status: 400 });
544 }
545​
546 const isWithinStaticRoot = (candidate: string) =>
547 candidate === staticRoot ||
548 candidate.startsWith(staticRoot.endsWith(path.sep) ? staticRoot : `${staticRoot}${path.sep}`);
549​
550 let filePath = path.resolve(staticRoot, staticRelativePath);
551 if (!isWithinStaticRoot(filePath)) {
552 return HttpServerResponse.text("Invalid static file path", { status: 400 });
553 }
554​
555 const ext = path.extname(filePath);
556 if (!ext) {
557 filePath = path.resolve(filePath, "index.html");
558 if (!isWithinStaticRoot(filePath)) {
559 return HttpServerResponse.text("Invalid static file path", { status: 400 });
560 }
561 }
562​
563 let opened = yield* openStaticFile(filePath);
564 if (!opened) {
565 filePath = path.resolve(staticRoot, "index.html");
566 opened = yield* openStaticFile(filePath);
567 if (!opened) {
568 return HttpServerResponse.text("Not Found", { status: 404 });
569 }
570 }
571 const fileInfo = opened.info;
572 const mimeType = Mime.getType(filePath) ?? "application/octet-stream";
573 const isHtml = mimeType === "text/html";
574​
575 // A hash-like name is not enough: custom static files can use the same naming pattern.
576 const relativePath = path.relative(staticRoot, filePath).replaceAll("\\", "/");
577 const immutable =
578 !isHtml &&
579 /^assets\/.+-[\w-]{8}\.[^/]+$/.test(relativePath) &&
580 immutableBuildAssets.has(relativePath);
581 const headers: Record<string, string> = {
582 "Cache-Control": immutable ? "public, max-age=31536000, immutable" : "no-cache",
583 };
584 // Deployments can preserve HTML size and mtime while changing its bundle URLs.
585 const modifiedAt = isHtml ? undefined : Option.getOrUndefined(fileInfo.mtime);
586 const etag = modifiedAt
587 ? `W/"${fileInfo.size.toString(16)}-${modifiedAt.getTime().toString(16)}"`
588 : undefined;
589 if (etag !== undefined && modifiedAt !== undefined) {
590 headers.ETag = etag;
591 headers["Last-Modified"] = modifiedAt.toUTCString();
592 }
593​
594 // If-None-Match takes precedence over dates and uses weak comparison for
595 // GET/HEAD, including when compression changes the transferred bytes.
596 const ifNoneMatch = request.headers["if-none-match"];
597 const ifModifiedSince = request.headers["if-modified-since"];
598 const unchanged =
599 ifNoneMatch !== undefined
600 ? ifNoneMatch.split(",").some((value) => {
601 const candidate = value.trim();
602 return (
603 candidate === "*" ||
604 (etag !== undefined && candidate.replace(/^W\//i, "") === etag.slice(2))
605 );
606 })
607 : ifModifiedSince !== undefined &&
608 modifiedAt !== undefined &&
609 Date.parse(modifiedAt.toUTCString()) <= Date.parse(ifModifiedSince);
610 if (!isHtml && unchanged) {
611 return HttpServerResponse.empty({
612 status: 304,
613 headers: { ...headers, Vary: "Accept-Encoding" },
614 });
615 }
616​
617 const contentType = isHtml ? "text/html; charset=utf-8" : mimeType;
618 // The request scope closes the handle for GET, HEAD, 304, errors, and cancellation.
619 // HEAD still passes through compression, which selects headers without reading the stream.
620 return HttpServerResponse.stream(streamStaticFile(opened.file, fileInfo.size), {
621 headers,
622 contentType,
623 contentLength: Number(fileInfo.size),
624 });
625 },
626 Effect.catchTags({
627 PlatformError: () =>
628 Effect.succeed(HttpServerResponse.text("Internal Server Error", { status: 500 })),
629 }),
630);
631​
632// Read the installed build's manifest once. Unknown files use revalidation.
633export const staticAndDevRouteLayer = Layer.unwrap(
634 loadImmutableBuildAssets.pipe(
635 Effect.map((assets) => HttpRouter.add("GET", "*", handleStaticAndDevRequest(assets))),
636 ),
637);