@productbrain/mcp 0.0.1-beta.12 → 0.0.1-beta.12010

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 ADDED
@@ -0,0 +1,1541 @@
1
+ import {
2
+ PRODUCT_NAME,
3
+ SERVER_VERSION,
4
+ createProductBrainServer
5
+ } from "./chunk-E2KS5CTD.js";
6
+ import {
7
+ DEFAULT_CLOUD_URL,
8
+ PASTE_NOW,
9
+ apiKeysUrl,
10
+ bootstrapHttp,
11
+ checkKeyAgainstCandidates,
12
+ forgetStreamLifecycle,
13
+ getKeyState,
14
+ hashKey,
15
+ parseFallbackUrls,
16
+ runWithAuth
17
+ } from "./chunk-LWGNWR3F.js";
18
+
19
+ // src/http.ts
20
+ import { createHash, randomUUID } from "crypto";
21
+ import express from "express";
22
+ import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
23
+ import { isInitializeRequest } from "@modelcontextprotocol/sdk/types.js";
24
+ import rateLimit2 from "express-rate-limit";
25
+
26
+ // src/brand/logo-markup.ts
27
+ var SIZE_CLASSES = {
28
+ sm: "pb-logo--sm",
29
+ md: "pb-logo--md"
30
+ };
31
+ var appLogoStyles = `
32
+ .pb-logo{display:inline-flex;align-items:center;gap:8px;color:inherit}
33
+ .pb-logo__mark{
34
+ border-radius:4px;background:#1c1e24;
35
+ border:1px solid rgba(255,255,255,0.06);
36
+ display:inline-grid;place-items:center;flex-shrink:0;
37
+ }
38
+ .pb-logo__core{border-radius:50%;background:var(--accent,#c9b99a)}
39
+ .pb-logo__name{
40
+ font-family:var(--font-mono,"IBM Plex Mono",ui-monospace,monospace);
41
+ font-weight:500;text-transform:uppercase;
42
+ letter-spacing:0.22em;color:var(--fg4,#6a6560);
43
+ }
44
+ .pb-logo--sm .pb-logo__mark{width:16px;height:16px}
45
+ .pb-logo--sm .pb-logo__core{width:5px;height:5px}
46
+ .pb-logo--sm .pb-logo__name{font-size:10.5px}
47
+ .pb-logo--md .pb-logo__mark{width:24px;height:24px;border-radius:6px}
48
+ .pb-logo--md .pb-logo__core{width:8px;height:8px}
49
+ .pb-logo--md .pb-logo__name{font-size:13px}
50
+ `;
51
+ function appLogoMarkup(opts = {}) {
52
+ const size = opts.size ?? "sm";
53
+ const showWordmark = opts.showWordmark ?? true;
54
+ const cls = ["pb-logo", SIZE_CLASSES[size], opts.className].filter(Boolean).join(" ");
55
+ const wordmark = showWordmark ? `<span class="pb-logo__name">${PRODUCT_NAME}</span>` : "";
56
+ return `<span class="${cls}"><span class="pb-logo__mark"><span class="pb-logo__core"></span></span>${wordmark}</span>`;
57
+ }
58
+
59
+ // src/sessionCap.ts
60
+ function planKeyAdmission(sessions2, keyHash, cap, now, opts) {
61
+ if (cap < 1) {
62
+ throw new RangeError(`cap must be >= 1, got ${cap}`);
63
+ }
64
+ const { ttlMs, graceMs } = opts;
65
+ const isProtected = (s) => s.inFlight > 0 || now - s.lastAccess < graceMs;
66
+ const keyEntries = [];
67
+ for (const [id, session] of sessions2) {
68
+ if (session.keyHash === keyHash) {
69
+ keyEntries.push([id, session]);
70
+ }
71
+ }
72
+ const evictSet = /* @__PURE__ */ new Set();
73
+ for (const [id, session] of keyEntries) {
74
+ if (!isProtected(session) && now - session.lastAccess >= ttlMs) {
75
+ evictSet.add(id);
76
+ }
77
+ }
78
+ let survivors = keyEntries.filter(([id]) => !evictSet.has(id));
79
+ if (survivors.length >= cap) {
80
+ const idleSurvivors = survivors.filter(([, s]) => !isProtected(s)).sort(([, a], [, b]) => a.lastAccess - b.lastAccess);
81
+ for (const [id] of idleSurvivors) {
82
+ if (survivors.length < cap) break;
83
+ evictSet.add(id);
84
+ survivors = survivors.filter(([sid]) => sid !== id);
85
+ }
86
+ }
87
+ const evict = Array.from(evictSet);
88
+ const admit = survivors.length < cap;
89
+ let retryAfterSeconds = 0;
90
+ let retryIsPoll = false;
91
+ if (!admit) {
92
+ const graceBlockers = survivors.filter(([, s]) => s.inFlight === 0);
93
+ if (graceBlockers.length > 0) {
94
+ const minLastAccess = Math.min(...graceBlockers.map(([, s]) => s.lastAccess));
95
+ const msRemaining = graceMs - (now - minLastAccess);
96
+ retryAfterSeconds = Math.max(1, Math.ceil(msRemaining / 1e3));
97
+ } else {
98
+ retryAfterSeconds = 5;
99
+ retryIsPoll = true;
100
+ }
101
+ }
102
+ return { evict, admit, retryAfterSeconds, retryIsPoll };
103
+ }
104
+ function countKeySessions(sessions2, keyHash) {
105
+ let count = 0;
106
+ for (const session of sessions2.values()) {
107
+ if (session.keyHash === keyHash) count++;
108
+ }
109
+ return count;
110
+ }
111
+
112
+ // src/httpErrors.ts
113
+ function clampSeconds(s) {
114
+ return Math.max(0, Math.round(s));
115
+ }
116
+ function build(reason, message, p) {
117
+ const seconds = clampSeconds(p.retryAfterSeconds);
118
+ return {
119
+ status: 429,
120
+ headers: { "Retry-After": String(seconds) },
121
+ body: {
122
+ jsonrpc: "2.0",
123
+ id: p.id ?? null,
124
+ error: {
125
+ code: -32e3,
126
+ message,
127
+ data: {
128
+ reason,
129
+ retryAfterSeconds: seconds,
130
+ limit: p.limit,
131
+ current: p.current
132
+ }
133
+ }
134
+ }
135
+ };
136
+ }
137
+ function buildRateLimitError(p) {
138
+ const seconds = clampSeconds(p.retryAfterSeconds);
139
+ return build(
140
+ "rate_limited",
141
+ `Too many requests \u2014 retry after ${seconds} s.`,
142
+ p
143
+ );
144
+ }
145
+ function buildAuthLockoutError(p) {
146
+ const seconds = clampSeconds(p.retryAfterSeconds);
147
+ return build(
148
+ "auth_lockout",
149
+ `Too many failed auth attempts \u2014 locked out, retry after ${seconds} s.`,
150
+ p
151
+ );
152
+ }
153
+ function buildSessionCapError(p) {
154
+ const seconds = clampSeconds(p.retryAfterSeconds);
155
+ const message = p.poll ? "Server busy \u2014 all sessions active; retry shortly." : `Too many active sessions for this key \u2014 retry after ${seconds} s.`;
156
+ return build("session_cap", message, p);
157
+ }
158
+ function send429(res, built) {
159
+ if (res.headersSent) return;
160
+ for (const [k, v] of Object.entries(built.headers)) {
161
+ res.setHeader(k, v);
162
+ }
163
+ res.status(built.status).json(built.body);
164
+ }
165
+
166
+ // src/mcpRateLimit.ts
167
+ import rateLimit from "express-rate-limit";
168
+
169
+ // src/authLockout.ts
170
+ var AUTH_FAILURE_MAX = 10;
171
+ var AUTH_FAILURE_WINDOW_MS = 5 * 6e4;
172
+ var AUTH_BLOCK_DURATION_MS = 15 * 6e4;
173
+ var MAX_AUTH_FAILURE_ENTRIES = 1e4;
174
+ function rejected(presented) {
175
+ return { status: "rejected", credentialId: hashKey(presented) };
176
+ }
177
+ function resolveBearerAuth(authorizationHeader) {
178
+ if (typeof authorizationHeader !== "string" || authorizationHeader.trim() === "") {
179
+ return { status: "absent" };
180
+ }
181
+ if (!authorizationHeader.startsWith("Bearer ")) {
182
+ return rejected(authorizationHeader.trim());
183
+ }
184
+ const token = authorizationHeader.slice(7).trim();
185
+ if (!token.startsWith("pb_sk_")) return rejected(token);
186
+ return { status: "ok", apiKey: token, credentialId: hashKey(token) };
187
+ }
188
+ function resolvePastedKey(apiKey) {
189
+ if (apiKey === "") return { status: "absent" };
190
+ if (!apiKey.startsWith("pb_sk_")) return rejected(apiKey);
191
+ return { status: "ok", apiKey, credentialId: hashKey(apiKey) };
192
+ }
193
+ function isCrossSiteFormPost(origin, secFetchSite, ownOrigin) {
194
+ if (secFetchSite === "cross-site") return true;
195
+ if (typeof origin !== "string" || origin === "") return false;
196
+ try {
197
+ return new URL(origin).origin !== new URL(ownOrigin).origin;
198
+ } catch {
199
+ return true;
200
+ }
201
+ }
202
+ function checkAuthBlock(failures, credentialId, now) {
203
+ const rec = failures.get(credentialId);
204
+ if (!rec) return false;
205
+ return rec.blockedUntil > now;
206
+ }
207
+ function authLockoutError(failures, auth, now, id = null) {
208
+ if (auth.status === "absent") return null;
209
+ const rec = failures.get(auth.credentialId);
210
+ if (!rec || !checkAuthBlock(failures, auth.credentialId, now)) return null;
211
+ const retryAfterSeconds = Math.max(0, Math.ceil((rec.blockedUntil - now) / 1e3));
212
+ return buildAuthLockoutError({ retryAfterSeconds, limit: AUTH_FAILURE_MAX, current: rec.count, id });
213
+ }
214
+ function recordAuthFailure(failures, credentialId, now) {
215
+ const rec = failures.get(credentialId);
216
+ if (!rec) {
217
+ if (failures.size >= MAX_AUTH_FAILURE_ENTRIES) {
218
+ const oldest = failures.keys().next().value;
219
+ if (oldest !== void 0) failures.delete(oldest);
220
+ }
221
+ failures.set(credentialId, { count: 1, firstFailure: now, blockedUntil: 0 });
222
+ return;
223
+ }
224
+ if (now - rec.firstFailure > AUTH_FAILURE_WINDOW_MS) {
225
+ rec.count = 1;
226
+ rec.firstFailure = now;
227
+ rec.blockedUntil = 0;
228
+ } else {
229
+ rec.count++;
230
+ if (rec.count >= AUTH_FAILURE_MAX) {
231
+ rec.blockedUntil = now + AUTH_BLOCK_DURATION_MS;
232
+ }
233
+ }
234
+ }
235
+ function keyVerdictGate(verdict, failures, credentialId, now) {
236
+ if (verdict === "ok" || verdict === "rate_limited") return "admit";
237
+ if (verdict === "rejected") {
238
+ recordAuthFailure(failures, credentialId, now);
239
+ return "unauthorized";
240
+ }
241
+ return "unavailable";
242
+ }
243
+
244
+ // src/mcpRateLimit.ts
245
+ var MCP_KEY_LIMIT = 120;
246
+ var MCP_IP_CEILING = 1200;
247
+ function mcpRateKey(req) {
248
+ const auth = resolveBearerAuth(req.headers?.authorization);
249
+ return auth.status === "absent" ? `ip:${req.ip ?? ""}` : `key:${auth.credentialId}`;
250
+ }
251
+ function limiter(max, windowMs, keyGenerator) {
252
+ return rateLimit({
253
+ windowMs,
254
+ max,
255
+ standardHeaders: true,
256
+ legacyHeaders: false,
257
+ ...keyGenerator ? { keyGenerator } : {},
258
+ handler: (req, res) => {
259
+ const r = req.rateLimit;
260
+ const reset = r?.resetTime?.getTime?.() ?? Date.now() + windowMs;
261
+ send429(res, buildRateLimitError({
262
+ retryAfterSeconds: Math.max(1, Math.ceil((reset - Date.now()) / 1e3)),
263
+ limit: r?.limit ?? max,
264
+ current: r?.used ?? 0,
265
+ id: req.body?.id ?? null
266
+ // mirror the JSON-RPC id when a POST body is present
267
+ }));
268
+ }
269
+ });
270
+ }
271
+ function mcpLimiters(opts = {}) {
272
+ const windowMs = opts.windowMs ?? 6e4;
273
+ return [
274
+ limiter(opts.ipCeiling ?? MCP_IP_CEILING, windowMs),
275
+ limiter(opts.keyLimit ?? MCP_KEY_LIMIT, windowMs, mcpRateKey)
276
+ ];
277
+ }
278
+
279
+ // src/lib/oauthRedirectAllowlist.ts
280
+ var DEFAULT_OAUTH_REDIRECT_URIS = [
281
+ "https://claude.ai/api/mcp/auth_callback",
282
+ "https://claude.com/api/mcp/auth_callback",
283
+ "https://chatgpt.com/connector_platform_oauth_redirect",
284
+ "https://www.cursor.com/agents/mcp/oauth/callback"
285
+ ];
286
+ var CHATGPT_CONNECTOR_CALLBACK = /^https:\/\/chatgpt\.com\/connector\/oauth\/[A-Za-z0-9_-]+$/;
287
+ var LOOPBACK_HOSTS = ["localhost", "127.0.0.1", "[::1]"];
288
+ var MAX_REDIRECT_URI_LENGTH = 2048;
289
+ var MAX_REGISTRATION_REDIRECTS = 10;
290
+ 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)";
291
+ function exactForm(url) {
292
+ return `${url.origin}${url.pathname}`;
293
+ }
294
+ function parseRedirectUriAllowlist(raw) {
295
+ if (!raw) return { uris: [], configError: null };
296
+ const uris = [];
297
+ for (const part of raw.split(",")) {
298
+ const trimmed = part.trim();
299
+ if (!trimmed) continue;
300
+ let url = null;
301
+ try {
302
+ url = trimmed.includes("://") ? new URL(trimmed) : null;
303
+ } catch {
304
+ url = null;
305
+ }
306
+ const valid = url !== null && url.protocol === "https:" && !url.username && !url.password && !url.search && !url.hash && (url.port === "" || url.port === "443") && url.pathname !== "/";
307
+ if (!valid || url === null) {
308
+ return { uris: [], configError: `${OPERATOR_ENTRY_FORM}; got "${trimmed}"` };
309
+ }
310
+ uris.push(exactForm(url));
311
+ }
312
+ return { uris, configError: null };
313
+ }
314
+ function resolveOAuthRedirectAllowlist(opts = {}) {
315
+ const parsed = parseRedirectUriAllowlist(opts.explicitAllowlist);
316
+ return {
317
+ uris: [.../* @__PURE__ */ new Set([...DEFAULT_OAUTH_REDIRECT_URIS, ...parsed.uris])],
318
+ configError: parsed.configError
319
+ };
320
+ }
321
+ function checkRedirectUri(redirectUri, allowlist) {
322
+ if (allowlist.configError) return `OAuth is misconfigured: ${allowlist.configError}`;
323
+ if (typeof redirectUri !== "string" || redirectUri.length === 0) {
324
+ return "redirect_uri is required";
325
+ }
326
+ if (redirectUri.length > MAX_REDIRECT_URI_LENGTH) {
327
+ return `redirect_uri is longer than ${MAX_REDIRECT_URI_LENGTH} characters`;
328
+ }
329
+ let url;
330
+ try {
331
+ url = new URL(redirectUri);
332
+ } catch {
333
+ return "redirect_uri is not a valid absolute URL";
334
+ }
335
+ if (url.username || url.password) return "redirect_uri must not contain credentials";
336
+ if (url.hash) return "redirect_uri must not contain a fragment";
337
+ const host = url.hostname.toLowerCase();
338
+ if (url.protocol === "http:") {
339
+ return LOOPBACK_HOSTS.includes(host) ? null : "redirect_uri must use https (http is allowed only for localhost, 127.0.0.1 or [::1])";
340
+ }
341
+ if (url.protocol === "https:") {
342
+ if (url.port && url.port !== "443") return "redirect_uri must use the default https port (443)";
343
+ if (url.search) return "redirect_uri must not contain a query";
344
+ const exact = exactForm(url);
345
+ 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)";
346
+ }
347
+ return "redirect_uri scheme is not allowed (use https, or http on loopback)";
348
+ }
349
+ function checkRegistrationRedirects(redirectUris, allowlist) {
350
+ const refused = (refusal) => ({ refusal, allowed: [], dropped: [] });
351
+ if (!Array.isArray(redirectUris) || redirectUris.length === 0) return refused("redirect_uris is required");
352
+ if (redirectUris.length > MAX_REGISTRATION_REDIRECTS) {
353
+ return refused(`redirect_uris may hold at most ${MAX_REGISTRATION_REDIRECTS} entries`);
354
+ }
355
+ const allowed = [];
356
+ const dropped = [];
357
+ for (const uri of redirectUris) {
358
+ const reason = checkRedirectUri(uri, allowlist);
359
+ if (reason) dropped.push({ uri, reason });
360
+ else allowed.push(uri);
361
+ }
362
+ return { refusal: allowed.length === 0 ? dropped[0].reason : null, allowed, dropped };
363
+ }
364
+
365
+ // src/lib/oauthAuthCode.ts
366
+ function normalisePastedKey(raw) {
367
+ if (typeof raw !== "string") return "";
368
+ const trimmed = raw.trim();
369
+ const first = trimmed[0];
370
+ if (trimmed.length >= 2 && (first === '"' || first === "'" || first === "`") && trimmed.endsWith(first)) {
371
+ return trimmed.slice(1, -1).trim();
372
+ }
373
+ return trimmed;
374
+ }
375
+ function pendingCodeRefusal(pending, redirectUri, now) {
376
+ if (!pending) return "unknown_code";
377
+ if (pending.redirectUri !== redirectUri) return "redirect_mismatch";
378
+ if (now > pending.expiresAt) return "expired";
379
+ return null;
380
+ }
381
+ function tokenResponse(apiKey) {
382
+ return {
383
+ access_token: apiKey,
384
+ token_type: "Bearer",
385
+ // 1 year: validity is enforced by Convex on every call, not by this clock.
386
+ expires_in: 365 * 24 * 3600
387
+ };
388
+ }
389
+
390
+ // src/http.ts
391
+ bootstrapHttp();
392
+ var PORT = parseInt(process.env.PORT ?? process.env.MCP_PORT ?? "3002", 10);
393
+ function keyCheckCandidates() {
394
+ const primaryUrl = (process.env.CONVEX_SITE_URL ?? DEFAULT_CLOUD_URL).replace(/\/$/, "");
395
+ return [primaryUrl, ...parseFallbackUrls(process.env.CONVEX_FALLBACK_URLS).map((u) => u.replace(/\/$/, ""))];
396
+ }
397
+ function baseUrl(req) {
398
+ const proto = req.headers["x-forwarded-proto"] ?? req.protocol ?? "http";
399
+ const host = req.headers.host ?? `localhost:${PORT}`;
400
+ return `${proto}://${host}`;
401
+ }
402
+ var app = express();
403
+ app.set("trust proxy", 1);
404
+ app.use(express.json());
405
+ var ALLOWED_ORIGINS = (process.env.CORS_ORIGINS ?? "https://claude.ai").split(",").map((o) => o.trim()).filter(Boolean);
406
+ var OAUTH_REDIRECT_ALLOWLIST = resolveOAuthRedirectAllowlist({ explicitAllowlist: process.env.OAUTH_REDIRECT_HOST_ALLOWLIST });
407
+ app.use((_req, res, next) => {
408
+ const origin = _req.headers.origin;
409
+ if (origin && ALLOWED_ORIGINS.includes(origin)) {
410
+ res.setHeader("Access-Control-Allow-Origin", origin);
411
+ }
412
+ res.setHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS");
413
+ res.setHeader(
414
+ "Access-Control-Allow-Headers",
415
+ "Content-Type, Authorization, Mcp-Session-Id, Last-Event-Id"
416
+ );
417
+ res.setHeader("Access-Control-Expose-Headers", "Mcp-Session-Id, Retry-After");
418
+ if (_req.method === "OPTIONS") {
419
+ res.status(204).end();
420
+ return;
421
+ }
422
+ next();
423
+ });
424
+ app.get("/.well-known/oauth-protected-resource", (req, res) => {
425
+ const base = baseUrl(req);
426
+ res.json({
427
+ resource: base,
428
+ authorization_servers: [base],
429
+ scopes_supported: ["mcp:tools", "mcp:resources"],
430
+ bearer_methods_supported: ["header"]
431
+ });
432
+ });
433
+ app.get("/.well-known/oauth-authorization-server", (req, res) => {
434
+ const base = baseUrl(req);
435
+ res.json({
436
+ issuer: base,
437
+ authorization_endpoint: `${base}/authorize`,
438
+ token_endpoint: `${base}/oauth/token`,
439
+ registration_endpoint: `${base}/register`,
440
+ response_types_supported: ["code"],
441
+ grant_types_supported: ["authorization_code"],
442
+ // TEN-4548: no refresh grant (lib/oauthAuthCode.ts tokenResponse)
443
+ code_challenge_methods_supported: ["S256"],
444
+ token_endpoint_auth_methods_supported: ["none"],
445
+ scopes_supported: ["mcp:tools", "mcp:resources"]
446
+ });
447
+ });
448
+ function logOAuthDoor(door, status, reason, uris) {
449
+ const list = uris === void 0 ? "" : ` uris=${JSON.stringify(uris.map(String)).slice(0, 600)}`;
450
+ process.stderr.write(`[oauth] door=${door} status=${status} reason=${JSON.stringify(reason)}${list}
451
+ `);
452
+ }
453
+ var authLimiter = rateLimit2({
454
+ windowMs: 6e4,
455
+ max: 20,
456
+ standardHeaders: true,
457
+ legacyHeaders: false,
458
+ handler: (req, res) => {
459
+ logOAuthDoor(`${req.method} /authorize`, 429, "rate_limited_per_ip");
460
+ res.status(429).json({ error: "Too many auth requests. Try again later." });
461
+ }
462
+ });
463
+ app.post(
464
+ "/register",
465
+ express.json(),
466
+ (req, res) => {
467
+ const { redirect_uris, client_name } = req.body ?? {};
468
+ const { refusal, allowed, dropped } = checkRegistrationRedirects(redirect_uris, OAUTH_REDIRECT_ALLOWLIST);
469
+ if (refusal) {
470
+ logOAuthDoor("POST /register", 400, refusal, Array.isArray(redirect_uris) ? redirect_uris : [redirect_uris]);
471
+ res.status(400).json({ error: "invalid_redirect_uri", error_description: refusal });
472
+ return;
473
+ }
474
+ const clientId = `pb_client_${randomUUID()}`;
475
+ const droppedUris = dropped.length > 0 ? dropped.map((d) => d.uri) : void 0;
476
+ logOAuthDoor("POST /register", 201, droppedUris ? "dropped_redirects" : "registered", droppedUris);
477
+ res.status(201).json({
478
+ client_id: clientId,
479
+ client_name: client_name ?? "MCP Client",
480
+ redirect_uris: allowed,
481
+ grant_types: ["authorization_code"],
482
+ response_types: ["code"],
483
+ token_endpoint_auth_method: "none"
484
+ });
485
+ }
486
+ );
487
+ var pendingCodes = /* @__PURE__ */ new Map();
488
+ setInterval(() => {
489
+ const now = Date.now();
490
+ for (const [code, auth] of pendingCodes) {
491
+ if (now > auth.expiresAt) pendingCodes.delete(code);
492
+ }
493
+ for (const [credentialId, rec] of authFailures) {
494
+ if (rec.blockedUntil < now && rec.firstFailure + AUTH_FAILURE_WINDOW_MS < now) {
495
+ authFailures.delete(credentialId);
496
+ }
497
+ }
498
+ }, 6e4);
499
+ function esc(s) {
500
+ return String(s ?? "").replace(
501
+ /[&"'<>]/g,
502
+ (c) => ({ "&": "&amp;", '"': "&quot;", "'": "&#39;", "<": "&lt;", ">": "&gt;" })[c]
503
+ );
504
+ }
505
+ function authPageShell(title, bodyContent, headExtra = "") {
506
+ return `<!DOCTYPE html>
507
+ <html lang="en" data-theme="parchment-dark"><head>
508
+ <meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
509
+ <title>${esc(title)} \u2014 Product Brain</title>
510
+ <link rel="preconnect" href="https://fonts.googleapis.com">
511
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
512
+ <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Source+Serif+4:opsz,wght@8..60,600&family=IBM+Plex+Sans:wght@400;500;600;700&family=IBM+Plex+Mono:wght@400;500;700&display=swap">
513
+ ${headExtra}
514
+ <style>
515
+ :root{
516
+ --bg:#1a1917;--bg-warm:#201f1c;--surface:#262521;
517
+ --fg1:#e4e0d8;--fg2:#c4bfb4;--fg3:#9a9589;--fg4:#6a6560;--fg-bright:#ffffff;
518
+ --border:rgba(255,255,255,0.07);--border-light:rgba(255,255,255,0.04);
519
+ --accent:#c9b99a;
520
+ --btn-bg:#ffffff;--btn-fg:#1a1917;--btn-hover:#e4e0d8;
521
+ --green:#4ade80;--rose:#ef4444;
522
+ --ghost:rgba(38,37,33,0.55);
523
+ --radius-md:7px;--radius-lg:10px;
524
+ --font-display:"Source Serif 4",ui-serif,Georgia,serif;
525
+ --font-body:"IBM Plex Sans",ui-sans-serif,system-ui,sans-serif;
526
+ --font-mono:"IBM Plex Mono",ui-monospace,"SF Mono",Menlo,monospace;
527
+ }
528
+ *,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
529
+ html,body{height:100%}
530
+ body{
531
+ font-family:var(--font-body);font-size:13px;line-height:1.45;
532
+ color:var(--fg1);background:var(--bg);
533
+ min-height:100vh;display:grid;place-items:center;padding:24px;
534
+ -webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;
535
+ position:relative;overflow:hidden;
536
+ }
537
+ body::before{
538
+ content:"";position:fixed;inset:0;
539
+ background:radial-gradient(900px 600px at 50% 50%,rgba(228,224,216,0.025),transparent 60%);
540
+ pointer-events:none;z-index:0;
541
+ }
542
+ .top-mark{position:fixed;top:22px;left:24px;z-index:5;opacity:0.7}
543
+ ${appLogoStyles}
544
+ .stage{
545
+ width:100%;max-width:460px;text-align:center;
546
+ position:relative;z-index:1;
547
+ display:grid;
548
+ }
549
+ .panel{
550
+ grid-area:1/1;
551
+ transition:opacity 280ms ease-out,transform 380ms cubic-bezier(.2,.6,.2,1),filter 380ms ease-out;
552
+ }
553
+ .panel[hidden]{
554
+ display:block !important;
555
+ opacity:0;transform:scale(0.96) translateY(-2px);filter:blur(6px);
556
+ pointer-events:none;
557
+ }
558
+ .panel:not([hidden]){opacity:1;transform:scale(1);filter:none;pointer-events:auto}
559
+
560
+ /* eyebrows */
561
+ .eyebrow{
562
+ font-family:var(--font-mono);font-size:10px;font-weight:700;
563
+ letter-spacing:0.28em;text-transform:uppercase;color:var(--fg4);
564
+ margin-bottom:24px;display:inline-flex;align-items:center;gap:7px;
565
+ }
566
+ .eyebrow .dot{width:5px;height:5px;border-radius:50%;background:currentColor}
567
+ .eyebrow.danger{color:var(--rose)}
568
+ .eyebrow.success{color:var(--green)}
569
+ .eyebrow.success .dot{box-shadow:0 0 0 3px rgba(74,222,128,0.18)}
570
+
571
+ /* form input */
572
+ .input-wrap{
573
+ display:flex;align-items:center;background:rgba(0,0,0,0.22);
574
+ border:1px solid var(--border);border-radius:var(--radius-md);
575
+ transition:border-color 200ms ease-out,box-shadow 200ms ease-out;
576
+ }
577
+ .input-wrap:focus-within{
578
+ border-color:rgba(228,224,216,0.45);
579
+ box-shadow:0 0 0 3px rgba(228,224,216,0.10);
580
+ }
581
+ .input-wrap.has-error{
582
+ border-color:rgba(239,68,68,0.55);
583
+ box-shadow:0 0 0 3px rgba(239,68,68,0.12);
584
+ animation:shake 360ms cubic-bezier(.36,.07,.19,.97);
585
+ }
586
+ @keyframes shake{
587
+ 10%,90%{transform:translateX(-1px)}20%,80%{transform:translateX(2px)}
588
+ 30%,50%,70%{transform:translateX(-4px)}40%,60%{transform:translateX(4px)}
589
+ }
590
+ .input{
591
+ flex:1;min-width:0;background:transparent;border:0;outline:none;
592
+ padding:16px;
593
+ font-family:var(--font-mono);font-size:14px;color:var(--fg1);letter-spacing:0.02em;
594
+ }
595
+ .input::placeholder{color:var(--fg4)}
596
+ .hint{
597
+ margin-top:10px;font-family:var(--font-mono);font-size:10.5px;
598
+ letter-spacing:0.16em;text-transform:uppercase;
599
+ text-align:left;padding-left:4px;height:14px;color:var(--fg4);
600
+ transition:color 160ms ease-out;
601
+ }
602
+ .hint.is-error{color:var(--rose)}
603
+
604
+ /* primary button */
605
+ .btn-primary{
606
+ width:100%;height:48px;margin-top:14px;
607
+ border:0;border-radius:var(--radius-md);
608
+ background:var(--btn-bg);color:var(--btn-fg);
609
+ font-family:var(--font-body);font-size:14.5px;font-weight:600;letter-spacing:-0.005em;
610
+ cursor:pointer;display:inline-flex;align-items:center;justify-content:center;gap:10px;
611
+ transition:background 140ms ease-out,transform 80ms ease-out,opacity 200ms ease-out;
612
+ position:relative;overflow:hidden;
613
+ }
614
+ .btn-primary:hover:not([disabled]){background:var(--btn-hover)}
615
+ .btn-primary:active:not([disabled]){transform:translateY(1px)}
616
+ .btn-primary[disabled]{opacity:0.45;cursor:default}
617
+ .spin{
618
+ width:14px;height:14px;border-radius:50%;
619
+ border:1.5px solid currentColor;border-top-color:transparent;
620
+ animation:spin 700ms linear infinite;opacity:0.85;
621
+ }
622
+ @keyframes spin{to{transform:rotate(360deg)}}
623
+
624
+ /* secondary link */
625
+ .small-link{
626
+ margin-top:18px;font-family:var(--font-mono);font-size:11px;
627
+ letter-spacing:0.18em;text-transform:uppercase;color:var(--fg4);
628
+ }
629
+ .small-link a{
630
+ color:var(--fg3);text-decoration:none;border-bottom:1px dotted currentColor;
631
+ padding-bottom:1px;transition:color 140ms;
632
+ }
633
+ .small-link a:hover{color:var(--fg1)}
634
+
635
+ /* orb */
636
+ .orb-wrap{
637
+ position:relative;width:160px;height:160px;margin:0 auto 36px;
638
+ display:grid;place-items:center;
639
+ }
640
+ .orb-ring{position:absolute;border-radius:50%}
641
+ .orb-ring.r1{inset:0;border:1px solid rgba(228,224,216,0.06);animation:drift1 40s linear infinite}
642
+ .orb-ring.r2{inset:18px;border:1px dashed rgba(228,224,216,0.10);animation:drift2 28s linear infinite}
643
+ .orb-ring.r3{inset:38px;border:1px solid rgba(74,222,128,0.20);animation:ringPulse 3.4s ease-in-out infinite}
644
+ @keyframes drift1{to{transform:rotate(360deg)}}
645
+ @keyframes drift2{to{transform:rotate(-360deg)}}
646
+ @keyframes ringPulse{0%,100%{opacity:0.6}50%{opacity:1}}
647
+
648
+ .orb-wrap.is-verifying .orb-ring.r3{
649
+ border-color:rgba(228,224,216,0.20);
650
+ animation:ringPulse 1.1s ease-in-out infinite;
651
+ }
652
+ .orb-wrap.is-verifying .orb-core{
653
+ box-shadow:0 0 0 6px rgba(228,224,216,0.04),0 0 22px rgba(228,224,216,0.10),inset 0 0 16px rgba(228,224,216,0.06);
654
+ animation:corePulseNeutral 1.6s ease-in-out infinite;
655
+ }
656
+ .orb-wrap.is-verifying .orb-dot{background:var(--fg3);box-shadow:0 0 10px rgba(228,224,216,0.4)}
657
+ @keyframes corePulseNeutral{
658
+ 0%,100%{box-shadow:0 0 0 6px rgba(228,224,216,0.04),0 0 22px rgba(228,224,216,0.10),inset 0 0 16px rgba(228,224,216,0.06)}
659
+ 50%{box-shadow:0 0 0 9px rgba(228,224,216,0.07),0 0 32px rgba(228,224,216,0.18),inset 0 0 22px rgba(228,224,216,0.10)}
660
+ }
661
+
662
+ .orb-wrap.is-error .orb-ring.r3{border-color:rgba(239,68,68,0.30);animation:none;opacity:1}
663
+ .orb-wrap.is-error .orb-ring.r1,.orb-wrap.is-error .orb-ring.r2{animation-play-state:paused}
664
+ .orb-wrap.is-error .orb-core{
665
+ box-shadow:0 0 0 6px rgba(239,68,68,0.05),0 0 22px rgba(239,68,68,0.20),inset 0 0 16px rgba(239,68,68,0.08);
666
+ animation:none;
667
+ }
668
+ .orb-wrap.is-error .orb-dot{background:var(--rose);box-shadow:0 0 10px rgba(239,68,68,0.6)}
669
+
670
+ .sat-orbit{position:absolute;inset:0;pointer-events:none}
671
+ .sat-orbit.o1{animation:drift1 40s linear infinite}
672
+ .sat-orbit.o2{animation:drift2 56s linear infinite}
673
+ .sat{
674
+ position:absolute;top:50%;left:50%;
675
+ font-family:var(--font-mono);font-size:9px;font-weight:700;letter-spacing:0.14em;
676
+ background:var(--bg);padding:2px 6px;border-radius:3px;
677
+ border:1px solid var(--border-light);
678
+ transform-origin:0 0;opacity:0;
679
+ }
680
+ .panel:not([hidden])[data-state="connected"] .sat{animation:satIn 600ms ease-out forwards}
681
+ @keyframes satIn{from{opacity:0}to{opacity:1}}
682
+ .sat span{display:inline-block;animation:counter 40s linear infinite}
683
+ .sat-orbit.o2 .sat span{animation:counter2 56s linear infinite}
684
+ @keyframes counter{to{transform:rotate(-360deg)}}
685
+ @keyframes counter2{to{transform:rotate(360deg)}}
686
+
687
+ .orb-core{
688
+ position:relative;width:60px;height:60px;border-radius:50%;
689
+ background:radial-gradient(circle at 50% 45%,#1a1a1a 0%,#0c0c0c 60%,#050505 100%);
690
+ border:1px solid rgba(255,255,255,0.06);
691
+ display:grid;place-items:center;
692
+ box-shadow:0 0 0 6px rgba(74,222,128,0.04),0 0 28px rgba(74,222,128,0.20),inset 0 0 18px rgba(74,222,128,0.08);
693
+ animation:corePulse 3.4s ease-in-out infinite;
694
+ }
695
+ @keyframes corePulse{
696
+ 0%,100%{box-shadow:0 0 0 6px rgba(74,222,128,0.04),0 0 24px rgba(74,222,128,0.18),inset 0 0 16px rgba(74,222,128,0.06)}
697
+ 50%{box-shadow:0 0 0 9px rgba(74,222,128,0.06),0 0 40px rgba(74,222,128,0.32),inset 0 0 22px rgba(74,222,128,0.14)}
698
+ }
699
+ .orb-dot{width:10px;height:10px;border-radius:50%;background:#4ade80;box-shadow:0 0 12px rgba(74,222,128,0.7)}
700
+
701
+ .core-shockwave{
702
+ position:absolute;inset:0;border-radius:50%;
703
+ border:1px solid rgba(74,222,128,0.6);
704
+ opacity:0;pointer-events:none;
705
+ }
706
+ .panel:not([hidden])[data-state="connected"] .core-shockwave{animation:shock 1100ms ease-out 200ms}
707
+ @keyframes shock{
708
+ 0%{opacity:0.7;transform:scale(0.4);border-width:2px}
709
+ 100%{opacity:0;transform:scale(2.4);border-width:1px}
710
+ }
711
+
712
+ /* titles */
713
+ .ok-title{
714
+ font-family:var(--font-display);font-weight:600;
715
+ font-size:38px;line-height:1.05;letter-spacing:-0.025em;
716
+ color:var(--fg-bright);opacity:0;
717
+ }
718
+ .panel:not([hidden]) .ok-title{animation:rise 600ms ease-out 380ms forwards}
719
+ .ok-lead{
720
+ margin:18px auto 0;max-width:22em;font-size:16px;line-height:1.55;color:var(--fg2);
721
+ opacity:0;
722
+ }
723
+ .panel:not([hidden]) .ok-lead{animation:rise 600ms ease-out 500ms forwards}
724
+ .ok-phrase-row{
725
+ margin-top:14px;display:flex;align-items:center;justify-content:center;
726
+ opacity:0;
727
+ }
728
+ .panel:not([hidden]) .ok-phrase-row{animation:rise 600ms ease-out 620ms forwards}
729
+ .cmd.is-copied .cmd-quote-part{display:none}
730
+ .success-cta-wrap{
731
+ margin-top:48px;width:100%;opacity:0;
732
+ }
733
+ .panel:not([hidden]) .success-cta-wrap{animation:rise 600ms ease-out 780ms forwards}
734
+ a.btn-primary.success-cta{color:var(--btn-fg);text-decoration:none}
735
+
736
+ .cmd{
737
+ display:inline-flex;align-items:center;gap:8px;vertical-align:middle;
738
+ font-family:var(--font-mono);font-size:15px;font-weight:500;color:var(--accent);
739
+ background:rgba(201,185,154,0.08);border:1px solid rgba(201,185,154,0.30);
740
+ padding:5px 10px 5px 12px;border-radius:6px;letter-spacing:0.02em;
741
+ cursor:pointer;user-select:none;
742
+ transition:background 140ms ease-out,border-color 140ms ease-out,color 140ms ease-out;
743
+ }
744
+ .cmd:hover{background:rgba(201,185,154,0.14);border-color:rgba(201,185,154,0.50);color:#dcc9a4}
745
+ .cmd.is-copied{color:var(--green);border-color:rgba(74,222,128,0.35);background:rgba(74,222,128,0.08)}
746
+ .cmd .cmd-icon{
747
+ width:12px;height:12px;color:currentColor;opacity:0.75;
748
+ display:inline-grid;place-items:center;
749
+ transition:opacity 140ms;
750
+ }
751
+ .cmd:hover .cmd-icon{opacity:1}
752
+ .cmd.is-copied .cmd-icon{color:var(--green);opacity:1}
753
+ .cmd .cmd-icon svg{width:12px;height:12px;stroke:currentColor;fill:none;stroke-width:1.5;stroke-linecap:round;stroke-linejoin:round}
754
+
755
+ /* error specifics */
756
+ .err-title{
757
+ font-family:var(--font-display);font-weight:600;
758
+ font-size:32px;line-height:1.1;letter-spacing:-0.02em;
759
+ color:var(--fg1);margin-bottom:12px;
760
+ }
761
+ .err-msg{
762
+ font-size:14.5px;line-height:1.55;color:var(--fg3);
763
+ margin-bottom:28px;
764
+ }
765
+ .err-msg code{
766
+ font-family:var(--font-mono);font-size:12px;
767
+ background:rgba(255,255,255,0.06);padding:1px 5px;border-radius:4px;color:var(--fg2);
768
+ }
769
+ .err-actions{display:flex;gap:8px}
770
+ .btn-secondary{
771
+ flex:1;height:44px;border-radius:var(--radius-md);
772
+ background:transparent;color:var(--fg2);
773
+ border:1px solid var(--border);
774
+ font-family:var(--font-body);font-size:13.5px;font-weight:500;
775
+ cursor:pointer;text-decoration:none;
776
+ display:inline-flex;align-items:center;justify-content:center;
777
+ transition:background 140ms,color 140ms,border-color 140ms;
778
+ }
779
+ .btn-secondary:hover{background:rgba(255,255,255,0.04);color:var(--fg1);border-color:rgba(255,255,255,0.14)}
780
+
781
+ /* verifying */
782
+ .verifying-eyebrow{
783
+ font-family:var(--font-mono);font-size:10px;
784
+ letter-spacing:0.28em;text-transform:uppercase;color:var(--fg3);
785
+ font-weight:700;margin-bottom:14px;
786
+ }
787
+ .verifying-title{
788
+ font-family:var(--font-display);font-weight:600;
789
+ font-size:28px;line-height:1.1;color:var(--fg1);margin-bottom:8px;
790
+ letter-spacing:-0.02em;
791
+ }
792
+ .verifying-sub{font-size:13px;color:var(--fg3);min-height:1.45em}
793
+
794
+ /* form heading */
795
+ .form-title{
796
+ font-family:var(--font-display);font-weight:600;
797
+ font-size:32px;line-height:1.1;letter-spacing:-0.02em;
798
+ color:var(--fg1);margin-bottom:10px;
799
+ }
800
+ .form-sub{font-size:13.5px;color:var(--fg3);margin-bottom:28px;line-height:1.55}
801
+
802
+ @keyframes rise{from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:translateY(0)}}
803
+
804
+ @media (prefers-reduced-motion: reduce){
805
+ *,*::before,*::after{
806
+ animation-duration:0.01ms !important;animation-iteration-count:1 !important;
807
+ transition-duration:0.01ms !important;
808
+ }
809
+ }
810
+ </style>
811
+ </head><body>
812
+ <div class="top-mark">${appLogoMarkup({ size: "sm" })}</div>
813
+ <div class="stage">${bodyContent}</div>
814
+ </body></html>`;
815
+ }
816
+ var PROVIDER_NAME = "your assistant";
817
+ function successPanelInner(workspaceName, redirectUrl, providerName) {
818
+ return `
819
+ <div class="orb-wrap">
820
+ <div class="orb-ring r1"></div>
821
+ <div class="orb-ring r2"></div>
822
+ <div class="orb-ring r3"></div>
823
+ <div class="sat-orbit o1">
824
+ <span class="sat" style="transform:rotate(20deg) translate(78px) rotate(-20deg);color:#4ade80;animation-delay:600ms"><span>DEC</span></span>
825
+ <span class="sat" style="transform:rotate(140deg) translate(78px) rotate(-140deg);color:#c9b99a;animation-delay:720ms"><span>WP</span></span>
826
+ <span class="sat" style="transform:rotate(260deg) translate(78px) rotate(-260deg);color:#f59e0b;animation-delay:840ms"><span>TEN</span></span>
827
+ </div>
828
+ <div class="sat-orbit o2">
829
+ <span class="sat" style="transform:rotate(80deg) translate(54px) rotate(-80deg);color:#60a5fa;animation-delay:960ms"><span>STD</span></span>
830
+ <span class="sat" style="transform:rotate(220deg) translate(54px) rotate(-220deg);color:#a78bfa;animation-delay:1080ms"><span>INS</span></span>
831
+ </div>
832
+ <div class="core-shockwave"></div>
833
+ <div class="orb-core"><div class="orb-dot"></div></div>
834
+ </div>
835
+ <div class="eyebrow success"><span class="dot"></span>Connected</div>
836
+ <h1 class="ok-title">Product Brain is Live</h1>
837
+ <p class="ok-lead">Return to your assistant, then say</p>
838
+ <div class="ok-phrase-row">
839
+ <button class="cmd" type="button" data-cmd-pill data-redirect="${esc(redirectUrl)}" aria-label="Copy &quot;${esc(PASTE_NOW)}&quot; and return to ${esc(providerName)}">
840
+ <span class="cmd-quote-part" aria-hidden="true">&ldquo;</span><span data-cmd-text>${esc(PASTE_NOW)}</span><span class="cmd-quote-part" aria-hidden="true">&rdquo;</span>
841
+ <span class="cmd-icon" aria-hidden="true">
842
+ <svg data-cmd-svg viewBox="0 0 24 24"><rect x="9" y="9" width="11" height="11" rx="2"/><path d="M5 15V6a2 2 0 0 1 2-2h9"/></svg>
843
+ </span>
844
+ </button>
845
+ </div>
846
+ <div class="success-cta-wrap">
847
+ <a class="btn-primary success-cta" href="${esc(redirectUrl)}">Continue in ${esc(providerName)}</a>
848
+ </div>
849
+ <!-- workspace name retained as data hook for tests, hidden from view -->
850
+ <span hidden data-field="ws-name">${esc(workspaceName)}</span>`;
851
+ }
852
+ function errorPanelInner(title, trustedDetailHtml, retryUrl) {
853
+ return `
854
+ <div class="orb-wrap is-error">
855
+ <div class="orb-ring r1"></div>
856
+ <div class="orb-ring r2"></div>
857
+ <div class="orb-ring r3"></div>
858
+ <div class="orb-core"><div class="orb-dot"></div></div>
859
+ </div>
860
+ <div class="eyebrow danger"><span class="dot"></span>Couldn't connect</div>
861
+ <h2 class="err-title" data-field="err-title">${esc(title)}</h2>
862
+ <p class="err-msg" data-field="err-msg">${trustedDetailHtml}</p>
863
+ <div class="err-actions">
864
+ <a href="${esc(retryUrl)}" class="btn-secondary" data-retry-link>&larr; Try again</a>
865
+ <a href="${esc(apiKeysUrl())}" target="_blank" rel="noopener noreferrer" class="btn-secondary">Get an API key &rarr;</a>
866
+ </div>`;
867
+ }
868
+ var cmdScript = `
869
+ (function(){
870
+ function bindCmd(pill){
871
+ if(!pill||pill.__bound)return;pill.__bound=true;
872
+ var textEl=pill.querySelector('[data-cmd-text]');
873
+ var svgEl=pill.querySelector('[data-cmd-svg]');
874
+ var redirectUrl=pill.getAttribute('data-redirect')||'';
875
+ pill.addEventListener('click',function(){
876
+ var done=function(){
877
+ pill.classList.add('is-copied');
878
+ if(textEl)textEl.textContent='Copied';
879
+ if(svgEl)svgEl.innerHTML='<polyline points="4 12 10 18 20 6"/>';
880
+ setTimeout(function(){if(redirectUrl)window.location.assign(redirectUrl)},900);
881
+ };
882
+ try{
883
+ if(navigator.clipboard&&navigator.clipboard.writeText){
884
+ navigator.clipboard.writeText(${JSON.stringify(PASTE_NOW)}).then(done,done);
885
+ }else{done()}
886
+ }catch(e){done()}
887
+ });
888
+ }
889
+ document.querySelectorAll('[data-cmd-pill]').forEach(bindCmd);
890
+ })();
891
+ `;
892
+ function authorizeFormPage(params) {
893
+ const { redirect_uri, code_challenge, code_challenge_method, state, client_id } = params;
894
+ const providerName = PROVIDER_NAME;
895
+ const body = `
896
+ <!-- \u2500\u2500\u2500 CONNECT \u2500\u2500\u2500 -->
897
+ <div class="panel" id="p-connect" data-state="connect">
898
+ <div class="eyebrow">Connect Product Brain</div>
899
+ <h1 class="form-title">Paste your API key</h1>
900
+ <p class="form-sub">Give <span data-provider>${esc(providerName)}</span> access to your workspace memory.</p>
901
+ <form method="POST" action="/authorize" id="f" autocomplete="off">
902
+ <input type="hidden" name="redirect_uri" value="${esc(redirect_uri)}">
903
+ <input type="hidden" name="code_challenge" value="${esc(code_challenge)}">
904
+ <input type="hidden" name="code_challenge_method" value="${esc(code_challenge_method)}">
905
+ <input type="hidden" name="state" value="${esc(state)}">
906
+ <input type="hidden" name="client_id" value="${esc(client_id)}">
907
+ <div class="input-wrap" id="iw">
908
+ <input type="password" id="k" name="api_key" class="input input-full" placeholder="pb_sk_\u2026" required autofocus spellcheck="false">
909
+ </div>
910
+ <div class="hint" id="hint" hidden></div>
911
+ <button type="submit" class="btn-primary" id="sb" disabled><span id="bt">Connect</span></button>
912
+ </form>
913
+ <div class="small-link"><a href="${esc(apiKeysUrl())}" target="_blank" rel="noopener noreferrer">No key? Generate one &rarr;</a></div>
914
+ </div>
915
+
916
+ <!-- \u2500\u2500\u2500 VERIFYING \u2500\u2500\u2500 -->
917
+ <div class="panel" id="p-verifying" data-state="verifying" hidden>
918
+ <div class="orb-wrap is-verifying">
919
+ <div class="orb-ring r1"></div>
920
+ <div class="orb-ring r2"></div>
921
+ <div class="orb-ring r3"></div>
922
+ <div class="orb-core"><div class="orb-dot"></div></div>
923
+ </div>
924
+ <div class="verifying-eyebrow">Handshake</div>
925
+ <h2 class="verifying-title">Verifying key\u2026</h2>
926
+ <p class="verifying-sub" id="verify-sub">Checking workspace \xB7 \u2026</p>
927
+ </div>
928
+
929
+ <!-- \u2500\u2500\u2500 CONNECTED (filled by JS from JSON response) \u2500\u2500\u2500 -->
930
+ <div class="panel" id="p-connected" data-state="connected" hidden></div>
931
+
932
+ <!-- \u2500\u2500\u2500 ERROR (filled by JS from JSON response) \u2500\u2500\u2500 -->
933
+ <div class="panel" id="p-error" data-state="error" hidden></div>
934
+
935
+ <template id="tpl-connected">${successPanelInner("__WS__", "__URL__", "__PROVIDER__")}</template>
936
+ <template id="tpl-error">${errorPanelInner("__TITLE__", "__DETAIL__", "__RETRY__")}</template>
937
+
938
+ <script>
939
+ ${cmdScript}
940
+ (function(){
941
+ var f=document.getElementById('f'),k=document.getElementById('k'),iw=document.getElementById('iw'),hint=document.getElementById('hint'),sb=document.getElementById('sb'),bt=document.getElementById('bt');
942
+ var pConnect=document.getElementById('p-connect'),pVerify=document.getElementById('p-verifying'),pOk=document.getElementById('p-connected'),pErr=document.getElementById('p-error');
943
+ var verifySub=document.getElementById('verify-sub');
944
+
945
+ function show(panel){
946
+ [pConnect,pVerify,pOk,pErr].forEach(function(p){
947
+ if(p===panel){p.removeAttribute('hidden')}else{p.setAttribute('hidden','')}
948
+ });
949
+ }
950
+
951
+ function syncInput(){
952
+ sb.disabled=!k.value.trim();
953
+ iw.classList.remove('has-error');
954
+ hint.classList.remove('is-error');
955
+ hint.textContent='';
956
+ hint.setAttribute('hidden','');
957
+ }
958
+ k.addEventListener('input',syncInput);
959
+ k.addEventListener('keydown',function(e){
960
+ if(e.key==='Escape'){k.value='';syncInput()}
961
+ });
962
+
963
+ function showError(title,detailHtml){
964
+ var tpl=document.getElementById('tpl-error');
965
+ var html=tpl.innerHTML
966
+ .replace('__TITLE__',title.replace(/[<>&]/g,function(c){return{'<':'&lt;','>':'&gt;','&':'&amp;'}[c]}))
967
+ .replace('__DETAIL__',detailHtml)
968
+ .replace('__RETRY__','#');
969
+ pErr.innerHTML=html;
970
+ var retry=pErr.querySelector('[data-retry-link]');
971
+ if(retry){retry.addEventListener('click',function(e){e.preventDefault();show(pConnect);k.focus();k.select()})}
972
+ show(pErr);
973
+ }
974
+
975
+ function showSuccess(workspaceName,redirectUrl,providerName){
976
+ var tpl=document.getElementById('tpl-connected');
977
+ var safeWs=String(workspaceName||'').replace(/[<>&]/g,function(c){return{'<':'&lt;','>':'&gt;','&':'&amp;'}[c]});
978
+ var safeProv=String(providerName||'your assistant').replace(/[<>&]/g,function(c){return{'<':'&lt;','>':'&gt;','&':'&amp;'}[c]});
979
+ var safeUrl=String(redirectUrl||'').replace(/"/g,'&quot;').replace(/[<>]/g,function(c){return{'<':'&lt;','>':'&gt;'}[c]});
980
+ var html=tpl.innerHTML.split('__WS__').join(safeWs).split('__URL__').join(safeUrl).split('__PROVIDER__').join(safeProv);
981
+ pOk.innerHTML=html;
982
+ pOk.querySelectorAll('[data-cmd-pill]').forEach(function(pill){
983
+ pill.__bound=false;
984
+ });
985
+ // Re-run binder
986
+ var s=document.createElement('script');s.textContent=${JSON.stringify(cmdScript)};document.body.appendChild(s);s.remove();
987
+ show(pOk);
988
+ }
989
+
990
+ f.addEventListener('submit',function(e){
991
+ e.preventDefault();
992
+ var v=k.value.trim();
993
+ if(!v){iw.classList.add('has-error');hint.classList.add('is-error');hint.textContent='Paste your key first';hint.removeAttribute('hidden');return}
994
+ sb.disabled=true;bt.textContent='Verifying';
995
+ show(pVerify);
996
+
997
+ var steps=['Checking workspace \xB7 \u2026','Loading chain \xB7 \u2026','Establishing memory \xB7 \u2026'];
998
+ var i=0;verifySub.textContent=steps[0];
999
+ var ti=setInterval(function(){i++;if(i>=steps.length){clearInterval(ti);return}verifySub.textContent=steps[i]},900);
1000
+
1001
+ var minDelay=new Promise(function(r){setTimeout(r,2800)});
1002
+ var fd=new FormData(f);
1003
+ var body=new URLSearchParams();
1004
+ fd.forEach(function(val,key){body.append(key,String(val))});
1005
+
1006
+ var req=fetch('/authorize',{
1007
+ method:'POST',
1008
+ headers:{'Accept':'application/json','Content-Type':'application/x-www-form-urlencoded'},
1009
+ body:body.toString(),
1010
+ credentials:'same-origin'
1011
+ }).then(function(r){return r.json().then(function(j){return{status:r.status,body:j}})});
1012
+
1013
+ Promise.all([req,minDelay]).then(function(arr){
1014
+ clearInterval(ti);
1015
+ var res=arr[0];
1016
+ if(res.body&&res.body.ok){
1017
+ showSuccess(res.body.workspaceName,res.body.redirectUrl,res.body.providerName);
1018
+ }else{
1019
+ showError(res.body&&res.body.title||'Couldn\\'t connect',res.body&&res.body.detail||'Try again, or generate a new key.');
1020
+ sb.disabled=false;bt.textContent='Connect';
1021
+ }
1022
+ }).catch(function(){
1023
+ clearInterval(ti);
1024
+ showError('Network error','We couldn\\'t reach Product Brain. Check your connection and try again.');
1025
+ sb.disabled=false;bt.textContent='Connect';
1026
+ });
1027
+ });
1028
+
1029
+ k.focus();
1030
+ })();
1031
+ </script>`;
1032
+ return authPageShell("Connect Product Brain", body);
1033
+ }
1034
+ function authorizeSuccessPage(workspaceName, redirectUrl, providerName) {
1035
+ const body = `
1036
+ <div class="panel" data-state="connected">
1037
+ ${successPanelInner(workspaceName, redirectUrl, providerName)}
1038
+ </div>
1039
+ <script>${cmdScript}</script>`;
1040
+ return authPageShell("Connected", body);
1041
+ }
1042
+ function authorizeErrorPage(title, trustedDetailHtml, retryUrl) {
1043
+ const body = `
1044
+ <div class="panel" data-state="error">
1045
+ ${errorPanelInner(title, trustedDetailHtml, retryUrl)}
1046
+ </div>`;
1047
+ return authPageShell("Connection error", body);
1048
+ }
1049
+ app.get("/authorize", authLimiter, (req, res) => {
1050
+ const { redirect_uri, code_challenge, code_challenge_method, state, client_id } = req.query;
1051
+ const refusal = checkRedirectUri(redirect_uri, OAUTH_REDIRECT_ALLOWLIST);
1052
+ if (refusal) {
1053
+ logOAuthDoor("GET /authorize", 400, refusal);
1054
+ res.status(400).json({ error: "invalid_request", error_description: refusal });
1055
+ return;
1056
+ }
1057
+ res.type("html").send(authorizeFormPage({
1058
+ redirect_uri: String(redirect_uri ?? ""),
1059
+ code_challenge: String(code_challenge ?? ""),
1060
+ code_challenge_method: String(code_challenge_method ?? "S256"),
1061
+ state: String(state ?? ""),
1062
+ client_id: String(client_id ?? "")
1063
+ }));
1064
+ });
1065
+ app.post(
1066
+ "/authorize",
1067
+ authLimiter,
1068
+ express.urlencoded({ extended: false }),
1069
+ async (req, res) => {
1070
+ const { redirect_uri, code_challenge, code_challenge_method, state, client_id } = req.body;
1071
+ const api_key = normalisePastedKey(req.body.api_key);
1072
+ const wantsJson = String(req.headers["accept"] ?? "").includes("application/json");
1073
+ const retryParams = new URLSearchParams({
1074
+ redirect_uri: redirect_uri ?? "",
1075
+ code_challenge: code_challenge ?? "",
1076
+ code_challenge_method: code_challenge_method ?? "S256",
1077
+ ...state ? { state } : {},
1078
+ ...client_id ? { client_id } : {}
1079
+ }).toString();
1080
+ const retryUrl = `/authorize?${retryParams}`;
1081
+ function sendError(title, trustedDetailHtml, status = 400) {
1082
+ logOAuthDoor("POST /authorize", status, title);
1083
+ if (wantsJson) {
1084
+ res.status(status).json({ ok: false, title, detail: trustedDetailHtml });
1085
+ } else {
1086
+ res.status(status).type("html").send(authorizeErrorPage(title, trustedDetailHtml, retryUrl));
1087
+ }
1088
+ }
1089
+ if (isCrossSiteFormPost(req.headers["origin"], req.headers["sec-fetch-site"], baseUrl(req))) {
1090
+ sendError("Request refused", "This form only accepts keys sent from its own sign-in page. Open the connect link again.", 403);
1091
+ return;
1092
+ }
1093
+ const nowTs = Date.now();
1094
+ const pasted = resolvePastedKey(api_key);
1095
+ const lockout = authLockoutError(authFailures, pasted, nowTs);
1096
+ if (lockout) {
1097
+ const retryAfter = lockout.headers["Retry-After"];
1098
+ res.setHeader("Retry-After", retryAfter);
1099
+ sendError("Too many attempts", `This key was not recognized too many times. Try again in ${retryAfter}s.`, 429);
1100
+ return;
1101
+ }
1102
+ if (pasted.status !== "ok") {
1103
+ if (pasted.status === "rejected") recordAuthFailure(authFailures, pasted.credentialId, nowTs);
1104
+ sendError("Invalid key format", "API keys start with <code>pb_sk_</code>. Check your key and try again.");
1105
+ return;
1106
+ }
1107
+ if (!client_id) {
1108
+ logOAuthDoor("POST /authorize", 400, "client_id is required");
1109
+ res.status(400).json({ error: "invalid_request", error_description: "client_id is required" });
1110
+ return;
1111
+ }
1112
+ const redirectRefusal = checkRedirectUri(redirect_uri, OAUTH_REDIRECT_ALLOWLIST);
1113
+ if (redirectRefusal) {
1114
+ logOAuthDoor("POST /authorize", 400, redirectRefusal);
1115
+ res.status(400).json({ error: "invalid_request", error_description: redirectRefusal });
1116
+ return;
1117
+ }
1118
+ let workspaceName = "Your Workspace";
1119
+ const check = await checkKeyAgainstCandidates(keyCheckCandidates(), api_key, 5e3);
1120
+ const gate = keyVerdictGate(check.verdict, authFailures, pasted.credentialId, nowTs);
1121
+ if (check.verdict === "ok") {
1122
+ if (check.workspaceName) workspaceName = check.workspaceName;
1123
+ getKeyState(api_key).deploymentUrl = check.deploymentUrl;
1124
+ } else if (check.verdict === "rate_limited") {
1125
+ sendError(
1126
+ "Rate limited",
1127
+ `This API key is valid but temporarily rate limited. Try again in ${check.retryAfterSeconds ?? 60}s.`,
1128
+ 429
1129
+ );
1130
+ return;
1131
+ } else if (gate === "unauthorized") {
1132
+ sendError("Key not recognized", "This API key wasn't found in Product Brain. Check your API Keys in Cortex and try again.", 401);
1133
+ return;
1134
+ } else {
1135
+ process.stderr.write("[authorize] key-check unavailable \u2014 proceeding without validation\n");
1136
+ }
1137
+ const code = randomUUID();
1138
+ pendingCodes.set(code, {
1139
+ apiKey: api_key,
1140
+ codeChallenge: code_challenge,
1141
+ redirectUri: redirect_uri,
1142
+ expiresAt: Date.now() + 5 * 6e4
1143
+ });
1144
+ const url = new URL(redirect_uri);
1145
+ url.searchParams.set("code", code);
1146
+ if (state) url.searchParams.set("state", state);
1147
+ const redirectUrl = url.toString();
1148
+ const providerName = PROVIDER_NAME;
1149
+ logOAuthDoor("POST /authorize", 200, "code_issued");
1150
+ if (wantsJson) {
1151
+ res.json({ ok: true, workspaceName, redirectUrl, providerName });
1152
+ } else {
1153
+ res.type("html").send(authorizeSuccessPage(workspaceName, redirectUrl, providerName));
1154
+ }
1155
+ }
1156
+ );
1157
+ app.post(
1158
+ "/oauth/token",
1159
+ express.urlencoded({ extended: false }),
1160
+ express.json(),
1161
+ (req, res) => {
1162
+ const { grant_type, code, code_verifier, redirect_uri } = req.body ?? {};
1163
+ if (grant_type !== "authorization_code") {
1164
+ logOAuthDoor("POST /oauth/token", 400, "unsupported_grant_type");
1165
+ res.status(400).json({ error: "unsupported_grant_type" });
1166
+ return;
1167
+ }
1168
+ const pending = pendingCodes.get(code);
1169
+ const codeRefusal = pendingCodeRefusal(pending, redirect_uri, Date.now());
1170
+ if (codeRefusal === "expired") {
1171
+ pendingCodes.delete(code);
1172
+ logOAuthDoor("POST /oauth/token", 400, "expired");
1173
+ res.status(400).json({ error: "invalid_grant", error_description: "authorization code expired" });
1174
+ return;
1175
+ }
1176
+ if (codeRefusal || !pending) {
1177
+ logOAuthDoor("POST /oauth/token", 400, codeRefusal ?? "unknown_code");
1178
+ res.status(400).json({ error: "invalid_grant" });
1179
+ return;
1180
+ }
1181
+ const challenge = createHash("sha256").update(code_verifier ?? "").digest("base64url");
1182
+ if (challenge !== pending.codeChallenge) {
1183
+ pendingCodes.delete(code);
1184
+ logOAuthDoor("POST /oauth/token", 400, "pkce_failed");
1185
+ res.status(400).json({
1186
+ error: "invalid_grant",
1187
+ error_description: "PKCE verification failed"
1188
+ });
1189
+ return;
1190
+ }
1191
+ pendingCodes.delete(code);
1192
+ logOAuthDoor("POST /oauth/token", 200, "token_issued");
1193
+ res.json(tokenResponse(pending.apiKey));
1194
+ }
1195
+ );
1196
+ var mcpLimit = mcpLimiters();
1197
+ var authFailures = /* @__PURE__ */ new Map();
1198
+ app.get("/health", (_req, res) => {
1199
+ res.json({ status: "ok", version: SERVER_VERSION, transport: "http" });
1200
+ });
1201
+ var sessions = /* @__PURE__ */ new Map();
1202
+ var SESSION_TTL_MS = 30 * 60 * 1e3;
1203
+ var MAX_SESSIONS = 200;
1204
+ var EVICT_GRACE_MS = 6e4;
1205
+ var MAX_SESSIONS_PER_KEY = Math.max(
1206
+ 1,
1207
+ Math.min(MAX_SESSIONS - 1, Number(process.env.MCP_MAX_SESSIONS_PER_KEY) || 25)
1208
+ );
1209
+ function evictStaleSessions() {
1210
+ const now = Date.now();
1211
+ for (const [id, entry] of sessions) {
1212
+ if (now - entry.lastAccess > SESSION_TTL_MS) {
1213
+ logSessionLifecycle(
1214
+ "session_deleted",
1215
+ id,
1216
+ entry.inFlight > 0 ? "inflight_leak" : "ttl"
1217
+ );
1218
+ entry.transport.close().catch(() => {
1219
+ });
1220
+ sessions.delete(id);
1221
+ }
1222
+ }
1223
+ if (sessions.size > MAX_SESSIONS) {
1224
+ const sorted = [...sessions.entries()].filter(([, e]) => e.inFlight === 0).sort((a, b) => a[1].lastAccess - b[1].lastAccess);
1225
+ const overflow = sessions.size - MAX_SESSIONS;
1226
+ for (let i = 0; i < Math.min(overflow, sorted.length); i++) {
1227
+ logSessionLifecycle("session_deleted", sorted[i][0], "eviction");
1228
+ sorted[i][1].transport.close().catch(() => {
1229
+ });
1230
+ sessions.delete(sorted[i][0]);
1231
+ }
1232
+ if (sessions.size > MAX_SESSIONS) {
1233
+ const ts = (/* @__PURE__ */ new Date()).toISOString();
1234
+ process.stderr.write(
1235
+ `[HTTP] ${ts} session_cap_breach size=${sessions.size} max=${MAX_SESSIONS} reason=all_inflight (no idle sessions to evict; TTL backstop will reclaim)
1236
+ `
1237
+ );
1238
+ }
1239
+ }
1240
+ }
1241
+ setInterval(evictStaleSessions, 6e4);
1242
+ function send401(req, res) {
1243
+ const base = baseUrl(req);
1244
+ res.status(401).set(
1245
+ "WWW-Authenticate",
1246
+ `Bearer resource_metadata="${base}/.well-known/oauth-protected-resource"`
1247
+ ).json({ error: "unauthorized" });
1248
+ }
1249
+ function logRequest(method, outcome, sessionId, durationMs) {
1250
+ const ts = (/* @__PURE__ */ new Date()).toISOString();
1251
+ const sid = sessionId ? ` session=${sessionId}` : "";
1252
+ const dur = durationMs != null ? ` duration=${durationMs}ms` : "";
1253
+ process.stderr.write(`[HTTP] ${ts} ${method} ${outcome}${sid}${dur}
1254
+ `);
1255
+ }
1256
+ function logSessionLifecycle(event, sessionId, reason) {
1257
+ const ts = (/* @__PURE__ */ new Date()).toISOString();
1258
+ const r = reason ? ` reason=${reason}` : "";
1259
+ process.stderr.write(`[HTTP] ${ts} ${event} session=${sessionId}${r}
1260
+ `);
1261
+ }
1262
+ app.post("/mcp", ...mcpLimit, async (req, res) => {
1263
+ const nowTs = Date.now();
1264
+ const auth = resolveBearerAuth(req.headers?.authorization);
1265
+ const lockout = authLockoutError(authFailures, auth, nowTs, req.body?.id ?? null);
1266
+ if (lockout) {
1267
+ send429(res, lockout);
1268
+ return;
1269
+ }
1270
+ if (auth.status !== "ok") {
1271
+ logRequest("POST", "auth_fail");
1272
+ if (auth.status === "rejected") recordAuthFailure(authFailures, auth.credentialId, nowTs);
1273
+ send401(req, res);
1274
+ return;
1275
+ }
1276
+ const apiKey = auth.apiKey;
1277
+ const sessionId = req.headers["mcp-session-id"];
1278
+ const reqStart = Date.now();
1279
+ try {
1280
+ await runWithAuth({ apiKey, mcpSessionId: sessionId }, async () => {
1281
+ if (sessionId && sessions.has(sessionId)) {
1282
+ const entry = sessions.get(sessionId);
1283
+ if (entry.keyHash !== hashKey(apiKey)) {
1284
+ res.status(403).json({
1285
+ jsonrpc: "2.0",
1286
+ error: { code: -32e3, message: "Session key mismatch" },
1287
+ id: null
1288
+ });
1289
+ return;
1290
+ }
1291
+ try {
1292
+ entry.inFlight++;
1293
+ entry.lastAccess = Date.now();
1294
+ await entry.transport.handleRequest(req, res, req.body);
1295
+ logRequest("POST", "ok", sessionId, Date.now() - reqStart);
1296
+ } finally {
1297
+ entry.inFlight--;
1298
+ entry.lastAccess = Date.now();
1299
+ }
1300
+ } else if (!sessionId && isInitializeRequest(req.body)) {
1301
+ const check = await checkKeyAgainstCandidates(keyCheckCandidates(), apiKey, 5e3);
1302
+ const gate = keyVerdictGate(check.verdict, authFailures, auth.credentialId, Date.now());
1303
+ if (gate === "unauthorized") {
1304
+ logRequest("POST", "auth_fail");
1305
+ send401(req, res);
1306
+ return;
1307
+ }
1308
+ if (gate === "unavailable") {
1309
+ res.status(503).json({
1310
+ jsonrpc: "2.0",
1311
+ error: { code: -32e3, message: "Product Brain could not verify this API key right now. Retry shortly." },
1312
+ id: req.body?.id ?? null
1313
+ });
1314
+ return;
1315
+ }
1316
+ if (check.verdict === "ok" || check.verdict === "rate_limited") getKeyState(apiKey).deploymentUrl = check.deploymentUrl;
1317
+ const keyH = hashKey(apiKey);
1318
+ const plan = planKeyAdmission(
1319
+ sessions,
1320
+ keyH,
1321
+ MAX_SESSIONS_PER_KEY,
1322
+ Date.now(),
1323
+ { ttlMs: SESSION_TTL_MS, graceMs: EVICT_GRACE_MS }
1324
+ );
1325
+ for (const sid2 of plan.evict) {
1326
+ const victim = sessions.get(sid2);
1327
+ sessions.delete(sid2);
1328
+ victim?.transport.close().catch(() => {
1329
+ });
1330
+ logSessionLifecycle("session_deleted", sid2, "lru_evict");
1331
+ }
1332
+ if (!plan.admit) {
1333
+ send429(res, buildSessionCapError({
1334
+ retryAfterSeconds: plan.retryAfterSeconds,
1335
+ limit: MAX_SESSIONS_PER_KEY,
1336
+ current: countKeySessions(sessions, keyH),
1337
+ poll: plan.retryIsPoll,
1338
+ id: req.body?.id ?? null
1339
+ }));
1340
+ return;
1341
+ }
1342
+ const sid = randomUUID();
1343
+ let initialized = false;
1344
+ const transport = new StreamableHTTPServerTransport({
1345
+ sessionIdGenerator: () => sid,
1346
+ onsessioninitialized: (s) => {
1347
+ initialized = true;
1348
+ logSessionLifecycle("session_created", s);
1349
+ }
1350
+ // log only — no map write
1351
+ });
1352
+ const reserved = { transport, lastAccess: Date.now(), keyHash: keyH, inFlight: 1 };
1353
+ sessions.set(sid, reserved);
1354
+ transport.onclose = () => {
1355
+ const s = transport.sessionId ?? sid;
1356
+ forgetStreamLifecycle(keyH, s);
1357
+ if (sessions.has(s)) {
1358
+ sessions.delete(s);
1359
+ logSessionLifecycle("session_deleted", s, "onclose");
1360
+ }
1361
+ };
1362
+ try {
1363
+ const server = createProductBrainServer();
1364
+ await server.connect(transport);
1365
+ await transport.handleRequest(req, res, req.body);
1366
+ logRequest("POST", "ok", transport.sessionId ?? void 0, Date.now() - reqStart);
1367
+ } catch (e) {
1368
+ transport.onclose = void 0;
1369
+ sessions.delete(sid);
1370
+ throw e;
1371
+ } finally {
1372
+ if (!initialized) {
1373
+ transport.onclose = void 0;
1374
+ if (sessions.delete(sid)) logSessionLifecycle("session_deleted", sid, "init_rejected");
1375
+ } else {
1376
+ const e = sessions.get(sid);
1377
+ if (e) {
1378
+ e.inFlight--;
1379
+ e.lastAccess = Date.now();
1380
+ }
1381
+ }
1382
+ }
1383
+ } else if (sessionId) {
1384
+ process.stderr.write(
1385
+ `[HTTP] ${(/* @__PURE__ */ new Date()).toISOString()} session_stale sessionId=${sessionId} (likely server restart \u2014 instructing client to re-initialise)
1386
+ `
1387
+ );
1388
+ res.status(404).json({
1389
+ jsonrpc: "2.0",
1390
+ error: { code: -32001, message: "Session not found \u2014 re-initialise" },
1391
+ id: null
1392
+ });
1393
+ } else {
1394
+ process.stderr.write(
1395
+ `[HTTP] ${(/* @__PURE__ */ new Date()).toISOString()} session_invalid no valid session ID (client may have omitted Mcp-Session-Id)
1396
+ `
1397
+ );
1398
+ res.status(400).json({
1399
+ jsonrpc: "2.0",
1400
+ error: { code: -32e3, message: "Bad Request: no valid session ID provided" },
1401
+ id: null
1402
+ });
1403
+ }
1404
+ });
1405
+ } catch (err) {
1406
+ logRequest("POST", "error", sessionId, Date.now() - reqStart);
1407
+ if (!res.headersSent) {
1408
+ res.status(500).json({
1409
+ jsonrpc: "2.0",
1410
+ error: { code: -32603, message: "Internal server error" },
1411
+ id: null
1412
+ });
1413
+ }
1414
+ }
1415
+ });
1416
+ app.get("/mcp", ...mcpLimit, async (req, res) => {
1417
+ const nowTs = Date.now();
1418
+ const auth = resolveBearerAuth(req.headers?.authorization);
1419
+ const lockout = authLockoutError(authFailures, auth, nowTs, req.body?.id ?? null);
1420
+ if (lockout) {
1421
+ send429(res, lockout);
1422
+ return;
1423
+ }
1424
+ if (auth.status !== "ok") {
1425
+ logRequest("GET", "auth_fail");
1426
+ if (auth.status === "rejected") recordAuthFailure(authFailures, auth.credentialId, nowTs);
1427
+ send401(req, res);
1428
+ return;
1429
+ }
1430
+ const apiKey = auth.apiKey;
1431
+ const sessionId = req.headers["mcp-session-id"];
1432
+ if (!sessionId) {
1433
+ res.status(400).send("Missing Mcp-Session-Id header");
1434
+ return;
1435
+ }
1436
+ if (!sessions.has(sessionId)) {
1437
+ process.stderr.write(
1438
+ `[HTTP] ${(/* @__PURE__ */ new Date()).toISOString()} session_stale GET sessionId=${sessionId}
1439
+ `
1440
+ );
1441
+ res.status(404).send("Session not found \u2014 re-initialise");
1442
+ return;
1443
+ }
1444
+ try {
1445
+ await runWithAuth({ apiKey, mcpSessionId: sessionId }, async () => {
1446
+ const entry = sessions.get(sessionId);
1447
+ if (entry.keyHash !== hashKey(apiKey)) {
1448
+ res.status(403).json({
1449
+ jsonrpc: "2.0",
1450
+ error: { code: -32e3, message: "Session key mismatch" },
1451
+ id: null
1452
+ });
1453
+ return;
1454
+ }
1455
+ entry.lastAccess = Date.now();
1456
+ await entry.transport.handleRequest(req, res);
1457
+ logRequest("GET", "ok", sessionId);
1458
+ });
1459
+ } catch {
1460
+ logRequest("GET", "error", sessionId);
1461
+ }
1462
+ });
1463
+ app.delete("/mcp", ...mcpLimit, async (req, res) => {
1464
+ const nowTs = Date.now();
1465
+ const auth = resolveBearerAuth(req.headers?.authorization);
1466
+ const lockout = authLockoutError(authFailures, auth, nowTs, req.body?.id ?? null);
1467
+ if (lockout) {
1468
+ send429(res, lockout);
1469
+ return;
1470
+ }
1471
+ if (auth.status !== "ok") {
1472
+ logRequest("DELETE", "auth_fail");
1473
+ if (auth.status === "rejected") recordAuthFailure(authFailures, auth.credentialId, nowTs);
1474
+ send401(req, res);
1475
+ return;
1476
+ }
1477
+ const apiKey = auth.apiKey;
1478
+ const sessionId = req.headers["mcp-session-id"];
1479
+ if (!sessionId) {
1480
+ res.status(400).send("Missing Mcp-Session-Id header");
1481
+ return;
1482
+ }
1483
+ if (!sessions.has(sessionId)) {
1484
+ process.stderr.write(
1485
+ `[HTTP] ${(/* @__PURE__ */ new Date()).toISOString()} session_stale DELETE sessionId=${sessionId}
1486
+ `
1487
+ );
1488
+ res.status(404).send("Session not found \u2014 re-initialise");
1489
+ return;
1490
+ }
1491
+ try {
1492
+ await runWithAuth({ apiKey, mcpSessionId: sessionId }, async () => {
1493
+ const entry = sessions.get(sessionId);
1494
+ if (entry.keyHash !== hashKey(apiKey)) {
1495
+ res.status(403).json({
1496
+ jsonrpc: "2.0",
1497
+ error: { code: -32e3, message: "Session key mismatch" },
1498
+ id: null
1499
+ });
1500
+ return;
1501
+ }
1502
+ await entry.transport.handleRequest(req, res);
1503
+ logRequest("DELETE", "ok", sessionId);
1504
+ });
1505
+ } catch {
1506
+ logRequest("DELETE", "error", sessionId);
1507
+ }
1508
+ });
1509
+ process.on("unhandledRejection", (reason) => {
1510
+ const msg = reason instanceof Error ? reason.message : String(reason);
1511
+ console.error(`[MCP HTTP] Unhandled rejection: ${msg}`);
1512
+ });
1513
+ process.on("uncaughtException", (err) => {
1514
+ console.error(`[MCP HTTP] Uncaught exception: ${err.stack ?? err.message}`);
1515
+ gracefulShutdown();
1516
+ });
1517
+ var shuttingDown = false;
1518
+ async function gracefulShutdown() {
1519
+ if (shuttingDown) return;
1520
+ shuttingDown = true;
1521
+ setTimeout(() => process.exit(1), 3e3).unref();
1522
+ console.log("Shutting down...");
1523
+ for (const [, entry] of sessions) {
1524
+ await entry.transport.close().catch(() => {
1525
+ });
1526
+ }
1527
+ process.exit(0);
1528
+ }
1529
+ var LISTEN_HOST = "0.0.0.0";
1530
+ var httpServer = app.listen(PORT, LISTEN_HOST, () => {
1531
+ console.log(
1532
+ `Product Brain MCP HTTP server v${SERVER_VERSION} listening on ${LISTEN_HOST}:${PORT}`
1533
+ );
1534
+ });
1535
+ httpServer.on("error", (err) => {
1536
+ console.error(`[MCP HTTP] Server error: ${err.message}`);
1537
+ process.exit(1);
1538
+ });
1539
+ process.on("SIGINT", gracefulShutdown);
1540
+ process.on("SIGTERM", gracefulShutdown);
1541
+ //# sourceMappingURL=http.js.map