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

http.ts

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