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

http.ts

859 lines32.6 KB

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