# MCP OAuth2 — tiledesk-server Implementation Plan

> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.

**Goal:** tiledesk-server acts as OAuth2 client for MCP servers (MCP-spec discovery + DCR, Google preset, manual), stores tokens encrypted, refreshes them lazily, serves a valid access token to the chatbot, and exposes a token-protected refresh API for the scheduler.

**Architecture:** Pure helpers (`mcpOAuthCrypto.js`, `mcpOAuthPkce.js`, `outboundUrlGuard.js`) → `mcpOAuthDiscovery.js` (RFC 9728 / 8414 / 7591) → `mcpOAuthService.js` (authorize, callback, refresh with Redis lock, revoke) over the `mcp_oauth_connections` model → admin/bot routes in `routes/mcpOAuth.js`, public callback in `routes/mcpOAuthCallback.js`, scheduler API in `routes/webhook.js` → `mcpService` injects the bearer.

**Tech Stack:** Node 18/Express, Mongoose, axios, Node `crypto` / `dns`, TdCache (Redis), mocha + chai-http + nock (test MongoDB + Redis).

**Spec:** `docs/superpowers/specs/2026-11-10-mcp-oauth2-design.md`

## Global Constraints

- Branch `features-2611/oauth2-mcp` (checked out). One commit per task. Never push.
- No new npm dependency (axios + Node built-ins only).
- Feature gate: every OAuth route answers 503 `"MCP OAuth is not available on this installation"` when `MCP_OAUTH_ENCRYPTION_KEY` is unset or not 32 bytes after base64 decoding. `mode: 'google'` additionally needs `MCP_OAUTH_GOOGLE_CLIENT_ID` and `_SECRET`; the scheduler API needs `MCP_OAUTH_REFRESH_TOKEN`. No default secrets.
- Tokens and client secrets are never in the `mcp` integration, never in a response except `access_token` on the bot-only token endpoint, never in logs.
- Redirect URI = `(MCP_OAUTH_REDIRECT_BASE_URL || API_URL)` without trailing slash + `/oauth2/mcp/callback`.
- Redis keys: `mcp_oauth:state:<state>` (TTL 600 s), `mcp_oauth:refresh_lock:<connection_id>` (TTL 30 s). `REFRESH_WINDOW_S = 300`.
- Outbound HTTP to user-influenced URLs goes through `outboundUrlGuard` (https, no private/loopback after DNS resolution, `maxRedirects: 0`, timeout 10000, `maxContentLength` 1 MB) unless `MCP_OAUTH_ALLOW_INSECURE_URLS=true`. Google endpoints are constants and skip the guard.
- Token endpoint requests are `application/x-www-form-urlencoded`; client auth `client_secret_basic` → `Authorization: Basic base64(urlencode(id):urlencode(secret))`, `client_secret_post` → `client_id` + `client_secret` in the body, `none` → `client_id` only.
- Errors returned by the service carry `.status` and `.code` (`needs_reauth`, `not_configured`, `bad_request`, `not_found`, `provider_error`); routes map them with `res.status(err.status || 500).send({ success: false, error: err.message, code: err.code })`.
- Tests: `NODE_ENV=test ./node_modules/.bin/mocha <files> --timeout 60000 --exit` with test MongoDB/Redis up (docker `tiledesk-test-mongo`, `tiledesk-test-redis`). nock every provider and MCP call; tests set `MCP_OAUTH_ALLOW_INSECURE_URLS=true` only where they target `http://` hosts, and one test keeps it unset to exercise the guard. `nock.isDone()` asserted per test.

## Review Focus

1. A connection of project A can never be read, refreshed, used or deleted from project B (token endpoint, management API, `oauth.connection_id` in `POST /mcp/servers`).
2. An admin JWT on `GET …/connections/:id/token` → 403; a bot JWT of the same project → 200.
3. Two concurrent token requests on an expiring token → exactly one call to the provider token endpoint, both callers get the new token.
4. A refresh response without `refresh_token` keeps the old one; with one, it replaces it (rotation).
5. State reuse: calling the callback twice with the same `state` → second call 400, no second code exchange.
6. `invalid_grant` on refresh → `needs_reauth`, token endpoint then answers 409 without calling the provider again.

---

### Task 1: crypto, PKCE, URL guard, model

**Files:**
- Create: `utils/mcpOAuthCrypto.js`, `utils/mcpOAuthPkce.js`, `utils/outboundUrlGuard.js`, `models/mcpOAuthConnection.js`
- Modify: `utils/logRedactor.js` (`SENSITIVE_KEY_RE` and the JSON-string replace gain `access_token|refresh_token|code_verifier|client_secret`; key `code` only in the key regex)
- Test: `test/mcpOAuthUtils.test.js`

