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