File size: 23,529 Bytes
3464008
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
/**
 * GET /oauth/authorize-pro
 *
 * U5 of plan 2026-05-10-001 β€” receives the bounce-back from the apex
 * `/mcp-grant` flow (U3) and finishes the OAuth authorization on the
 * api subdomain. This endpoint:
 *
 *   1. HMAC-verifies the signed grant FIRST (via `verifyGrant` from
 *      `api/_mcp-grant-hmac.ts`). On any failure (malformed / bad-sig /
 *      expired / invalid-payload) β†’ vague HTML error. Never reveal which
 *      piece failed (avoids enumeration).
 *   2. Asserts the grant payload's `nonce` matches the URL `?nonce=` query
 *      parameter (defense vs grant-payload-swap forgery class).
 *   3. Atomically `GETDEL mcp-grant:<n>` β†’ recovers `{userId, exp}` written
 *      by U3. Strict equality check against grant payload's `userId` AND
 *      `exp` (defense vs grant-without-redis-record forgery + token cloning
 *      across users).
 *   4. Atomically `GETDEL oauth:nonce:<n>` β†’ recovers
 *      `{client_id, redirect_uri, code_challenge, state}` written by
 *      `api/oauth/authorize.js`. One-shot β€” replay fails on the second hit.
 *   5. Reads (does NOT consume) `oauth:client:<client_id>` for client_name
 *      + redirect_uri allowlist re-check (defense-in-depth; DCR validated
 *      this at register time but allowlist could be tightened since).
 *   6. Re-fetches `getEntitlements(userId)` from Convex β€” the grant could
 *      be up to 5 minutes old; tier may have lapsed since mint. A denial here
 *      is split three ways (#5622): an unverifiable entitlement or in-flight
 *      renewal check renders a retryable 503 page (`Retry-After` +
 *      `X-Billing-Verification`), a provider-confirmed lapse renders a distinct
 *      403, and only a confirmed non-Pro row gets the "Pro Subscription
 *      Required" upsell.
 *   7. Calls `issueProMcpTokenForUser` to insert a Convex `mcpProTokens`
 *      row. NO `wm_` key, NO `WORLDMONITOR_VALID_KEYS` write β€” Pro identity
 *      lives only in Convex, the OAuth code carries the row id.
 *   8. Writes `oauth:code:<code>` = `{kind:'pro', userId, mcpTokenId,
 *      client_id, redirect_uri, code_challenge, scope:'mcp_pro'}` with
 *      10-min TTL (matches the legacy authorize.js code TTL).
 *   9. On `oauth:code` SETEX failure: best-effort `revokeProMcpToken`
 *      rollback (does NOT throw per U2's contract) so we don't leave
 *      orphaned `mcpProTokens` rows.
 *  10. 302 β†’ `redirect_uri?code=<code>` (+ optional `state`). Cache-Control:
 *      no-store on every response (memory `warmping-origin-trust-cdn-401-poisoning`:
 *      CF can poison-cache 4xx; we never want intermediate caches holding
 *      either the redirect or an error page).
 *
 * Security invariants:
 *   - HMAC verify happens BEFORE any Redis call. Forged grants never burn
 *     the one-shot Redis nonces.
 *   - Both `mcp-grant:<n>` and `oauth:nonce:<n>` are GETDEL'd (one-shot).
 *     Replay of either fails the second time.
 *   - `oauth:code` value uses `kind:'pro'` discriminator β€” U6's bearer
 *     resolver branches on this. The shape is load-bearing for U6.
 *
 * Discriminated `oauth:code:<code>` shape (LOAD-BEARING β€” see U6):
 *
 *   {
 *     kind: 'pro',
 *     userId: string,
 *     mcpTokenId: string,
 *     client_id: string,
 *     redirect_uri: string,
 *     code_challenge: string,
 *     scope: 'mcp_pro',
 *   }
 *
 * Errors return HTML (browser-facing flow). All errors set Cache-Control:
 * no-store. The error copy is intentionally vague to avoid leaking which
 * security check tripped.
 */

