emailengine-app 2.79.9 → 2.80.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 (75) hide show
  1. package/.release-please-manifest.json +1 -1
  2. package/CHANGELOG.md +49 -0
  3. package/config/default.toml +5 -1
  4. package/data/google-crawlers.json +1 -1
  5. package/encrypt.js +43 -0
  6. package/lib/account/account-state.js +62 -0
  7. package/lib/account.js +34 -2
  8. package/lib/api-routes/account-routes.js +20 -0
  9. package/lib/api-routes/index.js +1 -1
  10. package/lib/api-routes/settings-routes.js +17 -2
  11. package/lib/autodetect-imap-settings.js +349 -47
  12. package/lib/cert-handler.js +62 -0
  13. package/lib/consts.js +50 -6
  14. package/lib/db.js +12 -0
  15. package/lib/egress-fetch.js +21 -9
  16. package/lib/email-client/base-client.js +234 -66
  17. package/lib/email-client/credential-errors.js +118 -0
  18. package/lib/email-client/gmail/gmail-api.js +2 -1
  19. package/lib/email-client/gmail-client.js +70 -64
  20. package/lib/email-client/imap/connection-errors.js +52 -0
  21. package/lib/email-client/imap/listing-diff.js +47 -6
  22. package/lib/email-client/imap/mailbox.js +457 -379
  23. package/lib/email-client/imap/subconnection.js +15 -11
  24. package/lib/email-client/imap/sync-operations.js +46 -59
  25. package/lib/email-client/imap-client.js +136 -95
  26. package/lib/email-client/message-builder.js +11 -11
  27. package/lib/email-client/outlook/graph-api.js +2 -1
  28. package/lib/email-client/outlook-client.js +219 -106
  29. package/lib/imap-proxy-auth.js +58 -3
  30. package/lib/imapproxy/imap-server.js +53 -62
  31. package/lib/lua/h-del-if-equals.lua +39 -0
  32. package/lib/lua/h-set-if-equals.lua +39 -0
  33. package/lib/routes-ui.js +4 -34
  34. package/lib/schemas.js +32 -0
  35. package/lib/security-headers.js +15 -0
  36. package/lib/tls/context.js +376 -0
  37. package/lib/tls/der.js +223 -0
  38. package/lib/tls/provision.js +555 -0
  39. package/lib/tls/self-signed.js +282 -0
  40. package/lib/tls/status.js +431 -0
  41. package/lib/tls/store.js +666 -0
  42. package/lib/tools.js +72 -27
  43. package/lib/ui-routes/account-routes.js +43 -30
  44. package/lib/ui-routes/admin-config-routes.js +22 -1
  45. package/lib/ui-routes/auth-routes.js +16 -1
  46. package/lib/ui-routes/internals-routes.js +3 -5
  47. package/lib/ui-routes/network-config-routes.js +54 -45
  48. package/lib/ui-routes/tls-config-routes.js +581 -0
  49. package/lib/utils/mailbox-path.js +51 -0
  50. package/lib/utils/severity.js +31 -0
  51. package/package.json +4 -4
  52. package/sbom.json +1 -1
  53. package/server.js +16 -0
  54. package/static/css/flyonui.css +1 -1
  55. package/static/css/src/app.tailwind.css +11 -0
  56. package/static/js/app.js +34 -0
  57. package/static/js/public.js +6 -2
  58. package/static/js/ui.js +8 -25
  59. package/static/licenses.html +328 -1257
  60. package/translations/messages.pot +87 -87
  61. package/views/account/login-redirect.hbs +22 -0
  62. package/views/config/imap-proxy.hbs +0 -3
  63. package/views/config/smtp.hbs +0 -3
  64. package/views/config/tls-upload.hbs +81 -0
  65. package/views/config/tls.hbs +492 -0
  66. package/views/partials/side_menu.hbs +1 -0
  67. package/views/partials/tls_security_card.hbs +25 -53
  68. package/views/partials/ui/alert-banner.hbs +3 -2
  69. package/views/partials/ui/badge.hbs +6 -2
  70. package/views/partials/ui/btn.hbs +5 -2
  71. package/workers/api.js +93 -134
  72. package/workers/imap-proxy.js +4 -1
  73. package/workers/smtp.js +51 -44
  74. package/views/partials/tls_security_js.hbs +0 -64
  75. package/views/partials/tls_security_modal.hbs +0 -22
@@ -14,6 +14,8 @@ const {
14
14
  collectCidReferences,
15
15
  cidReferenceRegex
16
16
  } = require('../../tools');
17
+ const { samePath } = require('../../utils/mailbox-path');
18
+ const { connectionNotAvailableError } = require('./connection-errors');
17
19
  const msgpack = require('../../msgpack');
18
20
  const he = require('he');
19
21
  const libmime = require('libmime');
@@ -59,6 +61,32 @@ const {
59
61
  FULL_SYNC_DELAY
60
62
  } = require('./sync-operations');
61
63
 
64
+ /**
65
+ * Whether the connection is gone, rather than this message being a problem. An enrichment step that
66
+ * hits one must let it propagate: publishSyncedEvents() keeps the message queued for the next pass
67
+ * instead of announcing it with its inline images pointing at content that was never downloaded.
68
+ * No notification has been sent by then - processNew() emits all of them at the end - so the retry
69
+ * delivers exactly one webhook rather than a second copy.
70
+ *
71
+ * Deliberately narrower than the set the outer catch in publishSyncedEvents() tests: it covers only
72
+ * "the connection went away", which ends the pass anyway and clears itself on the reconnect. A
73
+ * transient network code is not obviously self-correcting, and because that loop always reads the
74
+ * head of the queue, a message failing the same way on every pass would block every message behind
75
+ * it in the folder for good.
76
+ *
77
+ * Work earlier in the pass does run twice when a later step re-queues the message: the seen-messages
78
+ * HyperLogLog (so the retry reports `seemsLikeNew: false`, an informational field), a stored bounce
79
+ * record (a duplicate row in the message's `bounces` array), and, the expensive one, the LLM summary
80
+ * and embeddings, which sit just before the inline-image download. All of it needs the connection to
81
+ * die in one narrow window, and a re-queue was already reachable from every error thrown outside
82
+ * these catches
83
+ * @param {Error} err - The error to check
84
+ * @returns {Boolean} True when the connection, not the message, is what failed
85
+ */
86
+ function isConnectionGone(err) {
87
+ return !!err && CONNECTION_CLOSING_CODES.has(err.code);
88
+ }
89
+
62
90
  /**
63
91
  * Compact fingerprint of the STATUS counters stored in the phantom folder
64
92
  * marker - a parked phantom folder is re-probed as soon as this changes
@@ -244,7 +272,8 @@ class Mailbox {
244
272
 
245
273
  this.runPartialSyncTimer = false; // Timer for delayed partial sync after EXISTS
246
274
 
247
- this.synced = false; // Whether initial sync is complete
275
+ this.synced = false; // Resolver of the sync() promise while a pass is waiting for its SELECT
276
+ this.syncChain = null; // Promise of the latest sync() pass, which the next caller waits for
248
277
  this.syncing = false; // Whether currently syncing
249
278
  this.processingOpen = false; // Whether onOpen() is currently running for this mailbox
250
279
  this.processingOpenClient = null; // The IMAP client whose open event holds the processingOpen latch
@@ -253,19 +282,33 @@ class Mailbox {
253
282
  this.syncOps = new SyncOperations(this);
254
283
  }
255
284
 
285
+ /**
286
+ * The connection's IMAP client, or the shared connection-closed throw.
287
+ * `connection.imapClient` is null between a teardown and the
288
+ * next connect, and a sync pass already in flight reaches these calls in that window - which
289
+ * surfaced as `Cannot read properties of null (reading 'downloadMany')` in the error log and in
290
+ * Sentry, and, because a TypeError carries no code, got the message announced with its inline
291
+ * images stripped instead of re-queued.
292
+ *
293
+ * Named apart from the `connectionClient` parameter that getMailboxStatus() and
294
+ * getMailboxLock() bind, and from IMAPClient.getImapConnection(), which answers a bigger
295
+ * question (pooled or secondary connections) that these callers have no business asking
296
+ * @returns {Object} The live ImapFlow client
297
+ */
298
+ requireImapClient() {
299
+ if (!this.connection.imapClient) {
300
+ throw connectionNotAvailableError();
301
+ }
302
+ return this.connection.imapClient;
303
+ }
304
+
256
305
  /**
257
306
  * Gets current mailbox status from IMAP connection
258
307
  * @param {Object} connectionClient - IMAP client to use (defaults to main connection)
259
308
  * @returns {Object} Status object with path, highestModseq, uidValidity, uidNext, messages
260
309
  */
