emailengine-app 2.81.0 → 2.81.2

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.
@@ -6,7 +6,6 @@ const logger = require('../logger');
6
6
  const settings = require('../settings');
7
7
  const { isDocumentStoreEnabled } = require('../document-store');
8
8
  const msgpack = require('../msgpack');
9
- const appendList = require('../append-list');
10
9
  const { templates } = require('../templates');
11
10
  const { Gateway } = require('../gateway');
12
11
  const os = require('os');
@@ -18,7 +17,7 @@ const { addTrackers } = require('../add-trackers');
18
17
  const { getRawEmail } = require('../get-raw-email');
19
18
  const { getTemplate } = require('@postalsys/templates');
20
19
  const { deepEqual } = require('assert');
21
- const { arfDetect, camelCaseComplaint } = require('../arf-detect');
20
+ const { arfDetect, camelCaseComplaint, FEEDBACK_REPORT_TYPE, ORIGINAL_MESSAGE_TYPES, COMPLAINT_ATTACHMENT_TYPES } = require('../arf-detect');
22
21
  const { createTransaction } = require('../redis-operations');
23
22
  const { ACCOUNT_STATES } = require('../account/account-state');
24
23
  const { credentialErrorStatus, isTransientCredentialError, resolveAuthServerCredentials } = require('./credential-errors');
@@ -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');
@@ -307,6 +307,16 @@ async function retryOnTransientError(fn, options = {}) {
307
307
  }
308
308
  }
309
309
 
