emailengine-app 2.79.1 → 2.79.3
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/.github/workflows/deploy.yml +92 -39
- package/.github/workflows/release.yaml +94 -34
- package/.release-please-manifest.json +1 -1
- package/CHANGELOG.md +85 -0
- package/bin/emailengine.js +8 -1
- package/config/default.toml +6 -0
- package/copy-static-files.sh +23 -2
- package/data/google-crawlers.json +1 -1
- package/lib/account.js +138 -18
- package/lib/api-routes/account-routes.js +13 -1
- package/lib/api-routes/index.js +12 -0
- package/lib/api-routes/mailbox-routes.js +6 -0
- package/lib/api-routes/mcp-oauth-routes.js +259 -0
- package/lib/api-routes/mcp-routes.js +172 -0
- package/lib/api-routes/message-routes.js +125 -4
- package/lib/api-routes/outbox-routes.js +7 -0
- package/lib/api-routes/permission-map.js +97 -1
- package/lib/api-routes/route-helpers.js +16 -4
- package/lib/api-routes/route-metadata.js +24 -4
- package/lib/api-routes/submit-routes.js +41 -0
- package/lib/api-routes/template-routes.js +7 -0
- package/lib/api-routes/token-routes.js +4 -2
- package/lib/consts.js +30 -1
- package/lib/email-client/base-client.js +235 -163
- package/lib/email-client/gmail-client.js +99 -22
- package/lib/email-client/imap/mailbox.js +140 -66
- package/lib/email-client/imap-client.js +74 -68
- package/lib/email-client/outlook-client.js +29 -14
- package/lib/enum-descriptions.js +2 -1
- package/lib/field-usage.js +17 -1
- package/lib/logger.js +43 -3
- package/lib/lua/s-list-accounts.lua +5 -2
- package/lib/mcp/index.js +29 -0
- package/lib/mcp/inject.js +70 -0
- package/lib/mcp/json-schema.js +120 -0
- package/lib/mcp/listen.js +171 -0
- package/lib/mcp/oauth.js +324 -0
- package/lib/mcp/protocol.js +489 -0
- package/lib/mcp/resources.js +139 -0
- package/lib/mcp/tools.js +655 -0
- package/lib/openapi/index.js +3 -1
- package/lib/response-stream.js +52 -21
- package/lib/routes-ui.js +4 -0
- package/lib/schemas.js +24 -3
- package/lib/token-permission-view.js +104 -8
- package/lib/tokens.js +34 -5
- package/lib/tools.js +96 -0
- package/lib/ui-routes/account-routes.js +43 -1
- package/lib/ui-routes/admin-config-routes.js +114 -1
- package/lib/ui-routes/admin-entities-routes.js +54 -5
- package/lib/ui-routes/auth-routes.js +13 -0
- package/lib/ui-routes/mcp-consent-routes.js +330 -0
- package/lib/ui-routes/route-helpers.js +116 -1
- package/lib/utils/network.js +9 -1
- package/lib/web-safe-html.js +61 -0
- package/lib/webhooks.js +3 -8
- package/package.json +15 -14
- package/sbom.json +1 -1
- package/scripts/README.md +25 -0
- package/scripts/build-icon.js +77 -0
- package/server.js +21 -9
- package/static/css/flyonui.css +1 -1
- package/static/css/src/app.tailwind.css +98 -0
- package/static/emailengine.ico +0 -0
- package/static/js/ui.js +465 -1
- package/static/licenses.html +85 -135
- package/translations/messages.pot +103 -103
- package/views/config/mcp.hbs +361 -0
- package/views/config/oauth/index.hbs +7 -0
- package/views/layout/prompt.hbs +62 -0
- package/views/mcp/authorize.hbs +136 -0
- package/views/partials/head_assets.hbs +3 -3
- package/views/partials/mcp_access_levels.hbs +13 -0
- package/views/partials/mcp_account_limit.hbs +14 -0
- package/views/partials/mcp_tool_count.hbs +19 -0
- package/views/partials/side_menu.hbs +1 -0
- package/views/partials/ui/account-picker.hbs +59 -0
- package/views/partials/ui/code-block.hbs +26 -0
- package/views/partials/ui/menu-item.hbs +5 -0
- package/views/partials/ui/radio.hbs +41 -0
- package/views/partials/ui/tab.hbs +15 -10
- package/views/partials/ui/tabs.hbs +8 -5
- package/views/templates/template.hbs +4 -3
- package/views/tokens/index.hbs +8 -2
- package/views/tokens/new.hbs +514 -243
- package/winconf.js +148 -48
- package/workers/api.js +198 -48
|
@@ -26,9 +26,14 @@ const { validateWebhookTarget } = require('../webhook-egress');
|
|
|
26
26
|
const { sendWebhookRequest } = require('../webhook-request');
|
|
27
27
|
const { llmPreProcess } = require('../llm-pre-process');
|
|
28
28
|
const { documentStoreFeatureEnabled } = require('../document-store');
|
|
29
|
+
const { mcpFeatureEnabled } = require('../mcp');
|
|
30
|
+
const { mcpResource } = require('../mcp/oauth');
|
|
31
|
+
const { getToolRegistry } = require('../mcp/tools');
|
|
32
|
+
const { serverUrl } = require('../openapi');
|
|
33
|
+
const { MCP_ACCESS_LEVELS, MCP_ACCESS_LEVEL_OPTIONS } = require('../token-permission-view');
|
|
29
34
|
const { locales } = require('../translations');
|
|
30
35
|
const { settingsSchema } = require('../schemas');
|
|
31
|
-
const { getOpenAiModels, OPEN_AI_MODELS, getExampleDocumentsPayloads } = require('./route-helpers');
|
|
36
|
+
const { getOpenAiModels, OPEN_AI_MODELS, getExampleDocumentsPayloads, mcpToolGrants } = require('./route-helpers');
|
|
32
37
|
const { registerSettingsPage } = require('./settings-page');
|
|
33
38
|
|
|
34
39
|
const {
|
|
@@ -555,6 +560,114 @@ function init(args) {
|
|
|
555
560
|
}
|
|
556
561
|
});
|
|
557
562
|
|
|
563
|
+
registerSettingsPage(server, {
|
|
564
|
+
path: '/admin/config/mcp',
|
|
565
|
+
view: 'config/mcp',
|
|
566
|
+
pageTitle: 'MCP',
|
|
567
|
+
menuKey: 'menuConfigMcp',
|
|
568
|
+
schema: {
|
|
569
|
+
mcpEnabled: settingsSchema.mcpEnabled.default(false),
|
|
570
|
+
mcpOAuthEnabled: settingsSchema.mcpOAuthEnabled.default(false)
|
|
571
|
+
},
|
|
572
|
+
|
|
573
|
+
async loadValues() {
|
|
574
|
+
const storedValues = await settings.getMulti('mcpEnabled', 'mcpOAuthEnabled');
|
|
575
|
+
|
|
576
|
+
return {
|
|
577
|
+
mcpEnabled: !!storedValues.mcpEnabled,
|
|
578
|
+
mcpOAuthEnabled: !!storedValues.mcpOAuthEnabled
|
|
579
|
+
};
|
|
580
|
+
},
|
|
581
|
+
|
|
582
|
+
async viewContext(request) {
|
|
583
|
+
const { serviceUrl, mcpOAuthEnabled } = await settings.getMulti('serviceUrl', 'mcpOAuthEnabled');
|
|
584
|
+
|
|
585
|
+
// The configured public address when a Service URL is set (the same derivation the
|
|
586
|
+
// OAuth metadata publishes as the resource identifier), otherwise the address this
|
|
587
|
+
// request arrived on - the same request-derived answer /swagger.json publishes
|
|
588
|
+
let configuredOrigin = null;
|
|
589
|
+
try {
|
|
590
|
+
configuredOrigin = serviceUrl ? new URL(serviceUrl).origin : null;
|
|
591
|
+
} catch (err) {
|
|
592
|
+
// an unparseable serviceUrl setting falls back to the request address
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
const mcpUrl = mcpResource(configuredOrigin || serverUrl(request));
|
|
596
|
+
|
|
597
|
+
// The catalog and the endpoint read one registry (lib/mcp/tools.js), so this list is
|
|
598
|
+
// exactly what an agent receives from tools/list - the operator approves what they
|
|
599
|
+
// can see, not a prose summary of it. The badge collapses the annotation hints back
|
|
600
|
+
// into the one action they were derived from.
|
|
601
|
+
const mcpTools = mcpToolGrants(server, request.logger);
|
|
602
|
+
|
|
603
|
+
let toolCatalog = [];
|
|
604
|
+
try {
|
|
605
|
+
toolCatalog = getToolRegistry(server).tools.map(tool => ({
|
|
606
|
+
name: tool.name,
|
|
607
|
+
description: tool.description,
|
|
608
|
+
badge: tool.annotations.openWorldHint
|
|
609
|
+
? { label: 'sends email', variant: 'warning' }
|
|
610
|
+
: tool.annotations.destructiveHint
|
|
611
|
+
? { label: 'destructive', variant: 'error' }
|
|
612
|
+
: tool.annotations.readOnlyHint
|
|
613
|
+
? { label: 'read-only', variant: 'success' }
|
|
614
|
+
: { label: 'write', variant: 'info' }
|
|
615
|
+
}));
|
|
616
|
+
} catch (err) {
|
|
617
|
+
request.logger.error({ msg: 'Failed to derive the MCP tool catalog', err });
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
const serviceUrlConfigured = !!configuredOrigin;
|
|
621
|
+
|
|
622
|
+
// Which precondition blocks the OAuth connection method right now, or null when it
|
|
623
|
+
// is ready: the stored setting first (the page-local action), then a usable Service
|
|
624
|
+
// URL. This is what oauthOrigin() checks minus the mcpEnabled setting - deliberately,
|
|
625
|
+
// because the Connect tab's own "endpoint not enabled" alert owns that state and the
|
|
626
|
+
// badge must not double-report it; null with the deployment gate off for the same
|
|
627
|
+
// reason. The one value drives both the method tab's badge and the panel's warning,
|
|
628
|
+
// so the two cannot disagree. Stored state on purpose, not the posted form value:
|
|
629
|
+
// it reports what a connector would actually get today. The blocked method's tab
|
|
630
|
+
// stays clickable - a disabled tab cannot explain how to enable itself - and carries
|
|
631
|
+
// a "not enabled" badge instead.
|
|
632
|
+
let oauthMethodBlocker = null;
|
|
633
|
+
if (mcpFeatureEnabled) {
|
|
634
|
+
if (!mcpOAuthEnabled) {
|
|
635
|
+
oauthMethodBlocker = 'setting';
|
|
636
|
+
} else if (!serviceUrlConfigured) {
|
|
637
|
+
oauthMethodBlocker = 'serviceUrl';
|
|
638
|
+
}
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
return {
|
|
642
|
+
mcpFeatureEnabled,
|
|
643
|
+
mcpUrl,
|
|
644
|
+
serviceUrlConfigured,
|
|
645
|
+
oauthMethodBlocker,
|
|
646
|
+
toolCatalog,
|
|
647
|
+
// The same catalog reduced to what the tool count needs: one entry per tool with
|
|
648
|
+
// the operation it dispatches under and whether it can be bound to an account
|
|
649
|
+
mcpTools,
|
|
650
|
+
// The whole access-level table, `full: null` included: the page script keys on
|
|
651
|
+
// the same map the consent route mints from, so a level added there is offered
|
|
652
|
+
// here without a second list to update
|
|
653
|
+
mcpAccessPresets: MCP_ACCESS_LEVELS,
|
|
654
|
+
// The generator's radio group renders through the shared mcp_access_levels
|
|
655
|
+
// partial, from the same table the consent prompt offers
|
|
656
|
+
accessOptions: MCP_ACCESS_LEVEL_OPTIONS,
|
|
657
|
+
// The same gate as the token pages: minting needs an authenticated admin
|
|
658
|
+
// session on this request, not just a password existing in Redis
|
|
659
|
+
canProvision: request.auth.isAuthenticated
|
|
660
|
+
};
|
|
661
|
+
},
|
|
662
|
+
|
|
663
|
+
async applySettings(request) {
|
|
664
|
+
await settings.setMulti({
|
|
665
|
+
mcpEnabled: request.payload.mcpEnabled,
|
|
666
|
+
mcpOAuthEnabled: request.payload.mcpOAuthEnabled
|
|
667
|
+
});
|
|
668
|
+
}
|
|
669
|
+
});
|
|
670
|
+
|
|
558
671
|
registerSettingsPage(server, {
|
|
559
672
|
path: '/admin/config/ai',
|
|
560
673
|
view: 'config/ai',
|
|
@@ -11,16 +11,22 @@ const { failAction, verifyAccountInfo, formatPartialSecretKey } = require('../to
|
|
|
11
11
|
const { templateSchemas, accountIdSchema, tokenPermissionsSchema } = require('../schemas');
|
|
12
12
|
const tokenPermissionView = require('../token-permission-view');
|
|
13
13
|
const { Account, accountExists } = require('../account');
|
|
14
|
+
const { isMcpEnabled } = require('../mcp');
|
|
14
15
|
const { Gateway } = require('../gateway');
|
|
15
16
|
const { templates } = require('../templates');
|
|
16
17
|
const { webhooks } = require('../webhooks');
|
|
17
18
|
const consts = require('../consts');
|
|
18
19
|
const wellKnownServices = require('nodemailer/lib/well-known/services.json');
|
|
19
|
-
const { authAwareLevel, resolveKnownAccounts, adminUrl } = require('./route-helpers');
|
|
20
|
+
const { authAwareLevel, resolveKnownAccounts, adminUrl, mcpToolGrants, accountPickerEntry } = require('./route-helpers');
|
|
20
21
|
const exampleWebhookPayloads = require('../payload-examples-webhooks.json');
|
|
21
22
|
|
|
22
23
|
const { DEFAULT_PAGE_SIZE } = consts;
|
|
23
24
|
|
|
25
|
+
// Every scope the admin token form can mint - one list, because the listing's ?scope= filter
|
|
26
|
+
// validates against the same vocabulary and a scope added to one side must not leave the other
|
|
27
|
+
// behind. Deliberately wider than the /v1/tokens set, which excludes '*' and 'metrics'.
|
|
28
|
+
const ADMIN_TOKEN_SCOPES = ['*', 'api', 'metrics', 'smtp', 'imap-proxy', 'mcp'];
|
|
29
|
+
|
|
24
30
|
const notificationTypes = Object.keys(consts)
|
|
25
31
|
.map(key => {
|
|
26
32
|
if (/_NOTIFY$/.test(key)) {
|
|
@@ -2182,7 +2188,11 @@ return payload;`)
|
|
|
2182
2188
|
// Every token on the instance, not just the unbound ones. A bound token lives in its
|
|
2183
2189
|
// account's index, so without this the page that manages access tokens was the one
|
|
2184
2190
|
// place a bound token could not be seen - and the form can now issue one directly.
|
|
2185
|
-
all: !request.query.account
|
|
2191
|
+
all: !request.query.account,
|
|
2192
|
+
// The deep-link filter the MCP pages use ("which agents are connected"), general
|
|
2193
|
+
// over every scope because the listing search cannot answer it - scopes are not
|
|
2194
|
+
// among the fields it matches
|
|
2195
|
+
scope: request.query.scope
|
|
2186
2196
|
});
|
|
2187
2197
|
|
|
2188
2198
|
// A token outlives the account it was bound to: deleting an account drops that account's
|
|
@@ -2238,6 +2248,10 @@ return payload;`)
|
|
|
2238
2248
|
url.searchParams.append('query', request.query.query);
|
|
2239
2249
|
}
|
|
2240
2250
|
|
|
2251
|
+
if (request.query.scope) {
|
|
2252
|
+
url.searchParams.append('scope', request.query.scope);
|
|
2253
|
+
}
|
|
2254
|
+
|
|
2241
2255
|
return url.pathname + url.search;
|
|
2242
2256
|
};
|
|
2243
2257
|
|
|
@@ -2268,9 +2282,15 @@ return payload;`)
|
|
|
2268
2282
|
searchTarget: '/admin/tokens',
|
|
2269
2283
|
searchPlaceholder: 'Search for access tokens…',
|
|
2270
2284
|
query: request.query.query,
|
|
2285
|
+
// The active scope filter, so the page can say it is showing a subset and
|
|
2286
|
+
// offer the way out of it
|
|
2287
|
+
scopeFilter: request.query.scope,
|
|
2271
2288
|
// The create button leads to a form that cannot submit without an admin session
|
|
2272
2289
|
canProvision: request.auth.isAuthenticated,
|
|
2273
|
-
searchHidden:
|
|
2290
|
+
searchHidden: [
|
|
2291
|
+
request.query.account ? { name: 'account', value: request.query.account } : null,
|
|
2292
|
+
request.query.scope ? { name: 'scope', value: request.query.scope } : null
|
|
2293
|
+
].filter(entry => entry),
|
|
2274
2294
|
total: data.total,
|
|
2275
2295
|
|
|
2276
2296
|
account: accountData,
|
|
@@ -2312,7 +2332,13 @@ return payload;`)
|
|
|
2312
2332
|
// Trimmed like the /v1/tokens listing: an untrimmed whitespace-only value is a
|
|
2313
2333
|
// query to the route and no query at all to the filter, so the listing would
|
|
2314
2334
|
// read every record on the instance and then match all of them
|
|
2315
|
-
query: Joi.string().empty('').trim().example('prometheus').description('Filter by search term')
|
|
2335
|
+
query: Joi.string().empty('').trim().example('prometheus').description('Filter by search term'),
|
|
2336
|
+
// The vocabulary the token form accepts, so the filter cannot name a scope
|
|
2337
|
+
// no token could carry
|
|
2338
|
+
scope: Joi.string()
|
|
2339
|
+
.empty('')
|
|
2340
|
+
.valid(...ADMIN_TOKEN_SCOPES)
|
|
2341
|
+
.description('Only tokens carrying this scope')
|
|
2316
2342
|
})
|
|
2317
2343
|
}
|
|
2318
2344
|
}
|
|
@@ -2333,6 +2359,14 @@ return payload;`)
|
|
|
2333
2359
|
|
|
2334
2360
|
const permissionModel = tokenPermissionView.formModel();
|
|
2335
2361
|
|
|
2362
|
+
// What an mcp-scoped token would actually be able to call, per (action, group) grant.
|
|
2363
|
+
// The form counts the surviving tools against the selected narrowing, which is the only
|
|
2364
|
+
// answer a reader of the two axes cannot work out for themselves: the MCP surface reaches
|
|
2365
|
+
// six of the thirteen sections, so a section ticked here can add nothing at all to it.
|
|
2366
|
+
// From the registry the endpoint itself dispatches through, like the MCP config page's
|
|
2367
|
+
// catalog, so the count cannot describe a tool set that has since changed.
|
|
2368
|
+
const mcpTools = mcpToolGrants(server, request.logger);
|
|
2369
|
+
|
|
2336
2370
|
return h.view(
|
|
2337
2371
|
'tokens/new',
|
|
2338
2372
|
{
|
|
@@ -2351,7 +2385,22 @@ return payload;`)
|
|
|
2351
2385
|
...permissionModel,
|
|
2352
2386
|
// Handed to the page as data rather than restated in its script
|
|
2353
2387
|
permissionSurfacesJson: JSON.stringify(permissionModel.permissionSurfaces),
|
|
2388
|
+
mcpTools,
|
|
2389
|
+
// The same three access levels the OAuth consent prompt and the MCP config
|
|
2390
|
+
// page offer, from the same table, rendered through the same partial. An
|
|
2391
|
+
// mcp-scoped token is minted from three places and the levels have to mean
|
|
2392
|
+
// the same thing in all of them.
|
|
2393
|
+
accessOptions: tokenPermissionView.MCP_ACCESS_LEVEL_OPTIONS,
|
|
2394
|
+
mcpAccessPresets: tokenPermissionView.MCP_ACCESS_LEVELS,
|
|
2395
|
+
// Whether the endpoint an mcp-scoped token would talk to is actually serving.
|
|
2396
|
+
// Both halves of the gate, because a token minted against either one being off
|
|
2397
|
+
// is a credential for nothing, and the form is the last place to say so.
|
|
2398
|
+
mcpReady: await isMcpEnabled(),
|
|
2354
2399
|
account: accountData,
|
|
2400
|
+
// The account picker's starting state, from the record already loaded above:
|
|
2401
|
+
// arriving from an account's own token list pre-binds the form, and the picker
|
|
2402
|
+
// shows that as the account it names rather than as a raw id
|
|
2403
|
+
selectedAccount: accountData ? accountPickerEntry(accountData) : null,
|
|
2355
2404
|
accountTokensLink: accountTokensLink.pathname + accountTokensLink.search
|
|
2356
2405
|
},
|
|
2357
2406
|
{
|
|
@@ -2454,7 +2503,7 @@ return payload;`)
|
|
|
2454
2503
|
payload: Joi.object({
|
|
2455
2504
|
description: Joi.string().empty('').trim().max(1024).required().example('Token description').description('Token description'),
|
|
2456
2505
|
scopes: Joi.array()
|
|
2457
|
-
.items(Joi.string().valid(
|
|
2506
|
+
.items(Joi.string().valid(...ADMIN_TOKEN_SCOPES))
|
|
2458
2507
|
.required()
|
|
2459
2508
|
.label('Scopes'),
|
|
2460
2509
|
// Null when the restriction is off, which is what "not narrowed" means on the
|
|
@@ -1251,6 +1251,19 @@ function init(args) {
|
|
|
1251
1251
|
let authData = await settings.get('authData');
|
|
1252
1252
|
let hasExistingPassword = !!(authData && authData.password);
|
|
1253
1253
|
if (hasExistingPassword) {
|
|
1254
|
+
// The current-password field is a password check like the login form's, and
|
|
1255
|
+
// unthrottled it let a hijacked session guess the password at full speed - the
|
|
1256
|
+
// one thing a session alone is not supposed to reveal. Keyed on the account
|
|
1257
|
+
// rather than the address because the caller is already authenticated as it,
|
|
1258
|
+
// and the same budget as the login form's per-username limiter.
|
|
1259
|
+
let rateLimit = await h.checkRateLimit(`password:verify:${authData.user || 'admin'}`, 1, 10, 60);
|
|
1260
|
+
if (!rateLimit.success) {
|
|
1261
|
+
request.logger.warn({ msg: 'Rate limited', rateLimit, remoteAddress: request.app.ip });
|
|
1262
|
+
let err = new Error('Rate limited, please wait and try again');
|
|
1263
|
+
err.details = { password0: err.message };
|
|
1264
|
+
throw err;
|
|
1265
|
+
}
|
|
1266
|
+
|
|
1254
1267
|
let valid;
|
|
1255
1268
|
try {
|
|
1256
1269
|
valid = await pbkdf2.verify(authData.password, request.payload.password0);
|
|
@@ -0,0 +1,330 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// The consent page of the MCP OAuth flow: the one step with a human in it. An MCP client sends
|
|
4
|
+
// the operator's browser here; approving mints a single-use authorization code that the client
|
|
5
|
+
// exchanges for an mcp-scoped access token at POST /mcp/oauth/token.
|
|
6
|
+
//
|
|
7
|
+
// Nothing reachable before the human clicks ever redirects off this origin. RFC 6749 4.1.2.1
|
|
8
|
+
// only forbids redirecting when the client or the redirect_uri cannot be validated, and an
|
|
9
|
+
// earlier revision of this file followed that literally: a validated-but-malformed request
|
|
10
|
+
// (wrong response_type, a code_challenge_method other than S256, a resource naming another
|
|
11
|
+
// server) bounced straight back to the client's address with ?error=. Client registration is
|
|
12
|
+
// open and unauthenticated, so anyone could register their own https redirect_uri and turn that
|
|
13
|
+
// into a no-interaction redirect off the admin origin - an open redirector aimed by whoever
|
|
14
|
+
// composed the link, which is exactly what the rule exists to prevent. Those cases now render
|
|
15
|
+
// the error page instead. The cost is that a misconfigured client gets no callback for them,
|
|
16
|
+
// which is the right trade: a conforming client never sends them, and a developer debugging one
|
|
17
|
+
// reads the reason on screen.
|
|
18
|
+
//
|
|
19
|
+
// Only the two outcomes of a human decision redirect: approval carries the code, Deny carries
|
|
20
|
+
// error=access_denied.
|
|
21
|
+
//
|
|
22
|
+
// Approval requires request.auth.isAuthenticated, exactly like the admin token mint
|
|
23
|
+
// (lib/ui-routes/admin-entities-routes.js): a token is never invalidated once issued, and the
|
|
24
|
+
// session default is applied conditionally, so the gate has to key on the actual request
|
|
25
|
+
// principal rather than the global secured-state.
|
|
26
|
+
|
|
27
|
+
const Boom = require('@hapi/boom');
|
|
28
|
+
const Joi = require('joi');
|
|
29
|
+
|
|
30
|
+
const { redis } = require('../db');
|
|
31
|
+
const { accountExists } = require('../account');
|
|
32
|
+
const { accountPickerSelection, mcpToolGrants } = require('./route-helpers');
|
|
33
|
+
const { failAction } = require('../tools');
|
|
34
|
+
const { accountIdSchema } = require('../schemas');
|
|
35
|
+
const { MCP_ACCESS_LEVELS, MCP_ACCESS_LEVEL_OPTIONS, MCP_GRANT_WORDING } = require('../token-permission-view');
|
|
36
|
+
const { mcpFeatureEnabled } = require('../mcp');
|
|
37
|
+
const { oauthOrigin, getClient, touchClient, createAuthorizationCode, isAcceptableResource } = require('../mcp/oauth');
|
|
38
|
+
|
|
39
|
+
// The OAuth request parameters, carried through the GET render and posted back with the
|
|
40
|
+
// decision. state is a client-side value with no format promises; the size bounds are only
|
|
41
|
+
// there so the consent form cannot be used to store arbitrary blobs in a hidden field.
|
|
42
|
+
const oauthParamsSchema = {
|
|
43
|
+
client_id: Joi.string().hex().length(32).required(),
|
|
44
|
+
redirect_uri: Joi.string().uri().max(2048).required(),
|
|
45
|
+
state: Joi.string().max(4096).allow(''),
|
|
46
|
+
code_challenge: Joi.string()
|
|
47
|
+
.pattern(/^[A-Za-z0-9\-._~]{43,128}$/)
|
|
48
|
+
.required(),
|
|
49
|
+
resource: Joi.string().max(2048).allow('')
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
function redirectHostOf(redirectUri) {
|
|
53
|
+
try {
|
|
54
|
+
return new URL(redirectUri).host || redirectUri;
|
|
55
|
+
} catch (err) {
|
|
56
|
+
return redirectUri;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// Sends the browser back to the client. `state` and the RFC 9207 `iss` marker ride along on
|
|
61
|
+
// every authorization response, success and failure alike, so each call site names only what
|
|
62
|
+
// is specific to it.
|
|
63
|
+
function redirectToClient(h, { redirectUri, state, origin }, params) {
|
|
64
|
+
const url = new URL(redirectUri);
|
|
65
|
+
for (const [key, value] of Object.entries(Object.assign({ state, iss: origin }, params))) {
|
|
66
|
+
if (value !== undefined && value !== null && value !== '') {
|
|
67
|
+
url.searchParams.set(key, value);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
return h.redirect(url.href);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// Both render paths use the chrome-free `prompt` layout: the operator lands here from an MCP
|
|
74
|
+
// client mid-flow, so the page reads as a consent dialog, not as a place inside the admin app.
|
|
75
|
+
// It is still an admin-surface page (admin session gate, admin IP perimeter, FlyonUI) - only
|
|
76
|
+
// the navigation chrome is gone.
|
|
77
|
+
function renderError(h, message) {
|
|
78
|
+
return h.view(
|
|
79
|
+
'mcp/authorize',
|
|
80
|
+
{
|
|
81
|
+
pageTitle: 'Authorize MCP client',
|
|
82
|
+
errorMessage: message
|
|
83
|
+
},
|
|
84
|
+
{ layout: 'prompt' }
|
|
85
|
+
);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
async function init(args) {
|
|
89
|
+
const { server } = args;
|
|
90
|
+
|
|
91
|
+
// The one construction of the consent view context, shared by the GET render and the POST
|
|
92
|
+
// re-render, so the two cannot drift on what the page needs.
|
|
93
|
+
async function renderConsent(h, { client, redirectUri, canProvision, values, errors }) {
|
|
94
|
+
// Only resolved for a render that can actually approve, and only when the form carries an
|
|
95
|
+
// account at all: the picker fetches its own suggestions, so a render costs an account
|
|
96
|
+
// lookup exactly when there is a choice on the form to show back
|
|
97
|
+
const selectedAccount = canProvision && values && values.account ? await accountPickerSelection(values.account, server.logger) : null;
|
|
98
|
+
|
|
99
|
+
// Read-only unless the operator picked otherwise; a re-render after a validation error
|
|
100
|
+
// keeps whatever they chose. The template compares this against each option itself
|
|
101
|
+
// (the `equals` helper), so the level is one value rather than three booleans.
|
|
102
|
+
const accessLevel = values && Object.hasOwn(MCP_ACCESS_LEVELS, values.access) ? values.access : 'read';
|
|
103
|
+
|
|
104
|
+
// From the registry the endpoint dispatches through, so the count under the radios cannot
|
|
105
|
+
// describe a tool set that has since changed
|
|
106
|
+
const mcpTools = mcpToolGrants(server, server.logger);
|
|
107
|
+
|
|
108
|
+
return h.view(
|
|
109
|
+
'mcp/authorize',
|
|
110
|
+
{
|
|
111
|
+
pageTitle: 'Authorize MCP client',
|
|
112
|
+
|
|
113
|
+
clientName: (client && client.client_name) || 'An MCP client',
|
|
114
|
+
redirectHost: redirectHostOf(redirectUri),
|
|
115
|
+
|
|
116
|
+
// What approving actually grants, in plain words, derived once at load from the
|
|
117
|
+
// same tables the enforcement reads - hand-written prose here would drift the
|
|
118
|
+
// first time the tool set changes
|
|
119
|
+
grantWording: MCP_GRANT_WORDING,
|
|
120
|
+
|
|
121
|
+
accessLevel,
|
|
122
|
+
// The radio group itself renders through the shared mcp_access_levels partial
|
|
123
|
+
accessOptions: MCP_ACCESS_LEVEL_OPTIONS,
|
|
124
|
+
|
|
125
|
+
// The tool count under the radios, through the shared mcp_tool_count partial. The
|
|
126
|
+
// grant sentences above it say what a level allows in the permission vocabulary;
|
|
127
|
+
// this says which tools the client ends up holding, which is the thing the person
|
|
128
|
+
// approving is actually being asked about.
|
|
129
|
+
mcpTools,
|
|
130
|
+
mcpAccessPresets: MCP_ACCESS_LEVELS,
|
|
131
|
+
|
|
132
|
+
selectedAccount,
|
|
133
|
+
|
|
134
|
+
// Mirrors the admin token mint: the form warns instead of letting the operator
|
|
135
|
+
// fill everything in and lose it to a 403
|
|
136
|
+
canProvision,
|
|
137
|
+
|
|
138
|
+
values,
|
|
139
|
+
errors
|
|
140
|
+
},
|
|
141
|
+
{ layout: 'prompt' }
|
|
142
|
+
);
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
if (!mcpFeatureEnabled) {
|
|
146
|
+
// Same shape as the Document Store UI module: with the deployment gate off, the routes
|
|
147
|
+
// do not exist
|
|
148
|
+
return;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
server.route({
|
|
152
|
+
method: 'GET',
|
|
153
|
+
path: '/admin/mcp/authorize',
|
|
154
|
+
|
|
155
|
+
async handler(request, h) {
|
|
156
|
+
const origin = await oauthOrigin();
|
|
157
|
+
if (!origin) {
|
|
158
|
+
return renderError(h, 'MCP OAuth sign-in is not enabled on this instance. Enable it under Configuration > MCP.');
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
const client = await getClient(request.query.client_id);
|
|
162
|
+
if (!client) {
|
|
163
|
+
return renderError(h, 'Unknown MCP client. The client registration may have expired - ask the client to register again.');
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
if (!client.redirect_uris.includes(request.query.redirect_uri)) {
|
|
167
|
+
return renderError(h, 'The redirect address of this request is not registered for the client, so the request cannot be trusted.');
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
// Rendered, never redirected: see the note at the top of this file on why a
|
|
171
|
+
// validated redirect_uri is not enough to make an automatic redirect safe here
|
|
172
|
+
if (request.query.response_type !== 'code') {
|
|
173
|
+
return renderError(h, `This client asked for an unsupported response type ("${request.query.response_type}"). Only "code" is supported.`);
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
if (request.query.code_challenge_method && request.query.code_challenge_method !== 'S256') {
|
|
177
|
+
return renderError(h, 'This client asked for an unsupported PKCE method. Only "S256" is supported.');
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
if (!isAcceptableResource(request.query.resource, origin)) {
|
|
181
|
+
return renderError(h, 'This authorization request names a different server as its resource, so it was not meant for this instance.');
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
await touchClient(client.client_id);
|
|
185
|
+
|
|
186
|
+
return renderConsent(h, {
|
|
187
|
+
client,
|
|
188
|
+
redirectUri: request.query.redirect_uri,
|
|
189
|
+
canProvision: request.auth.isAuthenticated,
|
|
190
|
+
values: {
|
|
191
|
+
client_id: client.client_id,
|
|
192
|
+
redirect_uri: request.query.redirect_uri,
|
|
193
|
+
state: request.query.state,
|
|
194
|
+
code_challenge: request.query.code_challenge,
|
|
195
|
+
resource: request.query.resource
|
|
196
|
+
}
|
|
197
|
+
});
|
|
198
|
+
},
|
|
199
|
+
|
|
200
|
+
options: {
|
|
201
|
+
validate: {
|
|
202
|
+
options: {
|
|
203
|
+
stripUnknown: true,
|
|
204
|
+
abortEarly: false,
|
|
205
|
+
convert: true
|
|
206
|
+
},
|
|
207
|
+
|
|
208
|
+
// A malformed authorization request never reaches a redirect, so the failure
|
|
209
|
+
// renders in place
|
|
210
|
+
failAction: (request, h) => renderError(h, 'This MCP authorization link is malformed or incomplete.').takeover(),
|
|
211
|
+
|
|
212
|
+
query: Joi.object(
|
|
213
|
+
Object.assign({}, oauthParamsSchema, {
|
|
214
|
+
response_type: Joi.string().max(64).required(),
|
|
215
|
+
code_challenge_method: Joi.string().max(64),
|
|
216
|
+
scope: Joi.string().max(1024).allow('')
|
|
217
|
+
})
|
|
218
|
+
)
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
});
|
|
222
|
+
|
|
223
|
+
server.route({
|
|
224
|
+
method: 'POST',
|
|
225
|
+
path: '/admin/mcp/authorize',
|
|
226
|
+
|
|
227
|
+
async handler(request, h) {
|
|
228
|
+
const origin = await oauthOrigin();
|
|
229
|
+
if (!origin) {
|
|
230
|
+
return renderError(h, 'MCP OAuth sign-in is not enabled on this instance.');
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
const client = await getClient(request.payload.client_id);
|
|
234
|
+
if (!client || !client.redirect_uris.includes(request.payload.redirect_uri)) {
|
|
235
|
+
return renderError(h, 'Unknown MCP client or unregistered redirect address. The registration may have expired while this page was open.');
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
const authRequest = { redirectUri: request.payload.redirect_uri, state: request.payload.state, origin };
|
|
239
|
+
|
|
240
|
+
// Denying is checked before the mint gate, and needs no credential: refusing to hand
|
|
241
|
+
// out a token is not an action that requires the authority to hand one out. With no
|
|
242
|
+
// admin password set the page hides Approve and tells the operator that denying is
|
|
243
|
+
// all they can do, so a 403 on Deny would leave the client waiting for a callback
|
|
244
|
+
// that the only available button could never send.
|
|
245
|
+
if (request.payload.decision !== 'approve') {
|
|
246
|
+
return redirectToClient(h, authRequest, { error: 'access_denied' });
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
// The same rule as the admin token mint, for the same reason: this POST creates a
|
|
250
|
+
// lasting credential, so it needs a real authenticated admin session on THIS request
|
|
251
|
+
if (!request.auth.isAuthenticated) {
|
|
252
|
+
throw Boom.forbidden('Can not authorize an MCP client without an authenticated admin session');
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
// Re-checked here and not only on the GET, because the POST is where the value is
|
|
256
|
+
// written onto the code record and the GET is not what supplied it - a hand-crafted
|
|
257
|
+
// form can name any resource it likes. Redemption refuses a code whose resource does
|
|
258
|
+
// not name this server, so without this the mint succeeds and the exchange fails,
|
|
259
|
+
// which reads to the operator as an approval that did nothing.
|
|
260
|
+
if (!isAcceptableResource(request.payload.resource, origin)) {
|
|
261
|
+
return renderError(h, 'This authorization request names a different server as its resource, so it was not meant for this instance.');
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
const account = request.payload.account || null;
|
|
265
|
+
if (account && !(await accountExists(redis, account))) {
|
|
266
|
+
return renderConsent(h, {
|
|
267
|
+
client,
|
|
268
|
+
redirectUri: request.payload.redirect_uri,
|
|
269
|
+
canProvision: true,
|
|
270
|
+
values: request.payload,
|
|
271
|
+
errors: { account: 'No such account' }
|
|
272
|
+
});
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
// Read-only is the default here exactly as it is on the admin generator, and for a
|
|
276
|
+
// stronger reason: this flow issues credentials to the least controllable clients on
|
|
277
|
+
// the least controllable devices. The radio always posts a value, so the schema
|
|
278
|
+
// default only ever fires for a stale or hand-crafted POST - and defaulting that to
|
|
279
|
+
// 'read' means an omitted field mints the narrowest token, not the widest.
|
|
280
|
+
const access = request.payload.access;
|
|
281
|
+
|
|
282
|
+
const code = await createAuthorizationCode({
|
|
283
|
+
clientId: client.client_id,
|
|
284
|
+
redirectUri: request.payload.redirect_uri,
|
|
285
|
+
codeChallenge: request.payload.code_challenge,
|
|
286
|
+
resource: request.payload.resource || null,
|
|
287
|
+
account,
|
|
288
|
+
permissions: MCP_ACCESS_LEVELS[access],
|
|
289
|
+
description: `MCP: ${client.client_name || redirectHostOf(request.payload.redirect_uri)}${account ? ` (${account})` : ''}`
|
|
290
|
+
});
|
|
291
|
+
|
|
292
|
+
request.logger.info({
|
|
293
|
+
msg: 'Approved an MCP OAuth authorization',
|
|
294
|
+
client: client.client_id,
|
|
295
|
+
clientName: client.client_name,
|
|
296
|
+
account,
|
|
297
|
+
access
|
|
298
|
+
});
|
|
299
|
+
|
|
300
|
+
return redirectToClient(h, authRequest, { code });
|
|
301
|
+
},
|
|
302
|
+
|
|
303
|
+
options: {
|
|
304
|
+
validate: {
|
|
305
|
+
options: {
|
|
306
|
+
stripUnknown: true,
|
|
307
|
+
abortEarly: false,
|
|
308
|
+
convert: true
|
|
309
|
+
},
|
|
310
|
+
|
|
311
|
+
failAction,
|
|
312
|
+
|
|
313
|
+
payload: Joi.object(
|
|
314
|
+
Object.assign({}, oauthParamsSchema, {
|
|
315
|
+
decision: Joi.string().valid('approve', 'deny').required(),
|
|
316
|
+
account: accountIdSchema.allow('').default(null),
|
|
317
|
+
// The keys of MCP_ACCESS_LEVELS, defaulting to the narrowest: a payload
|
|
318
|
+
// that names no level (a stale form, a hand-crafted POST) mints the
|
|
319
|
+
// read-only token, never the wide one
|
|
320
|
+
access: Joi.string()
|
|
321
|
+
.valid(...Object.keys(MCP_ACCESS_LEVELS))
|
|
322
|
+
.default('read')
|
|
323
|
+
})
|
|
324
|
+
)
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
});
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
module.exports = init;
|