**Interfaces:**
- `mcpOAuthCrypto`: `isConfigured() → boolean`, `encrypt(plain) → 'v1:…'`, `decrypt(enc) → string` (throws on tamper / wrong key), `null`/`undefined` pass through.
- `mcpOAuthPkce`: `randomState() → base64url(32 bytes)`, `createVerifier() → 64-char base64url`, `challengeOf(verifier) → base64url(sha256)`.
- `outboundUrlGuard`: `assertAllowed(url) → Promise<URL>` (throws `.status = 400`, message `"URL not allowed: <reason>"`), `httpOptions() → { maxRedirects: 0, timeout: 10000, maxContentLength: 1048576 }`.
- Model fields exactly as spec §4, `timestamps: true`, unique index `{ id_project: 1, server_url: 1 }`, `toPublic(doc)` static returning the spec §9 shape.

- [ ] **Step 1: Failing tests.** Encrypt/decrypt round-trip; flipping one ciphertext byte throws; key unset → `isConfigured()` false; challenge of RFC 7636 appendix B verifier `dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk` = `E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM`; guard rejects `http://x`, `https://127.0.0.1`, `https://10.0.0.1`, `https://169.254.169.254`, `https://[::1]`, `https://[fd00::1]`, a hostname that resolves to `192.168.1.1` (stub `dns.promises.lookup`), accepts a public address; guard with `MCP_OAUTH_ALLOW_INSECURE_URLS=true` accepts `http://localhost:3232`; `redactValue({ access_token: 'x', refresh_token: 'y', code_verifier: 'z' })` all `[REDACTED]`; `toPublic` has no `*_enc`.
- [ ] **Step 2: Run** `… test/mcpOAuthUtils.test.js` → fail.
- [ ] **Step 3: Implement.** AES-256-GCM, 12-byte IV. Guard: `dns.promises.lookup(host, { all: true })`, reject if **any** address is in 0.0.0.0/8, 10/8, 100.64/10, 127/8, 169.254/16, 172.16/12, 192.168/16, ::, ::1, fc00::/7, fe80::/10, IPv4-mapped forms of those.
- [ ] **Step 4: Run** the file plus `test/logRedactor*.js` if present → pass.
- [ ] **Step 5: Commit** — `feat(mcp-oauth): encryption, PKCE, outbound URL guard and connection model`.

### Task 2: discovery and dynamic client registration

**Files:**
- Create: `services/mcpOAuthDiscovery.js`
- Test: `test/mcpOAuthDiscovery.test.js`

**Interfaces:**
- `discover(serverUrl) → { resource, issuer, authorization_endpoint, token_endpoint, revocation_endpoint?, registration_endpoint?, scopes_supported?, token_endpoint_auth_methods_supported? }` per spec §6.1. Errors 400 `"This MCP server does not require OAuth"`, 400 `"OAuth metadata not found for <url>"`, 400 `"Authorization server does not support PKCE S256"`, 502 on network failure.
- `register(metadata, redirectUri) → { client_id, client_secret?, token_endpoint_auth_method }` per spec §6.2; 400 when `registration_endpoint` is missing.
- Pure `wellKnownUrls(baseUrl, suffix) → string[]` (path-inserted first, then root).

- [ ] **Step 1: Failing tests (nock).** 401 with `WWW-Authenticate: Bearer resource_metadata="https://mcp.example.com/.well-known/oauth-protected-resource/mcp"` → that URL is fetched; without the header → path-inserted then root well-known tried in order; issuer `https://auth.example.com/tenant1` → `https://auth.example.com/.well-known/oauth-authorization-server/tenant1` first, then `/.well-known/openid-configuration` fallback; 200 on unauthenticated initialize → "does not require OAuth"; `code_challenge_methods_supported: ['plain']` → PKCE error; DCR body asserted (redirect URI, grant types, `client_name: 'Tiledesk'`); a metadata URL pointing to `https://10.0.0.5/…` rejected by the guard (insecure flag unset).
- [ ] **Step 2: Run** → fail.
- [ ] **Step 3: Implement** with axios + `outboundUrlGuard` before every request. The initialize body is the same JSON-RPC `initialize` as `mcpService.sendInitializeRequest` (protocol `2025-03-26`), headers `Accept: application/json, text/event-stream`. Parse `WWW-Authenticate` with a small regex for `resource_metadata="…"`.
- [ ] **Step 4: Run** → pass.
- [ ] **Step 5: Commit** — `feat(mcp-oauth): MCP authorization discovery and dynamic client registration`.

### Task 3: OAuth service — authorize, callback, refresh, revoke

**Files:**
- Create: `services/mcpOAuthService.js`
- Modify: `app.js` (`mcpOAuthService.setTdCache(tdCache)` next to `mcpService.setTdCache`)
- Test: `test/mcpOAuthService.test.js`

