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

http.ts

654 lines24.9 KB

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