| 377 | idleTimeout: 0, |
| 378 | routes: { ...staticRoutes }, |
| 379 | async fetch(req) { |
| 380 | const withCors = (response: Response): Response => |
| 381 | withCorsHeaders(req, response, corsAllowedHosts); |
| 382 | |
| 383 | if (req.method === "OPTIONS" && req.headers.has("origin")) { |
| 384 | return corsPreflightResponse(req, corsAllowedHosts); |
| 385 | } |
| 386 | |
| 387 | const url = new URL(req.url); |
| 388 | |
| 389 | // Unauthenticated liveness probe — carries no data, used by the CLI |
| 390 | // reachability check (which therefore never forwards a credential). |
| 391 | if (url.pathname === "/api/health" && req.method === "GET") { |
| 392 | return withCors(new Response("ok", { headers: { "content-type": "text/plain" } })); |
| 393 | } |
| 394 | |
| 395 | // OAuth callbacks and CIMD documents are reached by the external |
| 396 | // provider, which cannot carry our local bearer. Everything else under |
| 397 | // /api and /mcp requires the bearer. |
| 398 | const skipAuth = isUnauthenticatedOAuthPath(url.pathname); |
| 399 | const isMcpPath = url.pathname === "/mcp" || url.pathname.startsWith("/mcp/"); |
| 400 | const isGatedSurface = url.pathname.startsWith("/api") || isMcpPath; |
| 401 | |
| 402 | if (isGatedSurface && !skipAuth && !isAuthorized(req)) { |
| 403 | return withCors( |
| 404 | new Response("Unauthorized", { |
| 405 | status: 401, |
| 406 | headers: { "www-authenticate": 'Bearer realm="executor"' }, |
| 407 | }), |
| 408 | ); |
| 409 | } |
| 410 | |
| 411 | if (isUnauthenticatedOAuthClientMetadataPath(url.pathname) && req.method === "GET") { |
| 412 | return withCors(oauthClientMetadataResponse(`${url.pathname}${url.search}`, req)); |
| 413 | } |
| 414 | |
| 415 | if (isMcpPath) { |
| 416 | return withCors(await handlers.mcp.handleRequest(req)); |
| 417 | } |
| 418 | |
| 419 | if (url.pathname.startsWith("/api/mcp-sessions/")) { |
| 420 | // GET → paused-execution detail for the approval page; POST → record the |
| 421 | // decision. Both are bearer-gated above. |
| 422 | const handler = |
| 423 | req.method === "GET" |
| 424 | ? handlers.mcp.handlePausedRequest |
| 425 | : handlers.mcp.handleApprovalRequest; |
| 426 | return withCors(await handler(req)); |
| 427 | } |
| 428 | |
| 429 | // OAuth result polling — local-only, served outside the typed API |
| 430 | // because cloud (Cloudflare Workers, stateless) can't back the |
| 431 | // in-memory store. See setOAuthCompletionListener above. |
| 432 | const awaitMatch = /^\/api\/oauth\/await\/([^/?#]+)$/.exec(url.pathname); |
| 433 | if (awaitMatch && req.method === "GET") { |
| 434 | const result = consumeOAuthResult(awaitMatch[1]); |
| 435 | return withCors( |
| 436 | new Response(JSON.stringify(result), { |