emailengine-app 2.84.2 → 2.86.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 (164) hide show
  1. package/.ncurc.js +29 -9
  2. package/.prettierignore +5 -1
  3. package/.prettierrc.js +2 -0
  4. package/.release-please-manifest.json +1 -1
  5. package/CHANGELOG.md +107 -0
  6. package/Dockerfile +20 -1
  7. package/ENVIRONMENT.md +139 -0
  8. package/README.md +2 -2
  9. package/bin/emailengine.js +434 -408
  10. package/config/default.toml +2 -0
  11. package/copy-static-files.sh +41 -14
  12. package/data/google-crawlers.json +1 -1
  13. package/data/public_suffix_list.dat +16563 -0
  14. package/eslint.config.js +81 -99
  15. package/lib/account-assignment.js +19 -0
  16. package/lib/account.js +230 -170
  17. package/lib/api-error-codes.js +49 -0
  18. package/lib/api-reference/format.js +4 -3
  19. package/lib/api-reference/model.js +6 -1
  20. package/lib/api-routes/account-routes.js +255 -38
  21. package/lib/api-routes/blocklist-routes.js +91 -4
  22. package/lib/api-routes/delivery-test-routes.js +27 -4
  23. package/lib/api-routes/export-routes.js +28 -2
  24. package/lib/api-routes/gateway-routes.js +110 -12
  25. package/lib/api-routes/index.js +4 -0
  26. package/lib/api-routes/license-routes.js +2 -2
  27. package/lib/api-routes/mailbox-routes.js +44 -5
  28. package/lib/api-routes/message-routes.js +112 -10
  29. package/lib/api-routes/oauth2-app-routes.js +63 -23
  30. package/lib/api-routes/outbox-routes.js +97 -52
  31. package/lib/api-routes/permission-map.js +67 -7
  32. package/lib/api-routes/scoped-routes.js +74 -0
  33. package/lib/api-routes/settings-routes.js +34 -6
  34. package/lib/api-routes/stats-routes.js +5 -1
  35. package/lib/api-routes/submit-routes.js +337 -309
  36. package/lib/api-routes/template-routes.js +45 -8
  37. package/lib/api-routes/token-routes.js +152 -100
  38. package/lib/api-routes/webhook-delivery-routes.js +262 -0
  39. package/lib/api-routes/webhook-route-routes.js +132 -6
  40. package/lib/bounce-detect.js +397 -205
  41. package/lib/calendar-event.js +81 -1
  42. package/lib/consts.js +38 -45
  43. package/lib/db.js +14 -6
  44. package/lib/delivery-error.js +6 -0
  45. package/lib/deprecations.js +270 -0
  46. package/lib/email-client/base-client.js +137 -184
  47. package/lib/email-client/fallback-poll.js +62 -0
  48. package/lib/email-client/gmail-client.js +60 -22
  49. package/lib/email-client/imap/adaptive-idle-store.js +73 -0
  50. package/lib/email-client/imap/adaptive-idle.js +278 -0
  51. package/lib/email-client/imap/connection-errors.js +14 -1
  52. package/lib/email-client/imap/idle-settings.js +31 -5
  53. package/lib/email-client/imap/listing-diff.js +37 -0
  54. package/lib/email-client/imap/mailbox.js +372 -242
  55. package/lib/email-client/imap/subconnection.js +8 -30
  56. package/lib/email-client/imap/sync-operations.js +220 -127
  57. package/lib/email-client/imap-client.js +228 -164
  58. package/lib/email-client/message-builder.js +14 -79
  59. package/lib/email-client/notification-handler.js +1 -2
  60. package/lib/email-client/outlook-client.js +372 -338
  61. package/lib/email-client/smtp-pool-manager.js +16 -13
  62. package/lib/email-client/sync-state-fields.js +19 -0
  63. package/lib/encrypt.js +157 -41
  64. package/lib/enum-descriptions.js +3 -1
  65. package/lib/env-setting-overrides.js +288 -0
  66. package/lib/export-worker.js +751 -0
  67. package/lib/export.js +64 -15
  68. package/lib/gateway.js +19 -4
  69. package/lib/get-raw-email.js +25 -107
  70. package/lib/hapi-request-logger.js +107 -0
  71. package/lib/health.js +75 -0
  72. package/lib/imapproxy/imap-core/README.md +6 -5
  73. package/lib/lock-run.js +119 -0
  74. package/lib/logger-consts.js +48 -0
  75. package/lib/logger.js +1 -1
  76. package/lib/lua/z-head-scores.lua +28 -0
  77. package/lib/mcp/tools.js +37 -8
  78. package/lib/network-errors.js +1 -1
  79. package/lib/node-version.js +24 -0
  80. package/lib/notify-attachments.js +36 -0
  81. package/lib/oauth/outlook-mailbox.js +35 -0
  82. package/lib/oauth/state.js +24 -0
  83. package/lib/oauth2-apps.js +631 -656
  84. package/lib/outbox.js +184 -54
  85. package/lib/parse-message.js +3 -3
  86. package/lib/pbkdf2-phc.js +1 -1
  87. package/lib/privileged-settings.js +2 -2
  88. package/lib/queue-browser/definitions.js +11 -0
  89. package/lib/queue-browser/index.js +68 -19
  90. package/lib/queue-job-actions.js +18 -1
  91. package/lib/queue-retention.js +48 -12
  92. package/lib/queue-stats.js +11 -2
  93. package/lib/read-env-value.js +3 -0
  94. package/lib/redis-memory-warnings.js +99 -0
  95. package/lib/redis-reconnect.js +29 -0
  96. package/lib/request-timing.js +23 -0
  97. package/lib/respawn-backoff.js +35 -0
  98. package/lib/rewrite-text-nodes.js +19 -59
  99. package/lib/schemas.js +164 -40
  100. package/lib/settings.js +6 -2
  101. package/lib/smtp-auth.js +19 -1
  102. package/lib/sso.js +1 -1
  103. package/lib/swagger-options.js +1 -1
  104. package/lib/thread-diagnostics.js +63 -0
  105. package/lib/timezones.js +109 -0
  106. package/lib/tls/provision.js +6 -3
  107. package/lib/token-audit-log.js +19 -20
  108. package/lib/token-permission-view.js +7 -6
  109. package/lib/tools.js +48 -51
  110. package/lib/totp.js +2 -5
  111. package/lib/translations.js +1 -2
  112. package/lib/ui-routes/account-routes.js +475 -454
  113. package/lib/ui-routes/account-setup.js +99 -0
  114. package/lib/ui-routes/admin-config-routes.js +152 -100
  115. package/lib/ui-routes/admin-entities-routes.js +93 -21
  116. package/lib/ui-routes/auth-routes.js +90 -38
  117. package/lib/ui-routes/imap-idle-field.js +1 -1
  118. package/lib/ui-routes/internals-routes.js +5 -0
  119. package/lib/ui-routes/oauth-config-routes.js +124 -82
  120. package/lib/ui-routes/outlook-subscription-view.js +1 -1
  121. package/lib/ui-routes/overridable-fields.js +84 -0
  122. package/lib/ui-routes/queue-routes.js +8 -5
  123. package/lib/ui-routes/route-helpers.js +19 -3
  124. package/lib/ui-routes/settings-page.js +6 -0
  125. package/lib/ui-routes/tls-config-routes.js +58 -15
  126. package/lib/utils/back-off.js +82 -0
  127. package/lib/utils/decode-headers.js +3 -12
  128. package/lib/utils/filter-empty.js +20 -0
  129. package/lib/utils/int-setting.js +48 -0
  130. package/lib/utils/murmurhash3.js +66 -0
  131. package/lib/utils/public-suffix.js +122 -0
  132. package/lib/utils/random-id.js +26 -0
  133. package/lib/utils/tracking-settings.js +35 -0
  134. package/lib/utils/version.js +74 -0
  135. package/lib/web-safe-html.js +18 -105
  136. package/lib/webhook-delivery.js +461 -0
  137. package/lib/webhook-failures.js +132 -0
  138. package/lib/webhook-request.js +29 -1
  139. package/lib/webhook-routing.js +56 -0
  140. package/lib/webhook-test.js +88 -0
  141. package/lib/webhooks.js +93 -45
  142. package/lib/worker-rpc-error.js +2 -1
  143. package/package.json +37 -38
  144. package/sbom.json +7902 -1
  145. package/server.js +784 -518
  146. package/static/js/ace/ace.js +1 -1
  147. package/static/licenses.html +225 -1060
  148. package/translations/messages.pot +62 -63
  149. package/views/config/ai.hbs +1 -1
  150. package/views/config/security.hbs +24 -2
  151. package/views/config/service.hbs +47 -0
  152. package/views/config/webhooks.hbs +36 -0
  153. package/views/internals/index.hbs +8 -0
  154. package/views/partials/queue_retention_note.hbs +12 -8
  155. package/views/partials/ui/env-managed-alert.hbs +16 -7
  156. package/views/partials/webhook_form.hbs +1 -1
  157. package/views/suppression-lists/index.hbs +1 -1
  158. package/workers/api.js +840 -611
  159. package/workers/export.js +17 -632
  160. package/workers/imap.js +13 -0
  161. package/workers/smtp.js +9 -11
  162. package/workers/submit.js +1 -1
  163. package/workers/webhooks.js +18 -448
  164. package/lib/email-client/outlook-fallback-poll.js +0 -30
