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

http.ts

810 lines30.8 KB

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