emailengine-app 2.85.0 → 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 (128) hide show
  1. package/.ncurc.js +24 -6
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +74 -0
  4. package/Dockerfile +14 -1
  5. package/ENVIRONMENT.md +139 -0
  6. package/README.md +1 -1
  7. package/config/default.toml +2 -0
  8. package/copy-static-files.sh +4 -2
  9. package/data/google-crawlers.json +1 -1
  10. package/data/public_suffix_list.dat +4 -3
  11. package/lib/account-assignment.js +19 -0
  12. package/lib/account.js +194 -165
  13. package/lib/api-error-codes.js +49 -0
  14. package/lib/api-reference/model.js +6 -1
  15. package/lib/api-routes/account-routes.js +78 -26
  16. package/lib/api-routes/blocklist-routes.js +68 -2
  17. package/lib/api-routes/delivery-test-routes.js +1 -1
  18. package/lib/api-routes/gateway-routes.js +82 -10
  19. package/lib/api-routes/index.js +4 -0
  20. package/lib/api-routes/license-routes.js +2 -2
  21. package/lib/api-routes/mailbox-routes.js +3 -3
  22. package/lib/api-routes/message-routes.js +15 -7
  23. package/lib/api-routes/oauth2-app-routes.js +15 -8
  24. package/lib/api-routes/outbox-routes.js +77 -66
  25. package/lib/api-routes/permission-map.js +55 -6
  26. package/lib/api-routes/scoped-routes.js +74 -0
  27. package/lib/api-routes/settings-routes.js +11 -4
  28. package/lib/api-routes/stats-routes.js +5 -1
  29. package/lib/api-routes/submit-routes.js +4 -3
  30. package/lib/api-routes/template-routes.js +7 -6
  31. package/lib/api-routes/token-routes.js +11 -5
  32. package/lib/api-routes/webhook-delivery-routes.js +262 -0
  33. package/lib/api-routes/webhook-route-routes.js +119 -4
  34. package/lib/calendar-event.js +81 -1
  35. package/lib/consts.js +38 -46
  36. package/lib/db.js +14 -6
  37. package/lib/delivery-error.js +6 -0
  38. package/lib/deprecations.js +270 -0
  39. package/lib/email-client/base-client.js +130 -156
  40. package/lib/email-client/fallback-poll.js +62 -0
  41. package/lib/email-client/gmail-client.js +51 -11
  42. package/lib/email-client/imap/adaptive-idle-store.js +73 -0
  43. package/lib/email-client/imap/adaptive-idle.js +278 -0
  44. package/lib/email-client/imap/connection-errors.js +14 -1
  45. package/lib/email-client/imap/idle-settings.js +31 -5
  46. package/lib/email-client/imap/listing-diff.js +37 -0
  47. package/lib/email-client/imap/mailbox.js +372 -226
  48. package/lib/email-client/imap/subconnection.js +7 -29
  49. package/lib/email-client/imap/sync-operations.js +220 -127
  50. package/lib/email-client/imap-client.js +227 -163
  51. package/lib/email-client/message-builder.js +14 -79
  52. package/lib/email-client/outlook-client.js +372 -338
  53. package/lib/email-client/smtp-pool-manager.js +16 -13
  54. package/lib/email-client/sync-state-fields.js +19 -0
  55. package/lib/encrypt.js +157 -41
  56. package/lib/enum-descriptions.js +3 -1
  57. package/lib/env-setting-overrides.js +288 -0
  58. package/lib/export-worker.js +751 -0
  59. package/lib/export.js +64 -15
  60. package/lib/gateway.js +17 -1
  61. package/lib/get-raw-email.js +25 -107
  62. package/lib/health.js +75 -0
  63. package/lib/lock-run.js +119 -0
  64. package/lib/logger-consts.js +48 -0
  65. package/lib/logger.js +1 -1
  66. package/lib/lua/z-head-scores.lua +28 -0
  67. package/lib/network-errors.js +1 -1
  68. package/lib/node-version.js +24 -0
  69. package/lib/notify-attachments.js +20 -1
  70. package/lib/oauth2-apps.js +630 -655
  71. package/lib/outbox.js +184 -54
  72. package/lib/parse-message.js +3 -3
  73. package/lib/privileged-settings.js +2 -2
  74. package/lib/queue-browser/definitions.js +11 -0
  75. package/lib/queue-browser/index.js +68 -19
  76. package/lib/queue-job-actions.js +18 -1
  77. package/lib/queue-retention.js +48 -12
  78. package/lib/queue-stats.js +11 -2
  79. package/lib/read-env-value.js +3 -0
  80. package/lib/redis-memory-warnings.js +99 -0
  81. package/lib/redis-reconnect.js +29 -0
  82. package/lib/request-timing.js +23 -0
  83. package/lib/respawn-backoff.js +35 -0
  84. package/lib/rewrite-text-nodes.js +19 -59
  85. package/lib/schemas.js +163 -39
  86. package/lib/settings.js +6 -2
  87. package/lib/smtp-auth.js +19 -1
  88. package/lib/thread-diagnostics.js +18 -1
  89. package/lib/tls/provision.js +6 -3
  90. package/lib/token-audit-log.js +19 -20
  91. package/lib/token-permission-view.js +4 -3
  92. package/lib/tools.js +8 -41
  93. package/lib/ui-routes/admin-config-routes.js +64 -90
  94. package/lib/ui-routes/admin-entities-routes.js +2 -14
  95. package/lib/ui-routes/imap-idle-field.js +1 -1
  96. package/lib/ui-routes/outlook-subscription-view.js +1 -1
  97. package/lib/ui-routes/overridable-fields.js +84 -0
  98. package/lib/ui-routes/queue-routes.js +8 -5
  99. package/lib/ui-routes/settings-page.js +6 -0
  100. package/lib/utils/decode-headers.js +3 -12
  101. package/lib/utils/filter-empty.js +20 -0
  102. package/lib/utils/int-setting.js +48 -0
  103. package/lib/utils/tracking-settings.js +35 -0
  104. package/lib/web-safe-html.js +18 -105
  105. package/lib/webhook-delivery.js +461 -0
  106. package/lib/webhook-failures.js +132 -0
  107. package/lib/webhook-request.js +29 -1
  108. package/lib/webhook-routing.js +30 -1
  109. package/lib/webhook-test.js +88 -0
  110. package/lib/webhooks.js +54 -41
  111. package/lib/worker-rpc-error.js +2 -1
  112. package/package.json +21 -20
  113. package/sbom.json +304 -382
  114. package/server.js +149 -76
  115. package/static/js/ace/ace.js +1 -1
  116. package/static/licenses.html +21 -31
  117. package/translations/messages.pot +26 -26
  118. package/views/config/security.hbs +22 -0
  119. package/views/config/service.hbs +44 -0
  120. package/views/config/webhooks.hbs +36 -0
  121. package/views/partials/queue_retention_note.hbs +12 -8
  122. package/views/partials/ui/env-managed-alert.hbs +16 -7
  123. package/workers/api.js +102 -28
  124. package/workers/export.js +16 -631
  125. package/workers/imap.js +13 -0
  126. package/workers/smtp.js +9 -11
  127. package/workers/webhooks.js +18 -432
  128. 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,8 +26,8 @@ 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');
