emailengine-app 2.85.0 → 2.87.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 (137) hide show
  1. package/.ncurc.js +24 -6
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +97 -0
  4. package/DOCKER_DEPLOYMENT.md +2 -1
  5. package/Dockerfile +16 -3
  6. package/ENVIRONMENT.md +139 -0
  7. package/README.md +5 -1
  8. package/config/default.toml +2 -0
  9. package/copy-static-files.sh +4 -2
  10. package/data/google-crawlers.json +1 -1
  11. package/data/public_suffix_list.dat +4 -3
  12. package/lib/account-assignment.js +19 -0
  13. package/lib/account.js +285 -195
  14. package/lib/api-error-codes.js +49 -0
  15. package/lib/api-reference/model.js +6 -1
  16. package/lib/api-routes/account-routes.js +91 -32
  17. package/lib/api-routes/blocklist-routes.js +68 -2
  18. package/lib/api-routes/delivery-test-routes.js +1 -1
  19. package/lib/api-routes/gateway-routes.js +82 -10
  20. package/lib/api-routes/index.js +4 -0
  21. package/lib/api-routes/license-routes.js +2 -2
  22. package/lib/api-routes/mailbox-routes.js +3 -3
  23. package/lib/api-routes/message-routes.js +15 -7
  24. package/lib/api-routes/oauth2-app-routes.js +15 -8
  25. package/lib/api-routes/outbox-routes.js +77 -66
  26. package/lib/api-routes/permission-map.js +55 -6
  27. package/lib/api-routes/scoped-routes.js +74 -0
  28. package/lib/api-routes/settings-routes.js +11 -4
  29. package/lib/api-routes/stats-routes.js +5 -1
  30. package/lib/api-routes/submit-routes.js +25 -5
  31. package/lib/api-routes/template-routes.js +7 -6
  32. package/lib/api-routes/token-routes.js +11 -5
  33. package/lib/api-routes/webhook-delivery-routes.js +262 -0
  34. package/lib/api-routes/webhook-route-routes.js +119 -4
  35. package/lib/calendar-event.js +81 -1
  36. package/lib/consts.js +38 -46
  37. package/lib/db.js +14 -6
  38. package/lib/delivery-error.js +6 -0
  39. package/lib/deprecations.js +270 -0
  40. package/lib/email-client/base-client.js +134 -158
  41. package/lib/email-client/fallback-poll.js +62 -0
  42. package/lib/email-client/gmail-client.js +59 -11
  43. package/lib/email-client/imap/adaptive-idle-store.js +73 -0
  44. package/lib/email-client/imap/adaptive-idle.js +278 -0
  45. package/lib/email-client/imap/connection-errors.js +14 -1
  46. package/lib/email-client/imap/idle-settings.js +31 -5
  47. package/lib/email-client/imap/listing-diff.js +37 -0
  48. package/lib/email-client/imap/mailbox.js +380 -227
  49. package/lib/email-client/imap/subconnection.js +7 -29
  50. package/lib/email-client/imap/sync-operations.js +220 -127
  51. package/lib/email-client/imap-client.js +227 -163
  52. package/lib/email-client/message-builder.js +14 -79
  53. package/lib/email-client/outlook-client.js +378 -338
  54. package/lib/email-client/smtp-pool-manager.js +16 -13
  55. package/lib/email-client/sync-state-fields.js +19 -0
  56. package/lib/encrypt.js +157 -41
  57. package/lib/enum-descriptions.js +3 -1
  58. package/lib/env-setting-overrides.js +288 -0
  59. package/lib/export-worker.js +751 -0
  60. package/lib/export.js +64 -15
  61. package/lib/field-usage.js +1 -1
  62. package/lib/gateway.js +17 -1
  63. package/lib/get-raw-email.js +35 -108
  64. package/lib/health.js +75 -0
  65. package/lib/lock-run.js +119 -0
  66. package/lib/logger-consts.js +48 -0
  67. package/lib/logger.js +1 -1
  68. package/lib/lua/z-head-scores.lua +28 -0
  69. package/lib/network-errors.js +1 -1
  70. package/lib/node-version.js +24 -0
  71. package/lib/notify-attachments.js +20 -1
  72. package/lib/oauth/gmail.js +54 -29
  73. package/lib/oauth2-apps.js +630 -655
  74. package/lib/otp.js +66 -0
  75. package/lib/outbox.js +184 -54
  76. package/lib/parse-message.js +3 -3
  77. package/lib/privileged-settings.js +2 -2
  78. package/lib/queue-browser/definitions.js +11 -0
  79. package/lib/queue-browser/index.js +68 -19
  80. package/lib/queue-job-actions.js +18 -1
  81. package/lib/queue-retention.js +48 -12
  82. package/lib/queue-stats.js +11 -2
  83. package/lib/read-env-value.js +3 -0
  84. package/lib/redis-memory-warnings.js +99 -0
  85. package/lib/redis-reconnect.js +29 -0
  86. package/lib/request-timing.js +23 -0
  87. package/lib/respawn-backoff.js +35 -0
  88. package/lib/rewrite-text-nodes.js +19 -59
  89. package/lib/schemas.js +225 -41
  90. package/lib/settings.js +6 -2
  91. package/lib/smtp-auth.js +19 -1
  92. package/lib/swagger-options.js +2 -2
  93. package/lib/thread-diagnostics.js +18 -1
  94. package/lib/tls/provision.js +6 -3
  95. package/lib/token-audit-log.js +19 -20
  96. package/lib/token-permission-view.js +4 -3
  97. package/lib/tools.js +8 -41
  98. package/lib/ui-routes/admin-config-routes.js +64 -90
  99. package/lib/ui-routes/admin-entities-routes.js +2 -14
  100. package/lib/ui-routes/imap-idle-field.js +1 -1
  101. package/lib/ui-routes/outlook-subscription-view.js +1 -1
  102. package/lib/ui-routes/overridable-fields.js +84 -0
  103. package/lib/ui-routes/queue-routes.js +8 -5
  104. package/lib/ui-routes/settings-page.js +6 -0
  105. package/lib/utils/decode-headers.js +3 -12
  106. package/lib/utils/filter-empty.js +20 -0
  107. package/lib/utils/int-setting.js +48 -0
  108. package/lib/utils/tracking-settings.js +35 -0
  109. package/lib/web-safe-html.js +18 -105
  110. package/lib/webhook-delivery.js +461 -0
  111. package/lib/webhook-failures.js +132 -0
  112. package/lib/webhook-request.js +29 -1
  113. package/lib/webhook-routing.js +30 -1
  114. package/lib/webhook-test.js +88 -0
  115. package/lib/webhooks.js +59 -41
  116. package/lib/worker-rpc-error.js +2 -1
  117. package/package.json +28 -26
  118. package/sbom.json +600 -678
  119. package/server.js +149 -76
  120. package/static/css/flyonui.css +1 -1
  121. package/static/js/ace/ace.js +1 -1
  122. package/static/js/ee-client.js +650 -196
  123. package/static/licenses.html +49 -59
  124. package/translations/messages.pot +26 -26
  125. package/views/config/security.hbs +22 -0
  126. package/views/config/service.hbs +44 -0
  127. package/views/config/webhooks.hbs +36 -0
  128. package/views/layout/app.hbs +9 -6
  129. package/views/legal.hbs +8 -0
  130. package/views/partials/queue_retention_note.hbs +12 -8
  131. package/views/partials/ui/env-managed-alert.hbs +16 -7
  132. package/workers/api.js +112 -37
  133. package/workers/export.js +16 -631
  134. package/workers/imap.js +13 -0
  135. package/workers/smtp.js +9 -11
  136. package/workers/webhooks.js +18 -432
  137. package/lib/email-client/outlook-fallback-poll.js +0 -30
