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,461 @@
1
+ 'use strict';
2
+
3
+ // The notify queue's job processor: decides whether and where a queued webhook event is delivered,
4
+ // sends it, and records the outcome. It used to be written inline in workers/webhooks.js, which a
5
+ // test cannot import (requiring it starts a BullMQ worker and talks to the parent thread), so its
6
+ // decisions were only tested through the helpers it calls. Everything with a side effect is passed
7
+ // in, see createWebhookProcessor().
8
+
9
+ const { UnrecoverableError, DelayedError } = require('bullmq');
10
+
11
+ const { redactUrlCredentials, splitUrlCredentials } = require('./tools');
12
+ const { sendWebhookRequest, isUnrecoverableWebhookError, baseDeliveryHeaders, signDelivery } = require('./webhook-request');
13
+ const { willBeFinalAttempt } = require('./delivery-error');
14
+ const { penaltyKey, penaltyFor } = require('./webhook-penalty');
15
+ const {
16
+ resolveTargetUrl,
17
+ isDeliverableRoute,
18
+ eventAllowed,
19
+ defaultRouteTakes,
20
+ headerLevels,
21
+ deliveryCustomHeaders,
22
+ isRouteMappingMissing
23
+ } = require('./webhook-routing');
24
+ const { REDIS_PREFIX, ACCOUNT_DELETED_NOTIFY, DEFAULT_WEBHOOK_REQUEST_TIMEOUT } = require('./consts');
25
+
26
+ // The payload fields of `data` that are logged as they are; anything else only marks it partial
27
+ const LOGGED_DATA_KEYS = new Set(['id', 'uid', 'path', 'messageId']);
28
+
29
+ const getAccountKey = account => `${REDIS_PREFIX}iad:${account}`;
30
+
31
+ /**
32
+ * Log context shared by every line about one job
33
+ * @param {Object} job - BullMQ job
34
+ * @returns {Object} Fields to spread into a log entry
35
+ */
36
+ const jobLogFields = job => ({ action: 'webhook', queue: job.queue.name, job: job.id, event: job.name, account: job.data.account });
37
+
38
+ /**
39
+ * The job payload reduced to what is safe and useful to log: everything except `data`, of which
40
+ * only the identifying fields are kept
41
+ * @param {Object} payload - Job data
42
+ * @returns {Object} Loggable copy
43
+ */
44
+ function filterLogData(payload) {
45
+ let filteredData = {};
46
+ for (let key of Object.keys(payload)) {
47
+ if (key !== 'data') {
48
+ filteredData[key] = payload[key];
49
+ continue;
50
+ }
51
+
52
+ let filteredSubData = {};
53
+ let isPartial = false;
54
+ for (let dataKey of Object.keys(payload.data || {})) {
55
+ if (LOGGED_DATA_KEYS.has(dataKey)) {
56
+ filteredSubData[dataKey] = payload.data[dataKey];
57
+ } else {
58
+ isPartial = true;
59
+ }
60
+ }
61
+ if (isPartial) {
62
+ if (Object.keys(filteredSubData).length) {
63
+ filteredSubData.partial = true;
64
+ } else {
65
+ filteredSubData = true;
66
+ }
67
+ }
68
+ filteredData[key] = filteredSubData;
69
+ }
70
+ return filteredData;
71
+ }
72
+
73
+ /**
74
+ * Loads the custom route a job was queued for. Removes `_route` from the payload, so it is never
75
+ * delivered
76
+ * @returns {Promise<Object>} `{ skip }` when nothing is to be sent, otherwise `{ customRoute, customMapping }`
77
+ */
78
+ async function loadCustomRoute(job, deps) {
79
+ if (!job.data._route || !job.data._route.id) {
80
+ return {};
81
+ }
82
+
83
+ let customRoute = await deps.webhooks.getMeta(job.data._route.id);
84
+ let customMapping = job.data._route.mapping;
85
+ let mappingMissing = isRouteMappingMissing(job.data._route);
86
+ delete job.data._route;
87
+
88
+ if (!isDeliverableRoute(customRoute)) {
89
+ return { skip: true };
90
+ }
91
+
92
+ if (mappingMissing) {
93
+ deps.logger.warn({
94
+ msg: 'Custom webhook route has no mapped payload, not sending',
95
+ ...jobLogFields(job),
96
+ code: 'missing_mapping',
97
+ route: customRoute.id
98
+ });
99
+ return { skip: true };
100
+ }
101
+
102
+ return { customRoute, customMapping };
103
+ }
104
+
105
+ /**
106
+ * Parses the account's custom header list. A value that does not parse is ignored, as before
107
+ * @returns {Object[]|undefined} Header entries
108
+ */
109
+ function parseAccountHeaders(json, job, logger) {
110
+ if (!json) {
111
+ return undefined;
112
+ }
113
+ try {
114
+ return JSON.parse(json);
115
+ } catch (err) {
116
+ // do not log the header values, they may carry authentication secrets
117
+ logger.debug({ msg: 'Failed to parse custom webhook headers', ...jobLogFields(job), jsonLength: json.length, err });
118
+ return undefined;
119
+ }
120
+ }
121
+
122
+ /**
123
+ * Delays the job while its target is penalised; see lib/webhook-penalty.js. The attempt count is
124
+ * not spent by the wait
125
+ * @returns {Promise<string|null>} The target's penalty key, for recordFailure()
126
+ * @throws {DelayedError} When the job was moved to the delayed set
127
+ */
128
+ async function waitOutPenalty(job, token, webhooks, deps) {
129
+ const targetPenaltyKey = penaltyKey(webhooks);
130
+ if (!targetPenaltyKey) {
131
+ return null;
132
+ }
133
+ let remaining = await deps.redis.pttl(targetPenaltyKey);
134
+ if (remaining > 0) {
135
+ deps.logger.debug({
136
+ msg: 'Webhook target is penalised, delaying delivery',
137
+ ...jobLogFields(job),
138
+ code: 'target_penalised',
139
+ webhooks: redactUrlCredentials(webhooks),
140
+ delay: remaining
141
+ });
142
+ await job.moveToDelayed(Date.now() + remaining, token);
143
+ throw new DelayedError();
144
+ }
145
+ return targetPenaltyKey;
146
+ }
147
+
148
+ /**
149
+ * Decides whether a job is delivered and, if it is, where and with which header lists. Every
150
+ * check that can skip a job runs here, in the order the inline processor ran them
151
+ * @returns {Promise<Object|null>} Delivery plan, or null when the job is completed without sending
152
+ */
153
+ async function planDelivery(job, token, deps) {
154
+ const { redis, settings, logger, openAccountField } = deps;
155
+ let accountKey = getAccountKey(job.data.account);
156
+
157
+ // Keep the route id reachable for the completed/failed event handlers, which see this same
158
+ // job instance after _route has been deleted from the payload. Stashed before the early
159
+ // returns below so a job that never reaches delivery still reports which route queued it.
160
+ if (job.data._route && job.data._route.id) {
161
+ job.__routeId = job.data._route.id;
162
+ }
163
+
164
+ // One round trip for the existence check and the two account fields a delivery may need.
165
+ // The fields are opened where they are used, below.
166
+ let [accountExists, storedWebhooks, storedCustomHeaders] = await redis.hmget(accountKey, 'account', 'webhooks', 'webhooksCustomHeaders');
167
+ if (!accountExists && job.name !== ACCOUNT_DELETED_NOTIFY) {
168
+ logger.debug({ msg: 'Account not found', ...jobLogFields(job), code: 'account_not_found' });
169
+ return null;
170
+ }
171
+
172
+ if (!(await settings.get('webhooksEnabled'))) {
173
+ logger.debug({ msg: 'Webhooks are disabled', ...jobLogFields(job), code: 'webhooks_disabled' });
174
+ return null;
175
+ }
176
+
177
+ let { skip, customRoute, customMapping } = await loadCustomRoute(job, deps);
178
+ if (skip) {
179
+ return null;
180
+ }
181
+
182
+ let accountWebhooks = await openAccountField('webhooks', storedWebhooks, job.data.account);
183
+
184
+ // the global setting is only fetched when neither a custom route nor the account override decides the target
185
+ let target = resolveTargetUrl(customRoute && customRoute.targetUrl, accountWebhooks, null);
186
+ if (!target.url) {
187
+ target = resolveTargetUrl(null, null, await settings.get('webhooks'));
188
+ }
189
+ let webhooks = target.url;
190
+ if (!webhooks) {
191
+ // A skipped delivery still reports the job as completed, so without this line a
192
+ // missing target is indistinguishable from a successful delivery - it reads as the
193
+ // receiver being slow rather than as nothing having been sent
194
+ logger.debug({ msg: 'Webhook URL is not set', ...jobLogFields(job), code: 'no_target_url' });
195
+ return null;
196
+ }
197
+
198
+ const targetPenaltyKey = await waitOutPenalty(job, token, webhooks, deps);
199
+
200
+ // Only the header lists that travel to this target are loaded; lib/webhook-routing.js
201
+ // holds the rule and the reasons
202
+ let levels = headerLevels(target.source);
203
+ let accountHeadersJson = levels.includes('account') ? await openAccountField('webhooksCustomHeaders', storedCustomHeaders, job.data.account) : null;
204
+ let accountCustomHeaders = parseAccountHeaders(accountHeadersJson, job, logger);
205
+
206
+ if (!customRoute) {
207
+ // custom routes have their own mappings; the default route follows webhookEvents and
208
+ // inboxNewOnly, by the same rule pushToQueue() applied before queueing
209
+ let { webhookEvents, inboxNewOnly } = await settings.getMulti('webhookEvents', 'inboxNewOnly');
210
+ if (!defaultRouteTakes(job.name, job.data, { webhookEvents, inboxNewOnly })) {
211
+ logger.trace({
212
+ msg: 'Webhook event not taken by the default route',
213
+ ...jobLogFields(job),
214
+ code: eventAllowed(webhookEvents, job.name) ? 'inbox_new_only' : 'event_not_whitelisted',
215
+ webhookEvents
216
+ });
217
+ return null;
218
+ }
219
+ }
220
+
221
+ return {
222
+ accountKey,
223
+ customRoute,
224
+ customMapping,
225
+ accountWebhooks,
226
+ target,
227
+ // never log the raw target URL, it may embed basic auth credentials
228
+ redactedWebhooks: redactUrlCredentials(webhooks),
229
+ accountCustomHeaders,
230
+ targetPenaltyKey
231
+ };
232
+ }
233
+
234
+ /**
235
+ * Builds the request: the body, and every header that goes with it, the signature last
236
+ * @returns {Promise<Object>} `{ url, headers, body }`
237
+ */
238
+ async function buildRequest(job, plan, deps) {
239
+ let { url: parsed, authorization } = splitUrlCredentials(plan.target.url);
240
+ let headers = Object.assign(baseDeliveryHeaders(authorization), {
241
+ 'X-EE-Wh-Id': (job.id || '').toString(),
242
+ 'X-EE-Wh-Attempts-Made': (job.attemptsMade || 0).toString(),
243
+ 'X-EE-Wh-Queued-Time': Math.round(Math.max(0, (Date.now() - job.timestamp) / 1000)) + 's'
244
+ });
245
+
246
+ if (plan.customRoute) {
247
+ headers['X-EE-Wh-Custom-Route'] = plan.customRoute.id;
248
+ }
249
+ Object.assign(
250
+ headers,
251
+ deliveryCustomHeaders(plan.target.source, {
252
+ route: plan.customRoute && plan.customRoute.customHeaders,
253
+ global: headerLevels(plan.target.source).includes('global') ? await deps.settings.get('webhooksCustomHeaders') : null,
254
+ account: plan.accountCustomHeaders
255
+ })
256
+ );
257
+
258
+ let webhookPayload = plan.customMapping || job.data;
259
+ if (webhookPayload.eventId) {
260
+ headers['X-EE-Wh-Event-Id'] = webhookPayload.eventId;
261
+ webhookPayload.eventId = undefined; // not included in JSON
262
+ }
263
+ let body = Buffer.from(JSON.stringify(webhookPayload));
264
+
265
+ // Explicitly set Content-Length to prevent undici mismatch errors
266
+ headers['Content-Length'] = body.length.toString();
267
+
268
+ signDelivery(headers, body, await deps.getServiceSecret());
269
+
270
+ return { url: parsed.toString(), headers, body };
271
+ }
272
+
273
+ /**
274
+ * Writes the error flag of whichever level decided the target: the custom route, the account
275
+ * override or the global setting. An empty flag clears it, by removing the field: every successful
276
+ * delivery clears, and a removal of a field that is not there changes nothing, so Redis neither
277
+ * writes nor replicates it. Never throws, a missed flag write must not change the outcome of the
278
+ * delivery
279
+ */
280
+ async function writeErrorFlag(plan, flag, deps) {
281
+ try {
282
+ if (plan.customRoute || plan.accountWebhooks) {
283
+ const [key, field] = plan.customRoute
284
+ ? [deps.webhooks.getWebhooksContentKey(), `${plan.customRoute.id}:webhookErrorFlag`]
285
+ : [plan.accountKey, 'webhookErrorFlag'];
286
+ await (flag ? deps.redis.hset(key, field, JSON.stringify(flag)) : deps.redis.hdel(key, field));
287
+ } else if (flag) {
288
+ await deps.settings.set('webhookErrorFlag', flag);
289
+ } else {
290
+ await deps.settings.clear('webhookErrorFlag');
291
+ }
292
+ } catch (err) {
293
+ // ignore
294
+ }
295
+ }
296
+
297
+ /**
298
+ * Records a failed attempt everywhere it is read back: the target penalty, the job's progress
299
+ * field (for the queue browser), the log, the error flag and the metrics
300
+ */
301
+ async function recordFailure(job, plan, request, err, duration, deps) {
302
+ const { redis, logger } = deps;
303
+
304
+ // egress and redirect failures are thrown as UnrecoverableError, so they are final as well
305
+ let isFinalAttempt = willBeFinalAttempt(job) || isUnrecoverableWebhookError(err);
306
+
307
+ // A target that held the attempt until it timed out is penalised so the next deliveries to
308
+ // it do not each cost the same wait
309
+ let penalty = penaltyFor(err, deps.timeout || DEFAULT_WEBHOOK_REQUEST_TIMEOUT);
310
+ if (penalty && plan.targetPenaltyKey) {
311
+ try {
312
+ await redis.set(plan.targetPenaltyKey, '1', 'PX', penalty);
313
+ } catch (penaltyErr) {
314
+ // a missed penalty costs the queue one more timeout, nothing else
315
+ }
316
+ }
317
+
318
+ // BullMQ keeps only the message of a failure on the job. The code and the HTTP status
319
+ // are what explain it, so they are recorded the way the submit worker records its own
320
+ // delivery errors, for the queue browser to read back
321
+ try {
322
+ await job.updateProgress({ status: 'error', error: { message: err.message, code: err.code, statusCode: err.statusCode }, duration });
323
+ } catch (progressErr) {
324
+ // ignore
325
+ }
326
+
327
+ logger[isFinalAttempt ? 'error' : 'warn']({
328
+ msg: 'Failed posting webhook',
329
+ ...jobLogFields(job),
330
+ code: 'result_fail',
331
+ webhooks: plan.redactedWebhooks,
332
+ requestBodySize: request.body.length,
333
+ accountWebhooks: !!plan.accountWebhooks,
334
+ route: plan.customRoute && plan.customRoute.id,
335
+ err
336
+ });
337
+
338
+ await writeErrorFlag(
339
+ plan,
340
+ {
341
+ event: job.name,
342
+ message: err.message,
343
+ time: Date.now(),
344
+ // stored without credentials: the flag is read back through the webhook route
345
+ // listing, the account page and the settings API. A route's own URL is the target
346
+ url: plan.redactedWebhooks,
347
+ code: err.code,
348
+ statusCode: err.statusCode
349
+ },
350
+ deps
351
+ );
352
+
353
+ deps.metrics('webhooks', 'inc', { event: job.name, status: 'fail' });
354
+ }
355
+
356
+ /**
357
+ * Sends a planned delivery and records the outcome
358
+ * @returns {Promise<Object>} The job's return value, stored by BullMQ
359
+ */
360
+ async function deliver(job, plan, deps) {
361
+ const { logger } = deps;
362
+
363
+ // the redacted target stays reachable for the failed event handler
364
+ job.__redactedTargetUrl = plan.redactedWebhooks;
365
+
366
+ logger.trace({
367
+ msg: 'Processing webhook',
368
+ ...jobLogFields(job),
369
+ code: 'processing',
370
+ webhooks: plan.redactedWebhooks,
371
+ accountWebhooks: !!plan.accountWebhooks,
372
+ data: filterLogData(job.data),
373
+ route: plan.customRoute && plan.customRoute.id
374
+ });
375
+
376
+ let request = await buildRequest(job, plan, deps);
377
+
378
+ let start = Date.now();
379
+ let duration;
380
+ try {
381
+ let status;
382
+ try {
383
+ status = await sendWebhookRequest(deps.fetch, request.url, {
384
+ method: 'post',
385
+ body: request.body,
386
+ headers: request.headers,
387
+ dispatcher: deps.dispatcher,
388
+ timeout: deps.timeout,
389
+ validateTarget: deps.validateTarget
390
+ });
391
+ duration = Date.now() - start;
392
+ } catch (err) {
393
+ duration = Date.now() - start;
394
+ throw err.cause || err;
395
+ }
396
+
397
+ logger.trace({
398
+ msg: 'Webhook posted',
399
+ ...jobLogFields(job),
400
+ code: 'result_success',
401
+ webhooks: plan.redactedWebhooks,
402
+ requestBodySize: request.body.length,
403
+ accountWebhooks: !!plan.accountWebhooks,
404
+ status,
405
+ route: plan.customRoute && plan.customRoute.id
406
+ });
407
+
408
+ await writeErrorFlag(plan, null, deps);
409
+ deps.metrics('webhooks', 'inc', { event: job.name, status: 'success' });
410
+
411
+ // Stored by BullMQ as the job's return value in the same write that completes it, so
412
+ // a retained completed job shows what the endpoint answered and how long it took
413
+ return { status: 'delivered', statusCode: status, duration };
414
+ } catch (err) {
415
+ await recordFailure(job, plan, request, err, duration, deps);
416
+
417
+ // Spending the remaining attempts on an unrecoverable failure only delays the operator
418
+ // seeing the real reason in the error flag. Fail the job now and keep the message.
419
+ if (isUnrecoverableWebhookError(err)) {
420
+ // UnrecoverableError copies the message only, and the failed-event handler logs the
421
+ // error it is given, so carry the code over or that log loses the actual reason
422
+ let unrecoverableErr = new UnrecoverableError(err.message);
423
+ unrecoverableErr.code = err.code;
424
+ throw unrecoverableErr;
425
+ }
426
+
427
+ throw err;
428
+ } finally {
429
+ if (duration) {
430
+ deps.metrics('webhookReq', 'observe', duration);
431
+ }
432
+ }
433
+ }
434
+
435
+ /**
436
+ * Creates the notify queue's job processor
437
+ * @param {Object} deps
438
+ * @param {Object} deps.redis - ioredis client (hmget, pttl, set, hset)
439
+ * @param {Object} deps.settings - lib/settings (get, getMulti, set, clear)
440
+ * @param {Object} deps.webhooks - lib/webhooks instance (getMeta, getWebhooksContentKey)
441
+ * @param {Object} deps.logger - pino logger
442
+ * @param {Function} deps.metrics - (key, method, ...args) metrics reporter
443
+ * @param {Function} deps.openAccountField - (field, value, account) decrypts an account field
444
+ * @param {Function} deps.getServiceSecret - Resolves the HMAC signing secret
445
+ * @param {Function} deps.fetch - fetch implementation
446
+ * @param {Object} [deps.dispatcher] - undici dispatcher
447
+ * @param {number|false} [deps.timeout] - Attempt timeout in ms, false for the default
448
+ * @param {Function} [deps.validateTarget] - Egress policy check
449
+ * @returns {Function} async (job, token) => result
450
+ */
451
+ function createWebhookProcessor(deps) {
452
+ return async function processWebhookJob(job, token) {
453
+ let plan = await planDelivery(job, token, deps);
454
+ if (!plan) {
455
+ return;
456
+ }
457
+ return await deliver(job, plan, deps);
458
+ };
459
+ }
460
+
461
+ module.exports = { createWebhookProcessor, filterLogData };
@@ -0,0 +1,132 @@
1
+ 'use strict';
2
+
3
+ // The webhook deliveries that failed for good, for the REST API: list them, put one back into the
4
+ // queue, or remove it. The admin queue browser (lib/queue-browser) offers the same over the whole
5
+ // notify queue; this is the failed set only, in the shape an integrator replaying the events a
6
+ // receiver outage cost it needs, and optionally held to one account so a token bound to that
7
+ // account reaches only its own deliveries.
8
+ //
9
+ // A listing carries what a delivery was about (event, account, folder, message, the route that
10
+ // sent it and why it failed), never the event payload itself, which can hold up to notifyTextSize
11
+ // of message text.
12
+
13
+ const { notifyQueue } = require('./db');
14
+ const { QUEUES_BY_NAME, listJobs } = require('./queue-browser');
15
+ const { retryFailedJob, assertJobState, getAccountJob } = require('./queue-job-actions');
16
+ const { statusError } = require('./utils/status-error');
17
+
18
+ const NOTIFY_QUEUE = QUEUES_BY_NAME.get('notify');
19
+
20
+ /**
21
+ * The API form of a failed delivery, from the queue browser's formatted entry
22
+ * @param {Object} entry - Entry from listJobs()
23
+ * @returns {Object}
24
+ */
25
+ function formatFailedDelivery(entry) {
26
+ return {
27
+ id: entry.id,
28
+ event: entry.event,
29
+ eventId: entry.eventId,
30
+ account: entry.account,
31
+ path: entry.path,
32
+ messageId: entry.messageId,
33
+ route: entry.routeId ? { id: entry.routeId, name: entry.routeName || null } : null,
34
+ created: entry.created,
35
+ failed: entry.finishedOn,
36
+ attemptsMade: entry.attemptsMade,
37
+ attempts: entry.attempts,
38
+ error: entry.failure
39
+ ? {
40
+ message: entry.failure.reason,
41
+ code: entry.failure.code,
42
+ statusCode: entry.failure.statusCode,
43
+ permanent: entry.failure.permanent
44
+ }
45
+ : null
46
+ };
47
+ }
48
+
49
+ /**
50
+ * One page of failed deliveries, most recent first. With an account the failed set is scanned from
51
+ * its head for that account's deliveries, as far as the queue browser scans a filtered listing, and
52
+ * the result says when the scan stopped short of the end.
53
+ *
54
+ * @param {Object} options
55
+ * @param {string} [options.account] - Only deliveries of this account
56
+ * @param {number} [options.page] - Zero-based page
57
+ * @param {number} [options.pageSize] - Entries per page
58
+ * @param {Object} options.logger - Logger instance
59
+ * @returns {Promise<Object>} `{ total, page, pages, scanLimited, deliveries }`
60
+ */
61
+ async function list(options) {
62
+ const result = await listJobs({
63
+ queue: NOTIFY_QUEUE,
64
+ state: 'failed',
65
+ page: options.page,
66
+ pageSize: options.pageSize,
67
+ account: options.account,
68
+ logger: options.logger
69
+ });
70
+
71
+ return {
72
+ total: result.total,
73
+ page: result.page,
74
+ pages: result.total ? result.pages : 0,
75
+ scanLimited: result.scanLimited,
76
+ deliveries: result.entries.map(formatFailedDelivery)
77
+ };
78
+ }
79
+
80
+ /**
81
+ * Puts a failed delivery back into the queue with a fresh set of attempts.
82
+ *
83
+ * @param {Object} options
84
+ * @param {string} options.id - Job ID
85
+ * @param {string} [options.account] - Account the delivery has to belong to
86
+ * @param {Object} options.logger - Logger instance
87
+ * @returns {Promise<Object|false>} `{ retried: true, id }`, or false when there is no such delivery
88
+ * @throws {Error} 409 NotFailed when the delivery is not in the failed state
89
+ */
90
+ async function retry(options) {
91
+ const job = await getAccountJob(notifyQueue, options.id, options.account);
92
+ if (!job) {
93
+ return false;
94
+ }
95
+
96
+ await assertJobState(job, 'failed', NOTIFY_QUEUE.noun, 'retried');
97
+ await retryFailedJob(job, NOTIFY_QUEUE.noun);
98
+
99
+ options.logger.info({ msg: 'Retrying failed webhook delivery', job: job.id, event: job.name, account: job.data && job.data.account });
100
+ return { retried: true, id: String(job.id) };
101
+ }
102
+
103
+ /**
104
+ * Removes a failed delivery from the queue.
105
+ *
106
+ * @param {Object} options
107
+ * @param {string} options.id - Job ID
108
+ * @param {string} [options.account] - Account the delivery has to belong to
109
+ * @param {Object} options.logger - Logger instance
110
+ * @returns {Promise<Object|false>} `{ deleted: true, id }`, or false when there is no such delivery
111
+ * @throws {Error} 409 NotFailed when the delivery is not in the failed state
112
+ */
113
+ async function del(options) {
114
+ const job = await getAccountJob(notifyQueue, options.id, options.account);
115
+ if (!job) {
116
+ return false;
117
+ }
118
+
119
+ await assertJobState(job, 'failed', NOTIFY_QUEUE.noun, 'removed');
120
+
121
+ try {
122
+ await job.remove();
123
+ } catch (err) {
124
+ // retried and picked up by a worker between the check and the removal
125
+ throw statusError('The webhook delivery is being processed and cannot be removed', 'Locked', 409);
126
+ }
127
+
128
+ options.logger.info({ msg: 'Removed failed webhook delivery', job: job.id, event: job.name, account: job.data && job.data.account });
129
+ return { deleted: true, id: String(job.id) };
130
+ }
131
+
132
+ module.exports = { list, retry, del, formatFailedDelivery };
@@ -1,8 +1,36 @@
1
1
  'use strict';
