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
@@ -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
  }
package/lib/export.js CHANGED
@@ -89,6 +89,31 @@ function parseActiveEntry(entry) {
89
89
  return { account, exportId };
90
90
  }
91
91
 
92
+ const EXPORT_FILE_EXTENSION = '.ndjson.gz';
93
+ const EXPORT_FILE_EXTENSION_ENCRYPTED = '.ndjson.gz.enc';
94
+
95
+ /**
96
+ * Tells whether a stored file path is the export's own file.
97
+ *
98
+ * `filePath` is read back from Redis by the download and delete paths. Nothing but this module
99
+ * writes it, but a path trusted only because it was stored is exactly the field a later bug, or
100
+ * write access to Redis, would use to make the download route serve or the delete route unlink
101
+ * an arbitrary file. The basename is checked rather than the directory, because the export
102
+ * directory setting can change between an export and its download, and an older export still
103
+ * lives where it was written.
104
+ *
105
+ * @param {string} exportId - Export id the record belongs to
106
+ * @param {string} filePath - Stored path
107
+ * @returns {boolean} true when the path names the export's own file
108
+ */
109
+ function isOwnExportFile(exportId, filePath) {
110
+ if (!exportId || typeof filePath !== 'string') {
111
+ return false;
112
+ }
113
+ const base = pathlib.basename(filePath);
114
+ return [EXPORT_FILE_EXTENSION, EXPORT_FILE_EXTENSION_ENCRYPTED].some(ext => base === `${exportId}${ext}`);
115
+ }
116
+
92
117
  function generateExportId() {
93
118
  return EXPORT_ID_PREFIX + crypto.randomBytes(12).toString('hex');
94
119
  }
