@productbrain/mcp 0.0.1-beta.16 → 0.0.1-beta.16007

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,44 +1,474 @@
1
1
  import {
2
2
  SERVER_VERSION,
3
3
  createProductBrainServer
4
- } from "./chunk-5V4JXM4G.js";
4
+ } from "./chunk-ERVVKGIY.js";
5
5
  import {
6
+ DEFAULT_CLOUD_URL,
7
+ UNAVAILABLE,
8
+ appUrl,
6
9
  bootstrapHttp,
10
+ checkKeyAgainstCandidates,
11
+ getKeyState,
12
+ hashKey,
13
+ isApiKeyShaped,
14
+ parseFallbackUrls,
7
15
  runWithAuth
8
- } from "./chunk-47LO6K2R.js";
9
- import {
10
- initAnalytics,
11
- shutdownAnalytics
12
- } from "./chunk-XBMI6QHR.js";
16
+ } from "./chunk-TLR7A2WH.js";
13
17
 
14
18
  // src/http.ts
15
- import { createHash, randomUUID } from "crypto";
19
+ import { randomUUID } from "crypto";
16
20
  import express from "express";
17
- import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
18
- 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
19
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
20
445
  bootstrapHttp();
21
- initAnalytics();
22
- var PORT = parseInt(process.env.PORT ?? process.env.MCP_PORT ?? "3000", 10);
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
+ }
23
451
  function baseUrl(req) {
24
452
  const proto = req.headers["x-forwarded-proto"] ?? req.protocol ?? "http";
25
453
  const host = req.headers.host ?? `localhost:${PORT}`;
26
454
  return `${proto}://${host}`;
27
455
  }
28
456
  var app = express();
457
+ app.set("trust proxy", 1);
29
458
  app.use(express.json());
30
- 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 });
31
461
  app.use((_req, res, next) => {
32
462
  const origin = _req.headers.origin;
33
- if (!ALLOWED_ORIGINS || origin && ALLOWED_ORIGINS.includes(origin)) {
34
- res.setHeader("Access-Control-Allow-Origin", origin ?? "*");
463
+ if (origin && ALLOWED_ORIGINS.includes(origin)) {
464
+ res.setHeader("Access-Control-Allow-Origin", origin);
35
465
  }
36
466
  res.setHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS");
37
467
  res.setHeader(
38
468
  "Access-Control-Allow-Headers",
39
- "Content-Type, Authorization, Mcp-Session-Id, Last-Event-Id"
469
+ "Content-Type, Authorization, Mcp-Protocol-Version, Mcp-Method, Mcp-Name"
40
470
  );
41
- res.setHeader("Access-Control-Expose-Headers", "Mcp-Session-Id");
471
+ res.setHeader("Access-Control-Expose-Headers", "Retry-After");
42
472
  if (_req.method === "OPTIONS") {
43
473
  res.status(204).end();
44
474
  return;
@@ -63,193 +493,73 @@ app.get("/.well-known/oauth-authorization-server", (req, res) => {
63
493
  registration_endpoint: `${base}/register`,
64
494
  response_types_supported: ["code"],
65
495
  grant_types_supported: ["authorization_code"],
496
+ // TEN-4548: no refresh grant (lib/oauthAuthCode.ts tokenResponse)
66
497
  code_challenge_methods_supported: ["S256"],
67
498
  token_endpoint_auth_methods_supported: ["none"],
68
499
  scopes_supported: ["mcp:tools", "mcp:resources"]
69
500
  });
70
501
  });
71
- var registeredClients = /* @__PURE__ */ new Map();
502
+ var authLimiter = rateLimit2({
503
+ windowMs: 6e4,
504
+ max: 20,
505
+ standardHeaders: true,
506
+ legacyHeaders: false,
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
+ }
511
+ });
72
512
  app.post(
73
513
  "/register",
74
514
  express.json(),
75
515
  (req, res) => {
76
- const { redirect_uris, client_name } = req.body;
77
- if (!Array.isArray(redirect_uris) || redirect_uris.length === 0) {
78
- res.status(400).json({
79
- error: "invalid_client_metadata",
80
- error_description: "redirect_uris is required"
81
- });
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 });
82
521
  return;
83
522
  }
84
- const clientId = `pb_client_${randomUUID()}`;
85
- const client = {
86
- client_id: clientId,
87
- redirect_uris,
88
- client_name,
89
- registeredAt: Date.now()
90
- };
91
- 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);
92
526
  res.status(201).json({
93
527
  client_id: clientId,
94
528
  client_name: client_name ?? "MCP Client",
95
- redirect_uris,
529
+ redirect_uris: allowed,
96
530
  grant_types: ["authorization_code"],
97
531
  response_types: ["code"],
98
532
  token_endpoint_auth_method: "none"
99
533
  });
