emailengine-app 2.80.0 → 2.81.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (178) hide show
  1. package/.dockerignore +44 -0
  2. package/.github/docker-smoke-test.sh +16 -0
  3. package/.github/workflows/deploy.yml +4 -0
  4. package/.github/workflows/release.yaml +4 -0
  5. package/.github/workflows/test.yml +2 -0
  6. package/.release-please-manifest.json +1 -1
  7. package/CHANGELOG.md +56 -0
  8. package/Dockerfile +17 -9
  9. package/README.md +6 -0
  10. package/data/google-crawlers.json +1 -1
  11. package/docker-compose.yml +7 -1
  12. package/lib/api-routes/account-routes.js +239 -73
  13. package/lib/api-routes/blocklist-routes.js +24 -0
  14. package/lib/api-routes/delivery-test-routes.js +6 -0
  15. package/lib/api-routes/gateway-routes.js +30 -0
  16. package/lib/api-routes/license-routes.js +10 -0
  17. package/lib/api-routes/mcp-oauth-routes.js +3 -3
  18. package/lib/api-routes/mcp-routes.js +39 -21
  19. package/lib/api-routes/oauth2-app-routes.js +38 -1
  20. package/lib/api-routes/outbox-routes.js +6 -0
  21. package/lib/api-routes/permission-map.js +212 -42
  22. package/lib/api-routes/pubsub-routes.js +8 -0
  23. package/lib/api-routes/route-helpers.js +58 -11
  24. package/lib/api-routes/settings-routes.js +50 -4
  25. package/lib/api-routes/stats-routes.js +6 -0
  26. package/lib/api-routes/template-routes.js +21 -0
  27. package/lib/api-routes/token-routes.js +34 -2
  28. package/lib/api-routes/webhook-route-routes.js +13 -0
  29. package/lib/autodetect-imap-settings.js +4 -4
  30. package/lib/email-client/base-client.js +6 -3
  31. package/lib/email-client/credential-errors.js +4 -0
  32. package/lib/email-client/imap/login-failure.js +52 -0
  33. package/lib/email-client/imap/subconnection.js +2 -1
  34. package/lib/email-client/imap-client.js +3 -6
  35. package/lib/enum-descriptions.js +12 -2
  36. package/lib/imapproxy/imap-server.js +1 -1
  37. package/lib/mcp/oauth.js +46 -8
  38. package/lib/mcp/protocol.js +78 -35
  39. package/lib/mcp/tools.js +53 -17
  40. package/lib/privileged-settings.js +147 -0
  41. package/lib/schemas.js +60 -16
  42. package/lib/sentry.js +13 -2
  43. package/lib/settings.js +13 -0
  44. package/lib/tls/catalog.js +428 -0
  45. package/lib/tls/context.js +87 -161
  46. package/lib/tls/listeners.js +62 -0
  47. package/lib/tls/provision.js +1 -1
  48. package/lib/tls/status.js +128 -79
  49. package/lib/tls/store.js +3 -2
  50. package/lib/token-permission-view.js +253 -102
  51. package/lib/token-permissions.js +176 -26
  52. package/lib/tokens.js +7 -6
  53. package/lib/tools.js +5 -3
  54. package/lib/ui-routes/account-routes.js +195 -61
  55. package/lib/ui-routes/admin-config-routes.js +41 -21
  56. package/lib/ui-routes/admin-entities-routes.js +32 -22
  57. package/lib/ui-routes/mcp-consent-routes.js +72 -31
  58. package/lib/ui-routes/tls-config-routes.js +121 -74
  59. package/package.json +16 -16
  60. package/sbom.json +1 -1
  61. package/server.js +7 -1
  62. package/static/css/flyonui.css +1 -1
  63. package/static/css/public.css +41 -0
  64. package/static/css/src/app.tailwind.css +135 -4
  65. package/static/js/public.js +218 -0
  66. package/static/js/ui.js +89 -36
  67. package/static/licenses.html +55 -37
  68. package/translations/README.md +4 -3
  69. package/translations/de.mo +0 -0
  70. package/translations/de.po +296 -185
  71. package/translations/en.po +220 -128
  72. package/translations/es.mo +0 -0
  73. package/translations/es.po +558 -0
  74. package/translations/et.mo +0 -0
  75. package/translations/et.po +288 -181
  76. package/translations/fr.mo +0 -0
  77. package/translations/fr.po +295 -183
  78. package/translations/it.mo +0 -0
  79. package/translations/it.po +558 -0
  80. package/translations/ja.mo +0 -0
  81. package/translations/ja.po +268 -192
  82. package/translations/locales.json +24 -0
  83. package/translations/messages.pot +179 -127
  84. package/translations/nl.mo +0 -0
  85. package/translations/nl.po +288 -175
  86. package/translations/pl.mo +0 -0
  87. package/translations/pl.po +294 -181
  88. package/translations/sv.mo +0 -0
  89. package/translations/sv.po +555 -0
  90. package/translations/tr.mo +0 -0
  91. package/translations/tr.po +555 -0
  92. package/update-info.sh +12 -6
  93. package/views/account/login-redirect.hbs +6 -5
  94. package/views/account/passkeys.hbs +8 -8
  95. package/views/account/security.hbs +2 -2
  96. package/views/accounts/account.hbs +19 -21
  97. package/views/accounts/browse.hbs +1 -1
  98. package/views/accounts/edit.hbs +15 -15
  99. package/views/accounts/index.hbs +3 -3
  100. package/views/accounts/register/imap-server.hbs +27 -173
  101. package/views/accounts/register/validating.hbs +139 -0
  102. package/views/config/ai.hbs +15 -17
  103. package/views/config/branding.hbs +7 -7
  104. package/views/config/document-store/chat.hbs +9 -8
  105. package/views/config/document-store/index.hbs +14 -15
  106. package/views/config/document-store/mappings/index.hbs +5 -6
  107. package/views/config/document-store/mappings/new.hbs +1 -2
  108. package/views/config/document-store/pre-processing/index.hbs +4 -4
  109. package/views/config/email-processing.hbs +6 -6
  110. package/views/config/imap-proxy.hbs +7 -8
  111. package/views/config/license.hbs +9 -9
  112. package/views/config/logging.hbs +5 -7
  113. package/views/config/mcp.hbs +90 -58
  114. package/views/config/network.hbs +4 -4
  115. package/views/config/oauth/app.hbs +12 -12
  116. package/views/config/oauth/index.hbs +6 -6
  117. package/views/config/oauth/subscriptions.hbs +9 -9
  118. package/views/config/security.hbs +5 -7
  119. package/views/config/service.hbs +11 -10
  120. package/views/config/smtp.hbs +9 -12
  121. package/views/config/tls-upload.hbs +3 -3
  122. package/views/config/tls.hbs +281 -182
  123. package/views/config/webhooks.hbs +12 -15
  124. package/views/dashboard.hbs +9 -8
  125. package/views/gateways/edit.hbs +3 -3
  126. package/views/gateways/gateway.hbs +3 -3
  127. package/views/gateways/index.hbs +6 -6
  128. package/views/gateways/new.hbs +3 -3
  129. package/views/internals/index.hbs +15 -13
  130. package/views/layout/app.hbs +6 -6
  131. package/views/layout/login.hbs +32 -19
  132. package/views/layout/main.hbs +2 -2
  133. package/views/layout/prompt.hbs +15 -18
  134. package/views/layout/public.hbs +1 -1
  135. package/views/mcp/authorize.hbs +47 -45
  136. package/views/partials/accounts_table.hbs +5 -5
  137. package/views/partials/ace_assets.hbs +1 -1
  138. package/views/partials/add_account_modal.hbs +4 -4
  139. package/views/partials/address_list.hbs +4 -4
  140. package/views/partials/filter_editor_js.hbs +2 -2
  141. package/views/partials/gateway_form.hbs +5 -5
  142. package/views/partials/gateway_js.hbs +1 -1
  143. package/views/partials/mcp_access_levels.hbs +16 -9
  144. package/views/partials/mcp_account_limit.hbs +2 -2
  145. package/views/partials/mcp_tool_count.hbs +15 -14
  146. package/views/partials/oauth_config_header.hbs +2 -2
  147. package/views/partials/oauth_form.hbs +37 -42
  148. package/views/partials/public_alerts.hbs +1 -1
  149. package/views/partials/public_test_labels.hbs +15 -0
  150. package/views/partials/public_theme_init.hbs +1 -1
  151. package/views/partials/security_header.hbs +2 -2
  152. package/views/partials/template_form.hbs +4 -4
  153. package/views/partials/theme_init.hbs +1 -1
  154. package/views/partials/tls_security_card.hbs +4 -1
  155. package/views/partials/ui/form-field.hbs +6 -1
  156. package/views/partials/ui/setting-ref.hbs +12 -7
  157. package/views/partials/ui/stat-card.hbs +4 -1
  158. package/views/partials/ui/tabs.hbs +3 -7
  159. package/views/partials/webhook_form.hbs +9 -12
  160. package/views/partials/webhooks_editor_functions.hbs +1 -1
  161. package/views/reference/index.hbs +3 -3
  162. package/views/reference/redirect.hbs +1 -1
  163. package/views/reference/tag.hbs +1 -1
  164. package/views/reference/token.hbs +4 -4
  165. package/views/suppression-lists/index.hbs +8 -6
  166. package/views/suppression-lists/list.hbs +13 -8
  167. package/views/templates/edit.hbs +1 -1
  168. package/views/templates/index.hbs +10 -11
  169. package/views/templates/template.hbs +5 -5
  170. package/views/tokens/index.hbs +17 -17
  171. package/views/tokens/new.hbs +190 -93
  172. package/views/unsubscribe.hbs +1 -1
  173. package/views/webhooks/edit.hbs +1 -1
  174. package/views/webhooks/index.hbs +10 -11
  175. package/views/webhooks/new.hbs +1 -1
  176. package/views/webhooks/webhook.hbs +5 -6
  177. package/workers/api.js +9 -8
  178. package/workers/smtp.js +1 -1