310
+ /**
311
+ * The next attempt of a deferred change, and how long to wait before it
312
+ * @param {Object} event - A deferred change
313
+ * @returns {{next: Object, delay: number|undefined}} delay is undefined once the attempts are used up
314
+ */
315
+ function nextChangeAttempt(event) {
316
+ const attempt = (event.attempt || 0) + 1;
317
+ return { next: Object.assign({}, event, { attempt }), delay: CHANGE_EVENT_RETRY_DELAYS[attempt - 1] };
318
+ }
319
+
310
320
  /**
311
321
  * Base class for email client implementations
312
322
  * Provides common functionality for IMAP/SMTP operations
@@ -353,6 +363,17 @@ class BaseClient {
353
363
  // already been told
354
364
  this.authSuccessNotified = false;
355
365
 
366
+ // Deferred change retries of the API clients, see deferFailedChangeEvent(). deferredDueAt is
367
+ // when the earliest one is due: undefined until Redis has been asked (so changes deferred
368
+ // before a restart are found), null when none is waiting
369
+ this.deferredDueAt = undefined;
370
+ this.deferredRetryTimer = null;
371
+ // Bumped by cancelDeferredRetryTimer(), so a Redis read already in flight does not
372
+ // overwrite the "ask Redis again" it asked for
373
+ this.deferredEpoch = 0;
374
+ // The deferred change being retried right now, see processDueDeferredEvents()
375
+ this.activeLease = null;
376
+
356
377
  // Initialize notification handler for webhook and event delivery
357
378
  this.notificationHandler = new NotificationHandler({
358
379
  account: this.account,
@@ -430,6 +451,143 @@ class BaseClient {
430
451
  this.initRetryTimer.unref();
431
452
  }
432
453
 
454
+ /**
455
+ * Schedules a retry for a mailbox change the API clients failed to process. Gmail and Graph
456
+ * answer 5xx and time out often enough that dropping the change on the first failure lost a
457
+ * messageNew webhook every few hours on a busy instance, with nothing left to recover it
458
+ * from. Only a failure of the service is retried (the same line the credential paths draw);
459
+ * anything else would fail the same way again. Giving up on new messages or on a recovery pass
460
+ * emits a syncWarning, the only record left that they were never announced
461
+ * @param {Object} event - JSON-serializable change; for `created`, `message` is the message id
462
+ * or an object carrying `id`
463
+ * @param {Error} err - Why it failed
464
+ */
465
+ async deferFailedChangeEvent(event, err) {
466
+ const { next: nextAttempt, delay } = nextChangeAttempt(event);
467
+ const messageIds = event.type === 'created' ? [typeof event.message === 'string' ? event.message : event.message?.id] : undefined;
468
+ const logEntry = { account: this.account, eventType: event.type, messageIds, attempt: nextAttempt.attempt, err };
469
+
470
+ if (delay && isTransientCredentialError(err)) {
471
+ const dueTime = Date.now() + delay;
472
+ // The change being retried right now is already stored as this attempt (its lease),
473
+ // so moving that entry is the deferral
474
+ const lease = this.activeLease?.event === event ? this.activeLease : null;
475
+ try {
476
+ if (lease?.member) {
477
+ await this.accountObject.rescheduleChangeEvent(lease.member, dueTime);
478
+ lease.deferred = true;
479
+ } else {
480
+ await this.accountObject.deferChangeEvent(nextAttempt, dueTime);
481
+ }
482
+ // undefined (unknown, Redis is asked on the next run) stays unknown: something
483
+ // stored earlier may be due before this
484
+ if (this.deferredDueAt === null || dueTime < this.deferredDueAt) {
485
+ this.deferredDueAt = dueTime;
486
+ }
487
+ this.logger.warn({ msg: 'Failed to process mailbox change, retrying later', delay, ...logEntry });
488
+ return;
489
+ } catch (deferErr) {
490
+ this.logger.error({ msg: 'Failed to defer mailbox change', deferErr, ...logEntry });
491
+ }
492
+ }
493
+
494
+ this.logger.error({ msg: 'Failed to process mailbox change, giving up', ...logEntry });
495
+ if (messageIds?.length) {
496
+ await emitChangeEvent(this.logger, this.account, 'syncWarning', {
497
+ type: 'changeSkipped',
498
+ message: 'New messages could not be fetched, no messageNew webhook was sent for them',
499
+ messageIds
500
+ });
501
+ } else if (event.type === 'missedRecovery') {
502
+ await emitChangeEvent(this.logger, this.account, 'syncWarning', {
503
+ type: 'missedRecoveryFailed',
504
+ message: 'Missed change notifications could not be recovered, new messages may not have been announced'
505
+ });
506
+ }
507
+ }
508
+
509
+ /**
510
+ * Runs `handler` for each deferred change that is due. Costs no Redis round trip while nothing
511
+ * is known to be waiting.
512
+ *
513
+ * Before the handler runs, the stored change is swapped for its next attempt, due when that
514
+ * attempt would be (a lease). A worker that dies while handling it finds it again only then
515
+ * and one attempt further along, so a change that kills the worker runs out of attempts
516
+ * instead of taking the worker down on every restart. Deferring the change again moves the
517
+ * lease (see deferFailedChangeEvent()); otherwise the lease is dropped once the handler is done
518
+ * @param {Function} handler - async (event) => void; it defers a failure itself through
519
+ * deferFailedChangeEvent() with the event it was given, and anything it throws is deferred
520
+ * the same way
521
+ */
522
+ async processDueDeferredEvents(handler) {
523
+ if (this.deferredDueAt === null || this.deferredDueAt > Date.now()) {
524
+ return;
525
+ }
526
+
527
+ const epoch = this.deferredEpoch;
528
+ const { due, next } = await this.accountObject.listDueChangeEvents();
529
+ if (epoch === this.deferredEpoch) {
530
+ this.deferredDueAt = next;
531
+ }
532
+
533
+ try {
534
+ for (const { event, member } of due) {
535
+ const lease = nextChangeAttempt(event);
536
+ this.activeLease = {
537
+ event,
538
+ member: await this.accountObject.leaseChangeEvent(member, lease.delay ? lease.next : null, Date.now() + (lease.delay || 0)),
539
+ deferred: false
540
+ };
541
+
542
+ try {
543
+ await handler(event);
544
+ } catch (err) {
545
+ await this.deferFailedChangeEvent(event, err);
546
+ }
547
+
548
+ if (this.activeLease.member && !this.activeLease.deferred) {
549
+ await this.accountObject.completeChangeEvent(this.activeLease.member);
550
+ }
551
+ this.activeLease = null;
552
+ }
553
+ } catch (err) {
554
+ this.activeLease = null;
555
+ // the rest of the batch is still stored, make the next run ask Redis again
556
+ this.deferredDueAt = undefined;
557
+ throw err;
558
+ }
559
+ }
560
+
561
+ /**
562
+ * Arms a timer for the earliest deferred change, called after every processing run. When the
563
+ * due time is unknown (a run failed to read Redis), it checks again in a minute rather than
564
+ * leaving what was deferred to wait for the next notification
565
+ */
566
+ scheduleDeferredRetryTimer() {
567
+ clearTimeout(this.deferredRetryTimer);
568
+ const dueAt = this.deferredDueAt === undefined ? Date.now() + CHANGE_EVENT_RETRY_DELAYS[0] : this.deferredDueAt;
569
+ if (this.closed || !dueAt) {
570
+ return;
571
+ }
572
+
573
+ this.deferredRetryTimer = setTimeout(() => this.retryDeferredEvents(), dueAt - Date.now());
574
+ this.deferredRetryTimer.unref();
575
+ }
576
+
577
+ /**
578
+ * Runs the client's usual change processing, which picks up the deferred changes that are due
579
+ */
580
+ retryDeferredEvents() {
581
+ this.triggerSync();
582
+ }
583
+
584
+ // Also forgets the due time, so the next run asks Redis again
585
+ cancelDeferredRetryTimer() {
586
+ clearTimeout(this.deferredRetryTimer);
587
+ this.deferredDueAt = undefined;
588
+ this.deferredEpoch++;
589
+ }
590
+
433
591
  /**
434
592
  * Drops a pending init() retry, if any
435
593
  */