**Interfaces:**
- Consumes Task 1 and Task 2.
- `startAuthorization(id_project, user_id, body) → { authorization_url, connection_id }` (spec §6 step 1; validates `mode`, `server_url`, `return_url` origin vs `MCP_OAUTH_RETURN_ORIGINS`, manual fields).
- `completeAuthorization({ code, state, error }) → { connection, return_url }` (spec §6 step 2; state read + `del` before the exchange).
- `getAccessToken(id_project, connection_id, { force } = {}) → { access_token, token_type, expires_at }` (spec §7, lock + poll).
- `refreshDue(withinSeconds) → { refreshed, failed, needs_reauth }`.
- `revokeAndDelete(id_project, connection_id) → { revoked }` (does not touch the integration; Task 4 does).
- `getConnection(id_project, connection_id)` → doc or 404; `listConnections(id_project)`.

- [ ] **Step 1: Failing tests (nock + Redis).**
  - mcp mode end-to-end: authorize → discovery + DCR called, URL has `code_challenge_method=S256`, `resource`, `state`; Redis state exists; callback → token exchange body has `code_verifier` matching the challenge, `redirect_uri`, `resource`; connection `active`, tokens decrypt to the mocked values; state key gone.
  - Second authorize on the same server reuses the stored DCR client (no second `/register`).
  - google mode: authorize URL host `accounts.google.com`, has `access_type=offline`, `prompt=consent`; env unset → 503.
  - manual mode: client secret stored encrypted; `client_secret_basic` sends the Basic header.
  - `return_url` with origin not allowed → 400.
  - Callback with unknown state → 400; with `error=access_denied` → `last_error.code = 'access_denied'`, returns `return_url`; same state twice → second 400 (Review Focus 5).
  - `getAccessToken`: fresh token → no provider call; expiring → refresh, `last_refresh_at` set; response without `refresh_token` keeps the old, with one replaces it (Review Focus 4); `invalid_grant` → `needs_reauth` 409, next call 409 with no nock interceptor consumed (Review Focus 6); `invalid_client` in mcp mode → `client_id` cleared; 500 from provider → 503, status still `active`; two parallel calls → one interceptor, both resolve with the new token (Review Focus 3); connection of another project → 404 (Review Focus 1).
  - `refreshDue(900)`: refreshes only active connections with a refresh token expiring within 900 s; one failure does not stop the others.
  - `revokeAndDelete`: revocation called with the refresh token; revocation 500 → still deleted, `revoked: false`.