@@ -3,6 +3,7 @@
3
3
  const Boom = require('@hapi/boom');
4
4
  const { isDeepStrictEqual } = require('node:util');
5
5
  const tokenPermissions = require('../token-permissions');
6
+ const settings = require('../settings');
6
7
 
7
8
  // Shared helpers for the extracted API route modules under lib/api-routes/.
8
9
 
@@ -155,7 +156,7 @@ function maskUrlPassword(url) {
155
156
  }
156
157
 
157
158
  // Stored values that are URLs which may embed a password.
158
- const URL_SECRET_KEYS = ['proxy', 'proxyUrl', 'httpProxyUrl', 'webhooks', 'targetUrl'];
159
+ const URL_SECRET_KEYS = ['proxy', 'proxyUrl', 'httpProxyUrl', 'webhooks', 'targetUrl', 'sentryDsn', 'documentStoreUrl'];
159
160
 
160
161
  // Stored values that are {key, value} header lists whose values are credentials.
161
162
  const HEADER_SECRET_KEYS = ['customHeaders', 'webhooksCustomHeaders'];
@@ -340,26 +341,72 @@ function assertNoNetworkOverride(request) {
340
341
  return;
341
342
  }
342
343
 
343
- // Set by the api-token strategy for a `sess_` credential. Marked on the request rather than
344
- // faked into a permissions record: the session bound is a grant list, which the two axes cannot
345
- // express without widening it, and a record that says more than the rule would be read as
346
- // policy by the next thing that looks at it.
347
- const sessionToken = !!(request.app && request.app.sessionToken);
348
-
349
- // Asked of the module that enforces the narrowing rather than by testing `permissions` for
350
- // truthiness, so `{}` and an unreadable record are read here exactly as they are at the
351
- // strategy. `artifacts` is the token record the api-token strategy resolved.
352
- if (!sessionToken && !tokenPermissions.inspect(request.auth && request.auth.artifacts).narrowed) {
344
+ if (!isRestrictedCredential(request)) {
353
345
  return;
354
346
  }
355
347
 
356
348
  throw Boom.forbidden('A token with restricted permissions can not override the connection route');
357
349
  }
