emailengine-app 2.87.2 → 2.88.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 (64) hide show
  1. package/.release-please-manifest.json +1 -1
  2. package/CHANGELOG.md +23 -0
  3. package/ENVIRONMENT.md +26 -23
  4. package/LICENSE_EMAILENGINE.txt +20 -12
  5. package/app.json +3 -3
  6. package/bin/emailengine.js +7 -11
  7. package/data/google-crawlers.json +1 -1
  8. package/data/public_suffix_list.dat +48 -10
  9. package/lib/account.js +69 -49
  10. package/lib/admin-password.js +85 -0
  11. package/lib/api-routes/license-routes.js +9 -0
  12. package/lib/api-token-auth.js +21 -5
  13. package/lib/calendar-event.js +15 -3
  14. package/lib/consts.js +5 -0
  15. package/lib/db.js +1 -0
  16. package/lib/email-client/base-client.js +36 -15
  17. package/lib/email-client/gmail-client.js +20 -6
  18. package/lib/email-client/imap/connection-errors.js +30 -1
  19. package/lib/email-client/imap/session-expiry.js +83 -0
  20. package/lib/email-client/imap-client.js +12 -2
  21. package/lib/email-client/smtp-pool-manager.js +66 -8
  22. package/lib/export.js +147 -22
  23. package/lib/graph-notifications.js +60 -0
  24. package/lib/imap-proxy-auth.js +52 -18
  25. package/lib/imapproxy/imap-core/lib/commands/id.js +4 -2
  26. package/lib/imapproxy/imap-core/lib/imap-command.js +44 -4
  27. package/lib/imapproxy/imap-server.js +10 -1
  28. package/lib/imapproxy/proxy-handoff.js +100 -5
  29. package/lib/license-subscription.js +238 -0
  30. package/lib/oauth/gmail.js +18 -0
  31. package/lib/oauth/outlook-identity.js +54 -12
  32. package/lib/prepared-password.js +38 -0
  33. package/lib/queue-browser/index.js +6 -6
  34. package/lib/queue-job-actions.js +59 -4
  35. package/lib/read-env-value.js +46 -21
  36. package/lib/redis-url.js +23 -0
  37. package/lib/response-stream.js +69 -1
  38. package/lib/revocation-events.js +79 -0
  39. package/lib/schemas.js +18 -2
  40. package/lib/settings.js +47 -24
  41. package/lib/sso.js +23 -0
  42. package/lib/submit-penalty.js +24 -0
  43. package/lib/submit-processor.js +10 -2
  44. package/lib/tokens.js +6 -0
  45. package/lib/tools.js +86 -15
  46. package/lib/ui-routes/admin-config-routes.js +3 -276
  47. package/lib/ui-routes/auth-routes.js +13 -64
  48. package/lib/ui-routes/license-routes.js +326 -0
  49. package/lib/web-safe-html.js +29 -0
  50. package/lib/webhook-delivery.js +21 -20
  51. package/lib/webhook-penalty.js +18 -17
  52. package/lib/webhooks.js +18 -0
  53. package/package.json +18 -18
  54. package/sbom.json +294 -294
  55. package/scan.js +2 -0
  56. package/server.js +253 -80
  57. package/static/css/flyonui.css +2 -2
  58. package/static/js/ui.js +11 -4
  59. package/static/licenses.html +27 -27
  60. package/translations/messages.pot +17 -17
  61. package/views/config/license.hbs +43 -16
  62. package/views/partials/side_menu.hbs +1 -1
  63. package/workers/api.js +108 -107
  64. package/workers/imap.js +4 -6
package/workers/api.js CHANGED
@@ -1,6 +1,7 @@
1
1
  'use strict';
2
2
 
3
3
  const { parentPort, workerData } = require('worker_threads');
4
+ const { isSuspended } = require('../lib/license-subscription');
4
5
 
5
6
  const packageData = require('../package.json');
6
7
  const config = require('@zone-eu/wild-config');
