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