261
310
  getMailboxStatus(connectionClient) {
262
- connectionClient = connectionClient || this.connection.imapClient;
263
- if (!connectionClient) {
264
- let err = new Error('IMAP connection not available');
265
- err.code = 'IMAPConnectionClosing';
266
- err.statusCode = 503;
267
- throw err;
268
- }
311
+ connectionClient = connectionClient || this.requireImapClient();
269
312
 
270
313
  let mailboxInfo = connectionClient.mailbox;
271
314
 
@@ -281,6 +324,27 @@ class Mailbox {
281
324
  throw new Error('IMAP mailbox state is not available');
282
325
  }
283
326
 
327
+ if (!samePath(mailboxInfo.path, this.path)) {
328
+ // The counters would describe whatever folder the connection has open. Persisted
329
+ // as this folder's state, the next open would read them as a UIDVALIDITY change
330
+ // and rebuild the index. Whether the mismatch is a problem is the caller's call
331
+ this.logger.debug({ msg: 'IMAP connection has a different mailbox selected', path: this.path, selectedPath: mailboxInfo.path });
332
+ let err = new Error('Requested mailbox is not selected');
333
+ err.code = 'MailboxNotSelected';
334
+ err.statusCode = 503;
335
+ throw err;
336
+ }
337
+
338
+ return this.mailboxStatusFromInfo(mailboxInfo, connectionClient);
339
+ }
340
+
341
+ /**
342
+ * Normalizes an ImapFlow mailbox object into the status shape the sync state machine compares
343
+ * @param {Object} mailboxInfo - ImapFlow mailbox object: the selected mailbox, or the mailboxOpen event payload
344
+ * @param {Object} [connectionClient] - IMAP client the object came from, for diagnostics
345
+ * @returns {Object} Status object with path, highestModseq, uidValidity, uidNext, messages
346
+ */
347
+ mailboxStatusFromInfo(mailboxInfo, connectionClient) {
284
348
  let status = {
285
349
  path: this.path
286
350
  };
@@ -304,8 +368,8 @@ class Mailbox {
304
368
  uidNext: status.uidNext,
305
369
  messages: status.messages,
306
370
  mailboxPath: mailboxInfo.path,
307
- connectionState: connectionClient.state,
308
- usable: connectionClient.usable
371
+ connectionState: connectionClient?.state,
372
+ usable: connectionClient?.usable
309
373
  });
310
374
  }
311
375
 
