emailengine-app 2.79.7 → 2.79.9

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 (188) 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 +37 -0
  5. package/DOCKER_DEPLOYMENT.md +8 -7
  6. package/Dockerfile +35 -11
  7. package/bin/emailengine.js +29 -13
  8. package/config/default.toml +15 -4
  9. package/copy-static-files.sh +23 -5
  10. package/data/google-crawlers.json +7 -1
  11. package/docker-compose.yml +12 -3
  12. package/install.sh +2 -0
  13. package/lib/account.js +26 -1
  14. package/lib/api-routes/account-routes.js +14 -3
  15. package/lib/api-routes/bull-board-routes.js +3 -2
  16. package/lib/api-routes/mailbox-routes.js +4 -1
  17. package/lib/api-routes/message-routes.js +6 -5
  18. package/lib/api-routes/outbox-routes.js +7 -4
  19. package/lib/api-routes/route-helpers.js +8 -0
  20. package/lib/api-routes/settings-routes.js +34 -25
  21. package/lib/api-routes/stats-routes.js +8 -1
  22. package/lib/api-routes/submit-routes.js +2 -1
  23. package/lib/api-routes/template-routes.js +3 -2
  24. package/lib/auth-token.js +73 -2
  25. package/lib/autodetect-imap-settings.js +33 -25
  26. package/lib/bounce-detect.js +45 -0
  27. package/lib/consts.js +13 -2
  28. package/lib/egress-fetch.js +133 -0
  29. package/lib/egress-filter.js +39 -4
  30. package/lib/email-client/base-client.js +274 -24
  31. package/lib/email-client/gmail/gmail-api.js +15 -7
  32. package/lib/email-client/gmail-client.js +121 -64
  33. package/lib/email-client/imap/mailbox.js +18 -59
  34. package/lib/email-client/imap-client.js +53 -29
  35. package/lib/email-client/notification-handler.js +11 -2
  36. package/lib/email-client/outlook/graph-api.js +106 -90
  37. package/lib/email-client/outlook-client.js +222 -106
  38. package/lib/export.js +35 -2
  39. package/lib/generate-text-preview.js +10 -5
  40. package/lib/handlebars-helpers.js +129 -0
  41. package/lib/headers-rewriter.js +1 -1
  42. package/lib/imap-proxy-auth.js +41 -21
  43. package/lib/imapproxy/imap-core/README.md +1 -0
  44. package/lib/imapproxy/imap-core/lib/tls-options.js +5 -46
  45. package/lib/imapproxy/imap-server.js +9 -10
  46. package/lib/llm-pre-process.js +4 -1
  47. package/lib/mcp/json-schema.js +50 -2
  48. package/lib/openapi/index.js +3 -0
  49. package/lib/outbox.js +50 -8
  50. package/lib/pre-process.js +4 -1
  51. package/lib/rate-limit.js +23 -4
  52. package/lib/rewrite-text-nodes.js +12 -1
  53. package/lib/schemas.js +37 -8
  54. package/lib/security-headers.js +396 -0
  55. package/lib/sentry.js +36 -4
  56. package/lib/settings.js +19 -1
  57. package/lib/smtp-auth.js +86 -7
  58. package/lib/sso.js +13 -3
  59. package/lib/submit-progress.js +29 -0
  60. package/lib/templates.js +11 -0
  61. package/lib/tools.js +361 -173
  62. package/lib/ui-routes/account-routes.js +73 -13
  63. package/lib/ui-routes/admin-config-routes.js +7 -21
  64. package/lib/ui-routes/admin-entities-routes.js +42 -12
  65. package/lib/ui-routes/auth-routes.js +87 -28
  66. package/lib/ui-routes/dashboard-routes.js +1 -1
  67. package/lib/ui-routes/export-routes.js +4 -0
  68. package/lib/ui-routes/internals-routes.js +2 -0
  69. package/lib/ui-routes/mcp-consent-routes.js +12 -2
  70. package/lib/ui-routes/network-config-routes.js +6 -5
  71. package/lib/ui-routes/oauth-config-routes.js +12 -1
  72. package/lib/ui-routes/route-helpers.js +65 -14
  73. package/lib/ui-routes/settings-page.js +10 -0
  74. package/lib/ui-routes/smtp-test-routes.js +7 -0
  75. package/lib/ui-routes/suppression-list-routes.js +16 -5
  76. package/lib/ui-routes/unsubscribe-routes.js +22 -3
  77. package/lib/webhook-egress.js +5 -0
  78. package/lib/webhooks.js +14 -2
  79. package/package.json +23 -26
  80. package/sbom.json +1 -1
  81. package/server.js +100 -71
  82. package/static/css/flyonui.css +1 -1
  83. package/static/js/ace/css/ace.css +1462 -0
  84. package/static/js/ace/css/kuroir-1.png +0 -0
  85. package/static/js/ace/css/kuroir-2.png +0 -0
  86. package/static/js/ace/css/main-1.png +0 -0
  87. package/static/js/ace/css/main-10.svg +4 -0
  88. package/static/js/ace/css/main-11.svg +5 -0
  89. package/static/js/ace/css/main-12.svg +4 -0
  90. package/static/js/ace/css/main-13.png +0 -0
  91. package/static/js/ace/css/main-14.png +0 -0
  92. package/static/js/ace/css/main-15.png +0 -0
  93. package/static/js/ace/css/main-16.png +0 -0
  94. package/static/js/ace/css/main-17.png +0 -0
  95. package/static/js/ace/css/main-18.png +0 -0
  96. package/static/js/ace/css/main-19.png +0 -0
  97. package/static/js/ace/css/main-2.png +0 -0
  98. package/static/js/ace/css/main-20.png +0 -0
  99. package/static/js/ace/css/main-21.png +0 -0
  100. package/static/js/ace/css/main-22.png +0 -0
  101. package/static/js/ace/css/main-23.png +0 -0
  102. package/static/js/ace/css/main-24.png +0 -0
  103. package/static/js/ace/css/main-25.svg +1 -0
  104. package/static/js/ace/css/main-26.png +0 -0
  105. package/static/js/ace/css/main-3.png +0 -0
  106. package/static/js/ace/css/main-4.png +0 -0
  107. package/static/js/ace/css/main-5.svg +7 -0
  108. package/static/js/ace/css/main-6.svg +9 -0
  109. package/static/js/ace/css/main-7.svg +7 -0
  110. package/static/js/ace/css/main-8.svg +9 -0
  111. package/static/js/ace/css/main-9.svg +6 -0
  112. package/static/js/ace/css/theme/kuroir.css +78 -0
  113. package/static/js/ace/css/theme/tomorrow_night.css +128 -0
  114. package/static/js/ace/css/theme/tomorrow_night_eighties.css +128 -0
  115. package/static/js/ace/css/theme/xcode.css +106 -0
  116. package/static/js/ace/css/tomorrow_night-1.png +0 -0
  117. package/static/js/ace/css/tomorrow_night-2.png +0 -0
  118. package/static/js/ace/css/tomorrow_night_eighties-1.png +0 -0
  119. package/static/js/ace/css/tomorrow_night_eighties-2.png +0 -0
  120. package/static/js/ace/css/xcode-1.png +0 -0
  121. package/static/js/ace/css/xcode-2.png +0 -0
  122. package/static/js/ee-client.js +256 -102
  123. package/static/js/public.js +7 -0
  124. package/static/js/ui.js +32 -0
  125. package/static/licenses.html +338 -298
  126. package/static/vendor/simplewebauthn/browser.min.js +2 -2
  127. package/translations/messages.pot +158 -112
  128. package/views/account/passkeys.hbs +8 -0
  129. package/views/account/password.hbs +11 -0
  130. package/views/account/security.hbs +18 -7
  131. package/views/accounts/account.hbs +21 -38
  132. package/views/accounts/browse.hbs +3 -1
  133. package/views/accounts/edit.hbs +1 -1
  134. package/views/accounts/register/imap-server.hbs +11 -3
  135. package/views/config/ai.hbs +3 -1
  136. package/views/config/branding.hbs +4 -2
  137. package/views/config/document-store/chat.hbs +1 -1
  138. package/views/config/document-store/index.hbs +1 -1
  139. package/views/config/email-processing.hbs +2 -0
  140. package/views/config/imap-proxy.hbs +3 -1
  141. package/views/config/license.hbs +1 -1
  142. package/views/config/logging.hbs +3 -1
  143. package/views/config/mcp.hbs +3 -1
  144. package/views/config/network.hbs +16 -16
  145. package/views/config/oauth/app.hbs +4 -4
  146. package/views/config/security.hbs +2 -0
  147. package/views/config/service.hbs +3 -1
  148. package/views/config/smtp.hbs +3 -1
  149. package/views/config/webhooks.hbs +4 -2
  150. package/views/error.hbs +10 -2
  151. package/views/internals/index.hbs +1 -1
  152. package/views/layout/app.hbs +9 -14
  153. package/views/layout/login.hbs +1 -1
  154. package/views/layout/prompt.hbs +1 -1
  155. package/views/layout/public.hbs +1 -1
  156. package/views/legal.hbs +1 -1
  157. package/views/mcp/authorize.hbs +1 -1
  158. package/views/partials/ace_assets.hbs +13 -0
  159. package/views/partials/add_account_modal.hbs +1 -1
  160. package/views/partials/address_list.hbs +4 -4
  161. package/views/partials/filter_editor_js.hbs +3 -3
  162. package/views/partials/gateway_js.hbs +1 -1
  163. package/views/partials/oauth_form.hbs +6 -6
  164. package/views/partials/public_theme_init.hbs +1 -1
  165. package/views/partials/template_form.hbs +2 -2
  166. package/views/partials/test_send.hbs +7 -4
  167. package/views/partials/theme_init.hbs +1 -1
  168. package/views/partials/ui/details.hbs +2 -2
  169. package/views/partials/ui/env-managed-alert.hbs +19 -0
  170. package/views/partials/webhook_form.hbs +1 -1
  171. package/views/partials/webhooks_editor_functions.hbs +1 -1
  172. package/views/reference/redirect.hbs +1 -1
  173. package/views/templates/template.hbs +2 -2
  174. package/views/tokens/new.hbs +1 -1
  175. package/views/unsubscribe.hbs +7 -1
  176. package/views/webhooks/webhook.hbs +2 -2
  177. package/workers/api.js +179 -175
  178. package/workers/export.js +1 -5
  179. package/workers/imap.js +33 -6
  180. package/workers/smtp.js +19 -43
  181. package/workers/submit.js +31 -13
  182. package/workers/webhooks.js +9 -24
  183. package/lib/reconnection-manager.js +0 -106
  184. package/static/front/EmailEngine_logo_horiz.png +0 -0
  185. package/static/front/EmailEngine_logo_vert.png +0 -0
  186. package/static/front/index.html +0 -57
  187. package/static/front/logo.png +0 -0
  188. package/static/vendor/handlebars/handlebars.min-v4.7.9.js +0 -29
