emailengine-app 2.85.0 → 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 (128) hide show
  1. package/.ncurc.js +24 -6
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +74 -0
  4. package/Dockerfile +14 -1
  5. package/ENVIRONMENT.md +139 -0
  6. package/README.md +1 -1
  7. package/config/default.toml +2 -0
  8. package/copy-static-files.sh +4 -2
  9. package/data/google-crawlers.json +1 -1
  10. package/data/public_suffix_list.dat +4 -3
  11. package/lib/account-assignment.js +19 -0
  12. package/lib/account.js +194 -165
  13. package/lib/api-error-codes.js +49 -0
  14. package/lib/api-reference/model.js +6 -1
  15. package/lib/api-routes/account-routes.js +78 -26
  16. package/lib/api-routes/blocklist-routes.js +68 -2
  17. package/lib/api-routes/delivery-test-routes.js +1 -1
  18. package/lib/api-routes/gateway-routes.js +82 -10
  19. package/lib/api-routes/index.js +4 -0
  20. package/lib/api-routes/license-routes.js +2 -2
  21. package/lib/api-routes/mailbox-routes.js +3 -3
  22. package/lib/api-routes/message-routes.js +15 -7
  23. package/lib/api-routes/oauth2-app-routes.js +15 -8
  24. package/lib/api-routes/outbox-routes.js +77 -66
  25. package/lib/api-routes/permission-map.js +55 -6
  26. package/lib/api-routes/scoped-routes.js +74 -0
  27. package/lib/api-routes/settings-routes.js +11 -4
  28. package/lib/api-routes/stats-routes.js +5 -1
  29. package/lib/api-routes/submit-routes.js +4 -3
  30. package/lib/api-routes/template-routes.js +7 -6
  31. package/lib/api-routes/token-routes.js +11 -5
  32. package/lib/api-routes/webhook-delivery-routes.js +262 -0
  33. package/lib/api-routes/webhook-route-routes.js +119 -4
  34. package/lib/calendar-event.js +81 -1
  35. package/lib/consts.js +38 -46
  36. package/lib/db.js +14 -6
  37. package/lib/delivery-error.js +6 -0
  38. package/lib/deprecations.js +270 -0
  39. package/lib/email-client/base-client.js +130 -156
  40. package/lib/email-client/fallback-poll.js +62 -0
  41. package/lib/email-client/gmail-client.js +51 -11
  42. package/lib/email-client/imap/adaptive-idle-store.js +73 -0
  43. package/lib/email-client/imap/adaptive-idle.js +278 -0
  44. package/lib/email-client/imap/connection-errors.js +14 -1
  45. package/lib/email-client/imap/idle-settings.js +31 -5
  46. package/lib/email-client/imap/listing-diff.js +37 -0
  47. package/lib/email-client/imap/mailbox.js +372 -226
  48. package/lib/email-client/imap/subconnection.js +7 -29
  49. package/lib/email-client/imap/sync-operations.js +220 -127
  50. package/lib/email-client/imap-client.js +227 -163
  51. package/lib/email-client/message-builder.js +14 -79
  52. package/lib/email-client/outlook-client.js +372 -338
  53. package/lib/email-client/smtp-pool-manager.js +16 -13
  54. package/lib/email-client/sync-state-fields.js +19 -0
  55. package/lib/encrypt.js +157 -41
  56. package/lib/enum-descriptions.js +3 -1
  57. package/lib/env-setting-overrides.js +288 -0
  58. package/lib/export-worker.js +751 -0
  59. package/lib/export.js +64 -15
  60. package/lib/gateway.js +17 -1
  61. package/lib/get-raw-email.js +25 -107
  62. package/lib/health.js +75 -0
  63. package/lib/lock-run.js +119 -0
  64. package/lib/logger-consts.js +48 -0
  65. package/lib/logger.js +1 -1
  66. package/lib/lua/z-head-scores.lua +28 -0
  67. package/lib/network-errors.js +1 -1
  68. package/lib/node-version.js +24 -0
  69. package/lib/notify-attachments.js +20 -1
  70. package/lib/oauth2-apps.js +630 -655
  71. package/lib/outbox.js +184 -54
  72. package/lib/parse-message.js +3 -3
  73. package/lib/privileged-settings.js +2 -2
  74. package/lib/queue-browser/definitions.js +11 -0
  75. package/lib/queue-browser/index.js +68 -19
  76. package/lib/queue-job-actions.js +18 -1
  77. package/lib/queue-retention.js +48 -12
  78. package/lib/queue-stats.js +11 -2
  79. package/lib/read-env-value.js +3 -0
  80. package/lib/redis-memory-warnings.js +99 -0
  81. package/lib/redis-reconnect.js +29 -0
  82. package/lib/request-timing.js +23 -0
  83. package/lib/respawn-backoff.js +35 -0
  84. package/lib/rewrite-text-nodes.js +19 -59
  85. package/lib/schemas.js +163 -39
  86. package/lib/settings.js +6 -2
  87. package/lib/smtp-auth.js +19 -1
  88. package/lib/thread-diagnostics.js +18 -1
  89. package/lib/tls/provision.js +6 -3
  90. package/lib/token-audit-log.js +19 -20
  91. package/lib/token-permission-view.js +4 -3
  92. package/lib/tools.js +8 -41
  93. package/lib/ui-routes/admin-config-routes.js +64 -90
  94. package/lib/ui-routes/admin-entities-routes.js +2 -14
  95. package/lib/ui-routes/imap-idle-field.js +1 -1
  96. package/lib/ui-routes/outlook-subscription-view.js +1 -1
  97. package/lib/ui-routes/overridable-fields.js +84 -0
  98. package/lib/ui-routes/queue-routes.js +8 -5
  99. package/lib/ui-routes/settings-page.js +6 -0
  100. package/lib/utils/decode-headers.js +3 -12
  101. package/lib/utils/filter-empty.js +20 -0
  102. package/lib/utils/int-setting.js +48 -0
  103. package/lib/utils/tracking-settings.js +35 -0
  104. package/lib/web-safe-html.js +18 -105
  105. package/lib/webhook-delivery.js +461 -0
  106. package/lib/webhook-failures.js +132 -0
  107. package/lib/webhook-request.js +29 -1
  108. package/lib/webhook-routing.js +30 -1
  109. package/lib/webhook-test.js +88 -0
  110. package/lib/webhooks.js +54 -41
  111. package/lib/worker-rpc-error.js +2 -1
  112. package/package.json +21 -20
  113. package/sbom.json +304 -382
  114. package/server.js +149 -76
  115. package/static/js/ace/ace.js +1 -1
  116. package/static/licenses.html +21 -31
  117. package/translations/messages.pot +26 -26
  118. package/views/config/security.hbs +22 -0
  119. package/views/config/service.hbs +44 -0
  120. package/views/config/webhooks.hbs +36 -0
  121. package/views/partials/queue_retention_note.hbs +12 -8
  122. package/views/partials/ui/env-managed-alert.hbs +16 -7
  123. package/workers/api.js +102 -28
  124. package/workers/export.js +16 -631
  125. package/workers/imap.js +13 -0
  126. package/workers/smtp.js +9 -11
  127. package/workers/webhooks.js +18 -432
  128. package/lib/email-client/outlook-fallback-poll.js +0 -30