35
33
  const { isFailedDelivery } = require('../base-client');
@@ -50,7 +48,8 @@ const {
50
48
  TRANSIENT_NETWORK_CODES,
51
49
  CONNECTION_CLOSING_CODES,
52
50
  PHANTOM_SELECT_FAIL_THRESHOLD,
53
- PHANTOM_REPROBE_INTERVAL
51
+ PHANTOM_REPROBE_INTERVAL,
52
+ NEW_MESSAGE_SETTINGS
54
53
  } = require('../../consts');
55
54
 
56
55
  const {
@@ -64,6 +63,11 @@ const {
64
63
  FULL_SYNC_DELAY
65
64
  } = require('./sync-operations');
66
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
+
67
71
  /**
68
72
  * Whether the connection is gone, rather than this message being a problem. An enrichment step that
69
73
  * hits one must let it propagate: publishSyncedEvents() keeps the message queued for the next pass
@@ -176,17 +180,12 @@ function parseAddressHeader(values) {
176
180
  }
177
181
 
178
182
  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
- });
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 }));
190
189
 
191
190
  return addressList.length ? addressList : undefined;
192
191
  } catch (err) {
@@ -201,7 +200,7 @@ function parseAddressHeader(values) {
201
200
  * An ENVELOPE list can come back holding no address anyone could use: RFC 9051 7.5.2 group
202
201
  * markers carry a group name and nothing else, and a server that failed to parse a malformed
203
202
  * 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
203
+ * the better answer then, because the header parser sees the original value and can still recover
205
204
  * the recipient. A list has to be judged on what its entries hold, not on being non-empty.
206
205
  *
207
206
  * The header is parsed only when the ENVELOPE turns out to be unusable, which is rare.
@@ -270,6 +269,7 @@ class Mailbox {
270
269
 
271
270
  this.synced = false; // Resolver of the sync() promise while a pass is waiting for its SELECT
272
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
273
273
  this.syncing = false; // Whether currently syncing
274
274
  this.processingOpen = false; // Whether onOpen() is currently running for this mailbox
275
275
  this.processingOpenClient = null; // The IMAP client whose open event holds the processingOpen latch
@@ -420,8 +420,8 @@ class Mailbox {
420
420
  * @param {string} notificationType - Type of notification for logging context
421
421
  * @returns {string|null} Packed UID or null if packing failed
422
422
  */
423
- async packUidWithLogging(uid, notificationType) {
424
- let packedUid = await this.connection.packUid(this, uid);
423
+ async packUidWithLogging(uid, notificationType, statusCache) {
424
+ let packedUid = await this.connection.packUid(this, uid, statusCache);
425
425
  if (!packedUid) {
426
426
  this.logger.warn({
427
427
  msg: 'Skipping notification, packUid returned invalid result',
@@ -502,12 +502,43 @@ class Mailbox {
502
502
  * @returns {Number} Sequence number for the added entry
503
503
  */
504
504
  async entryListSet(data) {
505
- if (isNaN(data.uid)) {
505
+ const args = this.entryListSetArgs(data);
506
+ if (!args) {
506
507
  return null;
507
508
  }
508
509
 
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));
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)];
511
542
  }
512
543
 
513
544
  /**
@@ -537,6 +568,30 @@ class Mailbox {
537
568
  return null;
538
569
  }
539
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
+
540
595
  /**
541
596
  * Deletes entry from message list for the provided sequence value or UID
542
597
  * @param {Number} seq - Sequence number (0 if using UID)
@@ -556,6 +611,56 @@ class Mailbox {
556
611
  return null;
557
612
  }
558
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
+
559
664
  /**
560
665
  * Checks if this mailbox is currently selected in the IMAP connection
561
666
  * @returns {Boolean} True if selected
@@ -672,15 +777,34 @@ class Mailbox {
672
777
  * the first still waits for its SELECT would take the slot over, and the first
673
778
  * caller - the resync loop, which re-arms its timer only once every folder has
674
779
  * returned - would never be settled. Calls overlap whenever a subconnection reports
675
- * 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
676
786
  * @param {Boolean} forceEmpty - Force sync even if mailbox appears unchanged
677
787
  * @returns {Boolean} True if synced
678
788
  */
679
789
  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;
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;
684
808
  }
685
809
 
686
810
  /**
@@ -953,11 +1077,83 @@ class Mailbox {
953
1077
  return lock;
954
1078
  }
955
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
+ */
956
1130
  async getMailboxLock(connectionClient, options) {
957
1131
  connectionClient = connectionClient || this.requireImapClient();
958
1132
 
959
- 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));
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
+ }
960
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) {
961
1157
  if (connectionClient !== this.connection.imapClient) {
962
1158
  return lock;
963
1159
  }
@@ -1011,22 +1207,41 @@ class Mailbox {
1011
1207
  return;
1012
1208
  }
1013
1209
 
1014
- // 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) {
1015
1235
  clearTimeout(this.runPartialSyncTimer);
1016
1236
  this.runPartialSyncTimer = setTimeout(() => {
1017
1237
  this.runPartialSyncTimer = null;
1018
- this.shouldRunPartialSyncAfterExists()
1019
- .then(shouldRun => {
1020
- if (shouldRun) {
1021
- return this.partialSync();
1022
- }
1023
- return false;
1024
- })
1238
+ shouldRun()
1239
+ .then(run => (run ? this.partialSync() : false))
1025
1240
  .catch(err => {
1026
1241
  if (CONNECTION_CLOSING_CODES.has(err.code)) {
1027
1242
  this.logger.debug({ msg: 'Sync skipped, connection closing', err });
1028
1243
  } else {
1029
- this.logger.warn({ msg: 'Failed to sync mailbox after EXISTS', err });
1244
+ this.logger.warn({ msg: `Failed to sync mailbox after ${trigger}`, err });
1030
1245
  }
1031
1246
  });
1032
1247
  }, 1000);
@@ -1125,12 +1340,16 @@ class Mailbox {
1125
1340
  /**
1126
1341
  * Processes a deleted message and sends the notification
1127
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()
1128
1347
  */
1129
- async processDeleted(messageData) {
1348
+ async processDeleted(messageData, opts = {}) {
1130
1349
  this.logger.debug({ msg: 'Message deleted', uid: messageData.uid });
1131
1350
 
1132
1351
  // Generate packed UID for external reference
1133
- let packedUid = await this.packUidWithLogging(messageData.uid, 'delete');
1352
+ let packedUid = await this.packUidWithLogging(messageData.uid, 'delete', opts.statusCache);
1134
1353
  if (!packedUid) {
1135
1354
  return;
1136
1355
  }
@@ -1139,6 +1358,10 @@ class Mailbox {
1139
1358
  uid: messageData.uid
1140
1359
  });
1141
1360
 
1361
+ if (opts.dequeued) {
1362
+ return;
1363
+ }
1364
+
1142
1365
  try {
1143
1366
  // Remove from notifications queue since message no longer exists
1144
1367
  await this.connection.redis.zremrangebyscore(this.getNotificationsKey(), messageData.uid, messageData.uid);
@@ -1193,7 +1416,7 @@ class Mailbox {
1193
1416
  * @param {Object} options - Processing options
1194
1417
  * @param {Object} storedStatus - Current mailbox status
1195
1418
  */
1196
- async processNew(messageData, options, storedStatus) {
1419
+ async processNew(messageData, options, storedStatus, categories, passSettings) {
1197
1420
  this.logger.debug({ msg: 'New message', uid: messageData.uid, flags: Array.from(messageData.flags) });
1198
1421
 
1199
1422
  options.skipLock = true;
@@ -1444,6 +1667,8 @@ class Mailbox {
1444
1667
  });
1445
1668
  }
1446
1669
  } catch (err) {
1670
+ // A parser failure leaves the IMAP download unconsumed, as in the DSN branch above
1671
+ content?.destroy?.();
1447
1672
  if (isConnectionGone(err)) {
1448
1673
  throw err;
1449
1674
  }
@@ -1457,145 +1682,49 @@ class Mailbox {
1457
1682
  }
1458
1683
  }
1459
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
+
1460
1689
  // Resolve Gmail category for inbox messages
1461
1690
  if (
1462
1691
  this.connection.imapClient?.capabilities?.has('X-GM-EXT-1') &&
1463
1692
  this.isAllMail &&
1464
1693
  messageInfo.labels &&
1465
1694
  messageInfo.labels.includes('\\Inbox') &&
1466
- (await settings.get('resolveGmailCategories'))
1695
+ resolveGmailCategories
1467
1696
  ) {
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;
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
+ });
1707
+ }
1708
+ } catch (err) {
1709
+ if (isConnectionGone(err)) {
1710
+ throw err;
1500
1711
  }
1712
+ this.logger.warn({ msg: 'Failed to resolve category for message', err, uid: messageData.uid, id: messageInfo.id });
1501
1713
  }
1502
1714
  }
