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