# MCP OAuth2 — Piano di implementazione tiledesk-server

> **Per gli agenti:** SUB-SKILL RICHIESTA: usare superpowers:subagent-driven-development (consigliata) o superpowers:executing-plans per implementare questo piano task per task. Gli step usano la sintassi checkbox (`- [ ]`) per il tracciamento.

**Obiettivo:** tiledesk-server fa da client OAuth2 per i server MCP (discovery + DCR secondo la specifica MCP, preset Google, manuale), salva i token cifrati, li rinfresca in modo lazy, fornisce un access token valido al chatbot ed espone un'API di refresh protetta da token per lo scheduler.

**Architettura:** Helper puri (`mcpOAuthCrypto.js`, `mcpOAuthPkce.js`, `outboundUrlGuard.js`) → `mcpOAuthDiscovery.js` (RFC 9728 / 8414 / 7591) → `mcpOAuthService.js` (authorize, callback, refresh con lock Redis, revoca) sopra il modello `mcp_oauth_connections` → rotte admin/bot in `routes/mcpOAuth.js`, callback pubblica in `routes/mcpOAuthCallback.js`, API per lo scheduler in `routes/webhook.js` → `mcpService` inietta il bearer.

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

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

## Vincoli globali

- Branch `features-2611/oauth2-mcp` (già in checkout). Un commit per task. Mai fare push.
- Nessuna nuova dipendenza npm (solo axios + moduli built-in di Node).
- Gate della feature: ogni rotta OAuth risponde 503 `"MCP OAuth is not available on this installation"` quando `MCP_OAUTH_ENCRYPTION_KEY` non è impostata o non è di 32 byte dopo la decodifica base64. `mode: 'google'` richiede in più `MCP_OAUTH_GOOGLE_CLIENT_ID` e `_SECRET`; l'API dello scheduler richiede `MCP_OAUTH_REFRESH_TOKEN`. Nessun segreto di default.
- Token e client secret non stanno mai nell'integration `mcp`, non compaiono mai in una risposta (tranne `access_token` sull'endpoint del token riservato ai bot), mai nei log.
- Redirect URI = `(MCP_OAUTH_REDIRECT_BASE_URL || API_URL)` senza slash finale + `/oauth2/mcp/callback`.
- Chiavi Redis: `mcp_oauth:state:<state>` (TTL 600 s), `mcp_oauth:refresh_lock:<connection_id>` (TTL 30 s). `REFRESH_WINDOW_S = 300`.
- Le chiamate HTTP verso URL influenzati dall'utente passano da `outboundUrlGuard` (https, nessun indirizzo privato/loopback dopo la risoluzione DNS, `maxRedirects: 0`, timeout 10000, `maxContentLength` 1 MB) salvo `MCP_OAUTH_ALLOW_INSECURE_URLS=true`. Gli endpoint Google sono costanti e saltano il guard.
- Le richieste al token endpoint sono `application/x-www-form-urlencoded`; autenticazione del client `client_secret_basic` → `Authorization: Basic base64(urlencode(id):urlencode(secret))`, `client_secret_post` → `client_id` + `client_secret` nel body, `none` → solo `client_id`.
- Gli errori restituiti dal service hanno `.status` e `.code` (`needs_reauth`, `not_configured`, `bad_request`, `not_found`, `provider_error`); le rotte li mappano con `res.status(err.status || 500).send({ success: false, error: err.message, code: err.code })`.
- Test: `NODE_ENV=test ./node_modules/.bin/mocha <file> --timeout 60000 --exit` con MongoDB/Redis di test attivi (docker `tiledesk-test-mongo`, `tiledesk-test-redis`). nock su ogni chiamata a provider e MCP; i test impostano `MCP_OAUTH_ALLOW_INSECURE_URLS=true` solo quando puntano a host `http://`, e un test lo lascia non impostato per esercitare il guard. `nock.isDone()` verificato in ogni test.

## Punti di attenzione per la review