export const config = { runtime: 'edge' };

import { verifyGrant, GrantConfigError } from '../_mcp-grant-hmac';
import {
  getEntitlements,
  isEntitlementBackendConfigured,
  type BillingVerificationDenial,
} from '../../server/_shared/entitlement-check';
import { checkProMcpAccess, type ProMcpEntitlement } from '../../server/_shared/pro-mcp-gate';
import {
  issueProMcpTokenForUser,
  revokeProMcpToken,
  ProMcpIssueFailed,
} from '../../server/_shared/pro-mcp-token';
// @ts-expect-error β€” JS module, no declaration file
import { captureSilentError } from '../_sentry-edge.js';

/** OAuth authorization-code TTL β€” matches `api/oauth/authorize.js:10`. */
const CODE_TTL_SECONDS = 600;

const PAGE_HEADERS: Record<string, string> = {
  'Content-Type': 'text/html; charset=utf-8',
  'X-Frame-Options': 'DENY',
  'Cache-Control': 'no-store',
  Pragma: 'no-cache',
};

const GLOBE_SVG =
  '<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><path d="M2 12h20M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/></svg>';

function escapeHtml(str: string): string {
  return String(str)
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#x27;');
}

/**
 * HTML error response β€” mirrors the visual style of
 * `api/oauth/authorize.js::htmlError` (line 89). Kept identical so the
 * user experience is consistent between the legacy API-key path and the
 * Pro Clerk path. Status defaults to 400; pass 500/503 for server-side
 * issues so monitoring distinguishes them, but copy is vague to the user.
 */
function htmlError(
  title: string,
  detail: string,
  status: number = 400,
  extraHeaders: Record<string, string> = {},
): Response {
  return new Response(
    `<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Error &#x2014; WorldMonitor MCP</title>
<style>*{box-sizing:border-box;margin:0;padding:0}body{font-family:ui-monospace,'SF Mono','Cascadia Code',monospace;background:#0a0a0a;color:#e8e8e8;min-height:100vh;display:flex;flex-direction:column;align-items:center;justify-content:center;padding:1.5rem}.wm-logo{display:flex;align-items:center;gap:.5rem;margin-bottom:2rem;text-decoration:none}.wm-logo svg{color:#2d8a6e}.wm-logo-text{font-size:.75rem;color:#555;letter-spacing:.1em;text-transform:uppercase}.card{width:100%;max-width:420px;background:#111;border:1px solid #1e1e1e;padding:2rem}h1{font-size:.95rem;font-weight:600;color:#ef4444;margin-bottom:.75rem;letter-spacing:.02em}p{font-size:.85rem;color:#666;line-height:1.6}.back{display:inline-block;margin-top:1.5rem;font-size:.75rem;color:#444;text-decoration:none;letter-spacing:.03em}.back:hover{color:#888}.footer{margin-top:1.5rem;font-size:.7rem;color:#2a2a2a;text-align:center}.footer a{color:#333;text-decoration:none}.footer a:hover{color:#555}</style></head>
<body><a href="https://www.worldmonitor.app" class="wm-logo" target="_blank" rel="noopener">${GLOBE_SVG}<span class="wm-logo-text">WorldMonitor MCP</span></a>
<div class="card"><h1>${escapeHtml(title)}</h1><p>${escapeHtml(detail)}</p><a href="javascript:history.back()" class="back">&#8592; go back</a></div>
<p class="footer"><a href="https://www.worldmonitor.app" target="_blank" rel="noopener">worldmonitor.app</a></p>
</body></html>`,
    { status, headers: { ...PAGE_HEADERS, ...extraHeaders } },
  );
}

