Files
worldmonitor/todos/086-complete-p3-bearer-resolution-deferred-check-and-discriminated-return.md
Elie Habib 14a31c4283 feat(mcp): OAuth 2.0 Authorization Server for claude.ai connector (#2418)
* feat(mcp): add OAuth 2.0 Authorization Server for claude.ai connector

Implements spec-compliant MCP authentication so claude.ai's remote connector
(which requires OAuth Client ID + Secret, no custom headers) can authenticate.

- public/.well-known/oauth-authorization-server: RFC 8414 discovery document
- api/oauth/token.js: client_credentials grant, issues UUID Bearer token in Redis TTL 3600s
- api/_oauth-token.js: resolveApiKeyFromBearer() looks up token in Redis
- api/mcp.ts: 3-tier auth (Bearer OAuth first, then ?key=, then X-WorldMonitor-Key);
  switch to getPublicCorsHeaders; surface error messages in catch
- vercel.json: rewrite /oauth/token, exclude oauth from SPA, CORS headers
- tests: update SPA no-cache pattern

Supersedes PR #2417. Usage: URL=worldmonitor.app/mcp, Client ID=worldmonitor, Client Secret=<API key>

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* docs: fix markdown lint in OAuth plan (blank lines around lists)

* fix(oauth): address all P1+P2 code review findings for MCP OAuth endpoint

- Add per-IP rate limiting (10 req/min) to /oauth/token via Upstash slidingWindow
- Return HTTP 401 + WWW-Authenticate header when Bearer token is invalid/expired
- Add Cache-Control: no-store + Pragma: no-cache to token response (RFC 6749 §5.1)
- Simplify _oauth-token.js to delegate to readJsonFromUpstash (removes duplicated Redis boilerplate)
- Remove dead code from token.js: parseBasicAuth, JSON body path, clientId/issuedAt fields
- Add Content-Type: application/json header for /.well-known/oauth-authorization-server
- Remove response_types_supported (only applies to authorization endpoint, not client_credentials)

Closes: todos 075, 076, 077, 078, 079

🤖 Generated with claude-sonnet-4-6 via Claude Code (https://claude.ai/claude-code) + Compound Engineering v2.40.0

Co-Authored-By: claude-sonnet-4-6 (200K context) <noreply@anthropic.com>

* chore(review): fresh review findings — todos 081-086, mark 075/077/078/079 complete

* fix(mcp): remove ?key= URL param auth + mask internal errors

- Remove ?key= query param auth path — API keys in URLs appear in
  Vercel/CF access logs, browser history, Referer headers. OAuth
  client_credentials (same PR) already covers clients that cannot
  set custom headers. Only two auth paths remain: Bearer OAuth and
  X-WorldMonitor-Key header.

- Revert err.message disclosure: catch block was accidentally exposing
  internal service URLs/IPs via err.message. Restore original hardcoded
  string, add console.error for server-side visibility.

Resolves: todos 081, 082

* fix(oauth): resolve all P2/P3 review findings (todos 076, 080, 083-086)

- 076: no-credentials path in mcp.ts now returns HTTP 401 + WWW-Authenticate instead of rpcError (200)
- 080: store key fingerprint (sha256 first 16 hex chars) in Redis, not plaintext key
- 083: replace Array.includes() with timingSafeIncludes() (constant-time HMAC comparison) in token.js and mcp.ts
- 084: resolveApiKeyFromBearer uses direct fetch that throws on Redis errors (500 not 401 on infra failure)
- 085: token.js imports getClientIp, getPublicCorsHeaders, jsonResponse from shared helpers; removes local duplicates
- 086: mcp.ts auth chain restructured to check Bearer header first, passes token string to resolveApiKeyFromBearer (eliminates double header read + unconditional await)

* test(mcp): update auth test to expect HTTP 401 for missing credentials

Align with todo 076 fix: no-credentials path now returns 401 + WWW-Authenticate
instead of JSON-RPC 200 response. Also asserts WWW-Authenticate header presence.

* chore: mark todos 076, 080, 083-086 complete

* fix(mcp): harden OAuth error paths and fix rate limit cross-user collision

- Wrap resolveApiKeyFromBearer() in try/catch in mcp.ts; Redis/network
  errors now return 503 + Retry-After: 5 instead of crashing the handler
- Wrap storeToken() fetch in try/catch in oauth/token.js; network errors
  return false so the existing if (!stored) path returns 500 cleanly
- Re-key token endpoint rate limit by sha256(clientSecret).slice(0,8)
  instead of IP; prevents cross-user 429s when callers share Anthropic's
  shared outbound IPs (Claude remote MCP connector)

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-28 14:53:32 +04:00

4.0 KiB

status, priority, issue_id, tags, dependencies
status priority issue_id tags dependencies
complete p3 086
code-review
quality
oauth
mcp
084

Defer Bearer resolution in mcp.ts + discriminated return type for resolveApiKeyFromBearer

Problem Statement

Two related simplification opportunities in api/mcp.ts auth chain:

  1. resolveApiKeyFromBearer(req) is called unconditionally before the Bearer header is checked, creating an invisible await for non-Bearer requests (though no I/O fires due to the short-circuit in _oauth-token.js). Future maintainers may not know there's zero cost for non-Bearer callers.

  2. resolveApiKeyFromBearer returns string | null where null means EITHER "no Bearer header" OR "Bearer present but token not found." mcp.ts handles the "Bearer present" case by re-reading req.headers.get('Authorization') — the header is parsed twice.

Findings

  • api/mcp.ts:431-435bearerHeader is read to gate the 401 path, but resolveApiKeyFromBearer also reads Authorization internally
  • Performance oracle: "The await on a synchronously-resolved null return is a microtask tick, not a real I/O pause — but the pattern prevents future readers from understanding the cost model."
  • Simplicity reviewer: "The correct fix is a discriminated return type that makes the call contract explicit and testable."
  • Double header read: req.headers.get('Authorization') called at line 431 and again at line 5 of _oauth-token.js

Proposed Solutions

Option 1: Deferred conditional resolution

let apiKey = '';
const authHeader = req.headers.get('Authorization') ?? '';
if (authHeader.startsWith('Bearer ')) {
  const bearerApiKey = await resolveApiKeyFromBearer(req);
  if (bearerApiKey) {
    apiKey = bearerApiKey;
  } else {
    return new Response(...401...);
  }
} else {
  // Direct key path — zero Upstash I/O
  const candidateKey = req.headers.get('X-WorldMonitor-Key') ?? '';
  ...
}

Eliminates unconditional await and the double header read. resolveApiKeyFromBearer can accept the pre-read token string instead of req.

Pros: Self-documenting cost model. Single header read. Cons: Slightly longer code but clearer. Effort: Small


Option 2: Discriminated return from resolveApiKeyFromBearer

type BearerResult = { found: true; apiKey: string } | { found: false; hadBearer: boolean };

export async function resolveApiKeyFromBearer(req): Promise<BearerResult> {
  const hdr = req.headers.get('Authorization') || '';
  if (!hdr.startsWith('Bearer ')) return { found: false, hadBearer: false };
  const token = hdr.slice(7).trim();
  if (!token) return { found: false, hadBearer: true };
  const apiKey = await readJsonFromUpstash(`oauth:token:${token}`);
  if (typeof apiKey === 'string' && apiKey) return { found: true, apiKey };
  return { found: false, hadBearer: true };
}

mcp.ts then needs no second header read and no bearerHeader variable.

Pros: Explicit contract, eliminates double-read, testable. Cons: Changes _oauth-token.js signature (only called from one place today). Effort: Small-Medium

Option 1 is the quickest win. Option 2 is cleaner if todo #084 is also implemented (since the discriminated return would add the error case there too).

Technical Details

Affected files:

  • api/mcp.ts:430-445 — restructure auth chain
  • api/_oauth-token.js — optionally change signature per Option 2

Acceptance Criteria

  • Authorization header is not read twice for the same request
  • Unconditional await resolveApiKeyFromBearer is replaced with conditional logic
  • All existing auth paths still work
  • No test regressions

Work Log

2026-03-28 — Code Review Discovery

By: Claude Code (compound-engineering:ce-review)

Actions:

  • Performance oracle and simplicity reviewer both flagged
  • Confirmed: double header read at mcp.ts:431 and _oauth-token.js:5
  • No runtime performance issue (short-circuit returns synchronously) but code clarity suffers