@@ -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;
@@ -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({
@@ -28,7 +30,7 @@ function registerListWebhookRoutes(server, 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 @@ function registerListWebhookRoutes(server, 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
 
@@ -151,7 +154,8 @@ function registerGetWebhookRoute(server, args) {
151
154
  mcp: {
152
155
  name: 'get_webhook_route',
153
156
  title: 'Get webhook route',
154
- 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.'
155
159
  },
156
160
  openapi: {
157
161
  responses: apiResponses('Returns the webhook route, including its filter and transform functions.', 400, 401, 403, 404, 429, 500)
@@ -205,11 +209,122 @@ function registerGetWebhookRoute(server, args) {
205
209
  });
206
210
  }
207
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
+
208
322
  async function init(args) {
209
323
  const { server } = args;
210
324
 
211
325
  registerListWebhookRoutes(server, args);
212
326
  registerGetWebhookRoute(server, args);
327
+ registerTestWebhook(server, args);
213
328
  }
214
329
 
215
330
  module.exports = init;
@@ -9,6 +9,7 @@
9
9
  // ISO timestamps are the instant the invite means wherever EmailEngine happens to run.
10
10
 
11
11
  const ical = require('ical.js');
12
+ const { filterEmptyObjectValues } = require('./utils/filter-empty');
12
13
 
13
14
  const CALENDAR_CONTENT_TYPES = ['text/calendar', 'application/ics'];
14
15
 
@@ -75,4 +76,83 @@ function parseCalendarEvent(content) {
75
76
  };
76
77
  }
77
78
 
78
- module.exports = { CALENDAR_CONTENT_TYPES, sortCalendarAttachments, parseCalendarEvent };
79
+ /**
80
+ * The calendar events of a new message, for the messageNew webhook (`notifyCalendarEvents`).
81
+ * Shared by the IMAP mailbox and the Gmail API and Graph clients, which differ only in how an
82
+ * attachment's content is loaded. text/calendar is read before application/ics, an event seen in
83
+ * both is listed once, and an event without a file name gets invite.ics or event.ics
84
+ * @param {Object[]} attachments - The message's attachments
85
+ * @param {Function} load - async (attachment) => void, sets attachment.content (base64) when it can
86
+ * @param {Object} logger
87
+ * @returns {Promise<Object[]|undefined>} The events, or undefined when there are none
88
+ */
89
+ async function collectCalendarEvents(attachments, load, logger) {
90
+ const events = new Map();
91
+
92
+ for (const attachment of [...(attachments || [])].sort(sortCalendarAttachments)) {
93
+ if (!CALENDAR_CONTENT_TYPES.includes(attachment.contentType)) {
94
+ continue;
95
+ }
96
+ if (!attachment.content) {
97
+ await load(attachment);
98
+ }
99
+ if (!attachment.content) {
100
+ continue;
101
+ }
102
+
103
+ const contentBuf = Buffer.from(attachment.content, 'base64');
104
+ let event;
105
+ try {
106
+ event = parseCalendarEvent(contentBuf);
107
+ } catch (err) {
108
+ logger.warn({ msg: 'Failed to parse calendar event', attachment: Object.assign({}, attachment, { content: `${contentBuf.length} bytes` }), err });
109
+ continue;
110
+ }
111
+ if (!event) {
112
+ continue;
113
+ }
114
+
115
+ if (events.has(event.eventId)) {
116
+ const existing = events.get(event.eventId);
117
+ if (attachment.filename && !existing.filename) {
118
+ existing.filename = attachment.filename;
119
+ }
120
+ continue;
121
+ }
122
+
123
+ events.set(
124
+ event.eventId,
125
+ filterEmptyObjectValues({
126
+ eventId: event.eventId,
127
+ attachment: attachment.id,
128
+ method: attachment.method || event.method || null,
129
+
130
+ summary: event.summary,
131
+ description: event.description,
132
+ timezone: event.timezone,
133
+ startDate: event.startDate,
134
+ endDate: event.endDate,
135
+ organizer: event.organizer,
136
+
137
+ filename: attachment.filename,
138
+ contentType: attachment.contentType,
139
+ encoding: 'base64',
140
+ content: attachment.content
141
+ })
142
+ );
143
+ }
144
+
145
+ if (!events.size) {
146
+ return undefined;
147
+ }
148
+
149
+ return Array.from(events.values()).map(calendarEvent => {
150
+ if (!calendarEvent.filename) {
151
+ const method = calendarEvent.method && calendarEvent.method.toUpperCase();
152
+ calendarEvent.filename = method === 'CANCEL' || method === 'REQUEST' ? 'invite.ics' : 'event.ics';
153
+ }
154
+ return calendarEvent;
155
+ });
156
+ }
157
+
158
+ module.exports = { CALENDAR_CONTENT_TYPES, sortCalendarAttachments, parseCalendarEvent, collectCalendarEvents };