emailengine-app 2.79.6 → 2.79.8

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 (109) hide show
  1. package/.release-please-manifest.json +1 -1
  2. package/CHANGELOG.md +32 -0
  3. package/DOCKER_DEPLOYMENT.md +2 -0
  4. package/bin/emailengine.js +29 -13
  5. package/config/default.toml +13 -3
  6. package/data/google-crawlers.json +7 -1
  7. package/docker-compose.yml +12 -3
  8. package/install.sh +2 -0
  9. package/lib/api-routes/account-routes.js +14 -3
  10. package/lib/api-routes/mailbox-routes.js +4 -1
  11. package/lib/api-routes/message-routes.js +6 -5
  12. package/lib/api-routes/outbox-routes.js +7 -4
  13. package/lib/api-routes/settings-routes.js +34 -25
  14. package/lib/api-routes/stats-routes.js +8 -1
  15. package/lib/api-routes/submit-routes.js +2 -1
  16. package/lib/api-routes/template-routes.js +3 -2
  17. package/lib/bounce-detect.js +45 -0
  18. package/lib/consts.js +9 -3
  19. package/lib/egress-filter.js +39 -4
  20. package/lib/email-client/base-client.js +274 -24
  21. package/lib/email-client/gmail/gmail-api.js +15 -7
  22. package/lib/email-client/gmail-client.js +121 -64
  23. package/lib/email-client/imap/mailbox.js +18 -59
  24. package/lib/email-client/imap-client.js +53 -29
  25. package/lib/email-client/notification-handler.js +11 -2
  26. package/lib/email-client/outlook/graph-api.js +106 -90
  27. package/lib/email-client/outlook-client.js +222 -106
  28. package/lib/generate-text-preview.js +10 -5
  29. package/lib/headers-rewriter.js +1 -1
  30. package/lib/llm-pre-process.js +4 -1
  31. package/lib/mcp/json-schema.js +50 -2
  32. package/lib/outbox.js +22 -5
  33. package/lib/passkeys.js +39 -7
  34. package/lib/pre-process.js +4 -1
  35. package/lib/rewrite-text-nodes.js +12 -1
  36. package/lib/schemas.js +27 -5
  37. package/lib/settings.js +19 -1
  38. package/lib/sso.js +60 -7
  39. package/lib/submit-progress.js +29 -0
  40. package/lib/templates.js +11 -0
  41. package/lib/tools.js +115 -53
  42. package/lib/ui-routes/account-routes.js +79 -12
  43. package/lib/ui-routes/admin-config-routes.js +7 -21
  44. package/lib/ui-routes/admin-entities-routes.js +42 -12
  45. package/lib/ui-routes/auth-routes.js +242 -87
  46. package/lib/ui-routes/dashboard-routes.js +1 -1
  47. package/lib/ui-routes/internals-routes.js +2 -0
  48. package/lib/ui-routes/mcp-consent-routes.js +5 -2
  49. package/lib/ui-routes/network-config-routes.js +12 -3
  50. package/lib/ui-routes/oauth-config-routes.js +12 -1
  51. package/lib/ui-routes/route-helpers.js +41 -6
  52. package/lib/ui-routes/settings-page.js +10 -0
  53. package/lib/ui-routes/suppression-list-routes.js +16 -5
  54. package/lib/ui-routes/unsubscribe-routes.js +22 -3
  55. package/lib/webhooks.js +14 -2
  56. package/package.json +17 -17
  57. package/sbom.json +1 -1
  58. package/server.js +63 -35
  59. package/static/css/flyonui.css +1 -1
  60. package/static/css/src/app.tailwind.css +55 -0
  61. package/static/js/app.js +4 -35
  62. package/static/js/passkey-register.js +50 -1
  63. package/static/js/public.js +128 -0
  64. package/static/js/ui.js +183 -6
  65. package/static/licenses.html +371 -770
  66. package/translations/messages.pot +66 -66
  67. package/views/account/passkeys.hbs +141 -0
  68. package/views/account/password.hbs +11 -0
  69. package/views/account/security.hbs +318 -326
  70. package/views/accounts/account.hbs +90 -115
  71. package/views/accounts/register/imap-server.hbs +18 -12
  72. package/views/config/ai.hbs +2 -0
  73. package/views/config/branding.hbs +2 -0
  74. package/views/config/document-store/index.hbs +6 -6
  75. package/views/config/email-processing.hbs +2 -0
  76. package/views/config/imap-proxy.hbs +2 -0
  77. package/views/config/license.hbs +4 -1
  78. package/views/config/logging.hbs +3 -1
  79. package/views/config/mcp.hbs +2 -0
  80. package/views/config/network.hbs +2 -0
  81. package/views/config/oauth/app.hbs +3 -3
  82. package/views/config/oauth/edit.hbs +1 -1
  83. package/views/config/oauth/new.hbs +1 -1
  84. package/views/config/security.hbs +2 -0
  85. package/views/config/service.hbs +2 -0
  86. package/views/config/smtp.hbs +2 -0
  87. package/views/config/webhooks.hbs +9 -6
  88. package/views/error.hbs +6 -0
  89. package/views/layout/app.hbs +6 -3
  90. package/views/layout/login.hbs +1 -1
  91. package/views/layout/prompt.hbs +1 -1
  92. package/views/layout/public.hbs +1 -1
  93. package/views/legal.hbs +1 -1
  94. package/views/partials/filter_editor_js.hbs +1 -1
  95. package/views/partials/gateway_js.hbs +7 -6
  96. package/views/partials/oauth_form.hbs +5 -5
  97. package/views/partials/ui/btn.hbs +8 -2
  98. package/views/partials/ui/confirm-modal.hbs +2 -3
  99. package/views/partials/ui/empty-state.hbs +25 -0
  100. package/views/partials/ui/env-managed-alert.hbs +19 -0
  101. package/views/partials/webhook_form.hbs +1 -1
  102. package/views/partials/webhooks_editor_functions.hbs +5 -5
  103. package/views/unsubscribe.hbs +6 -0
  104. package/workers/api.js +193 -81
  105. package/workers/imap.js +32 -3
  106. package/workers/smtp.js +7 -0
  107. package/workers/submit.js +25 -1
  108. package/workers/webhooks.js +13 -17
  109. package/lib/reconnection-manager.js +0 -106