@@ -502,13 +566,20 @@ class Mailbox {
502
566
  */
503
567
  isSelected() {
504
568
  return (
505
- this.selected &&
506
- this.connection.imapClient &&
507
- this.connection.imapClient.mailbox &&
508
- normalizePath(this.connection.imapClient.mailbox.path) === normalizePath(this.path)
569
+ this.selected && this.connection.imapClient && this.connection.imapClient.mailbox && samePath(this.connection.imapClient.mailbox.path, this.path)
509
570
  );
510
571
  }
511
572
 
573
+ /**
574
+ * Settles the sync() pass waiting for this mailbox to be opened, if one armed a
575
+ * resolver. Calling it twice is harmless - the second call lands on a settled promise
576
+ */
577
+ settleSyncPass() {
578
+ if (this.synced) {
579
+ this.synced();
580
+ }
581
+ }
582
+
512
583
  // Redis key generators for different data types
513
584
 
514
585
  /**
@@ -539,18 +610,6 @@ class Mailbox {
539
610
  return `${REDIS_PREFIX}iam:${this.connection.account}:n:${this.redisKey}`;
540
611
  }
541
612
 
542
- /**
543
- * Starts IDLE mode to receive real-time updates
544
- */
545
- startIdle() {
546
- if (!this.isSelected() || !this.connection.imapClient || this.connection.imapClient.idling) {
547
- return;
548
- }
549
- this.connection.imapClient.idle().catch(err => {
550
- this.logger.warn({ msg: 'IDLE error', err });
551
- });
552
- }
553
-
554
613
  /**
555
614
  * Clears all mailbox records from Redis and notifies about deletion
556
615
  * @param {Object} opts - Options
@@ -561,17 +620,46 @@ class Mailbox {
561
620
 
562
621
  clearTimeout(this.runPartialSyncTimer);
563
622
 
564
- // Delete all Redis keys for this mailbox
565
- await this.connection.redis.del(this.getMailboxKey());
566
- await this.connection.redis.del(this.getMessagesKey());
567
- await this.connection.redis.del(this.getNotificationsKey());
623
+ const normalizedPath = normalizePath(this.path);
624
+
625
+ // Dropping the folder from the stored listing is also the claim to announce it. That
626
+ // hash is the only record that the folder was ever listed, and HDEL reports whether
627
+ // this call is the one that removed it, so exactly one caller announces a deletion.
628
+ // Every announcement is otherwise made off a listing snapshot: deleteMailbox() clears
629
+ // the folder while the stored listing still holds it, so the next getCurrentListing()
630
+ // finds it missing from the server and announces it a second time, and two overlapping
631
+ // passes that read the hash before either wrote it announce it once each.
632
+ //
633
+ // One transaction, so the claim can not outlive the teardown it guards: with the
634
+ // listing entry gone and the index behind it left in place, nothing enumerates the
635
+ // folder again - it would neither be cleared nor announced by any later pass, and a
636
+ // folder recreated under the same name would sync against the stale index.
637
+ let result = await this.connection.redis
638
+ .multi()
639
+ .hdel(this.connection.getMailboxListKey(), normalizedPath)
640
+ .del(this.getMailboxKey(), this.getMessagesKey(), this.getNotificationsKey())
641
+ .exec();
642
+
643
+ for (let [err] of result) {
644
+ if (err) {
645
+ throw err;
646
+ }
647
+ }
568
648
 
569
- // Remove from connection's mailbox cache
570
- this.connection.mailboxes.delete(normalizePath(this.path));
649
+ let removedFromListing = !!result[0][1];
650
+
651
+ // Removing the folder from the connection's own map is the other half of that claim, and
652
+ // just as one-shot. A folder can be tracked here while its listing entry is already gone:
653
+ // processListing() registers a Mailbox without writing the hash, and a pass that had to
654
+ // defer the entry (no primary connection) or purged it as corrupt writes the hash back
655
+ // without it. Gating on the HDEL alone, a folder in that state was torn down in silence
656
+ // and no later pass could announce it either - the deleted entries a pass reports come
657
+ // from the very hash the folder is missing from.
658
+ const removedFromTracking = this.connection.mailboxes.delete(normalizedPath);
571
659
 
572
660
  this.logger.debug({ msg: 'Deleted mailbox', path: this.listingEntry.path });
573
661
 
574
- if (!opts.skipNotify) {
662
+ if (!opts.skipNotify && (removedFromListing || removedFromTracking)) {
575
663
  this.connection
576
664
  .notify(this, MAILBOX_DELETED_NOTIFY, {
577
665
  path: this.listingEntry.path,
@@ -583,11 +671,29 @@ class Mailbox {
583
671
  }
584
672
 
585
673
  /**
586
- * Syncs mailbox without selecting it (using STATUS command)
674
+ * Syncs the mailbox, running overlapping calls one after another. A pass awaits a
675
+ * promise with a single resolver slot (this.synced): a second call arming it while
676
+ * the first still waits for its SELECT would take the slot over, and the first
677
+ * caller - the resync loop, which re-arms its timer only once every folder has
678
+ * returned - would never be settled. Calls overlap whenever a subconnection reports
679
+ * a change or a listing refresh registers folders during a resync pass
587
680
  * @param {Boolean} forceEmpty - Force sync even if mailbox appears unchanged
588
681
  * @returns {Boolean} True if synced
589
682
  */
590
683
  async sync(forceEmpty) {
684
+ // A rejected pass was reported to its own caller; the next pass runs regardless
685
+ const current = (this.syncChain || Promise.resolve()).catch(() => {}).then(() => this.syncOnce(forceEmpty));
686
+ this.syncChain = current;
687
+ return await current;
688
+ }
689
+
690
+ /**
691
+ * One sync pass: compares the STATUS counters with the stored state and selects the
692
+ * mailbox when they drifted, which runs the state machine in onOpen()
693
+ * @param {Boolean} forceEmpty - Force sync even if mailbox appears unchanged
694
+ * @returns {Boolean} True if synced
695
+ */
696
+ async syncOnce(forceEmpty) {
591
697
  if (this.selected || !this.connection.imapClient) {
592
698
  // expect current folder to be already synced
593
699
  return false;
@@ -654,7 +760,7 @@ class Mailbox {
654
760
 
655
761
  // Re-check after the awaits above: a concurrent operation may have
656
762
  // selected this mailbox while we were reading STATUS / stored state.
657
- // In that case onOpen() owns the sync work, and select(true) below
763
+ // In that case onOpen() owns the sync work, and select() below
658
764
  // would skip the SELECT without another mailboxOpen event ever firing
659
765
  if (this.selected || !this.connection.imapClient) {
660
766
  // expect current folder to be already synced
@@ -688,7 +794,7 @@ class Mailbox {
688
794
  // Need to sync - create promise that resolves when sync is complete
689
795
  let syncedPromise = new Promise((resolve, reject) => {
690
796
  this.synced = resolve;
691
- this.select(true).catch(err => reject(err));
797
+ this.select().catch(err => reject(err));
692
798
  });
693
799
 
694
800
  try {
@@ -703,7 +809,6 @@ class Mailbox {
703
809
  // A failing refresh is a connection-level error and propagates, same
704
810
  // as in the NotFound branch above.
705
811
  this.logger.info({ msg: 'Mailbox is missing, refreshing folder listing', path: this.path });
706
- this.synced = false;
707
812
  await this.connection.refreshAndProcessListing();
708
813
  return;
709
814
  }
@@ -720,13 +825,16 @@ class Mailbox {
720
825
  serverResponseCode: err.serverResponseCode,
721
826
  responseText: err.responseText
722
827
  });
723
- this.synced = false;
724
828
  // Count the failure so a permanent phantom stops being probed on
725
829
  // every sync pass once it hits PHANTOM_SELECT_FAIL_THRESHOLD
726
830
  await this.setPhantomState(phantomState, status);
727
831
  return;
728
832
  }
729
833
  throw err;
834
+ } finally {
835
+ // Settled either way, so the slot is free for the next pass. select() and
836
+ // onOpen() call the resolver only while one is armed
837
+ this.synced = false;
730
838
  }
731
839
 
732
840
  if (phantomState) {
@@ -787,105 +895,68 @@ class Mailbox {
787
895
  }
788
896
 
789
897
  /**
790
- * Selects mailbox and optionally starts IDLE
791
- * @param {Boolean} skipIdle - Don't start IDLE after selecting
898
+ * Selects the mailbox on the primary connection, so IDLE watches it. Taking the
899
+ * lock is the SELECT: ImapFlow opens the path before granting, so once granted
900
+ * the mailbox is open and the lock is given straight back - its release re-arms
901
+ * auto-IDLE, and holding it any longer would only queue the other operations
792
902
  */
793
- async select(skipIdle) {
794
- if (!this.connection.imapClient) {
795
- let err = new Error('IMAP connection not available');
796
- err.code = 'IMAPConnectionClosing';
797
- err.statusCode = 503;
798
- throw err;
799
- }
800
- const currentLock = this.connection.imapClient.currentLock;
801
- // Avoid interfering with any active operations
802
- if (currentLock) {
803
- if (this.path === currentLock.path) {
804
- // Already on the correct mailbox with an active lock
805
- this.logger.trace({
806
- msg: 'Skip extra lock on active mailbox',
807
- activeLock: {
808
- lockId: currentLock.lockId,
809
- path: currentLock.path,
810
- ...(currentLock.options?.description && { description: currentLock.options?.description })
811
- }
812
- });
813
- if (this.synced) {
814
- // Locks are only granted after the mailbox is open, so no
815
- // further mailboxOpen event is coming for this path. Settle
816
- // the resolver armed by sync() instead of leaving it waiting
817
- // forever. If the open's onOpen() is still running, its own
818
- // resolve call later is a no-op on the settled promise
819
- this.synced();
820
- }
821
- return;
822
- }
823
- // Different mailbox is locked - queue this select to run after lock is released
824
- // This ensures we don't interfere with ongoing operations
825
- this.logger.trace({
826
- msg: 'Queueing select - another mailbox is locked',
827
- requestedPath: this.path,
828
- lockedPath: currentLock.path,
829
- activeLock: currentLock.lockId
830
- });
831
- }
832
-
833
- // Get lock and wait our turn - this will queue if another operation is active
834
- let lock = await this.getMailboxLock(null, { description: `Select mailbox: ${this.path}` });
835
-
836
- // Check if we still need to select after getting the lock
837
- // Another operation might have already selected this mailbox while we were waiting
838
- if (this.connection.imapClient?.mailbox && this.connection.imapClient.mailbox.path === this.path) {
839
- this.logger.trace({
840
- msg: 'Mailbox already selected after lock acquired',
841
- path: this.path
842
- });
843
- if (this.synced) {
844
- // The lock was granted against the already-open mailbox without
845
- // a new SELECT, so no mailboxOpen event fires - settle the
846
- // resolver armed by sync() instead of leaving it waiting forever
847
- this.synced();
848
- }
903
+ async select() {
904
+ // Captured before the await: this is the pass select() was called for, and by the
905
+ // time it returns the slot can hold the resolver of a later one
906
+ const settle = this.synced;
907
+
908
+ if (!this.isSelected()) {
909
+ // getMailboxLock() throws when there is no connection to select on
910
+ let lock = await this.getMailboxLock(null, { description: `Select mailbox: ${this.path}` });
849
911
  lock.release();
850
- return;
851
912
  }
852
913
 
853
- // Keep the lock briefly to ensure IDLE can start without interference
854
- // Release after a short delay to allow IDLE to initialize
855
- setTimeout(() => {
856
- lock.release();
857
- }, 100);
858
-
859
- if (!skipIdle) {
860
- // Do not wait until command finishes before proceeding
861
- this.startIdle();
914
+ // An open handler settles the pass itself, once its sync work is done - which
915
+ // connection it belongs to does not matter, the resolver is per mailbox. With none
916
+ // running, no mailboxOpen event is coming for this already-open mailbox and the
917
+ // pass would wait forever
918
+ if (settle && !this.processingOpen) {
919
+ settle();
862
920
  }
863
921
  }
864
922
 
865
923
  /**
866
- * Acquires exclusive lock on mailbox to prevent concurrent operations
924
+ * Acquires exclusive lock on mailbox to prevent concurrent operations.
925
+ *
926
+ * A lock on the primary connection takes it away from the mailbox it watches, so the
927
+ * pending return to the main mailbox is cancelled here and re-armed by the returned
928
+ * release(). Both halves live in this one place on purpose: when each holder had to
929
+ * report the task itself, the sync operations never did, and an API command's SELECT
930
+ * whose open handler ran a sync left the connection parked on that folder until the
931
+ * next resync pass. A lock on a pooled secondary never moved the primary and reports nothing
867
932
  * @param {Object} connectionClient - IMAP client to use
868
933
  * @param {Object} options - Lock options
869
934
  * @returns {Object} Lock object with release() method
870
935
  */
871
936
  async getMailboxLock(connectionClient, options) {
872
- connectionClient = connectionClient || this.connection.imapClient;
873
-
874
- if (!connectionClient) {
875
- let err = new Error('IMAP connection not available');
876
- err.code = 'IMAPConnectionClosing';
877
- err.statusCode = 503;
878
- throw err;
879
- }
937
+ connectionClient = connectionClient || this.requireImapClient();
880
938
 
881
939
  let lock = await connectionClient.getMailboxLock(this.path, options || {});
882
940
 
883
- // Reset idle timer when using main connection
884
- if (connectionClient === this.connection.imapClient) {
885
- clearTimeout(this.connection.completedTimer);
941
+ if (connectionClient !== this.connection.imapClient) {
942
+ return lock;
886
943
  }
887
944
 
888
- return lock;
945
+ clearTimeout(this.connection.completedTimer);
946
+
947
+ let released = false;
948
+ return {
949
+ ...lock,
950
+ release: () => {
951
+ if (released) {
952
+ // ImapFlow ignores a repeated release; a repeated report would arm a timer for nothing
953
+ return;
954
+ }
955
+ released = true;
956
+ lock.release();
957
+ this.connection.onTaskCompleted(connectionClient);
958
+ }
959
+ };
889
960
  }
890
961
 
891
962
  /**
@@ -914,6 +985,12 @@ class Mailbox {
914
985
  async onExists(event) {
915
986
  this.logEvent('Untagged EXISTS', event);
916
987
 
988
+ if (this.syncDisabled) {
989
+ // An API command opened a folder that is excluded from syncing. Its untagged
990
+ // responses arrive like any other, but nothing in it may be indexed or advertised
991
+ return;
992
+ }
993
+
917
994
  // Debounce partial sync to avoid multiple syncs for rapid changes
918
995
  clearTimeout(this.runPartialSyncTimer);
919
996
  this.runPartialSyncTimer = setTimeout(() => {
@@ -925,7 +1002,6 @@ class Mailbox {
925
1002
  }
926
1003
  return false;
927
1004
  })
928
- .then(() => this.select())
929
1005
  .catch(err => {
930
1006
  if (CONNECTION_CLOSING_CODES.has(err.code)) {
931
1007
  this.logger.debug({ msg: 'Sync skipped, connection closing', err });
@@ -945,7 +1021,7 @@ class Mailbox {
945
1021
  event.imapIndexer = imapIndexer;
946
1022
  this.logEvent('Untagged EXPUNGE', event);
947
1023
 
948
- if (imapIndexer !== 'full') {
1024
+ if (imapIndexer !== 'full' || this.syncDisabled) {
949
1025
  // ignore as we can not compare this value against the index
950
1026
  return null;
951
1027
  }
@@ -975,7 +1051,7 @@ class Mailbox {
975
1051
  event.imapIndexer = imapIndexer;
976
1052
  this.logEvent('Untagged FETCH', event);
977
1053
 
978
- if (imapIndexer !== 'full') {
1054
+ if (imapIndexer !== 'full' || this.syncDisabled) {
979
1055
  // ignore as we can not compare this value against the index
980
1056
  return null;
981
1057
  }
@@ -1008,6 +1084,12 @@ class Mailbox {
1008
1084
  */
1009
1085
  async shouldRunPartialSyncAfterExists() {
1010
1086
  let storedStatus = await this.getStoredStatus();
1087
+ if (!this.isSelected()) {
1088
+ // An API command opened another folder while the stored state was read. The
1089
+ // connection now reports that folder's counters; the drift this folder
1090
+ // accumulated is picked up by the state machine when it is opened again
1091
+ return false;
1092
+ }
1011
1093
  let mailboxStatus = this.getMailboxStatus();
1012
1094
  // Count-only comparison misses balanced churn (an arrival paired with an
1013
1095
  // expunge in the same window) and does not work at all in 'fast' indexer
@@ -1070,6 +1152,46 @@ class Mailbox {
1070
1152
  }
1071
1153
  }
1072
1154
 
1155
+ /**
1156
+ * Downloads one attachment's body and stores it on the attachment as base64. Three enrichment
1157
+ * passes need this - the notifyAttachments loop, the inline images referenced from the HTML,
1158
+ * and calendar parts - and each carried its own copy of the decode, the download and the error
1159
+ * handling.
1160
+ *
1161
+ * A gone connection is rethrown so processNew() re-queues the message rather than announcing it
1162
+ * with the content missing; anything else is this attachment's problem and is logged. A
1163
+ * zero-length body leaves `content` unset rather than storing an empty string, which is what
1164
+ * the calendar copy always did and what the other two meant to
1165
+ * @param {Object} messageInfo - The message being enriched
1166
+ * @param {Object} attachment - Attachment entry to fill in
1167
+ * @param {Object} options - Processing options, for the download chunk size
1168
+ * @returns {Promise<void>}
1169
+ */
1170
+ async loadAttachmentContent(messageInfo, attachment, options) {
1171
+ try {
1172
+ let buf = Buffer.from(attachment.id, 'base64url');
1173
+ let part = buf.subarray(8).toString();
1174
+
1175
+ let { content: downloadStream } = await this.requireImapClient().download(messageInfo.uid, part, {
1176
+ uid: true,
1177
+ chunkSize: options.chunkSize,
1178
+ maxBytes: MAX_ALLOWED_DOWNLOAD_SIZE
1179
+ });
1180
+
1181
+ if (downloadStream) {
1182
+ let contentBuf = await download(downloadStream);
1183
+ if (contentBuf && contentBuf.length) {
1184
+ attachment.content = contentBuf.toString('base64');
1185
+ }
1186
+ }
1187
+ } catch (err) {
1188
+ if (isConnectionGone(err)) {
1189
+ throw err;
1190
+ }
1191
+ this.logger.error({ msg: 'Failed to load attachment content', attachment, err });
1192
+ }
1193
+ }
1194
+
1073
1195
  /**
1074
1196
  * Processes a new message - fetches details, detects bounces/complaints, sends notifications
1075
1197
  * @param {Object} messageData - Basic message data (uid, flags, etc)
@@ -1161,7 +1283,7 @@ class Mailbox {
1161
1283
  }
1162
1284
 
1163
1285
  // Skip old messages in non-INBOX folders on reconnect
1164
- if (this.previouslyConnected && this.path !== 'INBOX' && !this.isAllMail && storedStatus.initialUidNext > messageData.uid) {
1286
+ if (this.previouslyConnected && !samePath(this.path, 'INBOX') && !this.isAllMail && storedStatus.initialUidNext > messageData.uid) {
1165
1287
  this.logger.debug({
1166
1288
  msg: 'Skip old message',
1167
1289
  action: 'webhook_ignore',
@@ -1189,7 +1311,7 @@ class Mailbox {
1189
1311
  let buf = Buffer.from(attachment.id, 'base64url');
1190
1312
  let part = buf.subarray(8).toString();
1191
1313
 
1192
- let { content: sourceStream } = await this.connection.imapClient.download(messageInfo.uid, part, {
1314
+ let { content: sourceStream } = await this.requireImapClient().download(messageInfo.uid, part, {
1193
1315
  uid: true,
1194
1316
  // headers should fit into 1MB, don't need all contents
1195
1317
  maxBytes: Math.min(1 * 1024 * 1024, MAX_ALLOWED_DOWNLOAD_SIZE),
@@ -1220,6 +1342,9 @@ class Mailbox {
1220
1342
  }
1221
1343
  }
1222
1344
  } catch (err) {
1345
+ if (isConnectionGone(err)) {
1346
+ throw err;
1347
+ }
1223
1348
  this.logger.error({
1224
1349
  msg: 'Failed to process ARF',
1225
1350
  id: messageInfo.id,
@@ -1233,7 +1358,7 @@ class Mailbox {
1233
1358
  // Check if this might be a DSN (Delivery Status Notification)
1234
1359
  if (this.mightBeDSNResponse(messageInfo)) {
1235
1360
  try {
1236
- let { content: sourceStream } = await this.connection.imapClient.download(messageInfo.uid, false, {
1361
+ let { content: sourceStream } = await this.requireImapClient().download(messageInfo.uid, false, {
1237
1362
  uid: true,
1238
1363
  chunkSize: options.chunkSize,
1239
1364
  maxBytes: MAX_ALLOWED_DOWNLOAD_SIZE
@@ -1245,6 +1370,9 @@ class Mailbox {
1245
1370
  applyDeliveryReport(parsed, messageInfo, this.logger);
1246
1371
  }
1247
1372
  } catch (err) {
1373
+ if (isConnectionGone(err)) {
1374
+ throw err;
1375
+ }
1248
1376
  this.logger.error({
1249
1377
  msg: 'Failed to process DSN',
1250
1378
  id: messageInfo.id,
@@ -1260,7 +1388,7 @@ class Mailbox {
1260
1388
  // Parse for bounce information
1261
1389
  try {
1262
1390
  if (!content) {
1263
- let result = await this.connection.imapClient.download(messageInfo.uid, false, {
1391
+ let result = await this.requireImapClient().download(messageInfo.uid, false, {
1264
1392
  uid: true,
1265
1393
  chunkSize: options.chunkSize,
1266
1394
  maxBytes: MAX_ALLOWED_DOWNLOAD_SIZE
@@ -1325,6 +1453,9 @@ class Mailbox {
1325
1453
  });
1326
1454
  }
1327
1455
  } catch (err) {
1456
+ if (isConnectionGone(err)) {
1457
+ throw err;
1458
+ }
1328
1459
  this.logger.error({
1329
1460
  msg: 'Failed to process potential bounce',
1330
1461
  id: messageInfo.id,
@@ -1352,7 +1483,7 @@ class Mailbox {
1352
1483
  // Try each Gmail category in order
1353
1484
  for (let category of ['primary', 'social', 'promotions', 'updates', 'forums', 'reservations', 'purchases']) {
1354
1485
  try {
1355
- let results = await this.connection.imapClient.search(
1486
+ let results = await this.requireImapClient().search(
1356
1487
  {
1357
1488
  uid: messageInfo.uid,
1358
1489
  gmraw: `category:${category}`
@@ -1370,6 +1501,9 @@ class Mailbox {
1370
1501
  break;
1371
1502
  }
1372
1503
  } catch (err) {
1504
+ if (isConnectionGone(err)) {
1505
+ throw err;
1506
+ }
1373
1507
  this.logger.warn({ msg: 'Failed to resolve category for message', err, category, uid: messageData.uid, id: messageInfo.id });
1374
1508
  break;
1375
1509
  }
@@ -1386,22 +1520,7 @@ class Mailbox {
1386
1520
  continue;
1387
1521
  }
1388
1522
  if (!attachment.content) {
1389
- try {
1390
- let buf = Buffer.from(attachment.id, 'base64url');
1391
- let part = buf.subarray(8).toString();
1392
-
1393
- let { content: downloadStream } = await this.connection.imapClient.download(messageInfo.uid, part, {
1394
- uid: true,
1395
- chunkSize: options.chunkSize,
1396
- maxBytes: MAX_ALLOWED_DOWNLOAD_SIZE
1397
- });
1398
-
1399
- if (downloadStream) {
1400
- attachment.content = (await download(downloadStream)).toString('base64');
1401
- }
1402
- } catch (err) {
1403
- this.logger.error({ msg: 'Failed to load attachment content', attachment, err });
1404
- }
1523
+ await this.loadAttachmentContent(messageInfo, attachment, options);
1405
1524
  }
1406
1525
  }
1407
1526
  }
@@ -1418,22 +1537,7 @@ class Mailbox {
1418
1537
 
1419
1538
  // Check if attachment is referenced by Content-ID in HTML
1420
1539
  if (!attachment.content && attachment.contentId && cidReferences.has(attachment.contentId.replace(/^<|>$/g, ''))) {
1421
- try {
1422
- let buf = Buffer.from(attachment.id, 'base64url');
1423
- let part = buf.subarray(8).toString();
1424
-
1425
- let { content: downloadStream } = await this.connection.imapClient.download(messageInfo.uid, part, {
1426
- uid: true,
1427
- chunkSize: options.chunkSize,
1428
- maxBytes: MAX_ALLOWED_DOWNLOAD_SIZE
1429
- });
1430
-
1431
- if (downloadStream) {
1432
- attachment.content = (await download(downloadStream)).toString('base64');
1433
- }
1434
- } catch (err) {
1435
- this.logger.error({ msg: 'Failed to load attachment content', attachment, err });
1436
- }
1540
+ await this.loadAttachmentContent(messageInfo, attachment, options);
1437
1541
  }
1438
1542
  }
1439
1543
  }
@@ -1460,26 +1564,7 @@ class Mailbox {
1460
1564
  if (['text/calendar', 'application/ics'].includes(attachment.contentType)) {
1461
1565
  // Download calendar attachment if not already loaded
1462
1566
  if (!attachment.content) {
1463
- try {
1464
- let buf = Buffer.from(attachment.id, 'base64url');
1465
- let part = buf.subarray(8).toString();
1466
-
1467
- let { content: downloadStream } = await this.connection.imapClient.download(messageInfo.uid, part, {
1468
- uid: true,
1469
- chunkSize: options.chunkSize,
1470
- maxBytes: MAX_ALLOWED_DOWNLOAD_SIZE
1471
- });
1472
-
1473
- if (downloadStream) {
1474
- let contentBuf = await download(downloadStream);
1475
-
1476
- if (contentBuf && contentBuf.length) {
1477
- attachment.content = contentBuf.toString('base64');
1478
- }
1479
- }
1480
- } catch (err) {
1481
- this.logger.error({ msg: 'Failed to load attachment content', attachment, err });
1482
- }
1567
+ await this.loadAttachmentContent(messageInfo, attachment, options);
1483
1568
  }
1484
1569
  if (attachment.content) {
1485
1570
  let contentBuf = Buffer.from(attachment.content, 'base64');
@@ -1731,7 +1816,7 @@ class Mailbox {
1731
1816
  if (partList.length) {
1732
1817
  // Download missing attachments in batch
1733
1818
  try {
1734
- let contentParts = await this.connection.imapClient.downloadMany(messageInfo.uid, partList, {
1819
+ let contentParts = await this.requireImapClient().downloadMany(messageInfo.uid, partList, {
1735
1820
  uid: true
1736
1821
  });
1737
1822
 
@@ -1743,6 +1828,9 @@ class Mailbox {
1743
1828
  }
1744
1829
  }
1745
1830
  } catch (err) {
1831
+ if (isConnectionGone(err)) {
1832
+ throw err;
1833
+ }
1746
1834
  this.logger.error({ msg: 'Failed to download attachments', uid: messageInfo.uid, partList, err });
1747
1835
  }
1748
1836
  }
@@ -2078,7 +2166,7 @@ class Mailbox {
2078
2166
 
2079
2167
  /**
2080
2168
  * Performs full synchronization based on indexer type
2081
- * Delegates to SyncOperations
2169
+ * Delegates to SyncOperations, which reads the stored state itself under the lock
2082
2170
  */
2083
2171
  async fullSync() {
2084
2172
  return this.syncOps.fullSync();
@@ -2086,11 +2174,10 @@ class Mailbox {
2086
2174
 
2087
2175
  /**
2088
2176
  * Performs partial synchronization based on indexer type
2089
- * Delegates to SyncOperations
2090
- * @param {Object} storedStatus - Current stored mailbox status
2177
+ * Delegates to SyncOperations, which reads the stored state itself under the lock
2091
2178
  */
2092
- async partialSync(storedStatus) {
2093
- return this.syncOps.partialSync(storedStatus);
2179
+ async partialSync() {
2180
+ return this.syncOps.partialSync();
2094
2181
  }
2095
2182
 
2096
2183
  /**
@@ -2174,7 +2261,10 @@ class Mailbox {
2174
2261
  await this.processNew(messageData, messageFetchOptions, canSync, storedStatus);
2175
2262
  await this.connection.redis.zrem(notificationsKey, rawMember);
2176
2263
  } catch (err) {
2177
- if (CONNECTION_CLOSING_CODES.has(err.code) || TRANSIENT_NETWORK_CODES.has(err.code)) {
2264
+ // Wider than the enrichment steps on purpose: this is the last chance to keep a
2265
+ // message that failed on a transient network error, and it is not a step that can
2266
+ // re-run the same failure indefinitely - the pass ends here either way
2267
+ if (isConnectionGone(err) || TRANSIENT_NETWORK_CODES.has(err.code)) {
2178
2268
  throw err;
2179
2269
  }
2180
2270
  await this.connection.redis.zrem(notificationsKey, rawMember);
@@ -2211,9 +2301,7 @@ class Mailbox {
2211
2301
  // failing it becomes an endless reseed storm of back-to-back
2212
2302
  // SELECTs. The outer invocation owns the sync work; settle an
2213
2303
  // armed sync() resolver and bail out
2214
- if (this.synced) {
2215
- this.synced();
2216
- }
2304
+ this.settleSyncPass();
2217
2305
  return false;
2218
2306
  }
2219
2307
  // Take the latch (over) - if a previous connection's handler is still
@@ -2231,8 +2319,23 @@ class Mailbox {
2231
2319
  // Track connection count to detect reconnects
2232
2320
  this.previouslyConnected = Number(await this.connection.redis.hget(this.connection.getAccountKey(), `state:count:connected`)) || 0;
2233
2321
 
2234
- mailboxStatus = this.getMailboxStatus();
2322
+ // The event payload is the mailbox object of the SELECT that triggered this
2323
+ // handler, frozen once another folder is selected - the snapshot this decision
2324
+ // wants, whatever an API command opens on the connection during the await above
2325
+ mailboxStatus = event ? this.mailboxStatusFromInfo(event, openedClient) : this.getMailboxStatus();
2235
2326
 
2327
+ if (this.syncDisabled) {
2328
+ // Excluded from syncing but opened by an API command: refresh the listing
2329
+ // counters as syncOnce() does and index nothing
2330
+ await this.updateStoredStatus(mailboxStatus);
2331
+ return false;
2332
+ }
2333
+
2334
+ // Read outside the mailbox lock, so it only decides which sync to run. The sync
2335
+ // itself reads the stored state again once it holds the lock: a pass ahead of it in
2336
+ // the queue (an EXISTS debounce, a previous connection's open still unwinding) has
2337
+ // moved uidNext on by then, and re-fetching the range it already handled is wasted
2338
+ // work on every folder the account has
2236
2339
  let storedStatus = await this.getStoredStatus();
2237
2340
 
2238
2341
  // Lost-index recovery: the account has synced in a previous session but this folder
@@ -2251,13 +2354,9 @@ class Mailbox {
2251
2354
  storedStatus = await this.getStoredStatus();
2252
2355
  }
2253
2356
 
2254
- // Process any queued notifications first
2255
- let hasQueuedNotifications = await this.connection.redis.exists(this.getNotificationsKey());
2256
- if (hasQueuedNotifications) {
2257
- return await this.fullSync();
2258
- }
2259
-
2260
- // Check for UIDVALIDITY change (mailbox recreated)
2357
+ // Check for UIDVALIDITY change (mailbox recreated). Checked ahead of the
2358
+ // queued notifications: those reference UIDs of the previous incarnation,
2359
+ // and the reseed below drops them together with the index
2261
2360
  if (hasUidValidityChanged(storedStatus, mailboxStatus)) {
2262
2361
  // UIDVALIDITY has changed, full sync is required!
2263
2362
  // delete mailbox status
@@ -2273,9 +2372,6 @@ class Mailbox {
2273
2372
 
2274
2373
  this.logger.debug({ msg: 'Mailbox reset', path: this.listingEntry.path });
2275
2374
 
2276
- // do not advertise messages as new
2277
- this.listingEntry.isNew = true;
2278
-
2279
2375
  // Rebuild the index silently from the recreated mailbox and emit a single
2280
2376
  // mailboxReset (with prev/current UIDVALIDITY) instead of replaying every message.
2281
2377
  await this.seedMailboxIndex(mailboxStatus, {
@@ -2285,6 +2381,12 @@ class Mailbox {
2285
2381
  return false;
2286
2382
  }
2287
2383
 
2384
+ // Process any queued notifications first
2385
+ let hasQueuedNotifications = await this.connection.redis.exists(this.getNotificationsKey());
2386
+ if (hasQueuedNotifications) {
2387
+ return await this.fullSync();
2388
+ }
2389
+
2288
2390
  // Determine sync strategy using helper functions
2289
2391
 
2290
2392
  // No changes if MODSEQ hasn't changed
@@ -2299,12 +2401,12 @@ class Mailbox {
2299
2401
 
2300
2402
  // Partial sync if CONDSTORE indicates only new messages or flag changes
2301
2403
  if (this.connection.imapClient && canUseCondstorePartialSync(this.connection.imapClient, storedStatus, mailboxStatus)) {
2302
- return await this.partialSync(storedStatus);
2404
+ return await this.partialSync();
2303
2405
  }
2304
2406
 
2305
2407
  // Partial sync if only new messages
2306
2408
  if (canUseSimplePartialSync(storedStatus, mailboxStatus)) {
2307
- return await this.partialSync(storedStatus);
2409
+ return await this.partialSync();
2308
2410
  }
2309
2411
 
2310
2412
  // Skip if nothing changed and recent full sync
@@ -2354,16 +2456,8 @@ class Mailbox {
2354
2456
  .catch(err => this.logger.error({ msg: 'Failed to send new mailbox notification', err }));
2355
2457
  }
2356
2458
 
2357
- // Resolve sync promise or start IDLE
2358
- if (this.synced) {
2359
- this.synced();
2360
- } else {
2361
- try {
2362
- await this.select();
2363
- } catch (err) {
2364
- this.logger.warn({ msg: 'Failed to select after sync', err });
2365
- }
2366
- }
2459
+ // IDLE needs no restart: ImapFlow re-arms auto-IDLE on every lock release
2460
+ this.settleSyncPass();
2367
2461
  }
2368
2462
  }
2369
2463
  }
@@ -2377,8 +2471,8 @@ class Mailbox {
2377
2471
  }
2378
2472
 
2379
2473
  // User methods
2380
- // getMailboxLock() clears connection.completedTimer for the primary connection
2381
- // Call this.connection.onTaskCompleted(connectionClient) after the selected mailbox is processed and the lock is released
2474
+ // Every method takes its lock through getMailboxLock(), whose release() reports the task
2475
+ // to the connection - nothing else has to be called once the lock is given back
2382
2476
 
2383
2477
  /**
2384
2478
  * Fetches text content for a message
@@ -2452,7 +2546,6 @@ class Mailbox {
2452
2546
  // connection, so it still has to be sent back to the one it is watching.
2453
2547
  if (lock) {
2454
2548
  lock.release();
2455
- this.connection.onTaskCompleted(connectionClient);
2456
2549
  }
2457
2550
  }
2458
2551
 
@@ -2522,11 +2615,10 @@ class Mailbox {
2522
2615
  // that simply destroys the stream hold the lock forever: an abort emits neither 'end' nor
2523
2616
  // 'error', only 'close'. finished() covers end, error, destroy and premature close by
2524
2617
  // contract, and fires exactly once, so there is no set of terminal events left to get
2525
- // wrong. Reporting the task either way is what every other method here does: however the
2526
- // download ended, the connection has to go back to the mailbox it is watching.
2618
+ // wrong. However the download ended, the release sends the connection back to the
2619
+ // mailbox it is watching.
2527
2620
  finished(content, () => {
2528
2621
  lock.release();
2529
- this.connection.onTaskCompleted(connectionClient);
2530
2622
  });
2531
2623
 
2532
2624
  // Only once finished() has taken over. Set before the call, a synchronous throw from it
@@ -2538,7 +2630,6 @@ class Mailbox {
2538
2630
  } finally {
2539
2631
  if (!streaming) {
2540
2632
  lock.release();
2541
- this.connection.onTaskCompleted(connectionClient);
2542
2633
  }
2543
2634
  }
2544
2635
  }
@@ -2557,190 +2648,184 @@ class Mailbox {
2557
2648
 
2558
2649
  const connectionClient = await this.connection.getImapConnection(connectionOptions);
2559
2650
 
2560
- try {
2561
- let lock;
2562
- if (!options.skipLock) {
2563
- lock = await this.getMailboxLock(connectionClient, { description: `Get message: ${message.uid}` });
2564
- }
2651
+ let lock;
2652
+ if (!options.skipLock) {
2653
+ lock = await this.getMailboxLock(connectionClient, { description: `Get message: ${message.uid}` });
2654
+ }
2565
2655
 
2566
- try {
2567
- // Configure which fields to fetch
2568
- let fields = options.fields || {
2569
- uid: true,
2570
- flags: true,
2571
- size: true,
2572
- bodyStructure: true,
2573
- envelope: true,
2574
- internalDate: true,
2575
- headers: 'headers' in options ? options.headers : true,
2576
- emailId: true,
2577
- threadId: true,
2578
- labels: true
2579
- };
2656
+ try {
2657
+ // Configure which fields to fetch
2658
+ let fields = options.fields || {
2659
+ uid: true,
2660
+ flags: true,
2661
+ size: true,
2662
+ bodyStructure: true,
2663
+ envelope: true,
2664
+ internalDate: true,
2665
+ headers: 'headers' in options ? options.headers : true,
2666
+ emailId: true,
2667
+ threadId: true,
2668
+ labels: true
2669
+ };
2580
2670
 
2581
- let messageData = await connectionClient.fetchOne(message.uid, fields, { uid: true });
2671
+ let messageData = await connectionClient.fetchOne(message.uid, fields, { uid: true });
2582
2672
 
2583
- if (!messageData || !messageData.uid) {
2584
- //TODO: support partial responses
2585
- this.logger.debug({ msg: 'Partial FETCH response', code: 'partial_fetch', query: { range: message.uid, fields, opts: { uid: true } } });
2586
- return false;
2587
- }
2673
+ if (!messageData || !messageData.uid) {
2674
+ //TODO: support partial responses
2675
+ this.logger.debug({ msg: 'Partial FETCH response', code: 'partial_fetch', query: { range: message.uid, fields, opts: { uid: true } } });
2676
+ return false;
2677
+ }
2588
2678
 
2589
- // Mark as seen if requested
2590
- if (options.markAsSeen && !messageData.flags?.has('\\Seen')) {
2591
- try {
2592
- let res = await connectionClient.messageFlagsAdd(message.uid, ['\\Seen'], { uid: true });
2593
- // Mirror the flag locally so the returned message reflects it. A
2594
- // caller-provided field list can leave FLAGS out and a server can
2595
- // answer the FETCH without them - in that case there is nothing to
2596
- // mirror into, and inventing a set here would report the message as
2597
- // carrying \Seen and no other flag
2598
- if (res && messageData.flags) {
2599
- messageData.flags.add('\\Seen');
2600
- }
2601
- } catch (err) {
2602
- this.logger.debug({ msg: 'Failed to mark message as Seen', uid: message.uid, err });
2679
+ // Mark as seen if requested
2680
+ if (options.markAsSeen && !messageData.flags?.has('\\Seen')) {
2681
+ try {
2682
+ let res = await connectionClient.messageFlagsAdd(message.uid, ['\\Seen'], { uid: true });
2683
+ // Mirror the flag locally so the returned message reflects it. A
2684
+ // caller-provided field list can leave FLAGS out and a server can
2685
+ // answer the FETCH without them - in that case there is nothing to
2686
+ // mirror into, and inventing a set here would report the message as
2687
+ // carrying \Seen and no other flag
2688
+ if (res && messageData.flags) {
2689
+ messageData.flags.add('\\Seen');
2603
2690
  }
2604
- }
2605
-
2606
- messageInfo = await this.getMessageInfo(messageData, true);
2607
- } finally {
2608
- if (lock) {
2609
- lock.release();
2691
+ } catch (err) {
2692
+ this.logger.debug({ msg: 'Failed to mark message as Seen', uid: message.uid, err });
2610
2693
  }
2611
2694
  }
2612
2695
 
2613
- if (!messageInfo) {
2614
- return false;
2696
+ messageInfo = await this.getMessageInfo(messageData, true);
2697
+ } finally {
2698
+ if (lock) {
2699
+ lock.release();
2615
2700
  }
2701
+ }
2616
2702
 
2617
- // Merge decoded text content with message data (if requested)
2618
- if (options.textType && messageInfo.text && messageInfo.text.id) {
2619
- let { textParts } = await this.connection.getMessageTextPaths(messageInfo.text.id);
2620
- if (textParts && textParts.length) {
2621
- // Select which text parts to fetch
2622
- switch (options.textType) {
2623
- case 'plain':
2624
- textParts = textParts[0];
2625
- break;
2626
- case 'html':
2627
- textParts = textParts[1];
2628
- break;
2629
- default:
2630
- textParts = textParts.flatMap(entry => entry);
2631
- break;
2632
- }
2703
+ if (!messageInfo) {
2704
+ return false;
2705
+ }
2633
2706
 
2634
- if (textParts && textParts.length) {
2635
- let textContent = await this.getText(message, textParts, options, { connectionClient });
2636
- if (options.textType && options.textType !== '*') {
2637
- textContent = {
2638
- [options.textType]: textContent[options.textType] || '',
2639
- hasMore: textContent.hasMore
2640
- };
2641
- }
2642
- messageInfo.text = Object.assign(messageInfo.text, textContent);
2707
+ // Merge decoded text content with message data (if requested)
2708
+ if (options.textType && messageInfo.text && messageInfo.text.id) {
2709
+ let { textParts } = await this.connection.getMessageTextPaths(messageInfo.text.id);
2710
+ if (textParts && textParts.length) {
2711
+ // Select which text parts to fetch
2712
+ switch (options.textType) {
2713
+ case 'plain':
2714
+ textParts = textParts[0];
2715
+ break;
2716
+ case 'html':
2717
+ textParts = textParts[1];
2718
+ break;
2719
+ default:
2720
+ textParts = textParts.flatMap(entry => entry);
2721
+ break;
2722
+ }
2723
+
2724
+ if (textParts && textParts.length) {
2725
+ let textContent = await this.getText(message, textParts, options, { connectionClient });
2726
+ if (options.textType && options.textType !== '*') {
2727
+ textContent = {
2728
+ [options.textType]: textContent[options.textType] || '',
2729
+ hasMore: textContent.hasMore
2730
+ };
2643
2731
  }
2732
+ messageInfo.text = Object.assign(messageInfo.text, textContent);
2644
2733
  }
2645
2734
  }
2735
+ }
2646
2736
 
2647
- // Convert to web-safe HTML if requested
2648
- if (options.preProcessHtml && messageInfo.text && (messageInfo.text.html || messageInfo.text.plain)) {
2649
- messageInfo.text.html = await messageWebSafeHtml(messageInfo);
2650
- messageInfo.text.webSafe = true;
2651
- }
2737
+ // Convert to web-safe HTML if requested
2738
+ if (options.preProcessHtml && messageInfo.text && (messageInfo.text.html || messageInfo.text.plain)) {
2739
+ messageInfo.text.html = await messageWebSafeHtml(messageInfo);
2740
+ messageInfo.text.webSafe = true;
2741
+ }
2652
2742
 
2653
- // Embed attached images as data URIs if requested
2654
- if (options.embedAttachedImages && messageInfo.text && messageInfo.text.html && messageInfo.attachments) {
2655
- let attachmentList = new Map();
2656
- let partList = [];
2657
- let cidReferences = collectCidReferences(messageInfo.text.html);
2743
+ // Embed attached images as data URIs if requested
2744
+ if (options.embedAttachedImages && messageInfo.text && messageInfo.text.html && messageInfo.attachments) {
2745
+ let attachmentList = new Map();
2746
+ let partList = [];
2747
+ let cidReferences = collectCidReferences(messageInfo.text.html);
2658
2748
 
2659
- // Find images referenced by CID
2660
- for (let attachment of messageInfo.attachments || []) {
2661
- let contentId = attachment.contentId && attachment.contentId.replace(/^<|>$/g, '');
2662
- if (contentId && cidReferences.has(contentId)) {
2663
- attachmentList.set(contentId, { attachment, content: null });
2749
+ // Find images referenced by CID
2750
+ for (let attachment of messageInfo.attachments || []) {
2751
+ let contentId = attachment.contentId && attachment.contentId.replace(/^<|>$/g, '');
2752
+ if (contentId && cidReferences.has(contentId)) {
2753
+ attachmentList.set(contentId, { attachment, content: null });
2664
2754
 
2665
- let buf = Buffer.from(attachment.id, 'base64url');
2666
- let part = buf.subarray(8).toString();
2755
+ let buf = Buffer.from(attachment.id, 'base64url');
2756
+ let part = buf.subarray(8).toString();
2667
2757
 
2668
- Object.defineProperty(attachment, 'part', {
2669
- value: part,
2670
- enumerable: false
2671
- });
2758
+ Object.defineProperty(attachment, 'part', {
2759
+ value: part,
2760
+ enumerable: false
2761
+ });
2672
2762
 
2673
- if (!partList.includes(part)) {
2674
- partList.push(part);
2675
- }
2763
+ if (!partList.includes(part)) {
2764
+ partList.push(part);
2676
2765
  }
2677
2766
  }
2767
+ }
2678
2768
 
2679
- if (partList.length) {
2680
- let lock;
2681
- try {
2682
- // The lock taken for the FETCH above is released by now. Without one
2683
- // another task can select a different mailbox on this connection first,
2684
- // and the UID would then address whatever message carries it there
2685
- if (!options.skipLock) {
2686
- lock = await this.getMailboxLock(connectionClient, { description: `Download inline images: ${message.uid}` });
2687
- }
2769
+ if (partList.length) {
2770
+ let lock;
2771
+ try {
2772
+ // The lock taken for the FETCH above is released by now. Without one
2773
+ // another task can select a different mailbox on this connection first,
2774
+ // and the UID would then address whatever message carries it there
2775
+ if (!options.skipLock) {
2776
+ lock = await this.getMailboxLock(connectionClient, { description: `Download inline images: ${message.uid}` });
2777
+ }
2688
2778
 
2689
- // Download all referenced images in batch
2690
- let contentParts = await connectionClient.downloadMany(messageInfo.uid, partList, {
2691
- uid: true
2692
- });
2779
+ // Download all referenced images in batch
2780
+ let contentParts = await connectionClient.downloadMany(messageInfo.uid, partList, {
2781
+ uid: true
2782
+ });
2693
2783
 
2694
- if (contentParts) {
2695
- for (let { attachment } of attachmentList.values()) {
2696
- if (attachment.part && contentParts[attachment.part] && contentParts[attachment.part].content) {
2697
- Object.defineProperty(attachment, 'content', {
2698
- value: contentParts[attachment.part].content,
2699
- enumerable: false
2700
- });
2701
- }
2784
+ if (contentParts) {
2785
+ for (let { attachment } of attachmentList.values()) {
2786
+ if (attachment.part && contentParts[attachment.part] && contentParts[attachment.part].content) {
2787
+ Object.defineProperty(attachment, 'content', {
2788
+ value: contentParts[attachment.part].content,
2789
+ enumerable: false
2790
+ });
2702
2791
  }
2792
+ }
2703
2793
 
2704
- // Replace CID references with data URIs
2705
- messageInfo.text.html = messageInfo.text.html.replace(cidReferenceRegex(), (fullMatch, cidMatch) => {
2706
- if (attachmentList.has(cidMatch)) {
2707
- let { attachment } = attachmentList.get(cidMatch);
2708
- if (attachment.content) {
2709
- return `data:${attachment.contentType || 'application/octet-stream'};base64,${attachment.content.toString('base64')}`;
2710
- }
2794
+ // Replace CID references with data URIs
2795
+ messageInfo.text.html = messageInfo.text.html.replace(cidReferenceRegex(), (fullMatch, cidMatch) => {
2796
+ if (attachmentList.has(cidMatch)) {
2797
+ let { attachment } = attachmentList.get(cidMatch);
2798
+ if (attachment.content) {
2799
+ return `data:${attachment.contentType || 'application/octet-stream'};base64,${attachment.content.toString('base64')}`;
2711
2800
  }
2712
- return fullMatch;
2713
- });
2714
- }
2715
- } catch (err) {
2716
- this.logger.error({ msg: 'Failed to download attachments', uid: messageInfo.uid, partList, err });
2717
- } finally {
2718
- if (lock) {
2719
- lock.release();
2720
- }
2801
+ }
2802
+ return fullMatch;
2803
+ });
2804
+ }
2805
+ } catch (err) {
2806
+ this.logger.error({ msg: 'Failed to download attachments', uid: messageInfo.uid, partList, err });
2807
+ } finally {
2808
+ if (lock) {
2809
+ lock.release();
2721
2810
  }
2722
2811
  }
2723
2812
  }
2813
+ }
2724
2814
 
2725
- // Add mailbox special use information
2726
- if (this.listingEntry.specialUse) {
2727
- messageInfo.specialUse = this.listingEntry.specialUse;
2728
- }
2729
-
2730
- // Determine message's special use folder
2731
- for (let specialUseTag of ['\\Junk', '\\Sent', '\\Trash', '\\Inbox', '\\Drafts']) {
2732
- if (this.listingEntry.specialUse === specialUseTag || (messageInfo.labels && messageInfo.labels.includes(specialUseTag))) {
2733
- messageInfo.messageSpecialUse = specialUseTag;
2734
- break;
2735
- }
2736
- }
2815
+ // Add mailbox special use information
2816
+ if (this.listingEntry.specialUse) {
2817
+ messageInfo.specialUse = this.listingEntry.specialUse;
2818
+ }
2737
2819
 
2738
- return messageInfo;
2739
- } finally {
2740
- if (!options.skipLock) {
2741
- this.connection.onTaskCompleted(connectionClient);
2820
+ // Determine message's special use folder
2821
+ for (let specialUseTag of ['\\Junk', '\\Sent', '\\Trash', '\\Inbox', '\\Drafts']) {
2822
+ if (this.listingEntry.specialUse === specialUseTag || (messageInfo.labels && messageInfo.labels.includes(specialUseTag))) {
2823
+ messageInfo.messageSpecialUse = specialUseTag;
2824
+ break;
2742
2825
  }
2743
2826
  }
2827
+
2828
+ return messageInfo;
2744
2829
  }
2745
2830
 
2746
2831
  /**
@@ -2817,7 +2902,6 @@ class Mailbox {
2817
2902
  return result;
2818
2903
  } finally {
2819
2904
  lock.release();
2820
- this.connection.onTaskCompleted(connectionClient);
2821
2905
  }
2822
2906
  }
2823
2907
 
@@ -2895,7 +2979,6 @@ class Mailbox {
2895
2979
  return result;
2896
2980
  } finally {
2897
2981
  lock.release();
2898
- this.connection.onTaskCompleted(connectionClient);
2899
2982
  }
2900
2983
  }
2901
2984
 
@@ -2934,7 +3017,6 @@ class Mailbox {
2934
3017
  return result;
2935
3018
  } finally {
2936
3019
  lock.release();
2937
- this.connection.onTaskCompleted(connectionClient);
2938
3020
  }
2939
3021
  }
2940
3022
 
@@ -2973,7 +3055,6 @@ class Mailbox {
2973
3055
  return result;
2974
3056
  } finally {
2975
3057
  lock.release();
2976
- this.connection.onTaskCompleted(connectionClient);
2977
3058
  }
2978
3059
  }
2979
3060
 
@@ -3000,7 +3081,7 @@ class Mailbox {
3000
3081
  // Move to trash
3001
3082
  // Find Trash folder path
3002
3083
  let trashMailbox = await this.connection.getSpecialUseMailbox('\\Trash');
3003
- if (!trashMailbox || normalizePath(trashMailbox.path) === normalizePath(this.path)) {
3084
+ if (!trashMailbox || samePath(trashMailbox.path, this.path)) {
3004
3085
  // No Trash found or already in trash - delete permanently
3005
3086
  result.deleted = await connectionClient.messageDelete(message.uid, { uid: true });
3006
3087
  } else {
@@ -3021,7 +3102,6 @@ class Mailbox {
3021
3102
  return result;
3022
3103
  } finally {
3023
3104
  lock.release();
3024
- this.connection.onTaskCompleted(connectionClient);
3025
3105
  }
3026
3106
  }
3027
3107
 
@@ -3048,7 +3128,7 @@ class Mailbox {
3048
3128
  // Move to trash
3049
3129
  // Find Trash folder path
3050
3130
  let trashMailbox = await this.connection.getSpecialUseMailbox('\\Trash');
3051
- if (!trashMailbox || normalizePath(trashMailbox.path) === normalizePath(this.path)) {
3131
+ if (!trashMailbox || samePath(trashMailbox.path, this.path)) {
3052
3132
  // No Trash found or already in trash - delete permanently
3053
3133
  result.deleted = await connectionClient.messageDelete(search, { uid: true });
3054
3134
  } else {
@@ -3073,7 +3153,6 @@ class Mailbox {
3073
3153
  return result;
3074
3154
  } finally {
3075
3155
  lock.release();
3076
- this.connection.onTaskCompleted(connectionClient);
3077
3156
  }
3078
3157
  }
3079
3158
 
@@ -3235,7 +3314,6 @@ class Mailbox {
3235
3314
  };
3236
3315
  } finally {
3237
3316
  lock.release();
3238
- this.connection.onTaskCompleted(connectionClient);
3239
3317
  }
3240
3318
  }
3241
3319
 
@@ -3330,7 +3408,7 @@ class Mailbox {
3330
3408
  */
3331
3409
  mightBeAComplaint(messageInfo) {
3332
3410
  // Only check inbox messages
3333
- if (this.path !== 'INBOX' && !(this.isAllMail && messageInfo.labels && messageInfo.labels.includes('\\Inbox'))) {
3411
+ if (!samePath(this.path, 'INBOX') && !(this.isAllMail && messageInfo.labels && messageInfo.labels.includes('\\Inbox'))) {
3334
3412
  return false;
3335
3413
  }
3336
3414
 
@@ -3378,7 +3456,7 @@ class Mailbox {
3378
3456
  */
3379
3457
  mightBeDSNResponse(messageInfo) {
3380
3458
  // Only check inbox messages
3381
- if (this.path !== 'INBOX' && !(this.isAllMail && messageInfo.labels && messageInfo.labels.includes('\\Inbox'))) {
3459
+ if (!samePath(this.path, 'INBOX') && !(this.isAllMail && messageInfo.labels && messageInfo.labels.includes('\\Inbox'))) {
3382
3460
  return false;
3383
3461
  }
3384
3462