@@ -278,7 +303,7 @@ class Export {
278
303
 
279
304
  const secret = await getSecret();
280
305
  const isEncrypted = !!secret;
281
- const fileExtension = isEncrypted ? '.ndjson.gz.enc' : '.ndjson.gz';
306
+ const fileExtension = isEncrypted ? EXPORT_FILE_EXTENSION_ENCRYPTED : EXPORT_FILE_EXTENSION;
282
307
  const filePath = pathlib.join(exportPath, `${exportId}${fileExtension}`);
283
308
  const startDate = toTimestamp(options.startDate);
284
309
  const endDate = toTimestamp(options.endDate);
@@ -432,8 +457,10 @@ class Export {
432
457
  if (!isActive) {
433
458
  await redis.multi().del(exportKey).del(queueKey).srem(ACTIVE_EXPORTS_KEY, buildActiveEntry(account, exportId)).exec();
434
459
 
435
- if (data.filePath) {
460
+ if (isOwnExportFile(exportId, data.filePath)) {
436
461
  await fs.promises.unlink(data.filePath).catch(() => {});
462
+ } else if (data.filePath) {
463
+ logger.error({ msg: 'Refusing to delete a file that is not the export file', account, exportId, filePath: data.filePath });
437
464
  }
438
465
  }
439
466
 
@@ -671,6 +698,11 @@ class Export {
671
698
  throw createError('Export file not found', 'FileNotFound', 404);
672
699
  }
673
700
 
701
+ if (!isOwnExportFile(exportId, data.filePath)) {
702
+ logger.error({ msg: 'Refusing to serve a file that is not the export file', account, exportId, filePath: data.filePath });
703
+ throw createError('Export file not found', 'FileNotFound', 404);
704
+ }
705
+
674
706
  try {
675
707
  await fs.promises.access(data.filePath, fs.constants.R_OK);
676
708
  } catch {
@@ -690,6 +722,7 @@ class Export {
690
722
  module.exports = {
691
723
  Export,
692
724
  generateExportId,
725
+ isOwnExportFile,
693
726
  calculateScore,
694
727
  getExportKey,
695
728
  getExportQueueKey,
@@ -0,0 +1,129 @@
1
+ 'use strict';
2
+
3
+ // The Handlebars helpers the admin views render with. Registered on the shared handlebars
4
+ // instance by workers/api.js at startup; kept apart from the worker so a test can register
5
+ // the same helpers and render a template that relies on them (the delivery-test fragment in
6
+ // lib/ui-routes/route-helpers.js is compiled with this instance too).
7
+
8
+ const util = require('util');
9
+
10
+ /**
11
+ * Registers every view helper on the given handlebars instance.
12
+ *
13
+ * @param {Object} handlebars - The handlebars module instance vision renders with
14
+ * @param {Object} options
15
+ * @param {Object} options.gt - Gettext instance for the translation helpers
16
+ */
17
+ function registerHandlebarsHelpers(handlebars, { gt }) {
18
+ handlebars.registerHelper('_', (...args) => {
19
+ let params = args.slice(1, args.length - 1);
20
+
21
+ let locale = params.shift();
22
+
23
+ let localGt = locale ? gt.useLocale(locale) : gt;
24
+
25
+ let translated = localGt.gettext(args[0]);
26
+ if (params.length) {
27
+ translated = util.format(translated, ...params);
28
+ }
29
+
30
+ return new handlebars.SafeString(translated);
31
+ });
32
+
33
+ // HTML-escape a value for safe interpolation into an otherwise-unescaped context - e.g. a
34
+ // dynamic `%s` argument to the SafeString-returning `_` helper. Returns a plain string so
35
+ // the surrounding markup stays live while the value itself is entity-escaped.
36
+ handlebars.registerHelper('escapeHtml', value => handlebars.escapeExpression(value));
37
+
38
+ // Translate Bootstrap-era color names emitted by server code (flash types,
39
+ // systemAlerts levels) into the FlyonUI color vocabulary used by the admin
40
+ // theme, so templates interpolate a single closed set of class suffixes
41
+ // (which the stylesheet safelists). Single translation point - producers
42
+ // keep using "danger" etc.
43
+ handlebars.registerHelper('eeColor', value => (value === 'danger' ? 'error' : value || 'neutral'));
44
+
45
+ // Percent-encode a value for interpolation into a URL path segment. Handlebars escapes for
46
+ // HTML, which leaves "#", "/", "?" and "%" untouched - and an account ID is free text, so
47
+ // href="/admin/accounts/{{account}}" resolves somewhere else entirely for an ID carrying one.
48
+ handlebars.registerHelper('urlpart', value => encodeURIComponent(value === null || value === undefined ? '' : value));
49
+
50
+ // Join string fragments in subexpressions, e.g. building composed partial
51
+ // hash values: text=(concat "Up to " (formatInteger n locale) " lines")
52
+ handlebars.registerHelper('concat', (...args) => args.slice(0, -1).join(''));
53
+
54
+ // Ternary for subexpressions: placeholder=(when hasPass "set..." "")
55
+ handlebars.registerHelper('when', (cond, truthyValue, falsyValue) => (cond ? truthyValue : typeof falsyValue === 'string' ? falsyValue : ''));
56
+
57
+ handlebars.registerHelper('isodate', time => new Date(Number(time)).toISOString());
58
+
59
+ handlebars.registerHelper('ngettext', (msgid, plural, count) => util.format(gt.ngettext(msgid, plural, count), count));
60
+
61
+ handlebars.registerHelper('equals', function (compareVal, baseVal, options) {
62
+ if (baseVal === compareVal) {
63
+ return options.fn(this);
64
+ }
65
+ return options.inverse(this);
66
+ });
67
+
68
+ handlebars.registerHelper('inc', (nr, inc) => Number(nr) + Number(inc));
69
+
70
+ // Delivery-test verdict (SPF/DKIM/DMARC status.result) to the FlyonUI color and icon the
71
+ // results fragment (views/partials/test_send.hbs) shows next to each check
72
+ const STATUS_COLORS = { pass: 'success', softfail: 'warning', fail: 'error', permerror: 'info', temperror: 'info' };
73
+ handlebars.registerHelper('statusColor', result => STATUS_COLORS[result] || 'neutral');
74
+
75
+ handlebars.registerHelper('statusIcon', result => {
76
+ switch (result) {
77
+ case 'pass':
78
+ return 'icon-[tabler--circle-check]';
79
+ case 'neutral':
80
+ case 'none':
81
+ return 'icon-[tabler--circle-off]';
82
+ default:
83
+ return 'icon-[tabler--alert-triangle]';
84
+ }
85
+ });
86
+
87
+ handlebars.registerHelper('json', payload => {
88
+ let res;
89
+ try {
90
+ res = typeof payload === 'undefined' ? 'undefined' : JSON.stringify(payload, false, 2);
91
+ } catch (err) {
92
+ res = util.inspect(payload, false, 4, false);
93
+ }
94
+ // SECURITY: return a plain string (NOT a SafeString) so Handlebars HTML-escapes the
95
+ // output. `payload` can carry attacker-controlled data (e.g. inbound email fields in
96
+ // webhook / pre-processing error logs); wrapping it in a SafeString allowed a stored
97
+ // XSS via a </textarea> breakout in the error-log views (security review H1). In the
98
+ // <textarea> render contexts this is display-identical (the browser decodes entities).
99
+ return res;
100
+ });
101
+
102
+ handlebars.registerHelper('lastVal', (value, separator) => {
103
+ separator = separator || '/';
104
+
105
+ let res = (value || '').toString().split(separator).pop();
106
+
107
+ return new handlebars.SafeString(res);
108
+ });
109
+
110
+ handlebars.registerHelper('formatInteger', (intVal, locale) => {
111
+ if (isNaN(intVal)) {
112
+ // ignore non-numbers
113
+ return intVal;
114
+ }
115
+
116
+ locale = (locale || 'en_US').replace(/_/g, '-');
117
+
118
+ let formatter;
119
+ try {
120
+ formatter = new Intl.NumberFormat(locale, {});
121
+ } catch (err) {
122
+ formatter = new Intl.NumberFormat('en-US', {});
123
+ }
124
+
125
+ return formatter.format(intVal);
126
+ });
127
+ }
128
+
129
+ module.exports = { registerHandlebarsHelpers };