@productbrain/mcp 0.0.1-beta.1660 → 0.0.1-beta.16622
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.env.mcp.example +1 -1
- package/README.md +67 -0
- package/dist/chunk-EZJ2DV6F.js +2490 -0
- package/dist/chunk-EZJ2DV6F.js.map +1 -0
- package/dist/chunk-KYZUAHTL.js +12542 -0
- package/dist/chunk-KYZUAHTL.js.map +1 -0
- package/dist/cli/index.js +1 -1
- package/dist/http.js +462 -1288
- package/dist/http.js.map +1 -1
- package/dist/index.js +10 -27
- package/dist/index.js.map +1 -1
- package/dist/{setup-6DPGRAQS.js → setup-3EM3LSDE.js} +22 -122
- package/dist/setup-3EM3LSDE.js.map +1 -0
- package/dist/views/src/entry-cards/index.html +108 -90
- package/dist/views/src/graph-constellation/index.html +109 -91
- package/package.json +12 -10
- package/dist/chunk-AMJILQKI.js +0 -1052
- package/dist/chunk-AMJILQKI.js.map +0 -1
- package/dist/chunk-OJTGZZ3C.js +0 -14663
- package/dist/chunk-OJTGZZ3C.js.map +0 -1
- package/dist/setup-6DPGRAQS.js.map +0 -1
package/dist/http.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/http.ts","../src/brand/logo-markup.ts","../src/lib/refresh-token.ts","../src/sessionCap.ts","../src/httpErrors.ts"],"sourcesContent":["/**\n * HTTP transport entry point for Product Brain MCP.\n *\n * Serves the MCP protocol over Streamable HTTP for web clients\n * (Claude web app, API consumers) that can't spawn local processes.\n *\n * Implements the full MCP OAuth 2.1 spec (Nov 2025):\n * 1. Protected Resource Metadata (/.well-known/oauth-protected-resource)\n * 2. Authorization Server Metadata (/.well-known/oauth-authorization-server)\n * 3. Dynamic Client Registration (POST /register)\n * 4. Authorization Code + PKCE (GET/POST /authorize)\n * 5. Token Exchange (POST /oauth/token)\n *\n * Env:\n * CONVEX_SITE_URL — Convex deployment URL (defaults to cloud)\n * PORT / MCP_PORT — Listen port (default 3000)\n * CORS_ORIGINS — Comma-separated allowed origins (default: all)\n * PB_MODULES — Comma-separated modules (default: core,gitchain,arch)\n */\n\nimport { createHash, randomUUID } from \"node:crypto\";\nimport express from \"express\";\nimport { StreamableHTTPServerTransport } from \"@modelcontextprotocol/sdk/server/streamableHttp.js\";\nimport { isInitializeRequest } from \"@modelcontextprotocol/sdk/types.js\";\nimport rateLimit from \"express-rate-limit\";\n\nimport { bootstrapHttp, DEFAULT_CLOUD_URL } from \"./client.js\";\nimport { runWithAuth, hashKey, getKeyState } from \"./auth.js\";\nimport { createProductBrainServer, SERVER_VERSION } from \"./server.js\";\nimport { initAnalytics, shutdownAnalytics, getPostHogClient } from \"./analytics.js\";\nimport { initFeatureFlags } from \"./featureFlags.js\";\nimport { appLogoMarkup, appLogoStyles } from \"./brand/logo-markup.js\";\nimport {\n signRefreshToken,\n verifyRefreshToken,\n} from \"./lib/refresh-token.js\";\nimport { planKeyAdmission, countKeySessions } from \"./sessionCap.js\";\nimport {\n send429,\n buildRateLimitError,\n buildAuthLockoutError,\n buildSessionCapError,\n} from \"./httpErrors.js\";\n\n// ── Bootstrap ───────────────────────────────────────────────────────────\n\nbootstrapHttp();\ninitAnalytics();\ninitFeatureFlags(getPostHogClient());\n\nconst PORT = parseInt(process.env.PORT ?? process.env.MCP_PORT ?? \"3002\", 10);\n\nfunction baseUrl(req: any): string {\n const proto = req.headers[\"x-forwarded-proto\"] ?? req.protocol ?? \"http\";\n const host = req.headers.host ?? `localhost:${PORT}`;\n return `${proto}://${host}`;\n}\n\n// ── Express App ─────────────────────────────────────────────────────────\n\nconst app = express();\n// Required when behind a reverse proxy (e.g. Railway): rate limiter uses X-Forwarded-For\n// and throws ERR_ERL_UNEXPECTED_X_FORWARDED_FOR if trust proxy is false.\napp.set(\"trust proxy\", 1);\napp.use(express.json());\n\n// CORS — defaults to https://claude.ai (per REMOTE.md). Override via CORS_ORIGINS env var.\nconst ALLOWED_ORIGINS = (process.env.CORS_ORIGINS ?? \"https://claude.ai\")\n .split(\",\")\n .map((o) => o.trim())\n .filter(Boolean);\n\napp.use((_req: any, res: any, next: any) => {\n const origin = _req.headers.origin;\n if (origin && ALLOWED_ORIGINS.includes(origin)) {\n res.setHeader(\"Access-Control-Allow-Origin\", origin);\n }\n res.setHeader(\"Access-Control-Allow-Methods\", \"GET, POST, DELETE, OPTIONS\");\n res.setHeader(\n \"Access-Control-Allow-Headers\",\n \"Content-Type, Authorization, Mcp-Session-Id, Last-Event-Id\",\n );\n // Retry-After is exposed so browser MCP clients (default origin https://claude.ai)\n // can read the structured-429 retry timing from JS, not just from the JSON body.\n res.setHeader(\"Access-Control-Expose-Headers\", \"Mcp-Session-Id, Retry-After\");\n if (_req.method === \"OPTIONS\") {\n res.status(204).end();\n return;\n }\n next();\n});\n\n// ── OAuth: Protected Resource Metadata (RFC 9728) ────────────────────────\n// Step 1 of MCP auth: Claude fetches this to discover the authorization server.\n\napp.get(\"/.well-known/oauth-protected-resource\", (req: any, res: any) => {\n const base = baseUrl(req);\n res.json({\n resource: base,\n authorization_servers: [base],\n scopes_supported: [\"mcp:tools\", \"mcp:resources\"],\n bearer_methods_supported: [\"header\"],\n });\n});\n\n// ── OAuth: Authorization Server Metadata (RFC 8414) ──────────────────────\n// Step 2: Claude fetches this to discover authorize, token, and register endpoints.\n\napp.get(\"/.well-known/oauth-authorization-server\", (req: any, res: any) => {\n const base = baseUrl(req);\n res.json({\n issuer: base,\n authorization_endpoint: `${base}/authorize`,\n token_endpoint: `${base}/oauth/token`,\n registration_endpoint: `${base}/register`,\n response_types_supported: [\"code\"],\n grant_types_supported: [\"authorization_code\", \"refresh_token\"],\n code_challenge_methods_supported: [\"S256\"],\n token_endpoint_auth_methods_supported: [\"none\"],\n scopes_supported: [\"mcp:tools\", \"mcp:resources\"],\n });\n});\n\n// ── OAuth: Rate Limiting (Fix 2) ─────────────────────────────────────────\n// Separate, stricter limiter for auth endpoints to prevent brute-force and\n// enumeration attacks on the OAuth flow.\n\nconst authLimiter = rateLimit({\n windowMs: 60_000,\n max: 20,\n standardHeaders: true,\n legacyHeaders: false,\n message: { error: \"Too many auth requests. Try again later.\" },\n});\n\n// ── OAuth: Dynamic Client Registration (RFC 7591) ────────────────────────\n// Step 3: Claude registers itself as a client before starting the auth flow.\n\ninterface RegisteredClient {\n client_id: string;\n redirect_uris: string[];\n client_name?: string;\n registeredAt: number;\n}\n\nconst registeredClients = new Map<string, RegisteredClient>();\n// Fix 4 — Cap client registrations at 500 to prevent unbounded memory growth.\nconst MAX_REGISTERED_CLIENTS = 500;\n\napp.post(\n \"/register\",\n authLimiter,\n express.json(),\n (req: any, res: any) => {\n // Fix 4 — Reject registration when cap is reached.\n if (registeredClients.size >= MAX_REGISTERED_CLIENTS) {\n res.status(503).json({\n error: \"server_error\",\n error_description: \"Registration limit reached. Try again later.\",\n });\n return;\n }\n\n const { redirect_uris, client_name } = req.body;\n\n if (!Array.isArray(redirect_uris) || redirect_uris.length === 0) {\n res.status(400).json({\n error: \"invalid_client_metadata\",\n error_description: \"redirect_uris is required\",\n });\n return;\n }\n\n const clientId = `pb_client_${randomUUID()}`;\n const client: RegisteredClient = {\n client_id: clientId,\n redirect_uris,\n client_name,\n registeredAt: Date.now(),\n };\n registeredClients.set(clientId, client);\n\n res.status(201).json({\n client_id: clientId,\n client_name: client_name ?? \"MCP Client\",\n redirect_uris,\n grant_types: [\"authorization_code\"],\n response_types: [\"code\"],\n token_endpoint_auth_method: \"none\",\n });\n },\n);\n\n// ── OAuth: Authorization Code + PKCE ─────────────────────────────────────\n// Step 4: User enters their pb_sk_* key, server generates a one-time code.\n\ninterface PendingAuth {\n apiKey: string;\n codeChallenge: string;\n redirectUri: string;\n expiresAt: number;\n}\n\nconst pendingCodes = new Map<string, PendingAuth>();\n\n// Refresh tokens are now stateless HMAC-signed (see lib/refresh-token.ts).\n// No in-memory store, no cleanup loop, no per-key caps — they survive\n// Railway redeploys, which fixes TEN-1661.\nconst ACCESS_TOKEN_TTL = 3600; // 1 hour\nconst ACCESS_TOKEN_TTL_MS = ACCESS_TOKEN_TTL * 1000;\n\n// Fix 1 — Opaque access token store.\n// Maps pb_at_<uuid> → { apiKey, createdAt } so the raw pb_sk_* key is never\n// exposed through the OAuth flow. Capped at 1000 entries with LRU eviction.\ninterface AccessTokenEntry {\n apiKey: string;\n createdAt: number;\n}\nconst accessTokens = new Map<string, AccessTokenEntry>();\nconst MAX_ACCESS_TOKENS = 1000;\n\nsetInterval(() => {\n const now = Date.now();\n for (const [code, auth] of pendingCodes) {\n if (now > auth.expiresAt) pendingCodes.delete(code);\n }\n for (const [id, client] of registeredClients) {\n if (now - client.registeredAt > 24 * 60 * 60_000) registeredClients.delete(id);\n }\n // Fix 1 — Evict expired opaque access tokens.\n for (const [token, entry] of accessTokens) {\n if (now - entry.createdAt > ACCESS_TOKEN_TTL_MS) accessTokens.delete(token);\n }\n // Fix 5 — Clean up stale auth failure tracking entries.\n for (const [ip, rec] of authFailures) {\n if (rec.blockedUntil < now && rec.firstFailure + AUTH_FAILURE_WINDOW_MS < now) {\n authFailures.delete(ip);\n }\n }\n // Cap authFailures map size.\n if (authFailures.size > MAX_AUTH_FAILURE_ENTRIES) {\n const sorted = [...authFailures.entries()].sort((a, b) => a[1].firstFailure - b[1].firstFailure);\n for (let i = 0; i < sorted.length - MAX_AUTH_FAILURE_ENTRIES; i++) {\n authFailures.delete(sorted[i][0]);\n }\n }\n}, 60_000);\n\nfunction esc(s: unknown): string {\n return String(s ?? \"\").replace(/[&\"'<>]/g, (c) =>\n ({ \"&\": \"&\", '\"': \""\", \"'\": \"'\", \"<\": \"<\", \">\": \">\" })[c]!,\n );\n}\n\n// ── Authorize Page Templates ─────────────────────────────────────────────\n// Parchment-dark OAuth pages — brand tokens from DEC-419 (brand-tokens.json).\n// Monochrome-first per DEC-417, warm temperature per DEC-418.\n// Provider-agnostic: copy interpolates registered client_name (RFC 7591),\n// never hardcodes \"Claude\" — any MCP client may reach this page.\n\nfunction authPageShell(title: string, bodyContent: string, headExtra = \"\"): string {\n return `<!DOCTYPE html>\n<html lang=\"en\" data-theme=\"parchment-dark\"><head>\n<meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\n<title>${esc(title)} — Product Brain</title>\n<link rel=\"preconnect\" href=\"https://fonts.googleapis.com\">\n<link rel=\"preconnect\" href=\"https://fonts.gstatic.com\" crossorigin>\n<link rel=\"stylesheet\" href=\"https://fonts.googleapis.com/css2?family=Source+Serif+4:opsz,wght@8..60,600&family=IBM+Plex+Sans:wght@400;500;600;700&family=IBM+Plex+Mono:wght@400;500;700&display=swap\">\n${headExtra}\n<style>\n:root{\n --bg:#1a1917;--bg-warm:#201f1c;--surface:#262521;\n --fg1:#e4e0d8;--fg2:#c4bfb4;--fg3:#9a9589;--fg4:#6a6560;--fg-bright:#ffffff;\n --border:rgba(255,255,255,0.07);--border-light:rgba(255,255,255,0.04);\n --accent:#c9b99a;\n --btn-bg:#ffffff;--btn-fg:#1a1917;--btn-hover:#e4e0d8;\n --green:#4ade80;--rose:#ef4444;\n --ghost:rgba(38,37,33,0.55);\n --radius-md:7px;--radius-lg:10px;\n --font-display:\"Source Serif 4\",ui-serif,Georgia,serif;\n --font-body:\"IBM Plex Sans\",ui-sans-serif,system-ui,sans-serif;\n --font-mono:\"IBM Plex Mono\",ui-monospace,\"SF Mono\",Menlo,monospace;\n}\n*,*::before,*::after{box-sizing:border-box;margin:0;padding:0}\nhtml,body{height:100%}\nbody{\n font-family:var(--font-body);font-size:13px;line-height:1.45;\n color:var(--fg1);background:var(--bg);\n min-height:100vh;display:grid;place-items:center;padding:24px;\n -webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;\n position:relative;overflow:hidden;\n}\nbody::before{\n content:\"\";position:fixed;inset:0;\n background:radial-gradient(900px 600px at 50% 50%,rgba(228,224,216,0.025),transparent 60%);\n pointer-events:none;z-index:0;\n}\n.top-mark{position:fixed;top:22px;left:24px;z-index:5;opacity:0.7}\n${appLogoStyles}\n.stage{\n width:100%;max-width:460px;text-align:center;\n position:relative;z-index:1;\n display:grid;\n}\n.panel{\n grid-area:1/1;\n transition:opacity 280ms ease-out,transform 380ms cubic-bezier(.2,.6,.2,1),filter 380ms ease-out;\n}\n.panel[hidden]{\n display:block !important;\n opacity:0;transform:scale(0.96) translateY(-2px);filter:blur(6px);\n pointer-events:none;\n}\n.panel:not([hidden]){opacity:1;transform:scale(1);filter:none;pointer-events:auto}\n\n/* eyebrows */\n.eyebrow{\n font-family:var(--font-mono);font-size:10px;font-weight:700;\n letter-spacing:0.28em;text-transform:uppercase;color:var(--fg4);\n margin-bottom:24px;display:inline-flex;align-items:center;gap:7px;\n}\n.eyebrow .dot{width:5px;height:5px;border-radius:50%;background:currentColor}\n.eyebrow.danger{color:var(--rose)}\n.eyebrow.success{color:var(--green)}\n.eyebrow.success .dot{box-shadow:0 0 0 3px rgba(74,222,128,0.18)}\n\n/* form input */\n.input-wrap{\n display:flex;align-items:center;background:rgba(0,0,0,0.22);\n border:1px solid var(--border);border-radius:var(--radius-md);\n transition:border-color 200ms ease-out,box-shadow 200ms ease-out;\n}\n.input-wrap:focus-within{\n border-color:rgba(228,224,216,0.45);\n box-shadow:0 0 0 3px rgba(228,224,216,0.10);\n}\n.input-wrap.has-error{\n border-color:rgba(239,68,68,0.55);\n box-shadow:0 0 0 3px rgba(239,68,68,0.12);\n animation:shake 360ms cubic-bezier(.36,.07,.19,.97);\n}\n@keyframes shake{\n 10%,90%{transform:translateX(-1px)}20%,80%{transform:translateX(2px)}\n 30%,50%,70%{transform:translateX(-4px)}40%,60%{transform:translateX(4px)}\n}\n.input{\n flex:1;min-width:0;background:transparent;border:0;outline:none;\n padding:16px;\n font-family:var(--font-mono);font-size:14px;color:var(--fg1);letter-spacing:0.02em;\n}\n.input::placeholder{color:var(--fg4)}\n.hint{\n margin-top:10px;font-family:var(--font-mono);font-size:10.5px;\n letter-spacing:0.16em;text-transform:uppercase;\n text-align:left;padding-left:4px;height:14px;color:var(--fg4);\n transition:color 160ms ease-out;\n}\n.hint.is-error{color:var(--rose)}\n\n/* primary button */\n.btn-primary{\n width:100%;height:48px;margin-top:14px;\n border:0;border-radius:var(--radius-md);\n background:var(--btn-bg);color:var(--btn-fg);\n font-family:var(--font-body);font-size:14.5px;font-weight:600;letter-spacing:-0.005em;\n cursor:pointer;display:inline-flex;align-items:center;justify-content:center;gap:10px;\n transition:background 140ms ease-out,transform 80ms ease-out,opacity 200ms ease-out;\n position:relative;overflow:hidden;\n}\n.btn-primary:hover:not([disabled]){background:var(--btn-hover)}\n.btn-primary:active:not([disabled]){transform:translateY(1px)}\n.btn-primary[disabled]{opacity:0.45;cursor:default}\n.spin{\n width:14px;height:14px;border-radius:50%;\n border:1.5px solid currentColor;border-top-color:transparent;\n animation:spin 700ms linear infinite;opacity:0.85;\n}\n@keyframes spin{to{transform:rotate(360deg)}}\n\n/* secondary link */\n.small-link{\n margin-top:18px;font-family:var(--font-mono);font-size:11px;\n letter-spacing:0.18em;text-transform:uppercase;color:var(--fg4);\n}\n.small-link a{\n color:var(--fg3);text-decoration:none;border-bottom:1px dotted currentColor;\n padding-bottom:1px;transition:color 140ms;\n}\n.small-link a:hover{color:var(--fg1)}\n\n/* orb */\n.orb-wrap{\n position:relative;width:160px;height:160px;margin:0 auto 36px;\n display:grid;place-items:center;\n}\n.orb-ring{position:absolute;border-radius:50%}\n.orb-ring.r1{inset:0;border:1px solid rgba(228,224,216,0.06);animation:drift1 40s linear infinite}\n.orb-ring.r2{inset:18px;border:1px dashed rgba(228,224,216,0.10);animation:drift2 28s linear infinite}\n.orb-ring.r3{inset:38px;border:1px solid rgba(74,222,128,0.20);animation:ringPulse 3.4s ease-in-out infinite}\n@keyframes drift1{to{transform:rotate(360deg)}}\n@keyframes drift2{to{transform:rotate(-360deg)}}\n@keyframes ringPulse{0%,100%{opacity:0.6}50%{opacity:1}}\n\n.orb-wrap.is-verifying .orb-ring.r3{\n border-color:rgba(228,224,216,0.20);\n animation:ringPulse 1.1s ease-in-out infinite;\n}\n.orb-wrap.is-verifying .orb-core{\n box-shadow:0 0 0 6px rgba(228,224,216,0.04),0 0 22px rgba(228,224,216,0.10),inset 0 0 16px rgba(228,224,216,0.06);\n animation:corePulseNeutral 1.6s ease-in-out infinite;\n}\n.orb-wrap.is-verifying .orb-dot{background:var(--fg3);box-shadow:0 0 10px rgba(228,224,216,0.4)}\n@keyframes corePulseNeutral{\n 0%,100%{box-shadow:0 0 0 6px rgba(228,224,216,0.04),0 0 22px rgba(228,224,216,0.10),inset 0 0 16px rgba(228,224,216,0.06)}\n 50%{box-shadow:0 0 0 9px rgba(228,224,216,0.07),0 0 32px rgba(228,224,216,0.18),inset 0 0 22px rgba(228,224,216,0.10)}\n}\n\n.orb-wrap.is-error .orb-ring.r3{border-color:rgba(239,68,68,0.30);animation:none;opacity:1}\n.orb-wrap.is-error .orb-ring.r1,.orb-wrap.is-error .orb-ring.r2{animation-play-state:paused}\n.orb-wrap.is-error .orb-core{\n box-shadow:0 0 0 6px rgba(239,68,68,0.05),0 0 22px rgba(239,68,68,0.20),inset 0 0 16px rgba(239,68,68,0.08);\n animation:none;\n}\n.orb-wrap.is-error .orb-dot{background:var(--rose);box-shadow:0 0 10px rgba(239,68,68,0.6)}\n\n.sat-orbit{position:absolute;inset:0;pointer-events:none}\n.sat-orbit.o1{animation:drift1 40s linear infinite}\n.sat-orbit.o2{animation:drift2 56s linear infinite}\n.sat{\n position:absolute;top:50%;left:50%;\n font-family:var(--font-mono);font-size:9px;font-weight:700;letter-spacing:0.14em;\n background:var(--bg);padding:2px 6px;border-radius:3px;\n border:1px solid var(--border-light);\n transform-origin:0 0;opacity:0;\n}\n.panel:not([hidden])[data-state=\"connected\"] .sat{animation:satIn 600ms ease-out forwards}\n@keyframes satIn{from{opacity:0}to{opacity:1}}\n.sat span{display:inline-block;animation:counter 40s linear infinite}\n.sat-orbit.o2 .sat span{animation:counter2 56s linear infinite}\n@keyframes counter{to{transform:rotate(-360deg)}}\n@keyframes counter2{to{transform:rotate(360deg)}}\n\n.orb-core{\n position:relative;width:60px;height:60px;border-radius:50%;\n background:radial-gradient(circle at 50% 45%,#1a1a1a 0%,#0c0c0c 60%,#050505 100%);\n border:1px solid rgba(255,255,255,0.06);\n display:grid;place-items:center;\n box-shadow:0 0 0 6px rgba(74,222,128,0.04),0 0 28px rgba(74,222,128,0.20),inset 0 0 18px rgba(74,222,128,0.08);\n animation:corePulse 3.4s ease-in-out infinite;\n}\n@keyframes corePulse{\n 0%,100%{box-shadow:0 0 0 6px rgba(74,222,128,0.04),0 0 24px rgba(74,222,128,0.18),inset 0 0 16px rgba(74,222,128,0.06)}\n 50%{box-shadow:0 0 0 9px rgba(74,222,128,0.06),0 0 40px rgba(74,222,128,0.32),inset 0 0 22px rgba(74,222,128,0.14)}\n}\n.orb-dot{width:10px;height:10px;border-radius:50%;background:#4ade80;box-shadow:0 0 12px rgba(74,222,128,0.7)}\n\n.core-shockwave{\n position:absolute;inset:0;border-radius:50%;\n border:1px solid rgba(74,222,128,0.6);\n opacity:0;pointer-events:none;\n}\n.panel:not([hidden])[data-state=\"connected\"] .core-shockwave{animation:shock 1100ms ease-out 200ms}\n@keyframes shock{\n 0%{opacity:0.7;transform:scale(0.4);border-width:2px}\n 100%{opacity:0;transform:scale(2.4);border-width:1px}\n}\n\n/* titles */\n.ok-title{\n font-family:var(--font-display);font-weight:600;\n font-size:38px;line-height:1.05;letter-spacing:-0.025em;\n color:var(--fg-bright);opacity:0;\n}\n.panel:not([hidden]) .ok-title{animation:rise 600ms ease-out 380ms forwards}\n.ok-lead{\n margin:18px auto 0;max-width:22em;font-size:16px;line-height:1.55;color:var(--fg2);\n opacity:0;\n}\n.panel:not([hidden]) .ok-lead{animation:rise 600ms ease-out 500ms forwards}\n.ok-phrase-row{\n margin-top:14px;display:flex;align-items:center;justify-content:center;\n opacity:0;\n}\n.panel:not([hidden]) .ok-phrase-row{animation:rise 600ms ease-out 620ms forwards}\n.cmd.is-copied .cmd-quote-part{display:none}\n.success-cta-wrap{\n margin-top:48px;width:100%;opacity:0;\n}\n.panel:not([hidden]) .success-cta-wrap{animation:rise 600ms ease-out 780ms forwards}\na.btn-primary.success-cta{color:var(--btn-fg);text-decoration:none}\n\n.cmd{\n display:inline-flex;align-items:center;gap:8px;vertical-align:middle;\n font-family:var(--font-mono);font-size:15px;font-weight:500;color:var(--accent);\n background:rgba(201,185,154,0.08);border:1px solid rgba(201,185,154,0.30);\n padding:5px 10px 5px 12px;border-radius:6px;letter-spacing:0.02em;\n cursor:pointer;user-select:none;\n transition:background 140ms ease-out,border-color 140ms ease-out,color 140ms ease-out;\n}\n.cmd:hover{background:rgba(201,185,154,0.14);border-color:rgba(201,185,154,0.50);color:#dcc9a4}\n.cmd.is-copied{color:var(--green);border-color:rgba(74,222,128,0.35);background:rgba(74,222,128,0.08)}\n.cmd .cmd-icon{\n width:12px;height:12px;color:currentColor;opacity:0.75;\n display:inline-grid;place-items:center;\n transition:opacity 140ms;\n}\n.cmd:hover .cmd-icon{opacity:1}\n.cmd.is-copied .cmd-icon{color:var(--green);opacity:1}\n.cmd .cmd-icon svg{width:12px;height:12px;stroke:currentColor;fill:none;stroke-width:1.5;stroke-linecap:round;stroke-linejoin:round}\n\n/* error specifics */\n.err-title{\n font-family:var(--font-display);font-weight:600;\n font-size:32px;line-height:1.1;letter-spacing:-0.02em;\n color:var(--fg1);margin-bottom:12px;\n}\n.err-msg{\n font-size:14.5px;line-height:1.55;color:var(--fg3);\n margin-bottom:28px;\n}\n.err-msg code{\n font-family:var(--font-mono);font-size:12px;\n background:rgba(255,255,255,0.06);padding:1px 5px;border-radius:4px;color:var(--fg2);\n}\n.err-actions{display:flex;gap:8px}\n.btn-secondary{\n flex:1;height:44px;border-radius:var(--radius-md);\n background:transparent;color:var(--fg2);\n border:1px solid var(--border);\n font-family:var(--font-body);font-size:13.5px;font-weight:500;\n cursor:pointer;text-decoration:none;\n display:inline-flex;align-items:center;justify-content:center;\n transition:background 140ms,color 140ms,border-color 140ms;\n}\n.btn-secondary:hover{background:rgba(255,255,255,0.04);color:var(--fg1);border-color:rgba(255,255,255,0.14)}\n\n/* verifying */\n.verifying-eyebrow{\n font-family:var(--font-mono);font-size:10px;\n letter-spacing:0.28em;text-transform:uppercase;color:var(--fg3);\n font-weight:700;margin-bottom:14px;\n}\n.verifying-title{\n font-family:var(--font-display);font-weight:600;\n font-size:28px;line-height:1.1;color:var(--fg1);margin-bottom:8px;\n letter-spacing:-0.02em;\n}\n.verifying-sub{font-size:13px;color:var(--fg3);min-height:1.45em}\n\n/* form heading */\n.form-title{\n font-family:var(--font-display);font-weight:600;\n font-size:32px;line-height:1.1;letter-spacing:-0.02em;\n color:var(--fg1);margin-bottom:10px;\n}\n.form-sub{font-size:13.5px;color:var(--fg3);margin-bottom:28px;line-height:1.55}\n\n@keyframes rise{from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:translateY(0)}}\n\n@media (prefers-reduced-motion: reduce){\n *,*::before,*::after{\n animation-duration:0.01ms !important;animation-iteration-count:1 !important;\n transition-duration:0.01ms !important;\n }\n}\n</style>\n</head><body>\n<div class=\"top-mark\">${appLogoMarkup({ size: \"sm\" })}</div>\n<div class=\"stage\">${bodyContent}</div>\n</body></html>`;\n}\n\n// Provider-agnostic display name. Trims and clamps to keep page chrome stable.\nfunction providerDisplayName(clientName: string | undefined): string {\n const name = (clientName ?? \"\").trim();\n if (!name) return \"your assistant\";\n return name.length > 40 ? name.slice(0, 40) + \"…\" : name;\n}\n\n// Inner HTML for the success panel. Used both by the JSON path (cloned client-side\n// from a <template>) and by the no-JS server-rendered fallback page.\nfunction successPanelInner(workspaceName: string, redirectUrl: string, providerName: string): string {\n return `\n<div class=\"orb-wrap\">\n <div class=\"orb-ring r1\"></div>\n <div class=\"orb-ring r2\"></div>\n <div class=\"orb-ring r3\"></div>\n <div class=\"sat-orbit o1\">\n <span class=\"sat\" style=\"transform:rotate(20deg) translate(78px) rotate(-20deg);color:#4ade80;animation-delay:600ms\"><span>DEC</span></span>\n <span class=\"sat\" style=\"transform:rotate(140deg) translate(78px) rotate(-140deg);color:#c9b99a;animation-delay:720ms\"><span>WP</span></span>\n <span class=\"sat\" style=\"transform:rotate(260deg) translate(78px) rotate(-260deg);color:#f59e0b;animation-delay:840ms\"><span>TEN</span></span>\n </div>\n <div class=\"sat-orbit o2\">\n <span class=\"sat\" style=\"transform:rotate(80deg) translate(54px) rotate(-80deg);color:#60a5fa;animation-delay:960ms\"><span>STD</span></span>\n <span class=\"sat\" style=\"transform:rotate(220deg) translate(54px) rotate(-220deg);color:#a78bfa;animation-delay:1080ms\"><span>INS</span></span>\n </div>\n <div class=\"core-shockwave\"></div>\n <div class=\"orb-core\"><div class=\"orb-dot\"></div></div>\n</div>\n<div class=\"eyebrow success\"><span class=\"dot\"></span>Connected</div>\n<h1 class=\"ok-title\">Product Brain is Live</h1>\n<p class=\"ok-lead\">Return to your assistant, then say</p>\n<div class=\"ok-phrase-row\">\n <button class=\"cmd\" type=\"button\" data-cmd-pill data-redirect=\"${esc(redirectUrl)}\" aria-label=\"Copy "Start PB" and return to ${esc(providerName)}\">\n <span class=\"cmd-quote-part\" aria-hidden=\"true\">“</span><span data-cmd-text>Start PB</span><span class=\"cmd-quote-part\" aria-hidden=\"true\">”</span>\n <span class=\"cmd-icon\" aria-hidden=\"true\">\n <svg data-cmd-svg viewBox=\"0 0 24 24\"><rect x=\"9\" y=\"9\" width=\"11\" height=\"11\" rx=\"2\"/><path d=\"M5 15V6a2 2 0 0 1 2-2h9\"/></svg>\n </span>\n </button>\n</div>\n<div class=\"success-cta-wrap\">\n <a class=\"btn-primary success-cta\" href=\"${esc(redirectUrl)}\">Continue in ${esc(providerName)}</a>\n</div>\n<!-- workspace name retained as data hook for tests, hidden from view -->\n<span hidden data-field=\"ws-name\">${esc(workspaceName)}</span>`;\n}\n\nfunction errorPanelInner(title: string, trustedDetailHtml: string, retryUrl: string): string {\n return `\n<div class=\"orb-wrap is-error\">\n <div class=\"orb-ring r1\"></div>\n <div class=\"orb-ring r2\"></div>\n <div class=\"orb-ring r3\"></div>\n <div class=\"orb-core\"><div class=\"orb-dot\"></div></div>\n</div>\n<div class=\"eyebrow danger\"><span class=\"dot\"></span>Couldn't connect</div>\n<h2 class=\"err-title\" data-field=\"err-title\">${esc(title)}</h2>\n<p class=\"err-msg\" data-field=\"err-msg\">${trustedDetailHtml}</p>\n<div class=\"err-actions\">\n <a href=\"${esc(retryUrl)}\" class=\"btn-secondary\" data-retry-link>← Try again</a>\n <a href=\"https://productbrain.io\" target=\"_blank\" rel=\"noopener noreferrer\" class=\"btn-secondary\">Get an API key →</a>\n</div>`;\n}\n\nconst cmdScript = `\n(function(){\n function bindCmd(pill){\n if(!pill||pill.__bound)return;pill.__bound=true;\n var textEl=pill.querySelector('[data-cmd-text]');\n var svgEl=pill.querySelector('[data-cmd-svg]');\n var redirectUrl=pill.getAttribute('data-redirect')||'';\n pill.addEventListener('click',function(){\n var done=function(){\n pill.classList.add('is-copied');\n if(textEl)textEl.textContent='Copied';\n if(svgEl)svgEl.innerHTML='<polyline points=\"4 12 10 18 20 6\"/>';\n setTimeout(function(){if(redirectUrl)window.location.assign(redirectUrl)},900);\n };\n try{\n if(navigator.clipboard&&navigator.clipboard.writeText){\n navigator.clipboard.writeText('Start PB').then(done,done);\n }else{done()}\n }catch(e){done()}\n });\n }\n document.querySelectorAll('[data-cmd-pill]').forEach(bindCmd);\n})();\n`;\n\nfunction authorizeFormPage(params: {\n redirect_uri: string;\n code_challenge: string;\n code_challenge_method: string;\n state: string;\n client_id: string;\n client_name?: string;\n}): string {\n const { redirect_uri, code_challenge, code_challenge_method, state, client_id } = params;\n const providerName = providerDisplayName(params.client_name);\n const body = `\n<!-- ─── CONNECT ─── -->\n<div class=\"panel\" id=\"p-connect\" data-state=\"connect\">\n <div class=\"eyebrow\">Connect Product Brain</div>\n <h1 class=\"form-title\">Paste your API key</h1>\n <p class=\"form-sub\">Give <span data-provider>${esc(providerName)}</span> access to your workspace memory.</p>\n <form method=\"POST\" action=\"/authorize\" id=\"f\" autocomplete=\"off\">\n <input type=\"hidden\" name=\"redirect_uri\" value=\"${esc(redirect_uri)}\">\n <input type=\"hidden\" name=\"code_challenge\" value=\"${esc(code_challenge)}\">\n <input type=\"hidden\" name=\"code_challenge_method\" value=\"${esc(code_challenge_method)}\">\n <input type=\"hidden\" name=\"state\" value=\"${esc(state)}\">\n <input type=\"hidden\" name=\"client_id\" value=\"${esc(client_id)}\">\n <div class=\"input-wrap\" id=\"iw\">\n <input type=\"password\" id=\"k\" name=\"api_key\" class=\"input input-full\" placeholder=\"pb_sk_…\" required autofocus spellcheck=\"false\">\n </div>\n <div class=\"hint\" id=\"hint\" hidden></div>\n <button type=\"submit\" class=\"btn-primary\" id=\"sb\" disabled><span id=\"bt\">Connect</span></button>\n </form>\n <div class=\"small-link\"><a href=\"https://productbrain.io\" target=\"_blank\" rel=\"noopener noreferrer\">No key? Generate one →</a></div>\n</div>\n\n<!-- ─── VERIFYING ─── -->\n<div class=\"panel\" id=\"p-verifying\" data-state=\"verifying\" hidden>\n <div class=\"orb-wrap is-verifying\">\n <div class=\"orb-ring r1\"></div>\n <div class=\"orb-ring r2\"></div>\n <div class=\"orb-ring r3\"></div>\n <div class=\"orb-core\"><div class=\"orb-dot\"></div></div>\n </div>\n <div class=\"verifying-eyebrow\">Handshake</div>\n <h2 class=\"verifying-title\">Verifying key…</h2>\n <p class=\"verifying-sub\" id=\"verify-sub\">Checking workspace · …</p>\n</div>\n\n<!-- ─── CONNECTED (filled by JS from JSON response) ─── -->\n<div class=\"panel\" id=\"p-connected\" data-state=\"connected\" hidden></div>\n\n<!-- ─── ERROR (filled by JS from JSON response) ─── -->\n<div class=\"panel\" id=\"p-error\" data-state=\"error\" hidden></div>\n\n<template id=\"tpl-connected\">${successPanelInner(\"__WS__\", \"__URL__\", \"__PROVIDER__\")}</template>\n<template id=\"tpl-error\">${errorPanelInner(\"__TITLE__\", \"__DETAIL__\", \"__RETRY__\")}</template>\n\n<script>\n${cmdScript}\n(function(){\n var f=document.getElementById('f'),k=document.getElementById('k'),iw=document.getElementById('iw'),hint=document.getElementById('hint'),sb=document.getElementById('sb'),bt=document.getElementById('bt');\n var pConnect=document.getElementById('p-connect'),pVerify=document.getElementById('p-verifying'),pOk=document.getElementById('p-connected'),pErr=document.getElementById('p-error');\n var verifySub=document.getElementById('verify-sub');\n\n function show(panel){\n [pConnect,pVerify,pOk,pErr].forEach(function(p){\n if(p===panel){p.removeAttribute('hidden')}else{p.setAttribute('hidden','')}\n });\n }\n\n function syncInput(){\n sb.disabled=!k.value.trim();\n iw.classList.remove('has-error');\n hint.classList.remove('is-error');\n hint.textContent='';\n hint.setAttribute('hidden','');\n }\n k.addEventListener('input',syncInput);\n k.addEventListener('keydown',function(e){\n if(e.key==='Escape'){k.value='';syncInput()}\n });\n\n function showError(title,detailHtml){\n var tpl=document.getElementById('tpl-error');\n var html=tpl.innerHTML\n .replace('__TITLE__',title.replace(/[<>&]/g,function(c){return{'<':'<','>':'>','&':'&'}[c]}))\n .replace('__DETAIL__',detailHtml)\n .replace('__RETRY__','#');\n pErr.innerHTML=html;\n var retry=pErr.querySelector('[data-retry-link]');\n if(retry){retry.addEventListener('click',function(e){e.preventDefault();show(pConnect);k.focus();k.select()})}\n show(pErr);\n }\n\n function showSuccess(workspaceName,redirectUrl,providerName){\n var tpl=document.getElementById('tpl-connected');\n var safeWs=String(workspaceName||'').replace(/[<>&]/g,function(c){return{'<':'<','>':'>','&':'&'}[c]});\n var safeProv=String(providerName||'your assistant').replace(/[<>&]/g,function(c){return{'<':'<','>':'>','&':'&'}[c]});\n var safeUrl=String(redirectUrl||'').replace(/\"/g,'"').replace(/[<>]/g,function(c){return{'<':'<','>':'>'}[c]});\n var html=tpl.innerHTML.split('__WS__').join(safeWs).split('__URL__').join(safeUrl).split('__PROVIDER__').join(safeProv);\n pOk.innerHTML=html;\n pOk.querySelectorAll('[data-cmd-pill]').forEach(function(pill){\n pill.__bound=false;\n });\n // Re-run binder\n var s=document.createElement('script');s.textContent=${JSON.stringify(cmdScript)};document.body.appendChild(s);s.remove();\n show(pOk);\n }\n\n f.addEventListener('submit',function(e){\n e.preventDefault();\n var v=k.value.trim();\n if(!v){iw.classList.add('has-error');hint.classList.add('is-error');hint.textContent='Paste your key first';hint.removeAttribute('hidden');return}\n if(v.indexOf('pb_sk_')!==0){iw.classList.add('has-error');hint.classList.add('is-error');hint.textContent='Key must start with pb_sk_';hint.removeAttribute('hidden');return}\n sb.disabled=true;bt.textContent='Verifying';\n show(pVerify);\n\n var steps=['Checking workspace · …','Loading chain · …','Establishing memory · …'];\n var i=0;verifySub.textContent=steps[0];\n var ti=setInterval(function(){i++;if(i>=steps.length){clearInterval(ti);return}verifySub.textContent=steps[i]},900);\n\n var minDelay=new Promise(function(r){setTimeout(r,2800)});\n var fd=new FormData(f);\n var body=new URLSearchParams();\n fd.forEach(function(val,key){body.append(key,String(val))});\n\n var req=fetch('/authorize',{\n method:'POST',\n headers:{'Accept':'application/json','Content-Type':'application/x-www-form-urlencoded'},\n body:body.toString(),\n credentials:'same-origin'\n }).then(function(r){return r.json().then(function(j){return{status:r.status,body:j}})});\n\n Promise.all([req,minDelay]).then(function(arr){\n clearInterval(ti);\n var res=arr[0];\n if(res.body&&res.body.ok){\n showSuccess(res.body.workspaceName,res.body.redirectUrl,res.body.providerName);\n }else{\n showError(res.body&&res.body.title||'Couldn\\\\'t connect',res.body&&res.body.detail||'Try again, or generate a new key.');\n sb.disabled=false;bt.textContent='Connect';\n }\n }).catch(function(){\n clearInterval(ti);\n showError('Network error','We couldn\\\\'t reach Product Brain. Check your connection and try again.');\n sb.disabled=false;bt.textContent='Connect';\n });\n });\n\n k.focus();\n})();\n</script>`;\n return authPageShell(\"Connect Product Brain\", body);\n}\n\nfunction authorizeSuccessPage(workspaceName: string, redirectUrl: string, providerName: string): string {\n const body = `\n<div class=\"panel\" data-state=\"connected\">\n${successPanelInner(workspaceName, redirectUrl, providerName)}\n</div>\n<script>${cmdScript}</script>`;\n return authPageShell(\"Connected\", body);\n}\n\n// security: trustedDetailHtml must be a hardcoded literal — never pass user-controlled data.\nfunction authorizeErrorPage(title: string, trustedDetailHtml: string, retryUrl: string): string {\n const body = `\n<div class=\"panel\" data-state=\"error\">\n${errorPanelInner(title, trustedDetailHtml, retryUrl)}\n</div>`;\n return authPageShell(\"Connection error\", body);\n}\n\napp.get(\"/authorize\", authLimiter, (req: any, res: any) => {\n const { redirect_uri, code_challenge, code_challenge_method, state, client_id } = req.query;\n const cid = String(client_id ?? \"\");\n const clientName = cid && registeredClients.has(cid)\n ? registeredClients.get(cid)!.client_name\n : undefined;\n res.type(\"html\").send(authorizeFormPage({\n redirect_uri: String(redirect_uri ?? \"\"),\n code_challenge: String(code_challenge ?? \"\"),\n code_challenge_method: String(code_challenge_method ?? \"S256\"),\n state: String(state ?? \"\"),\n client_id: cid,\n client_name: clientName,\n }));\n});\n\napp.post(\n \"/authorize\",\n authLimiter,\n express.urlencoded({ extended: false }),\n async (req: any, res: any) => {\n const { api_key, redirect_uri, code_challenge, code_challenge_method, state, client_id } = req.body;\n\n // Negotiate response shape: fetch path sets Accept: application/json,\n // form-post no-JS path gets the standard rebranded HTML page.\n const wantsJson = String(req.headers[\"accept\"] ?? \"\").includes(\"application/json\");\n\n // Build \"retry\" URL so error pages can link back to the form.\n const retryParams = new URLSearchParams({\n redirect_uri: redirect_uri ?? \"\",\n code_challenge: code_challenge ?? \"\",\n code_challenge_method: code_challenge_method ?? \"S256\",\n ...(state ? { state } : {}),\n ...(client_id ? { client_id } : {}),\n }).toString();\n const retryUrl = `/authorize?${retryParams}`;\n\n function sendError(title: string, trustedDetailHtml: string, status = 400): void {\n if (wantsJson) {\n res.status(status).json({ ok: false, title, detail: trustedDetailHtml });\n } else {\n res.status(status).type(\"html\").send(authorizeErrorPage(title, trustedDetailHtml, retryUrl));\n }\n }\n\n if (!api_key?.startsWith(\"pb_sk_\")) {\n sendError(\n \"Invalid key format\",\n \"API keys start with <code>pb_sk_</code>. Check your key and try again.\",\n );\n return;\n }\n\n // Validate redirect_uri against the registered client's allowed redirects.\n // Open redirect prevention: never trust a request-supplied redirect_uri without\n // checking it was pre-registered during dynamic client registration (RFC 7591).\n //\n // When client_id is provided but unknown (e.g. server restart wiped the in-memory Map\n // after claude.ai cached its client_id from a previous session), auto-re-register using\n // the supplied redirect_uri rather than hard-rejecting. The API key validation below is\n // the primary security gate; basic HTTPS validation guards against degenerate redirect URIs.\n if (!client_id) {\n res.status(400).json({\n error: \"invalid_request\",\n error_description: \"client_id is required\",\n });\n return;\n }\n if (!registeredClients.has(client_id)) {\n if (typeof redirect_uri === \"string\" && redirect_uri.startsWith(\"https://\")) {\n registeredClients.set(client_id, {\n client_id,\n redirect_uris: [redirect_uri],\n registeredAt: Date.now(),\n });\n process.stderr.write(`[authorize] auto-re-registered stale client_id after restart\\n`);\n } else {\n res.status(400).json({\n error: \"invalid_request\",\n error_description: \"Unknown client_id and redirect_uri is not a valid https URL\",\n });\n return;\n }\n }\n\n const client = registeredClients.get(client_id)!;\n if (!client.redirect_uris.includes(redirect_uri)) {\n res.status(400).json({\n error: \"invalid_request\",\n error_description: \"redirect_uri does not match any registered redirect for this client\",\n });\n return;\n }\n\n // Validate key against Convex before issuing the code.\n // DEC-789 S2: probe primary then fallback URLs so DEV keys work against PROD Railway MCP.\n let workspaceName = \"Your Workspace\";\n try {\n const primaryUrl = (process.env.CONVEX_SITE_URL ?? DEFAULT_CLOUD_URL).replace(/\\/$/, \"\");\n const fallbackUrls = (process.env.CONVEX_FALLBACK_URLS ?? \"\")\n .split(\",\").map((u) => u.trim().replace(/\\/$/, \"\")).filter(Boolean);\n const candidates = [primaryUrl, ...fallbackUrls];\n\n let foundUrl: string | undefined;\n let anyDefinitiveReject = false;\n\n for (const url of candidates) {\n let checkData: { ok: boolean; workspaceName?: string; deploymentUrl?: string } | null = null;\n try {\n const checkRes = await fetch(`${url}/api/key-check`, {\n method: \"POST\",\n headers: { \"Authorization\": `Bearer ${api_key}`, \"Content-Type\": \"application/json\" },\n signal: AbortSignal.timeout(5000),\n });\n checkData = await checkRes.json() as { ok: boolean; workspaceName?: string; deploymentUrl?: string };\n } catch {\n // This candidate unreachable — try next.\n continue;\n }\n if (checkData.ok) {\n if (checkData.workspaceName) workspaceName = checkData.workspaceName;\n foundUrl = checkData.deploymentUrl ?? url;\n break;\n }\n anyDefinitiveReject = true;\n }\n\n if (!foundUrl) {\n if (anyDefinitiveReject) {\n sendError(\n \"Key not recognized\",\n \"This API key wasn't found in Product Brain. Check your API Keys in Cortex and try again.\",\n 401,\n );\n return;\n }\n // All candidates unreachable (network errors only) — fail-open.\n process.stderr.write(\"[authorize] key-check unavailable — proceeding without validation\\n\");\n } else {\n getKeyState(api_key).deploymentUrl = foundUrl;\n }\n } catch {\n // Outer guard: fail-open so auth works even if the entire block throws.\n process.stderr.write(\"[authorize] key-check unavailable — proceeding without validation\\n\");\n }\n\n const code = randomUUID();\n pendingCodes.set(code, {\n apiKey: api_key,\n codeChallenge: code_challenge,\n redirectUri: redirect_uri,\n expiresAt: Date.now() + 5 * 60_000,\n });\n\n const url = new URL(redirect_uri);\n url.searchParams.set(\"code\", code);\n if (state) url.searchParams.set(\"state\", state);\n const redirectUrl = url.toString();\n const providerName = providerDisplayName(client.client_name);\n\n if (wantsJson) {\n res.json({ ok: true, workspaceName, redirectUrl, providerName });\n } else {\n // No-JS path: server-rendered success page. User clicks the pill or the\n // Primary CTA + copy pill both complete the OAuth redirect — no auto-bounce.\n res.type(\"html\").send(authorizeSuccessPage(workspaceName, redirectUrl, providerName));\n }\n },\n);\n\n// ── OAuth: Token Exchange ────────────────────────────────────────────────\n// Step 5: Claude exchanges the authorization code (with PKCE verifier) for a token.\n// Supports both authorization_code and refresh_token grants.\n\nfunction issueTokens(apiKey: string): object {\n // Return the pb_sk_* key directly as the access_token so connections\n // survive server restarts. Railway deploys on every git push, wiping\n // in-memory Maps. pb_sk_* keys are long-lived (valid until explicitly\n // revoked in Cortex); actual validity is enforced by Convex per tool call.\n // extractBearerKey() already handles pb_sk_* with zero Map lookup.\n //\n // The refresh token is HMAC-signed and self-contained (TEN-1661, lib/\n // refresh-token.ts) so it also survives redeploys. No server-side store.\n return {\n access_token: apiKey,\n token_type: \"Bearer\",\n // 1-year TTL: actual validity enforced by Convex, not by expiry clock.\n // Long TTL prevents unnecessary refresh cycles after restarts.\n expires_in: 365 * 24 * 3600,\n refresh_token: signRefreshToken(apiKey),\n };\n}\n\napp.post(\n \"/oauth/token\",\n authLimiter,\n express.urlencoded({ extended: false }),\n express.json(),\n (req: any, res: any) => {\n const { grant_type, code, code_verifier, redirect_uri, refresh_token } =\n req.body;\n\n if (grant_type === \"refresh_token\") {\n const verified = verifyRefreshToken(refresh_token);\n if (!verified) {\n res.status(400).json({\n error: \"invalid_grant\",\n error_description: \"Invalid or expired refresh token\",\n });\n return;\n }\n // Rotation = re-issuance. With stateless tokens there is no Map entry\n // to revoke; the new pair simply takes over from the next request.\n res.json(issueTokens(verified.apiKey));\n return;\n }\n\n if (grant_type !== \"authorization_code\") {\n res.status(400).json({ error: \"unsupported_grant_type\" });\n return;\n }\n\n const pending = pendingCodes.get(code);\n if (!pending || pending.redirectUri !== redirect_uri) {\n res.status(400).json({ error: \"invalid_grant\" });\n return;\n }\n\n // PKCE S256 validation\n const challenge = createHash(\"sha256\")\n .update(code_verifier ?? \"\")\n .digest(\"base64url\");\n if (challenge !== pending.codeChallenge) {\n pendingCodes.delete(code);\n res.status(400).json({\n error: \"invalid_grant\",\n error_description: \"PKCE verification failed\",\n });\n return;\n }\n\n pendingCodes.delete(code);\n res.json(issueTokens(pending.apiKey));\n },\n);\n\n// ── Rate Limiting ────────────────────────────────────────────────────────\n\nconst mcpLimiter = rateLimit({\n windowMs: 60_000,\n max: 120,\n standardHeaders: true,\n legacyHeaders: false,\n handler: (req: any, res: any) => {\n const r = req.rateLimit;\n const reset = r?.resetTime?.getTime?.() ?? Date.now() + 60_000;\n send429(res, buildRateLimitError({\n retryAfterSeconds: Math.max(1, Math.ceil((reset - Date.now()) / 1000)),\n limit: r?.limit ?? 120,\n current: r?.used ?? 0,\n id: req.body?.id ?? null, // mirror the JSON-RPC id when a POST body is present\n }));\n },\n});\n\n// ── Auth Failure Backoff (Fix 5) ──────────────────────────────────────────\n// Per-IP progressive lockout for failed API key auth attempts to prevent\n// brute-force attacks through the MCP endpoints.\n\ninterface AuthFailureRecord {\n count: number;\n firstFailure: number;\n blockedUntil: number;\n}\n\nconst authFailures = new Map<string, AuthFailureRecord>();\nconst AUTH_FAILURE_MAX = 10;\nconst AUTH_FAILURE_WINDOW_MS = 5 * 60_000; // 5 minutes\nconst AUTH_BLOCK_DURATION_MS = 15 * 60_000; // 15 minutes\nconst MAX_AUTH_FAILURE_ENTRIES = 10_000;\n\nfunction checkAuthBlock(ip: string): boolean {\n const rec = authFailures.get(ip);\n if (!rec) return false;\n return rec.blockedUntil > Date.now();\n}\n\nfunction recordAuthFailure(ip: string): void {\n const now = Date.now();\n const rec = authFailures.get(ip);\n\n if (!rec) {\n authFailures.set(ip, { count: 1, firstFailure: now, blockedUntil: 0 });\n return;\n }\n\n // Reset window if the first failure is outside the tracking window.\n if (now - rec.firstFailure > AUTH_FAILURE_WINDOW_MS) {\n rec.count = 1;\n rec.firstFailure = now;\n rec.blockedUntil = 0;\n } else {\n rec.count++;\n if (rec.count >= AUTH_FAILURE_MAX) {\n rec.blockedUntil = now + AUTH_BLOCK_DURATION_MS;\n }\n }\n}\n\n// ── Health Check ─────────────────────────────────────────────────────────\n\napp.get(\"/health\", (_req: any, res: any) => {\n res.json({ status: \"ok\", version: SERVER_VERSION, transport: \"http\" });\n});\n\n// ── Session Management ──────────────────────────────────────────────────\n\ninterface SessionEntry {\n transport: StreamableHTTPServerTransport;\n lastAccess: number;\n // Fix 3 — short hash of the API key that created this session. Used to\n // detect session hijacking when subsequent requests arrive with a different key.\n keyHash: string;\n // Number of POST tool-call requests currently being handled. Incremented at\n // POST start, decremented in finally. A session with inFlight > 0 is never\n // torn by planKeyAdmission; the only exception is the evictStaleSessions TTL\n // backstop, which force-evicts past SESSION_TTL_MS to self-heal a leaked\n // counter (logged as reason=inflight_leak). GET SSE and DELETE do NOT touch\n // this — see design §3.1.\n inFlight: number;\n}\n\nconst sessions = new Map<string, SessionEntry>();\nconst SESSION_TTL_MS = 30 * 60 * 1000;\nconst MAX_SESSIONS = 200;\n// Grace window: a session touched within this many ms is \"recently active\" and\n// is never evicted by the per-key planner (covers the gap between back-to-back\n// POST calls). See planKeyAdmission in sessionCap.ts.\nconst EVICT_GRACE_MS = 60_000;\n// Fix 6 — MAX_SESSIONS_PER_KEY is an in-process memory/working-set guard, NOT a\n// concurrency policy. Raising MCP_MAX_SESSIONS_PER_KEY does NOT grant more\n// concurrent agents — it only widens the idle-session reclaim window. It must\n// never be the thing that limits how many agents can work; fleet concurrency is\n// a kernel concern (TEN-2229), not a per-key surface cap.\n// Clamped to [1, MAX_SESSIONS - 1]: a value < 1 would make planKeyAdmission\n// throw on every init (RangeError); the MAX_SESSIONS - 1 ceiling guarantees a\n// single key can never alone fill the entire global pool (always leaves >= 1\n// slot), so a bad env degrades to a safe bound rather than breaking init or\n// disabling the cross-key fairness guard. Default 25 is far below this ceiling.\nconst MAX_SESSIONS_PER_KEY = Math.max(\n 1,\n Math.min(MAX_SESSIONS - 1, Number(process.env.MCP_MAX_SESSIONS_PER_KEY) || 25),\n);\n\n// The other eviction site is planKeyAdmission (sessionCap.ts), which runs\n// per-key on init. Keep both coherent — a change to one may affect the other.\nfunction evictStaleSessions(): void {\n const now = Date.now();\n for (const [id, entry] of sessions) {\n // TTL branch: evict regardless of inFlight once past SESSION_TTL_MS. GET is\n // no longer inFlight-guarded after the round-3 fix, so an unconditional skip\n // on inFlight > 0 could make a session with a *leaked* counter immortal. The\n // hard-age backstop turns that leak into a self-healing, observable event.\n if (now - entry.lastAccess > SESSION_TTL_MS) {\n // Force-evicting an inFlight > 0 session here means the counter leaked\n // (an unexpected throw outside the POST try/finally). Log it as such.\n logSessionLifecycle(\n \"session_deleted\",\n id,\n entry.inFlight > 0 ? \"inflight_leak\" : \"ttl\",\n );\n entry.transport.close().catch(() => {});\n sessions.delete(id);\n }\n }\n if (sessions.size > MAX_SESSIONS) {\n // Global memory-pressure branch: SKIP inFlight > 0 so we can't drop a live\n // POST call mid-flight.\n const sorted = [...sessions.entries()]\n .filter(([, e]) => e.inFlight === 0)\n .sort((a, b) => a[1].lastAccess - b[1].lastAccess);\n const overflow = sessions.size - MAX_SESSIONS;\n for (let i = 0; i < Math.min(overflow, sorted.length); i++) {\n logSessionLifecycle(\"session_deleted\", sorted[i][0], \"eviction\");\n sorted[i][1].transport.close().catch(() => {});\n sessions.delete(sorted[i][0]);\n }\n // Observability: if every session is inFlight (sorted is empty / too short)\n // the loop above could not bring us under MAX_SESSIONS. We deliberately do\n // NOT tear live POSTs — the TTL backstop reclaims them at SESSION_TTL_MS —\n // but a sustained breach is worth surfacing rather than silently exceeding\n // the global memory ceiling.\n if (sessions.size > MAX_SESSIONS) {\n const ts = new Date().toISOString();\n process.stderr.write(\n `[HTTP] ${ts} session_cap_breach size=${sessions.size} max=${MAX_SESSIONS} ` +\n `reason=all_inflight (no idle sessions to evict; TTL backstop will reclaim)\\n`,\n );\n }\n }\n}\n\nsetInterval(evictStaleSessions, 60_000);\n\n// ── Auth Helpers ─────────────────────────────────────────────────────────\n\nfunction extractBearerKey(req: any): string | null {\n const header = req.headers?.authorization;\n if (typeof header !== \"string\" || !header.startsWith(\"Bearer \")) return null;\n const token = header.slice(7).trim();\n\n // Fix 1 — Support both direct API keys (stdio/backward compat) and opaque\n // OAuth access tokens issued by issueTokens().\n if (token.startsWith(\"pb_sk_\")) {\n // Direct API key — accepted for stdio and backward compatibility.\n return token;\n }\n if (token.startsWith(\"pb_at_\")) {\n // Opaque OAuth access token — resolve to the underlying API key.\n const entry = accessTokens.get(token);\n if (!entry) return null;\n const now = Date.now();\n if (now - entry.createdAt > ACCESS_TOKEN_TTL_MS) {\n // Expired — remove and reject.\n accessTokens.delete(token);\n return null;\n }\n return entry.apiKey;\n }\n return null;\n}\n\nfunction send401(req: any, res: any): void {\n const base = baseUrl(req);\n res\n .status(401)\n .set(\n \"WWW-Authenticate\",\n `Bearer resource_metadata=\"${base}/.well-known/oauth-protected-resource\"`,\n )\n .json({ error: \"unauthorized\" });\n}\n\nfunction logRequest(\n method: string,\n outcome: \"ok\" | \"auth_fail\" | \"error\",\n sessionId?: string,\n durationMs?: number,\n): void {\n const ts = new Date().toISOString();\n const sid = sessionId ? ` session=${sessionId}` : \"\";\n const dur = durationMs != null ? ` duration=${durationMs}ms` : \"\";\n process.stderr.write(`[HTTP] ${ts} ${method} ${outcome}${sid}${dur}\\n`);\n}\n\nfunction logSessionLifecycle(\n event: \"session_created\" | \"session_deleted\",\n sessionId: string,\n reason?: \"ttl\" | \"eviction\" | \"onclose\" | \"lru_evict\" | \"inflight_leak\" | \"init_rejected\",\n): void {\n const ts = new Date().toISOString();\n const r = reason ? ` reason=${reason}` : \"\";\n process.stderr.write(`[HTTP] ${ts} ${event} session=${sessionId}${r}\\n`);\n}\n\n// ── MCP Handlers ────────────────────────────────────────────────────────\n\napp.post(\"/mcp\", mcpLimiter, async (req: any, res: any) => {\n // Fix 5 — Block IPs that have exceeded the auth failure threshold.\n const reqIp: string = req.ip ?? \"unknown\";\n if (checkAuthBlock(reqIp)) {\n const rec = authFailures.get(reqIp);\n const retryAfterSeconds = rec ? Math.max(0, Math.ceil((rec.blockedUntil - Date.now()) / 1000)) : 0;\n send429(res, buildAuthLockoutError({ retryAfterSeconds, limit: AUTH_FAILURE_MAX, current: rec?.count ?? AUTH_FAILURE_MAX, id: req.body?.id ?? null }));\n return;\n }\n\n const apiKey = extractBearerKey(req);\n if (!apiKey) {\n logRequest(\"POST\", \"auth_fail\");\n // Fix 5 — Record the auth failure for progressive lockout.\n recordAuthFailure(reqIp);\n send401(req, res);\n return;\n }\n\n const sessionId = req.headers[\"mcp-session-id\"] as string | undefined;\n const reqStart = Date.now();\n\n try {\n await runWithAuth({ apiKey }, async () => {\n if (sessionId && sessions.has(sessionId)) {\n const entry = sessions.get(sessionId)!;\n // Fix 3 — Verify the session belongs to the presenting key.\n if (entry.keyHash !== hashKey(apiKey)) {\n res.status(403).json({\n jsonrpc: \"2.0\",\n error: { code: -32000, message: \"Session key mismatch\" },\n id: null,\n });\n return;\n }\n // inFlight guard (design §3.3): the increment is the FIRST statement\n // inside the try so nothing throwable sits between it and the guarded\n // region; finally decrements and re-stamps lastAccess so a long tool\n // call leaves a fresh stamp (never looks idle mid-flight).\n try {\n entry.inFlight++;\n entry.lastAccess = Date.now();\n await entry.transport.handleRequest(req, res, req.body);\n logRequest(\"POST\", \"ok\", sessionId, Date.now() - reqStart);\n } finally {\n entry.inFlight--;\n entry.lastAccess = Date.now();\n }\n } else if (!sessionId && isInitializeRequest(req.body)) {\n // Fix 6 — per-key session cap with recency-guarded LRU eviction.\n const keyH = hashKey(apiKey);\n const plan = planKeyAdmission(sessions, keyH, MAX_SESSIONS_PER_KEY, Date.now(),\n { ttlMs: SESSION_TTL_MS, graceMs: EVICT_GRACE_MS });\n for (const sid of plan.evict) {\n const victim = sessions.get(sid);\n sessions.delete(sid); // delete before close; onclose guards on membership\n victim?.transport.close().catch(() => {});\n logSessionLifecycle(\"session_deleted\", sid, \"lru_evict\");\n }\n if (!plan.admit) {\n // poll-vs-deadline is decided by the planner from the same snapshot it\n // evicted against (plan.retryIsPoll) — no second scan / clock read here.\n send429(res, buildSessionCapError({\n retryAfterSeconds: plan.retryAfterSeconds,\n limit: MAX_SESSIONS_PER_KEY,\n current: countKeySessions(sessions, keyH),\n poll: plan.retryIsPoll,\n id: req.body?.id ?? null,\n }));\n return;\n }\n const sid = randomUUID();\n let initialized = false; // set true once the SDK confirms the session initialized\n const transport = new StreamableHTTPServerTransport({\n sessionIdGenerator: () => sid,\n onsessioninitialized: (s: string) => { initialized = true; logSessionLifecycle(\"session_created\", s); }, // log only — no map write\n });\n const reserved: SessionEntry = { transport, lastAccess: Date.now(), keyHash: keyH, inFlight: 1 };\n sessions.set(sid, reserved); // synchronous single-writer reservation (closes TOCTOU)\n transport.onclose = () => {\n const s = transport.sessionId ?? sid;\n if (sessions.has(s)) { sessions.delete(s); logSessionLifecycle(\"session_deleted\", s, \"onclose\"); }\n };\n try {\n const server = createProductBrainServer();\n await server.connect(transport);\n await transport.handleRequest(req, res, req.body);\n logRequest(\"POST\", \"ok\", transport.sessionId ?? undefined, Date.now() - reqStart);\n } catch (e) {\n transport.onclose = undefined as any; // detach → no phantom delete log on failure\n sessions.delete(sid);\n throw e;\n } finally {\n // handleRequest can reject an init-shaped POST with a 4xx WITHOUT throwing\n // (e.g. missing \"Accept: application/json, text/event-stream\", bad content\n // type, invalid batch init) — onsessioninitialized never fires and no\n // session id reaches the client, so the reservation would otherwise linger\n // until grace/TTL and let a broken/malicious client pin per-key slots.\n // Drop the orphan reservation immediately when init did not complete.\n if (!initialized) {\n transport.onclose = undefined as any;\n if (sessions.delete(sid)) logSessionLifecycle(\"session_deleted\", sid, \"init_rejected\");\n } else {\n const e = sessions.get(sid); if (e) { e.inFlight--; e.lastAccess = Date.now(); }\n }\n }\n } else if (sessionId) {\n // Stale Mcp-Session-Id (client cached one from before a Railway restart\n // or after TTL eviction). Per MCP Streamable HTTP spec § Session\n // Management clause 3, the server MUST respond with HTTP 404 Not Found\n // so the client (clause 4) re-initialises with a fresh InitializeRequest\n // without prompting OAuth re-auth. Returning 400 here was the root cause\n // of \"Claude.ai re-auths after every deploy\".\n process.stderr.write(\n `[HTTP] ${new Date().toISOString()} session_stale sessionId=${sessionId} (likely server restart — instructing client to re-initialise)\\n`,\n );\n res.status(404).json({\n jsonrpc: \"2.0\",\n error: { code: -32001, message: \"Session not found — re-initialise\" },\n id: null,\n });\n } else {\n // Non-initialise request with no Mcp-Session-Id — per spec clause 2,\n // servers that require a session ID SHOULD respond with HTTP 400.\n process.stderr.write(\n `[HTTP] ${new Date().toISOString()} session_invalid no valid session ID (client may have omitted Mcp-Session-Id)\\n`,\n );\n res.status(400).json({\n jsonrpc: \"2.0\",\n error: { code: -32000, message: \"Bad Request: no valid session ID provided\" },\n id: null,\n });\n }\n });\n } catch (err: any) {\n logRequest(\"POST\", \"error\", sessionId, Date.now() - reqStart);\n if (!res.headersSent) {\n res.status(500).json({\n jsonrpc: \"2.0\",\n error: { code: -32603, message: \"Internal server error\" },\n id: null,\n });\n }\n }\n});\n\napp.get(\"/mcp\", mcpLimiter, async (req: any, res: any) => {\n // Fix 5 — Block IPs that have exceeded the auth failure threshold.\n const reqIp: string = req.ip ?? \"unknown\";\n if (checkAuthBlock(reqIp)) {\n const rec = authFailures.get(reqIp);\n const retryAfterSeconds = rec ? Math.max(0, Math.ceil((rec.blockedUntil - Date.now()) / 1000)) : 0;\n send429(res, buildAuthLockoutError({ retryAfterSeconds, limit: AUTH_FAILURE_MAX, current: rec?.count ?? AUTH_FAILURE_MAX, id: req.body?.id ?? null }));\n return;\n }\n\n const apiKey = extractBearerKey(req);\n if (!apiKey) {\n logRequest(\"GET\", \"auth_fail\");\n // Fix 5 — Record the auth failure for progressive lockout.\n recordAuthFailure(reqIp);\n send401(req, res);\n return;\n }\n\n const sessionId = req.headers[\"mcp-session-id\"] as string | undefined;\n if (!sessionId) {\n res.status(400).send(\"Missing Mcp-Session-Id header\");\n return;\n }\n if (!sessions.has(sessionId)) {\n // Stale session — per MCP spec § Session Management clauses 3-4, return 404\n // so the client re-initialises without re-authing. Survives Railway restarts.\n process.stderr.write(\n `[HTTP] ${new Date().toISOString()} session_stale GET sessionId=${sessionId}\\n`,\n );\n res.status(404).send(\"Session not found — re-initialise\");\n return;\n }\n\n try {\n await runWithAuth({ apiKey }, async () => {\n const entry = sessions.get(sessionId)!;\n // Fix 3 — Verify the session belongs to the presenting key.\n if (entry.keyHash !== hashKey(apiKey)) {\n res.status(403).json({\n jsonrpc: \"2.0\",\n error: { code: -32000, message: \"Session key mismatch\" },\n id: null,\n });\n return;\n }\n // NOT inFlight-guarded (design §3.1, round-3 review): the SSE\n // handleRequest stays open for the stream's whole life, so guarding it\n // would pin every active session → permanent 429 lockout. Re-stamp\n // lastAccess on stream open; the recency guard alone governs evictability.\n entry.lastAccess = Date.now();\n await entry.transport.handleRequest(req, res);\n logRequest(\"GET\", \"ok\", sessionId);\n });\n } catch {\n logRequest(\"GET\", \"error\", sessionId);\n }\n});\n\napp.delete(\"/mcp\", mcpLimiter, async (req: any, res: any) => {\n // Fix 5 — Block IPs that have exceeded the auth failure threshold.\n const reqIp: string = req.ip ?? \"unknown\";\n if (checkAuthBlock(reqIp)) {\n const rec = authFailures.get(reqIp);\n const retryAfterSeconds = rec ? Math.max(0, Math.ceil((rec.blockedUntil - Date.now()) / 1000)) : 0;\n send429(res, buildAuthLockoutError({ retryAfterSeconds, limit: AUTH_FAILURE_MAX, current: rec?.count ?? AUTH_FAILURE_MAX, id: req.body?.id ?? null }));\n return;\n }\n\n const apiKey = extractBearerKey(req);\n if (!apiKey) {\n logRequest(\"DELETE\", \"auth_fail\");\n // Fix 5 — Record the auth failure for progressive lockout.\n recordAuthFailure(reqIp);\n send401(req, res);\n return;\n }\n\n const sessionId = req.headers[\"mcp-session-id\"] as string | undefined;\n if (!sessionId) {\n res.status(400).send(\"Missing Mcp-Session-Id header\");\n return;\n }\n if (!sessions.has(sessionId)) {\n // Stale session — per MCP spec § Session Management clauses 3-4, return 404\n // so the client re-initialises without re-authing. Survives Railway restarts.\n process.stderr.write(\n `[HTTP] ${new Date().toISOString()} session_stale DELETE sessionId=${sessionId}\\n`,\n );\n res.status(404).send(\"Session not found — re-initialise\");\n return;\n }\n\n try {\n await runWithAuth({ apiKey }, async () => {\n const entry = sessions.get(sessionId)!;\n // Fix 3 — Verify the session belongs to the presenting key.\n if (entry.keyHash !== hashKey(apiKey)) {\n res.status(403).json({\n jsonrpc: \"2.0\",\n error: { code: -32000, message: \"Session key mismatch\" },\n id: null,\n });\n return;\n }\n await entry.transport.handleRequest(req, res);\n logRequest(\"DELETE\", \"ok\", sessionId);\n });\n } catch {\n logRequest(\"DELETE\", \"error\", sessionId);\n }\n});\n\n// ── Start ───────────────────────────────────────────────────────────────\n\nprocess.on(\"unhandledRejection\", (reason) => {\n const msg = reason instanceof Error ? reason.message : String(reason);\n console.error(`[MCP HTTP] Unhandled rejection: ${msg}`);\n});\n\nprocess.on(\"uncaughtException\", (err) => {\n console.error(`[MCP HTTP] Uncaught exception: ${err.stack ?? err.message}`);\n gracefulShutdown();\n});\n\nlet shuttingDown = false;\nasync function gracefulShutdown() {\n if (shuttingDown) return;\n shuttingDown = true;\n setTimeout(() => process.exit(1), 3_000).unref();\n console.log(\"Shutting down...\");\n for (const [, entry] of sessions) {\n await entry.transport.close().catch(() => {});\n }\n try {\n await shutdownAnalytics();\n } catch {\n /* best-effort */\n }\n process.exit(0);\n}\n\n// Bind all interfaces — Railway/Cloudflare reach the container on its non-loopback IP.\n// Loopback-only (127.0.0.1) causes edge 502: the proxy never connects to localhost inside the pod.\nconst LISTEN_HOST = \"0.0.0.0\";\nconst httpServer = app.listen(PORT, LISTEN_HOST, () => {\n console.log(\n `Product Brain MCP HTTP server v${SERVER_VERSION} listening on ${LISTEN_HOST}:${PORT}`,\n );\n});\nhttpServer.on(\"error\", (err) => {\n console.error(`[MCP HTTP] Server error: ${err.message}`);\n process.exit(1);\n});\n\nprocess.on(\"SIGINT\", gracefulShutdown);\nprocess.on(\"SIGTERM\", gracefulShutdown);\n","// SSOT for the Product Brain APP logo (wordmark style).\n// Used by: src/lib/brand/AppLogo.svelte (Cortex UI) AND\n// packages/mcp-server (mirrored via prebuild) for /authorize and other agent surfaces.\n//\n// NOT used by marketing pages (they have their own brand treatment).\n//\n// To change the logo, edit ONLY this file. Both surfaces re-render automatically.\n\nexport type AppLogoSize = \"sm\" | \"md\";\n\nexport interface AppLogoOptions {\n size?: AppLogoSize;\n showWordmark?: boolean;\n className?: string;\n}\n\nconst SIZE_CLASSES: Record<AppLogoSize, string> = {\n sm: \"pb-logo--sm\",\n md: \"pb-logo--md\",\n};\n\n// Self-contained CSS for environments that can't load Svelte styles\n// (the MCP authorize page, embedded HTML responses, etc.).\n// Cortex UI consumers can rely on AppLogo.svelte's scoped styles instead;\n// the inline class hooks are designed not to collide.\nexport const appLogoStyles = `\n.pb-logo{display:inline-flex;align-items:center;gap:8px;color:inherit}\n.pb-logo__mark{\n border-radius:4px;background:#1c1e24;\n border:1px solid rgba(255,255,255,0.06);\n display:inline-grid;place-items:center;flex-shrink:0;\n}\n.pb-logo__core{border-radius:50%;background:var(--accent,#c9b99a)}\n.pb-logo__name{\n font-family:var(--font-mono,\"IBM Plex Mono\",ui-monospace,monospace);\n font-weight:500;text-transform:uppercase;\n letter-spacing:0.22em;color:var(--fg4,#6a6560);\n}\n.pb-logo--sm .pb-logo__mark{width:16px;height:16px}\n.pb-logo--sm .pb-logo__core{width:5px;height:5px}\n.pb-logo--sm .pb-logo__name{font-size:10.5px}\n.pb-logo--md .pb-logo__mark{width:24px;height:24px;border-radius:6px}\n.pb-logo--md .pb-logo__core{width:8px;height:8px}\n.pb-logo--md .pb-logo__name{font-size:13px}\n`;\n\nexport function appLogoMarkup(opts: AppLogoOptions = {}): string {\n const size = opts.size ?? \"sm\";\n const showWordmark = opts.showWordmark ?? true;\n const cls = [\"pb-logo\", SIZE_CLASSES[size], opts.className].filter(Boolean).join(\" \");\n const wordmark = showWordmark ? `<span class=\"pb-logo__name\">Product Brain</span>` : \"\";\n return `<span class=\"${cls}\"><span class=\"pb-logo__mark\"><span class=\"pb-logo__core\"></span></span>${wordmark}</span>`;\n}\n","/**\n * Stateless HMAC-signed OAuth refresh tokens.\n *\n * Why this exists (TEN-1661, DEC-783):\n * Railway redeploys on every git push, wiping in-memory Maps. The previous\n * `refreshTokens` Map made claude.ai's proactive refresh calls fail with\n * `invalid_grant`, forcing OAuth re-auth after every deploy. DEC-783 fixed\n * the access-token side by returning the underlying pb_sk_* key directly.\n * This module is the refresh-token equivalent: a self-contained,\n * HMAC-signed token format that needs no server-side state.\n *\n * Format: pb_rt_<base64url(payload)>.<base64url(hmac-sha256(payload))>\n * Payload: { k: apiKey, i: iat-ms, j: jti }\n *\n * The jti (j) field is reserved for future revocation/rotation work and is\n * not yet checked. Signature comparison uses crypto.timingSafeEqual.\n */\n\nimport { createHmac, randomBytes, randomUUID, timingSafeEqual } from \"node:crypto\";\n\nexport const REFRESH_TOKEN_TTL_MS = 90 * 24 * 60 * 60_000; // 90 days\nconst PREFIX = \"pb_rt_\";\n\ninterface RefreshPayload {\n k: string; // apiKey\n i: number; // iat (ms since epoch)\n j: string; // jti\n}\n\n// Read once at module load. In production we warn rather than crash so the\n// server keeps working — degrades gracefully to current Railway-lifetime\n// behaviour if the secret is missing.\nconst secret: Buffer = (() => {\n const fromEnv = process.env.MCP_REFRESH_SECRET;\n if (fromEnv && fromEnv.length > 0) return Buffer.from(fromEnv, \"utf8\");\n if (process.env.NODE_ENV === \"production\") {\n // eslint-disable-next-line no-console\n console.warn(\n \"[HTTP] WARNING MCP_REFRESH_SECRET not set — refresh tokens will not survive restart\",\n );\n }\n return randomBytes(32);\n})();\n\nfunction sign(payloadB64: string): Buffer {\n return createHmac(\"sha256\", secret).update(payloadB64).digest();\n}\n\nexport function signRefreshToken(apiKey: string): string {\n const payload: RefreshPayload = {\n k: apiKey,\n i: Date.now(),\n j: randomUUID(),\n };\n const payloadB64 = Buffer.from(JSON.stringify(payload), \"utf8\").toString(\"base64url\");\n const sigB64 = sign(payloadB64).toString(\"base64url\");\n return `${PREFIX}${payloadB64}.${sigB64}`;\n}\n\nexport function verifyRefreshToken(token: string): { apiKey: string } | null {\n if (typeof token !== \"string\" || !token.startsWith(PREFIX)) return null;\n const body = token.slice(PREFIX.length);\n const dot = body.indexOf(\".\");\n if (dot <= 0 || dot === body.length - 1) return null;\n const payloadB64 = body.slice(0, dot);\n const sigB64 = body.slice(dot + 1);\n\n let providedSig: Buffer;\n try {\n providedSig = Buffer.from(sigB64, \"base64url\");\n } catch {\n return null;\n }\n const expectedSig = sign(payloadB64);\n if (providedSig.length !== expectedSig.length) return null;\n if (!timingSafeEqual(providedSig, expectedSig)) return null;\n\n let payload: RefreshPayload;\n try {\n const json = Buffer.from(payloadB64, \"base64url\").toString(\"utf8\");\n payload = JSON.parse(json);\n } catch {\n return null;\n }\n if (\n !payload ||\n typeof payload.k !== \"string\" ||\n typeof payload.i !== \"number\" ||\n typeof payload.j !== \"string\"\n ) {\n return null;\n }\n if (Date.now() - payload.i > REFRESH_TOKEN_TTL_MS) return null;\n\n return { apiKey: payload.k };\n}\n","/**\n * sessionCap.ts — Pure, side-effect-free session cap planner.\n *\n * Used by http.ts init branch to decide which sessions to evict before\n * admitting a new one for the presenting API key.\n *\n * Two eviction sites in the codebase:\n * 1. planKeyAdmission (here) — per-key, on init, targets only the presenting key.\n * 2. evictStaleSessions (http.ts) — global TTL sweep, runs every 60 s.\n * Keep both coherent; a change to one may affect the other.\n */\n\n// ---------------------------------------------------------------------------\n// Public types\n// ---------------------------------------------------------------------------\n\nexport interface CapSession {\n /** Unix-ms timestamp of last request start (or completion). */\n lastAccess: number;\n /** Hash of the API key that owns this session. */\n keyHash: string;\n /**\n * Number of POST tool-call requests currently being handled.\n * Incremented at POST start; decremented in finally.\n * GET SSE handlers and DELETE are NOT counted here — see design §3.1.\n */\n inFlight: number;\n}\n\nexport interface AdmissionPlan {\n /** IDs of sessions the caller should evict before admitting the new one. */\n evict: string[];\n /** True if the new session can be admitted after evictions. */\n admit: boolean;\n /**\n * Seconds the caller should suggest as a retry delay when admit=false.\n * 0 when admit=true.\n */\n retryAfterSeconds: number;\n /**\n * True when admit=false AND every blocking same-key session has inFlight > 0\n * — there is no grace deadline to wait out, so retryAfterSeconds is a fixed\n * poll-hint rather than a guarantee. The caller surfaces this as a \"retry\n * shortly\" message instead of a hard deadline. Always false when admit=true.\n * This is the single source of truth for poll-vs-deadline — callers must not\n * re-derive it from the live session map (avoids a second clock read).\n */\n retryIsPoll: boolean;\n}\n\n// ---------------------------------------------------------------------------\n// planKeyAdmission\n// ---------------------------------------------------------------------------\n\n/**\n * Plan how the presenting key admits ONE new session under `cap`.\n *\n * Protected = inFlight > 0 OR (now - lastAccess) < graceMs. Never evicted.\n *\n * 1. Throw RangeError if cap < 1.\n * 2. Collect entries belonging to `keyHash`.\n * 3. Mark the key's TTL-expired-AND-not-protected sessions for eviction (G2).\n * (inFlight===0 && now-lastAccess >= ttlMs)\n * 4. If survivors (key ids not in evict) >= cap, additionally evict the key's\n * idle sessions (inFlight===0 && now-lastAccess >= graceMs) sorted\n * ascending by lastAccess (Map-insertion-order stable sort resolves ties)\n * until survivors < cap or none remain.\n * 5. admit = survivors.length < cap.\n * 6. retryAfterSeconds: 0 when admit; else computed from the oldest\n * grace-blocker (smallest lastAccess), or 5 if every blocker is inFlight\n * (retryIsPoll=true in that all-inFlight case).\n * 7. Return { evict, admit, retryAfterSeconds, retryIsPoll }.\n *\n * Only the presenting key's sessions are ever touched.\n * Pure; total over empty maps. Ties in lastAccess resolve by Map insertion order.\n */\nexport function planKeyAdmission(\n sessions: ReadonlyMap<string, CapSession>,\n keyHash: string,\n cap: number,\n now: number,\n opts: { ttlMs: number; graceMs: number },\n): AdmissionPlan {\n if (cap < 1) {\n throw new RangeError(`cap must be >= 1, got ${cap}`);\n }\n\n const { ttlMs, graceMs } = opts;\n\n // Helper: a session is \"protected\" if it has an active POST call OR was\n // recently accessed (within the grace window).\n const isProtected = (s: CapSession): boolean =>\n s.inFlight > 0 || now - s.lastAccess < graceMs;\n\n // Step 2: collect the presenting key's entries as an ordered array.\n // Map iteration order equals insertion order (ES2015+; V8 stable).\n const keyEntries: [string, CapSession][] = [];\n for (const [id, session] of sessions) {\n if (session.keyHash === keyHash) {\n keyEntries.push([id, session]);\n }\n }\n\n // Step 3: always evict TTL-expired AND non-protected sessions (G2).\n const evictSet = new Set<string>();\n for (const [id, session] of keyEntries) {\n if (!isProtected(session) && now - session.lastAccess >= ttlMs) {\n evictSet.add(id);\n }\n }\n\n // Step 4: if survivors (key sessions not in evict) >= cap, additionally\n // evict idle sessions (inFlight===0 && now-lastAccess >= graceMs) sorted\n // ascending by lastAccess until survivors < cap.\n let survivors = keyEntries.filter(([id]) => !evictSet.has(id));\n\n if (survivors.length >= cap) {\n // Collect idle (evictable) survivors, preserving insertion order for\n // stable sort — Array.sort is stable in V8 and spec-required ES2019+.\n const idleSurvivors = survivors\n .filter(([, s]) => !isProtected(s))\n // Ascending by lastAccess (oldest first); equal values keep insertion order.\n .sort(([, a], [, b]) => a.lastAccess - b.lastAccess);\n\n for (const [id] of idleSurvivors) {\n if (survivors.length < cap) break;\n evictSet.add(id);\n // Recompute survivors in-place without the evicted id.\n survivors = survivors.filter(([sid]) => sid !== id);\n }\n }\n\n const evict = Array.from(evictSet);\n\n // Step 5.\n const admit = survivors.length < cap;\n\n // Step 6.\n let retryAfterSeconds = 0;\n let retryIsPoll = false;\n if (!admit) {\n // Grace-blockers: surviving sessions with inFlight===0 (blocked by grace only).\n const graceBlockers = survivors.filter(([, s]) => s.inFlight === 0);\n if (graceBlockers.length > 0) {\n // Target the oldest (smallest lastAccess) — crosses graceMs soonest.\n const minLastAccess = Math.min(...graceBlockers.map(([, s]) => s.lastAccess));\n const msRemaining = graceMs - (now - minLastAccess);\n retryAfterSeconds = Math.max(1, Math.ceil(msRemaining / 1000));\n } else {\n // All blockers have inFlight > 0; completion time is unpredictable. The\n // 5 s value is a poll-hint fallback, not a guarantee — flag it so the\n // caller's 429 reads as \"retry shortly\" rather than a hard deadline.\n retryAfterSeconds = 5;\n retryIsPoll = true;\n }\n }\n\n return { evict, admit, retryAfterSeconds, retryIsPoll };\n}\n\n// ---------------------------------------------------------------------------\n// countKeySessions\n// ---------------------------------------------------------------------------\n\n/**\n * Count how many sessions in the map belong to `keyHash`.\n * Pure; returns 0 for an empty map.\n */\nexport function countKeySessions(\n sessions: ReadonlyMap<string, CapSession>,\n keyHash: string,\n): number {\n let count = 0;\n for (const session of sessions.values()) {\n if (session.keyHash === keyHash) count++;\n }\n return count;\n}\n","/**\n * httpErrors.ts — pure, import-safe builders for structured 429 responses.\n *\n * All three 429 sources (rate limit, auth lockout, session cap) return a\n * JSON-RPC envelope so the consuming MCP client can tell them apart.\n *\n * Rule — id mirrors the JSON-RPC request id when known\n * ---------------------------------------------------------------------------\n * JSON-RPC requires the response id to mirror the request id so the client can\n * correlate. All three call-sites run AFTER the global `express.json()`\n * middleware, so a POST body is already parsed and callers SHOULD thread\n * `req.body?.id` through `BuildParams.id` (the POST `/mcp` rate-limit,\n * auth-lockout, and session-cap gates all do). Requests with no parsable body\n * (GET/DELETE, or a malformed POST) have no id to mirror — those omit `id` and\n * it defaults to `null`, which is the correct JSON-RPC value for \"unknown id\".\n * ---------------------------------------------------------------------------\n */\n\nexport interface Built429 {\n status: 429;\n headers: Record<string, string>;\n body: unknown;\n}\n\n// ---------------------------------------------------------------------------\n// Internal helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Clamp to non-negative, round to integer — used for both the Retry-After\n * header value and the `retryAfterSeconds` field in `data`.\n */\nfunction clampSeconds(s: number): number {\n return Math.max(0, Math.round(s));\n}\n\ntype Reason = \"rate_limited\" | \"auth_lockout\" | \"session_cap\";\n\n/** JSON-RPC request/response id. `null` is the spec value for \"unknown id\". */\ntype JsonRpcId = string | number | null;\n\ninterface BuildParams {\n retryAfterSeconds: number;\n limit: number;\n current: number;\n /** Request id to mirror; defaults to null when the caller has no body id. */\n id?: JsonRpcId;\n}\n\nfunction build(\n reason: Reason,\n message: string,\n p: BuildParams,\n): Built429 {\n const seconds = clampSeconds(p.retryAfterSeconds);\n return {\n status: 429,\n headers: { \"Retry-After\": String(seconds) },\n body: {\n jsonrpc: \"2.0\",\n id: p.id ?? null,\n error: {\n code: -32000,\n message,\n data: {\n reason,\n retryAfterSeconds: seconds,\n limit: p.limit,\n current: p.current,\n },\n },\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// Public builders\n// ---------------------------------------------------------------------------\n\n/**\n * Per-IP rate-limit 429 (source: mcpLimiter middleware).\n * reason = \"rate_limited\"\n */\nexport function buildRateLimitError(p: BuildParams): Built429 {\n const seconds = clampSeconds(p.retryAfterSeconds);\n return build(\n \"rate_limited\",\n `Too many requests — retry after ${seconds} s.`,\n p,\n );\n}\n\n/**\n * Per-IP auth-failure lockout 429 (source: checkAuthBlock).\n * reason = \"auth_lockout\"\n */\nexport function buildAuthLockoutError(p: BuildParams): Built429 {\n const seconds = clampSeconds(p.retryAfterSeconds);\n return build(\n \"auth_lockout\",\n `Too many failed auth attempts — locked out, retry after ${seconds} s.`,\n p,\n );\n}\n\n/**\n * Per-key session-cap 429 (source: planKeyAdmission !admit fallback).\n * reason = \"session_cap\"\n *\n * @param p.poll - true when ALL blockers have inFlight > 0 (no grace deadline\n * can be predicted; the 5 s value is a fixed fallback, not a guarantee).\n * The message reads as a poll-hint rather than a hard deadline.\n * false (default) when at least one blocker is grace-protected; the\n * retryAfterSeconds is a real guarantee and the message names it.\n */\nexport function buildSessionCapError(\n p: BuildParams & { poll?: boolean },\n): Built429 {\n const seconds = clampSeconds(p.retryAfterSeconds);\n const message = p.poll\n ? \"Server busy — all sessions active; retry shortly.\"\n : `Too many active sessions for this key — retry after ${seconds} s.`;\n return build(\"session_cap\", message, p);\n}\n\n// ---------------------------------------------------------------------------\n// Sender\n// ---------------------------------------------------------------------------\n\n/**\n * Minimal structural shape of the response object send429 needs. Any\n * Express/Hono response satisfies it; the explicit interface (rather than\n * `any`) keeps a wrong argument from compiling and silently swallowing a 429.\n */\nexport interface Http429Response {\n headersSent: boolean;\n setHeader(name: string, value: string): unknown;\n status(code: number): { json(body: unknown): unknown };\n}\n\n/**\n * Write a Built429 to an Express/Hono-compatible response object.\n *\n * Guards `res.headersSent` first so calling this on an already-flushed\n * response is a safe no-op (e.g. when a middleware has already sent a body).\n */\nexport function send429(res: Http429Response, built: Built429): void {\n if (res.headersSent) return;\n for (const [k, v] of Object.entries(built.headers)) {\n res.setHeader(k, v);\n }\n res.status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AAC;AAED,QAAQ,GAAG,UAAU,gBAAgB;AACrC,QAAQ,GAAG,WAAW,gBAAgB;","names":["randomUUID","sessions","randomUUID","url","randomUUID","sid"]}
|
|
1
|
+
{"version":3,"sources":["../src/http.ts","../src/httpErrors.ts","../src/mcpRateLimit.ts","../src/authLockout.ts","../src/lib/oauthRedirectAllowlist.ts","../src/lib/connectClientNames.ts","../src/lib/connectClients.ts","../src/lib/oauthAuthCode.ts","../src/lib/oauthDoors.ts"],"sourcesContent":["/**\n * HTTP transport entry point for Product Brain MCP.\n *\n * Serves the MCP protocol over Streamable HTTP for web clients\n * (Claude web app, API consumers) that can't spawn local processes.\n * TASK-1640 (WP-862): one SDK 2.x handler serves 2026-07-28 and 2025-era clients per request, with no MCP session.\n *\n * Implements the full MCP OAuth 2.1 spec (Nov 2025):\n * 1. Protected Resource Metadata (/.well-known/oauth-protected-resource)\n * 2. Authorization Server Metadata (/.well-known/oauth-authorization-server)\n * 3. Dynamic Client Registration (POST /register)\n * 4. Authorization Code + PKCE (GET /authorize: the web app's connect page mints the code)\n * 5. Token Exchange (POST /oauth/token)\n *\n * Env:\n * CONVEX_SITE_URL — Convex deployment URL (defaults to cloud)\n * PORT / MCP_PORT — Listen port (default 3000)\n * CORS_ORIGINS — Comma-separated allowed origins (default: https://claude.ai)\n * OAUTH_REDIRECT_HOST_ALLOWLIST — Extra exact https redirect URIs, comma-separated full URIs (see lib/oauthRedirectAllowlist.ts)\n *\n * WP-757 TASK-224 F2 (DEC-1722): the PB_MODULES env var and its one module (gitchain: the\n * `chain` / `chain-review` tools) are deleted along with gitchain itself — the tool surface\n * is flat and always registered now, no opt-in module left to gate.\n */\n\nimport { randomUUID } from \"node:crypto\";\nimport express from \"express\";\nimport { createMcpHandler } from \"@modelcontextprotocol/server\";\nimport { toNodeHandler } from \"@modelcontextprotocol/node\";\nimport rateLimit from \"express-rate-limit\";\n\nimport { bootstrapHttp, DEFAULT_CLOUD_URL } from \"./client.js\"; import { appUrl } from \"./lib/appUrl.js\";\nimport { runWithAuth, getKeyState } from \"./auth.js\";\nimport { createProductBrainServer, SERVER_VERSION } from \"./server.js\";\nimport { buildUnavailableError, send429 } from \"./httpErrors.js\";\nimport { mcpLimiters } from \"./mcpRateLimit.js\";\nimport { AUTH_FAILURE_WINDOW_MS, authLockoutError, recordAuthFailure } from \"./authLockout.js\";\nimport { resolveBearerAuth, keyVerdictGate, type AuthFailureRecord } from \"./authLockout.js\";\nimport { checkRegistrationRedirects, resolveOAuthRedirectAllowlist } from \"./lib/oauthRedirectAllowlist.js\";\nimport { authorizeOutcome, exchangeOutcome, logOAuthDoor, sendDoor } from \"./lib/oauthDoors.js\";\nimport { registeredClientId } from \"./lib/connectClients.js\";\nimport { checkKeyAgainstCandidates, parseFallbackUrls } from \"./lib/deploymentUrlResolver.js\";\n\n// ── Bootstrap ───────────────────────────────────────────────────────────\n\nbootstrapHttp();\n\nconst PORT = parseInt(process.env.PORT ?? process.env.MCP_PORT ?? \"3002\", 10);\n\n/** DEC-789 S2: the deployments a key may live on — primary first, then CONVEX_FALLBACK_URLS. */\nfunction keyCheckCandidates(): string[] {\n const primaryUrl = (process.env.CONVEX_SITE_URL ?? DEFAULT_CLOUD_URL).replace(/\\/$/, \"\");\n return [primaryUrl, ...parseFallbackUrls(process.env.CONVEX_FALLBACK_URLS).map((u) => u.replace(/\\/$/, \"\"))];\n}\n\nfunction baseUrl(req: any): string {\n const proto = req.headers[\"x-forwarded-proto\"] ?? req.protocol ?? \"http\";\n const host = req.headers.host ?? `localhost:${PORT}`;\n return `${proto}://${host}`;\n}\n\n// ── Express App ─────────────────────────────────────────────────────────\n\nconst app = express();\n// Required when behind a reverse proxy (e.g. Railway): rate limiter uses X-Forwarded-For\n// and throws ERR_ERL_UNEXPECTED_X_FORWARDED_FOR if trust proxy is false.\napp.set(\"trust proxy\", 1);\napp.use(express.json());\n\n// CORS — defaults to https://claude.ai (per REMOTE.md). Override via CORS_ORIGINS env var.\nconst ALLOWED_ORIGINS = (process.env.CORS_ORIGINS ?? \"https://claude.ai\")\n .split(\",\")\n .map((o) => o.trim())\n .filter(Boolean);\n\n// The API key IS the access token, so every redirect_uri is vetted (lib/oauthRedirectAllowlist.ts).\nconst OAUTH_REDIRECT_ALLOWLIST = resolveOAuthRedirectAllowlist({ explicitAllowlist: process.env.OAUTH_REDIRECT_HOST_ALLOWLIST });\n\napp.use((_req: any, res: any, next: any) => {\n const origin = _req.headers.origin;\n if (origin && ALLOWED_ORIGINS.includes(origin)) {\n res.setHeader(\"Access-Control-Allow-Origin\", origin);\n }\n res.setHeader(\"Access-Control-Allow-Methods\", \"GET, POST, DELETE, OPTIONS\");\n // TASK-1640: no Mcp-Session-Id or Last-Event-Id any more (stateless); 2026-07-28 clients send Mcp-Method and Mcp-Name.\n res.setHeader(\n \"Access-Control-Allow-Headers\",\n \"Content-Type, Authorization, Mcp-Protocol-Version, Mcp-Method, Mcp-Name\",\n );\n // Retry-After is exposed so browser MCP clients (default origin https://claude.ai)\n // can read the structured-429 retry timing from JS, not just from the JSON body.\n res.setHeader(\"Access-Control-Expose-Headers\", \"Retry-After\");\n if (_req.method === \"OPTIONS\") {\n res.status(204).end();\n return;\n }\n next();\n});\n\n// ── OAuth: Protected Resource Metadata (RFC 9728) ────────────────────────\n// Step 1 of MCP auth: Claude fetches this to discover the authorization server.\n\napp.get(\"/.well-known/oauth-protected-resource\", (req: any, res: any) => {\n const base = baseUrl(req);\n res.json({\n resource: base,\n authorization_servers: [base],\n scopes_supported: [\"mcp:tools\", \"mcp:resources\"],\n bearer_methods_supported: [\"header\"],\n });\n});\n\n// ── OAuth: Authorization Server Metadata (RFC 8414) ──────────────────────\n// Step 2: Claude fetches this to discover authorize, token, and register endpoints.\n\napp.get(\"/.well-known/oauth-authorization-server\", (req: any, res: any) => {\n const base = baseUrl(req);\n res.json({\n issuer: base,\n authorization_endpoint: `${base}/authorize`,\n token_endpoint: `${base}/oauth/token`,\n registration_endpoint: `${base}/register`,\n response_types_supported: [\"code\"],\n grant_types_supported: [\"authorization_code\"], // TEN-4548: no refresh grant (lib/oauthAuthCode.ts tokenResponse)\n code_challenge_methods_supported: [\"S256\"],\n token_endpoint_auth_methods_supported: [\"none\"],\n scopes_supported: [\"mcp:tools\", \"mcp:resources\"],\n });\n});\n\n// ── OAuth: Rate Limiting ─────────────────────────────────────────────────\n// 20 a minute keyed on the client IP, on GET /authorize only, where the IP is the person's own browser.\n// It is off /register (stateless, stores nothing) and /oauth/token (a code is single-use, PKCE-bound\n// and dies in 5 minutes), where the caller is a vendor's server and every claude.ai user shares Anthropic's\n// egress IP (TEN-4678; DEC-2002 keeps the key lockout per credential for the same reason).\n\nconst authLimiter = rateLimit({\n windowMs: 60_000,\n max: 20,\n standardHeaders: true,\n legacyHeaders: false,\n handler: (req: any, res: any) => {\n logOAuthDoor(`${req.method} /authorize`, 429, \"rate_limited_per_ip\");\n res.status(429).json({ error: \"Too many auth requests. Try again later.\" });\n },\n});\n\n// ── OAuth: Dynamic Client Registration (RFC 7591) ────────────────────────\n// Step 3: the client registers before starting the auth flow. Stateless (TASK-1005): every\n// redirect_uri is checked against the exact-URI allowlist and an opaque id comes back, carrying the\n// app's own name (lib/connectClients.ts registeredClientId); nothing is stored, so a restart or a\n// deploy forgets nothing and there is no cap to hit. The guards are the allowlist at /authorize and\n// the code bound to its redirect_uri and PKCE challenge in Convex (DEC-2588); RFC 7591 does not\n// require server-side state for a public client (token_endpoint_auth_method \"none\").\n\napp.post(\n \"/register\",\n express.json(),\n (req: any, res: any) => {\n const { redirect_uris, client_name } = req.body ?? {};\n\n const { refusal, allowed, dropped } = checkRegistrationRedirects(redirect_uris, OAUTH_REDIRECT_ALLOWLIST); // DEC-2203\n if (refusal) {\n logOAuthDoor(\"POST /register\", 400, refusal, Array.isArray(redirect_uris) ? redirect_uris : [redirect_uris]);\n res.status(400).json({ error: \"invalid_redirect_uri\", error_description: refusal });\n return;\n }\n\n const clientId = registeredClientId(randomUUID(), client_name);\n const droppedUris = dropped.length > 0 ? dropped.map((d) => d.uri) : undefined;\n logOAuthDoor(\"POST /register\", 201, droppedUris ? \"dropped_redirects\" : \"registered\", droppedUris);\n res.status(201).json({\n client_id: clientId,\n client_name: client_name ?? \"MCP Client\",\n redirect_uris: allowed,\n grant_types: [\"authorization_code\"],\n response_types: [\"code\"],\n token_endpoint_auth_method: \"none\",\n });\n },\n);\n\n// ── OAuth: Authorization Code + PKCE ─────────────────────────────────────\n// Step 4 (DEC-2588): no form here. The client's request bounces to the web app's connect page, which signs the person in, lets them pick\n// a workspace and mints a connect token bound to the PKCE challenge and this redirect; the page sends the person back here with that code\n// (or with access_denied on Cancel), and this door returns it to the client. Every branch checks the redirect first\n// (lib/oauthDoors.ts authorizeOutcome). Nothing is kept: a redeploy mid-sign-in loses nothing.\n\napp.get(\"/authorize\", authLimiter, (req: any, res: any) => {\n sendDoor(res, \"GET /authorize\", authorizeOutcome(req.query ?? {}, { allowlist: OAUTH_REDIRECT_ALLOWLIST, appUrl: appUrl() }));\n});\n\n// The lockout map's stale records (the size cap is enforced at insert, recordAuthFailure).\nsetInterval(() => {\n const now = Date.now();\n for (const [credentialId, rec] of authFailures) {\n if (rec.blockedUntil < now && rec.firstFailure + AUTH_FAILURE_WINDOW_MS < now) {\n authFailures.delete(credentialId);\n }\n }\n}, 60_000);\n\n// ── OAuth: Token Exchange ────────────────────────────────────────────────\n// Step 5: the client exchanges the code with its PKCE verifier. The Convex redeem door checks the S256, the redirect, expiry and single\n// use, burns the code on a miss and only then mints the key, which is the access token (DEC-7; lib/oauthDoors.ts exchangeOutcome).\n// authorization_code is the only grant (TEN-4548).\n\napp.post(\n \"/oauth/token\",\n express.urlencoded({ extended: false }),\n express.json(),\n async (req: any, res: any) => {\n sendDoor(res, \"POST /oauth/token\", await exchangeOutcome(req.body ?? {}, { candidates: keyCheckCandidates() }));\n },\n);\n\n// ── Rate Limiting ────────────────────────────────────────────────────────\n// One pair for all three /mcp routes, so they share one budget: per credential, under a per-IP ceiling\n// (./mcpRateLimit.ts, TEN-4678).\nconst mcpLimit = mcpLimiters();\n\n// ── Auth Failure Backoff (Fix 5) ──────────────────────────────────────────\n// Progressive lockout for failed API key attempts, keyed on the presented key's hash (TEN-4673), on /mcp,\n// the one door that takes a key (DEC-2002). Policy + key classification live in ./authLockout.ts\n// (unit-tested); the state map stays here.\nconst authFailures = new Map<string, AuthFailureRecord>();\n\n// ── Health Check ─────────────────────────────────────────────────────────\n\napp.get(\"/health\", (_req: any, res: any) => {\n res.json({ status: \"ok\", version: SERVER_VERSION, transport: \"http\" });\n});\n\n// ── MCP Handler ─────────────────────────────────────────────────────────\n// TASK-1640: a fresh server per request for either era (legacy 'stateless', the default); GET and DELETE answer 405.\n\nconst mcpHandler = createMcpHandler(createProductBrainServer, { onerror: (err) => process.stderr.write(`[HTTP] handler_error ${err.message}\\n`) });\nconst serveNode = toNodeHandler(mcpHandler);\n\n\n// ── Auth Helpers ─────────────────────────────────────────────────────────\n// Bearer classification (absent vs. rejected vs. ok) lives in ./authLockout.ts\n// via resolveBearerAuth(); handlers call it directly so that only a\n// presented-and-rejected credential accrues toward the lockout (TEN-2606).\n\nfunction send401(req: any, res: any): void {\n const base = baseUrl(req);\n res\n .status(401)\n .set(\n \"WWW-Authenticate\",\n `Bearer resource_metadata=\"${base}/.well-known/oauth-protected-resource\"`,\n )\n .json({ error: \"unauthorized\" });\n}\n\nfunction logRequest(method: string, outcome: \"ok\" | \"auth_fail\" | \"error\", durationMs?: number, status?: number): void {\n const ts = new Date().toISOString();\n const st = status != null ? ` status=${status}` : \"\";\n const dur = durationMs != null ? ` duration=${durationMs}ms` : \"\";\n process.stderr.write(`[HTTP] ${ts} ${method} ${outcome}${st}${dur}\\n`);\n}\n\n// ── MCP Route ───────────────────────────────────────────────────────────\n\n/** The key of a request that may go on, or undefined once the lockout or a missing/refused bearer has answered it. */\nfunction admit(req: any, res: any, auth: ReturnType<typeof resolveBearerAuth>): Extract<typeof auth, { status: \"ok\" }> | undefined {\n // Fix 5 / TEN-4673 — refuse a presented key whose hash has exceeded the auth failure threshold.\n // TEN-2606 — only a *presented-and-rejected* credential accrues, and an absent one (the OAuth\n // bootstrap probe) is never recorded nor refused, so a locked key can always re-sign-in.\n const nowTs = Date.now();\n const lockout = authLockoutError(authFailures, auth, nowTs, req.body?.id ?? null);\n if (lockout) { send429(res, lockout); return; }\n if (auth.status === \"ok\") return auth;\n logRequest(req.method, \"auth_fail\");\n if (auth.status === \"rejected\") recordAuthFailure(authFailures, auth.credentialId, nowTs);\n send401(req, res);\n}\n\n/** TEN-4549: the kernel's verdict on the key, asked on every POST; false once a refusal has answered. Nothing caches the verdict. */\nfunction keyPasses(req: any, res: any, auth: Extract<ReturnType<typeof resolveBearerAuth>, { status: \"ok\" }>, check: Awaited<ReturnType<typeof checkKeyAgainstCandidates>>): boolean {\n const gate = keyVerdictGate(check.verdict, authFailures, auth.credentialId, Date.now());\n if (gate === \"unauthorized\") { logRequest(req.method, \"auth_fail\"); send401(req, res); return false; }\n if (gate === \"unavailable\") { // TASK-1849: our outage, never the key\n const built = buildUnavailableError(req.body?.id ?? null);\n res.status(built.status).json(built.body);\n return false;\n }\n if (check.verdict === \"ok\" || check.verdict === \"rate_limited\") getKeyState(auth.apiKey).deploymentUrl = check.deploymentUrl;\n return true;\n}\n\n/** Hands the request to the SDK handler inside its auth context, and logs or answers 500 on a throw. */\nasync function serve(req: any, res: any, apiKey: string, handle: () => Promise<unknown> | unknown): Promise<void> {\n const reqStart = Date.now();\n try {\n await runWithAuth({ apiKey, requestId: randomUUID() }, handle);\n logRequest(req.method, \"ok\", Date.now() - reqStart, res.statusCode);\n } catch {\n logRequest(req.method, \"error\", Date.now() - reqStart);\n if (!res.headersSent) res.status(500).json({ jsonrpc: \"2.0\", error: { code: -32603, message: \"Internal server error\" }, id: null });\n }\n}\n\n// Each block reads: the bearer, on POST the kernel's key check, then the handler (the security contract reads them here).\napp.post(\"/mcp\", ...mcpLimit, async (req, res) => {\n const auth = admit(req, res, resolveBearerAuth(req.headers?.authorization));\n if (!auth) return;\n if (!keyPasses(req, res, auth, await checkKeyAgainstCandidates(keyCheckCandidates(), auth.apiKey, 5000))) return;\n await serve(req, res, auth.apiKey, () => serveNode(req, res, req.body));\n});\napp.get(\"/mcp\", ...mcpLimit, async (req, res) => {\n const auth = admit(req, res, resolveBearerAuth(req.headers?.authorization));\n if (auth) await serve(req, res, auth.apiKey, () => serveNode(req, res));\n});\napp.delete(\"/mcp\", ...mcpLimit, async (req, res) => {\n const auth = admit(req, res, resolveBearerAuth(req.headers?.authorization));\n if (auth) await serve(req, res, auth.apiKey, () => serveNode(req, res));\n});\n\n// ── Start ───────────────────────────────────────────────────────────────\n\nprocess.on(\"unhandledRejection\", (reason) => {\n const msg = reason instanceof Error ? reason.message : String(reason);\n console.error(`[MCP HTTP] Unhandled rejection: ${msg}`);\n});\n\nprocess.on(\"uncaughtException\", (err) => {\n console.error(`[MCP HTTP] Uncaught exception: ${err.stack ?? err.message}`);\n gracefulShutdown();\n});\n\nlet shuttingDown = false;\nasync function gracefulShutdown() {\n if (shuttingDown) return;\n shuttingDown = true;\n setTimeout(() => process.exit(1), 3_000).unref();\n console.log(\"Shutting down...\");\n await mcpHandler.close().catch(() => {});\n process.exit(0);\n}\n\n// Bind all interfaces — Railway/Cloudflare reach the container on its non-loopback IP.\n// Loopback-only (127.0.0.1) causes edge 502: the proxy never connects to localhost inside the pod.\nconst LISTEN_HOST = \"0.0.0.0\";\nconst httpServer = app.listen(PORT, LISTEN_HOST, () => {\n console.log(\n `Product Brain MCP HTTP server v${SERVER_VERSION} listening on ${LISTEN_HOST}:${PORT}`,\n );\n});\nhttpServer.on(\"error\", (err: Error) => {\n console.error(`[MCP HTTP] Server error: ${err.message}`);\n process.exit(1);\n});\n\nprocess.on(\"SIGINT\", gracefulShutdown);\nprocess.on(\"SIGTERM\", gracefulShutdown);\n","/**\n * httpErrors.ts — pure, import-safe builders for structured 429 responses, and the 503 the key check answers when Product Brain is down.\n *\n * Both 429 sources (rate limit, auth lockout) return a\n * JSON-RPC envelope so the consuming MCP client can tell them apart.\n *\n * Rule — id mirrors the JSON-RPC request id when known\n * ---------------------------------------------------------------------------\n * JSON-RPC requires the response id to mirror the request id so the client can\n * correlate. Both call-sites run AFTER the global `express.json()`\n * middleware, so a POST body is already parsed and callers SHOULD thread\n * `req.body?.id` through `BuildParams.id` (the POST `/mcp` rate-limit and\n * auth-lockout gates both do). Requests with no parsable body\n * (GET/DELETE, or a malformed POST) have no id to mirror — those omit `id` and\n * it defaults to `null`, which is the correct JSON-RPC value for \"unknown id\".\n * ---------------------------------------------------------------------------\n */\n\nimport { UNAVAILABLE } from \"./lib/unavailableWords.js\"; // GENERATED copy of kernel/unavailableWords.ts\n\nexport interface Built429 {\n status: 429;\n headers: Record<string, string>;\n body: unknown;\n}\n\n// ---------------------------------------------------------------------------\n// Internal helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Clamp to non-negative, round to integer — used for both the Retry-After\n * header value and the `retryAfterSeconds` field in `data`.\n */\nfunction clampSeconds(s: number): number {\n return Math.max(0, Math.round(s));\n}\n\ntype Reason = \"rate_limited\" | \"auth_lockout\";\n\n/** JSON-RPC request/response id. `null` is the spec value for \"unknown id\". */\ntype JsonRpcId = string | number | null;\n\ninterface BuildParams {\n retryAfterSeconds: number;\n limit: number;\n current: number;\n /** Request id to mirror; defaults to null when the caller has no body id. */\n id?: JsonRpcId;\n}\n\nfunction build(\n reason: Reason,\n message: string,\n p: BuildParams,\n): Built429 {\n const seconds = clampSeconds(p.retryAfterSeconds);\n return {\n status: 429,\n headers: { \"Retry-After\": String(seconds) },\n body: {\n jsonrpc: \"2.0\",\n id: p.id ?? null,\n error: {\n code: -32000,\n message,\n data: {\n reason,\n retryAfterSeconds: seconds,\n limit: p.limit,\n current: p.current,\n },\n },\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// Public builders\n// ---------------------------------------------------------------------------\n\n/**\n * Rate-limit 429 (source: the /mcp limiters in mcpRateLimit.ts, per credential under a per-IP ceiling).\n * reason = \"rate_limited\"\n */\nexport function buildRateLimitError(p: BuildParams): Built429 {\n const seconds = clampSeconds(p.retryAfterSeconds);\n return build(\n \"rate_limited\",\n `Too many requests — retry after ${seconds} s.`,\n p,\n );\n}\n\n/**\n * Per-presented-key auth-failure lockout 429 (source: authLockoutError in authLockout.ts, TEN-4673).\n * reason = \"auth_lockout\"\n */\nexport function buildAuthLockoutError(p: BuildParams): Built429 {\n const seconds = clampSeconds(p.retryAfterSeconds);\n return build(\n \"auth_lockout\",\n `Too many failed auth attempts — locked out, retry after ${seconds} s.`,\n p,\n );\n}\n\n/**\n * TASK-1849 (TEN-6491): the key check got no answer from Product Brain (http.ts keyPasses), so the request is refused as our\n * outage. It says nothing about the key: the key was not checked. Nothing ran, so nothing was saved.\n */\nexport function buildUnavailableError(id: JsonRpcId = null): { status: 503; body: { jsonrpc: \"2.0\"; id: JsonRpcId; error: { code: number; message: string } } } {\n return { status: 503, body: { jsonrpc: \"2.0\", id, error: { code: -32000, message: `${UNAVAILABLE.down}\\n${UNAVAILABLE.nothingSaved}` } } };\n}\n\n// ---------------------------------------------------------------------------\n// Sender\n// ---------------------------------------------------------------------------\n\n/**\n * Minimal structural shape of the response object send429 needs. Any\n * Express/Hono response satisfies it; the explicit interface (rather than\n * `any`) keeps a wrong argument from compiling and silently swallowing a 429.\n */\nexport interface Http429Response {\n headersSent: boolean;\n setHeader(name: string, value: string): unknown;\n status(code: number): { json(body: unknown): unknown };\n}\n\n/**\n * Write a Built429 to an Express/Hono-compatible response object.\n *\n * Guards `res.headersSent` first so calling this on an already-flushed\n * response is a safe no-op (e.g. when a middleware has already sent a body).\n */\nexport function send429(res: Http429Response, built: Built429): void {\n if (res.headersSent) return;\n for (const [k, v] of Object.entries(built.headers)) {\n res.setHeader(k, v);\n }\n res.status(built.status).json(built.body);\n}\n","// The /mcp request limiter (POST, GET, DELETE), out of http.ts so a test can drive it (http.ts binds a live\n// server on import).\n//\n// TEN-4678: every claude.ai user reaches /mcp from Anthropic's shared egress addresses, so a bucket per\n// client IP let one busy connector answer 429 to every other one. The budget is per credential instead:\n// the hash of the presented bearer (never the raw key, RULE-232), the same id the auth lockout keys on.\n// The limiter runs before auth, so a caller could rotate made-up bearers to get a fresh bucket each time;\n// a looser ceiling per client IP sits in front of the per-key bucket and bounds that. A request with no\n// bearer (the OAuth bootstrap probe) counts against its IP.\n\nimport rateLimit from \"express-rate-limit\";\nimport { resolveBearerAuth } from \"./authLockout.js\";\nimport { buildRateLimitError, send429 } from \"./httpErrors.js\";\n\n/** Requests a minute per credential. */\nexport const MCP_KEY_LIMIT = 120;\n/** Requests a minute per client IP, across every credential it presents: ten busy keys' worth. */\nexport const MCP_IP_CEILING = 1_200;\n\n/** The bucket a request counts against: its bearer's hash, or its IP when it presents none. */\nexport function mcpRateKey(req: { headers?: { authorization?: unknown }; ip?: string }): string {\n const auth = resolveBearerAuth(req.headers?.authorization);\n return auth.status === \"absent\" ? `ip:${req.ip ?? \"\"}` : `key:${auth.credentialId}`;\n}\n\nfunction limiter(max: number, windowMs: number, keyGenerator?: (req: any) => string) {\n return rateLimit({\n windowMs,\n max,\n standardHeaders: true,\n legacyHeaders: false,\n ...(keyGenerator ? { keyGenerator } : {}),\n handler: (req: any, res: any) => {\n const r = req.rateLimit;\n const reset = r?.resetTime?.getTime?.() ?? Date.now() + windowMs;\n send429(res, buildRateLimitError({\n retryAfterSeconds: Math.max(1, Math.ceil((reset - Date.now()) / 1000)),\n limit: r?.limit ?? max,\n current: r?.used ?? 0,\n id: req.body?.id ?? null, // mirror the JSON-RPC id when a POST body is present\n }));\n },\n });\n}\n\n/** The two limiters every /mcp route mounts, in order: the per-IP ceiling, then the per-credential bucket. */\nexport function mcpLimiters(opts: { keyLimit?: number; ipCeiling?: number; windowMs?: number } = {}) {\n const windowMs = opts.windowMs ?? 60_000;\n return [\n limiter(opts.ipCeiling ?? MCP_IP_CEILING, windowMs),\n limiter(opts.keyLimit ?? MCP_KEY_LIMIT, windowMs, mcpRateKey),\n ];\n}\n","// Progressive lockout for failed API-key auth attempts, keyed on the hash of the PRESENTED\n// credential, plus the classification that feeds it. Extracted from http.ts so the policy is\n// unit-testable in isolation (http.ts binds a live server on import).\n//\n// TEN-4673 (WP-827, TASK-698): the counter keys on hashKey(presented credential), the thing being\n// guessed, never the raw key and never the client IP. claude.ai and other hosted clients reach\n// /mcp from shared egress addresses, so a per-IP counter let ten bad keys from one stale connector\n// lock every user of that platform out. Now ten rejected presentations of key A lock key A from\n// every address, and a valid key B from the same address keeps working. No path counts per IP: an\n// absent credential never accrues (TEN-2606). The lockout is defence in depth and load shedding; the\n// 128-bit key itself is the guard against guessing.\n//\n// TEN-2606: the lockout penalizes only a *presented-and-rejected* credential, never an *absent*\n// one, and never answers 429 to one. Absent-credential /mcp calls are the spec-mandated OAuth\n// bootstrap probe (the client hits the resource with no token to receive the 401 +\n// WWW-Authenticate challenge), so a client whose key is locked can always start a fresh sign-in.\n//\n// TEN-4549: the shape check alone let any `pb_sk_<anything>` open an MCP session without ever\n// accruing toward the lockout. keyVerdictGate() is where the kernel's verdict on the key lands:\n// a key the kernel rejects is a presented-and-rejected credential like any other.\n//\n// TEN-4601 (TASK-684): the lockout guards every door a key is presented at, over ONE map in http.ts. Since DEC-2588 no key is\n// pasted anywhere: /mcp (POST, GET, DELETE) is the one such door.\n\nimport { hashKey } from \"./auth.js\";\nimport type { KeyCheckResult } from \"./lib/deploymentUrlResolver.js\";\nimport { buildAuthLockoutError, type Built429 } from \"./httpErrors.js\";\nimport { isApiKeyShaped } from \"./lib/tokenConstants.js\";\n\nexport interface AuthFailureRecord {\n count: number;\n firstFailure: number;\n blockedUntil: number;\n}\n\n// Outcome of classifying a presented credential. `credentialId` is hashKey() of what was\n// presented (RULE-232: the map never holds a raw key) and is the lockout map's key.\n// - \"ok\": an API-key-shaped key; initialize asks the kernel whether it is real.\n// - \"absent\": no credential was presented: never penalized, never locked out.\n// - \"rejected\": a credential was presented but can never authenticate: penalized.\nexport type BearerAuth =\n | { status: \"ok\"; apiKey: string; credentialId: string }\n | { status: \"absent\" }\n | { status: \"rejected\"; credentialId: string };\n\nexport const AUTH_FAILURE_MAX = 10;\nexport const AUTH_FAILURE_WINDOW_MS = 5 * 60_000; // 5 minutes\nexport const AUTH_BLOCK_DURATION_MS = 15 * 60_000; // 15 minutes\nexport const MAX_AUTH_FAILURE_ENTRIES = 10_000;\n\nfunction rejected(presented: string): BearerAuth {\n return { status: \"rejected\", credentialId: hashKey(presented) };\n}\n\n/**\n * Classify a request's Authorization header into absent / rejected / ok.\n *\n * The only credential is an API key: the OAuth token door hands the key itself back as\n * the access token (DEC-7, lib/oauthAuthCode.ts tokenResponse; TEN-4548 deleted the never-written\n * pb_at_ opaque-token store).\n */\nexport function resolveBearerAuth(authorizationHeader: unknown): BearerAuth {\n if (typeof authorizationHeader !== \"string\" || authorizationHeader.trim() === \"\") {\n // No Authorization header at all: the OAuth bootstrap probe. This is the ONLY case that\n // escapes the lockout: a client hitting the resource with no credential to fetch the\n // 401 + WWW-Authenticate challenge.\n return { status: \"absent\" };\n }\n if (!authorizationHeader.startsWith(\"Bearer \")) {\n // A credential of a wrong scheme (e.g. Basic) was presented. It can never authenticate, so it\n // is a rejected attempt; classifying it \"absent\" would let a caller bypass the guard.\n return rejected(authorizationHeader.trim());\n }\n const token = authorizationHeader.slice(7).trim();\n // \"Bearer \" with an empty token is a presented, unusable credential, not the header-less probe;\n // a token of unknown shape is garbage that was still presented.\n if (!isApiKeyShaped(token)) return rejected(token);\n return { status: \"ok\", apiKey: token, credentialId: hashKey(token) };\n}\n\n/** True if `credentialId` is currently within an active lockout block. */\nexport function checkAuthBlock(\n failures: Map<string, AuthFailureRecord>,\n credentialId: string,\n now: number,\n): boolean {\n const rec = failures.get(credentialId);\n if (!rec) return false;\n return rec.blockedUntil > now;\n}\n\n/**\n * The lockout 429 for the presented credential (Retry-After = seconds left in the block), or null\n * when it is not blocked or no credential was presented (TEN-2606: the bootstrap probe is never\n * refused). /mcp asks this first and sends it as is. `id` mirrors the JSON-RPC request id when known.\n */\nexport function authLockoutError(\n failures: Map<string, AuthFailureRecord>,\n auth: BearerAuth,\n now: number,\n id: string | number | null = null,\n): Built429 | null {\n if (auth.status === \"absent\") return null;\n const rec = failures.get(auth.credentialId);\n if (!rec || !checkAuthBlock(failures, auth.credentialId, now)) return null;\n const retryAfterSeconds = Math.max(0, Math.ceil((rec.blockedUntil - now) / 1000));\n return buildAuthLockoutError({ retryAfterSeconds, limit: AUTH_FAILURE_MAX, current: rec.count, id });\n}\n\n/**\n * Record one presented-and-rejected auth failure for `credentialId`. Callers MUST NOT call this\n * for an absent credential (TEN-2606). Tips the credential into a block once AUTH_FAILURE_MAX\n * failures land inside AUTH_FAILURE_WINDOW_MS; a failure past the window resets the count rather\n * than accumulating across windows. The map holds at most MAX_AUTH_FAILURE_ENTRIES records: a new\n * credential past the cap evicts the oldest-inserted one (a memory bound, not a guard; see header).\n */\nexport function recordAuthFailure(\n failures: Map<string, AuthFailureRecord>,\n credentialId: string,\n now: number,\n): void {\n const rec = failures.get(credentialId);\n\n if (!rec) {\n if (failures.size >= MAX_AUTH_FAILURE_ENTRIES) {\n const oldest = failures.keys().next().value;\n if (oldest !== undefined) failures.delete(oldest);\n }\n failures.set(credentialId, { count: 1, firstFailure: now, blockedUntil: 0 });\n return;\n }\n\n // Reset the window if the first failure is outside the tracking window.\n if (now - rec.firstFailure > AUTH_FAILURE_WINDOW_MS) {\n rec.count = 1;\n rec.firstFailure = now;\n rec.blockedUntil = 0;\n } else {\n rec.count++;\n if (rec.count >= AUTH_FAILURE_MAX) {\n rec.blockedUntil = now + AUTH_BLOCK_DURATION_MS;\n }\n }\n}\n\n/**\n * TEN-4549 / TEN-4601: what a door does with the kernel's verdict on a presented API key\n * (lib/deploymentUrlResolver.ts checkKeyAgainstCandidates, asked once per MCP initialize; no cache\n * of accepted keys outlives the session).\n * - ok / rate_limited → \"admit\": the key is real (a throttled workspace is still a real key).\n * - rejected → \"unauthorized\", and the failure accrues to that key's lockout record.\n * - unreachable → \"unavailable\": never penalize the caller for the kernel being down\n * (initialize fails closed with no session).\n */\nexport function keyVerdictGate(\n verdict: KeyCheckResult[\"verdict\"],\n failures: Map<string, AuthFailureRecord>,\n credentialId: string,\n now: number,\n): \"admit\" | \"unauthorized\" | \"unavailable\" {\n if (verdict === \"ok\" || verdict === \"rate_limited\") return \"admit\";\n if (verdict === \"rejected\") {\n recordAuthFailure(failures, credentialId, now);\n return \"unauthorized\";\n }\n return \"unavailable\";\n}\n","/**\n * OAuth redirect_uri policy for the remote MCP HTTP server (POST /register, GET /authorize).\n *\n * Why this exists: /oauth/token returns the caller's raw API key as the OAuth access\n * token (intentional: it survives Railway restarts). Before this policy, /register stored any\n * redirect_uris and /authorize auto-registered any https redirect_uri for an unknown client_id,\n * so a link on our real domain could send a victim's pasted key to an attacker:\n * 1. attacker builds /authorize?client_id=x&redirect_uri=https://evil.example/cb&code_challenge=...\n * 2. victim pastes their API key into our real page\n * 3. the one-time code lands at evil.example; the attacker redeems it at /oauth/token for the key.\n *\n * The policy, applied at every entry point:\n * - https redirect_uris are accepted only as an EXACT redirect URI (scheme + host + path) on the\n * allowlist: the platforms' own documented callbacks below, plus OAUTH_REDIRECT_HOST_ALLOWLIST\n * entries. A host alone is not enough: an allowed host can serve a callback path that belongs\n * to someone else (a custom GPT's `https://chatgpt.com/aip/{g-ID}/oauth/callback` exchanges the\n * code at a token URL its builder chose). The host compares case-insensitively; the path\n * compares exactly, so a trailing slash or an extra segment is refused. CORS_ORIGINS is\n * deliberately NOT included: a CORS origin is a browser-fetch permission, not a place we send\n * an API key.\n * - http redirect_uris are accepted only on a loopback host (localhost, 127.0.0.1, [::1]), any\n * port and path. This is the RFC 8252 section 7.3 native-app exception (Claude Code and other\n * local MCP clients use it) and is on in production: the browser follows the redirect on the\n * victim's OWN machine, so an attacker cannot receive the code unless they already run code there.\n * - https must use the default port (empty or 443) and carry no query; loopback keeps any port.\n * - no credentials in the URI, no fragment, at most 2048 characters.\n * Every check returns a plain-language refusal reason, or null when the URI is allowed. Callers\n * respond 400 with that reason; nothing here ever fails open.\n */\n\n/**\n * Built-in exact https redirect URIs (origin + path).\n * - https://claude.ai/api/mcp/auth_callback: the hosted Claude apps' one callback,\n * https://claude.com/docs/connectors/building/authentication (\"Callback URLs\").\n * - https://claude.com/api/mcp/auth_callback: the announced move of that callback to claude.com.\n * Anthropic's current page above names only claude.ai; the claude.com form is listed by\n * https://docs.strata.io/guides/ai-identity/connect/claude. Same owner, same path.\n * - https://chatgpt.com/connector_platform_oauth_redirect: ChatGPT's stable connector callback,\n * https://developers.openai.com/plugins/build/auth.\n * - https://www.cursor.com/agents/mcp/oauth/callback: Cursor web and Cursor agents' one callback,\n * https://cursor.com/docs/context/mcp (TASK-1005). Cursor desktop uses loopback, allowed below;\n * its cursor:// scheme stays refused. Every MCP server a person connects in Cursor shares this\n * URL and is told apart by state alone (TEN-5409, open).\n */\nexport const DEFAULT_OAUTH_REDIRECT_URIS: readonly string[] = [\n \"https://claude.ai/api/mcp/auth_callback\",\n \"https://claude.com/api/mcp/auth_callback\",\n \"https://chatgpt.com/connector_platform_oauth_redirect\",\n \"https://www.cursor.com/agents/mcp/oauth/callback\",\n];\n\n/**\n * ChatGPT's per-connection callback `https://chatgpt.com/connector/oauth/{callback_id}`\n * (https://developers.openai.com/plugins/build/auth). Exactly one id segment, nothing after it.\n */\nconst CHATGPT_CONNECTOR_CALLBACK = /^https:\\/\\/chatgpt\\.com\\/connector\\/oauth\\/[A-Za-z0-9_-]+$/;\n\n/** Hostnames as `URL.hostname` reports them (IPv6 keeps its brackets). */\nconst LOOPBACK_HOSTS: readonly string[] = [\"localhost\", \"127.0.0.1\", \"[::1]\"];\n\nconst MAX_REDIRECT_URI_LENGTH = 2048;\nconst MAX_REGISTRATION_REDIRECTS = 10;\n\nconst OPERATOR_ENTRY_FORM =\n \"OAUTH_REDIRECT_HOST_ALLOWLIST entries must be full https redirect URIs such as https://partner.example/oauth/callback (no bare host, no query, no fragment)\";\n\n/** The effective https redirect policy. A non-null `configError` refuses every redirect_uri. */\nexport interface OAuthRedirectAllowlist {\n uris: readonly string[];\n configError: string | null;\n}\n\n/** `origin + pathname` of an absolute URL: the form every allowlist entry is compared in. */\nfunction exactForm(url: URL): string {\n return `${url.origin}${url.pathname}`;\n}\n\n/**\n * Parse OAUTH_REDIRECT_HOST_ALLOWLIST (comma-separated). Every entry must be a full https redirect\n * URI with a path; one bare host or malformed entry makes the whole value a config error, so OAuth\n * fails closed until the operator fixes it (the error names the required form).\n */\nexport function parseRedirectUriAllowlist(raw: string | undefined): { uris: string[]; configError: string | null } {\n if (!raw) return { uris: [], configError: null };\n const uris: string[] = [];\n for (const part of raw.split(\",\")) {\n const trimmed = part.trim();\n if (!trimmed) continue;\n let url: URL | null = null;\n try {\n url = trimmed.includes(\"://\") ? new URL(trimmed) : null;\n } catch {\n url = null;\n }\n const valid =\n url !== null &&\n url.protocol === \"https:\" &&\n !url.username && !url.password && !url.search && !url.hash &&\n (url.port === \"\" || url.port === \"443\") &&\n url.pathname !== \"/\";\n if (!valid || url === null) {\n return { uris: [], configError: `${OPERATOR_ENTRY_FORM}; got \"${trimmed}\"` };\n }\n uris.push(exactForm(url));\n }\n return { uris, configError: null };\n}\n\n/** Effective allowlist: built-in exact URIs + OAUTH_REDIRECT_HOST_ALLOWLIST, nothing else. */\nexport function resolveOAuthRedirectAllowlist(opts: { explicitAllowlist?: string } = {}): OAuthRedirectAllowlist {\n const parsed = parseRedirectUriAllowlist(opts.explicitAllowlist);\n return {\n uris: [...new Set<string>([...DEFAULT_OAUTH_REDIRECT_URIS, ...parsed.uris])],\n configError: parsed.configError,\n };\n}\n\n/**\n * Check one redirect_uri. Returns the refusal reason, or null when it is allowed.\n */\nexport function checkRedirectUri(redirectUri: unknown, allowlist: OAuthRedirectAllowlist): string | null {\n if (allowlist.configError) return `OAuth is misconfigured: ${allowlist.configError}`;\n if (typeof redirectUri !== \"string\" || redirectUri.length === 0) {\n return \"redirect_uri is required\";\n }\n if (redirectUri.length > MAX_REDIRECT_URI_LENGTH) {\n return `redirect_uri is longer than ${MAX_REDIRECT_URI_LENGTH} characters`;\n }\n let url: URL;\n try {\n url = new URL(redirectUri);\n } catch {\n return \"redirect_uri is not a valid absolute URL\";\n }\n if (url.username || url.password) return \"redirect_uri must not contain credentials\";\n if (url.hash) return \"redirect_uri must not contain a fragment\";\n\n const host = url.hostname.toLowerCase();\n if (url.protocol === \"http:\") {\n return LOOPBACK_HOSTS.includes(host)\n ? null\n : \"redirect_uri must use https (http is allowed only for localhost, 127.0.0.1 or [::1])\";\n }\n if (url.protocol === \"https:\") {\n if (url.port && url.port !== \"443\") return \"redirect_uri must use the default https port (443)\";\n if (url.search) return \"redirect_uri must not contain a query\";\n const exact = exactForm(url);\n return allowlist.uris.includes(exact) || CHATGPT_CONNECTOR_CALLBACK.test(exact)\n ? null\n : \"redirect_uri is not an allowed callback (an operator can add the full URI with OAUTH_REDIRECT_HOST_ALLOWLIST)\";\n }\n return \"redirect_uri scheme is not allowed (use https, or http on loopback)\";\n}\n\n/** A registration's redirect_uris split by the policy; `refusal` is set when the request must be refused. */\nexport interface RegistrationRedirects {\n refusal: string | null;\n allowed: string[];\n dropped: { uri: unknown; reason: string }[];\n}\n\n/**\n * Check a whole registration `redirect_uris` value (DEC-2203). The registration is accepted when at\n * least one entry passes, and the 201 lists only the passing entries (RFC 7591 lets the server\n * return altered metadata); it is refused (invalid_redirect_uri) only when none passes, or when the\n * value is not a 1-to-10 entry array. Cursor sends cursor://, its web callback and a loopback URI in\n * one array. /authorize re-checks the redirect on every request, so dropping refuses nothing extra.\n */\nexport function checkRegistrationRedirects(redirectUris: unknown, allowlist: OAuthRedirectAllowlist): RegistrationRedirects {\n const refused = (refusal: string): RegistrationRedirects => ({ refusal, allowed: [], dropped: [] });\n if (!Array.isArray(redirectUris) || redirectUris.length === 0) return refused(\"redirect_uris is required\");\n if (redirectUris.length > MAX_REGISTRATION_REDIRECTS) {\n return refused(`redirect_uris may hold at most ${MAX_REGISTRATION_REDIRECTS} entries`);\n }\n const allowed: string[] = [];\n const dropped: { uri: unknown; reason: string }[] = [];\n for (const uri of redirectUris) {\n const reason = checkRedirectUri(uri, allowlist);\n if (reason) dropped.push({ uri, reason });\n else allowed.push(uri as string);\n }\n return { refusal: allowed.length === 0 ? dropped[0].reason : null, allowed, dropped };\n}\n","// GENERATED by scripts/generate-mcp-embedded-copies.mjs from kernel/governance/connectClientNames.ts.\n// DO NOT EDIT. Run `npm run mcp:embedded-copies` to regenerate.\n// Local runtime copy for the isolated connector build.\n\n/**\n * The hosted vendors whose connect replaces that person's earlier key for the same client in that workspace (DEC-2588, TASK-1011),\n * keyed by the exact redirect's host. One source (RULE-664): the web connect page and the hosted server name a client from it\n * (src/lib/connect/connectClients.ts and its generated copy), and Convex reads which names it holds live keys for (connectPage).\n * Zero imports, so the generator copies it verbatim.\n */\nexport const CONNECT_CLIENT_LABELS: Readonly<Record<string, string>> = {\n\t'claude.ai': 'Claude',\n\t'claude.com': 'Claude',\n\t'chatgpt.com': 'ChatGPT',\n\t'www.cursor.com': 'Cursor (web)',\n};\n\n/** Each clientName a key can carry: only these connects replace. */\nexport const REPLACEABLE_CLIENT_NAMES: readonly string[] = [...new Set(Object.values(CONNECT_CLIENT_LABELS))];\n","// GENERATED by scripts/generate-mcp-embedded-copies.mjs from src/lib/connect/connectClients.ts.\n// DO NOT EDIT. Run `npm run mcp:embedded-copies` to regenerate.\n// Local runtime copy for the isolated connector build.\n\n/**\n * Who is connecting, read from the OAuth request itself (DEC-2588, TASK-1011): the exact redirect a client sent and the client_id the\n * hosted /register issued. One place for the label table that sits beside the hosted redirect allowlist; the hosted server reads its\n * generated copy (packages/mcp-server/src/lib/connectClients.ts, scripts/generate-mcp-embedded-copies.mjs) and the web connect page reads\n * this file. Its one import, the label table (kernel/governance/connectClientNames.ts, which Convex reads too), is rewritten in the copy;\n * it lives in src/ because the kernel's lib has no URL.\n *\n * - A hosted vendor (Claude, ChatGPT, Cursor (web)) is named from the redirect's host, and that name is the key's clientName: a reconnect\n * replaces the person's earlier key for it (generateApiKey).\n * - An app on this computer (a loopback redirect) is never replaced; it is named from the client_name it registered, carried in the\n * stateless client_id as pb_client_<uuid>.<base64url name>, else \"Local app\". Anything can call itself \"Zed\", so a screen shows it quoted.\n * - Any other https redirect the operator allowed is named by its host and never replaced.\n * The allowlist stays the door that refuses a redirect; this file only names one.\n */\n\nimport { CONNECT_CLIENT_LABELS } from './connectClientNames.js';\n\n/** What an app's own name may be: at most 40 characters, printable, one line. */\nexport const LOCAL_APP_NAME_MAX = 40;\n/** A local app's key name when it registered no usable name. */\nexport const LOCAL_APP_KEY_NAME = 'Local app';\n\nconst CLIENT_ID_PREFIX = 'pb_client_';\nconst LOOPBACK_HOSTS = ['localhost', '127.0.0.1', '[::1]'];\n\nexport type ConnectClient =\n\t| { kind: 'vendor'; clientName: string; host: string }\n\t| { kind: 'local'; appName: string | null; at: string }\n\t| { kind: 'web'; host: string };\n\n/** A registered name made safe to show and store: control characters dropped, spaces folded, trimmed, cut to 40 characters. */\nexport function cleanAppName(raw: unknown): string | null {\n\tif (typeof raw !== 'string') return null;\n\t// eslint-disable-next-line no-control-regex\n\tconst folded = raw.replace(/[\\u0000-\\u001f\\u007f-\\u009f\\u200b-\\u200f\\u2028-\\u202e\\u2066-\\u2069]/g, ' ').replace(/\\s+/g, ' ').trim();\n\tconst cut = Array.from(folded).slice(0, LOCAL_APP_NAME_MAX).join('').trim();\n\treturn cut === '' ? null : cut;\n}\n\nconst B64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';\n\nfunction utf8Bytes(text: string): number[] {\n\tconst bytes: number[] = [];\n\tconst escaped = encodeURIComponent(text);\n\tfor (let i = 0; i < escaped.length; i++) {\n\t\tif (escaped[i] === '%') { bytes.push(parseInt(escaped.slice(i + 1, i + 3), 16)); i += 2; }\n\t\telse bytes.push(escaped.charCodeAt(i));\n\t}\n\treturn bytes;\n}\n\nfunction base64url(bytes: number[]): string {\n\tlet out = '';\n\tfor (let i = 0; i < bytes.length; i += 3) {\n\t\tconst n = (bytes[i]! << 16) | ((bytes[i + 1] ?? 0) << 8) | (bytes[i + 2] ?? 0);\n\t\tout += B64[(n >> 18) & 63]! + B64[(n >> 12) & 63]!;\n\t\tif (i + 1 < bytes.length) out += B64[(n >> 6) & 63]!;\n\t\tif (i + 2 < bytes.length) out += B64[n & 63]!;\n\t}\n\treturn out;\n}\n\nfunction fromBase64url(text: string): string | null {\n\tif (!/^[A-Za-z0-9_-]*$/.test(text) || text.length % 4 === 1) return null;\n\tlet escaped = '';\n\tfor (let i = 0; i < text.length; i += 4) {\n\t\tconst quad = text.slice(i, i + 4);\n\t\tconst n = Array.from(quad).reduce((acc, ch, j) => acc | (B64.indexOf(ch) << (18 - 6 * j)), 0);\n\t\tconst bytes = [(n >> 16) & 255, (n >> 8) & 255, n & 255].slice(0, quad.length - 1);\n\t\tfor (const b of bytes) escaped += `%${b.toString(16).padStart(2, '0')}`;\n\t}\n\ttry { return decodeURIComponent(escaped); } catch { return null; }\n}\n\n/** The client_id /register hands out: pb_client_<uuid>, with the app's cleaned name after a dot when it gave one. */\nexport function registeredClientId(uuid: string, clientName: unknown): string {\n\tconst name = cleanAppName(clientName);\n\treturn name === null ? `${CLIENT_ID_PREFIX}${uuid}` : `${CLIENT_ID_PREFIX}${uuid}.${base64url(utf8Bytes(name))}`;\n}\n\n/** The app name a client_id carries, cleaned again on the way out (never trusted), or null. */\nexport function appNameFromClientId(clientId: unknown): string | null {\n\tif (typeof clientId !== 'string' || !clientId.startsWith(CLIENT_ID_PREFIX)) return null;\n\tconst dot = clientId.indexOf('.');\n\tif (dot === -1) return null;\n\treturn cleanAppName(fromBase64url(clientId.slice(dot + 1)));\n}\n\n/** Who a redirect and client_id name, or null when the redirect is not an absolute http(s) URL. */\nexport function connectClientOf(redirectUri: unknown, clientId: unknown): ConnectClient | null {\n\tif (typeof redirectUri !== 'string') return null;\n\tlet url: URL;\n\ttry { url = new URL(redirectUri); } catch { return null; }\n\tconst host = url.hostname.toLowerCase();\n\tif (url.protocol === 'http:' && LOOPBACK_HOSTS.includes(host)) return { kind: 'local', appName: appNameFromClientId(clientId), at: url.host };\n\tif (url.protocol !== 'https:') return null;\n\tconst clientName = CONNECT_CLIENT_LABELS[host];\n\treturn clientName ? { kind: 'vendor', clientName, host } : { kind: 'web', host };\n}\n\n/** The name the minted key carries in Settings. */\nexport const connectKeyName = (client: ConnectClient): string =>\n\tclient.kind === 'vendor' ? client.clientName : client.kind === 'local' ? (client.appName ?? LOCAL_APP_KEY_NAME) : client.host;\n\n/** The clientName a key is stored with: only a hosted vendor's, so only those connects replace. */\nexport const connectClientName = (client: ConnectClient): string | undefined => (client.kind === 'vendor' ? client.clientName : undefined);\n","/** What the OAuth token door answers (DEC-2588: the code is a connect token Convex redeems; lib/oauthDoors.ts). */\n/**\n * The POST /oauth/token response body (DEC-7: the access token IS the caller's API key).\n *\n * TEN-4548: no refresh_token. The key is valid until revoked in Cortex, so a refresh grant could\n * only re-issue the same key; the old pb_rt_ token carried that key base64url-readable and was\n * never revoked, a second place the key leaked for no security gain. The MCP authorization spec\n * makes refresh tokens optional, so a client re-authorizes when the key is rejected.\n */\nexport function tokenResponse(apiKey: string): {\n access_token: string;\n token_type: \"Bearer\";\n expires_in: number;\n} {\n return {\n access_token: apiKey,\n token_type: \"Bearer\",\n // 1 year: validity is enforced by Convex on every call, not by this clock.\n expires_in: 365 * 24 * 3600,\n };\n}\n","/**\n * The hosted connector's two OAuth doors, as decisions (DEC-2588, TASK-1011). http.ts registers the routes and sends what these return;\n * the web app signs the person in, lets them pick a workspace and mints the code; Convex checks it. Nothing is kept here: a redeploy\n * mid-sign-in loses nothing.\n *\n * - GET /authorize (`authorizeOutcome`): the redirect is checked against the exact allowlist first, on every branch. Then:\n * error=access_denied (the page's Cancel) → back to the client with that error;\n * code=<connect token> (the page's Continue) → back to the client with the code;\n * otherwise the client's own request, which must carry an S256 challenge → the web app's connect page.\n * - POST /oauth/token (`exchangeOutcome`): forwards the code with the PKCE verifier and the redirect to the Convex redeem door, which\n * mints the key only when the S256 and the redirect match the code's row (and burns it on a miss). The key name and clientName come\n * from the presented redirect and client_id (connectClients.ts), never from the caller. The access token is the key (DEC-7).\n */\nimport { checkRedirectUri, type OAuthRedirectAllowlist } from \"./oauthRedirectAllowlist.js\";\nimport { connectClientName, connectClientOf, connectKeyName } from \"./connectClients.js\";\nimport { tokenResponse } from \"./oauthAuthCode.js\";\n\n/** What a door answers: a 302 to `location`, or a status with a JSON body. `reason` is its one stderr line (never a code or a key). */\nexport type DoorOutcome = { status: number; reason: string; location?: string; json?: unknown };\n\n/** The web app's page that signs the person in and mints the code. */\nexport const CONNECT_PAGE_PATH = \"/connect\";\n\n/** RFC 7636: the S256 challenge is the base64url SHA-256 of the verifier, exactly 43 characters. */\nconst S256_CHALLENGE = /^[A-Za-z0-9_-]{43}$/;\n/** The connect token the page mints (convex/lib/tokenConstants.ts CONNECT_TOKEN_PREFIX, 32 random bytes). */\nconst CONNECT_CODE = /^pb_ct_[A-Za-z0-9_-]{43}$/;\n\nconst text = (value: unknown): string | undefined => (typeof value === \"string\" ? value : undefined);\n\n/** One stderr line per door outcome (TASK-1005): the kill line reads these. Never a key, a code or a verifier. */\nexport function logOAuthDoor(door: string, status: number, reason: string, uris?: unknown[]): void {\n const list = uris === undefined ? \"\" : ` uris=${JSON.stringify(uris.map(String)).slice(0, 600)}`;\n process.stderr.write(`[oauth] door=${door} status=${status} reason=${JSON.stringify(reason)}${list}\\n`);\n}\n\n/** The client's redirect with these params added, and its state echoed (RFC 6749 4.1.2). */\nfunction backToClient(redirectUri: string, params: Record<string, string>, state: string | undefined): string {\n const url = new URL(redirectUri);\n for (const [key, value] of Object.entries(params)) url.searchParams.set(key, value);\n if (state !== undefined) url.searchParams.set(\"state\", state);\n return url.toString();\n}\n\nexport function authorizeOutcome(\n query: Record<string, unknown>,\n { allowlist, appUrl }: { allowlist: OAuthRedirectAllowlist; appUrl: string },\n): DoorOutcome {\n const redirectUri = text(query.redirect_uri);\n const refusal = checkRedirectUri(query.redirect_uri, allowlist); // first, on every branch: a bad redirect gets nothing\n if (refusal || redirectUri === undefined) {\n return { status: 400, reason: refusal ?? \"redirect_uri is required\", json: { error: \"invalid_request\", error_description: refusal } };\n }\n const state = text(query.state);\n if (query.error !== undefined) {\n if (query.error !== \"access_denied\") return { status: 400, reason: \"unknown_error_param\", json: { error: \"invalid_request\" } };\n return { status: 302, reason: \"access_denied\", location: backToClient(redirectUri, { error: \"access_denied\" }, state) };\n }\n if (query.code !== undefined) {\n const code = text(query.code);\n if (code === undefined || !CONNECT_CODE.test(code)) return { status: 400, reason: \"malformed_code\", json: { error: \"invalid_request\" } };\n return { status: 302, reason: \"code_returned\", location: backToClient(redirectUri, { code }, state) };\n }\n const challenge = text(query.code_challenge);\n if (query.code_challenge_method !== \"S256\" || challenge === undefined || !S256_CHALLENGE.test(challenge)) {\n const description = \"code_challenge (S256) is required\";\n return { status: 302, reason: \"pkce_required\", location: backToClient(redirectUri, { error: \"invalid_request\", error_description: description }, state) };\n }\n const page = new URL(`${appUrl}${CONNECT_PAGE_PATH}`);\n page.searchParams.set(\"client_id\", text(query.client_id) ?? \"\");\n page.searchParams.set(\"redirect_uri\", redirectUri);\n page.searchParams.set(\"code_challenge\", challenge);\n if (state !== undefined) page.searchParams.set(\"state\", state);\n return { status: 302, reason: \"to_connect_page\", location: page.toString() };\n}\n\ntype RedeemFetch = (url: string, init: { method: string; headers: Record<string, string>; body: string; signal: AbortSignal }) => Promise<{\n status: number;\n json: () => Promise<unknown>;\n}>;\n\n/** A refusal the client restarts from (RFC 6749 5.2). */\nconst invalidGrant = (reason: string): DoorOutcome => ({ status: 400, reason, json: { error: \"invalid_grant\" } });\n\nexport async function exchangeOutcome(\n body: Record<string, unknown>,\n { candidates, fetchImpl = fetch as unknown as RedeemFetch, timeoutMs = 5000 }: { candidates: string[]; fetchImpl?: RedeemFetch; timeoutMs?: number },\n): Promise<DoorOutcome> {\n if (body.grant_type !== \"authorization_code\") return { status: 400, reason: \"unsupported_grant_type\", json: { error: \"unsupported_grant_type\" } };\n const code = text(body.code), codeVerifier = text(body.code_verifier), redirectUri = text(body.redirect_uri);\n if (!code || !codeVerifier || !redirectUri) return { status: 400, reason: \"missing_param\", json: { error: \"invalid_request\" } };\n const client = connectClientOf(redirectUri, body.client_id);\n if (!client) return invalidGrant(\"unreadable_redirect\");\n const clientName = connectClientName(client);\n const payload = JSON.stringify({\n token: code, codeVerifier, redirectUri, name: connectKeyName(client), ...(clientName === undefined ? {} : { clientName }),\n });\n // DEC-789: the primary deployment, then each fallback. A deployment that does not hold the code answers 400 invalid_token; a code's hash\n // lives on one deployment at most, so the next is asked only then. Any other answer, or none, ends the exchange: the client restarts.\n for (const base of candidates) {\n let status: number;\n let json: unknown;\n try {\n const res = await fetchImpl(`${base}/auth/redeem-connect-token`, {\n method: \"POST\", headers: { \"content-type\": \"application/json\" }, body: payload, signal: AbortSignal.timeout(timeoutMs),\n });\n status = res.status;\n json = await res.json().catch(() => null);\n } catch {\n return invalidGrant(\"redeem_unreachable\");\n }\n const apiKey = (json as { apiKey?: unknown } | null)?.apiKey;\n if (status === 200 && typeof apiKey === \"string\") return { status: 200, reason: \"token_issued\", json: tokenResponse(apiKey) };\n const refusal = (json as { error?: { code?: unknown } } | null)?.error?.code;\n if (!(status === 400 && refusal === \"invalid_token\")) return invalidGrant(`redeem_refused_${status}`);\n }\n return invalidGrant(\"code_refused\");\n}\n\n/** Sends a door's outcome and writes its line. */\nexport function sendDoor(res: any, door: string, outcome: DoorOutcome): void {\n logOAuthDoor(door, outcome.status, outcome.reason);\n if (outcome.location !== undefined) res.redirect(302, outcome.location);\n else res.status(outcome.status).json(outcome.json);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAyBA,SAAS,kBAAkB;AAC3B,OAAO,aAAa;AACpB,SAAS,wBAAwB;AACjC,SAA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S","text","appUrl","rateLimit"]}
|
package/dist/index.js
CHANGED
|
@@ -1,25 +1,19 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import {
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
initFeatureFlags
|
|
6
|
-
} from "./chunk-OJTGZZ3C.js";
|
|
3
|
+
createProductBrainServer
|
|
4
|
+
} from "./chunk-KYZUAHTL.js";
|
|
7
5
|
import {
|
|
8
6
|
bootstrap,
|
|
9
7
|
getAgentSessionId,
|
|
10
|
-
getPostHogClient,
|
|
11
8
|
getWorkspaceId,
|
|
12
|
-
initAnalytics,
|
|
13
9
|
orphanAgentSession,
|
|
14
|
-
recoverSessionState
|
|
15
|
-
|
|
16
|
-
trackSessionStarted
|
|
17
|
-
} from "./chunk-AMJILQKI.js";
|
|
10
|
+
recoverSessionState
|
|
11
|
+
} from "./chunk-EZJ2DV6F.js";
|
|
18
12
|
|
|
19
13
|
// src/index.ts
|
|
20
14
|
import { readFileSync } from "fs";
|
|
21
15
|
import { resolve } from "path";
|
|
22
|
-
import {
|
|
16
|
+
import { serveStdio } from "@modelcontextprotocol/server/stdio";
|
|
23
17
|
try {
|
|
24
18
|
const envPath = resolve(process.cwd(), ".env.mcp");
|
|
25
19
|
for (const line of readFileSync(envPath, "utf-8").split("\n")) {
|
|
@@ -45,10 +39,6 @@ async function gracefulShutdown() {
|
|
|
45
39
|
if (getAgentSessionId()) await withTimeout(orphanAgentSession(), 1500);
|
|
46
40
|
} catch {
|
|
47
41
|
}
|
|
48
|
-
try {
|
|
49
|
-
await withTimeout(shutdownAnalytics(), 1e3);
|
|
50
|
-
} catch {
|
|
51
|
-
}
|
|
52
42
|
clearTimeout(hardExit);
|
|
53
43
|
process.exit(0);
|
|
54
44
|
}
|
|
@@ -62,26 +52,19 @@ process.on("unhandledRejection", (reason) => {
|
|
|
62
52
|
process.on("uncaughtException", (err) => {
|
|
63
53
|
process.stderr.write(`[MCP] Uncaught exception: ${err.stack ?? err.message}
|
|
64
54
|
`);
|
|
65
|
-
getPostHogClient()?.capture({ distinctId: "mcp-server", event: "mcp_process_crashed", properties: { message: err.message, stack: err.stack } });
|
|
66
55
|
gracefulShutdown();
|
|
67
56
|
});
|
|
68
57
|
bootstrap();
|
|
69
|
-
initAnalytics();
|
|
70
|
-
initFeatureFlags(getPostHogClient());
|
|
71
|
-
var server = createProductBrainServer();
|
|
72
|
-
var transport = new StdioServerTransport();
|
|
73
|
-
transport.onerror = (error) => {
|
|
74
|
-
process.stderr.write(`[MCP] Transport error: ${error.message}
|
|
75
|
-
`);
|
|
76
|
-
};
|
|
77
58
|
process.stderr.write("[MCP] Starting server.\n");
|
|
78
|
-
|
|
59
|
+
serveStdio(createProductBrainServer, {
|
|
60
|
+
onerror: (error) => process.stderr.write(`[MCP] Transport error: ${error.message}
|
|
61
|
+
`)
|
|
62
|
+
});
|
|
79
63
|
process.stderr.write("[MCP] Server connected.\n");
|
|
80
64
|
process.stdin.on("end", () => {
|
|
81
65
|
gracefulShutdown();
|
|
82
66
|
});
|
|
83
|
-
getWorkspaceId().then(async (
|
|
84
|
-
trackSessionStarted(wsId, SERVER_VERSION);
|
|
67
|
+
getWorkspaceId().then(async () => {
|
|
85
68
|
try {
|
|
86
69
|
await recoverSessionState();
|
|
87
70
|
} catch {
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["import { readFileSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport {
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["import { readFileSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport { serveStdio } from \"@modelcontextprotocol/server/stdio\";\n\nimport {\n getWorkspaceId,\n bootstrap,\n orphanAgentSession,\n getAgentSessionId,\n recoverSessionState,\n} from \"./client.js\";\nimport { createProductBrainServer } from \"./server.js\";\n\ntry {\n const envPath = resolve(process.cwd(), \".env.mcp\");\n for (const line of readFileSync(envPath, \"utf-8\").split(\"\\n\")) {\n const trimmed = line.trim();\n if (!trimmed || trimmed.startsWith(\"#\")) continue;\n const eqIdx = trimmed.indexOf(\"=\");\n if (eqIdx === -1) continue;\n process.env[trimmed.slice(0, eqIdx)] ??= trimmed.slice(eqIdx + 1);\n }\n} catch {\n // .env.mcp not found — rely on env vars being set by the launcher\n}\n\nconst withTimeout = <T>(p: Promise<T>, ms: number): Promise<T | void> =>\n Promise.race([p, new Promise<void>((r) => setTimeout(r, ms))]);\n\nlet shuttingDown = false;\nasync function gracefulShutdown() {\n if (shuttingDown) return;\n shuttingDown = true;\n process.stderr.write(\"[MCP] Graceful shutdown initiated.\\n\");\n // Hard-exit guard — fires if async cleanup exceeds budget.\n // Still exits 0: SIGTERM/stdin-close is an intentional shutdown regardless.\n const hardExit = setTimeout(() => {\n process.stderr.write(\"[MCP] Hard exit after shutdown timeout.\\n\");\n process.exit(0);\n }, 3_000);\n try {\n if (getAgentSessionId()) await withTimeout(orphanAgentSession(), 1_500);\n } catch {\n /* best-effort */\n }\n clearTimeout(hardExit);\n process.exit(0);\n}\n\n// Register signal handlers BEFORE serveStdio so they are always active\nprocess.on(\"SIGINT\", gracefulShutdown);\nprocess.on(\"SIGTERM\", gracefulShutdown);\nprocess.on(\"unhandledRejection\", (reason) => {\n const msg = reason instanceof Error ? reason.message : String(reason);\n process.stderr.write(`[MCP] Unhandled rejection: ${msg}\\n`);\n});\nprocess.on(\"uncaughtException\", (err) => {\n process.stderr.write(`[MCP] Uncaught exception: ${err.stack ?? err.message}\\n`);\n gracefulShutdown();\n});\n\nbootstrap();\n\n// TASK-1640 (WP-862; QUE-689): the opening exchange picks the era (2025's initialize or 2026-07-28's\n// server/discover) and one server from the factory serves the connection.\nprocess.stderr.write(\"[MCP] Starting server.\\n\");\nserveStdio(createProductBrainServer, {\n onerror: (error) => process.stderr.write(`[MCP] Transport error: ${error.message}\\n`),\n});\nprocess.stderr.write(\"[MCP] Server connected.\\n\");\n\nprocess.stdin.on(\"end\", () => {\n gracefulShutdown();\n});\n\n// Do not auto-start agent sessions here: a second concurrent startAgentSession (e.g. from\n// `session action=start` right after connect) can supersede the first session while client\n// state still holds the stale id — markOriented then fails with SESSION_CLOSED.\n// Call `session action=start` or `start` explicitly (STD-135).\ngetWorkspaceId()\n .then(async () => {\n try {\n await recoverSessionState();\n } catch {\n /* best-effort — fresh stdio has nothing to recover */\n }\n })\n .catch(() => {\n process.stderr.write(\"[MCP] Workspace resolution deferred — will retry on first tool call.\\n\");\n });\n"],"mappings":";;;;;;;;;;;;AAAA,SAAS,oBAAoB;AAC7B,SAAS,eAAe;AACxB,SAAS,kBAAkB;AAW3B,IAAI;AACF,QAAM,UAAU,QAAQ,QAAQ,IAAI,GAAG,UAAU;AACjD,aAAW,QAAQ,aAAa,SAAS,OAAO,EAAE,MAAM,IAAI,GAAG;AAC7D,UAAM,UAAU,KAAK,KAAK;AAC1B,QAAI,CAAC,WAAW,QAAQ,WAAW,GAAG,EAAG;AACzC,UAAM,QAAQ,QAAQ,QAAQ,GAAG;AACjC,QAAI,UAAU,GAAI;AAClB,YAAQ,IAAI,QAAQ,MAAM,GAAG,KAAK,CAAC,MAAM,QAAQ,MAAM,QAAQ,CAAC;AAAA,EAClE;AACF,QAAQ;AAER;AAEA,IAAM,cAAc,CAAI,GAAe,OACrC,QAAQ,KAAK,CAAC,GAAG,IAAI,QAAc,CAAC,MAAM,WAAW,GAAG,EAAE,CAAC,CAAC,CAAC;AAE/D,IAAI,eAAe;AACnB,eAAe,mBAAmB;AAChC,MAAI,aAAc;AAClB,iBAAe;AACf,UAAQ,OAAO,MAAM,sCAAsC;AAG3D,QAAM,WAAW,WAAW,MAAM;AAChC,YAAQ,OAAO,MAAM,2CAA2C;AAChE,YAAQ,KAAK,CAAC;AAAA,EAChB,GAAG,GAAK;AACR,MAAI;AACF,QAAI,kBAAkB,EAAG,OAAM,YAAY,mBAAmB,GAAG,IAAK;AAAA,EACxE,QAAQ;AAAA,EAER;AACA,eAAa,Q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