/**
 * The Pro gate's HTML rendering of the shared billing-verification contract
 * (#5622). Six JSON endpoints adopted that contract in #5600; this page was
 * deliberately left out because it needed a copy decision, and until now it
 * flattened an *unverifiable* entitlement into the same terminal "Pro
 * Subscription Required" page a confirmed free user sees.
 *
 * Two things make the copy here different from the JSON surfaces:
 *
 *  1. **Retrying THIS URL cannot work.** By the time the gate runs, both
 *     one-shot Redis keys (`mcp-grant:<n>`, `oauth:nonce:<n>`) have been
 *     GETDEL'd in steps 3-4, so a reload fails as an expired session. The copy
 *     therefore sends the user back to their MCP client to start the connection
 *     again β€” it never says "reload this page". The machine-readable retry
 *     signal still goes out as `Retry-After` + `X-Billing-Verification` for
 *     monitoring and for any non-browser client following the redirect.
 *  2. **No locale fan-out.** This page is hardcoded `lang="en"` with literal
 *     English copy (matching `api/oauth/authorize.js::htmlError`), so it is not
 *     part of the ~25-locale surface β€” new copy here costs no translation work.
 */
function billingVerificationPage(
  denial: BillingVerificationDenial,
): Response {
  const headers: Record<string, string> = { 'X-Billing-Verification': denial.code };
  if (!denial.retryable) {
    return htmlError(
      'Subscription Lapsed',
      'Your WorldMonitor Pro subscription is no longer active, so this connection '
      + 'cannot be authorized. Renew your subscription at worldmonitor.app, then '
      + 'start the connection again from your MCP client.',
      403,
      headers,
    );
  }
  headers['Retry-After'] = String(denial.retryAfterSeconds);
  return htmlError(
    'Verifying Your Subscription',
    `We could not confirm your WorldMonitor Pro subscription just now β€” this is `
    + `temporary and does not mean your subscription has a problem. Wait about `
    + `${denial.retryAfterSeconds} seconds, then start the connection again from your `
    + `MCP client. (This authorization session is single-use, so it has to be `
    + `restarted rather than reloaded.)`,
    503,
    headers,
  );
}

// ---------------------------------------------------------------------------
// Redis helpers β€” match the on-the-wire format used by api/oauth/authorize.js
// (raw `oauth:*` and `mcp-grant:*` keys, no env prefix).
// ---------------------------------------------------------------------------

async function rawRedisGetDel(key: string): Promise<unknown | null> {
  const url = process.env.UPSTASH_REDIS_REST_URL;
  const token = process.env.UPSTASH_REDIS_REST_TOKEN;
  if (!url || !token) throw new Error('Redis not configured');
  const resp = await fetch(`${url}/getdel/${encodeURIComponent(key)}`, {
    headers: { Authorization: `Bearer ${token}` },
    signal: AbortSignal.timeout(3_000),
  });
  if (!resp.ok) throw new Error(`Redis HTTP ${resp.status}`);
  const data = (await resp.json()) as { result?: string | null };
  if (!data?.result) return null;
  try {
    return JSON.parse(data.result);
  } catch {
    return null;
  }
}

async function rawRedisGet(key: string): Promise<unknown | null> {
  const url = process.env.UPSTASH_REDIS_REST_URL;
  const token = process.env.UPSTASH_REDIS_REST_TOKEN;
  if (!url || !token) throw new Error('Redis not configured');
  const resp = await fetch(`${url}/get/${encodeURIComponent(key)}`, {
    headers: { Authorization: `Bearer ${token}` },
    signal: AbortSignal.timeout(3_000),
  });
  if (!resp.ok) throw new Error(`Redis HTTP ${resp.status}`);
  const data = (await resp.json()) as { result?: string | null };
  if (!data?.result) return null;
  try {
    return JSON.parse(data.result);
  } catch {
    return null;
  }
}

async function rawRedisSetEx(key: string, value: unknown, ttlSeconds: number): Promise<boolean> {
  const url = process.env.UPSTASH_REDIS_REST_URL;
  const token = process.env.UPSTASH_REDIS_REST_TOKEN;
  if (!url || !token) return false;
  try {
    const resp = await fetch(`${url}/pipeline`, {
      method: 'POST',
      headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' },
      body: JSON.stringify([['SET', key, JSON.stringify(value), 'EX', ttlSeconds]]),
      signal: AbortSignal.timeout(3_000),
    });
    if (!resp.ok) return false;
    const results = (await resp.json().catch(() => null)) as Array<{ result?: string }> | null;
    return Array.isArray(results) && results[0]?.result === 'OK';
  } catch {
    return false;
  }
}

