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