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