emailengine-app 2.85.0 → 2.87.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (137) hide show
  1. package/.ncurc.js +24 -6
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +97 -0
  4. package/DOCKER_DEPLOYMENT.md +2 -1
  5. package/Dockerfile +16 -3
  6. package/ENVIRONMENT.md +139 -0
  7. package/README.md +5 -1
  8. package/config/default.toml +2 -0
  9. package/copy-static-files.sh +4 -2
  10. package/data/google-crawlers.json +1 -1
  11. package/data/public_suffix_list.dat +4 -3
  12. package/lib/account-assignment.js +19 -0
  13. package/lib/account.js +285 -195
  14. package/lib/api-error-codes.js +49 -0
  15. package/lib/api-reference/model.js +6 -1
  16. package/lib/api-routes/account-routes.js +91 -32
  17. package/lib/api-routes/blocklist-routes.js +68 -2
  18. package/lib/api-routes/delivery-test-routes.js +1 -1
  19. package/lib/api-routes/gateway-routes.js +82 -10
  20. package/lib/api-routes/index.js +4 -0
  21. package/lib/api-routes/license-routes.js +2 -2
  22. package/lib/api-routes/mailbox-routes.js +3 -3
  23. package/lib/api-routes/message-routes.js +15 -7
  24. package/lib/api-routes/oauth2-app-routes.js +15 -8
  25. package/lib/api-routes/outbox-routes.js +77 -66
  26. package/lib/api-routes/permission-map.js +55 -6
  27. package/lib/api-routes/scoped-routes.js +74 -0
  28. package/lib/api-routes/settings-routes.js +11 -4
  29. package/lib/api-routes/stats-routes.js +5 -1
  30. package/lib/api-routes/submit-routes.js +25 -5
  31. package/lib/api-routes/template-routes.js +7 -6
  32. package/lib/api-routes/token-routes.js +11 -5
  33. package/lib/api-routes/webhook-delivery-routes.js +262 -0
  34. package/lib/api-routes/webhook-route-routes.js +119 -4
  35. package/lib/calendar-event.js +81 -1
  36. package/lib/consts.js +38 -46
  37. package/lib/db.js +14 -6
  38. package/lib/delivery-error.js +6 -0
  39. package/lib/deprecations.js +270 -0
  40. package/lib/email-client/base-client.js +134 -158
  41. package/lib/email-client/fallback-poll.js +62 -0
  42. package/lib/email-client/gmail-client.js +59 -11
  43. package/lib/email-client/imap/adaptive-idle-store.js +73 -0
  44. package/lib/email-client/imap/adaptive-idle.js +278 -0
  45. package/lib/email-client/imap/connection-errors.js +14 -1
  46. package/lib/email-client/imap/idle-settings.js +31 -5
  47. package/lib/email-client/imap/listing-diff.js +37 -0
  48. package/lib/email-client/imap/mailbox.js +380 -227
  49. package/lib/email-client/imap/subconnection.js +7 -29
  50. package/lib/email-client/imap/sync-operations.js +220 -127
  51. package/lib/email-client/imap-client.js +227 -163
  52. package/lib/email-client/message-builder.js +14 -79
  53. package/lib/email-client/outlook-client.js +378 -338
  54. package/lib/email-client/smtp-pool-manager.js +16 -13
  55. package/lib/email-client/sync-state-fields.js +19 -0
  56. package/lib/encrypt.js +157 -41
  57. package/lib/enum-descriptions.js +3 -1
  58. package/lib/env-setting-overrides.js +288 -0
  59. package/lib/export-worker.js +751 -0
  60. package/lib/export.js +64 -15
  61. package/lib/field-usage.js +1 -1
  62. package/lib/gateway.js +17 -1
  63. package/lib/get-raw-email.js +35 -108
  64. package/lib/health.js +75 -0
  65. package/lib/lock-run.js +119 -0
  66. package/lib/logger-consts.js +48 -0
  67. package/lib/logger.js +1 -1
  68. package/lib/lua/z-head-scores.lua +28 -0
  69. package/lib/network-errors.js +1 -1
  70. package/lib/node-version.js +24 -0
  71. package/lib/notify-attachments.js +20 -1
  72. package/lib/oauth/gmail.js +54 -29
  73. package/lib/oauth2-apps.js +630 -655
  74. package/lib/otp.js +66 -0
  75. package/lib/outbox.js +184 -54
  76. package/lib/parse-message.js +3 -3
  77. package/lib/privileged-settings.js +2 -2
  78. package/lib/queue-browser/definitions.js +11 -0
  79. package/lib/queue-browser/index.js +68 -19
  80. package/lib/queue-job-actions.js +18 -1
  81. package/lib/queue-retention.js +48 -12
  82. package/lib/queue-stats.js +11 -2
  83. package/lib/read-env-value.js +3 -0
  84. package/lib/redis-memory-warnings.js +99 -0
  85. package/lib/redis-reconnect.js +29 -0
  86. package/lib/request-timing.js +23 -0
  87. package/lib/respawn-backoff.js +35 -0
  88. package/lib/rewrite-text-nodes.js +19 -59
  89. package/lib/schemas.js +225 -41
  90. package/lib/settings.js +6 -2
  91. package/lib/smtp-auth.js +19 -1
  92. package/lib/swagger-options.js +2 -2
  93. package/lib/thread-diagnostics.js +18 -1
  94. package/lib/tls/provision.js +6 -3
  95. package/lib/token-audit-log.js +19 -20
  96. package/lib/token-permission-view.js +4 -3
  97. package/lib/tools.js +8 -41
  98. package/lib/ui-routes/admin-config-routes.js +64 -90
  99. package/lib/ui-routes/admin-entities-routes.js +2 -14
  100. package/lib/ui-routes/imap-idle-field.js +1 -1
  101. package/lib/ui-routes/outlook-subscription-view.js +1 -1
  102. package/lib/ui-routes/overridable-fields.js +84 -0
  103. package/lib/ui-routes/queue-routes.js +8 -5
  104. package/lib/ui-routes/settings-page.js +6 -0
  105. package/lib/utils/decode-headers.js +3 -12
  106. package/lib/utils/filter-empty.js +20 -0
  107. package/lib/utils/int-setting.js +48 -0
  108. package/lib/utils/tracking-settings.js +35 -0
  109. package/lib/web-safe-html.js +18 -105
  110. package/lib/webhook-delivery.js +461 -0
  111. package/lib/webhook-failures.js +132 -0
  112. package/lib/webhook-request.js +29 -1
  113. package/lib/webhook-routing.js +30 -1
  114. package/lib/webhook-test.js +88 -0
  115. package/lib/webhooks.js +59 -41
  116. package/lib/worker-rpc-error.js +2 -1
  117. package/package.json +28 -26
  118. package/sbom.json +600 -678
  119. package/server.js +149 -76
  120. package/static/css/flyonui.css +1 -1
  121. package/static/js/ace/ace.js +1 -1
  122. package/static/js/ee-client.js +650 -196
  123. package/static/licenses.html +49 -59
  124. package/translations/messages.pot +26 -26
  125. package/views/config/security.hbs +22 -0
  126. package/views/config/service.hbs +44 -0
  127. package/views/config/webhooks.hbs +36 -0
  128. package/views/layout/app.hbs +9 -6
  129. package/views/legal.hbs +8 -0
  130. package/views/partials/queue_retention_note.hbs +12 -8
  131. package/views/partials/ui/env-managed-alert.hbs +16 -7
  132. package/workers/api.js +112 -37
  133. package/workers/export.js +16 -631
  134. package/workers/imap.js +13 -0
  135. package/workers/smtp.js +9 -11
  136. package/workers/webhooks.js +18 -432
  137. package/lib/email-client/outlook-fallback-poll.js +0 -30
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');
@@ -4,38 +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 {
18
- resolveTargetUrl,
19
- isDeliverableRoute,
20
- eventAllowed,
21
- defaultRouteTakes,
22
- headerLevels,
23
- deliveryCustomHeaders,
24
- isRouteMappingMissing
25
- } = require('../lib/webhook-routing');
15
+ const { createWebhookProcessor } = require('../lib/webhook-delivery');
26
16
 
