@tiledesk/tiledesk-server 3.3.5 → 3.5.1
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.
- package/CHANGELOG.md +20 -0
- package/app.js +7 -0
- package/deploynew.sh +7 -1
- package/docs/activities-client.md +27 -0
- package/docs/mcp-oauth2-it.md +279 -0
- package/docs/mcp-oauth2.md +279 -0
- package/docs/numeric-input-validation.md +91 -0
- package/docs/superpowers/plans/2026-11-10-mcp-oauth2-server-it.md +155 -0
- package/docs/superpowers/plans/2026-11-10-mcp-oauth2-server.md +155 -0
- package/docs/superpowers/plans/2026-11-10-mcp-oauth2-tybot-it.md +63 -0
- package/docs/superpowers/plans/2026-11-10-mcp-oauth2-tybot.md +63 -0
- package/docs/superpowers/specs/2026-11-10-mcp-oauth2-design-it.md +207 -0
- package/docs/superpowers/specs/2026-11-10-mcp-oauth2-design.md +207 -0
- package/jobs.js +15 -0
- package/models/mcpOAuthConnection.js +131 -0
- package/models/request.js +8 -0
- package/package.json +1 -1
- package/pubmodules/activities/activityMessageUtil.js +137 -0
- package/pubmodules/activities/models/activity.js +2 -0
- package/pubmodules/activities/routes/activity.js +39 -11
- package/pubmodules/activities/test/execution-filter.test.js +133 -0
- package/pubmodules/activities/test/execution-messages.test.js +158 -0
- package/pubmodules/canned/cannedResponseRoute.js +6 -9
- package/pubmodules/events/eventRoute.js +6 -9
- package/pubmodules/executions-publisher/index.js +457 -0
- package/pubmodules/executions-publisher/test/audit-consumer.test.js +384 -0
- package/pubmodules/executions-publisher/test/executions-publisher.test.js +204 -0
- package/pubmodules/pubModulesManager.js +12 -0
- package/routes/answered.js +7 -3
- package/routes/campaigns.js +7 -3
- package/routes/department.js +14 -3
- package/routes/executions-refire.js +148 -0
- package/routes/faq.js +6 -14
- package/routes/filesp.js +9 -4
- package/routes/kb.js +40 -15
- package/routes/lead.js +23 -28
- package/routes/logs.js +8 -1
- package/routes/mcp.js +11 -8
- package/routes/mcpOAuth.js +133 -0
- package/routes/mcpOAuthCallback.js +75 -0
- package/routes/message.js +3 -1
- package/routes/messagesRoot.js +5 -18
- package/routes/project.js +57 -12
- package/routes/project_user.js +21 -4
- package/routes/property.js +18 -20
- package/routes/request.js +36 -45
- package/routes/roles.js +8 -18
- package/routes/segment.js +8 -18
- package/routes/subscription.js +4 -5
- package/routes/tag.js +6 -9
- package/routes/unanswered.js +7 -3
- package/routes/user-request.js +29 -34
- package/routes/webhook.js +120 -54
- package/services/mcpOAuthDiscovery.js +248 -0
- package/services/mcpOAuthGoogleScopes.js +55 -0
- package/services/mcpOAuthService.js +732 -0
- package/services/mcpService.js +111 -15
- package/services/requestService.js +4 -2
- package/services/webhookService.js +4 -2
- package/test/executions-refire.test.js +362 -0
- package/test/kbRoute.js +4 -7
- package/test/mcpOAuthDiscovery.test.js +331 -0
- package/test/mcpOAuthGoogleScopes.test.js +25 -0
- package/test/mcpOAuthRoute.test.js +455 -0
- package/test/mcpOAuthService.test.js +693 -0
- package/test/mcpOAuthUtils.test.js +348 -0
- package/test/mcpServiceOAuth.test.js +267 -0
- package/test/numericInput.js +137 -0
- package/test/requestRoute.js +57 -0
- package/test/webhookConversationRoute.js +51 -0
- package/utils/logRedactor.js +4 -2
- package/utils/mcpOAuthCrypto.js +69 -0
- package/utils/mcpOAuthPkce.js +20 -0
- package/utils/numericInput.js +200 -0
- 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,91 @@
|
|
|
1
|
+
# Endpoints protected by numeric validation
|
|
2
|
+
|
|
3
|
+
Starting vulnerability: **Insufficient Input Validation**. A client could send a negative number, or any value outside the field's domain, and the API accepted it.
|
|
4
|
+
|
|
5
|
+
An invalid value gets **422** with `{ "success": false, "msg": "..." }` and is neither saved nor used in queries. Negative values that belong to the domain are still accepted and are listed in the Rule column.
|
|
6
|
+
|
|
7
|
+
## Rating (reported endpoint)
|
|
8
|
+
|
|
9
|
+
| Method | Endpoint | Field | Rule |
|
|
10
|
+
| --- | --- | --- | --- |
|
|
11
|
+
| PATCH | `/:projectid/requests/:requestid/rating` | `rating` | integer from 1 to 5 |
|
|
12
|
+
| PATCH | `/:projectid/requests/:requestid/rating` | `rating_message` | string, if present |
|
|
13
|
+
| PATCH | `/:projectid/requests/:requestid` | `rating` | integer from 1 to 5 |
|
|
14
|
+
|
|
15
|
+
The `Request.rating` model rejects the same values on write too, through Mongoose validators (`min: 1`, `max: 5`, integer).
|
|
16
|
+
|
|
17
|
+
## Requests and messages
|
|
18
|
+
|
|
19
|
+
| Method | Endpoint | Field | Rule |
|
|
20
|
+
| --- | --- | --- | --- |
|
|
21
|
+
| POST | `/:projectid/requests` | message `status` | one of `-100, 0, 100, 150, 200, 250, 300`. `-100` is a failed send |
|
|
22
|
+
| PATCH | `/:projectid/requests/:requestid` | `status` | one of `50, 100, 150, 200, 300, 1000` |
|
|
23
|
+
| GET | `/:projectid/requests` | `limit`, `page` | `limit` integer ≥ 1; above 100 the default 40 is used. `page` integer ≥ 0 |
|
|
24
|
+
| GET | `/:projectid/requests` | `status` | `all` or a comma-separated list of request codes |
|
|
25
|
+
| GET | `/:projectid/requests` | `direction` | `-1` or `1` |
|
|
26
|
+
| GET | `/:projectid/requests/csv` | `page`, `status`, `direction` | same rules as the list |
|
|
27
|
+
| GET | `/:projectid/requests/me` | `limit`, `page`, `status`, `direction` | `limit` as above; `status` a single request code or `all`; `direction` `-1` or `1` |
|
|
28
|
+
| POST | `/:projectid/requests/:request_id/messages` | `status` | one of `-100, 0, 100, 150, 200, 250, 300` |
|
|
29
|
+
| GET | `/:projectid/messages` | `limit`, `page` | `limit` integer ≥ 1; above 50 the default 10 is used. `page` integer ≥ 0 |
|
|
30
|
+
| POST | `/:projectid/campaigns` | `status` | one of `-100, 0, 100, 150, 200, 250, 300` |
|
|
31
|
+
| POST | `/:projectid/campaigns/direct` | `status` | one of `-100, 0, 100, 150, 200, 250, 300` |
|
|
32
|
+
| POST | `/:projectid/campaigns/directDEPRECATED?` | `status` | one of `-100, 0, 100, 150, 200, 250, 300` |
|
|
33
|
+
|
|
34
|
+
## Project, departments, leads, properties
|
|
35
|
+
|
|
36
|
+
| Method | Endpoint | Field | Rule |
|
|
37
|
+
| --- | --- | --- | --- |
|
|
38
|
+
| PUT | `/projects/:projectid` | `versions` | integer from 0 to 99999999 |
|
|
39
|
+
| PUT | `/projects/:projectid` | `settings.max_agent_assigned_chat` | `-1` (no limit) or integer from 0 to 100000. Applies both to the dotted field and inside the `settings` object |
|
|
40
|
+
| PUT | `/projects/:projectid` | `settings.reassignment_delay` | integer from 0 to 315360000 |
|
|
41
|
+
| PUT | `/projects/:projectid` | `settings.email.config.port` | integer from 1 to 65535 |
|
|
42
|
+
| PATCH | `/projects/:projectid` | the same four fields | the same rules as PUT |
|
|
43
|
+
| PUT | `/:projectid/project_users` | `max_assigned_chat` | `-1` or integer from 0 to 100000 |
|
|
44
|
+
| PUT | `/:projectid/project_users` | `number_assigned_requests` | integer from 0 to 1000000 |
|
|
45
|
+
| PUT | `/:projectid/project_users/:project_userid` | `max_assigned_chat`, `number_assigned_requests` | the same rules |
|
|
46
|
+
| POST | `/:projectid/departments` | `status` | one of `-1, 0, 1`. `-1` is a hidden department |
|
|
47
|
+
| PUT | `/:projectid/departments/:departmentid` | `status` | one of `-1, 0, 1` |
|
|
48
|
+
| PATCH | `/:projectid/departments/:departmentid` | `status` | one of `-1, 0, 1` |
|
|
49
|
+
| PUT | `/:projectid/leads/:leadid` | `status` | one of `50, 100, 1000` |
|
|
50
|
+
| GET | `/:projectid/leads` | `limit`, `page`, `status`, `direction` | `limit` from 1 to 1000; `page` ≥ 0; `status` a lead code; `direction` `-1` or `1` |
|
|
51
|
+
| GET | `/:projectid/leads/csv` | `page`, `direction` | `page` ≥ 0; `direction` `-1` or `1` |
|
|
52
|
+
| PUT | `/:projectid/properties/:propertyid` | `status` | one of `100, 1000` |
|
|
53
|
+
| GET | `/:projectid/properties` | `limit`, `page`, `status`, `direction` | `limit` from 1 to 1000; `page` ≥ 0; `status` `100` or `1000`; `direction` `-1` or `1` |
|
|
54
|
+
|
|
55
|
+
## Knowledge base, FAQ, files, logs
|
|
56
|
+
|
|
57
|
+
| Method | Endpoint | Field | Rule |
|
|
58
|
+
| --- | --- | --- | --- |
|
|
59
|
+
| GET | `/:projectid/kb` | `limit`, `page`, `status`, `direction` | `limit` from 1 to 1000; `page` ≥ 0; `status` integer from `-1` to 10000; `direction` `-1` or `1` |
|
|
60
|
+
| GET | `/:projectid/kb/namespace/export/:id` | `status` | integer from `-1` to 10000 |
|
|
61
|
+
| POST | `/:projectid/kb` | `scrape_type` | one of `0, 1, 2, 4` |
|
|
62
|
+
| POST | `/:projectid/kb/multi` | `scrape_type` | one of `0, 1, 2, 4` |
|
|
63
|
+
| POST | `/:projectid/kb/sitemap/import` | `scrape_type` | one of `0, 1, 2, 4` |
|
|
64
|
+
| POST | `/:projectid/kb/namespace/import/:id` | `contents[].scrape_type` | one of `0, 1, 2, 4` |
|
|
65
|
+
| GET | `/:projectid/kb/unanswered/:namespace` | `limit`, `page`, `direction` | `limit` from 1 to 100; `page` ≥ 0; `direction` `-1` or `1` |
|
|
66
|
+
| GET | `/:projectid/kb/answered/:namespace` | `limit`, `page`, `direction` | `limit` from 1 to 100; `page` ≥ 0; `direction` `-1` or `1` |
|
|
67
|
+
| GET | `/:projectid/faq` | `limit`, `page` | `limit` from 1 to 10000; `page` ≥ 0 |
|
|
68
|
+
| GET | `/:projectid/intents` | `limit`, `page` | same route as `/faq` |
|
|
69
|
+
| POST | `/:projectid/files/assets` | `expiration` | seconds, integer from 1 to 315360000. If missing, the file does not expire |
|
|
70
|
+
| POST | `/logs/whatsapp` | `status_code` | integer from 0 to 999, required |
|
|
71
|
+
| POST | `/:projectid/logs/whatsapp` | `status_code` | integer from 0 to 999, required |
|
|
72
|
+
|
|
73
|
+
## Lists, sorting and activities
|
|
74
|
+
|
|
75
|
+
| Method | Endpoint | Field | Rule |
|
|
76
|
+
| --- | --- | --- | --- |
|
|
77
|
+
| GET | `/:projectid/roles` | `limit`, `page`, `direction` | `limit` from 1 to 1000; `page` ≥ 0; `direction` `-1` or `1` |
|
|
78
|
+
| GET | `/:projectid/segments` | `limit`, `page`, `direction` | `limit` from 1 to 1000; `page` ≥ 0; `direction` `-1` or `1` |
|
|
79
|
+
| GET | `/:projectid/tags` | `page`, `direction` | `page` ≥ 0; `direction` `-1` or `1` |
|
|
80
|
+
| GET | `/:projectid/subscriptions/history` | `page` | integer ≥ 0 |
|
|
81
|
+
| GET | `/:projectid/canned` | `page`, `direction` | `page` ≥ 0; `direction` `-1` or `1` |
|
|
82
|
+
| GET | `/:projectid/events` | `page`, `direction` | `page` ≥ 0; `direction` `-1` or `1` |
|
|
83
|
+
| GET | `/:projectid/activities` | `page`, `direction` | `page` ≥ 0; `direction` `-1` or `1`. The `limit` of this list was already capped |
|
|
84
|
+
| GET | `/:projectid/activities/csv` | `page`, `direction` | `page` ≥ 0; `direction` `-1` or `1` |
|
|
85
|
+
|
|
86
|
+
## Already safe, not changed
|
|
87
|
+
|
|
88
|
+
These lists already discarded negative `page` and `limit` values, bringing them back into range:
|
|
89
|
+
|
|
90
|
+
- `GET /:projectid/agent-prompts`
|
|
91
|
+
- `GET /:projectid/modules/ai-generations/agents/:id_faq_kb/revisions`
|
|
@@ -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`.
|