@@ -8,6 +8,7 @@ const consts = require('../consts');
8
8
  const { failAction, maybeReloadTlsCertificates, TLS_MATERIAL_SETTINGS } = require('../tools');
9
9
  const { tlsSettingChanged } = require('../tls/store');
10
10
  const { queueStats } = require('../queue-stats');
11
+ const { isOverridableSetting, storeOverridableSetting } = require('../env-setting-overrides');
11
12
  const Boom = require('@hapi/boom');
12
13
  const { handleError, maskSecrets, containsMaskedSecret, isMaskedRoundTrip, assertNoPrivilegedSettings, MASKED } = require('./route-helpers');
13
14
  const { settingsSchema, settingsQuerySchema, isHiddenSetting, apiResponses, ENUM_DESCRIPTIONS } = require('../schemas');
@@ -25,7 +26,7 @@ for (let key of Object.keys(settingsSchema)) {
25
26
  } else {
26
27
  // Use a distinct label for the nullable response variant, otherwise the generated
27
28
  // OpenAPI spec would contain suffixed duplicates of the request-side components
28
- settingsOutputSchema[key] = settingsSchema[key].allow(null).label(`${key}Response`);
29
+ settingsOutputSchema[key] = settingsSchema[key].allow(null).label(`Setting${key.charAt(0).toUpperCase()}${key.slice(1)}`);
29
30
  }
