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

http.ts

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