@@ -506,88 +664,45 @@ class BaseClient {
506
664
  }
507
665
 
508
666
  /**
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
667
+ * Decides `isBounce` and `relatedMessageId` for fetched message details from the message
668
+ * content, the way processNew() decides them for the messageNew webhook. Nothing is stored:
669
+ * only a message in the Inbox that looks like a bounce is downloaded, and a delivery or delay
670
+ * report is not a bounce, as on the arrival path. A failure is logged and leaves the fields
671
+ * unset rather than failing the fetch
672
+ * @param {Object} messageData - Formatted message details (with `messageSpecialUse` decided), updated in place
673
+ * @param {Function} [getContent] - Supplies the raw message; the IMAP fetch downloads under the lock it already holds
522
674
  */
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;
675
+ async detectBounce(messageData, getContent = () => this.getRawMessage(messageData.id)) {
676
+ if (messageData.messageSpecialUse !== '\\Inbox' || !this.looksLikeABounce(messageData)) {
677
+ return;
537
678
  }
538
679
 
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;
680
+ // The report parser annotates the object it is given, and deliveryReport is not part of
681
+ // the details response, so it gets the log fields instead of the message
682
+ let logContext = { id: messageData.id, uid: messageData.uid, messageId: messageData.messageId };
683
+ let content;
684
+ try {
685
+ content = await getContent();
686
+ if (!content) {
687
+ return;
560
688
  }
561
- if (row.s) {
562
- bounce.response.status = row.s;
689
+
690
+ let parsed = await simpleParser(content, { keepDeliveryStatus: true, skipTextToHtml: true, skipImageLinks: true });
691
+ if (applyDeliveryReport(parsed, logContext, this.logger)) {
692
+ return;
563
693
  }
564
- bounce.date = new Date(row.t).toISOString();
565
- return bounce;
566
- });
567
- }
568
694
 
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;
695
+ let bounce = await bounceDetect({ parsed });
696
+ if (bounce.action && bounce.recipient && bounce.messageId) {
697
+ messageData.isBounce = true;
698
+ messageData.relatedMessageId = bounce.messageId;
582
699
  }