// ---------------------------------------------------------------------------
// Inner handler β€” exported for unit tests with injected deps.
// ---------------------------------------------------------------------------

export interface NonceData {
  client_id: string;
  redirect_uri: string;
  code_challenge: string;
  state?: string;
  created_at?: number;
}

export interface ClientData {
  client_name?: string;
  redirect_uris?: unknown;
}

export interface GrantRedisData {
  userId: string;
  exp: number;
}

export interface AuthorizeProDeps {
  /** Atomic GETDEL on a raw `mcp-grant:*` or `oauth:nonce:*` key. */
  redisGetDel: (key: string) => Promise<unknown | null>;
  /** Non-consuming read of the `oauth:client:<id>` row. */
  redisGet: (key: string) => Promise<unknown | null>;
  /** SETEX of `oauth:code:<code>`. Returns false on failure (caller rolls back). */
  redisSetEx: (key: string, value: unknown, ttlSeconds: number) => Promise<boolean>;
  /** Verifies the wire-format HMAC grant. */
  verifyGrant: typeof verifyGrant;
  /**
   * Returns Pro entitlement info or null.
   *
   * The billing-verification fields are part of the contract, not incidental:
   * the gate below classifies them to decide retryable-vs-terminal (#5622), so
   * a stub that omits them would type-check while silently exercising only the
   * terminal branch.
   */
  getEntitlements: (userId: string) => Promise<ProMcpEntitlement | null>;
  /** Issues the Convex mcpProTokens row. Throws ProMcpIssueFailed on failure. */
  issueProMcpTokenForUser: typeof issueProMcpTokenForUser;
  /** Best-effort revoke for the rollback path. Must NOT throw (matches U2 contract). */
  revokeProMcpToken: typeof revokeProMcpToken;
  /** Random code generator β€” injectable for deterministic tests. */
  randomCode: () => string;
  /** Wall clock β€” injectable for deterministic tests. */
  now: () => number;
}

