emailengine-app 2.80.0 → 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.
Files changed (101) hide show
  1. package/.release-please-manifest.json +1 -1
  2. package/CHANGELOG.md +24 -0
  3. package/README.md +6 -0
  4. package/data/google-crawlers.json +1 -1
  5. package/lib/api-routes/account-routes.js +81 -1
  6. package/lib/api-routes/blocklist-routes.js +24 -0
  7. package/lib/api-routes/delivery-test-routes.js +6 -0
  8. package/lib/api-routes/gateway-routes.js +30 -0
  9. package/lib/api-routes/license-routes.js +10 -0
  10. package/lib/api-routes/mcp-oauth-routes.js +3 -3
  11. package/lib/api-routes/mcp-routes.js +39 -21
  12. package/lib/api-routes/oauth2-app-routes.js +38 -1
  13. package/lib/api-routes/outbox-routes.js +6 -0
  14. package/lib/api-routes/permission-map.js +208 -43
  15. package/lib/api-routes/pubsub-routes.js +8 -0
  16. package/lib/api-routes/route-helpers.js +58 -11
  17. package/lib/api-routes/settings-routes.js +50 -4
  18. package/lib/api-routes/stats-routes.js +6 -0
  19. package/lib/api-routes/template-routes.js +21 -0
  20. package/lib/api-routes/token-routes.js +34 -2
  21. package/lib/api-routes/webhook-route-routes.js +13 -0
  22. package/lib/email-client/base-client.js +6 -3
  23. package/lib/email-client/credential-errors.js +4 -0
  24. package/lib/email-client/imap/login-failure.js +52 -0
  25. package/lib/email-client/imap/subconnection.js +2 -1
  26. package/lib/email-client/imap-client.js +3 -6
  27. package/lib/enum-descriptions.js +12 -2
  28. package/lib/imapproxy/imap-server.js +1 -1
  29. package/lib/mcp/oauth.js +46 -8
  30. package/lib/mcp/protocol.js +78 -35
  31. package/lib/mcp/tools.js +53 -17
  32. package/lib/privileged-settings.js +147 -0
  33. package/lib/schemas.js +60 -16
  34. package/lib/settings.js +13 -0
  35. package/lib/tls/catalog.js +428 -0
  36. package/lib/tls/context.js +87 -161
  37. package/lib/tls/listeners.js +62 -0
  38. package/lib/tls/status.js +128 -79
  39. package/lib/tls/store.js +3 -2
  40. package/lib/token-permission-view.js +252 -102
  41. package/lib/token-permissions.js +176 -26
  42. package/lib/tokens.js +7 -6
  43. package/lib/tools.js +4 -3
  44. package/lib/ui-routes/admin-config-routes.js +41 -21
  45. package/lib/ui-routes/admin-entities-routes.js +23 -13
  46. package/lib/ui-routes/mcp-consent-routes.js +72 -31
  47. package/lib/ui-routes/tls-config-routes.js +121 -74
  48. package/package.json +12 -12
  49. package/sbom.json +1 -1
  50. package/server.js +7 -1
  51. package/static/css/flyonui.css +1 -1
  52. package/static/js/ui.js +89 -36
  53. package/static/licenses.html +46 -28
  54. package/translations/messages.pot +74 -68
  55. package/views/account/login-redirect.hbs +1 -1
  56. package/views/account/passkeys.hbs +2 -2
  57. package/views/accounts/account.hbs +2 -2
  58. package/views/accounts/browse.hbs +1 -1
  59. package/views/accounts/edit.hbs +1 -1
  60. package/views/accounts/register/imap-server.hbs +1 -1
  61. package/views/config/ai.hbs +1 -1
  62. package/views/config/branding.hbs +2 -2
  63. package/views/config/document-store/chat.hbs +1 -1
  64. package/views/config/document-store/index.hbs +1 -1
  65. package/views/config/imap-proxy.hbs +1 -1
  66. package/views/config/license.hbs +1 -1
  67. package/views/config/mcp.hbs +88 -52
  68. package/views/config/network.hbs +1 -1
  69. package/views/config/oauth/app.hbs +2 -2
  70. package/views/config/service.hbs +1 -1
  71. package/views/config/smtp.hbs +1 -1
  72. package/views/config/tls.hbs +266 -165
  73. package/views/config/webhooks.hbs +2 -2
  74. package/views/internals/index.hbs +1 -1
  75. package/views/layout/app.hbs +6 -6
  76. package/views/layout/login.hbs +5 -5
  77. package/views/layout/main.hbs +2 -2
  78. package/views/layout/prompt.hbs +3 -3
  79. package/views/layout/public.hbs +1 -1
  80. package/views/mcp/authorize.hbs +47 -45
  81. package/views/partials/ace_assets.hbs +1 -1
  82. package/views/partials/add_account_modal.hbs +1 -1
  83. package/views/partials/filter_editor_js.hbs +2 -2
  84. package/views/partials/gateway_js.hbs +1 -1
  85. package/views/partials/mcp_access_levels.hbs +16 -9
  86. package/views/partials/mcp_tool_count.hbs +15 -14
  87. package/views/partials/oauth_form.hbs +1 -1
  88. package/views/partials/public_theme_init.hbs +1 -1
  89. package/views/partials/template_form.hbs +1 -1
  90. package/views/partials/theme_init.hbs +1 -1
  91. package/views/partials/webhooks_editor_functions.hbs +1 -1
  92. package/views/reference/index.hbs +1 -1
  93. package/views/reference/redirect.hbs +1 -1
  94. package/views/reference/tag.hbs +1 -1
  95. package/views/reference/token.hbs +1 -1
  96. package/views/templates/template.hbs +1 -1
  97. package/views/tokens/new.hbs +175 -74
  98. package/views/unsubscribe.hbs +1 -1
  99. package/views/webhooks/webhook.hbs +1 -1
  100. package/workers/api.js +9 -8
  101. package/workers/smtp.js +1 -1
