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