emailengine-app 2.87.1 → 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 (73) hide show
  1. package/.release-please-manifest.json +1 -1
  2. package/CHANGELOG.md +31 -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/dbsc/index.js +292 -0
  17. package/lib/dbsc/jwt.js +157 -0
  18. package/lib/dbsc/protocol.js +132 -0
  19. package/lib/dbsc/store.js +136 -0
  20. package/lib/email-client/base-client.js +36 -15
  21. package/lib/email-client/gmail-client.js +20 -6
  22. package/lib/email-client/imap/connection-errors.js +30 -1
  23. package/lib/email-client/imap/session-expiry.js +83 -0
  24. package/lib/email-client/imap-client.js +12 -2
  25. package/lib/email-client/smtp-pool-manager.js +66 -8
  26. package/lib/export.js +147 -22
  27. package/lib/graph-notifications.js +60 -0
  28. package/lib/imap-proxy-auth.js +52 -18
  29. package/lib/imapproxy/imap-core/lib/commands/id.js +4 -2
  30. package/lib/imapproxy/imap-core/lib/imap-command.js +44 -4
  31. package/lib/imapproxy/imap-server.js +10 -1
  32. package/lib/imapproxy/proxy-handoff.js +100 -5
  33. package/lib/license-subscription.js +238 -0
  34. package/lib/oauth/gmail.js +18 -0
  35. package/lib/oauth/outlook-identity.js +54 -12
  36. package/lib/prepared-password.js +38 -0
  37. package/lib/privileged-settings.js +6 -0
  38. package/lib/queue-browser/index.js +6 -6
  39. package/lib/queue-job-actions.js +59 -4
  40. package/lib/read-env-value.js +46 -21
  41. package/lib/redis-url.js +23 -0
  42. package/lib/response-stream.js +69 -1
  43. package/lib/revocation-events.js +79 -0
  44. package/lib/routes-ui.js +4 -1
  45. package/lib/schemas.js +26 -2
  46. package/lib/session-default.js +13 -3
  47. package/lib/settings.js +47 -24
  48. package/lib/sso.js +23 -0
  49. package/lib/submit-penalty.js +24 -0
  50. package/lib/submit-processor.js +10 -2
  51. package/lib/tokens.js +6 -0
  52. package/lib/tools.js +86 -15
  53. package/lib/ui-routes/admin-config-routes.js +30 -281
  54. package/lib/ui-routes/auth-routes.js +17 -64
  55. package/lib/ui-routes/dbsc-routes.js +43 -0
  56. package/lib/ui-routes/license-routes.js +326 -0
  57. package/lib/web-safe-html.js +29 -0
  58. package/lib/webhook-delivery.js +21 -20
  59. package/lib/webhook-penalty.js +18 -17
  60. package/lib/webhooks.js +18 -0
  61. package/package.json +18 -18
  62. package/sbom.json +294 -294
  63. package/scan.js +2 -0
  64. package/server.js +253 -80
  65. package/static/css/flyonui.css +2 -2
  66. package/static/js/ui.js +11 -4
  67. package/static/licenses.html +27 -27
  68. package/translations/messages.pot +17 -17
  69. package/views/config/license.hbs +43 -16
  70. package/views/config/security.hbs +37 -0
  71. package/views/partials/side_menu.hbs +1 -1
  72. package/workers/api.js +128 -109
  73. 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');
@@ -87,6 +88,7 @@ const tokenAuditLog = require('../lib/token-audit-log');
87
88
  const { redis } = require('../lib/db');
88
89
  const { createHealthChecks } = require('../lib/health');
89
90
  const { requireSessionOnceSecured, TOTP_EXEMPT_PATHS } = require('../lib/session-default');
91
+ const { setupDbsc, registerDbscExtensions } = require('../lib/dbsc');
90
92
  const { Account } = require('../lib/account');
91
93
  const settings = require('../lib/settings');
92
94
 
@@ -152,7 +154,7 @@ const SUPPORTED_LOCALES = locales.map(locale => locale.locale);
152
154
 
153
155
  const FLAG_SORT_ORDER = ['\\Inbox', '\\Flagged', '\\Sent', '\\Drafts', '\\All', '\\Archive', '\\Junk', '\\Trash'];
