emailengine-app 2.84.2 → 2.86.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 (164) hide show
  1. package/.ncurc.js +29 -9
  2. package/.prettierignore +5 -1
  3. package/.prettierrc.js +2 -0
  4. package/.release-please-manifest.json +1 -1
  5. package/CHANGELOG.md +107 -0
  6. package/Dockerfile +20 -1
  7. package/ENVIRONMENT.md +139 -0
  8. package/README.md +2 -2
  9. package/bin/emailengine.js +434 -408
  10. package/config/default.toml +2 -0
  11. package/copy-static-files.sh +41 -14
  12. package/data/google-crawlers.json +1 -1
  13. package/data/public_suffix_list.dat +16563 -0
  14. package/eslint.config.js +81 -99
  15. package/lib/account-assignment.js +19 -0
  16. package/lib/account.js +230 -170
  17. package/lib/api-error-codes.js +49 -0
  18. package/lib/api-reference/format.js +4 -3
  19. package/lib/api-reference/model.js +6 -1
  20. package/lib/api-routes/account-routes.js +255 -38
  21. package/lib/api-routes/blocklist-routes.js +91 -4
  22. package/lib/api-routes/delivery-test-routes.js +27 -4
  23. package/lib/api-routes/export-routes.js +28 -2
  24. package/lib/api-routes/gateway-routes.js +110 -12
  25. package/lib/api-routes/index.js +4 -0
  26. package/lib/api-routes/license-routes.js +2 -2
  27. package/lib/api-routes/mailbox-routes.js +44 -5
  28. package/lib/api-routes/message-routes.js +112 -10
  29. package/lib/api-routes/oauth2-app-routes.js +63 -23
  30. package/lib/api-routes/outbox-routes.js +97 -52
  31. package/lib/api-routes/permission-map.js +67 -7
  32. package/lib/api-routes/scoped-routes.js +74 -0
  33. package/lib/api-routes/settings-routes.js +34 -6
  34. package/lib/api-routes/stats-routes.js +5 -1
  35. package/lib/api-routes/submit-routes.js +337 -309
  36. package/lib/api-routes/template-routes.js +45 -8
  37. package/lib/api-routes/token-routes.js +152 -100
  38. package/lib/api-routes/webhook-delivery-routes.js +262 -0
  39. package/lib/api-routes/webhook-route-routes.js +132 -6
  40. package/lib/bounce-detect.js +397 -205
  41. package/lib/calendar-event.js +81 -1
  42. package/lib/consts.js +38 -45
  43. package/lib/db.js +14 -6
  44. package/lib/delivery-error.js +6 -0
  45. package/lib/deprecations.js +270 -0
  46. package/lib/email-client/base-client.js +137 -184
  47. package/lib/email-client/fallback-poll.js +62 -0
  48. package/lib/email-client/gmail-client.js +60 -22
  49. package/lib/email-client/imap/adaptive-idle-store.js +73 -0
  50. package/lib/email-client/imap/adaptive-idle.js +278 -0
  51. package/lib/email-client/imap/connection-errors.js +14 -1
  52. package/lib/email-client/imap/idle-settings.js +31 -5
  53. package/lib/email-client/imap/listing-diff.js +37 -0
  54. package/lib/email-client/imap/mailbox.js +372 -242
  55. package/lib/email-client/imap/subconnection.js +8 -30
  56. package/lib/email-client/imap/sync-operations.js +220 -127
  57. package/lib/email-client/imap-client.js +228 -164
  58. package/lib/email-client/message-builder.js +14 -79
  59. package/lib/email-client/notification-handler.js +1 -2
  60. package/lib/email-client/outlook-client.js +372 -338
  61. package/lib/email-client/smtp-pool-manager.js +16 -13
  62. package/lib/email-client/sync-state-fields.js +19 -0
  63. package/lib/encrypt.js +157 -41
  64. package/lib/enum-descriptions.js +3 -1
  65. package/lib/env-setting-overrides.js +288 -0
  66. package/lib/export-worker.js +751 -0
  67. package/lib/export.js +64 -15
  68. package/lib/gateway.js +19 -4
  69. package/lib/get-raw-email.js +25 -107
  70. package/lib/hapi-request-logger.js +107 -0
  71. package/lib/health.js +75 -0
  72. package/lib/imapproxy/imap-core/README.md +6 -5
  73. package/lib/lock-run.js +119 -0
  74. package/lib/logger-consts.js +48 -0
  75. package/lib/logger.js +1 -1
  76. package/lib/lua/z-head-scores.lua +28 -0
  77. package/lib/mcp/tools.js +37 -8
  78. package/lib/network-errors.js +1 -1
  79. package/lib/node-version.js +24 -0
  80. package/lib/notify-attachments.js +36 -0
  81. package/lib/oauth/outlook-mailbox.js +35 -0
  82. package/lib/oauth/state.js +24 -0
  83. package/lib/oauth2-apps.js +631 -656
  84. package/lib/outbox.js +184 -54
  85. package/lib/parse-message.js +3 -3
  86. package/lib/pbkdf2-phc.js +1 -1
  87. package/lib/privileged-settings.js +2 -2
  88. package/lib/queue-browser/definitions.js +11 -0
  89. package/lib/queue-browser/index.js +68 -19
  90. package/lib/queue-job-actions.js +18 -1
  91. package/lib/queue-retention.js +48 -12
  92. package/lib/queue-stats.js +11 -2
  93. package/lib/read-env-value.js +3 -0
  94. package/lib/redis-memory-warnings.js +99 -0
  95. package/lib/redis-reconnect.js +29 -0
  96. package/lib/request-timing.js +23 -0
  97. package/lib/respawn-backoff.js +35 -0
  98. package/lib/rewrite-text-nodes.js +19 -59
  99. package/lib/schemas.js +164 -40
  100. package/lib/settings.js +6 -2
  101. package/lib/smtp-auth.js +19 -1
  102. package/lib/sso.js +1 -1
  103. package/lib/swagger-options.js +1 -1
  104. package/lib/thread-diagnostics.js +63 -0
  105. package/lib/timezones.js +109 -0
  106. package/lib/tls/provision.js +6 -3
  107. package/lib/token-audit-log.js +19 -20
  108. package/lib/token-permission-view.js +7 -6
  109. package/lib/tools.js +48 -51
  110. package/lib/totp.js +2 -5
  111. package/lib/translations.js +1 -2
  112. package/lib/ui-routes/account-routes.js +475 -454
  113. package/lib/ui-routes/account-setup.js +99 -0
  114. package/lib/ui-routes/admin-config-routes.js +152 -100
  115. package/lib/ui-routes/admin-entities-routes.js +93 -21
  116. package/lib/ui-routes/auth-routes.js +90 -38
  117. package/lib/ui-routes/imap-idle-field.js +1 -1
  118. package/lib/ui-routes/internals-routes.js +5 -0
  119. package/lib/ui-routes/oauth-config-routes.js +124 -82
  120. package/lib/ui-routes/outlook-subscription-view.js +1 -1
  121. package/lib/ui-routes/overridable-fields.js +84 -0
  122. package/lib/ui-routes/queue-routes.js +8 -5
  123. package/lib/ui-routes/route-helpers.js +19 -3
  124. package/lib/ui-routes/settings-page.js +6 -0
  125. package/lib/ui-routes/tls-config-routes.js +58 -15
  126. package/lib/utils/back-off.js +82 -0
  127. package/lib/utils/decode-headers.js +3 -12
  128. package/lib/utils/filter-empty.js +20 -0
  129. package/lib/utils/int-setting.js +48 -0
  130. package/lib/utils/murmurhash3.js +66 -0
  131. package/lib/utils/public-suffix.js +122 -0
  132. package/lib/utils/random-id.js +26 -0
  133. package/lib/utils/tracking-settings.js +35 -0
  134. package/lib/utils/version.js +74 -0
  135. package/lib/web-safe-html.js +18 -105
  136. package/lib/webhook-delivery.js +461 -0
  137. package/lib/webhook-failures.js +132 -0
  138. package/lib/webhook-request.js +29 -1
  139. package/lib/webhook-routing.js +56 -0
  140. package/lib/webhook-test.js +88 -0
  141. package/lib/webhooks.js +93 -45
  142. package/lib/worker-rpc-error.js +2 -1
  143. package/package.json +37 -38
  144. package/sbom.json +7902 -1
  145. package/server.js +784 -518
  146. package/static/js/ace/ace.js +1 -1
  147. package/static/licenses.html +225 -1060
  148. package/translations/messages.pot +62 -63
  149. package/views/config/ai.hbs +1 -1
  150. package/views/config/security.hbs +24 -2
  151. package/views/config/service.hbs +47 -0
  152. package/views/config/webhooks.hbs +36 -0
  153. package/views/internals/index.hbs +8 -0
  154. package/views/partials/queue_retention_note.hbs +12 -8
  155. package/views/partials/ui/env-managed-alert.hbs +16 -7
  156. package/views/partials/webhook_form.hbs +1 -1
  157. package/views/suppression-lists/index.hbs +1 -1
  158. package/workers/api.js +840 -611
  159. package/workers/export.js +17 -632
  160. package/workers/imap.js +13 -0
  161. package/workers/smtp.js +9 -11
  162. package/workers/submit.js +1 -1
  163. package/workers/webhooks.js +18 -448
  164. 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,10 +15,10 @@ const {
16
15
  embedCidImages
17
16
  } = require('../../tools');