2
2
 
3
+ const { createHmac } = require('crypto');
4
+ const packageData = require('../package.json');
3
5
  const { DEFAULT_WEBHOOK_REQUEST_TIMEOUT } = require('./consts');
4
6
  const { readBodyCapped } = require('./egress-fetch');
5
7
 
8
+ /**
9
+ * The headers every webhook request starts from, a real delivery and a test probe alike
10
+ * @param {string} [authorization] - Basic auth taken from the target URL
11
+ * @returns {Object}
12
+ */
13
+ function baseDeliveryHeaders(authorization) {
14
+ const headers = {
15
+ 'Content-Type': 'application/json',
16
+ 'User-Agent': `${packageData.name}/${packageData.version} (+${packageData.homepage})`
17
+ };
18
+ if (authorization) {
19
+ headers.Authorization = authorization;
20
+ }
21
+ return headers;
22
+ }
23
+
24
+ /**
25
+ * Signs a request body into X-EE-Wh-Signature, the header a receiver verifies with the service secret
26
+ * @param {Object} headers - Request headers, modified in place
27
+ * @param {Buffer|string} body - The exact bytes that are sent
28
+ * @param {string} secret - The service secret
29
+ */
30
+ function signDelivery(headers, body, secret) {
31
+ headers['X-EE-Wh-Signature'] = createHmac('sha256', secret).update(body).digest('base64url');
32
+ }
33
+
6
34
  // How much of a response body is read before the connection is dropped instead. The body is never
7
35
  // used, it is read only so the pooled socket can be reused, and undici inflates a compressed one,
8
36
  // so a receiver answering a POST with an endless or a bomb body would otherwise be buffered in
@@ -121,4 +149,4 @@ function isUnrecoverableWebhookError(err) {
121
149
  return !!err && (err.code === 'EEGRESSBLOCKED' || err.code === 'EREDIRECTNOTFOLLOWED');
122
150
  }
123
151
 
124
- module.exports = { sendWebhookRequest, isUnrecoverableWebhookError, MAX_DRAIN_BYTES };
152
+ module.exports = { sendWebhookRequest, isUnrecoverableWebhookError, baseDeliveryHeaders, signDelivery, MAX_DRAIN_BYTES };