@productbrain/mcp 0.0.1-beta.165 → 0.0.1-beta.16514

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 CHANGED
@@ -1,27 +1,453 @@
1
1
  import {
2
2
  SERVER_VERSION,
3
+ createProductBrainServer
4
+ } from "./chunk-JCRSJYX2.js";
5
+ import {
6
+ DEFAULT_CLOUD_URL,
7
+ UNAVAILABLE,
8
+ appUrl,
3
9
  bootstrapHttp,
4
- createProductBrainServer,
10
+ checkKeyAgainstCandidates,
11
+ getKeyState,
5
12
  hashKey,
6
- initFeatureFlags,
13
+ isApiKeyShaped,
14
+ parseFallbackUrls,
7
15
  runWithAuth
8
- } from "./chunk-M7ITTWWM.js";
9
- import {
10
- getPostHogClient,
11
- initAnalytics,
12
- shutdownAnalytics
13
- } from "./chunk-YMF3IQ5E.js";
16
+ } from "./chunk-PJG3QSEU.js";
14
17
 
15
18
  // src/http.ts
16
- import { createHash, randomUUID } from "crypto";
19
+ import { randomUUID } from "crypto";
17
20
  import express from "express";
18
- import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
19
- import { isInitializeRequest } from "@modelcontextprotocol/sdk/types.js";
21
+ import { createMcpHandler } from "@modelcontextprotocol/server";
22
+ import { toNodeHandler } from "@modelcontextprotocol/node";
23
+ import rateLimit2 from "express-rate-limit";
24
+
25
+ // src/httpErrors.ts
26
+ function clampSeconds(s) {
27
+ return Math.max(0, Math.round(s));
28
+ }
29
+ function build(reason, message, p) {
30
+ const seconds = clampSeconds(p.retryAfterSeconds);
31
+ return {
32
+ status: 429,
33
+ headers: { "Retry-After": String(seconds) },
34
+ body: {
35
+ jsonrpc: "2.0",
36
+ id: p.id ?? null,
37
+ error: {
38
+ code: -32e3,
39
+ message,
40
+ data: {
41
+ reason,
42
+ retryAfterSeconds: seconds,
43
+ limit: p.limit,
44
+ current: p.current
45
+ }
46
+ }
47
+ }
48
+ };
49
+ }
50
+ function buildRateLimitError(p) {
51
+ const seconds = clampSeconds(p.retryAfterSeconds);
52
+ return build(
53
+ "rate_limited",
54
+ `Too many requests \u2014 retry after ${seconds} s.`,
55
+ p
56
+ );
57
+ }
58
+ function buildAuthLockoutError(p) {
59
+ const seconds = clampSeconds(p.retryAfterSeconds);
60
+ return build(
61
+ "auth_lockout",
62
+ `Too many failed auth attempts \u2014 locked out, retry after ${seconds} s.`,
63
+ p
64
+ );
65
+ }
66
+ function buildUnavailableError(id = null) {
67
+ return { status: 503, body: { jsonrpc: "2.0", id, error: { code: -32e3, message: `${UNAVAILABLE.down}
68
+ ${UNAVAILABLE.nothingSaved}` } } };
69
+ }
70
+ function send429(res, built) {
71
+ if (res.headersSent) return;
72
+ for (const [k, v] of Object.entries(built.headers)) {
73
+ res.setHeader(k, v);
74
+ }
75
+ res.status(built.status).json(built.body);
76
+ }
77
+
78
+ // src/mcpRateLimit.ts
20
79
  import rateLimit from "express-rate-limit";
