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