@productbrain/mcp 0.0.1-beta.13982 → 0.0.1-beta.13997

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/http.js CHANGED
@@ -1,12 +1,10 @@
1
1
  import {
2
- PRODUCT_NAME,
3
2
  SERVER_VERSION,
4
3
  createProductBrainServer
5
- } from "./chunk-2Y7UBHKN.js";
4
+ } from "./chunk-5ICMC6O7.js";
6
5
  import {
7
6
  DEFAULT_CLOUD_URL,
8
- PASTE_NOW,
9
- apiKeysUrl,
7
+ appUrl,
10
8
  bootstrapHttp,
11
9
  checkKeyAgainstCandidates,
12
10
  forgetStreamLifecycle,
@@ -15,48 +13,15 @@ import {
15
13
  isApiKeyShaped,
16
14
  parseFallbackUrls,
17
15
  runWithAuth
18
- } from "./chunk-4IZUEL4P.js";
16
+ } from "./chunk-MJCZCZA5.js";
19
17
 
20
18
  // src/http.ts
21
- import { createHash, randomUUID } from "crypto";
19
+ import { randomUUID } from "crypto";
22
20
  import express from "express";
23
21
  import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
24
22
  import { isInitializeRequest } from "@modelcontextprotocol/sdk/types.js";
25
23
  import rateLimit2 from "express-rate-limit";
26
24
 
27
- // src/brand/logo-markup.ts
28
- var SIZE_CLASSES = {
29
- sm: "pb-logo--sm",
30
- md: "pb-logo--md"
31
- };
32
- var appLogoStyles = `
33
- .pb-logo{display:inline-flex;align-items:center;gap:8px;color:inherit}
34
- .pb-logo__mark{
35
- border-radius:4px;background:#1c1e24;
36
- border:1px solid rgba(255,255,255,0.06);
37
- display:inline-grid;place-items:center;flex-shrink:0;
38
- }
39
- .pb-logo__core{border-radius:50%;background:var(--accent,#c9b99a)}
40
- .pb-logo__name{
41
- font-family:var(--font-mono,"IBM Plex Mono",ui-monospace,monospace);
42
- font-weight:500;text-transform:uppercase;
43
- letter-spacing:0.22em;color:var(--fg4,#6a6560);
44
- }
45
- .pb-logo--sm .pb-logo__mark{width:16px;height:16px}
46
- .pb-logo--sm .pb-logo__core{width:5px;height:5px}
47
- .pb-logo--sm .pb-logo__name{font-size:10.5px}
48
- .pb-logo--md .pb-logo__mark{width:24px;height:24px;border-radius:6px}
49
- .pb-logo--md .pb-logo__core{width:8px;height:8px}
50
- .pb-logo--md .pb-logo__name{font-size:13px}
51
- `;
52
- function appLogoMarkup(opts = {}) {
53
- const size = opts.size ?? "sm";
54
- const showWordmark = opts.showWordmark ?? true;
55
- const cls = ["pb-logo", SIZE_CLASSES[size], opts.className].filter(Boolean).join(" ");
56
- const wordmark = showWordmark ? `<span class="pb-logo__name">${PRODUCT_NAME}</span>` : "";
57
- return `<span class="${cls}"><span class="pb-logo__mark"><span class="pb-logo__core"></span></span>${wordmark}</span>`;
58
- }
59
-
60
25
  // src/sessionCap.ts
