@productbrain/mcp 0.0.1-beta.149 → 0.0.1-beta.14908

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