1. Una connessione del progetto A non può mai essere letta, rinfrescata, usata o cancellata dal progetto B (endpoint del token, API di gestione, `oauth.connection_id` in `POST /mcp/servers`).
2. Un JWT admin su `GET …/connections/:id/token` → 403; un JWT bot dello stesso progetto → 200.
3. Due richieste concorrenti del token su un token in scadenza → esattamente una chiamata al token endpoint del provider, entrambi i chiamanti ricevono il nuovo token.
4. Una risposta di refresh senza `refresh_token` mantiene quello vecchio; con uno nuovo, lo sostituisce (rotazione).
5. Riuso dello state: chiamare la callback due volte con lo stesso `state` → seconda chiamata 400, nessun secondo scambio del code.
6. `invalid_grant` sul refresh → `needs_reauth`, poi l'endpoint del token risponde 409 senza chiamare di nuovo il provider.

---

### Task 1: cifratura, PKCE, URL guard, modello

**File:**
- Creare: `utils/mcpOAuthCrypto.js`, `utils/mcpOAuthPkce.js`, `utils/outboundUrlGuard.js`, `models/mcpOAuthConnection.js`
- Modificare: `utils/logRedactor.js` (`SENSITIVE_KEY_RE` e il replace sulle stringhe JSON aggiungono `access_token|refresh_token|code_verifier|client_secret`; la chiave `code` solo nella regex delle chiavi)
- Test: `test/mcpOAuthUtils.test.js`

**Interfacce:**
- `mcpOAuthCrypto`: `isConfigured() → boolean`, `encrypt(plain) → 'v1:…'`, `decrypt(enc) → string` (lancia in caso di manomissione / chiave errata), `null`/`undefined` passano invariati.
- `mcpOAuthPkce`: `randomState() → base64url(32 byte)`, `createVerifier() → base64url di 64 caratteri`, `challengeOf(verifier) → base64url(sha256)`.
- `outboundUrlGuard`: `assertAllowed(url) → Promise<URL>` (lancia con `.status = 400`, messaggio `"URL not allowed: <reason>"`), `httpOptions() → { maxRedirects: 0, timeout: 10000, maxContentLength: 1048576 }`.
- Campi del modello esattamente come spec §4, `timestamps: true`, indice univoco `{ id_project: 1, server_url: 1 }`, static `toPublic(doc)` che restituisce la forma di spec §9.

- [ ] **Step 1: Test che falliscono.** Round-trip encrypt/decrypt; modificare un byte del ciphertext fa lanciare un errore; chiave non impostata → `isConfigured()` false; challenge del verifier dell'appendice B di RFC 7636 `dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk` = `E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM`; il guard rifiuta `http://x`, `https://127.0.0.1`, `https://10.0.0.1`, `https://169.254.169.254`, `https://[::1]`, `https://[fd00::1]`, un hostname che risolve in `192.168.1.1` (stub di `dns.promises.lookup`), accetta un indirizzo pubblico; il guard con `MCP_OAUTH_ALLOW_INSECURE_URLS=true` accetta `http://localhost:3232`; `redactValue({ access_token: 'x', refresh_token: 'y', code_verifier: 'z' })` tutti `[REDACTED]`; `toPublic` non ha campi `*_enc`.
- [ ] **Step 2: Eseguire** `… test/mcpOAuthUtils.test.js` → fallisce.
- [ ] **Step 3: Implementare.** AES-256-GCM, IV di 12 byte. Guard: `dns.promises.lookup(host, { all: true })`, rifiutare se **un qualsiasi** indirizzo è 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, o nelle forme IPv4-mapped di questi.
- [ ] **Step 4: Eseguire** il file più `test/logRedactor*.js` se presente → passa.
- [ ] **Step 5: Commit** — `feat(mcp-oauth): encryption, PKCE, outbound URL guard and connection model`.

### Task 2: discovery e dynamic client registration

**File:**
- Creare: `services/mcpOAuthDiscovery.js`
- Test: `test/mcpOAuthDiscovery.test.js`

