emailengine-app 2.81.1 → 2.82.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 (208) hide show
  1. package/.ncurc.js +12 -6
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +52 -0
  4. package/Dockerfile +4 -2
  5. package/bin/emailengine.js +28 -18
  6. package/config/default.toml +0 -5
  7. package/config/test.toml +0 -5
  8. package/data/google-crawlers.json +1 -1
  9. package/encrypt.js +70 -42
  10. package/getswagger.sh +0 -4
  11. package/lib/account/account-state.js +2 -110
  12. package/lib/account/bounce-store-sweep.js +63 -0
  13. package/lib/account/expected-identity.js +1 -1
  14. package/lib/account-assignment.js +207 -0
  15. package/lib/account.js +374 -878
  16. package/lib/api-reference/index.js +2 -3
  17. package/lib/api-reference/schema-tree.js +53 -3
  18. package/lib/api-routes/account-routes.js +18 -29
  19. package/lib/api-routes/blocklist-routes.js +2 -2
  20. package/lib/api-routes/bull-board-routes.js +1 -6
  21. package/lib/api-routes/export-routes.js +2 -22
  22. package/lib/api-routes/gateway-routes.js +5 -14
  23. package/lib/api-routes/index.js +1 -13
  24. package/lib/api-routes/mailbox-routes.js +2 -7
  25. package/lib/api-routes/mcp-oauth-routes.js +2 -1
  26. package/lib/api-routes/mcp-routes.js +7 -7
  27. package/lib/api-routes/message-routes.js +44 -236
  28. package/lib/api-routes/mint-bounds.js +110 -0
  29. package/lib/api-routes/oauth2-app-routes.js +23 -32
  30. package/lib/api-routes/operation-impact.js +1 -1
  31. package/lib/api-routes/outbox-routes.js +2 -2
  32. package/lib/api-routes/permission-map.js +1 -7
  33. package/lib/api-routes/route-helpers.js +11 -5
  34. package/lib/api-routes/settings-routes.js +19 -19
  35. package/lib/api-routes/stats-routes.js +1 -1
  36. package/lib/api-routes/submit-routes.js +17 -18
  37. package/lib/api-routes/template-routes.js +4 -9
  38. package/lib/api-routes/token-routes.js +27 -5
  39. package/lib/api-token-scheme.js +71 -0
  40. package/lib/arf-detect.js +41 -7
  41. package/lib/auth-token.js +44 -24
  42. package/lib/autodetect-imap-settings.js +163 -123
  43. package/lib/bounce-detect.js +25 -16
  44. package/lib/calendar-event.js +78 -0
  45. package/lib/consts.js +51 -5
  46. package/lib/create-imap-client.js +24 -0
  47. package/lib/db.js +76 -17
  48. package/lib/delivery-error.js +2 -1
  49. package/lib/egress-fetch.js +54 -3
  50. package/lib/egress-filter.js +11 -0
  51. package/lib/email-client/api-retry.js +147 -0
  52. package/lib/email-client/base-client.js +628 -615
  53. package/lib/email-client/gmail/gmail-api.js +38 -125
  54. package/lib/email-client/gmail/send-request.js +1 -1
  55. package/lib/email-client/gmail-client.js +170 -84
  56. package/lib/email-client/imap/mailbox.js +244 -535
  57. package/lib/email-client/imap/stale-view.js +109 -0
  58. package/lib/email-client/imap/subconnection.js +46 -9
  59. package/lib/email-client/imap/sync-operations.js +5 -37
  60. package/lib/email-client/imap-client.js +188 -64
  61. package/lib/email-client/message-builder.js +9 -14
  62. package/lib/email-client/notification-handler.js +5 -219
  63. package/lib/email-client/outlook/graph-api.js +147 -126
  64. package/lib/email-client/outlook/send-request.js +10 -4
  65. package/lib/email-client/outlook-client.js +519 -617
  66. package/lib/email-client/smtp-pool-manager.js +3 -2
  67. package/lib/encrypt.js +184 -19
  68. package/lib/enum-descriptions.js +1 -2
  69. package/lib/export.js +144 -41
  70. package/lib/gateway.js +20 -6
  71. package/lib/get-raw-email.js +26 -44
  72. package/lib/handlebars-helpers.js +31 -10
  73. package/lib/imap-proxy-auth.js +13 -29
  74. package/lib/imapproxy/imap-core/README.md +1 -0
  75. package/lib/imapproxy/imap-core/lib/handler/imap-parser.js +12 -0
  76. package/lib/imapproxy/imap-core/lib/imap-command.js +74 -10
  77. package/lib/imapproxy/imap-core/lib/imap-connection.js +9 -1
  78. package/lib/imapproxy/imap-core/lib/imap-server.js +112 -26
  79. package/lib/imapproxy/imap-core/lib/imap-stream.js +41 -1
  80. package/lib/imapproxy/imap-core/lib/imap-tools.js +10 -2
  81. package/lib/imapproxy/imap-core/lib/indexer/indexer.js +4 -2
  82. package/lib/imapproxy/imap-server.js +17 -177
  83. package/lib/imapproxy/proxy-handoff.js +235 -0
  84. package/lib/imapproxy/response-error.js +33 -0
  85. package/lib/imapproxy/upstream-client.js +2 -2
  86. package/lib/license-beacon.js +3 -9
  87. package/lib/llm-pre-process.js +182 -43
  88. package/lib/logger.js +1 -1
  89. package/lib/lua/ee-export-queue-add.lua +39 -0
  90. package/lib/lua/ee-get-idempotency.lua +15 -3
  91. package/lib/lua/ee-release-attempts.lua +23 -0
  92. package/lib/lua/ee-reserve-attempts.lua +42 -0
  93. package/lib/lua/h-set-bigger.lua +12 -2
  94. package/lib/lua/s-list-accounts.lua +6 -3
  95. package/lib/mcp/index.js +1 -2
  96. package/lib/mcp/listen.js +221 -18
  97. package/lib/mcp/oauth.js +44 -5
  98. package/lib/mcp/resources.js +8 -2
  99. package/lib/mcp/tools.js +13 -0
  100. package/lib/message-port-stream.js +64 -6
  101. package/lib/msgpack.js +1 -6
  102. package/lib/oauth/external-account-signer.js +16 -13
  103. package/lib/oauth/gmail.js +22 -20
  104. package/lib/oauth/outlook.js +19 -16
  105. package/lib/oauth/pubsub/google.js +38 -2
  106. package/lib/oauth/scope-checker.js +4 -7
  107. package/lib/oauth/verify-app.js +2 -2
  108. package/lib/oauth2-apps.js +139 -44
  109. package/lib/openapi/build-document.js +1 -1
  110. package/lib/openapi/joi-schema.js +78 -9
  111. package/lib/parse-message.js +21 -0
  112. package/lib/payload-examples-webhooks.json +4 -7
  113. package/lib/pbkdf2-phc.js +101 -0
  114. package/lib/privileged-settings.js +0 -14
  115. package/lib/rate-limit.js +54 -15
  116. package/lib/redis-scan-delete.js +56 -29
  117. package/lib/redis-url.js +3 -1
  118. package/lib/respawn-backoff.js +5 -4
  119. package/lib/response-stream.js +25 -4
  120. package/lib/rewrite-text-nodes.js +27 -40
  121. package/lib/routes-ui.js +0 -5
  122. package/lib/schemas.js +129 -262
  123. package/lib/sentry.js +21 -5
  124. package/lib/settings.js +58 -59
  125. package/lib/smtp-auth.js +6 -2
  126. package/lib/smtp-message-processor.js +28 -7
  127. package/lib/sso.js +7 -3
  128. package/lib/stream-encrypt.js +14 -13
  129. package/lib/swagger-options.js +3 -1
  130. package/lib/tls/provision.js +69 -3
  131. package/lib/tls/store.js +14 -1
  132. package/lib/tools.js +113 -52
  133. package/lib/totp.js +16 -1
  134. package/lib/ui-routes/account-routes.js +27 -63
  135. package/lib/ui-routes/admin-config-routes.js +111 -134
  136. package/lib/ui-routes/admin-entities-routes.js +101 -191
  137. package/lib/ui-routes/ai-options.js +104 -0
  138. package/lib/ui-routes/auth-routes.js +98 -18
  139. package/lib/ui-routes/export-routes.js +3 -23
  140. package/lib/ui-routes/internals-routes.js +12 -9
  141. package/lib/ui-routes/network-config-routes.js +8 -18
  142. package/lib/ui-routes/oauth-config-routes.js +80 -214
  143. package/lib/ui-routes/route-helpers.js +40 -44
  144. package/lib/ui-routes/unsubscribe-routes.js +2 -2
  145. package/lib/utils/decode-headers.js +32 -5
  146. package/lib/utils/header-map.js +62 -1
  147. package/lib/utils/network.js +2 -0
  148. package/lib/web-safe-html.js +77 -4
  149. package/lib/webhook-request.js +9 -1
  150. package/lib/webhook-routing.js +27 -1
  151. package/lib/webhooks.js +120 -43
  152. package/lib/worker-rpc-error.js +43 -2
  153. package/list-generate.js +13 -2
  154. package/package.json +38 -46
  155. package/sbom.json +1 -1
  156. package/scripts/refresh-test-tokens.js +42 -14
  157. package/server.js +340 -336
  158. package/static/css/flyonui.css +1 -1
  159. package/static/css/src/app.tailwind.css +7 -8
  160. package/static/js/ee-client.js +145 -70
  161. package/static/js/ui.js +350 -154
  162. package/static/licenses.html +460 -1861
  163. package/translations/messages.pot +99 -99
  164. package/views/accounts/browse.hbs +10 -4
  165. package/views/config/ai.hbs +49 -41
  166. package/views/config/oauth/app.hbs +2 -1
  167. package/views/dashboard.hbs +18 -16
  168. package/views/layout/app.hbs +0 -22
  169. package/views/layout/login.hbs +2 -1
  170. package/views/partials/filter_editor_js.hbs +4 -3
  171. package/views/partials/side_menu.hbs +0 -4
  172. package/views/partials/ui/account-picker.hbs +6 -32
  173. package/views/partials/ui/model-picker.hbs +31 -0
  174. package/views/partials/ui/pagination.hbs +6 -1
  175. package/views/partials/ui/picker.hbs +47 -0
  176. package/views/unsubscribe.hbs +1 -1
  177. package/workers/api.js +33 -23
  178. package/workers/export.js +55 -60
  179. package/workers/imap.js +134 -47
  180. package/workers/submit.js +3 -1
  181. package/workers/webhooks.js +46 -27
  182. package/.githooks/pre-commit +0 -80
  183. package/.github/CODE_OF_CONDUCT.md +0 -76
  184. package/.github/contributing.md +0 -17
  185. package/.github/dependabot.yml +0 -22
  186. package/.github/docker-smoke-test.sh +0 -61
  187. package/.github/workflows/deploy.yml +0 -215
  188. package/.github/workflows/e2e.yml +0 -55
  189. package/.github/workflows/release.yaml +0 -217
  190. package/.github/workflows/test.yml +0 -307
  191. package/lib/api-routes/chat-routes.js +0 -535
  192. package/lib/append-list.js +0 -63
  193. package/lib/document-store.js +0 -75
  194. package/lib/es.js +0 -757
  195. package/lib/generate-text-preview.js +0 -61
  196. package/lib/imapproxy/imap-core/memory-notifier.js +0 -129
  197. package/lib/lua/h-push.lua +0 -32
  198. package/lib/pre-process.js +0 -196
  199. package/lib/threads.js +0 -155
  200. package/lib/ui-routes/document-store-routes.js +0 -806
  201. package/playwright.config.js +0 -47
  202. package/views/config/document-store/chat.hbs +0 -286
  203. package/views/config/document-store/index.hbs +0 -146
  204. package/views/config/document-store/mappings/index.hbs +0 -108
  205. package/views/config/document-store/mappings/new.hbs +0 -68
  206. package/views/config/document-store/pre-processing/index.hbs +0 -103
  207. package/views/partials/document_store_header.hbs +0 -30
  208. package/workers/documents.js +0 -1128
