@productbrain/mcp 0.0.1-beta.914 → 0.0.1-beta.9141

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,18 +1,20 @@
1
1
  import {
2
- DEFAULT_CLOUD_URL,
3
2
  SERVER_VERSION,
4
- bootstrapHttp,
5
3
  createProductBrainServer,
6
- getKeyState,
7
- hashKey,
8
- initFeatureFlags,
9
- runWithAuth
10
- } from "./chunk-7TU5QHN7.js";
4
+ initFeatureFlags
5
+ } from "./chunk-GGI6WIZW.js";
11
6
  import {
7
+ DEFAULT_CLOUD_URL,
8
+ apiKeysUrl,
9
+ bootstrapHttp,
10
+ forgetStreamLifecycle,
11
+ getKeyState,
12
12
  getPostHogClient,
13
+ hashKey,
13
14
  initAnalytics,
15
+ runWithAuth,
14
16
  shutdownAnalytics
15
- } from "./chunk-YMF3IQ5E.js";
17
+ } from "./chunk-5VJTLT2S.js";
16
18
 
17
19
  // src/http.ts
18
20
  import { createHash, randomUUID as randomUUID2 } from "crypto";
@@ -111,6 +113,232 @@ function verifyRefreshToken(token) {
111
113
  return { apiKey: payload.k };
112
114
  }
113
115
 