**Interfacce:**
- `discover(serverUrl) → { resource, issuer, authorization_endpoint, token_endpoint, revocation_endpoint?, registration_endpoint?, scopes_supported?, token_endpoint_auth_methods_supported? }` secondo spec §6.1. Errori 400 `"This MCP server does not require OAuth"`, 400 `"OAuth metadata not found for <url>"`, 400 `"Authorization server does not support PKCE S256"`, 502 su errore di rete.
- `register(metadata, redirectUri) → { client_id, client_secret?, token_endpoint_auth_method }` secondo spec §6.2; 400 se manca `registration_endpoint`.
- Funzione pura `wellKnownUrls(baseUrl, suffix) → string[]` (prima con path inserito, poi root).

- [ ] **Step 1: Test che falliscono (nock).** 401 con `WWW-Authenticate: Bearer resource_metadata="https://mcp.example.com/.well-known/oauth-protected-resource/mcp"` → viene letto quell'URL; senza l'header → provati in ordine il well-known con path inserito e quello root; issuer `https://auth.example.com/tenant1` → prima `https://auth.example.com/.well-known/oauth-authorization-server/tenant1`, poi fallback su `/.well-known/openid-configuration`; 200 sull'initialize non autenticato → "does not require OAuth"; `code_challenge_methods_supported: ['plain']` → errore PKCE; body della DCR verificato (redirect URI, grant type, `client_name: 'Tiledesk'`); un URL di metadati che punta a `https://10.0.0.5/…` rifiutato dal guard (flag insecure non impostato).
- [ ] **Step 2: Eseguire** → fallisce.
- [ ] **Step 3: Implementare** con axios + `outboundUrlGuard` prima di ogni richiesta. Il body dell'initialize è lo stesso `initialize` JSON-RPC di `mcpService.sendInitializeRequest` (protocollo `2025-03-26`), header `Accept: application/json, text/event-stream`. Fare il parsing di `WWW-Authenticate` con una piccola regex per `resource_metadata="…"`.
- [ ] **Step 4: Eseguire** → passa.
- [ ] **Step 5: Commit** — `feat(mcp-oauth): MCP authorization discovery and dynamic client registration`.

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

**File:**
- Creare: `services/mcpOAuthService.js`
- Modificare: `app.js` (`mcpOAuthService.setTdCache(tdCache)` accanto a `mcpService.setTdCache`)
- Test: `test/mcpOAuthService.test.js`