@@ -4,9 +4,7 @@ const { threadId: workerThreadId } = require('worker_threads');
4
4
  const crypto = require('crypto');
5
5
  const logger = require('../logger');
6
6
  const settings = require('../settings');
7
- const { isDocumentStoreEnabled } = require('../document-store');
8
7
  const msgpack = require('../msgpack');
9
- const appendList = require('../append-list');
10
8
  const { templates } = require('../templates');
11
9
  const { Gateway } = require('../gateway');
12
10
  const os = require('os');
@@ -18,15 +16,16 @@ const { addTrackers } = require('../add-trackers');
18
16
  const { getRawEmail } = require('../get-raw-email');
19
17
  const { getTemplate } = require('@postalsys/templates');
20
18
  const { deepEqual } = require('assert');
21
- const { arfDetect, camelCaseComplaint } = require('../arf-detect');
19
+ const { arfDetect, camelCaseComplaint, FEEDBACK_REPORT_TYPE, ORIGINAL_MESSAGE_TYPES, COMPLAINT_ATTACHMENT_TYPES } = require('../arf-detect');
22
20
  const { createTransaction } = require('../redis-operations');
23
21
  const { ACCOUNT_STATES } = require('../account/account-state');
24
22
  const { credentialErrorStatus, isTransientCredentialError, resolveAuthServerCredentials } = require('./credential-errors');
25
- const simpleParser = require('mailparser').simpleParser;
23
+ const { parseMessage } = require('../parse-message');
26
24
  const libmime = require('libmime');
27
- const { bounceDetect, applyDeliveryReport } = require('../bounce-detect');
28
- const ical = require('ical.js');
29
- const { llmPreProcess } = require('../llm-pre-process');
25
+ const { bounceDetect, applyDeliveryReport, PARSER_OPTIONS: DSN_PARSER_OPTIONS } = require('../bounce-detect');
26
+ const { parseCalendarEvent, sortCalendarAttachments, CALENDAR_CONTENT_TYPES } = require('../calendar-event');
27
+ const { llmPreProcess, summaryFetchHeaders, summaryProvider } = require('../llm-pre-process');
28
+ const { notificationHeaderFields, narrowHeaders } = require('../utils/header-map');
30
29
  const { oauth2Apps } = require('../oauth2-apps');
31
30
  const { Account } = require('../account');
32
31
  const { removeBcc } = require('../get-raw-email');
@@ -55,7 +54,7 @@ const {
55
54
  getDateBuckets,
56
55
  useAuthServerForOAuth2,
57
56
  collectCidReferences,
58
- cidReferenceRegex
57
+ embedCidImages
59
58
  } = require('../tools');
60
59
 
61
60
  // Import application constants
@@ -76,7 +75,8 @@ const {
76
75
  LAST_ERROR_EVENT_FIELD,
77
76
  AUTH_FAILURE_DISABLED_DESCRIPTION,
78
77
  EMAIL_DELIVERY_ERROR_NOTIFY,
79
- EMAIL_SENT_NOTIFY
78
+ EMAIL_SENT_NOTIFY,
79
+ CHANGE_EVENT_RETRY_DELAYS
80
80
  } = require('../consts');
81
81
  const { buildRetentionPolicy } = require('../queue-retention');
82
82
  const { readImapData } = require('../account/imap-data');
@@ -164,6 +164,74 @@ function applyReferenceRecipients(data, referencedMessage) {
164
164
  }
165
165
  }
166
166
 
167
+ // Message-ids kept in an outgoing References header besides the thread root, so a long thread
168
+ // does not grow the header without bound
169
+ const MAX_REFERENCES_TAIL = 20;
170
+
171
+ /**
172
+ * Builds the References header of a reply or forward (RFC 5322 3.6.4): the parent's References,
173
+ * or its In-Reply-To when it has none, followed by the parent's own Message-ID last. JWZ-style
174
+ * threading reads the last entry as the direct parent, so the order carries meaning. A repeated
175
+ * id keeps its last position, and a long chain is cut to the thread root plus the most recent
176
+ * MAX_REFERENCES_TAIL entries
177
+ * @param {Object} referencedMessage - The message being replied to or forwarded
178
+ * @returns {string[]} Message-ids in angle brackets, in header order
179
+ */
180
+ function buildReferences(referencedMessage) {
181
+ const split = value =>
182
+ []
183
+ .concat(value || [])
184
+ .flatMap(line => (typeof line === 'string' ? line.split(/\s+/) : []))
185
+ .map(ref => ref.trim())
186
+ .filter(ref => ref)
187
+ .map(ref => {
188
+ // Ensure proper Message-ID format
189
+ if (!/^</.test(ref)) {
190
+ ref = '<' + ref;
191
+ }
192
+ if (!/>$/.test(ref)) {
193
+ ref = ref + '>';
194
+ }
195
+ return ref;
196
+ });
197
+
198
+ let chain = split(referencedMessage.headers && referencedMessage.headers.references);
199
+ if (!chain.length) {
200
+ chain = split(referencedMessage.inReplyTo);
201
+ }
202
+ chain = chain.concat(split(referencedMessage.messageId));
203
+
204
+ // Walked from the end, so the last occurrence of a repeated id is the one kept, and pushed
205
+ // then reversed once: the sender controls the length of this header, and an unshift per
206
+ // entry made the dedupe quadratic
207
+ let seen = new Set();
208
+ let references = [];
209
+ for (let i = chain.length - 1; i >= 0; i--) {
210
+ if (!seen.has(chain[i])) {
211
+ seen.add(chain[i]);
212
+ references.push(chain[i]);
213
+ }
214
+ }
215
+ references.reverse();
216
+
217
+ if (references.length > MAX_REFERENCES_TAIL + 1) {
218
+ references = [references[0]].concat(references.slice(-MAX_REFERENCES_TAIL));
219
+ }
220
+
221
+ return references;
222
+ }
223
+
224
+ /**
225
+ * Whether a parsed bounce reports a failed delivery. A DSN also reports delivered, delayed,
226
+ * relayed and expanded recipients, and none of those is a bounce to store or to fire emailBounce
227
+ * for; a delayed DSN that landed in Junk used to reach the bounce path with its action set
228
+ * @param {Object} bounce - Result of bounceDetect()
229
+ * @returns {boolean}
230
+ */
231
+ function isFailedDelivery(bounce) {
232
+ return !!bounce && typeof bounce.action === 'string' && bounce.action.trim().toLowerCase() === 'failed' && !!bounce.recipient && !!bounce.messageId;
233
+ }
234
+
167
235
  // Finds the attachments of a referenced message whose content id the given HTML links to
168
236
  function findReferencedCidAttachments(html, attachments) {
169
237
  let cidAttachments = [];
@@ -307,6 +375,16 @@ async function retryOnTransientError(fn, options = {}) {
307
375
  }
308
376
  }
309
377
 