package/workers/api.js CHANGED
@@ -42,7 +42,8 @@ const {
42
42
  claimFormNonce,
43
43
  releaseFormNonce,
44
44
  setAdminSession,
45
- isEndedSession
45
+ isEndedSession,
46
+ reloadTlsServers
46
47
  } = require('../lib/tools');
47
48
  const { matchIp, resolveClientIp, detectAutomatedRequest } = require('../lib/utils/network');
48
49
 
@@ -94,7 +95,7 @@ const { registerOpenApiRoute } = require('../lib/openapi');
94
95
  const { getModel: getApiReferenceModel, clearServiceUrlCache } = require('../lib/api-reference');
95
96
 
96
97
  const { encrypt, decrypt } = require('../lib/encrypt');
97
- const { Certs } = require('@postalsys/certs');
98
+ const { Certs, isRenewalDue } = require('@postalsys/certs');
98
99
  const net = require('net');
99
100
 
100
101
  const consts = require('../lib/consts');
@@ -102,7 +103,6 @@ const {
102
103
  TRACK_OPEN_NOTIFY,
103
104
  TRACK_CLICK_NOTIFY,
104
105
  REDIS_PREFIX,
105
- RENEW_TLS_AFTER,
106
106
  BLOCK_TLS_RENEW,
107
107
  TLS_RENEW_CHECK_INTERVAL,
108
108
  DEFAULT_CORS_MAX_AGE,
@@ -124,6 +124,7 @@ const {
124
124
  oauth2Schema,
125
125
  accountIdSchema,
126
126
  apiHeadersSchema,
127
+ headerTimeoutSchema,
127
128
  oauth2ProviderSchema: OAuth2ProviderSchema,
128
129
  accountTypeSchema: AccountTypeSchema
129
130
  } = require('../lib/schemas');
@@ -402,6 +403,11 @@ function publishChangeEvent(data) {
402
403
  }
403
404
  }
404
405
 
406
+ // The Hapi server, published by init() once the session strategy is registered and the boot-time
407
+ // default has been decided, so the authData branch of the settings dispatcher below cannot set a
408
+ // strategy that does not exist yet or race the boot-time server.auth.default() call
409
+ let sessionAuthServer = null;
410
+
405
411
  parentPort.on('message', message => {
406
412
  if (message && message.cmd === 'resp' && message.mid && callQueue.has(message.mid)) {
407
413
  let { resolve, reject, timer } = callQueue.get(message.mid);
@@ -458,6 +464,17 @@ parentPort.on('message', message => {
458
464
  maybeReloadHttpProxyAgent(message.data);
459
465
  // ...and the API reference's memoized serviceUrl, which its code samples embed
460
466
  clearServiceUrlCache();
467
+
468
+ // The first admin password is saved by whichever API worker served the form, and only
469
+ // that worker's server gets the default strategy in-process (lib/ui-routes/auth-routes.js).
470
+ // The same handler broadcasts a settings change carrying the authData key, so with
471
+ // EENGINE_WORKERS_API > 1 the other workers stop serving /admin open here instead of at
472
+ // the next restart. hapi refuses a second default, hence the guard, which also covers
473
+ // the sender.
474
+ if (message.data && message.data.authData && sessionAuthServer && !sessionAuthServer.auth.settings.default) {
475
+ sessionAuthServer.auth.default('session');
476
+ logger.info({ msg: 'Admin session authentication enabled after the first password was set' });
477
+ }
461
478
  }
462
479
  });
463
480
 
@@ -574,7 +591,12 @@ const init = async () => {
574
591
  messages: joiLocales,
575
592
  convert: true,
576
593
  errors: {
577
- language: 'en' // Default language
594
+ // Resolved per request from request.app.locale, which onPreAuth sets and
595
+ // hapi exposes to joi as the $app.request context. A locale with no
596
+ // joi catalog falls through to joi's own English messages. This has to be
597
+ // a reference: the route settings are shared by every request on the
598
+ // route, so writing the locale into them races concurrent requests
599
+ language: Joi.ref('$app.request.locale')
578
600
  }
579
601
  },
580
602
  headers: apiHeadersSchema
@@ -770,21 +792,9 @@ const init = async () => {
770
792
  request.app.gt = gt;
771
793
  }
772
794
 
773
- // Make sure validation errors use selected locale
774
- if (request.route.settings.validate && request.route.settings.validate.options) {
775
- // Get user's locale
776
- const locale = request.app.locale || 'en';
777
-
778
- // Create new validation options for this request
779
- const validationOptions = Object.assign({}, request.route.settings.validate.options, {
780
- errors: {
781
- language: locale
782
- }
783
- });
784
-
785
- // Apply to this request only
786
- request.route.settings.validate.options = validationOptions;
787
- }
795
+ // Validation errors pick their language up from request.app.locale through the
796
+ // errors.language reference in the server-wide route defaults (see serverOptions), so
797
+ // nothing per request is written into the shared route settings here
788
798
 
789
799
  return h.continue;
790
800
  });
