emailengine-app 2.85.0 → 2.87.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (137) hide show
  1. package/.ncurc.js +24 -6
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +97 -0
  4. package/DOCKER_DEPLOYMENT.md +2 -1
  5. package/Dockerfile +16 -3
  6. package/ENVIRONMENT.md +139 -0
  7. package/README.md +5 -1
  8. package/config/default.toml +2 -0
  9. package/copy-static-files.sh +4 -2
  10. package/data/google-crawlers.json +1 -1
  11. package/data/public_suffix_list.dat +4 -3
  12. package/lib/account-assignment.js +19 -0
  13. package/lib/account.js +285 -195
  14. package/lib/api-error-codes.js +49 -0
  15. package/lib/api-reference/model.js +6 -1
  16. package/lib/api-routes/account-routes.js +91 -32
  17. package/lib/api-routes/blocklist-routes.js +68 -2
  18. package/lib/api-routes/delivery-test-routes.js +1 -1
  19. package/lib/api-routes/gateway-routes.js +82 -10
  20. package/lib/api-routes/index.js +4 -0
  21. package/lib/api-routes/license-routes.js +2 -2
  22. package/lib/api-routes/mailbox-routes.js +3 -3
  23. package/lib/api-routes/message-routes.js +15 -7
  24. package/lib/api-routes/oauth2-app-routes.js +15 -8
  25. package/lib/api-routes/outbox-routes.js +77 -66
  26. package/lib/api-routes/permission-map.js +55 -6
  27. package/lib/api-routes/scoped-routes.js +74 -0
  28. package/lib/api-routes/settings-routes.js +11 -4
  29. package/lib/api-routes/stats-routes.js +5 -1
  30. package/lib/api-routes/submit-routes.js +25 -5
  31. package/lib/api-routes/template-routes.js +7 -6
  32. package/lib/api-routes/token-routes.js +11 -5
  33. package/lib/api-routes/webhook-delivery-routes.js +262 -0
  34. package/lib/api-routes/webhook-route-routes.js +119 -4
  35. package/lib/calendar-event.js +81 -1
  36. package/lib/consts.js +38 -46
  37. package/lib/db.js +14 -6
  38. package/lib/delivery-error.js +6 -0
  39. package/lib/deprecations.js +270 -0
  40. package/lib/email-client/base-client.js +134 -158
  41. package/lib/email-client/fallback-poll.js +62 -0
  42. package/lib/email-client/gmail-client.js +59 -11
  43. package/lib/email-client/imap/adaptive-idle-store.js +73 -0
  44. package/lib/email-client/imap/adaptive-idle.js +278 -0
  45. package/lib/email-client/imap/connection-errors.js +14 -1
  46. package/lib/email-client/imap/idle-settings.js +31 -5
  47. package/lib/email-client/imap/listing-diff.js +37 -0
  48. package/lib/email-client/imap/mailbox.js +380 -227
  49. package/lib/email-client/imap/subconnection.js +7 -29
  50. package/lib/email-client/imap/sync-operations.js +220 -127
  51. package/lib/email-client/imap-client.js +227 -163
  52. package/lib/email-client/message-builder.js +14 -79
  53. package/lib/email-client/outlook-client.js +378 -338
  54. package/lib/email-client/smtp-pool-manager.js +16 -13
  55. package/lib/email-client/sync-state-fields.js +19 -0
  56. package/lib/encrypt.js +157 -41
  57. package/lib/enum-descriptions.js +3 -1
  58. package/lib/env-setting-overrides.js +288 -0
  59. package/lib/export-worker.js +751 -0
  60. package/lib/export.js +64 -15
  61. package/lib/field-usage.js +1 -1
  62. package/lib/gateway.js +17 -1
  63. package/lib/get-raw-email.js +35 -108
  64. package/lib/health.js +75 -0
  65. package/lib/lock-run.js +119 -0
  66. package/lib/logger-consts.js +48 -0
  67. package/lib/logger.js +1 -1
  68. package/lib/lua/z-head-scores.lua +28 -0
  69. package/lib/network-errors.js +1 -1
  70. package/lib/node-version.js +24 -0
  71. package/lib/notify-attachments.js +20 -1
  72. package/lib/oauth/gmail.js +54 -29
  73. package/lib/oauth2-apps.js +630 -655
  74. package/lib/otp.js +66 -0
  75. package/lib/outbox.js +184 -54
  76. package/lib/parse-message.js +3 -3
  77. package/lib/privileged-settings.js +2 -2
  78. package/lib/queue-browser/definitions.js +11 -0
  79. package/lib/queue-browser/index.js +68 -19
  80. package/lib/queue-job-actions.js +18 -1
  81. package/lib/queue-retention.js +48 -12
  82. package/lib/queue-stats.js +11 -2
  83. package/lib/read-env-value.js +3 -0
  84. package/lib/redis-memory-warnings.js +99 -0
  85. package/lib/redis-reconnect.js +29 -0
  86. package/lib/request-timing.js +23 -0
  87. package/lib/respawn-backoff.js +35 -0
  88. package/lib/rewrite-text-nodes.js +19 -59
  89. package/lib/schemas.js +225 -41
  90. package/lib/settings.js +6 -2
  91. package/lib/smtp-auth.js +19 -1
  92. package/lib/swagger-options.js +2 -2
  93. package/lib/thread-diagnostics.js +18 -1
  94. package/lib/tls/provision.js +6 -3
  95. package/lib/token-audit-log.js +19 -20
  96. package/lib/token-permission-view.js +4 -3
  97. package/lib/tools.js +8 -41
  98. package/lib/ui-routes/admin-config-routes.js +64 -90
  99. package/lib/ui-routes/admin-entities-routes.js +2 -14
  100. package/lib/ui-routes/imap-idle-field.js +1 -1
  101. package/lib/ui-routes/outlook-subscription-view.js +1 -1
  102. package/lib/ui-routes/overridable-fields.js +84 -0
  103. package/lib/ui-routes/queue-routes.js +8 -5
  104. package/lib/ui-routes/settings-page.js +6 -0
  105. package/lib/utils/decode-headers.js +3 -12
  106. package/lib/utils/filter-empty.js +20 -0
  107. package/lib/utils/int-setting.js +48 -0
  108. package/lib/utils/tracking-settings.js +35 -0
  109. package/lib/web-safe-html.js +18 -105
  110. package/lib/webhook-delivery.js +461 -0
  111. package/lib/webhook-failures.js +132 -0
  112. package/lib/webhook-request.js +29 -1
  113. package/lib/webhook-routing.js +30 -1
  114. package/lib/webhook-test.js +88 -0
  115. package/lib/webhooks.js +59 -41
  116. package/lib/worker-rpc-error.js +2 -1
  117. package/package.json +28 -26
  118. package/sbom.json +600 -678
  119. package/server.js +149 -76
  120. package/static/css/flyonui.css +1 -1
  121. package/static/js/ace/ace.js +1 -1
  122. package/static/js/ee-client.js +650 -196
  123. package/static/licenses.html +49 -59
  124. package/translations/messages.pot +26 -26
  125. package/views/config/security.hbs +22 -0
  126. package/views/config/service.hbs +44 -0
  127. package/views/config/webhooks.hbs +36 -0
  128. package/views/layout/app.hbs +9 -6
  129. package/views/legal.hbs +8 -0
  130. package/views/partials/queue_retention_note.hbs +12 -8
  131. package/views/partials/ui/env-managed-alert.hbs +16 -7
  132. package/workers/api.js +112 -37
  133. package/workers/export.js +16 -631
  134. package/workers/imap.js +13 -0
  135. package/workers/smtp.js +9 -11
  136. package/workers/webhooks.js +18 -432
  137. package/lib/email-client/outlook-fallback-poll.js +0 -30
