| 405 | idleTimeout: 0, |
| 406 | routes: { ...staticRoutes }, |
| 407 | async fetch(req) { |
| 408 | const withCors = (response: Response): Response => |
| 409 | withCorsHeaders(req, response, corsAllowedHosts); |
| 410 | |
| 411 | if (req.method === "OPTIONS" && req.headers.has("origin")) { |
| 412 | return corsPreflightResponse(req, corsAllowedHosts); |
| 413 | } |
| 414 | |
| 415 | const url = new URL(req.url); |
| 416 | |
| 417 | // Unauthenticated liveness probe — carries no data, used by the CLI |
| 418 | // reachability check (which therefore never forwards a credential). |
| 419 | if (url.pathname === "/api/health" && req.method === "GET") { |
| 420 | return withCors(new Response("ok", { headers: { "content-type": "text/plain" } })); |
| 421 | } |
| 422 | |
| 423 | // OAuth callbacks and CIMD documents are reached by the external |
| 424 | // provider, which cannot carry our local bearer. Everything else under |
| 425 | // /api and /mcp requires the bearer. |
| 426 | const skipAuth = isUnauthenticatedOAuthPath(url.pathname); |
| 427 | const isMcpPath = url.pathname === "/mcp" || url.pathname.startsWith("/mcp/"); |
| 428 | const isGatedSurface = url.pathname.startsWith("/api") || isMcpPath; |
| 429 | |
| 430 | if (isGatedSurface && !skipAuth && !isAuthorized(req)) { |
| 431 | return withCors( |
| 432 | new Response("Unauthorized", { |
| 433 | status: 401, |
| 434 | headers: { "www-authenticate": 'Bearer realm="executor"' }, |
| 435 | }), |
| 436 | ); |
| 437 | } |
| 438 | |
| 439 | if (isUnauthenticatedOAuthClientMetadataPath(url.pathname) && req.method === "GET") { |
| 440 | return withCors(oauthClientMetadataResponse(`${url.pathname}${url.search}`, req)); |
| 441 | } |
| 442 | |
| 443 | if (isMcpPath) { |
| 444 | return withCors(await handlers.mcp.handleRequest(req)); |
| 445 | } |
| 446 | |
| 447 | if (url.pathname.startsWith("/api/mcp-sessions/")) { |
| 448 | // GET → paused-execution detail for the approval page; POST → record the |
| 449 | // decision. Both are bearer-gated above. |
| 450 | const handler = |
| 451 | req.method === "GET" |
| 452 | ? handlers.mcp.handlePausedRequest |
| 453 | : handlers.mcp.handleApprovalRequest; |
| 454 | return withCors(await handler(req)); |
| 455 | } |
| 456 | |
| 457 | // OAuth result polling — local-only, served outside the typed API |
| 458 | // because cloud (Cloudflare Workers, stateless) can't back the |
| 459 | // in-memory store. See setOAuthCompletionListener above. |
| 460 | const awaitMatch = /^\/api\/oauth\/await\/([^/?#]+)$/.exec(url.pathname); |
| 461 | if (awaitMatch && req.method === "GET") { |
| 462 | const result = consumeOAuthResult(awaitMatch[1]); |
| 463 | return withCors( |
| 464 | new Response(JSON.stringify(result), { |