154
156
 
155
- const { GMAIL_SCOPES, OPENID_SCOPES, workspaceDomainOf } = require('../lib/oauth/gmail');
157
+ const { GMAIL_SCOPES, OPENID_SCOPES, workspaceDomainOf, verifiedEmailOf } = require('../lib/oauth/gmail');
156
158
  const { MAIL_RU_SCOPES } = require('../lib/oauth/mail-ru');
157
159
 
158
160
  const GMAIL_SCOPE_DESCRIPTIONS = {
@@ -178,11 +180,7 @@ function formatScopeDescription(scope) {
178
180
  return shortName.replace(/\./g, ' ').replace(/\b\w/g, c => c.toUpperCase());
179
181
  }
180
182
 
181
- // The two MS Graph subscription routes are unauthenticated and deliberately carry no payload
182
- // schema: they must answer 202 to anything, because a 400 would make Graph tear the subscription
183
- // down, and the validation handshake posts an empty body. So the payload is arbitrary JSON and
184
- // every read of it has to be defensive.
185
- 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');
186
184
 
187
185
  const SMTP_TEST_HOST = 'https://api.nodemailer.com';
188
186
 
@@ -209,6 +207,9 @@ const USE_OIDC_AUTH = sso.USE_OIDC_AUTH;
209
207
  const oidcAllowList = sso.parseAllowList(sso.OIDC_ALLOWED_USERS);
210
208
  const oidcAllowGroups = sso.parseGroupList(sso.OIDC_ALLOWED_GROUPS);
211
209
 
210
+ // Bound to this instance's allow-lists; see sso.ssoSessionAdmitted()
211
+ const ssoSessionAdmitted = session => sso.ssoSessionAdmitted(session, oidcAllowList, oidcAllowGroups);
212
+
212
213
  const EENGINE_TIMEOUT = getDuration(readEnvValue('EENGINE_TIMEOUT') || config.service.commandTimeout) || DEFAULT_EENGINE_TIMEOUT;
213
214
  const MAX_ATTACHMENT_SIZE = getByteSize(readEnvValue('EENGINE_MAX_SIZE') || config.api.maxSize) || DEFAULT_MAX_ATTACHMENT_SIZE;
214
215
 
@@ -453,6 +454,11 @@ parentPort.on('message', message => {
453
454
  mcpListen.publishAccountChange(message, logger);
454
455
  }
455
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
+
456
462
  if (message && message.cmd === 'settings') {
457
463
  // the API reference memoizes serviceUrl, which its code samples embed
458
464
  clearServiceUrlCache();
@@ -474,6 +480,19 @@ parentPort.on('message', message => {
474
480
  // by the onPreResponse extension (registerResponseExtensions)
475
481
  let assertPreconditionResult;
476
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
+
477
496
  /**
478
497
  * Builds the hapi server, with the API TLS context when the API is served over HTTPS
479
498
  * @returns {Promise<Object>} The server, the certificate handler, the API TLS context and the
@@ -690,7 +709,16 @@ function registerRequestContextExtension(server) {
690
709
 
691
710
  // Both settings are needed on every request and neither depends on the other, so they are
692
711
  // read in a single HMGET rather than two serialized round trips
693
- let { enableApiProxy, disableTokens, serviceUrl } = await settings.getMulti('enableApiProxy', 'disableTokens', 'serviceUrl');
712
+ let { enableApiProxy, disableTokens, serviceUrl, dbscEnabled } = await settings.getMulti(
713
+ 'enableApiProxy',
714
+ 'disableTokens',
715
+ 'serviceUrl',
716
+ 'dbscEnabled'
717
+ );
718
+
719
+ // Device-bound admin sessions only work on an https origin, which is what serviceUrl says
720
+ // the admin UI is reached on (the same signal that marks the cookies Secure)
721
+ request.app.dbscEnabled = !!dbscEnabled && isSecureOrigin(serviceUrl);
694
722
 
695
723
  // Before anything can render a view (the allowlist refusal below does), so the nonce
696
724
  // the template stamps on its scripts is the one the response header carries
@@ -791,6 +819,7 @@ function registerApiTokenAuth(server) {
791
819
  redis,
792
820
  checkRateLimit,
793
821
  sessionPasswordVersion,
822
+ sessionAdmitted: ssoSessionAdmitted,
794
823
  adminAccessAddresses: ADMIN_ACCESS_ADDRESSES,
795
824
  logger
796
825
  })
@@ -832,11 +861,13 @@ async function registerSessionAuth(server) {
832
861
  isSecure: secureCookie
833
862
  });
834
863
 
864
+ const cookiePassword = await settings.get('cookiePassword');
865
+
835
866
  // Authentication for admin pages
836
867
  server.auth.strategy('session', 'cookie', {
837
868
  cookie: {
838
869
  name: 'ee',
839
- password: await settings.get('cookiePassword'),
870
+ password: cookiePassword,
840
871
  isSecure: secureCookie,
841
872
  path: '/',
842
873
  isSameSite: 'Lax'
@@ -865,34 +896,24 @@ async function registerSessionAuth(server) {
865
896
  switch (session.provider) {
866
897
  case 'okta':
867
898
  case 'oidc': {
868
- if (session.profile && session.profile.id) {
869
- let profile = session.profile;
870
-
871
- // Re-check OIDC authorization (email + group allow-lists) on every request
872
- // so changes to OIDC_ALLOWED_USERS/OIDC_ALLOWED_GROUPS (after a restart)
873
- // take effect without waiting out the existing session cookie. Okta has no
874
- // allow-list.
875
- if (session.provider === 'oidc' && !sso.isAuthorized(profile, oidcAllowList, oidcAllowGroups)) {
876
- return { isValid: false };
877
- }
878
-
879
- return {
880
- isValid: true,
881
- credentials: {
882
- enabled: true,
883
- user: profile.username
884
- },
885
- // Expose the SSO provider on artifacts so the "SSO users can't manage
886
- // local password/TOTP/passkeys" guards in the UI routes fire. idToken is
887
- // carried for OIDC RP-initiated logout (undefined for Okta).
888
- artifacts: {
889
- provider: session.provider,
890
- profile,
891
- idToken: session.idToken
892
- }
893
- };
899
+ if (!ssoSessionAdmitted(session)) {
900
+ return { isValid: false };
894
901
  }
895
- 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
+ };
896
917
  }
897
918
  }
898
919
 
@@ -923,6 +944,9 @@ async function registerSessionAuth(server) {
923
944
  }
924
945
  });
925
946
 
947
+ // Device-bound sessions ride on the same cookie settings (lib/dbsc)
948
+ setupDbsc(server, { redis, logger, secure: secureCookie, password: cookiePassword });
949
+
926
950
  return secureCookie;
927
951
  }
928
952
 
@@ -1738,41 +1762,26 @@ function registerOutlookNotificationRoute(server) {
1738
1762
  const notificationEntries = graphNotificationEntries(request.payload);
1739
1763
 
1740
1764
  if (!accountData.outlookSubscription) {
1741
- request.logger.warn({
1742
- msg: 'Subscription not found for account',
1743
- account: request.query.account,
1744
- subscriptionIds: notificationEntries.map(entry => entry.subscriptionId)
1745
- });
1765
+ logUnknownGraphSubscription(request, notificationEntries);
1746
1766
  return h.response(Buffer.alloc(0)).code(202);
1747
1767
  }
1748
1768
 
1749
1769
  const outlookSubscription = accountData.outlookSubscription;
1750
1770
 
1751
- const events = [];
1752
- for (let entry of notificationEntries) {
1753
- // enumerate and queue all entries
1754
- const subscriptionIdMatch = entry.subscriptionId === outlookSubscription.id;
1755
- const clientStateMatch = constantTimeEqual(entry.clientState, outlookSubscription.clientState);
1756
- if (!subscriptionIdMatch || !clientStateMatch) {
1757
- // Security: Log webhook validation failures - could indicate spoofed notifications
1758
- request.logger.warn({
1759
- msg: 'Webhook validation failed - potential security issue',
1760
- securityEvent: 'webhook_validation_failure',
1761
- account: request.query.account,
1762
- subscriptionIdMatch,
1763
- clientStateMatch,
1764
- receivedSubscriptionId: entry.subscriptionId,
1765
- changeType: entry.changeType,
1766
- resource: entry.resource
1767
- });
1768
- continue;
1769
- }
1770
-
1771
- events.push({
1772
- type: entry.changeType,
1773
- message: entry.resourceData && entry.resourceData.id
1774
- });
1775
- }
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
+ });
1776
1785
 
1777
1786
  if (events.length) {
1778
1787
  await accountObject.pushQueueEvents(events);
@@ -1843,11 +1852,7 @@ function registerOutlookLifecycleRoute(server) {
1843
1852
  const lifecycleEntries = graphNotificationEntries(request.payload);
1844
1853
 
1845
1854
  if (!accountData.outlookSubscription) {
1846
- request.logger.warn({
1847
- msg: 'Subscription not found for account',
1848
- account: request.query.account,
1849
- subscriptionIds: lifecycleEntries.map(entry => entry.subscriptionId)
1850
- });
1855
+ logUnknownGraphSubscription(request, lifecycleEntries);
1851
1856
  return h.response(Buffer.alloc(0)).code(202);
1852
1857
  }
1853
1858
 
@@ -1857,7 +1862,8 @@ function registerOutlookLifecycleRoute(server) {
1857
1862
  // concurrent handlers racing (e.g., two subscriptionRemoved entries)
1858
1863
  const seenLifecycleEvents = new Set();
1859
1864
 
1860
- for (let entry of lifecycleEntries) {
1865
+ const { valid, rejected } = partitionGraphEntries(lifecycleEntries, outlookSubscription, entry => ({ lifecycleEvent: entry.lifecycleEvent }));
1866
+ for (let entry of valid) {
1861
1867
  request.logger.debug({
1862
1868
  msg: 'MS Graph subscription event',
1863
1869
  type: 'lifecycle',
@@ -1866,23 +1872,6 @@ function registerOutlookLifecycleRoute(server) {
1866
1872
  subscriptionId: entry.subscriptionId
1867
1873
  });
1868
1874
 
1869
- // enumerate and queue all entries
1870
- const subscriptionIdMatch = entry.subscriptionId === outlookSubscription.id;
1871
- const clientStateMatch = constantTimeEqual(entry.clientState, outlookSubscription.clientState);
1872
- if (!subscriptionIdMatch || !clientStateMatch) {
1873
- // Security: Log lifecycle webhook validation failures - could indicate spoofed notifications
1874
- request.logger.warn({
1875
- msg: 'Lifecycle webhook validation failed - potential security issue',
1876
- securityEvent: 'lifecycle_webhook_validation_failure',
1877
- account: request.query.account,
1878
- subscriptionIdMatch,
1879
- clientStateMatch,
1880
- receivedSubscriptionId: entry.subscriptionId,
1881
- lifecycleEvent: entry.lifecycleEvent
1882
- });
1883
- continue;
1884
- }
1885
-
1886
1875
  // Route recognized lifecycle events to the IMAP worker
1887
1876
  // so the live client with its OAuth state handles them
1888
1877
  if (entry.lifecycleEvent === 'reauthorizationRequired' || entry.lifecycleEvent === 'subscriptionRemoved' || entry.lifecycleEvent === 'missed') {
@@ -1930,6 +1919,12 @@ function registerOutlookLifecycleRoute(server) {
1930
1919
  }
1931
1920
  }
1932
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
+
1933
1928
  return h.response(Buffer.alloc(0)).code(202);
1934
1929
  },
1935
1930
  options: {
@@ -2077,8 +2072,9 @@ async function resolveGmailUserEmail(flow, r, grantedScopes) {
2077
2072
  if (r.id_token && !idTokenPayload) {
2078
2073
  request.logger.warn({ msg: 'Failed to decode Gmail ID token' });
2079
2074
  }
2080
- if (idTokenPayload && typeof idTokenPayload.email === 'string' && isEmail(idTokenPayload.email)) {
2081
- userEmail = idTokenPayload.email;
2075
+ const idTokenEmail = verifiedEmailOf(idTokenPayload);
2076
+ if (idTokenEmail) {
2077
+ userEmail = idTokenEmail;
2082
2078
  userName = idTokenPayload.name || null;
2083
2079
  request.logger.info({ msg: 'Extracted user info from ID token', userEmail, userName });
2084
2080
  }
@@ -2229,6 +2225,11 @@ async function resolveOutlookCallbackUser(flow, r) {
2229
2225
  }
2230
2226
 
2231
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
+ }
2232
2233
 
2233
2234
  request.logger.info({
2234
2235
  msg: 'User profile returned by MS Graph API',
@@ -2251,8 +2252,10 @@ async function completeOutlookCallback(flow) {
2251
2252
 
2252
2253
  const userInfo = await resolveOutlookCallbackUser(flow, r);
2253
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
2254
2257
  const authData = {
2255
- user: userInfo.username || userInfo.email
2258
+ user: userInfo.username
2256
2259
  };
2257
2260
 
2258
2261
  if (!authData.user) {
@@ -2655,7 +2658,6 @@ function registerViews(server) {
2655
2658
  flash(redis, request),
2656
2659
  settings.getMulti(
2657
2660
  'upgrade',
2658
- 'subexp',
2659
2661
  'webhookErrorFlag',
2660
2662
  'webhooksEnabled',
2661
2663
  'disableTokens',
@@ -2678,7 +2680,6 @@ function registerViews(server) {
2678
2680
 
2679
2681
  const {
2680
2682
  upgrade: upgradeInfo,
2681
- subexp,
2682
2683
  webhookErrorFlag,
2683
2684
  webhooksEnabled,
2684
2685
  disableTokens,
@@ -2754,15 +2755,23 @@ function registerViews(server) {
2754
2755
  });
2755
2756
  }
2756
2757
 
2757
- if (subexp && !(request.app.licenseInfo && request.app.licenseInfo.details && request.app.licenseInfo.details.lt)) {
2758
- let delayMs = new Date(subexp) - Date.now();
2759
- let expiresDays = Math.max(Math.ceil(delayMs / (24 * 3600 * 1000)), 0);
2760
-
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) {
2761
2768
  systemAlerts.push({
2762
2769
  url: '/admin/config/license',
2763
2770
  level: 'danger',
2764
2771
  icon: 'icon-[tabler--alert-triangle]',
2765
- 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`
2766
2775
  });
2767
2776
  }
2768
2777
 
@@ -2787,7 +2796,8 @@ function registerViews(server) {
2787
2796
  });
2788
2797
  }
2789
2798
 
2790
- 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)) {
2791
2801
  systemAlerts.push({
2792
2802
  url: '/admin/config/license',
2793
2803
  level: 'warning',
@@ -2889,7 +2899,11 @@ function registerResponseExtensions(server) {
2889
2899
  const preResponse = async (request, h) => {
2890
2900
  let response = request.response;
2891
2901
 
2892
- 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) {
2893
2907
  response = assertPreconditionResult;
2894
2908
  }
2895
2909
 
@@ -3130,12 +3144,7 @@ function scheduleCertificateReconciler(certHandler) {
3130
3144
  // switched on, which is what the checkbox used to be; see listenersServeTls() there.
3131
3145
  setInterval(() => {
3132
3146
  async function handler() {
3133
- try {
3134
- await runPrechecks(redis);
3135
- assertPreconditionResult = false;
3136
- } catch (err) {
3137
- assertPreconditionResult = Boom.boomify(err);
3138
- }
3147
+ await refreshPreconditions();
3139
3148
 
3140
3149
  if (!IS_PRIMARY_API_WORKER) {
3141
3150
  return;
@@ -3179,6 +3188,13 @@ const init = async () => {
3179
3188
 
3180
3189
  registerRequestEvents(server);
3181
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
+
3182
3198
  registerStaticPageRoutes(server);
3183
3199
  registerStaticFilesRoute(server);
3184
3200
  registerHealthRoute(server);
@@ -3218,6 +3234,9 @@ const init = async () => {
3218
3234
 
3219
3235
  registerTotpExtension(server);
3220
3236
 
3237
+ // After the TOTP step and the error pages, see registerDbscExtensions()
3238
+ registerDbscExtensions(server);
3239
+
3221
3240
  registerChangesRoute(server);
3222
3241
 
3223
3242
  // setup web UI
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
  }