30
31
  }
31
32
  settingsOutputSchema.eventTypes = Joi.array()
@@ -179,7 +180,13 @@ function registerUpdateSettings(server, args) {
179
180
  tlsChanged.push(key);
180
181
  }
181
182
 
182
- await settings.set(key, value);
183
+ if (isOverridableSetting(key)) {
184
+ // null clears the setting so its environment variable or default applies
185
+ // again; settings.set() would have stored the null
186
+ await storeOverridableSetting(key, value);
187
+ } else {
188
+ await settings.set(key, value);
189
+ }
183
190
  applied[key] = value;
184
191
  }
185
192
  } catch (err) {
@@ -303,7 +310,7 @@ function registerGetQueueSettings(server, args) {
303
310
  },
304
311
  options: {
305
312
  description: 'Show queue information',
306
- notes: 'Show queue status and current state',
313
+ notes: 'Returns how many jobs a queue holds in each state and whether it is paused.',
307
314
  tags: ['api', 'Settings'],
308
315
 
309
316
  plugins: {
@@ -408,7 +415,7 @@ function registerUpdateQueueSettings(server, args) {
408
415
  },
409
416
  options: {
410
417
  description: 'Set queue settings',
411
- notes: 'Set queue settings',
418
+ notes: 'Pauses or resumes a queue. A paused queue keeps accepting jobs, the workers stop taking them until it is resumed.',
412
419
  tags: ['api', 'Settings'],
413
420
 
414
421
  plugins: {
@@ -27,6 +27,7 @@ async function init(args) {
27
27
 
28
28
  options: {
29
29
  description: 'Return server stats',
30
+ notes: 'Returns the running version and license, how many accounts are in each connection state, message and webhook counters for the last `seconds`, and the Redis server details with any warnings about how Redis is configured.',
30
31
  tags: ['api', 'Stats'],
31
32
 
32
33
  plugins: {
@@ -85,7 +86,10 @@ async function init(args) {
85
86
  key: Joi.string().example('maxmemory-policy').description('Warning identifier'),
86
87
  color: Joi.string().example('warning').description('Severity indicator'),
87
88
  title: Joi.string().example('Unsafe Redis eviction policy').description('Warning title'),
88
- details: Joi.array().items(Joi.string().example('maxmemory-policy is allkeys-lru')).description('Warning details')
89
+ details: Joi.array()
90
+ .items(Joi.string().example('maxmemory-policy is allkeys-lru'))
91
+ .description('Warning details')
92
+ .label('RedisWarningDetails')
89
93
  })
90
94
  .unknown()
91
95
  .label('RedisWarningEntry')
@@ -1,6 +1,7 @@
1
1
  'use strict';
2
2
 
3
3
  const Joi = require('joi');
4
+ const Boom = require('@hapi/boom');
4
5
  const { redis } = require('../db');
5
6
  const { Account } = require('../account');
6
7
  const getSecret = require('../get-secret');
@@ -27,7 +28,8 @@ const {
27
28
  apiResponses,
28
29
  ENUM_DESCRIPTIONS,
29
30
  MAX_MESSAGE_ATTACHMENTS,
30
- apiBoolean
31
+ apiBoolean,
32
+ submitOtpSchema
31
33
  } = require('../schemas');
32
34
 
33
35
  // Schema fragments shared between the message submit and the draft submit routes. Joi schemas
@@ -91,10 +93,23 @@ const idempotencyResponseSchema = Joi.object({
91
93
  .example('MISS')
92
94
  .description('Whether this response was produced now or replayed from the idempotency cache')
93
95
  .meta({ enumDescriptions: ENUM_DESCRIPTIONS.idempotencyStatus })
96
+ .label('ResponseIdempotencyStatus')
94
97
  })
95
98
  .description('Idempotency info, present when an Idempotency-Key header was used')
96
99
  .label('ResponseIdempotency');
97
100
 
101
+ /**
102
+ * Refuses an otp with useStructuredFormat, whose JSON Graph send would drop the OTP-Token header
103
+ *
104
+ * @param {Object} request - the Hapi request
105
+ */
106
+ function assertOtpFormat(request) {
107
+ const payload = request.payload || {};
108
+ if (request.query.useStructuredFormat && (payload.otp || (payload.mailMerge || []).some(entry => entry && entry.otp))) {
109
+ throw Boom.badRequest('A one-time passcode (otp) can not be sent with useStructuredFormat');
110
+ }
111
+ }
112
+
98
113
  function buildSubmitMessagePayloadSchema(MAX_ATTACHMENT_SIZE) {
99
114
  return Joi.object({
100
115
  reference: messageReferenceSchema,
@@ -202,7 +217,8 @@ function buildSubmitMessagePayloadSchema(MAX_ATTACHMENT_SIZE) {
202
217
  sendAt: Joi.date()
203
218
  .iso()
204
219
  .example('2021-07-08T07:06:34.336Z')
205
- .description('Send message at specified time. Overrides message level `sendAt` value.')
220
+ .description('Send message at specified time. Overrides message level `sendAt` value.'),
221
+ otp: submitOtpSchema.description('One-time passcode for this recipient. Overrides message level `otp` value.').label('MailMergeOtp')
206
222
  }).label('MailMergeListEntry')
207
223
  )
208
224
  .min(1)
@@ -240,17 +256,19 @@ function buildSubmitMessagePayloadSchema(MAX_ATTACHMENT_SIZE) {
240
256
  .description('References an existing attachment by its ID instead of providing new attachment content')
241
257
  .meta({ usage: FIELD_USAGE.attachmentReference })
242
258
  .label('AttachmentReference')
243
- }).label('UploadAttachment')
259
+ }).label('SubmitAttachment')
244
260
  )
245
261
  .max(MAX_MESSAGE_ATTACHMENTS)
246
262
  .description('List of attachments')
247
- .label('UploadAttachmentList'),
263
+ .label('SubmitAttachmentList'),
248
264
 
249
265
  messageId: Joi.string().max(996).example('<test123@example.com>').description('Message ID'),
250
266
  headers: Joi.object().label('CustomHeaders').description('Custom Headers').unknown().example({
251
267
  'X-My-Custom-Header': 'Custom header value'
252
268
  }),
253
269
 
270
+ otp: submitOtpSchema,
271
+
254
272
  trackingEnabled: Joi.boolean().example(false).description('Should EmailEngine track clicks and opens for this message').meta({ swaggerHidden: true }),
255
273
 
256
274
  trackOpens: Joi.boolean().example(false).description('Should EmailEngine track opens for this message'),
@@ -353,7 +371,7 @@ function buildSubmitMessageResponseSchema() {
353
371
  error: Joi.string().example('Referenced message was not found').description('An error message if referenced message processing failed')
354
372
  })
355
373
  .description('Reference info if referencing was requested')
356
- .label('ResponseReference'),
374
+ .label('SubmitResponseReference'),
357
375
 
358
376
  preview: Joi.string()
359
377
  .base64()
@@ -417,6 +435,7 @@ function registerSubmitMessage(server, args) {
417
435
 
418
436
  try {
419
437
  assertNoNetworkOverride(request);
438
+ assertOtpFormat(request);
420
439
 
421
440
  return await accountObject.queueMessage(request.payload, {
422
441
  source: 'api',
@@ -709,3 +728,4 @@ async function init(args) {
709
728
  }
710
729
 
711
730
  module.exports = init;
731
+ module.exports.assertOtpFormat = assertOtpFormat;
@@ -8,7 +8,7 @@ const Joi = require('joi');
8
8
  const { failAction } = require('../tools');
9
9
  const { handleError, throwNotFound } = require('./route-helpers');
10
10
 
11
- const { templateSchemas, accountIdSchema, apiResponses, apiBoolean } = require('../schemas');
11
+ const { templateSchemas, accountIdSchema, apiResponses, apiBoolean, listQuerySchema } = require('../schemas');
12
12
  const { IMPACT } = require('./operation-impact');
13
13
  const { MCP_MAX_PAGE_SIZE } = require('../consts');
14
14
 
@@ -152,7 +152,7 @@ function registerUpdateTemplate(server, args) {
152
152
 
153
153
  options: {
154
154
  description: 'Update a template',
155
- notes: 'Update a stored template.',
155
+ notes: 'Changes a stored template. Fields left out of the request keep their stored values.',
156
156
  tags: ['api', 'Templates'],
157
157
 
158
158
  plugins: {
@@ -235,7 +235,7 @@ function registerListTemplates(server, args) {
235
235
  await accountObject.loadAccountData();
236
236
  }
237
237
 
238
- return await templates.list(request.query.account, request.query.page, request.query.pageSize);
238
+ return await templates.list(request.query.account, request.query.page, request.query.pageSize, request.query.query);
239
239
  } catch (err) {
240
240
  handleError(request, err);
241
241
  }
@@ -243,7 +243,7 @@ function registerListTemplates(server, args) {
243
243
 
244
244
  options: {
245
245
  description: 'List account templates',
246
- notes: 'Lists stored templates for the account',
246
+ notes: 'Lists the stored templates, one page at a time: the shared ones, or with `account` set the templates of that account.',
247
247
  tags: ['api', 'Templates'],
248
248
 
249
249
  plugins: {
@@ -283,7 +283,8 @@ function registerListTemplates(server, args) {
283
283
  .example(0)
284
284
  .description('Page number (zero indexed, so use 0 for first page)')
285
285
  .label('PageNumber'),
286
- pageSize: Joi.number().integer().min(1).max(1000).default(20).example(20).description('How many entries per page').label('PageSize')
286
+ pageSize: Joi.number().integer().min(1).max(1000).default(20).example(20).description('How many entries per page').label('PageSize'),
287
+ query: listQuerySchema('ID, name or description', 'TemplatesListQuery')
287
288
  }).label('AccountTemplatesRequest')
288
289
  },
289
290
 
@@ -422,7 +423,7 @@ function registerDeleteTemplate(server, args) {
422
423
  },
423
424
  options: {
424
425
  description: 'Remove a template',
425
- notes: 'Delete a stored template',
426
+ notes: 'Deletes a stored template. Messages already queued from it are not affected.',
426
427
  tags: ['api', 'Templates'],
427
428
 
428
429
  plugins: {
@@ -22,6 +22,7 @@ const {
22
22
  const { IMPACT } = require('./operation-impact');
23
23
  const { mintWidenings } = require('./mint-bounds');
24
24
  const { MCP_MAX_PAGE_SIZE } = require('../consts');
25
+ const { REMOVAL_DATE, TOKEN_ROUTES_DEPRECATED_AT } = require('../deprecations');
25
26
 
26
27
  const tokenAccessSchema = Joi.object({
27
28
  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'),
@@ -325,7 +326,7 @@ function registerDeleteToken(server, ctx) {
325
326
  handler: deleteTokenHandler,
326
327
  options: {
327
328
  description: 'Remove a token',
328
- notes: 'Delete an access token',
329
+ notes: 'Revokes an access token. Requests made with it are refused from then on.',
329
330
  tags: ['api', 'Access Tokens'],
330
331
 
331
332
  plugins: {
@@ -697,10 +698,11 @@ function registerDeprecatedCreateToken(server, ctx) {
697
698
 
698
699
  options: {
699
700
  description: 'Provision an access token (deprecated)',
700
- notes: 'Deprecated alias of `POST /v1/tokens`, which behaves identically - use that path instead.',
701
+ notes: `Deprecated alias of \`POST /v1/tokens\`, which behaves identically - use that path instead. Will be removed after ${REMOVAL_DATE}.`,
701
702
  tags: ['api', 'Access Tokens'],
702
703
 
703
704
  plugins: {
705
+ deprecation: { since: TOKEN_ROUTES_DEPRECATED_AT, successor: 'POST /v1/tokens', link: '/v1/tokens' },
704
706
  openapi: {
705
707
  deprecated: true,
706
708
  responses: apiResponses('Returns the new token value. This is the only time it is shown - store it now.', 400, 401, 403, 404, 429, 500)
@@ -742,10 +744,12 @@ function registerDeprecatedDeleteToken(server, ctx) {
742
744
  handler: deleteTokenHandler,
743
745
  options: {
744
746
  description: 'Remove a token (deprecated)',
745
- notes: 'Deprecated alias of `DELETE /v1/tokens/{token}`, which behaves identically - use that path instead.',
747
+ notes: `Deprecated alias of \`DELETE /v1/tokens/{token}\`, which behaves identically - use that path instead. Will be removed after ${REMOVAL_DATE}.`,
746
748
  tags: ['api', 'Access Tokens'],
747
749
 
748
750
  plugins: {
751
+ // no Link: the successor path would have to carry the token
752
+ deprecation: { since: TOKEN_ROUTES_DEPRECATED_AT, successor: 'DELETE /v1/tokens/{token}' },
749
753
  openapi: {
750
754
  deprecated: true,
751
755
  'x-ee-impact': IMPACT.DESTRUCTIVE,
@@ -796,10 +800,11 @@ function registerDeprecatedListAccountTokens(server, ctx) {
796
800
 
797
801
  options: {
798
802
  description: 'List account tokens (deprecated)',
799
- notes: 'Deprecated alias for listing the access tokens of one account - use `GET /v1/tokens` with the `account` argument instead, which also pages the listing.',
803
+ notes: `Deprecated alias for listing the access tokens of one account - use \`GET /v1/tokens\` with the \`account\` argument instead, which also pages the listing. Will be removed after ${REMOVAL_DATE}.`,
800
804
  tags: ['api', 'Access Tokens'],
801
805
 
802
806
  plugins: {
807
+ deprecation: { since: TOKEN_ROUTES_DEPRECATED_AT, successor: 'GET /v1/tokens?account={account}', link: '/v1/tokens' },
803
808
  openapi: {
804
809
  deprecated: true,
805
810
  responses: apiResponses('Returns the access tokens scoped to the account.', 400, 401, 403, 429, 500)
@@ -861,7 +866,8 @@ async function init(args) {
861
866
  // first. The old paths stay registered against the same handlers and schema instances, but are
862
867
  // left OUT of the published document and the API reference (plugins.openapi.deprecated - see
863
868
  // lib/openapi/build-document.js): they exist for old integrations to keep working, and
864
- // documenting them would steer new ones onto retired paths.
869
+ // documenting them would steer new ones onto retired paths. They are removed after
870
+ // REMOVAL_DATE (lib/deprecations.js); until then every response says so in its headers.
865
871
 
866
872
  registerDeprecatedCreateToken(server, ctx);
867
873
  registerDeprecatedDeleteToken(server, ctx);
@@ -0,0 +1,262 @@
1
+ 'use strict';
2
+
3
+ const Joi = require('joi');
4
+ const logger = require('../logger');
5
+ const webhookFailures = require('../webhook-failures');
6
+ const { failAction } = require('../tools');
7
+ const { handleError, throwNotFound } = require('./route-helpers');
8
+ const { accountIdSchema, apiResponses, apiBoolean } = require('../schemas');
9
+ const { routeScopes, routeParams, scopedLabel, mcpFor, pagingQuery } = require('./scoped-routes');
10
+ const { IMPACT } = require('./operation-impact');
11
+ const { MCP_MAX_PAGE_SIZE } = require('../consts');
12
+
13
+ // The webhook deliveries that failed for good: list, retry, remove. Like the outbox routes they
14
+ // exist for the whole instance and for one account (see scoped-routes.js); every delivery ID the
15
+ // account form is given has to belong to that account.
16
+ const SCOPES = routeScopes({ instance: '/v1/webhooks/failed', account: '/v1/account/{account}/webhooks/failed' });
17
+
18
+ const deliveryIdParam = {
19
+ delivery: Joi.string().max(256).example('1543').description('Failed webhook delivery ID, as the listing returns it').required()
20
+ };
21
+
22
+ const failedDeliverySchema = Joi.object({
23
+ id: Joi.string().example('1543').description('Delivery ID'),
24
+ event: Joi.string().example('messageNew').description('Webhook event type'),
25
+ eventId: Joi.string().allow(null).example('c4a2bd7e-3a50-4b5d-a0d1-29fa2c9e2b6c').description('Event identifier, as sent in the webhook payload'),
26
+ account: Joi.string().allow(null).example('user123').description('Account the event is about'),
27
+ path: Joi.string().allow(null).example('INBOX').description('Folder the event is about'),
28
+ messageId: Joi.string().allow(null).example('<test123@example.com>').description('Message-ID of the message the event is about'),
29
+ route: Joi.object({
30
+ id: Joi.string().example('AAABgS-UcAYAAAABAA').description('Webhook route ID'),
31
+ name: Joi.string().allow(null).example('Send to Slack').description('Webhook route name. Null when the route no longer exists')
32
+ })
33
+ .allow(null)
34
+ .description('The custom webhook route the delivery was for. Null for the default webhook target')
35
+ .label('FailedWebhookDeliveryRoute'),
36
+ created: Joi.date().iso().allow(null).example('2026-10-21T08:02:11.120Z').description('When the event was queued'),
37
+ failed: Joi.date().iso().allow(null).example('2026-10-21T09:40:43.301Z').description('When the last attempt failed'),
38
+ attemptsMade: Joi.number().integer().example(10).description('Delivery attempts made'),
39
+ attempts: Joi.number().integer().example(10).description('Delivery attempts allowed'),
40
+ error: Joi.object({
41
+ message: Joi.string().example('Request failed with status 503').description('Why the last attempt failed'),
42
+ code: Joi.string().allow(null).example('ECONNREFUSED').description('Error code, when the failure carried one'),
43
+ statusCode: Joi.number().integer().allow(null).example(503).description('HTTP status the receiver answered with, when it answered'),
44
+ permanent: Joi.boolean().example(false).description('True when retrying could not help, so the delivery was given up on early')
45
+ })
46
+ .allow(null)
47
+ .label('FailedWebhookDeliveryError')
48
+ }).label('FailedWebhookDelivery');
49
+
50
+ function registerListFailed(server, ctx, scope) {
51
+ const { CORS_CONFIG } = ctx;
52
+
53
+ const query = pagingQuery();
54
+ if (scope.isInstance) {
55
+ query.account = accountIdSchema.description('List only the deliveries of this account');
56
+ }
57
+
58
+ server.route({
59
+ method: 'GET',
60
+ path: scope.prefix,
61
+
62
+ async handler(request) {
63
+ try {
64
+ return await webhookFailures.list(Object.assign({ logger }, request.query, request.params.account ? { account: request.params.account } : {}));
65
+ } catch (err) {
66
+ handleError(request, err);
67
+ }
68
+ },
69
+
70
+ options: {
71
+ description: scope.isInstance ? 'List failed webhook deliveries' : 'List failed webhook deliveries of an account',
72
+ notes: 'Lists webhook deliveries that failed for good, most recent first: every attempt failed, or the failure was permanent. Each entry says what the event was about and why the last attempt failed; the event payload itself is not included. With an account filter, the most recent failed deliveries of the whole queue are scanned for that account, and `scanLimited` says when the scan stopped before the end of the queue. How many failed deliveries are kept is set by EENGINE_QUEUE_KEEP_FAILED and EENGINE_QUEUE_KEEP_FAILED_AGE.',
73
+ tags: ['api', 'Webhooks'],
74
+
75
+ plugins: {
76
+ mcp: mcpFor(scope, {
77
+ name: 'list_failed_webhooks',
78
+ title: 'List failed webhook deliveries',
79
+ description:
80
+ 'List the webhook deliveries that failed for good, most recent first: the event, the account and message it was about, the route it was for and why the last attempt failed. Use it after a receiver outage to find what to replay with retry_failed_webhook.',
81
+ bounds: { pageSize: MCP_MAX_PAGE_SIZE }
82
+ }),
83
+ openapi: {
84
+ responses: apiResponses('Returns a page of failed webhook deliveries.', 400, 401, 403, 429, 500)
85
+ }
86
+ },
87
+
88
+ auth: {
89
+ strategy: 'api-token',
90
+ mode: 'required'
91
+ },
92
+ cors: CORS_CONFIG,
93
+
94
+ validate: {
95
+ options: {
96
+ stripUnknown: false,
97
+ abortEarly: false,
98
+ convert: true
99
+ },
100
+ failAction,
101
+
102
+ params: routeParams(scope),
103
+ query: Joi.object(query).label(scopedLabel(scope, 'FailedWebhookDeliveriesFilter'))
104
+ },
105
+
106
+ response: {
107
+ schema: Joi.object({
108
+ total: Joi.number().integer().example(12).description('How many matching entries').label('TotalNumber'),
109
+ page: Joi.number().integer().example(0).description('Current page (0-based index)').label('PageNumber'),
110
+ pages: Joi.number().integer().example(1).description('Total page count').label('PagesNumber'),
111
+ scanLimited: Joi.boolean()
112
+ .example(false)
113
+ .description('True when an account filter was applied and the scan stopped before the end of the failed deliveries'),
114
+ deliveries: Joi.array().items(failedDeliverySchema).label('FailedWebhookDeliveryList')
115
+ }).label('FailedWebhookDeliveriesResponse'),
116
+ failAction: 'log'
117
+ }
118
+ }
119
+ });
120
+ }
121
+
122
+ function registerRetryFailed(server, ctx, scope) {
123
+ const { CORS_CONFIG } = ctx;
124
+
125
+ server.route({
126
+ method: 'POST',
127
+ path: `${scope.prefix}/{delivery}/retry`,
128
+
129
+ async handler(request) {
130
+ try {
131
+ const result = await webhookFailures.retry({ id: request.params.delivery, account: request.params.account, logger });
132
+ if (!result) {
133
+ throwNotFound('Requested webhook delivery was not found');
134
+ }
135
+ return result;
136
+ } catch (err) {
137
+ handleError(request, err);
138
+ }
139
+ },
140
+
141
+ options: {
142
+ description: 'Retry a failed webhook delivery',
143
+ notes: 'Puts a webhook delivery that failed for good back into the queue with a fresh set of attempts. It is sent to the target the event was queued for, with the payload it was queued with. A delivery that is not in the failed state answers 409 with `code` NotFailed.',
144
+ tags: ['api', 'Webhooks'],
145
+
146
+ plugins: {
147
+ mcp: mcpFor(scope, {
148
+ name: 'retry_failed_webhook',
149
+ title: 'Retry failed webhook delivery',
150
+ description:
151
+ 'Send a failed webhook delivery again, by the id list_failed_webhooks returned, with a fresh set of attempts. It goes to the target it was queued for, with the payload it was queued with.'
152
+ }),
153
+ openapi: {
154
+ responses: apiResponses('Returns a retry marker. The delivery is waiting for an attempt again.', 400, 401, 403, 404, 409, 429, 500)
155
+ }
156
+ },
157
+
158
+ auth: {
159
+ strategy: 'api-token',
160
+ mode: 'required'
161
+ },
162
+ cors: CORS_CONFIG,
163
+
164
+ validate: {
165
+ options: {
166
+ stripUnknown: false,
167
+ abortEarly: false,
168
+ convert: true
169
+ },
170
+ failAction,
171
+
172
+ params: routeParams(scope, deliveryIdParam).label(scopedLabel(scope, 'FailedWebhookDeliveryParams'))
173
+ },
174
+
175
+ response: {
176
+ schema: Joi.object({
177
+ retried: apiBoolean().default(true).description('Was the delivery put back into the queue'),
178
+ id: Joi.string().example('1543').description('Delivery ID')
179
+ }).label('RetryFailedWebhookDeliveryResponse'),
180
+ failAction: 'log'
181
+ }
182
+ }
183
+ });
184
+ }
185
+
186
+ function registerDeleteFailed(server, ctx, scope) {
187
+ const { CORS_CONFIG } = ctx;
188
+
189
+ server.route({
190
+ method: 'DELETE',
191
+ path: `${scope.prefix}/{delivery}`,
192
+
193
+ async handler(request) {
194
+ try {
195
+ const result = await webhookFailures.del({ id: request.params.delivery, account: request.params.account, logger });
196
+ if (!result) {
197
+ throwNotFound('Requested webhook delivery was not found');
198
+ }
199
+ return result;
200
+ } catch (err) {
201
+ handleError(request, err);
202
+ }
203
+ },
204
+
205
+ options: {
206
+ description: 'Remove a failed webhook delivery',
207
+ notes: 'Removes a webhook delivery that failed for good from the queue, so it is not kept for inspection or a retry. A delivery that is not in the failed state answers 409 with `code` NotFailed.',
208
+ tags: ['api', 'Webhooks'],
209
+
210
+ plugins: {
211
+ mcp: mcpFor(scope, {
212
+ name: 'remove_failed_webhook',
213
+ title: 'Remove failed webhook delivery',
214
+ description:
215
+ 'Remove a failed webhook delivery from the queue, by the id list_failed_webhooks returned, so it is no longer kept for a retry. Confirm with the user before calling this.'
216
+ }),
217
+ openapi: {
218
+ 'x-ee-impact': IMPACT.DESTRUCTIVE,
219
+ responses: apiResponses('Returns a deletion marker.', 400, 401, 403, 404, 409, 429, 500)
220
+ }
221
+ },
222
+
223
+ auth: {
224
+ strategy: 'api-token',
225
+ mode: 'required'
226
+ },
227
+ cors: CORS_CONFIG,
228
+
229
+ validate: {
230
+ options: {
231
+ stripUnknown: false,
232
+ abortEarly: false,
233
+ convert: true
234
+ },
235
+ failAction,
236
+
237
+ params: routeParams(scope, deliveryIdParam).label(scopedLabel(scope, 'FailedWebhookDeliveryParams'))
238
+ },
239
+
240
+ response: {
241
+ schema: Joi.object({
242
+ deleted: apiBoolean().default(true).description('Was the delivery removed'),
243
+ id: Joi.string().example('1543').description('Delivery ID')
244
+ }).label('DeleteFailedWebhookDeliveryResponse'),
245
+ failAction: 'log'
246
+ }
247
+ }
248
+ });
249
+ }
250
+
251
+ async function init(args) {
252
+ const { server, CORS_CONFIG } = args;
253
+ const ctx = { CORS_CONFIG };
254
+
255
+ for (const scope of SCOPES.all) {
256
+ registerListFailed(server, ctx, scope);
257
+ registerRetryFailed(server, ctx, scope);
258
+ registerDeleteFailed(server, ctx, scope);
259
+ }
260
+ }
261
+
262
+ module.exports = init;