@@ -8,7 +8,6 @@ const {
8
8
  compareExisting,
9
9
  normalizePath,
10
10
  download,
11
- filterEmptyObjectValues,
12
11
  validUidValidity,
13
12
  mailboxPathHash,
14
13
  getMailboxStatusKey,
@@ -16,11 +15,10 @@ const {
16
15
  embedCidImages
17
16
  } = require('../../tools');
18
17
  const { samePath } = require('../../utils/mailbox-path');
19
- const { withinNotifyAttachmentSize } = require('../../notify-attachments');
18
+ const { loadNotifyAttachments } = require('../../notify-attachments');
20
19
  const { connectionNotAvailableError } = require('./connection-errors');
21
20
  const msgpack = require('../../msgpack');
22
21
  const he = require('he');
23
- const libmime = require('libmime');
24
22
  const settings = require('../../settings');
25
23
  const { bounceDetect, applyDeliveryReport, PARSER_OPTIONS: DSN_PARSER_OPTIONS } = require('../../bounce-detect');
26
24
  const { decodeHeaders } = require('../../utils/decode-headers');
@@ -28,10 +26,11 @@ const { isUnsafeKey } = require('../../utils/unsafe-key');
28
26
  const { arfDetect, camelCaseComplaint, COMPLAINT_ATTACHMENT_TYPES } = require('../../arf-detect');
29
27
  const { messageWebSafeHtml } = require('../../web-safe-html');
30
28
  const { parseMessage } = require('../../parse-message');
31
- const { parseCalendarEvent, sortCalendarAttachments, CALENDAR_CONTENT_TYPES } = require('../../calendar-event');
32
- const addressparser = require('nodemailer/lib/addressparser');
29
+ const { collectCalendarEvents } = require('../../calendar-event');
30
+ const { parseAddressHeader: parseMailboxes } = require('mailparser');
33
31
  const { llmPreProcess, summaryFetchHeaders, summaryProvider } = require('../../llm-pre-process');
34
32
  const { notificationHeaderFields, narrowHeaders } = require('../../utils/header-map');
33
+ const { getMessageOtp, notifyHeadersIncludeOtp, OTP_FETCH_HEADERS } = require('../../otp');
35
34
  const { isFailedDelivery } = require('../base-client');
36
35
 
37
36
  const {
@@ -50,7 +49,8 @@ const {
50
49
  TRANSIENT_NETWORK_CODES,
51
50
  CONNECTION_CLOSING_CODES,
52
51
  PHANTOM_SELECT_FAIL_THRESHOLD,
53
- PHANTOM_REPROBE_INTERVAL
52
+ PHANTOM_REPROBE_INTERVAL,
53
+ NEW_MESSAGE_SETTINGS
54
54
  } = require('../../consts');
55
55
 
56
56
  const {
@@ -64,6 +64,11 @@ const {
64
64
  FULL_SYNC_DELAY
65
65
  } = require('./sync-operations');
66
66
 
67
+ // Gmail categories in the order a message is matched against them, see createCategoryResolver()
68
+ const GMAIL_CATEGORIES = ['primary', 'social', 'promotions', 'updates', 'forums', 'reservations', 'purchases'];
69
+ // Queued messages whose categories one lookup covers
70
+ const CATEGORY_BATCH_SIZE = 500;
71
+
67
72
  /**
68
73
  * Whether the connection is gone, rather than this message being a problem. An enrichment step that
69
74
  * hits one must let it propagate: publishSyncedEvents() keeps the message queued for the next pass
@@ -176,17 +181,12 @@ function parseAddressHeader(values) {
176
181
  }
177
182
 
178
183
  try {
179
- let addressList = addressparser(values)
180
- .filter(address => isUsableAddress(address.address))
181
- .map(address => {
182
- let name = address.name;
183
- try {
184
- name = libmime.decodeWords(name);
185
- } catch (err) {
186
- // keep the undecoded name
187
- }
188
- return { name, address: address.address };
189
- });
184
+ // Flattened: a group ("Team: a@example.com, b@example.com;") is one entry with no address
185
+ // of its own, so the filter below used to drop every member it named. A punycode domain is
186
+ // kept as the header has it, the way the server's ENVELOPE reports it
187
+ let addressList = parseMailboxes(values, { flatten: true, decodePunycode: false })
188
+ .value.filter(address => isUsableAddress(address.address))
189
+ .map(address => ({ name: address.name, address: address.address }));
190
190
 
191
191
  return addressList.length ? addressList : undefined;
192
192
  } catch (err) {
@@ -201,7 +201,7 @@ function parseAddressHeader(values) {
201
201
  * An ENVELOPE list can come back holding no address anyone could use: RFC 9051 7.5.2 group
202
202
  * markers carry a group name and nothing else, and a server that failed to parse a malformed
203
203
  * header reports the wreckage in the shapes isUsableAddress() turns down. The raw header is
204
- * the better answer then, because addressparser sees the original value and can still recover
204
+ * the better answer then, because the header parser sees the original value and can still recover
205
205
  * the recipient. A list has to be judged on what its entries hold, not on being non-empty.
206
206
  *
207
207
  * The header is parsed only when the ENVELOPE turns out to be unusable, which is rare.
@@ -270,6 +270,7 @@ class Mailbox {
270
270
 
271
271
  this.synced = false; // Resolver of the sync() promise while a pass is waiting for its SELECT
272
272
  this.syncChain = null; // Promise of the latest sync() pass, which the next caller waits for
273
+ this.pendingSync = null; // The sync() pass waiting for its turn, shared by the calls made meanwhile
273
274
  this.syncing = false; // Whether currently syncing
274
275
  this.processingOpen = false; // Whether onOpen() is currently running for this mailbox
275
276
  this.processingOpenClient = null; // The IMAP client whose open event holds the processingOpen latch
@@ -420,8 +421,8 @@ class Mailbox {
420
421
  * @param {string} notificationType - Type of notification for logging context
421
422
  * @returns {string|null} Packed UID or null if packing failed
422
423
  */
423
- async packUidWithLogging(uid, notificationType) {
424
- let packedUid = await this.connection.packUid(this, uid);
424
+ async packUidWithLogging(uid, notificationType, statusCache) {
425
+ let packedUid = await this.connection.packUid(this, uid, statusCache);
425
426
  if (!packedUid) {
426
427
  this.logger.warn({
427
428
  msg: 'Skipping notification, packUid returned invalid result',
@@ -502,12 +503,43 @@ class Mailbox {
502
503
  * @returns {Number} Sequence number for the added entry
503
504
  */
504
505
  async entryListSet(data) {
505
- if (isNaN(data.uid)) {
506
+ const args = this.entryListSetArgs(data);
507
+ if (!args) {
506
508
  return null;
507
509
  }
508
510
 
509
- // Store in sorted set with UID as score for efficient range queries
510
- return await this.connection.redis.zSet(this.getMessagesKey(), Number(data.uid), serialize(data));
511
+ return await this.connection.redis.zSet(...args);
512
+ }
513
+
514
+ /**
515
+ * Queues the index writes of several messages onto a transaction, encoded as entryListSet()
516
+ * encodes them. A message without a numeric UID is skipped, as entryListSet() refuses it
517
+ * @param {Object} txn - Transaction from createTransaction()
518
+ * @param {Object[]} messages - Message data with uid, flags, etc.
519
+ * @returns {Object[]} The messages that were queued
520
+ */
521
+ entryListSetMany(txn, messages) {
522
+ const queued = [];
523
+ for (const data of messages) {
524
+ const args = this.entryListSetArgs(data);
525
+ if (args) {
526
+ txn.add('zSet', ...args);
527
+ queued.push(data);
528
+ }
529
+ }
530
+ return queued;
531
+ }
532
+
533
+ /**
534
+ * The zSet arguments of an index write: the sorted set has the UID as score for range queries
535
+ * @param {Object} data - Message data
536
+ * @returns {Array|null} Null for a message without a numeric UID
537
+ */
538
+ entryListSetArgs(data) {
539
+ if (isNaN(data.uid)) {
540
+ return null;
541
+ }
542
+ return [this.getMessagesKey(), Number(data.uid), serialize(data)];
511
543
  }
512
544
 
513
545
  /**
@@ -537,6 +569,30 @@ class Mailbox {
537
569
  return null;
538
570
  }
539
571
 
572
+ /**
573
+ * Index entries with a UID above `afterUid` and up to `toUid`, in UID order, in one read. An
574
+ * entry that does not parse is returned with `entry: null`, which entryListGet() answers as a
575
+ * missing entry
576
+ * @param {Number} afterUid - Exclusive lower bound
577
+ * @param {Number} toUid - Inclusive upper bound, Infinity for no bound
578
+ * @returns {Promise<Array<{uid: Number, entry: Object|null}>>}
579
+ */
580
+ async entryListRange(afterUid, toUid) {
581
+ const max = Number.isFinite(toUid) ? toUid : '+inf';
582
+ const response = await this.connection.redis.zrangebyscoreBuffer(this.getMessagesKey(), `(${afterUid}`, max, 'WITHSCORES');
583
+ const entries = [];
584
+ for (let i = 0; i < response.length; i += 2) {
585
+ let entry;
586
+ try {
587
+ entry = unserialize(response[i]);
588
+ } catch (err) {
589
+ entry = null;
590
+ }
591
+ entries.push({ uid: Number(response[i + 1].toString()), entry });
592
+ }
593
+ return entries;
594
+ }
595
+
540
596
  /**
541
597
  * Deletes entry from message list for the provided sequence value or UID
542
598
  * @param {Number} seq - Sequence number (0 if using UID)
@@ -556,6 +612,56 @@ class Mailbox {
556
612
  return null;
557
613
  }
558
614
 
615
+ /**
616
+ * Deletes several entries from the message list in one round trip, by UID, and drops whatever
617
+ * the notifications queue still holds for them in the same round trip: a message that is gone
618
+ * has nothing left to announce, which processDeleted() used to remove one message at a time
619
+ * @param {number[]} uids
620
+ * @returns {Promise<Object[]>} The entries that were deleted, in the order given
621
+ */
622
+ async entryListExpungeMany(uids) {
623
+ if (!uids.length) {
624
+ return [];
625
+ }
626
+ let pipeline = this.connection.redis.pipeline();
627
+ for (const uid of uids) {
628
+ pipeline = pipeline.zExpungeBuffer(this.getMessagesKey(), this.getMailboxKey(), 0, uid);
629
+ pipeline = pipeline.zremrangebyscore(this.getNotificationsKey(), uid, uid);
630
+ }
631
+ const results = await pipeline.exec();
632
+ const entries = [];
633
+ for (let i = 0; i < results.length; i += 2) {
634
+ const [err, response] = results[i];
635
+ if (err) {
636
+ throw err;
637
+ }
638
+ if (response) {
639
+ try {
640
+ entries.push(unserialize(response[1]));
641
+ } catch (parseErr) {
642
+ // an entry that does not parse was still removed, there is nothing to report
643
+ }
644
+ }
645
+ }
646
+ return entries;
647
+ }
648
+
649
+ /**
650
+ * UIDs of the index entries above `afterUid`, at most `limit` of them, lowest first. The entries
651
+ * themselves come along (Redis has no scores-only range), but are not decoded
652
+ * @param {number} afterUid - Exclusive lower bound
653
+ * @param {number} limit
654
+ * @returns {Promise<number[]>}
655
+ */
656
+ async entryListUidsAfter(afterUid, limit) {
657
+ const response = await this.connection.redis.zrangebyscoreBuffer(this.getMessagesKey(), `(${afterUid}`, '+inf', 'WITHSCORES', 'LIMIT', 0, limit);
658
+ const uids = [];
659
+ for (let i = 1; i < response.length; i += 2) {
660
+ uids.push(Number(response[i].toString()));
661
+ }
662
+ return uids;
663
+ }
664
+
559
665
  /**
560
666
  * Checks if this mailbox is currently selected in the IMAP connection
561
667
  * @returns {Boolean} True if selected
@@ -672,15 +778,34 @@ class Mailbox {
672
778
  * the first still waits for its SELECT would take the slot over, and the first
673
779
  * caller - the resync loop, which re-arms its timer only once every folder has
674
780
  * returned - would never be settled. Calls overlap whenever a subconnection reports
675
- * a change or a listing refresh registers folders during a resync pass
781
+ * a change or a listing refresh registers folders during a resync pass.
782
+ *
783
+ * Calls that arrive while a pass is already waiting its turn share that pass rather than
784
+ * queueing one each: it has not started yet, so it still sees everything that happened
785
+ * before they were made. A burst of moves into one folder used to queue one STATUS round
786
+ * trip per moved message
676
787
  * @param {Boolean} forceEmpty - Force sync even if mailbox appears unchanged
677
788
  * @returns {Boolean} True if synced
678
789
  */
679
790
  async sync(forceEmpty) {
680
- // A rejected pass was reported to its own caller; the next pass runs regardless
681
- const current = (this.syncChain || Promise.resolve()).catch(() => {}).then(() => this.syncOnce(forceEmpty));
682
- this.syncChain = current;
683
- return await current;
791
+ if (this.pendingSync) {
792
+ // a waiting pass forces the sync if any of the callers sharing it asked for that
793
+ this.pendingSync.forceEmpty = this.pendingSync.forceEmpty || !!forceEmpty;
794
+ return await this.pendingSync.promise;
795
+ }
796
+
797
+ const pending = { forceEmpty: !!forceEmpty };
798
+ // A rejected pass was reported to its own callers; the next pass runs regardless
799
+ pending.promise = (this.syncChain || Promise.resolve())
800
+ .catch(() => {})
801
+ .then(() => {
802
+ // started: a call made from here on needs a pass of its own
803
+ this.pendingSync = null;
804
+ return this.syncOnce(pending.forceEmpty);
805
+ });
806
+ this.pendingSync = pending;
807
+ this.syncChain = pending.promise;
808
+ return await pending.promise;
684
809
  }
685
810
 
686
811
  /**
@@ -953,11 +1078,83 @@ class Mailbox {
953
1078
  return lock;
954
1079
  }
955
1080
 
1081
+ /**
1082
+ * Runs `fn` under the lock of a message's folder, released however `fn` ends
1083
+ * @param {Object} connectionClient - IMAP client to use
1084
+ * @param {Object} message - Unpacked message reference, see lockForMessage()
1085
+ * @param {Object} options - Lock options
1086
+ * @param {Function} fn - The work to do under the lock
1087
+ * @returns {*} What `fn` returned, or false when the reference was issued for a previous
1088
+ * incarnation of this folder (fn is not called then)
1089
+ */
1090
+ async withMessageLock(connectionClient, message, options, fn) {
1091
+ let lock = await this.lockForMessage(connectionClient, message, options);
1092
+ if (!lock) {
1093
+ // issued for a previous incarnation of this folder
1094
+ return false;
1095
+ }
1096
+ try {
1097
+ return await fn();
1098
+ } finally {
1099
+ lock.release();
1100
+ }
1101
+ }
1102
+
1103
+ /**
1104
+ * Runs `fn` under this folder's lock, released however `fn` ends
1105
+ * @param {Object} connectionClient - IMAP client to use
1106
+ * @param {Object} options - Lock options
1107
+ * @param {Function} fn - The work to do under the lock
1108
+ * @returns {*} What `fn` returned
1109
+ */
1110
+ async withMailboxLock(connectionClient, options, fn) {
1111
+ let lock = await this.getMailboxLock(connectionClient, options);
1112
+ try {
1113
+ return await fn();
1114
+ } finally {
1115
+ lock.release();
1116
+ }
1117
+ }
1118
+
1119
+ /**
1120
+ * Takes this folder's lock on a connection
1121
+ * @param {Object} [connectionClient] - IMAP client to use, the primary connection by default
1122
+ * @param {Object} [options] - ImapFlow lock options, plus `refresh`: the caller is about to
1123
+ * read the session's view of the folder (counters, SEARCH), so make sure it is current.
1124
+ * A folder the connection already has open is not selected again, and a change made over
1125
+ * another connection (a move over the command connection) reaches that view only once the
1126
+ * server reports it, which a server may hold until the next command boundary. A NOOP is
1127
+ * that boundary. Not needed when the connection was idling, IDLE reports changes as they
1128
+ * happen
1129
+ * @returns {Object} Lock object with release()
1130
+ */
956
1131
  async getMailboxLock(connectionClient, options) {
957
1132
  connectionClient = connectionClient || this.requireImapClient();
958
1133
 
959
- let lock = await connectionClient.getMailboxLock(this.path, options || {});
1134
+ let { refresh, ...lockOptions } = options || {};
1135
+ let needsRefresh = !!refresh && !!connectionClient.mailbox && samePath(connectionClient.mailbox.path, this.path) && !connectionClient.idling;
960
1136
 
1137
+ let lock = await this.wrapLock(connectionClient, await connectionClient.getMailboxLock(this.path, lockOptions));
1138
+
1139
+ if (needsRefresh) {
1140
+ try {
1141
+ await connectionClient.noop();
1142
+ } catch (err) {
1143
+ lock.release();
1144
+ throw err;
1145
+ }
1146
+ }
1147
+
1148
+ return lock;
1149
+ }
1150
+
1151
+ /**
1152
+ * A lock on the primary connection reports the task when it is released, see onTaskCompleted()
1153
+ * @param {Object} connectionClient - IMAP client the lock was taken on
1154
+ * @param {Object} lock - ImapFlow lock
1155
+ * @returns {Object} Lock object with release()
1156
+ */
1157
+ wrapLock(connectionClient, lock) {
961
1158
  if (connectionClient !== this.connection.imapClient) {
962
1159
  return lock;
963
1160
  }
@@ -1011,22 +1208,41 @@ class Mailbox {
1011
1208
  return;
1012
1209
  }
1013
1210
 
1014
- // Debounce partial sync to avoid multiple syncs for rapid changes
1211
+ this.schedulePartialSync(() => this.shouldRunPartialSyncAfterExists(), 'EXISTS');
1212
+ }
1213
+
1214
+ /**
1215
+ * Handles a HIGHESTMODSEQ change ImapFlow found while polling a server without IDLE (the
1216
+ * `highestModseq` event, ImapFlow 2.6.0). Such a server sends no FETCH for a flag change, so
1217
+ * this is the only sign of one before the next resync
1218
+ * @param {Object} event - `{ path, highestModseq, prevHighestModseq }`
1219
+ */
1220
+ async onHighestModseq(event) {
1221
+ this.logEvent('HIGHESTMODSEQ changed', event);
1222
+
1223
+ if (this.syncDisabled) {
1224
+ return;
1225
+ }
1226
+
1227
+ this.schedulePartialSync(async () => true, 'HIGHESTMODSEQ');
1228
+ }
1229
+
1230
+ /**
1231
+ * Debounces a partial sync so a burst of changes runs one
1232
+ * @param {Function} shouldRun - Async check made when the timer fires
1233
+ * @param {string} trigger - What asked for it, for the log
1234
+ */
1235
+ schedulePartialSync(shouldRun, trigger) {
1015
1236
  clearTimeout(this.runPartialSyncTimer);
1016
1237
  this.runPartialSyncTimer = setTimeout(() => {
1017
1238
  this.runPartialSyncTimer = null;
1018
- this.shouldRunPartialSyncAfterExists()
1019
- .then(shouldRun => {
1020
- if (shouldRun) {
1021
- return this.partialSync();
1022
- }
1023
- return false;
1024
- })
1239
+ shouldRun()
1240
+ .then(run => (run ? this.partialSync() : false))
1025
1241
  .catch(err => {
1026
1242
  if (CONNECTION_CLOSING_CODES.has(err.code)) {
1027
1243
  this.logger.debug({ msg: 'Sync skipped, connection closing', err });
1028
1244
  } else {
1029
- this.logger.warn({ msg: 'Failed to sync mailbox after EXISTS', err });
1245
+ this.logger.warn({ msg: `Failed to sync mailbox after ${trigger}`, err });
1030
1246
  }
1031
1247
  });
1032
1248
  }, 1000);
@@ -1125,12 +1341,16 @@ class Mailbox {
1125
1341
  /**
1126
1342
  * Processes a deleted message and sends the notification
1127
1343
  * @param {Object} messageData - Deleted message data
1344
+ * @param {Object} [opts]
1345
+ * @param {Map} [opts.statusCache] - Shared by the messages of one batch, see packUid()
1346
+ * @param {boolean} [opts.dequeued] - The notifications queue entry was already removed, by
1347
+ * entryListExpungeMany()
1128
1348
  */
1129
- async processDeleted(messageData) {
1349
+ async processDeleted(messageData, opts = {}) {
1130
1350
  this.logger.debug({ msg: 'Message deleted', uid: messageData.uid });
1131
1351
 
1132
1352
  // Generate packed UID for external reference
1133
- let packedUid = await this.packUidWithLogging(messageData.uid, 'delete');
1353
+ let packedUid = await this.packUidWithLogging(messageData.uid, 'delete', opts.statusCache);
1134
1354
  if (!packedUid) {
1135
1355
  return;
1136
1356
  }
@@ -1139,6 +1359,10 @@ class Mailbox {
1139
1359
  uid: messageData.uid
1140
1360
  });
1141
1361
 
1362
+ if (opts.dequeued) {
1363
+ return;
1364
+ }
1365
+
1142
1366
  try {
1143
1367
  // Remove from notifications queue since message no longer exists
1144
1368
  await this.connection.redis.zremrangebyscore(this.getNotificationsKey(), messageData.uid, messageData.uid);
@@ -1193,7 +1417,7 @@ class Mailbox {
1193
1417
  * @param {Object} options - Processing options
1194
1418
  * @param {Object} storedStatus - Current mailbox status
1195
1419
  */
1196
- async processNew(messageData, options, storedStatus) {
1420
+ async processNew(messageData, options, storedStatus, categories, passSettings) {
1197
1421
  this.logger.debug({ msg: 'New message', uid: messageData.uid, flags: Array.from(messageData.flags) });
1198
1422
 
1199
1423
  options.skipLock = true;
@@ -1444,6 +1668,8 @@ class Mailbox {
1444
1668
  });
1445
1669
  }
1446
1670
  } catch (err) {
1671
+ // A parser failure leaves the IMAP download unconsumed, as in the DSN branch above
1672
+ content?.destroy?.();
1447
1673
  if (isConnectionGone(err)) {
1448
1674
  throw err;
1449
1675
  }
@@ -1457,145 +1683,49 @@ class Mailbox {
1457
1683
  }
1458
1684
  }
1459
1685
 
1686
+ // The settings the rest of this message reads: those the pass read once, or one round trip
1687
+ const { notifyAttachments, notifyAttachmentSize, notifyCalendarEvents, notifyWebSafeHtml, resolveGmailCategories } =
1688
+ passSettings || (await settings.getMulti(...NEW_MESSAGE_SETTINGS));
1689
+
1460
1690
  // Resolve Gmail category for inbox messages
1461
1691
  if (
1462
1692
  this.connection.imapClient?.capabilities?.has('X-GM-EXT-1') &&
1463
1693
  this.isAllMail &&
1464
1694
  messageInfo.labels &&
1465
1695
  messageInfo.labels.includes('\\Inbox') &&
1466
- (await settings.get('resolveGmailCategories'))
1696
+ resolveGmailCategories
1467
1697
  ) {
1468
- this.logger.trace({
1469
- msg: 'Resolving category for incoming email',
1470
- uid: messageData.uid,
1471
- id: messageInfo.id
1472
- });
1473
-
1474
- // Try each Gmail category in order
1475
- for (let category of ['primary', 'social', 'promotions', 'updates', 'forums', 'reservations', 'purchases']) {
1476
- try {
1477
- let results = await this.requireImapClient().search(
1478
- {
1479
- uid: messageInfo.uid,
1480
- gmraw: `category:${category}`
1481
- },
1482
- { uid: true }
1483
- );
1484
- if (results && results.includes(messageInfo.uid)) {
1485
- messageInfo.category = category;
1486
- this.logger.debug({
1487
- msg: 'Resolved category for incoming email',
1488
- category,
1489
- uid: messageData.uid,
1490
- id: messageInfo.id
1491
- });
1492
- break;
1493
- }
1494
- } catch (err) {
1495
- if (isConnectionGone(err)) {
1496
- throw err;
1497
- }
1498
- this.logger.warn({ msg: 'Failed to resolve category for message', err, category, uid: messageData.uid, id: messageInfo.id });
1499
- break;
1698
+ try {
1699
+ const category = await (categories || this.createCategoryResolver()).categoryOf(messageInfo.uid);
1700
+ if (category) {
1701
+ messageInfo.category = category;
1702
+ this.logger.debug({
1703
+ msg: 'Resolved category for incoming email',
1704
+ category,
1705
+ uid: messageData.uid,
1706
+ id: messageInfo.id
1707
+ });
1708
+ }
1709
+ } catch (err) {
1710
+ if (isConnectionGone(err)) {
1711
+ throw err;
1500
1712
  }
1713
+ this.logger.warn({ msg: 'Failed to resolve category for message', err, uid: messageData.uid, id: messageInfo.id });
1501
1714
  }
1502
1715
  }
1503
1716
 
1717
+ const loadAttachment = attachment => this.loadAttachmentContent(messageInfo, attachment, options);
1718
+
1504
1719
  // Download attachment content if configured
1505
- let notifyAttachments = await settings.get('notifyAttachments');
1506
- let notifyAttachmentSize = await settings.get('notifyAttachmentSize');
1507
- if (notifyAttachments && messageInfo.attachments?.length) {
1508
- for (let attachment of messageInfo.attachments || []) {
1509
- if (!withinNotifyAttachmentSize(attachment, notifyAttachmentSize)) {
1510
- // skip large attachments
1511
- continue;
1512
- }
1513
- if (!attachment.content) {
1514
- await this.loadAttachmentContent(messageInfo, attachment, options);
1515
- }
1516
- }
1720
+ if (notifyAttachments) {
1721
+ await loadNotifyAttachments(messageInfo.attachments, notifyAttachmentSize, loadAttachment);
1517
1722
  }
1518
1723
 
1519
1724
  // Fetch and process calendar events if needed
1520
- let notifyCalendarEvents = await settings.get('notifyCalendarEvents');
1521
- if (notifyCalendarEvents && messageInfo.attachments && messageInfo.attachments.length) {
1522
- let calendarEventMap = new Map();
1523
-
1524
- // Process calendar attachments, text/calendar before application/ics
1525
- for (let attachment of [...messageInfo.attachments].sort(sortCalendarAttachments)) {
1526
- if (CALENDAR_CONTENT_TYPES.includes(attachment.contentType)) {
1527
- // Download calendar attachment if not already loaded
1528
- if (!attachment.content) {
1529
- await this.loadAttachmentContent(messageInfo, attachment, options);
1530
- }
1531
- if (attachment.content) {
1532
- let contentBuf = Buffer.from(attachment.content, 'base64');
1533
- try {
1534
- const event = parseCalendarEvent(contentBuf);
1535
- if (!event) {
1536
- continue;
1537
- }
1538
-
1539
- // Skip if we already processed this event
1540
- if (calendarEventMap.has(event.eventId)) {
1541
- if (attachment.filename) {
1542
- let existingEntry = calendarEventMap.get(event.eventId);
1543
- if (!existingEntry.filename) {
1544
- // inject filename
1545
- existingEntry.filename = attachment.filename;
1546
- }
1547
- }
1548
- continue;
1549
- }
1550
-
1551
- // Store calendar event data
1552
- calendarEventMap.set(
1553
- event.eventId,
1554
- filterEmptyObjectValues({
1555
- eventId: event.eventId,
1556
- attachment: attachment.id,
1557
- method: attachment.method || event.method || null,
1558
-
1559
- summary: event.summary,
1560
- description: event.description,
1561
- timezone: event.timezone,
1562
- startDate: event.startDate,
1563
- endDate: event.endDate,
1564
- organizer: event.organizer,
1565
-
1566
- filename: attachment.filename,
1567
- contentType: attachment.contentType,
1568
- encoding: 'base64',
1569
- content: attachment.content
1570
- })
1571
- );
1572
- } catch (err) {
1573
- this.logger.warn({
1574
- msg: 'Failed to parse calendar event',
1575
- attachment: Object.assign({}, attachment, { content: `${contentBuf.length} bytes` }),
1576
- err
1577
- });
1578
- }
1579
- }
1580
- }
1581
- }
1582
-
1583
- if (calendarEventMap && calendarEventMap.size) {
1584
- messageInfo.calendarEvents = Array.from(calendarEventMap.values()).map(calendarEvent => {
1585
- // Generate default filename based on method
1586
- if (!calendarEvent.filename) {
1587
- switch (calendarEvent.method && calendarEvent.method.toUpperCase()) {
1588
- case 'CANCEL':
1589
- case 'REQUEST':
1590
- calendarEvent.filename = 'invite.ics';
1591
- break;
1592
- default:
1593
- calendarEvent.filename = 'event.ics';
1594
- break;
1595
- }
1596
- }
1597
- return calendarEvent;
1598
- });
1725
+ if (notifyCalendarEvents) {
1726
+ const calendarEvents = await collectCalendarEvents(messageInfo.attachments, loadAttachment, this.logger);
1727
+ if (calendarEvents) {
1728
+ messageInfo.calendarEvents = calendarEvents;
1599
1729
  }
1600
1730
  }
1601
1731
 
@@ -1622,7 +1752,6 @@ class Mailbox {
1622
1752
  }
1623
1753
 
1624
1754
  // Convert message HTML to web safe HTML
1625
- let notifyWebSafeHtml = await settings.get('notifyWebSafeHtml');
1626
1755
  if (notifyWebSafeHtml && messageInfo.text && (messageInfo.text.html || messageInfo.text.plain)) {
1627
1756
  // convert to web safe
1628
1757
  messageInfo.text._generatedHtml = await messageWebSafeHtml(messageInfo);
@@ -1758,13 +1887,13 @@ class Mailbox {
1758
1887
  * @param {Boolean} extended - Include extended information
1759
1888
  * @returns {Object} Formatted message info
1760
1889
  */
1761
- async getMessageInfo(messageData, extended) {
1890
+ async getMessageInfo(messageData, extended, statusCache) {
1762
1891
  if (!messageData) {
1763
1892
  return false;
1764
1893
  }
1765
1894
 
1766
1895
  // Generate unique message ID
1767
- let packedUid = await this.connection.packUid(this, messageData.uid);
1896
+ let packedUid = await this.connection.packUid(this, messageData.uid, statusCache);
1768
1897
 
1769
1898
  if (!packedUid) {
1770
1899
  let storedStatus;
@@ -1882,6 +2011,11 @@ class Mailbox {
1882
2011
  result.isAutoReply = true;
1883
2012
  }
1884
2013
 
2014
+ const otp = extended && getMessageOtp(headers, summaryProvider(this.connection));
2015
+ if (otp) {
2016
+ result.otp = otp;
2017
+ }
2018
+
1885
2019
  return result;
1886
2020
  }
1887
2021
 
@@ -1983,9 +2117,10 @@ class Mailbox {
1983
2117
  * Processes flag changes for a message
1984
2118
  * @param {Object} messageData - Message data with changes
1985
2119
  * @param {Object} changes - What changed
2120
+ * @param {Map} [statusCache] - Shared by the messages of one batch, see packUid()
1986
2121
  */
1987
- async processChanges(messageData, changes) {
1988
- let packedUid = await this.packUidWithLogging(messageData.uid, 'update');
2122
+ async processChanges(messageData, changes, statusCache) {
2123
+ let packedUid = await this.packUidWithLogging(messageData.uid, 'update', statusCache);
1989
2124
  if (!packedUid) {
1990
2125
  return;
1991
2126
  }
@@ -2023,6 +2158,53 @@ class Mailbox {
2023
2158
  return this.syncOps.seedMailboxIndex(mailboxStatus, options);
2024
2159
  }
2025
2160
 
2161
+ /**
2162
+ * Resolves the Gmail category (X-GM-RAW category:...) of new Inbox messages. Asked for one
2163
+ * message, it looks up every message still queued for announcing in the same pass (up to
2164
+ * CATEGORY_BATCH_SIZE), one search per category over all of them, instead of up to seven searches
2165
+ * for each message. Categories are tried in GMAIL_CATEGORIES order and the first match wins, as it
2166
+ * did per message. A message queued after the lookup gets a lookup of its own
2167
+ * @returns {{categoryOf: Function}}
2168
+ */
2169
+ createCategoryResolver() {
2170
+ const resolved = new Map();
2171
+ const searched = new Set();
2172
+
2173
+ const lookup = async uids => {
2174
+ const uidSet = uids.join(',');
2175
+ let pending = new Set(uids);
2176
+ try {
2177
+ for (const category of GMAIL_CATEGORIES) {
2178
+ const results = await this.requireImapClient().search({ uid: uidSet, gmraw: `category:${category}` }, { uid: true });
2179
+ for (const uid of results || []) {
2180
+ if (pending.delete(uid)) {
2181
+ resolved.set(uid, category);
2182
+ }
2183
+ }
2184
+ if (!pending.size) {
2185
+ break;
2186
+ }
2187
+ }
2188
+ } finally {
2189
+ // a failed lookup is not repeated for each message of the batch
2190
+ uids.forEach(uid => searched.add(uid));
2191
+ }
2192
+ };
2193
+
2194
+ return {
2195
+ categoryOf: async uid => {
2196
+ if (!searched.has(uid)) {
2197
+ // the UIDs are the scores; the members are full payloads this has no use for
2198
+ const uids = (await this.connection.redis.zHeadScores(this.getNotificationsKey(), CATEGORY_BATCH_SIZE)).map(Number);
2199
+ const batch = [...new Set([uid].concat(uids))].filter(other => !searched.has(other));
2200
+ this.logger.trace({ msg: 'Resolving categories for incoming email', uid, batch: batch.length });
2201
+ await lookup(batch);
2202
+ }
2203
+ return resolved.get(uid) || null;
2204
+ }
2205
+ };
2206
+ }
2207
+
2026
2208
  /**
2027
2209
  * Processes queued notification events after sync
2028
2210
  * Fetches full message details and sends notifications
@@ -2056,9 +2238,16 @@ class Mailbox {
2056
2238
  (this.isAllMail || this.listingEntry.specialUse === '\\Inbox') && (await llmPreProcess.getPreProcessHandler())
2057
2239
  ? summaryFetchHeaders(summaryProvider(this.connection))
2058
2240
  : [];
2059
- messageFetchOptions.fetchHeaders = notificationHeaderFields(messageFetchOptions.headers, summaryHeaders);
2241
+ const otpHeaders = notifyHeadersIncludeOtp(notifyHeaders) ? OTP_FETCH_HEADERS : [];
2242
+ messageFetchOptions.fetchHeaders = notificationHeaderFields(messageFetchOptions.headers, summaryHeaders.concat(otpHeaders));
2060
2243
  }
2061
2244
 
2245
+ // Gmail categories of the messages this pass announces, looked up together
2246
+ const categories = this.createCategoryResolver();
2247
+
2248
+ // Read once for every message the pass announces, not once per message
2249
+ const passSettings = await settings.getMulti(...NEW_MESSAGE_SETTINGS);
2250
+
2062
2251
  // Peek-then-remove: read entries without removing so that connection errors
2063
2252
  // leave unprocessed entries in Redis for retry on reconnect.
2064
2253
  let queuedEntry;
@@ -2086,7 +2275,7 @@ class Mailbox {
2086
2275
  }
2087
2276
 
2088
2277
  try {
2089
- await this.processNew(messageData, messageFetchOptions, storedStatus);
2278
+ await this.processNew(messageData, messageFetchOptions, storedStatus, categories, passSettings);
2090
2279
  await this.connection.redis.zrem(notificationsKey, rawMember);
2091
2280
  this.throttledArrivals?.delete(rawMember);
2092
2281
  } catch (err) {
@@ -2687,13 +2876,7 @@ class Mailbox {
2687
2876
 
2688
2877
  const connectionClient = await this.connection.getImapConnection(connectionOptions);
2689
2878
 
2690
- let lock = await this.lockForMessage(connectionClient, message, { description: `Update message: ${message.uid}` });
2691
- if (!lock) {
2692
- // issued for a previous incarnation of this folder
2693
- return false;
2694
- }
2695
-
2696
- try {
2879
+ return await this.withMessageLock(connectionClient, message, { description: `Update message: ${message.uid}` }, async () => {
2697
2880
  let result = {};
2698
2881
 
2699
2882
  // Update flags
@@ -2751,9 +2934,7 @@ class Mailbox {
2751
2934
  }
2752
2935
 
2753
2936
  return result;
2754
- } finally {
2755
- lock.release();
2756
- }
2937
+ });
2757
2938
  }
2758
2939
 
2759
2940
  /**
@@ -2768,9 +2949,7 @@ class Mailbox {
2768
2949
 
2769
2950
  const connectionClient = await this.connection.getImapConnection(connectionOptions);
2770
2951
 
2771
- let lock = await this.getMailboxLock(connectionClient, { description: `Update messages` });
2772
-
2773
- try {
2952
+ return await this.withMailboxLock(connectionClient, { description: `Update messages`, refresh: true }, async () => {
2774
2953
  let result = {};
2775
2954
 
2776
2955
  // Update flags for matching messages
@@ -2828,9 +3007,7 @@ class Mailbox {
2828
3007
  }
2829
3008
 
2830
3009
  return result;
2831
- } finally {
2832
- lock.release();
2833
- }
3010
+ });
2834
3011
  }
2835
3012
 
2836
3013
  /**
@@ -2846,13 +3023,7 @@ class Mailbox {
2846
3023
 
2847
3024
  const connectionClient = await this.connection.getImapConnection(connectionOptions);
2848
3025
 
2849
- let lock = await this.lockForMessage(connectionClient, message, { description: `Move message: ${message.uid} to: ${target.path}` });
2850
- if (!lock) {
2851
- // issued for a previous incarnation of this folder
2852
- return false;
2853
- }
2854
-
2855
- try {
3026
+ return await this.withMessageLock(connectionClient, message, { description: `Move message: ${message.uid} to: ${target.path}` }, async () => {
2856
3027
  let result = {};
2857
3028
 
2858
3029
  if (target.path) {
@@ -2870,9 +3041,7 @@ class Mailbox {
2870
3041
  }
2871
3042
 
2872
3043
  return result;
2873
- } finally {
2874
- lock.release();
2875
- }
3044
+ });
2876
3045
  }
2877
3046
 
2878
3047
  /**
@@ -2887,9 +3056,7 @@ class Mailbox {
2887
3056
 
2888
3057
  const connectionClient = await this.connection.getImapConnection(connectionOptions);
2889
3058
 
2890
- let lock = await this.getMailboxLock(connectionClient, { description: `Move messages to: ${target.path}` });
2891
-
2892
- try {
3059
+ return await this.withMailboxLock(connectionClient, { description: `Move messages to: ${target.path}`, refresh: true }, async () => {
2893
3060
  let result = {};
2894
3061
 
2895
3062
  if (target.path) {
@@ -2908,9 +3075,7 @@ class Mailbox {
2908
3075
  }
2909
3076
 
2910
3077
  return result;
2911
- } finally {
2912
- lock.release();
2913
- }
3078
+ });
2914
3079
  }
2915
3080
 
2916
3081
  /**
@@ -2923,13 +3088,7 @@ class Mailbox {
2923
3088
  async deleteMessage(message, force, connectionOptions) {
2924
3089
  const connectionClient = await this.connection.getImapConnection(connectionOptions);
2925
3090
 
2926
- let lock = await this.lockForMessage(connectionClient, message, { description: `Delete message: ${message.uid}` });
2927
- if (!lock) {
2928
- // issued for a previous incarnation of this folder
2929
- return false;
2930
- }
2931
-
2932
- try {
3091
+ return await this.withMessageLock(connectionClient, message, { description: `Delete message: ${message.uid}` }, async () => {
2933
3092
  let result = {};
2934
3093
 
2935
3094
  // Permanently delete if in Trash/Junk or forced
@@ -2959,9 +3118,7 @@ class Mailbox {
2959
3118
  }
2960
3119
 
2961
3120
  return result;
2962
- } finally {
2963
- lock.release();
2964
- }
3121
+ });
2965
3122
  }
2966
3123
 
2967
3124
  /**
@@ -2974,9 +3131,7 @@ class Mailbox {
2974
3131
  async deleteMessages(search, force, connectionOptions) {
2975
3132
  const connectionClient = await this.connection.getImapConnection(connectionOptions);
2976
3133
 
2977
- let lock = await this.getMailboxLock(connectionClient, { description: `Delete messages` });
2978
-
2979
- try {
3134
+ return await this.withMailboxLock(connectionClient, { description: `Delete messages`, refresh: true }, async () => {
2980
3135
  let result = {};
2981
3136
 
2982
3137
  // Permanently delete if in Trash/Junk or forced
@@ -3010,9 +3165,7 @@ class Mailbox {
3010
3165
  }
3011
3166
 
3012
3167
  return result;
3013
- } finally {
3014
- lock.release();
3015
- }
3168
+ });
3016
3169
  }
3017
3170
 
3018
3171
  /**
@@ -3042,9 +3195,8 @@ class Mailbox {
3042
3195
 
3043
3196
  const connectionClient = await this.connection.getImapConnection(connectionOptions);
3044
3197
 
3045
- let lock = await this.getMailboxLock(connectionClient, { description: `List messages from: ${this.path}` });
3046
-
3047
- try {
3198
+ // refresh: the counters and the SEARCH below read the session's view of the folder
3199
+ return await this.withMailboxLock(connectionClient, { description: `List messages from: ${this.path}`, refresh: true }, async () => {
3048
3200
  let mailboxStatus = this.getMailboxStatus(connectionClient);
3049
3201
 
3050
3202
  let messageCount = mailboxStatus.messages;
@@ -3140,6 +3292,9 @@ class Mailbox {
3140
3292
  }
3141
3293
  }
3142
3294
 
3295
+ // One stored status read for the whole page, not one per message
3296
+ const statusCache = new Map();
3297
+
3143
3298
  // Fetch messages in the range
3144
3299
  for await (let messageData of connectionClient.fetch(range, fields, opts)) {
3145
3300
  if (!messageData || !messageData.uid) {
@@ -3149,7 +3304,7 @@ class Mailbox {
3149
3304
  }
3150
3305
  let messageInfo;
3151
3306
  try {
3152
- messageInfo = await this.getMessageInfo(messageData);
3307
+ messageInfo = await this.getMessageInfo(messageData, false, statusCache);
3153
3308
  } catch (err) {
3154
3309
  // Return error info for failed messages
3155
3310
  messageInfo = {
@@ -3171,9 +3326,7 @@ class Mailbox {
3171
3326
  // List newer entries first. Servers like yahoo do not return ordered list, so we need to order manually
3172
3327
  messages: messages.sort((a, b) => b.uid - a.uid)
3173
3328
  };
3174
- } finally {
3175
- lock.release();
3176
- }
3329
+ });
3177
3330
  }
3178
3331
 
3179
3332
  /**