@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.
- package/CHANGELOG.md +20 -1
- package/app.js +7 -0
- package/docs/activities-client.md +27 -0
- package/docs/mcp-oauth2-it.md +279 -0
- package/docs/mcp-oauth2.md +279 -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/package.json +2 -2
- package/pubmodules/activities/activityMessageUtil.js +137 -0
- package/pubmodules/activities/models/activity.js +2 -0
- package/pubmodules/activities/routes/activity.js +30 -1
- package/pubmodules/activities/test/execution-filter.test.js +133 -0
- package/pubmodules/activities/test/execution-messages.test.js +158 -0
- 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/executions-refire.js +148 -0
- package/routes/mcp.js +11 -8
- package/routes/mcpOAuth.js +133 -0
- package/routes/mcpOAuthCallback.js +75 -0
- package/routes/request.js +5 -0
- 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/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/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/outboundUrlGuard.js +131 -0
package/routes/webhook.js
CHANGED
|
@@ -17,6 +17,7 @@ const webhookSettingsValidator = require('../services/webhookSettingsValidator')
|
|
|
17
17
|
const webhookConversationService = require('../services/webhookConversationService');
|
|
18
18
|
const scheduledStartRules = require('../services/scheduledStartRules');
|
|
19
19
|
const scheduledStartService = require('../services/scheduledStartService');
|
|
20
|
+
const mcpOAuthService = require('../services/mcpOAuthService');
|
|
20
21
|
const KB_WEBHOOK_TOKEN = process.env.KB_WEBHOOK_TOKEN || 'kbcustomtoken';
|
|
21
22
|
const AMQP_MANAGER_URL = process.env.AMQP_MANAGER_URL;
|
|
22
23
|
const JOB_TOPIC_EXCHANGE = process.env.JOB_TOPIC_EXCHANGE_TRAIN || 'tiledesk-trainer';
|
|
@@ -49,7 +50,7 @@ async function checkEnabledAndRateLimit(req, res, webhook) {
|
|
|
49
50
|
return true;
|
|
50
51
|
}
|
|
51
52
|
|
|
52
|
-
async function
|
|
53
|
+
async function startWebhookConversation(res, webhook, payload, options) {
|
|
53
54
|
let chatbot;
|
|
54
55
|
try {
|
|
55
56
|
chatbot = await webhookSettingsValidator.findChatbot(webhook.id_project, webhook.chatbot_id);
|
|
@@ -75,6 +76,69 @@ async function startConversation(res, webhook, payload, options) {
|
|
|
75
76
|
}
|
|
76
77
|
}
|
|
77
78
|
|
|
79
|
+
// Starts the live scheduled start of a chatbot as a conversation; sends the response. Shared by
|
|
80
|
+
// POST /webhook/scheduled-start (the scheduler) and POST /:projectid/executions/refire (a user's start new):
|
|
81
|
+
// - options.payload: the input to start with (refire: the user-confirmed input); else the live mapping's payload;
|
|
82
|
+
// - options.extraAttributes: merged into the request attributes after scheduled_at (refire: retry_of);
|
|
83
|
+
// - options.offlineWhenGone: take the scheduler workflow offline when the start is gone (scheduler route only).
|
|
84
|
+
async function startScheduledRun(req, res, options) {
|
|
85
|
+
const id_project = options.id_project;
|
|
86
|
+
const chatbot_id = options.chatbot_id;
|
|
87
|
+
if (!id_project || !chatbot_id) {
|
|
88
|
+
return res.status(400).send({ success: false, error: "id_project and chatbot_id are required" });
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
let webhook;
|
|
92
|
+
let chatbot;
|
|
93
|
+
try {
|
|
94
|
+
webhook = await Webhook.findOne({ id_project: String(id_project), chatbot_id: String(chatbot_id) });
|
|
95
|
+
chatbot = await webhookSettingsValidator.findChatbot(String(id_project), String(chatbot_id));
|
|
96
|
+
} catch (err) {
|
|
97
|
+
winston.error("Error loading scheduled start ", err);
|
|
98
|
+
return res.status(500).send({ success: false, error: "Error loading scheduled start" });
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
const live = webhook && webhook.scheduled_live;
|
|
102
|
+
if (!chatbot || !live || live.enabled !== true || !live.block_id) {
|
|
103
|
+
if (options.offlineWhenGone) {
|
|
104
|
+
winston.warn("Scheduled start for chatbot " + chatbot_id + " is gone or disabled: taking the workflow offline");
|
|
105
|
+
// Uses the live ids when stored, else finds the workflow by name; never throws.
|
|
106
|
+
await scheduledStartService.offlineFor(String(chatbot_id), live);
|
|
107
|
+
}
|
|
108
|
+
return res.status(410).send({ success: false, error: "Scheduled start is no longer active" });
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
let allowed;
|
|
112
|
+
try {
|
|
113
|
+
allowed = await req.app.get("rate_manager").canExecute(webhook.id_project, null, 'webhook');
|
|
114
|
+
} catch (err) {
|
|
115
|
+
winston.error("Error checking the rate limit of scheduled start ", err);
|
|
116
|
+
return res.status(500).send({ success: false, error: "Error checking the rate limit" });
|
|
117
|
+
}
|
|
118
|
+
if (!allowed) {
|
|
119
|
+
winston.warn("Webhook rate limit exceeded for project " + webhook.id_project);
|
|
120
|
+
return res.status(429).send({ success: false, message: "Rate limit exceeded" });
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
try {
|
|
124
|
+
const mapping = live.mapping || {};
|
|
125
|
+
const payload = options.payload !== undefined ? options.payload : (mapping.payload || {});
|
|
126
|
+
const result = await webhookConversationService.start(webhook, chatbot, payload, {
|
|
127
|
+
startPoint: { block_id: live.block_id, mapping: mapping },
|
|
128
|
+
startType: 'scheduled',
|
|
129
|
+
leadId: 'scheduled_' + chatbot_id,
|
|
130
|
+
leadName: mapping.source_name || chatbot.name || 'Scheduled',
|
|
131
|
+
extraAttributes: Object.assign({ scheduled_at: new Date().toISOString() }, options.extraAttributes || {})
|
|
132
|
+
});
|
|
133
|
+
return res.status(202).send({ success: true, request_id: result.request_id });
|
|
134
|
+
} catch (err) {
|
|
135
|
+
if (!err.status) {
|
|
136
|
+
winston.error("Error starting scheduled conversation for chatbot " + chatbot_id, err);
|
|
137
|
+
}
|
|
138
|
+
return res.status(err.status || 500).send({ success: false, error: err.status ? err.message : "Error starting conversation" });
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
78
142
|
let jobManager = new JobManager(AMQP_MANAGER_URL, {
|
|
79
143
|
debug: false,
|
|
80
144
|
topic: JOB_TOPIC_EXCHANGE,
|
|
@@ -320,6 +384,40 @@ router.post('/kb/status', async (req, res) => {
|
|
|
320
384
|
|
|
321
385
|
})
|
|
322
386
|
|
|
387
|
+
// Called by the scheduler to refresh MCP OAuth tokens ahead of expiry.
|
|
388
|
+
// Body: { connection_id } for one connection, or { within_seconds } (60..86400, default 900) for all the due ones.
|
|
389
|
+
router.post('/mcp-oauth/refresh', async (req, res) => {
|
|
390
|
+
if (!process.env.MCP_OAUTH_REFRESH_TOKEN || !mcpOAuthService.isConfigured()) {
|
|
391
|
+
return res.status(503).send({ success: false, error: "MCP OAuth refresh is not available on this installation" });
|
|
392
|
+
}
|
|
393
|
+
const token = req.headers['x-auth-token'];
|
|
394
|
+
const expected = Buffer.from(String(process.env.MCP_OAUTH_REFRESH_TOKEN));
|
|
395
|
+
const given = Buffer.from(String(token || ''));
|
|
396
|
+
if (!token || given.length !== expected.length || !crypto.timingSafeEqual(given, expected)) {
|
|
397
|
+
return res.status(401).send({ success: false, error: "Unauthorized" });
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
const body = req.body || {};
|
|
401
|
+
try {
|
|
402
|
+
if (body.connection_id) {
|
|
403
|
+
const result = await mcpOAuthService.refreshConnection(String(body.connection_id));
|
|
404
|
+
return res.status(200).send({ success: true, connection_id: String(body.connection_id), expires_at: result.expires_at });
|
|
405
|
+
}
|
|
406
|
+
const within = body.within_seconds === undefined ? 900 : Number(body.within_seconds);
|
|
407
|
+
if (!Number.isInteger(within) || within < 60 || within > 86400) {
|
|
408
|
+
return res.status(400).send({ success: false, error: "within_seconds must be an integer between 60 and 86400" });
|
|
409
|
+
}
|
|
410
|
+
const result = await mcpOAuthService.refreshDue(within);
|
|
411
|
+
return res.status(200).send({ success: true, ...result });
|
|
412
|
+
} catch (err) {
|
|
413
|
+
const status = err.status || 500;
|
|
414
|
+
if (status >= 500) {
|
|
415
|
+
winston.error("Error refreshing MCP OAuth tokens ", err);
|
|
416
|
+
}
|
|
417
|
+
return res.status(status).send({ success: false, error: status === 500 ? "Error refreshing MCP OAuth tokens" : err.message, code: err.code });
|
|
418
|
+
}
|
|
419
|
+
})
|
|
420
|
+
|
|
323
421
|
// Run endpoint called by the DolphinScheduler workflow of a scheduled start point. It ignores
|
|
324
422
|
// webhook.enabled and the webhook start point (they govern the public webhook URL only) and
|
|
325
423
|
// applies just the per-project rate limit.
|
|
@@ -334,64 +432,26 @@ router.post('/scheduled-start', async (req, res) => {
|
|
|
334
432
|
return res.status(401).send({ success: false, error: "Unauthorized" });
|
|
335
433
|
}
|
|
336
434
|
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
}
|
|
342
|
-
|
|
343
|
-
let webhook;
|
|
344
|
-
let chatbot;
|
|
345
|
-
try {
|
|
346
|
-
webhook = await Webhook.findOne({ id_project: String(id_project), chatbot_id: String(chatbot_id) });
|
|
347
|
-
chatbot = await webhookSettingsValidator.findChatbot(String(id_project), String(chatbot_id));
|
|
348
|
-
} catch (err) {
|
|
349
|
-
winston.error("Error loading scheduled start ", err);
|
|
350
|
-
return res.status(500).send({ success: false, error: "Error loading scheduled start" });
|
|
351
|
-
}
|
|
352
|
-
|
|
353
|
-
const live = webhook && webhook.scheduled_live;
|
|
354
|
-
if (!chatbot || !live || live.enabled !== true || !live.block_id) {
|
|
355
|
-
winston.warn("Scheduled start for chatbot " + chatbot_id + " is gone or disabled: taking the workflow offline");
|
|
356
|
-
// Uses the live ids when stored, else finds the workflow by name; never throws.
|
|
357
|
-
await scheduledStartService.offlineFor(String(chatbot_id), live);
|
|
358
|
-
return res.status(410).send({ success: false, error: "Scheduled start is no longer active" });
|
|
359
|
-
}
|
|
360
|
-
|
|
361
|
-
let allowed;
|
|
362
|
-
try {
|
|
363
|
-
allowed = await req.app.get("rate_manager").canExecute(webhook.id_project, null, 'webhook');
|
|
364
|
-
} catch (err) {
|
|
365
|
-
winston.error("Error checking the rate limit of scheduled start ", err);
|
|
366
|
-
return res.status(500).send({ success: false, error: "Error checking the rate limit" });
|
|
367
|
-
}
|
|
368
|
-
if (!allowed) {
|
|
369
|
-
winston.warn("Webhook rate limit exceeded for project " + webhook.id_project);
|
|
370
|
-
return res.status(429).send({ success: false, message: "Rate limit exceeded" });
|
|
371
|
-
}
|
|
435
|
+
return startScheduledRun(req, res, {
|
|
436
|
+
id_project: req.body && req.body.id_project,
|
|
437
|
+
chatbot_id: req.body && req.body.chatbot_id,
|
|
438
|
+
offlineWhenGone: true
|
|
439
|
+
});
|
|
440
|
+
});
|
|
372
441
|
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
leadId: 'scheduled_' + chatbot_id,
|
|
379
|
-
leadName: mapping.source_name || chatbot.name || 'Scheduled',
|
|
380
|
-
extraAttributes: { scheduled_at: new Date().toISOString() }
|
|
381
|
-
});
|
|
382
|
-
return res.status(202).send({ success: true, request_id: result.request_id });
|
|
383
|
-
} catch (err) {
|
|
384
|
-
if (!err.status) {
|
|
385
|
-
winston.error("Error starting scheduled conversation for chatbot " + chatbot_id, err);
|
|
386
|
-
}
|
|
387
|
-
return res.status(err.status || 500).send({ success: false, error: err.status ? err.message : "Error starting conversation" });
|
|
442
|
+
// Executions lineage: retry_of links a run to the one it starts again and is set only by the executions refire
|
|
443
|
+
// (routes/executions-refire.js); a public caller's retry_of is dropped (tiledesk-executions contract 8).
|
|
444
|
+
function dropRetryOf(payload) {
|
|
445
|
+
if (payload && typeof payload === 'object') {
|
|
446
|
+
delete payload.retry_of;
|
|
388
447
|
}
|
|
389
|
-
}
|
|
448
|
+
}
|
|
390
449
|
|
|
391
450
|
router.all('/:webhook_id', async (req, res) => {
|
|
392
451
|
|
|
393
452
|
let webhook_id = req.params.webhook_id;
|
|
394
453
|
let payload = req.body;
|
|
454
|
+
dropRetryOf(payload);
|
|
395
455
|
payload.webhook_http_method = req.method;
|
|
396
456
|
let params = req.query;
|
|
397
457
|
let dev = params.dev;
|
|
@@ -415,7 +475,7 @@ router.all('/:webhook_id', async (req, res) => {
|
|
|
415
475
|
}
|
|
416
476
|
|
|
417
477
|
if (webhook.mode === webhookSettingsValidator.CONVERSATION_MODE) {
|
|
418
|
-
return
|
|
478
|
+
return startWebhookConversation(res, webhook, payload, { dev: false });
|
|
419
479
|
}
|
|
420
480
|
|
|
421
481
|
payload.request_id = "automation-request-" + webhook.id_project + "-" + new ObjectId() + "-" + webhook_id;
|
|
@@ -449,6 +509,7 @@ router.all('/:webhook_id/dev', async (req, res) => {
|
|
|
449
509
|
|
|
450
510
|
let webhook_id = req.params.webhook_id;
|
|
451
511
|
let payload = req.body;
|
|
512
|
+
dropRetryOf(payload);
|
|
452
513
|
payload.webhook_http_method = req.method;
|
|
453
514
|
let params = req.query;
|
|
454
515
|
delete params.dev;
|
|
@@ -492,7 +553,7 @@ router.all('/:webhook_id/dev', async (req, res) => {
|
|
|
492
553
|
winston.error("Error deleting consumed preloaded development request ", err);
|
|
493
554
|
}
|
|
494
555
|
|
|
495
|
-
return
|
|
556
|
+
return startWebhookConversation(res, webhook, payload, { dev: true, request_id: JSON.parse(preloaded).request_id });
|
|
496
557
|
}
|
|
497
558
|
|
|
498
559
|
let redis_client = req.app.get('redis_client');
|
|
@@ -526,3 +587,8 @@ router.all('/:webhook_id/dev', async (req, res) => {
|
|
|
526
587
|
// }
|
|
527
588
|
|
|
528
589
|
module.exports = router;
|
|
590
|
+
|
|
591
|
+
// Shared with routes/executions-refire.js (start new of an execution).
|
|
592
|
+
module.exports.checkEnabledAndRateLimit = checkEnabledAndRateLimit;
|
|
593
|
+
module.exports.startWebhookConversation = startWebhookConversation;
|
|
594
|
+
module.exports.startScheduledRun = startScheduledRun;
|
|
@@ -0,0 +1,248 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const axios = require('axios').default;
|
|
4
|
+
const winston = require('../config/winston');
|
|
5
|
+
const outboundUrlGuard = require('../utils/outboundUrlGuard');
|
|
6
|
+
|
|
7
|
+
const MCP_PROTOCOL_VERSION = '2025-03-26';
|
|
8
|
+
const CLIENT_NAME = 'Tiledesk';
|
|
9
|
+
|
|
10
|
+
function oauthError(status, code, message) {
|
|
11
|
+
const error = new Error(message);
|
|
12
|
+
error.status = status;
|
|
13
|
+
error.code = code;
|
|
14
|
+
return error;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Well-known URLs for a base URL, path-inserted first (RFC 8414 §3.1, RFC 9728 §3.1):
|
|
19
|
+
* https://a.com/tenant1 + suffix → [https://a.com/.well-known/<suffix>/tenant1, https://a.com/.well-known/<suffix>]
|
|
20
|
+
*/
|
|
21
|
+
function wellKnownUrls(baseUrl, suffix) {
|
|
22
|
+
const url = new URL(baseUrl);
|
|
23
|
+
const path = url.pathname.replace(/\/+$/, '');
|
|
24
|
+
const root = url.origin + '/.well-known/' + suffix;
|
|
25
|
+
return path ? [root + path, root] : [root];
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function authorizationServerMetadataUrls(issuer) {
|
|
29
|
+
const url = new URL(issuer);
|
|
30
|
+
const path = url.pathname.replace(/\/+$/, '');
|
|
31
|
+
const urls = wellKnownUrls(issuer, 'oauth-authorization-server');
|
|
32
|
+
if (path) {
|
|
33
|
+
urls.push(url.origin + '/.well-known/openid-configuration' + path);
|
|
34
|
+
urls.push(url.origin + path + '/.well-known/openid-configuration');
|
|
35
|
+
}
|
|
36
|
+
urls.push(url.origin + '/.well-known/openid-configuration');
|
|
37
|
+
return [...new Set(urls)];
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function parseWwwAuthenticate(header) {
|
|
41
|
+
if (!header) {
|
|
42
|
+
return {};
|
|
43
|
+
}
|
|
44
|
+
const value = Array.isArray(header) ? header.join(', ') : String(header);
|
|
45
|
+
const read = (name) => {
|
|
46
|
+
const match = value.match(new RegExp(name + '="([^"]*)"', 'i')) || value.match(new RegExp(name + '=([^\\s,]+)', 'i'));
|
|
47
|
+
return match ? match[1] : undefined;
|
|
48
|
+
};
|
|
49
|
+
return { resource_metadata: read('resource_metadata'), scope: read('scope') };
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function assertBrowserUrl(rawUrl, field) {
|
|
53
|
+
let url;
|
|
54
|
+
try {
|
|
55
|
+
url = new URL(rawUrl);
|
|
56
|
+
} catch (error) {
|
|
57
|
+
throw oauthError(400, 'bad_request', 'Invalid ' + field + ' in OAuth metadata');
|
|
58
|
+
}
|
|
59
|
+
const insecure = process.env.MCP_OAUTH_ALLOW_INSECURE_URLS === 'true';
|
|
60
|
+
if (url.protocol !== 'https:' && !(insecure && url.protocol === 'http:')) {
|
|
61
|
+
throw oauthError(400, 'bad_request', 'The ' + field + ' in OAuth metadata must use https');
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function asNetworkError(error, url) {
|
|
66
|
+
if (error.status) {
|
|
67
|
+
return error;
|
|
68
|
+
}
|
|
69
|
+
return oauthError(502, 'provider_error', 'Cannot reach ' + url + ': ' + error.message);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
async function request(config) {
|
|
73
|
+
await outboundUrlGuard.assertAllowed(config.url);
|
|
74
|
+
try {
|
|
75
|
+
return await axios({
|
|
76
|
+
...outboundUrlGuard.httpOptions(),
|
|
77
|
+
validateStatus: () => true,
|
|
78
|
+
...config
|
|
79
|
+
});
|
|
80
|
+
} catch (error) {
|
|
81
|
+
throw asNetworkError(error, config.url);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** The JSON object at url, or null when the server has none there (any non-200 answer). */
|
|
86
|
+
async function fetchJson(url) {
|
|
87
|
+
const response = await request({ method: 'GET', url, headers: { Accept: 'application/json' } });
|
|
88
|
+
if (response.status !== 200 || !response.data || typeof response.data !== 'object') {
|
|
89
|
+
return null;
|
|
90
|
+
}
|
|
91
|
+
return response.data;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
async function firstJson(urls, isValid) {
|
|
95
|
+
for (const url of urls) {
|
|
96
|
+
const data = await fetchJson(url);
|
|
97
|
+
if (data && isValid(data)) {
|
|
98
|
+
return { url, data };
|
|
99
|
+
}
|
|
100
|
+
winston.debug('MCP OAuth discovery: no usable metadata at ' + url);
|
|
101
|
+
}
|
|
102
|
+
return null;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
async function probeServer(serverUrl) {
|
|
106
|
+
const response = await request({
|
|
107
|
+
method: 'POST',
|
|
108
|
+
url: serverUrl,
|
|
109
|
+
headers: {
|
|
110
|
+
'Content-Type': 'application/json',
|
|
111
|
+
'Accept': 'application/json, text/event-stream'
|
|
112
|
+
},
|
|
113
|
+
data: {
|
|
114
|
+
jsonrpc: '2.0',
|
|
115
|
+
id: Date.now(),
|
|
116
|
+
method: 'initialize',
|
|
117
|
+
params: {
|
|
118
|
+
protocolVersion: MCP_PROTOCOL_VERSION,
|
|
119
|
+
capabilities: { tools: {} },
|
|
120
|
+
clientInfo: { name: 'tiledesk-server', version: '1.0.0' }
|
|
121
|
+
}
|
|
122
|
+
},
|
|
123
|
+
// The body of an SSE answer is not needed, only status and headers.
|
|
124
|
+
responseType: 'text'
|
|
125
|
+
});
|
|
126
|
+
|
|
127
|
+
if (response.status >= 200 && response.status < 300) {
|
|
128
|
+
throw oauthError(400, 'bad_request', 'This MCP server does not require OAuth');
|
|
129
|
+
}
|
|
130
|
+
return parseWwwAuthenticate(response.headers['www-authenticate']);
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* MCP Authorization discovery: probes the MCP server, reads its Protected Resource
|
|
135
|
+
* Metadata (RFC 9728) and the Authorization Server Metadata (RFC 8414 / OIDC).
|
|
136
|
+
*/
|
|
137
|
+
async function discover(serverUrl) {
|
|
138
|
+
const challenge = await probeServer(serverUrl);
|
|
139
|
+
|
|
140
|
+
const resourceUrls = [
|
|
141
|
+
...(challenge.resource_metadata ? [challenge.resource_metadata] : []),
|
|
142
|
+
...wellKnownUrls(serverUrl, 'oauth-protected-resource')
|
|
143
|
+
];
|
|
144
|
+
const resourceMetadata = await firstJson([...new Set(resourceUrls)], (data) =>
|
|
145
|
+
Array.isArray(data.authorization_servers) && data.authorization_servers.length > 0
|
|
146
|
+
);
|
|
147
|
+
|
|
148
|
+
const server = new URL(serverUrl);
|
|
149
|
+
let resource = serverUrl;
|
|
150
|
+
let issuer = server.origin;
|
|
151
|
+
let resourceScopes;
|
|
152
|
+
|
|
153
|
+
if (resourceMetadata) {
|
|
154
|
+
if (resourceMetadata.data.resource) {
|
|
155
|
+
if (new URL(resourceMetadata.data.resource).origin !== server.origin) {
|
|
156
|
+
throw oauthError(400, 'bad_request', 'Protected resource metadata is for another server: ' + resourceMetadata.data.resource);
|
|
157
|
+
}
|
|
158
|
+
resource = resourceMetadata.data.resource;
|
|
159
|
+
}
|
|
160
|
+
issuer = resourceMetadata.data.authorization_servers[0];
|
|
161
|
+
resourceScopes = resourceMetadata.data.scopes_supported;
|
|
162
|
+
} else {
|
|
163
|
+
// MCP 2025-03-26 servers publish no resource metadata: the MCP server origin is the authorization server.
|
|
164
|
+
winston.debug('MCP OAuth discovery: no protected resource metadata for ' + serverUrl + ', using its origin as issuer');
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
const authorizationServer = await firstJson(authorizationServerMetadataUrls(issuer), (data) =>
|
|
168
|
+
typeof data.authorization_endpoint === 'string' && typeof data.token_endpoint === 'string'
|
|
169
|
+
);
|
|
170
|
+
if (!authorizationServer) {
|
|
171
|
+
throw oauthError(400, 'bad_request', 'OAuth metadata not found for ' + serverUrl);
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
const metadata = authorizationServer.data;
|
|
175
|
+
const challengeMethods = metadata.code_challenge_methods_supported;
|
|
176
|
+
if (Array.isArray(challengeMethods) && !challengeMethods.includes('S256')) {
|
|
177
|
+
throw oauthError(400, 'bad_request', 'Authorization server does not support PKCE S256');
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
assertBrowserUrl(metadata.authorization_endpoint, 'authorization_endpoint');
|
|
181
|
+
|
|
182
|
+
const scopes = challenge.scope ? challenge.scope.split(' ').filter(Boolean) : resourceScopes;
|
|
183
|
+
|
|
184
|
+
const result = {
|
|
185
|
+
resource,
|
|
186
|
+
issuer: metadata.issuer || issuer,
|
|
187
|
+
authorization_endpoint: metadata.authorization_endpoint,
|
|
188
|
+
token_endpoint: metadata.token_endpoint
|
|
189
|
+
};
|
|
190
|
+
if (metadata.revocation_endpoint) {
|
|
191
|
+
result.revocation_endpoint = metadata.revocation_endpoint;
|
|
192
|
+
}
|
|
193
|
+
if (metadata.registration_endpoint) {
|
|
194
|
+
result.registration_endpoint = metadata.registration_endpoint;
|
|
195
|
+
}
|
|
196
|
+
if (Array.isArray(scopes) && scopes.length > 0) {
|
|
197
|
+
result.scopes_supported = scopes;
|
|
198
|
+
}
|
|
199
|
+
if (Array.isArray(metadata.token_endpoint_auth_methods_supported)) {
|
|
200
|
+
result.token_endpoint_auth_methods_supported = metadata.token_endpoint_auth_methods_supported;
|
|
201
|
+
}
|
|
202
|
+
return result;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
function preferredAuthMethod(supported) {
|
|
206
|
+
if (!Array.isArray(supported) || supported.length === 0) {
|
|
207
|
+
return 'client_secret_post';
|
|
208
|
+
}
|
|
209
|
+
return ['client_secret_post', 'client_secret_basic', 'none'].find((method) => supported.includes(method)) || 'client_secret_post';
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/** Dynamic Client Registration (RFC 7591) of Tiledesk at the authorization server. */
|
|
213
|
+
async function register(metadata, redirectUri) {
|
|
214
|
+
if (!metadata || !metadata.registration_endpoint) {
|
|
215
|
+
throw oauthError(400, 'bad_request', "This MCP server does not support dynamic client registration; use mode 'manual'");
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
const requestedAuthMethod = preferredAuthMethod(metadata.token_endpoint_auth_methods_supported);
|
|
219
|
+
const response = await request({
|
|
220
|
+
method: 'POST',
|
|
221
|
+
url: metadata.registration_endpoint,
|
|
222
|
+
headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
|
|
223
|
+
data: {
|
|
224
|
+
client_name: CLIENT_NAME,
|
|
225
|
+
redirect_uris: [redirectUri],
|
|
226
|
+
grant_types: ['authorization_code', 'refresh_token'],
|
|
227
|
+
response_types: ['code'],
|
|
228
|
+
token_endpoint_auth_method: requestedAuthMethod
|
|
229
|
+
}
|
|
230
|
+
});
|
|
231
|
+
|
|
232
|
+
const body = response.data && typeof response.data === 'object' ? response.data : {};
|
|
233
|
+
if (response.status < 200 || response.status >= 300 || !body.client_id) {
|
|
234
|
+
const reason = body.error_description || body.error || ('HTTP ' + response.status);
|
|
235
|
+
throw oauthError(502, 'provider_error', 'Dynamic client registration failed: ' + reason);
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
const client = {
|
|
239
|
+
client_id: body.client_id,
|
|
240
|
+
token_endpoint_auth_method: body.token_endpoint_auth_method || (body.client_secret ? requestedAuthMethod : 'none')
|
|
241
|
+
};
|
|
242
|
+
if (body.client_secret) {
|
|
243
|
+
client.client_secret = body.client_secret;
|
|
244
|
+
}
|
|
245
|
+
return client;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
module.exports = { discover, register, wellKnownUrls, authorizationServerMetadataUrls, parseWwwAuthenticate };
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// Scopes documented by Google for its remote MCP servers, used when an authorize request in
|
|
4
|
+
// google mode sends none. Workspace: developers.google.com/workspace/guides/configure-mcp-servers.
|
|
5
|
+
// BigQuery: docs.cloud.google.com/bigquery/docs/use-bigquery-mcp.
|
|
6
|
+
const AUTH = 'https://www.googleapis.com/auth/';
|
|
7
|
+
const DRIVE = [AUTH + 'drive.readonly', AUTH + 'drive.file'];
|
|
8
|
+
|
|
9
|
+
const DEFAULT_SCOPES = {
|
|
10
|
+
'gmailmcp.googleapis.com': [AUTH + 'gmail.readonly', AUTH + 'gmail.compose'],
|
|
11
|
+
'drivemcp.googleapis.com': DRIVE,
|
|
12
|
+
'docsmcp.googleapis.com': [...DRIVE, AUTH + 'documents.readonly', AUTH + 'documents'],
|
|
13
|
+
'sheetsmcp.googleapis.com': [...DRIVE, AUTH + 'spreadsheets.readonly', AUTH + 'spreadsheets'],
|
|
14
|
+
'slidesmcp.googleapis.com': [...DRIVE, AUTH + 'presentations.readonly', AUTH + 'presentations'],
|
|
15
|
+
'calendarmcp.googleapis.com': [
|
|
16
|
+
AUTH + 'calendar.calendarlist.readonly',
|
|
17
|
+
AUTH + 'calendar.events.freebusy',
|
|
18
|
+
AUTH + 'calendar.events.readonly'
|
|
19
|
+
],
|
|
20
|
+
'chatmcp.googleapis.com': [
|
|
21
|
+
AUTH + 'chat.spaces.readonly',
|
|
22
|
+
AUTH + 'chat.memberships.readonly',
|
|
23
|
+
AUTH + 'chat.messages.readonly',
|
|
24
|
+
AUTH + 'chat.messages.create',
|
|
25
|
+
AUTH + 'chat.users.readstate',
|
|
26
|
+
AUTH + 'chat.users.spacesettings'
|
|
27
|
+
],
|
|
28
|
+
'people.googleapis.com': [AUTH + 'directory.readonly', AUTH + 'userinfo.profile', AUTH + 'contacts.readonly'],
|
|
29
|
+
'classroommcp.googleapis.com': [
|
|
30
|
+
AUTH + 'classroom.announcements',
|
|
31
|
+
AUTH + 'classroom.courses.readonly',
|
|
32
|
+
AUTH + 'classroom.coursework.students',
|
|
33
|
+
AUTH + 'classroom.courseworkmaterials',
|
|
34
|
+
AUTH + 'classroom.rosters.readonly',
|
|
35
|
+
AUTH + 'classroom.student-submissions.students.readonly',
|
|
36
|
+
AUTH + 'classroom.topics.readonly'
|
|
37
|
+
],
|
|
38
|
+
'bigquery.googleapis.com': [AUTH + 'bigquery']
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
/** Default scopes for a known Google MCP server URL (`https://<host>/mcp...`), else []. */
|
|
42
|
+
function defaultScopesFor(serverUrl) {
|
|
43
|
+
let url;
|
|
44
|
+
try {
|
|
45
|
+
url = new URL(serverUrl);
|
|
46
|
+
} catch (error) {
|
|
47
|
+
return [];
|
|
48
|
+
}
|
|
49
|
+
if (url.protocol !== 'https:' || !url.pathname.startsWith('/mcp')) {
|
|
50
|
+
return [];
|
|
51
|
+
}
|
|
52
|
+
return [...(DEFAULT_SCOPES[url.hostname] || [])];
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
module.exports = { defaultScopesFor, DEFAULT_SCOPES };
|