1503
1715
 
1716
+ const loadAttachment = attachment => this.loadAttachmentContent(messageInfo, attachment, options);
1717
+
1504
1718
  // 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
- }
1719
+ if (notifyAttachments) {
1720
+ await loadNotifyAttachments(messageInfo.attachments, notifyAttachmentSize, loadAttachment);
1517
1721
  }
1518
1722
 
1519
1723
  // 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
- });
1724
+ if (notifyCalendarEvents) {
1725
+ const calendarEvents = await collectCalendarEvents(messageInfo.attachments, loadAttachment, this.logger);
1726
+ if (calendarEvents) {
1727
+ messageInfo.calendarEvents = calendarEvents;
1599
1728
  }
1600
1729
  }
1601
1730
 
@@ -1622,7 +1751,6 @@ class Mailbox {
1622
1751
  }
1623
1752
 
1624
1753
  // Convert message HTML to web safe HTML
1625
- let notifyWebSafeHtml = await settings.get('notifyWebSafeHtml');
1626
1754
  if (notifyWebSafeHtml && messageInfo.text && (messageInfo.text.html || messageInfo.text.plain)) {
1627
1755
  // convert to web safe
1628
1756
  messageInfo.text._generatedHtml = await messageWebSafeHtml(messageInfo);
@@ -1758,13 +1886,13 @@ class Mailbox {
1758
1886
  * @param {Boolean} extended - Include extended information
1759
1887
  * @returns {Object} Formatted message info
1760
1888
  */
1761
- async getMessageInfo(messageData, extended) {
1889
+ async getMessageInfo(messageData, extended, statusCache) {
1762
1890
  if (!messageData) {
1763
1891
  return false;
1764
1892
  }
1765
1893
 
1766
1894
  // Generate unique message ID
1767
- let packedUid = await this.connection.packUid(this, messageData.uid);
1895
+ let packedUid = await this.connection.packUid(this, messageData.uid, statusCache);
1768
1896
 
1769
1897
  if (!packedUid) {
1770
1898
  let storedStatus;
@@ -1983,9 +2111,10 @@ class Mailbox {
1983
2111
  * Processes flag changes for a message
1984
2112
  * @param {Object} messageData - Message data with changes
1985
2113
  * @param {Object} changes - What changed
2114
+ * @param {Map} [statusCache] - Shared by the messages of one batch, see packUid()
1986
2115
  */
1987
- async processChanges(messageData, changes) {
1988
- let packedUid = await this.packUidWithLogging(messageData.uid, 'update');
2116
+ async processChanges(messageData, changes, statusCache) {
2117
+ let packedUid = await this.packUidWithLogging(messageData.uid, 'update', statusCache);
1989
2118
  if (!packedUid) {
1990
2119
  return;
1991
2120
  }
@@ -2023,6 +2152,53 @@ class Mailbox {
2023
2152
  return this.syncOps.seedMailboxIndex(mailboxStatus, options);
2024
2153
  }
2025
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
+
2026
2202
  /**
2027
2203
  * Processes queued notification events after sync
2028
2204
  * Fetches full message details and sends notifications
@@ -2059,6 +2235,12 @@ class Mailbox {
2059
2235
  messageFetchOptions.fetchHeaders = notificationHeaderFields(messageFetchOptions.headers, summaryHeaders);
2060
2236
  }
2061
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
+
2062
2244
  // Peek-then-remove: read entries without removing so that connection errors
2063
2245
  // leave unprocessed entries in Redis for retry on reconnect.
2064
2246
  let queuedEntry;
@@ -2086,7 +2268,7 @@ class Mailbox {
2086
2268
  }
2087
2269
 
2088
2270
  try {
2089
- await this.processNew(messageData, messageFetchOptions, storedStatus);
2271
+ await this.processNew(messageData, messageFetchOptions, storedStatus, categories, passSettings);
2090
2272
  await this.connection.redis.zrem(notificationsKey, rawMember);
2091
2273
  this.throttledArrivals?.delete(rawMember);
2092
2274
  } catch (err) {
@@ -2687,13 +2869,7 @@ class Mailbox {
2687
2869
 
2688
2870
  const connectionClient = await this.connection.getImapConnection(connectionOptions);
2689
2871
 
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 {
2872
+ return await this.withMessageLock(connectionClient, message, { description: `Update message: ${message.uid}` }, async () => {
2697
2873
  let result = {};
2698
2874
 
2699
2875
  // Update flags
@@ -2751,9 +2927,7 @@ class Mailbox {
2751
2927
  }
2752
2928
 
2753
2929
  return result;
2754
- } finally {
2755
- lock.release();
2756
- }
2930
+ });
2757
2931
  }
2758
2932
 
2759
2933
  /**
@@ -2768,9 +2942,7 @@ class Mailbox {
2768
2942
 
2769
2943
  const connectionClient = await this.connection.getImapConnection(connectionOptions);
2770
2944
 
2771
- let lock = await this.getMailboxLock(connectionClient, { description: `Update messages` });
2772
-
2773
- try {
2945
+ return await this.withMailboxLock(connectionClient, { description: `Update messages`, refresh: true }, async () => {
2774
2946
  let result = {};
2775
2947
 
2776
2948
  // Update flags for matching messages
@@ -2828,9 +3000,7 @@ class Mailbox {
2828
3000
  }
2829
3001
 
2830
3002
  return result;
2831
- } finally {
2832
- lock.release();
2833
- }
3003
+ });
2834
3004
  }
2835
3005
 
2836
3006
  /**
@@ -2846,13 +3016,7 @@ class Mailbox {
2846
3016
 
2847
3017
  const connectionClient = await this.connection.getImapConnection(connectionOptions);
2848
3018
 
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 {
3019
+ return await this.withMessageLock(connectionClient, message, { description: `Move message: ${message.uid} to: ${target.path}` }, async () => {
2856
3020
  let result = {};
2857
3021
 
2858
3022
  if (target.path) {
@@ -2870,9 +3034,7 @@ class Mailbox {
2870
3034
  }
2871
3035
 
2872
3036
  return result;
2873
- } finally {
2874
- lock.release();
2875
- }
3037
+ });
2876
3038
  }
2877
3039
 
2878
3040
  /**
@@ -2887,9 +3049,7 @@ class Mailbox {
2887
3049
 
2888
3050
  const connectionClient = await this.connection.getImapConnection(connectionOptions);
2889
3051
 
2890
- let lock = await this.getMailboxLock(connectionClient, { description: `Move messages to: ${target.path}` });
2891
-
2892
- try {
3052
+ return await this.withMailboxLock(connectionClient, { description: `Move messages to: ${target.path}`, refresh: true }, async () => {
2893
3053
  let result = {};
2894
3054
 
2895
3055
  if (target.path) {
@@ -2908,9 +3068,7 @@ class Mailbox {
2908
3068
  }
2909
3069
 
2910
3070
  return result;
2911
- } finally {
2912
- lock.release();
2913
- }
3071
+ });
2914
3072
  }
2915
3073
 
2916
3074
  /**
@@ -2923,13 +3081,7 @@ class Mailbox {
2923
3081
  async deleteMessage(message, force, connectionOptions) {
2924
3082
  const connectionClient = await this.connection.getImapConnection(connectionOptions);
2925
3083
 
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 {
3084
+ return await this.withMessageLock(connectionClient, message, { description: `Delete message: ${message.uid}` }, async () => {
2933
3085
  let result = {};
2934
3086
 
2935
3087
  // Permanently delete if in Trash/Junk or forced
@@ -2959,9 +3111,7 @@ class Mailbox {
2959
3111
  }
2960
3112
 
2961
3113
  return result;
2962
- } finally {
2963
- lock.release();
2964
- }
3114
+ });
2965
3115
  }
2966
3116
 
2967
3117
  /**
@@ -2974,9 +3124,7 @@ class Mailbox {
2974
3124
  async deleteMessages(search, force, connectionOptions) {
2975
3125
  const connectionClient = await this.connection.getImapConnection(connectionOptions);
2976
3126
 
2977
- let lock = await this.getMailboxLock(connectionClient, { description: `Delete messages` });
2978
-
2979
- try {
3127
+ return await this.withMailboxLock(connectionClient, { description: `Delete messages`, refresh: true }, async () => {
2980
3128
  let result = {};
2981
3129
 
2982
3130
  // Permanently delete if in Trash/Junk or forced
@@ -3010,9 +3158,7 @@ class Mailbox {
3010
3158
  }
3011
3159
 
3012
3160
  return result;
3013
- } finally {
3014
- lock.release();
3015
- }
3161
+ });
3016
3162
  }
3017
3163
 
3018
3164
  /**
@@ -3042,9 +3188,8 @@ class Mailbox {
3042
3188
 
3043
3189
  const connectionClient = await this.connection.getImapConnection(connectionOptions);
3044
3190
 
3045
- let lock = await this.getMailboxLock(connectionClient, { description: `List messages from: ${this.path}` });
3046
-
3047
- 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 () => {
3048
3193
  let mailboxStatus = this.getMailboxStatus(connectionClient);
3049
3194
 
3050
3195
  let messageCount = mailboxStatus.messages;
@@ -3140,6 +3285,9 @@ class Mailbox {
3140
3285
  }
3141
3286
  }
3142
3287
 
3288
+ // One stored status read for the whole page, not one per message
3289
+ const statusCache = new Map();
3290
+
3143
3291
  // Fetch messages in the range
3144
3292
  for await (let messageData of connectionClient.fetch(range, fields, opts)) {
3145
3293
  if (!messageData || !messageData.uid) {
@@ -3149,7 +3297,7 @@ class Mailbox {
3149
3297
  }
3150
3298
  let messageInfo;
3151
3299
  try {
3152
- messageInfo = await this.getMessageInfo(messageData);
3300
+ messageInfo = await this.getMessageInfo(messageData, false, statusCache);
3153
3301
  } catch (err) {
3154
3302
  // Return error info for failed messages
3155
3303
  messageInfo = {
@@ -3171,9 +3319,7 @@ class Mailbox {
3171
3319
  // List newer entries first. Servers like yahoo do not return ordered list, so we need to order manually
3172
3320
  messages: messages.sort((a, b) => b.uid - a.uid)
3173
3321
  };
3174
- } finally {
3175
- lock.release();
3176
- }
3322
+ });
3177
3323
  }
3178
3324
 
3179
3325
  /**