@tiledesk/tiledesk-server 3.3.5 → 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 +17 -0
  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 +1 -1
  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,732 @@
1
+ 'use strict';
2
+
3
+ const crypto = require('crypto');
4
+ const mongoose = require('mongoose');
5
+ const axios = require('axios').default;
6
+ const winston = require('../config/winston');
7
+ const McpOAuthConnection = require('../models/mcpOAuthConnection');
8
+ const mcpOAuthCrypto = require('../utils/mcpOAuthCrypto');
9
+ const pkce = require('../utils/mcpOAuthPkce');
10
+ const outboundUrlGuard = require('../utils/outboundUrlGuard');
11
+ const discovery = require('./mcpOAuthDiscovery');
12
+ const googleScopes = require('./mcpOAuthGoogleScopes');
13
+
14
+ const STATE_TTL_S = 600;
15
+ const LOCK_TTL_S = 30;
16
+ const REFRESH_WINDOW_S = 300;
17
+ const LOCK_WAIT_MS = 5000;
18
+ const LOCK_POLL_MS = 250;
19
+ const GOOGLE_TIMEOUT_MS = 10000;
20
+
21
+ const MODES = ['mcp', 'google', 'manual'];
22
+ const AUTH_METHODS = ['client_secret_basic', 'client_secret_post', 'none'];
23
+
24
+ const GOOGLE = {
25
+ issuer: 'https://accounts.google.com',
26
+ authorization_endpoint: 'https://accounts.google.com/o/oauth2/v2/auth',
27
+ token_endpoint: 'https://oauth2.googleapis.com/token',
28
+ revocation_endpoint: 'https://oauth2.googleapis.com/revoke'
29
+ };
30
+
31
+ const RELEASE_LOCK_SCRIPT = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
32
+
33
+ const stateKey = (state) => 'mcp_oauth:state:' + state;
34
+ const lockKey = (connectionId) => 'mcp_oauth:refresh_lock:' + connectionId;
35
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
36
+
37
+ function oauthError(status, code, message) {
38
+ const error = new Error(message);
39
+ error.status = status;
40
+ error.code = code;
41
+ return error;
42
+ }
43
+
44
+ const needsReauth = (message) => oauthError(409, 'needs_reauth', message || 'The MCP OAuth connection must be authorized again');
45
+
46
+ function present(value) {
47
+ return value !== undefined && value !== null && String(value).trim() !== '';
48
+ }
49
+
50
+ function normalizeScopes(scopes) {
51
+ if (Array.isArray(scopes)) {
52
+ return scopes.map((scope) => String(scope).trim()).filter(Boolean);
53
+ }
54
+ if (typeof scopes === 'string') {
55
+ return scopes.split(/\s+/).filter(Boolean);
56
+ }
57
+ return [];
58
+ }
59
+
60
+ function parseUrl(value, field) {
61
+ try {
62
+ return new URL(value);
63
+ } catch (error) {
64
+ throw oauthError(400, 'bad_request', "Invalid URL in field '" + field + "'");
65
+ }
66
+ }
67
+
68
+ function assertBrowserUrl(value, field) {
69
+ const url = parseUrl(value, field);
70
+ const insecure = process.env.MCP_OAUTH_ALLOW_INSECURE_URLS === 'true';
71
+ if (url.protocol !== 'https:' && !(insecure && url.protocol === 'http:')) {
72
+ throw oauthError(400, 'bad_request', "Field '" + field + "' must use https");
73
+ }
74
+ }
75
+
76
+ function idOf(connection) {
77
+ return connection._id.toString();
78
+ }
79
+
80
+ function timeOf(date) {
81
+ return date ? new Date(date).getTime() : 0;
82
+ }
83
+
84
+ function isFresh(connection, now) {
85
+ if (!connection.access_token_enc) {
86
+ return false;
87
+ }
88
+ if (!connection.expires_at) {
89
+ return true;
90
+ }
91
+ return timeOf(connection.expires_at) - (now || Date.now()) > REFRESH_WINDOW_S * 1000;
92
+ }
93
+
94
+ function isUnexpired(connection) {
95
+ return !!connection.access_token_enc && (!connection.expires_at || timeOf(connection.expires_at) > Date.now());
96
+ }
97
+
98
+ function tokenView(connection) {
99
+ return {
100
+ access_token: mcpOAuthCrypto.decrypt(connection.access_token_enc),
101
+ token_type: connection.token_type || 'Bearer',
102
+ expires_at: connection.expires_at || null
103
+ };
104
+ }
105
+
106
+ class McpOAuthService {
107
+
108
+ constructor() {
109
+ this.tdCache = undefined;
110
+ this.memoryStates = new Map();
111
+ this.inflightRefreshes = new Map();
112
+ }
113
+
114
+ setTdCache(tdCache) {
115
+ this.tdCache = tdCache;
116
+ }
117
+
118
+ isConfigured() {
119
+ return mcpOAuthCrypto.isConfigured();
120
+ }
121
+
122
+ assertConfigured() {
123
+ if (!this.isConfigured()) {
124
+ throw oauthError(503, 'not_configured', 'MCP OAuth is not available on this installation');
125
+ }
126
+ }
127
+
128
+ googleConfigured() {
129
+ return !!(process.env.MCP_OAUTH_GOOGLE_CLIENT_ID && process.env.MCP_OAUTH_GOOGLE_CLIENT_SECRET);
130
+ }
131
+
132
+ redirectUri() {
133
+ const base = process.env.MCP_OAUTH_REDIRECT_BASE_URL || process.env.API_URL;
134
+ if (!base) {
135
+ throw oauthError(503, 'not_configured', 'MCP OAuth redirect URL is not configured on this installation');
136
+ }
137
+ return String(base).replace(/\/+$/, '') + '/oauth2/mcp/callback';
138
+ }
139
+
140
+ validateReturnUrl(returnUrl) {
141
+ if (returnUrl === undefined || returnUrl === null || returnUrl === '') {
142
+ return undefined;
143
+ }
144
+ const url = parseUrl(returnUrl, 'return_url');
145
+ const allowed = String(process.env.MCP_OAUTH_RETURN_ORIGINS || '')
146
+ .split(',')
147
+ .map((origin) => origin.trim().replace(/\/+$/, ''))
148
+ .filter(Boolean);
149
+ if (!allowed.includes(url.origin)) {
150
+ throw oauthError(400, 'bad_request', 'return_url is not allowed');
151
+ }
152
+ return url.toString();
153
+ }
154
+
155
+ // ---- state (single use) ----
156
+
157
+ async saveState(state, value) {
158
+ if (this.tdCache) {
159
+ await this.tdCache.setJSON(stateKey(state), value, { EX: STATE_TTL_S });
160
+ return;
161
+ }
162
+ this.memoryStates.set(state, { value, expiresAt: Date.now() + STATE_TTL_S * 1000 });
163
+ }
164
+
165
+ async takeState(state) {
166
+ if (this.tdCache) {
167
+ const key = stateKey(state);
168
+ const replies = await new Promise((resolve, reject) => {
169
+ this.tdCache.getClient().multi().get(key).del(key).exec((err, result) => (err ? reject(err) : resolve(result)));
170
+ });
171
+ return replies && replies[0] ? JSON.parse(replies[0]) : null;
172
+ }
173
+ const entry = this.memoryStates.get(state);
174
+ this.memoryStates.delete(state);
175
+ return entry && entry.expiresAt > Date.now() ? entry.value : null;
176
+ }
177
+
178
+ // ---- refresh lock ----
179
+
180
+ async acquireLock(connectionId, owner) {
181
+ if (!this.tdCache) {
182
+ return true;
183
+ }
184
+ try {
185
+ return await this.tdCache.setNX(lockKey(connectionId), owner, LOCK_TTL_S);
186
+ } catch (error) {
187
+ winston.warn('MCP OAuth refresh lock unavailable, refreshing without it: ' + error.message);
188
+ return true;
189
+ }
190
+ }
191
+
192
+ async releaseLock(connectionId, owner) {
193
+ if (!this.tdCache) {
194
+ return;
195
+ }
196
+ await new Promise((resolve) => {
197
+ this.tdCache.getClient().eval(RELEASE_LOCK_SCRIPT, 1, lockKey(connectionId), owner, (err) => {
198
+ if (err) {
199
+ winston.warn('MCP OAuth refresh lock not released: ' + err.message);
200
+ }
201
+ resolve();
202
+ });
203
+ });
204
+ }
205
+
206
+ // ---- connections ----
207
+
208
+ async getConnection(id_project, connection_id) {
209
+ if (!mongoose.isValidObjectId(connection_id)) {
210
+ throw oauthError(404, 'not_found', 'MCP OAuth connection not found');
211
+ }
212
+ const connection = await McpOAuthConnection.findOne({ _id: connection_id, id_project: String(id_project) });
213
+ if (!connection) {
214
+ throw oauthError(404, 'not_found', 'MCP OAuth connection not found');
215
+ }
216
+ return connection;
217
+ }
218
+
219
+ async listConnections(id_project) {
220
+ return McpOAuthConnection.find({ id_project: String(id_project) }).sort({ createdAt: 1 });
221
+ }
222
+
223
+ clientCredentials(connection) {
224
+ if (connection.mode === 'google') {
225
+ if (!this.googleConfigured()) {
226
+ throw oauthError(503, 'not_configured', 'Google OAuth is not configured on this installation');
227
+ }
228
+ return {
229
+ client_id: process.env.MCP_OAUTH_GOOGLE_CLIENT_ID,
230
+ client_secret: process.env.MCP_OAUTH_GOOGLE_CLIENT_SECRET,
231
+ method: 'client_secret_post'
232
+ };
233
+ }
234
+ if (!connection.client_id) {
235
+ throw needsReauth('The MCP OAuth client is not registered; authorize the connection again');
236
+ }
237
+ const client_secret = mcpOAuthCrypto.decrypt(connection.client_secret_enc);
238
+ return {
239
+ client_id: connection.client_id,
240
+ client_secret,
241
+ method: connection.token_endpoint_auth_method || (client_secret ? 'client_secret_post' : 'none')
242
+ };
243
+ }
244
+
245
+ /** Form-encoded POST to a token or revocation endpoint with the client authentication of the connection. */
246
+ async postForm(connection, url, params) {
247
+ const credentials = this.clientCredentials(connection);
248
+ const body = new URLSearchParams(params);
249
+ const headers = {
250
+ 'Content-Type': 'application/x-www-form-urlencoded',
251
+ 'Accept': 'application/json'
252
+ };
253
+
254
+ if (credentials.method === 'client_secret_basic') {
255
+ const basic = encodeURIComponent(credentials.client_id) + ':' + encodeURIComponent(credentials.client_secret || '');
256
+ headers['Authorization'] = 'Basic ' + Buffer.from(basic).toString('base64');
257
+ } else {
258
+ body.set('client_id', credentials.client_id);
259
+ if (credentials.method === 'client_secret_post' && credentials.client_secret) {
260
+ body.set('client_secret', credentials.client_secret);
261
+ }
262
+ }
263
+
264
+ let options;
265
+ if (connection.mode === 'google') {
266
+ options = { maxRedirects: 0, timeout: GOOGLE_TIMEOUT_MS };
267
+ } else {
268
+ await outboundUrlGuard.assertAllowed(url);
269
+ options = outboundUrlGuard.httpOptions();
270
+ }
271
+
272
+ try {
273
+ return await axios({
274
+ ...options,
275
+ method: 'POST',
276
+ url,
277
+ headers,
278
+ data: body.toString(),
279
+ validateStatus: () => true
280
+ });
281
+ } catch (error) {
282
+ if (error.status) {
283
+ throw error;
284
+ }
285
+ const networkError = oauthError(503, 'provider_error', 'Cannot reach the OAuth provider: ' + error.message);
286
+ networkError.oauth_error = 'network_error';
287
+ throw networkError;
288
+ }
289
+ }
290
+
291
+ async tokenRequest(connection, params) {
292
+ const tokenParams = { ...params };
293
+ if (connection.mode === 'mcp' && connection.resource) {
294
+ tokenParams.resource = connection.resource;
295
+ }
296
+
297
+ const response = await this.postForm(connection, connection.token_endpoint, tokenParams);
298
+
299
+ let data = response.data;
300
+ if (typeof data === 'string') {
301
+ try {
302
+ data = JSON.parse(data);
303
+ } catch (error) {
304
+ data = {};
305
+ }
306
+ }
307
+ data = data || {};
308
+
309
+ if (response.status >= 200 && response.status < 300 && data.access_token) {
310
+ return data;
311
+ }
312
+
313
+ const oauthCode = data.error || ('http_' + response.status);
314
+ const error = oauthError(503, 'provider_error', 'OAuth token request failed: ' + (data.error_description || oauthCode));
315
+ error.oauth_error = oauthCode;
316
+ throw error;
317
+ }
318
+
319
+ applyTokens(connection, data) {
320
+ connection.access_token_enc = mcpOAuthCrypto.encrypt(data.access_token);
321
+ connection.token_type = !data.token_type || String(data.token_type).toLowerCase() === 'bearer' ? 'Bearer' : data.token_type;
322
+ connection.expires_at = data.expires_in ? new Date(Date.now() + Number(data.expires_in) * 1000) : null;
323
+ if (data.refresh_token) {
324
+ connection.refresh_token_enc = mcpOAuthCrypto.encrypt(data.refresh_token);
325
+ }
326
+ if (data.scope) {
327
+ connection.granted_scopes = normalizeScopes(data.scope);
328
+ }
329
+ connection.last_refresh_at = new Date();
330
+ }
331
+
332
+ async markNeedsReauth(connection, code, message) {
333
+ connection.status = 'needs_reauth';
334
+ connection.last_error = { code, message, at: new Date() };
335
+ await connection.save();
336
+ }
337
+
338
+ // ---- authorization code flow ----
339
+
340
+ async configureMode(connection, mode, body, redirectUri) {
341
+ let scopes = normalizeScopes(body.scopes);
342
+ const extraParams = {};
343
+
344
+ if (mode === 'mcp') {
345
+ const metadata = await discovery.discover(connection.server_url);
346
+ connection.resource = metadata.resource;
347
+ connection.issuer = metadata.issuer;
348
+ connection.authorization_endpoint = metadata.authorization_endpoint;
349
+ connection.token_endpoint = metadata.token_endpoint;
350
+ connection.revocation_endpoint = metadata.revocation_endpoint;
351
+ connection.registration_endpoint = metadata.registration_endpoint;
352
+ if (scopes.length === 0 && metadata.scopes_supported) {
353
+ scopes = metadata.scopes_supported;
354
+ }
355
+ if (!connection.client_id) {
356
+ const client = await discovery.register(metadata, redirectUri);
357
+ connection.client_id = client.client_id;
358
+ connection.client_secret_enc = mcpOAuthCrypto.encrypt(client.client_secret);
359
+ connection.token_endpoint_auth_method = client.token_endpoint_auth_method;
360
+ connection.client_registered_at = new Date();
361
+ }
362
+ } else if (mode === 'google') {
363
+ if (!this.googleConfigured()) {
364
+ throw oauthError(503, 'not_configured', 'Google OAuth is not configured on this installation');
365
+ }
366
+ if (scopes.length === 0) {
367
+ scopes = googleScopes.defaultScopesFor(connection.server_url);
368
+ }
369
+ if (scopes.length === 0) {
370
+ throw oauthError(400, 'bad_request', "Missing required field 'scopes': no default scopes are known for this Google MCP server");
371
+ }
372
+ Object.assign(connection, GOOGLE);
373
+ extraParams.access_type = 'offline';
374
+ extraParams.prompt = 'consent';
375
+ extraParams.include_granted_scopes = 'true';
376
+ } else {
377
+ // An existing connection keeps the client already stored. A later edit can send only
378
+ // the fields that changed (for example the scopes) and the rest stay as they are.
379
+ const manual = body.manual || {};
380
+ const authorizationEndpoint = present(manual.authorization_endpoint) ? manual.authorization_endpoint : connection.authorization_endpoint;
381
+ const tokenEndpoint = present(manual.token_endpoint) ? manual.token_endpoint : connection.token_endpoint;
382
+ const clientId = present(manual.client_id) ? manual.client_id : connection.client_id;
383
+ for (const [field, value] of [
384
+ ['authorization_endpoint', authorizationEndpoint],
385
+ ['token_endpoint', tokenEndpoint],
386
+ ['client_id', clientId]
387
+ ]) {
388
+ if (!value) {
389
+ throw oauthError(400, 'bad_request', "Missing required field 'manual." + field + "'");
390
+ }
391
+ }
392
+ if (manual.token_endpoint_auth_method && !AUTH_METHODS.includes(manual.token_endpoint_auth_method)) {
393
+ throw oauthError(400, 'bad_request', "Invalid field 'manual.token_endpoint_auth_method'");
394
+ }
395
+ assertBrowserUrl(authorizationEndpoint, 'manual.authorization_endpoint');
396
+ await outboundUrlGuard.assertAllowed(tokenEndpoint);
397
+ connection.issuer = parseUrl(authorizationEndpoint, 'manual.authorization_endpoint').origin;
398
+ connection.authorization_endpoint = authorizationEndpoint;
399
+ connection.token_endpoint = tokenEndpoint;
400
+ connection.client_id = clientId;
401
+ if (present(manual.revocation_endpoint)) {
402
+ await outboundUrlGuard.assertAllowed(manual.revocation_endpoint);
403
+ connection.revocation_endpoint = manual.revocation_endpoint;
404
+ }
405
+ if (present(manual.client_secret)) {
406
+ connection.client_secret_enc = mcpOAuthCrypto.encrypt(manual.client_secret);
407
+ }
408
+ if (manual.token_endpoint_auth_method) {
409
+ connection.token_endpoint_auth_method = manual.token_endpoint_auth_method;
410
+ } else if (!connection.token_endpoint_auth_method) {
411
+ connection.token_endpoint_auth_method = connection.client_secret_enc ? 'client_secret_post' : 'none';
412
+ }
413
+ }
414
+
415
+ connection.scopes = scopes;
416
+ return extraParams;
417
+ }
418
+
419
+ resetForMode(connection, mode) {
420
+ connection.mode = mode;
421
+ connection.status = 'pending';
422
+ for (const field of [
423
+ 'client_id', 'client_secret_enc', 'client_registered_at', 'resource', 'issuer', 'authorization_endpoint',
424
+ 'token_endpoint', 'revocation_endpoint', 'registration_endpoint', 'token_endpoint_auth_method',
425
+ 'access_token_enc', 'refresh_token_enc', 'token_type', 'expires_at', 'last_refresh_at'
426
+ ]) {
427
+ connection[field] = undefined;
428
+ }
429
+ connection.granted_scopes = [];
430
+ }
431
+
432
+ /** Starts the authorization code + PKCE flow; returns the URL to open in the browser. */
433
+ async startAuthorization(id_project, user_id, body) {
434
+ this.assertConfigured();
435
+ body = body || {};
436
+ const { mode, name } = body;
437
+
438
+ if (!MODES.includes(mode)) {
439
+ throw oauthError(400, 'bad_request', "Invalid field 'mode': use one of " + MODES.join(', '));
440
+ }
441
+ if (!body.server_url) {
442
+ throw oauthError(400, 'bad_request', "Missing required field 'server_url'");
443
+ }
444
+ const serverUrl = parseUrl(body.server_url, 'server_url').toString();
445
+ const returnUrl = this.validateReturnUrl(body.return_url);
446
+ const redirectUri = this.redirectUri();
447
+
448
+ let connection = await McpOAuthConnection.findOne({ id_project: String(id_project), server_url: serverUrl });
449
+ if (!connection) {
450
+ connection = new McpOAuthConnection({
451
+ id_project: String(id_project),
452
+ server_url: serverUrl,
453
+ mode,
454
+ status: 'pending',
455
+ created_by: user_id ? String(user_id) : undefined
456
+ });
457
+ } else if (connection.mode !== mode) {
458
+ this.resetForMode(connection, mode);
459
+ }
460
+ if (name) {
461
+ connection.name = name;
462
+ } else if (!connection.name) {
463
+ connection.name = new URL(serverUrl).host;
464
+ }
465
+
466
+ const extraParams = await this.configureMode(connection, mode, body, redirectUri);
467
+ await connection.save();
468
+
469
+ const state = pkce.randomState();
470
+ const codeVerifier = pkce.createVerifier();
471
+ await this.saveState(state, {
472
+ id_project: String(id_project),
473
+ connection_id: idOf(connection),
474
+ code_verifier: codeVerifier,
475
+ redirect_uri: redirectUri,
476
+ return_url: returnUrl,
477
+ user_id: user_id ? String(user_id) : undefined
478
+ });
479
+
480
+ const credentials = this.clientCredentials(connection);
481
+ const url = new URL(connection.authorization_endpoint);
482
+ url.searchParams.set('response_type', 'code');
483
+ url.searchParams.set('client_id', credentials.client_id);
484
+ url.searchParams.set('redirect_uri', redirectUri);
485
+ url.searchParams.set('code_challenge', pkce.challengeOf(codeVerifier));
486
+ url.searchParams.set('code_challenge_method', 'S256');
487
+ url.searchParams.set('state', state);
488
+ if (connection.scopes.length > 0) {
489
+ url.searchParams.set('scope', connection.scopes.join(' '));
490
+ }
491
+ if (mode === 'mcp' && connection.resource) {
492
+ url.searchParams.set('resource', connection.resource);
493
+ }
494
+ for (const [key, value] of Object.entries(extraParams)) {
495
+ url.searchParams.set(key, value);
496
+ }
497
+
498
+ return { authorization_url: url.toString(), connection_id: idOf(connection) };
499
+ }
500
+
501
+ /**
502
+ * Handles the provider redirect. Throws only for a missing/expired state; provider
503
+ * errors are returned as `error` so the caller can send the user back to return_url.
504
+ */
505
+ async completeAuthorization({ code, state, error, error_description } = {}) {
506
+ this.assertConfigured();
507
+ if (!state) {
508
+ throw oauthError(400, 'bad_request', 'Missing state');
509
+ }
510
+ const saved = await this.takeState(state);
511
+ if (!saved) {
512
+ throw oauthError(400, 'bad_request', 'Invalid or expired state');
513
+ }
514
+
515
+ const connection = await this.getConnection(saved.id_project, saved.connection_id);
516
+ const result = { connection, return_url: saved.return_url };
517
+
518
+ if (error || !code) {
519
+ const errorCode = error || 'missing_code';
520
+ connection.last_error = { code: errorCode, message: error_description || errorCode, at: new Date() };
521
+ await connection.save();
522
+ return { ...result, error: errorCode };
523
+ }
524
+
525
+ try {
526
+ const data = await this.tokenRequest(connection, {
527
+ grant_type: 'authorization_code',
528
+ code,
529
+ redirect_uri: saved.redirect_uri,
530
+ code_verifier: saved.code_verifier
531
+ });
532
+ this.applyTokens(connection, data);
533
+ connection.status = 'active';
534
+ connection.last_error = undefined;
535
+ await connection.save();
536
+ return result;
537
+ } catch (err) {
538
+ const errorCode = err.oauth_error || err.code || 'token_exchange_failed';
539
+ winston.warn('MCP OAuth code exchange failed for connection ' + idOf(connection) + ': ' + err.message);
540
+ if (errorCode === 'invalid_client' && connection.mode === 'mcp') {
541
+ connection.client_id = undefined;
542
+ connection.client_secret_enc = undefined;
543
+ connection.client_registered_at = undefined;
544
+ }
545
+ connection.last_error = { code: errorCode, message: err.message, at: new Date() };
546
+ await connection.save();
547
+ return { ...result, error: errorCode };
548
+ }
549
+ }
550
+
551
+ // ---- tokens ----
552
+
553
+ /** A valid access token for the connection, refreshed when it expires within REFRESH_WINDOW_S. */
554
+ async getAccessToken(id_project, connection_id, { force } = {}) {
555
+ this.assertConfigured();
556
+ const connection = await this.getConnection(id_project, connection_id);
557
+ if (connection.status !== 'active') {
558
+ throw needsReauth();
559
+ }
560
+ if (!force && isFresh(connection)) {
561
+ return tokenView(connection);
562
+ }
563
+ return this.refresh(connection);
564
+ }
565
+
566
+ refresh(connection) {
567
+ const id = idOf(connection);
568
+ if (this.inflightRefreshes.has(id)) {
569
+ return this.inflightRefreshes.get(id);
570
+ }
571
+ const pending = this.refreshWithLock(connection).finally(() => this.inflightRefreshes.delete(id));
572
+ this.inflightRefreshes.set(id, pending);
573
+ return pending;
574
+ }
575
+
576
+ async refreshWithLock(connection) {
577
+ const id = idOf(connection);
578
+ const seenRefreshAt = timeOf(connection.last_refresh_at);
579
+ const owner = crypto.randomBytes(16).toString('hex');
580
+
581
+ if (!(await this.acquireLock(id, owner))) {
582
+ return this.waitForRefresh(connection, seenRefreshAt);
583
+ }
584
+
585
+ try {
586
+ const current = await McpOAuthConnection.findById(connection._id);
587
+ if (!current) {
588
+ throw oauthError(404, 'not_found', 'MCP OAuth connection not found');
589
+ }
590
+ if (current.status !== 'active') {
591
+ throw needsReauth();
592
+ }
593
+ if (timeOf(current.last_refresh_at) > seenRefreshAt && isFresh(current)) {
594
+ return tokenView(current);
595
+ }
596
+ if (!current.refresh_token_enc) {
597
+ await this.markNeedsReauth(current, 'no_refresh_token', 'The access token expired and the provider gave no refresh token');
598
+ throw needsReauth();
599
+ }
600
+
601
+ let data;
602
+ try {
603
+ data = await this.tokenRequest(current, {
604
+ grant_type: 'refresh_token',
605
+ refresh_token: mcpOAuthCrypto.decrypt(current.refresh_token_enc)
606
+ });
607
+ } catch (error) {
608
+ if (error.oauth_error === 'invalid_grant' || error.oauth_error === 'invalid_client') {
609
+ if (error.oauth_error === 'invalid_client' && current.mode === 'mcp') {
610
+ current.client_id = undefined;
611
+ current.client_secret_enc = undefined;
612
+ current.client_registered_at = undefined;
613
+ }
614
+ await this.markNeedsReauth(current, error.oauth_error, error.message);
615
+ throw needsReauth();
616
+ }
617
+ if (error.code === 'needs_reauth') {
618
+ throw error;
619
+ }
620
+ current.last_error = { code: error.oauth_error || error.code || 'provider_error', message: error.message, at: new Date() };
621
+ await current.save();
622
+ throw oauthError(503, 'provider_error', error.message);
623
+ }
624
+
625
+ this.applyTokens(current, data);
626
+ current.last_error = undefined;
627
+ await current.save();
628
+ return tokenView(current);
629
+ } finally {
630
+ await this.releaseLock(id, owner);
631
+ }
632
+ }
633
+
634
+ async waitForRefresh(connection, seenRefreshAt) {
635
+ const deadline = Date.now() + LOCK_WAIT_MS;
636
+ let latest = connection;
637
+ while (Date.now() < deadline) {
638
+ await sleep(LOCK_POLL_MS);
639
+ latest = await McpOAuthConnection.findById(connection._id);
640
+ if (!latest) {
641
+ throw oauthError(404, 'not_found', 'MCP OAuth connection not found');
642
+ }
643
+ if (latest.status !== 'active') {
644
+ throw needsReauth();
645
+ }
646
+ if (timeOf(latest.last_refresh_at) > seenRefreshAt && isUnexpired(latest)) {
647
+ return tokenView(latest);
648
+ }
649
+ }
650
+ if (isUnexpired(latest)) {
651
+ return tokenView(latest);
652
+ }
653
+ throw oauthError(503, 'provider_error', 'MCP OAuth token refresh in progress, try again');
654
+ }
655
+
656
+ /** Refreshes one connection by id (scheduler API, no project scope). */
657
+ async refreshConnection(connection_id) {
658
+ this.assertConfigured();
659
+ if (!mongoose.isValidObjectId(connection_id)) {
660
+ throw oauthError(404, 'not_found', 'MCP OAuth connection not found');
661
+ }
662
+ const connection = await McpOAuthConnection.findById(connection_id).select('id_project');
663
+ if (!connection) {
664
+ throw oauthError(404, 'not_found', 'MCP OAuth connection not found');
665
+ }
666
+ return this.getAccessToken(connection.id_project, connection_id, { force: true });
667
+ }
668
+
669
+ /** Refreshes every active connection whose access token expires within withinSeconds. */
670
+ async refreshDue(withinSeconds) {
671
+ this.assertConfigured();
672
+ const limit = new Date(Date.now() + withinSeconds * 1000);
673
+ const due = await McpOAuthConnection.find({
674
+ status: 'active',
675
+ refresh_token_enc: { $exists: true, $ne: null },
676
+ expires_at: { $ne: null, $lte: limit }
677
+ }).select('_id id_project');
678
+
679
+ const result = { refreshed: 0, failed: 0, needs_reauth: 0 };
680
+ for (const connection of due) {
681
+ try {
682
+ await this.getAccessToken(connection.id_project, connection._id, { force: true });
683
+ result.refreshed++;
684
+ } catch (error) {
685
+ if (error.code === 'needs_reauth') {
686
+ result.needs_reauth++;
687
+ } else {
688
+ result.failed++;
689
+ }
690
+ winston.warn('MCP OAuth scheduled refresh failed for connection ' + connection._id + ': ' + error.message);
691
+ }
692
+ }
693
+ return result;
694
+ }
695
+
696
+ // ---- revocation ----
697
+
698
+ async revoke(connection, token, hint) {
699
+ const response = await this.postForm(connection, connection.revocation_endpoint, { token, token_type_hint: hint });
700
+ return response.status >= 200 && response.status < 300;
701
+ }
702
+
703
+ /** Best-effort revocation at the provider, then deletes the connection. */
704
+ async revokeAndDelete(id_project, connection_id) {
705
+ this.assertConfigured();
706
+ const connection = await this.getConnection(id_project, connection_id);
707
+
708
+ let revoked = false;
709
+ if (connection.revocation_endpoint && (connection.refresh_token_enc || connection.access_token_enc)) {
710
+ try {
711
+ if (connection.refresh_token_enc) {
712
+ revoked = await this.revoke(connection, mcpOAuthCrypto.decrypt(connection.refresh_token_enc), 'refresh_token');
713
+ }
714
+ if (connection.access_token_enc) {
715
+ const accessRevoked = await this.revoke(connection, mcpOAuthCrypto.decrypt(connection.access_token_enc), 'access_token');
716
+ revoked = connection.refresh_token_enc ? revoked : accessRevoked;
717
+ }
718
+ } catch (error) {
719
+ winston.warn('MCP OAuth revocation failed for connection ' + idOf(connection) + ': ' + error.message);
720
+ }
721
+ }
722
+
723
+ await McpOAuthConnection.deleteOne({ _id: connection._id });
724
+ return { revoked };
725
+ }
726
+ }
727
+
728
+ const mcpOAuthService = new McpOAuthService();
729
+
730
+ module.exports = mcpOAuthService;
731
+ module.exports.McpOAuthService = McpOAuthService;
732
+ module.exports.REFRESH_WINDOW_S = REFRESH_WINDOW_S;