80
+
81
+ // src/authLockout.ts
82
+ var AUTH_FAILURE_MAX = 10;
83
+ var AUTH_FAILURE_WINDOW_MS = 5 * 6e4;
84
+ var AUTH_BLOCK_DURATION_MS = 15 * 6e4;
85
+ var MAX_AUTH_FAILURE_ENTRIES = 1e4;
86
+ function rejected(presented) {
87
+ return { status: "rejected", credentialId: hashKey(presented) };
88
+ }
89
+ function resolveBearerAuth(authorizationHeader) {
90
+ if (typeof authorizationHeader !== "string" || authorizationHeader.trim() === "") {
91
+ return { status: "absent" };
92
+ }
93
+ if (!authorizationHeader.startsWith("Bearer ")) {
94
+ return rejected(authorizationHeader.trim());
95
+ }
96
+ const token = authorizationHeader.slice(7).trim();
97
+ if (!isApiKeyShaped(token)) return rejected(token);
98
+ return { status: "ok", apiKey: token, credentialId: hashKey(token) };
99
+ }
100
+ function checkAuthBlock(failures, credentialId, now) {
101
+ const rec = failures.get(credentialId);
102
+ if (!rec) return false;
103
+ return rec.blockedUntil > now;
104
+ }
105
+ function authLockoutError(failures, auth, now, id = null) {
106
+ if (auth.status === "absent") return null;
107
+ const rec = failures.get(auth.credentialId);
108
+ if (!rec || !checkAuthBlock(failures, auth.credentialId, now)) return null;
109
+ const retryAfterSeconds = Math.max(0, Math.ceil((rec.blockedUntil - now) / 1e3));
110
+ return buildAuthLockoutError({ retryAfterSeconds, limit: AUTH_FAILURE_MAX, current: rec.count, id });
111
+ }
112
+ function recordAuthFailure(failures, credentialId, now) {
113
+ const rec = failures.get(credentialId);
114
+ if (!rec) {
115
+ if (failures.size >= MAX_AUTH_FAILURE_ENTRIES) {
116
+ const oldest = failures.keys().next().value;
117
+ if (oldest !== void 0) failures.delete(oldest);
118
+ }
119
+ failures.set(credentialId, { count: 1, firstFailure: now, blockedUntil: 0 });
120
+ return;
121
+ }
122
+ if (now - rec.firstFailure > AUTH_FAILURE_WINDOW_MS) {
123
+ rec.count = 1;
124
+ rec.firstFailure = now;
125
+ rec.blockedUntil = 0;
126
+ } else {
127
+ rec.count++;
128
+ if (rec.count >= AUTH_FAILURE_MAX) {
129
+ rec.blockedUntil = now + AUTH_BLOCK_DURATION_MS;
130
+ }
131
+ }
132
+ }
133
+ function keyVerdictGate(verdict, failures, credentialId, now) {
134
+ if (verdict === "ok" || verdict === "rate_limited") return "admit";
135
+ if (verdict === "rejected") {
136
+ recordAuthFailure(failures, credentialId, now);
137
+ return "unauthorized";
138
+ }
139
+ return "unavailable";
140
+ }
141
+
142
+ // src/mcpRateLimit.ts
143
+ var MCP_KEY_LIMIT = 120;
144
+ var MCP_IP_CEILING = 1200;
145
+ function mcpRateKey(req) {
146
+ const auth = resolveBearerAuth(req.headers?.authorization);
147
+ return auth.status === "absent" ? `ip:${req.ip ?? ""}` : `key:${auth.credentialId}`;
148
+ }
149
+ function limiter(max, windowMs, keyGenerator) {
150
+ return rateLimit({
151
+ windowMs,
152
+ max,
153
+ standardHeaders: true,
154
+ legacyHeaders: false,
155
+ ...keyGenerator ? { keyGenerator } : {},
156
+ handler: (req, res) => {
157
+ const r = req.rateLimit;
158
+ const reset = r?.resetTime?.getTime?.() ?? Date.now() + windowMs;
159
+ send429(res, buildRateLimitError({
160
+ retryAfterSeconds: Math.max(1, Math.ceil((reset - Date.now()) / 1e3)),
161
+ limit: r?.limit ?? max,
162
+ current: r?.used ?? 0,
163
+ id: req.body?.id ?? null
164
+ // mirror the JSON-RPC id when a POST body is present
165
+ }));
166
+ }
167
+ });
168
+ }
169
+ function mcpLimiters(opts = {}) {
170
+ const windowMs = opts.windowMs ?? 6e4;
171
+ return [
172
+ limiter(opts.ipCeiling ?? MCP_IP_CEILING, windowMs),
173
+ limiter(opts.keyLimit ?? MCP_KEY_LIMIT, windowMs, mcpRateKey)
174
+ ];
175
+ }
176
+
177
+ // src/lib/oauthRedirectAllowlist.ts
178
+ var DEFAULT_OAUTH_REDIRECT_URIS = [
179
+ "https://claude.ai/api/mcp/auth_callback",
180
+ "https://claude.com/api/mcp/auth_callback",
181
+ "https://chatgpt.com/connector_platform_oauth_redirect",
182
+ "https://www.cursor.com/agents/mcp/oauth/callback"
183
+ ];
184
+ var CHATGPT_CONNECTOR_CALLBACK = /^https:\/\/chatgpt\.com\/connector\/oauth\/[A-Za-z0-9_-]+$/;
185
+ var LOOPBACK_HOSTS = ["localhost", "127.0.0.1", "[::1]"];
186
+ var MAX_REDIRECT_URI_LENGTH = 2048;
187
+ var MAX_REGISTRATION_REDIRECTS = 10;
188
+ var OPERATOR_ENTRY_FORM = "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)";
189
+ function exactForm(url) {
190
+ return `${url.origin}${url.pathname}`;
191
+ }
192
+ function parseRedirectUriAllowlist(raw) {
193
+ if (!raw) return { uris: [], configError: null };
194
+ const uris = [];
195
+ for (const part of raw.split(",")) {
196
+ const trimmed = part.trim();
197
+ if (!trimmed) continue;
198
+ let url = null;
199
+ try {
200
+ url = trimmed.includes("://") ? new URL(trimmed) : null;
201
+ } catch {
202
+ url = null;
203
+ }
204
+ const valid = url !== null && url.protocol === "https:" && !url.username && !url.password && !url.search && !url.hash && (url.port === "" || url.port === "443") && url.pathname !== "/";
205
+ if (!valid || url === null) {
206
+ return { uris: [], configError: `${OPERATOR_ENTRY_FORM}; got "${trimmed}"` };
207
+ }
208
+ uris.push(exactForm(url));
209
+ }
210
+ return { uris, configError: null };
211
+ }
212
+ function resolveOAuthRedirectAllowlist(opts = {}) {
213
+ const parsed = parseRedirectUriAllowlist(opts.explicitAllowlist);
214
+ return {
215
+ uris: [.../* @__PURE__ */ new Set([...DEFAULT_OAUTH_REDIRECT_URIS, ...parsed.uris])],
216
+ configError: parsed.configError
217
+ };
218
+ }
219
+ function checkRedirectUri(redirectUri, allowlist) {
220
+ if (allowlist.configError) return `OAuth is misconfigured: ${allowlist.configError}`;
221
+ if (typeof redirectUri !== "string" || redirectUri.length === 0) {
222
+ return "redirect_uri is required";
223
+ }
224
+ if (redirectUri.length > MAX_REDIRECT_URI_LENGTH) {
225
+ return `redirect_uri is longer than ${MAX_REDIRECT_URI_LENGTH} characters`;
226
+ }
227
+ let url;
228
+ try {
229
+ url = new URL(redirectUri);
230
+ } catch {
231
+ return "redirect_uri is not a valid absolute URL";
232
+ }
233
+ if (url.username || url.password) return "redirect_uri must not contain credentials";
234
+ if (url.hash) return "redirect_uri must not contain a fragment";
235
+ const host = url.hostname.toLowerCase();
236
+ if (url.protocol === "http:") {
237
+ return LOOPBACK_HOSTS.includes(host) ? null : "redirect_uri must use https (http is allowed only for localhost, 127.0.0.1 or [::1])";
238
+ }
239
+ if (url.protocol === "https:") {
240
+ if (url.port && url.port !== "443") return "redirect_uri must use the default https port (443)";
241
+ if (url.search) return "redirect_uri must not contain a query";
242
+ const exact = exactForm(url);
243
+ return allowlist.uris.includes(exact) || CHATGPT_CONNECTOR_CALLBACK.test(exact) ? null : "redirect_uri is not an allowed callback (an operator can add the full URI with OAUTH_REDIRECT_HOST_ALLOWLIST)";
244
+ }
245
+ return "redirect_uri scheme is not allowed (use https, or http on loopback)";
246
+ }
247
+ function checkRegistrationRedirects(redirectUris, allowlist) {
248
+ const refused = (refusal) => ({ refusal, allowed: [], dropped: [] });
249
+ if (!Array.isArray(redirectUris) || redirectUris.length === 0) return refused("redirect_uris is required");
250
+ if (redirectUris.length > MAX_REGISTRATION_REDIRECTS) {
251
+ return refused(`redirect_uris may hold at most ${MAX_REGISTRATION_REDIRECTS} entries`);
252
+ }
253
+ const allowed = [];
254
+ const dropped = [];
255
+ for (const uri of redirectUris) {
256
+ const reason = checkRedirectUri(uri, allowlist);
257
+ if (reason) dropped.push({ uri, reason });
258
+ else allowed.push(uri);
259
+ }
260
+ return { refusal: allowed.length === 0 ? dropped[0].reason : null, allowed, dropped };
261
+ }
262
+
263
+ // src/lib/connectClientNames.ts
264
+ var CONNECT_CLIENT_LABELS = {
265
+ "claude.ai": "Claude",
266
+ "claude.com": "Claude",
267
+ "chatgpt.com": "ChatGPT",
268
+ "www.cursor.com": "Cursor (web)"
269
+ };
270
+ var REPLACEABLE_CLIENT_NAMES = [...new Set(Object.values(CONNECT_CLIENT_LABELS))];
271
+
272
+ // src/lib/connectClients.ts
273
+ var LOCAL_APP_NAME_MAX = 40;
274
+ var LOCAL_APP_KEY_NAME = "Local app";
275
+ var CLIENT_ID_PREFIX = "pb_client_";
276
+ var LOOPBACK_HOSTS2 = ["localhost", "127.0.0.1", "[::1]"];
277
+ function cleanAppName(raw) {
278
+ if (typeof raw !== "string") return null;
279
+ const folded = raw.replace(/[\u0000-\u001f\u007f-\u009f\u200b-\u200f\u2028-\u202e\u2066-\u2069]/g, " ").replace(/\s+/g, " ").trim();
280
+ const cut = Array.from(folded).slice(0, LOCAL_APP_NAME_MAX).join("").trim();
281
+ return cut === "" ? null : cut;
282
+ }
283
+ var B64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
284
+ function utf8Bytes(text2) {
285
+ const bytes = [];
286
+ const escaped = encodeURIComponent(text2);
287
+ for (let i = 0; i < escaped.length; i++) {
288
+ if (escaped[i] === "%") {
289
+ bytes.push(parseInt(escaped.slice(i + 1, i + 3), 16));
290
+ i += 2;
291
+ } else bytes.push(escaped.charCodeAt(i));
292
+ }
293
+ return bytes;
294
+ }
295
+ function base64url(bytes) {
296
+ let out = "";
297
+ for (let i = 0; i < bytes.length; i += 3) {
298
+ const n = bytes[i] << 16 | (bytes[i + 1] ?? 0) << 8 | (bytes[i + 2] ?? 0);
299
+ out += B64[n >> 18 & 63] + B64[n >> 12 & 63];
300
+ if (i + 1 < bytes.length) out += B64[n >> 6 & 63];
301
+ if (i + 2 < bytes.length) out += B64[n & 63];
302
+ }
303
+ return out;
304
+ }
305
+ function fromBase64url(text2) {
306
+ if (!/^[A-Za-z0-9_-]*$/.test(text2) || text2.length % 4 === 1) return null;
307
+ let escaped = "";
308
+ for (let i = 0; i < text2.length; i += 4) {
309
+ const quad = text2.slice(i, i + 4);
310
+ const n = Array.from(quad).reduce((acc, ch, j) => acc | B64.indexOf(ch) << 18 - 6 * j, 0);
311
+ const bytes = [n >> 16 & 255, n >> 8 & 255, n & 255].slice(0, quad.length - 1);
312
+ for (const b of bytes) escaped += `%${b.toString(16).padStart(2, "0")}`;
313
+ }
314
+ try {
315
+ return decodeURIComponent(escaped);
316
+ } catch {
317
+ return null;
318
+ }
319
+ }
320
+ function registeredClientId(uuid, clientName) {
321
+ const name = cleanAppName(clientName);
322
+ return name === null ? `${CLIENT_ID_PREFIX}${uuid}` : `${CLIENT_ID_PREFIX}${uuid}.${base64url(utf8Bytes(name))}`;
323
+ }
324
+ function appNameFromClientId(clientId) {
325
+ if (typeof clientId !== "string" || !clientId.startsWith(CLIENT_ID_PREFIX)) return null;
326
+ const dot = clientId.indexOf(".");
327
+ if (dot === -1) return null;
328
+ return cleanAppName(fromBase64url(clientId.slice(dot + 1)));
329
+ }
330
+ function connectClientOf(redirectUri, clientId) {
331
+ if (typeof redirectUri !== "string") return null;
332
+ let url;
333
+ try {
334
+ url = new URL(redirectUri);
335
+ } catch {
336
+ return null;
337
+ }
338
+ const host = url.hostname.toLowerCase();
339
+ if (url.protocol === "http:" && LOOPBACK_HOSTS2.includes(host)) return { kind: "local", appName: appNameFromClientId(clientId), at: url.host };
340
+ if (url.protocol !== "https:") return null;
341
+ const clientName = CONNECT_CLIENT_LABELS[host];
342
+ return clientName ? { kind: "vendor", clientName, host } : { kind: "web", host };
343
+ }
344
+ var connectKeyName = (client) => client.kind === "vendor" ? client.clientName : client.kind === "local" ? client.appName ?? LOCAL_APP_KEY_NAME : client.host;
345
+ var connectClientName = (client) => client.kind === "vendor" ? client.clientName : void 0;
346
+
347
+ // src/lib/oauthAuthCode.ts
348
+ function tokenResponse(apiKey) {
349
+ return {
350
+ access_token: apiKey,
351
+ token_type: "Bearer",
352
+ // 1 year: validity is enforced by Convex on every call, not by this clock.
353
+ expires_in: 365 * 24 * 3600
354
+ };
355
+ }
356
+
357
+ // src/lib/oauthDoors.ts
358
+ var CONNECT_PAGE_PATH = "/connect";
359
+ var S256_CHALLENGE = /^[A-Za-z0-9_-]{43}$/;
360
+ var CONNECT_CODE = /^pb_ct_[A-Za-z0-9_-]{43}$/;
361
+ var text = (value) => typeof value === "string" ? value : void 0;
362
+ function logOAuthDoor(door, status, reason, uris) {
363
+ const list = uris === void 0 ? "" : ` uris=${JSON.stringify(uris.map(String)).slice(0, 600)}`;
364
+ process.stderr.write(`[oauth] door=${door} status=${status} reason=${JSON.stringify(reason)}${list}
365
+ `);
366
+ }
367
+ function backToClient(redirectUri, params, state) {
368
+ const url = new URL(redirectUri);
369
+ for (const [key, value] of Object.entries(params)) url.searchParams.set(key, value);
370
+ if (state !== void 0) url.searchParams.set("state", state);
371
+ return url.toString();
372
+ }
373
+ function authorizeOutcome(query, { allowlist, appUrl: appUrl2 }) {
374
+ const redirectUri = text(query.redirect_uri);
375
+ const refusal = checkRedirectUri(query.redirect_uri, allowlist);
376
+ if (refusal || redirectUri === void 0) {
377
+ return { status: 400, reason: refusal ?? "redirect_uri is required", json: { error: "invalid_request", error_description: refusal } };
378
+ }
379
+ const state = text(query.state);
380
+ if (query.error !== void 0) {
381
+ if (query.error !== "access_denied") return { status: 400, reason: "unknown_error_param", json: { error: "invalid_request" } };
382
+ return { status: 302, reason: "access_denied", location: backToClient(redirectUri, { error: "access_denied" }, state) };
383
+ }
384
+ if (query.code !== void 0) {
385
+ const code = text(query.code);
386
+ if (code === void 0 || !CONNECT_CODE.test(code)) return { status: 400, reason: "malformed_code", json: { error: "invalid_request" } };
387
+ return { status: 302, reason: "code_returned", location: backToClient(redirectUri, { code }, state) };
388
+ }
389
+ const challenge = text(query.code_challenge);
390
+ if (query.code_challenge_method !== "S256" || challenge === void 0 || !S256_CHALLENGE.test(challenge)) {
391
+ const description = "code_challenge (S256) is required";
392
+ return { status: 302, reason: "pkce_required", location: backToClient(redirectUri, { error: "invalid_request", error_description: description }, state) };
393
+ }
394
+ const page = new URL(`${appUrl2}${CONNECT_PAGE_PATH}`);
395
+ page.searchParams.set("client_id", text(query.client_id) ?? "");
396
+ page.searchParams.set("redirect_uri", redirectUri);
397
+ page.searchParams.set("code_challenge", challenge);
398
+ if (state !== void 0) page.searchParams.set("state", state);
399
+ return { status: 302, reason: "to_connect_page", location: page.toString() };
400
+ }
401
+ var invalidGrant = (reason) => ({ status: 400, reason, json: { error: "invalid_grant" } });
402
+ async function exchangeOutcome(body, { candidates, fetchImpl = fetch, timeoutMs = 5e3 }) {
403
+ if (body.grant_type !== "authorization_code") return { status: 400, reason: "unsupported_grant_type", json: { error: "unsupported_grant_type" } };
404
+ const code = text(body.code), codeVerifier = text(body.code_verifier), redirectUri = text(body.redirect_uri);
405
+ if (!code || !codeVerifier || !redirectUri) return { status: 400, reason: "missing_param", json: { error: "invalid_request" } };
406
+ const client = connectClientOf(redirectUri, body.client_id);
407
+ if (!client) return invalidGrant("unreadable_redirect");
408
+ const clientName = connectClientName(client);
409
+ const payload = JSON.stringify({
410
+ token: code,
411
+ codeVerifier,
412
+ redirectUri,
413
+ name: connectKeyName(client),
414
+ ...clientName === void 0 ? {} : { clientName }
415
+ });
416
+ for (const base of candidates) {
417
+ let status;
418
+ let json;
419
+ try {
420
+ const res = await fetchImpl(`${base}/auth/redeem-connect-token`, {
421
+ method: "POST",
422
+ headers: { "content-type": "application/json" },
423
+ body: payload,
424
+ signal: AbortSignal.timeout(timeoutMs)
425
+ });
426
+ status = res.status;
427
+ json = await res.json().catch(() => null);
428
+ } catch {
429
+ return invalidGrant("redeem_unreachable");
430
+ }
431
+ const apiKey = json?.apiKey;
432
+ if (status === 200 && typeof apiKey === "string") return { status: 200, reason: "token_issued", json: tokenResponse(apiKey) };
433
+ const refusal = json?.error?.code;
434
+ if (!(status === 400 && refusal === "invalid_token")) return invalidGrant(`redeem_refused_${status}`);
435
+ }
436
+ return invalidGrant("code_refused");
437
+ }
438
+ function sendDoor(res, door, outcome) {
439
+ logOAuthDoor(door, outcome.status, outcome.reason);
440
+ if (outcome.location !== void 0) res.redirect(302, outcome.location);
441
+ else res.status(outcome.status).json(outcome.json);
442
+ }
443
+
444
+ // src/http.ts
21
445
  bootstrapHttp();
