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