**Interfacce:**
- Usa Task 1 e Task 2.
- `startAuthorization(id_project, user_id, body) → { authorization_url, connection_id }` (spec §6 step 1; valida `mode`, `server_url`, l'origin di `return_url` rispetto a `MCP_OAUTH_RETURN_ORIGINS`, i campi manual).
- `completeAuthorization({ code, state, error }) → { connection, return_url }` (spec §6 step 2; lettura dello state + `del` prima dello scambio).
- `getAccessToken(id_project, connection_id, { force } = {}) → { access_token, token_type, expires_at }` (spec §7, lock + polling).
- `refreshDue(withinSeconds) → { refreshed, failed, needs_reauth }`.
- `revokeAndDelete(id_project, connection_id) → { revoked }` (non tocca l'integration; lo fa il Task 4).
- `getConnection(id_project, connection_id)` → documento o 404; `listConnections(id_project)`.

- [ ] **Step 1: Test che falliscono (nock + Redis).**
  - Modalità mcp end-to-end: authorize → chiamate discovery + DCR, l'URL ha `code_challenge_method=S256`, `resource`, `state`; lo state esiste su Redis; callback → il body dello scambio ha `code_verifier` coerente con la challenge, `redirect_uri`, `resource`; connessione `active`, i token decifrati corrispondono ai valori mockati; chiave dello state rimossa.
  - Un secondo authorize sullo stesso server riusa il client DCR salvato (nessun secondo `/register`).
  - Modalità google: host dell'URL di authorize `accounts.google.com`, con `access_type=offline`, `prompt=consent`; env non impostate → 503.
  - Modalità manual: client secret salvato cifrato; `client_secret_basic` invia l'header Basic.
  - `return_url` con origin non ammessa → 400.
  - Callback con state sconosciuto → 400; con `error=access_denied` → `last_error.code = 'access_denied'`, restituisce `return_url`; stesso state due volte → la seconda 400 (punto di review 5).
  - `getAccessToken`: token fresco → nessuna chiamata al provider; in scadenza → refresh, `last_refresh_at` valorizzato; risposta senza `refresh_token` mantiene il vecchio, con uno nuovo lo sostituisce (punto di review 4); `invalid_grant` → `needs_reauth` 409, la chiamata successiva 409 senza consumare interceptor nock (punto di review 6); `invalid_client` in modalità mcp → `client_id` azzerato; 500 dal provider → 503, stato ancora `active`; due chiamate parallele → un solo interceptor, entrambe risolvono con il nuovo token (punto di review 3); connessione di un altro progetto → 404 (punto di review 1).
  - `refreshDue(900)`: rinfresca solo le connessioni active con refresh token in scadenza entro 900 s; un errore non ferma le altre.
  - `revokeAndDelete`: revoca chiamata con il refresh token; revoca 500 → connessione comunque cancellata, `revoked: false`.
- [ ] **Step 2: Eseguire** → fallisce.
- [ ] **Step 3: Implementare.** Lock tramite `tdCache.setNX`; rilascio con `tdCache.del` nel `finally`. Il polling confronta `last_refresh_at` con il valore letto prima di tentare il lock. Senza `tdCache` (test che non lo configurano) si ricade su una `Map` in-process di promise pendenti per id connessione, così il comportamento su singola istanza è lo stesso.
- [ ] **Step 4: Eseguire** → passa.
- [ ] **Step 5: Commit** — `feat(mcp-oauth): authorization code + PKCE flow, lazy refresh with lock, revocation`.

### Task 4: rotte — admin, token per i bot, callback, refresh per lo scheduler

**File:**
- Creare: `routes/mcpOAuth.js` (montato dentro `routes/mcp.js` come `router.use('/oauth', mcpOAuth)`), `routes/mcpOAuthCallback.js`
- Modificare: `app.js` (`app.use('/oauth2/mcp', mcpOAuthCallback)` prima del primo router `/:projectid`), `routes/webhook.js` (`POST /mcp-oauth/refresh`)
- Test: `test/mcpOAuthRoute.test.js`

**Interfacce:**
- `POST /:projectid/mcp/oauth/authorize` (admin) → `startAuthorization` del Task 3 con `req.user._id`.
- `GET /:projectid/mcp/oauth/connections`, `GET …/:id` (admin) → forma pubblica.
- `POST …/:id/refresh` (admin) → `getAccessToken(..., { force: true })`, risponde con la connessione pubblica (senza token).
- `DELETE …/:id` (admin) → `revokeAndDelete`, poi rimuove `oauth` da ogni server dell'integration `mcp` con quel `connection_id`, salva, `integrationEvent.emit('integration.update', …)`.
- `GET …/:id/token` (solo bot/subscription: `roleChecker.isTypesAsFunction(['bot','subscription'], req.user, req.projectid)`, altrimenti 403) → `{ access_token, token_type, expires_at }`.
- Le sotto-rotte solo admin aggiungono `roleChecker.hasRole('admin')` (il mount `/mcp` ammette anche bot/subscription).
- `GET /oauth2/mcp/callback` → 302 verso `return_url` con `mcp_oauth=success&connection_id=` oppure `mcp_oauth=error&error=`; senza `return_url` una piccola pagina HTML; pagina HTML 400 se lo state non è valido.
- `POST /webhook/mcp-oauth/refresh` → controllo timing-safe di `x-auth-token` (copiato da `/scheduled-start`), body `{ connection_id }` oppure `{ within_seconds }` (intero 60..86400, default 900).

- [ ] **Step 1: Test che falliscono (chai-http + nock).** Flusso admin authorize → callback (Location del 302 verificata) → la lista mostra `active` e nessun campo segreto; JWT admin su `/token` → 403, JWT bot → 200 (punto di review 2); bot del progetto B sulla connessione del progetto A → 404 (punto di review 1); ruolo agent su `/authorize` → 403; DELETE rimuove `oauth` dalla voce dell'integration e la voce resta; env della feature non impostata → 503 su ogni rotta; refresh via webhook: nessun token → 401, token errato → 401, `MCP_OAUTH_REFRESH_TOKEN` non impostata → 503, `{ within_seconds: 900 }` → conteggi.
- [ ] **Step 2: Eseguire** → fallisce.
- [ ] **Step 3: Implementare.** Verificare come i test esistenti creano un JWT di bot (es. `test/nativemcp.test.js`, i test di faq_kb) e riusare quell'helper.
- [ ] **Step 4: Eseguire** il file più `test/nativemcp.test.js` → passa.
- [ ] **Step 5: Commit** — `feat(mcp-oauth): admin, bot token, callback and scheduler refresh routes`.

### Task 5: mcpService usa le connessioni OAuth

**File:**
- Modificare: `services/mcpService.js`, `routes/mcp.js` (solo commenti di documentazione: `oauth: { connection_id }`)
- Test: `test/mcpServiceOAuth.test.js`

**Interfacce:**
- `buildServerConfig(projectId, body)`: `oauth.connection_id` → `serverConfig.oauth = { connection_id }`; la forma vecchia (`clientId`/`clientSecret`/`redirectUrl`/`scope` senza `connection_id`) mantiene l'errore attuale.
- `resolveRequestHeaders(headers, serverConfig) → Promise<Boolean>`: l'attuale `applyRequestHeaders`, poi il bearer OAuth (sovrascrive `Authorization`).
- `sendJSONRPCRequest` / `sendInitializedNotification` chiamano `resolveRequestHeaders`; su HTTP 401 con `serverConfig.oauth` → `getAccessToken(..., { force: true })` e un solo nuovo tentativo.
- `normalizeMcpServerEntry`: le voci custom e native accettano `oauth.connection_id`; la connessione deve esistere in `projectId` (404 altrimenti); salvata come `oauth: { connection_id, mode }`; la discovery dei tool la usa. `resolveNativeServerConfig` inoltra `oauth` quando presente.
- `getCacheKey(url, projectId, connectionId?)`.

- [ ] **Step 1: Test che falliscono (server MCP mockato con nock).** `POST /:projectid/mcp/connect` con `oauth.connection_id` → le richieste MCP hanno `Authorization: Bearer <token>`; l'`Authorization` dei customHeaders viene sovrascritto; un 401 dal MCP → refresh + nuovo tentativo riuscito; due 401 → errore, nessun loop; `POST /mcp/servers` con una connessione di un altro progetto → 404 (punto di review 1); la voce salvata ha `oauth: { connection_id, mode }` e nessun token in `integration.value` (verifica con `JSON.stringify`); la vecchia forma `oauth: { clientId }` resta 400 con il messaggio attuale.
- [ ] **Step 2: Eseguire** → fallisce.
- [ ] **Step 3: Implementare.**
- [ ] **Step 4: Eseguire** il file più `test/nativemcp.test.js test/mcpOAuthRoute.test.js` → passa.
- [ ] **Step 5: Commit** — `feat(mcp-oauth): bearer injection and 401 retry in mcpService`.

### Task 6: documentazione ed end-to-end manuale

**File:**
- Modificare: `CHANGELOG.md` (voce unreleased), `docs/superpowers/specs/2026-11-10-mcp-oauth2-design.md` (stato, eventuali decisioni prese durante l'implementazione)

- [ ] **Step 1:** Avviare il server di riferimento: `git clone https://github.com/modelcontextprotocol/example-remote-server && npm i && npm run dev:internal` (porta 3232).
- [ ] **Step 2:** Server con `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' }` → aprire l'URL, dare il consenso → callback → `active`.
- [ ] **Step 3:** `POST /:projectid/mcp/connect { url, oauth: { connection_id } }` → tool elencati. JWT bot su `/token` → token. Impostare `expires_at` nel passato su Mongo → il `/token` successivo rinfresca. `POST /webhook/mcp-oauth/refresh` → conteggi.
- [ ] **Step 4:** Registrare i risultati (cosa è stato eseguito, cosa era mockato) nella riga di stato della spec.
- [ ] **Step 5: Commit** — `docs(mcp-oauth): changelog and verification notes`.