100
534
  }
101
535
  );
102
- var pendingCodes = /* @__PURE__ */ new Map();
536
+ app.get("/authorize", authLimiter, (req, res) => {
537
+ sendDoor(res, "GET /authorize", authorizeOutcome(req.query ?? {}, { allowlist: OAUTH_REDIRECT_ALLOWLIST, appUrl: appUrl() }));
538
+ });
103
539
  setInterval(() => {
104
540
  const now = Date.now();
105
- for (const [code, auth] of pendingCodes) {
106
- if (now > auth.expiresAt) pendingCodes.delete(code);
107
- }
108
- for (const [id, client] of registeredClients) {
109
- if (now - client.registeredAt > 24 * 60 * 6e4) registeredClients.delete(id);
110
- }
111
- }, 6e4);
112
- function esc(s) {
113
- return String(s ?? "").replace(
114
- /[&"<>]/g,
115
- (c) => ({ "&": "&amp;", '"': "&quot;", "<": "&lt;", ">": "&gt;" })[c]
116
- );
117
- }
118
- app.get("/authorize", (req, res) => {
119
- const { redirect_uri, code_challenge, code_challenge_method, state } = req.query;
120
- res.type("html").send(`<!DOCTYPE html>
121
- <html lang="en"><head>
122
- <meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
123
- <title>Authorize \u2014 Product Brain</title>
124
- <style>
125
- *{margin:0;padding:0;box-sizing:border-box}
126
- body{font-family:-apple-system,system-ui,sans-serif;background:#0a0a0a;color:#e5e5e5;
127
- display:flex;align-items:center;justify-content:center;min-height:100vh;padding:1rem}
128
- .card{background:#1a1a1a;border:1px solid #333;border-radius:12px;padding:2rem;max-width:400px;width:100%}
129
- h1{font-size:1.2rem;margin-bottom:.25rem}
130
- .sub{color:#999;font-size:.85rem;margin-bottom:1.5rem}
131
- label{display:block;font-size:.85rem;margin-bottom:.4rem;color:#ccc}
132
- input[type=password]{width:100%;padding:.6rem .75rem;background:#111;border:1px solid #444;
133
- border-radius:8px;color:#e5e5e5;font:.85rem/1.4 monospace}
134
- input:focus{outline:none;border-color:#7c3aed}
135
- button{width:100%;padding:.6rem;background:#7c3aed;color:#fff;border:none;
136
- border-radius:8px;font-size:.85rem;cursor:pointer;margin-top:1rem}
137
- button:hover{background:#6d28d9}
138
- .err{color:#ef4444;font-size:.8rem;margin-top:.5rem;display:none}
139
- </style></head><body>
140
- <div class="card">
141
- <h1>Product Brain</h1>
142
- <p class="sub">Enter your API key to connect Claude to your workspace.</p>
143
- <form method="POST" action="/authorize">
144
- <input type="hidden" name="redirect_uri" value="${esc(redirect_uri)}">
145
- <input type="hidden" name="code_challenge" value="${esc(code_challenge)}">
146
- <input type="hidden" name="code_challenge_method" value="${esc(code_challenge_method)}">
147
- <input type="hidden" name="state" value="${esc(state)}">
148
- <label for="k">API Key</label>
149
- <input type="password" id="k" name="api_key" placeholder="pb_sk_\u2026" required autofocus>
150
- <p class="err" id="e">Key must start with pb_sk_</p>
151
- <button type="submit">Authorize</button>
152
- </form>
153
- </div>
154
- <script>document.querySelector("form").onsubmit=function(e){
155
- if(!document.getElementById("k").value.startsWith("pb_sk_")){
156
- e.preventDefault();document.getElementById("e").style.display="block"}}</script>
157
- </body></html>`);
158
- });
159
- app.post(
160
- "/authorize",
161
- express.urlencoded({ extended: false }),
162
- (req, res) => {
163
- const { api_key, redirect_uri, code_challenge, state } = req.body;
164
- if (!api_key?.startsWith("pb_sk_")) {
165
- res.status(400).send("Invalid API key");
166
- return;
541
+ for (const [credentialId, rec] of authFailures) {
542
+ if (rec.blockedUntil < now && rec.firstFailure + AUTH_FAILURE_WINDOW_MS < now) {
543
+ authFailures.delete(credentialId);
167
544
  }
168
- const code = randomUUID();
169
- pendingCodes.set(code, {
170
- apiKey: api_key,
171
- codeChallenge: code_challenge,
172
- redirectUri: redirect_uri,
173
- expiresAt: Date.now() + 5 * 6e4
174
- });
175
- const url = new URL(redirect_uri);
176
- url.searchParams.set("code", code);
177
- if (state) url.searchParams.set("state", state);
178
- res.redirect(302, url.toString());
179
545
  }
180
- );
546
+ }, 6e4);
181
547
  app.post(
182
548
  "/oauth/token",
183
549
  express.urlencoded({ extended: false }),
184
550
  express.json(),
185
- (req, res) => {
186
- const { grant_type, code, code_verifier, redirect_uri } = req.body;
187
- if (grant_type !== "authorization_code") {
188
- res.status(400).json({ error: "unsupported_grant_type" });
189
- return;
190
- }
191
- const pending = pendingCodes.get(code);
192
- if (!pending || pending.redirectUri !== redirect_uri) {
193
- res.status(400).json({ error: "invalid_grant" });
194
- return;
195
- }
196
- const challenge = createHash("sha256").update(code_verifier ?? "").digest("base64url");
197
- if (challenge !== pending.codeChallenge) {
198
- pendingCodes.delete(code);
199
- res.status(400).json({
200
- error: "invalid_grant",
201
- error_description: "PKCE verification failed"
202
- });
203
- return;
204
- }
205
- pendingCodes.delete(code);
206
- res.json({
207
- access_token: pending.apiKey,
208
- token_type: "Bearer",
209
- expires_in: 3600
210
- });
551
+ async (req, res) => {
552
+ sendDoor(res, "POST /oauth/token", await exchangeOutcome(req.body ?? {}, { candidates: keyCheckCandidates() }));
211
553
  }
212
554
  );
213
- var mcpLimiter = rateLimit({
214
- windowMs: 6e4,
215
- max: 120,
216
- standardHeaders: true,
217
- legacyHeaders: false,
218
- message: { error: "Too many requests. Try again later." }
219
- });
555
+ var mcpLimit = mcpLimiters();
556
+ var authFailures = /* @__PURE__ */ new Map();
220
557
  app.get("/health", (_req, res) => {
221
558
  res.json({ status: "ok", version: SERVER_VERSION, transport: "http" });
222
559
  });
223
- var sessions = /* @__PURE__ */ new Map();
224
- var SESSION_TTL_MS = 30 * 60 * 1e3;
225
- var MAX_SESSIONS = 200;
226
- function evictStaleSessions() {
227
- const now = Date.now();
228
- for (const [id, entry] of sessions) {
229
- if (now - entry.lastAccess > SESSION_TTL_MS) {
230
- entry.transport.close().catch(() => {
231
- });
232
- sessions.delete(id);
233
- }
234
- }
235
- if (sessions.size > MAX_SESSIONS) {
236
- const sorted = [...sessions.entries()].sort(
237
- (a, b) => a[1].lastAccess - b[1].lastAccess
238
- );
239
- for (let i = 0; i < sorted.length - MAX_SESSIONS; i++) {
240
- sorted[i][1].transport.close().catch(() => {
241
- });
242
- sessions.delete(sorted[i][0]);
243
- }
244
- }
245
- }
246
- setInterval(evictStaleSessions, 6e4);
247
- function extractBearerKey(req) {
248
- const header = req.headers?.authorization;
249
- if (typeof header !== "string" || !header.startsWith("Bearer ")) return null;
250
- const token = header.slice(7).trim();
251
- return token.startsWith("pb_sk_") ? token : null;
252
- }
560
+ var mcpHandler = createMcpHandler(createProductBrainServer, { onerror: (err) => process.stderr.write(`[HTTP] handler_error ${err.message}
561
+ `) });
562
+ var serveNode = toNodeHandler(mcpHandler);
253
563
  function send401(req, res) {
254
564
  const base = baseUrl(req);
255
565
  res.status(401).set(
@@ -257,118 +567,92 @@ function send401(req, res) {
257
567
  `Bearer resource_metadata="${base}/.well-known/oauth-protected-resource"`
258
568
  ).json({ error: "unauthorized" });
259
569
  }
260
- function logRequest(method, outcome, sessionId) {
570
+ function logRequest(method, outcome, durationMs, status) {
261
571
  const ts = (/* @__PURE__ */ new Date()).toISOString();
262
- const sid = sessionId ? ` session=${sessionId}` : "";
263
- process.stderr.write(`[HTTP] ${ts} ${method} ${outcome}${sid}
572
+ const st = status != null ? ` status=${status}` : "";
573
+ const dur = durationMs != null ? ` duration=${durationMs}ms` : "";
574
+ process.stderr.write(`[HTTP] ${ts} ${method} ${outcome}${st}${dur}
264
575
  `);
265
576
  }
266
- app.post("/mcp", mcpLimiter, async (req, res) => {
267
- const apiKey = extractBearerKey(req);
268
- if (!apiKey) {
269
- logRequest("POST", "auth_fail");
270
- send401(req, res);
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);
271
582
  return;
272
583
  }
273
- const sessionId = req.headers["mcp-session-id"];
274
- try {
275
- await runWithAuth({ apiKey }, async () => {
276
- if (sessionId && sessions.has(sessionId)) {
277
- const entry = sessions.get(sessionId);
278
- entry.lastAccess = Date.now();
279
- await entry.transport.handleRequest(req, res, req.body);
280
- logRequest("POST", "ok", sessionId);
281
- } else if (!sessionId && isInitializeRequest(req.body)) {
282
- const transport = new StreamableHTTPServerTransport({
283
- sessionIdGenerator: () => randomUUID(),
284
- onsessioninitialized: (sid) => {
285
- sessions.set(sid, { transport, lastAccess: Date.now() });
286
- logRequest("POST", "ok", sid);
287
- }
288
- });
289
- transport.onclose = () => {
290
- const sid = transport.sessionId;
291
- if (sid) sessions.delete(sid);
292
- };
293
- const server = createProductBrainServer();
294
- await server.connect(transport);
295
- await transport.handleRequest(req, res, req.body);
296
- } else {
297
- res.status(400).json({
298
- jsonrpc: "2.0",
299
- error: { code: -32e3, message: "Bad Request: no valid session ID provided" },
300
- id: null
301
- });
302
- }
303
- });
304
- } catch (err) {
305
- logRequest("POST", "error", sessionId);
306
- if (!res.headersSent) {
307
- res.status(500).json({
308
- jsonrpc: "2.0",
309
- error: { code: -32603, message: "Internal server error" },
310
- id: null
311
- });
312
- }
313
- }
314
- });
315
- app.get("/mcp", mcpLimiter, async (req, res) => {
316
- const apiKey = extractBearerKey(req);
317
- if (!apiKey) {
318
- logRequest("GET", "auth_fail");
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");
319
593
  send401(req, res);
320
- return;
594
+ return false;
321
595
  }
322
- const sessionId = req.headers["mcp-session-id"];
323
- if (!sessionId || !sessions.has(sessionId)) {
324
- res.status(400).send("Invalid or missing session ID");
325
- return;
596
+ if (gate === "unavailable") {
597
+ const built = buildUnavailableError(req.body?.id ?? null);
598
+ res.status(built.status).json(built.body);
599
+ return false;
326
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();
327
606
  try {
328
- await runWithAuth({ apiKey }, async () => {
329
- const entry = sessions.get(sessionId);
330
- entry.lastAccess = Date.now();
331
- await entry.transport.handleRequest(req, res);
332
- logRequest("GET", "ok", sessionId);
333
- });
607
+ await runWithAuth({ apiKey, requestId: randomUUID() }, handle);
608
+ logRequest(req.method, "ok", Date.now() - reqStart, res.statusCode);
334
609
  } catch {
335
- 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 });
336
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));
337
619
  });
338
- app.delete("/mcp", mcpLimiter, async (req, res) => {
339
- const apiKey = extractBearerKey(req);
340
- if (!apiKey) {
341
- logRequest("DELETE", "auth_fail");
342
- send401(req, res);
343
- return;
344
- }
345
- const sessionId = req.headers["mcp-session-id"];
346
- if (!sessionId || !sessions.has(sessionId)) {
347
- res.status(400).send("Invalid or missing session ID");
348
- return;
349
- }
350
- try {
351
- await runWithAuth({ apiKey }, async () => {
352
- const entry = sessions.get(sessionId);
353
- await entry.transport.handleRequest(req, res);
354
- logRequest("DELETE", "ok", sessionId);
355
- });
356
- } catch {
357
- logRequest("DELETE", "error", sessionId);
358
- }
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));
359
627
  });
360
- app.listen(PORT, "0.0.0.0", () => {
361
- console.log(`Product Brain MCP HTTP server v${SERVER_VERSION} listening on port ${PORT}`);
628
+ process.on("unhandledRejection", (reason) => {
629
+ const msg = reason instanceof Error ? reason.message : String(reason);
630
+ console.error(`[MCP HTTP] Unhandled rejection: ${msg}`);
362
631
  });
632
+ process.on("uncaughtException", (err) => {
633
+ console.error(`[MCP HTTP] Uncaught exception: ${err.stack ?? err.message}`);
634
+ gracefulShutdown();
635
+ });
636
+ var shuttingDown = false;
363
637
  async function gracefulShutdown() {
638
+ if (shuttingDown) return;
639
+ shuttingDown = true;
640
+ setTimeout(() => process.exit(1), 3e3).unref();
364
641
  console.log("Shutting down...");
365
- for (const [, entry] of sessions) {
366
- await entry.transport.close().catch(() => {
367
- });
368
- }
369
- await shutdownAnalytics();
642
+ await mcpHandler.close().catch(() => {
643
+ });
370
644
  process.exit(0);
371
645
  }
646
+ var LISTEN_HOST = "0.0.0.0";
647
+ var httpServer = app.listen(PORT, LISTEN_HOST, () => {
648
+ console.log(
649
+ `Product Brain MCP HTTP server v${SERVER_VERSION} listening on ${LISTEN_HOST}:${PORT}`
650
+ );
651
+ });
652
+ httpServer.on("error", (err) => {
653
+ console.error(`[MCP HTTP] Server error: ${err.message}`);
654
+ process.exit(1);
655
+ });
372
656
  process.on("SIGINT", gracefulShutdown);
373
657
  process.on("SIGTERM", gracefulShutdown);
374
658
  //# sourceMappingURL=http.js.map