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

http.ts

671 lines26.1 KB

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