emailengine-app 2.79.9 → 2.80.1

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 (146) hide show
  1. package/.release-please-manifest.json +1 -1
  2. package/CHANGELOG.md +73 -0
  3. package/README.md +6 -0
  4. package/config/default.toml +5 -1
  5. package/data/google-crawlers.json +1 -1
  6. package/encrypt.js +43 -0
  7. package/lib/account/account-state.js +62 -0
  8. package/lib/account.js +34 -2
  9. package/lib/api-routes/account-routes.js +101 -1
  10. package/lib/api-routes/blocklist-routes.js +24 -0
  11. package/lib/api-routes/delivery-test-routes.js +6 -0
  12. package/lib/api-routes/gateway-routes.js +30 -0
  13. package/lib/api-routes/index.js +1 -1
  14. package/lib/api-routes/license-routes.js +10 -0
  15. package/lib/api-routes/mcp-oauth-routes.js +3 -3
  16. package/lib/api-routes/mcp-routes.js +39 -21
  17. package/lib/api-routes/oauth2-app-routes.js +38 -1
  18. package/lib/api-routes/outbox-routes.js +6 -0
  19. package/lib/api-routes/permission-map.js +208 -43
  20. package/lib/api-routes/pubsub-routes.js +8 -0
  21. package/lib/api-routes/route-helpers.js +58 -11
  22. package/lib/api-routes/settings-routes.js +67 -6
  23. package/lib/api-routes/stats-routes.js +6 -0
  24. package/lib/api-routes/template-routes.js +21 -0
  25. package/lib/api-routes/token-routes.js +34 -2
  26. package/lib/api-routes/webhook-route-routes.js +13 -0
  27. package/lib/autodetect-imap-settings.js +349 -47
  28. package/lib/cert-handler.js +62 -0
  29. package/lib/consts.js +50 -6
  30. package/lib/db.js +12 -0
  31. package/lib/egress-fetch.js +21 -9
  32. package/lib/email-client/base-client.js +238 -67
  33. package/lib/email-client/credential-errors.js +122 -0
  34. package/lib/email-client/gmail/gmail-api.js +2 -1
  35. package/lib/email-client/gmail-client.js +70 -64
  36. package/lib/email-client/imap/connection-errors.js +52 -0
  37. package/lib/email-client/imap/listing-diff.js +47 -6
  38. package/lib/email-client/imap/login-failure.js +52 -0
  39. package/lib/email-client/imap/mailbox.js +457 -379
  40. package/lib/email-client/imap/subconnection.js +17 -12
  41. package/lib/email-client/imap/sync-operations.js +46 -59
  42. package/lib/email-client/imap-client.js +139 -101
  43. package/lib/email-client/message-builder.js +11 -11
  44. package/lib/email-client/outlook/graph-api.js +2 -1
  45. package/lib/email-client/outlook-client.js +219 -106
  46. package/lib/enum-descriptions.js +12 -2
  47. package/lib/imap-proxy-auth.js +58 -3
  48. package/lib/imapproxy/imap-server.js +53 -62
  49. package/lib/lua/h-del-if-equals.lua +39 -0
  50. package/lib/lua/h-set-if-equals.lua +39 -0
  51. package/lib/mcp/oauth.js +46 -8
  52. package/lib/mcp/protocol.js +78 -35
  53. package/lib/mcp/tools.js +53 -17
  54. package/lib/privileged-settings.js +147 -0
  55. package/lib/routes-ui.js +4 -34
  56. package/lib/schemas.js +92 -16
  57. package/lib/security-headers.js +15 -0
  58. package/lib/settings.js +13 -0
  59. package/lib/tls/catalog.js +428 -0
  60. package/lib/tls/context.js +302 -0
  61. package/lib/tls/der.js +223 -0
  62. package/lib/tls/listeners.js +62 -0
  63. package/lib/tls/provision.js +555 -0
  64. package/lib/tls/self-signed.js +282 -0
  65. package/lib/tls/status.js +480 -0
  66. package/lib/tls/store.js +667 -0
  67. package/lib/token-permission-view.js +252 -102
  68. package/lib/token-permissions.js +176 -26
  69. package/lib/tokens.js +7 -6
  70. package/lib/tools.js +73 -27
  71. package/lib/ui-routes/account-routes.js +43 -30
  72. package/lib/ui-routes/admin-config-routes.js +63 -22
  73. package/lib/ui-routes/admin-entities-routes.js +23 -13
  74. package/lib/ui-routes/auth-routes.js +16 -1
  75. package/lib/ui-routes/internals-routes.js +3 -5
  76. package/lib/ui-routes/mcp-consent-routes.js +72 -31
  77. package/lib/ui-routes/network-config-routes.js +54 -45
  78. package/lib/ui-routes/tls-config-routes.js +628 -0
  79. package/lib/utils/mailbox-path.js +51 -0
  80. package/lib/utils/severity.js +31 -0
  81. package/package.json +12 -12
  82. package/sbom.json +1 -1
  83. package/server.js +23 -1
  84. package/static/css/flyonui.css +1 -1
  85. package/static/css/src/app.tailwind.css +11 -0
  86. package/static/js/app.js +34 -0
  87. package/static/js/public.js +6 -2
  88. package/static/js/ui.js +97 -61
  89. package/static/licenses.html +341 -1252
  90. package/translations/messages.pot +62 -56
  91. package/views/account/login-redirect.hbs +22 -0
  92. package/views/account/passkeys.hbs +2 -2
  93. package/views/accounts/account.hbs +2 -2
  94. package/views/accounts/browse.hbs +1 -1
  95. package/views/accounts/edit.hbs +1 -1
  96. package/views/accounts/register/imap-server.hbs +1 -1
  97. package/views/config/ai.hbs +1 -1
  98. package/views/config/branding.hbs +2 -2
  99. package/views/config/document-store/chat.hbs +1 -1
  100. package/views/config/document-store/index.hbs +1 -1
  101. package/views/config/imap-proxy.hbs +1 -4
  102. package/views/config/license.hbs +1 -1
  103. package/views/config/mcp.hbs +88 -52
  104. package/views/config/network.hbs +1 -1
  105. package/views/config/oauth/app.hbs +2 -2
  106. package/views/config/service.hbs +1 -1
  107. package/views/config/smtp.hbs +1 -4
  108. package/views/config/tls-upload.hbs +81 -0
  109. package/views/config/tls.hbs +593 -0
  110. package/views/config/webhooks.hbs +2 -2
  111. package/views/internals/index.hbs +1 -1
  112. package/views/layout/app.hbs +6 -6
  113. package/views/layout/login.hbs +5 -5
  114. package/views/layout/main.hbs +2 -2
  115. package/views/layout/prompt.hbs +3 -3
  116. package/views/layout/public.hbs +1 -1
  117. package/views/mcp/authorize.hbs +47 -45
  118. package/views/partials/ace_assets.hbs +1 -1
  119. package/views/partials/add_account_modal.hbs +1 -1
  120. package/views/partials/filter_editor_js.hbs +2 -2
  121. package/views/partials/gateway_js.hbs +1 -1
  122. package/views/partials/mcp_access_levels.hbs +16 -9
  123. package/views/partials/mcp_tool_count.hbs +15 -14
  124. package/views/partials/oauth_form.hbs +1 -1
  125. package/views/partials/public_theme_init.hbs +1 -1
  126. package/views/partials/side_menu.hbs +1 -0
  127. package/views/partials/template_form.hbs +1 -1
  128. package/views/partials/theme_init.hbs +1 -1
  129. package/views/partials/tls_security_card.hbs +25 -53
  130. package/views/partials/ui/alert-banner.hbs +3 -2
  131. package/views/partials/ui/badge.hbs +6 -2
  132. package/views/partials/ui/btn.hbs +5 -2
  133. package/views/partials/webhooks_editor_functions.hbs +1 -1
  134. package/views/reference/index.hbs +1 -1
  135. package/views/reference/redirect.hbs +1 -1
  136. package/views/reference/tag.hbs +1 -1
  137. package/views/reference/token.hbs +1 -1
  138. package/views/templates/template.hbs +1 -1
  139. package/views/tokens/new.hbs +175 -74
  140. package/views/unsubscribe.hbs +1 -1
  141. package/views/webhooks/webhook.hbs +1 -1
  142. package/workers/api.js +102 -142
  143. package/workers/imap-proxy.js +4 -1
  144. package/workers/smtp.js +51 -44
  145. package/views/partials/tls_security_js.hbs +0 -64
  146. package/views/partials/tls_security_modal.hbs +0 -22
