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
@@ -20,6 +20,8 @@ const { getTemplate } = require('@postalsys/templates');
20
20
  const { deepEqual } = require('assert');
21
21
  const { arfDetect, camelCaseComplaint } = require('../arf-detect');
22
22
  const { createTransaction } = require('../redis-operations');
23
+ const { ACCOUNT_STATES } = require('../account/account-state');
24
+ const { credentialErrorStatus, isTransientCredentialError, resolveAuthServerCredentials } = require('./credential-errors');
23
25
  const simpleParser = require('mailparser').simpleParser;
24
26
  const libmime = require('libmime');
25
27
  const { bounceDetect, applyDeliveryReport } = require('../bounce-detect');
@@ -51,7 +53,6 @@ const {
51
53
  emitChangeEvent,
52
54
  filterEmptyObjectValues,
53
55
  getDateBuckets,
54
- resolveCredentials,
55
56
  useAuthServerForOAuth2,
56
57
  collectCidReferences,
57
58
  cidReferenceRegex
@@ -60,6 +61,7 @@ const {
60
61
  // Import application constants
61
62
  const {
62
63
  AUTH_ERROR_NOTIFY,
64
+ AUTH_SUCCESS_NOTIFY,
63
65
  ACCOUNT_INITIALIZED_NOTIFY,
64
66
  REDIS_PREFIX,
65
67
  MESSAGE_NEW_NOTIFY,
@@ -71,10 +73,10 @@ const {
71
73
  MAX_INLINE_ATTACHMENT_SIZE,
72
74
  DEFAULT_MAX_IMAP_AUTH_FAILURE_TIME,
73
75
  AUTH_FAILURE_DISABLED_FIELD,
76
+ LAST_ERROR_EVENT_FIELD,
74
77
  AUTH_FAILURE_DISABLED_DESCRIPTION,
75
78
  EMAIL_DELIVERY_ERROR_NOTIFY,
76
- EMAIL_SENT_NOTIFY,
77
- TRANSIENT_NETWORK_CODES
79
+ EMAIL_SENT_NOTIFY
78
80
  } = require('../consts');
79
81
  const { buildRetentionPolicy } = require('../queue-retention');
80
82
  const { readImapData } = require('../account/imap-data');
@@ -210,19 +212,28 @@ async function renewRejectedAccessToken(context, err, tokenData, tokenRenewed) {
210
212
  return true;
211
213
  }
212
214
 
215
+ // Everything an error run stores. One list, because clearing a subset leaves an account that has
216
+ // recovered still carrying the counters the auth-failure safety net reads, and the list has already
217
+ // grown once - LAST_ERROR_EVENT_FIELD was added after the other three
218
+ const ERROR_STATE_FIELDS = Object.freeze(['lastErrorState', LAST_ERROR_EVENT_FIELD, 'lastError:errorCount', 'lastError:first']);
219
+
213
220
  /**
214
- * Failing to reach a remote endpoint is a connection problem, not a rejected credential. Both
215
- * OAuth2 credential sources (EmailEngine's own token refresh and an external authentication
216
- * server) use this to avoid reporting an unreachable host as an authentication error, which
217
- * would webhook and park every account on the instance over a brief outage, and the API
218
- * transports use it to decide which failed requests to repeat. undici reports a connection
219
- * failure as a generic TypeError ("fetch failed") with the real DNS/socket error attached as
220
- * err.cause, so the code is looked up there as well
221
- * @param {Error} err - The error to check
222
- * @returns {boolean} True if the error is a transient network failure
221
+ * Reads a stored `lastErrorState`. `isSet` says whether it describes an error that actually
222
+ * happened: an empty object is what a cleared-but-rewritten state looks like, and a value that
223
+ * will not parse still counts as a run that happened even though nothing can be read off it
224
+ * @param {String} storedState - Raw JSON read from the account hash
225
+ * @returns {Object} { parsed, isSet }
223
226
  */
224
- function isTransientNetworkError(err) {
225
- return !!err && (TRANSIENT_NETWORK_CODES.has(err.code) || (!!err.cause && TRANSIENT_NETWORK_CODES.has(err.cause.code)));
227
+ function parseErrorState(storedState) {
228
+ if (!storedState) {
229
+ return { parsed: null, isSet: false };
230
+ }
231
+ try {
232
+ const parsed = JSON.parse(storedState);
233
+ return { parsed, isSet: !!parsed && (typeof parsed !== 'object' || !!Object.keys(parsed).length) };
234
+ } catch (err) {
235
+ return { parsed: null, isSet: true };
236
+ }
226
237
  }
227
238
 
228
239
  /**
@@ -336,6 +347,12 @@ class BaseClient {
336
347
  // scheduleInitRetry(). IMAPClient reconnects with its own backoff instead
337
348
  this.retriesInit = false;
338
349
 
350
+ // Read by notifyAuthenticationSuccess(). Deliberately not persisted: a worker restart
351
+ // re-arming it costs at most one extra event for an account that never manages to connect,
352
+ // while a new account hash field would have to guess what every existing account had
353
+ // already been told
354
+ this.authSuccessNotified = false;
355
+
339
356
  // Initialize notification handler for webhook and event delivery
340
357
  this.notificationHandler = new NotificationHandler({
341
358
  account: this.account,
@@ -574,6 +591,21 @@ class BaseClient {
574
591
  }
575
592
  }
576
593
 
594
+ /**
595
+ * The answer every client gives for a text or attachment identifier it can not decode, built in
596
+ * one place so the three agree on it
597
+ * @returns {Error} Coded 400
598
+ */
599
+ invalidIdError() {
600
+ let error = new Error('Invalid identifier');
601
+ error.info = {
602
+ response: 'The provided identifier can not be decoded'
603
+ };
604
+ error.code = 'InvalidId';
605
+ error.statusCode = 400;
606
+ return error;
607
+ }
608
+
577
609
  /**
578
610
  * Decodes a base64url msgpack identifier the API clients hand out for text and
579
611
  * attachment references. A truncated or foreign value used to surface as a RangeError,
@@ -591,13 +623,7 @@ class BaseClient {
591
623
  }
592
624
 
593
625
  if (!Array.isArray(parts) || !isValid(parts)) {
594
- let error = new Error('Invalid identifier');
595
- error.info = {
596
- response: 'The provided identifier can not be decoded'
597
- };
598
- error.code = 'InvalidId';
599
- error.statusCode = 400;
600
- throw error;
626
+ throw this.invalidIdError();
601
627
  }
602
628
 
603
629
  return parts;
@@ -705,6 +731,156 @@ class BaseClient {
705
731
  }
706
732
  }
707
733
 
734
+ /**
735
+ * Drops everything an error run stored. Used by every recovery route: a completed login, and
736
+ * the Graph client's change subscription starting to work again. One implementation, so the set
737
+ * of fields cannot grow a second idea of itself.
738
+ *
739
+ * The delete is conditional, and `expected` is required for it: only the caller knows which
740
+ * failure it judged, and between reading that failure and getting here it can have been
741
+ * replaced by an unrelated one (see lib/lua/h-del-if-equals.lua).
742
+ *
743
+ * @param {String|null} expected - The raw `lastErrorState` the caller read, null when there
744
+ * was none. The delete is skipped when the field no longer holds it
745
+ * @returns {Promise<boolean>} Whether the fields were dropped
746
+ */
747
+ async clearStoredErrorState(expected) {
748
+ return !!(await this.redis.hDelIfEquals(this.getAccountKey(), 'lastErrorState', expected || '', ...ERROR_STATE_FIELDS));
749
+ }
750
+
751
+ /**
752
+ * Whether a stored error run is one only the code that reported it may lift. A login clears
753
+ * every failure that stood between the account and a session, which is every failure a client
754
+ * stores by default - so this says no. A reporter whose failure a login says nothing about
755
+ * overrides it and keeps its own report standing (the Graph client's change subscription is
756
+ * one: a tenant that disabled the Exchange Online service principal keeps refreshing tokens
757
+ * and logging in perfectly while no subscription can be created).
758
+ * @param {Object} parsedState - The stored `lastErrorState`, parsed; null when there is none
759
+ * @returns {boolean} True when only the code that reported it may clear it
760
+ */
761
+ isSelfClearedErrorState(parsedState) {
762
+ return false;
763
+ }
764
+
765
+ /**
766
+ * Reports a completed login: decides whether it is worth an `authenticationSuccess` webhook,
767
+ * clears the error state the previous attempt left behind, and sends the notification.
768
+ *
769
+ * Reading and clearing the error state is one step on purpose. The IMAP client used to read it
770
+ * on login and clear it only once a full folder sync had completed, so an account that
771
+ * authenticates but never manages to sync re-read the same stale error on every reconnect and
772
+ * announced itself again each time.
773
+ *
774
+ * Call this BEFORE the account state is flipped to `connected`. The first-login test reads the
775
+ * connected-session counter that setStateVal() raises, and the Graph client used to read it
776
+ * afterwards - so an Outlook account never announced its first login at all.
777
+ *
778
+ * @param {String} user - Username the login used, for the webhook payload
779
+ * @returns {Promise<boolean>} Whether the notification was sent
780
+ */
781
+ async notifyAuthenticationSuccess(user) {
782
+ const accountKey = this.getAccountKey();
783
+
784
+ let storedState;
785
+ let storedEvent;
786
+ let prevConnectedCount;
787
+ let parsedState;
788
+
789
+ try {
790
+ // Read what the previous attempt left behind, then drop the run it describes. A run
791
+ // this login did not get past stays where it is, for the code that reported it to
792
+ // lift. The delete is otherwise conditional on the value just read, so a failure
793
+ // written since is left for whoever wrote it rather than taken along
794
+ [storedState, storedEvent, prevConnectedCount] = await this.redis.hmget(
795
+ accountKey,
796
+ 'lastErrorState',
797
+ LAST_ERROR_EVENT_FIELD,
798
+ 'state:count:connected'
799
+ );
800
+
801
+ parsedState = parseErrorState(storedState);
802
+
803
+ if (!this.isSelfClearedErrorState(parsedState.parsed)) {
804
+ await this.clearStoredErrorState(storedState);
805
+ }
806
+ } catch (err) {
807
+ // Saying nothing is the quiet answer: a webhook that is not sent can be read off the
808
+ // account state, one that is sent twice cannot be taken back
809
+ this.logger.error({ msg: 'Failed to consume the stored error state', account: this.account, err });
810
+ return false;
811
+ }
812
+
813
+ // What had been failing, or null when the account was not in an error state. An error state
814
+ // written before the event field existed carries no marker; read it as an authentication
815
+ // failure, which is how every recovery used to be reported
816
+ const errorEvent = parsedState.isSet ? storedEvent || AUTH_ERROR_NOTIFY : null;
817
+
818
+ // A string zero means the account has been initialized but not yet connected. The counter
819
+ // is only raised once the account reaches `connected`, which for an IMAP account means a
820
+ // completed folder sync - so it stays at zero for an account that logs in but cannot sync,
821
+ // and the instance flag is what keeps that from announcing a first login every time round
822
+ const isInitial = prevConnectedCount === '0' && !this.authSuccessNotified;
823
+
824
+ // Announce a recovery only when authentication was what had been failing. `connectError`
825
+ // stores the same error state, and reporting a name-resolution blip as
826
+ // `authenticationSuccess` is both wrong and, on an account that keeps flapping, one more
827
+ // webhook per cycle
828
+ if (!isInitial && errorEvent !== AUTH_ERROR_NOTIFY) {
829
+ this.logger.info({ msg: 'Successful login with a previous active session', account: this.account, prevActive: true, errorEvent });
830
+ return false;
831
+ }
832
+
833
+ this.authSuccessNotified = true;
834
+ this.logger.info({ msg: 'Successful login without a previous active session', account: this.account, isInitial, prevActive: false });
835
+ await this.notify(false, AUTH_SUCCESS_NOTIFY, { user });
836
+ return true;
837
+ }
838
+
839
+ /**
840
+ * Fetches this account's credentials from the operator's external authentication server. See
841
+ * resolveAuthServerCredentials() in ./credential-errors for what it reports and why
842
+ * @param {String} target - Protocol the credentials are for ('imap', 'smtp' or 'api')
843
+ * @param {Object} ctx - What to report the failure on (a subconnection reports on itself)
844
+ * @returns {Promise<Object>} Resolved credentials
845
+ */
846
+ async resolveAuthServerCredentials(target, ctx) {
847
+ return await resolveAuthServerCredentials(this.account, target, ctx || this);
848
+ }
849
+
850
+ /**
851
+ * Reports a failed OAuth2 token refresh for an API-backed account. Both API clients call this
852
+ * from getTokenData(); the IMAP path reports its own through loadOAuth2LoginCredentials().
853
+ *
854
+ * @param {Error} err - The ETokenRefresh failure
855
+ * @param {String} provider - Provider name for the metrics label
856
+ * @returns {Promise<void>}
857
+ */
858
+ async reportTokenRefreshFailure(err, provider) {
859
+ const statusCode = String(err.statusCode || 0);
860
+ postMetrics({ account: this.account }, this.logger, 'oauth2TokenRefresh', 'inc', { status: 'failure', provider, statusCode });
861
+
862
+ if (isTransientCredentialError(err)) {
863
+ // The endpoint is unavailable, it has not refused the refresh token. Left unflagged and
864
+ // unannounced so the caller retries instead of parking the account and webhooking an
865
+ // authentication failure that the next attempt contradicts
866
+ this.logger.warn({ msg: 'Token endpoint is unavailable', account: this.account, statusCode, err });
867
+ return;
868
+ }
869
+
870
+ this.state = ACCOUNT_STATES.AUTHENTICATION_ERROR;
871
+ await this.setStateVal();
872
+
873
+ err.authenticationFailed = true;
874
+
875
+ if (!err.errorNotified) {
876
+ err.errorNotified = true;
877
+ await this.notify(false, AUTH_ERROR_NOTIFY, {
878
+ response: err.oauthRequest?.response?.error?.message || err.response,
879
+ serverResponseCode: 'TokenGenerationError'
880
+ });
881
+ }
882
+ }
883
+
708
884
  /**
709
885
  * Sets error state and manages error tracking/notifications
710
886
  * Implements logic to disable IMAP after repeated authentication failures
@@ -733,8 +909,18 @@ class BaseClient {
733
909
 
734
910
  let shouldNotify = true;
735
911
 
736
- // Store current error state
737
- await this.redis.hSetExists(this.getAccountKey(), 'lastErrorState', JSON.stringify(data));
912
+ // Store current error state. The event is recorded beside it rather than inside it: `data`
913
+ // is the webhook payload and a published response shape, and notifyAuthenticationSuccess()
914
+ // needs to know whether the run that is ending was an authentication failure or a
915
+ // connection one
916
+ const stateTxn = createTransaction(this.redis, { logger: this.logger });
917
+ stateTxn.add('hSetExists', this.getAccountKey(), 'lastErrorState', JSON.stringify(data));
918
+ stateTxn.add('hSetExists', this.getAccountKey(), LAST_ERROR_EVENT_FIELD, event);
919
+ // Throws rather than reporting the failure in a return value nobody reads: an error that
920
+ // was not stored is one the next login announces a recovery from, one the repeat check
921
+ // below cannot suppress, and one the auth-failure safety net never counts towards a park
922
+ await stateTxn.execOrThrow();
923
+
738
924
  await emitChangeEvent(this.logger, this.account, 'state', event, { error: data });
739
925
 
740
926
  // Check if this is a repeat of the same error
@@ -760,7 +946,12 @@ class BaseClient {
760
946
  const txn = createTransaction(this.redis, { logger: this.logger });
761
947
  txn.add('hSetExists', this.getAccountKey(), 'lastError:errorCount', 1);
762
948
  txn.add('hSetExists', this.getAccountKey(), 'lastError:first', new Date().toISOString());
763
- await txn.exec();
949
+ const { error } = await txn.exec();
950
+ if (error) {
951
+ // Not fatal - the caller still reports the error - but the timestamp is what the
952
+ // auth-failure park measures its three days from, so a lost write is worth saying
953
+ this.logger.error({ msg: 'Redis error while resetting error state counters', error });
954
+ }
764
955
  } else {
765
956
  let errorCount;
766
957
  let firstError;
@@ -1006,44 +1197,17 @@ class BaseClient {
1006
1197
  // one instead of renewing from a stored refresh token (it has none). The app is still
1007
1198
  // resolved above, because the caller needs it for the provider's host and port.
1008
1199
  if (await useAuthServerForOAuth2(accountData.oauth2, ctx.logger, { account: accountObject.account, target })) {
1009
- try {
1010
- let authData = await resolveCredentials(accountObject.account, target);
1011
- // The auth server owns the credentials, but a shared mailbox is still addressed by
1012
- // the configured delegatedUser - same precedence as the stored-token path above.
1013
- return {
1014
- oauth2User: accountData.oauth2.auth.delegatedUser || authData.user,
1015
- accessToken: authData.accessToken,
1016
- oauth2App
1017
- };
1018
- } catch (err) {
1019
- // A transient failure to reach the auth server is a connection problem, not a
1020
- // rejected credential. Reporting it as an authentication error would webhook every
1021
- // account on the instance and park them in an error state over a brief blip.
1022
- if (isTransientNetworkError(err)) {
1023
- ctx.logger.warn({
1024
- msg: 'Network error while resolving credentials from the authentication server',
1025
- account: accountObject.account,
1026
- target,
1027
- code: err.code,
1028
- err
1029
- });
1030
- throw err;
1031
- }
1032
-
1033
- err.authenticationFailed = true;
1034
- await ctx.notify(false, AUTH_ERROR_NOTIFY, {
1035
- response: err.message,
1036
- serverResponseCode: 'HTTPRequestError'
1037
- });
1038
- ctx.logger.error({
1039
- msg: 'Failed to resolve OAuth2 credentials from the authentication server',
1040
- account: accountObject.account,
1041
- target,
1042
- err
1043
- });
1044
- ctx.state = AUTH_ERROR_NOTIFY;
1045
- throw err;
1046
- }
1200
+ // Bound to accountObject rather than to this client: a shared mailbox opened through a
1201
+ // delegated account draws its token from the delegating account's record
1202
+ let authData = await resolveAuthServerCredentials(accountObject.account, target, ctx);
1203
+
1204
+ // The auth server owns the credentials, but a shared mailbox is still addressed by
1205
+ // the configured delegatedUser - same precedence as the stored-token path above.
1206
+ return {
1207
+ oauth2User: accountData.oauth2.auth.delegatedUser || authData.user,
1208
+ accessToken: authData.accessToken,
1209
+ oauth2App
1210
+ };
1047
1211
  }
1048
1212
 
1049
1213
  // Check if token needs refresh (with 30 second buffer)
@@ -1056,12 +1220,17 @@ class BaseClient {
1056
1220
  });
1057
1221
  accessToken = accountData.oauth2.accessToken;
1058
1222
  } catch (err) {
1059
- // Transient network errors are not authentication failures
1060
- if (isTransientNetworkError(err)) {
1223
+ // A token endpoint that could not be reached, or that answered 429 or a 5xx, has not
1224
+ // refused the refresh token. Microsoft and Google both throttle and fail this
1225
+ // endpoint often enough that treating it as an authentication failure produced a
1226
+ // steady stream of authenticationError / authenticationSuccess pairs and parked
1227
+ // otherwise healthy accounts
1228
+ if (isTransientCredentialError(err)) {
1061
1229
  ctx.logger.warn({
1062
1230
  msg: 'Network error during OAuth2 token refresh',
1063
1231
  account: accountObject.account,
1064
1232
  code: err.code,
1233
+ status: credentialErrorStatus(err) || undefined,
1065
1234
  err
1066
1235
  });
1067
1236
  // Do not mark as authenticationFailed, let the caller handle as a connection error
@@ -1082,7 +1251,7 @@ class BaseClient {
1082
1251
  account: accountObject.account,
1083
1252
  err
1084
1253
  });
1085
- ctx.state = 'authenticationError';
1254
+ ctx.state = ACCOUNT_STATES.AUTHENTICATION_ERROR;
1086
1255
  throw err;
1087
1256
  }
1088
1257
  } else {
@@ -3743,7 +3912,6 @@ module.exports = {
3743
3912
  BaseClient,
3744
3913
  metricsMeta: postMetrics,
3745
3914
  applyReferenceRecipients,
3746
- isTransientNetworkError,
3747
3915
  markRejectedAccessToken,
3748
3916
  renewRejectedAccessToken
3749
3917
  };
@@ -0,0 +1,118 @@
1
+ 'use strict';
2
+
3
+ // Where EmailEngine decides whether a failed attempt to obtain a credential means "the credential
4
+ // was refused" or "the service that holds it is having a bad minute". Getting that wrong is
5
+ // expensive: a refusal webhooks `authenticationError`, parks the account in an error state and
6
+ // stops the API clients retrying, and then the next attempt contradicts it with
7
+ // `authenticationSuccess`. Microsoft and Google throttle and 5xx their token endpoints often
8
+ // enough, and one authentication server is shared by every account on an instance, for that to be
9
+ // a steady stream of events and parked accounts on a busy deployment.
10
+ //
11
+ // Its own module rather than a corner of base-client.js because both sides of the fence need it:
12
+ // base-client owns the IMAP and API credential paths, message-builder owns the SMTP one, and
13
+ // base-client already imports message-builder - so there is no direction in which one could
14
+ // require the other.
15
+
16
+ const { resolveCredentials } = require('../tools');
17
+ const { AUTH_ERROR_NOTIFY, TRANSIENT_NETWORK_CODES } = require('../consts');
18
+ const { ACCOUNT_STATES } = require('../account/account-state');
19
+
20
+ /**
21
+ * Failing to reach a remote endpoint is a connection problem, not a rejected credential. Both
22
+ * OAuth2 credential sources (EmailEngine's own token refresh and an external authentication
23
+ * server) use this to avoid reporting an unreachable host as an authentication error, and the API
24
+ * transports use it to decide which failed requests to repeat. undici reports a connection failure
25
+ * as a generic TypeError ("fetch failed") with the real DNS/socket error attached as err.cause, so
26
+ * the code is looked up there as well
27
+ * @param {Error} err - The error to check
28
+ * @returns {boolean} True if the error is a transient network failure
29
+ */
30
+ function isTransientNetworkError(err) {
31
+ return !!err && (TRANSIENT_NETWORK_CODES.has(err.code) || (!!err.cause && TRANSIENT_NETWORK_CODES.has(err.cause.code)));
32
+ }
33
+
34
+ /**
35
+ * Reads the HTTP status a failed credential request came back with. The OAuth2 clients put it on
36
+ * the error itself and repeat it in the request record they attach; the Graph and Gmail transports
37
+ * only carry the request record, and so does the external authentication server (`authRequest`,
38
+ * attached by resolveCredentials() in lib/tools.js - it must not put an operator's status on
39
+ * err.statusCode, which is read as the status of the API request being served). Boom wrappers are
40
+ * deliberately not consulted: Account.getActiveAccessTokenData() boomifies every renewal failure
41
+ * as 403, which would mask the status the token endpoint actually sent
42
+ * @param {Error} err - The error to read
43
+ * @returns {number} The status, or 0 when the failure never reached a response
44
+ */
45
+ function credentialErrorStatus(err) {
46
+ return Number(err?.statusCode || err?.tokenRequest?.status || err?.oauthRequest?.status || err?.authRequest?.status || 0);
47
+ }
48
+
49
+ /**
50
+ * Whether a failed attempt to obtain a credential means the credential service is unavailable
51
+ * rather than the credential being refused. 408, 429 and every 5xx are the service failing; only a
52
+ * 4xx is the credential itself being rejected (an expired refresh token comes back as 400
53
+ * invalid_grant, a revoked one as 401), which is the case a human has to resolve by
54
+ * re-authorizing the account
55
+ * @param {Error} err - The error to check
56
+ * @returns {boolean} True when the failure is the service's, not the credential's
57
+ */
58
+ function isTransientCredentialError(err) {
59
+ if (isTransientNetworkError(err)) {
60
+ return true;
61
+ }
62
+
63
+ const status = credentialErrorStatus(err);
64
+ return status === 408 || status === 429 || (status >= 500 && status < 600);
65
+ }
66
+
67
+ /**
68
+ * Fetches an account's credentials from the operator's external authentication server and reports
69
+ * a refusal as an authentication error. Shared by every connection path - IMAP, SMTP and the API
70
+ * clients - because they all have to draw the same line: one authentication server serves every
71
+ * account on the instance, so announcing an outage as an authentication failure webhooks and parks
72
+ * the whole fleet at once. A transient failure is rethrown unflagged, and the caller reports it as
73
+ * a connection error and retries.
74
+ *
75
+ * @param {String} account - Account id
76
+ * @param {String} target - Protocol the credentials are for ('imap', 'smtp' or 'api')
77
+ * @param {Object} ctx - What to report the failure on; needs `logger`, `notify` and `state` (an
78
+ * IMAP subconnection passes itself, and its notify() is a no-op, so its failures stay its own)
79
+ * @returns {Promise<Object>} Resolved credentials
80
+ */
81
+ async function resolveAuthServerCredentials(account, target, ctx) {
82
+ try {
83
+ return await resolveCredentials(account, target);
84
+ } catch (err) {
85
+ if (isTransientCredentialError(err)) {
86
+ ctx.logger.warn({
87
+ msg: 'Network error while resolving credentials from the authentication server',
88
+ account,
89
+ target,
90
+ code: err.code,
91
+ status: credentialErrorStatus(err) || undefined,
92
+ err
93
+ });
94
+ throw err;
95
+ }
96
+
97
+ err.authenticationFailed = true;
98
+ await ctx.notify(false, AUTH_ERROR_NOTIFY, {
99
+ response: err.message,
100
+ serverResponseCode: 'HTTPRequestError'
101
+ });
102
+ ctx.logger.error({
103
+ msg: 'Failed to resolve credentials from the authentication server',
104
+ account,
105
+ target,
106
+ err
107
+ });
108
+ ctx.state = ACCOUNT_STATES.AUTHENTICATION_ERROR;
109
+ throw err;
110
+ }
111
+ }
112
+
113
+ module.exports = {
114
+ isTransientNetworkError,
115
+ credentialErrorStatus,
116
+ isTransientCredentialError,
117
+ resolveAuthServerCredentials
118
+ };
@@ -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
  // Gmail API configuration
6
7
  const GMAIL_API_BASE = 'https://gmail.googleapis.com';