27
17
  const { initSentry } = require('../lib/sentry');
28
18
  initSentry('webhooks');
29
19
 
30
20
  const { redis, queueConf, logBullErrors } = require('../lib/db');
31
- const { Worker, UnrecoverableError, DelayedError } = require('bullmq');
32
- const { penaltyKey, penaltyFor } = require('../lib/webhook-penalty');
21
+ const { Worker } = require('bullmq');
33
22
  const settings = require('../lib/settings');
34
23
  const { decryptField } = require('../lib/encrypt');
35
24
  const getSecret = require('../lib/get-secret');
36
25
 
37
- const { REDIS_PREFIX, ACCOUNT_DELETED_NOTIFY, DEFAULT_WEBHOOK_REQUEST_TIMEOUT } = require('../lib/consts');
38
-
39
26
  const { fetch: fetchCmd } = require('undici');
40
27
 
41
28
  config.queues = config.queues || {
@@ -92,10 +79,6 @@ const googlePubSub = new GooglePubSub({
92
79
  call
93
80
  });
94
81
 
95
- function getAccountKey(account) {
96
- return `${REDIS_PREFIX}iad:${account}`;
97
- }
98
-
99
82
  // The account `webhooks` and `webhooksCustomHeaders` fields are encrypted at rest (see
100
83
  // ENCRYPTED_ACCOUNT_FIELDS in lib/account.js); a value stored before that is cleartext, which
101
84
  // decrypt() passes through. One that no longer decrypts reads as unset, as it does for the account.
@@ -211,417 +194,20 @@ parentPort.on('message', message => {
211
194
 
212
195
  const notifyWorker = new Worker(
213
196
  'notify',
214
- async (job, token) => {
215
- // do not process active jobs, use it for debugging only
216
- //return new Promise((resolve, reject) => {});
217
- let accountKey = getAccountKey(job.data.account);
218
-
219
- // Keep the route id reachable for the completed/failed event handlers, which see this same
220
- // job instance after _route has been deleted from the payload. Stashed before the early
221
- // returns below so a job that never reaches delivery still reports which route queued it.
222
- if (job.data._route && job.data._route.id) {
223
- job.__routeId = job.data._route.id;
224
- }
225
-
226
- // One round trip for the existence check and the two account fields a delivery may need
227
- // (used to be three, one per job). The fields are opened where they are used, below.
228
- let [accountExists, storedWebhooks, storedCustomHeaders] = await redis.hmget(accountKey, 'account', 'webhooks', 'webhooksCustomHeaders');
229
- if (!accountExists && job.name !== ACCOUNT_DELETED_NOTIFY) {
230
- logger.debug({
231
- msg: 'Account not found',
232
- action: 'webhook',
233
- queue: job.queue.name,
234
- code: 'account_not_found',
235
- job: job.id,
236
- event: job.name,
237
- account: job.data.account
238
- });
239
- return;
240
- }
241
-
242
- let webhooksEnabled = await settings.get('webhooksEnabled');
243
- if (!webhooksEnabled) {
244
- logger.debug({
245
- msg: 'Webhooks are disabled',
246
- action: 'webhook',
247
- queue: job.queue.name,
248
- code: 'webhooks_disabled',
249
- job: job.id,
250
- event: job.name,
251
- account: job.data.account
252
- });
253
- return;
254
- }
255
-
256
- let customRoute;
257
- let customMapping;
258
- if (job.data._route && job.data._route.id) {
259
- customRoute = await Webhooks.getMeta(job.data._route.id);
260
- customMapping = job.data._route.mapping;
261
- let mappingMissing = isRouteMappingMissing(job.data._route);
262
- delete job.data._route;
263
- if (!isDeliverableRoute(customRoute)) {
264
- return;
265
- }
266
- if (mappingMissing) {
267
- logger.warn({
268
- msg: 'Custom webhook route has no mapped payload, not sending',
269
- action: 'webhook',
270
- queue: job.queue.name,
271
- code: 'missing_mapping',
272
- job: job.id,
273
- event: job.name,
274
- account: job.data.account,
275
- route: customRoute.id
276
- });
277
- return;
278
- }
279
- }
280
-
281
- let accountWebhooks = await openAccountField('webhooks', storedWebhooks, job.data.account);
282
-
283
- // the global setting is only fetched when neither a custom route nor the account override decides the target
284
- let target = resolveTargetUrl(customRoute && customRoute.targetUrl, accountWebhooks, null);
285
- if (!target.url) {
286
- target = resolveTargetUrl(null, null, await settings.get('webhooks'));
287
- }
288
- let webhooks = target.url;
289
- if (!webhooks) {
290
- // A skipped delivery still reports the job as completed, so without this line a
291
- // missing target is indistinguishable from a successful delivery - it reads as the
292
- // receiver being slow rather than as nothing having been sent
293
- logger.debug({
294
- msg: 'Webhook URL is not set',
295
- action: 'webhook',
296
- queue: job.queue.name,
297
- code: 'no_target_url',
298
- job: job.id,
299
- event: job.name,
300
- account: job.data.account
301
- });
302
- return;
303
- }
304
-
305
- // A target whose last attempt ran into the timeout is penalised for a short while, and a
306
- // delivery to it waits out the penalty in the delayed set instead of costing the queue
307
- // another full attempt timeout; see lib/webhook-penalty.js. The attempt count is not
308
- // spent by the wait
309
- const targetPenaltyKey = penaltyKey(webhooks);
310
- if (targetPenaltyKey) {
311
- let remaining = await redis.pttl(targetPenaltyKey);
312
- if (remaining > 0) {
313
- logger.debug({
314
- msg: 'Webhook target is penalised, delaying delivery',
315
- action: 'webhook',
316
- queue: job.queue.name,
317
- code: 'target_penalised',
318
- job: job.id,
319
- event: job.name,
320
- account: job.data.account,
321
- webhooks: redactUrlCredentials(webhooks),
322
- delay: remaining
323
- });
324
- await job.moveToDelayed(Date.now() + remaining, token);
325
- throw new DelayedError();
326
- }
327
- }
328
-
329
- // Only the header lists that travel to this target are loaded; lib/webhook-routing.js
330
- // holds the rule and the reasons
331
- let levels = headerLevels(target.source);
332
-
333
- let accountWebhooksCustomHeaders;
334
- let accountWebhooksCustomHeadersJson = levels.includes('account')
335
- ? await openAccountField('webhooksCustomHeaders', storedCustomHeaders, job.data.account)
336
- : null;
337
- if (accountWebhooksCustomHeadersJson) {
338
- try {
339
- accountWebhooksCustomHeaders = JSON.parse(accountWebhooksCustomHeadersJson);
340
- } catch (err) {
341
- // do not log the header values, they may carry authentication secrets
342
- logger.debug({
343
- msg: 'Failed to parse custom webhook headers',
344
- action: 'webhook',
345
- event: job.name,
346
- account: job.data.account,
347
- jsonLength: accountWebhooksCustomHeadersJson.length,
348
- err
349
- });
350
- }
351
- }
352
-
353
- if (!customRoute) {
354
- // custom routes have their own mappings; the default route follows webhookEvents and
355
- // inboxNewOnly, by the same rule pushToQueue() applied before queueing
356
- let { webhookEvents, inboxNewOnly } = await settings.getMulti('webhookEvents', 'inboxNewOnly');
357
- if (!defaultRouteTakes(job.name, job.data, { webhookEvents, inboxNewOnly })) {
358
- logger.trace({
359
- msg: 'Webhook event not taken by the default route',
360
- action: 'webhook',
361
- queue: job.queue.name,
362
- code: eventAllowed(webhookEvents, job.name) ? 'inbox_new_only' : 'event_not_whitelisted',
363
- job: job.id,
364
- event: job.name,
365
- account: job.data.account,
366
- webhookEvents
367
- });
368
- return;
369
- }
370
- }
371
-
372
- // only log some of the properties for webhooks, not full contents
373
- let filteredData = {};
374
- for (let key of Object.keys(job.data)) {
375
- switch (key) {
376
- case 'data':
377
- {
378
- let filteredSubData = {};
379
- let isPartial = false;
380
- for (let dataKey of Object.keys(job.data.data || {})) {
381
- switch (dataKey) {
382
- case 'id':
383
- case 'uid':
384
- case 'path':
385
- case 'messageId':
386
- filteredSubData[dataKey] = job.data.data[dataKey];
387
- break;
388
- default:
389
- isPartial = true;
390
- }
391
- }
392
- if (isPartial) {
393
- if (Object.keys(filteredSubData).length) {
394
- filteredSubData.partial = true;
395
- } else {
396
- filteredSubData = true;
397
- }
398
- }
399
- filteredData[key] = filteredSubData;
400
- }
401
- break;
402
- default:
403
- filteredData[key] = job.data[key];
404
- }
405
- }
406
-
407
- // never log the raw target URL, it may embed basic auth credentials; keep the redacted
408
- // form reachable for the failed event handler
409
- let redactedWebhooks = redactUrlCredentials(webhooks);
410
- job.__redactedTargetUrl = redactedWebhooks;
411
-
412
- logger.trace({
413
- msg: 'Processing webhook',
414
- action: 'webhook',
415
- queue: job.queue.name,
416
- code: 'processing',
417
- job: job.id,
418
- webhooks: redactedWebhooks,
419
- accountWebhooks: !!accountWebhooks,
420
- event: job.name,
421
- data: filteredData,
422
- account: job.data.account,
423
- route: customRoute && customRoute.id
424
- });
425
-
426
- let headers = {
427
- 'Content-Type': 'application/json',
428
- 'User-Agent': `${packageData.name}/${packageData.version} (+${packageData.homepage})`,
429
- 'X-EE-Wh-Id': (job.id || '').toString(),
430
- 'X-EE-Wh-Attempts-Made': (job.attemptsMade || 0).toString(),
431
- 'X-EE-Wh-Queued-Time': Math.round(Math.max(0, (Date.now() - job.timestamp) / 1000)) + 's'
432
- };
433
-
434
- let { url: parsed, authorization } = splitUrlCredentials(webhooks);
435
- if (authorization) {
436
- headers.Authorization = authorization;
437
- }
438
-
439
- if (customRoute) {
440
- headers['X-EE-Wh-Custom-Route'] = customRoute.id;
441
- }
442
- Object.assign(
443
- headers,
444
- deliveryCustomHeaders(target.source, {
445
- route: customRoute && customRoute.customHeaders,
446
- global: levels.includes('global') ? await settings.get('webhooksCustomHeaders') : null,
447
- account: accountWebhooksCustomHeaders
448
- })
449
- );
450
-
451
- let start = Date.now();
452
- let duration;
453
-
454
- let webhookPayload = customMapping || job.data;
455
- if (webhookPayload.eventId) {
456
- headers['X-EE-Wh-Event-Id'] = webhookPayload.eventId;
457
- webhookPayload.eventId = undefined; // not included in JSON
458
- }
459
- let body = Buffer.from(JSON.stringify(webhookPayload));
460
-
461
- // Explicitly set Content-Length to prevent undici mismatch errors
462
- headers['Content-Length'] = body.length.toString();
463
-
464
- const serviceSecret = await getServiceSecret();
465
- let hmac = createHmac('sha256', serviceSecret);
466
- hmac.update(body);
467
- headers['X-EE-Wh-Signature'] = hmac.digest('base64url');
468
-
469
- try {
470
- let status;
471
- try {
472
- status = await sendWebhookRequest(fetchCmd, parsed.toString(), {
473
- method: 'post',
474
- body,
475
- headers,
476
- dispatcher: httpAgent.webhook,
477
- timeout: WEBHOOK_TIMEOUT,
478
- validateTarget: validateWebhookTarget
479
- });
480
- duration = Date.now() - start;
481
- } catch (err) {
482
- duration = Date.now() - start;
483
- throw err.cause || err;
484
- }
485
-
486
- logger.trace({
487
- msg: 'Webhook posted',
488
- action: 'webhook',
489
- queue: job.queue.name,
490
- code: 'result_success',
491
- job: job.id,
492
- webhooks: redactedWebhooks,
493
- requestBodySize: body.length,
494
- accountWebhooks: !!accountWebhooks,
495
- event: job.name,
496
- status,
497
- account: job.data.account,
498
- route: customRoute && customRoute.id
499
- });
500
-
501
- try {
502
- if (customRoute) {
503
- await redis.hset(Webhooks.getWebhooksContentKey(), `${customRoute.id}:webhookErrorFlag`, JSON.stringify({}));
504
- } else if (accountWebhooks) {
505
- await redis.hset(accountKey, 'webhookErrorFlag', JSON.stringify({}));
506
- } else {
507
- await settings.clear('webhookErrorFlag');
508
- }
509
- } catch (err) {
510
- // ignore
511
- }
512
-
513
- metrics(logger, 'webhooks', 'inc', {
514
- event: job.name,
515
- status: 'success'
516
- });
517
-
518
- // Stored by BullMQ as the job's return value in the same write that completes it, so
519
- // a retained completed job shows what the endpoint answered and how long it took
520
- return { status: 'delivered', statusCode: status, duration };
521
- } catch (err) {
522
- // egress and redirect failures are thrown as UnrecoverableError below, so they are final as well
523
- let isFinalAttempt = willBeFinalAttempt(job) || isUnrecoverableWebhookError(err);
524
-
525
- // A target that held the attempt until it timed out, or refused the connection, is
526
- // penalised so the next deliveries to it do not each cost the same wait
527
- let penalty = penaltyFor(err, WEBHOOK_TIMEOUT || DEFAULT_WEBHOOK_REQUEST_TIMEOUT);
528
- if (penalty && targetPenaltyKey) {
529
- try {
530
- await redis.set(targetPenaltyKey, '1', 'PX', penalty);
531
- } catch (penaltyErr) {
532
- // a missed penalty costs the queue one more timeout, nothing else
533
- }
534
- }
535
-
536
- // BullMQ keeps only the message of a failure on the job. The code and the HTTP status
537
- // are what explain it, so they are recorded the way the submit worker records its own
538
- // delivery errors, for the queue browser to read back
539
- try {
540
- await job.updateProgress({ status: 'error', error: { message: err.message, code: err.code, statusCode: err.statusCode }, duration });
541
- } catch (progressErr) {
542
- // ignore
543
- }
544
-
545
- logger[isFinalAttempt ? 'error' : 'warn']({
546
- msg: 'Failed posting webhook',
547
- action: 'webhook',
548
- queue: job.queue.name,
549
- code: 'result_fail',
550
- job: job.id,
551
- webhooks: redactedWebhooks,
552
- requestBodySize: body.length,
553
- accountWebhooks: !!accountWebhooks,
554
- event: job.name,
555
- account: job.data.account,
556
- route: customRoute && customRoute.id,
557
- err
558
- });
559
-
560
- try {
561
- if (customRoute) {
562
- await redis.hset(
563
- Webhooks.getWebhooksContentKey(),
564
- `${customRoute.id}:webhookErrorFlag`,
565
- JSON.stringify({
566
- event: job.name,
567
- message: err.message,
568
- time: Date.now(),
569
- // stored without credentials: the flag is read back through the
570
- // webhook route listing, the account page and the settings API
571
- url: redactUrlCredentials(customRoute.targetUrl),
572
- code: err.code,
573
- statusCode: err.statusCode
574
- })
575
- );
576
- } else if (accountWebhooks) {
577
- await redis.hset(
578
- accountKey,
579
- 'webhookErrorFlag',
580
- JSON.stringify({
581
- event: job.name,
582
- message: err.message,
583
- time: Date.now(),
584
- url: redactedWebhooks,
585
- code: err.code,
586
- statusCode: err.statusCode
587
- })
588
- );
589
- } else {
590
- await settings.set('webhookErrorFlag', {
591
- event: job.name,
592
- message: err.message,
593
- time: Date.now(),
594
- url: redactedWebhooks,
595
- code: err.code,
596
- statusCode: err.statusCode
597
- });
598
- }
599
- } catch (err) {
600
- // ignore
601
- }
602
-
603
- metrics(logger, 'webhooks', 'inc', {
604
- event: job.name,
605
- status: 'fail'
606
- });
607
-
608
- // Spending the remaining attempts on an unrecoverable failure only delays the operator
609
- // seeing the real reason in the error flag. Fail the job now and keep the message.
610
- if (isUnrecoverableWebhookError(err)) {
611
- // UnrecoverableError copies the message only, and the failed-event handler logs the
612
- // error it is given, so carry the code over or that log loses the actual reason
613
- let unrecoverableErr = new UnrecoverableError(err.message);
614
- unrecoverableErr.code = err.code;
615
- throw unrecoverableErr;
616
- }
617
-
618
- throw err;
619
- } finally {
620
- if (duration) {
621
- metrics(logger, 'webhookReq', 'observe', duration);
622
- }
623
- }
624
- },
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
+ }),
625
211
  Object.assign(
626
212
  {
627
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 };