358
350
 
351
+ /**
352
+ * Whether the credential behind a request is bounded below the full API.
353
+ *
354
+ * Two kinds are. A narrowed token, one carrying a `permissions` record. And a browse-page session
355
+ * token, which is bounded by SESSION_TOKEN_GRANTS rather than by a record and so reads as
356
+ * unnarrowed to the permission check - it is marked on the request by the api-token strategy
357
+ * rather than faked into a record, because the session bound is a grant list the two axes cannot
358
+ * express without widening it. The permission verdict is asked of the module that enforces it
359
+ * rather than read off `permissions` for truthiness, so `{}` and an unreadable record count here
360
+ * exactly as they do at the strategy. `artifacts` is the token record the strategy resolved.
361
+ *
362
+ * An unnarrowed API token is not restricted: it already reaches everything, so the payload rules
363
+ * that key on this would cost it a documented capability and buy nothing.
364
+ *
365
+ * @param {Object} request - the Hapi request
366
+ * @returns {Boolean}
367
+ */
368
+ function isRestrictedCredential(request) {
369
+ if (request.app && request.app.sessionToken) {
370
+ return true;
371
+ }
372
+ return tokenPermissions.inspect(request.auth && request.auth.artifacts).narrowed;
373
+ }
374
+
375
+ /**
376
+ * Refuses a settings request that names a privileged key, when the credential making it is
377
+ * narrowed.
378
+ *
379
+ * `read/settings` and `write/settings` are grantable permissions, and the settings blob is the
380
+ * one endpoint whose fields span every trust level: `serviceUrl` beside `openAiPreProcessingFn`,
381
+ * which is operator code run inside the instance, and `scriptEnv`, where the admin UI tells
382
+ * operators to keep the API keys their scripts use. The second payload rule in the model after
383
+ * assertNoNetworkOverride(), and like it a static list rather than an interpretation of a value:
384
+ * PRIVILEGED_SETTINGS_KEYS in lib/privileged-settings.js says which keys, and the MCP settings tools hide the
385
+ * same keys from their schemas, so the grants mean the same thing on both surfaces. Applied to
386
+ * reads as well as writes, because several of the keys are secrets a narrowed credential is
387
+ * promised it cannot read, and the write guard alone left them readable.
388
+ *
389
+ * Refused as a whole rather than applied minus the privileged keys, because a partial answer that
390
+ * silently dropped fields would read to the caller as success.
391
+ *
392
+ * @param {Object} request - the Hapi request
393
+ * @param {Array<String>} keys - the settings the request names (payload keys, or the query flags set)
394
+ * @param {String} [verb] - 'change' or 'read', for the refusal
395
+ */
396
+ function assertNoPrivilegedSettings(request, keys, verb = 'change') {
397
+ const privileged = settings.privilegedKeys.filter(key => keys.includes(key));
398
+ if (!privileged.length || !isRestrictedCredential(request)) {
399
+ return;
400
+ }
401
+
402
+ throw Boom.forbidden(`A token with restricted permissions can not ${verb} ${privileged.join(', ')}`);
403
+ }
404
+
359
405
  module.exports = {
360
406
  handleError,
361
407
  logApiError,
362
408
  throwNotFound,
409
+ assertNoPrivilegedSettings,
363
410
  flattenOAuthAppMeta,
364
411
  maskCustomHeaders,
365
412
  maskUrlPassword,
@@ -3,12 +3,13 @@
3
3
  const Joi = require('joi');
4
4
  const { QUEUES_BY_NAME } = require('../db');
5
5
  const settings = require('../settings');
6
+ const { PRIVILEGED_SETTINGS_SUMMARY } = require('../privileged-settings');
6
7
  const consts = require('../consts');
7
8
  const { failAction, maybeReloadTlsCertificates, TLS_MATERIAL_SETTINGS } = require('../tools');
8
9
  const { tlsSettingChanged } = require('../tls/store');
9
10
  const { queueStats } = require('../queue-stats');
10
11
  const Boom = require('@hapi/boom');
11
- const { handleError, maskSecrets, containsMaskedSecret, isMaskedRoundTrip, MASKED } = require('./route-helpers');
12
+ const { handleError, maskSecrets, containsMaskedSecret, isMaskedRoundTrip, assertNoPrivilegedSettings, MASKED } = require('./route-helpers');
12
13
  const { settingsSchema, settingsQuerySchema, apiResponses, ENUM_DESCRIPTIONS } = require('../schemas');
13
14
 
14
15
  // Response variant of the settings schema. Secret values are masked and returned as booleans,
@@ -32,6 +33,17 @@ settingsOutputSchema.eventTypes = Joi.array()
32
33
  .description('Supported webhook event types')
33
34
  .label('EventTypesList');
34
35
 
36
+ // The settings the two MCP settings tools offer: every key of the schema except the privileged
37
+ // ones (PRIVILEGED_SETTINGS_KEYS in lib/privileged-settings.js) and the ones the schema hides from the
38
+ // published document (`swaggerHidden`, the deprecated aliases), which the tool schema converter
39
+ // drops as well. Derived rather than listed, so a setting added to the schema is offered and one
40
+ // added to the privileged list is withdrawn without a second edit here. The REST handler refuses
41
+ // the privileged keys to a narrowed credential, so the `write/settings` grant means the same thing
42
+ // on both surfaces; test/settings-privileged-keys-test.js asserts the tool schema and the list
43
+ // agree.
44
+ const isHiddenSetting = key => (settingsSchema[key].describe().metas || []).some(meta => meta && meta.swaggerHidden);
45
+ const MCP_SETTINGS_KEYS = Object.keys(settingsSchema).filter(key => !settings.privilegedKeys.includes(key) && !isHiddenSetting(key));
46
+
35
47
  async function init(args) {
36
48
  const { server, call, notify, CORS_CONFIG } = args;
37
49
 
@@ -42,6 +54,14 @@ async function init(args) {
42
54
  async handler(request) {
43
55
  let values = {};
44
56
  try {
57
+ // Before the first read, like the write below: the keys a narrowed credential may
58
+ // not change are the ones it may not read either
59
+ assertNoPrivilegedSettings(
60
+ request,
61
+ Object.keys(request.query).filter(key => request.query[key]),
62
+ 'read'
63
+ );
64
+
45
65
  for (let key of Object.keys(request.query)) {
46
66
  if (request.query[key]) {
47
67
  if (key === 'eventTypes') {
@@ -70,9 +90,8 @@ async function init(args) {
70
90
  // covers the values that are hidden behind a boolean, which is not the same set:
71
91
  // proxyUrl, httpProxyUrl, webhooks and webhooksCustomHeaders are returned as values
72
92
  // (they are useful to read back) and used to be returned in full, so this endpoint
73
- // disclosed exactly what the account getters were masking. It sits in the
74
- // never-grantable admin group, so no narrowed token reaches it - but leaving the
75
- // asymmetry here is how the next reader learns the wrong pattern.
93
+ // disclosed exactly what the account getters were masking. A narrowed credential is
94
+ // refused the privileged keys above; this is what the unnarrowed one gets.
76
95
  maskSecrets(values);
77
96
 
78
97
  return values;
@@ -83,6 +102,12 @@ async function init(args) {
83
102
  tags: ['api', 'Settings'],
84
103
 
85
104
  plugins: {
105
+ mcp: {
106
+ name: 'get_settings',
107
+ title: 'Get settings',
108
+ description: `Read instance settings. Set each setting you want returned to true. Secrets come back as a boolean saying whether a value is stored, credentials inside URLs are masked, and eventTypes lists the webhook event names the instance supports. Settings that would widen this credential (${PRIVILEGED_SETTINGS_SUMMARY}) are not offered.`,
109
+ keep: MCP_SETTINGS_KEYS.concat(['eventTypes'])
110
+ },
86
111
  openapi: {
87
112
  responses: apiResponses('Returns the values of the settings requested via query arguments. Secrets are masked.', 400, 401, 403, 429, 500)
88
113
  }
@@ -121,6 +146,9 @@ async function init(args) {
121
146
  // Only the keys whose value actually changed, unlike `applied` - see tlsSettingChanged()
122
147
  let tlsChanged = [];
123
148
  try {
149
+ // Before the first write, so a refused payload leaves nothing half-applied
150
+ assertNoPrivilegedSettings(request, Object.keys(request.payload));
151
+
124
152
  for (let key of Object.keys(request.payload)) {
125
153
  let value = request.payload[key];
126
154
 
@@ -179,6 +207,12 @@ async function init(args) {
179
207
  tags: ['api', 'Settings'],
180
208
 
181
209
  plugins: {
210
+ mcp: {
211
+ name: 'update_settings',
212
+ title: 'Update settings',
213
+ description: `Change instance settings. Send only the keys to change; they take effect immediately on every worker. Covers where webhooks are delivered and which events are sent, notification shaping, branding, sync strategy, queue retention and AI processing. Confirm with the user before changing the webhook target. The settings that would widen this credential (${PRIVILEGED_SETTINGS_SUMMARY}) are not offered.`,
214
+ keep: MCP_SETTINGS_KEYS
215
+ },
182
216
  openapi: {
183
217
  responses: apiResponses('Returns the list of setting keys that were updated.', 400, 401, 403, 429, 500)
184
218
  }
@@ -252,6 +286,12 @@ async function init(args) {
252
286
  tags: ['api', 'Settings'],
253
287
 
254
288
  plugins: {
289
+ mcp: {
290
+ name: 'get_queue',
291
+ title: 'Get queue state',
292
+ description:
293
+ 'Get the state of a job queue: whether it is paused and how many jobs are active, waiting and delayed. `notify` carries webhook deliveries, `submit` carries outbound mail.'
294
+ },
255
295
  openapi: {
256
296
  responses: apiResponses('Returns the job counts and paused state for the queue.', 400, 401, 403, 429, 500)
257
297
  }
@@ -354,6 +394,12 @@ async function init(args) {
354
394
  tags: ['api', 'Settings'],
355
395
 
356
396
  plugins: {
397
+ mcp: {
398
+ name: 'set_queue_state',
399
+ title: 'Pause or resume a queue',
400
+ description:
401
+ 'Pause or resume a job queue. Set paused to true to stop the queue from processing jobs (they keep accumulating), false to resume it.'
402
+ },
357
403
  openapi: {
358
404
  responses: apiResponses('Returns the queue state after the change.', 400, 401, 403, 429, 500)
359
405
  }
@@ -30,6 +30,12 @@ async function init(args) {
30
30
  tags: ['api', 'Stats'],
31
31
 
32
32
  plugins: {
33
+ mcp: {
34
+ name: 'get_instance_stats',
35
+ title: 'Get instance statistics',
36
+ description:
37
+ 'Get instance-wide statistics: the running version, the license, how many accounts are connected, disconnected or failing, and message and webhook counters for the last `seconds` (default one day). The first call to make when asked how the instance is doing.'
38
+ },
33
39
  openapi: {
34
40
  responses: apiResponses('Returns counters, connection states and process information for this instance.', 400, 401, 403, 429, 500)
35
41
  }
@@ -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
  }
@@ -1138,10 +1138,10 @@ async function resolver(email, gt, credentials) {
1138
1138
  * @param {Object} gt - gettext instance, for the app-password hints
1139
1139
  * @param {Object} [credentials] - `{ user, pass }` for the mailbox. Only used to answer an
1140
1140
  * autodiscovery endpoint that refuses to respond anonymously, which is how hosted Exchange
1141
- * behaves; every other resolver is unauthenticated. The hosted setup form is the one caller that
1142
- * holds a password, so it is the one that passes this. `GET /v1/autoconfig` takes the address in
1143
- * a query string and can never carry one, which is why an Exchange domain stays unresolvable
1144
- * there - deliberately, rather than for want of a credential-carrying endpoint.
1141
+ * behaves; every other resolver is unauthenticated. The callers that hold a password pass it:
1142
+ * the hosted setup form, and `POST /v1/autoconfig` for an integrator running its own form.
1143
+ * `GET /v1/autoconfig` takes the address in a query string, where a password must never go, so
1144
+ * it stays anonymous and an Exchange domain stays unresolvable there - use the POST instead.
1145
1145
  * @returns {Promise<Object>} `{ imap, smtp, _source }`, plus `appPassword` where one applies
1146
1146
  */
1147
1147
  async function autodetectImapSettings(email, gt, credentials) {
@@ -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');