@productbrain/mcp 0.0.1-beta.160 → 0.0.1-beta.16017

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/dist/http.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/http.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 } from \"./client.js\";\nimport { runWithAuth, hashKey } from \"./auth.js\";\nimport { createProductBrainServer, SERVER_VERSION } from \"./server.js\";\nimport { initAnalytics, shutdownAnalytics, getPostHogClient } from \"./analytics.js\";\nimport { initFeatureFlags } from \"./featureFlags.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 — fail-closed; requires CORS_ORIGINS to be explicitly configured.\nconst ALLOWED_ORIGINS = process.env.CORS_ORIGINS\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 (ALLOWED_ORIGINS && 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 res.setHeader(\"Access-Control-Expose-Headers\", \"Mcp-Session-Id\");\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 token store — declared here so the cleanup interval can reference it.\nconst ACCESS_TOKEN_TTL = 3600; // 1 hour\nconst ACCESS_TOKEN_TTL_MS = ACCESS_TOKEN_TTL * 1000;\nconst REFRESH_TOKEN_TTL_MS = 90 * 24 * 60 * 60_000; // 90 days\n\ninterface RefreshEntry {\n apiKey: string;\n createdAt: number;\n}\n\nconst refreshTokens = new Map<string, RefreshEntry>();\nconst MAX_REFRESH_TOKENS = 2000;\n// Per-key cap mirrors MAX_SESSIONS_PER_KEY (see ~line 524): prevents any single\n// API key from monopolising the global refresh-token budget. PR #34 review Finding 3.\nconst MAX_REFRESH_TOKENS_PER_KEY = 20;\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 for (const [token, entry] of refreshTokens) {\n if (now - entry.createdAt > REFRESH_TOKEN_TTL_MS) refreshTokens.delete(token);\n }\n if (refreshTokens.size > MAX_REFRESH_TOKENS) {\n const sorted = [...refreshTokens.entries()].sort((a, b) => a[1].createdAt - b[1].createdAt);\n for (let i = 0; i < sorted.length - MAX_REFRESH_TOKENS; i++) {\n refreshTokens.delete(sorted[i][0]);\n }\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 ({ \"&\": \"&amp;\", '\"': \"&quot;\", \"<\": \"&lt;\", \">\": \"&gt;\" })[c]!,\n );\n}\n\napp.get(\"/authorize\", authLimiter, (req: any, res: any) => {\n const { redirect_uri, code_challenge, code_challenge_method, state, client_id } =\n req.query;\n res.type(\"html\").send(`<!DOCTYPE html>\n<html lang=\"en\"><head>\n<meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\n<title>Authorize — Product Brain</title>\n<style>\n*{margin:0;padding:0;box-sizing:border-box}\nbody{font-family:-apple-system,system-ui,sans-serif;background:#0a0a0a;color:#e5e5e5;\n display:flex;align-items:center;justify-content:center;min-height:100vh;padding:1rem}\n.card{background:#1a1a1a;border:1px solid #333;border-radius:12px;padding:2rem;max-width:400px;width:100%}\nh1{font-size:1.2rem;margin-bottom:.25rem}\n.sub{color:#999;font-size:.85rem;margin-bottom:1.5rem}\nlabel{display:block;font-size:.85rem;margin-bottom:.4rem;color:#ccc}\ninput[type=password]{width:100%;padding:.6rem .75rem;background:#111;border:1px solid #444;\n border-radius:8px;color:#e5e5e5;font:.85rem/1.4 monospace}\ninput:focus{outline:none;border-color:#7c3aed}\nbutton{width:100%;padding:.6rem;background:#7c3aed;color:#fff;border:none;\n border-radius:8px;font-size:.85rem;cursor:pointer;margin-top:1rem}\nbutton:hover{background:#6d28d9}\n.err{color:#ef4444;font-size:.8rem;margin-top:.5rem;display:none}\n</style></head><body>\n<div class=\"card\">\n<h1>Product Brain</h1>\n<p class=\"sub\">Enter your API key to connect Claude to your workspace.</p>\n<form method=\"POST\" action=\"/authorize\">\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 <label for=\"k\">API Key</label>\n <input type=\"password\" id=\"k\" name=\"api_key\" placeholder=\"pb_sk_…\" required autofocus>\n <p class=\"err\" id=\"e\">Key must start with pb_sk_</p>\n <button type=\"submit\">Authorize</button>\n</form>\n</div>\n<script>document.querySelector(\"form\").onsubmit=function(e){\nif(!document.getElementById(\"k\").value.startsWith(\"pb_sk_\")){\ne.preventDefault();document.getElementById(\"e\").style.display=\"block\"}}</script>\n</body></html>`);\n});\n\napp.post(\n \"/authorize\",\n authLimiter,\n express.urlencoded({ extended: false }),\n (req: any, res: any) => {\n const { api_key, redirect_uri, code_challenge, state, client_id } = req.body;\n\n if (!api_key?.startsWith(\"pb_sk_\")) {\n res.status(400).send(\"Invalid API key\");\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 if (!client_id || !registeredClients.has(client_id)) {\n res.status(400).json({\n error: \"invalid_request\",\n error_description: \"Unknown or missing client_id\",\n });\n return;\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 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 res.redirect(302, url.toString());\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 // Fix 1 — Generate an opaque pb_at_* access token so the raw pb_sk_* key\n // is never returned through the OAuth flow.\n const opaqueToken = `pb_at_${randomUUID()}`;\n const now = Date.now();\n\n // LRU eviction: if at cap, remove the oldest entry before inserting.\n if (accessTokens.size >= MAX_ACCESS_TOKENS) {\n let oldestKey = \"\";\n let oldestTime = Infinity;\n for (const [k, v] of accessTokens) {\n if (v.createdAt < oldestTime) {\n oldestTime = v.createdAt;\n oldestKey = k;\n }\n }\n if (oldestKey) accessTokens.delete(oldestKey);\n }\n\n accessTokens.set(opaqueToken, { apiKey, createdAt: now });\n\n const refreshToken = `pb_rt_${randomUUID()}`;\n\n // Per-key cap (Finding 3, PR #34): before the global backstop kicks in, ensure\n // no single apiKey holds more than MAX_REFRESH_TOKENS_PER_KEY entries. Mirrors\n // MAX_SESSIONS_PER_KEY. Prevents one abusive/leaked key from evicting every\n // other tenant's refresh tokens via the global FIFO backstop below.\n let perKeyCount = 0;\n let oldestKeyForApiKey: string | null = null;\n let oldestAtForApiKey = Infinity;\n for (const [k, v] of refreshTokens) {\n if (v.apiKey === apiKey) {\n perKeyCount++;\n if (v.createdAt < oldestAtForApiKey) {\n oldestAtForApiKey = v.createdAt;\n oldestKeyForApiKey = k;\n }\n }\n }\n if (perKeyCount >= MAX_REFRESH_TOKENS_PER_KEY && oldestKeyForApiKey) {\n refreshTokens.delete(oldestKeyForApiKey);\n }\n\n // Global backstop — unchanged behaviour.\n if (refreshTokens.size >= MAX_REFRESH_TOKENS) {\n let oldestKey: string | null = null;\n let oldestAt = Infinity;\n for (const [k, v] of refreshTokens) {\n if (v.createdAt < oldestAt) {\n oldestAt = v.createdAt;\n oldestKey = k;\n }\n }\n if (oldestKey) refreshTokens.delete(oldestKey);\n }\n refreshTokens.set(refreshToken, { apiKey, createdAt: now });\n return {\n access_token: opaqueToken,\n token_type: \"Bearer\",\n expires_in: ACCESS_TOKEN_TTL,\n refresh_token: refreshToken,\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 entry = refreshTokens.get(refresh_token);\n if (!entry) {\n res.status(400).json({ error: \"invalid_grant\", error_description: \"Invalid refresh token\" });\n return;\n }\n if (Date.now() - entry.createdAt > REFRESH_TOKEN_TTL_MS) {\n refreshTokens.delete(refresh_token);\n res.status(400).json({ error: \"invalid_grant\", error_description: \"Refresh token expired\" });\n return;\n }\n // Rotate: revoke old, issue new pair\n const apiKey = entry.apiKey;\n refreshTokens.delete(refresh_token);\n res.json(issueTokens(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 message: { error: \"Too many requests. Try again later.\" },\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}\n\nconst sessions = new Map<string, SessionEntry>();\nconst SESSION_TTL_MS = 30 * 60 * 1000;\nconst MAX_SESSIONS = 200;\n// Fix 6 — prevent a single API key from monopolising all session slots.\nconst MAX_SESSIONS_PER_KEY = 5;\n\nfunction evictStaleSessions(): void {\n const now = Date.now();\n for (const [id, entry] of sessions) {\n if (now - entry.lastAccess > SESSION_TTL_MS) {\n logSessionLifecycle(\"session_deleted\", id, \"ttl\");\n entry.transport.close().catch(() => {});\n sessions.delete(id);\n }\n }\n if (sessions.size > MAX_SESSIONS) {\n const sorted = [...sessions.entries()].sort(\n (a, b) => a[1].lastAccess - b[1].lastAccess,\n );\n for (let i = 0; i < sorted.length - MAX_SESSIONS; i++) {\n logSessionLifecycle(\"session_deleted\", sorted[i][0], \"eviction\");\n sorted[i][1].transport.close().catch(() => {});\n sessions.delete(sorted[i][0]);\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\",\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 res.status(429).json({ error: \"Too many failed auth attempts. Try again later.\" });\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 entry.lastAccess = Date.now();\n await entry.transport.handleRequest(req, res, req.body);\n logRequest(\"POST\", \"ok\", sessionId, Date.now() - reqStart);\n } else if (!sessionId && isInitializeRequest(req.body)) {\n // Fix 6 — Enforce per-key session cap before creating a new session.\n const keyH = hashKey(apiKey);\n let keySessionCount = 0;\n for (const entry of sessions.values()) {\n if (entry.keyHash === keyH) keySessionCount++;\n }\n if (keySessionCount >= MAX_SESSIONS_PER_KEY) {\n res.status(429).json({\n jsonrpc: \"2.0\",\n error: { code: -32000, message: \"Too many sessions for this API key\" },\n id: null,\n });\n return;\n }\n\n const transport = new StreamableHTTPServerTransport({\n sessionIdGenerator: () => randomUUID(),\n onsessioninitialized: (sid: string) => {\n // Fix 3 — Store a key hash with the session entry.\n sessions.set(sid, { transport, lastAccess: Date.now(), keyHash: keyH });\n logSessionLifecycle(\"session_created\", sid);\n },\n });\n\n transport.onclose = () => {\n const sid = transport.sessionId;\n if (sid) {\n logSessionLifecycle(\"session_deleted\", sid, \"onclose\");\n sessions.delete(sid);\n }\n };\n\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 } else {\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 res.status(429).json({ error: \"Too many failed auth attempts. Try again later.\" });\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 || !sessions.has(sessionId)) {\n res.status(400).send(\"Invalid or missing session ID\");\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 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 res.status(429).json({ error: \"Too many failed auth attempts. Try again later.\" });\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 || !sessions.has(sessionId)) {\n res.status(400).send(\"Invalid or missing session ID\");\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"],"mappings":";;;;;;;;;;;;;;;AAoBA,SAAS,YAAY,kBAAkB;AACvC,OAAO,aAAa;AACpB,SAAS,qCAAqC;AAC9C,SAAS,2BAA2B;AACpC,OAAO,eAAe;AAUtB,cAAc;AACd,cAAc;AACd,iBAAiB,iBAAiB,CAAC;AAEnC,IAAM,OAAO,SAAS,QAAQ,IAAI,QAAQ,QAAQ,IAAI,YAAY,QAAQ,EAAE;AAE5E,SAAS,QAAQ,KAAkB;AACjC,QAAM,QAAQ,IAAI,QAAQ,mBAAmB,KAAK,IAAI,YAAY;AAClE,QAAM,OAAO,IAAI,QAAQ,QAAQ,aAAa,IAAI;AAClD,SAAO,GAAG,KAAK,MAAM,IAAI;AAC3B;AAIA,IAAM,MAAM,QAAQ;AAGpB,IAAI,IAAI,eAAe,CAAC;AACxB,IAAI,IAAI,QAAQ,KAAK,CAAC;AAGtB,IAAM,kBAAkB,QAAQ,IAAI,cAChC,MAAM,GAAG,EACV,IAAI,CAAC,MAAM,EAAE,KAAK,CAAC,EACnB,OAAO,OAAO;AAEjB,IAAI,IAAI,CAAC,MAAW,KAAU,SAAc;AAC1C,QAAM,S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M,SAAS;AAAA,IACtC,CAAC;AAAA,EACH,QAAQ;AACN,eAAW,UAAU,SAAS,SAAS;AAAA,EACzC;AACF,CAAC;AAID,QAAQ,GAAG,sBAAsB,CAAC,WAAW;AAC3C,QAAM,MAAM,kBAAkB,QAAQ,OAAO,UAAU,OAAO,MAAM;AACpE,UAAQ,MAAM,mCAAmC,GAAG,EAAE;AACxD,CAAC;AAED,QAAQ,GAAG,qBAAqB,CAAC,QAAQ;AACvC,UAAQ,MAAM,kCAAkC,IAAI,SAAS,IAAI,OAAO,EAAE;AAC1E,mBAAiB;AACnB,CAAC;AAED,IAAI,eAAe;AACnB,eAAe,mBAAmB;AAChC,MAAI,aAAc;AAClB,iBAAe;AACf,aAAW,MAAM,QAAQ,KAAK,CAAC,GAAG,GAAK,EAAE,MAAM;AAC/C,UAAQ,IAAI,kBAAkB;AAC9B,aAAW,CAAC,EAAE,KAAK,KAAK,UAAU;AAChC,UAAM,MAAM,UAAU,MAAM,EAAE,MAAM,MAAM;AAAA,IAAC,CAAC;AAAA,EAC9C;AACA,MAAI;AACF,UAAM,kBAAkB;AAAA,EAC1B,QAAQ;AAAA,EAER;AACA,UAAQ,KAAK,CAAC;AAChB;AAIA,IAAM,cAAc;AACpB,IAAM,aAAa,IAAI,OAAO,MAAM,aAAa,MAAM;AACrD,UAAQ;AAAA,IACN,kCAAkC,cAAc,iBAAiB,WAAW,IAAI,IAAI;AAAA,EACtF;AACF,CAAC;AACD,WAAW,GAAG,SAAS,CAAC,QAAQ;AAC9B,UAAQ,MAAM,4BAA4B,IAAI,OAAO,EAAE;AACvD,UAAQ,KAAK,CAAC;AAChB,CAAC;AAED,QAAQ,GAAG,UAAU,gBAAgB;AACrC,QAAQ,GAAG,WAAW,gBAAgB;","names":[]}
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,SAAS,qBAAqB;AAC9B,OAAOA,gBAAe;;;ACKtB,SAAS,aAAa,GAAmB;AACvC,SAAO,KAAK,IAAI,GAAG,KAAK,MAAM,CAAC,CAAC;AAClC;AAeA,SAAS,MACP,QACA,SACA,GACU;AACV,QAAM,UAAU,aAAa,EAAE,iBAAiB;AAChD,SAAO;AAAA,IACL,QAAQ;AAAA,IACR,SAAS,EAAE,eAAe,OAAO,OAAO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AM,OAAM,MAAM,KAAK,KAAK,KAAK,QAAQ,MAAM,UAAU,KAAK,GAAG,CAAC;AACxE,CAAC;AAID,QAAQ,GAAG,sBAAsB,CAAC,WAAW;AAC3C,QAAM,MAAM,kBAAkB,QAAQ,OAAO,UAAU,OAAO,MAAM;AACpE,UAAQ,MAAM,mCAAmC,GAAG,EAAE;AACxD,CAAC;AAED,QAAQ,GAAG,qBAAqB,CAAC,QAAQ;AACvC,UAAQ,MAAM,kCAAkC,IAAI,SAAS,IAAI,OAAO,EAAE;AAC1E,mBAAiB;AACnB,CAAC;AAED,IAAI,eAAe;AACnB,eAAe,mBAAmB;AAChC,MAAI,aAAc;AAClB,iBAAe;AACf,aAAW,MAAM,QAAQ,KAAK,CAAC,GAAG,GAAK,EAAE,MAAM;AAC/C,UAAQ,IAAI,kBAAkB;AAC9B,QAAM,WAAW,MAAM,EAAE,MAAM,MAAM;AAAA,EAAC,CAAC;AACvC,UAAQ,KAAK,CAAC;AAChB;AAIA,IAAM,cAAc;AACpB,IAAM,aAAa,IAAI,OAAO,MAAM,aAAa,MAAM;AACrD,UAAQ;AAAA,IACN,kCAAkC,cAAc,iBAAiB,WAAW,IAAI,IAAI;AAAA,EACtF;AACF,CAAC;AACD,WAAW,GAAG,SAAS,CAAC,QAAe;AACrC,UAAQ,MAAM,4BAA4B,IAAI,OAAO,EAAE;AACvD,UAAQ,KAAK,CAAC;AAChB,CAAC;AAED,QAAQ,GAAG,UAAU,gBAAgB;AACrC,QAAQ,GAAG,WAAW,gBAAgB;","names":["rateLimit","LOOPBACK_HOSTS","text","appUrl","rateLimit"]}
package/dist/index.js CHANGED
@@ -1,26 +1,19 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
- SERVER_VERSION,
3
+ createProductBrainServer
4
+ } from "./chunk-ERVVKGIY.js";
5
+ import {
4
6
  bootstrap,
5
- createProductBrainServer,
6
7
  getAgentSessionId,
7
8
  getWorkspaceId,
8
- initFeatureFlags,
9
9
  orphanAgentSession,
10
- recoverSessionState,
11
- startAgentSession
12
- } from "./chunk-LKUFRQUO.js";
13
- import {
14
- getPostHogClient,
15
- initAnalytics,
16
- shutdownAnalytics,
17
- trackSessionStarted
18
- } from "./chunk-YMF3IQ5E.js";
10
+ recoverSessionState
11
+ } from "./chunk-TLR7A2WH.js";
19
12
 
