@tiledesk/tiledesk-server 3.3.4 → 3.5.0

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.
Files changed (48) hide show
  1. package/CHANGELOG.md +20 -1
  2. package/app.js +7 -0
  3. package/docs/activities-client.md +27 -0
  4. package/docs/mcp-oauth2-it.md +279 -0
  5. package/docs/mcp-oauth2.md +279 -0
  6. package/docs/superpowers/plans/2026-11-10-mcp-oauth2-server-it.md +155 -0
  7. package/docs/superpowers/plans/2026-11-10-mcp-oauth2-server.md +155 -0
  8. package/docs/superpowers/plans/2026-11-10-mcp-oauth2-tybot-it.md +63 -0
  9. package/docs/superpowers/plans/2026-11-10-mcp-oauth2-tybot.md +63 -0
  10. package/docs/superpowers/specs/2026-11-10-mcp-oauth2-design-it.md +207 -0
  11. package/docs/superpowers/specs/2026-11-10-mcp-oauth2-design.md +207 -0
  12. package/jobs.js +15 -0
  13. package/models/mcpOAuthConnection.js +131 -0
  14. package/package.json +2 -2
  15. package/pubmodules/activities/activityMessageUtil.js +137 -0
  16. package/pubmodules/activities/models/activity.js +2 -0
  17. package/pubmodules/activities/routes/activity.js +30 -1
  18. package/pubmodules/activities/test/execution-filter.test.js +133 -0
  19. package/pubmodules/activities/test/execution-messages.test.js +158 -0
  20. package/pubmodules/executions-publisher/index.js +457 -0
  21. package/pubmodules/executions-publisher/test/audit-consumer.test.js +384 -0
  22. package/pubmodules/executions-publisher/test/executions-publisher.test.js +204 -0
  23. package/pubmodules/pubModulesManager.js +12 -0
  24. package/routes/executions-refire.js +148 -0
  25. package/routes/mcp.js +11 -8
  26. package/routes/mcpOAuth.js +133 -0
  27. package/routes/mcpOAuthCallback.js +75 -0
  28. package/routes/request.js +5 -0
  29. package/routes/webhook.js +120 -54
  30. package/services/mcpOAuthDiscovery.js +248 -0
  31. package/services/mcpOAuthGoogleScopes.js +55 -0
  32. package/services/mcpOAuthService.js +732 -0
  33. package/services/mcpService.js +111 -15
  34. package/services/requestService.js +4 -2
  35. package/services/webhookService.js +4 -2
  36. package/test/executions-refire.test.js +362 -0
  37. package/test/mcpOAuthDiscovery.test.js +331 -0
  38. package/test/mcpOAuthGoogleScopes.test.js +25 -0
  39. package/test/mcpOAuthRoute.test.js +455 -0
  40. package/test/mcpOAuthService.test.js +693 -0
  41. package/test/mcpOAuthUtils.test.js +348 -0
  42. package/test/mcpServiceOAuth.test.js +267 -0
  43. package/test/requestRoute.js +57 -0
  44. package/test/webhookConversationRoute.js +51 -0
  45. package/utils/logRedactor.js +4 -2
  46. package/utils/mcpOAuthCrypto.js +69 -0
  47. package/utils/mcpOAuthPkce.js +20 -0
  48. package/utils/outboundUrlGuard.js +131 -0
