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
@@ -1,6 +1,7 @@
1
1
  'use strict';
2
2
 
3
- const { BaseClient, metricsMeta, isTransientNetworkError } = require('./base-client');
3
+ const { BaseClient, metricsMeta } = require('./base-client');
4
+ const { isTransientCredentialError } = require('./credential-errors');
4
5
  const { Account } = require('../account');
5
6
  const { checkAccountScopes } = require('../oauth/scope-checker');
6
7
  const settings = require('../settings');
@@ -22,7 +23,7 @@ const { pushHeaderValue } = require('../utils/header-map');
22
23
  const {
23
24
  REDIS_PREFIX,
24
25
  AUTH_ERROR_NOTIFY,
25
- AUTH_SUCCESS_NOTIFY,
26
+ CONNECT_ERROR_NOTIFY,
26
27
  EMAIL_SENT_NOTIFY,
27
28
  OUTLOOK_EXPIRATION_TIME,
28
29
  OUTLOOK_EXPIRATION_RENEW_TIME,
@@ -43,6 +44,12 @@ const MAX_BATCH_SIZE = graphApi.MAX_BATCH_SIZE;
43
44
  // Subscription is renewed automatically. But just in case, check once in an hour
44
45
  const RENEW_WATCH_TTL = 60 * 60 * 1000; // 1h
45
46
 
47
+ // The `serverResponseCode` a failed change subscription is reported with, and the marker that
48
+ // tells the report apart from anything else the account may have stored. Only this client reads
49
+ // it: reportSubscriptionFailure() writes it, clearSubscriptionFailure() lifts it, and
50
+ // isSelfClearedErrorState() is what keeps a login from taking it along
51
+ const SUBSCRIPTION_SETUP_ERROR_CODE = 'SubscriptionSetupError';
52
+
46
53
  // MS Graph folder hierarchy is defined by id/parentFolderId, not by "/" in folder
47
54
  // names. To build an unambiguous, reversible pathName we percent-encode "%" and "/"
48
55
  // inside a single displayName segment, keeping the real "/" as the delimiter BETWEEN
@@ -127,6 +134,10 @@ class OutlookClient extends BaseClient {
127
134
  // MS Graph webhook subscription state (for metrics)
128
135
  // Possible values: 'unset', 'valid', 'expired', 'failed', 'pending'
129
136
  this.subscriptionState = 'unset';
137
+
138
+ // Whether clearSubscriptionFailure() has looked for a report written before this process
139
+ // started. Deliberately not persisted: it asks a question only a restart can raise
140
+ this.storedSubscriptionReportChecked = false;
130
141
  }
131
142
 
132
143
  /**
@@ -295,10 +306,9 @@ class OutlookClient extends BaseClient {
295
306
  try {
296
307
  profileRes = await this.request(`/${this.oauth2UserPath}`, 'get', {});
297
308
  } catch (err) {
298
- if (isTransientNetworkError(err)) {
299
- // The provider could not be reached - a connection problem, not a refused
300
- // credential. Left unflagged so the worker retries init() instead of reporting
301
- // an authentication error that only re-authorization could clear
309
+ if (isTransientCredentialError(err)) {
310
+ // Not a refused credential - left unflagged so the worker retries init() instead of
311
+ // reporting an authentication error only re-authorization could clear
302
312
  throw err;
303
313
  }
304
314
 
@@ -357,56 +367,20 @@ class OutlookClient extends BaseClient {
357
367
  sendOnly: isSendOnly
358
368
  });
359
369
 
370
+ // Before the state flip below - see notifyAuthenticationSuccess(). This used to run after
371
+ // it, which is why a Graph account never announced its first login at all
372
+ await this.notifyAuthenticationSuccess(accountData.oauth2?.auth?.user);
373
+
360
374
  this.state = 'connected';
361
375
  await this.setStateVal();
362
376
 
363
- // Check if this is the first successful connection
364
- let prevConnectedCount = await this.redis.hget(this.getAccountKey(), `state:count:connected`);
365
- let isFirstSuccessfulConnection = prevConnectedCount === '0'; // string zero means the account has been initialized but not yet connected
366
-
367
- let isInitial = !!isFirstSuccessfulConnection;
368
-
369
- if (!isFirstSuccessfulConnection) {
370
- // check if the connection was previously in an errored state
371
- let prevLastErrorState = await this.redis.hget(this.getAccountKey(), 'lastErrorState');
372
- if (prevLastErrorState) {
373
- try {
374
- prevLastErrorState = JSON.parse(prevLastErrorState);
375
- } catch (err) {
376
- // ignore
377
- }
378
- }
379
-
380
- if (prevLastErrorState && typeof prevLastErrorState === 'object' && Object.keys(prevLastErrorState).length) {
381
- // was previously errored
382
- isFirstSuccessfulConnection = true;
383
- }
384
- }
385
-
386
- if (isFirstSuccessfulConnection) {
387
- this.logger.info({ msg: 'Successful login without a previous active session', account: this.account, isInitial, prevActive: false });
388
- await this.notify(false, AUTH_SUCCESS_NOTIFY, {
389
- user: accountData.oauth2?.auth?.user
390
- });
391
- } else {
392
- this.logger.info({ msg: 'Successful login with a previous active session', account: this.account, isInitial, prevActive: true });
393
- }
394
-
395
- // Clear any previous error states
396
- await this.redis.hdel(this.getAccountKey(), 'lastErrorState', 'lastError:errorCount', 'lastError:first');
397
377
  await emitChangeEvent(this.logger, this.account, 'state', this.state);
398
378
 
399
379
  if (!isSendOnly) {
400
380
  // additional operations for full access accounts
401
381
 
402
- // Reset subscription retry counts on reconnect — fresh auth = fresh slate
403
- let storedSub = await this.getStoredSubscription();
404
- if (storedSub.state && (storedSub.state.createRetryCount > 0 || storedSub.state.retryCount > 0)) {
405
- storedSub.state.createRetryCount = 0;
406
- storedSub.state.retryCount = 0;
407
- storedSub.state.error = null;
408
- await this.saveStoredSubscription(storedSub);
409
- }
382
+ // Reset subscription retry counts on reconnect - fresh auth = fresh slate
383
+ await this.resetSubscriptionRetryState();
410
384
 
411
385
  // Set up webhook subscription for real-time updates
412
386
  await this.ensureSubscription();
@@ -3044,6 +3018,125 @@ class OutlookClient extends BaseClient {
3044
3018
  }
3045
3019
  }
3046
3020
 
3021
+ /**
3022
+ * Reports that the account has no working change subscription left to fall back on - and for a
3023
+ * Graph account there is no fallback: unlike the Gmail client there is no polling timer, so a
3024
+ * subscription that cannot be established means the account never sees new mail again. Both the
3025
+ * creation and the renewal paths retry with backoff and then give up; giving up used to write a
3026
+ * log line and nothing else, so the account went on reporting `connected`. A tenant that
3027
+ * disables the Exchange Online service principal (AADSTS500014) hits this without ever failing a
3028
+ * token refresh, so no authentication error fires either - reported in the field after nine
3029
+ * months of accounts looking healthy and syncing nothing.
3030
+ *
3031
+ * Sent as `connectError` rather than `authenticationError` on purpose: the credential is fine,
3032
+ * and re-authorizing does not lift a disabled service principal. It also keeps the failure away
3033
+ * from the auth-failure safety net, which would switch the account off after three days and
3034
+ * offer the operator only a re-authorization that cannot help.
3035
+ *
3036
+ * NB! `connectError` is not in VALID_STATES, so this also makes the account's own operations
3037
+ * (reading a message, moving one) answer 503 until a subscription works again. That is the
3038
+ * intended reading for an account that cannot sync at all, and it is the only reading this
3039
+ * state machine offers - there is no degraded-but-usable state.
3040
+ *
3041
+ * setErrorState() suppresses a repeat of the same code, so a permanently broken tenant produces
3042
+ * one webhook per distinct failure rather than one per renewal cycle
3043
+ * @param {String} stage - 'creation' or 'renewal', for the log line and the fallback message
3044
+ * @param {Object} state - The stored subscription state, carrying the last error text
3045
+ * @param {Number} retryCount - Attempts made, for the log line
3046
+ * @returns {Promise<void>}
3047
+ */
3048
+ async reportSubscriptionFailure(stage, state, retryCount) {
3049
+ this.logger.error({ msg: `Max subscription ${stage} retries exceeded`, account: this.account, retryCount });
3050
+
3051
+ try {
3052
+ await this.notify(false, CONNECT_ERROR_NOTIFY, {
3053
+ response: state?.error || `MS Graph subscription ${stage} failed`,
3054
+ serverResponseCode: SUBSCRIPTION_SETUP_ERROR_CODE
3055
+ });
3056
+ } catch (err) {
3057
+ // Best effort. This is awaited from inside ensureSubscription(), which init() awaits in
3058
+ // turn, so letting a Redis hiccup out of here would fail the whole account setup over a
3059
+ // report about a failure that has already been logged
3060
+ this.logger.error({ msg: 'Failed to report the subscription failure', account: this.account, err });
3061
+ }
3062
+ }
3063
+
3064
+ /**
3065
+ * A failed change subscription is this client's own report to lift. A tenant that disabled the
3066
+ * Exchange Online service principal keeps refreshing tokens and logging in perfectly while no
3067
+ * subscription can be created, so a login says nothing about it and clearing it on one leaves
3068
+ * the account reporting healthy while it syncs nothing
3069
+ * @param {Object} parsedState - The stored `lastErrorState`, parsed
3070
+ * @returns {boolean} True when the stored run is a reported subscription failure
3071
+ */
3072
+ isSelfClearedErrorState(parsedState) {
3073
+ return parsedState?.serverResponseCode === SUBSCRIPTION_SETUP_ERROR_CODE;
3074
+ }
3075
+
3076
+ /**
3077
+ * Lifts the error state reportSubscriptionFailure() left behind, once a subscription is working
3078
+ * again - which is every path that concludes there is a working one, not only a renewal that
3079
+ * had to make a request. A subscription 60 hours from expiry is checked hourly and renewed
3080
+ * once, so an account reported while it had one would have stayed in `connectError` for two
3081
+ * days with notifications arriving the whole time.
3082
+ *
3083
+ * Only touches a failure this client reported, so an unrelated error state is left for whatever
3084
+ * owns it. A report this process wrote is visible in `this.state`; the one way a standing
3085
+ * report is not is a worker that restarted since it was written, which can only be true once
3086
+ * per account per worker - so a healthy account calling this every hourly pass reads the stored
3087
+ * state once and then costs nothing.
3088
+ *
3089
+ * @returns {Promise<void>}
3090
+ */
3091
+ async clearSubscriptionFailure() {
3092
+ if (this.state !== 'connectError' && this.storedSubscriptionReportChecked) {
3093
+ // Nothing of ours to take back
3094
+ return;
3095
+ }
3096
+
3097
+ // Best effort throughout. Both callers report a throw here as a Graph subscription that
3098
+ // could not be renewed or created: it would count against the retry budget and, at the cap,
3099
+ // announce a Redis error text to the operator as the tenant's problem
3100
+ try {
3101
+ const storedValue = await this.redis.hget(this.getAccountKey(), 'lastErrorState');
3102
+ this.storedSubscriptionReportChecked = true;
3103
+
3104
+ let stored;
3105
+ try {
3106
+ stored = storedValue && JSON.parse(storedValue);
3107
+ } catch (err) {
3108
+ stored = null;
3109
+ }
3110
+
3111
+ const isOwnReport = this.isSelfClearedErrorState(stored);
3112
+
3113
+ if (stored && !isOwnReport) {
3114
+ return;
3115
+ }
3116
+
3117
+ if (this.state !== 'connectError' && !isOwnReport) {
3118
+ // Nothing of ours to take back
3119
+ return;
3120
+ }
3121
+
3122
+ // The clear goes first, and it only applies while the error is still the one judged
3123
+ // above: a failure written since then is a different one, and reporting `connected`
3124
+ // over it is exactly the state this whole path exists to stop
3125
+ if (!(await this.clearStoredErrorState(storedValue))) {
3126
+ this.logger.info({ msg: 'Subscription recovered into a newer error state, leaving it alone', account: this.account });
3127
+ return;
3128
+ }
3129
+
3130
+ if (this.state !== 'connected') {
3131
+ this.state = 'connected';
3132
+ await this.setStateVal();
3133
+ await emitChangeEvent(this.logger, this.account, 'state', this.state);
3134
+ }
3135
+ } catch (err) {
3136
+ this.logger.error({ msg: 'Failed to clear the reported subscription failure', account: this.account, err });
3137
+ }
3138
+ }
3139
+
3047
3140
  /**
3048
3141
  * Get OAuth2 access token from account or delegated account
3049
3142
  */
@@ -3051,9 +3144,15 @@ class OutlookClient extends BaseClient {
3051
3144
  let tokenData;
3052
3145
  try {
3053
3146
  tokenData = await (this.delegatedAccountObject || this.accountObject).getActiveAccessTokenData();
3054
- if (!['init', 'connecting', 'connected'].includes(this.state)) {
3055
- // We're in an error state (authenticationError, disconnected, etc.)
3056
- // But we just got a valid token, so we've recovered
3147
+ if (this.state === 'authenticationError') {
3148
+ // A valid token means the credential recovered, so announce it here as well as in
3149
+ // init() - this is also what clears the stored error state, which would otherwise
3150
+ // outlive the error it describes. Deliberately only the authentication error: a
3151
+ // token says nothing about a `connectError` from a subscription that cannot be
3152
+ // established, and treating it as a recovery is what let a tenant with a disabled
3153
+ // service principal keep reporting `connected`
3154
+ await this.notifyAuthenticationSuccess(tokenData.user);
3155
+
3057
3156
  this.state = 'connected';
3058
3157
  await this.setStateVal();
3059
3158
  }
@@ -3068,27 +3167,7 @@ class OutlookClient extends BaseClient {
3068
3167
  }
3069
3168
  } catch (E) {
3070
3169
  if (E.code === 'ETokenRefresh') {
3071
- // Track failed token refresh
3072
- const statusCode = String(E.statusCode || 0);
3073
- metricsMeta({ account: this.account }, this.logger, 'oauth2TokenRefresh', 'inc', {
3074
- status: 'failure',
3075
- provider: this.oAuth2Client?.provider || 'outlook',
3076
- statusCode
3077
- });
3078
-
3079
- // treat as authentication failure
3080
- this.state = 'authenticationError';
3081
- await this.setStateVal();
3082
-
3083
- E.authenticationFailed = true;
3084
-
3085
- if (!E.errorNotified) {
3086
- E.errorNotified = true;
3087
- await this.notify(false, AUTH_ERROR_NOTIFY, {
3088
- response: E.oauthRequest?.response?.error?.message || E.response,
3089
- serverResponseCode: 'TokenGenerationError'
3090
- });
3091
- }
3170
+ await this.reportTokenRefreshFailure(E, this.oAuth2Client?.provider || 'outlook');
3092
3171
  }
3093
3172
 
3094
3173
  throw E;
@@ -3129,38 +3208,72 @@ class OutlookClient extends BaseClient {
3129
3208
  return;
3130
3209
  }
3131
3210
  clearTimeout(this.renewWatchTimer);
3132
- this.renewWatchTimer = setTimeout(async () => {
3211
+ this.renewWatchTimer = setTimeout(() => {
3133
3212
  if (this.closed) {
3134
3213
  return;
3135
3214
  }
3136
3215
 
3137
- try {
3138
- // First try to renew existing subscription
3139
- const renewalResult = await this.renewSubscription({ force: false });
3140
-
3141
- if (!renewalResult.success && (renewalResult.reason === 'expired' || renewalResult.reason === 'no_subscription')) {
3142
- // Check if we've exceeded max creation retries
3143
- let subscriptionData = await this.getStoredSubscription();
3144
- if (subscriptionData?.state?.createRetryCount >= OUTLOOK_MAX_RETRY_ATTEMPTS) {
3145
- this.logger.error({
3146
- msg: 'Max subscription creation retries exceeded, waiting for reconnect',
3147
- account: this.account,
3148
- createRetryCount: subscriptionData.state.createRetryCount
3149
- });
3150
- } else {
3151
- await this.ensureSubscription();
3152
- }
3153
- }
3154
- } catch (err) {
3155
- this.logger.error({ msg: 'Failed to renew MS Graph change subscription', account: this.account, err });
3156
- } finally {
3157
- // restart timer
3158
- this.setupRenewWatchTimer();
3159
- }
3216
+ // Never rejects - the pass reports its own failures
3217
+ this.renewOrCreateSubscription().finally(() => this.setupRenewWatchTimer());
3160
3218
  }, RENEW_WATCH_TTL);
3161
3219
  this.renewWatchTimer.unref();
3162
3220
  }
3163
3221
 
3222
+ /**
3223
+ * Clears the retry counters a failing subscription left on the stored record, so the next
3224
+ * attempt starts with a full fast-retry budget rather than the exhausted one it inherited.
3225
+ * Shared by the two occasions that count as a fresh start: a reconnect, and the hourly pass
3226
+ * @returns {Promise<void>}
3227
+ */
3228
+ async resetSubscriptionRetryState() {
3229
+ let storedSub = await this.getStoredSubscription();
3230
+ if (storedSub.state && (storedSub.state.createRetryCount > 0 || storedSub.state.retryCount > 0)) {
3231
+ storedSub.state.createRetryCount = 0;
3232
+ storedSub.state.retryCount = 0;
3233
+ storedSub.state.error = null;
3234
+ await this.saveStoredSubscription(storedSub);
3235
+ }
3236
+ }
3237
+
3238
+ /**
3239
+ * One pass of the renewal timer: renews the change subscription, and recreates it when there is
3240
+ * nothing left to renew.
3241
+ *
3242
+ * This is the account's only slow retry. The fast ones ensureSubscription() schedules are
3243
+ * capped, so a tenant-side failure - a disabled service principal, a permission an admin
3244
+ * revoked - exhausts them within minutes and leaves the account with no subscription at all.
3245
+ * This pass used to read that count, find it at the cap and give up, waiting for a reconnect
3246
+ * that only a worker restart, an account update or a re-authorization brings; a tenant that
3247
+ * fixed the cause an hour later was never noticed. Unlike the Gmail client there is no poller
3248
+ * behind this to fall back on, so an account left unsubscribed syncs nothing at all while it
3249
+ * waits. The counters are cleared before anything else is attempted, so an hour that could have
3250
+ * recovered gets the fast ladder back instead of one attempt every hour forever - a renewal
3251
+ * ladder as much as a creation one, since a subscription inside the renew window whose retries
3252
+ * are spent is not recreated by this pass at all and would otherwise never get another.
3253
+ *
3254
+ * A failing account is not heard twice, but it is logged twice: reportSubscriptionFailure()
3255
+ * stores the same serverResponseCode every pass, which is what setErrorState() suppresses a
3256
+ * repeat notification on, while the log line it writes recurs hourly. The account stays in
3257
+ * `connectError` until a creation actually succeeds.
3258
+ *
3259
+ * @returns {Promise<void>}
3260
+ */
3261
+ async renewOrCreateSubscription() {
3262
+ try {
3263
+ await this.resetSubscriptionRetryState();
3264
+
3265
+ const renewalResult = await this.renewSubscription({ force: false });
3266
+
3267
+ // Only a subscription there is nothing left to renew is recreated here; any other
3268
+ // failure leaves one in place, and the reset above is what gives it another ladder
3269
+ if (!renewalResult.success && (renewalResult.reason === 'expired' || renewalResult.reason === 'no_subscription')) {
3270
+ await this.ensureSubscription();
3271
+ }
3272
+ } catch (err) {
3273
+ this.logger.error({ msg: 'Failed to renew MS Graph change subscription', account: this.account, err });
3274
+ }
3275
+ }
3276
+
3164
3277
  /**
3165
3278
  * Check if mailbox folder structure has changed using delta API
3166
3279
  * Returns true if changes detected, false otherwise
@@ -3492,6 +3605,8 @@ class OutlookClient extends BaseClient {
3492
3605
  account: this.account
3493
3606
  });
3494
3607
  this.subscriptionState = 'valid';
3608
+ // A subscription that is still good is the same recovery as one just renewed
3609
+ await this.clearSubscriptionFailure();
3495
3610
  return { success: true, reason: 'not_needed' };
3496
3611
  }
3497
3612
 
@@ -3528,6 +3643,7 @@ class OutlookClient extends BaseClient {
3528
3643
 
3529
3644
  await this.saveStoredSubscription(outlookSubscription);
3530
3645
  this.subscriptionState = 'valid';
3646
+ await this.clearSubscriptionFailure();
3531
3647
 
3532
3648
  this.logger.info({
3533
3649
  msg: previousRetryCount > 0 ? 'Subscription renewed successfully after retry' : 'Subscription renewed successfully',
@@ -3579,11 +3695,7 @@ class OutlookClient extends BaseClient {
3579
3695
  retryDelayMs: retryDelay
3580
3696
  });
3581
3697
  } else {
3582
- this.logger.error({
3583
- msg: 'Max subscription renewal retries exceeded',
3584
- account: this.account,
3585
- retryCount
3586
- });
3698
+ await this.reportSubscriptionFailure('renewal', outlookSubscription.state, retryCount);
3587
3699
  }
3588
3700
 
3589
3701
  return { success: false, reason: 'renewal_failed', error: err.message };
@@ -3704,6 +3816,8 @@ class OutlookClient extends BaseClient {
3704
3816
  expirationDateTime: outlookSubscription.expirationDateTime
3705
3817
  });
3706
3818
  this.subscriptionState = 'valid';
3819
+ // A subscription that is still good is the same recovery as one just created
3820
+ await this.clearSubscriptionFailure();
3707
3821
  return;
3708
3822
  }
3709
3823
  }
@@ -3753,6 +3867,7 @@ class OutlookClient extends BaseClient {
3753
3867
  }
3754
3868
  };
3755
3869
  this.subscriptionState = 'valid';
3870
+ await this.clearSubscriptionFailure();
3756
3871
  } else {
3757
3872
  throw new Error('Empty server response');
3758
3873
  }
@@ -3797,11 +3912,9 @@ class OutlookClient extends BaseClient {
3797
3912
  retryDelayMs: retryDelay
3798
3913
  });
3799
3914
  } else {
3800
- this.logger.error({
3801
- msg: 'Max subscription creation retries exceeded',
3802
- account: this.account,
3803
- createRetryCount
3804
- });
3915
+ // End of the fast ladder, not the end of trying: renewOrCreateSubscription()
3916
+ // clears the counters and starts a new one on the next hourly pass
3917
+ await this.reportSubscriptionFailure('creation', outlookSubscription.state, createRetryCount);
3805
3918
  }
3806
3919
  }
3807
3920
  }
@@ -1,6 +1,7 @@
1
1
  'use strict';
2
2
 
3
3
  const { ADDRESS_STRATEGIES } = require('./address-strategies');
4
+ const { PRIVILEGED_SETTINGS_SUMMARY } = require('./privileged-settings');
4
5
 
5
6
  // Per-value documentation for the enums whose values are not self-explanatory. Attached to
6
7
  // the joi schemas below with `.meta({ enumDescriptions })`, which the OpenAPI generator emits
@@ -93,7 +94,9 @@ const ENUM_DESCRIPTIONS = {
93
94
  api: 'Call the REST API',
94
95
  smtp: 'Authenticate against the built-in SMTP submission server',
95
96
  'imap-proxy': 'Authenticate against the built-in IMAP proxy',
96
- mcp: 'Connect AI agents through the MCP endpoint. Admits only the operations the MCP tool set wraps, and is not valid for plain REST calls'
97
+ 'mcp-manage':
98
+ 'Let an AI agent manage this instance through the MCP endpoint: accounts, settings, OAuth2 applications, gateways, tokens, the license. Admits only the operations the management tools wrap, and is not valid for plain REST calls',
99
+ mcp: 'Let an AI agent work with mailbox contents through the MCP endpoint. Admits only the operations the mail tools wrap, and is not valid for plain REST calls'
97
100
  },
98
101
 
99
102
  // The verb axis of a narrowed token. Each operation requires exactly one of these, published
@@ -122,7 +125,14 @@ const ENUM_DESCRIPTIONS = {
122
125
  gateway: 'Manage SMTP gateways, which hold outbound SMTP credentials',
123
126
  events: 'Subscribe to the instance-wide change stream, which covers every account',
124
127
  diagnostics: 'Read statistics and service status',
125
- logs: 'Read the per-account connection log. Entries include the protocol or API trace, so they include folder names and message subjects'
128
+ logs: 'Read the per-account connection log. Entries include the protocol or API trace, so they include folder names and message subjects',
129
+ // The parenthetical is rendered from the list the rule reads, so it cannot fall behind it
130
+ settings: `Read and change instance settings and pause or resume the queues. A write reaches the global webhook target. The keys that would widen a token beyond settings (${PRIVILEGED_SETTINGS_SUMMARY}) are refused to a restricted token, on reads and writes alike`,
131
+ oauth2: 'Manage OAuth2 applications. Client secrets are write-only, and a change can move where the provider sends authorization codes',
132
+ license: 'Read, apply and remove the license key',
133
+ token: 'List, inspect and revoke access tokens and read their audit logs, which record who read which account. Cannot create tokens',
134
+ provisioning:
135
+ 'Add and reconfigure email accounts and SMTP gateways, including where they connect. A stored credential is sent to whatever host the record names after the change'
126
136
  },
127
137
 
128
138
  queueId: {
@@ -13,10 +13,10 @@ const getSecret = require('./get-secret');
13
13
  const { isApiBasedApp } = require('./oauth2-apps');
14
14
  const { validateAuthToken, withAuthFailureBudget, REASON_MESSAGES } = require('./auth-token');
15
15
  const { constantTimeEqual } = require('./tools');
16
+ const { isTransientCredentialError } = require('./email-client/credential-errors');
16
17
 
17
18
  /**
18
- * Tags an error as an IMAP authentication rejection for the proxy client. Shared with the
19
- * server, which raises the same rejection for a credential it could not load.
19
+ * Tags an error as an IMAP authentication rejection for the proxy client.
20
20
  *
21
21
  * @param {Error} err - Error to tag
22
22
  * @returns {Error} the same error
@@ -30,6 +30,59 @@ function failImapAuth(err) {
30
30
 
31
31
  const authenticationFailedError = message => failImapAuth(new Error(message));
32
32
 
33
+ /**
34
+ * Tags an error as a temporary failure the client should retry rather than a rejected password.
35
+ * Deliberately without the authenticationFailed flag: nothing refused the credential, the service
36
+ * that holds it was unreachable. RFC 5530 [UNAVAILABLE] is the code for exactly that, and the
37
+ * response status has to be set explicitly - an error reaching the IMAP server with no `response`
38
+ * is rendered as BAD and counts against the connection's bad-command budget.
39
+ *
40
+ * @param {Error} err - Error to tag
41
+ * @returns {Error} the same error
42
+ */
43
+ function failImapUnavailable(err) {
44
+ err.serverResponseCode = 'UNAVAILABLE';
45
+ err.responseStatus = 'NO';
46
+ return err;
47
+ }
48
+
49
+ /**
50
+ * Decides how a failed attempt to obtain the account's upstream credentials is answered. One
51
+ * authentication server serves every account on the instance, so its bad minute must not reach a
52
+ * desktop client as a wrong password - which is what makes the user retype a working one.
53
+ *
54
+ * @param {Error} err - The credential failure
55
+ * @returns {Error} the same error, tagged with the response to send
56
+ */
57
+ function classifyCredentialFailure(err) {
58
+ return isTransientCredentialError(err) ? failImapUnavailable(err) : failImapAuth(err);
59
+ }
60
+
61
+ /**
62
+ * Whether an error already names the IMAP response to answer the client with, as opposed to being
63
+ * an internal proxy fault. Both a refusal and a temporary failure carry one.
64
+ *
65
+ * @param {Error} err - The error to check
66
+ * @returns {boolean} True when the error carries an IMAP response
67
+ */
68
+ function isImapResponseError(err) {
69
+ return !!err && (!!err.authenticationFailed || err.serverResponseCode === 'AUTHENTICATIONFAILED' || err.serverResponseCode === 'UNAVAILABLE');
70
+ }
71
+
72
+ /**
73
+ * Renders a tagged failure as the error the IMAP server answers the client with. imap-core reads
74
+ * the status off `response`, and an error that carries none is answered BAD, which counts against
75
+ * the connection's bad-command budget instead of telling the client what happened.
76
+ *
77
+ * @param {Error} err - The tagged failure
78
+ * @returns {Error} A new error carrying the response line to send
79
+ */
80
+ function toImapResponseError(err) {
81
+ let error = new Error(`${err.serverResponseCode ? `[${err.serverResponseCode}] ` : ''}${err.responseText || err.message || 'Authentication failed'}`);
82
+ error.response = err.responseStatus || 'NO';
83
+ return error;
84
+ }
85
+
33
86
  /**
34
87
  * Builds the IMAP proxy authentication handler.
35
88
  *
@@ -99,4 +152,6 @@ function createImapProxyAuthHandler({ call }) {
99
152
  };
100
153
  }
101
154
 
102
- module.exports = { createImapProxyAuthHandler, failImapAuth };
155
+ // Only what the proxy server and its tests reach for: the two taggers are reached through
156
+ // classifyCredentialFailure(), which is the decision that has to be made in one place
157
+ module.exports = { createImapProxyAuthHandler, classifyCredentialFailure, isImapResponseError, toImapResponseError };