378
+ /**
379
+ * The next attempt of a deferred change, and how long to wait before it
380
+ * @param {Object} event - A deferred change
381
+ * @returns {{next: Object, delay: number|undefined}} delay is undefined once the attempts are used up
382
+ */
383
+ function nextChangeAttempt(event) {
384
+ const attempt = (event.attempt || 0) + 1;
385
+ return { next: Object.assign({}, event, { attempt }), delay: CHANGE_EVENT_RETRY_DELAYS[attempt - 1] };
386
+ }
387
+
310
388
  /**
311
389
  * Base class for email client implementations
312
390
  * Provides common functionality for IMAP/SMTP operations
@@ -330,8 +408,6 @@ class BaseClient {
330
408
  // Message queue connections
331
409
  this.notifyQueue = this.options.notifyQueue;
332
410
  this.submitQueue = this.options.submitQueue;
333
- this.documentsQueue = this.options.documentsQueue;
334
- this.flowProducer = this.options.flowProducer;
335
411
 
336
412
  // Inter-process communication handler
337
413
  this.call = this.options.call;
@@ -353,12 +429,21 @@ class BaseClient {
353
429
  // already been told
354
430
  this.authSuccessNotified = false;
355
431
 
432
+ // Deferred change retries of the API clients, see deferFailedChangeEvent(). deferredDueAt is
433
+ // when the earliest one is due: undefined until Redis has been asked (so changes deferred
434
+ // before a restart are found), null when none is waiting
435
+ this.deferredDueAt = undefined;
436
+ this.deferredRetryTimer = null;
437
+ // Bumped by cancelDeferredRetryTimer(), so a Redis read already in flight does not
438
+ // overwrite the "ask Redis again" it asked for
439
+ this.deferredEpoch = 0;
440
+ // The deferred change being retried right now, see processDueDeferredEvents()
441
+ this.activeLease = null;
442
+
356
443
  // Initialize notification handler for webhook and event delivery
357
444
  this.notificationHandler = new NotificationHandler({
358
445
  account: this.account,
359
- logger: this.logger,
360
- flowProducer: this.flowProducer,
361
- documentsQueue: this.documentsQueue
446
+ logger: this.logger
362
447
  });
363
448
  }
364
449
 
@@ -388,10 +473,6 @@ class BaseClient {
388
473
  return null;
389
474
  }
390
475
 
391
- async subconnections() {
392
- return [];
393
- }
394
-
395
476
  async getQuota() {
396
477
  return false;
397
478
  }
@@ -430,6 +511,143 @@ class BaseClient {
430
511
  this.initRetryTimer.unref();
431
512
  }
432
513
 
514
+ /**
515
+ * Schedules a retry for a mailbox change the API clients failed to process. Gmail and Graph
516
+ * answer 5xx and time out often enough that dropping the change on the first failure lost a
517
+ * messageNew webhook every few hours on a busy instance, with nothing left to recover it
518
+ * from. Only a failure of the service is retried (the same line the credential paths draw);
519
+ * anything else would fail the same way again. Giving up on new messages or on a recovery pass
520
+ * emits a syncWarning, the only record left that they were never announced
521
+ * @param {Object} event - JSON-serializable change; for `created`, `message` is the message id
522
+ * or an object carrying `id`
523
+ * @param {Error} err - Why it failed
524
+ */
525
+ async deferFailedChangeEvent(event, err) {
526
+ const { next: nextAttempt, delay } = nextChangeAttempt(event);
527
+ const messageIds = event.type === 'created' ? [typeof event.message === 'string' ? event.message : event.message?.id] : undefined;
528
+ const logEntry = { account: this.account, eventType: event.type, messageIds, attempt: nextAttempt.attempt, err };
529
+
530
+ if (delay && isTransientCredentialError(err)) {
531
+ const dueTime = Date.now() + delay;
532
+ // The change being retried right now is already stored as this attempt (its lease),
533
+ // so moving that entry is the deferral
534
+ const lease = this.activeLease?.event === event ? this.activeLease : null;
535
+ try {
536
+ if (lease?.member) {
537
+ await this.accountObject.rescheduleChangeEvent(lease.member, dueTime);
538
+ lease.deferred = true;
539
+ } else {
540
+ await this.accountObject.deferChangeEvent(nextAttempt, dueTime);
541
+ }
542
+ // undefined (unknown, Redis is asked on the next run) stays unknown: something
543
+ // stored earlier may be due before this
544
+ if (this.deferredDueAt === null || dueTime < this.deferredDueAt) {
545
+ this.deferredDueAt = dueTime;
546
+ }
547
+ this.logger.warn({ msg: 'Failed to process mailbox change, retrying later', delay, ...logEntry });
548
+ return;
549
+ } catch (deferErr) {
550
+ this.logger.error({ msg: 'Failed to defer mailbox change', deferErr, ...logEntry });
551
+ }
552
+ }
553
+
554
+ this.logger.error({ msg: 'Failed to process mailbox change, giving up', ...logEntry });
555
+ if (messageIds?.length) {
556
+ await emitChangeEvent(this.logger, this.account, 'syncWarning', {
557
+ type: 'changeSkipped',
558
+ message: 'New messages could not be fetched, no messageNew webhook was sent for them',
559
+ messageIds
560
+ });
561
+ } else if (event.type === 'missedRecovery') {
562
+ await emitChangeEvent(this.logger, this.account, 'syncWarning', {
563
+ type: 'missedRecoveryFailed',
564
+ message: 'Missed change notifications could not be recovered, new messages may not have been announced'
565
+ });
566
+ }
567
+ }
568
+
569
+ /**
570
+ * Runs `handler` for each deferred change that is due. Costs no Redis round trip while nothing
571
+ * is known to be waiting.
572
+ *
573
+ * Before the handler runs, the stored change is swapped for its next attempt, due when that
574
+ * attempt would be (a lease). A worker that dies while handling it finds it again only then
575
+ * and one attempt further along, so a change that kills the worker runs out of attempts
576
+ * instead of taking the worker down on every restart. Deferring the change again moves the
577
+ * lease (see deferFailedChangeEvent()); otherwise the lease is dropped once the handler is done
578
+ * @param {Function} handler - async (event) => void; it defers a failure itself through
579
+ * deferFailedChangeEvent() with the event it was given, and anything it throws is deferred
580
+ * the same way
581
+ */
582
+ async processDueDeferredEvents(handler) {
583
+ if (this.deferredDueAt === null || this.deferredDueAt > Date.now()) {
584
+ return;
585
+ }
586
+
587
+ const epoch = this.deferredEpoch;
588
+ const { due, next } = await this.accountObject.listDueChangeEvents();
589
+ if (epoch === this.deferredEpoch) {
590
+ this.deferredDueAt = next;
591
+ }
592
+
593
+ try {
594
+ for (const { event, member } of due) {
595
+ const lease = nextChangeAttempt(event);
596
+ this.activeLease = {
597
+ event,
598
+ member: await this.accountObject.leaseChangeEvent(member, lease.delay ? lease.next : null, Date.now() + (lease.delay || 0)),
599
+ deferred: false
600
+ };
601
+
602
+ try {
603
+ await handler(event);
604
+ } catch (err) {
605
+ await this.deferFailedChangeEvent(event, err);
606
+ }
607
+
608
+ if (this.activeLease.member && !this.activeLease.deferred) {
609
+ await this.accountObject.completeChangeEvent(this.activeLease.member);
610
+ }
611
+ this.activeLease = null;
612
+ }
613
+ } catch (err) {
614
+ this.activeLease = null;
615
+ // the rest of the batch is still stored, make the next run ask Redis again
616
+ this.deferredDueAt = undefined;
617
+ throw err;
618
+ }
619
+ }
620
+
621
+ /**
622
+ * Arms a timer for the earliest deferred change, called after every processing run. When the
623
+ * due time is unknown (a run failed to read Redis), it checks again in a minute rather than
624
+ * leaving what was deferred to wait for the next notification
625
+ */
626
+ scheduleDeferredRetryTimer() {
627
+ clearTimeout(this.deferredRetryTimer);
628
+ const dueAt = this.deferredDueAt === undefined ? Date.now() + CHANGE_EVENT_RETRY_DELAYS[0] : this.deferredDueAt;
629
+ if (this.closed || !dueAt) {
630
+ return;
631
+ }
632
+
633
+ this.deferredRetryTimer = setTimeout(() => this.retryDeferredEvents(), dueAt - Date.now());
634
+ this.deferredRetryTimer.unref();
635
+ }
636
+
637
+ /**
638
+ * Runs the client's usual change processing, which picks up the deferred changes that are due
639
+ */
640
+ retryDeferredEvents() {
641
+ this.triggerSync();
642
+ }
643
+
644
+ // Also forgets the due time, so the next run asks Redis again
645
+ cancelDeferredRetryTimer() {
646
+ clearTimeout(this.deferredRetryTimer);
647
+ this.deferredDueAt = undefined;
648
+ this.deferredEpoch++;
649
+ }
650
+
433
651
  /**
434
652
  * Drops a pending init() retry, if any
435
653
  */
@@ -506,88 +724,45 @@ class BaseClient {
506
724
  }
507
725
 
508
726
  /**
509
- * Redis hash holding the bounces detected for this account, keyed by the Message-ID of
510
- * the message that bounced. Filled by the new-message processors of every client type
511
- * and read back into the `bounces` field of the message details response
512
- */
513
- getBounceKey() {
514
- return `${REDIS_PREFIX}iar:b:${this.account}`;
515
- }
516
-
517
- /**
518
- * Records a detected bounce against the Message-ID of the message that bounced
519
- * @param {string} bounceMessageId - EmailEngine id of the bounce message itself
520
- * @param {Object} bounce - Parsed bounce (recipient, action, messageId, response)
521
- * @returns {Promise<number|boolean>} appendList.append() result
727
+ * Decides `isBounce` and `relatedMessageId` for fetched message details from the message
728
+ * content, the way processNew() decides them for the messageNew webhook. Nothing is stored:
729
+ * only a message in the Inbox that looks like a bounce is downloaded, and a delivery or delay
730
+ * report is not a bounce, as on the arrival path. A failure is logged and leaves the fields
731
+ * unset rather than failing the fetch
732
+ * @param {Object} messageData - Formatted message details (with `messageSpecialUse` decided), updated in place
733
+ * @param {Function} [getContent] - Supplies the raw message; the IMAP fetch downloads under the lock it already holds
522
734
  */
