emailengine-app 2.78.0 → 2.79.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 (142) hide show
  1. package/.ncurc.js +23 -13
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +29 -0
  4. package/config/e2e.toml +2 -1
  5. package/config/test.toml +2 -1
  6. package/data/google-crawlers.json +1 -1
  7. package/lib/account.js +70 -35
  8. package/lib/api-reference/format.js +91 -4
  9. package/lib/api-reference/model.js +144 -19
  10. package/lib/api-reference/schema-tree.js +282 -28
  11. package/lib/api-routes/account-routes.js +80 -34
  12. package/lib/api-routes/blocklist-routes.js +21 -47
  13. package/lib/api-routes/chat-routes.js +10 -12
  14. package/lib/api-routes/delivery-test-routes.js +6 -26
  15. package/lib/api-routes/export-routes.js +2 -0
  16. package/lib/api-routes/gateway-routes.js +52 -11
  17. package/lib/api-routes/license-routes.js +2 -0
  18. package/lib/api-routes/mailbox-routes.js +29 -26
  19. package/lib/api-routes/message-routes.js +27 -21
  20. package/lib/api-routes/oauth2-app-routes.js +11 -29
  21. package/lib/api-routes/operation-impact.js +80 -0
  22. package/lib/api-routes/outbox-routes.js +15 -5
  23. package/lib/api-routes/permission-map.js +397 -0
  24. package/lib/api-routes/route-helpers.js +223 -9
  25. package/lib/api-routes/route-metadata.js +28 -0
  26. package/lib/api-routes/settings-routes.js +30 -25
  27. package/lib/api-routes/stats-routes.js +2 -2
  28. package/lib/api-routes/submit-routes.js +53 -31
  29. package/lib/api-routes/template-routes.js +3 -0
  30. package/lib/api-routes/token-routes.js +319 -33
  31. package/lib/api-routes/webhook-route-routes.js +14 -4
  32. package/lib/auth-token.js +80 -8
  33. package/lib/consts.js +10 -0
  34. package/lib/db.js +20 -2
  35. package/lib/delivery-error.js +30 -1
  36. package/lib/email-client/base-client.js +27 -41
  37. package/lib/email-client/gmail-client.js +19 -10
  38. package/lib/email-client/imap/mailbox.js +23 -24
  39. package/lib/email-client/imap/subconnection.js +10 -7
  40. package/lib/email-client/imap/sync-operations.js +46 -46
  41. package/lib/email-client/imap-client.js +36 -26
  42. package/lib/email-client/message-builder.js +3 -3
  43. package/lib/email-client/notification-handler.js +1 -1
  44. package/lib/email-client/outlook/graph-api.js +10 -4
  45. package/lib/email-client/outlook-client.js +53 -54
  46. package/lib/email-client/smtp-pool-manager.js +1 -1
  47. package/lib/enum-descriptions.js +92 -2
  48. package/lib/export.js +1 -1
  49. package/lib/field-usage.js +133 -0
  50. package/lib/gateway.js +1 -1
  51. package/lib/imapproxy/imap-core/lib/commands/authenticate-plain.js +3 -3
  52. package/lib/imapproxy/imap-core/lib/commands/id.js +2 -13
  53. package/lib/imapproxy/imap-core/lib/commands/starttls.js +1 -1
  54. package/lib/imapproxy/imap-core/lib/imap-command.js +21 -5
  55. package/lib/imapproxy/imap-core/lib/imap-connection.js +15 -5
  56. package/lib/imapproxy/imap-server.js +27 -7
  57. package/lib/license-beacon.js +4 -9
  58. package/lib/lists.js +49 -1
  59. package/lib/llm-pre-process.js +5 -5
  60. package/lib/logger.js +5 -1
  61. package/lib/metrics-collector.js +2 -2
  62. package/lib/oauth/gmail.js +9 -12
  63. package/lib/oauth/mail-ru.js +5 -7
  64. package/lib/oauth/outlook.js +9 -9
  65. package/lib/oauth/pubsub/google.js +25 -10
  66. package/lib/oauth/scope-checker.js +1 -1
  67. package/lib/oauth2-apps.js +223 -294
  68. package/lib/openapi/build-document.js +15 -7
  69. package/lib/openapi/joi-schema.js +20 -0
  70. package/lib/outbox.js +85 -17
  71. package/lib/pre-process.js +8 -8
  72. package/lib/queue-stats.js +49 -0
  73. package/lib/read-env-value.js +1 -1
  74. package/lib/reconnection-manager.js +2 -2
  75. package/lib/rewrite-text-nodes.js +4 -3
  76. package/lib/routes-ui.js +4 -0
  77. package/lib/schemas.js +216 -160
  78. package/lib/settings.js +84 -5
  79. package/lib/sub-script.js +2 -1
  80. package/lib/swagger-options.js +2 -1
  81. package/lib/templates.js +4 -4
  82. package/lib/threads.js +2 -2
  83. package/lib/token-audit-log.js +208 -0
  84. package/lib/token-permission-view.js +219 -0
  85. package/lib/token-permissions.js +172 -0
  86. package/lib/tokens.js +99 -15
  87. package/lib/tools.js +142 -37
  88. package/lib/ui-routes/account-routes.js +31 -11
  89. package/lib/ui-routes/admin-config-routes.js +18 -10
  90. package/lib/ui-routes/admin-entities-routes.js +66 -22
  91. package/lib/ui-routes/auth-routes.js +30 -24
  92. package/lib/ui-routes/export-routes.js +10 -4
  93. package/lib/ui-routes/oauth-config-routes.js +5 -5
  94. package/lib/ui-routes/reference-routes.js +3 -3
  95. package/lib/ui-routes/route-helpers.js +51 -2
  96. package/lib/ui-routes/settings-page.js +1 -1
  97. package/lib/ui-routes/smtp-test-routes.js +1 -1
  98. package/lib/ui-routes/suppression-list-routes.js +294 -0
  99. package/lib/ui-routes/unsubscribe-routes.js +19 -29
  100. package/lib/utils/network.js +2 -2
  101. package/lib/web-safe-html.js +1 -1
  102. package/lib/webhook-routing.js +80 -0
  103. package/lib/webhooks.js +20 -14
  104. package/package.json +11 -10
  105. package/sbom.json +1 -1
  106. package/server.js +80 -41
  107. package/static/css/flyonui.css +1 -1
  108. package/static/css/src/app.tailwind.css +136 -9
  109. package/static/js/reference.js +456 -10
  110. package/static/js/ui.js +43 -0
  111. package/static/licenses.html +51 -41
  112. package/translations/messages.pot +59 -59
  113. package/views/accounts/account.hbs +69 -7
  114. package/views/accounts/browse.hbs +18 -35
  115. package/views/config/logging.hbs +6 -0
  116. package/views/config/oauth/app.hbs +0 -2
  117. package/views/config/security.hbs +13 -0
  118. package/views/partials/oauth_form.hbs +0 -15
  119. package/views/partials/reference/disclosure.hbs +8 -2
  120. package/views/partials/reference/operation.hbs +47 -13
  121. package/views/partials/reference/params.hbs +17 -1
  122. package/views/partials/reference/schema-node.hbs +110 -52
  123. package/views/partials/reference/schema-tools.hbs +25 -0
  124. package/views/partials/reference/try-it.hbs +84 -11
  125. package/views/partials/side_menu.hbs +1 -0
  126. package/views/partials/ui/checkbox.hbs +2 -2
  127. package/views/partials/ui/tabs.hbs +7 -1
  128. package/views/reference/token.hbs +4 -0
  129. package/views/suppression-lists/index.hbs +85 -0
  130. package/views/suppression-lists/list.hbs +87 -0
  131. package/views/templates/index.hbs +8 -2
  132. package/views/tokens/index.hbs +31 -4
  133. package/views/tokens/new.hbs +324 -2
  134. package/workers/api.js +146 -57
  135. package/workers/documents.js +46 -26
  136. package/workers/export.js +20 -8
  137. package/workers/imap-proxy.js +2 -2
  138. package/workers/imap.js +12 -6
  139. package/workers/smtp.js +13 -7
  140. package/workers/submit.js +40 -30
  141. package/workers/webhooks.js +59 -25
  142. package/lib/feature-flags.js +0 -48
