@productbrain/mcp 0.0.1-beta.140 → 0.0.1-beta.14010
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/.env.mcp.example +5 -1
- package/README.md +67 -0
- package/dist/chunk-5ICMC6O7.js +12140 -0
- package/dist/chunk-5ICMC6O7.js.map +1 -0
- package/dist/chunk-MJCZCZA5.js +1861 -0
- package/dist/chunk-MJCZCZA5.js.map +1 -0
- package/dist/cli/index.js +1 -1
- package/dist/http.js +723 -229
- package/dist/http.js.map +1 -1
- package/dist/index.js +7 -25
- package/dist/index.js.map +1 -1
- package/dist/setup-KVJOROL4.js +204 -0
- package/dist/setup-KVJOROL4.js.map +1 -0
- package/dist/views/src/entry-cards/index.html +108 -90
- package/dist/views/src/graph-constellation/index.html +111 -93
- package/package.json +8 -8
- package/dist/chunk-CDBSOVW7.js +0 -15115
- package/dist/chunk-CDBSOVW7.js.map +0 -1
- package/dist/chunk-MOPOQUJP.js +0 -312
- package/dist/chunk-MOPOQUJP.js.map +0 -1
- package/dist/setup-YYADLH22.js +0 -297
- package/dist/setup-YYADLH22.js.map +0 -1
package/dist/http.js
CHANGED
|
@@ -1,26 +1,507 @@
|
|
|
1
1
|
import {
|
|
2
2
|
SERVER_VERSION,
|
|
3
|
+
createProductBrainServer
|
|
4
|
+
} from "./chunk-5ICMC6O7.js";
|
|
5
|
+
import {
|
|
6
|
+
DEFAULT_CLOUD_URL,
|
|
7
|
+
appUrl,
|
|
3
8
|
bootstrapHttp,
|
|
4
|
-
|
|
5
|
-
|
|
9
|
+
checkKeyAgainstCandidates,
|
|
10
|
+
forgetStreamLifecycle,
|
|
11
|
+
getKeyState,
|
|
12
|
+
hashKey,
|
|
13
|
+
isApiKeyShaped,
|
|
14
|
+
parseFallbackUrls,
|
|
6
15
|
runWithAuth
|
|
7
|
-
} from "./chunk-
|
|
8
|
-
import {
|
|
9
|
-
getPostHogClient,
|
|
10
|
-
initAnalytics,
|
|
11
|
-
shutdownAnalytics
|
|
12
|
-
} from "./chunk-MOPOQUJP.js";
|
|
16
|
+
} from "./chunk-MJCZCZA5.js";
|
|
13
17
|
|
|
14
18
|
// src/http.ts
|
|
15
|
-
import {
|
|
19
|
+
import { randomUUID } from "crypto";
|
|
16
20
|
import express from "express";
|
|
17
21
|
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
|
|
18
22
|
import { isInitializeRequest } from "@modelcontextprotocol/sdk/types.js";
|
|
23
|
+
import rateLimit2 from "express-rate-limit";
|
|
24
|
+
|
|
25
|
+
// src/sessionCap.ts
|
|
26
|
+
function planKeyAdmission(sessions2, keyHash, cap, now, opts) {
|
|
27
|
+
if (cap < 1) {
|
|
28
|
+
throw new RangeError(`cap must be >= 1, got ${cap}`);
|
|
29
|
+
}
|
|
30
|
+
const { ttlMs, graceMs } = opts;
|
|
31
|
+
const isProtected = (s) => s.inFlight > 0 || now - s.lastAccess < graceMs;
|
|
32
|
+
const keyEntries = [];
|
|
33
|
+
for (const [id, session] of sessions2) {
|
|
34
|
+
if (session.keyHash === keyHash) {
|
|
35
|
+
keyEntries.push([id, session]);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
const evictSet = /* @__PURE__ */ new Set();
|
|
39
|
+
for (const [id, session] of keyEntries) {
|
|
40
|
+
if (!isProtected(session) && now - session.lastAccess >= ttlMs) {
|
|
41
|
+
evictSet.add(id);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
let survivors = keyEntries.filter(([id]) => !evictSet.has(id));
|
|
45
|
+
if (survivors.length >= cap) {
|
|
46
|
+
const idleSurvivors = survivors.filter(([, s]) => !isProtected(s)).sort(([, a], [, b]) => a.lastAccess - b.lastAccess);
|
|
47
|
+
for (const [id] of idleSurvivors) {
|
|
48
|
+
if (survivors.length < cap) break;
|
|
49
|
+
evictSet.add(id);
|
|
50
|
+
survivors = survivors.filter(([sid]) => sid !== id);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
const evict = Array.from(evictSet);
|
|
54
|
+
const admit = survivors.length < cap;
|
|
55
|
+
let retryAfterSeconds = 0;
|
|
56
|
+
let retryIsPoll = false;
|
|
57
|
+
if (!admit) {
|
|
58
|
+
const graceBlockers = survivors.filter(([, s]) => s.inFlight === 0);
|
|
59
|
+
if (graceBlockers.length > 0) {
|
|
60
|
+
const minLastAccess = Math.min(...graceBlockers.map(([, s]) => s.lastAccess));
|
|
61
|
+
const msRemaining = graceMs - (now - minLastAccess);
|
|
62
|
+
retryAfterSeconds = Math.max(1, Math.ceil(msRemaining / 1e3));
|
|
63
|
+
} else {
|
|
64
|
+
retryAfterSeconds = 5;
|
|
65
|
+
retryIsPoll = true;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
return { evict, admit, retryAfterSeconds, retryIsPoll };
|
|
69
|
+
}
|
|
70
|
+
function countKeySessions(sessions2, keyHash) {
|
|
71
|
+
let count = 0;
|
|
72
|
+
for (const session of sessions2.values()) {
|
|
73
|
+
if (session.keyHash === keyHash) count++;
|
|
74
|
+
}
|
|
75
|
+
return count;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// src/httpErrors.ts
|
|
79
|
+
function clampSeconds(s) {
|
|
80
|
+
return Math.max(0, Math.round(s));
|
|
81
|
+
}
|
|
82
|
+
function build(reason, message, p) {
|
|
83
|
+
const seconds = clampSeconds(p.retryAfterSeconds);
|
|
84
|
+
return {
|
|
85
|
+
status: 429,
|
|
86
|
+
headers: { "Retry-After": String(seconds) },
|
|
87
|
+
body: {
|
|
88
|
+
jsonrpc: "2.0",
|
|
89
|
+
id: p.id ?? null,
|
|
90
|
+
error: {
|
|
91
|
+
code: -32e3,
|
|
92
|
+
message,
|
|
93
|
+
data: {
|
|
94
|
+
reason,
|
|
95
|
+
retryAfterSeconds: seconds,
|
|
96
|
+
limit: p.limit,
|
|
97
|
+
current: p.current
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
function buildRateLimitError(p) {
|
|
104
|
+
const seconds = clampSeconds(p.retryAfterSeconds);
|
|
105
|
+
return build(
|
|
106
|
+
"rate_limited",
|
|
107
|
+
`Too many requests \u2014 retry after ${seconds} s.`,
|
|
108
|
+
p
|
|
109
|
+
);
|
|
110
|
+
}
|
|
111
|
+
function buildAuthLockoutError(p) {
|
|
112
|
+
const seconds = clampSeconds(p.retryAfterSeconds);
|
|
113
|
+
return build(
|
|
114
|
+
"auth_lockout",
|
|
115
|
+
`Too many failed auth attempts \u2014 locked out, retry after ${seconds} s.`,
|
|
116
|
+
p
|
|
117
|
+
);
|
|
118
|
+
}
|
|
119
|
+
function buildSessionCapError(p) {
|
|
120
|
+
const seconds = clampSeconds(p.retryAfterSeconds);
|
|
121
|
+
const message = p.poll ? "Server busy \u2014 all sessions active; retry shortly." : `Too many active sessions for this key \u2014 retry after ${seconds} s.`;
|
|
122
|
+
return build("session_cap", message, p);
|
|
123
|
+
}
|
|
124
|
+
function send429(res, built) {
|
|
125
|
+
if (res.headersSent) return;
|
|
126
|
+
for (const [k, v] of Object.entries(built.headers)) {
|
|
127
|
+
res.setHeader(k, v);
|
|
128
|
+
}
|
|
129
|
+
res.status(built.status).json(built.body);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
// src/mcpRateLimit.ts
|
|
19
133
|
import rateLimit from "express-rate-limit";
|
|
134
|
+
|
|
135
|
+
// src/authLockout.ts
|
|
136
|
+
var AUTH_FAILURE_MAX = 10;
|
|
137
|
+
var AUTH_FAILURE_WINDOW_MS = 5 * 6e4;
|
|
138
|
+
var AUTH_BLOCK_DURATION_MS = 15 * 6e4;
|
|
139
|
+
var MAX_AUTH_FAILURE_ENTRIES = 1e4;
|
|
140
|
+
function rejected(presented) {
|
|
141
|
+
return { status: "rejected", credentialId: hashKey(presented) };
|
|
142
|
+
}
|
|
143
|
+
function resolveBearerAuth(authorizationHeader) {
|
|
144
|
+
if (typeof authorizationHeader !== "string" || authorizationHeader.trim() === "") {
|
|
145
|
+
return { status: "absent" };
|
|
146
|
+
}
|
|
147
|
+
if (!authorizationHeader.startsWith("Bearer ")) {
|
|
148
|
+
return rejected(authorizationHeader.trim());
|
|
149
|
+
}
|
|
150
|
+
const token = authorizationHeader.slice(7).trim();
|
|
151
|
+
if (!isApiKeyShaped(token)) return rejected(token);
|
|
152
|
+
return { status: "ok", apiKey: token, credentialId: hashKey(token) };
|
|
153
|
+
}
|
|
154
|
+
function checkAuthBlock(failures, credentialId, now) {
|
|
155
|
+
const rec = failures.get(credentialId);
|
|
156
|
+
if (!rec) return false;
|
|
157
|
+
return rec.blockedUntil > now;
|
|
158
|
+
}
|
|
159
|
+
function authLockoutError(failures, auth, now, id = null) {
|
|
160
|
+
if (auth.status === "absent") return null;
|
|
161
|
+
const rec = failures.get(auth.credentialId);
|
|
162
|
+
if (!rec || !checkAuthBlock(failures, auth.credentialId, now)) return null;
|
|
163
|
+
const retryAfterSeconds = Math.max(0, Math.ceil((rec.blockedUntil - now) / 1e3));
|
|
164
|
+
return buildAuthLockoutError({ retryAfterSeconds, limit: AUTH_FAILURE_MAX, current: rec.count, id });
|
|
165
|
+
}
|
|
166
|
+
function recordAuthFailure(failures, credentialId, now) {
|
|
167
|
+
const rec = failures.get(credentialId);
|
|
168
|
+
if (!rec) {
|
|
169
|
+
if (failures.size >= MAX_AUTH_FAILURE_ENTRIES) {
|
|
170
|
+
const oldest = failures.keys().next().value;
|
|
171
|
+
if (oldest !== void 0) failures.delete(oldest);
|
|
172
|
+
}
|
|
173
|
+
failures.set(credentialId, { count: 1, firstFailure: now, blockedUntil: 0 });
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
176
|
+
if (now - rec.firstFailure > AUTH_FAILURE_WINDOW_MS) {
|
|
177
|
+
rec.count = 1;
|
|
178
|
+
rec.firstFailure = now;
|
|
179
|
+
rec.blockedUntil = 0;
|
|
180
|
+
} else {
|
|
181
|
+
rec.count++;
|
|
182
|
+
if (rec.count >= AUTH_FAILURE_MAX) {
|
|
183
|
+
rec.blockedUntil = now + AUTH_BLOCK_DURATION_MS;
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
function keyVerdictGate(verdict, failures, credentialId, now) {
|
|
188
|
+
if (verdict === "ok" || verdict === "rate_limited") return "admit";
|
|
189
|
+
if (verdict === "rejected") {
|
|
190
|
+
recordAuthFailure(failures, credentialId, now);
|
|
191
|
+
return "unauthorized";
|
|
192
|
+
}
|
|
193
|
+
return "unavailable";
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
// src/mcpRateLimit.ts
|
|
197
|
+
var MCP_KEY_LIMIT = 120;
|
|
198
|
+
var MCP_IP_CEILING = 1200;
|
|
199
|
+
function mcpRateKey(req) {
|
|
200
|
+
const auth = resolveBearerAuth(req.headers?.authorization);
|
|
201
|
+
return auth.status === "absent" ? `ip:${req.ip ?? ""}` : `key:${auth.credentialId}`;
|
|
202
|
+
}
|
|
203
|
+
function limiter(max, windowMs, keyGenerator) {
|
|
204
|
+
return rateLimit({
|
|
205
|
+
windowMs,
|
|
206
|
+
max,
|
|
207
|
+
standardHeaders: true,
|
|
208
|
+
legacyHeaders: false,
|
|
209
|
+
...keyGenerator ? { keyGenerator } : {},
|
|
210
|
+
handler: (req, res) => {
|
|
211
|
+
const r = req.rateLimit;
|
|
212
|
+
const reset = r?.resetTime?.getTime?.() ?? Date.now() + windowMs;
|
|
213
|
+
send429(res, buildRateLimitError({
|
|
214
|
+
retryAfterSeconds: Math.max(1, Math.ceil((reset - Date.now()) / 1e3)),
|
|
215
|
+
limit: r?.limit ?? max,
|
|
216
|
+
current: r?.used ?? 0,
|
|
217
|
+
id: req.body?.id ?? null
|
|
218
|
+
// mirror the JSON-RPC id when a POST body is present
|
|
219
|
+
}));
|
|
220
|
+
}
|
|
221
|
+
});
|
|
222
|
+
}
|
|
223
|
+
function mcpLimiters(opts = {}) {
|
|
224
|
+
const windowMs = opts.windowMs ?? 6e4;
|
|
225
|
+
return [
|
|
226
|
+
limiter(opts.ipCeiling ?? MCP_IP_CEILING, windowMs),
|
|
227
|
+
limiter(opts.keyLimit ?? MCP_KEY_LIMIT, windowMs, mcpRateKey)
|
|
228
|
+
];
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
// src/lib/oauthRedirectAllowlist.ts
|
|
232
|
+
var DEFAULT_OAUTH_REDIRECT_URIS = [
|
|
233
|
+
"https://claude.ai/api/mcp/auth_callback",
|
|
234
|
+
"https://claude.com/api/mcp/auth_callback",
|
|
235
|
+
"https://chatgpt.com/connector_platform_oauth_redirect",
|
|
236
|
+
"https://www.cursor.com/agents/mcp/oauth/callback"
|
|
237
|
+
];
|
|
238
|
+
var CHATGPT_CONNECTOR_CALLBACK = /^https:\/\/chatgpt\.com\/connector\/oauth\/[A-Za-z0-9_-]+$/;
|
|
239
|
+
var LOOPBACK_HOSTS = ["localhost", "127.0.0.1", "[::1]"];
|
|
240
|
+
var MAX_REDIRECT_URI_LENGTH = 2048;
|
|
241
|
+
var MAX_REGISTRATION_REDIRECTS = 10;
|
|
242
|
+
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)";
|
|
243
|
+
function exactForm(url) {
|
|
244
|
+
return `${url.origin}${url.pathname}`;
|
|
245
|
+
}
|
|
246
|
+
function parseRedirectUriAllowlist(raw) {
|
|
247
|
+
if (!raw) return { uris: [], configError: null };
|
|
248
|
+
const uris = [];
|
|
249
|
+
for (const part of raw.split(",")) {
|
|
250
|
+
const trimmed = part.trim();
|
|
251
|
+
if (!trimmed) continue;
|
|
252
|
+
let url = null;
|
|
253
|
+
try {
|
|
254
|
+
url = trimmed.includes("://") ? new URL(trimmed) : null;
|
|
255
|
+
} catch {
|
|
256
|
+
url = null;
|
|
257
|
+
}
|
|
258
|
+
const valid = url !== null && url.protocol === "https:" && !url.username && !url.password && !url.search && !url.hash && (url.port === "" || url.port === "443") && url.pathname !== "/";
|
|
259
|
+
if (!valid || url === null) {
|
|
260
|
+
return { uris: [], configError: `${OPERATOR_ENTRY_FORM}; got "${trimmed}"` };
|
|
261
|
+
}
|
|
262
|
+
uris.push(exactForm(url));
|
|
263
|
+
}
|
|
264
|
+
return { uris, configError: null };
|
|
265
|
+
}
|
|
266
|
+
function resolveOAuthRedirectAllowlist(opts = {}) {
|
|
267
|
+
const parsed = parseRedirectUriAllowlist(opts.explicitAllowlist);
|
|
268
|
+
return {
|
|
269
|
+
uris: [.../* @__PURE__ */ new Set([...DEFAULT_OAUTH_REDIRECT_URIS, ...parsed.uris])],
|
|
270
|
+
configError: parsed.configError
|
|
271
|
+
};
|
|
272
|
+
}
|
|
273
|
+
function checkRedirectUri(redirectUri, allowlist) {
|
|
274
|
+
if (allowlist.configError) return `OAuth is misconfigured: ${allowlist.configError}`;
|
|
275
|
+
if (typeof redirectUri !== "string" || redirectUri.length === 0) {
|
|
276
|
+
return "redirect_uri is required";
|
|
277
|
+
}
|
|
278
|
+
if (redirectUri.length > MAX_REDIRECT_URI_LENGTH) {
|
|
279
|
+
return `redirect_uri is longer than ${MAX_REDIRECT_URI_LENGTH} characters`;
|
|
280
|
+
}
|
|
281
|
+
let url;
|
|
282
|
+
try {
|
|
283
|
+
url = new URL(redirectUri);
|
|
284
|
+
} catch {
|
|
285
|
+
return "redirect_uri is not a valid absolute URL";
|
|
286
|
+
}
|
|
287
|
+
if (url.username || url.password) return "redirect_uri must not contain credentials";
|
|
288
|
+
if (url.hash) return "redirect_uri must not contain a fragment";
|
|
289
|
+
const host = url.hostname.toLowerCase();
|
|
290
|
+
if (url.protocol === "http:") {
|
|
291
|
+
return LOOPBACK_HOSTS.includes(host) ? null : "redirect_uri must use https (http is allowed only for localhost, 127.0.0.1 or [::1])";
|
|
292
|
+
}
|
|
293
|
+
if (url.protocol === "https:") {
|
|
294
|
+
if (url.port && url.port !== "443") return "redirect_uri must use the default https port (443)";
|
|
295
|
+
if (url.search) return "redirect_uri must not contain a query";
|
|
296
|
+
const exact = exactForm(url);
|
|
297
|
+
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)";
|
|
298
|
+
}
|
|
299
|
+
return "redirect_uri scheme is not allowed (use https, or http on loopback)";
|
|
300
|
+
}
|
|
301
|
+
function checkRegistrationRedirects(redirectUris, allowlist) {
|
|
302
|
+
const refused = (refusal) => ({ refusal, allowed: [], dropped: [] });
|
|
303
|
+
if (!Array.isArray(redirectUris) || redirectUris.length === 0) return refused("redirect_uris is required");
|
|
304
|
+
if (redirectUris.length > MAX_REGISTRATION_REDIRECTS) {
|
|
305
|
+
return refused(`redirect_uris may hold at most ${MAX_REGISTRATION_REDIRECTS} entries`);
|
|
306
|
+
}
|
|
307
|
+
const allowed = [];
|
|
308
|
+
const dropped = [];
|
|
309
|
+
for (const uri of redirectUris) {
|
|
310
|
+
const reason = checkRedirectUri(uri, allowlist);
|
|
311
|
+
if (reason) dropped.push({ uri, reason });
|
|
312
|
+
else allowed.push(uri);
|
|
313
|
+
}
|
|
314
|
+
return { refusal: allowed.length === 0 ? dropped[0].reason : null, allowed, dropped };
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
// src/lib/connectClientNames.ts
|
|
318
|
+
var CONNECT_CLIENT_LABELS = {
|
|
319
|
+
"claude.ai": "Claude",
|
|
320
|
+
"claude.com": "Claude",
|
|
321
|
+
"chatgpt.com": "ChatGPT",
|
|
322
|
+
"www.cursor.com": "Cursor (web)"
|
|
323
|
+
};
|
|
324
|
+
var REPLACEABLE_CLIENT_NAMES = [...new Set(Object.values(CONNECT_CLIENT_LABELS))];
|
|
325
|
+
|
|
326
|
+
// src/lib/connectClients.ts
|
|
327
|
+
var LOCAL_APP_NAME_MAX = 40;
|
|
328
|
+
var LOCAL_APP_KEY_NAME = "Local app";
|
|
329
|
+
var CLIENT_ID_PREFIX = "pb_client_";
|
|
330
|
+
var LOOPBACK_HOSTS2 = ["localhost", "127.0.0.1", "[::1]"];
|
|
331
|
+
function cleanAppName(raw) {
|
|
332
|
+
if (typeof raw !== "string") return null;
|
|
333
|
+
const folded = raw.replace(/[\u0000-\u001f\u007f-\u009f\u200b-\u200f\u2028-\u202e\u2066-\u2069]/g, " ").replace(/\s+/g, " ").trim();
|
|
334
|
+
const cut = Array.from(folded).slice(0, LOCAL_APP_NAME_MAX).join("").trim();
|
|
335
|
+
return cut === "" ? null : cut;
|
|
336
|
+
}
|
|
337
|
+
var B64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
|
|
338
|
+
function utf8Bytes(text2) {
|
|
339
|
+
const bytes = [];
|
|
340
|
+
const escaped = encodeURIComponent(text2);
|
|
341
|
+
for (let i = 0; i < escaped.length; i++) {
|
|
342
|
+
if (escaped[i] === "%") {
|
|
343
|
+
bytes.push(parseInt(escaped.slice(i + 1, i + 3), 16));
|
|
344
|
+
i += 2;
|
|
345
|
+
} else bytes.push(escaped.charCodeAt(i));
|
|
346
|
+
}
|
|
347
|
+
return bytes;
|
|
348
|
+
}
|
|
349
|
+
function base64url(bytes) {
|
|
350
|
+
let out = "";
|
|
351
|
+
for (let i = 0; i < bytes.length; i += 3) {
|
|
352
|
+
const n = bytes[i] << 16 | (bytes[i + 1] ?? 0) << 8 | (bytes[i + 2] ?? 0);
|
|
353
|
+
out += B64[n >> 18 & 63] + B64[n >> 12 & 63];
|
|
354
|
+
if (i + 1 < bytes.length) out += B64[n >> 6 & 63];
|
|
355
|
+
if (i + 2 < bytes.length) out += B64[n & 63];
|
|
356
|
+
}
|
|
357
|
+
return out;
|
|
358
|
+
}
|
|
359
|
+
function fromBase64url(text2) {
|
|
360
|
+
if (!/^[A-Za-z0-9_-]*$/.test(text2) || text2.length % 4 === 1) return null;
|
|
361
|
+
let escaped = "";
|
|
362
|
+
for (let i = 0; i < text2.length; i += 4) {
|
|
363
|
+
const quad = text2.slice(i, i + 4);
|
|
364
|
+
const n = Array.from(quad).reduce((acc, ch, j) => acc | B64.indexOf(ch) << 18 - 6 * j, 0);
|
|
365
|
+
const bytes = [n >> 16 & 255, n >> 8 & 255, n & 255].slice(0, quad.length - 1);
|
|
366
|
+
for (const b of bytes) escaped += `%${b.toString(16).padStart(2, "0")}`;
|
|
367
|
+
}
|
|
368
|
+
try {
|
|
369
|
+
return decodeURIComponent(escaped);
|
|
370
|
+
} catch {
|
|
371
|
+
return null;
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
function registeredClientId(uuid, clientName) {
|
|
375
|
+
const name = cleanAppName(clientName);
|
|
376
|
+
return name === null ? `${CLIENT_ID_PREFIX}${uuid}` : `${CLIENT_ID_PREFIX}${uuid}.${base64url(utf8Bytes(name))}`;
|
|
377
|
+
}
|
|
378
|
+
function appNameFromClientId(clientId) {
|
|
379
|
+
if (typeof clientId !== "string" || !clientId.startsWith(CLIENT_ID_PREFIX)) return null;
|
|
380
|
+
const dot = clientId.indexOf(".");
|
|
381
|
+
if (dot === -1) return null;
|
|
382
|
+
return cleanAppName(fromBase64url(clientId.slice(dot + 1)));
|
|
383
|
+
}
|
|
384
|
+
function connectClientOf(redirectUri, clientId) {
|
|
385
|
+
if (typeof redirectUri !== "string") return null;
|
|
386
|
+
let url;
|
|
387
|
+
try {
|
|
388
|
+
url = new URL(redirectUri);
|
|
389
|
+
} catch {
|
|
390
|
+
return null;
|
|
391
|
+
}
|
|
392
|
+
const host = url.hostname.toLowerCase();
|
|
393
|
+
if (url.protocol === "http:" && LOOPBACK_HOSTS2.includes(host)) return { kind: "local", appName: appNameFromClientId(clientId), at: url.host };
|
|
394
|
+
if (url.protocol !== "https:") return null;
|
|
395
|
+
const clientName = CONNECT_CLIENT_LABELS[host];
|
|
396
|
+
return clientName ? { kind: "vendor", clientName, host } : { kind: "web", host };
|
|
397
|
+
}
|
|
398
|
+
var connectKeyName = (client) => client.kind === "vendor" ? client.clientName : client.kind === "local" ? client.appName ?? LOCAL_APP_KEY_NAME : client.host;
|
|
399
|
+
var connectClientName = (client) => client.kind === "vendor" ? client.clientName : void 0;
|
|
400
|
+
|
|
401
|
+
// src/lib/oauthAuthCode.ts
|
|
402
|
+
function tokenResponse(apiKey) {
|
|
403
|
+
return {
|
|
404
|
+
access_token: apiKey,
|
|
405
|
+
token_type: "Bearer",
|
|
406
|
+
// 1 year: validity is enforced by Convex on every call, not by this clock.
|
|
407
|
+
expires_in: 365 * 24 * 3600
|
|
408
|
+
};
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
// src/lib/oauthDoors.ts
|
|
412
|
+
var CONNECT_PAGE_PATH = "/connect";
|
|
413
|
+
var S256_CHALLENGE = /^[A-Za-z0-9_-]{43}$/;
|
|
414
|
+
var CONNECT_CODE = /^pb_ct_[A-Za-z0-9_-]{43}$/;
|
|
415
|
+
var text = (value) => typeof value === "string" ? value : void 0;
|
|
416
|
+
function logOAuthDoor(door, status, reason, uris) {
|
|
417
|
+
const list = uris === void 0 ? "" : ` uris=${JSON.stringify(uris.map(String)).slice(0, 600)}`;
|
|
418
|
+
process.stderr.write(`[oauth] door=${door} status=${status} reason=${JSON.stringify(reason)}${list}
|
|
419
|
+
`);
|
|
420
|
+
}
|
|
421
|
+
function backToClient(redirectUri, params, state) {
|
|
422
|
+
const url = new URL(redirectUri);
|
|
423
|
+
for (const [key, value] of Object.entries(params)) url.searchParams.set(key, value);
|
|
424
|
+
if (state !== void 0) url.searchParams.set("state", state);
|
|
425
|
+
return url.toString();
|
|
426
|
+
}
|
|
427
|
+
function authorizeOutcome(query, { allowlist, appUrl: appUrl2 }) {
|
|
428
|
+
const redirectUri = text(query.redirect_uri);
|
|
429
|
+
const refusal = checkRedirectUri(query.redirect_uri, allowlist);
|
|
430
|
+
if (refusal || redirectUri === void 0) {
|
|
431
|
+
return { status: 400, reason: refusal ?? "redirect_uri is required", json: { error: "invalid_request", error_description: refusal } };
|
|
432
|
+
}
|
|
433
|
+
const state = text(query.state);
|
|
434
|
+
if (query.error !== void 0) {
|
|
435
|
+
if (query.error !== "access_denied") return { status: 400, reason: "unknown_error_param", json: { error: "invalid_request" } };
|
|
436
|
+
return { status: 302, reason: "access_denied", location: backToClient(redirectUri, { error: "access_denied" }, state) };
|
|
437
|
+
}
|
|
438
|
+
if (query.code !== void 0) {
|
|
439
|
+
const code = text(query.code);
|
|
440
|
+
if (code === void 0 || !CONNECT_CODE.test(code)) return { status: 400, reason: "malformed_code", json: { error: "invalid_request" } };
|
|
441
|
+
return { status: 302, reason: "code_returned", location: backToClient(redirectUri, { code }, state) };
|
|
442
|
+
}
|
|
443
|
+
const challenge = text(query.code_challenge);
|
|
444
|
+
if (query.code_challenge_method !== "S256" || challenge === void 0 || !S256_CHALLENGE.test(challenge)) {
|
|
445
|
+
const description = "code_challenge (S256) is required";
|
|
446
|
+
return { status: 302, reason: "pkce_required", location: backToClient(redirectUri, { error: "invalid_request", error_description: description }, state) };
|
|
447
|
+
}
|
|
448
|
+
const page = new URL(`${appUrl2}${CONNECT_PAGE_PATH}`);
|
|
449
|
+
page.searchParams.set("client_id", text(query.client_id) ?? "");
|
|
450
|
+
page.searchParams.set("redirect_uri", redirectUri);
|
|
451
|
+
page.searchParams.set("code_challenge", challenge);
|
|
452
|
+
if (state !== void 0) page.searchParams.set("state", state);
|
|
453
|
+
return { status: 302, reason: "to_connect_page", location: page.toString() };
|
|
454
|
+
}
|
|
455
|
+
var invalidGrant = (reason) => ({ status: 400, reason, json: { error: "invalid_grant" } });
|
|
456
|
+
async function exchangeOutcome(body, { candidates, fetchImpl = fetch, timeoutMs = 5e3 }) {
|
|
457
|
+
if (body.grant_type !== "authorization_code") return { status: 400, reason: "unsupported_grant_type", json: { error: "unsupported_grant_type" } };
|
|
458
|
+
const code = text(body.code), codeVerifier = text(body.code_verifier), redirectUri = text(body.redirect_uri);
|
|
459
|
+
if (!code || !codeVerifier || !redirectUri) return { status: 400, reason: "missing_param", json: { error: "invalid_request" } };
|
|
460
|
+
const client = connectClientOf(redirectUri, body.client_id);
|
|
461
|
+
if (!client) return invalidGrant("unreadable_redirect");
|
|
462
|
+
const clientName = connectClientName(client);
|
|
463
|
+
const payload = JSON.stringify({
|
|
464
|
+
token: code,
|
|
465
|
+
codeVerifier,
|
|
466
|
+
redirectUri,
|
|
467
|
+
name: connectKeyName(client),
|
|
468
|
+
...clientName === void 0 ? {} : { clientName }
|
|
469
|
+
});
|
|
470
|
+
for (const base of candidates) {
|
|
471
|
+
let status;
|
|
472
|
+
let json;
|
|
473
|
+
try {
|
|
474
|
+
const res = await fetchImpl(`${base}/auth/redeem-connect-token`, {
|
|
475
|
+
method: "POST",
|
|
476
|
+
headers: { "content-type": "application/json" },
|
|
477
|
+
body: payload,
|
|
478
|
+
signal: AbortSignal.timeout(timeoutMs)
|
|
479
|
+
});
|
|
480
|
+
status = res.status;
|
|
481
|
+
json = await res.json().catch(() => null);
|
|
482
|
+
} catch {
|
|
483
|
+
return invalidGrant("redeem_unreachable");
|
|
484
|
+
}
|
|
485
|
+
const apiKey = json?.apiKey;
|
|
486
|
+
if (status === 200 && typeof apiKey === "string") return { status: 200, reason: "token_issued", json: tokenResponse(apiKey) };
|
|
487
|
+
const refusal = json?.error?.code;
|
|
488
|
+
if (!(status === 400 && refusal === "invalid_token")) return invalidGrant(`redeem_refused_${status}`);
|
|
489
|
+
}
|
|
490
|
+
return invalidGrant("code_refused");
|
|
491
|
+
}
|
|
492
|
+
function sendDoor(res, door, outcome) {
|
|
493
|
+
logOAuthDoor(door, outcome.status, outcome.reason);
|
|
494
|
+
if (outcome.location !== void 0) res.redirect(302, outcome.location);
|
|
495
|
+
else res.status(outcome.status).json(outcome.json);
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
// src/http.ts
|
|
20
499
|
bootstrapHttp();
|
|
21
|
-
initAnalytics();
|
|
22
|
-
initFeatureFlags(getPostHogClient());
|
|
23
500
|
var PORT = parseInt(process.env.PORT ?? process.env.MCP_PORT ?? "3002", 10);
|
|
501
|
+
function keyCheckCandidates() {
|
|
502
|
+
const primaryUrl = (process.env.CONVEX_SITE_URL ?? DEFAULT_CLOUD_URL).replace(/\/$/, "");
|
|
503
|
+
return [primaryUrl, ...parseFallbackUrls(process.env.CONVEX_FALLBACK_URLS).map((u) => u.replace(/\/$/, ""))];
|
|
504
|
+
}
|
|
24
505
|
function baseUrl(req) {
|
|
25
506
|
const proto = req.headers["x-forwarded-proto"] ?? req.protocol ?? "http";
|
|
26
507
|
const host = req.headers.host ?? `localhost:${PORT}`;
|
|
@@ -29,10 +510,11 @@ function baseUrl(req) {
|
|
|
29
510
|
var app = express();
|
|
30
511
|
app.set("trust proxy", 1);
|
|
31
512
|
app.use(express.json());
|
|
32
|
-
var ALLOWED_ORIGINS = process.env.CORS_ORIGINS
|
|
513
|
+
var ALLOWED_ORIGINS = (process.env.CORS_ORIGINS ?? "https://claude.ai").split(",").map((o) => o.trim()).filter(Boolean);
|
|
514
|
+
var OAUTH_REDIRECT_ALLOWLIST = resolveOAuthRedirectAllowlist({ explicitAllowlist: process.env.OAUTH_REDIRECT_HOST_ALLOWLIST });
|
|
33
515
|
app.use((_req, res, next) => {
|
|
34
516
|
const origin = _req.headers.origin;
|
|
35
|
-
if (
|
|
517
|
+
if (origin && ALLOWED_ORIGINS.includes(origin)) {
|
|
36
518
|
res.setHeader("Access-Control-Allow-Origin", origin);
|
|
37
519
|
}
|
|
38
520
|
res.setHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS");
|
|
@@ -40,7 +522,7 @@ app.use((_req, res, next) => {
|
|
|
40
522
|
"Access-Control-Allow-Headers",
|
|
41
523
|
"Content-Type, Authorization, Mcp-Session-Id, Last-Event-Id"
|
|
42
524
|
);
|
|
43
|
-
res.setHeader("Access-Control-Expose-Headers", "Mcp-Session-Id");
|
|
525
|
+
res.setHeader("Access-Control-Expose-Headers", "Mcp-Session-Id, Retry-After");
|
|
44
526
|
if (_req.method === "OPTIONS") {
|
|
45
527
|
res.status(204).end();
|
|
46
528
|
return;
|
|
@@ -64,240 +546,112 @@ app.get("/.well-known/oauth-authorization-server", (req, res) => {
|
|
|
64
546
|
token_endpoint: `${base}/oauth/token`,
|
|
65
547
|
registration_endpoint: `${base}/register`,
|
|
66
548
|
response_types_supported: ["code"],
|
|
67
|
-
grant_types_supported: ["authorization_code"
|
|
549
|
+
grant_types_supported: ["authorization_code"],
|
|
550
|
+
// TEN-4548: no refresh grant (lib/oauthAuthCode.ts tokenResponse)
|
|
68
551
|
code_challenge_methods_supported: ["S256"],
|
|
69
552
|
token_endpoint_auth_methods_supported: ["none"],
|
|
70
553
|
scopes_supported: ["mcp:tools", "mcp:resources"]
|
|
71
554
|
});
|
|
72
555
|
});
|
|
73
|
-
var
|
|
556
|
+
var authLimiter = rateLimit2({
|
|
557
|
+
windowMs: 6e4,
|
|
558
|
+
max: 20,
|
|
559
|
+
standardHeaders: true,
|
|
560
|
+
legacyHeaders: false,
|
|
561
|
+
handler: (req, res) => {
|
|
562
|
+
logOAuthDoor(`${req.method} /authorize`, 429, "rate_limited_per_ip");
|
|
563
|
+
res.status(429).json({ error: "Too many auth requests. Try again later." });
|
|
564
|
+
}
|
|
565
|
+
});
|
|
74
566
|
app.post(
|
|
75
567
|
"/register",
|
|
76
568
|
express.json(),
|
|
77
569
|
(req, res) => {
|
|
78
|
-
const { redirect_uris, client_name } = req.body;
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
});
|
|
570
|
+
const { redirect_uris, client_name } = req.body ?? {};
|
|
571
|
+
const { refusal, allowed, dropped } = checkRegistrationRedirects(redirect_uris, OAUTH_REDIRECT_ALLOWLIST);
|
|
572
|
+
if (refusal) {
|
|
573
|
+
logOAuthDoor("POST /register", 400, refusal, Array.isArray(redirect_uris) ? redirect_uris : [redirect_uris]);
|
|
574
|
+
res.status(400).json({ error: "invalid_redirect_uri", error_description: refusal });
|
|
84
575
|
return;
|
|
85
576
|
}
|
|
86
|
-
const clientId =
|
|
87
|
-
const
|
|
88
|
-
|
|
89
|
-
redirect_uris,
|
|
90
|
-
client_name,
|
|
91
|
-
registeredAt: Date.now()
|
|
92
|
-
};
|
|
93
|
-
registeredClients.set(clientId, client);
|
|
577
|
+
const clientId = registeredClientId(randomUUID(), client_name);
|
|
578
|
+
const droppedUris = dropped.length > 0 ? dropped.map((d) => d.uri) : void 0;
|
|
579
|
+
logOAuthDoor("POST /register", 201, droppedUris ? "dropped_redirects" : "registered", droppedUris);
|
|
94
580
|
res.status(201).json({
|
|
95
581
|
client_id: clientId,
|
|
96
582
|
client_name: client_name ?? "MCP Client",
|
|
97
|
-
redirect_uris,
|
|
583
|
+
redirect_uris: allowed,
|
|
98
584
|
grant_types: ["authorization_code"],
|
|
99
585
|
response_types: ["code"],
|
|
100
586
|
token_endpoint_auth_method: "none"
|
|
101
587
|
});
|
|
102
588
|
}
|
|
103
589
|
);
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
var refreshTokens = /* @__PURE__ */ new Map();
|
|
590
|
+
app.get("/authorize", authLimiter, (req, res) => {
|
|
591
|
+
sendDoor(res, "GET /authorize", authorizeOutcome(req.query ?? {}, { allowlist: OAUTH_REDIRECT_ALLOWLIST, appUrl: appUrl() }));
|
|
592
|
+
});
|
|
108
593
|
setInterval(() => {
|
|
109
594
|
const now = Date.now();
|
|
110
|
-
for (const [
|
|
111
|
-
if (now
|
|
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) => ({ "&": "&", '"': """, "<": "<", ">": ">" })[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;
|
|
595
|
+
for (const [credentialId, rec] of authFailures) {
|
|
596
|
+
if (rec.blockedUntil < now && rec.firstFailure + AUTH_FAILURE_WINDOW_MS < now) {
|
|
597
|
+
authFailures.delete(credentialId);
|
|
183
598
|
}
|
|
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;
|
|
191
|
-
}
|
|
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
599
|
}
|
|
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
|
-
}
|
|
600
|
+
}, 6e4);
|
|
215
601
|
app.post(
|
|
216
602
|
"/oauth/token",
|
|
217
603
|
express.urlencoded({ extended: false }),
|
|
218
604
|
express.json(),
|
|
219
|
-
(req, res) => {
|
|
220
|
-
|
|
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));
|
|
605
|
+
async (req, res) => {
|
|
606
|
+
sendDoor(res, "POST /oauth/token", await exchangeOutcome(req.body ?? {}, { candidates: keyCheckCandidates() }));
|
|
257
607
|
}
|
|
258
608
|
);
|
|
259
|
-
var
|
|
260
|
-
|
|
261
|
-
max: 120,
|
|
262
|
-
standardHeaders: true,
|
|
263
|
-
legacyHeaders: false,
|
|
264
|
-
message: { error: "Too many requests. Try again later." }
|
|
265
|
-
});
|
|
609
|
+
var mcpLimit = mcpLimiters();
|
|
610
|
+
var authFailures = /* @__PURE__ */ new Map();
|
|
266
611
|
app.get("/health", (_req, res) => {
|
|
267
612
|
res.json({ status: "ok", version: SERVER_VERSION, transport: "http" });
|
|
268
613
|
});
|
|
269
614
|
var sessions = /* @__PURE__ */ new Map();
|
|
270
615
|
var SESSION_TTL_MS = 30 * 60 * 1e3;
|
|
271
616
|
var MAX_SESSIONS = 200;
|
|
617
|
+
var EVICT_GRACE_MS = 6e4;
|
|
618
|
+
var MAX_SESSIONS_PER_KEY = Math.max(
|
|
619
|
+
1,
|
|
620
|
+
Math.min(MAX_SESSIONS - 1, Number(process.env.MCP_MAX_SESSIONS_PER_KEY) || 25)
|
|
621
|
+
);
|
|
272
622
|
function evictStaleSessions() {
|
|
273
623
|
const now = Date.now();
|
|
274
624
|
for (const [id, entry] of sessions) {
|
|
275
625
|
if (now - entry.lastAccess > SESSION_TTL_MS) {
|
|
276
|
-
logSessionLifecycle(
|
|
626
|
+
logSessionLifecycle(
|
|
627
|
+
"session_deleted",
|
|
628
|
+
id,
|
|
629
|
+
entry.inFlight > 0 ? "inflight_leak" : "ttl"
|
|
630
|
+
);
|
|
277
631
|
entry.transport.close().catch(() => {
|
|
278
632
|
});
|
|
279
633
|
sessions.delete(id);
|
|
280
634
|
}
|
|
281
635
|
}
|
|
282
636
|
if (sessions.size > MAX_SESSIONS) {
|
|
283
|
-
const sorted = [...sessions.entries()].sort(
|
|
284
|
-
|
|
285
|
-
);
|
|
286
|
-
for (let i = 0; i < sorted.length - MAX_SESSIONS; i++) {
|
|
637
|
+
const sorted = [...sessions.entries()].filter(([, e]) => e.inFlight === 0).sort((a, b) => a[1].lastAccess - b[1].lastAccess);
|
|
638
|
+
const overflow = sessions.size - MAX_SESSIONS;
|
|
639
|
+
for (let i = 0; i < Math.min(overflow, sorted.length); i++) {
|
|
287
640
|
logSessionLifecycle("session_deleted", sorted[i][0], "eviction");
|
|
288
641
|
sorted[i][1].transport.close().catch(() => {
|
|
289
642
|
});
|
|
290
643
|
sessions.delete(sorted[i][0]);
|
|
291
644
|
}
|
|
645
|
+
if (sessions.size > MAX_SESSIONS) {
|
|
646
|
+
const ts = (/* @__PURE__ */ new Date()).toISOString();
|
|
647
|
+
process.stderr.write(
|
|
648
|
+
`[HTTP] ${ts} session_cap_breach size=${sessions.size} max=${MAX_SESSIONS} reason=all_inflight (no idle sessions to evict; TTL backstop will reclaim)
|
|
649
|
+
`
|
|
650
|
+
);
|
|
651
|
+
}
|
|
292
652
|
}
|
|
293
653
|
}
|
|
294
654
|
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
|
-
}
|
|
301
655
|
function send401(req, res) {
|
|
302
656
|
const base = baseUrl(req);
|
|
303
657
|
res.status(401).set(
|
|
@@ -318,41 +672,137 @@ function logSessionLifecycle(event, sessionId, reason) {
|
|
|
318
672
|
process.stderr.write(`[HTTP] ${ts} ${event} session=${sessionId}${r}
|
|
319
673
|
`);
|
|
320
674
|
}
|
|
321
|
-
app.post("/mcp",
|
|
322
|
-
const
|
|
323
|
-
|
|
675
|
+
app.post("/mcp", ...mcpLimit, async (req, res) => {
|
|
676
|
+
const nowTs = Date.now();
|
|
677
|
+
const auth = resolveBearerAuth(req.headers?.authorization);
|
|
678
|
+
const lockout = authLockoutError(authFailures, auth, nowTs, req.body?.id ?? null);
|
|
679
|
+
if (lockout) {
|
|
680
|
+
send429(res, lockout);
|
|
681
|
+
return;
|
|
682
|
+
}
|
|
683
|
+
if (auth.status !== "ok") {
|
|
324
684
|
logRequest("POST", "auth_fail");
|
|
685
|
+
if (auth.status === "rejected") recordAuthFailure(authFailures, auth.credentialId, nowTs);
|
|
325
686
|
send401(req, res);
|
|
326
687
|
return;
|
|
327
688
|
}
|
|
689
|
+
const apiKey = auth.apiKey;
|
|
328
690
|
const sessionId = req.headers["mcp-session-id"];
|
|
329
691
|
const reqStart = Date.now();
|
|
330
692
|
try {
|
|
331
|
-
await runWithAuth({ apiKey }, async () => {
|
|
693
|
+
await runWithAuth({ apiKey, mcpSessionId: sessionId }, async () => {
|
|
332
694
|
if (sessionId && sessions.has(sessionId)) {
|
|
333
695
|
const entry = sessions.get(sessionId);
|
|
334
|
-
entry.
|
|
335
|
-
|
|
336
|
-
|
|
696
|
+
if (entry.keyHash !== hashKey(apiKey)) {
|
|
697
|
+
res.status(403).json({
|
|
698
|
+
jsonrpc: "2.0",
|
|
699
|
+
error: { code: -32e3, message: "Session key mismatch" },
|
|
700
|
+
id: null
|
|
701
|
+
});
|
|
702
|
+
return;
|
|
703
|
+
}
|
|
704
|
+
try {
|
|
705
|
+
entry.inFlight++;
|
|
706
|
+
entry.lastAccess = Date.now();
|
|
707
|
+
await entry.transport.handleRequest(req, res, req.body);
|
|
708
|
+
logRequest("POST", "ok", sessionId, Date.now() - reqStart);
|
|
709
|
+
} finally {
|
|
710
|
+
entry.inFlight--;
|
|
711
|
+
entry.lastAccess = Date.now();
|
|
712
|
+
}
|
|
337
713
|
} else if (!sessionId && isInitializeRequest(req.body)) {
|
|
714
|
+
const check = await checkKeyAgainstCandidates(keyCheckCandidates(), apiKey, 5e3);
|
|
715
|
+
const gate = keyVerdictGate(check.verdict, authFailures, auth.credentialId, Date.now());
|
|
716
|
+
if (gate === "unauthorized") {
|
|
717
|
+
logRequest("POST", "auth_fail");
|
|
718
|
+
send401(req, res);
|
|
719
|
+
return;
|
|
720
|
+
}
|
|
721
|
+
if (gate === "unavailable") {
|
|
722
|
+
res.status(503).json({
|
|
723
|
+
jsonrpc: "2.0",
|
|
724
|
+
error: { code: -32e3, message: "Product Brain could not verify this API key right now. Retry shortly." },
|
|
725
|
+
id: req.body?.id ?? null
|
|
726
|
+
});
|
|
727
|
+
return;
|
|
728
|
+
}
|
|
729
|
+
if (check.verdict === "ok" || check.verdict === "rate_limited") getKeyState(apiKey).deploymentUrl = check.deploymentUrl;
|
|
730
|
+
const keyH = hashKey(apiKey);
|
|
731
|
+
const plan = planKeyAdmission(
|
|
732
|
+
sessions,
|
|
733
|
+
keyH,
|
|
734
|
+
MAX_SESSIONS_PER_KEY,
|
|
735
|
+
Date.now(),
|
|
736
|
+
{ ttlMs: SESSION_TTL_MS, graceMs: EVICT_GRACE_MS }
|
|
737
|
+
);
|
|
738
|
+
for (const sid2 of plan.evict) {
|
|
739
|
+
const victim = sessions.get(sid2);
|
|
740
|
+
sessions.delete(sid2);
|
|
741
|
+
victim?.transport.close().catch(() => {
|
|
742
|
+
});
|
|
743
|
+
logSessionLifecycle("session_deleted", sid2, "lru_evict");
|
|
744
|
+
}
|
|
745
|
+
if (!plan.admit) {
|
|
746
|
+
send429(res, buildSessionCapError({
|
|
747
|
+
retryAfterSeconds: plan.retryAfterSeconds,
|
|
748
|
+
limit: MAX_SESSIONS_PER_KEY,
|
|
749
|
+
current: countKeySessions(sessions, keyH),
|
|
750
|
+
poll: plan.retryIsPoll,
|
|
751
|
+
id: req.body?.id ?? null
|
|
752
|
+
}));
|
|
753
|
+
return;
|
|
754
|
+
}
|
|
755
|
+
const sid = randomUUID();
|
|
756
|
+
let initialized = false;
|
|
338
757
|
const transport = new StreamableHTTPServerTransport({
|
|
339
|
-
sessionIdGenerator: () =>
|
|
340
|
-
onsessioninitialized: (
|
|
341
|
-
|
|
342
|
-
logSessionLifecycle("session_created",
|
|
758
|
+
sessionIdGenerator: () => sid,
|
|
759
|
+
onsessioninitialized: (s) => {
|
|
760
|
+
initialized = true;
|
|
761
|
+
logSessionLifecycle("session_created", s);
|
|
343
762
|
}
|
|
763
|
+
// log only — no map write
|
|
344
764
|
});
|
|
765
|
+
const reserved = { transport, lastAccess: Date.now(), keyHash: keyH, inFlight: 1 };
|
|
766
|
+
sessions.set(sid, reserved);
|
|
345
767
|
transport.onclose = () => {
|
|
346
|
-
const
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
sessions.delete(
|
|
768
|
+
const s = transport.sessionId ?? sid;
|
|
769
|
+
forgetStreamLifecycle(keyH, s);
|
|
770
|
+
if (sessions.has(s)) {
|
|
771
|
+
sessions.delete(s);
|
|
772
|
+
logSessionLifecycle("session_deleted", s, "onclose");
|
|
350
773
|
}
|
|
351
774
|
};
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
775
|
+
try {
|
|
776
|
+
const server = createProductBrainServer();
|
|
777
|
+
await server.connect(transport);
|
|
778
|
+
await transport.handleRequest(req, res, req.body);
|
|
779
|
+
logRequest("POST", "ok", transport.sessionId ?? void 0, Date.now() - reqStart);
|
|
780
|
+
} catch (e) {
|
|
781
|
+
transport.onclose = void 0;
|
|
782
|
+
sessions.delete(sid);
|
|
783
|
+
throw e;
|
|
784
|
+
} finally {
|
|
785
|
+
if (!initialized) {
|
|
786
|
+
transport.onclose = void 0;
|
|
787
|
+
if (sessions.delete(sid)) logSessionLifecycle("session_deleted", sid, "init_rejected");
|
|
788
|
+
} else {
|
|
789
|
+
const e = sessions.get(sid);
|
|
790
|
+
if (e) {
|
|
791
|
+
e.inFlight--;
|
|
792
|
+
e.lastAccess = Date.now();
|
|
793
|
+
}
|
|
794
|
+
}
|
|
795
|
+
}
|
|
796
|
+
} else if (sessionId) {
|
|
797
|
+
process.stderr.write(
|
|
798
|
+
`[HTTP] ${(/* @__PURE__ */ new Date()).toISOString()} session_stale sessionId=${sessionId} (likely server restart \u2014 instructing client to re-initialise)
|
|
799
|
+
`
|
|
800
|
+
);
|
|
801
|
+
res.status(404).json({
|
|
802
|
+
jsonrpc: "2.0",
|
|
803
|
+
error: { code: -32001, message: "Session not found \u2014 re-initialise" },
|
|
804
|
+
id: null
|
|
805
|
+
});
|
|
356
806
|
} else {
|
|
357
807
|
process.stderr.write(
|
|
358
808
|
`[HTTP] ${(/* @__PURE__ */ new Date()).toISOString()} session_invalid no valid session ID (client may have omitted Mcp-Session-Id)
|
|
@@ -376,21 +826,45 @@ app.post("/mcp", mcpLimiter, async (req, res) => {
|
|
|
376
826
|
}
|
|
377
827
|
}
|
|
378
828
|
});
|
|
379
|
-
app.get("/mcp",
|
|
380
|
-
const
|
|
381
|
-
|
|
829
|
+
app.get("/mcp", ...mcpLimit, async (req, res) => {
|
|
830
|
+
const nowTs = Date.now();
|
|
831
|
+
const auth = resolveBearerAuth(req.headers?.authorization);
|
|
832
|
+
const lockout = authLockoutError(authFailures, auth, nowTs, req.body?.id ?? null);
|
|
833
|
+
if (lockout) {
|
|
834
|
+
send429(res, lockout);
|
|
835
|
+
return;
|
|
836
|
+
}
|
|
837
|
+
if (auth.status !== "ok") {
|
|
382
838
|
logRequest("GET", "auth_fail");
|
|
839
|
+
if (auth.status === "rejected") recordAuthFailure(authFailures, auth.credentialId, nowTs);
|
|
383
840
|
send401(req, res);
|
|
384
841
|
return;
|
|
385
842
|
}
|
|
843
|
+
const apiKey = auth.apiKey;
|
|
386
844
|
const sessionId = req.headers["mcp-session-id"];
|
|
387
|
-
if (!sessionId
|
|
388
|
-
res.status(400).send("
|
|
845
|
+
if (!sessionId) {
|
|
846
|
+
res.status(400).send("Missing Mcp-Session-Id header");
|
|
847
|
+
return;
|
|
848
|
+
}
|
|
849
|
+
if (!sessions.has(sessionId)) {
|
|
850
|
+
process.stderr.write(
|
|
851
|
+
`[HTTP] ${(/* @__PURE__ */ new Date()).toISOString()} session_stale GET sessionId=${sessionId}
|
|
852
|
+
`
|
|
853
|
+
);
|
|
854
|
+
res.status(404).send("Session not found \u2014 re-initialise");
|
|
389
855
|
return;
|
|
390
856
|
}
|
|
391
857
|
try {
|
|
392
|
-
await runWithAuth({ apiKey }, async () => {
|
|
858
|
+
await runWithAuth({ apiKey, mcpSessionId: sessionId }, async () => {
|
|
393
859
|
const entry = sessions.get(sessionId);
|
|
860
|
+
if (entry.keyHash !== hashKey(apiKey)) {
|
|
861
|
+
res.status(403).json({
|
|
862
|
+
jsonrpc: "2.0",
|
|
863
|
+
error: { code: -32e3, message: "Session key mismatch" },
|
|
864
|
+
id: null
|
|
865
|
+
});
|
|
866
|
+
return;
|
|
867
|
+
}
|
|
394
868
|
entry.lastAccess = Date.now();
|
|
395
869
|
await entry.transport.handleRequest(req, res);
|
|
396
870
|
logRequest("GET", "ok", sessionId);
|
|
@@ -399,21 +873,45 @@ app.get("/mcp", mcpLimiter, async (req, res) => {
|
|
|
399
873
|
logRequest("GET", "error", sessionId);
|
|
400
874
|
}
|
|
401
875
|
});
|
|
402
|
-
app.delete("/mcp",
|
|
403
|
-
const
|
|
404
|
-
|
|
876
|
+
app.delete("/mcp", ...mcpLimit, async (req, res) => {
|
|
877
|
+
const nowTs = Date.now();
|
|
878
|
+
const auth = resolveBearerAuth(req.headers?.authorization);
|
|
879
|
+
const lockout = authLockoutError(authFailures, auth, nowTs, req.body?.id ?? null);
|
|
880
|
+
if (lockout) {
|
|
881
|
+
send429(res, lockout);
|
|
882
|
+
return;
|
|
883
|
+
}
|
|
884
|
+
if (auth.status !== "ok") {
|
|
405
885
|
logRequest("DELETE", "auth_fail");
|
|
886
|
+
if (auth.status === "rejected") recordAuthFailure(authFailures, auth.credentialId, nowTs);
|
|
406
887
|
send401(req, res);
|
|
407
888
|
return;
|
|
408
889
|
}
|
|
890
|
+
const apiKey = auth.apiKey;
|
|
409
891
|
const sessionId = req.headers["mcp-session-id"];
|
|
410
|
-
if (!sessionId
|
|
411
|
-
res.status(400).send("
|
|
892
|
+
if (!sessionId) {
|
|
893
|
+
res.status(400).send("Missing Mcp-Session-Id header");
|
|
894
|
+
return;
|
|
895
|
+
}
|
|
896
|
+
if (!sessions.has(sessionId)) {
|
|
897
|
+
process.stderr.write(
|
|
898
|
+
`[HTTP] ${(/* @__PURE__ */ new Date()).toISOString()} session_stale DELETE sessionId=${sessionId}
|
|
899
|
+
`
|
|
900
|
+
);
|
|
901
|
+
res.status(404).send("Session not found \u2014 re-initialise");
|
|
412
902
|
return;
|
|
413
903
|
}
|
|
414
904
|
try {
|
|
415
|
-
await runWithAuth({ apiKey }, async () => {
|
|
905
|
+
await runWithAuth({ apiKey, mcpSessionId: sessionId }, async () => {
|
|
416
906
|
const entry = sessions.get(sessionId);
|
|
907
|
+
if (entry.keyHash !== hashKey(apiKey)) {
|
|
908
|
+
res.status(403).json({
|
|
909
|
+
jsonrpc: "2.0",
|
|
910
|
+
error: { code: -32e3, message: "Session key mismatch" },
|
|
911
|
+
id: null
|
|
912
|
+
});
|
|
913
|
+
return;
|
|
914
|
+
}
|
|
417
915
|
await entry.transport.handleRequest(req, res);
|
|
418
916
|
logRequest("DELETE", "ok", sessionId);
|
|
419
917
|
});
|
|
@@ -439,10 +937,6 @@ async function gracefulShutdown() {
|
|
|
439
937
|
await entry.transport.close().catch(() => {
|
|
440
938
|
});
|
|
441
939
|
}
|
|
442
|
-
try {
|
|
443
|
-
await shutdownAnalytics();
|
|
444
|
-
} catch {
|
|
445
|
-
}
|
|
446
940
|
process.exit(0);
|
|
447
941
|
}
|
|
448
942
|
var LISTEN_HOST = "0.0.0.0";
|