116
+ // src/sessionCap.ts
117
+ function planKeyAdmission(sessions2, keyHash, cap, now, opts) {
118
+ if (cap < 1) {
119
+ throw new RangeError(`cap must be >= 1, got ${cap}`);
120
+ }
121
+ const { ttlMs, graceMs } = opts;
122
+ const isProtected = (s) => s.inFlight > 0 || now - s.lastAccess < graceMs;
123
+ const keyEntries = [];
124
+ for (const [id, session] of sessions2) {
125
+ if (session.keyHash === keyHash) {
126
+ keyEntries.push([id, session]);
127
+ }
128
+ }
129
+ const evictSet = /* @__PURE__ */ new Set();
130
+ for (const [id, session] of keyEntries) {
131
+ if (!isProtected(session) && now - session.lastAccess >= ttlMs) {
132
+ evictSet.add(id);
133
+ }
134
+ }
135
+ let survivors = keyEntries.filter(([id]) => !evictSet.has(id));
136
+ if (survivors.length >= cap) {
137
+ const idleSurvivors = survivors.filter(([, s]) => !isProtected(s)).sort(([, a], [, b]) => a.lastAccess - b.lastAccess);
138
+ for (const [id] of idleSurvivors) {
139
+ if (survivors.length < cap) break;
140
+ evictSet.add(id);
141
+ survivors = survivors.filter(([sid]) => sid !== id);
142
+ }
143
+ }
144
+ const evict = Array.from(evictSet);
145
+ const admit = survivors.length < cap;
146
+ let retryAfterSeconds = 0;
147
+ let retryIsPoll = false;
148
+ if (!admit) {
149
+ const graceBlockers = survivors.filter(([, s]) => s.inFlight === 0);
150
+ if (graceBlockers.length > 0) {
151
+ const minLastAccess = Math.min(...graceBlockers.map(([, s]) => s.lastAccess));
152
+ const msRemaining = graceMs - (now - minLastAccess);
153
+ retryAfterSeconds = Math.max(1, Math.ceil(msRemaining / 1e3));
154
+ } else {
155
+ retryAfterSeconds = 5;
156
+ retryIsPoll = true;
157
+ }
158
+ }
159
+ return { evict, admit, retryAfterSeconds, retryIsPoll };
160
+ }
161
+ function countKeySessions(sessions2, keyHash) {
162
+ let count = 0;
163
+ for (const session of sessions2.values()) {
164
+ if (session.keyHash === keyHash) count++;
165
+ }
166
+ return count;
167
+ }
168
+
169
+ // src/httpErrors.ts
170
+ function clampSeconds(s) {
171
+ return Math.max(0, Math.round(s));
172
+ }
173
+ function build(reason, message, p) {
174
+ const seconds = clampSeconds(p.retryAfterSeconds);
175
+ return {
176
+ status: 429,
177
+ headers: { "Retry-After": String(seconds) },
178
+ body: {
179
+ jsonrpc: "2.0",
180
+ id: p.id ?? null,
181
+ error: {
182
+ code: -32e3,
183
+ message,
184
+ data: {
185
+ reason,
186
+ retryAfterSeconds: seconds,
187
+ limit: p.limit,
188
+ current: p.current
189
+ }
190
+ }
191
+ }
192
+ };
193
+ }
194
+ function buildRateLimitError(p) {
195
+ const seconds = clampSeconds(p.retryAfterSeconds);
196
+ return build(
197
+ "rate_limited",
198
+ `Too many requests \u2014 retry after ${seconds} s.`,
199
+ p
200
+ );
201
+ }
202
+ function buildAuthLockoutError(p) {
203
+ const seconds = clampSeconds(p.retryAfterSeconds);
204
+ return build(
205
+ "auth_lockout",
206
+ `Too many failed auth attempts \u2014 locked out, retry after ${seconds} s.`,
207
+ p
208
+ );
209
+ }
210
+ function buildSessionCapError(p) {
211
+ const seconds = clampSeconds(p.retryAfterSeconds);
212
+ const message = p.poll ? "Server busy \u2014 all sessions active; retry shortly." : `Too many active sessions for this key \u2014 retry after ${seconds} s.`;
213
+ return build("session_cap", message, p);
214
+ }
215
+ function send429(res, built) {
216
+ if (res.headersSent) return;
217
+ for (const [k, v] of Object.entries(built.headers)) {
218
+ res.setHeader(k, v);
219
+ }
220
+ res.status(built.status).json(built.body);
221
+ }
222
+
223
+ // src/authLockout.ts
224
+ var AUTH_FAILURE_MAX = 10;
225
+ var AUTH_FAILURE_WINDOW_MS = 5 * 6e4;
226
+ var AUTH_BLOCK_DURATION_MS = 15 * 6e4;
227
+ var MAX_AUTH_FAILURE_ENTRIES = 1e4;
228
+ function resolveBearerAuth(authorizationHeader, accessTokens2, now, accessTokenTtlMs) {
229
+ if (typeof authorizationHeader !== "string" || authorizationHeader.trim() === "") {
230
+ return { status: "absent" };
231
+ }
232
+ if (!authorizationHeader.startsWith("Bearer ")) {
233
+ return { status: "rejected" };
234
+ }
235
+ const token = authorizationHeader.slice(7).trim();
236
+ if (token === "") {
237
+ return { status: "rejected" };
238
+ }
239
+ if (token.startsWith("pb_sk_")) {
240
+ return { status: "ok", apiKey: token };
241
+ }
242
+ if (token.startsWith("pb_at_")) {
243
+ const entry = accessTokens2.get(token);
244
+ if (!entry) return { status: "rejected" };
245
+ if (now - entry.createdAt > accessTokenTtlMs) {
246
+ accessTokens2.delete(token);
247
+ return { status: "rejected" };
248
+ }
249
+ return { status: "ok", apiKey: entry.apiKey };
250
+ }
251
+ return { status: "rejected" };
252
+ }
253
+ function checkAuthBlock(failures, ip, now) {
254
+ const rec = failures.get(ip);
255
+ if (!rec) return false;
256
+ return rec.blockedUntil > now;
257
+ }
258
+ function recordAuthFailure(failures, ip, now) {
259
+ const rec = failures.get(ip);
260
+ if (!rec) {
261
+ failures.set(ip, { count: 1, firstFailure: now, blockedUntil: 0 });
262
+ return;
263
+ }
264
+ if (now - rec.firstFailure > AUTH_FAILURE_WINDOW_MS) {
265
+ rec.count = 1;
266
+ rec.firstFailure = now;
267
+ rec.blockedUntil = 0;
268
+ } else {
269
+ rec.count++;
270
+ if (rec.count >= AUTH_FAILURE_MAX) {
271
+ rec.blockedUntil = now + AUTH_BLOCK_DURATION_MS;
272
+ }
273
+ }
274
+ }
275
+
276
+ // src/lib/oauthRedirectAllowlist.ts
277
+ var DEFAULT_OAUTH_REDIRECT_HOSTS = [
278
+ "claude.ai",
279
+ "claude.com",
280
+ "chatgpt.com"
281
+ ];
282
+ var LOOPBACK_HOSTS = ["localhost", "127.0.0.1", "[::1]"];
283
+ var MAX_REDIRECT_URI_LENGTH = 2048;
284
+ var MAX_REGISTRATION_REDIRECTS = 10;
285
+ function parseHostAllowlist(raw) {
286
+ if (!raw) return [];
287
+ const hosts = [];
288
+ for (const part of raw.split(",")) {
289
+ const trimmed = part.trim();
290
+ if (!trimmed) continue;
291
+ try {
292
+ const asUrl = trimmed.includes("://") ? new URL(trimmed) : new URL(`https://${trimmed}`);
293
+ const host = asUrl.hostname.toLowerCase();
294
+ if (host) hosts.push(host);
295
+ } catch {
296
+ }
297
+ }
298
+ return hosts;
299
+ }
300
+ function resolveOAuthRedirectHosts(opts = {}) {
301
+ const hosts = new Set(DEFAULT_OAUTH_REDIRECT_HOSTS);
302
+ for (const h of parseHostAllowlist(opts.explicitAllowlist)) hosts.add(h);
303
+ return [...hosts];
304
+ }
305
+ function checkRedirectUri(redirectUri, allowedHosts) {
306
+ if (typeof redirectUri !== "string" || redirectUri.length === 0) {
307
+ return "redirect_uri is required";
308
+ }
309
+ if (redirectUri.length > MAX_REDIRECT_URI_LENGTH) {
310
+ return `redirect_uri is longer than ${MAX_REDIRECT_URI_LENGTH} characters`;
311
+ }
312
+ let url;
313
+ try {
314
+ url = new URL(redirectUri);
315
+ } catch {
316
+ return "redirect_uri is not a valid absolute URL";
317
+ }
318
+ if (url.username || url.password) return "redirect_uri must not contain credentials";
319
+ if (url.hash) return "redirect_uri must not contain a fragment";
320
+ const host = url.hostname.toLowerCase();
321
+ if (url.protocol === "http:") {
322
+ return LOOPBACK_HOSTS.includes(host) ? null : "redirect_uri must use https (http is allowed only for localhost, 127.0.0.1 or [::1])";
323
+ }
324
+ if (url.protocol === "https:") {
325
+ if (url.port && url.port !== "443") return "redirect_uri must use the default https port (443)";
326
+ return allowedHosts.includes(host) ? null : "redirect_uri host is not allowed (an operator can add it with OAUTH_REDIRECT_HOST_ALLOWLIST)";
327
+ }
328
+ return "redirect_uri scheme is not allowed (use https, or http on loopback)";
329
+ }
330
+ function checkRegistrationRedirects(redirectUris, allowedHosts) {
331
+ if (!Array.isArray(redirectUris) || redirectUris.length === 0) return "redirect_uris is required";
332
+ if (redirectUris.length > MAX_REGISTRATION_REDIRECTS) {
333
+ return `redirect_uris may hold at most ${MAX_REGISTRATION_REDIRECTS} entries`;
334
+ }
335
+ for (const uri of redirectUris) {
336
+ const reason = checkRedirectUri(uri, allowedHosts);
337
+ if (reason) return reason;
338
+ }
339
+ return null;
340
+ }
341
+
114
342
  // src/http.ts