@@ -817,7 +827,12 @@ const init = async () => {
817
827
  // the outer request (lib/mcp/inject.js), so the IPC round trip is not paid twice for
818
828
  // one answer that cannot differ within a request.
819
829
  if (!request.app.licenseInfo) {
820
- request.app.licenseInfo = await call({ cmd: 'license', timeout: request.headers['x-ee-timeout'] });
830
+ // This runs before route validation, so the header is still the raw string here. The
831
+ // route schema decides what it accepts (a bad value is that route's 400 later); a value
832
+ // it would refuse is ignored rather than handed to the timer, where a non-number or an
833
+ // overflow collapses to a 1 ms timeout and a 500 before validation ever runs.
834
+ const { error: timeoutError, value: requestTimeout } = headerTimeoutSchema.validate(request.headers['x-ee-timeout']);
835
+ request.app.licenseInfo = await call({ cmd: 'license', timeout: timeoutError ? undefined : requestTimeout });
821
836
  }
822
837
 
823
838
  // flash notifications
@@ -966,11 +981,16 @@ const init = async () => {
966
981
  // only repeat it
967
982
  tokenData = await tokens.get(token, false, { log: !request.app.mcpInternal, remoteAddress: request.app.ip });
968
983
  } catch (err) {
969
- return {
970
- isValid: false,
971
- credentials: {},
972
- artifacts: { err: err.message }
973
- };
984
+ // A thrown Boom reaches the client the way the scope and permission refusals
985
+ // below do (hapi-auth-bearer-token does not catch it), so the reason travels as a
986
+ // machine-readable code - UnknownToken, ExpiredToken, InvalidToken - while the
987
+ // message stays the generic one the scheme itself would have sent. The scheme
988
+ // name keeps the WWW-Authenticate header the plugin's own refusal carries.
989
+ let error = Boom.unauthorized('Bad token', 'Bearer');
990
+ if (err.code) {
991
+ error.output.payload.code = err.code;
992
+ }
993
+ throw error;
974
994
  }
975
995
 
976
996
  // Bind the token hash (id) to the request logger so it is included in the per-request
@@ -1200,7 +1220,10 @@ const init = async () => {
1200
1220
  error.output.payload.ttl = Math.ceil(rateLimit.ttl);
1201
1221
  error.output.headers = {
1202
1222
  'X-RateLimit-Limit': rateLimit.allowed,
1203
- 'X-RateLimit-Reset': Math.ceil(rateLimit.ttl)
1223
+ 'X-RateLimit-Reset': Math.ceil(rateLimit.ttl),
1224
+ // The conventional header for a 429, so a generic HTTP client backs
1225
+ // off without knowing about the ttl field in the body
1226
+ 'Retry-After': Math.ceil(rateLimit.ttl)
1204
1227
  };
1205
1228
  throw error;
1206
1229
  } else {
@@ -1368,12 +1391,20 @@ const init = async () => {
1368
1391
  // break the registered callback URL) disables the SSO button instead of failing mid-flow.
1369
1392
  let getServiceRedirectUrl = async () => new URL((await settings.get('serviceUrl')) || `http://${API_HOST}${API_PORT !== 80 ? `:${API_PORT}` : ''}`);
1370
1393
  let serviceOriginUnchanged = async redirectUrl => (await getServiceRedirectUrl()).origin === redirectUrl.origin;
1371
- let assertSsoAuthenticated = request => {
1372
- if (!request.auth.isAuthenticated) {
1373
- let error = Boom.unauthorized('Failed to authorize user');
1374
- error.output.payload.details = [request.auth.error.message];
1375
- throw error;
1376
- }
1394
+ // A sign-in the IdP denied, or the user cancelled, comes back as an unauthenticated try-mode
1395
+ // request. It gets the same flash-and-redirect the allow-list denial in the OIDC handler
1396
+ // uses, so the user lands on the login form with a way to try again rather than on the
1397
+ // generic error page with bell's raw message. The reason goes to the log only. ?sso_denied=1
1398
+ // stops a forced instance from auto-redirecting straight back into the flow.
1399
+ let ssoFailureRedirect = async (request, h, method) => {
1400
+ request.logger.warn({
1401
+ msg: 'SSO login failed',
1402
+ method,
1403
+ reason: (request.auth.error && request.auth.error.message) || 'unknown',
1404
+ remoteAddress: request.app.ip
1405
+ });
1406
+ await request.flash({ type: 'danger', message: 'Single sign-on failed or was cancelled. Please try again' });
1407
+ return h.redirect('/admin/login?sso_denied=1');
1377
1408
  };
1378
1409
 
1379
1410
  if (USE_OKTA_AUTH) {
@@ -1398,10 +1429,28 @@ const init = async () => {
1398
1429
  method: ['GET', 'POST'],
1399
1430
  path: '/admin/login/okta',
1400
1431
  async handler(request, h) {
1401
- assertSsoAuthenticated(request);
1402
- setAdminSession(request, Object.assign({}, request.auth.credentials, { passwordVersion: await sessionPasswordVersion() }));
1403
- let oktaUser = request.auth.credentials && request.auth.credentials.profile && request.auth.credentials.profile.username;
1404
- request.logger.info({ msg: 'Admin login successful', user: oktaUser || 'unknown', method: 'okta', remoteAddress: request.app.ip });
1432
+ if (!request.auth.isAuthenticated) {
1433
+ return ssoFailureRedirect(request, h, 'okta');
1434
+ }
1435
+
1436
+ let profile = (request.auth.credentials && request.auth.credentials.profile) || {};
1437
+
1438
+ // The same minimal shape the OIDC branch below stores, for the same reasons: the
1439
+ // full bell credentials carry the access and refresh tokens, the callback query
1440
+ // and the raw userinfo document, none of which the session validator reads, and
1441
+ // all of which would sit in the browser's cookie for the life of the session.
1442
+ setAdminSession(request, {
1443
+ provider: 'okta',
1444
+ profile: {
1445
+ id: profile.id,
1446
+ username: profile.username,
1447
+ displayName: profile.displayName,
1448
+ email: profile.email
1449
+ },
1450
+ passwordVersion: await sessionPasswordVersion()
1451
+ });
1452
+
1453
+ request.logger.info({ msg: 'Admin login successful', user: profile.username || 'unknown', method: 'okta', remoteAddress: request.app.ip });
1405
1454
  return h.redirect('/admin');
1406
1455
  },
1407
1456
  options: {
@@ -1416,17 +1465,17 @@ const init = async () => {
1416
1465
  if (USE_OIDC_AUTH) {
1417
1466
  let redirectUrl = await getServiceRedirectUrl();
1418
1467
 
1419
- // Fetch the discovery document once at startup. bell needs static auth/token
1420
- // URLs at strategy-registration time, so this must precede registration. A
1421
- // failure here (IdP outage/misconfig) must NOT take EmailEngine down - password
1422
- // and passkey login plus the REST API have to keep working - so we log a
1423
- // prominent error, leave the strategy unregistered, and disable the SSO button.
1468
+ // bell needs static auth/token URLs at strategy-registration time, so the
1469
+ // discovery document has to be in hand before the strategy and the callback
1470
+ // route that depends on it can be registered. A failure to fetch it (IdP outage
1471
+ // or misconfig) must NOT take EmailEngine down - password and passkey login plus
1472
+ // the REST API have to keep working - so SSO simply stays switched off until a
1473
+ // later attempt succeeds.
1474
+ //
1475
+ // Assigned from enableOidc()'s return value, so it can only be set once that
1476
+ // strategy and route exist and validateOidcConfig() can never advertise a login
1477
+ // button - or trigger OIDC_FORCED - for a route that is not registered.
1424
1478
  let oidcDiscovery = null;
1425
- try {
1426
- oidcDiscovery = await sso.fetchOidcDiscovery();
1427
- } catch (err) {
1428
- logger.error({ msg: 'OIDC SSO disabled: discovery failed', issuer: sso.OIDC_ISSUER, err });
1429
- }
1430
1479
 
1431
1480
  // Registered unconditionally so the login/security views can call it; returns
1432
1481
  // false when discovery failed or the serviceUrl origin drifted from startup.
@@ -1448,9 +1497,9 @@ const init = async () => {
1448
1497
  });
1449
1498
  });
1450
1499
 
1451
- if (oidcDiscovery) {
1500
+ const enableOidc = async discoveryDoc => {
1452
1501
  server.auth.strategy('oidc', 'bell', {
1453
- provider: sso.buildOidcBellProvider(oidcDiscovery),
1502
+ provider: sso.buildOidcBellProvider(discoveryDoc),
1454
1503
  password: await settings.get('cookiePassword'),
1455
1504
  isSecure: secureCookie,
1456
1505
  location: redirectUrl.origin,
@@ -1463,7 +1512,9 @@ const init = async () => {
1463
1512
  method: ['GET', 'POST'],
1464
1513
  path: '/admin/login/oidc',
1465
1514
  async handler(request, h) {
1466
- assertSsoAuthenticated(request);
1515
+ if (!request.auth.isAuthenticated) {
1516
+ return ssoFailureRedirect(request, h, 'oidc');
1517
+ }
1467
1518
 
1468
1519
  let profile = (request.auth.credentials && request.auth.credentials.profile) || {};
1469
1520
 
@@ -1514,6 +1565,32 @@ const init = async () => {
1514
1565
  }
1515
1566
  }
1516
1567
  });
1568
+
1569
+ return discoveryDoc;
1570
+ };
1571
+
1572
+ let startupDoc = await sso.fetchOidcDiscovery().catch(err => {
1573
+ logger.error({ msg: 'OIDC SSO disabled for now: discovery failed, retrying in the background', issuer: sso.OIDC_ISSUER, err });
1574
+ return null;
1575
+ });
1576
+
1577
+ if (startupDoc) {
1578
+ // A registration failure here is deliberately fatal: a misconfiguration should
1579
+ // stop the worker at boot rather than come up quietly without SSO. The retry
1580
+ // path below is the opposite on purpose - it must not kill a serving process.
1581
+ oidcDiscovery = await enableOidc(startupDoc);
1582
+ } else {
1583
+ // Deliberately not awaited - this runs for as long as the IdP is unreachable.
1584
+ // hapi accepts both a new auth strategy and a new route after the server has
1585
+ // started, so a later success brings SSO up in place, with no restart.
1586
+ sso.retryDiscovery({
1587
+ onError: (err, attempt) => logger.debug({ msg: 'OIDC discovery retry failed', issuer: sso.OIDC_ISSUER, attempt, err })
1588
+ })
1589
+ .then(async retriedDoc => {
1590
+ oidcDiscovery = await enableOidc(retriedDoc);
1591
+ logger.info({ msg: 'OIDC SSO enabled after retrying discovery', issuer: sso.OIDC_ISSUER });
1592
+ })
1593
+ .catch(err => logger.error({ msg: 'OIDC SSO disabled: discovery retry failed', issuer: sso.OIDC_ISSUER, err }));
1517
1594
  }
1518
1595
  }
1519
1596
 
@@ -1521,6 +1598,10 @@ const init = async () => {
1521
1598
  server.auth.default('session');
1522
1599
  }
1523
1600
 
1601
+ // From here on a first password set on another API worker switches the session strategy on
1602
+ // through the settings dispatcher (see the authData branch there)
1603
+ sessionAuthServer = server;
1604
+
1524
1605
  await server.register({
1525
1606
  plugin: hapiPino,
1526
1607
  options: {
@@ -2244,40 +2325,44 @@ const init = async () => {
2244
2325
  method: 'GET',
2245
2326
  path: '/oauth',
2246
2327
  async handler(request, h) {
2247
- if (request.query.error) {
2248
- let error = Boom.boomify(new Error(`Oauth failed: ${request.query.error}`), { statusCode: 400 });
2328
+ // The mailbox owner sees these on the public error page, in the same locale as the
2329
+ // rest of the setup flow. The pending setup is still unspent at this point (its state
2330
+ // entry is claimed only below), so opening the setup link again is a valid retry.
2331
+ if (request.query.error === 'access_denied') {
2332
+ let error = Boom.badRequest(
2333
+ request.app.gt.gettext('The sign-in was cancelled or the requested access was not granted. Open the account setup link again to retry.')
2334
+ );
2335
+ if (request.query.error_description) {
2336
+ error.output.payload.details = [String(request.query.error_description)];
2337
+ }
2249
2338
  throw error;
2250
2339
  }
2251
2340
 
2252
- if (!request.query.code) {
2253
- // throw
2254
- let error = Boom.boomify(new Error(`Oauth failed: no code received`), { statusCode: 400 });
2255
- throw error;
2341
+ if (request.query.error) {
2342
+ throw Boom.badRequest(util.format(request.app.gt.gettext('Sign-in with the email provider failed: %s'), request.query.error));
2256
2343
  }
2257
2344
 
2258
- if (!/^account:add:/.test(request.query.state)) {
2259
- let error = Boom.boomify(new Error(`Oauth failed: invalid state received`), { statusCode: 400 });
2260
- throw error;
2345
+ if (!request.query.code) {
2346
+ throw Boom.badRequest(request.app.gt.gettext('Sign-in with the email provider failed: no authorization code was received'));
2261
2347
  }
2262
2348
 
2263
2349
  // Validate nonce format: 16 bytes base64url encoded = 21-22 characters
2264
2350
  // Also accept base64 encoding (+, /, =) for backward compatibility with old cached nonces
2265
- const stateNonce = request.query.state.slice('account:add:'.length);
2266
- if (!/^[A-Za-z0-9_\-+/]{21,22}={0,2}$/.test(stateNonce)) {
2267
- throw Boom.badRequest('Oauth failed: invalid state format');
2351
+ if (!/^account:add:[A-Za-z0-9_\-+/]{21,22}={0,2}$/.test(request.query.state)) {
2352
+ throw Boom.badRequest(request.app.gt.gettext('Sign-in with the email provider failed: the request state is not valid'));
2268
2353
  }
2269
2354
 
2270
2355
  let [[, accountData]] = await redis.multi().get(`${REDIS_PREFIX}${request.query.state}`).del(`${REDIS_PREFIX}${request.query.state}`).exec();
2271
2356
  if (!accountData) {
2272
- let error = Boom.boomify(new Error(`Oauth failed: session expired`), { statusCode: 400 });
2273
- throw error;
2357
+ throw Boom.badRequest(
2358
+ request.app.gt.gettext('The account setup session has expired or was already used. Open the account setup link again to retry.')
2359
+ );
2274
2360
  }
2275
2361
 
2276
2362
  try {
2277
2363
  accountData = JSON.parse(accountData);
2278
2364
  } catch (E) {
2279
- let error = Boom.boomify(new Error(`Oauth failed: invalid session`), { statusCode: 400 });
2280
- throw error;
2365
+ throw Boom.badRequest(request.app.gt.gettext('Sign-in with the email provider failed: the stored setup session is not valid'));
2281
2366
  }
2282
2367
 
2283
2368
  if (!accountData.account) {
@@ -3073,6 +3158,11 @@ const init = async () => {
3073
3158
  systemAlerts = systemAlerts.filter(alert => alert.level === 'danger');
3074
3159
  }
3075
3160
 
3161
+ // Whether the requester holds a session at all, so a public page (the hosted form's
3162
+ // error page, for one) can tell a mailbox owner from an admin without reading
3163
+ // authData, which describes the instance rather than the requester
3164
+ const isAuthenticated = !!(request.auth && request.auth.isAuthenticated);
3165
+
3076
3166
  return {
3077
3167
  pageBrandName: pageBrandName || 'EmailEngine',
3078
3168
  values: request.payload || {},
@@ -3082,6 +3172,10 @@ const init = async () => {
3082
3172
  licenseDetails,
3083
3173
  trialPossible: !tract,
3084
3174
  authData,
3175
+ isAuthenticated,
3176
+ // The dashboard is an admin destination: a link to it belongs on a page only for
3177
+ // a requester who holds an admin session, or on an instance with no admin login
3178
+ showDashboardLink: isAuthenticated || !(authData && authData.enabled),
3085
3179
  packageData,
3086
3180
  systemAlerts,
3087
3181
  embeddedTemplateHeader,
@@ -3113,14 +3207,16 @@ const init = async () => {
3113
3207
  response = assertPreconditionResult;
3114
3208
  }
3115
3209
 
3116
- if (!response.isBoom) {
3117
- if (request.app.rateLimitHeaders) {
3118
- const headers = request.response.output ? request.response.output.headers : request.response.headers;
3119
- for (let key of Object.keys(request.app.rateLimitHeaders)) {
3120
- headers[key] = request.app.rateLimitHeaders[key].toString();
3121
- }
3210
+ // On error responses too: a client pacing itself by these headers needs them most on
3211
+ // the request that failed, and the JSON error path below copies output.headers over
3212
+ if (request.app.rateLimitHeaders) {
3213
+ const headers = response.isBoom ? response.output.headers : response.headers;
3214
+ for (let key of Object.keys(request.app.rateLimitHeaders)) {
3215
+ headers[key] = request.app.rateLimitHeaders[key].toString();
3122
3216
  }
3217
+ }
3123
3218
 
3219
+ if (!response.isBoom) {
3124
3220
  return h.continue;
3125
3221
  }
3126
3222
 
@@ -3141,11 +3237,13 @@ const init = async () => {
3141
3237
  }
3142
3238
 
3143
3239
  if (error.output && error.output.statusCode === 401 && error.output.headers && /^Bearer/.test(error.output.headers['WWW-Authenticate'])) {
3144
- // bearer auth failed
3145
- return h
3146
- .response({ statusCode: 401, error: 'Unauthorized', message: error.message })
3147
- .header('WWW-Authenticate', error.output.headers['WWW-Authenticate'])
3148
- .code(error.output.statusCode);
3240
+ // bearer auth failed. The api-token strategy attaches the refusal reason as a code,
3241
+ // and it is the one field worth carrying into this rebuilt payload
3242
+ let payload = { statusCode: 401, error: 'Unauthorized', message: error.message };
3243
+ if (error.output.payload.code) {
3244
+ payload.code = error.output.payload.code;
3245
+ }
3246
+ return h.response(payload).header('WWW-Authenticate', error.output.headers['WWW-Authenticate']).code(error.output.statusCode);
3149
3247
  }
3150
3248
 
3151
3249
  const routeTags = (request.route && request.route.settings && request.route.settings.tags) || [];
@@ -3185,8 +3283,10 @@ const init = async () => {
3185
3283
 
3186
3284
  server.ext('onPostAuth', async (request, h) => {
3187
3285
  if (request.requireTotp) {
3188
- // Redirect authenticated pages to login page if TOTP is required
3189
- let url = new URL(`admin/login`, 'http://localhost');
3286
+ // The password step is done and only the second factor is missing, so the session
3287
+ // goes to the TOTP prompt rather than back to the login form, which would ask for
3288
+ // the password again
3289
+ let url = new URL(`admin/totp`, 'http://localhost');
3190
3290
 
3191
3291
  let nextUrl = (request.query && request.query.next) || (request.payload && request.payload.next) || false;
3192
3292
  if (nextUrl) {
@@ -3319,15 +3419,27 @@ const init = async () => {
3319
3419
  assertPreconditionResult = Boom.boomify(err);
3320
3420
  }
3321
3421
 
3422
+ // isRenewalDue() asks whether the certificate is close enough to expiry to replace,
3423
+ // scaled to the lifetime the CA issued. This used to compare against
3424
+ // Date.now() - RENEW_TLS_AFTER, which is the expiry date thirty days in the past: it
3425
+ // read as "renew with thirty days left" but meant "renew thirty days after it died",
3426
+ // so the automatic path only ever ran once the certificate had been broken for a
3427
+ // month. Let's Encrypt is on the way from 90 day certificates to 45, which would have
3428
+ // left a service unreachable for two thirds of every certificate's life.
3322
3429
  if (
3323
3430
  IS_PRIMARY_API_WORKER &&
3324
3431
  currentCert &&
3325
- currentCert.validTo < new Date(Date.now() - RENEW_TLS_AFTER) &&
3432
+ isRenewalDue(currentCert) &&
3326
3433
  (!currentCert.lastCheck || currentCert.lastCheck < new Date(Date.now() - BLOCK_TLS_RENEW))
3327
3434
  ) {
3328
3435
  try {
3329
- await certHandler.acquireCert(serviceDomain);
3330
- await call({ cmd: 'smtpReload' });
3436
+ let renewedCert = await certHandler.acquireCert(serviceDomain);
3437
+
3438
+ // Only when the certificate actually changed, so a renewal that was skipped
3439
+ // or failed does not restart both servers for nothing.
3440
+ if (renewedCert && renewedCert.fingerprint && renewedCert.fingerprint !== currentCert.fingerprint) {
3441
+ await reloadTlsServers(call, logger, { serviceDomain });
3442
+ }
3331
3443
  } catch (err) {
3332
3444
  logger.error({ msg: 'Failed to acquire TLS certificate', serviceDomain, err });
3333
3445
  } finally {
package/workers/imap.js CHANGED
@@ -305,9 +305,38 @@ class ConnectionHandler {
305
305
  }
306
306
 
307
307
  // do not wait before returning as it may take forever
308
- accountObject.connection.init(initOpts).catch(err => {
309
- logger.error({ msg: 'Failed to initialize account connection', account, err });
310
- });
308
+ this.startConnection(account, accountObject, initOpts);
309
+ }
310
+
311
+ /**
312
+ * Runs init() without waiting for it. A client that retries its own init() (the API
313
+ * clients, see BaseClient.scheduleInitRetry()) gets another attempt when it fails on
314
+ * something other than a refused credential; a client that was replaced in the meantime
315
+ * is left alone when the timer fires
316
+ * @param {string} account - Account ID
317
+ * @param {Object} accountObject - Account instance holding the connection
318
+ * @param {Object} initOpts - Options passed to init()
319
+ */
320
+ startConnection(account, accountObject, initOpts) {
321
+ const connection = accountObject.connection;
322
+
323
+ connection
324
+ .init(initOpts)
325
+ .then(() => connection.resetInitRetry())
326
+ .catch(err => {
327
+ logger.error({ msg: 'Failed to initialize account connection', account, err });
328
+
329
+ if (!connection.retriesInit || err.authenticationFailed) {
330
+ return;
331
+ }
332
+
333
+ connection.scheduleInitRetry(() => {
334
+ if (this.accounts.get(account) !== accountObject) {
335
+ return;
336
+ }
337
+ this.startConnection(account, accountObject, initOpts);
338
+ });
339
+ });
311
340
  }
312
341
 
313
342
  async deleteConnection(account) {
package/workers/smtp.js CHANGED
@@ -40,6 +40,12 @@ const DEFAULT_EENGINE_TIMEOUT = 10 * 1000;
40
40
  const MAX_SMTP_MESSAGE_SIZE = getByteSize(readEnvValue('EENGINE_MAX_SMTP_MESSAGE_SIZE') || config.smtp.maxMessageSize) || DEFAULT_MAX_SMTP_MESSAGE_SIZE;
41
41
  const EENGINE_TIMEOUT = getDuration(readEnvValue('EENGINE_TIMEOUT') || config.service.commandTimeout) || DEFAULT_EENGINE_TIMEOUT;
42
42
 
43
+ // Every connection buffers its message in memory up to MAX_SMTP_MESSAGE_SIZE before it is queued,
44
+ // so the concurrent connection count is what bounds this worker's memory. Excess connections are
45
+ // refused with a 421, which any SMTP client retries. The default matches Postfix's smtpd limit.
46
+ const DEFAULT_SMTP_MAX_CLIENTS = 100;
47
+ const SMTP_MAX_CLIENTS = Number(readEnvValue('EENGINE_SMTP_MAX_CLIENTS') || config.smtp.maxClients) || DEFAULT_SMTP_MAX_CLIENTS;
48
+
43
49
  const ACCOUNT_CACHE = new WeakMap();
44
50
 
45
51
  let callQueue = new Map();
@@ -158,6 +164,7 @@ async function init() {
158
164
  disableReverseLookup: true,
159
165
  banner: 'EmailEngine MSA',
160
166
  size: MAX_SMTP_MESSAGE_SIZE,
167
+ maxClients: SMTP_MAX_CLIENTS,
161
168
  useProxy: await settings.get('smtpServerProxy')
162
169
  };
163
170
 
package/workers/submit.js CHANGED
@@ -43,6 +43,7 @@ const SUBMIT_QC = (readEnvValue('EENGINE_SUBMIT_QC') && Number(readEnvValue('EEN
43
43
  const SUBMIT_DELAY = getDuration(readEnvValue('EENGINE_SUBMIT_DELAY') || config.submitDelay) || null;
44
44
 
45
45
  const { shouldDiscardJob, willBeFinalAttempt, isFinalFailedAttempt } = require('../lib/delivery-error');
46
+ const { isAlreadySent } = require('../lib/submit-progress');
46
47
  const { packRpcError, unpackRpcError } = require('../lib/worker-rpc-error');
47
48
 
48
49
  let callQueue = new Map();
@@ -142,6 +143,29 @@ const submitWorker = new Worker(
142
143
  job.data.queueId = job.data.qId;
143
144
  }
144
145
 
146
+ // A job re-run after a stall (heartbeat kill, crash, a shutdown drain that could not cover
147
+ // a long SMTP transaction plus the Sent-folder upload) comes back with the progress its
148
+ // previous run stored. Once that says the MTA accepted the message, sending again would
149
+ // deliver a duplicate under the same queueId: the message is done, only the bookkeeping
150
+ // after the 250 was cut short. The catch below covers the same state for a run that got
151
+ // as far as throwing; this covers the run that never got to throw anything.
152
+ if (isAlreadySent(job.progress)) {
153
+ logger.info({
154
+ msg: 'Skipping re-run of an already sent message',
155
+ action: 'submit',
156
+ queue: job.queue.name,
157
+ code: 'result_success',
158
+ job: job.id,
159
+ event: job.name,
160
+ account: job.data.account,
161
+ queueId: job.data.queueId,
162
+ messageId: job.data.messageId,
163
+ progress: job.progress.status,
164
+ attemptsMade: job.attemptsMade
165
+ });
166
+ return;
167
+ }
168
+
145
169
  let queueEntryBuf = await redis.hgetBuffer(`${REDIS_PREFIX}iaq:${job.data.account}`, job.data.queueId);
146
170
  if (!queueEntryBuf) {
147
171
  // nothing to do here
@@ -231,7 +255,7 @@ const submitWorker = new Worker(
231
255
  } catch (err) {
232
256
  try {
233
257
  const submitJobEntry = await submitQueue.getJob(job.id);
234
- if (submitJobEntry && submitJobEntry.progress && ['submitted', 'smtp-completed'].includes(submitJobEntry.progress.status)) {
258
+ if (submitJobEntry && isAlreadySent(submitJobEntry.progress)) {
235
259
  // SMTP transition succeeded, can accept even if the process yielded in error
236
260
  logger.trace({
237
261
  msg: 'Submitted queued message for delivery',
@@ -10,7 +10,16 @@ const { webhooks: Webhooks } = require('../lib/webhooks');
10
10
 
11
11
  const { GooglePubSub } = require('../lib/oauth/pubsub/google');
12
12
 
13
- const { readEnvValue, threadStats, getDuration, httpAgent, getServiceSecret, maybeReloadHttpProxyAgent, redactUrlCredentials } = require('../lib/tools');
13
+ const {
14
+ readEnvValue,
15
+ threadStats,
16
+ getDuration,
17
+ httpAgent,
18
+ getServiceSecret,
19
+ maybeReloadHttpProxyAgent,
20
+ redactUrlCredentials,
21
+ splitUrlCredentials
22
+ } = require('../lib/tools');
14
23
  const { sendWebhookRequest } = require('../lib/webhook-request');
15
24
  const { willBeFinalAttempt, isFinalFailedAttempt } = require('../lib/delivery-error');
16
25
  const { validateWebhookTarget } = require('../lib/webhook-egress');
@@ -24,7 +33,6 @@ const { Worker, UnrecoverableError } = require('bullmq');
24
33
  const settings = require('../lib/settings');
25
34
 
26
35
  const { REDIS_PREFIX, ACCOUNT_DELETED_NOTIFY, MESSAGE_NEW_NOTIFY } = require('../lib/consts');
27
- const he = require('he');
28
36
 
29
37
  const { fetch: fetchCmd } = require('undici');
30
38
 
@@ -393,21 +401,9 @@ const notifyWorker = new Worker(
393
401
  'X-EE-Wh-Queued-Time': Math.round(Math.max(0, (Date.now() - job.timestamp) / 1000)) + 's'
394
402
  };
395
403
 
396
- let parsed = new URL(webhooks);
397
- let username, password;
398
-
399
- if (parsed.username) {
400
- username = he.decode(parsed.username);
401
- parsed.username = '';
402
- }
403
-
404
- if (parsed.password) {
405
- password = he.decode(parsed.password);
406
- parsed.password = '';
407
- }
408
-
409
- if (username || password) {
410
- headers.Authorization = `Basic ${Buffer.from(he.encode(username || '') + ':' + he.encode(password || '')).toString('base64')}`;
404
+ let { url: parsed, authorization } = splitUrlCredentials(webhooks);
405
+ if (authorization) {
406
+ headers.Authorization = authorization;
411
407
  }
412
408
 
413
409
  if (customRoute) {