- [ ] **Step 2: Run** → fail.
- [ ] **Step 3: Implement.** Lock via `tdCache.setNX`; release with `tdCache.del` in `finally`. Poll compares `last_refresh_at` with the value read before trying the lock. Without `tdCache` (tests that don't wire it) fall back to an in-process `Map` of pending promises keyed by connection id, so the single-instance behaviour is the same.
- [ ] **Step 4: Run** → pass.
- [ ] **Step 5: Commit** — `feat(mcp-oauth): authorization code + PKCE flow, lazy refresh with lock, revocation`.

### Task 4: routes — admin, bot token, callback, scheduler refresh

**Files:**
- Create: `routes/mcpOAuth.js` (mounted inside `routes/mcp.js` as `router.use('/oauth', mcpOAuth)`), `routes/mcpOAuthCallback.js`
- Modify: `app.js` (`app.use('/oauth2/mcp', mcpOAuthCallback)` before the first `/:projectid` router), `routes/webhook.js` (`POST /mcp-oauth/refresh`)
- Test: `test/mcpOAuthRoute.test.js`

**Interfaces:**
- `POST /:projectid/mcp/oauth/authorize` (admin) → Task 3 `startAuthorization` with `req.user._id`.
- `GET /:projectid/mcp/oauth/connections`, `GET …/:id` (admin) → public shape.
- `POST …/:id/refresh` (admin) → `getAccessToken(..., { force: true })`, responds with the public connection (no token).
- `DELETE …/:id` (admin) → `revokeAndDelete`, then remove `oauth` from every `mcp` integration server with that `connection_id`, save, `integrationEvent.emit('integration.update', …)`.
- `GET …/:id/token` (bot/subscription only: `roleChecker.isTypesAsFunction(['bot','subscription'], req.user, req.projectid)` else 403) → `{ access_token, token_type, expires_at }`.
- Admin-only sub-routes add `roleChecker.hasRole('admin')` (the `/mcp` mount also admits bot/subscription).
- `GET /oauth2/mcp/callback` → 302 to `return_url` with `mcp_oauth=success&connection_id=` or `mcp_oauth=error&error=`; without `return_url` a small HTML page; 400 HTML page on bad state.
- `POST /webhook/mcp-oauth/refresh` → `x-auth-token` timing-safe check (copy `/scheduled-start`), body `{ connection_id }` or `{ within_seconds }` (integer 60..86400, default 900).

- [ ] **Step 1: Failing tests (chai-http + nock).** Admin flow authorize → callback (302 Location asserted) → list shows `active` and no secret field; admin JWT on `/token` → 403, bot JWT → 200 (Review Focus 2); bot of project B on project A's connection → 404 (Review Focus 1); agent role on `/authorize` → 403; DELETE removes `oauth` from the integration entry and the entry stays; feature env unset → 503 on every route; webhook refresh: no token → 401, wrong token → 401, `MCP_OAUTH_REFRESH_TOKEN` unset → 503, `{ within_seconds: 900 }` → counts.
- [ ] **Step 2: Run** → fail.
- [ ] **Step 3: Implement.** Check how existing tests create a bot JWT (e.g. `test/nativemcp.test.js`, faq_kb tests) and reuse that helper.
- [ ] **Step 4: Run** the file plus `test/nativemcp.test.js` → pass.
- [ ] **Step 5: Commit** — `feat(mcp-oauth): admin, bot token, callback and scheduler refresh routes`.

### Task 5: mcpService uses OAuth connections

**Files:**
- Modify: `services/mcpService.js`, `routes/mcp.js` (doc comments only: `oauth: { connection_id }`)
- Test: `test/mcpServiceOAuth.test.js`

**Interfaces:**
- `buildServerConfig(projectId, body)`: `oauth.connection_id` → `serverConfig.oauth = { connection_id }`; the legacy shape (`clientId`/`clientSecret`/`redirectUrl`/`scope` without `connection_id`) keeps today's error.
- `resolveRequestHeaders(headers, serverConfig) → Promise<Boolean>`: existing `applyRequestHeaders`, then the OAuth bearer (overrides `Authorization`).
- `sendJSONRPCRequest` / `sendInitializedNotification` call `resolveRequestHeaders`; on HTTP 401 with `serverConfig.oauth` → `getAccessToken(..., { force: true })` and one retry.
- `normalizeMcpServerEntry`: custom and native entries accept `oauth.connection_id`; the connection must exist in `projectId` (404 otherwise); stored as `oauth: { connection_id, mode }`; tools discovery uses it. `resolveNativeServerConfig` passes `oauth` through when given.
- `getCacheKey(url, projectId, connectionId?)`.

- [ ] **Step 1: Failing tests (nock MCP server).** `POST /:projectid/mcp/connect` with `oauth.connection_id` → MCP requests carry `Authorization: Bearer <token>`; customHeaders `Authorization` is overridden; MCP 401 once → refresh + retry succeeds; 401 twice → error, no loop; `POST /mcp/servers` with a connection of another project → 404 (Review Focus 1); saved entry has `oauth: { connection_id, mode }` and no token anywhere in `integration.value` (`JSON.stringify` check); legacy `oauth: { clientId }` still 400 with the old message.
- [ ] **Step 2: Run** → fail.
- [ ] **Step 3: Implement.**
- [ ] **Step 4: Run** the file plus `test/nativemcp.test.js test/mcpOAuthRoute.test.js` → pass.
- [ ] **Step 5: Commit** — `feat(mcp-oauth): bearer injection and 401 retry in mcpService`.

### Task 6: docs and manual end-to-end

**Files:**
- Modify: `CHANGELOG.md` (unreleased entry), `docs/superpowers/specs/2026-11-10-mcp-oauth2-design.md` (status, any decision taken during implementation)

- [ ] **Step 1:** Run the reference server: `git clone https://github.com/modelcontextprotocol/example-remote-server && npm i && npm run dev:internal` (port 3232).
- [ ] **Step 2:** Server with `MCP_OAUTH_ENCRYPTION_KEY=$(openssl rand -base64 32)`, `MCP_OAUTH_ALLOW_INSECURE_URLS=true`, `MCP_OAUTH_RETURN_ORIGINS=http://localhost:4200`, `MCP_OAUTH_REFRESH_TOKEN=<random>`. `POST /:projectid/mcp/oauth/authorize { mode: 'mcp', server_url: 'http://localhost:3232/mcp' }` → open the URL, consent → callback → `active`.
- [ ] **Step 3:** `POST /:projectid/mcp/connect { url, oauth: { connection_id } }` → tools listed. Bot JWT on `/token` → token. Set `expires_at` in the past in Mongo → next `/token` refreshes. `POST /webhook/mcp-oauth/refresh` → counts.
- [ ] **Step 4:** Record results (what ran, what was mocked) in the spec's status line.
- [ ] **Step 5: Commit** — `docs(mcp-oauth): changelog and verification notes`.