@@ -42,7 +43,6 @@ const {
42
43
  getBoolean,
43
44
  loadTlsConfig,
44
45
  resolveOAuthErrorStatus,
45
- constantTimeEqual,
46
46
  verifyServiceSignature,
47
47
  SIGNING_PURPOSE,
48
48
  setAdminSession,
@@ -66,10 +66,11 @@ const Accept = require('@hapi/accept');
66
66
  const pathlib = require('path');
67
67
 
68
68
  const crypto = require('crypto');
69
- const { registeredPublishers, openChangeStream } = require('../lib/response-stream');
69
+ const { registeredPublishers, openChangeStream, recheckChangeStreams } = require('../lib/response-stream');
70
+ const { onRevocation } = require('../lib/revocation-events');
70
71
  const { oauth2Apps } = require('../lib/oauth2-apps');
71
72
  const { decodeJwtPayload } = require('../lib/oauth/decode-jwt-payload');
72
- const { resolveOutlookUserInfo } = require('../lib/oauth/outlook-identity');
73
+ const { resolveOutlookUserInfo, readTenantVerifiedDomains } = require('../lib/oauth/outlook-identity');
73
74
  const { resolveOutlookMailbox } = require('../lib/oauth/outlook-mailbox');
74
75
  const { isValidOAuthState } = require('../lib/oauth/state');
75
76
  const { completeAccountSetup } = require('../lib/ui-routes/account-setup');
@@ -153,7 +154,7 @@ const SUPPORTED_LOCALES = locales.map(locale => locale.locale);
153
154
 
154
155
  const FLAG_SORT_ORDER = ['\\Inbox', '\\Flagged', '\\Sent', '\\Drafts', '\\All', '\\Archive', '\\Junk', '\\Trash'];
155
156
 
156
- const { GMAIL_SCOPES, OPENID_SCOPES, workspaceDomainOf } = require('../lib/oauth/gmail');
157
+ const { GMAIL_SCOPES, OPENID_SCOPES, workspaceDomainOf, verifiedEmailOf } = require('../lib/oauth/gmail');
157
158
  const { MAIL_RU_SCOPES } = require('../lib/oauth/mail-ru');
158
159
 
159
160
  const GMAIL_SCOPE_DESCRIPTIONS = {
@@ -179,11 +180,7 @@ function formatScopeDescription(scope) {
179
180
  return shortName.replace(/\./g, ' ').replace(/\b\w/g, c => c.toUpperCase());
180
181
  }
181
182
 
182
- // The two MS Graph subscription routes are unauthenticated and deliberately carry no payload
183
- // schema: they must answer 202 to anything, because a 400 would make Graph tear the subscription
184
- // down, and the validation handshake posts an empty body. So the payload is arbitrary JSON and
185
- // every read of it has to be defensive.
186
- const graphNotificationEntries = payload => (Array.isArray(payload && payload.value) ? payload.value.filter(entry => entry && typeof entry === 'object') : []);
183
+ const { graphNotificationEntries, partitionGraphEntries, logRejectedGraphEntries, logUnknownGraphSubscription } = require('../lib/graph-notifications');
187
184
 
188
185
  const SMTP_TEST_HOST = 'https://api.nodemailer.com';
189
186
 
@@ -210,6 +207,9 @@ const USE_OIDC_AUTH = sso.USE_OIDC_AUTH;
210
207
  const oidcAllowList = sso.parseAllowList(sso.OIDC_ALLOWED_USERS);
211
208
  const oidcAllowGroups = sso.parseGroupList(sso.OIDC_ALLOWED_GROUPS);
212
209
 
210
+ // Bound to this instance's allow-lists; see sso.ssoSessionAdmitted()
211
+ const ssoSessionAdmitted = session => sso.ssoSessionAdmitted(session, oidcAllowList, oidcAllowGroups);
212
+
213
213
  const EENGINE_TIMEOUT = getDuration(readEnvValue('EENGINE_TIMEOUT') || config.service.commandTimeout) || DEFAULT_EENGINE_TIMEOUT;
214
214
  const MAX_ATTACHMENT_SIZE = getByteSize(readEnvValue('EENGINE_MAX_SIZE') || config.api.maxSize) || DEFAULT_MAX_ATTACHMENT_SIZE;
215
215
 
@@ -454,6 +454,11 @@ parentPort.on('message', message => {
454
454
  mcpListen.publishAccountChange(message, logger);
455
455
  }
456
456
 
457
+ if (message && message.cmd === 'licenseState') {
458
+ // the main thread suspended or resumed the license: answer API requests accordingly now
459
+ refreshPreconditions().catch(err => logger.error({ msg: 'Failed to refresh the license prechecks', err }));
460
+ }
461
+
457
462
  if (message && message.cmd === 'settings') {
458
463
  // the API reference memoizes serviceUrl, which its code samples embed
459
464
  clearServiceUrlCache();
@@ -475,6 +480,19 @@ parentPort.on('message', message => {
475
480
  // by the onPreResponse extension (registerResponseExtensions)
476
481
  let assertPreconditionResult;
477
482
 
483
+ /**
484
+ * Runs the license prechecks and records the result the onPreResponse extension acts on
485
+ * @returns {Promise<void>}
486
+ */
487
+ async function refreshPreconditions() {
488
+ try {
489
+ await runPrechecks(redis);
490
+ assertPreconditionResult = false;
491
+ } catch (err) {
492
+ assertPreconditionResult = Boom.boomify(err, { statusCode: err.statusCode || 500 });
493
+ }
494
+ }
495
+
478
496
  /**
479
497
  * Builds the hapi server, with the API TLS context when the API is served over HTTPS
480
498
  * @returns {Promise<Object>} The server, the certificate handler, the API TLS context and the
@@ -801,6 +819,7 @@ function registerApiTokenAuth(server) {
801
819
  redis,
802
820
  checkRateLimit,
803
821
  sessionPasswordVersion,
822
+ sessionAdmitted: ssoSessionAdmitted,
804
823
  adminAccessAddresses: ADMIN_ACCESS_ADDRESSES,
805
824
  logger
806
825
  })
@@ -877,34 +896,24 @@ async function registerSessionAuth(server) {
877
896
  switch (session.provider) {
878
897
  case 'okta':
879
898
  case 'oidc': {
880
- if (session.profile && session.profile.id) {
881
- let profile = session.profile;
882
-
883
- // Re-check OIDC authorization (email + group allow-lists) on every request
884
- // so changes to OIDC_ALLOWED_USERS/OIDC_ALLOWED_GROUPS (after a restart)
885
- // take effect without waiting out the existing session cookie. Okta has no
886
- // allow-list.
887
- if (session.provider === 'oidc' && !sso.isAuthorized(profile, oidcAllowList, oidcAllowGroups)) {
888
- return { isValid: false };
889
- }
890
-
891
- return {
892
- isValid: true,
893
- credentials: {
894
- enabled: true,
895
- user: profile.username
896
- },
897
- // Expose the SSO provider on artifacts so the "SSO users can't manage
898
- // local password/TOTP/passkeys" guards in the UI routes fire. idToken is
899
- // carried for OIDC RP-initiated logout (undefined for Okta).
900
- artifacts: {
901
- provider: session.provider,
902
- profile,
903
- idToken: session.idToken
904
- }
905
- };
899
+ if (!ssoSessionAdmitted(session)) {
900
+ return { isValid: false };
906
901
  }
907
- return { isValid: false };
902
+ return {
903
+ isValid: true,
904
+ credentials: {
905
+ enabled: true,
906
+ user: session.profile.username
907
+ },
908
+ // Expose the SSO provider on artifacts so the "SSO users can't manage
909
+ // local password/TOTP/passkeys" guards in the UI routes fire. idToken is
910
+ // carried for OIDC RP-initiated logout (undefined for Okta).
911
+ artifacts: {
912
+ provider: session.provider,
913
+ profile: session.profile,
914
+ idToken: session.idToken
915
+ }
916
+ };
908
917
  }
909
918
  }
910
919
 
@@ -1753,41 +1762,26 @@ function registerOutlookNotificationRoute(server) {
1753
1762
  const notificationEntries = graphNotificationEntries(request.payload);
1754
1763
 
1755
1764
  if (!accountData.outlookSubscription) {
1756
- request.logger.warn({
1757
- msg: 'Subscription not found for account',
1758
- account: request.query.account,
1759
- subscriptionIds: notificationEntries.map(entry => entry.subscriptionId)
1760
- });
1765
+ logUnknownGraphSubscription(request, notificationEntries);
1761
1766
  return h.response(Buffer.alloc(0)).code(202);
1762
1767
  }
1763
1768
 
1764
1769
  const outlookSubscription = accountData.outlookSubscription;
1765
1770
 
1766
- const events = [];
1767
- for (let entry of notificationEntries) {
1768
- // enumerate and queue all entries
1769
- const subscriptionIdMatch = entry.subscriptionId === outlookSubscription.id;
1770
- const clientStateMatch = constantTimeEqual(entry.clientState, outlookSubscription.clientState);
1771
- if (!subscriptionIdMatch || !clientStateMatch) {
1772
- // Security: Log webhook validation failures - could indicate spoofed notifications
1773
- request.logger.warn({
1774
- msg: 'Webhook validation failed - potential security issue',
1775
- securityEvent: 'webhook_validation_failure',
1776
- account: request.query.account,
1777
- subscriptionIdMatch,
1778
- clientStateMatch,
1779
- receivedSubscriptionId: entry.subscriptionId,
1780
- changeType: entry.changeType,
1781
- resource: entry.resource
1782
- });
1783
- continue;
1784
- }
1785
-
1786
- events.push({
1787
- type: entry.changeType,
1788
- message: entry.resourceData && entry.resourceData.id
1789
- });
1790
- }
1771
+ const { valid, rejected } = partitionGraphEntries(notificationEntries, outlookSubscription, entry => ({
1772
+ changeType: entry.changeType,
1773
+ resource: entry.resource
1774
+ }));
1775
+ const events = valid.map(entry => ({
1776
+ type: entry.changeType,
1777
+ message: entry.resourceData && entry.resourceData.id
1778
+ }));
1779
+
1780
+ // Security: log webhook validation failures - could indicate spoofed notifications
1781
+ logRejectedGraphEntries(request, rejected, {
1782
+ msg: 'Webhook validation failed - potential security issue',
1783
+ securityEvent: 'webhook_validation_failure'
1784
+ });
1791
1785
 
1792
1786
  if (events.length) {
1793
1787
  await accountObject.pushQueueEvents(events);
@@ -1858,11 +1852,7 @@ function registerOutlookLifecycleRoute(server) {
1858
1852
  const lifecycleEntries = graphNotificationEntries(request.payload);
1859
1853
 
1860
1854
  if (!accountData.outlookSubscription) {
1861
- request.logger.warn({
1862
- msg: 'Subscription not found for account',
1863
- account: request.query.account,
1864
- subscriptionIds: lifecycleEntries.map(entry => entry.subscriptionId)
1865
- });
1855
+ logUnknownGraphSubscription(request, lifecycleEntries);
1866
1856
  return h.response(Buffer.alloc(0)).code(202);
1867
1857
  }
1868
1858
 
@@ -1872,7 +1862,8 @@ function registerOutlookLifecycleRoute(server) {
1872
1862
  // concurrent handlers racing (e.g., two subscriptionRemoved entries)
1873
1863
  const seenLifecycleEvents = new Set();
1874
1864
 
1875
- for (let entry of lifecycleEntries) {
1865
+ const { valid, rejected } = partitionGraphEntries(lifecycleEntries, outlookSubscription, entry => ({ lifecycleEvent: entry.lifecycleEvent }));
1866
+ for (let entry of valid) {
1876
1867
  request.logger.debug({
1877
1868
  msg: 'MS Graph subscription event',
1878
1869
  type: 'lifecycle',
@@ -1881,23 +1872,6 @@ function registerOutlookLifecycleRoute(server) {
1881
1872
  subscriptionId: entry.subscriptionId
1882
1873
  });
1883
1874
 
1884
- // enumerate and queue all entries
1885
- const subscriptionIdMatch = entry.subscriptionId === outlookSubscription.id;
1886
- const clientStateMatch = constantTimeEqual(entry.clientState, outlookSubscription.clientState);
1887
- if (!subscriptionIdMatch || !clientStateMatch) {
1888
- // Security: Log lifecycle webhook validation failures - could indicate spoofed notifications
1889
- request.logger.warn({
1890
- msg: 'Lifecycle webhook validation failed - potential security issue',
1891
- securityEvent: 'lifecycle_webhook_validation_failure',
1892
- account: request.query.account,
1893
- subscriptionIdMatch,
1894
- clientStateMatch,
1895
- receivedSubscriptionId: entry.subscriptionId,
1896
- lifecycleEvent: entry.lifecycleEvent
1897
- });
1898
- continue;
1899
- }
1900
-
1901
1875
  // Route recognized lifecycle events to the IMAP worker
1902
1876
  // so the live client with its OAuth state handles them
1903
1877
  if (entry.lifecycleEvent === 'reauthorizationRequired' || entry.lifecycleEvent === 'subscriptionRemoved' || entry.lifecycleEvent === 'missed') {
@@ -1945,6 +1919,12 @@ function registerOutlookLifecycleRoute(server) {
1945
1919
  }
1946
1920
  }
1947
1921
 
1922
+ // Security: log lifecycle webhook validation failures - could indicate spoofed notifications
1923
+ logRejectedGraphEntries(request, rejected, {
1924
+ msg: 'Lifecycle webhook validation failed - potential security issue',
1925
+ securityEvent: 'lifecycle_webhook_validation_failure'
1926
+ });
1927
+
1948
1928
  return h.response(Buffer.alloc(0)).code(202);
1949
1929
  },
1950
1930
  options: {
@@ -2092,8 +2072,9 @@ async function resolveGmailUserEmail(flow, r, grantedScopes) {
2092
2072
  if (r.id_token && !idTokenPayload) {
2093
2073
  request.logger.warn({ msg: 'Failed to decode Gmail ID token' });
2094
2074
  }
2095
- if (idTokenPayload && typeof idTokenPayload.email === 'string' && isEmail(idTokenPayload.email)) {
2096
- userEmail = idTokenPayload.email;
2075
+ const idTokenEmail = verifiedEmailOf(idTokenPayload);
2076
+ if (idTokenEmail) {
2077
+ userEmail = idTokenEmail;
2097
2078
  userName = idTokenPayload.name || null;
2098
2079
  request.logger.info({ msg: 'Extracted user info from ID token', userEmail, userName });
2099
2080
  }
@@ -2244,6 +2225,11 @@ async function resolveOutlookCallbackUser(flow, r) {
2244
2225
  }
2245
2226
 
2246
2227
  userInfo = resolveOutlookUserInfo({ profile: profileRes });
2228
+ if (profileRes && profileRes.mail && !userInfo.verifiedIdentities.includes(profileRes.mail)) {
2229
+ // A mailbox address outside the login's domain counts only in a domain the tenant verified
2230
+ const verifiedDomains = await readTenantVerifiedDomains(oAuth2Client, r.access_token, request.logger);
2231
+ userInfo = resolveOutlookUserInfo({ profile: profileRes, verifiedDomains });
2232
+ }
2247
2233
 
2248
2234
  request.logger.info({
2249
2235
  msg: 'User profile returned by MS Graph API',
@@ -2266,8 +2252,10 @@ async function completeOutlookCallback(flow) {
2266
2252
 
2267
2253
  const userInfo = await resolveOutlookCallbackUser(flow, r);
2268
2254
 
2255
+ // The login is the user principal name and nothing else: it used to fall back to the account
2256
+ // address, which could only come from client_info, a value the browser chooses
2269
2257
  const authData = {
2270
- user: userInfo.username || userInfo.email
2258
+ user: userInfo.username
2271
2259
  };
2272
2260
 
2273
2261
  if (!authData.user) {
@@ -2670,7 +2658,6 @@ function registerViews(server) {
2670
2658
  flash(redis, request),
2671
2659
  settings.getMulti(
2672
2660
  'upgrade',
2673
- 'subexp',
2674
2661
  'webhookErrorFlag',
2675
2662
  'webhooksEnabled',
2676
2663
  'disableTokens',
@@ -2693,7 +2680,6 @@ function registerViews(server) {
2693
2680
 
2694
2681
  const {
2695
2682
  upgrade: upgradeInfo,
2696
- subexp,
2697
2683
  webhookErrorFlag,
2698
2684
  webhooksEnabled,
2699
2685
  disableTokens,
@@ -2769,15 +2755,23 @@ function registerViews(server) {
2769
2755
  });
2770
2756
  }
2771
2757
 
2772
- if (subexp && !(request.app.licenseInfo && request.app.licenseInfo.details && request.app.licenseInfo.details.lt)) {
2773
- let delayMs = new Date(subexp) - Date.now();
2774
- let expiresDays = Math.max(Math.ceil(delayMs / (24 * 3600 * 1000)), 0);
2775
-
2758
+ // The subscription behind the license (lib/license-subscription.js): paused, or a date it pauses on
2759
+ let licenseSubscription = request.app.licenseInfo && request.app.licenseInfo.subscription;
2760
+ if (isSuspended(request.app.licenseInfo)) {
2761
+ systemAlerts.push({
2762
+ url: '/admin/config/license',
2763
+ level: 'danger',
2764
+ icon: 'icon-[tabler--player-pause]',
2765
+ message: 'EmailEngine is paused: the subscription behind the license key is not in good standing'
2766
+ });
2767
+ } else if (licenseSubscription) {
2776
2768
  systemAlerts.push({
2777
2769
  url: '/admin/config/license',
2778
2770
  level: 'danger',
2779
2771
  icon: 'icon-[tabler--alert-triangle]',
2780
- message: `The license key needs to be renewed or replaced in ${expiresDays} day${expiresDays !== 1 ? 's' : ''}`
2772
+ message: `Subscription payment overdue: EmailEngine pauses in ${licenseSubscription.days} day${
2773
+ licenseSubscription.days !== 1 ? 's' : ''
2774
+ } unless it is paid`
2781
2775
  });
2782
2776
  }
2783
2777
 
@@ -2802,7 +2796,8 @@ function registerViews(server) {
2802
2796
  });
2803
2797
  }
2804
2798
 
2805
- if (!request.app.licenseInfo || !request.app.licenseInfo.active) {
2799
+ // a paused license is still registered, and the alert above says why it is not active
2800
+ if (!request.app.licenseInfo || (!request.app.licenseInfo.active && !request.app.licenseInfo.details)) {
2806
2801
  systemAlerts.push({
2807
2802
  url: '/admin/config/license',
2808
2803
  level: 'warning',
@@ -2904,7 +2899,11 @@ function registerResponseExtensions(server) {
2904
2899
  const preResponse = async (request, h) => {
2905
2900
  let response = request.response;
2906
2901
 
2907
- if (assertPreconditionResult && request.route && request.route.settings && request.route.settings.tags && request.route.settings.tags.includes('api')) {
2902
+ // A route marked licensePrecheck: false (the license routes) stays open, so an instance without
2903
+ // a working license can still report its state and register a key through the API
2904
+ let routeSettings = (request.route && request.route.settings) || {};
2905
+ let preconditionApplies = (routeSettings.tags || []).includes('api') && !(routeSettings.plugins && routeSettings.plugins.licensePrecheck === false);
2906
+ if (assertPreconditionResult && preconditionApplies) {
2908
2907
  response = assertPreconditionResult;
2909
2908
  }
2910
2909
 
@@ -3145,12 +3144,7 @@ function scheduleCertificateReconciler(certHandler) {
3145
3144
  // switched on, which is what the checkbox used to be; see listenersServeTls() there.
3146
3145
  setInterval(() => {
3147
3146
  async function handler() {
3148
- try {
3149
- await runPrechecks(redis);
3150
- assertPreconditionResult = false;
3151
- } catch (err) {
3152
- assertPreconditionResult = Boom.boomify(err);
3153
- }
3147
+ await refreshPreconditions();
3154
3148
 
3155
3149
  if (!IS_PRIMARY_API_WORKER) {
3156
3150
  return;
@@ -3194,6 +3188,13 @@ const init = async () => {
3194
3188
 
3195
3189
  registerRequestEvents(server);
3196
3190
 
3191
+ // A revoked token, a deleted account or a changed session ends the change streams and MCP
3192
+ // listen streams it opened now rather than at their next periodic re-check
3193
+ onRevocation(() => {
3194
+ recheckChangeStreams().catch(err => logger.error({ msg: 'Change stream re-check failed', err }));
3195
+ mcpListen.recheckListenStreams().catch(err => logger.error({ msg: 'MCP listen stream re-check failed', err }));
3196
+ });
3197
+
3197
3198
  registerStaticPageRoutes(server);
3198
3199
  registerStaticFilesRoute(server);
3199
3200
  registerHealthRoute(server);
package/workers/imap.js CHANGED
@@ -6,6 +6,7 @@ const config = require('@zone-eu/wild-config');
6
6
  const logger = require('../lib/logger');
7
7
 
8
8
  const { REDIS_PREFIX } = require('../lib/consts');
9
+ const { assignRelayStatus } = require('../lib/email-client/imap/connection-errors');
9
10
 
10
11
  const { getDuration, getBoolean, emitChangeEvent, readEnvValue, hasEnvValue, threadStats } = require('../lib/tools');
11
12
 
@@ -22,7 +23,6 @@ const { redis, notifyQueue, submitQueue, watchRedisReconnect } = require('../lib
22
23
  const { sendToMessagePort, MessagePortWritable } = require('../lib/message-port-stream');
23
24
  const { describeRpcCommand } = require('../lib/worker-rpc-error');
24
25
  const { createRpcClient, respond, isCall } = require('../lib/worker-rpc');
25
- const { ImapFlowErrorCode } = require('imapflow');
26
26
  const settings = require('../lib/settings');
27
27
  const msgpack = require('../lib/msgpack');
28
28
 
@@ -1139,11 +1139,9 @@ parentPort.on('message', message => {
1139
1139
  // 503 is excluded from the error branch on purpose: both "no active handler" and
1140
1140
  // IMAPConnectionClosing carry it, and a worker taking over accounts answers every
1141
1141
  // in-flight command with one until the reassignment settles.
1142
- if (err && err.code === ImapFlowErrorCode.ETHROTTLE && !err.statusCode) {
1143
- // ImapFlow gave up after the server throttled every retry: the caller should
1144
- // back off, the same answer a throttled Gmail or Graph request gets
1145
- err.statusCode = 429;
1146
- }
1142
+ // ImapFlow's codes for "throttled" and "the connection went away" carry no HTTP
1143
+ // status of their own (429 and 503, see assignRelayStatus())
1144
+ assignRelayStatus(err);
1147
1145
  let isServerFault = !err || !err.statusCode || (err.statusCode >= 500 && err.statusCode !== 503);
1148
1146
  logger[isServerFault ? 'error' : 'debug'](Object.assign(describeRpcCommand(message), { msg: 'Command failed', err }));
1149
1147
  }