18
17
  const { samePath } = require('../../utils/mailbox-path');
18
+ const { loadNotifyAttachments } = require('../../notify-attachments');
19
19
  const { connectionNotAvailableError } = require('./connection-errors');
20
20
  const msgpack = require('../../msgpack');
21
21
  const he = require('he');
22
- const libmime = require('libmime');
23
22
  const settings = require('../../settings');
24
23
  const { bounceDetect, applyDeliveryReport, PARSER_OPTIONS: DSN_PARSER_OPTIONS } = require('../../bounce-detect');
25
24
  const { decodeHeaders } = require('../../utils/decode-headers');
@@ -27,8 +26,8 @@ const { isUnsafeKey } = require('../../utils/unsafe-key');
27
26
  const { arfDetect, camelCaseComplaint, COMPLAINT_ATTACHMENT_TYPES } = require('../../arf-detect');
28
27
  const { messageWebSafeHtml } = require('../../web-safe-html');
29
28
  const { parseMessage } = require('../../parse-message');
30
- const { parseCalendarEvent, sortCalendarAttachments, CALENDAR_CONTENT_TYPES } = require('../../calendar-event');
31
- const addressparser = require('nodemailer/lib/addressparser');
29
+ const { collectCalendarEvents } = require('../../calendar-event');
30
+ const { parseAddressHeader: parseMailboxes } = require('mailparser');
32
31
  const { llmPreProcess, summaryFetchHeaders, summaryProvider } = require('../../llm-pre-process');
33
32
  const { notificationHeaderFields, narrowHeaders } = require('../../utils/header-map');
34
33
  const { isFailedDelivery } = require('../base-client');
@@ -49,7 +48,8 @@ const {
49
48
  TRANSIENT_NETWORK_CODES,
50
49
  CONNECTION_CLOSING_CODES,
51
50
  PHANTOM_SELECT_FAIL_THRESHOLD,
52
- PHANTOM_REPROBE_INTERVAL
51
+ PHANTOM_REPROBE_INTERVAL,
52
+ NEW_MESSAGE_SETTINGS
53
53
  } = require('../../consts');
54
54
 