export async function authorizeProHandler(req: Request, deps: AuthorizeProDeps): Promise<Response> {
  if (req.method !== 'GET') {
    return new Response(null, {
      status: 405,
      headers: { Allow: 'GET', 'Cache-Control': 'no-store' },
    });
  }

  const url = new URL(req.url);
  const nonce = url.searchParams.get('nonce') ?? '';
  const grantToken = url.searchParams.get('grant') ?? '';

  if (!nonce || !grantToken) {
    // Edge: missing params β†’ HTML error WITHOUT touching Redis.
    return htmlError(
      'Invalid Authorization Request',
      'The authorization link is missing required parameters. Please start over from your dashboard.',
    );
  }

  // ----- 1. HMAC-verify FIRST (cheap; saves Redis round-trips on forged tokens) -----
  let verifyResult: Awaited<ReturnType<typeof verifyGrant>>;
  try {
    verifyResult = await deps.verifyGrant(grantToken, undefined, deps.now());
  } catch (err) {
    if (err instanceof GrantConfigError) {
      console.warn('[authorize-pro] missing MCP_PRO_GRANT_HMAC_SECRET');
      return htmlError(
        'Service Unavailable',
        'Pro MCP authorization is temporarily unavailable. Please try again shortly.',
        500,
      );
    }
    throw err;
  }
  if (!verifyResult.ok) {
    // Vague copy β€” do NOT distinguish malformed / bad-sig / expired / invalid-payload.
    return htmlError(
      'Authorization Expired',
      'This authorization link is no longer valid. Please start over from your dashboard.',
    );
  }
  const grantPayload = verifyResult.payload;

  // ----- 2. Grant payload's nonce MUST match the URL nonce -----
  // Defense vs grant-payload-swap: an attacker who captures a grant for one
  // nonce can't paste it onto a different nonce's URL.
  if (grantPayload.nonce !== nonce) {
    return htmlError(
      'Authorization Mismatch',
      'This authorization link is no longer valid. Please start over from your dashboard.',
    );
  }

  // ----- 3. Atomic GETDEL mcp-grant:<n> -----
  let grantRedis: GrantRedisData | null;
  try {
    grantRedis = (await deps.redisGetDel(`mcp-grant:${nonce}`)) as GrantRedisData | null;
  } catch {
    return htmlError(
      'Service Unavailable',
      'Authorization service is temporarily unavailable. Please try again shortly.',
      503,
    );
  }
  if (!grantRedis || typeof grantRedis.userId !== 'string' || typeof grantRedis.exp !== 'number') {
    // Replay (already consumed) or never minted β†’ vague.
    return htmlError(
      'Authorization Expired',
      'This authorization link is no longer valid. Please start over from your dashboard.',
    );
  }
  // Strict tuple equality with the signed payload. Even a valid HMAC can't
  // forge a record that doesn't exist in Redis under the matching userId+exp.
  if (grantRedis.userId !== grantPayload.userId || grantRedis.exp !== grantPayload.exp) {
    return htmlError(
      'Authorization Mismatch',
      'This authorization link is no longer valid. Please start over from your dashboard.',
    );
  }
  const userId = grantPayload.userId;

  // ----- 4. Atomic GETDEL oauth:nonce:<n> -----
  let nonceData: NonceData | null;
  try {
    nonceData = (await deps.redisGetDel(`oauth:nonce:${nonce}`)) as NonceData | null;
  } catch {
    return htmlError(
      'Service Unavailable',
      'Authorization service is temporarily unavailable. Please try again shortly.',
      503,
    );
  }
  if (
    !nonceData ||
    typeof nonceData.client_id !== 'string' ||
    typeof nonceData.redirect_uri !== 'string' ||
    typeof nonceData.code_challenge !== 'string'
  ) {
    return htmlError(
      'Session Expired',
      'Your authorization session has expired. Please start over from your dashboard.',
    );
  }
  const { client_id, redirect_uri, code_challenge } = nonceData;
  const state = typeof nonceData.state === 'string' ? nonceData.state : '';

  // ----- 5. Read oauth:client:<client_id> (no consume) -----
  let clientData: ClientData | null;
  try {
    clientData = (await deps.redisGet(`oauth:client:${client_id}`)) as ClientData | null;
  } catch {
    return htmlError(
      'Service Unavailable',
      'Authorization service is temporarily unavailable. Please try again shortly.',
      503,
    );
  }
  if (!clientData) {
    return htmlError(
      'Unknown Client',
      'The OAuth client registration has expired. Please re-register the client.',
    );
  }

  // ----- 6. Defense-in-depth: redirect_uri allowlist re-check -----
  const uris = Array.isArray(clientData.redirect_uris) ? clientData.redirect_uris : [];
  if (!uris.includes(redirect_uri)) {
    return htmlError(
      'Redirect URI Mismatch',
      'The redirect_uri does not match any registered redirect URI for this client.',
    );
  }

  // ----- 7. Re-fetch entitlement (grant could be up to 5min old; tier may have lapsed) -----
  // The decision is shared with api/internal/mcp-grant-{mint,context}.ts
  // (server/_shared/pro-mcp-gate.ts) so the three gates in this flow cannot
  // drift: both tier >= 1 AND mcpAccess === true are required β€” mirroring the
  // downstream MCP-edge gate, because gating on tier alone lets a tier-1 user
  // lacking mcpAccess complete OAuth and get a token row, then have every
  // tools/call fail at the gateway β€” and an entitlement that could not be
  // VERIFIED renders the retryable page rather than the terminal upsell (#5622).
  const ent = await deps.getEntitlements(userId);
  const gate = checkProMcpAccess(ent, deps.now(), {
    backendConfigured: isEntitlementBackendConfigured(),
  });
  if (gate) {
    if (gate.kind === 'billing_verification') return billingVerificationPage(gate.denial);
    return htmlError(
      'Pro Subscription Required',
      'A WorldMonitor Pro subscription is required for this connection. Please subscribe and try again.',
      403,
    );
  }

  // ----- 8. Issue the Convex mcpProTokens row -----
  const clientName = (typeof clientData.client_name === 'string' && clientData.client_name) || 'Unknown Client';
  let issueResult: { tokenId: string };
  try {
    issueResult = await deps.issueProMcpTokenForUser(userId, client_id, `Connected via ${clientName}`);
  } catch (err) {
    if (err instanceof ProMcpIssueFailed) {
      if (err.kind === 'pro-required') {
        return htmlError(
          'Pro Subscription Required',
          'A WorldMonitor Pro subscription is required for this connection. Please subscribe and try again.',
          403,
        );
      }
      if (err.kind === 'invalid-user-id') {
        return htmlError(
          'Authorization Failed',
          'Could not complete authorization. Please sign out, sign in again, and try again.',
          400,
        );
      }
      if (err.kind === 'config') {
        console.warn('[authorize-pro] Convex config missing for issue helper');
        return htmlError(
          'Service Unavailable',
          'Pro MCP authorization is temporarily unavailable. Please try again shortly.',
          500,
        );
      }
      // network / unknown
      return htmlError(
        'Service Unavailable',
        'Pro MCP authorization is temporarily unavailable. Please try again shortly.',
        503,
      );
    }
    throw err;
  }

  // ----- 9. Mint OAuth code + write oauth:code:<code> -----
  const code = deps.randomCode();
  const codeData = {
    kind: 'pro' as const,
    userId,
    mcpTokenId: issueResult.tokenId,
    client_id,
    redirect_uri,
    code_challenge,
    scope: 'mcp_pro' as const,
  };

  let codeStored = false;
  try {
    codeStored = await deps.redisSetEx(`oauth:code:${code}`, codeData, CODE_TTL_SECONDS);
  } catch {
    codeStored = false;
  }

  if (!codeStored) {
    // ----- 10. Best-effort rollback of the just-issued mcpProTokens row -----
    // U2's revokeProMcpToken does NOT throw β€” returns {ok, reason}. We log
    // outcome but do NOT mask the original storage failure: even if revoke
    // fails, the user sees "Server Error" + the orphaned row will get cleaned
    // up by the per-user 5-row cap rotation in U1 over time.
    try {
      const rollback = await deps.revokeProMcpToken(userId, issueResult.tokenId);
      if (!rollback.ok) {
        console.warn(
          `[authorize-pro] orphaned mcpProTokens row ${issueResult.tokenId} for user ${userId}: revoke failed (${rollback.reason})`,
        );
      }
    } catch (err) {
      // Defensive: U2's contract says no-throw, but if a future change breaks
      // that we still complete the error response.
      console.warn(
        `[authorize-pro] revoke rollback unexpectedly threw for token ${issueResult.tokenId}:`,
        err instanceof Error ? err.message : String(err),
      );
      captureSilentError(err, {
        tags: { route: 'api/oauth/authorize-pro', step: 'rollback-revoke' },
      });
    }
    return htmlError(
      'Server Error',
      'Failed to store authorization code. Please try again.',
      500,
    );
  }

  // ----- 11. 302 redirect -----
  const redirectUrl = new URL(redirect_uri);
  redirectUrl.searchParams.set('code', code);
  if (state) redirectUrl.searchParams.set('state', state);

  return new Response(null, {
    status: 302,
    headers: {
      Location: redirectUrl.toString(),
      'Cache-Control': 'no-store',
      Pragma: 'no-cache',
    },
  });
}

// ---------------------------------------------------------------------------
// Production handler β€” wires up the real deps.
// ---------------------------------------------------------------------------

export default async function handler(req: Request): Promise<Response> {
  return authorizeProHandler(req, {
    redisGetDel: rawRedisGetDel,
    redisGet: rawRedisGet,
    redisSetEx: rawRedisSetEx,
    verifyGrant,
    getEntitlements,
    issueProMcpTokenForUser,
    revokeProMcpToken,
    randomCode: () => crypto.randomUUID(),
    now: () => Date.now(),
  });
}