61
26
  function planKeyAdmission(sessions2, keyHash, cap, now, opts) {
62
27
  if (cap < 1) {
@@ -186,20 +151,6 @@ function resolveBearerAuth(authorizationHeader) {
186
151
  if (!isApiKeyShaped(token)) return rejected(token);
187
152
  return { status: "ok", apiKey: token, credentialId: hashKey(token) };
188
153
  }
189
- function resolvePastedKey(apiKey) {
190
- if (apiKey === "") return { status: "absent" };
191
- if (!isApiKeyShaped(apiKey)) return rejected(apiKey);
192
- return { status: "ok", apiKey, credentialId: hashKey(apiKey) };
193
- }
194
- function isCrossSiteFormPost(origin, secFetchSite, ownOrigin) {
195
- if (secFetchSite === "cross-site") return true;
196
- if (typeof origin !== "string" || origin === "") return false;
197
- try {
198
- return new URL(origin).origin !== new URL(ownOrigin).origin;
199
- } catch {
200
- return true;
201
- }
202
- }
203
154
  function checkAuthBlock(failures, credentialId, now) {
204
155
  const rec = failures.get(credentialId);
205
156
  if (!rec) return false;
@@ -363,22 +314,91 @@ function checkRegistrationRedirects(redirectUris, allowlist) {
363
314
  return { refusal: allowed.length === 0 ? dropped[0].reason : null, allowed, dropped };
364
315
  }
365
316
 
366
- // src/lib/oauthAuthCode.ts
367
- function normalisePastedKey(raw) {
368
- if (typeof raw !== "string") return "";
369
- const trimmed = raw.trim();
370
- const first = trimmed[0];
371
- if (trimmed.length >= 2 && (first === '"' || first === "'" || first === "`") && trimmed.endsWith(first)) {
372
- return trimmed.slice(1, -1).trim();
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;
373
372
  }
374
- return trimmed;
375
373
  }
376
- function pendingCodeRefusal(pending, redirectUri, now) {
377
- if (!pending) return "unknown_code";
378
- if (pending.redirectUri !== redirectUri) return "redirect_mismatch";
379
- if (now > pending.expiresAt) return "expired";
380
- return null;
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 };
381
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
382
402
  function tokenResponse(apiKey) {
383
403
  return {
384
404
  access_token: apiKey,
@@ -388,6 +408,93 @@ function tokenResponse(apiKey) {
388
408
  };
389
409
  }
390
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
+
391
498
  // src/http.ts
392
499
  bootstrapHttp();
393
500
  var PORT = parseInt(process.env.PORT ?? process.env.MCP_PORT ?? "3002", 10);
@@ -446,11 +553,6 @@ app.get("/.well-known/oauth-authorization-server", (req, res) => {
446
553
  scopes_supported: ["mcp:tools", "mcp:resources"]
447
554
  });
448
555
  });
449
- function logOAuthDoor(door, status, reason, uris) {
450
- const list = uris === void 0 ? "" : ` uris=${JSON.stringify(uris.map(String)).slice(0, 600)}`;
451
- process.stderr.write(`[oauth] door=${door} status=${status} reason=${JSON.stringify(reason)}${list}
452
- `);
453
- }
454
556
  var authLimiter = rateLimit2({
455
557
  windowMs: 6e4,
456
558
  max: 20,
@@ -472,7 +574,7 @@ app.post(
472
574
  res.status(400).json({ error: "invalid_redirect_uri", error_description: refusal });
473
575
  return;
474
576
  }
475
- const clientId = `pb_client_${randomUUID()}`;
577
+ const clientId = registeredClientId(randomUUID(), client_name);
476
578
  const droppedUris = dropped.length > 0 ? dropped.map((d) => d.uri) : void 0;
477
579
  logOAuthDoor("POST /register", 201, droppedUris ? "dropped_redirects" : "registered", droppedUris);
478
580
  res.status(201).json({
@@ -485,713 +587,23 @@ app.post(
485
587
  });
486
588
  }
487
589
  );
488
- var pendingCodes = /* @__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
+ });
489
593
  setInterval(() => {
490
594
  const now = Date.now();
491
- for (const [code, auth] of pendingCodes) {
492
- if (now > auth.expiresAt) pendingCodes.delete(code);
493
- }
494
595
  for (const [credentialId, rec] of authFailures) {
495
596
  if (rec.blockedUntil < now && rec.firstFailure + AUTH_FAILURE_WINDOW_MS < now) {
496
597
  authFailures.delete(credentialId);
497
598
  }
498
599
  }
499
600
  }, 6e4);
500
- function esc(s) {
501
- return String(s ?? "").replace(
502
- /[&"'<>]/g,
503
- (c) => ({ "&": "&amp;", '"': "&quot;", "'": "&#39;", "<": "&lt;", ">": "&gt;" })[c]
504
- );
505
- }
506
- function authPageShell(title, bodyContent, headExtra = "") {
507
- return `<!DOCTYPE html>
508
- <html lang="en" data-theme="parchment-dark"><head>
509
- <meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
510
- <title>${esc(title)} \u2014 Product Brain</title>
511
- <link rel="preconnect" href="https://fonts.googleapis.com">
512
- <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
513
- <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">
514
- ${headExtra}
515
- <style>
516
- :root{
517
- --bg:#1a1917;--bg-warm:#201f1c;--surface:#262521;
518
- --fg1:#e4e0d8;--fg2:#c4bfb4;--fg3:#9a9589;--fg4:#6a6560;--fg-bright:#ffffff;
519
- --border:rgba(255,255,255,0.07);--border-light:rgba(255,255,255,0.04);
520
- --accent:#c9b99a;
521
- --btn-bg:#ffffff;--btn-fg:#1a1917;--btn-hover:#e4e0d8;
522
- --green:#4ade80;--rose:#ef4444;
523
- --ghost:rgba(38,37,33,0.55);
524
- --radius-md:7px;--radius-lg:10px;
525
- --font-display:"Source Serif 4",ui-serif,Georgia,serif;
526
- --font-body:"IBM Plex Sans",ui-sans-serif,system-ui,sans-serif;
527
- --font-mono:"IBM Plex Mono",ui-monospace,"SF Mono",Menlo,monospace;
528
- }
529
- *,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
530
- html,body{height:100%}
531
- body{
532
- font-family:var(--font-body);font-size:13px;line-height:1.45;
533
- color:var(--fg1);background:var(--bg);
534
- min-height:100vh;display:grid;place-items:center;padding:24px;
535
- -webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;
536
- position:relative;overflow:hidden;
537
- }
538
- body::before{
539
- content:"";position:fixed;inset:0;
540
- background:radial-gradient(900px 600px at 50% 50%,rgba(228,224,216,0.025),transparent 60%);
541
- pointer-events:none;z-index:0;
542
- }
543
- .top-mark{position:fixed;top:22px;left:24px;z-index:5;opacity:0.7}
544
- ${appLogoStyles}
545
- .stage{
546
- width:100%;max-width:460px;text-align:center;
547
- position:relative;z-index:1;
548
- display:grid;
549
- }
550
- .panel{
551
- grid-area:1/1;
552
- transition:opacity 280ms ease-out,transform 380ms cubic-bezier(.2,.6,.2,1),filter 380ms ease-out;
553
- }
554
- .panel[hidden]{
555
- display:block !important;
556
- opacity:0;transform:scale(0.96) translateY(-2px);filter:blur(6px);
557
- pointer-events:none;
558
- }
559
- .panel:not([hidden]){opacity:1;transform:scale(1);filter:none;pointer-events:auto}
560
-
561
- /* eyebrows */
562
- .eyebrow{
563
- font-family:var(--font-mono);font-size:10px;font-weight:700;
564
- letter-spacing:0.28em;text-transform:uppercase;color:var(--fg4);
565
- margin-bottom:24px;display:inline-flex;align-items:center;gap:7px;
566
- }
567
- .eyebrow .dot{width:5px;height:5px;border-radius:50%;background:currentColor}
568
- .eyebrow.danger{color:var(--rose)}
569
- .eyebrow.success{color:var(--green)}
570
- .eyebrow.success .dot{box-shadow:0 0 0 3px rgba(74,222,128,0.18)}
571
-
572
- /* form input */
573
- .input-wrap{
574
- display:flex;align-items:center;background:rgba(0,0,0,0.22);
575
- border:1px solid var(--border);border-radius:var(--radius-md);
576
- transition:border-color 200ms ease-out,box-shadow 200ms ease-out;
577
- }
578
- .input-wrap:focus-within{
579
- border-color:rgba(228,224,216,0.45);
580
- box-shadow:0 0 0 3px rgba(228,224,216,0.10);
581
- }
582
- .input-wrap.has-error{
583
- border-color:rgba(239,68,68,0.55);
584
- box-shadow:0 0 0 3px rgba(239,68,68,0.12);
585
- animation:shake 360ms cubic-bezier(.36,.07,.19,.97);
586
- }
587
- @keyframes shake{
588
- 10%,90%{transform:translateX(-1px)}20%,80%{transform:translateX(2px)}
589
- 30%,50%,70%{transform:translateX(-4px)}40%,60%{transform:translateX(4px)}
590
- }
591
- .input{
592
- flex:1;min-width:0;background:transparent;border:0;outline:none;
593
- padding:16px;
594
- font-family:var(--font-mono);font-size:14px;color:var(--fg1);letter-spacing:0.02em;
595
- }
596
- .input::placeholder{color:var(--fg4)}
597
- .hint{
598
- margin-top:10px;font-family:var(--font-mono);font-size:10.5px;
599
- letter-spacing:0.16em;text-transform:uppercase;
600
- text-align:left;padding-left:4px;height:14px;color:var(--fg4);
601
- transition:color 160ms ease-out;
602
- }
603
- .hint.is-error{color:var(--rose)}
604
-
605
- /* primary button */
606
- .btn-primary{
607
- width:100%;height:48px;margin-top:14px;
608
- border:0;border-radius:var(--radius-md);
609
- background:var(--btn-bg);color:var(--btn-fg);
610
- font-family:var(--font-body);font-size:14.5px;font-weight:600;letter-spacing:-0.005em;
611
- cursor:pointer;display:inline-flex;align-items:center;justify-content:center;gap:10px;
612
- transition:background 140ms ease-out,transform 80ms ease-out,opacity 200ms ease-out;
613
- position:relative;overflow:hidden;
614
- }
615
- .btn-primary:hover:not([disabled]){background:var(--btn-hover)}
616
- .btn-primary:active:not([disabled]){transform:translateY(1px)}
617
- .btn-primary[disabled]{opacity:0.45;cursor:default}
618
- .spin{
619
- width:14px;height:14px;border-radius:50%;
620
- border:1.5px solid currentColor;border-top-color:transparent;
621
- animation:spin 700ms linear infinite;opacity:0.85;
622
- }
623
- @keyframes spin{to{transform:rotate(360deg)}}
624
-
625
- /* secondary link */
626
- .small-link{
627
- margin-top:18px;font-family:var(--font-mono);font-size:11px;
628
- letter-spacing:0.18em;text-transform:uppercase;color:var(--fg4);
629
- }
630
- .small-link a{
631
- color:var(--fg3);text-decoration:none;border-bottom:1px dotted currentColor;
632
- padding-bottom:1px;transition:color 140ms;
633
- }
634
- .small-link a:hover{color:var(--fg1)}
635
-
636
- /* orb */
637
- .orb-wrap{
638
- position:relative;width:160px;height:160px;margin:0 auto 36px;
639
- display:grid;place-items:center;
640
- }
641
- .orb-ring{position:absolute;border-radius:50%}
642
- .orb-ring.r1{inset:0;border:1px solid rgba(228,224,216,0.06);animation:drift1 40s linear infinite}
643
- .orb-ring.r2{inset:18px;border:1px dashed rgba(228,224,216,0.10);animation:drift2 28s linear infinite}
644
- .orb-ring.r3{inset:38px;border:1px solid rgba(74,222,128,0.20);animation:ringPulse 3.4s ease-in-out infinite}
645
- @keyframes drift1{to{transform:rotate(360deg)}}
646
- @keyframes drift2{to{transform:rotate(-360deg)}}
647
- @keyframes ringPulse{0%,100%{opacity:0.6}50%{opacity:1}}
648
-
649
- .orb-wrap.is-verifying .orb-ring.r3{
650
- border-color:rgba(228,224,216,0.20);
651
- animation:ringPulse 1.1s ease-in-out infinite;
652
- }
653
- .orb-wrap.is-verifying .orb-core{
654
- 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);
655
- animation:corePulseNeutral 1.6s ease-in-out infinite;
656
- }
657
- .orb-wrap.is-verifying .orb-dot{background:var(--fg3);box-shadow:0 0 10px rgba(228,224,216,0.4)}
658
- @keyframes corePulseNeutral{
659
- 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)}
660
- 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)}
661
- }
662
-
663
- .orb-wrap.is-error .orb-ring.r3{border-color:rgba(239,68,68,0.30);animation:none;opacity:1}
664
- .orb-wrap.is-error .orb-ring.r1,.orb-wrap.is-error .orb-ring.r2{animation-play-state:paused}
665
- .orb-wrap.is-error .orb-core{
666
- 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);
667
- animation:none;
668
- }
669
- .orb-wrap.is-error .orb-dot{background:var(--rose);box-shadow:0 0 10px rgba(239,68,68,0.6)}
670
-
671
- .sat-orbit{position:absolute;inset:0;pointer-events:none}
672
- .sat-orbit.o1{animation:drift1 40s linear infinite}
673
- .sat-orbit.o2{animation:drift2 56s linear infinite}
674
- .sat{
675
- position:absolute;top:50%;left:50%;
676
- font-family:var(--font-mono);font-size:9px;font-weight:700;letter-spacing:0.14em;
677
- background:var(--bg);padding:2px 6px;border-radius:3px;
678
- border:1px solid var(--border-light);
679
- transform-origin:0 0;opacity:0;
680
- }
681
- .panel:not([hidden])[data-state="connected"] .sat{animation:satIn 600ms ease-out forwards}
682
- @keyframes satIn{from{opacity:0}to{opacity:1}}
683
- .sat span{display:inline-block;animation:counter 40s linear infinite}
684
- .sat-orbit.o2 .sat span{animation:counter2 56s linear infinite}
685
- @keyframes counter{to{transform:rotate(-360deg)}}
686
- @keyframes counter2{to{transform:rotate(360deg)}}
687
-
688
- .orb-core{
689
- position:relative;width:60px;height:60px;border-radius:50%;
690
- background:radial-gradient(circle at 50% 45%,#1a1a1a 0%,#0c0c0c 60%,#050505 100%);
691
- border:1px solid rgba(255,255,255,0.06);
692
- display:grid;place-items:center;
693
- 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);
694
- animation:corePulse 3.4s ease-in-out infinite;
695
- }
696
- @keyframes corePulse{
697
- 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)}
698
- 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)}
699
- }
700
- .orb-dot{width:10px;height:10px;border-radius:50%;background:#4ade80;box-shadow:0 0 12px rgba(74,222,128,0.7)}
701
-
702
- .core-shockwave{
703
- position:absolute;inset:0;border-radius:50%;
704
- border:1px solid rgba(74,222,128,0.6);
705
- opacity:0;pointer-events:none;
706
- }
707
- .panel:not([hidden])[data-state="connected"] .core-shockwave{animation:shock 1100ms ease-out 200ms}
708
- @keyframes shock{
709
- 0%{opacity:0.7;transform:scale(0.4);border-width:2px}
710
- 100%{opacity:0;transform:scale(2.4);border-width:1px}
711
- }
712
-
713
- /* titles */
714
- .ok-title{
715
- font-family:var(--font-display);font-weight:600;
716
- font-size:38px;line-height:1.05;letter-spacing:-0.025em;
717
- color:var(--fg-bright);opacity:0;
718
- }
719
- .panel:not([hidden]) .ok-title{animation:rise 600ms ease-out 380ms forwards}
720
- .ok-lead{
721
- margin:18px auto 0;max-width:22em;font-size:16px;line-height:1.55;color:var(--fg2);
722
- opacity:0;
723
- }
724
- .panel:not([hidden]) .ok-lead{animation:rise 600ms ease-out 500ms forwards}
725
- .ok-phrase-row{
726
- margin-top:14px;display:flex;align-items:center;justify-content:center;
727
- opacity:0;
728
- }
729
- .panel:not([hidden]) .ok-phrase-row{animation:rise 600ms ease-out 620ms forwards}
730
- .cmd.is-copied .cmd-quote-part{display:none}
731
- .success-cta-wrap{
732
- margin-top:48px;width:100%;opacity:0;
733
- }
734
- .panel:not([hidden]) .success-cta-wrap{animation:rise 600ms ease-out 780ms forwards}
735
- a.btn-primary.success-cta{color:var(--btn-fg);text-decoration:none}
736
-
737
- .cmd{
738
- display:inline-flex;align-items:center;gap:8px;vertical-align:middle;
739
- font-family:var(--font-mono);font-size:15px;font-weight:500;color:var(--accent);
740
- background:rgba(201,185,154,0.08);border:1px solid rgba(201,185,154,0.30);
741
- padding:5px 10px 5px 12px;border-radius:6px;letter-spacing:0.02em;
742
- cursor:pointer;user-select:none;
743
- transition:background 140ms ease-out,border-color 140ms ease-out,color 140ms ease-out;
744
- }
745
- .cmd:hover{background:rgba(201,185,154,0.14);border-color:rgba(201,185,154,0.50);color:#dcc9a4}
746
- .cmd.is-copied{color:var(--green);border-color:rgba(74,222,128,0.35);background:rgba(74,222,128,0.08)}
747
- .cmd .cmd-icon{
748
- width:12px;height:12px;color:currentColor;opacity:0.75;
749
- display:inline-grid;place-items:center;
750
- transition:opacity 140ms;
751
- }
752
- .cmd:hover .cmd-icon{opacity:1}
753
- .cmd.is-copied .cmd-icon{color:var(--green);opacity:1}
754
- .cmd .cmd-icon svg{width:12px;height:12px;stroke:currentColor;fill:none;stroke-width:1.5;stroke-linecap:round;stroke-linejoin:round}
755
-
756
- /* error specifics */
757
- .err-title{
758
- font-family:var(--font-display);font-weight:600;
759
- font-size:32px;line-height:1.1;letter-spacing:-0.02em;
760
- color:var(--fg1);margin-bottom:12px;
761
- }
762
- .err-msg{
763
- font-size:14.5px;line-height:1.55;color:var(--fg3);
764
- margin-bottom:28px;
765
- }
766
- .err-msg code{
767
- font-family:var(--font-mono);font-size:12px;
768
- background:rgba(255,255,255,0.06);padding:1px 5px;border-radius:4px;color:var(--fg2);
769
- }
770
- .err-actions{display:flex;gap:8px}
771
- .btn-secondary{
772
- flex:1;height:44px;border-radius:var(--radius-md);
773
- background:transparent;color:var(--fg2);
774
- border:1px solid var(--border);
775
- font-family:var(--font-body);font-size:13.5px;font-weight:500;
776
- cursor:pointer;text-decoration:none;
777
- display:inline-flex;align-items:center;justify-content:center;
778
- transition:background 140ms,color 140ms,border-color 140ms;
779
- }
780
- .btn-secondary:hover{background:rgba(255,255,255,0.04);color:var(--fg1);border-color:rgba(255,255,255,0.14)}
781
-
782
- /* verifying */
783
- .verifying-eyebrow{
784
- font-family:var(--font-mono);font-size:10px;
785
- letter-spacing:0.28em;text-transform:uppercase;color:var(--fg3);
786
- font-weight:700;margin-bottom:14px;
787
- }
788
- .verifying-title{
789
- font-family:var(--font-display);font-weight:600;
790
- font-size:28px;line-height:1.1;color:var(--fg1);margin-bottom:8px;
791
- letter-spacing:-0.02em;
792
- }
793
- .verifying-sub{font-size:13px;color:var(--fg3);min-height:1.45em}
794
-
795
- /* form heading */
796
- .form-title{
797
- font-family:var(--font-display);font-weight:600;
798
- font-size:32px;line-height:1.1;letter-spacing:-0.02em;
799
- color:var(--fg1);margin-bottom:10px;
800
- }
801
- .form-sub{font-size:13.5px;color:var(--fg3);margin-bottom:28px;line-height:1.55}
802
-
803
- @keyframes rise{from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:translateY(0)}}
804
-
805
- @media (prefers-reduced-motion: reduce){
806
- *,*::before,*::after{
807
- animation-duration:0.01ms !important;animation-iteration-count:1 !important;
808
- transition-duration:0.01ms !important;
809
- }
810
- }
811
- </style>
812
- </head><body>
813
- <div class="top-mark">${appLogoMarkup({ size: "sm" })}</div>
814
- <div class="stage">${bodyContent}</div>
815
- </body></html>`;
816
- }
817
- var PROVIDER_NAME = "your assistant";
818
- function successPanelInner(workspaceName, redirectUrl, providerName) {
819
- return `
820
- <div class="orb-wrap">
821
- <div class="orb-ring r1"></div>
822
- <div class="orb-ring r2"></div>
823
- <div class="orb-ring r3"></div>
824
- <div class="sat-orbit o1">
825
- <span class="sat" style="transform:rotate(20deg) translate(78px) rotate(-20deg);color:#4ade80;animation-delay:600ms"><span>DEC</span></span>
826
- <span class="sat" style="transform:rotate(140deg) translate(78px) rotate(-140deg);color:#c9b99a;animation-delay:720ms"><span>WP</span></span>
827
- <span class="sat" style="transform:rotate(260deg) translate(78px) rotate(-260deg);color:#f59e0b;animation-delay:840ms"><span>TEN</span></span>
828
- </div>
829
- <div class="sat-orbit o2">
830
- <span class="sat" style="transform:rotate(80deg) translate(54px) rotate(-80deg);color:#60a5fa;animation-delay:960ms"><span>STD</span></span>
831
- <span class="sat" style="transform:rotate(220deg) translate(54px) rotate(-220deg);color:#a78bfa;animation-delay:1080ms"><span>INS</span></span>
832
- </div>
833
- <div class="core-shockwave"></div>
834
- <div class="orb-core"><div class="orb-dot"></div></div>
835
- </div>
836
- <div class="eyebrow success"><span class="dot"></span>Connected</div>
837
- <h1 class="ok-title">Product Brain is Live</h1>
838
- <p class="ok-lead">Return to your assistant, then say</p>
839
- <div class="ok-phrase-row">
840
- <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)}">
841
- <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>
842
- <span class="cmd-icon" aria-hidden="true">
843
- <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>
844
- </span>
845
- </button>
846
- </div>
847
- <div class="success-cta-wrap">
848
- <a class="btn-primary success-cta" href="${esc(redirectUrl)}">Continue in ${esc(providerName)}</a>
849
- </div>
850
- <!-- workspace name retained as data hook for tests, hidden from view -->
851
- <span hidden data-field="ws-name">${esc(workspaceName)}</span>`;
852
- }
853
- function errorPanelInner(title, trustedDetailHtml, retryUrl) {
854
- return `
855
- <div class="orb-wrap is-error">
856
- <div class="orb-ring r1"></div>
857
- <div class="orb-ring r2"></div>
858
- <div class="orb-ring r3"></div>
859
- <div class="orb-core"><div class="orb-dot"></div></div>
860
- </div>
861
- <div class="eyebrow danger"><span class="dot"></span>Couldn't connect</div>
862
- <h2 class="err-title" data-field="err-title">${esc(title)}</h2>
863
- <p class="err-msg" data-field="err-msg">${trustedDetailHtml}</p>
864
- <div class="err-actions">
865
- <a href="${esc(retryUrl)}" class="btn-secondary" data-retry-link>&larr; Try again</a>
866
- <a href="${esc(apiKeysUrl())}" target="_blank" rel="noopener noreferrer" class="btn-secondary">Get an API key &rarr;</a>
867
- </div>`;
868
- }
869
- var cmdScript = `
870
- (function(){
871
- function bindCmd(pill){
872
- if(!pill||pill.__bound)return;pill.__bound=true;
873
- var textEl=pill.querySelector('[data-cmd-text]');
874
- var svgEl=pill.querySelector('[data-cmd-svg]');
875
- var redirectUrl=pill.getAttribute('data-redirect')||'';
876
- pill.addEventListener('click',function(){
877
- var done=function(){
878
- pill.classList.add('is-copied');
879
- if(textEl)textEl.textContent='Copied';
880
- if(svgEl)svgEl.innerHTML='<polyline points="4 12 10 18 20 6"/>';
881
- setTimeout(function(){if(redirectUrl)window.location.assign(redirectUrl)},900);
882
- };
883
- try{
884
- if(navigator.clipboard&&navigator.clipboard.writeText){
885
- navigator.clipboard.writeText(${JSON.stringify(PASTE_NOW)}).then(done,done);
886
- }else{done()}
887
- }catch(e){done()}
888
- });
889
- }
890
- document.querySelectorAll('[data-cmd-pill]').forEach(bindCmd);
891
- })();
892
- `;
893
- function authorizeFormPage(params) {
894
- const { redirect_uri, code_challenge, code_challenge_method, state, client_id } = params;
895
- const providerName = PROVIDER_NAME;
896
- const body = `
897
- <!-- \u2500\u2500\u2500 CONNECT \u2500\u2500\u2500 -->
898
- <div class="panel" id="p-connect" data-state="connect">
899
- <div class="eyebrow">Connect Product Brain</div>
900
- <h1 class="form-title">Paste your API key</h1>
901
- <p class="form-sub">Give <span data-provider>${esc(providerName)}</span> access to your workspace memory.</p>
902
- <form method="POST" action="/authorize" id="f" autocomplete="off">
903
- <input type="hidden" name="redirect_uri" value="${esc(redirect_uri)}">
904
- <input type="hidden" name="code_challenge" value="${esc(code_challenge)}">
905
- <input type="hidden" name="code_challenge_method" value="${esc(code_challenge_method)}">
906
- <input type="hidden" name="state" value="${esc(state)}">
907
- <input type="hidden" name="client_id" value="${esc(client_id)}">
908
- <div class="input-wrap" id="iw">
909
- <input type="password" id="k" name="api_key" class="input input-full" placeholder="pb_sk_\u2026" required autofocus spellcheck="false">
910
- </div>
911
- <div class="hint" id="hint" hidden></div>
912
- <button type="submit" class="btn-primary" id="sb" disabled><span id="bt">Connect</span></button>
913
- </form>
914
- <div class="small-link"><a href="${esc(apiKeysUrl())}" target="_blank" rel="noopener noreferrer">No key? Generate one &rarr;</a></div>
915
- </div>
916
-
917
- <!-- \u2500\u2500\u2500 VERIFYING \u2500\u2500\u2500 -->
918
- <div class="panel" id="p-verifying" data-state="verifying" hidden>
919
- <div class="orb-wrap is-verifying">
920
- <div class="orb-ring r1"></div>
921
- <div class="orb-ring r2"></div>
922
- <div class="orb-ring r3"></div>
923
- <div class="orb-core"><div class="orb-dot"></div></div>
924
- </div>
925
- <div class="verifying-eyebrow">Handshake</div>
926
- <h2 class="verifying-title">Verifying key\u2026</h2>
927
- <p class="verifying-sub" id="verify-sub">Checking workspace \xB7 \u2026</p>
928
- </div>
929
-
930
- <!-- \u2500\u2500\u2500 CONNECTED (filled by JS from JSON response) \u2500\u2500\u2500 -->
931
- <div class="panel" id="p-connected" data-state="connected" hidden></div>
932
-
933
- <!-- \u2500\u2500\u2500 ERROR (filled by JS from JSON response) \u2500\u2500\u2500 -->
934
- <div class="panel" id="p-error" data-state="error" hidden></div>
935
-
936
- <template id="tpl-connected">${successPanelInner("__WS__", "__URL__", "__PROVIDER__")}</template>
937
- <template id="tpl-error">${errorPanelInner("__TITLE__", "__DETAIL__", "__RETRY__")}</template>
938
-
939
- <script>
940
- ${cmdScript}
941
- (function(){
942
- 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');
943
- var pConnect=document.getElementById('p-connect'),pVerify=document.getElementById('p-verifying'),pOk=document.getElementById('p-connected'),pErr=document.getElementById('p-error');
944
- var verifySub=document.getElementById('verify-sub');
945
-
946
- function show(panel){
947
- [pConnect,pVerify,pOk,pErr].forEach(function(p){
948
- if(p===panel){p.removeAttribute('hidden')}else{p.setAttribute('hidden','')}
949
- });
950
- }
951
-
952
- function syncInput(){
953
- sb.disabled=!k.value.trim();
954
- iw.classList.remove('has-error');
955
- hint.classList.remove('is-error');
956
- hint.textContent='';
957
- hint.setAttribute('hidden','');
958
- }
959
- k.addEventListener('input',syncInput);
960
- k.addEventListener('keydown',function(e){
961
- if(e.key==='Escape'){k.value='';syncInput()}
962
- });
963
-
964
- function showError(title,detailHtml){
965
- var tpl=document.getElementById('tpl-error');
966
- var html=tpl.innerHTML
967
- .replace('__TITLE__',title.replace(/[<>&]/g,function(c){return{'<':'&lt;','>':'&gt;','&':'&amp;'}[c]}))
968
- .replace('__DETAIL__',detailHtml)
969
- .replace('__RETRY__','#');
970
- pErr.innerHTML=html;
971
- var retry=pErr.querySelector('[data-retry-link]');
972
- if(retry){retry.addEventListener('click',function(e){e.preventDefault();show(pConnect);k.focus();k.select()})}
973
- show(pErr);
974
- }
975
-
976
- function showSuccess(workspaceName,redirectUrl,providerName){
977
- var tpl=document.getElementById('tpl-connected');
978
- var safeWs=String(workspaceName||'').replace(/[<>&]/g,function(c){return{'<':'&lt;','>':'&gt;','&':'&amp;'}[c]});
979
- var safeProv=String(providerName||'your assistant').replace(/[<>&]/g,function(c){return{'<':'&lt;','>':'&gt;','&':'&amp;'}[c]});
980
- var safeUrl=String(redirectUrl||'').replace(/"/g,'&quot;').replace(/[<>]/g,function(c){return{'<':'&lt;','>':'&gt;'}[c]});
981
- var html=tpl.innerHTML.split('__WS__').join(safeWs).split('__URL__').join(safeUrl).split('__PROVIDER__').join(safeProv);
982
- pOk.innerHTML=html;
983
- pOk.querySelectorAll('[data-cmd-pill]').forEach(function(pill){
984
- pill.__bound=false;
985
- });
986
- // Re-run binder
987
- var s=document.createElement('script');s.textContent=${JSON.stringify(cmdScript)};document.body.appendChild(s);s.remove();
988
- show(pOk);
989
- }
990
-
991
- f.addEventListener('submit',function(e){
992
- e.preventDefault();
993
- var v=k.value.trim();
994
- if(!v){iw.classList.add('has-error');hint.classList.add('is-error');hint.textContent='Paste your key first';hint.removeAttribute('hidden');return}
995
- sb.disabled=true;bt.textContent='Verifying';
996
- show(pVerify);
997
-
998
- var steps=['Checking workspace \xB7 \u2026','Loading chain \xB7 \u2026','Establishing memory \xB7 \u2026'];
999
- var i=0;verifySub.textContent=steps[0];
1000
- var ti=setInterval(function(){i++;if(i>=steps.length){clearInterval(ti);return}verifySub.textContent=steps[i]},900);
1001
-
1002
- var minDelay=new Promise(function(r){setTimeout(r,2800)});
1003
- var fd=new FormData(f);
1004
- var body=new URLSearchParams();
1005
- fd.forEach(function(val,key){body.append(key,String(val))});
1006
-
1007
- var req=fetch('/authorize',{
1008
- method:'POST',
1009
- headers:{'Accept':'application/json','Content-Type':'application/x-www-form-urlencoded'},
1010
- body:body.toString(),
1011
- credentials:'same-origin'
1012
- }).then(function(r){return r.json().then(function(j){return{status:r.status,body:j}})});
1013
-
1014
- Promise.all([req,minDelay]).then(function(arr){
1015
- clearInterval(ti);
1016
- var res=arr[0];
1017
- if(res.body&&res.body.ok){
1018
- showSuccess(res.body.workspaceName,res.body.redirectUrl,res.body.providerName);
1019
- }else{
1020
- showError(res.body&&res.body.title||'Couldn\\'t connect',res.body&&res.body.detail||'Try again, or generate a new key.');
1021
- sb.disabled=false;bt.textContent='Connect';
1022
- }
1023
- }).catch(function(){
1024
- clearInterval(ti);
1025
- showError('Network error','We couldn\\'t reach Product Brain. Check your connection and try again.');
1026
- sb.disabled=false;bt.textContent='Connect';
1027
- });
1028
- });
1029
-
1030
- k.focus();
1031
- })();
1032
- </script>`;
1033
- return authPageShell("Connect Product Brain", body);
1034
- }
1035
- function authorizeSuccessPage(workspaceName, redirectUrl, providerName) {
1036
- const body = `
1037
- <div class="panel" data-state="connected">
1038
- ${successPanelInner(workspaceName, redirectUrl, providerName)}
1039
- </div>
1040
- <script>${cmdScript}</script>`;
1041
- return authPageShell("Connected", body);
1042
- }
1043
- function authorizeErrorPage(title, trustedDetailHtml, retryUrl) {
1044
- const body = `
1045
- <div class="panel" data-state="error">
1046
- ${errorPanelInner(title, trustedDetailHtml, retryUrl)}
1047
- </div>`;
1048
- return authPageShell("Connection error", body);
1049
- }
1050
- app.get("/authorize", authLimiter, (req, res) => {
1051
- const { redirect_uri, code_challenge, code_challenge_method, state, client_id } = req.query;
1052
- const refusal = checkRedirectUri(redirect_uri, OAUTH_REDIRECT_ALLOWLIST);
1053
- if (refusal) {
1054
- logOAuthDoor("GET /authorize", 400, refusal);
1055
- res.status(400).json({ error: "invalid_request", error_description: refusal });
1056
- return;
1057
- }
1058
- res.type("html").send(authorizeFormPage({
1059
- redirect_uri: String(redirect_uri ?? ""),
1060
- code_challenge: String(code_challenge ?? ""),
1061
- code_challenge_method: String(code_challenge_method ?? "S256"),
1062
- state: String(state ?? ""),
1063
- client_id: String(client_id ?? "")
1064
- }));
1065
- });
1066
- app.post(
1067
- "/authorize",
1068
- authLimiter,
1069
- express.urlencoded({ extended: false }),
1070
- async (req, res) => {
1071
- const { redirect_uri, code_challenge, code_challenge_method, state, client_id } = req.body;
1072
- const api_key = normalisePastedKey(req.body.api_key);
1073
- const wantsJson = String(req.headers["accept"] ?? "").includes("application/json");
1074
- const retryParams = new URLSearchParams({
1075
- redirect_uri: redirect_uri ?? "",
1076
- code_challenge: code_challenge ?? "",
1077
- code_challenge_method: code_challenge_method ?? "S256",
1078
- ...state ? { state } : {},
1079
- ...client_id ? { client_id } : {}
1080
- }).toString();
1081
- const retryUrl = `/authorize?${retryParams}`;
1082
- function sendError(title, trustedDetailHtml, status = 400) {
1083
- logOAuthDoor("POST /authorize", status, title);
1084
- if (wantsJson) {
1085
- res.status(status).json({ ok: false, title, detail: trustedDetailHtml });
1086
- } else {
1087
- res.status(status).type("html").send(authorizeErrorPage(title, trustedDetailHtml, retryUrl));
1088
- }
1089
- }
1090
- if (isCrossSiteFormPost(req.headers["origin"], req.headers["sec-fetch-site"], baseUrl(req))) {
1091
- sendError("Request refused", "This form only accepts keys sent from its own sign-in page. Open the connect link again.", 403);
1092
- return;
1093
- }
1094
- const nowTs = Date.now();
1095
- const pasted = resolvePastedKey(api_key);
1096
- const lockout = authLockoutError(authFailures, pasted, nowTs);
1097
- if (lockout) {
1098
- const retryAfter = lockout.headers["Retry-After"];
1099
- res.setHeader("Retry-After", retryAfter);
1100
- sendError("Too many attempts", `This key was not recognized too many times. Try again in ${retryAfter}s.`, 429);
1101
- return;
1102
- }
1103
- if (pasted.status !== "ok") {
1104
- if (pasted.status === "rejected") recordAuthFailure(authFailures, pasted.credentialId, nowTs);
1105
- sendError("Invalid key format", "API keys start with <code>pb_sk_</code>. Check your key and try again.");
1106
- return;
1107
- }
1108
- if (!client_id) {
1109
- logOAuthDoor("POST /authorize", 400, "client_id is required");
1110
- res.status(400).json({ error: "invalid_request", error_description: "client_id is required" });
1111
- return;
1112
- }
1113
- const redirectRefusal = checkRedirectUri(redirect_uri, OAUTH_REDIRECT_ALLOWLIST);
1114
- if (redirectRefusal) {
1115
- logOAuthDoor("POST /authorize", 400, redirectRefusal);
1116
- res.status(400).json({ error: "invalid_request", error_description: redirectRefusal });
1117
- return;
1118
- }
1119
- let workspaceName = "Your Workspace";
1120
- const check = await checkKeyAgainstCandidates(keyCheckCandidates(), api_key, 5e3);
1121
- const gate = keyVerdictGate(check.verdict, authFailures, pasted.credentialId, nowTs);
1122
- if (check.verdict === "ok") {
1123
- if (check.workspaceName) workspaceName = check.workspaceName;
1124
- getKeyState(api_key).deploymentUrl = check.deploymentUrl;
1125
- } else if (check.verdict === "rate_limited") {
1126
- sendError(
1127
- "Rate limited",
1128
- `This API key is valid but temporarily rate limited. Try again in ${check.retryAfterSeconds ?? 60}s.`,
1129
- 429
1130
- );
1131
- return;
1132
- } else if (gate === "unauthorized") {
1133
- sendError("Key not recognized", "This API key wasn't found in Product Brain. Check your API Keys in Cortex and try again.", 401);
1134
- return;
1135
- } else {
1136
- process.stderr.write("[authorize] key-check unavailable \u2014 proceeding without validation\n");
1137
- }
1138
- const code = randomUUID();
1139
- pendingCodes.set(code, {
1140
- apiKey: api_key,
1141
- codeChallenge: code_challenge,
1142
- redirectUri: redirect_uri,
1143
- expiresAt: Date.now() + 5 * 6e4
1144
- });
1145
- const url = new URL(redirect_uri);
1146
- url.searchParams.set("code", code);
1147
- if (state) url.searchParams.set("state", state);
1148
- const redirectUrl = url.toString();
1149
- const providerName = PROVIDER_NAME;
1150
- logOAuthDoor("POST /authorize", 200, "code_issued");
1151
- if (wantsJson) {
1152
- res.json({ ok: true, workspaceName, redirectUrl, providerName });
1153
- } else {
1154
- res.type("html").send(authorizeSuccessPage(workspaceName, redirectUrl, providerName));
1155
- }
1156
- }
1157
- );
1158
601
  app.post(
1159
602
  "/oauth/token",
1160
603
  express.urlencoded({ extended: false }),
1161
604
  express.json(),
1162
- (req, res) => {
1163
- const { grant_type, code, code_verifier, redirect_uri } = req.body ?? {};
1164
- if (grant_type !== "authorization_code") {
1165
- logOAuthDoor("POST /oauth/token", 400, "unsupported_grant_type");
1166
- res.status(400).json({ error: "unsupported_grant_type" });
1167
- return;
1168
- }
1169
- const pending = pendingCodes.get(code);
1170
- const codeRefusal = pendingCodeRefusal(pending, redirect_uri, Date.now());
1171
- if (codeRefusal === "expired") {
1172
- pendingCodes.delete(code);
1173
- logOAuthDoor("POST /oauth/token", 400, "expired");
1174
- res.status(400).json({ error: "invalid_grant", error_description: "authorization code expired" });
1175
- return;
1176
- }
1177
- if (codeRefusal || !pending) {
1178
- logOAuthDoor("POST /oauth/token", 400, codeRefusal ?? "unknown_code");
1179
- res.status(400).json({ error: "invalid_grant" });
1180
- return;
1181
- }
1182
- const challenge = createHash("sha256").update(code_verifier ?? "").digest("base64url");
1183
- if (challenge !== pending.codeChallenge) {
1184
- pendingCodes.delete(code);
1185
- logOAuthDoor("POST /oauth/token", 400, "pkce_failed");
1186
- res.status(400).json({
1187
- error: "invalid_grant",
1188
- error_description: "PKCE verification failed"
1189
- });
1190
- return;
1191
- }
1192
- pendingCodes.delete(code);
1193
- logOAuthDoor("POST /oauth/token", 200, "token_issued");
1194
- res.json(tokenResponse(pending.apiKey));
605
+ async (req, res) => {
606
+ sendDoor(res, "POST /oauth/token", await exchangeOutcome(req.body ?? {}, { candidates: keyCheckCandidates() }));
1195
607
  }
1196
608
  );
1197
609
  var mcpLimit = mcpLimiters();