@@ -0,0 +1,279 @@
1
+ # MCP OAuth2 — Guide
2
+
3
+ What was built to connect Tiledesk AI agents to MCP servers protected by OAuth2, and which use cases it covers.
4
+
5
+ Italian version: [mcp-oauth2-it.md](mcp-oauth2-it.md). Detailed design: [superpowers/specs/2026-11-10-mcp-oauth2-design.md](superpowers/specs/2026-11-10-mcp-oauth2-design.md).
6
+
7
+ ## 1. In short
8
+
9
+ Many MCP servers (Google Workspace, Google Cloud, SaaS products, internal company servers) do not accept a static API key: they require OAuth2. The user who owns the data must approve access on the provider's page, and the client receives an access token that expires (usually after one hour) plus a refresh token to get new ones.
10
+
11
+ With this feature **tiledesk-server is the OAuth client** for the project:
12
+
13
+ - an admin connects the MCP server once, approving access on the provider's page;
14
+ - the server stores the tokens **encrypted** in the database and **refreshes** them when they are about to expire;
15
+ - the chatbot (tybot), when an AI Prompt action uses that MCP server, asks the server for a valid access token and sends it as `Authorization: Bearer …`.
16
+
17
+ Tokens never reach the browser and are never written into the project integrations.
18
+
19
+ ## 2. Use cases
20
+
21
+ | # | Use case | How |
22
+ |---|---|---|
23
+ | 1 | MCP server that follows the MCP Authorization spec (discovery + dynamic client registration) | Mode **`mcp`**: the admin types only the MCP server URL; the server discovers the OAuth provider and registers itself as a client |
24
+ | 2 | Google MCP servers (Calendar, Gmail, Drive, BigQuery, Cloud Run, …) | Mode **`google`**: one Google OAuth client for the whole installation, configured from env; scopes are optional for the known Google MCP servers (the server uses the ones documented by Google), required for the others |
25
+ | 3 | Any OAuth2 provider without discovery | Mode **`manual`**: the admin enters authorization URL, token URL, client ID and secret, scopes |
26
+ | 4 | AI agent using an OAuth MCP server during a conversation | tybot asks `GET /mcp/oauth/connections/:id/token` with the bot JWT and sends the Bearer to the MCP server through the LLM backend |
27
+ | 5 | Admin lists tools and saves the server from the dashboard | `/mcp/connect`, `/mcp/tools` and `/mcp/servers` accept `oauth: { connection_id }` |
28
+ | 6 | Access token expired | Automatic refresh when the token is requested (lazy) and, optionally, periodic refresh by the scheduler |
29
+ | 7 | Access revoked by the user at the provider, or refresh token expired | The connection becomes `needs_reauth`; the AI Prompt action fails with "MCP server … needs to be reconnected"; the admin reconnects |
30
+ | 8 | Disconnect a server | `DELETE` of the connection: revocation at the provider, deletion, `oauth` removed from the integration |
31
+
32
+ Not covered yet: OAuth on **native** MCP servers (Tiledesk catalog), per-end-user tokens (every conversation of the project uses the connection authorized by the admin), the Design Studio UI.
33
+
34
+ ## 3. Architecture
35
+
36
+ ```mermaid
37
+ flowchart LR
38
+ subgraph Browser
39
+ D[Dashboard<br/>Integrations → MCP]
40
+ P[Provider consent page]
41
+ end
42
+ subgraph Tiledesk
43
+ S[tiledesk-server<br/>OAuth client]
44
+ DB[(MongoDB<br/>mcp_oauth_connections<br/>tokens encrypted)]
45
+ R[(Redis<br/>state, refresh lock)]
46
+ T[tybot<br/>AI Prompt action]
47
+ L[LLM backend]
48
+ SC[scheduler-service]
49
+ end
50
+ subgraph External
51
+ AS[OAuth provider<br/>Google / MCP auth server / other]
52
+ M[MCP server]
53
+ end
54
+
55
+ D -- "authorize, connections, tools" --> S
56
+ D -. opens .-> P
57
+ P -- consent --> AS
58
+ AS -- "redirect /oauth2/mcp/callback" --> S
59
+ S <-- "code → tokens, refresh" --> AS
60
+ S --- DB
61
+ S --- R
62
+ T -- "GET …/token (bot JWT)" --> S
63
+ T -- "servers + Bearer" --> L
64
+ L -- "MCP calls + Bearer" --> M
65
+ S -- "connect / list tools + Bearer" --> M
66
+ SC -- "POST /webhook/mcp-oauth/refresh" --> S
67
+ ```
68
+
69
+ | Component | Role | Status |
70
+ |---|---|---|
71
+ | tiledesk-server | OAuth flow, encrypted storage, refresh, token endpoint, management API, scheduler webhook | Done, deployed on stage |
72
+ | tiledesk-chatbot (tybot) | Reads `oauth.connection_id` from the integration, gets the token, sends the Bearer | Implementation plan delivered |
73
+ | tiledesk-scheduler-service | `mcpOAuthRefresh` target calling the refresh webhook | Implementation plan delivered |
74
+ | tiledesk-dashboard | Authentication selector, popup flow, connection status, reconnect | Implementation plan delivered |
75
+
76
+ ## 4. Server components
77
+
78
+ | File | Content |
79
+ |---|---|
80
+ | `models/mcpOAuthConnection.js` | Collection `mcp_oauth_connections`: one connection per project and MCP server URL; public view without secrets (`toPublic`) |
81
+ | `services/mcpOAuthService.js` | Authorization start and callback, token exchange, lazy refresh with lock, refresh of due connections, revocation |
82
+ | `services/mcpOAuthDiscovery.js` | Mode `mcp`: Protected Resource Metadata (RFC 9728), Authorization Server Metadata (RFC 8414 / OIDC), Dynamic Client Registration (RFC 7591) |
83
+ | `utils/mcpOAuthCrypto.js` | AES-256-GCM encryption of tokens and client secrets (`v1:` format) |
84
+ | `utils/mcpOAuthPkce.js` | PKCE S256 verifier/challenge and random `state` |
85
+ | `utils/outboundUrlGuard.js` | Blocks calls to non-https URLs and to private/loopback addresses (SSRF) |
86
+ | `routes/mcpOAuth.js` | `/:projectid/mcp/oauth/*`: authorize, connections, refresh, delete, token |
87
+ | `routes/mcpOAuthCallback.js` | Public `GET /oauth2/mcp/callback` |
88
+ | `routes/webhook.js` | `POST /webhook/mcp-oauth/refresh` for the scheduler |
89
+ | `services/mcpService.js` | MCP calls with `oauth.connection_id`: adds the Bearer, retries once after a 401 with a forced refresh |
90
+
91
+ ## 5. Connecting a server (authorization flow)
92
+
93
+ ```mermaid
94
+ sequenceDiagram
95
+ autonumber
96
+ actor A as Admin
97
+ participant D as Dashboard
98
+ participant S as tiledesk-server
99
+ participant AS as OAuth provider
100
+ participant M as MCP server
101
+
102
+ A->>D: Connect (mode mcp / google / manual)
103
+ D->>S: POST /:project/mcp/oauth/authorize
104
+ opt mode mcp
105
+ S->>M: initialize without token → 401 + resource_metadata
106
+ S->>AS: metadata discovery + client registration (DCR)
107
+ end
108
+ S->>S: state + PKCE in Redis (10 min, single use)
109
+ S-->>D: authorization_url, connection_id
110
+ D->>AS: opens authorization_url (popup)
111
+ A->>AS: login + consent
112
+ AS->>S: GET /oauth2/mcp/callback?code&state
113
+ S->>AS: code + code_verifier → access + refresh token
114
+ S->>S: tokens encrypted in MongoDB, status active
115
+ S-->>A: "Connected" page (or redirect to return_url)
116
+ D->>S: POST /mcp/tools { url, oauth: { connection_id } }
117
+ S->>M: tools/list + Bearer
118
+ D->>S: save server with oauth.connection_id
119
+ ```
120
+
121
+ The saved integration entry holds only a reference:
122
+
123
+ ```json
124
+ { "name": "Google Calendar", "url": "https://calendarmcp.googleapis.com/mcp/v1",
125
+ "transport": "streamable_http", "tools": [ ... ],
126
+ "oauth": { "connection_id": "6731f0…", "mode": "google" } }
127
+ ```
128
+
129
+ ## 6. Using the token during a conversation
130
+
131
+ ```mermaid
132
+ sequenceDiagram
133
+ autonumber
134
+ participant U as End user
135
+ participant T as tybot (AI Prompt)
136
+ participant S as tiledesk-server
137
+ participant AS as OAuth provider
138
+ participant L as LLM backend
139
+ participant M as MCP server
140
+
141
+ U->>T: message
142
+ T->>S: GET /integration/name/mcp
143
+ T->>S: GET /mcp/oauth/connections/:id/token (bot JWT)
144
+ alt token valid for more than 5 minutes
145
+ S-->>T: access_token
146
+ else expiring or expired
147
+ S->>AS: grant_type=refresh_token (Redis lock)
148
+ AS-->>S: new access token (and refresh token, if rotated)
149
+ S-->>T: new access_token
150
+ end
151
+ T->>L: prompt + MCP servers with Authorization: Bearer
152
+ L->>M: tools/call + Bearer
153
+ M-->>L: result
154
+ L-->>T: answer
155
+ T-->>U: answer
156
+ ```
157
+
158
+ - The token endpoint answers only to **bot or subscription** credentials of the same project: an admin JWT gets 403, so tokens never reach the dashboard.
159
+ - tybot keeps the token in memory until 60 seconds before it expires.
160
+ - If the connection must be authorized again (409 `needs_reauth`), the action fails like a missing integration: `flowError` "MCP server … needs to be reconnected", then the action's false branch.
161
+
162
+ ## 7. Token refresh
163
+
164
+ Two mechanisms, both on the server:
165
+
166
+ 1. **Lazy (always active).** Every token request checks the expiry. If the access token expires within 5 minutes it is refreshed, otherwise the stored one is returned. A Redis lock makes sure that concurrent requests, even from different pods, cause a single refresh. A 401 from the MCP server triggers one forced refresh and a retry.
167
+ 2. **Periodic (optional).** The scheduler calls `POST /webhook/mcp-oauth/refresh` with `{ within_seconds }`: the server refreshes the active connections that expire within that window. It is useful for connections that nobody uses for days (some providers expire unused refresh tokens) and to find revoked connections before a conversation hits them. The lazy mechanism alone is enough for the chatbot to work.
168
+
169
+ ```mermaid
170
+ stateDiagram-v2
171
+ [*] --> pending: authorize
172
+ pending --> active: callback ok
173
+ pending --> pending: provider error (last_error)
174
+ active --> active: refresh ok
175
+ active --> needs_reauth: invalid_grant (revoked / expired)
176
+ needs_reauth --> active: new authorize + consent
177
+ active --> [*]: DELETE (revoke + delete)
178
+ needs_reauth --> [*]: DELETE
179
+ ```
180
+
181
+ A temporary provider error (network, 5xx) does not change the status: the request answers 503 and the next one tries again.
182
+
183
+ ## 8. API
184
+
185
+ Base: `/:project_id/mcp/oauth` (header `Authorization: JWT …`). Every route answers 503 `not_configured` when the feature is not configured.
186
+
187
+ | Method and path | Who | Purpose |
188
+ |---|---|---|
189
+ | `POST /authorize` | admin | Starts the flow. Body `{ mode, server_url, name?, scopes?, manual?, return_url? }` → `{ authorization_url, connection_id }` |
190
+ | `GET /connections` | admin | List of connections (no secrets) |
191
+ | `GET /connections/:id` | admin | One connection: `status`, `expires_at`, `last_error`, `granted_scopes`, … |
192
+ | `POST /connections/:id/refresh` | admin | Forces a refresh |
193
+ | `DELETE /connections/:id` | admin | Revokes at the provider, deletes, removes `oauth` from the integration |
194
+ | `GET /connections/:id/token` | bot, subscription | `{ access_token, token_type, expires_at }` |
195
+
196
+ Other routes:
197
+
198
+ | Method and path | Purpose |
199
+ |---|---|
200
+ | `GET /oauth2/mcp/callback` | Provider redirect (public, protected by the single-use `state`) |
201
+ | `POST /webhook/mcp-oauth/refresh` | Scheduler. Header `x-auth-token`. Body `{ within_seconds }` (60..86400, default 900) or `{ connection_id }` |
202
+ | `POST /:project_id/mcp/connect`, `/tools`, `/servers` | Accept `oauth: { connection_id }` for custom servers |
203
+
204
+ Main errors: 400 invalid body, discovery not supported, connection used for another URL; 403 admin on the token endpoint; 404 connection missing or of another project; 409 `needs_reauth`; 502/503 provider unreachable.
205
+
206
+ ## 9. Configuration
207
+
208
+ | Variable | Required | Purpose |
209
+ |---|---|---|
210
+ | `MCP_OAUTH_ENCRYPTION_KEY` | yes | 32 bytes in base64 (`openssl rand -base64 32`). Same value on every replica and stable over time: changing it makes the stored tokens unreadable |
211
+ | `MCP_OAUTH_REDIRECT_BASE_URL` | yes (fallback `API_URL`) | Public API URL, e.g. `https://stage.eks.tiledesk.com/api`. Redirect URI = `<base>/oauth2/mcp/callback` |
212
+ | `MCP_OAUTH_GOOGLE_CLIENT_ID`, `MCP_OAUTH_GOOGLE_CLIENT_SECRET` | for `google` | Google OAuth client of type "Web application" |
213
+ | `MCP_OAUTH_REFRESH_TOKEN` | for the scheduler | Shared secret of the refresh webhook (same value on the scheduler worker) |
214
+ | `MCP_OAUTH_RETURN_ORIGINS` | only with `return_url` | Origins allowed for the redirect after the callback. The popup flow of the dashboard does not need it |
215
+ | `MCP_OAUTH_ALLOW_INSECURE_URLS` | never in production | `true` allows `http://` and private addresses: local development only |
216
+
217
+ ### Google setup
218
+
219
+ 1. Google Cloud project: enable the API of the service and its MCP service (e.g. `calendar-json.googleapis.com` and `calendarmcp.googleapis.com`; for Google Cloud servers `gcloud beta services mcp enable <service>`).
220
+ 2. Google Auth Platform: consent screen (in "Testing", add the test users), scopes in Data Access.
221
+ 3. Client of type **Web application**, redirect URI exactly `<MCP_OAUTH_REDIRECT_BASE_URL>/oauth2/mcp/callback`, **"Use this client for an AI-powered agent"** selected (required by the Google Workspace MCP servers).
222
+ 4. Client ID and secret in the two env variables, restart the pods.
223
+
224
+ In "Testing" status Google refresh tokens last 7 days. Sensitive or restricted scopes (Gmail, Drive) need Google verification before production.
225
+
226
+ ## 10. Examples
227
+
228
+ **Google Calendar**
229
+
230
+ ```json
231
+ POST /:project_id/mcp/oauth/authorize
232
+ {
233
+ "mode": "google",
234
+ "server_url": "https://calendarmcp.googleapis.com/mcp/v1",
235
+ "name": "Google Calendar"
236
+ }
237
+ ```
238
+
239
+ `scopes` can be omitted for the Google MCP servers listed in `services/mcpOAuthGoogleScopes.js` (Gmail, Drive, Docs, Sheets, Slides, Calendar, Chat, People, Classroom, BigQuery): the server uses the scopes documented by Google, here the three read-only Calendar scopes. Scopes sent in the body replace the defaults, for example `"scopes": ["https://www.googleapis.com/auth/calendar.events"]` for write access. Any other Google URL without `scopes` answers 400. The same scopes must be added in Google Auth Platform → Data Access.
240
+
241
+ **MCP server with discovery**
242
+
243
+ ```json
244
+ { "mode": "mcp", "server_url": "https://mcp.example.com/mcp", "name": "Example" }
245
+ ```
246
+
247
+ **Manual provider**
248
+
249
+ ```json
250
+ {
251
+ "mode": "manual",
252
+ "server_url": "https://mcp.example.com/mcp",
253
+ "scopes": ["read"],
254
+ "manual": {
255
+ "authorization_endpoint": "https://auth.example.com/authorize",
256
+ "token_endpoint": "https://auth.example.com/token",
257
+ "client_id": "abc",
258
+ "client_secret": "…"
259
+ }
260
+ }
261
+ ```
262
+
263
+ Then, in all cases: open `authorization_url`, approve, and use the `connection_id` in `/mcp/tools` and `/mcp/servers`. A Postman collection for these calls is in `postman/import/` (local, not committed yet).
264
+
265
+ ## 11. Security
266
+
267
+ - Authorization code + **PKCE S256** always; `state` random, single use, 10 minutes, bound to project and user.
268
+ - Access tokens, refresh tokens and client secrets **encrypted at rest** (AES-256-GCM); never returned by the management API; redacted in the logs.
269
+ - The integration holds only `connection_id`: tokens never end up in the integration cache or in the dashboard.
270
+ - The Bearer is sent only to the URL the connection was authorized for: using a connection with another server URL answers 400.
271
+ - Outbound URL guard: https only, no private, loopback or link-local addresses, no redirects, timeouts and response size limits.
272
+ - `return_url` allowed only towards origins in `MCP_OAUTH_RETURN_ORIGINS`.
273
+ - Scheduler webhook protected by a shared token compared in constant time.
274
+
275
+ ## 12. Testing
276
+
277
+ - Automated: mocha tests `test/mcpOAuthUtils`, `mcpOAuthDiscovery`, `mcpOAuthService`, `mcpOAuthRoute`, `mcpServiceOAuth` (providers and MCP servers mocked with nock, real Mongo and Redis).
278
+ - End to end, locally: [modelcontextprotocol/example-remote-server](https://github.com/modelcontextprotocol/example-remote-server) (`npm run dev:internal`, port 3232) with `MCP_OAUTH_ALLOW_INSECURE_URLS=true`. On a public URL it must be started with `BASE_URI=<public URL>`, otherwise its metadata points to `localhost`.
279
+ - Stage: mode `mcp` with the reference server behind a public tunnel, mode `google` with a Google Cloud client.
@@ -0,0 +1,155 @@
1
+ # MCP OAuth2 — Piano di implementazione tiledesk-server
2
+
3
+ > **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.
4
+
5
+ **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.
6
+
7
+ **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.
8
+
9
+ **Stack:** Node 18/Express, Mongoose, axios, `crypto` / `dns` di Node, TdCache (Redis), mocha + chai-http + nock (MongoDB + Redis di test).
10
+
11
+ **Spec:** `docs/superpowers/specs/2026-11-10-mcp-oauth2-design.md`
12
+
13
+ ## Vincoli globali
14
+
15
+ - Branch `features-2611/oauth2-mcp` (già in checkout). Un commit per task. Mai fare push.
16
+ - Nessuna nuova dipendenza npm (solo axios + moduli built-in di Node).
17
+ - 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.
18
+ - 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.
19
+ - Redirect URI = `(MCP_OAUTH_REDIRECT_BASE_URL || API_URL)` senza slash finale + `/oauth2/mcp/callback`.
20
+ - Chiavi Redis: `mcp_oauth:state:<state>` (TTL 600 s), `mcp_oauth:refresh_lock:<connection_id>` (TTL 30 s). `REFRESH_WINDOW_S = 300`.
21
+ - 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.
22
+ - 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`.
23
+ - 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 })`.
24
+ - 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.
25
+
26
+ ## Punti di attenzione per la review
27
+
28
+ 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`).
29
+ 2. Un JWT admin su `GET …/connections/:id/token` → 403; un JWT bot dello stesso progetto → 200.
30
+ 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.
31
+ 4. Una risposta di refresh senza `refresh_token` mantiene quello vecchio; con uno nuovo, lo sostituisce (rotazione).
32
+ 5. Riuso dello state: chiamare la callback due volte con lo stesso `state` → seconda chiamata 400, nessun secondo scambio del code.
33
+ 6. `invalid_grant` sul refresh → `needs_reauth`, poi l'endpoint del token risponde 409 senza chiamare di nuovo il provider.
34
+
35
+ ---
36
+
37
+ ### Task 1: cifratura, PKCE, URL guard, modello
38
+
39
+ **File:**
40
+ - Creare: `utils/mcpOAuthCrypto.js`, `utils/mcpOAuthPkce.js`, `utils/outboundUrlGuard.js`, `models/mcpOAuthConnection.js`
41
+ - 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)
42
+ - Test: `test/mcpOAuthUtils.test.js`
43
+
44
+ **Interfacce:**
45
+ - `mcpOAuthCrypto`: `isConfigured() → boolean`, `encrypt(plain) → 'v1:…'`, `decrypt(enc) → string` (lancia in caso di manomissione / chiave errata), `null`/`undefined` passano invariati.
46
+ - `mcpOAuthPkce`: `randomState() → base64url(32 byte)`, `createVerifier() → base64url di 64 caratteri`, `challengeOf(verifier) → base64url(sha256)`.
47
+ - `outboundUrlGuard`: `assertAllowed(url) → Promise<URL>` (lancia con `.status = 400`, messaggio `"URL not allowed: <reason>"`), `httpOptions() → { maxRedirects: 0, timeout: 10000, maxContentLength: 1048576 }`.
48
+ - 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.
49
+
50
+ - [ ] **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`.
51
+ - [ ] **Step 2: Eseguire** `… test/mcpOAuthUtils.test.js` → fallisce.
52
+ - [ ] **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.
53
+ - [ ] **Step 4: Eseguire** il file più `test/logRedactor*.js` se presente → passa.
54
+ - [ ] **Step 5: Commit** — `feat(mcp-oauth): encryption, PKCE, outbound URL guard and connection model`.
55
+
56
+ ### Task 2: discovery e dynamic client registration
57
+
58
+ **File:**
59
+ - Creare: `services/mcpOAuthDiscovery.js`
60
+ - Test: `test/mcpOAuthDiscovery.test.js`
61
+
62
+ **Interfacce:**
63
+ - `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.
64
+ - `register(metadata, redirectUri) → { client_id, client_secret?, token_endpoint_auth_method }` secondo spec §6.2; 400 se manca `registration_endpoint`.
65
+ - Funzione pura `wellKnownUrls(baseUrl, suffix) → string[]` (prima con path inserito, poi root).
66
+
67
+ - [ ] **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).
68
+ - [ ] **Step 2: Eseguire** → fallisce.
69
+ - [ ] **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="…"`.
70
+ - [ ] **Step 4: Eseguire** → passa.
71
+ - [ ] **Step 5: Commit** — `feat(mcp-oauth): MCP authorization discovery and dynamic client registration`.
72
+
73
+ ### Task 3: service OAuth — authorize, callback, refresh, revoca
74
+
75
+ **File:**
76
+ - Creare: `services/mcpOAuthService.js`
77
+ - Modificare: `app.js` (`mcpOAuthService.setTdCache(tdCache)` accanto a `mcpService.setTdCache`)
78
+ - Test: `test/mcpOAuthService.test.js`
79
+
80
+ **Interfacce:**
81
+ - Usa Task 1 e Task 2.
82
+ - `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).
83
+ - `completeAuthorization({ code, state, error }) → { connection, return_url }` (spec §6 step 2; lettura dello state + `del` prima dello scambio).
84
+ - `getAccessToken(id_project, connection_id, { force } = {}) → { access_token, token_type, expires_at }` (spec §7, lock + polling).
85
+ - `refreshDue(withinSeconds) → { refreshed, failed, needs_reauth }`.
86
+ - `revokeAndDelete(id_project, connection_id) → { revoked }` (non tocca l'integration; lo fa il Task 4).
87
+ - `getConnection(id_project, connection_id)` → documento o 404; `listConnections(id_project)`.
88
+
89
+ - [ ] **Step 1: Test che falliscono (nock + Redis).**
90
+ - 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.
91
+ - Un secondo authorize sullo stesso server riusa il client DCR salvato (nessun secondo `/register`).
92
+ - Modalità google: host dell'URL di authorize `accounts.google.com`, con `access_type=offline`, `prompt=consent`; env non impostate → 503.
93
+ - Modalità manual: client secret salvato cifrato; `client_secret_basic` invia l'header Basic.
94
+ - `return_url` con origin non ammessa → 400.
95
+ - 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).
96
+ - `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).
97
+ - `refreshDue(900)`: rinfresca solo le connessioni active con refresh token in scadenza entro 900 s; un errore non ferma le altre.
98
+ - `revokeAndDelete`: revoca chiamata con il refresh token; revoca 500 → connessione comunque cancellata, `revoked: false`.
99
+ - [ ] **Step 2: Eseguire** → fallisce.
100
+ - [ ] **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.
101
+ - [ ] **Step 4: Eseguire** → passa.
102
+ - [ ] **Step 5: Commit** — `feat(mcp-oauth): authorization code + PKCE flow, lazy refresh with lock, revocation`.
103
+
104
+ ### Task 4: rotte — admin, token per i bot, callback, refresh per lo scheduler
105
+
106
+ **File:**
107
+ - Creare: `routes/mcpOAuth.js` (montato dentro `routes/mcp.js` come `router.use('/oauth', mcpOAuth)`), `routes/mcpOAuthCallback.js`
108
+ - Modificare: `app.js` (`app.use('/oauth2/mcp', mcpOAuthCallback)` prima del primo router `/:projectid`), `routes/webhook.js` (`POST /mcp-oauth/refresh`)
109
+ - Test: `test/mcpOAuthRoute.test.js`
110
+
111
+ **Interfacce:**
112
+ - `POST /:projectid/mcp/oauth/authorize` (admin) → `startAuthorization` del Task 3 con `req.user._id`.
113
+ - `GET /:projectid/mcp/oauth/connections`, `GET …/:id` (admin) → forma pubblica.
114
+ - `POST …/:id/refresh` (admin) → `getAccessToken(..., { force: true })`, risponde con la connessione pubblica (senza token).
115
+ - `DELETE …/:id` (admin) → `revokeAndDelete`, poi rimuove `oauth` da ogni server dell'integration `mcp` con quel `connection_id`, salva, `integrationEvent.emit('integration.update', …)`.
116
+ - `GET …/:id/token` (solo bot/subscription: `roleChecker.isTypesAsFunction(['bot','subscription'], req.user, req.projectid)`, altrimenti 403) → `{ access_token, token_type, expires_at }`.
117
+ - Le sotto-rotte solo admin aggiungono `roleChecker.hasRole('admin')` (il mount `/mcp` ammette anche bot/subscription).
118
+ - `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.
119
+ - `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).
120
+
121
+ - [ ] **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.
122
+ - [ ] **Step 2: Eseguire** → fallisce.
123
+ - [ ] **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.
124
+ - [ ] **Step 4: Eseguire** il file più `test/nativemcp.test.js` → passa.
125
+ - [ ] **Step 5: Commit** — `feat(mcp-oauth): admin, bot token, callback and scheduler refresh routes`.
126
+
127
+ ### Task 5: mcpService usa le connessioni OAuth
128
+
129
+ **File:**
130
+ - Modificare: `services/mcpService.js`, `routes/mcp.js` (solo commenti di documentazione: `oauth: { connection_id }`)
131
+ - Test: `test/mcpServiceOAuth.test.js`
132
+
133
+ **Interfacce:**
134
+ - `buildServerConfig(projectId, body)`: `oauth.connection_id` → `serverConfig.oauth = { connection_id }`; la forma vecchia (`clientId`/`clientSecret`/`redirectUrl`/`scope` senza `connection_id`) mantiene l'errore attuale.
135
+ - `resolveRequestHeaders(headers, serverConfig) → Promise<Boolean>`: l'attuale `applyRequestHeaders`, poi il bearer OAuth (sovrascrive `Authorization`).
136
+ - `sendJSONRPCRequest` / `sendInitializedNotification` chiamano `resolveRequestHeaders`; su HTTP 401 con `serverConfig.oauth` → `getAccessToken(..., { force: true })` e un solo nuovo tentativo.
137
+ - `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.
138
+ - `getCacheKey(url, projectId, connectionId?)`.
139
+
140
+ - [ ] **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.
141
+ - [ ] **Step 2: Eseguire** → fallisce.
142
+ - [ ] **Step 3: Implementare.**
143
+ - [ ] **Step 4: Eseguire** il file più `test/nativemcp.test.js test/mcpOAuthRoute.test.js` → passa.
144
+ - [ ] **Step 5: Commit** — `feat(mcp-oauth): bearer injection and 401 retry in mcpService`.
145
+
146
+ ### Task 6: documentazione ed end-to-end manuale
147
+
148
+ **File:**
149
+ - Modificare: `CHANGELOG.md` (voce unreleased), `docs/superpowers/specs/2026-11-10-mcp-oauth2-design.md` (stato, eventuali decisioni prese durante l'implementazione)
150
+
151
+ - [ ] **Step 1:** Avviare il server di riferimento: `git clone https://github.com/modelcontextprotocol/example-remote-server && npm i && npm run dev:internal` (porta 3232).
152
+ - [ ] **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`.
153
+ - [ ] **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.
154
+ - [ ] **Step 4:** Registrare i risultati (cosa è stato eseguito, cosa era mockato) nella riga di stato della spec.
155
+ - [ ] **Step 5: Commit** — `docs(mcp-oauth): changelog and verification notes`.
@@ -0,0 +1,155 @@
1
+ # MCP OAuth2 — tiledesk-server Implementation Plan
2
+
3
+ > **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.
4
+
5
+ **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.
6
+
7
+ **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.
8
+
9
+ **Tech Stack:** Node 18/Express, Mongoose, axios, Node `crypto` / `dns`, TdCache (Redis), mocha + chai-http + nock (test MongoDB + Redis).
10
+
11
+ **Spec:** `docs/superpowers/specs/2026-11-10-mcp-oauth2-design.md`
12
+
13
+ ## Global Constraints
14
+
15
+ - Branch `features-2611/oauth2-mcp` (checked out). One commit per task. Never push.
16
+ - No new npm dependency (axios + Node built-ins only).
17
+ - 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.
18
+ - 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.
19
+ - Redirect URI = `(MCP_OAUTH_REDIRECT_BASE_URL || API_URL)` without trailing slash + `/oauth2/mcp/callback`.
20
+ - Redis keys: `mcp_oauth:state:<state>` (TTL 600 s), `mcp_oauth:refresh_lock:<connection_id>` (TTL 30 s). `REFRESH_WINDOW_S = 300`.
21
+ - 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.
22
+ - 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.
23
+ - 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 })`.
24
+ - 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.
25
+
26
+ ## Review Focus
27
+
28
+ 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`).
29
+ 2. An admin JWT on `GET …/connections/:id/token` → 403; a bot JWT of the same project → 200.
30
+ 3. Two concurrent token requests on an expiring token → exactly one call to the provider token endpoint, both callers get the new token.
31
+ 4. A refresh response without `refresh_token` keeps the old one; with one, it replaces it (rotation).
32
+ 5. State reuse: calling the callback twice with the same `state` → second call 400, no second code exchange.
33
+ 6. `invalid_grant` on refresh → `needs_reauth`, token endpoint then answers 409 without calling the provider again.
34
+
35
+ ---
36
+
37
+ ### Task 1: crypto, PKCE, URL guard, model
38
+
39
+ **Files:**
40
+ - Create: `utils/mcpOAuthCrypto.js`, `utils/mcpOAuthPkce.js`, `utils/outboundUrlGuard.js`, `models/mcpOAuthConnection.js`
41
+ - 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)
42
+ - Test: `test/mcpOAuthUtils.test.js`
43
+
44
+ **Interfaces:**
45
+ - `mcpOAuthCrypto`: `isConfigured() → boolean`, `encrypt(plain) → 'v1:…'`, `decrypt(enc) → string` (throws on tamper / wrong key), `null`/`undefined` pass through.
46
+ - `mcpOAuthPkce`: `randomState() → base64url(32 bytes)`, `createVerifier() → 64-char base64url`, `challengeOf(verifier) → base64url(sha256)`.
47
+ - `outboundUrlGuard`: `assertAllowed(url) → Promise<URL>` (throws `.status = 400`, message `"URL not allowed: <reason>"`), `httpOptions() → { maxRedirects: 0, timeout: 10000, maxContentLength: 1048576 }`.
48
+ - Model fields exactly as spec §4, `timestamps: true`, unique index `{ id_project: 1, server_url: 1 }`, `toPublic(doc)` static returning the spec §9 shape.
49
+
50
+ - [ ] **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`.
51
+ - [ ] **Step 2: Run** `… test/mcpOAuthUtils.test.js` → fail.
52
+ - [ ] **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.
53
+ - [ ] **Step 4: Run** the file plus `test/logRedactor*.js` if present → pass.
54
+ - [ ] **Step 5: Commit** — `feat(mcp-oauth): encryption, PKCE, outbound URL guard and connection model`.
55
+
56
+ ### Task 2: discovery and dynamic client registration
57
+
58
+ **Files:**
59
+ - Create: `services/mcpOAuthDiscovery.js`
60
+ - Test: `test/mcpOAuthDiscovery.test.js`
61
+
62
+ **Interfaces:**
63
+ - `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.
64
+ - `register(metadata, redirectUri) → { client_id, client_secret?, token_endpoint_auth_method }` per spec §6.2; 400 when `registration_endpoint` is missing.
65
+ - Pure `wellKnownUrls(baseUrl, suffix) → string[]` (path-inserted first, then root).
66
+
67
+ - [ ] **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).
68
+ - [ ] **Step 2: Run** → fail.
69
+ - [ ] **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="…"`.
70
+ - [ ] **Step 4: Run** → pass.
71
+ - [ ] **Step 5: Commit** — `feat(mcp-oauth): MCP authorization discovery and dynamic client registration`.
72
+
73
+ ### Task 3: OAuth service — authorize, callback, refresh, revoke
74
+
75
+ **Files:**
76
+ - Create: `services/mcpOAuthService.js`
77
+ - Modify: `app.js` (`mcpOAuthService.setTdCache(tdCache)` next to `mcpService.setTdCache`)
78
+ - Test: `test/mcpOAuthService.test.js`
79
+
80
+ **Interfaces:**
81
+ - Consumes Task 1 and Task 2.
82
+ - `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).
83
+ - `completeAuthorization({ code, state, error }) → { connection, return_url }` (spec §6 step 2; state read + `del` before the exchange).
84
+ - `getAccessToken(id_project, connection_id, { force } = {}) → { access_token, token_type, expires_at }` (spec §7, lock + poll).
85
+ - `refreshDue(withinSeconds) → { refreshed, failed, needs_reauth }`.
86
+ - `revokeAndDelete(id_project, connection_id) → { revoked }` (does not touch the integration; Task 4 does).
87
+ - `getConnection(id_project, connection_id)` → doc or 404; `listConnections(id_project)`.
88
+
89
+ - [ ] **Step 1: Failing tests (nock + Redis).**
90
+ - 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.
91
+ - Second authorize on the same server reuses the stored DCR client (no second `/register`).
92
+ - google mode: authorize URL host `accounts.google.com`, has `access_type=offline`, `prompt=consent`; env unset → 503.
93
+ - manual mode: client secret stored encrypted; `client_secret_basic` sends the Basic header.
94
+ - `return_url` with origin not allowed → 400.
95
+ - 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).
96
+ - `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).
97
+ - `refreshDue(900)`: refreshes only active connections with a refresh token expiring within 900 s; one failure does not stop the others.
98
+ - `revokeAndDelete`: revocation called with the refresh token; revocation 500 → still deleted, `revoked: false`.
99
+ - [ ] **Step 2: Run** → fail.
100
+ - [ ] **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.
101
+ - [ ] **Step 4: Run** → pass.
102
+ - [ ] **Step 5: Commit** — `feat(mcp-oauth): authorization code + PKCE flow, lazy refresh with lock, revocation`.
103
+
104
+ ### Task 4: routes — admin, bot token, callback, scheduler refresh
105
+
106
+ **Files:**
107
+ - Create: `routes/mcpOAuth.js` (mounted inside `routes/mcp.js` as `router.use('/oauth', mcpOAuth)`), `routes/mcpOAuthCallback.js`
108
+ - Modify: `app.js` (`app.use('/oauth2/mcp', mcpOAuthCallback)` before the first `/:projectid` router), `routes/webhook.js` (`POST /mcp-oauth/refresh`)
109
+ - Test: `test/mcpOAuthRoute.test.js`
110
+
111
+ **Interfaces:**
112
+ - `POST /:projectid/mcp/oauth/authorize` (admin) → Task 3 `startAuthorization` with `req.user._id`.
113
+ - `GET /:projectid/mcp/oauth/connections`, `GET …/:id` (admin) → public shape.
114
+ - `POST …/:id/refresh` (admin) → `getAccessToken(..., { force: true })`, responds with the public connection (no token).
115
+ - `DELETE …/:id` (admin) → `revokeAndDelete`, then remove `oauth` from every `mcp` integration server with that `connection_id`, save, `integrationEvent.emit('integration.update', …)`.
116
+ - `GET …/:id/token` (bot/subscription only: `roleChecker.isTypesAsFunction(['bot','subscription'], req.user, req.projectid)` else 403) → `{ access_token, token_type, expires_at }`.
117
+ - Admin-only sub-routes add `roleChecker.hasRole('admin')` (the `/mcp` mount also admits bot/subscription).
118
+ - `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.
119
+ - `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).
120
+
121
+ - [ ] **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.
122
+ - [ ] **Step 2: Run** → fail.
123
+ - [ ] **Step 3: Implement.** Check how existing tests create a bot JWT (e.g. `test/nativemcp.test.js`, faq_kb tests) and reuse that helper.
124
+ - [ ] **Step 4: Run** the file plus `test/nativemcp.test.js` → pass.
125
+ - [ ] **Step 5: Commit** — `feat(mcp-oauth): admin, bot token, callback and scheduler refresh routes`.
126
+
127
+ ### Task 5: mcpService uses OAuth connections
128
+
129
+ **Files:**
130
+ - Modify: `services/mcpService.js`, `routes/mcp.js` (doc comments only: `oauth: { connection_id }`)
131
+ - Test: `test/mcpServiceOAuth.test.js`
132
+
133
+ **Interfaces:**
134
+ - `buildServerConfig(projectId, body)`: `oauth.connection_id` → `serverConfig.oauth = { connection_id }`; the legacy shape (`clientId`/`clientSecret`/`redirectUrl`/`scope` without `connection_id`) keeps today's error.
135
+ - `resolveRequestHeaders(headers, serverConfig) → Promise<Boolean>`: existing `applyRequestHeaders`, then the OAuth bearer (overrides `Authorization`).
136
+ - `sendJSONRPCRequest` / `sendInitializedNotification` call `resolveRequestHeaders`; on HTTP 401 with `serverConfig.oauth` → `getAccessToken(..., { force: true })` and one retry.
137
+ - `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.
138
+ - `getCacheKey(url, projectId, connectionId?)`.
139
+
140
+ - [ ] **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.
141
+ - [ ] **Step 2: Run** → fail.
142
+ - [ ] **Step 3: Implement.**
143
+ - [ ] **Step 4: Run** the file plus `test/nativemcp.test.js test/mcpOAuthRoute.test.js` → pass.
144
+ - [ ] **Step 5: Commit** — `feat(mcp-oauth): bearer injection and 401 retry in mcpService`.
145
+
146
+ ### Task 6: docs and manual end-to-end
147
+
148
+ **Files:**
149
+ - Modify: `CHANGELOG.md` (unreleased entry), `docs/superpowers/specs/2026-11-10-mcp-oauth2-design.md` (status, any decision taken during implementation)
150
+
151
+ - [ ] **Step 1:** Run the reference server: `git clone https://github.com/modelcontextprotocol/example-remote-server && npm i && npm run dev:internal` (port 3232).
152
+ - [ ] **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`.
153
+ - [ ] **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.
154
+ - [ ] **Step 4:** Record results (what ran, what was mocked) in the spec's status line.
155
+ - [ ] **Step 5: Commit** — `docs(mcp-oauth): changelog and verification notes`.