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

http.ts

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