@@ -58,6 +58,12 @@ async function init(args) {
58
58
  tags: ['api', 'Templates'],
59
59
 
60
60
  plugins: {
61
+ mcp: {
62
+ name: 'create_template',
63
+ title: 'Create template',
64
+ description:
65
+ 'Create a stored email template: a subject and body (html, text, previewText) that send_message can reference by id. account names the account the template belongs to.'
66
+ },
61
67
  openapi: {
62
68
  responses: apiResponses('Returns the created template.', 400, 401, 403, 404, 429, 500)
63
69
  }
@@ -146,6 +152,11 @@ async function init(args) {
146
152
  tags: ['api', 'Templates'],
147
153
 
148
154
  plugins: {
155
+ mcp: {
156
+ name: 'update_template',
157
+ title: 'Update template',
158
+ description: "Update a stored template's name, description, format or content. Send only the fields to change."
159
+ },
149
160
  openapi: {
150
161
  responses: apiResponses('Returns the updated template.', 400, 401, 403, 404, 429, 500)
151
162
  }
@@ -394,6 +405,11 @@ async function init(args) {
394
405
  tags: ['api', 'Templates'],
395
406
 
396
407
  plugins: {
408
+ mcp: {
409
+ name: 'delete_template',
410
+ title: 'Delete template',
411
+ description: 'Remove a stored template.'
412
+ },
397
413
  openapi: {
398
414
  'x-ee-impact': IMPACT.DESTRUCTIVE,
399
415
  responses: apiResponses('Returns a deletion marker.', 400, 401, 403, 429, 500)
@@ -459,6 +475,11 @@ async function init(args) {
459
475
  tags: ['api', 'Templates'],
460
476
 
461
477
  plugins: {
478
+ mcp: {
479
+ name: 'delete_account_templates',
480
+ title: 'Delete all templates of an account',
481
+ description: 'Remove every stored template of one account. Requires force to be true. Confirm with the user before calling this.'
482
+ },
462
483
  openapi: {
463
484
  'x-ee-impact': IMPACT.DESTRUCTIVE,
464
485
  responses: apiResponses('Returns the number of templates removed.', 400, 401, 403, 404, 429, 500)
@@ -11,6 +11,7 @@ const { failAction } = require('../tools');
11
11
  const { handleError, throwNotFound } = require('./route-helpers');
12
12
  const { accountIdSchema, tokenRestrictionsSchema, tokenPermissionsSchema, ipSchema, tokenIdSchema, apiResponses, ENUM_DESCRIPTIONS } = require('../schemas');
13
13
  const { IMPACT } = require('./operation-impact');
14
+ const { MCP_MAX_PAGE_SIZE } = require('../consts');
14
15
 
15
16
  const tokenAccessSchema = Joi.object({
16
17
  time: Joi.date().iso().allow(null).example('2021-02-17T13:43:18.860Z').description('Last time this token was used. Null if the token has never been used'),
@@ -123,12 +124,17 @@ async function init(args) {
123
124
  description: Joi.string().empty('').trim().max(1024).required().example('Token description').description('Token description'),
124
125
 
125
126
  scopes: Joi.array()
126
- .items(Joi.string().valid('api', 'smtp', 'imap-proxy', 'mcp').meta({ enumDescriptions: ENUM_DESCRIPTIONS.tokenScope }).label('TokenScope'))
127
+ .items(
128
+ Joi.string()
129
+ .valid('api', 'smtp', 'imap-proxy', 'mcp', 'mcp-manage')
130
+ .meta({ enumDescriptions: ENUM_DESCRIPTIONS.tokenScope })
131
+ .label('TokenScope')
132
+ )
127
133
  .single()
128
134
  .default(['api'])
129
135
  .required()
130
136
  .description(
131
- 'Token permission scopes: "api" for REST API access, "smtp" for SMTP submission, "imap-proxy" for IMAP proxy authentication, "mcp" for the MCP endpoint only'
137
+ 'Token permission scopes: "api" for REST API access, "smtp" for SMTP submission, "imap-proxy" for IMAP proxy authentication, "mcp-manage" for the instance management tools of the MCP endpoint, "mcp" for its mail tools'
132
138
  )
133
139
  .label('Scopes'),
134
140
 
@@ -296,6 +302,12 @@ async function init(args) {
296
302
  tags: ['api', 'Access Tokens'],
297
303
 
298
304
  plugins: {
305
+ mcp: {
306
+ name: 'revoke_token',
307
+ title: 'Revoke access token',
308
+ description:
309
+ 'Revoke an access token by its id. Every client using it is cut off immediately and there is no undo. Confirm with the user before calling this.'
310
+ },
299
311
  openapi: {
300
312
  'x-ee-impact': IMPACT.DESTRUCTIVE,
301
313
  responses: apiResponses('Returns a deletion marker. The token stops working immediately.', 400, 401, 403, 429, 500)
@@ -354,6 +366,13 @@ async function init(args) {
354
366
  tags: ['api', 'Access Tokens'],
355
367
 
356
368
  plugins: {
369
+ mcp: {
370
+ name: 'list_tokens',
371
+ title: 'List access tokens',
372
+ description:
373
+ 'List the access tokens on this instance, paged: description, scopes, restrictions, the account each is bound to and when it was last used. Token values are never shown. Filter with query, or with account for the tokens bound to one account.',
374
+ bounds: { pageSize: MCP_MAX_PAGE_SIZE }
375
+ },
357
376
  openapi: {
358
377
  responses: apiResponses('Returns the matching access tokens. Token values are never returned after creation.', 400, 401, 403, 429, 500)
359
378
  }
@@ -462,6 +481,12 @@ async function init(args) {
462
481
  tags: ['api', 'Access Tokens'],
463
482
 
464
483
  plugins: {
484
+ mcp: {
485
+ name: 'get_token',
486
+ title: 'Get access token',
487
+ description:
488
+ 'Get one access token by its id (from list_tokens): scopes, permissions, restrictions and last use. Never the token value itself.'
489
+ },
465
490
  openapi: {
466
491
  responses: apiResponses('Returns the stored token record. The token value is not included.', 400, 401, 403, 404, 429, 500)
467
492
  }
@@ -519,6 +544,13 @@ async function init(args) {
519
544
  tags: ['api', 'Access Tokens'],
520
545
 
521
546
  plugins: {
547
+ mcp: {
548
+ name: 'get_token_log',
549
+ title: 'Get access token audit log',
550
+ description:
551
+ 'Read the audit log of one access token, paged: which requests it made, against which account, from which address, and which were refused and why. Only kept while the tokenAuditLog setting is on.',
552
+ bounds: { pageSize: MCP_MAX_PAGE_SIZE }
553
+ },
522
554
  openapi: {
523
555
  'x-ee-impact': IMPACT.READONLY,
524
556
  responses: apiResponses('Returns the recorded requests for this token, newest first.', 400, 401, 403, 404, 429, 500)
@@ -5,6 +5,7 @@ const { webhooks: Webhooks } = require('../webhooks');
5
5
  const { failAction } = require('../tools');
6
6
  const { handleError, throwNotFound, maskSecrets, MASK_NOTE } = require('./route-helpers');
7
7
  const { settingsSchema, apiResponses } = require('../schemas');
8
+ const { MCP_MAX_PAGE_SIZE } = require('../consts');
8
9
 
9
10
  const webhookErrorFlagSchema = Joi.object({
10
11
  message: Joi.string().example('Request failed with status 500').description('Error message from the last failed delivery')
@@ -48,6 +49,13 @@ async function init(args) {
48
49
  tags: ['api', 'Webhooks'],
49
50
 
50
51
  plugins: {
52
+ mcp: {
53
+ name: 'list_webhook_routes',
54
+ title: 'List webhook routes',
55
+ description:
56
+ 'List the custom webhook routes, paged: per-route targets with their own event filters, beside the global webhook target in the settings. Credentials in target URLs are masked.',
57
+ bounds: { pageSize: MCP_MAX_PAGE_SIZE }
58
+ },
51
59
  openapi: {
52
60
  responses: apiResponses('Returns a page of custom webhook routes.', 400, 401, 403, 429, 500)
53
61
  }
@@ -136,6 +144,11 @@ async function init(args) {
136
144
  tags: ['api', 'Webhooks'],
137
145
 
138
146
  plugins: {
147
+ mcp: {
148
+ name: 'get_webhook_route',
149
+ title: 'Get webhook route',
150
+ description: 'Get one webhook route: its target URL, the events it forwards, whether it is enabled, and its filter and mapping functions.'
151
+ },
139
152
  openapi: {
140
153
  responses: apiResponses('Returns the webhook route, including its filter and transform functions.', 400, 401, 403, 404, 429, 500)
141
154
  }
@@ -912,9 +912,12 @@ class BaseClient {
912
912
  // Store current error state. The event is recorded beside it rather than inside it: `data`
913
913
  // is the webhook payload and a published response shape, and notifyAuthenticationSuccess()
914
914
  // needs to know whether the run that is ending was an authentication failure or a
915
- // connection one
915
+ // connection one.
916
+ // The repeat check below compares stored forms: JSON drops a key whose value is undefined
917
+ // (serverResponseCode, for a response with no bracketed code) and deepEqual() counts it
918
+ const storedState = JSON.stringify(data);
916
919
  const stateTxn = createTransaction(this.redis, { logger: this.logger });
917
- stateTxn.add('hSetExists', this.getAccountKey(), 'lastErrorState', JSON.stringify(data));
920
+ stateTxn.add('hSetExists', this.getAccountKey(), 'lastErrorState', storedState);
918
921
  stateTxn.add('hSetExists', this.getAccountKey(), LAST_ERROR_EVENT_FIELD, event);
919
922
  // Throws rather than reporting the failure in a return value nobody reads: an error that
920
923
  // was not stored is one the next login announces a recovery from, one the repeat check
@@ -932,7 +935,7 @@ class BaseClient {
932
935
  shouldNotify = false;
933
936
  } else {
934
937
  try {
935
- deepEqual(data, prevLastErrorState);
938
+ deepEqual(JSON.parse(storedState), prevLastErrorState);
936
939
  // nothing changed
937
940
  shouldNotify = false;
938
941
  } catch (err) {
@@ -12,6 +12,10 @@
12
12
  // base-client owns the IMAP and API credential paths, message-builder owns the SMTP one, and
13
13
  // base-client already imports message-builder - so there is no direction in which one could
14
14
  // require the other.
15
+ //
16
+ // The IMAP server's own verdict on a login (a NO to AUTHENTICATE that is the server's problem
17
+ // rather than the credential's) is decided in ./imap/login-failure.js, kept dependency-free so the
18
+ // pure subconnection tests do not inherit the Redis connections this module's imports open.
15
19
 
16
20
  const { resolveCredentials } = require('../tools');
17
21
  const { AUTH_ERROR_NOTIFY, TRANSIENT_NETWORK_CODES } = require('../consts');
@@ -0,0 +1,52 @@
1
+ 'use strict';
2
+
3
+ // What an IMAP server's answer to a login means. ImapFlow flags every failed AUTHENTICATE or LOGIN
4
+ // as `authenticationFailed`, which is the fact of what happened; whether the credential was refused
5
+ // or the server could not serve the login right now is decided here, the way
6
+ // lib/email-client/credential-errors.js decides it for a token endpoint. Reporting a backend outage
7
+ // as `authenticationError` puts the account in an error state that re-authorizing cannot clear, and
8
+ // the login that follows the outage then contradicts it with `authenticationSuccess`.
9
+ //
10
+ // Dependency-free on purpose: subconnection.js consults it, and the pure subconnection tests would
11
+ // otherwise inherit the Redis connections lib/tools.js opens at load and never exit.
12
+
13
+ // The RFC 5530 codes a server puts on a NO when the failure is its own and temporary: a subsystem
14
+ // the login depends on is down, the server tripped over itself, or a limit was hit.
15
+ // AUTHENTICATIONFAILED, AUTHORIZATIONFAILED, EXPIRED and PRIVACYREQUIRED are the verdicts on the
16
+ // credential
17
+ const TRANSIENT_RESPONSE_CODES = new Set(['UNAVAILABLE', 'SERVERBUG', 'INUSE', 'LIMIT']);
18
+
19
+ // The same meaning carried by text alone. Exchange Online sends no response code, and "User is
20
+ // authenticated but not connected." is its front end saying the token was accepted but the
21
+ // mailbox's backend could not be reached - a failover, a mailbox move, a throttled backend. It says
22
+ // the same thing permanently when IMAP is disabled for the mailbox, which is why a match is
23
+ // reported as a connection failure carrying the text rather than dropped
24
+ const TRANSIENT_RESPONSE_TEXT = /user is authenticated but not connected/i;
25
+
26
+ /**
27
+ * The readable text of a failed IMAP command. ImapFlow rewrites err.response into the response line
28
+ * for a login failure and leaves the parsed response object there for any other command, so the
29
+ * text field is the fallback - a stored error state or webhook payload built off the object would
30
+ * render as "[object Object]"
31
+ * @param {Error} err - The error ImapFlow threw
32
+ * @returns {string|undefined} The response line or its text, when there is one
33
+ */
34
+ function imapResponseText(err) {
35
+ return (typeof err?.response === 'string' && err.response) || err?.responseText;
36
+ }
37
+
38
+ /**
39
+ * Whether a failed IMAP login is the server refusing the credential, as opposed to being unable to
40
+ * serve the login right now
41
+ * @param {Error} err - The error a login attempt threw
42
+ * @returns {boolean} True when the server rejected the credential
43
+ */
44
+ function isRefusedImapLogin(err) {
45
+ if (!err || !err.authenticationFailed || TRANSIENT_RESPONSE_CODES.has(err.serverResponseCode)) {
46
+ return false;
47
+ }
48
+
49
+ return !TRANSIENT_RESPONSE_TEXT.test(imapResponseText(err) || '');
50
+ }
51
+
52
+ module.exports = { imapResponseText, isRefusedImapLogin };
@@ -5,6 +5,7 @@ const { backOff } = require('exponential-backoff');
5
5
  const { ReconnectBackoff } = require('../reconnect-backoff');
6
6
  const { detachImapClient } = require('./detach-client');
7
7
  const { connectionUnavailableError } = require('./connection-errors');
8
+ const { isRefusedImapLogin } = require('./login-failure');
8
9
  const { samePath } = require('../../utils/mailbox-path');
9
10
  const EventEmitter = require('events').EventEmitter;
10
11
 
@@ -256,7 +257,7 @@ class Subconnection extends EventEmitter {
256
257
  await this.parent.untrackConnection(imapClient);
257
258
  }
258
259
  } catch (err) {
259
- if (err.authenticationFailed) {
260
+ if (isRefusedImapLogin(err)) {
260
261
  this.logger.warn({ msg: 'Failed to authenticate subconnection', account: this.account, err });
261
262
  this.state = 'authenticationError';
262
263
  this.disabledReason = 'Authentication failed';
@@ -18,6 +18,7 @@ const { samePath } = require('../utils/mailbox-path');
18
18
  const { detachImapClient } = require('./imap/detach-client');
19
19
  const { connectionNotAvailableError, connectionUnavailableError } = require('./imap/connection-errors');
20
20
  const { ReconnectBackoff } = require('./reconnect-backoff');
21
+ const { isRefusedImapLogin, imapResponseText } = require('./imap/login-failure');
21
22
 
22
23
  const {
23
24
  normalizePath,
@@ -1885,12 +1886,8 @@ class IMAPClient extends BaseClient {
1885
1886
  }
1886
1887
  }
1887
1888
 
1888
- // ImapFlow rewrites err.response into a string for authentication
1889
- // failures, but for other command failures it is the parsed response
1890
- // object - prefer the response text so the stored error state and
1891
- // webhook payloads never render as "[object Object]"
1892
- let errorResponse = (typeof err.response === 'string' && err.response) || err.responseText;
1893
- if (err.authenticationFailed) {
1889
+ let errorResponse = imapResponseText(err);
1890
+ if (isRefusedImapLogin(err)) {
1894
1891
  this.logger.warn({ msg: 'Failed to authenticate', account: this.account, err });
1895
1892
  await this.notify(false, AUTH_ERROR_NOTIFY, {
1896
1893
  response: errorResponse,
@@ -1,6 +1,7 @@
1
1
  'use strict';
2
2
 
3
3
  const { ADDRESS_STRATEGIES } = require('./address-strategies');
4
+ const { PRIVILEGED_SETTINGS_SUMMARY } = require('./privileged-settings');
4
5
 
5
6
  // Per-value documentation for the enums whose values are not self-explanatory. Attached to
6
7
  // the joi schemas below with `.meta({ enumDescriptions })`, which the OpenAPI generator emits
@@ -93,7 +94,9 @@ const ENUM_DESCRIPTIONS = {
93
94
  api: 'Call the REST API',
94
95
  smtp: 'Authenticate against the built-in SMTP submission server',
95
96
  'imap-proxy': 'Authenticate against the built-in IMAP proxy',
96
- mcp: 'Connect AI agents through the MCP endpoint. Admits only the operations the MCP tool set wraps, and is not valid for plain REST calls'
97
+ 'mcp-manage':
98
+ 'Let an AI agent manage this instance through the MCP endpoint: accounts, settings, OAuth2 applications, gateways, tokens, the license. Admits only the operations the management tools wrap, and is not valid for plain REST calls',
99
+ mcp: 'Let an AI agent work with mailbox contents through the MCP endpoint. Admits only the operations the mail tools wrap, and is not valid for plain REST calls'
97
100
  },
98
101
 
99
102
  // The verb axis of a narrowed token. Each operation requires exactly one of these, published
@@ -122,7 +125,14 @@ const ENUM_DESCRIPTIONS = {
122
125
  gateway: 'Manage SMTP gateways, which hold outbound SMTP credentials',
123
126
  events: 'Subscribe to the instance-wide change stream, which covers every account',
124
127
  diagnostics: 'Read statistics and service status',
125
- logs: 'Read the per-account connection log. Entries include the protocol or API trace, so they include folder names and message subjects'
128
+ logs: 'Read the per-account connection log. Entries include the protocol or API trace, so they include folder names and message subjects',
129
+ // The parenthetical is rendered from the list the rule reads, so it cannot fall behind it
130
+ settings: `Read and change instance settings and pause or resume the queues. A write reaches the global webhook target. The keys that would widen a token beyond settings (${PRIVILEGED_SETTINGS_SUMMARY}) are refused to a restricted token, on reads and writes alike`,
131
+ oauth2: 'Manage OAuth2 applications. Client secrets are write-only, and a change can move where the provider sends authorization codes',
132
+ license: 'Read, apply and remove the license key',
133
+ token: 'List, inspect and revoke access tokens and read their audit logs, which record who read which account. Cannot create tokens',
134
+ provisioning:
135
+ 'Add and reconfigure email accounts and SMTP gateways, including where they connect. A stored credential is sent to whatever host the record names after the change'
126
136
  },
127
137
 
128
138
  queueId: {
@@ -512,7 +512,7 @@ module.exports.run = async () => {
512
512
  // The material loaded above is snapshotted inside, at entry, so a later refresh does not
513
513
  // read what this resolution wrote back into serverOptions as if the operator had supplied
514
514
  // it.
515
- tlsContext = await createTlsContext({ certs, logger, listenerOptions: serverOptions });
515
+ tlsContext = await createTlsContext({ certs, logger, listener: 'imapProxy', listenerOptions: serverOptions });
516
516
  Object.assign(serverOptions, tlsContext.options);
517
517
 
518
518
  assertTlsCredentials(serverOptions, 'The IMAP proxy');
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 with the
9
- // `mcp` scope. Every credential this issues is an ordinary access token: visible on the admin
10
- // tokens page, revocable there, and bounded by SURFACE_GRANTS.mcp like any other mcp-scoped
11
- // token. There are no refresh tokens and no expiry by default - revocation is the lifecycle.
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), description (for the admin tokens listing)
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 mcp scope, the same shape the admin generator posts.
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: ['mcp'],
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
- scope: 'mcp'
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,
@@ -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
- // Everything the instructions say that does not depend on which credential is asking. The collapse
50
- // marker earns its line here: it is a machine-readable "show more" boundary, and an agent that
51
- // knows the class name can read the new part of a thread without the quoted copies of everything
52
- // before it. The send warning is the other one that matters, and having it in one place is why it
53
- // cannot be edited in the generic set and forgotten in the bound one.
54
- const COMMON_INSTRUCTIONS = [
55
- 'Message ids come from list_messages or search_messages.',
56
- `Message bodies are returned as sanitized HTML; quoted reply and forward history is wrapped in a <details class="${COLLAPSE_CLASS}"> element, ` +
57
- 'so what the sender actually wrote is everything outside it.',
58
- 'send_message delivers real email to real recipients - confirm with the user before calling it.'
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
- * Only the opening differs, and it differs on the one thing that changes what the agent can do:
65
- * the generic set tells it to list the accounts and pass an id, which a bound credential can do
66
- * neither of - the listing tools are not advertised to it, and its tools carry no `account`
67
- * argument because the endpoint already knows which account they act on. Saying so up front is
68
- * what stops the agent looking for a way to supply one.
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 {String} [account] - the bound account id, for an account-bound credential
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(account) {
76
- const opening = account
77
- ? [
78
- `EmailEngine gives access to the email account '${account}' on this instance.`,
79
- 'This credential reaches that one account and no other, so the tools take no account argument - it is applied for you.'
80
- ]
81
- : [
82
- 'EmailEngine gives access to the email accounts registered on this instance.',
83
- 'Call list_accounts first and use the returned account id as the `account` argument of the other tools.'
84
- ];
85
-
86
- return opening.concat(COMMON_INSTRUCTIONS).join(' ');
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
- const SERVER_INSTRUCTIONS = serverInstructions();
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 - optional per-credential replacement for SERVER_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 || SERVER_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 || SERVER_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
  };