emailengine-app 2.79.9 → 2.80.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.release-please-manifest.json +1 -1
- package/CHANGELOG.md +73 -0
- package/README.md +6 -0
- package/config/default.toml +5 -1
- package/data/google-crawlers.json +1 -1
- package/encrypt.js +43 -0
- package/lib/account/account-state.js +62 -0
- package/lib/account.js +34 -2
- package/lib/api-routes/account-routes.js +101 -1
- package/lib/api-routes/blocklist-routes.js +24 -0
- package/lib/api-routes/delivery-test-routes.js +6 -0
- package/lib/api-routes/gateway-routes.js +30 -0
- package/lib/api-routes/index.js +1 -1
- package/lib/api-routes/license-routes.js +10 -0
- package/lib/api-routes/mcp-oauth-routes.js +3 -3
- package/lib/api-routes/mcp-routes.js +39 -21
- package/lib/api-routes/oauth2-app-routes.js +38 -1
- package/lib/api-routes/outbox-routes.js +6 -0
- package/lib/api-routes/permission-map.js +208 -43
- package/lib/api-routes/pubsub-routes.js +8 -0
- package/lib/api-routes/route-helpers.js +58 -11
- package/lib/api-routes/settings-routes.js +67 -6
- package/lib/api-routes/stats-routes.js +6 -0
- package/lib/api-routes/template-routes.js +21 -0
- package/lib/api-routes/token-routes.js +34 -2
- package/lib/api-routes/webhook-route-routes.js +13 -0
- package/lib/autodetect-imap-settings.js +349 -47
- package/lib/cert-handler.js +62 -0
- package/lib/consts.js +50 -6
- package/lib/db.js +12 -0
- package/lib/egress-fetch.js +21 -9
- package/lib/email-client/base-client.js +238 -67
- package/lib/email-client/credential-errors.js +122 -0
- package/lib/email-client/gmail/gmail-api.js +2 -1
- package/lib/email-client/gmail-client.js +70 -64
- package/lib/email-client/imap/connection-errors.js +52 -0
- package/lib/email-client/imap/listing-diff.js +47 -6
- package/lib/email-client/imap/login-failure.js +52 -0
- package/lib/email-client/imap/mailbox.js +457 -379
- package/lib/email-client/imap/subconnection.js +17 -12
- package/lib/email-client/imap/sync-operations.js +46 -59
- package/lib/email-client/imap-client.js +139 -101
- package/lib/email-client/message-builder.js +11 -11
- package/lib/email-client/outlook/graph-api.js +2 -1
- package/lib/email-client/outlook-client.js +219 -106
- package/lib/enum-descriptions.js +12 -2
- package/lib/imap-proxy-auth.js +58 -3
- package/lib/imapproxy/imap-server.js +53 -62
- package/lib/lua/h-del-if-equals.lua +39 -0
- package/lib/lua/h-set-if-equals.lua +39 -0
- package/lib/mcp/oauth.js +46 -8
- package/lib/mcp/protocol.js +78 -35
- package/lib/mcp/tools.js +53 -17
- package/lib/privileged-settings.js +147 -0
- package/lib/routes-ui.js +4 -34
- package/lib/schemas.js +92 -16
- package/lib/security-headers.js +15 -0
- package/lib/settings.js +13 -0
- package/lib/tls/catalog.js +428 -0
- package/lib/tls/context.js +302 -0
- package/lib/tls/der.js +223 -0
- package/lib/tls/listeners.js +62 -0
- package/lib/tls/provision.js +555 -0
- package/lib/tls/self-signed.js +282 -0
- package/lib/tls/status.js +480 -0
- package/lib/tls/store.js +667 -0
- package/lib/token-permission-view.js +252 -102
- package/lib/token-permissions.js +176 -26
- package/lib/tokens.js +7 -6
- package/lib/tools.js +73 -27
- package/lib/ui-routes/account-routes.js +43 -30
- package/lib/ui-routes/admin-config-routes.js +63 -22
- package/lib/ui-routes/admin-entities-routes.js +23 -13
- package/lib/ui-routes/auth-routes.js +16 -1
- package/lib/ui-routes/internals-routes.js +3 -5
- package/lib/ui-routes/mcp-consent-routes.js +72 -31
- package/lib/ui-routes/network-config-routes.js +54 -45
- package/lib/ui-routes/tls-config-routes.js +628 -0
- package/lib/utils/mailbox-path.js +51 -0
- package/lib/utils/severity.js +31 -0
- package/package.json +12 -12
- package/sbom.json +1 -1
- package/server.js +23 -1
- package/static/css/flyonui.css +1 -1
- package/static/css/src/app.tailwind.css +11 -0
- package/static/js/app.js +34 -0
- package/static/js/public.js +6 -2
- package/static/js/ui.js +97 -61
- package/static/licenses.html +341 -1252
- package/translations/messages.pot +62 -56
- package/views/account/login-redirect.hbs +22 -0
- package/views/account/passkeys.hbs +2 -2
- package/views/accounts/account.hbs +2 -2
- package/views/accounts/browse.hbs +1 -1
- package/views/accounts/edit.hbs +1 -1
- package/views/accounts/register/imap-server.hbs +1 -1
- package/views/config/ai.hbs +1 -1
- package/views/config/branding.hbs +2 -2
- package/views/config/document-store/chat.hbs +1 -1
- package/views/config/document-store/index.hbs +1 -1
- package/views/config/imap-proxy.hbs +1 -4
- package/views/config/license.hbs +1 -1
- package/views/config/mcp.hbs +88 -52
- package/views/config/network.hbs +1 -1
- package/views/config/oauth/app.hbs +2 -2
- package/views/config/service.hbs +1 -1
- package/views/config/smtp.hbs +1 -4
- package/views/config/tls-upload.hbs +81 -0
- package/views/config/tls.hbs +593 -0
- package/views/config/webhooks.hbs +2 -2
- package/views/internals/index.hbs +1 -1
- package/views/layout/app.hbs +6 -6
- package/views/layout/login.hbs +5 -5
- package/views/layout/main.hbs +2 -2
- package/views/layout/prompt.hbs +3 -3
- package/views/layout/public.hbs +1 -1
- package/views/mcp/authorize.hbs +47 -45
- package/views/partials/ace_assets.hbs +1 -1
- package/views/partials/add_account_modal.hbs +1 -1
- package/views/partials/filter_editor_js.hbs +2 -2
- package/views/partials/gateway_js.hbs +1 -1
- package/views/partials/mcp_access_levels.hbs +16 -9
- package/views/partials/mcp_tool_count.hbs +15 -14
- package/views/partials/oauth_form.hbs +1 -1
- package/views/partials/public_theme_init.hbs +1 -1
- package/views/partials/side_menu.hbs +1 -0
- package/views/partials/template_form.hbs +1 -1
- package/views/partials/theme_init.hbs +1 -1
- package/views/partials/tls_security_card.hbs +25 -53
- package/views/partials/ui/alert-banner.hbs +3 -2
- package/views/partials/ui/badge.hbs +6 -2
- package/views/partials/ui/btn.hbs +5 -2
- package/views/partials/webhooks_editor_functions.hbs +1 -1
- package/views/reference/index.hbs +1 -1
- package/views/reference/redirect.hbs +1 -1
- package/views/reference/tag.hbs +1 -1
- package/views/reference/token.hbs +1 -1
- package/views/templates/template.hbs +1 -1
- package/views/tokens/new.hbs +175 -74
- package/views/unsubscribe.hbs +1 -1
- package/views/webhooks/webhook.hbs +1 -1
- package/workers/api.js +102 -142
- package/workers/imap-proxy.js +4 -1
- package/workers/smtp.js +51 -44
- package/views/partials/tls_security_js.hbs +0 -64
- package/views/partials/tls_security_modal.hbs +0 -22
|
@@ -16,18 +16,16 @@ const {
|
|
|
16
16
|
readEnvValue,
|
|
17
17
|
emitChangeEvent,
|
|
18
18
|
loadTlsConfig,
|
|
19
|
-
assertTlsCredentials
|
|
20
|
-
httpAgent
|
|
19
|
+
assertTlsCredentials
|
|
21
20
|
} = require('../tools');
|
|
22
21
|
const { getLocalAddress } = require('../utils/network');
|
|
23
22
|
|
|
24
23
|
const { redis } = require('../db');
|
|
25
|
-
const { createImapProxyAuthHandler,
|
|
26
|
-
const getSecret = require('../get-secret');
|
|
24
|
+
const { createImapProxyAuthHandler, classifyCredentialFailure, isImapResponseError, toImapResponseError } = require('../imap-proxy-auth');
|
|
27
25
|
const settings = require('../settings');
|
|
28
26
|
|
|
29
|
-
const {
|
|
30
|
-
const {
|
|
27
|
+
const { createCertHandler } = require('../cert-handler');
|
|
28
|
+
const { createTlsContext, applyTlsContext } = require('../tls/context');
|
|
31
29
|
|
|
32
30
|
config.imap = config.imap || {
|
|
33
31
|
enabled: false,
|
|
@@ -44,7 +42,7 @@ const EENGINE_TIMEOUT = getDuration(readEnvValue('EENGINE_TIMEOUT') || config.se
|
|
|
44
42
|
const EENGINE_LOG_RAW = hasEnvValue('EENGINE_LOG_RAW') ? getBoolean(readEnvValue('EENGINE_LOG_RAW')) : getBoolean(config.log.raw);
|
|
45
43
|
const DISABLE_IMAP_COMPRESSION = getBoolean(readEnvValue('EENGINE_DISABLE_COMPRESSION'));
|
|
46
44
|
|
|
47
|
-
const {
|
|
45
|
+
const { TLS_DEFAULTS } = require('../consts');
|
|
48
46
|
|
|
49
47
|
let callQueue = new Map();
|
|
50
48
|
let mids = 0;
|
|
@@ -187,7 +185,7 @@ async function onAuth(auth, session) {
|
|
|
187
185
|
try {
|
|
188
186
|
imapAuth = await resolveCredentials(account, 'imap');
|
|
189
187
|
} catch (err) {
|
|
190
|
-
throw
|
|
188
|
+
throw classifyCredentialFailure(err);
|
|
191
189
|
}
|
|
192
190
|
} else {
|
|
193
191
|
if (!accountData.oauth2.accessToken || !accountData.oauth2.expires || accountData.oauth2.expires < new Date(Date.now() + 30 * 1000)) {
|
|
@@ -195,7 +193,7 @@ async function onAuth(auth, session) {
|
|
|
195
193
|
try {
|
|
196
194
|
accountData = await accountObject.renewAccessToken();
|
|
197
195
|
} catch (err) {
|
|
198
|
-
throw
|
|
196
|
+
throw classifyCredentialFailure(err);
|
|
199
197
|
}
|
|
200
198
|
}
|
|
201
199
|
imapAuth = { user: accountData.oauth2.auth.user, accessToken: accountData.oauth2.accessToken };
|
|
@@ -218,7 +216,7 @@ async function onAuth(auth, session) {
|
|
|
218
216
|
try {
|
|
219
217
|
imapConnectionConfig.auth = await resolveCredentials(account, 'imap');
|
|
220
218
|
} catch (err) {
|
|
221
|
-
throw
|
|
219
|
+
throw classifyCredentialFailure(err);
|
|
222
220
|
}
|
|
223
221
|
}
|
|
224
222
|
|
|
@@ -455,13 +453,9 @@ const createServer = function (options = {}) {
|
|
|
455
453
|
});
|
|
456
454
|
})
|
|
457
455
|
.catch(err => {
|
|
458
|
-
if (err
|
|
456
|
+
if (isImapResponseError(err)) {
|
|
459
457
|
serverLogger.warn({ msg: 'Upstream authentication failed', account, cid: session.id, err });
|
|
460
|
-
|
|
461
|
-
`${err.serverResponseCode ? `[${err.serverResponseCode}] ` : ''}${err.responseText || err.message || 'Authentication failed'}`
|
|
462
|
-
);
|
|
463
|
-
error.response = err.responseStatus || 'NO';
|
|
464
|
-
return callback(error);
|
|
458
|
+
return callback(toImapResponseError(err));
|
|
465
459
|
} else {
|
|
466
460
|
serverLogger.error({ msg: 'Failed to create proxy', account, cid: session.id, err });
|
|
467
461
|
return callback(err);
|
|
@@ -470,14 +464,10 @@ const createServer = function (options = {}) {
|
|
|
470
464
|
})
|
|
471
465
|
.catch(err => {
|
|
472
466
|
let entry = { msg: 'Authentication check failed', username: login.username, cid: session.id, remoteAddress: session.remoteAddress, err };
|
|
473
|
-
if (err
|
|
474
|
-
//
|
|
467
|
+
if (isImapResponseError(err)) {
|
|
468
|
+
// a refused login or a temporary failure the client is told to retry, not a proxy fault
|
|
475
469
|
serverLogger.warn(entry);
|
|
476
|
-
|
|
477
|
-
`${err.serverResponseCode ? `[${err.serverResponseCode}] ` : ''}${err.responseText || err.message || 'Authentication failed'}`
|
|
478
|
-
);
|
|
479
|
-
error.response = err.responseStatus || 'NO';
|
|
480
|
-
return callback(error);
|
|
470
|
+
return callback(toImapResponseError(err));
|
|
481
471
|
}
|
|
482
472
|
serverLogger.error(entry);
|
|
483
473
|
return callback(err);
|
|
@@ -487,6 +477,11 @@ const createServer = function (options = {}) {
|
|
|
487
477
|
return server;
|
|
488
478
|
};
|
|
489
479
|
|
|
480
|
+
// The running listener and the TLS material it serves, kept at module level so the certificate
|
|
481
|
+
// reload command can reach both without restarting the worker.
|
|
482
|
+
let proxyServer = null;
|
|
483
|
+
let tlsContext = null;
|
|
484
|
+
|
|
490
485
|
module.exports.run = async () => {
|
|
491
486
|
const serverOptions = {
|
|
492
487
|
useProxy: await settings.get('imapProxyServerProxy'),
|
|
@@ -501,64 +496,37 @@ module.exports.run = async () => {
|
|
|
501
496
|
const port = await settings.get('imapProxyServerPort');
|
|
502
497
|
const host = await settings.get('imapProxyServerHost');
|
|
503
498
|
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
namespace: `${REDIS_PREFIX}`,
|
|
507
|
-
|
|
508
|
-
environment: 'ee',
|
|
509
|
-
|
|
510
|
-
// long-lived client, see LiveDispatcher in lib/tools.js
|
|
511
|
-
dispatcher: httpAgent.live,
|
|
512
|
-
|
|
513
|
-
logger: logger.child({ sub: 'acme' }),
|
|
514
|
-
|
|
515
|
-
encryptFn: async value => {
|
|
516
|
-
const encryptSecret = await getSecret();
|
|
517
|
-
return encrypt(value, encryptSecret);
|
|
518
|
-
},
|
|
519
|
-
|
|
520
|
-
decryptFn: async value => {
|
|
521
|
-
const encryptSecret = await getSecret();
|
|
522
|
-
return decrypt(value, encryptSecret);
|
|
523
|
-
}
|
|
524
|
-
});
|
|
499
|
+
// Reads what the API worker provisioned; this one never orders a certificate itself.
|
|
500
|
+
let certs = createCertHandler(logger);
|
|
525
501
|
|
|
526
502
|
let tls = await settings.get('imapProxyServerTLSEnabled');
|
|
527
503
|
|
|
528
504
|
if (tls) {
|
|
529
505
|
serverOptions.secure = true;
|
|
530
506
|
|
|
531
|
-
//
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
507
|
+
// Environment and config-file material first, then whatever EmailEngine manages itself.
|
|
508
|
+
// The order used to be the other way round here, so an operator-supplied certificate was
|
|
509
|
+
// overwritten by an automatic one; lib/tls/context.js owns the precedence now.
|
|
535
510
|
loadTlsConfig(serverOptions, 'EENGINE_IMAPPROXY_TLS_');
|
|
536
511
|
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
'\n' +
|
|
543
|
-
[]
|
|
544
|
-
.concat(certificateData.ca || [])
|
|
545
|
-
.flatMap(entry => entry)
|
|
546
|
-
.join('\n');
|
|
547
|
-
serverOptions.key = certificateData.privateKey;
|
|
548
|
-
}
|
|
549
|
-
}
|
|
512
|
+
// The material loaded above is snapshotted inside, at entry, so a later refresh does not
|
|
513
|
+
// read what this resolution wrote back into serverOptions as if the operator had supplied
|
|
514
|
+
// it.
|
|
515
|
+
tlsContext = await createTlsContext({ certs, logger, listener: 'imapProxy', listenerOptions: serverOptions });
|
|
516
|
+
Object.assign(serverOptions, tlsContext.options);
|
|
550
517
|
|
|
551
518
|
assertTlsCredentials(serverOptions, 'The IMAP proxy');
|
|
552
519
|
}
|
|
553
520
|
|
|
554
521
|
const server = createServer(serverOptions);
|
|
522
|
+
proxyServer = server;
|
|
555
523
|
|
|
556
524
|
try {
|
|
557
525
|
await new Promise((resolve, reject) => {
|
|
558
526
|
server.once('error', err => reject(err));
|
|
559
527
|
server.listen(port || config.imap.port, host || config.imap.host, () => resolve(server));
|
|
560
528
|
});
|
|
561
|
-
await emitChangeEvent(logger, null, 'imapProxyServerState', 'listening');
|
|
529
|
+
await emitChangeEvent(logger, null, 'imapProxyServerState', 'listening', { tls: tlsContext ? tlsContext.active : null });
|
|
562
530
|
} catch (err) {
|
|
563
531
|
await emitChangeEvent(logger, null, 'imapProxyServerState', 'failed', {
|
|
564
532
|
error: { message: err.message, code: err.code || null }
|
|
@@ -568,3 +536,26 @@ module.exports.run = async () => {
|
|
|
568
536
|
|
|
569
537
|
return server;
|
|
570
538
|
};
|
|
539
|
+
|
|
540
|
+
/**
|
|
541
|
+
* Re-resolves the TLS material and hands it to the running proxy.
|
|
542
|
+
*
|
|
543
|
+
* Sessions already established keep the context they negotiated with. An IMAP client can hold a
|
|
544
|
+
* connection open for days, so restarting the worker to install a renewed certificate is the
|
|
545
|
+
* expensive way to do this.
|
|
546
|
+
*
|
|
547
|
+
* @returns {Promise<Object>} What the listener is serving after the reload
|
|
548
|
+
*/
|
|
549
|
+
module.exports.reloadCertificates = async () => {
|
|
550
|
+
const result = await applyTlsContext({
|
|
551
|
+
context: proxyServer ? tlsContext : null,
|
|
552
|
+
apply: options => proxyServer.updateSecureContext(options),
|
|
553
|
+
logger
|
|
554
|
+
});
|
|
555
|
+
|
|
556
|
+
if (result.updated) {
|
|
557
|
+
await emitChangeEvent(logger, null, 'imapProxyServerState', 'listening', { tls: result.tls });
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
return result;
|
|
561
|
+
};
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
--[[
|
|
2
|
+
Script: h-del-if-equals.lua
|
|
3
|
+
Purpose: Drops a set of hash fields only when a guard field still holds the value the caller read,
|
|
4
|
+
so a record that was replaced between the read and the delete is left for whoever wrote it.
|
|
5
|
+
|
|
6
|
+
The error state of an account is read, judged and then dropped. Everything in between is
|
|
7
|
+
an await, and another failure written in that window would be deleted by a decision taken
|
|
8
|
+
before it existed - leaving the account reporting a healthy state it is not in.
|
|
9
|
+
|
|
10
|
+
KEYS:
|
|
11
|
+
[1] hashKey - The hash key to operate on
|
|
12
|
+
|
|
13
|
+
ARGV:
|
|
14
|
+
[1] guardKey - The hash field whose value the decision was taken on
|
|
15
|
+
[2] expected - The value the caller read; an empty string means "expect the field to be absent"
|
|
16
|
+
[3..] fields - The fields to delete
|
|
17
|
+
|
|
18
|
+
Returns:
|
|
19
|
+
1 if the guard matched and the fields were dropped
|
|
20
|
+
0 if the guard holds something else, meaning the record is no longer the one that was judged
|
|
21
|
+
--]]
|
|
22
|
+
|
|
23
|
+
local hashKey = KEYS[1];
|
|
24
|
+
local guardKey = ARGV[1];
|
|
25
|
+
local expected = ARGV[2];
|
|
26
|
+
|
|
27
|
+
-- HGET answers a missing field with false, which is the same test as any other mismatch once it
|
|
28
|
+
-- is read as the empty string
|
|
29
|
+
local current = redis.call("HGET", hashKey, guardKey) or "";
|
|
30
|
+
|
|
31
|
+
if current ~= expected then
|
|
32
|
+
return 0;
|
|
33
|
+
end
|
|
34
|
+
|
|
35
|
+
if #ARGV > 2 then
|
|
36
|
+
redis.call("HDEL", hashKey, unpack(ARGV, 3));
|
|
37
|
+
end
|
|
38
|
+
|
|
39
|
+
return 1;
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
--[[
|
|
2
|
+
Script: h-set-if-equals.lua
|
|
3
|
+
Purpose: Replaces a hash field only when it still holds the value the caller last read, so two
|
|
4
|
+
processes that both decided to replace the same record converge on one winner instead of
|
|
5
|
+
overwriting each other.
|
|
6
|
+
|
|
7
|
+
HSETNX converges only when the field is absent. Deleting first and then HSETNX looks
|
|
8
|
+
equivalent but is not: between the delete and the set, a second process sees an empty field
|
|
9
|
+
and wins the HSETNX too, and both walk away believing they own the record.
|
|
10
|
+
|
|
11
|
+
KEYS:
|
|
12
|
+
[1] hashKey - The hash key to operate on
|
|
13
|
+
|
|
14
|
+
ARGV:
|
|
15
|
+
[1] entryKey - The hash field name
|
|
16
|
+
[2] value - The value to set
|
|
17
|
+
[3] expected - The value the caller read; an empty string means "expect the field to be absent"
|
|
18
|
+
|
|
19
|
+
Returns:
|
|
20
|
+
1 if the field matched and was replaced (or was absent as expected and created)
|
|
21
|
+
0 if the field holds something else, meaning another process got there first
|
|
22
|
+
--]]
|
|
23
|
+
|
|
24
|
+
local hashKey = KEYS[1];
|
|
25
|
+
local entryKey = ARGV[1];
|
|
26
|
+
|
|
27
|
+
local value = ARGV[2];
|
|
28
|
+
local expected = ARGV[3];
|
|
29
|
+
|
|
30
|
+
-- HGET answers a missing field with false, which is the same test as any other mismatch once it
|
|
31
|
+
-- is read as the empty string
|
|
32
|
+
local current = redis.call("HGET", hashKey, entryKey) or "";
|
|
33
|
+
|
|
34
|
+
if current ~= expected then
|
|
35
|
+
return 0;
|
|
36
|
+
end
|
|
37
|
+
|
|
38
|
+
redis.call("HSET", hashKey, entryKey, value);
|
|
39
|
+
return 1;
|
package/lib/mcp/oauth.js
CHANGED
|
@@ -5,10 +5,12 @@
|
|
|
5
5
|
// It exists for exactly one flow: an MCP client that cannot be configured with a static access
|
|
6
6
|
// token (claude.ai web connectors and similar) discovers this server through the protected
|
|
7
7
|
// resource metadata, registers itself as a public client, sends the operator's browser to the
|
|
8
|
-
// admin consent page, and exchanges the resulting code for an EmailEngine access token
|
|
9
|
-
//
|
|
10
|
-
//
|
|
11
|
-
//
|
|
8
|
+
// admin consent page, and exchanges the resulting code for an EmailEngine access token carrying
|
|
9
|
+
// the MCP scopes the operator approved (`mcp-manage` for the instance, `mcp` for mail, or both).
|
|
10
|
+
// Every credential this issues is an ordinary access token: visible on the admin tokens page,
|
|
11
|
+
// revocable there, and bounded by the SURFACE_GRANTS table of each scope it holds like any other
|
|
12
|
+
// MCP-scoped token. There are no refresh tokens and no expiry by default - revocation is the
|
|
13
|
+
// lifecycle.
|
|
12
14
|
//
|
|
13
15
|
// What is implemented, spec-wise: OAuth 2.0 Dynamic Client Registration (RFC 7591, open
|
|
14
16
|
// registration for public clients only, rate limited per IP), authorization code + PKCE S256
|
|
@@ -42,6 +44,25 @@ const CODE_TTL = 10 * 60;
|
|
|
42
44
|
// schema too, so the validation layer and the policy here cannot drift apart.
|
|
43
45
|
const MAX_REDIRECT_URIS = 10;
|
|
44
46
|
|
|
47
|
+
// The scopes this server issues, in the order the discovery documents advertise them and the
|
|
48
|
+
// order a token response lists them: management first, because that is what the consent page
|
|
49
|
+
// offers by default, and mail on request. A client that sends `scope=mcp` in its authorization
|
|
50
|
+
// request is asking for mail access; the consent page pre-ticks it, the person still decides.
|
|
51
|
+
const MCP_OAUTH_SCOPES = ['mcp-manage', 'mcp'];
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* The subset of the issuable scopes a list names, in canonical order. Anything else is dropped:
|
|
55
|
+
* the scope vocabulary is this server's to define, and an unknown value is not a narrower or
|
|
56
|
+
* wider grant, only noise from a client guessing.
|
|
57
|
+
*
|
|
58
|
+
* @param {Array|String} scopes - a scope list, or a space-separated scope string from the wire
|
|
59
|
+
* @returns {Array<String>}
|
|
60
|
+
*/
|
|
61
|
+
function normalizeScopes(scopes) {
|
|
62
|
+
const requested = new Set(typeof scopes === 'string' ? scopes.split(/\s+/) : [].concat(scopes || []));
|
|
63
|
+
return MCP_OAUTH_SCOPES.filter(scope => requested.has(scope));
|
|
64
|
+
}
|
|
65
|
+
|
|
45
66
|
const clientKey = clientId => `${REDIS_PREFIX}mcp:oauth:client:${clientId}`;
|
|
46
67
|
const codeKey = code => `${REDIS_PREFIX}mcp:oauth:code:${code}`;
|
|
47
68
|
|
|
@@ -205,10 +226,19 @@ function isAcceptableResource(resource, origin) {
|
|
|
205
226
|
* Mints a single-use authorization code after the admin approved the consent page.
|
|
206
227
|
*
|
|
207
228
|
* @param {Object} opts - clientId, redirectUri, codeChallenge, resource, account (optional
|
|
208
|
-
* binding for the token),
|
|
229
|
+
* binding for the token), scopes (the MCP scopes the operator approved), permissions,
|
|
230
|
+
* description (for the admin tokens listing)
|
|
209
231
|
* @returns {Promise<String>} the code
|
|
210
232
|
*/
|
|
211
233
|
async function createAuthorizationCode(opts) {
|
|
234
|
+
const scopes = normalizeScopes(opts.scopes);
|
|
235
|
+
if (!scopes.length) {
|
|
236
|
+
// A code that mints a token with no surface is a token that can do nothing; the consent
|
|
237
|
+
// page refuses the combination before it gets here, so this is the belt to that brace -
|
|
238
|
+
// and a caller that forgot the argument fails here rather than minting a mail credential
|
|
239
|
+
throw oauthFailure('invalid_scope', 'No MCP scope was approved');
|
|
240
|
+
}
|
|
241
|
+
|
|
212
242
|
const code = crypto.randomBytes(32).toString('base64url');
|
|
213
243
|
|
|
214
244
|
const record = {
|
|
@@ -217,8 +247,9 @@ async function createAuthorizationCode(opts) {
|
|
|
217
247
|
codeChallenge: opts.codeChallenge,
|
|
218
248
|
resource: opts.resource || null,
|
|
219
249
|
account: opts.account || null,
|
|
250
|
+
scopes,
|
|
220
251
|
// The narrowing the operator approved, applied to the token this code mints. Absent
|
|
221
|
-
// means unnarrowed within the
|
|
252
|
+
// means unnarrowed within the scopes, the same shape the admin generator posts.
|
|
222
253
|
permissions: opts.permissions || null,
|
|
223
254
|
description: opts.description,
|
|
224
255
|
created: Date.now()
|
|
@@ -293,10 +324,14 @@ async function redeemAuthorizationCode({ code, clientId, redirectUri, codeVerifi
|
|
|
293
324
|
throw oauthFailure('invalid_target', 'The resource parameter does not match the authorization request');
|
|
294
325
|
}
|
|
295
326
|
|
|
327
|
+
// A code minted before the scopes were recorded on it carries none; it was issued for the
|
|
328
|
+
// one scope the flow had then
|
|
329
|
+
const scopes = Array.isArray(record.scopes) && record.scopes.length ? record.scopes : ['mcp'];
|
|
330
|
+
|
|
296
331
|
const token = await tokens.provision({
|
|
297
332
|
account: record.account || undefined,
|
|
298
333
|
description: record.description,
|
|
299
|
-
scopes
|
|
334
|
+
scopes,
|
|
300
335
|
permissions: record.permissions || undefined,
|
|
301
336
|
ip,
|
|
302
337
|
metadata: JSON.stringify({ issuer: 'mcp-oauth', client: record.clientId })
|
|
@@ -305,13 +340,16 @@ async function redeemAuthorizationCode({ code, clientId, redirectUri, codeVerifi
|
|
|
305
340
|
return {
|
|
306
341
|
access_token: token,
|
|
307
342
|
token_type: 'Bearer',
|
|
308
|
-
|
|
343
|
+
// RFC 6749 3.3: space separated, and what was actually granted
|
|
344
|
+
scope: scopes.join(' ')
|
|
309
345
|
};
|
|
310
346
|
}
|
|
311
347
|
|
|
312
348
|
module.exports = {
|
|
313
349
|
oauthOrigin,
|
|
314
350
|
mcpResource,
|
|
351
|
+
MCP_OAUTH_SCOPES,
|
|
352
|
+
normalizeScopes,
|
|
315
353
|
registerClient,
|
|
316
354
|
getClient,
|
|
317
355
|
touchClient,
|
package/lib/mcp/protocol.js
CHANGED
|
@@ -24,6 +24,7 @@
|
|
|
24
24
|
|
|
25
25
|
const packageData = require('../../package.json');
|
|
26
26
|
const { COLLAPSE_CLASS } = require('../consts');
|
|
27
|
+
const { MCP_SCOPES } = require('../api-routes/permission-map');
|
|
27
28
|
|
|
28
29
|
const MODERN_PROTOCOL_VERSION = '2026-07-28';
|
|
29
30
|
const LEGACY_PROTOCOL_VERSIONS = ['2025-11-25', '2025-06-18'];
|
|
@@ -46,47 +47,90 @@ const ERROR_CODES = {
|
|
|
46
47
|
|
|
47
48
|
const SERVER_INFO = { name: 'EmailEngine', version: packageData.version };
|
|
48
49
|
|
|
49
|
-
//
|
|
50
|
-
//
|
|
51
|
-
// knows the class name can read the new part of a thread without the quoted copies of
|
|
52
|
-
// before it
|
|
53
|
-
//
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
50
|
+
// What the instructions say about each tool set, keyed by the scope that carries it. The mail
|
|
51
|
+
// lines earn their place: the collapse marker is a machine-readable "show more" boundary, and an
|
|
52
|
+
// agent that knows the class name can read the new part of a thread without the quoted copies of
|
|
53
|
+
// everything before it, and the send warning is the other one that matters. The management lines
|
|
54
|
+
// name what to confirm, because settings apply at once and several of the tools are one-way, and
|
|
55
|
+
// a client may or may not surface the tool descriptions. One place per set, so a line cannot be
|
|
56
|
+
// edited for one credential shape and forgotten for another.
|
|
57
|
+
const SURFACE_INSTRUCTIONS = {
|
|
58
|
+
[MCP_SCOPES.manage]: [
|
|
59
|
+
'Settings and configuration changes take effect immediately.',
|
|
60
|
+
'Confirm with the user before changing where webhooks or notifications are delivered, before changing where an account or gateway connects, and before anything destructive: deleting, revoking, flushing.',
|
|
61
|
+
'To add a mailbox, prefer create_account_setup_link so the user signs in themselves and no password passes through this conversation.'
|
|
62
|
+
],
|
|
63
|
+
[MCP_SCOPES.mail]: [
|
|
64
|
+
'Message ids come from list_messages or search_messages.',
|
|
65
|
+
`Message bodies are returned as sanitized HTML; quoted reply and forward history is wrapped in a <details class="${COLLAPSE_CLASS}"> element, ` +
|
|
66
|
+
'so what the sender actually wrote is everything outside it.',
|
|
67
|
+
'send_message delivers real email to real recipients - confirm with the user before calling it.'
|
|
68
|
+
]
|
|
69
|
+
};
|
|
60
70
|
|
|
61
71
|
/**
|
|
62
72
|
* The instructions shown to the calling model by clients that surface them.
|
|
63
73
|
*
|
|
64
|
-
*
|
|
65
|
-
*
|
|
66
|
-
*
|
|
67
|
-
*
|
|
68
|
-
*
|
|
74
|
+
* Written for the credential that is asking, on the two things that change what the agent can do.
|
|
75
|
+
* Which tool sets it holds, as the scopes its advertised catalog exercises: a management
|
|
76
|
+
* credential is told to start from the instance and what to confirm, a mail credential is told
|
|
77
|
+
* how messages are shaped, and one holding both hears both. And whether it is bound to one
|
|
78
|
+
* account: the generic opening tells the agent to list the accounts and pass an id, which a bound
|
|
79
|
+
* credential can do neither of - the listing tools are not advertised to it, and its tools carry
|
|
80
|
+
* no `account` argument because the endpoint already knows which account they act on. Saying so
|
|
81
|
+
* up front is what stops the agent looking for a way to supply one.
|
|
69
82
|
*
|
|
70
83
|
* Kept short either way: this rides along on every discover/initialize response.
|
|
71
84
|
*
|
|
72
|
-
* @param {
|
|
85
|
+
* @param {Object} [profile]
|
|
86
|
+
* @param {String} [profile.account] - the bound account id, for an account-bound credential
|
|
87
|
+
* @param {Array<String>} [profile.surfaces] - the per-request scopes the credential's catalog exercises
|
|
88
|
+
* @param {Boolean} [profile.hasTools] - whether the advertised catalog has anything in it, for a
|
|
89
|
+
* credential that exercises no scope on its own: the tools both sets share say nothing
|
|
90
|
+
* about either, and a credential narrowed to only those still has something to call
|
|
73
91
|
* @returns {String} instructions
|
|
74
92
|
*/
|
|
75
|
-
function serverInstructions(
|
|
76
|
-
const
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
93
|
+
function serverInstructions(profile) {
|
|
94
|
+
const { account = null, surfaces = [], hasTools = false } = profile || {};
|
|
95
|
+
const manage = surfaces.includes(MCP_SCOPES.manage);
|
|
96
|
+
const mail = surfaces.includes(MCP_SCOPES.mail);
|
|
97
|
+
|
|
98
|
+
const opening = ['EmailEngine is a self-hosted email sync service.'];
|
|
99
|
+
|
|
100
|
+
if (account) {
|
|
101
|
+
opening.push(
|
|
102
|
+
`This credential is bound to the email account '${account}' on this instance and reaches no other, so the tools take no account argument - it is applied for you.`
|
|
103
|
+
);
|
|
104
|
+
if (manage) {
|
|
105
|
+
opening.push('It can operate that account: inspect its state and logs, reconnect or sync it, change its configuration, or remove it.');
|
|
106
|
+
}
|
|
107
|
+
} else {
|
|
108
|
+
if (manage) {
|
|
109
|
+
opening.push(
|
|
110
|
+
'This credential manages this instance: accounts, settings, OAuth2 applications, SMTP gateways, access tokens and the license. Start with get_instance_stats and list_accounts.'
|
|
111
|
+
);
|
|
112
|
+
}
|
|
113
|
+
if (mail) {
|
|
114
|
+
opening.push(
|
|
115
|
+
(manage ? 'It also reaches mailbox contents.' : 'This credential gives access to the email accounts registered on this instance.') +
|
|
116
|
+
' Call list_accounts first and use the returned account id as the `account` argument of the mail tools.'
|
|
117
|
+
);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
if (!manage && !mail) {
|
|
122
|
+
// Told so rather than handed a workflow it cannot perform
|
|
123
|
+
opening.push(
|
|
124
|
+
hasTools
|
|
125
|
+
? 'This credential is offered only the tools both tool sets share; ask the operator to widen it for anything else.'
|
|
126
|
+
: 'This credential is offered no tools; ask the operator to widen it.'
|
|
127
|
+
);
|
|
128
|
+
}
|
|
88
129
|
|
|
89
|
-
|
|
130
|
+
// Management lines before mail lines, whatever order the surfaces arrived in
|
|
131
|
+
const held = Object.values(MCP_SCOPES).filter(scope => surfaces.includes(scope));
|
|
132
|
+
return opening.concat(...held.map(scope => SURFACE_INSTRUCTIONS[scope])).join(' ');
|
|
133
|
+
}
|
|
90
134
|
|
|
91
135
|
// URL hostnames that mean "this machine" for the transport policies below: the Origin check
|
|
92
136
|
// here and the loopback redirect-URI rule in lib/mcp/oauth.js read the same list, so the two
|
|
@@ -253,7 +297,7 @@ function capabilities(era) {
|
|
|
253
297
|
* listTools() => [tool definitions],
|
|
254
298
|
* callTool(name, args) => tool result (throws {rpcCode, message} for protocol errors),
|
|
255
299
|
* listResources() => [resources], readResource(uri) => contents,
|
|
256
|
-
* instructions -
|
|
300
|
+
* instructions - the per-credential instructions, from serverInstructions(),
|
|
257
301
|
* acceptsEventStream - whether the request's Accept header admits text/event-stream
|
|
258
302
|
* @returns {Promise<Object>} { httpStatus, body } for a JSON response (body undefined for 202),
|
|
259
303
|
* or { listen: { id, filter } } when a subscriptions/listen request was accepted and
|
|
@@ -341,7 +385,7 @@ async function processModern({ body, id, isNotification, params, metaVersion, he
|
|
|
341
385
|
const result = completeResult(body.method, {
|
|
342
386
|
supportedVersions: SUPPORTED_PROTOCOL_VERSIONS,
|
|
343
387
|
capabilities: capabilities('modern'),
|
|
344
|
-
instructions: ctx.instructions
|
|
388
|
+
instructions: ctx.instructions,
|
|
345
389
|
_meta: { [META_SERVER_INFO]: SERVER_INFO }
|
|
346
390
|
});
|
|
347
391
|
return { httpStatus: 200, body: rpcResult(id, result) };
|
|
@@ -403,7 +447,7 @@ async function processLegacy({ body, id, isNotification, params, headers, ctx })
|
|
|
403
447
|
protocolVersion: negotiated,
|
|
404
448
|
capabilities: capabilities('legacy'),
|
|
405
449
|
serverInfo: SERVER_INFO,
|
|
406
|
-
instructions: ctx.instructions
|
|
450
|
+
instructions: ctx.instructions
|
|
407
451
|
};
|
|
408
452
|
return { httpStatus: 200, body: rpcResult(id, result) };
|
|
409
453
|
}
|
|
@@ -484,6 +528,5 @@ module.exports = {
|
|
|
484
528
|
SUPPORTED_PROTOCOL_VERSIONS,
|
|
485
529
|
META_PROTOCOL_VERSION,
|
|
486
530
|
SERVER_INFO,
|
|
487
|
-
SERVER_INSTRUCTIONS,
|
|
488
531
|
serverInstructions
|
|
489
532
|
};
|