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

http.ts

668 lines25.9 KB

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