523
- async storeBounce(bounceMessageId, bounce) {
524
- let storedBounce = {
525
- i: bounceMessageId,
526
- r: bounce.recipient,
527
- t: Date.now(),
528
- a: bounce.action
529
- };
530
-
531
- if (bounce.response && bounce.response.message) {
532
- storedBounce.m = bounce.response.message;
533
- }
534
-
535
- if (bounce.response && bounce.response.status) {
536
- storedBounce.s = bounce.response.status;
735
+ async detectBounce(messageData, getContent = () => this.getRawMessage(messageData.id)) {
736
+ if (messageData.messageSpecialUse !== '\\Inbox' || !this.looksLikeABounce(messageData)) {
737
+ return;
537
738
  }
538
739
 
539
- return await appendList.append(this.redis, this.getBounceKey(), bounce.messageId, storedBounce);
540
- }
541
-
542
- /**
543
- * Lists the bounces recorded for a Message-ID in the shape of the `bounces` response field
544
- * @param {string} messageId - Message-ID header value of the sent message
545
- * @returns {Promise<Object[]>} Bounce entries, empty when none were recorded
546
- */
547
- async listBounces(messageId) {
548
- let rows = await appendList.list(this.redis, this.getBounceKey(), messageId);
549
- return rows.map(row => {
550
- let bounce = {
551
- message: row.i,
552
- recipient: row.r,
553
- action: row.a
554
- };
555
- if (row.m || row.s) {
556
- bounce.response = {};
557
- }
558
- if (row.m) {
559
- bounce.response.message = row.m;
740
+ // The report parser annotates the object it is given, and deliveryReport is not part of
741
+ // the details response, so it gets the log fields instead of the message
742
+ let logContext = { id: messageData.id, uid: messageData.uid, messageId: messageData.messageId };
743
+ let content;
744
+ try {
745
+ content = await getContent();
746
+ if (!content) {
747
+ return;
560
748
  }
561
- if (row.s) {
562
- bounce.response.status = row.s;
749
+
750
+ let parsed = await parseMessage(content, DSN_PARSER_OPTIONS);
751
+ if (applyDeliveryReport(parsed, logContext, this.logger)) {
752
+ return;
563
753
  }
564
- bounce.date = new Date(row.t).toISOString();
565
- return bounce;
566
- });
567
- }
568
754
 
569
- /**
570
- * Adds the recorded bounces to a formatted message, when there are any. A lookup failure
571
- * is logged and leaves the message without the field rather than failing the fetch
572
- * @param {Object} messageData - Formatted message (needs `messageId`), updated in place
573
- */
574
- async attachBounces(messageData) {
575
- if (!messageData || !messageData.messageId) {
576
- return;
577
- }
578
- try {
579
- let bounces = await this.listBounces(messageData.messageId);
580
- if (bounces.length) {
581
- messageData.bounces = bounces;
755
+ let bounce = await bounceDetect({ parsed });
756
+ if (isFailedDelivery(bounce)) {
757
+ messageData.isBounce = true;
758
+ messageData.relatedMessageId = bounce.messageId;
582
759
  }
583
760
  } catch (err) {
584
- this.logger.error({
585
- msg: 'Failed to fetch bounces',
586
- id: messageData.id,
587
- uid: messageData.uid,
588
- messageId: messageData.messageId,
589
- err
590
- });
761
+ // A parser failure leaves an IMAP download unconsumed, and its lock is released only once the stream ends
762
+ if (typeof content?.destroy === 'function') {
763
+ content.destroy();
764
+ }
765
+ this.logger.error(Object.assign({ msg: 'Failed to detect bounce', err }, logContext));
591
766
  }
592
767
  }
593
768
 
@@ -1148,7 +1323,7 @@ class BaseClient {
1148
1323
  * @param {Object} data - Event data payload
1149
1324
  * @param {Object} extraOpts - Additional options
1150
1325
  */
1151
- async notify(mailbox, event, data, extraOpts) {
1326
+ async notify(mailbox, event, data) {
1152
1327
  // Handle error state tracking for connection/auth errors
1153
1328
  // This is BaseClient-specific logic that must run before notification
1154
1329
  switch (event) {
@@ -1164,8 +1339,8 @@ class BaseClient {
1164
1339
  }
1165
1340
  }
1166
1341
 
1167
- // Delegate to notification handler for webhook and document store delivery
1168
- await this.notificationHandler.notify(mailbox, event, data, extraOpts);
1342
+ // Delegate to notification handler for webhook delivery
1343
+ await this.notificationHandler.notify(mailbox, event, data);
1169
1344
  }
1170
1345
 
1171
1346
  /**
@@ -1297,47 +1472,42 @@ class BaseClient {
1297
1472
  * @returns {Object} Final delegated account data
1298
1473
  */
1299
1474
  async getDelegatedAccount(accountData) {
1300
- let redirect = 0;
1301
1475
  let providerAccountData = accountData;
1302
- let delegatedAccountData;
1303
- let seenAccounts = new Set();
1304
- let hopsAllowed = 20;
1476
+ let seenAccounts = new Set([accountData.account]);
1477
+ const hopsAllowed = 20;
1478
+
1479
+ // Follow delegation chain. Each hop is built from the account the previous hop resolved
1480
+ // to - building it from the original account reloaded the first hop on every pass, so a
1481
+ // valid A->B->C chain was reported as a loop
1482
+ for (let hop = 0; hop < hopsAllowed; hop++) {
1483
+ const nextAccount = providerAccountData.oauth2.auth.delegatedAccount;
1484
+
1485
+ // Detect delegation loops
1486
+ if (seenAccounts.has(nextAccount)) {
1487
+ throw new Error('Delegation looping detected');
1488
+ }
1489
+ seenAccounts.add(nextAccount);
1305
1490
 
1306
- // Follow delegation chain
1307
- while (redirect++ < hopsAllowed) {
1308
1491
  // Load delegated account if not cached
1309
- if (!this.delegatedAccountObject || this.delegatedAccountObject.account !== providerAccountData.oauth2.auth.delegatedAccount) {
1492
+ if (!this.delegatedAccountObject || this.delegatedAccountObject.account !== nextAccount) {
1310
1493
  this.delegatedAccountObject = new Account({
1311
- account: accountData.oauth2.auth.delegatedAccount,
1494
+ account: nextAccount,
1312
1495
  redis: this.accountObject.redis,
1313
1496
  call: this.accountObject.call,
1314
1497
  secret: this.accountObject.secret,
1315
1498
  timeout: this.accountObject.timeout
1316
1499
  });
1317
1500
  }
1318
- delegatedAccountData = await this.delegatedAccountObject.loadAccountData();
1501
+ const delegatedAccountData = await this.delegatedAccountObject.loadAccountData();
1319
1502
 
1320
1503
  // Check if this account also delegates to another
1321
- if (delegatedAccountData.oauth2.auth.delegatedUser && delegatedAccountData.oauth2.auth.delegatedAccount) {
1322
- // Detect delegation loops
1323
- if (seenAccounts.has(providerAccountData.account)) {
1324
- // loop detected
1325
- let error = new Error('Delegation looping detected');
1326
- throw error;
1327
- }
1328
- seenAccounts.add(providerAccountData.account);
1329
- providerAccountData = delegatedAccountData;
1330
- continue;
1504
+ if (!(delegatedAccountData.oauth2?.auth?.delegatedUser && delegatedAccountData.oauth2.auth.delegatedAccount)) {
1505
+ return delegatedAccountData;
1331
1506
  }
1332
- break;
1333
- }
1334
-
1335
- if (redirect >= hopsAllowed) {
1336
- let error = new Error('Too many delegation hops');
1337
- throw error;
1507
+ providerAccountData = delegatedAccountData;
1338
1508
  }
1339
1509
 
1340
- return delegatedAccountData;
1510
+ throw new Error('Too many delegation hops');
1341
1511
  }
1342
1512
 
1343
1513
  /**
@@ -1561,11 +1731,9 @@ class BaseClient {
1561
1731
  let gatewayObject;
1562
1732
  if (data.gateway) {
1563
1733
  gatewayObject = new Gateway({ gateway: data.gateway, redis: this.redis, secret: this.secret });
1564
- try {
1565
- gatewayData = await gatewayObject.loadGatewayData();
1566
- } catch (err) {
1567
- this.logger.warn({ msg: 'Failed to load gateway data', messageId: data.messageId, gateway: data.gateway, err });
1568
- }
1734
+ // The message was asked to go through this gateway, so it must not fall through to
1735
+ // the account's own SMTP server: a missing gateway throws GatewayNotFound (404)
1736
+ gatewayData = await gatewayObject.loadGatewayData();
1569
1737
  }
1570
1738
 
1571
1739
  // Verify SMTP capability
@@ -1748,88 +1916,62 @@ class BaseClient {
1748
1916
  delete data.tz;
1749
1917
 
1750
1918
  let referencedMessage;
1751
- let documentStoreUsed = false;
1752
1919
 
1753
1920
  // Resolve reference and update reference/in-reply-to headers
1754
1921
  if (data.reference && data.reference.message) {
1755
- // Try document store first if enabled
1756
- if (data.reference.documentStore && (await isDocumentStoreEnabled())) {
1757
- try {
1758
- referencedMessage = await this.accountObject.getMessage(data.reference.message, {
1759
- documentStore: true,
1760
- textType: '*'
1922
+ // Fetch from IMAP/API with retry logic for transient errors
1923
+ let extendedData = data.reference.inline || data.reference.forwardAttachments;
1924
+
1925
+ try {
1926
+ referencedMessage = await retryOnTransientError(
1927
+ async () => {
1928
+ return await this.getMessage(
1929
+ data.reference.message,
1930
+ {
1931
+ fields: !extendedData
1932
+ ? {
1933
+ uid: true,
1934
+ flags: true,
1935
+ envelope: true,
1936
+ headers: ['references']
1937
+ }
1938
+ : false,
1939
+ textType: extendedData ? '*' : false
1940
+ },
1941
+ connectionOptions
1942
+ );
1943
+ },
1944
+ {
1945
+ maxAttempts: 3,
1946
+ baseDelay: 1000,
1947
+ logger: this.logger
1948
+ }
1949
+ );
1950
+ } catch (err) {
1951
+ // Check if this is a transient error that exhausted retries
1952
+ const isTransient = isTransientError(err);
1953
+
1954
+ if (isTransient && data.reference.ignoreMissing) {
1955
+ // Transient error but ignoreMissing is true - log and continue without reference
1956
+ this.logger.warn({
1957
+ msg: 'Failed to fetch referenced message due to transient error, continuing without reference',
1958
+ messageId: data.reference.message,
1959
+ err,
1960
+ statusCode: err.statusCode || (err.oauthRequest && err.oauthRequest.status)
1761
1961
  });
1762
- } catch (err) {
1763
- if (err.meta && err.meta.statusCode === 404) {
1764
- // not found
1765
- } else {
1766
- let error = new Error('ElasticSearch request failed');
1767
- error.info = {
1768
- response: (err.meta && err.meta.body) || err.message,
1769
- statusCode: err.meta && err.meta.statusCode
1770
- };
1771
- error.code = 'ESRequestError';
1772
- error.statusCode = (err.meta && err.meta.statusCode) || 500;
1962
+ referencedMessage = null;
1963
+ } else if (!isTransient && err.statusCode === 404) {
1964
+ // Permanent 404 error - respect ignoreMissing
1965
+ if (!data.reference.ignoreMissing) {
1966
+ let error = new Error('Referenced message was not found');
1967
+ error.code = 'ReferenceNotFound';
1968
+ error.statusCode = 404;
1773
1969
  throw error;
1774
1970
  }
1775
- }
1776
- documentStoreUsed = true;
1777
- } else {
1778
- // Fetch from IMAP/API with retry logic for transient errors
1779
- let extendedData = data.reference.inline || data.reference.forwardAttachments;
1780
-
1781
- try {
1782
- referencedMessage = await retryOnTransientError(
1783
- async () => {
1784
- return await this.getMessage(
1785
- data.reference.message,
1786
- {
1787
- fields: !extendedData
1788
- ? {
1789
- uid: true,
1790
- flags: true,
1791
- envelope: true,
1792
- headers: ['references']
1793
- }
1794
- : false,
1795
- header: extendedData ? true : false,
1796
- textType: extendedData ? '*' : false
1797
- },
1798
- connectionOptions
1799
- );
1800
- },
1801
- {
1802
- maxAttempts: 3,
1803
- baseDelay: 1000,
1804
- logger: this.logger
1805
- }
1806
- );
1807
- } catch (err) {
1808
- // Check if this is a transient error that exhausted retries
1809
- const isTransient = isTransientError(err);
1810
-
1811
- if (isTransient && data.reference.ignoreMissing) {
1812
- // Transient error but ignoreMissing is true - log and continue without reference
1813
- this.logger.warn({
1814
- msg: 'Failed to fetch referenced message due to transient error, continuing without reference',
1815
- messageId: data.reference.message,
1816
- err,
1817
- statusCode: err.statusCode || (err.oauthRequest && err.oauthRequest.status)
1818
- });
1819
- referencedMessage = null;
1820
- } else if (!isTransient && err.statusCode === 404) {
1821
- // Permanent 404 error - respect ignoreMissing
1822
- if (!data.reference.ignoreMissing) {
1823
- let error = new Error('Referenced message was not found');
1824
- error.code = 'ReferenceNotFound';
1825
- error.statusCode = 404;
1826
- throw error;
1827
- }
1828
- referencedMessage = null;
1829
- } else {
1830
- // Either transient error with ignoreMissing=false, or other permanent error
1831
- throw err;
1832
- }
1971
+ referencedMessage = null;
1972
+ } else {
1973
+ // Either transient error with ignoreMissing=false, or other permanent error
1974
+ throw err;
1833
1975
  }
1834
1976
  }
1835
1977
 
@@ -1850,25 +1992,7 @@ class BaseClient {
1850
1992
  }
1851
1993
 
1852
1994
  // Build references header chain
1853
- let references = []
1854
- .concat(referencedMessage.messageId || [])
1855
- .concat(referencedMessage.inReplyTo || [])
1856
- .concat((referencedMessage.headers && referencedMessage.headers.references) || [])
1857
- .flatMap(line => line.split(/\s+/))
1858
- .map(ref => ref.trim())
1859
- .filter(ref => ref)
1860
- .map(ref => {
1861
- // Ensure proper Message-ID format
1862
- if (!/^</.test(ref)) {
1863
- ref = '<' + ref;
1864
- }
1865
- if (!/>$/.test(ref)) {
1866
- ref = ref + '>';
1867
- }
1868
- return ref;
1869
- });
1870
-
1871
- references = Array.from(new Set(references));
1995
+ let references = buildReferences(referencedMessage);
1872
1996
  if (references.length) {
1873
1997
  if (!data.headers) {
1874
1998
  data.headers = {};
@@ -2043,7 +2167,7 @@ class BaseClient {
2043
2167
  // Generate raw MIME message
2044
2168
  let { raw, emailObject, messageId } = await getRawEmail(data, null, options);
2045
2169
 
2046
- return { raw, emailObject, messageId, documentStoreUsed, referencedMessage };
2170
+ return { raw, emailObject, messageId, referencedMessage };
2047
2171
  }
2048
2172
 
2049
2173
  /**
@@ -2185,90 +2309,64 @@ class BaseClient {
2185
2309
  }
2186
2310
 
2187
2311
  let referencedMessage;
2188
- let documentStoreUsed = false;
2189
2312
 
2190
2313
  // Resolve reference and update reference/in-reply-to headers
2191
2314
  if (data.reference && data.reference.message) {
2192
- // Try document store first if enabled
2193
- if (data.reference.documentStore && (await isDocumentStoreEnabled())) {
2194
- try {
2195
- referencedMessage = await this.accountObject.getMessage(data.reference.message, {
2196
- documentStore: true,
2197
- textType: '*'
2198
- });
2199
- } catch (err) {
2200
- if (err.meta && err.meta.statusCode === 404) {
2201
- // not found
2202
- } else {
2203
- let error = new Error('ElasticSearch request failed');
2204
- error.info = {
2205
- response: (err.meta && err.meta.body) || err.message,
2206
- statusCode: err.meta && err.meta.statusCode
2207
- };
2208
- error.code = 'ESRequestError';
2209
- error.statusCode = (err.meta && err.meta.statusCode) || 500;
2210
- throw error;
2211
- }
2212
- }
2213
- documentStoreUsed = true;
2214
- } else {
2215
- // Fetch from IMAP/API with retry logic for transient errors
2216
- this.checkIMAPConnection(connectionOptions);
2315
+ // Fetch from IMAP/API with retry logic for transient errors
2316
+ this.checkIMAPConnection(connectionOptions);
2217
2317
 
2218
- let extendedData = data.reference.inline || data.reference.forwardAttachments;
2318
+ let extendedData = data.reference.inline || data.reference.forwardAttachments;
2219
2319
 
2220
- try {
2221
- referencedMessage = await retryOnTransientError(
2222
- async () => {
2223
- return await this.getMessage(
2224
- data.reference.message,
2225
- {
2226
- fields: !extendedData
2227
- ? {
2228
- uid: true,
2229
- flags: true,
2230
- envelope: true,
2231
- headers: ['references']
2232
- }
2233
- : false,
2234
- header: extendedData ? true : false,
2235
- textType: extendedData ? '*' : false
2236
- },
2237
- connectionOptions
2238
- );
2239
- },
2240
- {
2241
- maxAttempts: 3,
2242
- baseDelay: 1000,
2243
- logger: this.logger
2244
- }
2245
- );
2246
- } catch (err) {
2247
- // Check if this is a transient error that exhausted retries
2248
- const isTransient = isTransientError(err);
2249
-
2250
- if (isTransient && data.reference.ignoreMissing) {
2251
- // Transient error but ignoreMissing is true - log and continue without reference
2252
- this.logger.warn({
2253
- msg: 'Failed to fetch referenced message due to transient error, continuing without reference',
2254
- messageId: data.reference.message,
2255
- err,
2256
- statusCode: err.statusCode || (err.oauthRequest && err.oauthRequest.status)
2257
- });
2258
- referencedMessage = null;
2259
- } else if (!isTransient && err.statusCode === 404) {
2260
- // Permanent 404 error - respect ignoreMissing
2261
- if (!data.reference.ignoreMissing) {
2262
- let error = new Error('Referenced message was not found');
2263
- error.code = 'ReferenceNotFound';
2264
- error.statusCode = 404;
2265
- throw error;
2266
- }
2267
- referencedMessage = null;
2268
- } else {
2269
- // Either transient error with ignoreMissing=false, or other permanent error
2270
- throw err;
2320
+ try {
2321
+ referencedMessage = await retryOnTransientError(
2322
+ async () => {
2323
+ return await this.getMessage(
2324
+ data.reference.message,
2325
+ {
2326
+ fields: !extendedData
2327
+ ? {
2328
+ uid: true,
2329
+ flags: true,
2330
+ envelope: true,
2331
+ headers: ['references']
2332
+ }
2333
+ : false,
2334
+ textType: extendedData ? '*' : false
2335
+ },
2336
+ connectionOptions
2337
+ );
2338
+ },
2339
+ {
2340
+ maxAttempts: 3,
2341
+ baseDelay: 1000,
2342
+ logger: this.logger
2271
2343
  }
2344
+ );
2345
+ } catch (err) {
2346
+ // Check if this is a transient error that exhausted retries
2347
+ const isTransient = isTransientError(err);
2348
+
2349
+ if (isTransient && data.reference.ignoreMissing) {
2350
+ // Transient error but ignoreMissing is true - log and continue without reference
2351
+ this.logger.warn({
2352
+ msg: 'Failed to fetch referenced message due to transient error, continuing without reference',
2353
+ messageId: data.reference.message,
2354
+ err,
2355
+ statusCode: err.statusCode || (err.oauthRequest && err.oauthRequest.status)
2356
+ });
2357
+ referencedMessage = null;
2358
+ } else if (!isTransient && err.statusCode === 404) {
2359
+ // Permanent 404 error - respect ignoreMissing
2360
+ if (!data.reference.ignoreMissing) {
2361
+ let error = new Error('Referenced message was not found');
2362
+ error.code = 'ReferenceNotFound';
2363
+ error.statusCode = 404;
2364
+ throw error;
2365
+ }
2366
+ referencedMessage = null;
2367
+ } else {
2368
+ // Either transient error with ignoreMissing=false, or other permanent error
2369
+ throw err;
2272
2370
  }
2273
2371
  }
2274
2372
 
@@ -2289,25 +2387,7 @@ class BaseClient {
2289
2387
  }
2290
2388
 
2291
2389
  // Build references header chain
2292
- let references = []
2293
- .concat(referencedMessage.messageId || [])
2294
- .concat(referencedMessage.inReplyTo || [])
2295
- .concat((referencedMessage.headers && referencedMessage.headers.references) || [])
2296
- .flatMap(line => line.split(/\s+/))
2297
- .map(ref => ref.trim())
2298
- .filter(ref => ref)
2299
- .map(ref => {
2300
- // Ensure proper Message-ID format
2301
- if (!/^</.test(ref)) {
2302
- ref = '<' + ref;
2303
- }
2304
- if (!/>$/.test(ref)) {
2305
- ref = ref + '>';
2306
- }
2307
- return ref;
2308
- });
2309
-
2310
- references = Array.from(new Set(references));
2390
+ let references = buildReferences(referencedMessage);
2311
2391
  if (references.length) {
2312
2392
  if (!data.headers) {
2313
2393
  data.headers = {};
@@ -2496,7 +2576,6 @@ class BaseClient {
2496
2576
  response.reference = {};
2497
2577
  if (data.reference.message) {
2498
2578
  response.reference.message = data.reference.message;
2499
- response.reference.documentStore = documentStoreUsed;
2500
2579
  response.reference.success = referencedMessage ? true : false;
2501
2580
  if (!referencedMessage) {
2502
2581
  response.reference.error = 'Referenced message was not found';
@@ -2516,11 +2595,9 @@ class BaseClient {
2516
2595
  let gatewayData;
2517
2596
  if (gateway) {
2518
2597
  let gatewayObject = new Gateway({ gateway, redis: this.redis, secret: this.secret });
2519
- try {
2520
- gatewayData = await gatewayObject.loadGatewayData();
2521
- } catch (err) {
2522
- this.logger.warn({ msg: 'Failed to load gateway data', envelope, messageId, gateway, err });
2523
- }
2598
+ // never fall through to the account's own SMTP server when a gateway was requested:
2599
+ // a missing gateway throws GatewayNotFound (404)
2600
+ gatewayData = await gatewayObject.loadGatewayData();
2524
2601
  }
2525
2602
 
2526
2603
  // Verify SMTP capability
@@ -2567,7 +2644,6 @@ class BaseClient {
2567
2644
  response.reference = {};
2568
2645
  if (data.reference.message) {
2569
2646
  response.reference.message = data.reference.message;
2570
- response.reference.documentStore = documentStoreUsed;
2571
2647
  response.reference.success = referencedMessage ? true : false;
2572
2648
  if (!referencedMessage) {
2573
2649
  response.reference.error = 'Referenced message was not found';
@@ -2741,11 +2817,9 @@ class BaseClient {
2741
2817
  let gatewayData;
2742
2818
  if (gateway) {
2743
2819
  let gatewayObject = new Gateway({ gateway, redis: this.redis, secret: this.secret });
2744
- try {
2745
- gatewayData = await gatewayObject.loadGatewayData();
2746
- } catch (err) {
2747
- this.logger.warn({ msg: 'Failed to load gateway data', envelope, messageId, gateway, err });
2748
- }
2820
+ // never fall through to the account's own SMTP server when a gateway was requested:
2821
+ // a missing gateway throws GatewayNotFound (404)
2822
+ gatewayData = await gatewayObject.loadGatewayData();
2749
2823
  }
2750
2824
 
2751
2825
  // Verify SMTP capability
@@ -2875,6 +2949,12 @@ class BaseClient {
2875
2949
  * Gets message fetch options based on settings
2876
2950
  * @returns {Object} Fetch options for IMAP message retrieval
2877
2951
  */
2952
+ // The provider behind this client, for the AI summary's authentication trust rule: the Gmail
2953
+ // and Outlook API clients each set their type, and nothing else is reachable through an API
2954
+ summaryProvider() {
2955
+ return summaryProvider({ isGmail: this.type === 'gmail', isOutlook: this.type === 'outlook' });
2956
+ }
2957
+
2878
2958
  async getMessageFetchOptions() {
2879
2959
  let messageFetchOptions = {};
2880
2960
 
@@ -2895,24 +2975,11 @@ class BaseClient {
2895
2975
  messageFetchOptions.headers = notifyHeaders.includes('*') ? true : notifyHeaders.length ? notifyHeaders : false;
2896
2976
  }
2897
2977
 
2898
- // also request autoresponse headers
2978
+ // Also request the headers this path needs for its own processing, and the summary's
2979
+ // while summaries are on. Skipped when the setting already asks for every header
2899
2980
  if (messageFetchOptions.headers !== true) {
2900
- let fetchHeaders = new Set(messageFetchOptions.headers || []);
2901
-
2902
- // Headers for auto-reply detection
2903
- fetchHeaders.add('x-autoreply');
2904
- fetchHeaders.add('x-autorespond');
2905
- fetchHeaders.add('auto-submitted');
2906
- fetchHeaders.add('precedence');
2907
-
2908
- // Headers for threading
2909
- fetchHeaders.add('in-reply-to');
2910
- fetchHeaders.add('references');
2911
-
2912
- // Content type for detecting multipart/report
2913
- fetchHeaders.add('content-type');
2914
-
2915
- messageFetchOptions.fetchHeaders = Array.from(fetchHeaders);
2981
+ const summaryHeaders = (await llmPreProcess.getPreProcessHandler()) ? summaryFetchHeaders(this.summaryProvider()) : [];
2982
+ messageFetchOptions.fetchHeaders = notificationHeaderFields(messageFetchOptions.headers, summaryHeaders);
2916
2983
  }
2917
2984
 
2918
2985
  return messageFetchOptions;
@@ -2936,8 +3003,8 @@ class BaseClient {
2936
3003
  if (this.mightBeAComplaint(messageData)) {
2937
3004
  try {
2938
3005
  // Download attachments needed for complaint detection
2939
- for (let attachment of messageData.attachments) {
2940
- if (!['message/feedback-report', 'message/rfc822-headers', 'message/rfc822'].includes(attachment.contentType)) {
3006
+ for (let attachment of messageData.attachments || []) {
3007
+ if (!COMPLAINT_ATTACHMENT_TYPES.includes(attachment.contentType)) {
2941
3008
  continue;
2942
3009
  }
2943
3010
 
@@ -2979,7 +3046,7 @@ class BaseClient {
2979
3046
  try {
2980
3047
  let raw = await this.getRawMessage(messageData.id);
2981
3048
 
2982
- let parsed = await simpleParser(raw, { keepDeliveryStatus: true });
3049
+ let parsed = await parseMessage(raw, DSN_PARSER_OPTIONS);
2983
3050
  if (parsed) {
2984
3051
  content = { parsed };
2985
3052
  applyDeliveryReport(parsed, messageData, this.logger);
@@ -3037,11 +3104,7 @@ class BaseClient {
3037
3104
  }
3038
3105
  }
3039
3106
 
3040
- let stored = 0;
3041
- if (bounce.action && bounce.recipient && bounce.messageId) {
3042
- // Record it for the `bounces` field of the bounced message, as the IMAP path does
3043
- stored = await this.storeBounce(messageData.id, bounce);
3044
-
3107
+ if (isFailedDelivery(bounce)) {
3045
3108
  bounceNotifyInfo = Object.assign({ bounceMessage: messageData.id }, bounce);
3046
3109
 
3047
3110
  messageData.isBounce = true;
@@ -3053,8 +3116,7 @@ class BaseClient {
3053
3116
  id: messageData.id,
3054
3117
  uid: messageData.uid,
3055
3118
  messageId: messageData.messageId,
3056
- bounce,
3057
- stored
3119
+ bounce
3058
3120
  });
3059
3121
  }
3060
3122
  } catch (err) {
@@ -3112,22 +3174,9 @@ class BaseClient {
3112
3174
  if (notifyCalendarEvents && messageData.attachments && messageData.attachments.length) {
3113
3175
  let calendarEventMap = new Map();
3114
3176
 
3115
- // when iterating the attachment array, process text/calendar before application/ics
3116
- let sortCalendarAttachments = (a, b) => {
3117
- if (a.contentType !== b.contentType) {
3118
- if (a.contentType === 'text/calendar') {
3119
- return -1;
3120
- }
3121
- if (b.contentType === 'text/calendar') {
3122
- return 1;
3123
- }
3124
- }
3125
- return a.contentType.localeCompare(b.contentType);
3126
- };
3127
-
3128
- // Process calendar attachments
3177
+ // Process calendar attachments, text/calendar before application/ics
3129
3178
  for (let attachment of [...messageData.attachments].sort(sortCalendarAttachments)) {
3130
- if (['text/calendar', 'application/ics'].includes(attachment.contentType)) {
3179
+ if (CALENDAR_CONTENT_TYPES.includes(attachment.contentType)) {
3131
3180
  if (!attachment.content) {
3132
3181
  try {
3133
3182
  let calendarBuf = (await this.getAttachment(attachment.id))?.data;
@@ -3139,33 +3188,15 @@ class BaseClient {
3139
3188
  if (attachment.content) {
3140
3189
  let contentBuf = Buffer.from(attachment.content, 'base64');
3141
3190
  try {
3142
- // Parse iCalendar data
3143
- const jcalData = ical.parse(contentBuf.toString());
3144
-
3145
- const comp = new ical.Component(jcalData);
3146
- if (!comp) {
3147
- continue;
3148
- }
3149
-
3150
- const vevent = comp.getFirstSubcomponent('vevent');
3151
- if (!vevent) {
3152
- continue;
3153
- }
3154
-
3155
- // Extract method (REQUEST, CANCEL, etc.)
3156
- let eventMethodProp = comp.getFirstProperty('method');
3157
- let eventMethodValue = eventMethodProp ? eventMethodProp.getFirstValue() : null;
3158
-
3159
- const event = new ical.Event(vevent);
3160
-
3161
- if (!event || !event.uid) {
3191
+ const event = parseCalendarEvent(contentBuf);
3192
+ if (!event) {
3162
3193
  continue;
3163
3194
  }
3164
3195
 
3165
3196
  // Skip if we already processed this event
3166
- if (calendarEventMap.has(event.uid)) {
3197
+ if (calendarEventMap.has(event.eventId)) {
3167
3198
  if (attachment.filename) {
3168
- let existingEntry = calendarEventMap.get(event.uid);
3199
+ let existingEntry = calendarEventMap.get(event.eventId);
3169
3200
  if (!existingEntry.filename) {
3170
3201
  // inject filename
3171
3202
  existingEntry.filename = attachment.filename;
@@ -3174,31 +3205,20 @@ class BaseClient {
3174
3205
  continue;
3175
3206
  }
3176
3207
 
3177
- // Extract timezone information
3178
- let timezone;
3179
- const vtz = comp.getFirstSubcomponent('vtimezone');
3180
- if (vtz) {
3181
- const tz = new ical.Timezone(vtz);
3182
- timezone = tz && tz.tzid;
3183
- }
3184
-
3185
- let startDate = event.startDate && event.startDate.toJSDate();
3186
- let endDate = event.endDate && event.endDate.toJSDate();
3187
-
3188
3208
  // Store calendar event data
3189
3209
  calendarEventMap.set(
3190
- event.uid,
3210
+ event.eventId,
3191
3211
  filterEmptyObjectValues({
3192
- eventId: event.uid,
3212
+ eventId: event.eventId,
3193
3213
  attachment: attachment.id,
3194
- method: attachment.method || eventMethodValue || null,
3214
+ method: attachment.method || event.method || null,
3195
3215
 
3196
- summary: event.summary || null,
3197
- description: event.description || null,
3198
- timezone: timezone || null,
3199
- startDate: startDate ? startDate.toISOString() : null,
3200
- endDate: endDate ? endDate.toISOString() : null,
3201
- organizer: event.organizer && typeof event.organizer === 'string' ? event.organizer : null,
3216
+ summary: event.summary,
3217
+ description: event.description,
3218
+ timezone: event.timezone,
3219
+ startDate: event.startDate,
3220
+ endDate: event.endDate,
3221
+ organizer: event.organizer,
3202
3222
 
3203
3223
  filename: attachment.filename,
3204
3224
  contentType: attachment.contentType,
@@ -3236,96 +3256,19 @@ class BaseClient {
3236
3256
  }
3237
3257
  }
3238
3258
 
3239
- // Process with AI features for inbox messages
3240
- if (messageData.messageSpecialUse === '\\Inbox') {
3259
+ // Process with AI features for inbox messages. A message with no text part has no text
3260
+ // object at all, and nothing to summarize
3261
+ if (messageData.messageSpecialUse === '\\Inbox' && (messageData.text?.plain || messageData.text?.html)) {
3241
3262
  let llmMessageData = Object.assign({ account: this.account }, messageData);
3242
3263
 
3243
- // Check if LLM processing is enabled
3244
- let canUseLLM = await llmPreProcess.run(llmMessageData);
3245
-
3246
- if (canUseLLM && (messageData.text.plain || messageData.text.html)) {
3247
- // Generate email summary using AI
3248
- if (canUseLLM.generateEmailSummary) {
3249
- try {
3250
- messageData.summary = await this.call({
3251
- cmd: 'generateSummary',
3252
- data: {
3253
- message: {
3254
- headers: Object.keys(messageData.headers || {}).map(key => ({ key, value: [].concat(messageData.headers[key] || []) })),
3255
- attachments: messageData.attachments,
3256
- from: messageData.from,
3257
- subject: messageData.subject,
3258
- text: messageData.text.plain,
3259
- html: messageData.text.html
3260
- },
3261
- account: this.account
3262
- },
3263
- timeout: 2 * 60 * 1000
3264
- });
3265
-
3266
- if (messageData.summary) {
3267
- // Clean up summary output
3268
- for (let key of Object.keys(messageData.summary)) {
3269
- // remove meta keys from output
3270
- if (key.charAt(0) === '_' || messageData.summary[key] === '') {
3271
- delete messageData.summary[key];
3272
- }
3273
- if (key === 'riskAssessment') {
3274
- messageData.riskAssessment = messageData.summary.riskAssessment;
3275
- delete messageData.summary.riskAssessment;
3276
- }
3277
- }
3278
-
3279
- this.logger.trace({ msg: 'Fetched summary from OpenAI', summary: messageData.summary });
3280
- }
3281
-
3282
- await this.redis.del(`${REDIS_PREFIX}:openai:error`);
3283
- } catch (err) {
3284
- // Track OpenAI errors
3285
- await this.redis.set(
3286
- `${REDIS_PREFIX}:openai:error`,
3287
- JSON.stringify({
3288
- message: err.message,
3289
- code: err.code,
3290
- statusCode: err.statusCode,
3291
- created: Date.now()
3292
- })
3293
- );
3294
- this.logger.error({ msg: 'Failed to fetch summary from OpenAI', err });
3295
- }
3296
- }
3297
-
3298
- // Generate embeddings for semantic search
3299
- if (canUseLLM.generateEmbeddings) {
3300
- try {
3301
- messageData.embeddings = await this.call({
3302
- cmd: 'generateEmbeddings',
3303
- data: {
3304
- message: {
3305
- headers: Object.keys(messageData.headers || {}).map(key => ({ key, value: [].concat(messageData.headers[key] || []) })),
3306
- attachments: messageData.attachments,
3307
- from: messageData.from,
3308
- subject: messageData.subject,
3309
- text: messageData.text.plain,
3310
- html: messageData.text.html
3311
- },
3312
- account: this.account
3313
- },
3314
- timeout: 2 * 60 * 1000
3315
- });
3316
- } catch (err) {
3317
- await this.redis.set(
3318
- `${REDIS_PREFIX}:openai:error`,
3319
- JSON.stringify({
3320
- message: err.message,
3321
- code: err.code,
3322
- statusCode: err.statusCode,
3323
- time: Date.now()
3324
- })
3325
- );
3326
- this.logger.error({ msg: 'Failed to fetch embeddings from OpenAI', err });
3327
- }
3328
- }
3264
+ if (await llmPreProcess.run(llmMessageData)) {
3265
+ await llmPreProcess.summarize(messageData, {
3266
+ call: this.call,
3267
+ redis: this.redis,
3268
+ account: this.account,
3269
+ provider: this.summaryProvider(),
3270
+ logger: this.logger
3271
+ });
3329
3272
  }
3330
3273
  }
3331
3274
 
@@ -3344,11 +3287,14 @@ class BaseClient {
3344
3287
  for (let attachment of messageData.attachments) {
3345
3288
  let contentId = attachment.contentId && attachment.contentId.replace(/^<|>$/g, '');
3346
3289
  if (contentId && cidReferences.has(contentId)) {
3347
- if (attachment.content) {
3348
- // already downloaded in a previous step
3349
- continue;
3350
- } else {
3351
- attachment.content = (await this.getAttachment(attachment.id))?.data?.toString('base64');
3290
+ // An attachment the earlier inline pass already loaded is embedded as is; the
3291
+ // same size cap applies to anything downloaded here
3292
+ if (!attachment.content && !(attachment.encodedSize && attachment.encodedSize > MAX_INLINE_ATTACHMENT_SIZE)) {
3293
+ try {
3294
+ attachment.content = (await this.getAttachment(attachment.id))?.data?.toString('base64');
3295
+ } catch (err) {
3296
+ this.logger.error({ msg: 'Failed to load attachment content', attachment, err });
3297
+ }
3352
3298
  }
3353
3299
 
3354
3300
  attachmentList.set(contentId, {
@@ -3358,35 +3304,32 @@ class BaseClient {
3358
3304
  }
3359
3305
  }
3360
3306
 
3361
- // Replace CID references with data URIs
3307
+ // Replace CID references with data URIs. The web safe copy is what webhooks deliver
3308
+ // in place of the HTML, so it gets the same treatment
3362
3309
  if (attachmentList.size) {
3363
- messageData.text.html = messageData.text.html.replace(cidReferenceRegex(), (fullMatch, cidMatch) => {
3364
- if (attachmentList.has(cidMatch)) {
3365
- let { attachment, content } = attachmentList.get(cidMatch);
3366
- if (content) {
3367
- return `data:${attachment.contentType || 'application/octet-stream'};base64,${content}`;
3368
- }
3369
- }
3370
- return fullMatch;
3371
- });
3310
+ const embedImages = html =>
3311
+ embedCidImages(html, contentId => {
3312
+ let { attachment, content } = attachmentList.get(contentId) || {};
3313
+ return content && { contentType: attachment.contentType, content };
3314
+ });
3315
+
3316
+ messageData.text.html = embedImages(messageData.text.html);
3317
+ if (messageData.text._generatedHtml) {
3318
+ messageData.text._generatedHtml = embedImages(messageData.text._generatedHtml);
3319
+ }
3372
3320
  }
3373
3321
  }
3374
3322
 
3375
- messageData.text.webSafe = true;
3323
+ if (messageData.text._generatedHtml) {
3324
+ messageData.text.webSafe = true;
3325
+ }
3376
3326
  }
3377
3327
 
3378
- // Filter headers based on request
3379
- // we might have fetched more headers than was asked for, so filter out all the unneeded ones
3380
- if (options.headers && Array.isArray(requestedHeaders)) {
3381
- let filteredHeaders = {};
3382
- for (let key of Object.keys(messageData.headers || {})) {
3383
- if (requestedHeaders.includes(key)) {
3384
- filteredHeaders[key] = messageData.headers[key];
3385
- }
3386
- }
3387
- messageData.headers = filteredHeaders;
3388
- } else if (options.headers && requestedHeaders === false) {
3389
- delete messageData.headers;
3328
+ // Narrow the headers to what the caller asked for. This runs last: the checks and the AI
3329
+ // summary above read headers fetched for them (see notificationHeaderFields()) that the
3330
+ // published payload may not carry
3331
+ if (options.headers) {
3332
+ narrowHeaders(messageData, requestedHeaders);
3390
3333
  }
3391
3334
 
3392
3335
  let path = messageData.path || this.path;
@@ -3420,7 +3363,8 @@ class BaseClient {
3420
3363
  }
3421
3364
 
3422
3365
  /**
3423
- * Checks if message might be an abuse complaint based on headers and content
3366
+ * Checks if a newly arrived message might be an abuse complaint: one in the Inbox that looks
3367
+ * like one
3424
3368
  * @param {Object} messageData - Message data
3425
3369
  * @returns {boolean} True if message might be a complaint
3426
3370
  */
@@ -3429,22 +3373,46 @@ class BaseClient {
3429
3373
  return false;
3430
3374
  }
3431
3375
 
3376
+ return this.looksLikeAComplaint(messageData);
3377
+ }
3378
+
3379
+ /**
3380
+ * Checks if a message looks like an abuse complaint from its attachment types, sender and
3381
+ * subject, without regard to the folder: an ARF feedback report, or one of the shapes the
3382
+ * feedback loops that send no report part use
3383
+ * @param {Object} messageData - Message data
3384
+ * @returns {boolean} True if the message has the shape of a complaint
3385
+ */
3386
+ looksLikeAComplaint(messageData) {
3432
3387
  let hasEmbeddedMessage = false;
3433
3388
  for (let attachment of messageData.attachments || []) {
3434
- // ARF format indicator
3435
- if (attachment.contentType === 'message/feedback-report') {
3389
+ // Direct ARF indicator
3390
+ if (attachment.contentType === FEEDBACK_REPORT_TYPE) {
3436
3391
  return true;
3437
3392
  }
3438
3393
 
3439
- if (['message/rfc822', 'message/rfc822-headers'].includes(attachment.contentType)) {
3394
+ if (ORIGINAL_MESSAGE_TYPES.includes(attachment.contentType)) {
3440
3395
  hasEmbeddedMessage = true;
3441
3396
  }
3442
3397
  }
3443
3398
 
3444
3399
  let fromAddress = (messageData.from && messageData.from.address) || '';
3445
3400
 
3446
- // Hotmail-specific complaint format
3447
- if (hasEmbeddedMessage && fromAddress === 'staff@hotmail.com' && /complaint/i.test(messageData.subject)) {
3401
+ // Hotmail/Microsoft complaint pattern (may not have parsed attachments)
3402
+ if (fromAddress === 'staff@hotmail.com' && /complaint/i.test(messageData.subject)) {
3403
+ return true;
3404
+ }
3405
+
3406
+ // Generic feedback loop sender patterns
3407
+ if (
3408
+ /^(feedbackloop|fbl|complaints|abuse)@/i.test(fromAddress) &&
3409
+ (hasEmbeddedMessage || /abuse|complaint|feedback|report/i.test(messageData.subject))
3410
+ ) {
3411
+ return true;
3412
+ }
3413
+
3414
+ // ARF-style subject patterns with embedded message
3415
+ if (hasEmbeddedMessage && /abuse report|feedback report|spam report/i.test(messageData.subject)) {
3448
3416
  return true;
3449
3417
  }
3450
3418
 
@@ -3452,7 +3420,8 @@ class BaseClient {
3452
3420
  }
3453
3421
 
3454
3422
  /**
3455
- * Checks if message is a delivery status notification
3423
+ * Checks if a newly arrived message is a delivery status notification: one in the Inbox that
3424
+ * looks like one
3456
3425
  * @param {Object} messageData - Message data
3457
3426
  * @returns {boolean} True if message is a DSN
3458
3427
  */
@@ -3461,14 +3430,26 @@ class BaseClient {
3461
3430
  return false;
3462
3431
  }
3463
3432
 
3464
- // Check for multipart/report with delivery-status
3433
+ return this.looksLikeDSNResponse(messageData);
3434
+ }
3435
+
3436
+ /**
3437
+ * Checks if a message is a delivery status notification from its Content-Type header, without
3438
+ * regard to the folder: a multipart/report of type delivery-status
3439
+ * @param {Object} messageData - Message data
3440
+ * @returns {boolean} True if the message is a DSN
3441
+ */
3442
+ looksLikeDSNResponse(messageData) {
3465
3443
  if (messageData.headers && messageData.headers['content-type'] && messageData.headers['content-type'].length) {
3466
3444
  let parsedContentType = libmime.parseHeaderValue(messageData.headers['content-type'].at(-1));
3467
3445
  if (
3468
3446
  parsedContentType &&
3469
3447
  parsedContentType.value &&
3470
3448
  parsedContentType.value.toLowerCase().trim() === 'multipart/report' &&
3471
- parsedContentType.params['report-type'] === 'delivery-status'
3449
+ // parameter values are case-insensitive for this one (RFC 6522)
3450
+ String(parsedContentType.params['report-type'] || '')
3451
+ .toLowerCase()
3452
+ .trim() === 'delivery-status'
3472
3453
  ) {
3473
3454
  return true;
3474
3455
  }
@@ -3478,7 +3459,8 @@ class BaseClient {
3478
3459
  }
3479
3460
 
3480
3461
  /**
3481
- * Checks if message might be a bounce based on various heuristics
3462
+ * Checks if a newly arrived message might be a bounce: one in the Inbox or Junk folder that
3463
+ * was not already read as a delivery report, and that looks like a bounce
3482
3464
  * @param {Object} messageData - Message data
3483
3465
  * @returns {boolean} True if message might be a bounce
3484
3466
  */
@@ -3492,6 +3474,16 @@ class BaseClient {
3492
3474
  return false;
3493
3475
  }
3494
3476
 
3477
+ return this.looksLikeABounce(messageData);
3478
+ }
3479
+
3480
+ /**
3481
+ * Checks if a message looks like a bounce from its sender, subject and attachment types,
3482
+ * without regard to the folder
3483
+ * @param {Object} messageData - Message data
3484
+ * @returns {boolean} True if the message has the shape of a bounce
3485
+ */
3486
+ looksLikeABounce(messageData) {
3495
3487
  let name = (messageData.from && messageData.from.name) || '';
3496
3488
  let address = (messageData.from && messageData.from.address) || '';
3497
3489
 
@@ -3613,6 +3605,10 @@ class BaseClient {
3613
3605
  // Get SMTP transport from pool
3614
3606
  const transporter = getMailTransport(smtpSettings);
3615
3607
 
3608
+ // Only the send itself is inside this try. Once the server has accepted the message a
3609
+ // failure is a bookkeeping failure: rethrowing it made the submit worker retry (and so
3610
+ // deliver) an already delivered message, and reported a messageDeliveryError for it
3611
+ let info;
3616
3612
  try {
3617
3613
  // Update job progress
3618
3614
  try {
@@ -3622,104 +3618,116 @@ class BaseClient {
3622
3618
  }
3623
3619
 
3624
3620
  // Send the message
3625
- const info = await transporter.sendMail({
3621
+ info = await transporter.sendMail({
3626
3622
  envelope,
3627
3623
  messageId,
3628
3624
  raw: !hasBcc ? raw : await removeBcc(raw),
3629
3625
  dsn: data.dsn || null
3630
3626
  });
3627
+ } catch (err) {
3628
+ await this.handleSubmitError(err, {
3629
+ smtpSettings,
3630
+ networkRouting,
3631
+ gatewayData,
3632
+ gatewayObject,
3633
+ data,
3634
+ jobData,
3635
+ queueId,
3636
+ envelope
3637
+ });
3638
+ throw err;
3639
+ }
3631
3640
 
3632
- // Store EHLO response for debugging
3633
- if (info.ehlo) {
3641
+ // Store EHLO response for debugging
3642
+ if (info.ehlo) {
3643
+ try {
3634
3644
  await this.redis.hSetExists(this.getAccountKey(), 'smtpServerEhlo', JSON.stringify(info.ehlo));
3645
+ } catch (err) {
3646
+ this.logger.error({ msg: 'Failed to store the SMTP server EHLO response', queueId, messageId, err });
3635
3647
  }
3648
+ }
3636
3649
 
3637
- // Handle provider-specific message ID extraction
3638
- const originalMessageId = ProviderMessageIdHandler.processResponse(info, smtpSettings.host);
3650
+ // Handle provider-specific message ID extraction
3651
+ const originalMessageId = ProviderMessageIdHandler.processResponse(info, smtpSettings.host);
3639
3652
 
3640
- // Update job progress
3641
- try {
3642
- await submitJobEntry.updateProgress({
3643
- status: 'smtp-completed',
3644
- response: info.response,
3645
- messageId: info.messageId,
3646
- originalMessageId
3647
- });
3648
- } catch (err) {
3649
- // ignore
3650
- }
3653
+ // Update job progress
3654
+ try {
3655
+ await submitJobEntry.updateProgress({
3656
+ status: 'smtp-completed',
3657
+ response: info.response,
3658
+ messageId: info.messageId,
3659
+ originalMessageId
3660
+ });
3661
+ } catch (err) {
3662
+ // ignore
3663
+ }
3651
3664
 
3652
- // Send success notification
3665
+ // Send success notification
3666
+ try {
3653
3667
  await this.notify(
3654
3668
  false,
3655
3669
  EMAIL_SENT_NOTIFY,
3656
3670
  NotificationBuilder.buildSuccessPayload({ info, originalMessageId, queueId, envelope, networkRouting })
3657
3671
  );
3672
+ } catch (err) {
3673
+ this.logger.error({ msg: 'Failed to queue the messageSent notification', queueId, messageId, err });
3674
+ }
3658
3675
 
3659
- // Clear cached SMTP error
3660
- try {
3661
- await this.redis.hset(this.getAccountKey(), 'smtpStatus', JSON.stringify({ created: Date.now(), status: 'ok', response: info.response }));
3662
- } catch (err) {
3663
- // ignore
3664
- }
3665
-
3666
- // Handle sent mail copy to folder
3667
- const copyDeciderInputs = {
3668
- accountData,
3669
- data,
3670
- isGmail: this.isGmail,
3671
- isOutlook: this.isOutlook,
3672
- gatewayData
3673
- };
3674
- const shouldCopy = SentMailCopyDecider.shouldCopy(copyDeciderInputs);
3675
-
3676
- const connectionOptions = { allowSecondary: true };
3677
-
3678
- const sentCopySucceeded = shouldCopy ? await this.uploadToSentFolder(raw, data, queueId, messageId, connectionOptions) : false;
3679
-
3680
- // Remove the submitted draft. Delete it permanently when a copy of the message
3681
- // exists in the Sent Mail folder - either uploaded above, or filed by the provider
3682
- // itself (Gmail and Outlook store SMTP-sent messages on their own, which is also
3683
- // why the upload is suppressed for them). Otherwise move the draft to Trash so the
3684
- // content is not lost
3685
- if (data.draft) {
3686
- await this.cleanupSubmittedDraft(data.draft, {
3687
- permanent: sentCopySucceeded || SentMailCopyDecider.providerSavesSentCopy(copyDeciderInputs),
3688
- queueId,
3689
- messageId,
3690
- connectionOptions
3691
- });
3692
- }
3676
+ // Clear cached SMTP error
3677
+ try {
3678
+ await this.redis.hset(this.getAccountKey(), 'smtpStatus', JSON.stringify({ created: Date.now(), status: 'ok', response: info.response }));
3679
+ } catch (err) {
3680
+ // ignore
3681
+ }
3693
3682
 
3694
- // Update reference flags if needed
3695
- if (reference && reference.update) {
3696
- await this.updateReferenceFlags(reference, queueId, messageId, connectionOptions);
3697
- }
3683
+ // Handle sent mail copy to folder
3684
+ const copyDeciderInputs = {
3685
+ accountData,
3686
+ data,
3687
+ isGmail: this.isGmail,
3688
+ isOutlook: this.isOutlook,
3689
+ gatewayData
3690
+ };
3691
+ const shouldCopy = SentMailCopyDecider.shouldCopy(copyDeciderInputs);
3698
3692
 
3699
- // Update feedback key if provided
3700
- if (data.feedbackKey) {
3701
- await this.updateFeedbackKey(data.feedbackKey, true);
3702
- }
3693
+ const connectionOptions = { allowSecondary: true };
3703
3694
 
3704
- // Update gateway usage stats
3705
- if (gatewayData) {
3706
- await this.updateGatewayStats(gatewayObject, queueId, messageId, reference);
3707
- }
3695
+ const sentCopySucceeded = shouldCopy ? await this.uploadToSentFolder(raw, data, queueId, messageId, connectionOptions) : false;
3708
3696
 
3709
- return { response: info.response, messageId: info.messageId };
3710
- } catch (err) {
3711
- await this.handleSubmitError(err, {
3712
- smtpSettings,
3713
- networkRouting,
3714
- gatewayData,
3715
- gatewayObject,
3716
- data,
3717
- jobData,
3697
+ // Remove the submitted draft. Delete it permanently when a copy of the message
3698
+ // exists in the Sent Mail folder - either uploaded above, or filed by the provider
3699
+ // itself (Gmail and Outlook store SMTP-sent messages on their own, which is also
3700
+ // why the upload is suppressed for them). Otherwise move the draft to Trash so the
3701
+ // content is not lost
3702
+ if (data.draft) {
3703
+ await this.cleanupSubmittedDraft(data.draft, {
3704
+ permanent: sentCopySucceeded || SentMailCopyDecider.providerSavesSentCopy(copyDeciderInputs),
3718
3705
  queueId,
3719
- envelope
3706
+ messageId,
3707
+ connectionOptions
3720
3708
  });
3721
- throw err;
3722
3709
  }
3710
+
3711
+ // Update reference flags if needed
3712
+ if (reference && reference.update) {
3713
+ await this.updateReferenceFlags(reference, queueId, messageId, connectionOptions);
3714
+ }
3715
+
3716
+ // Update feedback key if provided
3717
+ if (data.feedbackKey) {
3718
+ try {
3719
+ await this.updateFeedbackKey(data.feedbackKey, true);
3720
+ } catch (err) {
3721
+ this.logger.error({ msg: 'Failed to update the submission feedback key', queueId, messageId, err });
3722
+ }
3723
+ }
3724
+
3725
+ // Update gateway usage stats
3726
+ if (gatewayData) {
3727
+ await this.updateGatewayStats(gatewayObject, queueId, messageId, reference);
3728
+ }
3729
+
3730
+ return { response: info.response, messageId: info.messageId };
3723
3731
  }
3724
3732
 
3725
3733
  /**
@@ -3754,6 +3762,9 @@ class BaseClient {
3754
3762
 
3755
3763
  return true;
3756
3764
  }
3765
+
3766
+ // A silent skip hid a listing regression for weeks (home.pl glued its LIST flags together, so Sent never made the listing)
3767
+ this.logger.warn({ msg: 'No Sent mailbox found, skipping the sent copy', queueId, messageId });
3757
3768
  } catch (err) {
3758
3769
  this.logger.error({ msg: 'Failed to upload Sent mail', queueId, messageId, err });
3759
3770
  }
@@ -3915,6 +3926,8 @@ module.exports = {
3915
3926
  BaseClient,
3916
3927
  metricsMeta: postMetrics,
3917
3928
  applyReferenceRecipients,
3929
+ buildReferences,
3930
+ isFailedDelivery,
3918
3931
  markRejectedAccessToken,
3919
3932
  renewRejectedAccessToken
3920
3933
  };