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

http.ts

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