emailengine-app 2.79.8 → 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 (182) hide show
  1. package/.github/dependabot.yml +22 -0
  2. package/.github/workflows/test.yml +39 -0
  3. package/.release-please-manifest.json +1 -1
  4. package/CHANGELOG.md +69 -0
  5. package/DOCKER_DEPLOYMENT.md +6 -7
  6. package/Dockerfile +35 -11
  7. package/config/default.toml +7 -2
  8. package/copy-static-files.sh +23 -5
  9. package/data/google-crawlers.json +1 -1
  10. package/encrypt.js +43 -0
  11. package/lib/account/account-state.js +62 -0
  12. package/lib/account.js +60 -3
  13. package/lib/api-routes/account-routes.js +20 -0
  14. package/lib/api-routes/bull-board-routes.js +3 -2
  15. package/lib/api-routes/index.js +1 -1
  16. package/lib/api-routes/route-helpers.js +8 -0
  17. package/lib/api-routes/settings-routes.js +17 -2
  18. package/lib/auth-token.js +73 -2
  19. package/lib/autodetect-imap-settings.js +379 -69
  20. package/lib/cert-handler.js +62 -0
  21. package/lib/consts.js +58 -7
  22. package/lib/db.js +12 -0
  23. package/lib/egress-fetch.js +145 -0
  24. package/lib/email-client/base-client.js +234 -66
  25. package/lib/email-client/credential-errors.js +118 -0
  26. package/lib/email-client/gmail/gmail-api.js +2 -1
  27. package/lib/email-client/gmail-client.js +70 -64
  28. package/lib/email-client/imap/connection-errors.js +52 -0
  29. package/lib/email-client/imap/listing-diff.js +47 -6
  30. package/lib/email-client/imap/mailbox.js +457 -379
  31. package/lib/email-client/imap/subconnection.js +15 -11
  32. package/lib/email-client/imap/sync-operations.js +46 -59
  33. package/lib/email-client/imap-client.js +136 -95
  34. package/lib/email-client/message-builder.js +11 -11
  35. package/lib/email-client/outlook/graph-api.js +2 -1
  36. package/lib/email-client/outlook-client.js +219 -106
  37. package/lib/export.js +35 -2
  38. package/lib/handlebars-helpers.js +129 -0
  39. package/lib/imap-proxy-auth.js +96 -21
  40. package/lib/imapproxy/imap-core/README.md +1 -0
  41. package/lib/imapproxy/imap-core/lib/tls-options.js +5 -46
  42. package/lib/imapproxy/imap-server.js +56 -66
  43. package/lib/lua/h-del-if-equals.lua +39 -0
  44. package/lib/lua/h-set-if-equals.lua +39 -0
  45. package/lib/openapi/index.js +3 -0
  46. package/lib/outbox.js +28 -3
  47. package/lib/rate-limit.js +23 -4
  48. package/lib/routes-ui.js +4 -34
  49. package/lib/schemas.js +42 -3
  50. package/lib/security-headers.js +411 -0
  51. package/lib/sentry.js +36 -4
  52. package/lib/smtp-auth.js +86 -7
  53. package/lib/tls/context.js +376 -0
  54. package/lib/tls/der.js +223 -0
  55. package/lib/tls/provision.js +555 -0
  56. package/lib/tls/self-signed.js +282 -0
  57. package/lib/tls/status.js +431 -0
  58. package/lib/tls/store.js +666 -0
  59. package/lib/tools.js +337 -147
  60. package/lib/ui-routes/account-routes.js +47 -33
  61. package/lib/ui-routes/admin-config-routes.js +22 -1
  62. package/lib/ui-routes/auth-routes.js +16 -1
  63. package/lib/ui-routes/export-routes.js +4 -0
  64. package/lib/ui-routes/internals-routes.js +3 -5
  65. package/lib/ui-routes/mcp-consent-routes.js +7 -0
  66. package/lib/ui-routes/network-config-routes.js +58 -48
  67. package/lib/ui-routes/route-helpers.js +24 -8
  68. package/lib/ui-routes/smtp-test-routes.js +7 -0
  69. package/lib/ui-routes/tls-config-routes.js +581 -0
  70. package/lib/utils/mailbox-path.js +51 -0
  71. package/lib/utils/severity.js +31 -0
  72. package/lib/webhook-egress.js +5 -0
  73. package/package.json +21 -24
  74. package/sbom.json +1 -1
  75. package/server.js +53 -36
  76. package/static/css/flyonui.css +1 -1
  77. package/static/css/src/app.tailwind.css +11 -0
  78. package/static/js/ace/css/ace.css +1462 -0
  79. package/static/js/ace/css/kuroir-1.png +0 -0
  80. package/static/js/ace/css/kuroir-2.png +0 -0
  81. package/static/js/ace/css/main-1.png +0 -0
  82. package/static/js/ace/css/main-10.svg +4 -0
  83. package/static/js/ace/css/main-11.svg +5 -0
  84. package/static/js/ace/css/main-12.svg +4 -0
  85. package/static/js/ace/css/main-13.png +0 -0
  86. package/static/js/ace/css/main-14.png +0 -0
  87. package/static/js/ace/css/main-15.png +0 -0
  88. package/static/js/ace/css/main-16.png +0 -0
  89. package/static/js/ace/css/main-17.png +0 -0
  90. package/static/js/ace/css/main-18.png +0 -0
  91. package/static/js/ace/css/main-19.png +0 -0
  92. package/static/js/ace/css/main-2.png +0 -0
  93. package/static/js/ace/css/main-20.png +0 -0
  94. package/static/js/ace/css/main-21.png +0 -0
  95. package/static/js/ace/css/main-22.png +0 -0
  96. package/static/js/ace/css/main-23.png +0 -0
  97. package/static/js/ace/css/main-24.png +0 -0
  98. package/static/js/ace/css/main-25.svg +1 -0
  99. package/static/js/ace/css/main-26.png +0 -0
  100. package/static/js/ace/css/main-3.png +0 -0
  101. package/static/js/ace/css/main-4.png +0 -0
  102. package/static/js/ace/css/main-5.svg +7 -0
  103. package/static/js/ace/css/main-6.svg +9 -0
  104. package/static/js/ace/css/main-7.svg +7 -0
  105. package/static/js/ace/css/main-8.svg +9 -0
  106. package/static/js/ace/css/main-9.svg +6 -0
  107. package/static/js/ace/css/theme/kuroir.css +78 -0
  108. package/static/js/ace/css/theme/tomorrow_night.css +128 -0
  109. package/static/js/ace/css/theme/tomorrow_night_eighties.css +128 -0
  110. package/static/js/ace/css/theme/xcode.css +106 -0
  111. package/static/js/ace/css/tomorrow_night-1.png +0 -0
  112. package/static/js/ace/css/tomorrow_night-2.png +0 -0
  113. package/static/js/ace/css/tomorrow_night_eighties-1.png +0 -0
  114. package/static/js/ace/css/tomorrow_night_eighties-2.png +0 -0
  115. package/static/js/ace/css/xcode-1.png +0 -0
  116. package/static/js/ace/css/xcode-2.png +0 -0
  117. package/static/js/app.js +34 -0
  118. package/static/js/ee-client.js +256 -102
  119. package/static/js/public.js +13 -2
  120. package/static/js/ui.js +40 -25
  121. package/static/licenses.html +393 -1282
  122. package/static/vendor/simplewebauthn/browser.min.js +2 -2
  123. package/translations/messages.pot +203 -157
  124. package/views/account/login-redirect.hbs +22 -0
  125. package/views/accounts/account.hbs +15 -37
  126. package/views/accounts/browse.hbs +3 -1
  127. package/views/accounts/edit.hbs +1 -1
  128. package/views/accounts/register/imap-server.hbs +1 -1
  129. package/views/config/ai.hbs +1 -1
  130. package/views/config/branding.hbs +2 -2
  131. package/views/config/document-store/chat.hbs +1 -1
  132. package/views/config/document-store/index.hbs +1 -1
  133. package/views/config/imap-proxy.hbs +1 -4
  134. package/views/config/license.hbs +1 -1
  135. package/views/config/mcp.hbs +1 -1
  136. package/views/config/network.hbs +14 -16
  137. package/views/config/oauth/app.hbs +2 -2
  138. package/views/config/service.hbs +1 -1
  139. package/views/config/smtp.hbs +1 -4
  140. package/views/config/tls-upload.hbs +81 -0
  141. package/views/config/tls.hbs +492 -0
  142. package/views/config/webhooks.hbs +2 -2
  143. package/views/error.hbs +4 -2
  144. package/views/internals/index.hbs +1 -1
  145. package/views/layout/app.hbs +3 -11
  146. package/views/mcp/authorize.hbs +1 -1
  147. package/views/partials/ace_assets.hbs +13 -0
  148. package/views/partials/add_account_modal.hbs +1 -1
  149. package/views/partials/address_list.hbs +4 -4
  150. package/views/partials/filter_editor_js.hbs +2 -2
  151. package/views/partials/gateway_js.hbs +1 -1
  152. package/views/partials/oauth_form.hbs +1 -1
  153. package/views/partials/public_theme_init.hbs +1 -1
  154. package/views/partials/side_menu.hbs +1 -0
  155. package/views/partials/template_form.hbs +2 -2
  156. package/views/partials/test_send.hbs +7 -4
  157. package/views/partials/theme_init.hbs +1 -1
  158. package/views/partials/tls_security_card.hbs +25 -53
  159. package/views/partials/ui/alert-banner.hbs +3 -2
  160. package/views/partials/ui/badge.hbs +6 -2
  161. package/views/partials/ui/btn.hbs +5 -2
  162. package/views/partials/ui/details.hbs +2 -2
  163. package/views/partials/webhooks_editor_functions.hbs +1 -1
  164. package/views/reference/redirect.hbs +1 -1
  165. package/views/templates/template.hbs +2 -2
  166. package/views/tokens/new.hbs +1 -1
  167. package/views/unsubscribe.hbs +1 -1
  168. package/views/webhooks/webhook.hbs +2 -2
  169. package/workers/api.js +131 -242
  170. package/workers/export.js +1 -5
  171. package/workers/imap-proxy.js +4 -1
  172. package/workers/imap.js +1 -3
  173. package/workers/smtp.js +59 -83
  174. package/workers/submit.js +6 -12
  175. package/workers/webhooks.js +6 -17
  176. package/static/front/EmailEngine_logo_horiz.png +0 -0
  177. package/static/front/EmailEngine_logo_vert.png +0 -0
  178. package/static/front/index.html +0 -57
  179. package/static/front/logo.png +0 -0
  180. package/static/vendor/handlebars/handlebars.min-v4.7.9.js +0 -29
  181. package/views/partials/tls_security_js.hbs +0 -64
  182. package/views/partials/tls_security_modal.hbs +0 -22
