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
package/lib/consts.js CHANGED
@@ -145,6 +145,13 @@ module.exports = {
145
145
  // carry is the separate, read-only `_authFailureDisabledAt`.
146
146
  AUTH_FAILURE_DISABLED_FIELD: '_authFailureDisabled',
147
147
 
148
+ // Account hash field recording which event wrote the current `lastErrorState`. Both
149
+ // `authenticationError` and `connectError` store their payload there, so without this the
150
+ // recovery path cannot tell them apart. Written next to `lastErrorState` and cleared with it;
151
+ // same leading-underscore convention as AUTH_FAILURE_DISABLED_FIELD, so unserializeAccountData()
152
+ // does not surface it.
153
+ LAST_ERROR_EVENT_FIELD: '_lastErrorEvent',
154
+
148
155
  // The `lastErrorState.description` the safety net stores when it parks an account, and the log
149
156
  // line it writes at the same moment. User-visible copy: reword it freely, nothing matches on it.
150
157
  AUTH_FAILURE_DISABLED_DESCRIPTION: 'IMAP was disabled for the account due to exceeding the authentication error threshold',
@@ -160,16 +167,53 @@ module.exports = {
160
167
 
161
168
  REDIS_BATCH_DELETE_SIZE: 1000,
162
169
 
163
- // When renewal becomes due is derived from each certificate's own lifetime by
164
- // isRenewalDue() in @postalsys/certs, so there is no constant for it here. Let's Encrypt is
165
- // shortening certificates from 90 days to 64 and then 45, and a fixed threshold is correct
166
- // for exactly one lifetime. https://letsencrypt.org/2025/12/02/from-90-to-45
170
+ // When renewal becomes due is decided by @postalsys/certs, so there is no constant for it here.
171
+ // It asks Let's Encrypt through ACME Renewal Information where it can, and otherwise renews two
172
+ // thirds of the way through whatever lifetime the certificate was issued with. A fixed "renew
173
+ // when N days remain" threshold is correct for exactly one lifetime, and Let's Encrypt is
174
+ // shortening them from 90 days to 64 and then 45. https://letsencrypt.org/2025/12/02/from-90-to-45
175
+
176
+ // The ACME account and directory that lib/cert-handler.js hands to every worker.
177
+ //
178
+ // These two only make sense as a pair. The environment names the stored ACME account record and
179
+ // the directory names the CA that issued it, so pointing one at Let's Encrypt staging without
180
+ // moving the other presents an account key the staging CA has never seen, and every request is
181
+ // rejected. Override both or neither. Staging is https://acme-staging-v02.api.letsencrypt.org/directory,
182
+ // which is what to test issuance against: same asynchronous finalization as production, no rate
183
+ // limits worth worrying about, and certificates signed by an untrusted root - which is also why
184
+ // the default here has to stay production. A build that shipped staging by default would hand
185
+ // every IMAP, SMTP and HTTPS client a certificate it refuses.
186
+ ACME_ENVIRONMENT: (process.env.EENGINE_ACME_ENVIRONMENT || '').toString().trim() || 'emailengine',
187
+ ACME_DIRECTORY_URL: (process.env.EENGINE_ACME_DIRECTORY_URL || '').toString().trim() || 'https://acme-v02.api.letsencrypt.org/directory',
188
+
189
+ // Exactly one of the two was overridden, which is the combination the paragraph above says
190
+ // cannot work. Derived here, from the same reads the values themselves come from, so it can
191
+ // never disagree with them; lib/cert-handler.js is what reports it, since nothing in the CA's
192
+ // rejection says why every order failed.
193
+ ACME_OVERRIDE_PARTIAL:
194
+ !!(process.env.EENGINE_ACME_ENVIRONMENT || '').toString().trim() !== !!(process.env.EENGINE_ACME_DIRECTORY_URL || '').toString().trim(),
167
195
 
168
196
  // do not attempt certificate renewal more often than once in 8 hours
169
197
  BLOCK_TLS_RENEW: 8 * 3600 * 1000,
170
198
 
171
- // check if we need to renew the certificate once in an hour
172
- TLS_RENEW_CHECK_INTERVAL: 1 * 3600 * 1000,
199
+ // How often the reconciler looks at the configured hostnames. Most passes do nothing: a valid
200
+ // certificate that was checked within BLOCK_TLS_RENEW is skipped without a call to anyone. The
201
+ // interval is what bounds how long a first certificate, or one whose record was lost, waits for
202
+ // its automatic attempt, which is why it is minutes rather than the hour renewal alone needs.
203
+ TLS_RENEW_CHECK_INTERVAL: 10 * 60 * 1000,
204
+
205
+ // How long a hostname whose last order failed is left alone by the reconciler. The certificate
206
+ // library arms its own failsafe lock on top of this (an hour after the CA answered, a minute
207
+ // after a transport error); this is the outer bound that also covers a name with no record at
208
+ // all, where the library has nothing to lock on.
209
+ TLS_RETRY_AFTER_FAILURE: 15 * 60 * 1000,
210
+
211
+ // Lifetime of a preflight probe token, in seconds. Long enough for a redirect chain and a slow
212
+ // reverse proxy, short enough that a token is not left answering for the rest of the day.
213
+ TLS_PREFLIGHT_TTL: 120,
214
+
215
+ // How long the preflight waits for the challenge path to answer
216
+ TLS_PREFLIGHT_TIMEOUT: 20 * 1000,
173
217
 
174
218
  // default download chunk size 1MB
175
219
  DEFAULT_DOWNLOAD_CHUNK_SIZE: 1000000,
package/lib/db.js CHANGED
@@ -133,6 +133,8 @@ const hSetBiggerScript = fs.readFileSync(pathlib.join(__dirname, 'lua/h-set-bigg
133
133
  const hUpdateBiggerScript = fs.readFileSync(pathlib.join(__dirname, 'lua/h-update-bigger.lua'), 'utf-8');
134
134
  const hSetExistsScript = fs.readFileSync(pathlib.join(__dirname, 'lua/h-set-exists.lua'), 'utf-8');
135
135
  const hSetNewScript = fs.readFileSync(pathlib.join(__dirname, 'lua/h-set-new.lua'), 'utf-8');
136
+ const hSetIfEqualsScript = fs.readFileSync(pathlib.join(__dirname, 'lua/h-set-if-equals.lua'), 'utf-8');
137
+ const hDelIfEqualsScript = fs.readFileSync(pathlib.join(__dirname, 'lua/h-del-if-equals.lua'), 'utf-8');
136
138
  const hSetNewMarkScript = fs.readFileSync(pathlib.join(__dirname, 'lua/h-set-new-mark.lua'), 'utf-8');
137
139
  const hIncrbyExistsScript = fs.readFileSync(pathlib.join(__dirname, 'lua/h-incrby-exists.lua'), 'utf-8');
138
140
  const eeListAddScript = fs.readFileSync(pathlib.join(__dirname, 'lua/ee-list-add.lua'), 'utf-8');
@@ -199,6 +201,16 @@ redis.defineCommand('hSetNew', {
199
201
  lua: hSetNewScript
200
202
  });
201
203
 
204
+ redis.defineCommand('hSetIfEquals', {
205
+ numberOfKeys: 1,
206
+ lua: hSetIfEqualsScript
207
+ });
208
+
209
+ redis.defineCommand('hDelIfEquals', {
210
+ numberOfKeys: 1,
211
+ lua: hDelIfEqualsScript
212
+ });
213
+
202
214
  redis.defineCommand('hSetNewMark', {
203
215
  numberOfKeys: 1,
204
216
  lua: hSetNewMarkScript
@@ -29,6 +29,11 @@ const ALLOWED_PROTOCOLS = new Set(['http:', 'https:']);
29
29
  // request outright)
30
30
  const BODY_HEADERS = new Set(['content-type', 'content-length', 'content-encoding', 'content-language', 'content-location']);
31
31
 
32
+ // Headers that authenticate a request to one specific origin, and so cannot travel to another one.
33
+ // A credential is issued against the host that asked for it; a redirect naming a different host is
34
+ // not a reason to hand it over. fetch() drops these on a cross-origin hop and so does this.
35
+ const CREDENTIAL_HEADERS = new Set(['authorization', 'cookie', 'proxy-authorization']);
36
+
32
37
  function redirectError(message, code) {
33
38
  let err = new Error(message);
34
39
  err.code = code;
@@ -40,7 +45,8 @@ function redirectError(message, code) {
40
45
  *
41
46
  * @param {string} location - Raw Location header
42
47
  * @param {string} base - URL of the response carrying it
43
- * @returns {string} Absolute URL of the next hop
48
+ * @returns {URL} Absolute URL of the next hop. Returned parsed, so the caller can compare origins
49
+ * without building it a second time
44
50
  * @throws {Error} EREDIRECTINVALID for an unparseable target, EREDIRECTSCHEME for a non-web one
45
51
  */
46
52
  function resolveRedirect(location, base) {
@@ -55,17 +61,18 @@ function resolveRedirect(location, base) {
55
61
  throw redirectError(`Redirect from ${base} points at an unsupported scheme (${next.protocol})`, 'EREDIRECTSCHEME');
56
62
  }
57
63
 
58
- return next.toString();
64
+ return next;
59
65
  }
60
66
 
61
67
  /**
62
- * Drops body-describing headers from a plain header object (the only shape the callers pass).
68
+ * Drops a set of headers from a plain header object (the only shape the callers pass).
63
69
  *
64
70
  * @param {Object} [headers] - Header name to value
71
+ * @param {Set} names - Lowercased header names to remove
65
72
  * @returns {Object|undefined} Filtered copy
66
73
  */
67
- function withoutBodyHeaders(headers) {
68
- return headers && Object.fromEntries(Object.entries(headers).filter(([name]) => !BODY_HEADERS.has(name.toLowerCase())));
74
+ function withoutHeaders(headers, names) {
75
+ return headers && Object.fromEntries(Object.entries(headers).filter(([name]) => !names.has(name.toLowerCase())));
69
76
  }
70
77
 
71
78
  /**
@@ -73,8 +80,9 @@ function withoutBodyHeaders(headers) {
73
80
  *
74
81
  * `validateTarget(url)` runs before the first request and before every hop; whatever it throws
75
82
  * ends the fetch. Redirect semantics match fetch(): 303 always becomes a bodyless GET, 301 and 302
76
- * do so for anything but GET and HEAD, 307 and 308 replay the request unchanged. A 3xx without a
77
- * Location is returned as it is, since it is not a redirect anyone can follow.
83
+ * do so for anything but GET and HEAD, 307 and 308 replay the request unchanged, and a hop to
84
+ * another origin drops the credential headers. A 3xx without a Location is returned as it is,
85
+ * since it is not a redirect anyone can follow.
78
86
  *
79
87
  * @param {Function} fetchImpl - fetch implementation (undici fetch)
80
88
  * @param {string} url - Destination URL
@@ -123,10 +131,14 @@ async function fetchWithVettedRedirects(fetchImpl, url, options) {
123
131
  if (res.status === 303 || ((res.status === 301 || res.status === 302) && method !== 'GET' && method !== 'HEAD')) {
124
132
  method = 'GET';
125
133
  body = undefined;
126
- headers = withoutBodyHeaders(headers);
134
+ headers = withoutHeaders(headers, BODY_HEADERS);
135
+ }
136
+
137
+ if (next.origin !== new URL(current).origin) {
138
+ headers = withoutHeaders(headers, CREDENTIAL_HEADERS);
127
139
  }
128
140
 
129
- current = next;
141
+ current = next.toString();
130
142
  }
131
143
  }
132
144
 
@@ -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,21 @@ 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
+ // The repeat check below compares stored forms: JSON drops a key whose value is undefined
917
+ // (serverResponseCode, for a response with no bracketed code) and deepEqual() counts it
918
+ const storedState = JSON.stringify(data);
919
+ const stateTxn = createTransaction(this.redis, { logger: this.logger });
920
+ stateTxn.add('hSetExists', this.getAccountKey(), 'lastErrorState', storedState);
921
+ stateTxn.add('hSetExists', this.getAccountKey(), LAST_ERROR_EVENT_FIELD, event);
922
+ // Throws rather than reporting the failure in a return value nobody reads: an error that
923
+ // was not stored is one the next login announces a recovery from, one the repeat check
924
+ // below cannot suppress, and one the auth-failure safety net never counts towards a park
925
+ await stateTxn.execOrThrow();
926
+
738
927
  await emitChangeEvent(this.logger, this.account, 'state', event, { error: data });
739
928
 
740
929
  // Check if this is a repeat of the same error
@@ -746,7 +935,7 @@ class BaseClient {
746
935
  shouldNotify = false;
747
936
  } else {
748
937
  try {
749
- deepEqual(data, prevLastErrorState);
938
+ deepEqual(JSON.parse(storedState), prevLastErrorState);
750
939
  // nothing changed
751
940
  shouldNotify = false;
752
941
  } catch (err) {
@@ -760,7 +949,12 @@ class BaseClient {
760
949
  const txn = createTransaction(this.redis, { logger: this.logger });
761
950
  txn.add('hSetExists', this.getAccountKey(), 'lastError:errorCount', 1);
762
951
  txn.add('hSetExists', this.getAccountKey(), 'lastError:first', new Date().toISOString());
763
- await txn.exec();
952
+ const { error } = await txn.exec();
953
+ if (error) {
954
+ // Not fatal - the caller still reports the error - but the timestamp is what the
955
+ // auth-failure park measures its three days from, so a lost write is worth saying
956
+ this.logger.error({ msg: 'Redis error while resetting error state counters', error });
957
+ }
764
958
  } else {
765
959
  let errorCount;
766
960
  let firstError;
@@ -1006,44 +1200,17 @@ class BaseClient {
1006
1200
  // one instead of renewing from a stored refresh token (it has none). The app is still
1007
1201
  // resolved above, because the caller needs it for the provider's host and port.
1008
1202
  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
- }
1203
+ // Bound to accountObject rather than to this client: a shared mailbox opened through a
1204
+ // delegated account draws its token from the delegating account's record
1205
+ let authData = await resolveAuthServerCredentials(accountObject.account, target, ctx);
1206
+
1207
+ // The auth server owns the credentials, but a shared mailbox is still addressed by
1208
+ // the configured delegatedUser - same precedence as the stored-token path above.
1209
+ return {
1210
+ oauth2User: accountData.oauth2.auth.delegatedUser || authData.user,
1211
+ accessToken: authData.accessToken,
1212
+ oauth2App
1213
+ };
1047
1214
  }
1048
1215
 
1049
1216
  // Check if token needs refresh (with 30 second buffer)
@@ -1056,12 +1223,17 @@ class BaseClient {
1056
1223
  });
1057
1224
  accessToken = accountData.oauth2.accessToken;
1058
1225
  } catch (err) {
1059
- // Transient network errors are not authentication failures
1060
- if (isTransientNetworkError(err)) {
1226
+ // A token endpoint that could not be reached, or that answered 429 or a 5xx, has not
1227
+ // refused the refresh token. Microsoft and Google both throttle and fail this
1228
+ // endpoint often enough that treating it as an authentication failure produced a
1229
+ // steady stream of authenticationError / authenticationSuccess pairs and parked
1230
+ // otherwise healthy accounts
1231
+ if (isTransientCredentialError(err)) {
1061
1232
  ctx.logger.warn({
1062
1233
  msg: 'Network error during OAuth2 token refresh',
1063
1234
  account: accountObject.account,
1064
1235
  code: err.code,
1236
+ status: credentialErrorStatus(err) || undefined,
1065
1237
  err
1066
1238
  });
1067
1239
  // Do not mark as authenticationFailed, let the caller handle as a connection error
@@ -1082,7 +1254,7 @@ class BaseClient {
1082
1254
  account: accountObject.account,
1083
1255
  err
1084
1256
  });
1085
- ctx.state = 'authenticationError';
1257
+ ctx.state = ACCOUNT_STATES.AUTHENTICATION_ERROR;
1086
1258
  throw err;
1087
1259
  }
1088
1260
  } else {
@@ -3743,7 +3915,6 @@ module.exports = {
3743
3915
  BaseClient,
3744
3916
  metricsMeta: postMetrics,
3745
3917
  applyReferenceRecipients,
3746
- isTransientNetworkError,
3747
3918
  markRejectedAccessToken,
3748
3919
  renewRejectedAccessToken
3749
3920
  };