22
- initAnalytics();
23
- initFeatureFlags(getPostHogClient());
24
446
  var PORT = parseInt(process.env.PORT ?? process.env.MCP_PORT ?? "3002", 10);
447
+ function keyCheckCandidates() {
448
+ const primaryUrl = (process.env.CONVEX_SITE_URL ?? DEFAULT_CLOUD_URL).replace(/\/$/, "");
449
+ return [primaryUrl, ...parseFallbackUrls(process.env.CONVEX_FALLBACK_URLS).map((u) => u.replace(/\/$/, ""))];
450
+ }
25
451
  function baseUrl(req) {
26
452
  const proto = req.headers["x-forwarded-proto"] ?? req.protocol ?? "http";
27
453
  const host = req.headers.host ?? `localhost:${PORT}`;
@@ -30,18 +456,19 @@ function baseUrl(req) {
30
456
  var app = express();
31
457
  app.set("trust proxy", 1);
32
458
  app.use(express.json());
33
- var ALLOWED_ORIGINS = process.env.CORS_ORIGINS?.split(",").map((o) => o.trim()).filter(Boolean);
459
+ var ALLOWED_ORIGINS = (process.env.CORS_ORIGINS ?? "https://claude.ai").split(",").map((o) => o.trim()).filter(Boolean);
460
+ var OAUTH_REDIRECT_ALLOWLIST = resolveOAuthRedirectAllowlist({ explicitAllowlist: process.env.OAUTH_REDIRECT_HOST_ALLOWLIST });
34
461
  app.use((_req, res, next) => {
35
462
  const origin = _req.headers.origin;
36
- if (ALLOWED_ORIGINS && origin && ALLOWED_ORIGINS.includes(origin)) {
463
+ if (origin && ALLOWED_ORIGINS.includes(origin)) {
37
464
  res.setHeader("Access-Control-Allow-Origin", origin);
38
465
  }
39
466
  res.setHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS");
40
467
  res.setHeader(
41
468
  "Access-Control-Allow-Headers",
42
- "Content-Type, Authorization, Mcp-Session-Id, Last-Event-Id"
469
+ "Content-Type, Authorization, Mcp-Protocol-Version, Mcp-Method, Mcp-Name"
43
470
  );
44
- res.setHeader("Access-Control-Expose-Headers", "Mcp-Session-Id");
471
+ res.setHeader("Access-Control-Expose-Headers", "Retry-After");
45
472
  if (_req.method === "OPTIONS") {
46
473
  res.status(204).end();
47
474
  return;
@@ -65,365 +492,74 @@ app.get("/.well-known/oauth-authorization-server", (req, res) => {
65
492
  token_endpoint: `${base}/oauth/token`,
66
493
  registration_endpoint: `${base}/register`,
67
494
  response_types_supported: ["code"],
68
- grant_types_supported: ["authorization_code", "refresh_token"],
495
+ grant_types_supported: ["authorization_code"],
496
+ // TEN-4548: no refresh grant (lib/oauthAuthCode.ts tokenResponse)
69
497
  code_challenge_methods_supported: ["S256"],
70
498
  token_endpoint_auth_methods_supported: ["none"],
71
499
  scopes_supported: ["mcp:tools", "mcp:resources"]
72
500
  });
73
501
  });
74
- var authLimiter = rateLimit({
502
+ var authLimiter = rateLimit2({
75
503
  windowMs: 6e4,
76
504
  max: 20,
77
505
  standardHeaders: true,
78
506
  legacyHeaders: false,
79
- message: { error: "Too many auth requests. Try again later." }
507
+ handler: (req, res) => {
508
+ logOAuthDoor(`${req.method} /authorize`, 429, "rate_limited_per_ip");
509
+ res.status(429).json({ error: "Too many auth requests. Try again later." });
510
+ }
80
511
  });
81
- var registeredClients = /* @__PURE__ */ new Map();
82
- var MAX_REGISTERED_CLIENTS = 500;
83
512
  app.post(
84
513
  "/register",
85
- authLimiter,
86
514
  express.json(),
87
515
  (req, res) => {
88
- if (registeredClients.size >= MAX_REGISTERED_CLIENTS) {
89
- res.status(503).json({
90
- error: "server_error",
91
- error_description: "Registration limit reached. Try again later."
92
- });
516
+ const { redirect_uris, client_name } = req.body ?? {};
517
+ const { refusal, allowed, dropped } = checkRegistrationRedirects(redirect_uris, OAUTH_REDIRECT_ALLOWLIST);
518
+ if (refusal) {
519
+ logOAuthDoor("POST /register", 400, refusal, Array.isArray(redirect_uris) ? redirect_uris : [redirect_uris]);
520
+ res.status(400).json({ error: "invalid_redirect_uri", error_description: refusal });
93
521
  return;
94
522
  }
95
- const { redirect_uris, client_name } = req.body;
96
- if (!Array.isArray(redirect_uris) || redirect_uris.length === 0) {
97
- res.status(400).json({
98
- error: "invalid_client_metadata",
99
- error_description: "redirect_uris is required"
100
- });
101
- return;
102
- }
103
- const clientId = `pb_client_${randomUUID()}`;
104
- const client = {
105
- client_id: clientId,
106
- redirect_uris,
107
- client_name,
108
- registeredAt: Date.now()
109
- };
110
- registeredClients.set(clientId, client);
523
+ const clientId = registeredClientId(randomUUID(), client_name);
524
+ const droppedUris = dropped.length > 0 ? dropped.map((d) => d.uri) : void 0;
525
+ logOAuthDoor("POST /register", 201, droppedUris ? "dropped_redirects" : "registered", droppedUris);
111
526
  res.status(201).json({
112
527
  client_id: clientId,
113
528
  client_name: client_name ?? "MCP Client",
114
- redirect_uris,
529
+ redirect_uris: allowed,
115
530
  grant_types: ["authorization_code"],
116
531
  response_types: ["code"],
117
532
  token_endpoint_auth_method: "none"
118
533
  });
119
534
  }
120
535
  );
121
- var pendingCodes = /* @__PURE__ */ new Map();
122
- var ACCESS_TOKEN_TTL = 3600;
123
- var ACCESS_TOKEN_TTL_MS = ACCESS_TOKEN_TTL * 1e3;
124
- var REFRESH_TOKEN_TTL_MS = 90 * 24 * 60 * 6e4;
125
- var refreshTokens = /* @__PURE__ */ new Map();
126
- var MAX_REFRESH_TOKENS = 2e3;
127
- var MAX_REFRESH_TOKENS_PER_KEY = 20;
128
- var accessTokens = /* @__PURE__ */ new Map();
129
- var MAX_ACCESS_TOKENS = 1e3;
536
+ app.get("/authorize", authLimiter, (req, res) => {
537
+ sendDoor(res, "GET /authorize", authorizeOutcome(req.query ?? {}, { allowlist: OAUTH_REDIRECT_ALLOWLIST, appUrl: appUrl() }));
538
+ });
130
539
  setInterval(() => {
131
540
  const now = Date.now();
132
- for (const [code, auth] of pendingCodes) {
133
- if (now > auth.expiresAt) pendingCodes.delete(code);
134
- }
135
- for (const [id, client] of registeredClients) {
136
- if (now - client.registeredAt > 24 * 60 * 6e4) registeredClients.delete(id);
137
- }
138
- for (const [token, entry] of refreshTokens) {
139
- if (now - entry.createdAt > REFRESH_TOKEN_TTL_MS) refreshTokens.delete(token);
140
- }
141
- if (refreshTokens.size > MAX_REFRESH_TOKENS) {
142
- const sorted = [...refreshTokens.entries()].sort((a, b) => a[1].createdAt - b[1].createdAt);
143
- for (let i = 0; i < sorted.length - MAX_REFRESH_TOKENS; i++) {
144
- refreshTokens.delete(sorted[i][0]);
145
- }
146
- }
147
- for (const [token, entry] of accessTokens) {
148
- if (now - entry.createdAt > ACCESS_TOKEN_TTL_MS) accessTokens.delete(token);
149
- }
150
- for (const [ip, rec] of authFailures) {
541
+ for (const [credentialId, rec] of authFailures) {
151
542
  if (rec.blockedUntil < now && rec.firstFailure + AUTH_FAILURE_WINDOW_MS < now) {
152
- authFailures.delete(ip);
153
- }
154
- }
155
- if (authFailures.size > MAX_AUTH_FAILURE_ENTRIES) {
156
- const sorted = [...authFailures.entries()].sort((a, b) => a[1].firstFailure - b[1].firstFailure);
157
- for (let i = 0; i < sorted.length - MAX_AUTH_FAILURE_ENTRIES; i++) {
158
- authFailures.delete(sorted[i][0]);
543
+ authFailures.delete(credentialId);
159
544
  }
160
545
  }
161
546
  }, 6e4);
162
- function esc(s) {
163
- return String(s ?? "").replace(
164
- /[&"<>]/g,
165
- (c) => ({ "&": "&amp;", '"': "&quot;", "<": "&lt;", ">": "&gt;" })[c]
166
- );
167
- }
168
- app.get("/authorize", authLimiter, (req, res) => {
169
- const { redirect_uri, code_challenge, code_challenge_method, state, client_id } = req.query;
170
- res.type("html").send(`<!DOCTYPE html>
171
- <html lang="en"><head>
172
- <meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
173
- <title>Authorize \u2014 Product Brain</title>
174
- <style>
175
- *{margin:0;padding:0;box-sizing:border-box}
176
- body{font-family:-apple-system,system-ui,sans-serif;background:#0a0a0a;color:#e5e5e5;
177
- display:flex;align-items:center;justify-content:center;min-height:100vh;padding:1rem}
178
- .card{background:#1a1a1a;border:1px solid #333;border-radius:12px;padding:2rem;max-width:400px;width:100%}
179
- h1{font-size:1.2rem;margin-bottom:.25rem}
180
- .sub{color:#999;font-size:.85rem;margin-bottom:1.5rem}
181
- label{display:block;font-size:.85rem;margin-bottom:.4rem;color:#ccc}
182
- input[type=password]{width:100%;padding:.6rem .75rem;background:#111;border:1px solid #444;
183
- border-radius:8px;color:#e5e5e5;font:.85rem/1.4 monospace}
184
- input:focus{outline:none;border-color:#7c3aed}
185
- button{width:100%;padding:.6rem;background:#7c3aed;color:#fff;border:none;
186
- border-radius:8px;font-size:.85rem;cursor:pointer;margin-top:1rem}
187
- button:hover{background:#6d28d9}
188
- .err{color:#ef4444;font-size:.8rem;margin-top:.5rem;display:none}
189
- </style></head><body>
190
- <div class="card">
191
- <h1>Product Brain</h1>
192
- <p class="sub">Enter your API key to connect Claude to your workspace.</p>
193
- <form method="POST" action="/authorize">
194
- <input type="hidden" name="redirect_uri" value="${esc(redirect_uri)}">
195
- <input type="hidden" name="code_challenge" value="${esc(code_challenge)}">
196
- <input type="hidden" name="code_challenge_method" value="${esc(code_challenge_method)}">
197
- <input type="hidden" name="state" value="${esc(state)}">
198
- <input type="hidden" name="client_id" value="${esc(client_id)}">
199
- <label for="k">API Key</label>
200
- <input type="password" id="k" name="api_key" placeholder="pb_sk_\u2026" required autofocus>
201
- <p class="err" id="e">Key must start with pb_sk_</p>
202
- <button type="submit">Authorize</button>
203
- </form>
204
- </div>
205
- <script>document.querySelector("form").onsubmit=function(e){
206
- if(!document.getElementById("k").value.startsWith("pb_sk_")){
207
- e.preventDefault();document.getElementById("e").style.display="block"}}</script>
208
- </body></html>`);
209
- });
210
- app.post(
211
- "/authorize",
212
- authLimiter,
213
- express.urlencoded({ extended: false }),
214
- (req, res) => {
215
- const { api_key, redirect_uri, code_challenge, state, client_id } = req.body;
216
- if (!api_key?.startsWith("pb_sk_")) {
217
- res.status(400).send("Invalid API key");
218
- return;
219
- }
220
- if (!client_id || !registeredClients.has(client_id)) {
221
- res.status(400).json({
222
- error: "invalid_request",
223
- error_description: "Unknown or missing client_id"
224
- });
225
- return;
226
- }
227
- const client = registeredClients.get(client_id);
228
- if (!client.redirect_uris.includes(redirect_uri)) {
229
- res.status(400).json({
230
- error: "invalid_request",
231
- error_description: "redirect_uri does not match any registered redirect for this client"
232
- });
233
- return;
234
- }
235
- const code = randomUUID();
236
- pendingCodes.set(code, {
237
- apiKey: api_key,
238
- codeChallenge: code_challenge,
239
- redirectUri: redirect_uri,
240
- expiresAt: Date.now() + 5 * 6e4
241
- });
242
- const url = new URL(redirect_uri);
243
- url.searchParams.set("code", code);
244
- if (state) url.searchParams.set("state", state);
245
- res.redirect(302, url.toString());
246
- }
247
- );
248
- function issueTokens(apiKey) {
249
- const opaqueToken = `pb_at_${randomUUID()}`;
250
- const now = Date.now();
251
- if (accessTokens.size >= MAX_ACCESS_TOKENS) {
252
- let oldestKey = "";
253
- let oldestTime = Infinity;
254
- for (const [k, v] of accessTokens) {
255
- if (v.createdAt < oldestTime) {
256
- oldestTime = v.createdAt;
257
- oldestKey = k;
258
- }
259
- }
260
- if (oldestKey) accessTokens.delete(oldestKey);
261
- }
262
- accessTokens.set(opaqueToken, { apiKey, createdAt: now });
263
- const refreshToken = `pb_rt_${randomUUID()}`;
264
- let perKeyCount = 0;
265
- let oldestKeyForApiKey = null;
266
- let oldestAtForApiKey = Infinity;
267
- for (const [k, v] of refreshTokens) {
268
- if (v.apiKey === apiKey) {
269
- perKeyCount++;
270
- if (v.createdAt < oldestAtForApiKey) {
271
- oldestAtForApiKey = v.createdAt;
272
- oldestKeyForApiKey = k;
273
- }
274
- }
275
- }
276
- if (perKeyCount >= MAX_REFRESH_TOKENS_PER_KEY && oldestKeyForApiKey) {
277
- refreshTokens.delete(oldestKeyForApiKey);
278
- }
279
- if (refreshTokens.size >= MAX_REFRESH_TOKENS) {
280
- let oldestKey = null;
281
- let oldestAt = Infinity;
282
- for (const [k, v] of refreshTokens) {
283
- if (v.createdAt < oldestAt) {
284
- oldestAt = v.createdAt;
285
- oldestKey = k;
286
- }
287
- }
288
- if (oldestKey) refreshTokens.delete(oldestKey);
289
- }
290
- refreshTokens.set(refreshToken, { apiKey, createdAt: now });
291
- return {
292
- access_token: opaqueToken,
293
- token_type: "Bearer",
294
- expires_in: ACCESS_TOKEN_TTL,
295
- refresh_token: refreshToken
296
- };
297
- }
298
547
  app.post(
299
548
  "/oauth/token",
300
- authLimiter,
301
549
  express.urlencoded({ extended: false }),
302
550
  express.json(),
303
- (req, res) => {
304
- const { grant_type, code, code_verifier, redirect_uri, refresh_token } = req.body;
305
- if (grant_type === "refresh_token") {
306
- const entry = refreshTokens.get(refresh_token);
307
- if (!entry) {
308
- res.status(400).json({ error: "invalid_grant", error_description: "Invalid refresh token" });
309
- return;
310
- }
311
- if (Date.now() - entry.createdAt > REFRESH_TOKEN_TTL_MS) {
312
- refreshTokens.delete(refresh_token);
313
- res.status(400).json({ error: "invalid_grant", error_description: "Refresh token expired" });
314
- return;
315
- }
316
- const apiKey = entry.apiKey;
317
- refreshTokens.delete(refresh_token);
318
- res.json(issueTokens(apiKey));
319
- return;
320
- }
321
- if (grant_type !== "authorization_code") {
322
- res.status(400).json({ error: "unsupported_grant_type" });
323
- return;
324
- }
325
- const pending = pendingCodes.get(code);
326
- if (!pending || pending.redirectUri !== redirect_uri) {
327
- res.status(400).json({ error: "invalid_grant" });
328
- return;
329
- }
330
- const challenge = createHash("sha256").update(code_verifier ?? "").digest("base64url");
331
- if (challenge !== pending.codeChallenge) {
332
- pendingCodes.delete(code);
333
- res.status(400).json({
334
- error: "invalid_grant",
335
- error_description: "PKCE verification failed"
336
- });
337
- return;
338
- }
339
- pendingCodes.delete(code);
340
- res.json(issueTokens(pending.apiKey));
551
+ async (req, res) => {
552
+ sendDoor(res, "POST /oauth/token", await exchangeOutcome(req.body ?? {}, { candidates: keyCheckCandidates() }));
341
553
  }
342
554
  );
343
- var mcpLimiter = rateLimit({
344
- windowMs: 6e4,
345
- max: 120,
346
- standardHeaders: true,
347
- legacyHeaders: false,
348
- message: { error: "Too many requests. Try again later." }
349
- });
555
+ var mcpLimit = mcpLimiters();
350
556
  var authFailures = /* @__PURE__ */ new Map();
351
- var AUTH_FAILURE_MAX = 10;
352
- var AUTH_FAILURE_WINDOW_MS = 5 * 6e4;
353
- var AUTH_BLOCK_DURATION_MS = 15 * 6e4;
354
- var MAX_AUTH_FAILURE_ENTRIES = 1e4;
355
- function checkAuthBlock(ip) {
356
- const rec = authFailures.get(ip);
357
- if (!rec) return false;
358
- return rec.blockedUntil > Date.now();
359
- }
360
- function recordAuthFailure(ip) {
361
- const now = Date.now();
362
- const rec = authFailures.get(ip);
363
- if (!rec) {
364
- authFailures.set(ip, { count: 1, firstFailure: now, blockedUntil: 0 });
365
- return;
366
- }
367
- if (now - rec.firstFailure > AUTH_FAILURE_WINDOW_MS) {
368
- rec.count = 1;
369
- rec.firstFailure = now;
370
- rec.blockedUntil = 0;
371
- } else {
372
- rec.count++;
373
- if (rec.count >= AUTH_FAILURE_MAX) {
374
- rec.blockedUntil = now + AUTH_BLOCK_DURATION_MS;
375
- }
376
- }
377
- }
378
557
  app.get("/health", (_req, res) => {
379
558
  res.json({ status: "ok", version: SERVER_VERSION, transport: "http" });
380
559
  });
381
- var sessions = /* @__PURE__ */ new Map();
382
- var SESSION_TTL_MS = 30 * 60 * 1e3;
383
- var MAX_SESSIONS = 200;
384
- var MAX_SESSIONS_PER_KEY = 5;
385
- function evictStaleSessions() {
386
- const now = Date.now();
387
- for (const [id, entry] of sessions) {
388
- if (now - entry.lastAccess > SESSION_TTL_MS) {
389
- logSessionLifecycle("session_deleted", id, "ttl");
390
- entry.transport.close().catch(() => {
391
- });
392
- sessions.delete(id);
393
- }
394
- }
395
- if (sessions.size > MAX_SESSIONS) {
396
- const sorted = [...sessions.entries()].sort(
397
- (a, b) => a[1].lastAccess - b[1].lastAccess
398
- );
399
- for (let i = 0; i < sorted.length - MAX_SESSIONS; i++) {
400
- logSessionLifecycle("session_deleted", sorted[i][0], "eviction");
401
- sorted[i][1].transport.close().catch(() => {
402
- });
403
- sessions.delete(sorted[i][0]);
404
- }
405
- }
406
- }
407
- setInterval(evictStaleSessions, 6e4);
408
- function extractBearerKey(req) {
409
- const header = req.headers?.authorization;
410
- if (typeof header !== "string" || !header.startsWith("Bearer ")) return null;
411
- const token = header.slice(7).trim();
412
- if (token.startsWith("pb_sk_")) {
413
- return token;
414
- }
415
- if (token.startsWith("pb_at_")) {
416
- const entry = accessTokens.get(token);
417
- if (!entry) return null;
418
- const now = Date.now();
419
- if (now - entry.createdAt > ACCESS_TOKEN_TTL_MS) {
420
- accessTokens.delete(token);
421
- return null;
422
- }
423
- return entry.apiKey;
424
- }
425
- return null;
426
- }
560
+ var mcpHandler = createMcpHandler(createProductBrainServer, { onerror: (err) => process.stderr.write(`[HTTP] handler_error ${err.message}
561
+ `) });
562
+ var serveNode = toNodeHandler(mcpHandler);
427
563
  function send401(req, res) {
428
564
  const base = baseUrl(req);
429
565
  res.status(401).set(
@@ -431,176 +567,63 @@ function send401(req, res) {
431
567
  `Bearer resource_metadata="${base}/.well-known/oauth-protected-resource"`
432
568
  ).json({ error: "unauthorized" });
433
569
  }
434
- function logRequest(method, outcome, sessionId, durationMs) {
570
+ function logRequest(method, outcome, durationMs, status) {
435
571
  const ts = (/* @__PURE__ */ new Date()).toISOString();
436
- const sid = sessionId ? ` session=${sessionId}` : "";
572
+ const st = status != null ? ` status=${status}` : "";
437
573
  const dur = durationMs != null ? ` duration=${durationMs}ms` : "";
438
- process.stderr.write(`[HTTP] ${ts} ${method} ${outcome}${sid}${dur}
574
+ process.stderr.write(`[HTTP] ${ts} ${method} ${outcome}${st}${dur}
439
575
  `);
440
576
  }
441
- function logSessionLifecycle(event, sessionId, reason) {
442
- const ts = (/* @__PURE__ */ new Date()).toISOString();
443
- const r = reason ? ` reason=${reason}` : "";
444
- process.stderr.write(`[HTTP] ${ts} ${event} session=${sessionId}${r}
445
- `);
446
- }
447
- app.post("/mcp", mcpLimiter, async (req, res) => {
448
- const reqIp = req.ip ?? "unknown";
449
- if (checkAuthBlock(reqIp)) {
450
- res.status(429).json({ error: "Too many failed auth attempts. Try again later." });
451
- return;
452
- }
453
- const apiKey = extractBearerKey(req);
454
- if (!apiKey) {
455
- logRequest("POST", "auth_fail");
456
- recordAuthFailure(reqIp);
457
- send401(req, res);
458
- return;
459
- }
460
- const sessionId = req.headers["mcp-session-id"];
461
- const reqStart = Date.now();
462
- try {
463
- await runWithAuth({ apiKey }, async () => {
464
- if (sessionId && sessions.has(sessionId)) {
465
- const entry = sessions.get(sessionId);
466
- if (entry.keyHash !== hashKey(apiKey)) {
467
- res.status(403).json({
468
- jsonrpc: "2.0",
469
- error: { code: -32e3, message: "Session key mismatch" },
470
- id: null
471
- });
472
- return;
473
- }
474
- entry.lastAccess = Date.now();
475
- await entry.transport.handleRequest(req, res, req.body);
476
- logRequest("POST", "ok", sessionId, Date.now() - reqStart);
477
- } else if (!sessionId && isInitializeRequest(req.body)) {
478
- const keyH = hashKey(apiKey);
479
- let keySessionCount = 0;
480
- for (const entry of sessions.values()) {
481
- if (entry.keyHash === keyH) keySessionCount++;
482
- }
483
- if (keySessionCount >= MAX_SESSIONS_PER_KEY) {
484
- res.status(429).json({
485
- jsonrpc: "2.0",
486
- error: { code: -32e3, message: "Too many sessions for this API key" },
487
- id: null
488
- });
489
- return;
490
- }
491
- const transport = new StreamableHTTPServerTransport({
492
- sessionIdGenerator: () => randomUUID(),
493
- onsessioninitialized: (sid) => {
494
- sessions.set(sid, { transport, lastAccess: Date.now(), keyHash: keyH });
495
- logSessionLifecycle("session_created", sid);
496
- }
497
- });
498
- transport.onclose = () => {
499
- const sid = transport.sessionId;
500
- if (sid) {
501
- logSessionLifecycle("session_deleted", sid, "onclose");
502
- sessions.delete(sid);
503
- }
504
- };
505
- const server = createProductBrainServer();
506
- await server.connect(transport);
507
- await transport.handleRequest(req, res, req.body);
508
- logRequest("POST", "ok", transport.sessionId ?? void 0, Date.now() - reqStart);
509
- } else {
510
- process.stderr.write(
511
- `[HTTP] ${(/* @__PURE__ */ new Date()).toISOString()} session_invalid no valid session ID (client may have omitted Mcp-Session-Id)
512
- `
513
- );
514
- res.status(400).json({
515
- jsonrpc: "2.0",
516
- error: { code: -32e3, message: "Bad Request: no valid session ID provided" },
517
- id: null
518
- });
519
- }
520
- });
521
- } catch (err) {
522
- logRequest("POST", "error", sessionId, Date.now() - reqStart);
523
- if (!res.headersSent) {
524
- res.status(500).json({
525
- jsonrpc: "2.0",
526
- error: { code: -32603, message: "Internal server error" },
527
- id: null
528
- });
529
- }
530
- }
531
- });
532
- app.get("/mcp", mcpLimiter, async (req, res) => {
533
- const reqIp = req.ip ?? "unknown";
534
- if (checkAuthBlock(reqIp)) {
535
- res.status(429).json({ error: "Too many failed auth attempts. Try again later." });
577
+ function admit(req, res, auth) {
578
+ const nowTs = Date.now();
579
+ const lockout = authLockoutError(authFailures, auth, nowTs, req.body?.id ?? null);
580
+ if (lockout) {
581
+ send429(res, lockout);
536
582
  return;
537
583
  }
538
- const apiKey = extractBearerKey(req);
539
- if (!apiKey) {
540
- logRequest("GET", "auth_fail");
541
- recordAuthFailure(reqIp);
584
+ if (auth.status === "ok") return auth;
585
+ logRequest(req.method, "auth_fail");
586
+ if (auth.status === "rejected") recordAuthFailure(authFailures, auth.credentialId, nowTs);
587
+ send401(req, res);
588
+ }
589
+ function keyPasses(req, res, auth, check) {
590
+ const gate = keyVerdictGate(check.verdict, authFailures, auth.credentialId, Date.now());
591
+ if (gate === "unauthorized") {
592
+ logRequest(req.method, "auth_fail");
542
593
  send401(req, res);
543
- return;
594
+ return false;
544
595
  }
545
- const sessionId = req.headers["mcp-session-id"];
546
- if (!sessionId || !sessions.has(sessionId)) {
547
- res.status(400).send("Invalid or missing session ID");
548
- return;
596
+ if (gate === "unavailable") {
597
+ const built = buildUnavailableError(req.body?.id ?? null);
598
+ res.status(built.status).json(built.body);
599
+ return false;
549
600
  }
601
+ if (check.verdict === "ok" || check.verdict === "rate_limited") getKeyState(auth.apiKey).deploymentUrl = check.deploymentUrl;
602
+ return true;
603
+ }
604
+ async function serve(req, res, apiKey, handle) {
605
+ const reqStart = Date.now();
550
606
  try {
551
- await runWithAuth({ apiKey }, async () => {
552
- const entry = sessions.get(sessionId);
553
- if (entry.keyHash !== hashKey(apiKey)) {
554
- res.status(403).json({
555
- jsonrpc: "2.0",
556
- error: { code: -32e3, message: "Session key mismatch" },
557
- id: null
558
- });
559
- return;
560
- }
561
- entry.lastAccess = Date.now();
562
- await entry.transport.handleRequest(req, res);
563
- logRequest("GET", "ok", sessionId);
564
- });
607
+ await runWithAuth({ apiKey, requestId: randomUUID() }, handle);
608
+ logRequest(req.method, "ok", Date.now() - reqStart, res.statusCode);
565
609
  } catch {
566
- logRequest("GET", "error", sessionId);
610
+ logRequest(req.method, "error", Date.now() - reqStart);
611
+ if (!res.headersSent) res.status(500).json({ jsonrpc: "2.0", error: { code: -32603, message: "Internal server error" }, id: null });
567
612
  }
613
+ }
614
+ app.post("/mcp", ...mcpLimit, async (req, res) => {
615
+ const auth = admit(req, res, resolveBearerAuth(req.headers?.authorization));
616
+ if (!auth) return;
617
+ if (!keyPasses(req, res, auth, await checkKeyAgainstCandidates(keyCheckCandidates(), auth.apiKey, 5e3))) return;
618
+ await serve(req, res, auth.apiKey, () => serveNode(req, res, req.body));
568
619
  });
569
- app.delete("/mcp", mcpLimiter, async (req, res) => {
570
- const reqIp = req.ip ?? "unknown";
571
- if (checkAuthBlock(reqIp)) {
572
- res.status(429).json({ error: "Too many failed auth attempts. Try again later." });
573
- return;
574
- }
575
- const apiKey = extractBearerKey(req);
576
- if (!apiKey) {
577
- logRequest("DELETE", "auth_fail");
578
- recordAuthFailure(reqIp);
579
- send401(req, res);
580
- return;
581
- }
582
- const sessionId = req.headers["mcp-session-id"];
583
- if (!sessionId || !sessions.has(sessionId)) {
584
- res.status(400).send("Invalid or missing session ID");
585
- return;
586
- }
587
- try {
588
- await runWithAuth({ apiKey }, async () => {
589
- const entry = sessions.get(sessionId);
590
- if (entry.keyHash !== hashKey(apiKey)) {
591
- res.status(403).json({
592
- jsonrpc: "2.0",
593
- error: { code: -32e3, message: "Session key mismatch" },
594
- id: null
595
- });
596
- return;
597
- }
598
- await entry.transport.handleRequest(req, res);
599
- logRequest("DELETE", "ok", sessionId);
600
- });
601
- } catch {
602
- logRequest("DELETE", "error", sessionId);
603
- }
620
+ app.get("/mcp", ...mcpLimit, async (req, res) => {
621
+ const auth = admit(req, res, resolveBearerAuth(req.headers?.authorization));
622
+ if (auth) await serve(req, res, auth.apiKey, () => serveNode(req, res));
623
+ });
624
+ app.delete("/mcp", ...mcpLimit, async (req, res) => {
625
+ const auth = admit(req, res, resolveBearerAuth(req.headers?.authorization));
626
+ if (auth) await serve(req, res, auth.apiKey, () => serveNode(req, res));
604
627
  });
605
628
  process.on("unhandledRejection", (reason) => {
606
629
  const msg = reason instanceof Error ? reason.message : String(reason);
@@ -616,14 +639,8 @@ async function gracefulShutdown() {
616
639
  shuttingDown = true;
617
640
  setTimeout(() => process.exit(1), 3e3).unref();
618
641
  console.log("Shutting down...");
619
- for (const [, entry] of sessions) {
620
- await entry.transport.close().catch(() => {
621
- });
622
- }
623
- try {
624
- await shutdownAnalytics();
625
- } catch {
626
- }
642
+ await mcpHandler.close().catch(() => {
643
+ });
627
644
  process.exit(0);
628
645
  }
629
646
  var LISTEN_HOST = "0.0.0.0";