package/workers/export.js CHANGED
@@ -658,8 +658,7 @@ async function exportMessages(job, exportData) {
658
658
  attempt,
659
659
  maxAttempts: IMAP_MESSAGE_MAX_RETRIES,
660
660
  delayMs: delay,
661
- errorCode: err.code,
662
- errorMessage: err.message
661
+ err
663
662
  });
664
663
  await new Promise(resolve => setTimeout(resolve, delay));
665
664
  continue;
@@ -785,7 +784,13 @@ const exportWorker = new Worker(
785
784
 
786
785
  logger.info({ msg: 'Export job completed', account, exportId, duration: Date.now() - startTime });
787
786
  } catch (err) {
788
- logger.error({ msg: 'Export job failed', account, exportId, err });
787
+ // a user-requested cancellation or a deleted account is not an operational failure
788
+ let failLevel = err.code === 'ExportCancelled' ? 'info' : err.code === 'AccountDeleted' ? 'warn' : 'error';
789
+ logger[failLevel]({ msg: 'Export job failed', account, exportId, err });
790
+
791
+ // Tells the 'failed' handler that this failure has already been reported with full
792
+ // context. Failures that never reach this catch (see that handler) have not been.
793
+ job.__failureLogged = true;
789
794
 
790
795
  const exportData = await redis.hgetall(`${REDIS_PREFIX}exp:${account}:${exportId}`).catch(() => ({}));
791
796
 
@@ -834,22 +839,29 @@ const exportWorker = new Worker(
834
839
 
835
840
  exportWorker.on('completed', async job => {
836
841
  metrics(logger, 'queuesProcessed', 'inc', { queue: 'export', status: 'completed' });
837
- logger.info({ msg: 'Export queue entry completed', queue: job.queue.name, job: job.id, account: job.data.account, exportId: job.data.exportId });
842
+ logger.debug({ msg: 'Export queue entry completed', queue: job.queue.name, job: job.id, account: job.data.account, exportId: job.data.exportId });
838
843
  });
839
844
 
840
845
  exportWorker.on('failed', async (job, err) => {
841
846
  metrics(logger, 'queuesProcessed', 'inc', { queue: 'export', status: 'failed' });
842
847
  if (!job) {
843
- logger.error({ msg: 'Export queue entry failed', err: err.message });
848
+ logger.error({ msg: 'Export queue entry failed', err });
844
849
  return;
845
850
  }
846
- logger.error({
851
+ // A stalled job (worker killed mid-export, lock lost) is failed by BullMQ through its
852
+ // deferred-failure path, which skips the processor entirely - so its catch never logged the
853
+ // failure and never ran Export.fail(). That leaves a dead export recoverable only by the
854
+ // startup pass, and this event is the sole record of it. Anything the processor did report is
855
+ // demoted to debug to avoid logging the same failure twice.
856
+ let level = job.__failureLogged ? 'debug' : 'error';
857
+ logger[level]({
847
858
  msg: 'Export queue entry failed',
848
859
  queue: job.queue.name,
849
860
  job: job.id,
850
861
  account: job.data.account,
851
862
  exportId: job.data.exportId,
852
- failedReason: job.failedReason
863
+ failedReason: job.failedReason,
864
+ reachedProcessor: !!job.__failureLogged
853
865
  });
854
866
  });
855
867
 
@@ -969,4 +981,4 @@ parentPort.on('message', message => {
969
981
  }
970
982
  });
971
983
 
972
- logger.info({ msg: 'Started export worker thread', version: packageData.version });
984
+ logger.info({ msg: 'Started Export worker thread', version: packageData.version });
@@ -59,13 +59,13 @@ parentPort.on('message', message => {
59
59
  run()
60
60
  .then(imapServer => {
61
61
  let address = imapServer.server.address();
62
- logger.debug({
62
+ logger.info({
63
63
  msg: 'Started IMAP proxy server thread',
64
64
  address,
65
65
  version: packageData.version
66
66
  });
67
67
  })
68
68
  .catch(err => {
69
- logger.error({ msg: 'Failed to initialize IMAP server', err });
69
+ logger.fatal({ msg: 'Failed to initialize IMAP proxy server', err });
70
70
  logger.flush(() => process.exit(3));
71
71
  });
package/workers/imap.js CHANGED
@@ -187,7 +187,7 @@ class ConnectionHandler {
187
187
  }
188
188
 
189
189
  async assignConnection(account, runIndex, initOpts) {
190
- logger.info({ msg: 'Assigned account to worker', account });
190
+ logger.debug({ msg: 'Assigned account to worker', account });
191
191
 
192
192
  if (!this.runIndex) {
193
193
  this.runIndex = runIndex;
@@ -306,7 +306,7 @@ class ConnectionHandler {
306
306
 
307
307
  // do not wait before returning as it may take forever
308
308
  accountObject.connection.init(initOpts).catch(err => {
309
- logger.error({ account, err });
309
+ logger.error({ msg: 'Failed to initialize account connection', account, err });
310
310
  });
311
311
  }
312
312
 
@@ -322,7 +322,7 @@ class ConnectionHandler {
322
322
  }
323
323
 
324
324
  async updateConnection(account) {
325
- logger.info({ msg: 'Account reconnect requested', account });
325
+ logger.info({ msg: 'Account update requested', account });
326
326
  if (this.accounts.has(account)) {
327
327
  let accountObject = this.accounts.get(account);
328
328
  if (accountObject.connection) {
@@ -330,7 +330,7 @@ class ConnectionHandler {
330
330
  level: 'info',
331
331
  t: Date.now(),
332
332
  cid: accountObject.connection.cid,
333
- msg: 'Account reconnect requested'
333
+ msg: 'Account update requested'
334
334
  });
335
335
 
336
336
  let state = 'connecting';
@@ -1031,7 +1031,13 @@ parentPort.on('message', message => {
1031
1031
  if (message.message && message.message.data && message.message.data.raw) {
1032
1032
  message.message.data.raw = message.message.data.raw.length;
1033
1033
  }
1034
- logger.error(Object.assign({ msg: 'Command failed' }, message, { err }));
1034
+ // Anything with a client-facing status (404 not found, 503 no active handler) is
1035
+ // reported back to the caller as the command response, so it is not a server fault.
1036
+ // 503 is excluded from the error branch on purpose: both "no active handler" and
1037
+ // IMAPConnectionClosing carry it, and a worker taking over accounts answers every
1038
+ // in-flight command with one until the reassignment settles.
1039
+ let isServerFault = !err.statusCode || (err.statusCode >= 500 && err.statusCode !== 503);
1040
+ logger[isServerFault ? 'error' : 'debug'](Object.assign({ msg: 'Command failed' }, message, { err }));
1035
1041
  parentPort.postMessage(Object.assign({ cmd: 'resp', mid: message.mid }, packRpcError(err)));
1036
1042
  });
1037
1043
  }
@@ -1044,6 +1050,6 @@ parentPort.on('message', message => {
1044
1050
  // server.js instead; see onCommand().
1045
1051
 
1046
1052
  main().catch(err => {
1047
- logger.fatal({ msg: 'Execution failed', err });
1053
+ logger.fatal({ msg: 'IMAP worker startup failed', err });
1048
1054
  logger.flush(() => process.exit(6));
1049
1055
  });
package/workers/smtp.js CHANGED
@@ -124,10 +124,10 @@ async function checkAccountData(session, messageMeta) {
124
124
  accountData = await accountObject.loadAccountData();
125
125
  if (accountData) {
126
126
  ACCOUNT_CACHE.set(session, accountObject);
127
- logger.info({ msg: 'Resolved requested account', account: messageMeta.requestedAccount });
127
+ logger.debug({ msg: 'Resolved requested account', account: messageMeta.requestedAccount });
128
128
  }
129
129
  } catch (err) {
130
- logger.error({ msg: 'Failed resolving requested account', account: messageMeta.requestedAccount, err });
130
+ logger.warn({ msg: 'Failed to resolve requested account', account: messageMeta.requestedAccount, err });
131
131
  }
132
132
  } else {
133
133
  accountObject = ACCOUNT_CACHE.get(session);
@@ -254,7 +254,7 @@ async function init() {
254
254
 
255
255
  logger.info({
256
256
  msg: 'Message queued',
257
- account: session.user,
257
+ account: accountObject.account,
258
258
  messageId: res.messageId,
259
259
  sendAt: res.sendAt,
260
260
  queueId: res.queueId,
@@ -267,7 +267,13 @@ async function init() {
267
267
  metrics(logger, 'events', 'inc', {
268
268
  event: 'smtpSubmitFail'
269
269
  });
270
- logger.error({ msg: 'Failed to submit message', account: session.user, err });
270
+ // a responseCode means the submission was refused with an SMTP reply,
271
+ // which is a client-caused rejection rather than a server fault
272
+ logger[err.responseCode ? 'warn' : 'error']({
273
+ msg: 'Failed to submit message',
274
+ account: session.user || messageMeta.requestedAccount,
275
+ err
276
+ });
271
277
  callback(err);
272
278
  });
273
279
  };
@@ -315,7 +321,7 @@ async function init() {
315
321
  return;
316
322
  }
317
323
  logger.error({
318
- msg: 'SMTP Server Error',
324
+ msg: 'SMTP server error',
319
325
  err
320
326
  });
321
327
  });
@@ -398,13 +404,13 @@ parentPort.on('message', message => {
398
404
  init()
399
405
  .then(smtpServer => {
400
406
  let address = smtpServer.server.address();
401
- logger.debug({
407
+ logger.info({
402
408
  msg: 'Started SMTP server thread',
403
409
  address,
404
410
  version: packageData.version
405
411
  });
406
412
  })
407
413
  .catch(err => {
408
- logger.error({ msg: 'Failed to initialize SMTP', err });
414
+ logger.fatal({ msg: 'Failed to initialize SMTP server', err });
409
415
  logger.flush(() => process.exit(3));
410
416
  });
package/workers/submit.js CHANGED
@@ -16,7 +16,7 @@ initSentry('submit');
16
16
 
17
17
  const util = require('util');
18
18
  const { redis, queueConf, submitQueue } = require('../lib/db');
19
- const { Worker } = require('bullmq');
19
+ const { Worker, UnrecoverableError } = require('bullmq');
20
20
  const { Account } = require('../lib/account');
21
21
  const getSecret = require('../lib/get-secret');
22
22
  const msgpack = require('../lib/msgpack');
@@ -42,7 +42,7 @@ const SUBMIT_QC = (readEnvValue('EENGINE_SUBMIT_QC') && Number(readEnvValue('EEN
42
42
 
43
43
  const SUBMIT_DELAY = getDuration(readEnvValue('EENGINE_SUBMIT_DELAY') || config.submitDelay) || null;
44
44
 
45
- const { shouldDiscardJob } = require('../lib/delivery-error');
45
+ const { shouldDiscardJob, willBeFinalAttempt, isFinalFailedAttempt } = require('../lib/delivery-error');
46
46
  const { packRpcError, unpackRpcError } = require('../lib/worker-rpc-error');
47
47
 
48
48
  let callQueue = new Map();
@@ -157,7 +157,7 @@ const submitWorker = new Worker(
157
157
  try {
158
158
  queueEntry = msgpack.decode(queueEntryBuf);
159
159
  } catch (err) {
160
- logger.error({ msg: 'Failed to parse queued email entry', job: job.data, err });
160
+ logger.error({ msg: 'Failed to parse queued email entry', job: job.id, account: job.data.account, queueId: job.data.queueId, err });
161
161
  try {
162
162
  await redis.hdel(`${REDIS_PREFIX}iaq:${job.data.account}`, job.data.queueId);
163
163
  } catch (err) {
@@ -197,7 +197,7 @@ const submitWorker = new Worker(
197
197
  let backoffDelay = Number(job.opts.backoff && job.opts.backoff.delay) || 0;
198
198
  // job.attemptsMade is not yet incremented for the ongoing attempt, so the
199
199
  // next retry (if this attempt fails) is delayed by 2^attemptsMade * base
200
- let nextAttempt = job.attemptsMade + 1 < job.opts.attempts ? Math.round(job.processedOn + Math.pow(2, job.attemptsMade) * backoffDelay) : false;
200
+ let nextAttempt = !willBeFinalAttempt(job) ? Math.round(job.processedOn + Math.pow(2, job.attemptsMade) * backoffDelay) : false;
201
201
 
202
202
  queueEntry.job = {
203
203
  id: job.id,
@@ -248,13 +248,17 @@ const submitWorker = new Worker(
248
248
  }
249
249
  } catch (err) {
250
250
  logger.error({
251
- msg: 'Job listing failed',
251
+ msg: 'Failed to fetch job status',
252
252
  job: job.id,
253
+ account: job.data.account,
253
254
  err
254
255
  });
255
256
  }
256
257
 
257
- logger.error({
258
+ const discardJob = shouldDiscardJob(err, job);
259
+ const isFinalAttempt = discardJob || willBeFinalAttempt(job);
260
+
261
+ logger[isFinalAttempt ? 'error' : 'warn']({
258
262
  msg: 'Message submission failed',
259
263
  action: 'submit',
260
264
  queue: job.queue.name,
@@ -281,28 +285,30 @@ const submitWorker = new Worker(
281
285
  // ignore
282
286
  }
283
287
 
284
- if (shouldDiscardJob(err, job)) {
285
- try {
286
- // do not retry after 5xx error (except 503 which is transient)
287
- await job.discard();
288
- logger.info({
289
- msg: 'Job discarded',
290
- account: queueEntry.account,
291
- queueId: job.data.queueId
292
- });
293
- } catch (E) {
294
- logger.error({
295
- msg: 'Failed to discard job',
296
- action: 'submit',
297
- queue: job.queue.name,
298
- code: 'discard_fail',
299
- job: job.id,
300
- event: job.name,
301
- data: job.data,
302
- account: job.data.account,
303
- err: E
304
- });
305
- }
288
+ if (discardJob) {
289
+ // Do not retry after a permanent rejection (5xx except 503, which is transient).
290
+ // BullMQ 6 removed Job#discard(), so the way to end a job before its attempts are
291
+ // spent is to throw UnrecoverableError. The stack is carried over because the
292
+ // 'failed' handler reports job.stacktrace[0] as the error in the failure webhook -
293
+ // constructing a bare UnrecoverableError would replace the SMTP reason with
294
+ // "UnrecoverableError" there.
295
+ let unrecoverableErr = new UnrecoverableError(err.message);
296
+ unrecoverableErr.stack = err.stack;
297
+ unrecoverableErr.code = err.code;
298
+ unrecoverableErr.responseCode = err.responseCode;
299
+ unrecoverableErr.statusCode = err.statusCode;
300
+
301
+ logger.info({
302
+ msg: 'Job discarded',
303
+ job: job.id,
304
+ account: queueEntry.account,
305
+ queueId: job.data.queueId,
306
+ messageId: job.data.messageId,
307
+ errorCode: err.code,
308
+ responseCode: err.responseCode
309
+ });
310
+
311
+ throw unrecoverableErr;
306
312
  }
307
313
 
308
314
  throw err;
@@ -369,7 +375,9 @@ submitWorker.on('failed', async job => {
369
375
  status: 'failed'
370
376
  });
371
377
 
372
- if (job.finishedOn || job.discarded) {
378
+ // BullMQ sets finishedOn only when the job is done for good, which covers both exhausting its
379
+ // attempts and being ended early by the UnrecoverableError thrown for a permanent rejection.
380
+ if (job.finishedOn) {
373
381
  // this was final attempt, remove it
374
382
  if (!job.data.queueId && job.data.qId) {
375
383
  // this value was used to be called qId
@@ -403,7 +411,9 @@ submitWorker.on('failed', async job => {
403
411
  }
404
412
  }
405
413
 
406
- logger.info({
414
+ let isFinal = isFinalFailedAttempt(job);
415
+
416
+ logger[isFinal ? 'error' : 'debug']({
407
417
  msg: 'Submission queue entry failed',
408
418
  action: 'submit',
409
419
  queue: job.queue.name,
@@ -10,9 +10,11 @@ const { webhooks: Webhooks } = require('../lib/webhooks');
10
10
 
11
11
  const { GooglePubSub } = require('../lib/oauth/pubsub/google');
12
12
 
13
- const { readEnvValue, threadStats, getDuration, httpAgent, getServiceSecret, maybeReloadHttpProxyAgent } = require('../lib/tools');
13
+ const { readEnvValue, threadStats, getDuration, httpAgent, getServiceSecret, maybeReloadHttpProxyAgent, redactUrlCredentials } = require('../lib/tools');
14
14
  const { sendWebhookRequest } = require('../lib/webhook-request');
15
+ const { willBeFinalAttempt, isFinalFailedAttempt } = require('../lib/delivery-error');
15
16
  const { validateWebhookTarget } = require('../lib/webhook-egress');
17
+ const { resolveTargetUrl, isDeliverableRoute, eventAllowed } = require('../lib/webhook-routing');
16
18
 
17
19
  const { initSentry } = require('../lib/sentry');
18
20
  initSentry('webhooks');
@@ -40,6 +42,11 @@ const NOTIFY_QC = (readEnvValue('EENGINE_NOTIFY_QC') && Number(readEnvValue('EEN
40
42
  // DEFAULT_WEBHOOK_REQUEST_TIMEOUT baked into sendWebhookRequest when unset
41
43
  const WEBHOOK_TIMEOUT = getDuration(readEnvValue('EENGINE_WEBHOOK_TIMEOUT')) || false;
42
44
 
45
+ // Neither of these changes on a retry: the egress policy rejects the same destination every time,
46
+ // and an endpoint configured to redirect keeps redirecting. Such a delivery is final on its first
47
+ // failure, which decides both the log level and whether the remaining attempts are spent.
48
+ const isUnrecoverableWebhookError = err => !!err && (err.code === 'EEGRESSBLOCKED' || err.code === 'EREDIRECTNOTFOLLOWED');
49
+
43
50
  let callQueue = new Map();
44
51
  let mids = 0;
45
52
 
@@ -196,11 +203,18 @@ const notifyWorker = new Worker(
196
203
  //return new Promise((resolve, reject) => {});
197
204
  let accountKey = getAccountKey(job.data.account);
198
205
 
206
+ // Keep the route id reachable for the completed/failed event handlers, which see this same
207
+ // job instance after _route has been deleted from the payload. Stashed before the early
208
+ // returns below so a job that never reaches delivery still reports which route queued it.
209
+ if (job.data._route && job.data._route.id) {
210
+ job.__routeId = job.data._route.id;
211
+ }
212
+
199
213
  // validate if we should even process this webhook
200
214
  let accountExists = await redis.hexists(accountKey, 'account');
201
215
  if (!accountExists && job.name !== ACCOUNT_DELETED_NOTIFY) {
202
216
  logger.debug({
203
- msg: 'Account is not enabled',
217
+ msg: 'Account not found',
204
218
  action: 'webhook',
205
219
  queue: job.queue.name,
206
220
  code: 'account_not_found',
@@ -222,14 +236,15 @@ const notifyWorker = new Worker(
222
236
  customRoute = await Webhooks.getMeta(job.data._route.id);
223
237
  customMapping = job.data._route.mapping;
224
238
  delete job.data._route;
225
- if (!customRoute || !customRoute.enabled || !customRoute.targetUrl) {
239
+ if (!isDeliverableRoute(customRoute)) {
226
240
  return;
227
241
  }
228
242
  }
229
243
 
230
244
  let accountWebhooks = await redis.hget(accountKey, 'webhooks');
231
245
 
232
- let webhooks = (customRoute && customRoute.targetUrl) || accountWebhooks || (await settings.get('webhooks'));
246
+ // the global setting is only fetched when neither a custom route nor the account override decides the target
247
+ let webhooks = resolveTargetUrl(customRoute && customRoute.targetUrl, accountWebhooks, null).url || (await settings.get('webhooks'));
233
248
  if (!webhooks) {
234
249
  // logger.debug({ msg: 'Webhook URL is not set', action: 'webhook', event: job.name, account: job.data.account });
235
250
  return;
@@ -241,12 +256,13 @@ const notifyWorker = new Worker(
241
256
  try {
242
257
  accountWebhooksCustomHeaders = JSON.parse(accountWebhooksCustomHeadersJson);
243
258
  } catch (err) {
259
+ // do not log the header values, they may carry authentication secrets
244
260
  logger.debug({
245
261
  msg: 'Failed to parse custom webhook headers',
246
262
  action: 'webhook',
247
263
  event: job.name,
248
264
  account: job.data.account,
249
- json: accountWebhooksCustomHeadersJson,
265
+ jsonLength: accountWebhooksCustomHeadersJson.length,
250
266
  err
251
267
  });
252
268
  }
@@ -255,7 +271,7 @@ const notifyWorker = new Worker(
255
271
  if (!customRoute) {
256
272
  // custom routes have their own mappings
257
273
  let webhookEvents = (await settings.get('webhookEvents')) || [];
258
- if (!webhookEvents.includes('*') && !webhookEvents.includes(job.name)) {
274
+ if (!eventAllowed(webhookEvents, job.name)) {
259
275
  logger.trace({
260
276
  msg: 'Webhook event not in whitelist',
261
277
  action: 'webhook',
@@ -264,8 +280,7 @@ const notifyWorker = new Worker(
264
280
  job: job.id,
265
281
  event: job.name,
266
282
  account: job.data.account,
267
- webhookEvents,
268
- data: job.data
283
+ webhookEvents
269
284
  });
270
285
  return;
271
286
  }
@@ -331,13 +346,18 @@ const notifyWorker = new Worker(
331
346
  }
332
347
  }
333
348
 
349
+ // never log the raw target URL, it may embed basic auth credentials; keep the redacted
350
+ // form reachable for the failed event handler
351
+ let redactedWebhooks = redactUrlCredentials(webhooks);
352
+ job.__redactedTargetUrl = redactedWebhooks;
353
+
334
354
  logger.trace({
335
355
  msg: 'Processing webhook',
336
356
  action: 'webhook',
337
357
  queue: job.queue.name,
338
358
  code: 'processing',
339
359
  job: job.id,
340
- webhooks,
360
+ webhooks: redactedWebhooks,
341
361
  accountWebhooks: !!accountWebhooks,
342
362
  event: job.name,
343
363
  data: filteredData,
@@ -429,7 +449,7 @@ const notifyWorker = new Worker(
429
449
  queue: job.queue.name,
430
450
  code: 'result_success',
431
451
  job: job.id,
432
- webhooks,
452
+ webhooks: redactedWebhooks,
433
453
  requestBodySize: body.length,
434
454
  accountWebhooks: !!accountWebhooks,
435
455
  event: job.name,
@@ -455,13 +475,16 @@ const notifyWorker = new Worker(
455
475
  status: 'success'
456
476
  });
457
477
  } catch (err) {
458
- logger.error({
478
+ // egress and redirect failures are thrown as UnrecoverableError below, so they are final as well
479
+ let isFinalAttempt = willBeFinalAttempt(job) || isUnrecoverableWebhookError(err);
480
+
481
+ logger[isFinalAttempt ? 'error' : 'warn']({
459
482
  msg: 'Failed posting webhook',
460
483
  action: 'webhook',
461
484
  queue: job.queue.name,
462
485
  code: 'result_fail',
463
486
  job: job.id,
464
- webhooks,
487
+ webhooks: redactedWebhooks,
465
488
  requestBodySize: body.length,
466
489
  accountWebhooks: !!accountWebhooks,
467
490
  event: job.name,
@@ -516,12 +539,14 @@ const notifyWorker = new Worker(
516
539
  status: 'fail'
517
540
  });
518
541
 
519
- // Neither of these changes on a retry: the egress policy rejects the same destination
520
- // every time, and an endpoint configured to redirect keeps redirecting. Spending the
521
- // remaining attempts on them only delays the operator seeing the real reason in the
522
- // error flag. Fail the job now and keep the message.
523
- if (err.code === 'EEGRESSBLOCKED' || err.code === 'EREDIRECTNOTFOLLOWED') {
524
- throw new UnrecoverableError(err.message);
542
+ // Spending the remaining attempts on an unrecoverable failure only delays the operator
543
+ // seeing the real reason in the error flag. Fail the job now and keep the message.
544
+ if (isUnrecoverableWebhookError(err)) {
545
+ // UnrecoverableError copies the message only, and the failed-event handler logs the
546
+ // error it is given, so carry the code over or that log loses the actual reason
547
+ let unrecoverableErr = new UnrecoverableError(err.message);
548
+ unrecoverableErr.code = err.code;
549
+ throw unrecoverableErr;
525
550
  }
526
551
 
527
552
  throw err;
@@ -556,31 +581,40 @@ notifyWorker.on('completed', async job => {
556
581
  status: 'completed'
557
582
  });
558
583
 
559
- logger.info({
584
+ logger.debug({
560
585
  msg: 'Notification queue entry completed',
561
586
  action: 'webhook',
562
587
  queue: job.queue.name,
563
588
  code: 'completed',
564
589
  job: job.id,
590
+ event: job.name,
565
591
  account: job.data.account,
566
- route: job.data._route && job.data._route.id
592
+ // a completed job always ran the processor, which stashes this before any early return
593
+ route: job.__routeId
567
594
  });
568
595
  });
569
596
 
570
- notifyWorker.on('failed', async job => {
597
+ notifyWorker.on('failed', async (job, err) => {
571
598
  metrics(logger, 'queuesProcessed', 'inc', {
572
599
  queue: 'notify',
573
600
  status: 'failed'
574
601
  });
575
602
 
576
- logger.info({
603
+ let isFinal = isFinalFailedAttempt(job);
604
+
605
+ logger[isFinal ? 'error' : 'debug']({
577
606
  msg: 'Notification queue entry failed',
578
607
  action: 'webhook',
579
608
  queue: job.queue.name,
580
609
  code: 'failed',
581
610
  job: job.id,
611
+ event: job.name,
582
612
  account: job.data.account,
583
- route: job.data._route && job.data._route.id,
613
+ // the fallback covers jobs that stalled out before this worker instance ever processed
614
+ // them, where the stash was never set and _route is still in the payload
615
+ route: job.__routeId || (job.data._route && job.data._route.id),
616
+ webhooks: job.__redactedTargetUrl,
617
+ err,
584
618
 
585
619
  failedReason: job.failedReason,
586
620
  stacktrace: job.stacktrace,
@@ -601,10 +635,10 @@ let startRetryTimer = null;
601
635
  let delay;
602
636
  if (attempt < maxNormalAttempts) {
603
637
  delay = Math.min(5000 * Math.pow(2, Math.min(attempt, 10)), 60000);
604
- logger.error({ msg: 'Failed to start processing Google pub/sub', err, attempt: attempt + 1, retryMs: delay });
638
+ logger.warn({ msg: 'Failed to start processing Google pub/sub', err, attempt: attempt + 1, retryMs: delay });
605
639
  } else {
606
640
  delay = 5 * 60 * 1000;
607
- logger.warn({ msg: 'Failed to start processing Google pub/sub (reduced frequency)', err, attempt: attempt + 1, retryMs: delay });
641
+ logger.error({ msg: 'Failed to start processing Google pub/sub (reduced frequency)', err, attempt: attempt + 1, retryMs: delay });
608
642
  }
609
643
  startRetryTimer = setTimeout(() => startGooglePubSub(attempt + 1), delay);
610
644
  });
@@ -1,48 +0,0 @@
1
- 'use strict';
2
-
3
- const logger = require('./logger');
4
-
5
- const FEATURES = new Set();
6
-
7
- const ENABLED_FEATURES = [];
8
-
9
- const formatFeatureKey = key =>
10
- (key || '')
11
- .toString()
12
- .trim()
13
- .toLowerCase()
14
- .replace(/[-_\s]+/g, '_');
15
-
16
- for (let feature of ENABLED_FEATURES) {
17
- FEATURES.add(formatFeatureKey(feature));
18
- }
19
-
20
- for (let key of Object.keys(process.env)) {
21
- if (/^EENGINE_FEATURE_/i.test(key)) {
22
- let feature = formatFeatureKey(key.substring('EENGINE_FEATURE_'.length));
23
- if (feature) {
24
- let value = /^(y|yes|true|t|1)$/i.test((process.env[key] || '').toString().trim());
25
- if (value) {
26
- FEATURES.add(feature);
27
- } else {
28
- FEATURES.delete(feature);
29
- }
30
- }
31
- }
32
- }
33
-
34
- module.exports = {
35
- enabled(key) {
36
- return FEATURES.has(formatFeatureKey(key));
37
- },
38
-
39
- // Sorted list of the currently enabled feature flag keys. Used by the license beacon
40
- // to report which EENGINE_FEATURE_* flags are active on this instance.
41
- listEnabled() {
42
- return Array.from(FEATURES).sort();
43
- }
44
- };
45
-
46
- if (FEATURES.size > 0) {
47
- logger.info({ msg: 'Enabled feature flags', featureFlags: Array.from(FEATURES) });
48
- }