package/workers/api.js CHANGED
@@ -35,7 +35,7 @@ const {
35
35
  hasEnvValue,
36
36
  getBoolean,
37
37
  loadTlsConfig,
38
- maybeReloadHttpProxyAgent,
38
+ httpAgent,
39
39
  resolveOAuthErrorStatus,
40
40
  constantTimeEqual,
41
41
  verifyServiceSignature,
@@ -117,6 +117,8 @@ const {
117
117
 
118
118
  const registerApiRoutes = require('../lib/api-routes');
119
119
  const bullBoardRoutes = require('../lib/api-routes/bull-board-routes');
120
+ const { securityHeadersExt, attachSecurityContext, isAdminPath, isMachineRoute, isSecureOrigin, CSP_MODES } = require('../lib/security-headers');
121
+ const { registerHandlebarsHelpers } = require('../lib/handlebars-helpers');
120
122
 
121
123
  const {
122
124
  imapSchema,
@@ -124,6 +126,7 @@ const {
124
126
  oauth2Schema,
125
127
  accountIdSchema,
126
128
  apiHeadersSchema,
129
+ headerTimeoutSchema,
127
130
  oauth2ProviderSchema: OAuth2ProviderSchema,
128
131
  accountTypeSchema: AccountTypeSchema
129
132
  } = require('../lib/schemas');
@@ -202,6 +205,16 @@ const API_TLS = hasEnvValue('EENGINE_API_TLS') ? getBoolean(readEnvValue('EENGIN
202
205
  // Merge TLS settings from config params and environment
203
206
  loadTlsConfig(API_TLS, 'EENGINE_API_TLS_');
204
207
 
208
+ // How the Content-Security-Policy is delivered: enforce (default), report-only, or off.
209
+ // An unknown value falls back to enforce, and says so once
210
+ const CSP_MODE_CONFIGURED = String(hasEnvValue('EENGINE_CSP_MODE') ? readEnvValue('EENGINE_CSP_MODE') : config.api.cspMode || '')
211
+ .trim()
212
+ .toLowerCase();
213
+ const CSP_MODE = CSP_MODES.includes(CSP_MODE_CONFIGURED) ? CSP_MODE_CONFIGURED : 'enforce';
214
+ if (CSP_MODE_CONFIGURED && CSP_MODE_CONFIGURED !== CSP_MODE) {
215
+ logger.warn({ msg: 'Unknown Content-Security-Policy mode, enforcing the policy', configured: CSP_MODE_CONFIGURED, cspMode: CSP_MODE });
216
+ }
217
+
205
218
  // Per-worker thread metadata. With multiple API workers (EENGINE_WORKERS_API > 1) the
206
219
  // main thread assigns each one an index and whether to bind with SO_REUSEPORT. Only
207
220
  // worker 0 runs singleton maintenance tasks (e.g. TLS certificate renewal).
@@ -402,6 +415,11 @@ function publishChangeEvent(data) {
402
415
  }
403
416
  }
404
417
 
418
+ // The Hapi server, published by init() once the session strategy is registered and the boot-time
419
+ // default has been decided, so the authData branch of the settings dispatcher below cannot set a
420
+ // strategy that does not exist yet or race the boot-time server.auth.default() call
421
+ let sessionAuthServer = null;
422
+
405
423
  parentPort.on('message', message => {
406
424
  if (message && message.cmd === 'resp' && message.mid && callQueue.has(message.mid)) {
407
425
  let { resolve, reject, timer } = callQueue.get(message.mid);
@@ -454,10 +472,19 @@ parentPort.on('message', message => {
454
472
  }
455
473
 
456
474
  if (message && message.cmd === 'settings') {
457
- // Keep this worker's in-memory HTTP proxy agent in sync when proxy settings change
458
- maybeReloadHttpProxyAgent(message.data);
459
- // ...and the API reference's memoized serviceUrl, which its code samples embed
475
+ // the API reference memoizes serviceUrl, which its code samples embed
460
476
  clearServiceUrlCache();
477
+
478
+ // The first admin password is saved by whichever API worker served the form, and only
479
+ // that worker's server gets the default strategy in-process (lib/ui-routes/auth-routes.js).
480
+ // The same handler broadcasts a settings change carrying the authData key, so with
481
+ // EENGINE_WORKERS_API > 1 the other workers stop serving /admin open here instead of at
482
+ // the next restart. hapi refuses a second default, hence the guard, which also covers
483
+ // the sender.
484
+ if (message.data && message.data.authData && sessionAuthServer && !sessionAuthServer.auth.settings.default) {
485
+ sessionAuthServer.auth.default('session');
486
+ logger.info({ msg: 'Admin session authentication enabled after the first password was set' });
487
+ }
461
488
  }
462
489
  });
463
490
 
@@ -466,98 +493,7 @@ const init = async () => {
466
493
 
467
494
  gt.setLocale((await settings.get('locale')) || 'en');
468
495
 
469
- handlebars.registerHelper('_', (...args) => {
470
- let params = args.slice(1, args.length - 1);
471
-
472
- let locale = params.shift();
473
-
474
- let localGt = locale ? gt.useLocale(locale) : gt;
475
-
476
- let translated = localGt.gettext(args[0]);
477
- if (params.length) {
478
- translated = util.format(translated, ...params);
479
- }
480
-
481
- return new handlebars.SafeString(translated);
482
- });
483
-
484
- // HTML-escape a value for safe interpolation into an otherwise-unescaped context - e.g. a
485
- // dynamic `%s` argument to the SafeString-returning `_` helper. Returns a plain string so
486
- // the surrounding markup stays live while the value itself is entity-escaped.
487
- handlebars.registerHelper('escapeHtml', value => handlebars.escapeExpression(value));
488
-
489
- // Translate Bootstrap-era color names emitted by server code (flash types,
490
- // systemAlerts levels) into the FlyonUI color vocabulary used by the admin
491
- // theme, so templates interpolate a single closed set of class suffixes
492
- // (which the stylesheet safelists). Single translation point - producers
493
- // keep using "danger" etc.
494
- handlebars.registerHelper('eeColor', value => (value === 'danger' ? 'error' : value || 'neutral'));
495
-
496
- // Percent-encode a value for interpolation into a URL path segment. Handlebars escapes for
497
- // HTML, which leaves "#", "/", "?" and "%" untouched - and an account ID is free text, so
498
- // href="/admin/accounts/{{account}}" resolves somewhere else entirely for an ID carrying one.
499
- handlebars.registerHelper('urlpart', value => encodeURIComponent(value === null || value === undefined ? '' : value));
500
-
501
- // Join string fragments in subexpressions, e.g. building composed partial
502
- // hash values: text=(concat "Up to " (formatInteger n locale) " lines")
503
- handlebars.registerHelper('concat', (...args) => args.slice(0, -1).join(''));
504
-
505
- // Ternary for subexpressions: placeholder=(when hasPass "set..." "")
506
- handlebars.registerHelper('when', (cond, truthyValue, falsyValue) => (cond ? truthyValue : typeof falsyValue === 'string' ? falsyValue : ''));
507
-
508
- handlebars.registerHelper('isodate', time => new Date(Number(time)).toISOString());
509
-
510
- handlebars.registerHelper('ngettext', (msgid, plural, count) => util.format(gt.ngettext(msgid, plural, count), count));
511
-
512
- handlebars.registerHelper('equals', function (compareVal, baseVal, options) {
513
- if (baseVal === compareVal) {
514
- return options.fn(this);
515
- }
516
- return options.inverse(this);
517
- });
518
-
519
- handlebars.registerHelper('inc', (nr, inc) => Number(nr) + Number(inc));
520
-
521
- handlebars.registerHelper('json', payload => {
522
- let res;
523
- try {
524
- res = typeof payload === 'undefined' ? 'undefined' : JSON.stringify(payload, false, 2);
525
- } catch (err) {
526
- res = util.inspect(payload, false, 4, false);
527
- }
528
- // SECURITY: return a plain string (NOT a SafeString) so Handlebars HTML-escapes the
529
- // output. `payload` can carry attacker-controlled data (e.g. inbound email fields in
530
- // webhook / pre-processing error logs); wrapping it in a SafeString allowed a stored
531
- // XSS via a </textarea> breakout in the error-log views (security review H1). In the
532
- // <textarea> render contexts this is display-identical (the browser decodes entities).
533
- return res;
534
- });
535
-
536
- handlebars.registerHelper('lastVal', (value, separator) => {
537
- separator = separator || '/';
538
-
539
- let res = (value || '').toString().split(separator).pop();
540
-
541
- return new handlebars.SafeString(res);
542
- });
543
-
544
- handlebars.registerHelper('formatInteger', (intVal, locale) => {
545
- if (isNaN(intVal)) {
546
- // ignore non-numbers
547
- return intVal;
548
- }
549
-
550
- locale = (locale || 'en_US').replace(/_/g, '-');
551
-
552
- let formatter;
553
- try {
554
- formatter = new Intl.NumberFormat(locale, {});
555
- } catch (err) {
556
- formatter = new Intl.NumberFormat('en-US', {});
557
- }
558
-
559
- return formatter.format(intVal);
560
- });
496
+ registerHandlebarsHelpers(handlebars, { gt });
561
497
 
562
498
  // Base Hapi options shared by both the default and SO_REUSEPORT binding paths
563
499
  const serverOptions = {
@@ -574,7 +510,12 @@ const init = async () => {
574
510
  messages: joiLocales,
575
511
  convert: true,
576
512
  errors: {
577
- language: 'en' // Default language
513
+ // Resolved per request from request.app.locale, which onPreAuth sets and
514
+ // hapi exposes to joi as the $app.request context. A locale with no
515
+ // joi catalog falls through to joi's own English messages. This has to be
516
+ // a reference: the route settings are shared by every request on the
517
+ // route, so writing the locale into them races concurrent requests
518
+ language: Joi.ref('$app.request.locale')
578
519
  }
579
520
  },
580
521
  headers: apiHeadersSchema
@@ -634,6 +575,9 @@ const init = async () => {
634
575
  //directoryUrl: 'https://acme-staging-v02.api.letsencrypt.org/directory',
635
576
  },
636
577
 
578
+ // long-lived client, see LiveDispatcher in lib/tools.js
579
+ dispatcher: httpAgent.live,
580
+
637
581
  logger: logger.child({ sub: 'acme' }),
638
582
 
639
583
  encryptFn: async value => {
@@ -770,21 +714,9 @@ const init = async () => {
770
714
  request.app.gt = gt;
771
715
  }
772
716
 
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
- }
717
+ // Validation errors pick their language up from request.app.locale through the
718
+ // errors.language reference in the server-wide route defaults (see serverOptions), so
719
+ // nothing per request is written into the shared route settings here
788
720
 
789
721
  return h.continue;
790
722
  });
@@ -795,7 +727,11 @@ const init = async () => {
795
727
 
796
728
  // Both settings are needed on every request and neither depends on the other, so they are
797
729
  // read in a single HMGET rather than two serialized round trips
798
- let { enableApiProxy, disableTokens } = await settings.getMulti('enableApiProxy', 'disableTokens');
730
+ let { enableApiProxy, disableTokens, serviceUrl } = await settings.getMulti('enableApiProxy', 'disableTokens', 'serviceUrl');
731
+
732
+ // Before anything can render a view (the allowlist refusal below does), so the nonce
733
+ // the template stamps on its scripts is the one the response header carries
734
+ attachSecurityContext(request, { secureOrigin: isSecureOrigin(serviceUrl) });
799
735
 
800
736
  // check if client IP is resolved from X-Forwarded-For or not
801
737
  request.app.ip = resolveClientIp({
@@ -817,14 +753,19 @@ const init = async () => {
817
753
  // the outer request (lib/mcp/inject.js), so the IPC round trip is not paid twice for
818
754
  // one answer that cannot differ within a request.
819
755
  if (!request.app.licenseInfo) {
820
- request.app.licenseInfo = await call({ cmd: 'license', timeout: request.headers['x-ee-timeout'] });
756
+ // This runs before route validation, so the header is still the raw string here. The
757
+ // route schema decides what it accepts (a bad value is that route's 400 later); a value
758
+ // it would refuse is ignored rather than handed to the timer, where a non-number or an
759
+ // overflow collapses to a 1 ms timeout and a 500 before validation ever runs.
760
+ const { error: timeoutError, value: requestTimeout } = headerTimeoutSchema.validate(request.headers['x-ee-timeout']);
761
+ request.app.licenseInfo = await call({ cmd: 'license', timeout: timeoutError ? undefined : requestTimeout });
821
762
  }
822
763
 
823
764
  // flash notifications
824
765
  request.flash = async message => await flash(redis, request, message);
825
766
 
826
767
  if (ADMIN_ACCESS_ADDRESSES && ADMIN_ACCESS_ADDRESSES.length) {
827
- if (request.path.startsWith('/admin') && !matchIp(request.app.ip, ADMIN_ACCESS_ADDRESSES)) {
768
+ if (isAdminPath(request.path) && !matchIp(request.app.ip, ADMIN_ACCESS_ADDRESSES)) {
828
769
  logger.info({
829
770
  msg: 'Blocked access from unlisted IP address',
830
771
  remoteAddress: request.app.ip,
@@ -966,11 +907,16 @@ const init = async () => {
966
907
  // only repeat it
967
908
  tokenData = await tokens.get(token, false, { log: !request.app.mcpInternal, remoteAddress: request.app.ip });
968
909
  } catch (err) {
969
- return {
970
- isValid: false,
971
- credentials: {},
972
- artifacts: { err: err.message }
973
- };
910
+ // A thrown Boom reaches the client the way the scope and permission refusals
911
+ // below do (hapi-auth-bearer-token does not catch it), so the reason travels as a
912
+ // machine-readable code - UnknownToken, ExpiredToken, InvalidToken - while the
913
+ // message stays the generic one the scheme itself would have sent. The scheme
914
+ // name keeps the WWW-Authenticate header the plugin's own refusal carries.
915
+ let error = Boom.unauthorized('Bad token', 'Bearer');
916
+ if (err.code) {
917
+ error.output.payload.code = err.code;
918
+ }
919
+ throw error;
974
920
  }
975
921
 
976
922
  // Bind the token hash (id) to the request logger so it is included in the per-request
@@ -1200,7 +1146,10 @@ const init = async () => {
1200
1146
  error.output.payload.ttl = Math.ceil(rateLimit.ttl);
1201
1147
  error.output.headers = {
1202
1148
  'X-RateLimit-Limit': rateLimit.allowed,
1203
- 'X-RateLimit-Reset': Math.ceil(rateLimit.ttl)
1149
+ 'X-RateLimit-Reset': Math.ceil(rateLimit.ttl),
1150
+ // The conventional header for a 429, so a generic HTTP client backs
1151
+ // off without knowing about the ttl field in the body
1152
+ 'Retry-After': Math.ceil(rateLimit.ttl)
1204
1153
  };
1205
1154
  throw error;
1206
1155
  } else {
@@ -1235,22 +1184,17 @@ const init = async () => {
1235
1184
  await server.register(Cookie);
1236
1185
  await server.register(Bell);
1237
1186
 
1238
- let secureCookie = false;
1239
- try {
1240
- let serviceUrl = await settings.get('serviceUrl');
1241
- if (serviceUrl) {
1242
- let parsedUrl = new URL(serviceUrl);
1243
- secureCookie = parsedUrl.protocol === 'https:';
1244
- }
1245
- } catch (err) {
1246
- // skip
1247
- }
1187
+ // the signal HSTS keys on too, so the cookies and the header agree on what "https" means
1188
+ let secureCookie = isSecureOrigin(await settings.get('serviceUrl'));
1248
1189
 
1249
1190
  server.state('locale', {
1250
1191
  ttl: null,
1251
1192
  encoding: 'base64json',
1252
1193
  clearInvalid: true,
1253
- path: '/'
1194
+ path: '/',
1195
+ // Same signal as the session and CSRF cookies. hapi's default is Secure, which a browser
1196
+ // drops on a plain-http instance, so the chosen locale never stuck there
1197
+ isSecure: secureCookie
1254
1198
  });
1255
1199
 
1256
1200
  // The version an SSO login stamps into its session, so the checks that end a session later can
@@ -1368,12 +1312,20 @@ const init = async () => {
1368
1312
  // break the registered callback URL) disables the SSO button instead of failing mid-flow.
1369
1313
  let getServiceRedirectUrl = async () => new URL((await settings.get('serviceUrl')) || `http://${API_HOST}${API_PORT !== 80 ? `:${API_PORT}` : ''}`);
1370
1314
  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
- }
1315
+ // A sign-in the IdP denied, or the user cancelled, comes back as an unauthenticated try-mode
1316
+ // request. It gets the same flash-and-redirect the allow-list denial in the OIDC handler
1317
+ // uses, so the user lands on the login form with a way to try again rather than on the
1318
+ // generic error page with bell's raw message. The reason goes to the log only. ?sso_denied=1
1319
+ // stops a forced instance from auto-redirecting straight back into the flow.
1320
+ let ssoFailureRedirect = async (request, h, method) => {
1321
+ request.logger.warn({
1322
+ msg: 'SSO login failed',
1323
+ method,
1324
+ reason: (request.auth.error && request.auth.error.message) || 'unknown',
1325
+ remoteAddress: request.app.ip
1326
+ });
1327
+ await request.flash({ type: 'danger', message: 'Single sign-on failed or was cancelled. Please try again' });
1328
+ return h.redirect('/admin/login?sso_denied=1');
1377
1329
  };
1378
1330
 
1379
1331
  if (USE_OKTA_AUTH) {
@@ -1398,10 +1350,28 @@ const init = async () => {
1398
1350
  method: ['GET', 'POST'],
1399
1351
  path: '/admin/login/okta',
1400
1352
  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 });
1353
+ if (!request.auth.isAuthenticated) {
1354
+ return ssoFailureRedirect(request, h, 'okta');
1355
+ }
1356
+
1357
+ let profile = (request.auth.credentials && request.auth.credentials.profile) || {};
1358
+
1359
+ // The same minimal shape the OIDC branch below stores, for the same reasons: the
1360
+ // full bell credentials carry the access and refresh tokens, the callback query
1361
+ // and the raw userinfo document, none of which the session validator reads, and
1362
+ // all of which would sit in the browser's cookie for the life of the session.
1363
+ setAdminSession(request, {
1364
+ provider: 'okta',
1365
+ profile: {
1366
+ id: profile.id,
1367
+ username: profile.username,
1368
+ displayName: profile.displayName,
1369
+ email: profile.email
1370
+ },
1371
+ passwordVersion: await sessionPasswordVersion()
1372
+ });
1373
+
1374
+ request.logger.info({ msg: 'Admin login successful', user: profile.username || 'unknown', method: 'okta', remoteAddress: request.app.ip });
1405
1375
  return h.redirect('/admin');
1406
1376
  },
1407
1377
  options: {
@@ -1463,7 +1433,9 @@ const init = async () => {
1463
1433
  method: ['GET', 'POST'],
1464
1434
  path: '/admin/login/oidc',
1465
1435
  async handler(request, h) {
1466
- assertSsoAuthenticated(request);
1436
+ if (!request.auth.isAuthenticated) {
1437
+ return ssoFailureRedirect(request, h, 'oidc');
1438
+ }
1467
1439
 
1468
1440
  let profile = (request.auth.credentials && request.auth.credentials.profile) || {};
1469
1441
 
@@ -1547,6 +1519,10 @@ const init = async () => {
1547
1519
  server.auth.default('session');
1548
1520
  }
1549
1521
 
1522
+ // From here on a first password set on another API worker switches the session strategy on
1523
+ // through the settings dispatcher (see the authData branch there)
1524
+ sessionAuthServer = server;
1525
+
1550
1526
  await server.register({
1551
1527
  plugin: hapiPino,
1552
1528
  options: {
@@ -2270,40 +2246,44 @@ const init = async () => {
2270
2246
  method: 'GET',
2271
2247
  path: '/oauth',
2272
2248
  async handler(request, h) {
2273
- if (request.query.error) {
2274
- let error = Boom.boomify(new Error(`Oauth failed: ${request.query.error}`), { statusCode: 400 });
2249
+ // The mailbox owner sees these on the public error page, in the same locale as the
2250
+ // rest of the setup flow. The pending setup is still unspent at this point (its state
2251
+ // entry is claimed only below), so opening the setup link again is a valid retry.
2252
+ if (request.query.error === 'access_denied') {
2253
+ let error = Boom.badRequest(
2254
+ request.app.gt.gettext('The sign-in was cancelled or the requested access was not granted. Open the account setup link again to retry.')
2255
+ );
2256
+ if (request.query.error_description) {
2257
+ error.output.payload.details = [String(request.query.error_description)];
2258
+ }
2275
2259
  throw error;
2276
2260
  }
2277
2261
 
2278
- if (!request.query.code) {
2279
- // throw
2280
- let error = Boom.boomify(new Error(`Oauth failed: no code received`), { statusCode: 400 });
2281
- throw error;
2262
+ if (request.query.error) {
2263
+ throw Boom.badRequest(util.format(request.app.gt.gettext('Sign-in with the email provider failed: %s'), request.query.error));
2282
2264
  }
2283
2265
 
2284
- if (!/^account:add:/.test(request.query.state)) {
2285
- let error = Boom.boomify(new Error(`Oauth failed: invalid state received`), { statusCode: 400 });
2286
- throw error;
2266
+ if (!request.query.code) {
2267
+ throw Boom.badRequest(request.app.gt.gettext('Sign-in with the email provider failed: no authorization code was received'));
2287
2268
  }
2288
2269
 
2289
2270
  // Validate nonce format: 16 bytes base64url encoded = 21-22 characters
2290
2271
  // Also accept base64 encoding (+, /, =) for backward compatibility with old cached nonces
2291
- const stateNonce = request.query.state.slice('account:add:'.length);
2292
- if (!/^[A-Za-z0-9_\-+/]{21,22}={0,2}$/.test(stateNonce)) {
2293
- throw Boom.badRequest('Oauth failed: invalid state format');
2272
+ if (!/^account:add:[A-Za-z0-9_\-+/]{21,22}={0,2}$/.test(request.query.state)) {
2273
+ throw Boom.badRequest(request.app.gt.gettext('Sign-in with the email provider failed: the request state is not valid'));
2294
2274
  }
2295
2275
 
2296
2276
  let [[, accountData]] = await redis.multi().get(`${REDIS_PREFIX}${request.query.state}`).del(`${REDIS_PREFIX}${request.query.state}`).exec();
2297
2277
  if (!accountData) {
2298
- let error = Boom.boomify(new Error(`Oauth failed: session expired`), { statusCode: 400 });
2299
- throw error;
2278
+ throw Boom.badRequest(
2279
+ request.app.gt.gettext('The account setup session has expired or was already used. Open the account setup link again to retry.')
2280
+ );
2300
2281
  }
2301
2282
 
2302
2283
  try {
2303
2284
  accountData = JSON.parse(accountData);
2304
2285
  } catch (E) {
2305
- let error = Boom.boomify(new Error(`Oauth failed: invalid session`), { statusCode: 400 });
2306
- throw error;
2286
+ throw Boom.badRequest(request.app.gt.gettext('Sign-in with the email provider failed: the stored setup session is not valid'));
2307
2287
  }
2308
2288
 
2309
2289
  if (!accountData.account) {
@@ -2881,7 +2861,7 @@ const init = async () => {
2881
2861
  skip: (request /*, h*/) => {
2882
2862
  let tags = (request.route && request.route.settings && request.route.settings.tags) || [];
2883
2863
 
2884
- if (tags.includes('api') || tags.includes('scope:metrics') || tags.includes('static') || tags.includes('external')) {
2864
+ if (isMachineRoute(tags)) {
2885
2865
  return true;
2886
2866
  }
2887
2867
 
@@ -3099,7 +3079,14 @@ const init = async () => {
3099
3079
  systemAlerts = systemAlerts.filter(alert => alert.level === 'danger');
3100
3080
  }
3101
3081
 
3082
+ // Whether the requester holds a session at all, so a public page (the hosted form's
3083
+ // error page, for one) can tell a mailbox owner from an admin without reading
3084
+ // authData, which describes the instance rather than the requester
3085
+ const isAuthenticated = !!(request.auth && request.auth.isAuthenticated);
3086
+
3102
3087
  return {
3088
+ // the per-request CSP nonce every inline <script> carries (lib/security-headers.js)
3089
+ cspNonce: request.app.cspNonce,
3103
3090
  pageBrandName: pageBrandName || 'EmailEngine',
3104
3091
  values: request.payload || {},
3105
3092
  errors: (request.error && request.error.details) || {},
@@ -3108,6 +3095,10 @@ const init = async () => {
3108
3095
  licenseDetails,
3109
3096
  trialPossible: !tract,
3110
3097
  authData,
3098
+ isAuthenticated,
3099
+ // The dashboard is an admin destination: a link to it belongs on a page only for
3100
+ // a requester who holds an admin session, or on an instance with no admin login
3101
+ showDashboardLink: isAuthenticated || !(authData && authData.enabled),
3111
3102
  packageData,
3112
3103
  systemAlerts,
3113
3104
  embeddedTemplateHeader,
@@ -3139,14 +3130,16 @@ const init = async () => {
3139
3130
  response = assertPreconditionResult;
3140
3131
  }
3141
3132
 
3142
- if (!response.isBoom) {
3143
- if (request.app.rateLimitHeaders) {
3144
- const headers = request.response.output ? request.response.output.headers : request.response.headers;
3145
- for (let key of Object.keys(request.app.rateLimitHeaders)) {
3146
- headers[key] = request.app.rateLimitHeaders[key].toString();
3147
- }
3133
+ // On error responses too: a client pacing itself by these headers needs them most on
3134
+ // the request that failed, and the JSON error path below copies output.headers over
3135
+ if (request.app.rateLimitHeaders) {
3136
+ const headers = response.isBoom ? response.output.headers : response.headers;
3137
+ for (let key of Object.keys(request.app.rateLimitHeaders)) {
3138
+ headers[key] = request.app.rateLimitHeaders[key].toString();
3148
3139
  }
3140
+ }
3149
3141
 
3142
+ if (!response.isBoom) {
3150
3143
  return h.continue;
3151
3144
  }
3152
3145
 
@@ -3167,17 +3160,21 @@ const init = async () => {
3167
3160
  }
3168
3161
 
3169
3162
  if (error.output && error.output.statusCode === 401 && error.output.headers && /^Bearer/.test(error.output.headers['WWW-Authenticate'])) {
3170
- // bearer auth failed
3171
- return h
3172
- .response({ statusCode: 401, error: 'Unauthorized', message: error.message })
3173
- .header('WWW-Authenticate', error.output.headers['WWW-Authenticate'])
3174
- .code(error.output.statusCode);
3163
+ // bearer auth failed. The api-token strategy attaches the refusal reason as a code,
3164
+ // and it is the one field worth carrying into this rebuilt payload
3165
+ let payload = { statusCode: 401, error: 'Unauthorized', message: error.message };
3166
+ if (error.output.payload.code) {
3167
+ payload.code = error.output.payload.code;
3168
+ }
3169
+ return h.response(payload).header('WWW-Authenticate', error.output.headers['WWW-Authenticate']).code(error.output.statusCode);
3175
3170
  }
3176
3171
 
3177
3172
  const routeTags = (request.route && request.route.settings && request.route.settings.tags) || [];
3178
3173
 
3179
3174
  // `external` covers the MCP endpoint and its OAuth routes: machine-facing surfaces whose
3180
- // clients expect JSON errors, never the admin HTML error page
3175
+ // clients expect JSON errors, never the admin HTML error page. Narrower than
3176
+ // isMachineRoute() on purpose: that one also covers `static`, and a browser following a
3177
+ // link to a missing asset is better served the themed error page than a JSON body
3181
3178
  const wantsJsonError = routeTags.includes('api') || routeTags.includes('external');
3182
3179
 
3183
3180
  if (request.errorInfo && wantsJsonError) {
@@ -3209,10 +3206,16 @@ const init = async () => {
3209
3206
 
3210
3207
  server.ext('onPreResponse', preResponse);
3211
3208
 
3209
+ // After preResponse on purpose: it replaces an error response with the rendered error page
3210
+ // or a JSON body, and the headers have to land on whatever is actually sent
3211
+ server.ext('onPreResponse', securityHeadersExt({ cspMode: CSP_MODE }));
3212
+
3212
3213
  server.ext('onPostAuth', async (request, h) => {
3213
3214
  if (request.requireTotp) {
3214
- // Redirect authenticated pages to login page if TOTP is required
3215
- let url = new URL(`admin/login`, 'http://localhost');
3215
+ // The password step is done and only the second factor is missing, so the session
3216
+ // goes to the TOTP prompt rather than back to the login form, which would ask for
3217
+ // the password again
3218
+ let url = new URL(`admin/totp`, 'http://localhost');
3216
3219
 
3217
3220
  let nextUrl = (request.query && request.query.next) || (request.payload && request.payload.next) || false;
3218
3221
  if (nextUrl) {
@@ -3248,7 +3251,8 @@ const init = async () => {
3248
3251
  return h.response(renderedMetrics).type('text/plain');
3249
3252
  },
3250
3253
  options: {
3251
- tags: ['scope:metrics'],
3254
+ // external: a Prometheus scraper wants JSON errors and no CSRF or page policy
3255
+ tags: ['scope:metrics', 'external'],
3252
3256
  auth: {
3253
3257
  strategy: 'api-token',
3254
3258
  mode: 'required'
package/workers/export.js CHANGED
@@ -17,7 +17,7 @@ const {
17
17
  DEFAULT_EXPORT_MAX_MESSAGES,
18
18
  DEFAULT_EXPORT_MAX_SIZE
19
19
  } = require('../lib/consts');
20
- const { getDuration, readEnvValue, threadStats, maybeReloadHttpProxyAgent } = require('../lib/tools');
20
+ const { getDuration, readEnvValue, threadStats } = require('../lib/tools');
21
21
  const { webhooks: Webhooks } = require('../lib/webhooks');
22
22
  const settings = require('../lib/settings');
23
23
  const {
@@ -975,10 +975,6 @@ parentPort.on('message', message => {
975
975
  .then(response => parentPort.postMessage({ cmd: 'resp', mid: message.mid, response }))
976
976
  .catch(err => parentPort.postMessage({ cmd: 'resp', mid: message.mid, error: err.message, code: err.code, statusCode: err.statusCode }));
977
977
  }
978
-
979
- if (message && message.cmd === 'settings') {
980
- maybeReloadHttpProxyAgent(message.data);
981
- }
982
978
  });
983
979
 
984
980
  logger.info({ msg: 'Started Export worker thread', version: packageData.version });
package/workers/imap.js CHANGED
@@ -7,7 +7,7 @@ const logger = require('../lib/logger');
7
7
 
8
8
  const { REDIS_PREFIX } = require('../lib/consts');
9
9
 
10
- const { getDuration, getBoolean, emitChangeEvent, readEnvValue, hasEnvValue, threadStats, maybeReloadHttpProxyAgent } = require('../lib/tools');
10
+ const { getDuration, getBoolean, emitChangeEvent, readEnvValue, hasEnvValue, threadStats } = require('../lib/tools');
11
11
 
12
12
  const { initSentry } = require('../lib/sentry');
13
13
  initSentry('imap');
@@ -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) {
@@ -845,8 +874,6 @@ class ConnectionHandler {
845
874
 
846
875
  switch (message.cmd) {
847
876
  case 'settings':
848
- maybeReloadHttpProxyAgent(message.data);
849
-
850
877
  if (message.data && message.data.logs) {
851
878
  for (let [account, accountObject] of this.accounts) {
852
879
  // update log handling