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
package/workers/smtp.js CHANGED
@@ -8,7 +8,7 @@ const logger = require('../lib/logger');
8
8
 
9
9
  const { getDuration, emitChangeEvent, readEnvValue, threadStats, loadTlsConfig, assertTlsCredentials, getByteSize } = require('../lib/tools');
10
10
  const { createTlsContext, applyTlsContext } = require('../lib/tls/context');
11
- const { createSmtpAuthHandler, createSmtpAccountResolver } = require('../lib/smtp-auth');
11
+ const { createSmtpAuthHandler, createSmtpAccountResolver, sessionDisabledCommands } = require('../lib/smtp-auth');
12
12
 
13
13
  const { initSentry } = require('../lib/sentry');
14
14
  initSentry('smtp');
@@ -136,6 +136,10 @@ async function init() {
136
136
  disableReverseLookup: true,
137
137
  banner: 'EmailEngine MSA',
138
138
  size: MAX_SMTP_MESSAGE_SIZE,
139
+ // The server answers an oversized message with 552 itself, also when the client sent no
140
+ // SIZE= parameter. onData still has to keep the truncated message out of the queue, see
141
+ // the sizeExceeded check below
142
+ rejectOversized: true,
139
143
  maxClients: SMTP_MAX_CLIENTS,
140
144
  useProxy: await settings.get('smtpServerProxy'),
141
145
  closeTimeout: SMTP_CLOSE_TIMEOUT
@@ -149,16 +153,10 @@ async function init() {
149
153
  settings
150
154
  .get('smtpServerAuthEnabled')
151
155
  .then(authEnabled => {
152
- if (authEnabled && server.options.disabledCommands.includes('AUTH')) {
153
- let disabledCommands = new Set(server.options.disabledCommands);
154
- disabledCommands.delete('AUTH');
155
- server.options.disabledCommands = Array.from(disabledCommands);
156
- logger.info({ msg: 'Enabled authentication for the SMTP server', disabledCommands: server.options.disabledCommands });
157
- } else if (!authEnabled && !server.options.disabledCommands.includes('AUTH')) {
158
- server.options.disabledCommands.push('AUTH');
159
- logger.info({ msg: 'Disabled authentication for the SMTP server', disabledCommands: server.options.disabledCommands });
160
- }
161
-
156
+ // Per session, so switching authentication on or off takes effect for the next
157
+ // connection without changing what connections already open were offered. It used
158
+ // to rewrite the server-wide list, which every open session reads on each command
159
+ session.disabledCommands = sessionDisabledCommands(server.options.disabledCommands, authEnabled);
162
160
  session.eeAuthEnabled = !!authEnabled;
163
161
 
164
162
  return settings.get('smtpServerProxy');
package/workers/submit.js CHANGED
@@ -116,7 +116,7 @@ async function notify(account, event, data) {
116
116
  payload.data = data;
117
117
  }
118
118
 
119
- await Webhooks.pushToQueue(event, await Webhooks.formatPayload(event, payload));
119
+ await Webhooks.enqueue(event, payload);
120
120
  }
121
121
 
122
122
  const smtpLogger = {};
@@ -4,30 +4,25 @@ const { parentPort } = require('worker_threads');
4
4
 
5
5
  const packageData = require('../package.json');
6
6
  const config = require('@zone-eu/wild-config');
7
- const { createHmac } = require('crypto');
8
7
  const logger = require('../lib/logger');
9
8
  const { webhooks: Webhooks } = require('../lib/webhooks');
10
9
 
11
10
  const { GooglePubSub } = require('../lib/oauth/pubsub/google');
12
11
 
13
- const { readEnvValue, threadStats, getDuration, httpAgent, getServiceSecret, redactUrlCredentials, splitUrlCredentials } = require('../lib/tools');
14
- const { sendWebhookRequest, isUnrecoverableWebhookError } = require('../lib/webhook-request');
15
- const { willBeFinalAttempt, isFinalFailedAttempt } = require('../lib/delivery-error');
12
+ const { readEnvValue, threadStats, getDuration, httpAgent, getServiceSecret } = require('../lib/tools');
13
+ const { isFinalFailedAttempt } = require('../lib/delivery-error');
16
14
  const { validateWebhookTarget } = require('../lib/webhook-egress');
17
- const { resolveTargetUrl, isDeliverableRoute, eventAllowed, headerLevels, deliveryCustomHeaders, isRouteMappingMissing } = require('../lib/webhook-routing');
15
+ const { createWebhookProcessor } = require('../lib/webhook-delivery');
18
16
 
19
17
  const { initSentry } = require('../lib/sentry');
20
18
  initSentry('webhooks');
21
19
 
22
20
  const { redis, queueConf, logBullErrors } = require('../lib/db');
23
- const { Worker, UnrecoverableError, DelayedError } = require('bullmq');
24
- const { penaltyKey, penaltyFor } = require('../lib/webhook-penalty');
21
+ const { Worker } = require('bullmq');
25
22
  const settings = require('../lib/settings');
26
23
  const { decryptField } = require('../lib/encrypt');
27
24
  const getSecret = require('../lib/get-secret');
28
25
 
29
- const { REDIS_PREFIX, ACCOUNT_DELETED_NOTIFY, MESSAGE_NEW_NOTIFY, DEFAULT_WEBHOOK_REQUEST_TIMEOUT } = require('../lib/consts');
30
-
31
26
  const { fetch: fetchCmd } = require('undici');
32
27
 
33
28
  config.queues = config.queues || {
@@ -84,10 +79,6 @@ const googlePubSub = new GooglePubSub({
84
79
  call
85
80
  });
86
81
 
87
- function getAccountKey(account) {
88
- return `${REDIS_PREFIX}iad:${account}`;
89
- }
90
-
91
82
  // The account `webhooks` and `webhooksCustomHeaders` fields are encrypted at rest (see
92
83
  // ENCRYPTED_ACCOUNT_FIELDS in lib/account.js); a value stored before that is cleartext, which
93
84
  // decrypt() passes through. One that no longer decrypts reads as unset, as it does for the account.
@@ -203,441 +194,20 @@ parentPort.on('message', message => {
203
194
 
204
195
  const notifyWorker = new Worker(
205
196
  'notify',
206
- async (job, token) => {
207
- // do not process active jobs, use it for debugging only
208
- //return new Promise((resolve, reject) => {});
209
- let accountKey = getAccountKey(job.data.account);
210
-
211
- // Keep the route id reachable for the completed/failed event handlers, which see this same
212
- // job instance after _route has been deleted from the payload. Stashed before the early
213
- // returns below so a job that never reaches delivery still reports which route queued it.
214
- if (job.data._route && job.data._route.id) {
215
- job.__routeId = job.data._route.id;
216
- }
217
-
218
- // One round trip for the existence check and the two account fields a delivery may need
219
- // (used to be three, one per job). The fields are opened where they are used, below.
220
- let [accountExists, storedWebhooks, storedCustomHeaders] = await redis.hmget(accountKey, 'account', 'webhooks', 'webhooksCustomHeaders');
221
- if (!accountExists && job.name !== ACCOUNT_DELETED_NOTIFY) {
222
- logger.debug({
223
- msg: 'Account not found',
224
- action: 'webhook',
225
- queue: job.queue.name,
226
- code: 'account_not_found',
227
- job: job.id,
228
- event: job.name,
229
- account: job.data.account
230
- });
231
- return;
232
- }
233
-
234
- let webhooksEnabled = await settings.get('webhooksEnabled');
235
- if (!webhooksEnabled) {
236
- logger.debug({
237
- msg: 'Webhooks are disabled',
238
- action: 'webhook',
239
- queue: job.queue.name,
240
- code: 'webhooks_disabled',
241
- job: job.id,
242
- event: job.name,
243
- account: job.data.account
244
- });
245
- return;
246
- }
247
-
248
- let customRoute;
249
- let customMapping;
250
- if (job.data._route && job.data._route.id) {
251
- customRoute = await Webhooks.getMeta(job.data._route.id);
252
- customMapping = job.data._route.mapping;
253
- let mappingMissing = isRouteMappingMissing(job.data._route);
254
- delete job.data._route;
255
- if (!isDeliverableRoute(customRoute)) {
256
- return;
257
- }
258
- if (mappingMissing) {
259
- logger.warn({
260
- msg: 'Custom webhook route has no mapped payload, not sending',
261
- action: 'webhook',
262
- queue: job.queue.name,
263
- code: 'missing_mapping',
264
- job: job.id,
265
- event: job.name,
266
- account: job.data.account,
267
- route: customRoute.id
268
- });
269
- return;
270
- }
271
- }
272
-
273
- let accountWebhooks = await openAccountField('webhooks', storedWebhooks, job.data.account);
274
-
275
- // the global setting is only fetched when neither a custom route nor the account override decides the target
276
- let target = resolveTargetUrl(customRoute && customRoute.targetUrl, accountWebhooks, null);
277
- if (!target.url) {
278
- target = resolveTargetUrl(null, null, await settings.get('webhooks'));
279
- }
280
- let webhooks = target.url;
281
- if (!webhooks) {
282
- // A skipped delivery still reports the job as completed, so without this line a
283
- // missing target is indistinguishable from a successful delivery - it reads as the
284
- // receiver being slow rather than as nothing having been sent
285
- logger.debug({
286
- msg: 'Webhook URL is not set',
287
- action: 'webhook',
288
- queue: job.queue.name,
289
- code: 'no_target_url',
290
- job: job.id,
291
- event: job.name,
292
- account: job.data.account
293
- });
294
- return;
295
- }
296
-
297
- // A target whose last attempt ran into the timeout is penalised for a short while, and a
298
- // delivery to it waits out the penalty in the delayed set instead of costing the queue
299
- // another full attempt timeout; see lib/webhook-penalty.js. The attempt count is not
300
- // spent by the wait
301
- const targetPenaltyKey = penaltyKey(webhooks);
302
- if (targetPenaltyKey) {
303
- let remaining = await redis.pttl(targetPenaltyKey);
304
- if (remaining > 0) {
305
- logger.debug({
306
- msg: 'Webhook target is penalised, delaying delivery',
307
- action: 'webhook',
308
- queue: job.queue.name,
309
- code: 'target_penalised',
310
- job: job.id,
311
- event: job.name,
312
- account: job.data.account,
313
- webhooks: redactUrlCredentials(webhooks),
314
- delay: remaining
315
- });
316
- await job.moveToDelayed(Date.now() + remaining, token);
317
- throw new DelayedError();
318
- }
319
- }
320
-
321
- // Only the header lists that travel to this target are loaded; lib/webhook-routing.js
322
- // holds the rule and the reasons
323
- let levels = headerLevels(target.source);
324
-
325
- let accountWebhooksCustomHeaders;
326
- let accountWebhooksCustomHeadersJson = levels.includes('account')
327
- ? await openAccountField('webhooksCustomHeaders', storedCustomHeaders, job.data.account)
328
- : null;
329
- if (accountWebhooksCustomHeadersJson) {
330
- try {
331
- accountWebhooksCustomHeaders = JSON.parse(accountWebhooksCustomHeadersJson);
332
- } catch (err) {
333
- // do not log the header values, they may carry authentication secrets
334
- logger.debug({
335
- msg: 'Failed to parse custom webhook headers',
336
- action: 'webhook',
337
- event: job.name,
338
- account: job.data.account,
339
- jsonLength: accountWebhooksCustomHeadersJson.length,
340
- err
341
- });
342
- }
343
- }
344
-
345
- if (!customRoute) {
346
- // custom routes have their own mappings
347
- let webhookEvents = (await settings.get('webhookEvents')) || [];
348
- if (!eventAllowed(webhookEvents, job.name)) {
349
- logger.trace({
350
- msg: 'Webhook event not in whitelist',
351
- action: 'webhook',
352
- queue: job.queue.name,
353
- code: 'event_not_whitelisted',
354
- job: job.id,
355
- event: job.name,
356
- account: job.data.account,
357
- webhookEvents
358
- });
359
- return;
360
- }
361
-
362
- switch (job.data.event) {
363
- case MESSAGE_NEW_NOTIFY: {
364
- // check if we need to send this event or not
365
- let isInbox = false;
366
- if (
367
- (job.data.account && job.data.path === 'INBOX') ||
368
- job.data.specialUse === '\\Inbox' ||
369
- (job.data.data && job.data.data.messageSpecialUse === '\\Inbox') ||
370
- (job.data.data && job.data.data.labels && job.data.data.labels.includes('\\Inbox'))
371
- ) {
372
- isInbox = true;
373
- }
374
-
375
- if (!isInbox) {
376
- const inboxNewOnly = (await settings.get('inboxNewOnly')) || false;
377
- if (inboxNewOnly) {
378
- // ignore this message
379
- return;
380
- }
381
- }
382
-
383
- break;
384
- }
385
- }
386
- }
387
-
388
- // only log some of the properties for webhooks, not full contents
389
- let filteredData = {};
390
- for (let key of Object.keys(job.data)) {
391
- switch (key) {
392
- case 'data':
393
- {
394
- let filteredSubData = {};
395
- let isPartial = false;
396
- for (let dataKey of Object.keys(job.data.data || {})) {
397
- switch (dataKey) {
398
- case 'id':
399
- case 'uid':
400
- case 'path':
401
- case 'messageId':
402
- filteredSubData[dataKey] = job.data.data[dataKey];
403
- break;
404
- default:
405
- isPartial = true;
406
- }
407
- }
408
- if (isPartial) {
409
- if (Object.keys(filteredSubData).length) {
410
- filteredSubData.partial = true;
411
- } else {
412
- filteredSubData = true;
413
- }
414
- }
415
- filteredData[key] = filteredSubData;
416
- }
417
- break;
418
- default:
419
- filteredData[key] = job.data[key];
420
- }
421
- }
422
-
423
- // never log the raw target URL, it may embed basic auth credentials; keep the redacted
424
- // form reachable for the failed event handler
425
- let redactedWebhooks = redactUrlCredentials(webhooks);
426
- job.__redactedTargetUrl = redactedWebhooks;
427
-
428
- logger.trace({
429
- msg: 'Processing webhook',
430
- action: 'webhook',
431
- queue: job.queue.name,
432
- code: 'processing',
433
- job: job.id,
434
- webhooks: redactedWebhooks,
435
- accountWebhooks: !!accountWebhooks,
436
- event: job.name,
437
- data: filteredData,
438
- account: job.data.account,
439
- route: customRoute && customRoute.id
440
- });
441
-
442
- let headers = {
443
- 'Content-Type': 'application/json',
444
- 'User-Agent': `${packageData.name}/${packageData.version} (+${packageData.homepage})`,
445
- 'X-EE-Wh-Id': (job.id || '').toString(),
446
- 'X-EE-Wh-Attempts-Made': (job.attemptsMade || 0).toString(),
447
- 'X-EE-Wh-Queued-Time': Math.round(Math.max(0, (Date.now() - job.timestamp) / 1000)) + 's'
448
- };
449
-
450
- let { url: parsed, authorization } = splitUrlCredentials(webhooks);
451
- if (authorization) {
452
- headers.Authorization = authorization;
453
- }
454
-
455
- if (customRoute) {
456
- headers['X-EE-Wh-Custom-Route'] = customRoute.id;
457
- }
458
- Object.assign(
459
- headers,
460
- deliveryCustomHeaders(target.source, {
461
- route: customRoute && customRoute.customHeaders,
462
- global: levels.includes('global') ? await settings.get('webhooksCustomHeaders') : null,
463
- account: accountWebhooksCustomHeaders
464
- })
465
- );
466
-
467
- let start = Date.now();
468
- let duration;
469
-
470
- let webhookPayload = customMapping || job.data;
471
- if (webhookPayload.eventId) {
472
- headers['X-EE-Wh-Event-Id'] = webhookPayload.eventId;
473
- webhookPayload.eventId = undefined; // not included in JSON
474
- }
475
- let body = Buffer.from(JSON.stringify(webhookPayload));
476
-
477
- // Explicitly set Content-Length to prevent undici mismatch errors
478
- headers['Content-Length'] = body.length.toString();
479
-
480
- const serviceSecret = await getServiceSecret();
481
- let hmac = createHmac('sha256', serviceSecret);
482
- hmac.update(body);
483
- headers['X-EE-Wh-Signature'] = hmac.digest('base64url');
484
-
485
- try {
486
- let status;
487
- try {
488
- status = await sendWebhookRequest(fetchCmd, parsed.toString(), {
489
- method: 'post',
490
- body,
491
- headers,
492
- dispatcher: httpAgent.webhook,
493
- timeout: WEBHOOK_TIMEOUT,
494
- validateTarget: validateWebhookTarget
495
- });
496
- duration = Date.now() - start;
497
- } catch (err) {
498
- duration = Date.now() - start;
499
- throw err.cause || err;
500
- }
501
-
502
- logger.trace({
503
- msg: 'Webhook posted',
504
- action: 'webhook',
505
- queue: job.queue.name,
506
- code: 'result_success',
507
- job: job.id,
508
- webhooks: redactedWebhooks,
509
- requestBodySize: body.length,
510
- accountWebhooks: !!accountWebhooks,
511
- event: job.name,
512
- status,
513
- account: job.data.account,
514
- route: customRoute && customRoute.id
515
- });
516
-
517
- try {
518
- if (customRoute) {
519
- await redis.hset(Webhooks.getWebhooksContentKey(), `${customRoute.id}:webhookErrorFlag`, JSON.stringify({}));
520
- } else if (accountWebhooks) {
521
- await redis.hset(accountKey, 'webhookErrorFlag', JSON.stringify({}));
522
- } else {
523
- await settings.clear('webhookErrorFlag');
524
- }
525
- } catch (err) {
526
- // ignore
527
- }
528
-
529
- metrics(logger, 'webhooks', 'inc', {
530
- event: job.name,
531
- status: 'success'
532
- });
533
-
534
- // Stored by BullMQ as the job's return value in the same write that completes it, so
535
- // a retained completed job shows what the endpoint answered and how long it took
536
- return { status: 'delivered', statusCode: status, duration };
537
- } catch (err) {
538
- // egress and redirect failures are thrown as UnrecoverableError below, so they are final as well
539
- let isFinalAttempt = willBeFinalAttempt(job) || isUnrecoverableWebhookError(err);
540
-
541
- // A target that held the attempt until it timed out, or refused the connection, is
542
- // penalised so the next deliveries to it do not each cost the same wait
543
- let penalty = penaltyFor(err, WEBHOOK_TIMEOUT || DEFAULT_WEBHOOK_REQUEST_TIMEOUT);
544
- if (penalty && targetPenaltyKey) {
545
- try {
546
- await redis.set(targetPenaltyKey, '1', 'PX', penalty);
547
- } catch (penaltyErr) {
548
- // a missed penalty costs the queue one more timeout, nothing else
549
- }
550
- }
551
-
552
- // BullMQ keeps only the message of a failure on the job. The code and the HTTP status
553
- // are what explain it, so they are recorded the way the submit worker records its own
554
- // delivery errors, for the queue browser to read back
555
- try {
556
- await job.updateProgress({ status: 'error', error: { message: err.message, code: err.code, statusCode: err.statusCode }, duration });
557
- } catch (progressErr) {
558
- // ignore
559
- }
560
-
561
- logger[isFinalAttempt ? 'error' : 'warn']({
562
- msg: 'Failed posting webhook',
563
- action: 'webhook',
564
- queue: job.queue.name,
565
- code: 'result_fail',
566
- job: job.id,
567
- webhooks: redactedWebhooks,
568
- requestBodySize: body.length,
569
- accountWebhooks: !!accountWebhooks,
570
- event: job.name,
571
- account: job.data.account,
572
- route: customRoute && customRoute.id,
573
- err
574
- });
575
-
576
- try {
577
- if (customRoute) {
578
- await redis.hset(
579
- Webhooks.getWebhooksContentKey(),
580
- `${customRoute.id}:webhookErrorFlag`,
581
- JSON.stringify({
582
- event: job.name,
583
- message: err.message,
584
- time: Date.now(),
585
- // stored without credentials: the flag is read back through the
586
- // webhook route listing, the account page and the settings API
587
- url: redactUrlCredentials(customRoute.targetUrl),
588
- code: err.code,
589
- statusCode: err.statusCode
590
- })
591
- );
592
- } else if (accountWebhooks) {
593
- await redis.hset(
594
- accountKey,
595
- 'webhookErrorFlag',
596
- JSON.stringify({
597
- event: job.name,
598
- message: err.message,
599
- time: Date.now(),
600
- url: redactedWebhooks,
601
- code: err.code,
602
- statusCode: err.statusCode
603
- })
604
- );
605
- } else {
606
- await settings.set('webhookErrorFlag', {
607
- event: job.name,
608
- message: err.message,
609
- time: Date.now(),
610
- url: redactedWebhooks,
611
- code: err.code,
612
- statusCode: err.statusCode
613
- });
614
- }
615
- } catch (err) {
616
- // ignore
617
- }
618
-
619
- metrics(logger, 'webhooks', 'inc', {
620
- event: job.name,
621
- status: 'fail'
622
- });
623
-
624
- // Spending the remaining attempts on an unrecoverable failure only delays the operator
625
- // seeing the real reason in the error flag. Fail the job now and keep the message.
626
- if (isUnrecoverableWebhookError(err)) {
627
- // UnrecoverableError copies the message only, and the failed-event handler logs the
628
- // error it is given, so carry the code over or that log loses the actual reason
629
- let unrecoverableErr = new UnrecoverableError(err.message);
630
- unrecoverableErr.code = err.code;
631
- throw unrecoverableErr;
632
- }
633
-
634
- throw err;
635
- } finally {
636
- if (duration) {
637
- metrics(logger, 'webhookReq', 'observe', duration);
638
- }
639
- }
640
- },
197
+ // the processor lives in lib/webhook-delivery.js so it can be tested; everything it touches is passed in here
198
+ createWebhookProcessor({
199
+ redis,
200
+ settings,
201
+ webhooks: Webhooks,
202
+ logger,
203
+ metrics: (key, method, ...args) => metrics(logger, key, method, ...args),
204
+ openAccountField,
205
+ getServiceSecret,
206
+ fetch: fetchCmd,
207
+ dispatcher: httpAgent.webhook,
208
+ timeout: WEBHOOK_TIMEOUT,
209
+ validateTarget: validateWebhookTarget
210
+ }),
641
211
  Object.assign(
642
212
  {
643
213
  concurrency: Number(NOTIFY_QC) || 1,
@@ -1,30 +0,0 @@
1
- 'use strict';
2
-
3
- const { readEnvValue, getDuration } = require('../tools');
4
-
5
- const DEFAULT_FALLBACK_POLL_INTERVAL = 10 * 60 * 1000;
6
- const MIN_FALLBACK_POLL_INTERVAL = 10 * 1000;
7
-
8
- /**
9
- * Reads EENGINE_OUTLOOK_FALLBACK_POLL_INTERVAL: a duration, 0 switching the periodic pass off.
10
- * Anything unreadable gets the default, and a positive value is never shorter than ten seconds, so
11
- * a typo cannot point every account at Graph in a loop
12
- * @param {*} value - The raw environment value
13
- * @returns {number} Milliseconds, 0 when the pass is off
14
- */
15
- function parseFallbackPollInterval(value) {
16
- // blank is "unset", which getDuration() would read as 0, the value that switches the pass off
17
- const raw = String(value ?? '').trim();
18
- const duration = raw ? getDuration(raw) : DEFAULT_FALLBACK_POLL_INTERVAL;
19
- if (!Number.isFinite(duration) || duration < 0) {
20
- return DEFAULT_FALLBACK_POLL_INTERVAL;
21
- }
22
- return duration && Math.max(duration, MIN_FALLBACK_POLL_INTERVAL);
23
- }
24
-
25
- // The interval of the periodic missed-notification recovery pass (OutlookClient.setupFallbackPollTimer()).
26
- // Its own module so the admin UI, which runs in the API worker, reads the same value the account
27
- // workers run with
28
- const FALLBACK_POLL_INTERVAL = parseFallbackPollInterval(readEnvValue('EENGINE_OUTLOOK_FALLBACK_POLL_INTERVAL'));
29
-
30
- module.exports = { parseFallbackPollInterval, FALLBACK_POLL_INTERVAL };