583
700
  } 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
- });
701
+ // A parser failure leaves an IMAP download unconsumed, and its lock is released only once the stream ends
702
+ if (typeof content?.destroy === 'function') {
703
+ content.destroy();
704
+ }
705
+ this.logger.error(Object.assign({ msg: 'Failed to detect bounce', err }, logContext));
591
706
  }
592
707
  }
593
708
 
@@ -2936,8 +3051,8 @@ class BaseClient {
2936
3051
  if (this.mightBeAComplaint(messageData)) {
2937
3052
  try {
2938
3053
  // 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)) {
3054
+ for (let attachment of messageData.attachments || []) {
3055
+ if (!COMPLAINT_ATTACHMENT_TYPES.includes(attachment.contentType)) {
2941
3056
  continue;
2942
3057
  }
2943
3058
 
@@ -3037,11 +3152,7 @@ class BaseClient {
3037
3152
  }
3038
3153
  }
3039
3154
 
3040
- let stored = 0;
3041
3155
  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
-
3045
3156
  bounceNotifyInfo = Object.assign({ bounceMessage: messageData.id }, bounce);
3046
3157
 
3047
3158
  messageData.isBounce = true;
@@ -3053,8 +3164,7 @@ class BaseClient {
3053
3164
  id: messageData.id,
3054
3165
  uid: messageData.uid,
3055
3166
  messageId: messageData.messageId,
3056
- bounce,
3057
- stored
3167
+ bounce
3058
3168
  });
3059
3169
  }
3060
3170
  } catch (err) {
@@ -3420,7 +3530,8 @@ class BaseClient {
3420
3530
  }
3421
3531
 
3422
3532
  /**
3423
- * Checks if message might be an abuse complaint based on headers and content
3533
+ * Checks if a newly arrived message might be an abuse complaint: one in the Inbox that looks
3534
+ * like one
3424
3535
  * @param {Object} messageData - Message data
3425
3536
  * @returns {boolean} True if message might be a complaint
3426
3537
  */
@@ -3429,22 +3540,46 @@ class BaseClient {
3429
3540
  return false;
3430
3541
  }
3431
3542
 
3543
+ return this.looksLikeAComplaint(messageData);
3544
+ }
3545
+
3546
+ /**
3547
+ * Checks if a message looks like an abuse complaint from its attachment types, sender and
3548
+ * subject, without regard to the folder: an ARF feedback report, or one of the shapes the
3549
+ * feedback loops that send no report part use
3550
+ * @param {Object} messageData - Message data
3551
+ * @returns {boolean} True if the message has the shape of a complaint
3552
+ */
3553
+ looksLikeAComplaint(messageData) {
3432
3554
  let hasEmbeddedMessage = false;
3433
3555
  for (let attachment of messageData.attachments || []) {
3434
- // ARF format indicator
3435
- if (attachment.contentType === 'message/feedback-report') {
3556
+ // Direct ARF indicator
3557
+ if (attachment.contentType === FEEDBACK_REPORT_TYPE) {
3436
3558
  return true;
3437
3559
  }
3438
3560
 
3439
- if (['message/rfc822', 'message/rfc822-headers'].includes(attachment.contentType)) {
3561
+ if (ORIGINAL_MESSAGE_TYPES.includes(attachment.contentType)) {
3440
3562
  hasEmbeddedMessage = true;
3441
3563
  }
3442
3564
  }
3443
3565
 
3444
3566
  let fromAddress = (messageData.from && messageData.from.address) || '';
3445
3567
 
3446
- // Hotmail-specific complaint format
3447
- if (hasEmbeddedMessage && fromAddress === 'staff@hotmail.com' && /complaint/i.test(messageData.subject)) {
3568
+ // Hotmail/Microsoft complaint pattern (may not have parsed attachments)
3569
+ if (fromAddress === 'staff@hotmail.com' && /complaint/i.test(messageData.subject)) {
3570
+ return true;
3571
+ }
3572
+
3573
+ // Generic feedback loop sender patterns
3574
+ if (
3575
+ /^(feedbackloop|fbl|complaints|abuse)@/i.test(fromAddress) &&
3576
+ (hasEmbeddedMessage || /abuse|complaint|feedback|report/i.test(messageData.subject))
3577
+ ) {
3578
+ return true;
3579
+ }
3580
+
3581
+ // ARF-style subject patterns with embedded message
3582
+ if (hasEmbeddedMessage && /abuse report|feedback report|spam report/i.test(messageData.subject)) {
3448
3583
  return true;
3449
3584
  }
3450
3585
 
@@ -3452,7 +3587,8 @@ class BaseClient {
3452
3587
  }
3453
3588
 
3454
3589
  /**
3455
- * Checks if message is a delivery status notification
3590
+ * Checks if a newly arrived message is a delivery status notification: one in the Inbox that
3591
+ * looks like one
3456
3592
  * @param {Object} messageData - Message data
3457
3593
  * @returns {boolean} True if message is a DSN
3458
3594
  */
@@ -3461,7 +3597,16 @@ class BaseClient {
3461
3597
  return false;
3462
3598
  }
3463
3599
 
3464
- // Check for multipart/report with delivery-status
3600
+ return this.looksLikeDSNResponse(messageData);
3601
+ }
3602
+
3603
+ /**
3604
+ * Checks if a message is a delivery status notification from its Content-Type header, without
3605
+ * regard to the folder: a multipart/report of type delivery-status
3606
+ * @param {Object} messageData - Message data
3607
+ * @returns {boolean} True if the message is a DSN
3608
+ */
3609
+ looksLikeDSNResponse(messageData) {
3465
3610
  if (messageData.headers && messageData.headers['content-type'] && messageData.headers['content-type'].length) {
3466
3611
  let parsedContentType = libmime.parseHeaderValue(messageData.headers['content-type'].at(-1));
3467
3612
  if (
@@ -3478,7 +3623,8 @@ class BaseClient {
3478
3623
  }
3479
3624
 
3480
3625
  /**
3481
- * Checks if message might be a bounce based on various heuristics
3626
+ * Checks if a newly arrived message might be a bounce: one in the Inbox or Junk folder that
3627
+ * was not already read as a delivery report, and that looks like a bounce
3482
3628
  * @param {Object} messageData - Message data
3483
3629
  * @returns {boolean} True if message might be a bounce
3484
3630
  */
@@ -3492,6 +3638,16 @@ class BaseClient {
3492
3638
  return false;
3493
3639
  }
3494
3640
 
3641
+ return this.looksLikeABounce(messageData);
3642
+ }
3643
+
3644
+ /**
3645
+ * Checks if a message looks like a bounce from its sender, subject and attachment types,
3646
+ * without regard to the folder
3647
+ * @param {Object} messageData - Message data
3648
+ * @returns {boolean} True if the message has the shape of a bounce
3649
+ */
3650
+ looksLikeABounce(messageData) {
3495
3651
  let name = (messageData.from && messageData.from.name) || '';
3496
3652
  let address = (messageData.from && messageData.from.address) || '';
3497
3653
 
@@ -3754,6 +3910,9 @@ class BaseClient {
3754
3910
 
3755
3911
  return true;
3756
3912
  }
3913
+
3914
+ // A silent skip hid a listing regression for weeks (home.pl glued its LIST flags together, so Sent never made the listing)
3915
+ this.logger.warn({ msg: 'No Sent mailbox found, skipping the sent copy', queueId, messageId });
3757
3916
  } catch (err) {
3758
3917
  this.logger.error({ msg: 'Failed to upload Sent mail', queueId, messageId, err });
3759
3918
  }