The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 03:37 UTC
| 1 | import * as Mime from "effect/http/Mime"; |
| 2 | import { |
| 3 | AuthOrchestrationOperateScope, |
| 4 | AuthOrchestrationReadScope, |
| 5 | EnvironmentHttpApi, |
| 6 | } from "@t3tools/contracts"; |
| 7 | import { isDevProxiedPath } from "@t3tools/shared/devProxy"; |
| 8 | import { injectMcpAppCookieBootstrap, injectMcpAppThemeBootstrap } from "@t3tools/shared/mcpApp"; |
| 9 | import { FILE_PREVIEW_SCROLL_SCRIPT } from "@t3tools/shared/htmlRender"; |
| 10 | import { decodeOtlpTraceRecords } from "@t3tools/shared/observability"; |
| 11 | import * as ByteSize from "effect/ByteSize"; |
| 12 | import * as Context from "effect/Context"; |
| 13 | import * as Effect from "effect/Effect"; |
| 14 | import * as FileSystem from "effect/FileSystem"; |
| 15 | import * as Layer from "effect/Layer"; |
| 16 | import * as Option from "effect/Option"; |
| 17 | import * as Path from "effect/Path"; |
| 18 | import * as Schema from "effect/Schema"; |
| 19 | import * as Stream from "effect/Stream"; |
| 20 | import * as Tracer from "effect/Tracer"; |
| 21 | import { cast, pipe } from "effect/Function"; |
| 22 | import { |
| 23 | HttpClient, |
| 24 | HttpClientResponse, |
| 25 | HttpMiddleware, |
| 26 | HttpRouter, |
| 27 | HttpServerResponse, |
| 28 | HttpServerRequest, |
| 29 | HttpServerRespondable, |
| 30 | } from "effect/http"; |
| 31 | import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder"; |
| 32 | import { OtlpTracer, OtlpSerialization } from "effect/observability"; |
| 33 | |
| 34 | import * as ServerConfig from "./config.ts"; |
| 35 | import { ASSET_ROUTE_PREFIX, readMcpAppHtml, resolveAsset } from "./assets/AssetAccess.ts"; |
| 36 | import { sourceControlMediaResponse } from "./assets/sourceControlMediaResponse.ts"; |
| 37 | import { statMediaFile, streamMediaFile, type OpenMediaFile } from "./assets/MediaFile.ts"; |
| 38 | import { |
| 39 | ATTACHMENT_UPLOAD_ROUTE_PREFIX, |
| 40 | storeAttachmentUpload, |
| 41 | validateAttachmentUploadToken, |
| 42 | } from "./assets/AttachmentUpload.ts"; |
| 43 | import * as BrowserTraceCollector from "./observability/BrowserTraceCollector.ts"; |
| 44 | import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts"; |
| 45 | import { traceRelayRequest } from "./cloud/traceRelayRequest.ts"; |
| 46 | import { |
| 47 | annotateEnvironmentRequest, |
| 48 | failEnvironmentScopeRequired, |
| 49 | failEnvironmentAuthInvalid, |
| 50 | failEnvironmentInternal, |
| 51 | } from "./auth/http.ts"; |
| 52 | import * as ServerEnvironment from "./environment/ServerEnvironment.ts"; |
| 53 | import { WEBHOOK_ROUTE_PREFIX } from "./scheduledTasks/ScheduledTaskService.ts"; |
| 54 | import { |
| 55 | browserApiCorsAllowedHeaders, |
| 56 | browserApiCorsAllowedMethods, |
| 57 | DESKTOP_RENDERER_ORIGINS, |
| 58 | MCP_HTTP_PATH, |
| 59 | } from "./httpCors.ts"; |
| 60 | import { requestUrl } from "./requestUrl.ts"; |
| 61 | |
| 62 | const OTLP_TRACES_PROXY_PATH = "/api/observability/v1/traces"; |
| 63 | const LOOPBACK_HOSTNAMES = new Set(["127.0.0.1", "::1", "localhost"]); |
| 64 | const 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. |
| 67 | const 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. |
| 71 | const DOWNLOAD_MIME_TYPE_PATTERN = /^[\w!#$&^.+-]+\/[\w!#$&^.+-]+$/; |
| 72 | const isSafeDownloadMimeType = (mimeType: string): boolean => |
| 73 | DOWNLOAD_MIME_TYPE_PATTERN.test(mimeType) && |
| 74 | !/(?:^text\/html$|\/xml(?:$|-)|\+xml$)/i.test(mimeType.trim().toLowerCase()); |
| 75 | const isSafeInlineMediaMimeType = (mimeType: string): boolean => |
| 76 | DOWNLOAD_MIME_TYPE_PATTERN.test(mimeType) && /^(?:audio|video)\//i.test(mimeType); |
| 77 | const isSafeInlineDocumentMimeType = (mimeType: string): boolean => |
| 78 | mimeType.toLowerCase() === "application/pdf" || mimeType.toLowerCase() === "text/html"; |
| 79 | |
| 80 | export 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 | }`; |
| 95 | } |
| 96 | |
| 97 | export 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 | }; |
| 141 | } |
| 142 | |
| 143 | function 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 | }; |
| 163 | } |
| 164 | |
| 165 | export 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 | |
| 274 | export const layerHttpCompression = HttpRouter.middleware(HttpMiddleware.compression(), { |
| 275 | global: true, |
| 276 | }); |
| 277 | |
| 278 | export const layerBrowserApiCors = Layer.unwrap( |
| 279 | Effect.gen(function* () { |
| 280 | const config = yield* ServerConfig.ServerConfig; |
| 281 | const devOrigin = config.devUrl?.origin; |
| 282 | // Credentialed dev requests need explicit Vite/Electron origins; packaged desktop uses the default wildcard. |
| 283 | const cors = HttpMiddleware.cors({ |
| 284 | ...(devOrigin |
| 285 | ? { |
| 286 | allowedOrigins: [devOrigin, ...DESKTOP_RENDERER_ORIGINS, ...config.devAllowedOrigins], |
| 287 | credentials: true, |
| 288 | } |
| 289 | : {}), |
| 290 | allowedMethods: browserApiCorsAllowedMethods, |
| 291 | allowedHeaders: browserApiCorsAllowedHeaders, |
| 292 | maxAge: 600, |
| 293 | }); |
| 294 | return HttpRouter.middleware( |
| 295 | (httpEffect) => { |
| 296 | const withCors = cors(httpEffect); |
| 297 | return Effect.flatMap(HttpServerRequest.HttpServerRequest, (request) => |
| 298 | request.url.split("?", 1)[0] === MCP_HTTP_PATH ? httpEffect : withCors, |
| 299 | ); |
| 300 | }, |
| 301 | { global: true }, |
| 302 | ); |
| 303 | }), |
| 304 | ); |
| 305 | |
| 306 | function isLoopbackHostname(hostname: string): boolean { |
| 307 | const normalizedHostname = hostname |
| 308 | .trim() |
| 309 | .toLowerCase() |
| 310 | .replace(/^\[(.*)\]$/, "$1"); |
| 311 | return LOOPBACK_HOSTNAMES.has(normalizedHostname); |
| 312 | } |
| 313 | |
| 314 | function resolveDevRedirectUrl(devUrl: URL, requestUrl: URL): string { |
| 315 | const redirectUrl = new URL(devUrl.toString()); |
| 316 | redirectUrl.pathname = requestUrl.pathname; |
| 317 | redirectUrl.search = requestUrl.search; |
| 318 | redirectUrl.hash = requestUrl.hash; |
| 319 | return redirectUrl.toString(); |
| 320 | } |
| 321 | |
| 322 | const authenticateRawRouteWithScope = |
| 323 | /* Request instrumentation already owns the span; keep this helper in that context. */ |
| 324 | Effect.fnUntraced(function* ( |
| 325 | scope: typeof AuthOrchestrationReadScope | typeof AuthOrchestrationOperateScope, |
| 326 | ) { |
| 327 | const request = yield* HttpServerRequest.HttpServerRequest; |
| 328 | const serverAuth = yield* EnvironmentAuth.EnvironmentAuth; |
| 329 | const session = yield* serverAuth.authenticateHttpRequest(request).pipe( |
| 330 | Effect.catchIf(EnvironmentAuth.isServerAuthCredentialError, (error) => |
| 331 | failEnvironmentAuthInvalid( |
| 332 | EnvironmentAuth.serverAuthCredentialReason(error), |
| 333 | EnvironmentAuth.serverAuthDpopFailureReason(error), |
| 334 | ), |
| 335 | ), |
| 336 | Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) => |
| 337 | failEnvironmentInternal("internal_error", error), |
| 338 | ), |
| 339 | ); |
| 340 | if (!session.scopes.includes(scope)) { |
| 341 | return yield* failEnvironmentScopeRequired(scope); |
| 342 | } |
| 343 | }); |
| 344 | |
| 345 | export const layerServerEnvironmentHttpApi = HttpApiBuilder.group( |
| 346 | EnvironmentHttpApi, |
| 347 | "metadata", |
| 348 | Effect.fnUntraced(function* (handlers) { |
| 349 | const serverEnvironment = yield* ServerEnvironment.ServerEnvironment; |
| 350 | return handlers.handle( |
| 351 | "descriptor", |
| 352 | Effect.fn("environment.metadata.descriptor")(function* (args) { |
| 353 | yield* annotateEnvironmentRequest(args.endpoint.name); |
| 354 | return yield* serverEnvironment.getDescriptor; |
| 355 | }, traceRelayRequest), |
| 356 | ); |
| 357 | }), |
| 358 | ); |
| 359 | |
| 360 | class DecodeOtlpTraceRecordsError extends Schema.TaggedError<DecodeOtlpTraceRecordsError>()( |
| 361 | "DecodeOtlpTraceRecordsError", |
| 362 | { cause: Schema.Defect() }, |
| 363 | ) {} |
| 364 | |
| 365 | // Tracing once-per-second renderer exports would create more spans than it forwards. |
| 366 | export const layerOtlpTracesProxyRoute = HttpRouter.add( |
| 367 | "POST", |
| 368 | OTLP_TRACES_PROXY_PATH, |
| 369 | Effect.gen(function* () { |
| 370 | yield* authenticateRawRouteWithScope(AuthOrchestrationOperateScope); |
| 371 | const request = yield* HttpServerRequest.HttpServerRequest; |
| 372 | const config = yield* ServerConfig.ServerConfig; |
| 373 | const otlpTracesUrl = config.otlpTracesUrl; |
| 374 | const otlpHeaders = config.otlpTracesExport.headers; |
| 375 | const browserTraceCollector = yield* BrowserTraceCollector.BrowserTraceCollector; |
| 376 | const httpClient = yield* HttpClient.HttpClient; |
| 377 | const serialization = yield* OtlpSerialization.OtlpSerialization; |
| 378 | const bodyJson = cast<unknown, OtlpTracer.TraceData>(yield* request.json); |
| 379 | |
| 380 | yield* Effect.try({ |
| 381 | try: () => decodeOtlpTraceRecords(bodyJson), |
| 382 | catch: (cause) => new DecodeOtlpTraceRecordsError({ cause }), |
| 383 | }).pipe( |
| 384 | Effect.flatMap((records) => browserTraceCollector.record(records)), |
| 385 | Effect.catch((cause) => Effect.logWarning("Failed to decode browser OTLP traces", { cause })), |
| 386 | ); |
| 387 | |
| 388 | if (otlpTracesUrl === undefined) { |
| 389 | return HttpServerResponse.empty({ status: 204 }); |
| 390 | } |
| 391 | |
| 392 | return yield* httpClient |
| 393 | .post(otlpTracesUrl, { |
| 394 | body: serialization.traces(bodyJson), |
| 395 | headers: otlpHeaders, |
| 396 | }) |
| 397 | .pipe( |
| 398 | Effect.flatMap(HttpClientResponse.filterStatusOk), |
| 399 | Effect.as(HttpServerResponse.empty({ status: 204 })), |
| 400 | Effect.tapError((cause) => |
| 401 | Effect.logWarning("Failed to export browser OTLP traces", { |
| 402 | cause, |
| 403 | otlpTracesUrl, |
| 404 | }), |
| 405 | ), |
| 406 | Effect.orElseSucceed(() => |
| 407 | HttpServerResponse.text("Trace export failed.", { status: 502 }), |
| 408 | ), |
| 409 | ); |
| 410 | }).pipe( |
| 411 | Effect.catchTags({ |
| 412 | EnvironmentAuthInvalidError: HttpServerRespondable.toResponse, |
| 413 | EnvironmentInternalError: HttpServerRespondable.toResponse, |
| 414 | EnvironmentScopeRequiredError: HttpServerRespondable.toResponse, |
| 415 | }), |
| 416 | Effect.withTracerEnabled(false), |
| 417 | ), |
| 418 | ); |
| 419 | |
| 420 | const requestPath = (request: HttpServerRequest.HttpServerRequest) => { |
| 421 | const queryIndex = request.url.indexOf("?"); |
| 422 | return queryIndex === -1 ? request.url : request.url.slice(0, queryIndex); |
| 423 | }; |
| 424 | |
| 425 | // Signed URLs carry bearer tokens in the path, which URL param redaction cannot reach. |
| 426 | const isSignedUrlRequest = (request: HttpServerRequest.HttpServerRequest) => { |
| 427 | const path = requestPath(request); |
| 428 | return ( |
| 429 | path.startsWith(`${WEBHOOK_ROUTE_PREFIX}/`) || |
| 430 | path.startsWith(`${ASSET_ROUTE_PREFIX}/`) || |
| 431 | path.startsWith(`${ATTACHMENT_UPLOAD_ROUTE_PREFIX}/`) |
| 432 | ); |
| 433 | }; |
| 434 | |
| 435 | // HttpRouter.serve builds routes privately; provide the server-wide TracerDisabledWhen to the served layer. |
| 436 | const layerUntracedRequests = Layer.succeed(HttpMiddleware.TracerDisabledWhen)( |
| 437 | (request) => requestPath(request) === OTLP_TRACES_PROXY_PATH || isSignedUrlRequest(request), |
| 438 | ); |
| 439 | |
| 440 | export const layerUnloggedSignedRequests = HttpRouter.middleware( |
| 441 | (httpEffect) => |
| 442 | Effect.flatMap(HttpServerRequest.HttpServerRequest, (request) => |
| 443 | isSignedUrlRequest(request) ? HttpMiddleware.withLoggerDisabled(httpEffect) : httpEffect, |
| 444 | ), |
| 445 | { global: true }, |
| 446 | ); |
| 447 | |
| 448 | export const withUntracedRequests = Layer.provide(layerUntracedRequests); |
| 449 | |
| 450 | // Request spans otherwise parent to the server's lifetime span, so every request shares one trace id. |
| 451 | export const withRootRequestSpans = <A, E, R>(layer: Layer.Layer<A, E, R>) => |
| 452 | Layer.fromBuild((memoMap, scope) => |
| 453 | Layer.buildWithMemoMap(layer, memoMap, scope).pipe( |
| 454 | // ParentSpan is optional to every reader, so removing it leaves R satisfied. |
| 455 | Effect.updateContext( |
| 456 | (context: Context.Context<R>) => |
| 457 | Context.omit(Tracer.ParentSpan)(context) as Context.Context<R>, |
| 458 | ), |
| 459 | ), |
| 460 | ); |
| 461 | |
| 462 | export const layerAssetRoute = HttpRouter.add( |
| 463 | "GET", |
| 464 | `${ASSET_ROUTE_PREFIX}/*`, |
| 465 | Effect.gen(function* () { |
| 466 | const request = yield* HttpServerRequest.HttpServerRequest; |
| 467 | const url = requestUrl(request); |
| 468 | if (Option.isNone(url)) { |
| 469 | return HttpServerResponse.text("Bad Request", { status: 400 }); |
| 470 | } |
| 471 | |
| 472 | const suffix = url.value.pathname.slice(`${ASSET_ROUTE_PREFIX}/`.length); |
| 473 | const separatorIndex = suffix.indexOf("/"); |
| 474 | if (separatorIndex <= 0) { |
| 475 | return HttpServerResponse.text("Not Found", { status: 404 }); |
| 476 | } |
| 477 | |
| 478 | const asset = yield* resolveAsset( |
| 479 | suffix.slice(0, separatorIndex), |
| 480 | suffix.slice(separatorIndex + 1), |
| 481 | ); |
| 482 | if (!asset) { |
| 483 | return HttpServerResponse.text("Not Found", { status: 404 }); |
| 484 | } |
| 485 | if (asset.kind === "bytes") { |
| 486 | return HttpServerResponse.uint8Array(asset.bytes, { |
| 487 | contentType: asset.mimeType, |
| 488 | headers: { "cache-control": "private, max-age=3600", "x-content-type-options": "nosniff" }, |
| 489 | }); |
| 490 | } |
| 491 | if (asset.kind === "source-control-media") { |
| 492 | return yield* sourceControlMediaResponse(asset, request.headers).pipe( |
| 493 | Effect.tapError((cause) => |
| 494 | // The URL can carry a token in its query string, and the error keeps the request it |
| 495 | // failed on; the host and the failure kind are enough to diagnose. |
| 496 | Effect.logWarning("Failed to fetch source control media.", { |
| 497 | host: URL.canParse(asset.url) ? new URL(asset.url).host : undefined, |
| 498 | reason: cause.reason._tag, |
| 499 | }), |
| 500 | ), |
| 501 | Effect.orElseSucceed(() => |
| 502 | HttpServerResponse.empty({ |
| 503 | status: 502, |
| 504 | headers: { "cache-control": "private, no-store", "x-content-type-options": "nosniff" }, |
| 505 | }), |
| 506 | ), |
| 507 | ); |
| 508 | } |
| 509 | return yield* assetFileResponse( |
| 510 | asset, |
| 511 | request.method === "GET" ? request.headers.range : undefined, |
| 512 | request.headers["if-range"], |
| 513 | request.method === "HEAD" ? "HEAD" : "GET", |
| 514 | ).pipe( |
| 515 | Effect.orElseSucceed(() => HttpServerResponse.text("Internal Server Error", { status: 500 })), |
| 516 | ); |
| 517 | }), |
| 518 | ); |
| 519 | |
| 520 | export const layerAttachmentUploadRoute = HttpRouter.add( |
| 521 | "POST", |
| 522 | `${ATTACHMENT_UPLOAD_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 token = url.value.pathname.slice(`${ATTACHMENT_UPLOAD_ROUTE_PREFIX}/`.length); |
| 531 | if (!token) { |
| 532 | return HttpServerResponse.text("Not Found", { status: 404 }); |
| 533 | } |
| 534 | const claims = yield* validateAttachmentUploadToken(token); |
| 535 | if (!claims) { |
| 536 | return HttpServerResponse.text("Not Found", { status: 404 }); |
| 537 | } |
| 538 | |
| 539 | const contentLengthHeader = request.headers["content-length"]; |
| 540 | if ( |
| 541 | contentLengthHeader !== undefined && |
| 542 | (!Number.isInteger(Number(contentLengthHeader)) || |
| 543 | Number(contentLengthHeader) !== claims.sizeBytes) |
| 544 | ) { |
| 545 | return HttpServerResponse.text("Content-Length must match the upload size.", { |
| 546 | status: 400, |
| 547 | }); |
| 548 | } |
| 549 | |
| 550 | // Keep the request stream in the route scope until the response is sent. |
| 551 | const bodyPull = yield* Stream.toPull(request.stream); |
| 552 | const stored = yield* storeAttachmentUpload(claims, Stream.fromPull(Effect.succeed(bodyPull))); |
| 553 | return stored.ok |
| 554 | ? HttpServerResponse.empty({ status: 204 }) |
| 555 | : HttpServerResponse.text(stored.detail, { status: stored.status }); |
| 556 | }), |
| 557 | ); |
| 558 | |
| 559 | const decodeBuildManifest = Schema.decodeUnknownEffect( |
| 560 | Schema.fromJsonString( |
| 561 | Schema.Record( |
| 562 | Schema.String, |
| 563 | Schema.Struct({ |
| 564 | file: Schema.String, |
| 565 | css: Schema.optional(Schema.Array(Schema.String)), |
| 566 | assets: Schema.optional(Schema.Array(Schema.String)), |
| 567 | }), |
| 568 | ), |
| 569 | ), |
| 570 | ); |
| 571 | |
| 572 | const loadImmutableBuildAssets = Effect.gen(function* () { |
| 573 | const config = yield* ServerConfig.ServerConfig; |
| 574 | const staticDir = |
| 575 | config.staticDir ?? (config.devUrl ? yield* ServerConfig.resolveStaticDir() : undefined); |
| 576 | if (!staticDir) return new Set<string>(); |
| 577 | const fileSystem = yield* FileSystem.FileSystem; |
| 578 | const path = yield* Path.Path; |
| 579 | return yield* fileSystem.readFileString(path.join(staticDir, ".vite", "manifest.json")).pipe( |
| 580 | Effect.flatMap(decodeBuildManifest), |
| 581 | Effect.map( |
| 582 | (manifest) => |
| 583 | new Set( |
| 584 | Object.values(manifest).flatMap((entry) => [ |
| 585 | entry.file, |
| 586 | ...(entry.css ?? []), |
| 587 | ...(entry.assets ?? []), |
| 588 | ]), |
| 589 | ), |
| 590 | ), |
| 591 | Effect.orElseSucceed(() => new Set<string>()), |
| 592 | ); |
| 593 | }); |
| 594 | |
| 595 | const openStaticFile = Effect.fn("openStaticFile")(function* (filePath: string) { |
| 596 | const fileSystem = yield* FileSystem.FileSystem; |
| 597 | const pathInfo = yield* fileSystem.stat(filePath).pipe(Effect.orElseSucceed(() => null)); |
| 598 | if (pathInfo?.type !== "File") return null; |
| 599 | const file = yield* fileSystem.open(filePath, { flag: "r" }).pipe( |
| 600 | Effect.catchTags({ |
| 601 | PlatformError: (error) => |
| 602 | error.reason._tag === "NotFound" ? Effect.succeed(null) : Effect.fail(error), |
| 603 | }), |
| 604 | ); |
| 605 | // Electron asar can stat and read files even when opening a handle returns NotFound. |
| 606 | // Refresh path metadata because the file may have been replaced since the first stat. |
| 607 | const info = yield* file === null ? fileSystem.stat(filePath) : file.stat; |
| 608 | return info.type === "File" ? { file, info } : null; |
| 609 | }); |
| 610 | |
| 611 | const streamStaticFile = (file: FileSystem.File, size: bigint) => |
| 612 | Stream.unfold( |
| 613 | 0n, |
| 614 | Effect.fnUntraced(function* (offset: bigint) { |
| 615 | if (offset >= size) return; |
| 616 | const remaining = size - offset; |
| 617 | const bytes = yield* file.readAlloc(Number(remaining < 65_536n ? remaining : 65_536n)); |
| 618 | if (Option.isNone(bytes)) return; |
| 619 | return [bytes.value, offset + BigInt(bytes.value.byteLength)] as const; |
| 620 | }), |
| 621 | ); |
| 622 | |
| 623 | // The app can approve agents and start threads in one click, so no other site may frame it. |
| 624 | const SPA_FRAME_HEADERS = { |
| 625 | "Content-Security-Policy": "frame-ancestors 'none'", |
| 626 | "X-Frame-Options": "DENY", |
| 627 | }; |
| 628 | |
| 629 | const handleStaticAndDevRequest = Effect.fn("handleStaticAndDevRequest")( |
| 630 | function* (immutableBuildAssets: ReadonlySet<string>) { |
| 631 | const request = yield* HttpServerRequest.HttpServerRequest; |
| 632 | const url = requestUrl(request); |
| 633 | |
| 634 | if (Option.isNone(url)) { |
| 635 | return HttpServerResponse.text("Bad Request", { status: 400 }); |
| 636 | } |
| 637 | |
| 638 | const config = yield* ServerConfig.ServerConfig; |
| 639 | if (config.devUrl && isDevProxiedPath(url.value.pathname)) { |
| 640 | return HttpServerResponse.text("Not Found", { status: 404 }); |
| 641 | } |
| 642 | |
| 643 | if (config.devUrl && isLoopbackHostname(url.value.hostname)) { |
| 644 | return HttpServerResponse.redirect(resolveDevRedirectUrl(config.devUrl, url.value), { |
| 645 | status: 302, |
| 646 | }); |
| 647 | } |
| 648 | |
| 649 | const staticDir = |
| 650 | config.staticDir ?? (config.devUrl ? yield* ServerConfig.resolveStaticDir() : undefined); |
| 651 | if (!staticDir && config.devUrl) { |
| 652 | // `vp run dev --share --built` prints the pairing URL before its first |
| 653 | // web build lands in apps/web/dist. Reload until it does. |
| 654 | return HttpServerResponse.text( |
| 655 | '<!doctype html><meta http-equiv="refresh" content="2"><p>Waiting for the first web build. This page reloads by itself.</p>', |
| 656 | { status: 503, contentType: "text/html", headers: { "Retry-After": "2" } }, |
| 657 | ); |
| 658 | } |
| 659 | if (!staticDir) { |
| 660 | return HttpServerResponse.text("No static directory configured and no dev URL set.", { |
| 661 | status: 503, |
| 662 | }); |
| 663 | } |
| 664 | |
| 665 | const path = yield* Path.Path; |
| 666 | const staticRoot = path.resolve(staticDir); |
| 667 | const staticRequestPath = url.value.pathname === "/" ? "/index.html" : url.value.pathname; |
| 668 | const rawStaticRelativePath = staticRequestPath.replace(/^[/\\]+/, ""); |
| 669 | const hasRawLeadingParentSegment = rawStaticRelativePath.startsWith(".."); |
| 670 | const staticRelativePath = path.normalize(rawStaticRelativePath).replace(/^[/\\]+/, ""); |
| 671 | const hasPathTraversalSegment = staticRelativePath.startsWith(".."); |
| 672 | if ( |
| 673 | staticRelativePath.length === 0 || |
| 674 | hasRawLeadingParentSegment || |
| 675 | hasPathTraversalSegment || |
| 676 | staticRelativePath.includes("\0") |
| 677 | ) { |
| 678 | return HttpServerResponse.text("Invalid static file path", { status: 400 }); |
| 679 | } |
| 680 | |
| 681 | const isWithinStaticRoot = (candidate: string) => |
| 682 | candidate === staticRoot || |
| 683 | candidate.startsWith(staticRoot.endsWith(path.sep) ? staticRoot : `${staticRoot}${path.sep}`); |
| 684 | |
| 685 | let filePath = path.resolve(staticRoot, staticRelativePath); |
| 686 | if (!isWithinStaticRoot(filePath)) { |
| 687 | return HttpServerResponse.text("Invalid static file path", { status: 400 }); |
| 688 | } |
| 689 | |
| 690 | const ext = path.extname(filePath); |
| 691 | if (!ext) { |
| 692 | filePath = path.resolve(filePath, "index.html"); |
| 693 | if (!isWithinStaticRoot(filePath)) { |
| 694 | return HttpServerResponse.text("Invalid static file path", { status: 400 }); |
| 695 | } |
| 696 | } |
| 697 | |
| 698 | let opened = yield* openStaticFile(filePath); |
| 699 | if (!opened) { |
| 700 | filePath = path.resolve(staticRoot, "index.html"); |
| 701 | opened = yield* openStaticFile(filePath); |
| 702 | if (!opened) { |
| 703 | return HttpServerResponse.text("Not Found", { status: 404 }); |
| 704 | } |
| 705 | } |
| 706 | const fileInfo = opened.info; |
| 707 | const mimeType = Option.getOrElse(Mime.getType(filePath), () => "application/octet-stream"); |
| 708 | const isHtml = mimeType === "text/html"; |
| 709 | |
| 710 | // A hash-like name is not enough: custom static files can use the same naming pattern. |
| 711 | const relativePath = path.relative(staticRoot, filePath).replaceAll("\\", "/"); |
| 712 | const immutable = |
| 713 | !isHtml && |
| 714 | /^assets\/.+-[\w-]{8}\.[^/]+$/.test(relativePath) && |
| 715 | immutableBuildAssets.has(relativePath); |
| 716 | const cacheControl = immutable ? "public, max-age=31536000, immutable" : "no-cache"; |
| 717 | const validators = (info: FileSystem.File.Info) => { |
| 718 | // Deployments can preserve HTML size and mtime while changing its bundle URLs. |
| 719 | const modifiedAt = isHtml ? undefined : Option.getOrUndefined(info.mtime); |
| 720 | return modifiedAt |
| 721 | ? { |
| 722 | ETag: `W/"${info.size.toString(16)}-${modifiedAt.getTime().toString(16)}"`, |
| 723 | "Last-Modified": modifiedAt.toUTCString(), |
| 724 | } |
| 725 | : {}; |
| 726 | }; |
| 727 | const headers: Record<string, string> = { |
| 728 | "Cache-Control": cacheControl, |
| 729 | ...(isHtml ? SPA_FRAME_HEADERS : {}), |
| 730 | ...validators(fileInfo), |
| 731 | }; |
| 732 | const etag = headers.ETag; |
| 733 | const lastModified = headers["Last-Modified"]; |
| 734 | |
| 735 | // If-None-Match precedes dates and uses weak GET/HEAD comparison even across compression. |
| 736 | const ifNoneMatch = request.headers["if-none-match"]; |
| 737 | const ifModifiedSince = request.headers["if-modified-since"]; |
| 738 | const unchanged = |
| 739 | ifNoneMatch !== undefined |
| 740 | ? ifNoneMatch.split(",").some((value) => { |
| 741 | const candidate = value.trim(); |
| 742 | return ( |
| 743 | candidate === "*" || |
| 744 | (etag !== undefined && candidate.replace(/^W\//i, "") === etag.slice(2)) |
| 745 | ); |
| 746 | }) |
| 747 | : ifModifiedSince !== undefined && |
| 748 | lastModified !== undefined && |
| 749 | Date.parse(lastModified) <= Date.parse(ifModifiedSince); |
| 750 | if (!isHtml && unchanged) { |
| 751 | return HttpServerResponse.empty({ |
| 752 | status: 304, |
| 753 | headers: { ...headers, Vary: "Accept-Encoding" }, |
| 754 | }); |
| 755 | } |
| 756 | |
| 757 | const contentType = isHtml ? "text/html; charset=utf-8" : mimeType; |
| 758 | if (opened.file === null && request.method !== "HEAD") { |
| 759 | const fileSystem = yield* FileSystem.FileSystem; |
| 760 | // Complete fallback reads before success headers; stream errors arrive too late for a 500. |
| 761 | const bytes = yield* fileSystem.readFile(filePath); |
| 762 | const info = yield* fileSystem.stat(filePath); |
| 763 | return HttpServerResponse.uint8Array(bytes, { |
| 764 | headers: { |
| 765 | "Cache-Control": cacheControl, |
| 766 | ...(isHtml ? SPA_FRAME_HEADERS : {}), |
| 767 | ...validators({ ...info, size: ByteSize.bytes(bytes.byteLength) }), |
| 768 | }, |
| 769 | contentType, |
| 770 | }); |
| 771 | } |
| 772 | // The request scope closes the handle for GET, HEAD, 304, errors, and cancellation. |
| 773 | // HEAD still passes through compression, which selects headers without reading the stream. |
| 774 | return HttpServerResponse.stream( |
| 775 | opened.file === null ? Stream.empty : streamStaticFile(opened.file, fileInfo.size), |
| 776 | { |
| 777 | headers, |
| 778 | contentType, |
| 779 | contentLength: Number(fileInfo.size), |
| 780 | }, |
| 781 | ); |
| 782 | }, |
| 783 | Effect.catchTags({ |
| 784 | PlatformError: () => |
| 785 | Effect.succeed(HttpServerResponse.text("Internal Server Error", { status: 500 })), |
| 786 | }), |
| 787 | ); |
| 788 | |
| 789 | export const layerStaticAndDevRoute = Layer.unwrap( |
| 790 | loadImmutableBuildAssets.pipe( |
| 791 | Effect.map((assets) => HttpRouter.add("GET", "*", handleStaticAndDevRequest(assets))), |
| 792 | ), |
| 793 | ); |