@@ -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;
@@ -2,9 +2,11 @@
2
2
 
3
3
  const Joi = require('joi');
4
4
  const { webhooks: Webhooks } = require('../webhooks');
5
+ const settings = require('../settings');
6
+ const { sendTestWebhook, testEventBody } = require('../webhook-test');
5
7
  const { failAction } = require('../tools');
6
8
  const { handleError, throwNotFound, maskSecrets, MASK_NOTE } = require('./route-helpers');
7
- const { settingsSchema, apiResponses } = require('../schemas');
9
+ const { settingsSchema, apiResponses, listQuerySchema } = require('../schemas');
8
10
  const { MCP_MAX_PAGE_SIZE } = require('../consts');
9
11
 
10
12
  const webhookErrorFlagSchema = Joi.object({
@@ -19,8 +21,8 @@ const webhookCustomHeadersSchema = settingsSchema.webhooksCustomHeaders
19
21
  .description('Custom HTTP headers added to webhook requests for this route')
20
22
  .label('WebhookRouteCustomHeaders');
21
23
 
22
- async function init(args) {
23
- const { server, CORS_CONFIG } = args;
24
+ function registerListWebhookRoutes(server, args) {
25
+ const { CORS_CONFIG } = args;
24
26
 
25
27
  server.route({
26
28
  method: 'GET',
@@ -28,7 +30,7 @@ async function init(args) {
28
30
 
29
31
  async handler(request) {
30
32
  try {
31
- const listing = await Webhooks.list(request.query.page, request.query.pageSize);
33
+ const listing = await Webhooks.list(request.query.page, request.query.pageSize, request.query.query);
32
34
 
33
35
  // customHeaders and the target URL both carry credentials for the customer's own
34
36
  // receiver, so a reader of this listing could otherwise post forged, correctly
@@ -84,7 +86,8 @@ async function init(args) {
84
86
  .example(0)
85
87
  .description('Page number (zero indexed, so use 0 for first page)')
86
88
  .label('PageNumber'),
87
- pageSize: Joi.number().integer().min(1).max(1000).default(20).example(20).description('How many entries per page').label('PageSize')
89
+ pageSize: Joi.number().integer().min(1).max(1000).default(20).example(20).description('How many entries per page').label('PageSize'),
90
+ query: listQuerySchema('ID, name, description or target URL', 'WebhookRoutesListQuery')
88
91
  }).label('WebhookRoutesListRequest')
89
92
  },
90
93
 
@@ -120,6 +123,10 @@ async function init(args) {
120
123
  }
121
124
  }
122
125
  });
126
+ }
127
+
128
+ function registerGetWebhookRoute(server, args) {
129
+ const { CORS_CONFIG } = args;
123
130
 
124
131
  server.route({
125
132
  method: 'GET',
@@ -147,7 +154,8 @@ async function init(args) {
147
154
  mcp: {
148
155
  name: 'get_webhook_route',
149
156
  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.'
157
+ description:
158
+ 'Get one webhook route: its target URL, whether it is enabled, its custom headers, and the filter and mapping functions that decide which events it forwards and in what shape.'
151
159
  },
152
160
  openapi: {
153
161
  responses: apiResponses('Returns the webhook route, including its filter and transform functions.', 400, 401, 403, 404, 429, 500)
@@ -201,4 +209,122 @@ async function init(args) {
201
209
  });
202
210
  }
203
211
 
212
+ function registerTestWebhook(server, args) {
213
+ const { CORS_CONFIG } = args;
214
+
215
+ server.route({
216
+ method: 'POST',
217
+ path: '/v1/webhooks/test',
218
+
219
+ async handler(request) {
220
+ try {
221
+ const routeId = request.payload && request.payload.webhookRoute;
222
+
223
+ // Only ever a configured target: the global one, or a custom route's. The target
224
+ // URL and its headers are credentials of the receiver, so they are neither taken
225
+ // from the request nor echoed back in the result
226
+ let url, customHeaders;
227
+ if (routeId) {
228
+ const route = await Webhooks.getMeta(routeId);
229
+ if (!route || !route.id) {
230
+ throwNotFound('Requested webhook route was not found');
231
+ }
232
+ url = route.targetUrl;
233
+ customHeaders = route.customHeaders;
234
+ } else {
235
+ const stored = await settings.getMulti('webhooks', 'webhooksCustomHeaders');
236
+ url = stored.webhooks;
237
+ customHeaders = stored.webhooksCustomHeaders;
238
+ }
239
+
240
+ const target = routeId ? 'route' : 'global';
241
+ if (!url) {
242
+ return { success: false, target, error: 'Webhook URL is not set', code: 'NoWebhookTarget' };
243
+ }
244
+
245
+ const result = await sendTestWebhook({
246
+ url,
247
+ customHeaders,
248
+ body: testEventBody(await settings.get('serviceUrl')),
249
+ logger: request.logger
250
+ });
251
+
252
+ return Object.assign({ target }, result);
253
+ } catch (err) {
254
+ handleError(request, err);
255
+ }
256
+ },
257
+
258
+ options: {
259
+ description: 'Send a test webhook',
260
+ notes: 'Posts a `test` event to the global webhook target, or with `webhookRoute` set to the target of that custom route, with the custom headers configured for it and signed like a real delivery, and reports whether the receiver accepted it. The target is never taken from the request.',
261
+ tags: ['api', 'Webhooks'],
262
+
263
+ plugins: {
264
+ openapi: {
265
+ responses: apiResponses(
266
+ 'Returns the result of the test delivery. A failed delivery is reported in the result, not as an error status.',
267
+ 400,
268
+ 401,
269
+ 403,
270
+ 404,
271
+ 429,
272
+ 500
273
+ )
274
+ }
275
+ },
276
+
277
+ auth: {
278
+ strategy: 'api-token',
279
+ mode: 'required'
280
+ },
281
+ cors: CORS_CONFIG,
282
+
283
+ validate: {
284
+ options: {
285
+ stripUnknown: false,
286
+ abortEarly: false,
287
+ convert: true
288
+ },
289
+ failAction,
290
+ payload: Joi.object({
291
+ webhookRoute: Joi.string()
292
+ .max(256)
293
+ .example('AAABgS-UcAYAAAABAA')
294
+ .description('Custom webhook route to test. Omit to test the global webhook target')
295
+ })
296
+ .allow(null)
297
+ .label('TestWebhookRequest')
298
+ },
299
+
300
+ response: {
301
+ schema: Joi.object({
302
+ success: Joi.boolean().example(true).description('Did the receiver accept the test event with a 2xx response'),
303
+ target: Joi.string()
304
+ .valid('global', 'route')
305
+ .example('global')
306
+ .description('Which configured target was tested')
307
+ .label('TestWebhookTarget'),
308
+ duration: Joi.number().integer().example(182).description('How long the delivery took, in milliseconds'),
309
+ error: Joi.string().example('Request failed with status 503').description('Why the delivery failed. Only present if success=false'),
310
+ code: Joi.string().example('ECONNREFUSED').description('Error code. Only present if success=false'),
311
+ statusCode: Joi.number()
312
+ .integer()
313
+ .example(503)
314
+ .description('HTTP status the receiver answered with. Only present if it answered with an error')
315
+ }).label('TestWebhookResponse'),
316
+ failAction: 'log'
317
+ }
318
+ }
319
+ });
320
+ }
321
+
322
+ async function init(args) {
323
+ const { server } = args;
324
+
325
+ registerListWebhookRoutes(server, args);
326
+ registerGetWebhookRoute(server, args);
327
+ registerTestWebhook(server, args);
328
+ }
329
+
204
330
  module.exports = init;