55
55
  const {
@@ -63,6 +63,11 @@ const {
63
63
  FULL_SYNC_DELAY
64
64
  } = require('./sync-operations');
65
65
 
66
+ // Gmail categories in the order a message is matched against them, see createCategoryResolver()
67
+ const GMAIL_CATEGORIES = ['primary', 'social', 'promotions', 'updates', 'forums', 'reservations', 'purchases'];
68
+ // Queued messages whose categories one lookup covers
69
+ const CATEGORY_BATCH_SIZE = 500;
70
+
66
71
  /**
67
72
  * Whether the connection is gone, rather than this message being a problem. An enrichment step that
68
73
  * hits one must let it propagate: publishSyncedEvents() keeps the message queued for the next pass
@@ -175,17 +180,12 @@ function parseAddressHeader(values) {
175
180
  }
176
181
 
177
182
  try {
178
- let addressList = addressparser(values)
179
- .filter(address => isUsableAddress(address.address))
180
- .map(address => {
181
- let name = address.name;
182
- try {
183
- name = libmime.decodeWords(name);
184
- } catch (err) {
185
- // keep the undecoded name
186
- }
187
- return { name, address: address.address };
188
- });
183
+ // Flattened: a group ("Team: a@example.com, b@example.com;") is one entry with no address
184
+ // of its own, so the filter below used to drop every member it named. A punycode domain is
185
+ // kept as the header has it, the way the server's ENVELOPE reports it
186
+ let addressList = parseMailboxes(values, { flatten: true, decodePunycode: false })
187
+ .value.filter(address => isUsableAddress(address.address))
188
+ .map(address => ({ name: address.name, address: address.address }));
189
189
 
190
190
  return addressList.length ? addressList : undefined;
191
191
  } catch (err) {
@@ -200,7 +200,7 @@ function parseAddressHeader(values) {
200
200
  * An ENVELOPE list can come back holding no address anyone could use: RFC 9051 7.5.2 group
201
201
  * markers carry a group name and nothing else, and a server that failed to parse a malformed
202
202
  * header reports the wreckage in the shapes isUsableAddress() turns down. The raw header is
203
- * the better answer then, because addressparser sees the original value and can still recover
203
+ * the better answer then, because the header parser sees the original value and can still recover
204
204
  * the recipient. A list has to be judged on what its entries hold, not on being non-empty.
205
205
  *
206
206
  * The header is parsed only when the ENVELOPE turns out to be unusable, which is rare.
@@ -269,6 +269,7 @@ class Mailbox {
269
269
 
270
270
  this.synced = false; // Resolver of the sync() promise while a pass is waiting for its SELECT
271
271
  this.syncChain = null; // Promise of the latest sync() pass, which the next caller waits for
272
+ this.pendingSync = null; // The sync() pass waiting for its turn, shared by the calls made meanwhile
272
273
  this.syncing = false; // Whether currently syncing
273
274
  this.processingOpen = false; // Whether onOpen() is currently running for this mailbox
274
275
  this.processingOpenClient = null; // The IMAP client whose open event holds the processingOpen latch
@@ -419,8 +420,8 @@ class Mailbox {
419
420
  * @param {string} notificationType - Type of notification for logging context
420
421
  * @returns {string|null} Packed UID or null if packing failed
421
422
  */
422
- async packUidWithLogging(uid, notificationType) {
423
- let packedUid = await this.connection.packUid(this, uid);
423
+ async packUidWithLogging(uid, notificationType, statusCache) {
424
+ let packedUid = await this.connection.packUid(this, uid, statusCache);
424
425
  if (!packedUid) {
425
426
  this.logger.warn({
426
427
  msg: 'Skipping notification, packUid returned invalid result',
@@ -501,12 +502,43 @@ class Mailbox {
501
502
  * @returns {Number} Sequence number for the added entry
502
503
  */
503
504
  async entryListSet(data) {
504
- if (isNaN(data.uid)) {
505
+ const args = this.entryListSetArgs(data);
506
+ if (!args) {
505
507
  return null;
506
508
  }
507
509
 
508
- // Store in sorted set with UID as score for efficient range queries
509
- return await this.connection.redis.zSet(this.getMessagesKey(), Number(data.uid), serialize(data));
510
+ return await this.connection.redis.zSet(...args);
511
+ }
512
+
513
+ /**
514
+ * Queues the index writes of several messages onto a transaction, encoded as entryListSet()
515
+ * encodes them. A message without a numeric UID is skipped, as entryListSet() refuses it
516
+ * @param {Object} txn - Transaction from createTransaction()
517
+ * @param {Object[]} messages - Message data with uid, flags, etc.
518
+ * @returns {Object[]} The messages that were queued
519
+ */
520
+ entryListSetMany(txn, messages) {
521
+ const queued = [];
522
+ for (const data of messages) {
523
+ const args = this.entryListSetArgs(data);
524
+ if (args) {
525
+ txn.add('zSet', ...args);
526
+ queued.push(data);
527
+ }
528
+ }
529
+ return queued;
530
+ }
531
+
532
+ /**
533
+ * The zSet arguments of an index write: the sorted set has the UID as score for range queries
534
+ * @param {Object} data - Message data
535
+ * @returns {Array|null} Null for a message without a numeric UID
536
+ */
537
+ entryListSetArgs(data) {
538
+ if (isNaN(data.uid)) {
539
+ return null;
540
+ }
541
+ return [this.getMessagesKey(), Number(data.uid), serialize(data)];
510
542
  }
511
543
 
512
544
  /**
@@ -536,6 +568,30 @@ class Mailbox {
536
568
  return null;
537
569
  }
538
570
 
571
+ /**
572
+ * Index entries with a UID above `afterUid` and up to `toUid`, in UID order, in one read. An
573
+ * entry that does not parse is returned with `entry: null`, which entryListGet() answers as a
574
+ * missing entry
575
+ * @param {Number} afterUid - Exclusive lower bound
576
+ * @param {Number} toUid - Inclusive upper bound, Infinity for no bound
577
+ * @returns {Promise<Array<{uid: Number, entry: Object|null}>>}
578
+ */
579
+ async entryListRange(afterUid, toUid) {
580
+ const max = Number.isFinite(toUid) ? toUid : '+inf';
581
+ const response = await this.connection.redis.zrangebyscoreBuffer(this.getMessagesKey(), `(${afterUid}`, max, 'WITHSCORES');
582
+ const entries = [];
583
+ for (let i = 0; i < response.length; i += 2) {
584
+ let entry;
585
+ try {
586
+ entry = unserialize(response[i]);
587
+ } catch (err) {
588
+ entry = null;
589
+ }
590
+ entries.push({ uid: Number(response[i + 1].toString()), entry });
591
+ }
592
+ return entries;
593
+ }
594
+
539
595
  /**
540
596
  * Deletes entry from message list for the provided sequence value or UID
541
597
  * @param {Number} seq - Sequence number (0 if using UID)
@@ -555,6 +611,56 @@ class Mailbox {
555
611
  return null;
556
612
  }
557
613
 
614
+ /**
615
+ * Deletes several entries from the message list in one round trip, by UID, and drops whatever
616
+ * the notifications queue still holds for them in the same round trip: a message that is gone
617
+ * has nothing left to announce, which processDeleted() used to remove one message at a time
618
+ * @param {number[]} uids
619
+ * @returns {Promise<Object[]>} The entries that were deleted, in the order given
620
+ */
621
+ async entryListExpungeMany(uids) {
622
+ if (!uids.length) {
623
+ return [];
624
+ }
625
+ let pipeline = this.connection.redis.pipeline();
626
+ for (const uid of uids) {
627
+ pipeline = pipeline.zExpungeBuffer(this.getMessagesKey(), this.getMailboxKey(), 0, uid);
628
+ pipeline = pipeline.zremrangebyscore(this.getNotificationsKey(), uid, uid);
629
+ }
630
+ const results = await pipeline.exec();
631
+ const entries = [];
632
+ for (let i = 0; i < results.length; i += 2) {
633
+ const [err, response] = results[i];
634
+ if (err) {
635
+ throw err;
636
+ }
637
+ if (response) {
638
+ try {
639
+ entries.push(unserialize(response[1]));
640
+ } catch (parseErr) {
641
+ // an entry that does not parse was still removed, there is nothing to report
642
+ }
643
+ }
644
+ }
645
+ return entries;
646
+ }
647
+
648
+ /**
649
+ * UIDs of the index entries above `afterUid`, at most `limit` of them, lowest first. The entries
650
+ * themselves come along (Redis has no scores-only range), but are not decoded
651
+ * @param {number} afterUid - Exclusive lower bound
652
+ * @param {number} limit
653
+ * @returns {Promise<number[]>}
654
+ */
655
+ async entryListUidsAfter(afterUid, limit) {
656
+ const response = await this.connection.redis.zrangebyscoreBuffer(this.getMessagesKey(), `(${afterUid}`, '+inf', 'WITHSCORES', 'LIMIT', 0, limit);
657
+ const uids = [];
658
+ for (let i = 1; i < response.length; i += 2) {
659
+ uids.push(Number(response[i].toString()));
660
+ }
661
+ return uids;
662
+ }
663
+
558
664
  /**
559
665
  * Checks if this mailbox is currently selected in the IMAP connection
560
666
  * @returns {Boolean} True if selected
@@ -671,15 +777,34 @@ class Mailbox {
671
777
  * the first still waits for its SELECT would take the slot over, and the first
672
778
  * caller - the resync loop, which re-arms its timer only once every folder has
673
779
  * returned - would never be settled. Calls overlap whenever a subconnection reports
674
- * a change or a listing refresh registers folders during a resync pass
780
+ * a change or a listing refresh registers folders during a resync pass.
781
+ *
782
+ * Calls that arrive while a pass is already waiting its turn share that pass rather than
783
+ * queueing one each: it has not started yet, so it still sees everything that happened
784
+ * before they were made. A burst of moves into one folder used to queue one STATUS round
785
+ * trip per moved message
675
786
  * @param {Boolean} forceEmpty - Force sync even if mailbox appears unchanged
676
787
  * @returns {Boolean} True if synced
677
788
  */
678
789
  async sync(forceEmpty) {
679
- // A rejected pass was reported to its own caller; the next pass runs regardless
680
- const current = (this.syncChain || Promise.resolve()).catch(() => {}).then(() => this.syncOnce(forceEmpty));
681
- this.syncChain = current;
682
- return await current;
790
+ if (this.pendingSync) {
791
+ // a waiting pass forces the sync if any of the callers sharing it asked for that
792
+ this.pendingSync.forceEmpty = this.pendingSync.forceEmpty || !!forceEmpty;
793
+ return await this.pendingSync.promise;
794
+ }
795
+
796
+ const pending = { forceEmpty: !!forceEmpty };
797
+ // A rejected pass was reported to its own callers; the next pass runs regardless
798
+ pending.promise = (this.syncChain || Promise.resolve())
799
+ .catch(() => {})
800
+ .then(() => {
801
+ // started: a call made from here on needs a pass of its own
802
+ this.pendingSync = null;
803
+ return this.syncOnce(pending.forceEmpty);
804
+ });
805
+ this.pendingSync = pending;
806
+ this.syncChain = pending.promise;
807
+ return await pending.promise;
683
808
  }
684
809
 
685
810
  /**
@@ -952,11 +1077,83 @@ class Mailbox {
952
1077
  return lock;
953
1078
  }
954
1079
 
1080
+ /**
1081
+ * Runs `fn` under the lock of a message's folder, released however `fn` ends
1082
+ * @param {Object} connectionClient - IMAP client to use
1083
+ * @param {Object} message - Unpacked message reference, see lockForMessage()
1084
+ * @param {Object} options - Lock options
1085
+ * @param {Function} fn - The work to do under the lock
1086
+ * @returns {*} What `fn` returned, or false when the reference was issued for a previous
1087
+ * incarnation of this folder (fn is not called then)
1088
+ */
1089
+ async withMessageLock(connectionClient, message, options, fn) {
1090
+ let lock = await this.lockForMessage(connectionClient, message, options);
1091
+ if (!lock) {
1092
+ // issued for a previous incarnation of this folder
1093
+ return false;
1094
+ }
1095
+ try {
1096
+ return await fn();
1097
+ } finally {
1098
+ lock.release();
1099
+ }
1100
+ }
1101
+
1102
+ /**
1103
+ * Runs `fn` under this folder's lock, released however `fn` ends
1104
+ * @param {Object} connectionClient - IMAP client to use
1105
+ * @param {Object} options - Lock options
1106
+ * @param {Function} fn - The work to do under the lock
1107
+ * @returns {*} What `fn` returned
1108
+ */
1109
+ async withMailboxLock(connectionClient, options, fn) {
1110
+ let lock = await this.getMailboxLock(connectionClient, options);
1111
+ try {
1112
+ return await fn();
1113
+ } finally {
1114
+ lock.release();
1115
+ }
1116
+ }
1117
+
1118
+ /**
1119
+ * Takes this folder's lock on a connection
1120
+ * @param {Object} [connectionClient] - IMAP client to use, the primary connection by default
1121
+ * @param {Object} [options] - ImapFlow lock options, plus `refresh`: the caller is about to
1122
+ * read the session's view of the folder (counters, SEARCH), so make sure it is current.
1123
+ * A folder the connection already has open is not selected again, and a change made over
1124
+ * another connection (a move over the command connection) reaches that view only once the
1125
+ * server reports it, which a server may hold until the next command boundary. A NOOP is
1126
+ * that boundary. Not needed when the connection was idling, IDLE reports changes as they
1127
+ * happen
1128
+ * @returns {Object} Lock object with release()
1129
+ */
955
1130
  async getMailboxLock(connectionClient, options) {
956
1131
  connectionClient = connectionClient || this.requireImapClient();
957
1132
 
958
- let lock = await connectionClient.getMailboxLock(this.path, options || {});
1133
+ let { refresh, ...lockOptions } = options || {};
1134
+ let needsRefresh = !!refresh && !!connectionClient.mailbox && samePath(connectionClient.mailbox.path, this.path) && !connectionClient.idling;
1135
+
1136
+ let lock = await this.wrapLock(connectionClient, await connectionClient.getMailboxLock(this.path, lockOptions));
959
1137
 
1138
+ if (needsRefresh) {
1139
+ try {
1140
+ await connectionClient.noop();
1141
+ } catch (err) {
1142
+ lock.release();
1143
+ throw err;
1144
+ }
1145
+ }
1146
+
1147
+ return lock;
1148
+ }
1149
+
1150
+ /**
1151
+ * A lock on the primary connection reports the task when it is released, see onTaskCompleted()
1152
+ * @param {Object} connectionClient - IMAP client the lock was taken on
1153
+ * @param {Object} lock - ImapFlow lock
1154
+ * @returns {Object} Lock object with release()
1155
+ */
1156
+ wrapLock(connectionClient, lock) {
960
1157
  if (connectionClient !== this.connection.imapClient) {
961
1158
  return lock;
962
1159
  }
@@ -1010,22 +1207,41 @@ class Mailbox {
1010
1207
  return;
1011
1208
  }
1012
1209
 
1013
- // Debounce partial sync to avoid multiple syncs for rapid changes
1210
+ this.schedulePartialSync(() => this.shouldRunPartialSyncAfterExists(), 'EXISTS');
1211
+ }
1212
+
1213
+ /**
1214
+ * Handles a HIGHESTMODSEQ change ImapFlow found while polling a server without IDLE (the
1215
+ * `highestModseq` event, ImapFlow 2.6.0). Such a server sends no FETCH for a flag change, so
1216
+ * this is the only sign of one before the next resync
1217
+ * @param {Object} event - `{ path, highestModseq, prevHighestModseq }`
1218
+ */
1219
+ async onHighestModseq(event) {
1220
+ this.logEvent('HIGHESTMODSEQ changed', event);
1221
+
1222
+ if (this.syncDisabled) {
1223
+ return;
1224
+ }
1225
+
1226
+ this.schedulePartialSync(async () => true, 'HIGHESTMODSEQ');
1227
+ }
1228
+
1229
+ /**
1230
+ * Debounces a partial sync so a burst of changes runs one
1231
+ * @param {Function} shouldRun - Async check made when the timer fires
1232
+ * @param {string} trigger - What asked for it, for the log
1233
+ */
1234
+ schedulePartialSync(shouldRun, trigger) {
1014
1235
  clearTimeout(this.runPartialSyncTimer);
1015
1236
  this.runPartialSyncTimer = setTimeout(() => {
1016
1237
  this.runPartialSyncTimer = null;
1017
- this.shouldRunPartialSyncAfterExists()
1018
- .then(shouldRun => {
1019
- if (shouldRun) {
1020
- return this.partialSync();
1021
- }
1022
- return false;
1023
- })
1238
+ shouldRun()
1239
+ .then(run => (run ? this.partialSync() : false))
1024
1240
  .catch(err => {
1025
1241
  if (CONNECTION_CLOSING_CODES.has(err.code)) {
1026
1242
  this.logger.debug({ msg: 'Sync skipped, connection closing', err });
1027
1243
  } else {
1028
- this.logger.warn({ msg: 'Failed to sync mailbox after EXISTS', err });
1244
+ this.logger.warn({ msg: `Failed to sync mailbox after ${trigger}`, err });
1029
1245
  }
1030
1246
  });
1031
1247
  }, 1000);
@@ -1124,12 +1340,16 @@ class Mailbox {
1124
1340
  /**
1125
1341
  * Processes a deleted message and sends the notification
1126
1342
  * @param {Object} messageData - Deleted message data
1343
+ * @param {Object} [opts]
1344
+ * @param {Map} [opts.statusCache] - Shared by the messages of one batch, see packUid()
1345
+ * @param {boolean} [opts.dequeued] - The notifications queue entry was already removed, by
1346
+ * entryListExpungeMany()
1127
1347
  */
1128
- async processDeleted(messageData) {
1348
+ async processDeleted(messageData, opts = {}) {
1129
1349
  this.logger.debug({ msg: 'Message deleted', uid: messageData.uid });
1130
1350
 
1131
1351
  // Generate packed UID for external reference
1132
- let packedUid = await this.packUidWithLogging(messageData.uid, 'delete');
1352
+ let packedUid = await this.packUidWithLogging(messageData.uid, 'delete', opts.statusCache);
1133
1353
  if (!packedUid) {
1134
1354
  return;
1135
1355
  }
@@ -1138,6 +1358,10 @@ class Mailbox {
1138
1358
  uid: messageData.uid
1139
1359
  });
1140
1360
 
1361
+ if (opts.dequeued) {
1362
+ return;
1363
+ }
1364
+
1141
1365
  try {
1142
1366
  // Remove from notifications queue since message no longer exists
1143
1367
  await this.connection.redis.zremrangebyscore(this.getNotificationsKey(), messageData.uid, messageData.uid);
@@ -1192,7 +1416,7 @@ class Mailbox {
1192
1416
  * @param {Object} options - Processing options
1193
1417
  * @param {Object} storedStatus - Current mailbox status
1194
1418
  */
1195
- async processNew(messageData, options, storedStatus) {
1419
+ async processNew(messageData, options, storedStatus, categories, passSettings) {
1196
1420
  this.logger.debug({ msg: 'New message', uid: messageData.uid, flags: Array.from(messageData.flags) });
1197
1421
 
1198
1422
  options.skipLock = true;
@@ -1443,6 +1667,8 @@ class Mailbox {
1443
1667
  });
1444
1668
  }
1445
1669
  } catch (err) {
1670
+ // A parser failure leaves the IMAP download unconsumed, as in the DSN branch above
1671
+ content?.destroy?.();
1446
1672
  if (isConnectionGone(err)) {
1447
1673
  throw err;
1448
1674
  }
@@ -1456,162 +1682,49 @@ class Mailbox {
1456
1682
  }
1457
1683
  }
1458
1684
 
1685
+ // The settings the rest of this message reads: those the pass read once, or one round trip
1686
+ const { notifyAttachments, notifyAttachmentSize, notifyCalendarEvents, notifyWebSafeHtml, resolveGmailCategories } =
1687
+ passSettings || (await settings.getMulti(...NEW_MESSAGE_SETTINGS));
1688
+
1459
1689
  // Resolve Gmail category for inbox messages
1460
1690
  if (
1461
1691
  this.connection.imapClient?.capabilities?.has('X-GM-EXT-1') &&
1462
1692
  this.isAllMail &&
1463
1693
  messageInfo.labels &&
1464
1694
  messageInfo.labels.includes('\\Inbox') &&
1465
- (await settings.get('resolveGmailCategories'))
1695
+ resolveGmailCategories
1466
1696
  ) {
1467
- this.logger.trace({
1468
- msg: 'Resolving category for incoming email',
1469
- uid: messageData.uid,
1470
- id: messageInfo.id
1471
- });
1472
-
1473
- // Try each Gmail category in order
1474
- for (let category of ['primary', 'social', 'promotions', 'updates', 'forums', 'reservations', 'purchases']) {
1475
- try {
1476
- let results = await this.requireImapClient().search(
1477
- {
1478
- uid: messageInfo.uid,
1479
- gmraw: `category:${category}`
1480
- },
1481
- { uid: true }
1482
- );
1483
- if (results && results.includes(messageInfo.uid)) {
1484
- messageInfo.category = category;
1485
- this.logger.debug({
1486
- msg: 'Resolved category for incoming email',
1487
- category,
1488
- uid: messageData.uid,
1489
- id: messageInfo.id
1490
- });
1491
- break;
1492
- }
1493
- } catch (err) {
1494
- if (isConnectionGone(err)) {
1495
- throw err;
1496
- }
1497
- this.logger.warn({ msg: 'Failed to resolve category for message', err, category, uid: messageData.uid, id: messageInfo.id });
1498
- break;
1499
- }
1500
- }
1501
- }
1502
-
1503
- // Download attachment content if configured
1504
- let notifyAttachments = await settings.get('notifyAttachments');
1505
- let notifyAttachmentSize = await settings.get('notifyAttachmentSize');
1506
- if (notifyAttachments && messageInfo.attachments?.length) {
1507
- for (let attachment of messageInfo.attachments || []) {
1508
- if (notifyAttachmentSize && attachment.encodedSize && attachment.encodedSize > notifyAttachmentSize) {
1509
- // skip large attachments
1510
- continue;
1697
+ try {
1698
+ const category = await (categories || this.createCategoryResolver()).categoryOf(messageInfo.uid);
1699
+ if (category) {
1700
+ messageInfo.category = category;
1701
+ this.logger.debug({
1702
+ msg: 'Resolved category for incoming email',
1703
+ category,
1704
+ uid: messageData.uid,
1705
+ id: messageInfo.id
1706
+ });
1511
1707
  }
1512
- if (!attachment.content) {
1513
- await this.loadAttachmentContent(messageInfo, attachment, options);
1708
+ } catch (err) {
1709
+ if (isConnectionGone(err)) {
1710
+ throw err;
1514
1711
  }
1712
+ this.logger.warn({ msg: 'Failed to resolve category for message', err, uid: messageData.uid, id: messageInfo.id });
1515
1713
  }
1516
1714
  }
1517
1715
 
1518
- // Fetch inline attachments referenced in HTML
1519
- if (messageInfo.attachments?.length && messageInfo.text?.html) {
1520
- // fetch inline attachments
1521
- let cidReferences = collectCidReferences(messageInfo.text.html);
1522
- for (let attachment of messageInfo.attachments || []) {
1523
- if (attachment.encodedSize && attachment.encodedSize > MAX_INLINE_ATTACHMENT_SIZE) {
1524
- // skip large attachments
1525
- continue;
1526
- }
1716
+ const loadAttachment = attachment => this.loadAttachmentContent(messageInfo, attachment, options);
1527
1717
 
1528
- // Check if attachment is referenced by Content-ID in HTML
1529
- if (!attachment.content && attachment.contentId && cidReferences.has(attachment.contentId.replace(/^<|>$/g, ''))) {
1530
- await this.loadAttachmentContent(messageInfo, attachment, options);
1531
- }
1532
- }
1718
+ // Download attachment content if configured
1719
+ if (notifyAttachments) {
1720
+ await loadNotifyAttachments(messageInfo.attachments, notifyAttachmentSize, loadAttachment);
1533
1721
  }
1534
1722
 
1535
1723
  // Fetch and process calendar events if needed
1536
- let notifyCalendarEvents = await settings.get('notifyCalendarEvents');
1537
- if (notifyCalendarEvents && messageInfo.attachments && messageInfo.attachments.length) {
1538
- let calendarEventMap = new Map();
1539
-
1540
- // Process calendar attachments, text/calendar before application/ics
1541
- for (let attachment of [...messageInfo.attachments].sort(sortCalendarAttachments)) {
1542
- if (CALENDAR_CONTENT_TYPES.includes(attachment.contentType)) {
1543
- // Download calendar attachment if not already loaded
1544
- if (!attachment.content) {
1545
- await this.loadAttachmentContent(messageInfo, attachment, options);
1546
- }
1547
- if (attachment.content) {
1548
- let contentBuf = Buffer.from(attachment.content, 'base64');
1549
- try {
1550
- const event = parseCalendarEvent(contentBuf);
1551
- if (!event) {
1552
- continue;
1553
- }
1554
-
1555
- // Skip if we already processed this event
1556
- if (calendarEventMap.has(event.eventId)) {
1557
- if (attachment.filename) {
1558
- let existingEntry = calendarEventMap.get(event.eventId);
1559
- if (!existingEntry.filename) {
1560
- // inject filename
1561
- existingEntry.filename = attachment.filename;
1562
- }
1563
- }
1564
- continue;
1565
- }
1566
-
1567
- // Store calendar event data
1568
- calendarEventMap.set(
1569
- event.eventId,
1570
- filterEmptyObjectValues({
1571
- eventId: event.eventId,
1572
- attachment: attachment.id,
1573
- method: attachment.method || event.method || null,
1574
-
1575
- summary: event.summary,
1576
- description: event.description,
1577
- timezone: event.timezone,
1578
- startDate: event.startDate,
1579
- endDate: event.endDate,
1580
- organizer: event.organizer,
1581
-
1582
- filename: attachment.filename,
1583
- contentType: attachment.contentType,
1584
- encoding: 'base64',
1585
- content: attachment.content
1586
- })
1587
- );
1588
- } catch (err) {
1589
- this.logger.warn({
1590
- msg: 'Failed to parse calendar event',
1591
- attachment: Object.assign({}, attachment, { content: `${contentBuf.length} bytes` }),
1592
- err
1593
- });
1594
- }
1595
- }
1596
- }
1597
- }
1598
-
1599
- if (calendarEventMap && calendarEventMap.size) {
1600
- messageInfo.calendarEvents = Array.from(calendarEventMap.values()).map(calendarEvent => {
1601
- // Generate default filename based on method
1602
- if (!calendarEvent.filename) {
1603
- switch (calendarEvent.method && calendarEvent.method.toUpperCase()) {
1604
- case 'CANCEL':
1605
- case 'REQUEST':
1606
- calendarEvent.filename = 'invite.ics';
1607
- break;
1608
- default:
1609
- calendarEvent.filename = 'event.ics';
1610
- break;
1611
- }
1612
- }
1613
- return calendarEvent;
1614
- });
1724
+ if (notifyCalendarEvents) {
1725
+ const calendarEvents = await collectCalendarEvents(messageInfo.attachments, loadAttachment, this.logger);
1726
+ if (calendarEvents) {
1727
+ messageInfo.calendarEvents = calendarEvents;
1615
1728
  }
1616
1729
  }
1617
1730
 
@@ -1638,7 +1751,6 @@ class Mailbox {
1638
1751
  }
1639
1752
 
1640
1753
  // Convert message HTML to web safe HTML
1641
- let notifyWebSafeHtml = await settings.get('notifyWebSafeHtml');
1642
1754
  if (notifyWebSafeHtml && messageInfo.text && (messageInfo.text.html || messageInfo.text.plain)) {
1643
1755
  // convert to web safe
1644
1756
  messageInfo.text._generatedHtml = await messageWebSafeHtml(messageInfo);
@@ -1660,7 +1772,7 @@ class Mailbox {
1660
1772
  });
1661
1773
 
1662
1774
  if (attachment.content || (attachment.encodedSize && attachment.encodedSize > MAX_INLINE_ATTACHMENT_SIZE)) {
1663
- // already downloaded in a previous step, or skipped there as too large to inline
1775
+ // already loaded by notifyAttachments, or too large to inline
1664
1776
  continue;
1665
1777
  }
1666
1778
 
@@ -1774,13 +1886,13 @@ class Mailbox {
1774
1886
  * @param {Boolean} extended - Include extended information
1775
1887
  * @returns {Object} Formatted message info
1776
1888
  */
1777
- async getMessageInfo(messageData, extended) {
1889
+ async getMessageInfo(messageData, extended, statusCache) {
1778
1890
  if (!messageData) {
1779
1891
  return false;
1780
1892
  }
1781
1893
 
1782
1894
  // Generate unique message ID
1783
- let packedUid = await this.connection.packUid(this, messageData.uid);
1895
+ let packedUid = await this.connection.packUid(this, messageData.uid, statusCache);
1784
1896
 
1785
1897
  if (!packedUid) {
1786
1898
  let storedStatus;
@@ -1999,9 +2111,10 @@ class Mailbox {
1999
2111
  * Processes flag changes for a message
2000
2112
  * @param {Object} messageData - Message data with changes
2001
2113
  * @param {Object} changes - What changed
2114
+ * @param {Map} [statusCache] - Shared by the messages of one batch, see packUid()
2002
2115
  */
2003
- async processChanges(messageData, changes) {
2004
- let packedUid = await this.packUidWithLogging(messageData.uid, 'update');
2116
+ async processChanges(messageData, changes, statusCache) {
2117
+ let packedUid = await this.packUidWithLogging(messageData.uid, 'update', statusCache);
2005
2118
  if (!packedUid) {
2006
2119
  return;
2007
2120
  }
@@ -2039,6 +2152,53 @@ class Mailbox {
2039
2152
  return this.syncOps.seedMailboxIndex(mailboxStatus, options);
2040
2153
  }
2041
2154
 
2155
+ /**
2156
+ * Resolves the Gmail category (X-GM-RAW category:...) of new Inbox messages. Asked for one
2157
+ * message, it looks up every message still queued for announcing in the same pass (up to
2158
+ * CATEGORY_BATCH_SIZE), one search per category over all of them, instead of up to seven searches
2159
+ * for each message. Categories are tried in GMAIL_CATEGORIES order and the first match wins, as it
2160
+ * did per message. A message queued after the lookup gets a lookup of its own
2161
+ * @returns {{categoryOf: Function}}
2162
+ */
2163
+ createCategoryResolver() {
2164
+ const resolved = new Map();
2165
+ const searched = new Set();
2166
+
2167
+ const lookup = async uids => {
2168
+ const uidSet = uids.join(',');
2169
+ let pending = new Set(uids);
2170
+ try {
2171
+ for (const category of GMAIL_CATEGORIES) {
2172
+ const results = await this.requireImapClient().search({ uid: uidSet, gmraw: `category:${category}` }, { uid: true });
2173
+ for (const uid of results || []) {
2174
+ if (pending.delete(uid)) {
2175
+ resolved.set(uid, category);
2176
+ }
2177
+ }
2178
+ if (!pending.size) {
2179
+ break;
2180
+ }
2181
+ }
2182
+ } finally {
2183
+ // a failed lookup is not repeated for each message of the batch
2184
+ uids.forEach(uid => searched.add(uid));
2185
+ }
2186
+ };
2187
+
2188
+ return {
2189
+ categoryOf: async uid => {
2190
+ if (!searched.has(uid)) {
2191
+ // the UIDs are the scores; the members are full payloads this has no use for
2192
+ const uids = (await this.connection.redis.zHeadScores(this.getNotificationsKey(), CATEGORY_BATCH_SIZE)).map(Number);
2193
+ const batch = [...new Set([uid].concat(uids))].filter(other => !searched.has(other));
2194
+ this.logger.trace({ msg: 'Resolving categories for incoming email', uid, batch: batch.length });
2195
+ await lookup(batch);
2196
+ }
2197
+ return resolved.get(uid) || null;
2198
+ }
2199
+ };
2200
+ }
2201
+
2042
2202
  /**
2043
2203
  * Processes queued notification events after sync
2044
2204
  * Fetches full message details and sends notifications
@@ -2075,6 +2235,12 @@ class Mailbox {
2075
2235
  messageFetchOptions.fetchHeaders = notificationHeaderFields(messageFetchOptions.headers, summaryHeaders);
2076
2236
  }
2077
2237
 
2238
+ // Gmail categories of the messages this pass announces, looked up together
2239
+ const categories = this.createCategoryResolver();
2240
+
2241
+ // Read once for every message the pass announces, not once per message
2242
+ const passSettings = await settings.getMulti(...NEW_MESSAGE_SETTINGS);
2243
+
2078
2244
  // Peek-then-remove: read entries without removing so that connection errors
2079
2245
  // leave unprocessed entries in Redis for retry on reconnect.
2080
2246
  let queuedEntry;
@@ -2102,7 +2268,7 @@ class Mailbox {
2102
2268
  }
2103
2269
 
2104
2270
  try {
2105
- await this.processNew(messageData, messageFetchOptions, storedStatus);
2271
+ await this.processNew(messageData, messageFetchOptions, storedStatus, categories, passSettings);
2106
2272
  await this.connection.redis.zrem(notificationsKey, rawMember);
2107
2273
  this.throttledArrivals?.delete(rawMember);
2108
2274
  } catch (err) {
@@ -2703,13 +2869,7 @@ class Mailbox {
2703
2869
 
2704
2870
  const connectionClient = await this.connection.getImapConnection(connectionOptions);
2705
2871
 
2706
- let lock = await this.lockForMessage(connectionClient, message, { description: `Update message: ${message.uid}` });
2707
- if (!lock) {
2708
- // issued for a previous incarnation of this folder
2709
- return false;
2710
- }
2711
-
2712
- try {
2872
+ return await this.withMessageLock(connectionClient, message, { description: `Update message: ${message.uid}` }, async () => {
2713
2873
  let result = {};
2714
2874
 
2715
2875
  // Update flags
@@ -2767,9 +2927,7 @@ class Mailbox {
2767
2927
  }
2768
2928
 
2769
2929
  return result;
2770
- } finally {
2771
- lock.release();
2772
- }
2930
+ });
2773
2931
  }
2774
2932
 
2775
2933
  /**
@@ -2784,9 +2942,7 @@ class Mailbox {
2784
2942
 
2785
2943
  const connectionClient = await this.connection.getImapConnection(connectionOptions);
2786
2944
 
2787
- let lock = await this.getMailboxLock(connectionClient, { description: `Update messages` });
2788
-
2789
- try {
2945
+ return await this.withMailboxLock(connectionClient, { description: `Update messages`, refresh: true }, async () => {
2790
2946
  let result = {};
2791
2947
 
2792
2948
  // Update flags for matching messages
@@ -2844,9 +3000,7 @@ class Mailbox {
2844
3000
  }
2845
3001
 
2846
3002
  return result;
2847
- } finally {
2848
- lock.release();
2849
- }
3003
+ });
2850
3004
  }
2851
3005
 
2852
3006
  /**
@@ -2862,13 +3016,7 @@ class Mailbox {
2862
3016
 
2863
3017
  const connectionClient = await this.connection.getImapConnection(connectionOptions);
2864
3018
 
2865
- let lock = await this.lockForMessage(connectionClient, message, { description: `Move message: ${message.uid} to: ${target.path}` });
2866
- if (!lock) {
2867
- // issued for a previous incarnation of this folder
2868
- return false;
2869
- }
2870
-
2871
- try {
3019
+ return await this.withMessageLock(connectionClient, message, { description: `Move message: ${message.uid} to: ${target.path}` }, async () => {
2872
3020
  let result = {};
2873
3021
 
2874
3022
  if (target.path) {
@@ -2886,9 +3034,7 @@ class Mailbox {
2886
3034
  }
2887
3035
 
2888
3036
  return result;
2889
- } finally {
2890
- lock.release();
2891
- }
3037
+ });
2892
3038
  }
2893
3039
 
2894
3040
  /**
@@ -2903,9 +3049,7 @@ class Mailbox {
2903
3049
 
2904
3050
  const connectionClient = await this.connection.getImapConnection(connectionOptions);
2905
3051
 
2906
- let lock = await this.getMailboxLock(connectionClient, { description: `Move messages to: ${target.path}` });
2907
-
2908
- try {
3052
+ return await this.withMailboxLock(connectionClient, { description: `Move messages to: ${target.path}`, refresh: true }, async () => {
2909
3053
  let result = {};
2910
3054
 
2911
3055
  if (target.path) {
@@ -2924,9 +3068,7 @@ class Mailbox {
2924
3068
  }
2925
3069
 
2926
3070
  return result;
2927
- } finally {
2928
- lock.release();
2929
- }
3071
+ });
2930
3072
  }
2931
3073
 
2932
3074
  /**
@@ -2939,13 +3081,7 @@ class Mailbox {
2939
3081
  async deleteMessage(message, force, connectionOptions) {
2940
3082
  const connectionClient = await this.connection.getImapConnection(connectionOptions);
2941
3083
 
2942
- let lock = await this.lockForMessage(connectionClient, message, { description: `Delete message: ${message.uid}` });
2943
- if (!lock) {
2944
- // issued for a previous incarnation of this folder
2945
- return false;
2946
- }
2947
-
2948
- try {
3084
+ return await this.withMessageLock(connectionClient, message, { description: `Delete message: ${message.uid}` }, async () => {
2949
3085
  let result = {};
2950
3086
 
2951
3087
  // Permanently delete if in Trash/Junk or forced
@@ -2975,9 +3111,7 @@ class Mailbox {
2975
3111
  }
2976
3112
 
2977
3113
  return result;
2978
- } finally {
2979
- lock.release();
2980
- }
3114
+ });
2981
3115
  }
2982
3116
 
2983
3117
  /**
@@ -2990,9 +3124,7 @@ class Mailbox {
2990
3124
  async deleteMessages(search, force, connectionOptions) {
2991
3125
  const connectionClient = await this.connection.getImapConnection(connectionOptions);
2992
3126
 
2993
- let lock = await this.getMailboxLock(connectionClient, { description: `Delete messages` });
2994
-
2995
- try {
3127
+ return await this.withMailboxLock(connectionClient, { description: `Delete messages`, refresh: true }, async () => {
2996
3128
  let result = {};
2997
3129
 
2998
3130
  // Permanently delete if in Trash/Junk or forced
@@ -3026,9 +3158,7 @@ class Mailbox {
3026
3158
  }
3027
3159
 
3028
3160
  return result;
3029
- } finally {
3030
- lock.release();
3031
- }
3161
+ });
3032
3162
  }
3033
3163
 
3034
3164
  /**
@@ -3058,9 +3188,8 @@ class Mailbox {
3058
3188
 
3059
3189
  const connectionClient = await this.connection.getImapConnection(connectionOptions);
3060
3190
 
3061
- let lock = await this.getMailboxLock(connectionClient, { description: `List messages from: ${this.path}` });
3062
-
3063
- try {
3191
+ // refresh: the counters and the SEARCH below read the session's view of the folder
3192
+ return await this.withMailboxLock(connectionClient, { description: `List messages from: ${this.path}`, refresh: true }, async () => {
3064
3193
  let mailboxStatus = this.getMailboxStatus(connectionClient);
3065
3194
 
3066
3195
  let messageCount = mailboxStatus.messages;
@@ -3156,6 +3285,9 @@ class Mailbox {
3156
3285
  }
3157
3286
  }
3158
3287
 
3288
+ // One stored status read for the whole page, not one per message
3289
+ const statusCache = new Map();
3290
+
3159
3291
  // Fetch messages in the range
3160
3292
  for await (let messageData of connectionClient.fetch(range, fields, opts)) {
3161
3293
  if (!messageData || !messageData.uid) {
@@ -3165,7 +3297,7 @@ class Mailbox {
3165
3297
  }
3166
3298
  let messageInfo;
3167
3299
  try {
3168
- messageInfo = await this.getMessageInfo(messageData);
3300
+ messageInfo = await this.getMessageInfo(messageData, false, statusCache);
3169
3301
  } catch (err) {
3170
3302
  // Return error info for failed messages
3171
3303
  messageInfo = {
@@ -3187,9 +3319,7 @@ class Mailbox {
3187
3319
  // List newer entries first. Servers like yahoo do not return ordered list, so we need to order manually
3188
3320
  messages: messages.sort((a, b) => b.uid - a.uid)
3189
3321
  };
3190
- } finally {
3191
- lock.release();
3192
- }
3322
+ });
3193
3323
  }
3194
3324
 
3195
3325
  /**