@@ -13,13 +13,15 @@ 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');
21
+ const { isRefusedImapLogin, imapResponseText } = require('./imap/login-failure');
19
22
 
20
23
  const {
21
24
  normalizePath,
22
- resolveCredentials,
23
25
  useAuthServerForConnection,
24
26
  emitChangeEvent,
25
27
  getByteSize,
@@ -39,7 +41,6 @@ const ENSURE_MAIN_TTL = 5 * 1000;
39
41
 
40
42
  const {
41
43
  AUTH_ERROR_NOTIFY,
42
- AUTH_SUCCESS_NOTIFY,
43
44
  CONNECT_ERROR_NOTIFY,
44
45
  CONNECTION_CLOSING_CODES,
45
46
  DEFAULT_DOWNLOAD_CHUNK_SIZE,
@@ -297,10 +298,7 @@ class IMAPClient extends BaseClient {
297
298
  if (!noPool && (!syncing || !allowSecondary)) {
298
299
  // Return the primary connection for most operations
299
300
  if (!this.imapClient) {
300
- let err = new Error('IMAP connection not available');
301
- err.code = 'IMAPConnectionClosing';
302
- err.statusCode = 503;
303
- throw err;
301
+ throw connectionNotAvailableError();
304
302
  }
305
303
  return this.imapClient;
306
304
  }
@@ -320,10 +318,7 @@ class IMAPClient extends BaseClient {
320
318
 
321
319
  // Fall back to primary connection
322
320
  if (!this.imapClient) {
323
- let err = new Error('IMAP connection not available');
324
- err.code = 'IMAPConnectionClosing';
325
- err.statusCode = 503;
326
- throw err;
321
+ throw connectionNotAvailableError();
327
322
  }
328
323
  return this.imapClient;
329
324
  }
@@ -455,7 +450,7 @@ class IMAPClient extends BaseClient {
455
450
  async ensureMainMailbox() {
456
451
  let mainPath = this.main ? this.main.path : 'INBOX';
457
452
 
458
- // start waiting for changes (Mailbox.select() skips the SELECT when it is already open)
453
+ // start waiting for changes (Mailbox.select() returns right away when it is already open)
459
454
  await this.select(mainPath);
460
455
  }
461
456
 
@@ -611,7 +606,15 @@ class IMAPClient extends BaseClient {
611
606
  async getMessageTextPaths(textId) {
612
607
  let buf = Buffer.from(textId, 'base64url');
613
608
  let id = buf.subarray(0, 8);
614
- let textParts = msgpack.decode(buf.subarray(8));
609
+
610
+ // The tail is msgpack, and the decoder throws outright on a truncated or absent one - an
611
+ // id one byte short of its parts list, or any foreign value, reached the API as a 500
612
+ let textParts;
613
+ try {
614
+ textParts = msgpack.decode(buf.subarray(8));
615
+ } catch (err) {
616
+ throw this.invalidIdError();
617
+ }
615
618
 
616
619
  let message = await this.unpackUid(id);
617
620
  if (!message) {
@@ -710,7 +713,7 @@ class IMAPClient extends BaseClient {
710
713
 
711
714
  // Flags entries of `listing` as isNew as a side effect - that one-shot flag is what makes
712
715
  // processListing() emit mailboxNew, so it has to ride along on the returned listing.
713
- let { hasChanges, deletedEntries } = diffMailboxListing(listing, storedListing);
716
+ let { hasChanges, hasChangesBesidesNew, deletedEntries } = diffMailboxListing(listing, storedListing);
714
717
 
715
718
  if (corruptPaths.length) {
716
719
  // An unusable stored value is not part of the comparison at all, so it can not be
@@ -726,6 +729,7 @@ class IMAPClient extends BaseClient {
726
729
  logger.notifyError(corruptErr, { user: this.account, meta: { paths: corruptPaths.join(', ') } });
727
730
  }
728
731
  hasChanges = true;
732
+ hasChangesBesidesNew = true;
729
733
  }
730
734
 
731
735
  for (let entry of deletedEntries) {
@@ -733,12 +737,19 @@ class IMAPClient extends BaseClient {
733
737
  await this.clearMailboxEntry(entry);
734
738
  }
735
739
 
740
+ // A folder that appeared is only recorded by a pass that can announce it: processListing()
741
+ // registers nothing without a primary connection, which a listing read over a pooled
742
+ // secondary is allowed to run without, and the stored listing is what the next pass diffs
743
+ // against (see .claude/rules/workers.md). Deletions are not deferred - they are complete on
744
+ // their own - so a pass that found nothing but folders it must defer has nothing to write.
745
+ const deferNewEntries = !this.imapClient;
746
+
736
747
  // on changes store updated listing
737
- if (hasChanges) {
748
+ if (hasChanges && (!deferNewEntries || hasChangesBesidesNew)) {
738
749
  // Atomic update of the mailbox listing. HMSET refuses an empty hash, and that error
739
750
  // aborts the entire MULTI including the DEL, so the write is only queued when there
740
751
  // is something to write.
741
- let listingObject = buildStoredListingObject(listing);
752
+ let listingObject = buildStoredListingObject(deferNewEntries ? listing.filter(entry => !entry.isNew) : listing);
742
753
  let updateListing = this.redis.multi().del(this.getMailboxListKey());
743
754
  if (Object.keys(listingObject).length) {
744
755
  updateListing = updateListing.hmset(this.getMailboxListKey(), listingObject);
@@ -749,19 +760,61 @@ class IMAPClient extends BaseClient {
749
760
  return listing;
750
761
  }
751
762
 
763
+ /**
764
+ * Registers a Mailbox instance for a listing entry, replacing whatever instance the
765
+ * path was tracked by. The one-shot `isNew` flag rides on the instance being replaced
766
+ * until an open of the folder succeeds, so it is carried over: the listing a
767
+ * reconnect registers from no longer reports the folder as new (it has been in the
768
+ * stored listing since the pass that discovered it), and a first sync interrupted by a
769
+ * disconnect - which can take minutes on a large folder - would otherwise lose its
770
+ * mailboxNew for good.
771
+ * @param {Object} entry - Mailbox entry from the server listing
772
+ * @returns {Mailbox} The registered mailbox instance
773
+ */
774
+ registerMailbox(entry) {
775
+ const normalizedPath = normalizePath(entry.path);
776
+
777
+ let previous = this.mailboxes.get(normalizedPath);
778
+ if (previous && previous.listingEntry && previous.listingEntry.isNew) {
779
+ entry.isNew = true;
780
+ }
781
+
782
+ let mailbox = new Mailbox(this, entry);
783
+ this.mailboxes.set(normalizedPath, mailbox);
784
+ return mailbox;
785
+ }
786
+
752
787
  /**
753
788
  * Registers Mailbox instances for previously unseen entries in a mailbox
754
789
  * listing and runs the initial sync for them. Entries carrying the one-shot
755
790
  * `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).
791
+ * sync emits the mailboxNew notification, so every listing refresh must route
792
+ * its result through here - callers that only read the listing hand it over
793
+ * through processNewListingEntries().
759
794
  * Intentionally not guarded by `refreshingList`: it must also run when called
760
795
  * from inside refreshFolderList()'s own sync loop.
761
796
  * @param {Array} listing - Listing returned by getCurrentListing()
762
797
  * @returns {Set} Set of newly created mailbox instances that were synced
763
798
  */
764
799
  async processListing(listing) {
800
+ let syncNeeded = new Set();
801
+
802
+ // Registration belongs to a connected account. A listing can be read over a pooled
803
+ // secondary connection while the primary is down (listMailboxes() allows that), and
804
+ // the provider flags this method filters on - isGmail above all - are only decided
805
+ // by connect(), which registers the whole listing itself once it is done
806
+ if (!this.imapClient) {
807
+ await this.releaseUnregisteredEntries(listing);
808
+ return syncNeeded;
809
+ }
810
+
811
+ // Every entry is tracked already, so the loop below would register nothing. Answered
812
+ // before the account load because this runs on every resync pass and after every
813
+ // folder-changing operation, and a listing that holds no unseen folder is the norm
814
+ if (!(listing || []).some(entry => !this.mailboxes.has(normalizePath(entry.path)))) {
815
+ return syncNeeded;
816
+ }
817
+
765
818
  let accountData = await this.accountObject.loadAccountData();
766
819
 
767
820
  // Get configured paths to monitor (default to all)
@@ -770,7 +823,6 @@ class IMAPClient extends BaseClient {
770
823
  accountPaths.push('*');
771
824
  }
772
825
 
773
- let syncNeeded = new Set();
774
826
  for (let entry of listing || []) {
775
827
  if (
776
828
  // previously unseen
@@ -778,7 +830,7 @@ class IMAPClient extends BaseClient {
778
830
  ) {
779
831
  // Apply filtering rules based on account configuration
780
832
  if (!accountPaths.includes('*')) {
781
- if (!accountPaths.includes(entry.path) && !accountPaths.includes(entry.specialUse)) {
833
+ if (configuredPathIndex(accountPaths, entry) < 0) {
782
834
  // ignore changes
783
835
  entry.syncDisabled = true;
784
836
  }
@@ -788,8 +840,7 @@ class IMAPClient extends BaseClient {
788
840
  entry.syncDisabled = true;
789
841
  }
790
842
 
791
- let mailbox = new Mailbox(this, entry);
792
- this.mailboxes.set(normalizePath(entry.path), mailbox);
843
+ let mailbox = this.registerMailbox(entry);
793
844
  syncNeeded.add(mailbox);
794
845
  }
795
846
  }
@@ -820,6 +871,44 @@ class IMAPClient extends BaseClient {
820
871
  return await this.processListing(listing);
821
872
  }
822
873
 
874
+ /**
875
+ * Hands a freshly read listing to processListing() without waiting for it, so a caller
876
+ * that only wanted to read the listing does not drop the one-shot `isNew` flag riding
877
+ * on it (see getCurrentListing()). The initial sync of a new folder can take minutes,
878
+ * which is why the caller does not wait
879
+ * @param {Array} listing - Listing returned by getCurrentListing()
880
+ */
881
+ processNewListingEntries(listing) {
882
+ this.processListing(listing).catch(err => {
883
+ this.logger.error({ msg: 'Failed to process listing', err });
884
+ });
885
+ }
886
+
887
+ /**
888
+ * Takes the folders a listing found back out of the stored listing when the pass that
889
+ * read them could not register them.
890
+ *
891
+ * getCurrentListing() leaves the `isNew` entries out of what it writes when the primary
892
+ * is down, but it decides that from the connection it saw before the write, and the
893
+ * primary can go away between that write and processListing(). The flag itself is not
894
+ * persisted, so a folder written in that window is absorbed: the next pass diffs it as
895
+ * known and its mailboxNew is never sent. Removing the entry is what the deferring write
896
+ * would have done, and the next pass finds the folder new again.
897
+ * @param {Array} listing - Listing returned by getCurrentListing()
898
+ */
899
+ async releaseUnregisteredEntries(listing) {
900
+ const deferred = (listing || []).filter(entry => entry.isNew).map(entry => normalizePath(entry.path));
901
+ if (!deferred.length) {
902
+ return;
903
+ }
904
+
905
+ try {
906
+ await this.redis.hdel(this.getMailboxListKey(), ...deferred);
907
+ } catch (err) {
908
+ this.logger.error({ msg: 'Failed to defer the folders a disconnected pass found', paths: deferred, err });
909
+ }
910
+ }
911
+
823
912
  /**
824
913
  * Refreshes the folder list and creates Mailbox instances for new folders
825
914
  * @returns {Set} Set of newly created mailbox instances that need syncing
@@ -897,11 +986,11 @@ class IMAPClient extends BaseClient {
897
986
  for (let entry of listing) {
898
987
  if (!accountPaths.includes('*')) {
899
988
  // Limited path monitoring - only specific folders
900
- if (!accountPaths.includes(entry.path) && !accountPaths.includes(entry.specialUse)) {
989
+ let index = configuredPathIndex(accountPaths, entry);
990
+ if (index < 0) {
901
991
  entry.syncDisabled = true;
902
992
  } else {
903
993
  // 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
994
  mainList.push({ index, entry });
906
995
  }
907
996
  } else {
@@ -918,8 +1007,7 @@ class IMAPClient extends BaseClient {
918
1007
  }
919
1008
  }
920
1009
 
921
- let mailbox = new Mailbox(this, entry);
922
- this.mailboxes.set(normalizePath(entry.path), mailbox);
1010
+ this.registerMailbox(entry);
923
1011
  }
924
1012
 
925
1013
  if (mainList.length) {
@@ -991,7 +1079,7 @@ class IMAPClient extends BaseClient {
991
1079
  return false;
992
1080
  }
993
1081
  for (let mailbox of this.mailboxes.values()) {
994
- if (mailbox.listingEntry && mailbox.listingEntry.specialUse === path) {
1082
+ if (mailbox.listingEntry && matchesListingEntry(path, mailbox.listingEntry)) {
995
1083
  return true;
996
1084
  }
997
1085
  }
@@ -1261,6 +1349,11 @@ class IMAPClient extends BaseClient {
1261
1349
  return;
1262
1350
  }
1263
1351
  if (!synced || !synced.has(mailbox)) {
1352
+ // The pass ends with its own select of the main mailbox. A folder synced
1353
+ // earlier in the walk reported a task when its lock was released, and a
1354
+ // stretch of STATUS-only folders can outlast that timer - clear it so the
1355
+ // main mailbox is not selected mid-walk and again at the end
1356
+ clearTimeout(this.completedTimer);
1264
1357
  await mailbox.sync();
1265
1358
  }
1266
1359
  }
@@ -1301,8 +1394,9 @@ class IMAPClient extends BaseClient {
1301
1394
  });
1302
1395
 
1303
1396
  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');
1397
+
1398
+ // NB! the stored error state is cleared by the login in start(), not here - see
1399
+ // BaseClient.notifyAuthenticationSuccess()
1306
1400
  await emitChangeEvent(this.logger, this.account, 'state', this.state);
1307
1401
 
1308
1402
  // Revive subconnections that disabled themselves while their monitored
@@ -1410,21 +1504,7 @@ class IMAPClient extends BaseClient {
1410
1504
 
1411
1505
  // If authentication server is set then it overrides authentication data
1412
1506
  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
- }
1507
+ imapConnectionConfig.auth = await this.resolveAuthServerCredentials('imap', ctx);
1428
1508
  }
1429
1509
 
1430
1510
  // Configure TLS settings
@@ -1763,38 +1843,8 @@ class IMAPClient extends BaseClient {
1763
1843
  return;
1764
1844
  }
1765
1845
 
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
- }
1846
+ // Announces the login and clears what the previous attempt left behind
1847
+ await this.notifyAuthenticationSuccess(imapConfig.auth.user);
1798
1848
 
1799
1849
  // Set up subconnections for monitoring multiple folders
1800
1850
  this.setupSubConnections()
@@ -1836,12 +1886,8 @@ class IMAPClient extends BaseClient {
1836
1886
  }
1837
1887
  }
1838
1888
 
1839
- // ImapFlow rewrites err.response into a string for authentication
1840
- // failures, but for other command failures it is the parsed response
1841
- // object - prefer the response text so the stored error state and
1842
- // webhook payloads never render as "[object Object]"
1843
- let errorResponse = (typeof err.response === 'string' && err.response) || err.responseText;
1844
- if (err.authenticationFailed) {
1889
+ let errorResponse = imapResponseText(err);
1890
+ if (isRefusedImapLogin(err)) {
1845
1891
  this.logger.warn({ msg: 'Failed to authenticate', account: this.account, err });
1846
1892
  await this.notify(false, AUTH_ERROR_NOTIFY, {
1847
1893
  response: errorResponse,
@@ -2005,10 +2051,7 @@ class IMAPClient extends BaseClient {
2005
2051
  !connectionOptions.allowSecondary &&
2006
2052
  (!connectionOptions.connectionClient || !connectionOptions.connectionClient.usable)
2007
2053
  ) {
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;
2054
+ throw connectionUnavailableError();
2012
2055
  }
2013
2056
  }
2014
2057
 
@@ -2165,7 +2208,9 @@ class IMAPClient extends BaseClient {
2165
2208
 
2166
2209
  this.checkIMAPConnection(connectionOptions);
2167
2210
 
2168
- return await this.getCurrentListing(options, connectionOptions);
2211
+ let listing = await this.getCurrentListing(options, connectionOptions);
2212
+ this.processNewListingEntries(listing);
2213
+ return listing;
2169
2214
  }
2170
2215
 
2171
2216
  /**
@@ -2847,18 +2892,11 @@ class IMAPClient extends BaseClient {
2847
2892
  // this mailbox is missing, refresh listing
2848
2893
  try {
2849
2894
  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
- });
2895
+ this.processNewListingEntries(listing);
2856
2896
  } catch (E) {
2857
2897
  this.logger.error({ msg: 'Failed to refresh listing after missing mailbox', err: E });
2858
2898
  }
2859
- }
2860
2899
 
2861
- if (err.mailboxMissing) {
2862
2900
  // The API clients answer an unknown target folder with a 404 as well
2863
2901
  throw this.unknownPathError(data.path);
2864
2902
  }
@@ -2934,13 +2972,14 @@ class IMAPClient extends BaseClient {
2934
2972
  const mailboxes = [];
2935
2973
 
2936
2974
  const listing = await this.getCurrentListing(false, { allowSecondary: true });
2975
+ this.processNewListingEntries(listing);
2937
2976
  // Capture reference so we can close it after the await-heavy loop below
2938
2977
  // without risking closure of a different command client obtained by a concurrent caller
2939
2978
  const commandClientForListing = this.commandClient;
2940
2979
 
2941
2980
  // Process each configured subconnection
2942
2981
  for (const path of accountData.subconnections || []) {
2943
- const entry = listing.find(entry => path === entry.path || path === entry.specialUse);
2982
+ const entry = listing.find(entry => matchesListingEntry(path, entry));
2944
2983
 
2945
2984
  if (!entry) {
2946
2985
  // Mailbox not found - mark as disabled. mailboxMissing is the
@@ -2962,7 +3001,7 @@ class IMAPClient extends BaseClient {
2962
3001
  }
2963
3002
 
2964
3003
  // Check if already covered by primary connection
2965
- if (accountPaths[0] === entry.path) {
3004
+ if (samePath(accountPaths[0], entry.path)) {
2966
3005
  mailboxes.push({
2967
3006
  path: entry.path,
2968
3007
  disabled: true,
@@ -3004,7 +3043,7 @@ class IMAPClient extends BaseClient {
3004
3043
  // remove unneeded subconnections
3005
3044
  for (let i = this.subconnections.length - 1; i >= 0; i--) {
3006
3045
  let subconnection = this.subconnections[i];
3007
- const mailbox = mailboxes.find(mailbox => mailbox.path === subconnection.path);
3046
+ const mailbox = mailboxes.find(mailbox => samePath(mailbox.path, subconnection.path));
3008
3047
 
3009
3048
  if (mailbox && !mailbox.disabled === !subconnection.disabled) {
3010
3049
  // Still listed with the same active/disabled status - keep it
@@ -3020,7 +3059,7 @@ class IMAPClient extends BaseClient {
3020
3059
 
3021
3060
  // create missing subconnections
3022
3061
  for (const mailbox of mailboxes) {
3023
- if (this.subconnections.find(subconnection => mailbox.path === subconnection.path)) {
3062
+ if (this.subconnections.find(subconnection => samePath(mailbox.path, subconnection.path))) {
3024
3063
  // already exists
3025
3064
  continue;
3026
3065
  }
@@ -3035,7 +3074,6 @@ class IMAPClient extends BaseClient {
3035
3074
  parent: this,
3036
3075
  account: this.account,
3037
3076
  mailbox,
3038
- getImapConfig: async () => await this.getImapConfig(),
3039
3077
  logger: this.logger.child({
3040
3078
  cid: `${this.cid}:s:${this.connectionCount++}`,
3041
3079
  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