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

http.ts

747 lines28.3 KB

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