20
13
  // src/index.ts
21
14
  import { readFileSync } from "fs";
22
15
  import { resolve } from "path";
23
- import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
16
+ import { serveStdio } from "@modelcontextprotocol/server/stdio";
24
17
  try {
25
18
  const envPath = resolve(process.cwd(), ".env.mcp");
26
19
  for (const line of readFileSync(envPath, "utf-8").split("\n")) {
@@ -46,10 +39,6 @@ async function gracefulShutdown() {
46
39
  if (getAgentSessionId()) await withTimeout(orphanAgentSession(), 1500);
47
40
  } catch {
48
41
  }
49
- try {
50
- await withTimeout(shutdownAnalytics(), 1e3);
51
- } catch {
52
- }
53
42
  clearTimeout(hardExit);
54
43
  process.exit(0);
55
44
  }
@@ -66,29 +55,19 @@ process.on("uncaughtException", (err) => {
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
- await server.connect(transport);
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 (wsId) => {
84
- trackSessionStarted(wsId, SERVER_VERSION);
67
+ getWorkspaceId().then(async () => {
85
68
  try {
86
- await startAgentSession();
87
- process.stderr.write("[MCP] Agent session started automatically.\n");
88
- } catch (err) {
89
- process.stderr.write(`[MCP] Auto session start failed: ${err.message}. Call session action=start manually.
90
- `);
91
69
  await recoverSessionState();
70
+ } catch {
92
71
  }
93
72
  }).catch(() => {
94
73
  process.stderr.write("[MCP] Workspace resolution deferred \u2014 will retry on first tool call.\n");
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 { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\n\nimport {\n getWorkspaceId,\n bootstrap,\n orphanAgentSession,\n startAgentSession,\n getAgentSessionId,\n recoverSessionState,\n} from \"./client.js\";\nimport { initAnalytics, trackSessionStarted, shutdownAnalytics, getPostHogClient } from \"./analytics.js\";\nimport { initFeatureFlags } from \"./featureFlags.js\";\nimport { createProductBrainServer, SERVER_VERSION } 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 try {\n await withTimeout(shutdownAnalytics(), 1_000);\n } catch {\n /* best-effort */\n }\n clearTimeout(hardExit);\n process.exit(0);\n}\n\n// Register signal handlers BEFORE server.connect 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();\ninitAnalytics();\ninitFeatureFlags(getPostHogClient());\n\nconst server = createProductBrainServer();\nconst transport = new StdioServerTransport();\ntransport.onerror = (error) => {\n process.stderr.write(`[MCP] Transport error: ${error.message}\\n`);\n};\nprocess.stderr.write(\"[MCP] Starting server.\\n\");\nawait server.connect(transport);\nprocess.stderr.write(\"[MCP] Server connected.\\n\");\n\nprocess.stdin.on(\"end\", () => {\n gracefulShutdown();\n});\n\ngetWorkspaceId()\n .then(async (wsId) => {\n trackSessionStarted(wsId, SERVER_VERSION);\n try {\n await startAgentSession();\n process.stderr.write(\"[MCP] Agent session started automatically.\\n\");\n } catch (err: any) {\n process.stderr.write(`[MCP] Auto session start failed: ${err.message}. Call session action=start manually.\\n`);\n await recoverSessionState();\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,4BAA4B;AAcrC,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,WAA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,IAAI,qBAAqB;AAC3C,UAAU,UAAU,CAAC,UAAU;AAC7B,UAAQ,OAAO,MAAM,0BAA0B,MAAM,OAAO;AAAA,CAAI;AAClE;AACA,QAAQ,OAAO,MAAM,0BAA0B;AAC/C,MAAM,OAAO,QAAQ,SAAS;AAC9B,QAAQ,OAAO,MAAM,2BAA2B;AAEhD,QAAQ,MAAM,GAAG,OAAO,MAAM;AAC5B,mBAAiB;AACnB,CAAC;AAED,eAAe,EACZ,KAAK,OAAO,SAAS;AACpB,sBAAoB,MAAM,cAAc;AACxC,MAAI;AACF,UAAM,kBAAkB;AACxB,YAAQ,OAAO,MAAM,8CAA8C;AAAA,EACrE,SAAS,KAAU;AACjB,YAAQ,OAAO,MAAM,oCAAoC,IAAI,OAAO;AAAA,CAAyC;AAC7G,UAAM,oBAAoB;AAAA,EAC5B;AACF,CAAC,EACA,MAAM,MAAM;AACX,UAAQ,OAAO,MAAM,6EAAwE;AAC/F,CAAC;","names":[]}
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":";;;;;;;;;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A6B,IAAI,SAAS,IAAI,OAAO;AAAA,CAAI;AAC9E,mBAAiB;AACnB,CAAC;AAED,UAAU;AAIV,QAAQ,OAAO,MAAM,0BAA0B;AAC/C,WAAW,0BAA0B;AAAA,EACnC,SAAS,CAAC,UAAU,QAAQ,OAAO,MAAM,0BAA0B,MAAM,OAAO;AAAA,CAAI;AACtF,CAAC;AACD,QAAQ,OAAO,MAAM,2BAA2B;AAEhD,QAAQ,MAAM,GAAG,OAAO,MAAM;AAC5B,mBAAiB;AACnB,CAAC;AAMD,eAAe,EACZ,KAAK,YAAY;AAChB,MAAI;AACF,UAAM,oBAAoB;AAAA,EAC5B,QAAQ;AAAA,EAER;AACF,CAAC,EACA,MAAM,MAAM;AACX,UAAQ,OAAO,MAAM,6EAAwE;AAC/F,CAAC;","names":[]}
@@ -0,0 +1,205 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ AGENT_KEY_PREFIX,
4
+ API_KEYS_PAGE,
5
+ API_KEY_FORMAT_LINE,
6
+ API_KEY_PREFIX,
7
+ DEFAULT_CLOUD_URL,
8
+ MCP_NPX_PACKAGE,
9
+ PASTE_NOW,
10
+ apiKeysUrl,
11
+ isApiKeyShaped,
12
+ resolveClient,
13
+ warnOnProdFallthrough,
14
+ writeClientConfig
15
+ } from "./chunk-TLR7A2WH.js";
16
+
17
+ // src/cli/setup.ts
18
+ import { execSync } from "child_process";
19
+ import { createInterface } from "readline";
20
+ function bold(s) {
21
+ return `\x1B[1m${s}\x1B[0m`;
22
+ }
23
+ function green(s) {
24
+ return `\x1B[32m${s}\x1B[0m`;
25
+ }
26
+ function dim(s) {
27
+ return `\x1B[2m${s}\x1B[0m`;
28
+ }
29
+ function orange(s) {
30
+ return `\x1B[33m${s}\x1B[0m`;
31
+ }
32
+ function log(msg) {
33
+ process.stdout.write(`${msg}
34
+ `);
35
+ }
36
+ function openBrowser(url) {
37
+ const platform = process.platform;
38
+ try {
39
+ if (platform === "darwin") execSync(`open "${url}"`);
40
+ else if (platform === "win32") execSync(`start "" "${url}"`);
41
+ else execSync(`xdg-open "${url}"`);
42
+ } catch {
43
+ log(dim(` Could not open browser automatically.`));
44
+ log(` Open this URL manually: ${url}`);
45
+ }
46
+ }
47
+ function prompt(question) {
48
+ return new Promise((resolve) => {
49
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
50
+ rl.question(question, (answer) => {
51
+ rl.close();
52
+ resolve(answer.trim());
53
+ });
54
+ });
55
+ }
56
+ function promptChoice(question, choices) {
57
+ return new Promise((resolve) => {
58
+ log("");
59
+ log(bold(question));
60
+ choices.forEach((c, i) => log(` ${i + 1}) ${c}`));
61
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
62
+ rl.question(`
63
+ ${dim("Choice [1]:")} `, (line) => {
64
+ rl.close();
65
+ const n = parseInt(line.trim(), 10);
66
+ if (isNaN(n) || n < 1 || n > choices.length) {
67
+ resolve(0);
68
+ } else {
69
+ resolve(n - 1);
70
+ }
71
+ });
72
+ });
73
+ }
74
+ function resolveSetupSiteUrl() {
75
+ const explicit = process.env.CONVEX_SITE_URL ?? process.env.PRODUCTBRAIN_URL;
76
+ const url = explicit ?? DEFAULT_CLOUD_URL;
77
+ warnOnProdFallthrough(url, { explicit: explicit != null });
78
+ return url;
79
+ }
80
+ async function verifyWorkspace(apiKey) {
81
+ const siteUrl = resolveSetupSiteUrl();
82
+ try {
83
+ const res = await fetch(`${siteUrl.replace(/\/$/, "")}/api/aki`, {
84
+ method: "POST",
85
+ headers: {
86
+ "Content-Type": "application/json",
87
+ Authorization: `Bearer ${apiKey}`
88
+ },
89
+ body: JSON.stringify({ fn: "resolveWorkspace", args: {} })
90
+ });
91
+ if (!res.ok) return null;
92
+ const json = await res.json();
93
+ return json.data ?? null;
94
+ } catch {
95
+ return null;
96
+ }
97
+ }
98
+ async function runSetup() {
99
+ log("");
100
+ log(bold(` Product${orange("Brain")} Setup`));
101
+ log(dim(" Connect your AI assistant to your chain\n"));
102
+ const keysUrl = apiKeysUrl();
103
+ log(` ${dim(`1. Get your API key from Settings \u2192 ${API_KEYS_PAGE}`)}`);
104
+ log(` ${dim(keysUrl)}
105
+ `);
106
+ const openNow = await prompt(` Open this URL in your browser? [Y/n]: `);
107
+ if (openNow.toLowerCase() !== "n" && openNow.toLowerCase() !== "no") {
108
+ openBrowser(keysUrl);
109
+ }
110
+ log("");
111
+ log(` ${dim("2. Generate a key (if you don't have one), then copy it.\n")}`);
112
+ const apiKey = await prompt(` Paste your API key (${API_KEY_PREFIX} or ${AGENT_KEY_PREFIX}): `);
113
+ if (!apiKey || !isApiKeyShaped(apiKey)) {
114
+ log(` ${orange("!")} ${API_KEY_FORMAT_LINE}`);
115
+ log(` Get one at ${keysUrl}
116
+ `);
117
+ process.exit(1);
118
+ }
119
+ log(` ${green("\u2713")} Key received`);
120
+ const workspace = await verifyWorkspace(apiKey);
121
+ if (workspace) {
122
+ log(` ${green("\u2713")} Connected to workspace: ${bold(workspace.name)} ${dim(`(${workspace.slug})`)}`);
123
+ } else {
124
+ log(` ${orange("!")} Could not verify workspace. Check your key at ${keysUrl}`);
125
+ }
126
+ log("");
127
+ const CLIENT_NAMES = ["Cursor", "Claude Desktop"];
128
+ const options = [...CLIENT_NAMES, "Other"];
129
+ const choice = await promptChoice("Where do you want to set up Product Brain?", options);
130
+ if (choice === 2) {
131
+ printConfigSnippet(apiKey);
132
+ } else {
133
+ const client = resolveClient(CLIENT_NAMES[choice]);
134
+ if (client) {
135
+ await writeConfig(client, apiKey);
136
+ } else {
137
+ log(` ${orange("!")} ${CLIENT_NAMES[choice]} config path not available on this platform.`);
138
+ printConfigSnippet(apiKey);
139
+ }
140
+ }
141
+ if (choice === 0) printDeeplink(apiKey);
142
+ log("");
143
+ log(
144
+ ` ${green("\u2713")} Done! Restart your AI assistant and try: ${bold(`"${PASTE_NOW}"`)}`
145
+ );
146
+ printHelpLink();
147
+ }
148
+ async function writeConfig(client, apiKey) {
149
+ try {
150
+ const wrote = await writeClientConfig(client, apiKey);
151
+ if (wrote) {
152
+ log(` ${green("\u2713")} Wrote config to ${dim(client.configPath)}`);
153
+ } else {
154
+ log(` ${dim("\u2139")} ${client.name} already configured \u2014 skipped`);
155
+ }
156
+ } catch (err) {
157
+ log(` ${orange("!")} Could not write ${client.name} config: ${err.message}`);
158
+ printConfigSnippet(apiKey);
159
+ }
160
+ }
161
+ function printHelpLink() {
162
+ log(` ${dim(`Need help? See ${apiKeysUrl()}`)}`);
163
+ log("");
164
+ }
165
+ function printConfigSnippet(apiKey) {
166
+ log("");
167
+ log(bold(" Add this to your MCP client config:\n"));
168
+ const snippet = JSON.stringify(
169
+ {
170
+ mcpServers: {
171
+ "Product Brain": {
172
+ command: "npx",
173
+ args: ["-y", MCP_NPX_PACKAGE],
174
+ env: { PRODUCTBRAIN_API_KEY: apiKey }
175
+ }
176
+ }
177
+ },
178
+ null,
179
+ 2
180
+ );
181
+ for (const line of snippet.split("\n")) {
182
+ log(` ${line}`);
183
+ }
184
+ log("");
185
+ }
186
+ function buildDeeplink(apiKey) {
187
+ const config = JSON.stringify({
188
+ command: "npx",
189
+ args: ["-y", MCP_NPX_PACKAGE],
190
+ env: { PRODUCTBRAIN_API_KEY: apiKey }
191
+ });
192
+ const encoded = Buffer.from(config).toString("base64url");
193
+ return `cursor://anysphere.cursor-deeplink/mcp/install?name=${encodeURIComponent("Product Brain")}&config=${encoded}`;
194
+ }
195
+ function printDeeplink(apiKey) {
196
+ const link = buildDeeplink(apiKey);
197
+ log("");
198
+ log(` ${dim("One-click install for Cursor (paste in browser):")}`);
199
+ log(` ${link}`);
200
+ }
201
+ export {
202
+ resolveSetupSiteUrl,
203
+ runSetup
204
+ };
205
+ //# sourceMappingURL=setup-KM6C74M2.js.map