@@ -13,13 +13,14 @@ const { BaseClient } = require('./base-client');
13
13
  const { oauth2Apps } = require('../oauth2-apps');
14
14
 
15
15
  const { Subconnection } = require('./imap/subconnection');
16
- const { decodeStoredListing, diffMailboxListing, buildStoredListingObject } = require('./imap/listing-diff');
16
+ const { decodeStoredListing, diffMailboxListing, buildStoredListingObject, matchesListingEntry, configuredPathIndex } = require('./imap/listing-diff');
17
+ const { samePath } = require('../utils/mailbox-path');
17
18
  const { detachImapClient } = require('./imap/detach-client');
19
+ const { connectionNotAvailableError, connectionUnavailableError } = require('./imap/connection-errors');
18
20
  const { ReconnectBackoff } = require('./reconnect-backoff');
19
21
 
20
22
  const {
21
23
  normalizePath,
22
- resolveCredentials,
23
24
  useAuthServerForConnection,
24
25
  emitChangeEvent,
25
26
  getByteSize,
@@ -39,7 +40,6 @@ const ENSURE_MAIN_TTL = 5 * 1000;
39
40
 
40
41
  const {
41
42
  AUTH_ERROR_NOTIFY,
42
- AUTH_SUCCESS_NOTIFY,
43
43
  CONNECT_ERROR_NOTIFY,
44
44
  CONNECTION_CLOSING_CODES,
45
45
  DEFAULT_DOWNLOAD_CHUNK_SIZE,
@@ -297,10 +297,7 @@ class IMAPClient extends BaseClient {
297
297
  if (!noPool && (!syncing || !allowSecondary)) {
298
298
  // Return the primary connection for most operations
299
299
  if (!this.imapClient) {
300
- let err = new Error('IMAP connection not available');
301
- err.code = 'IMAPConnectionClosing';
302
- err.statusCode = 503;
303
- throw err;
300
+ throw connectionNotAvailableError();
304
301
  }
305
302
  return this.imapClient;
306
303
  }
@@ -320,10 +317,7 @@ class IMAPClient extends BaseClient {
320
317
 
321
318
  // Fall back to primary connection
322
319
  if (!this.imapClient) {
323
- let err = new Error('IMAP connection not available');
324
- err.code = 'IMAPConnectionClosing';
325
- err.statusCode = 503;
326
- throw err;
320
+ throw connectionNotAvailableError();
327
321
  }
328
322
  return this.imapClient;
329
323
  }
@@ -455,7 +449,7 @@ class IMAPClient extends BaseClient {
455
449
  async ensureMainMailbox() {
456
450
  let mainPath = this.main ? this.main.path : 'INBOX';
457
451
 
458
- // start waiting for changes (Mailbox.select() skips the SELECT when it is already open)
452
+ // start waiting for changes (Mailbox.select() returns right away when it is already open)
459
453
  await this.select(mainPath);
460
454
  }
461
455
 
@@ -611,7 +605,15 @@ class IMAPClient extends BaseClient {
611
605
  async getMessageTextPaths(textId) {
612
606
  let buf = Buffer.from(textId, 'base64url');
613
607
  let id = buf.subarray(0, 8);
614
- let textParts = msgpack.decode(buf.subarray(8));
608
+
609
+ // The tail is msgpack, and the decoder throws outright on a truncated or absent one - an
610
+ // id one byte short of its parts list, or any foreign value, reached the API as a 500
611
+ let textParts;
612
+ try {
613
+ textParts = msgpack.decode(buf.subarray(8));
614
+ } catch (err) {
615
+ throw this.invalidIdError();
616
+ }
615
617
 
616
618
  let message = await this.unpackUid(id);
617
619
  if (!message) {
@@ -710,7 +712,7 @@ class IMAPClient extends BaseClient {
710
712
 
711
713
  // Flags entries of `listing` as isNew as a side effect - that one-shot flag is what makes
712
714
  // processListing() emit mailboxNew, so it has to ride along on the returned listing.
713
- let { hasChanges, deletedEntries } = diffMailboxListing(listing, storedListing);
715
+ let { hasChanges, hasChangesBesidesNew, deletedEntries } = diffMailboxListing(listing, storedListing);
714
716
 
715
717
  if (corruptPaths.length) {
716
718
  // An unusable stored value is not part of the comparison at all, so it can not be
@@ -726,6 +728,7 @@ class IMAPClient extends BaseClient {
726
728
  logger.notifyError(corruptErr, { user: this.account, meta: { paths: corruptPaths.join(', ') } });
727
729
  }
728
730
  hasChanges = true;
731
+ hasChangesBesidesNew = true;
729
732
  }
730
733
 
731
734
  for (let entry of deletedEntries) {
@@ -733,12 +736,19 @@ class IMAPClient extends BaseClient {
733
736
  await this.clearMailboxEntry(entry);
734
737
  }
735
738
 
739
+ // A folder that appeared is only recorded by a pass that can announce it: processListing()
740
+ // registers nothing without a primary connection, which a listing read over a pooled
741
+ // secondary is allowed to run without, and the stored listing is what the next pass diffs
742
+ // against (see .claude/rules/workers.md). Deletions are not deferred - they are complete on
743
+ // their own - so a pass that found nothing but folders it must defer has nothing to write.
744
+ const deferNewEntries = !this.imapClient;
745
+
736
746
  // on changes store updated listing
737
- if (hasChanges) {
747
+ if (hasChanges && (!deferNewEntries || hasChangesBesidesNew)) {
738
748
  // Atomic update of the mailbox listing. HMSET refuses an empty hash, and that error
739
749
  // aborts the entire MULTI including the DEL, so the write is only queued when there
740
750
  // is something to write.
741
- let listingObject = buildStoredListingObject(listing);
751
+ let listingObject = buildStoredListingObject(deferNewEntries ? listing.filter(entry => !entry.isNew) : listing);
742
752
  let updateListing = this.redis.multi().del(this.getMailboxListKey());
743
753
  if (Object.keys(listingObject).length) {
744
754
  updateListing = updateListing.hmset(this.getMailboxListKey(), listingObject);
@@ -749,19 +759,61 @@ class IMAPClient extends BaseClient {
749
759
  return listing;
750
760
  }
751
761
 
762
+ /**
763
+ * Registers a Mailbox instance for a listing entry, replacing whatever instance the
764
+ * path was tracked by. The one-shot `isNew` flag rides on the instance being replaced
765
+ * until an open of the folder succeeds, so it is carried over: the listing a
766
+ * reconnect registers from no longer reports the folder as new (it has been in the
767
+ * stored listing since the pass that discovered it), and a first sync interrupted by a
768
+ * disconnect - which can take minutes on a large folder - would otherwise lose its
769
+ * mailboxNew for good.
770
+ * @param {Object} entry - Mailbox entry from the server listing
771
+ * @returns {Mailbox} The registered mailbox instance
772
+ */
773
+ registerMailbox(entry) {
774
+ const normalizedPath = normalizePath(entry.path);
775
+
776
+ let previous = this.mailboxes.get(normalizedPath);
777
+ if (previous && previous.listingEntry && previous.listingEntry.isNew) {
778
+ entry.isNew = true;
779
+ }
780
+
781
+ let mailbox = new Mailbox(this, entry);
782
+ this.mailboxes.set(normalizedPath, mailbox);
783
+ return mailbox;
784
+ }
785
+
752
786
  /**
753
787
  * Registers Mailbox instances for previously unseen entries in a mailbox
754
788
  * listing and runs the initial sync for them. Entries carrying the one-shot
755
789
  * `isNew` flag from getCurrentListing() become Mailbox instances whose first
756
- * sync emits the mailboxNew notification, so every listing refresh done to
757
- * process folder changes must route its result through here (callers that
758
- * only read the listing, like listMailboxes(), do not).
790
+ * sync emits the mailboxNew notification, so every listing refresh must route
791
+ * its result through here - callers that only read the listing hand it over
792
+ * through processNewListingEntries().
759
793
  * Intentionally not guarded by `refreshingList`: it must also run when called
760
794
  * from inside refreshFolderList()'s own sync loop.
761
795
  * @param {Array} listing - Listing returned by getCurrentListing()
762
796
  * @returns {Set} Set of newly created mailbox instances that were synced
763
797
  */
764
798
  async processListing(listing) {
799
+ let syncNeeded = new Set();
800
+
801
+ // Registration belongs to a connected account. A listing can be read over a pooled
802
+ // secondary connection while the primary is down (listMailboxes() allows that), and
803
+ // the provider flags this method filters on - isGmail above all - are only decided
804
+ // by connect(), which registers the whole listing itself once it is done
805
+ if (!this.imapClient) {
806
+ await this.releaseUnregisteredEntries(listing);
807
+ return syncNeeded;
808
+ }
809
+
810
+ // Every entry is tracked already, so the loop below would register nothing. Answered
811
+ // before the account load because this runs on every resync pass and after every
812
+ // folder-changing operation, and a listing that holds no unseen folder is the norm
813
+ if (!(listing || []).some(entry => !this.mailboxes.has(normalizePath(entry.path)))) {
814
+ return syncNeeded;
815
+ }
816
+
765
817
  let accountData = await this.accountObject.loadAccountData();
766
818
 
767
819
  // Get configured paths to monitor (default to all)
@@ -770,7 +822,6 @@ class IMAPClient extends BaseClient {
770
822
  accountPaths.push('*');
771
823
  }
772
824
 
773
- let syncNeeded = new Set();
774
825
  for (let entry of listing || []) {
775
826
  if (
776
827
  // previously unseen
@@ -778,7 +829,7 @@ class IMAPClient extends BaseClient {
778
829
  ) {
779
830
  // Apply filtering rules based on account configuration
780
831
  if (!accountPaths.includes('*')) {
781
- if (!accountPaths.includes(entry.path) && !accountPaths.includes(entry.specialUse)) {
832
+ if (configuredPathIndex(accountPaths, entry) < 0) {
782
833
  // ignore changes
783
834
  entry.syncDisabled = true;
784
835
  }
@@ -788,8 +839,7 @@ class IMAPClient extends BaseClient {
788
839
  entry.syncDisabled = true;
789
840
  }
790
841
 
791
- let mailbox = new Mailbox(this, entry);
792
- this.mailboxes.set(normalizePath(entry.path), mailbox);
842
+ let mailbox = this.registerMailbox(entry);
793
843
  syncNeeded.add(mailbox);
794
844
  }
795
845
  }
@@ -820,6 +870,44 @@ class IMAPClient extends BaseClient {
820
870
  return await this.processListing(listing);
821
871
  }
822
872
 
873
+ /**
874
+ * Hands a freshly read listing to processListing() without waiting for it, so a caller
875
+ * that only wanted to read the listing does not drop the one-shot `isNew` flag riding
876
+ * on it (see getCurrentListing()). The initial sync of a new folder can take minutes,
877
+ * which is why the caller does not wait
878
+ * @param {Array} listing - Listing returned by getCurrentListing()
879
+ */
880
+ processNewListingEntries(listing) {
881
+ this.processListing(listing).catch(err => {
882
+ this.logger.error({ msg: 'Failed to process listing', err });
883
+ });
884
+ }
885
+
886
+ /**
887
+ * Takes the folders a listing found back out of the stored listing when the pass that
888
+ * read them could not register them.
889
+ *
890
+ * getCurrentListing() leaves the `isNew` entries out of what it writes when the primary
891
+ * is down, but it decides that from the connection it saw before the write, and the
892
+ * primary can go away between that write and processListing(). The flag itself is not
893
+ * persisted, so a folder written in that window is absorbed: the next pass diffs it as
894
+ * known and its mailboxNew is never sent. Removing the entry is what the deferring write
895
+ * would have done, and the next pass finds the folder new again.
896
+ * @param {Array} listing - Listing returned by getCurrentListing()
897
+ */
898
+ async releaseUnregisteredEntries(listing) {
899
+ const deferred = (listing || []).filter(entry => entry.isNew).map(entry => normalizePath(entry.path));
900
+ if (!deferred.length) {
901
+ return;
902
+ }
903
+
904
+ try {
905
+ await this.redis.hdel(this.getMailboxListKey(), ...deferred);
906
+ } catch (err) {
907
+ this.logger.error({ msg: 'Failed to defer the folders a disconnected pass found', paths: deferred, err });
908
+ }
909
+ }
910
+
823
911
  /**
824
912
  * Refreshes the folder list and creates Mailbox instances for new folders
825
913
  * @returns {Set} Set of newly created mailbox instances that need syncing
@@ -897,11 +985,11 @@ class IMAPClient extends BaseClient {
897
985
  for (let entry of listing) {
898
986
  if (!accountPaths.includes('*')) {
899
987
  // Limited path monitoring - only specific folders
900
- if (!accountPaths.includes(entry.path) && !accountPaths.includes(entry.specialUse)) {
988
+ let index = configuredPathIndex(accountPaths, entry);
989
+ if (index < 0) {
901
990
  entry.syncDisabled = true;
902
991
  } else {
903
992
  // insert to stored list with the sorting index
904
- let index = accountPaths.indexOf(entry.path) >= 0 ? accountPaths.indexOf(entry.path) : accountPaths.indexOf(entry.specialUse);
905
993
  mainList.push({ index, entry });
906
994
  }
907
995
  } else {
@@ -918,8 +1006,7 @@ class IMAPClient extends BaseClient {
918
1006
  }
919
1007
  }
920
1008
 
921
- let mailbox = new Mailbox(this, entry);
922
- this.mailboxes.set(normalizePath(entry.path), mailbox);
1009
+ this.registerMailbox(entry);
923
1010
  }
924
1011
 
925
1012
  if (mainList.length) {
@@ -991,7 +1078,7 @@ class IMAPClient extends BaseClient {
991
1078
  return false;
992
1079
  }
993
1080
  for (let mailbox of this.mailboxes.values()) {
994
- if (mailbox.listingEntry && mailbox.listingEntry.specialUse === path) {
1081
+ if (mailbox.listingEntry && matchesListingEntry(path, mailbox.listingEntry)) {
995
1082
  return true;
996
1083
  }
997
1084
  }
@@ -1261,6 +1348,11 @@ class IMAPClient extends BaseClient {
1261
1348
  return;
1262
1349
  }
1263
1350
  if (!synced || !synced.has(mailbox)) {
1351
+ // The pass ends with its own select of the main mailbox. A folder synced
1352
+ // earlier in the walk reported a task when its lock was released, and a
1353
+ // stretch of STATUS-only folders can outlast that timer - clear it so the
1354
+ // main mailbox is not selected mid-walk and again at the end
1355
+ clearTimeout(this.completedTimer);
1264
1356
  await mailbox.sync();
1265
1357
  }
1266
1358
  }
@@ -1301,8 +1393,9 @@ class IMAPClient extends BaseClient {
1301
1393
  });
1302
1394
 
1303
1395
  await this.redis.hSetExists(this.getAccountKey(), 'imapServerInfo', JSON.stringify(serverInfo));
1304
- // Clear error state on successful connection
1305
- await this.redis.hdel(this.getAccountKey(), 'lastErrorState', 'lastError:errorCount', 'lastError:first');
1396
+
1397
+ // NB! the stored error state is cleared by the login in start(), not here - see
1398
+ // BaseClient.notifyAuthenticationSuccess()
1306
1399
  await emitChangeEvent(this.logger, this.account, 'state', this.state);
1307
1400
 
1308
1401
  // Revive subconnections that disabled themselves while their monitored
@@ -1410,21 +1503,7 @@ class IMAPClient extends BaseClient {
1410
1503
 
1411
1504
  // If authentication server is set then it overrides authentication data
1412
1505
  if (await useAuthServerForConnection(imapConnectionConfig, ctx.logger, { account: this.account, target: 'imap' })) {
1413
- try {
1414
- imapConnectionConfig.auth = await resolveCredentials(this.account, 'imap');
1415
- } catch (err) {
1416
- err.authenticationFailed = true;
1417
- await ctx.notify(false, AUTH_ERROR_NOTIFY, {
1418
- response: err.message,
1419
- serverResponseCode: 'HTTPRequestError'
1420
- });
1421
- ctx.logger.error({
1422
- msg: 'Failed to resolve credentials from authentication server',
1423
- err
1424
- });
1425
- ctx.state = AUTH_ERROR_NOTIFY;
1426
- throw err;
1427
- }
1506
+ imapConnectionConfig.auth = await this.resolveAuthServerCredentials('imap', ctx);
1428
1507
  }
1429
1508
 
1430
1509
  // Configure TLS settings
@@ -1763,38 +1842,8 @@ class IMAPClient extends BaseClient {
1763
1842
  return;
1764
1843
  }
1765
1844
 
1766
- // Check if this is the first successful connection
1767
- let prevConnectedCount = await this.redis.hget(this.getAccountKey(), `state:count:connected`);
1768
- let isFirstSuccessfulConnection = prevConnectedCount === '0'; // string zero means the account has been initialized but not yet connected
1769
-
1770
- let isInitial = !!isFirstSuccessfulConnection;
1771
-
1772
- if (!isFirstSuccessfulConnection) {
1773
- // check if the connection was previously in an errored state
1774
- let prevLastErrorState = await this.redis.hget(this.getAccountKey(), 'lastErrorState');
1775
- if (prevLastErrorState) {
1776
- try {
1777
- prevLastErrorState = JSON.parse(prevLastErrorState);
1778
- } catch (err) {
1779
- // ignore
1780
- }
1781
- }
1782
-
1783
- if (prevLastErrorState && typeof prevLastErrorState === 'object' && Object.keys(prevLastErrorState).length) {
1784
- // was previously errored
1785
- isFirstSuccessfulConnection = true;
1786
- }
1787
- }
1788
-
1789
- // Send appropriate notifications based on connection history
1790
- if (isFirstSuccessfulConnection) {
1791
- this.logger.info({ msg: 'Successful login without a previous active session', account: this.account, isInitial, prevActive: false });
1792
- await this.notify(false, AUTH_SUCCESS_NOTIFY, {
1793
- user: imapConfig.auth.user
1794
- });
1795
- } else {
1796
- this.logger.info({ msg: 'Successful login with a previous active session', account: this.account, isInitial, prevActive: true });
1797
- }
1845
+ // Announces the login and clears what the previous attempt left behind
1846
+ await this.notifyAuthenticationSuccess(imapConfig.auth.user);
1798
1847
 
1799
1848
  // Set up subconnections for monitoring multiple folders
1800
1849
  this.setupSubConnections()
@@ -2005,10 +2054,7 @@ class IMAPClient extends BaseClient {
2005
2054
  !connectionOptions.allowSecondary &&
2006
2055
  (!connectionOptions.connectionClient || !connectionOptions.connectionClient.usable)
2007
2056
  ) {
2008
- let err = new Error('IMAP connection is currently not available for requested account');
2009
- err.code = 'IMAPUnavailable';
2010
- err.statusCode = 503;
2011
- throw err;
2057
+ throw connectionUnavailableError();
2012
2058
  }
2013
2059
  }
2014
2060
 
@@ -2165,7 +2211,9 @@ class IMAPClient extends BaseClient {
2165
2211
 
2166
2212
  this.checkIMAPConnection(connectionOptions);
2167
2213
 
2168
- return await this.getCurrentListing(options, connectionOptions);
2214
+ let listing = await this.getCurrentListing(options, connectionOptions);
2215
+ this.processNewListingEntries(listing);
2216
+ return listing;
2169
2217
  }
2170
2218
 
2171
2219
  /**
@@ -2847,18 +2895,11 @@ class IMAPClient extends BaseClient {
2847
2895
  // this mailbox is missing, refresh listing
2848
2896
  try {
2849
2897
  let listing = await this.getCurrentListing(false, { connectionClient });
2850
- // Register and sync newly found folders without delaying the
2851
- // upload error response - the initial sync of a new folder
2852
- // can take minutes
2853
- this.processListing(listing).catch(listingErr => {
2854
- this.logger.error({ msg: 'Failed to process listing', err: listingErr });
2855
- });
2898
+ this.processNewListingEntries(listing);
2856
2899
  } catch (E) {
2857
2900
  this.logger.error({ msg: 'Failed to refresh listing after missing mailbox', err: E });
2858
2901
  }
2859
- }
2860
2902
 
2861
- if (err.mailboxMissing) {
2862
2903
  // The API clients answer an unknown target folder with a 404 as well
2863
2904
  throw this.unknownPathError(data.path);
2864
2905
  }
@@ -2934,13 +2975,14 @@ class IMAPClient extends BaseClient {
2934
2975
  const mailboxes = [];
2935
2976
 
2936
2977
  const listing = await this.getCurrentListing(false, { allowSecondary: true });
2978
+ this.processNewListingEntries(listing);
2937
2979
  // Capture reference so we can close it after the await-heavy loop below
2938
2980
  // without risking closure of a different command client obtained by a concurrent caller
2939
2981
  const commandClientForListing = this.commandClient;
2940
2982
 
2941
2983
  // Process each configured subconnection
2942
2984
  for (const path of accountData.subconnections || []) {
2943
- const entry = listing.find(entry => path === entry.path || path === entry.specialUse);
2985
+ const entry = listing.find(entry => matchesListingEntry(path, entry));
2944
2986
 
2945
2987
  if (!entry) {
2946
2988
  // Mailbox not found - mark as disabled. mailboxMissing is the
@@ -2962,7 +3004,7 @@ class IMAPClient extends BaseClient {
2962
3004
  }
2963
3005
 
2964
3006
  // Check if already covered by primary connection
2965
- if (accountPaths[0] === entry.path) {
3007
+ if (samePath(accountPaths[0], entry.path)) {
2966
3008
  mailboxes.push({
2967
3009
  path: entry.path,
2968
3010
  disabled: true,
@@ -3004,7 +3046,7 @@ class IMAPClient extends BaseClient {
3004
3046
  // remove unneeded subconnections
3005
3047
  for (let i = this.subconnections.length - 1; i >= 0; i--) {
3006
3048
  let subconnection = this.subconnections[i];
3007
- const mailbox = mailboxes.find(mailbox => mailbox.path === subconnection.path);
3049
+ const mailbox = mailboxes.find(mailbox => samePath(mailbox.path, subconnection.path));
3008
3050
 
3009
3051
  if (mailbox && !mailbox.disabled === !subconnection.disabled) {
3010
3052
  // Still listed with the same active/disabled status - keep it
@@ -3020,7 +3062,7 @@ class IMAPClient extends BaseClient {
3020
3062
 
3021
3063
  // create missing subconnections
3022
3064
  for (const mailbox of mailboxes) {
3023
- if (this.subconnections.find(subconnection => mailbox.path === subconnection.path)) {
3065
+ if (this.subconnections.find(subconnection => samePath(mailbox.path, subconnection.path))) {
3024
3066
  // already exists
3025
3067
  continue;
3026
3068
  }
@@ -3035,7 +3077,6 @@ class IMAPClient extends BaseClient {
3035
3077
  parent: this,
3036
3078
  account: this.account,
3037
3079
  mailbox,
3038
- getImapConfig: async () => await this.getImapConfig(),
3039
3080
  logger: this.logger.child({
3040
3081
  cid: `${this.cid}:s:${this.connectionCount++}`,
3041
3082
  channel: 'subconnection',
@@ -2,7 +2,8 @@
2
2
 
3
3
  const { Gateway } = require('../gateway');
4
4
  const { oauth2ProviderData } = require('../oauth2-apps');
5
- const { resolveCredentials, useAuthServerForConnection } = require('../tools');
5
+ const { useAuthServerForConnection } = require('../tools');
6
+ const { resolveAuthServerCredentials } = require('./credential-errors');
6
7
  const { getLocalAddress } = require('../utils/network');
7
8
  const settings = require('../settings');
8
9
  const { TLS_DEFAULTS } = require('../consts');
@@ -134,16 +135,15 @@ class SmtpConfigBuilder {
134
135
  */
135
136
  async resolveAuthServer(smtpConnectionConfig) {
136
137
  if (await useAuthServerForConnection(smtpConnectionConfig, this.logger, { account: this.account, target: 'smtp' })) {
137
- try {
138
- return await resolveCredentials(this.account, 'smtp');
139
- } catch (err) {
140
- err.authenticationFailed = true;
141
- this.logger.error({
142
- msg: 'Failed to resolve SMTP credentials from the authentication server',
143
- err
144
- });
145
- throw err;
146
- }
138
+ // Shared with the IMAP and API paths so all three draw the same line between an
139
+ // authentication server that refused the account and one that is briefly unavailable.
140
+ // The builder carries no account state and sends no webhooks of its own, so the
141
+ // context only has to absorb what the shared helper reports
142
+ return await resolveAuthServerCredentials(this.account, 'smtp', {
143
+ logger: this.logger,
144
+ notify: async () => {},
145
+ state: null
146
+ });
147
147
  }
148
148
 
149
149
  return smtpConnectionConfig.auth;
@@ -1,6 +1,7 @@
1
1
  'use strict';
2
2
 
3
- const { metricsMeta, markRejectedAccessToken, renewRejectedAccessToken, isTransientNetworkError } = require('../base-client');
3
+ const { metricsMeta, markRejectedAccessToken, renewRejectedAccessToken } = require('../base-client');
4
+ const { isTransientNetworkError } = require('../credential-errors');
4
5
 
5
6
  const { OUTLOOK_MAX_BATCH_SIZE, OUTLOOK_MAX_RETRY_ATTEMPTS, OUTLOOK_RETRY_BASE_DELAY, OUTLOOK_RETRY_MAX_DELAY } = require('../../consts');
6
7