115
343
  bootstrapHttp();
116
344
  initAnalytics();
@@ -125,6 +353,7 @@ var app = express();
125
353
  app.set("trust proxy", 1);
126
354
  app.use(express.json());
127
355
  var ALLOWED_ORIGINS = (process.env.CORS_ORIGINS ?? "https://claude.ai").split(",").map((o) => o.trim()).filter(Boolean);
356
+ var OAUTH_REDIRECT_HOSTS = resolveOAuthRedirectHosts({ explicitAllowlist: process.env.OAUTH_REDIRECT_HOST_ALLOWLIST });
128
357
  app.use((_req, res, next) => {
129
358
  const origin = _req.headers.origin;
130
359
  if (origin && ALLOWED_ORIGINS.includes(origin)) {
@@ -135,7 +364,7 @@ app.use((_req, res, next) => {
135
364
  "Access-Control-Allow-Headers",
136
365
  "Content-Type, Authorization, Mcp-Session-Id, Last-Event-Id"
137
366
  );
138
- res.setHeader("Access-Control-Expose-Headers", "Mcp-Session-Id");
367
+ res.setHeader("Access-Control-Expose-Headers", "Mcp-Session-Id, Retry-After");
139
368
  if (_req.method === "OPTIONS") {
140
369
  res.status(204).end();
141
370
  return;
@@ -187,11 +416,9 @@ app.post(
187
416
  return;
188
417
  }
189
418
  const { redirect_uris, client_name } = req.body;
190
- if (!Array.isArray(redirect_uris) || redirect_uris.length === 0) {
191
- res.status(400).json({
192
- error: "invalid_client_metadata",
193
- error_description: "redirect_uris is required"
194
- });
419
+ const refusal = checkRegistrationRedirects(redirect_uris, OAUTH_REDIRECT_HOSTS);
420
+ if (refusal) {
421
+ res.status(400).json({ error: "invalid_redirect_uri", error_description: refusal });
195
422
  return;
196
423
  }
197
424
  const clientId = `pb_client_${randomUUID2()}`;
@@ -609,7 +836,7 @@ function errorPanelInner(title, trustedDetailHtml, retryUrl) {
609
836
  <p class="err-msg" data-field="err-msg">${trustedDetailHtml}</p>
610
837
  <div class="err-actions">
611
838
  <a href="${esc(retryUrl)}" class="btn-secondary" data-retry-link>&larr; Try again</a>
612
- <a href="https://productbrain.io" target="_blank" rel="noopener noreferrer" class="btn-secondary">Get an API key &rarr;</a>
839
+ <a href="${esc(apiKeysUrl())}" target="_blank" rel="noopener noreferrer" class="btn-secondary">Get an API key &rarr;</a>
613
840
  </div>`;
614
841
  }
615
842
  var cmdScript = `
@@ -657,7 +884,7 @@ function authorizeFormPage(params) {
657
884
  <div class="hint" id="hint" hidden></div>
658
885
  <button type="submit" class="btn-primary" id="sb" disabled><span id="bt">Connect</span></button>
659
886
  </form>
660
- <div class="small-link"><a href="https://productbrain.io" target="_blank" rel="noopener noreferrer">No key? Generate one &rarr;</a></div>
887
+ <div class="small-link"><a href="${esc(apiKeysUrl())}" target="_blank" rel="noopener noreferrer">No key? Generate one &rarr;</a></div>
661
888
  </div>
662
889
 
663
890
  <!-- \u2500\u2500\u2500 VERIFYING \u2500\u2500\u2500 -->
@@ -796,6 +1023,11 @@ ${errorPanelInner(title, trustedDetailHtml, retryUrl)}
796
1023
  }
797
1024
  app.get("/authorize", authLimiter, (req, res) => {
798
1025
  const { redirect_uri, code_challenge, code_challenge_method, state, client_id } = req.query;
1026
+ const refusal = checkRedirectUri(redirect_uri, OAUTH_REDIRECT_HOSTS);
1027
+ if (refusal) {
1028
+ res.status(400).json({ error: "invalid_request", error_description: refusal });
1029
+ return;
1030
+ }
799
1031
  const cid = String(client_id ?? "");
800
1032
  const clientName = cid && registeredClients.has(cid) ? registeredClients.get(cid).client_name : void 0;
801
1033
  res.type("html").send(authorizeFormPage({
@@ -837,28 +1069,22 @@ app.post(
837
1069
  return;
838
1070
  }
839
1071
  if (!client_id) {
840
- res.status(400).json({
841
- error: "invalid_request",
842
- error_description: "client_id is required"
843
- });
1072
+ res.status(400).json({ error: "invalid_request", error_description: "client_id is required" });
1073
+ return;
1074
+ }
1075
+ const redirectRefusal = checkRedirectUri(redirect_uri, OAUTH_REDIRECT_HOSTS);
1076
+ if (redirectRefusal) {
1077
+ res.status(400).json({ error: "invalid_request", error_description: redirectRefusal });
844
1078
  return;
845
1079
  }
846
1080
  if (!registeredClients.has(client_id)) {
847
- if (typeof redirect_uri === "string" && redirect_uri.startsWith("https://")) {
848
- registeredClients.set(client_id, {
849
- client_id,
850
- redirect_uris: [redirect_uri],
851
- registeredAt: Date.now()
852
- });
853
- process.stderr.write(`[authorize] auto-re-registered stale client_id after restart
854
- `);
855
- } else {
856
- res.status(400).json({
857
- error: "invalid_request",
858
- error_description: "Unknown client_id and redirect_uri is not a valid https URL"
859
- });
1081
+ if (registeredClients.size >= MAX_REGISTERED_CLIENTS) {
1082
+ res.status(503).json({ error: "server_error", error_description: "Registration limit reached. Try again later." });
860
1083
  return;
861
1084
  }
1085
+ registeredClients.set(client_id, { client_id, redirect_uris: [redirect_uri], registeredAt: Date.now() });
1086
+ process.stderr.write(`[authorize] auto-re-registered stale client_id after restart
1087
+ `);
862
1088
  }
863
1089
  const client = registeredClients.get(client_id);
864
1090
  if (!client.redirect_uris.includes(redirect_uri)) {
@@ -875,6 +1101,7 @@ app.post(
875
1101
  const candidates = [primaryUrl, ...fallbackUrls];
876
1102
  let foundUrl;
877
1103
  let anyDefinitiveReject = false;
1104
+ let rateLimitedRetryAfter;
878
1105
  for (const url2 of candidates) {
879
1106
  let checkData = null;
880
1107
  try {
@@ -892,9 +1119,21 @@ app.post(
892
1119
  foundUrl = checkData.deploymentUrl ?? url2;
893
1120
  break;
894
1121
  }
1122
+ if (checkData.error === "rate_limited") {
1123
+ rateLimitedRetryAfter = checkData.retryAfterSeconds;
1124
+ continue;
1125
+ }
895
1126
  anyDefinitiveReject = true;
896
1127
  }
897
1128
  if (!foundUrl) {
1129
+ if (rateLimitedRetryAfter != null && !anyDefinitiveReject) {
1130
+ sendError(
1131
+ "Rate limited",
1132
+ `This API key is valid but temporarily rate limited. Try again in ${rateLimitedRetryAfter}s.`,
1133
+ 429
1134
+ );
1135
+ return;
1136
+ }
898
1137
  if (anyDefinitiveReject) {
899
1138
  sendError(
900
1139
  "Key not recognized",
@@ -985,85 +1224,63 @@ var mcpLimiter = rateLimit({
985
1224
  max: 120,
986
1225
  standardHeaders: true,
987
1226
  legacyHeaders: false,
988
- message: { error: "Too many requests. Try again later." }
1227
+ handler: (req, res) => {
1228
+ const r = req.rateLimit;
1229
+ const reset = r?.resetTime?.getTime?.() ?? Date.now() + 6e4;
1230
+ send429(res, buildRateLimitError({
1231
+ retryAfterSeconds: Math.max(1, Math.ceil((reset - Date.now()) / 1e3)),
1232
+ limit: r?.limit ?? 120,
1233
+ current: r?.used ?? 0,
1234
+ id: req.body?.id ?? null
1235
+ // mirror the JSON-RPC id when a POST body is present
1236
+ }));
1237
+ }
989
1238
  });
990
1239
  var authFailures = /* @__PURE__ */ new Map();
991
- var AUTH_FAILURE_MAX = 10;
992
- var AUTH_FAILURE_WINDOW_MS = 5 * 6e4;
993
- var AUTH_BLOCK_DURATION_MS = 15 * 6e4;
994
- var MAX_AUTH_FAILURE_ENTRIES = 1e4;
995
- function checkAuthBlock(ip) {
996
- const rec = authFailures.get(ip);
997
- if (!rec) return false;
998
- return rec.blockedUntil > Date.now();
999
- }
1000
- function recordAuthFailure(ip) {
1001
- const now = Date.now();
1002
- const rec = authFailures.get(ip);
1003
- if (!rec) {
1004
- authFailures.set(ip, { count: 1, firstFailure: now, blockedUntil: 0 });
1005
- return;
1006
- }
1007
- if (now - rec.firstFailure > AUTH_FAILURE_WINDOW_MS) {
1008
- rec.count = 1;
1009
- rec.firstFailure = now;
1010
- rec.blockedUntil = 0;
1011
- } else {
1012
- rec.count++;
1013
- if (rec.count >= AUTH_FAILURE_MAX) {
1014
- rec.blockedUntil = now + AUTH_BLOCK_DURATION_MS;
1015
- }
1016
- }
1017
- }
1018
1240
  app.get("/health", (_req, res) => {
1019
1241
  res.json({ status: "ok", version: SERVER_VERSION, transport: "http" });
1020
1242
  });
1021
1243
  var sessions = /* @__PURE__ */ new Map();
1022
1244
  var SESSION_TTL_MS = 30 * 60 * 1e3;
1023
1245
  var MAX_SESSIONS = 200;
1024
- var MAX_SESSIONS_PER_KEY = 5;
1246
+ var EVICT_GRACE_MS = 6e4;
1247
+ var MAX_SESSIONS_PER_KEY = Math.max(
1248
+ 1,
1249
+ Math.min(MAX_SESSIONS - 1, Number(process.env.MCP_MAX_SESSIONS_PER_KEY) || 25)
1250
+ );
1025
1251
  function evictStaleSessions() {
1026
1252
  const now = Date.now();
1027
1253
  for (const [id, entry] of sessions) {
1028
1254
  if (now - entry.lastAccess > SESSION_TTL_MS) {
1029
- logSessionLifecycle("session_deleted", id, "ttl");
1255
+ logSessionLifecycle(
1256
+ "session_deleted",
1257
+ id,
1258
+ entry.inFlight > 0 ? "inflight_leak" : "ttl"
1259
+ );
1030
1260
  entry.transport.close().catch(() => {
1031
1261
  });
1032
1262
  sessions.delete(id);
1033
1263
  }
1034
1264
  }
1035
1265
  if (sessions.size > MAX_SESSIONS) {
1036
- const sorted = [...sessions.entries()].sort(
1037
- (a, b) => a[1].lastAccess - b[1].lastAccess
1038
- );
1039
- for (let i = 0; i < sorted.length - MAX_SESSIONS; i++) {
1266
+ const sorted = [...sessions.entries()].filter(([, e]) => e.inFlight === 0).sort((a, b) => a[1].lastAccess - b[1].lastAccess);
1267
+ const overflow = sessions.size - MAX_SESSIONS;
1268
+ for (let i = 0; i < Math.min(overflow, sorted.length); i++) {
1040
1269
  logSessionLifecycle("session_deleted", sorted[i][0], "eviction");
1041
1270
  sorted[i][1].transport.close().catch(() => {
1042
1271
  });
1043
1272
  sessions.delete(sorted[i][0]);
1044
1273
  }
1045
- }
1046
- }
1047
- setInterval(evictStaleSessions, 6e4);
1048
- function extractBearerKey(req) {
1049
- const header = req.headers?.authorization;
1050
- if (typeof header !== "string" || !header.startsWith("Bearer ")) return null;
1051
- const token = header.slice(7).trim();
1052
- if (token.startsWith("pb_sk_")) {
1053
- return token;
1054
- }
1055
- if (token.startsWith("pb_at_")) {
1056
- const entry = accessTokens.get(token);
1057
- if (!entry) return null;
1058
- const now = Date.now();
1059
- if (now - entry.createdAt > ACCESS_TOKEN_TTL_MS) {
1060
- accessTokens.delete(token);
1061
- return null;
1274
+ if (sessions.size > MAX_SESSIONS) {
1275
+ const ts = (/* @__PURE__ */ new Date()).toISOString();
1276
+ process.stderr.write(
1277
+ `[HTTP] ${ts} session_cap_breach size=${sessions.size} max=${MAX_SESSIONS} reason=all_inflight (no idle sessions to evict; TTL backstop will reclaim)
1278
+ `
1279
+ );
1062
1280
  }
1063
- return entry.apiKey;
1064
1281
  }
1065
- return null;
1066
1282
  }
1283
+ setInterval(evictStaleSessions, 6e4);
1067
1284
  function send401(req, res) {
1068
1285
  const base = baseUrl(req);
1069
1286
  res.status(401).set(
@@ -1086,21 +1303,25 @@ function logSessionLifecycle(event, sessionId, reason) {
1086
1303
  }
1087
1304
  app.post("/mcp", mcpLimiter, async (req, res) => {
1088
1305
  const reqIp = req.ip ?? "unknown";
1089
- if (checkAuthBlock(reqIp)) {
1090
- res.status(429).json({ error: "Too many failed auth attempts. Try again later." });
1306
+ const nowTs = Date.now();
1307
+ if (checkAuthBlock(authFailures, reqIp, nowTs)) {
1308
+ const rec = authFailures.get(reqIp);
1309
+ const retryAfterSeconds = rec ? Math.max(0, Math.ceil((rec.blockedUntil - nowTs) / 1e3)) : 0;
1310
+ send429(res, buildAuthLockoutError({ retryAfterSeconds, limit: AUTH_FAILURE_MAX, current: rec?.count ?? AUTH_FAILURE_MAX, id: req.body?.id ?? null }));
1091
1311
  return;
1092
1312
  }
1093
- const apiKey = extractBearerKey(req);
1094
- if (!apiKey) {
1313
+ const auth = resolveBearerAuth(req.headers?.authorization, accessTokens, nowTs, ACCESS_TOKEN_TTL_MS);
1314
+ if (auth.status !== "ok") {
1095
1315
  logRequest("POST", "auth_fail");
1096
- recordAuthFailure(reqIp);
1316
+ if (auth.status === "rejected") recordAuthFailure(authFailures, reqIp, nowTs);
1097
1317
  send401(req, res);
1098
1318
  return;
1099
1319
  }
1320
+ const apiKey = auth.apiKey;
1100
1321
  const sessionId = req.headers["mcp-session-id"];
1101
1322
  const reqStart = Date.now();
1102
1323
  try {
1103
- await runWithAuth({ apiKey }, async () => {
1324
+ await runWithAuth({ apiKey, mcpSessionId: sessionId }, async () => {
1104
1325
  if (sessionId && sessions.has(sessionId)) {
1105
1326
  const entry = sessions.get(sessionId);
1106
1327
  if (entry.keyHash !== hashKey(apiKey)) {
@@ -1111,41 +1332,82 @@ app.post("/mcp", mcpLimiter, async (req, res) => {
1111
1332
  });
1112
1333
  return;
1113
1334
  }
1114
- entry.lastAccess = Date.now();
1115
- await entry.transport.handleRequest(req, res, req.body);
1116
- logRequest("POST", "ok", sessionId, Date.now() - reqStart);
1335
+ try {
1336
+ entry.inFlight++;
1337
+ entry.lastAccess = Date.now();
1338
+ await entry.transport.handleRequest(req, res, req.body);
1339
+ logRequest("POST", "ok", sessionId, Date.now() - reqStart);
1340
+ } finally {
1341
+ entry.inFlight--;
1342
+ entry.lastAccess = Date.now();
1343
+ }
1117
1344
  } else if (!sessionId && isInitializeRequest(req.body)) {
1118
1345
  const keyH = hashKey(apiKey);
1119
- let keySessionCount = 0;
1120
- for (const entry of sessions.values()) {
1121
- if (entry.keyHash === keyH) keySessionCount++;
1122
- }
1123
- if (keySessionCount >= MAX_SESSIONS_PER_KEY) {
1124
- res.status(429).json({
1125
- jsonrpc: "2.0",
1126
- error: { code: -32e3, message: "Too many sessions for this API key" },
1127
- id: null
1346
+ const plan = planKeyAdmission(
1347
+ sessions,
1348
+ keyH,
1349
+ MAX_SESSIONS_PER_KEY,
1350
+ Date.now(),
1351
+ { ttlMs: SESSION_TTL_MS, graceMs: EVICT_GRACE_MS }
1352
+ );
1353
+ for (const sid2 of plan.evict) {
1354
+ const victim = sessions.get(sid2);
1355
+ sessions.delete(sid2);
1356
+ victim?.transport.close().catch(() => {
1128
1357
  });
1358
+ logSessionLifecycle("session_deleted", sid2, "lru_evict");
1359
+ }
1360
+ if (!plan.admit) {
1361
+ send429(res, buildSessionCapError({
1362
+ retryAfterSeconds: plan.retryAfterSeconds,
1363
+ limit: MAX_SESSIONS_PER_KEY,
1364
+ current: countKeySessions(sessions, keyH),
1365
+ poll: plan.retryIsPoll,
1366
+ id: req.body?.id ?? null
1367
+ }));
1129
1368
  return;
1130
1369
  }
1370
+ const sid = randomUUID2();
1371
+ let initialized = false;
1131
1372
  const transport = new StreamableHTTPServerTransport({
1132
- sessionIdGenerator: () => randomUUID2(),
1133
- onsessioninitialized: (sid) => {
1134
- sessions.set(sid, { transport, lastAccess: Date.now(), keyHash: keyH });
1135
- logSessionLifecycle("session_created", sid);
1373
+ sessionIdGenerator: () => sid,
1374
+ onsessioninitialized: (s) => {
1375
+ initialized = true;
1376
+ logSessionLifecycle("session_created", s);
1136
1377
  }
1378
+ // log only — no map write
1137
1379
  });
1380
+ const reserved = { transport, lastAccess: Date.now(), keyHash: keyH, inFlight: 1 };
1381
+ sessions.set(sid, reserved);
1138
1382
  transport.onclose = () => {
1139
- const sid = transport.sessionId;
1140
- if (sid) {
1141
- logSessionLifecycle("session_deleted", sid, "onclose");
1142
- sessions.delete(sid);
1383
+ const s = transport.sessionId ?? sid;
1384
+ forgetStreamLifecycle(keyH, s);
1385
+ if (sessions.has(s)) {
1386
+ sessions.delete(s);
1387
+ logSessionLifecycle("session_deleted", s, "onclose");
1143
1388
  }
1144
1389
  };
1145
- const server = createProductBrainServer();
1146
- await server.connect(transport);
1147
- await transport.handleRequest(req, res, req.body);
1148
- logRequest("POST", "ok", transport.sessionId ?? void 0, Date.now() - reqStart);
1390
+ try {
1391
+ const server = createProductBrainServer();
1392
+ await server.connect(transport);
1393
+ await transport.handleRequest(req, res, req.body);
1394
+ logRequest("POST", "ok", transport.sessionId ?? void 0, Date.now() - reqStart);
1395
+ } catch (e) {
1396
+ transport.onclose = void 0;
1397
+ sessions.delete(sid);
1398
+ throw e;
1399
+ } finally {
1400
+ if (!initialized) {
1401
+ transport.onclose = void 0;
1402
+ if (sessions.delete(sid)) logSessionLifecycle("session_deleted", sid, "init_rejected");
1403
+ } else {
1404
+ const e = sessions.get(sid);
1405
+ if (e) {
1406
+ e.inFlight--;
1407
+ e.lastAccess = Date.now();
1408
+ }
1409
+ }
1410
+ }
1149
1411
  } else if (sessionId) {
1150
1412
  process.stderr.write(
1151
1413
  `[HTTP] ${(/* @__PURE__ */ new Date()).toISOString()} session_stale sessionId=${sessionId} (likely server restart \u2014 instructing client to re-initialise)
@@ -1181,17 +1443,21 @@ app.post("/mcp", mcpLimiter, async (req, res) => {
1181
1443
  });
1182
1444
  app.get("/mcp", mcpLimiter, async (req, res) => {
1183
1445
  const reqIp = req.ip ?? "unknown";
1184
- if (checkAuthBlock(reqIp)) {
1185
- res.status(429).json({ error: "Too many failed auth attempts. Try again later." });
1446
+ const nowTs = Date.now();
1447
+ if (checkAuthBlock(authFailures, reqIp, nowTs)) {
1448
+ const rec = authFailures.get(reqIp);
1449
+ const retryAfterSeconds = rec ? Math.max(0, Math.ceil((rec.blockedUntil - nowTs) / 1e3)) : 0;
1450
+ send429(res, buildAuthLockoutError({ retryAfterSeconds, limit: AUTH_FAILURE_MAX, current: rec?.count ?? AUTH_FAILURE_MAX, id: req.body?.id ?? null }));
1186
1451
  return;
1187
1452
  }
1188
- const apiKey = extractBearerKey(req);
1189
- if (!apiKey) {
1453
+ const auth = resolveBearerAuth(req.headers?.authorization, accessTokens, nowTs, ACCESS_TOKEN_TTL_MS);
1454
+ if (auth.status !== "ok") {
1190
1455
  logRequest("GET", "auth_fail");
1191
- recordAuthFailure(reqIp);
1456
+ if (auth.status === "rejected") recordAuthFailure(authFailures, reqIp, nowTs);
1192
1457
  send401(req, res);
1193
1458
  return;
1194
1459
  }
1460
+ const apiKey = auth.apiKey;
1195
1461
  const sessionId = req.headers["mcp-session-id"];
1196
1462
  if (!sessionId) {
1197
1463
  res.status(400).send("Missing Mcp-Session-Id header");
@@ -1206,7 +1472,7 @@ app.get("/mcp", mcpLimiter, async (req, res) => {
1206
1472
  return;
1207
1473
  }
1208
1474
  try {
1209
- await runWithAuth({ apiKey }, async () => {
1475
+ await runWithAuth({ apiKey, mcpSessionId: sessionId }, async () => {
1210
1476
  const entry = sessions.get(sessionId);
1211
1477
  if (entry.keyHash !== hashKey(apiKey)) {
1212
1478
  res.status(403).json({
@@ -1226,17 +1492,21 @@ app.get("/mcp", mcpLimiter, async (req, res) => {
1226
1492
  });
1227
1493
  app.delete("/mcp", mcpLimiter, async (req, res) => {
1228
1494
  const reqIp = req.ip ?? "unknown";
1229
- if (checkAuthBlock(reqIp)) {
1230
- res.status(429).json({ error: "Too many failed auth attempts. Try again later." });
1495
+ const nowTs = Date.now();
1496
+ if (checkAuthBlock(authFailures, reqIp, nowTs)) {
1497
+ const rec = authFailures.get(reqIp);
1498
+ const retryAfterSeconds = rec ? Math.max(0, Math.ceil((rec.blockedUntil - nowTs) / 1e3)) : 0;
1499
+ send429(res, buildAuthLockoutError({ retryAfterSeconds, limit: AUTH_FAILURE_MAX, current: rec?.count ?? AUTH_FAILURE_MAX, id: req.body?.id ?? null }));
1231
1500
  return;
1232
1501
  }
1233
- const apiKey = extractBearerKey(req);
1234
- if (!apiKey) {
1502
+ const auth = resolveBearerAuth(req.headers?.authorization, accessTokens, nowTs, ACCESS_TOKEN_TTL_MS);
1503
+ if (auth.status !== "ok") {
1235
1504
  logRequest("DELETE", "auth_fail");
1236
- recordAuthFailure(reqIp);
1505
+ if (auth.status === "rejected") recordAuthFailure(authFailures, reqIp, nowTs);
1237
1506
  send401(req, res);
1238
1507
  return;
1239
1508
  }
1509
+ const apiKey = auth.apiKey;
1240
1510
  const sessionId = req.headers["mcp-session-id"];
1241
1511
  if (!sessionId) {
1242
1512
  res.status(400).send("Missing Mcp-Session-Id header");
@@ -1251,7 +1521,7 @@ app.delete("/mcp", mcpLimiter, async (req, res) => {
1251
1521
  return;
1252
1522
  }
1253
1523
  try {
1254
- await runWithAuth({ apiKey }, async () => {
1524
+ await runWithAuth({ apiKey, mcpSessionId: sessionId }, async () => {
1255
1525
  const entry = sessions.get(sessionId);
1256
1526
  if (entry.keyHash !== hashKey(apiKey)) {
1257
1527
  res.status(403).json({