emailengine-app 2.79.9 → 2.80.1

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 (146) hide show
  1. package/.release-please-manifest.json +1 -1
  2. package/CHANGELOG.md +73 -0
  3. package/README.md +6 -0
  4. package/config/default.toml +5 -1
  5. package/data/google-crawlers.json +1 -1
  6. package/encrypt.js +43 -0
  7. package/lib/account/account-state.js +62 -0
  8. package/lib/account.js +34 -2
  9. package/lib/api-routes/account-routes.js +101 -1
  10. package/lib/api-routes/blocklist-routes.js +24 -0
  11. package/lib/api-routes/delivery-test-routes.js +6 -0
  12. package/lib/api-routes/gateway-routes.js +30 -0
  13. package/lib/api-routes/index.js +1 -1
  14. package/lib/api-routes/license-routes.js +10 -0
  15. package/lib/api-routes/mcp-oauth-routes.js +3 -3
  16. package/lib/api-routes/mcp-routes.js +39 -21
  17. package/lib/api-routes/oauth2-app-routes.js +38 -1
  18. package/lib/api-routes/outbox-routes.js +6 -0
  19. package/lib/api-routes/permission-map.js +208 -43
  20. package/lib/api-routes/pubsub-routes.js +8 -0
  21. package/lib/api-routes/route-helpers.js +58 -11
  22. package/lib/api-routes/settings-routes.js +67 -6
  23. package/lib/api-routes/stats-routes.js +6 -0
  24. package/lib/api-routes/template-routes.js +21 -0
  25. package/lib/api-routes/token-routes.js +34 -2
  26. package/lib/api-routes/webhook-route-routes.js +13 -0
  27. package/lib/autodetect-imap-settings.js +349 -47
  28. package/lib/cert-handler.js +62 -0
  29. package/lib/consts.js +50 -6
  30. package/lib/db.js +12 -0
  31. package/lib/egress-fetch.js +21 -9
  32. package/lib/email-client/base-client.js +238 -67
  33. package/lib/email-client/credential-errors.js +122 -0
  34. package/lib/email-client/gmail/gmail-api.js +2 -1
  35. package/lib/email-client/gmail-client.js +70 -64
  36. package/lib/email-client/imap/connection-errors.js +52 -0
  37. package/lib/email-client/imap/listing-diff.js +47 -6
  38. package/lib/email-client/imap/login-failure.js +52 -0
  39. package/lib/email-client/imap/mailbox.js +457 -379
  40. package/lib/email-client/imap/subconnection.js +17 -12
  41. package/lib/email-client/imap/sync-operations.js +46 -59
  42. package/lib/email-client/imap-client.js +139 -101
  43. package/lib/email-client/message-builder.js +11 -11
  44. package/lib/email-client/outlook/graph-api.js +2 -1
  45. package/lib/email-client/outlook-client.js +219 -106
  46. package/lib/enum-descriptions.js +12 -2
  47. package/lib/imap-proxy-auth.js +58 -3
  48. package/lib/imapproxy/imap-server.js +53 -62
  49. package/lib/lua/h-del-if-equals.lua +39 -0
  50. package/lib/lua/h-set-if-equals.lua +39 -0
  51. package/lib/mcp/oauth.js +46 -8
  52. package/lib/mcp/protocol.js +78 -35
  53. package/lib/mcp/tools.js +53 -17
  54. package/lib/privileged-settings.js +147 -0
  55. package/lib/routes-ui.js +4 -34
  56. package/lib/schemas.js +92 -16
  57. package/lib/security-headers.js +15 -0
  58. package/lib/settings.js +13 -0
  59. package/lib/tls/catalog.js +428 -0
  60. package/lib/tls/context.js +302 -0
  61. package/lib/tls/der.js +223 -0
  62. package/lib/tls/listeners.js +62 -0
  63. package/lib/tls/provision.js +555 -0
  64. package/lib/tls/self-signed.js +282 -0
  65. package/lib/tls/status.js +480 -0
  66. package/lib/tls/store.js +667 -0
  67. package/lib/token-permission-view.js +252 -102
  68. package/lib/token-permissions.js +176 -26
  69. package/lib/tokens.js +7 -6
  70. package/lib/tools.js +73 -27
  71. package/lib/ui-routes/account-routes.js +43 -30
  72. package/lib/ui-routes/admin-config-routes.js +63 -22
  73. package/lib/ui-routes/admin-entities-routes.js +23 -13
  74. package/lib/ui-routes/auth-routes.js +16 -1
  75. package/lib/ui-routes/internals-routes.js +3 -5
  76. package/lib/ui-routes/mcp-consent-routes.js +72 -31
  77. package/lib/ui-routes/network-config-routes.js +54 -45
  78. package/lib/ui-routes/tls-config-routes.js +628 -0
  79. package/lib/utils/mailbox-path.js +51 -0
  80. package/lib/utils/severity.js +31 -0
  81. package/package.json +12 -12
  82. package/sbom.json +1 -1
  83. package/server.js +23 -1
  84. package/static/css/flyonui.css +1 -1
  85. package/static/css/src/app.tailwind.css +11 -0
  86. package/static/js/app.js +34 -0
  87. package/static/js/public.js +6 -2
  88. package/static/js/ui.js +97 -61
  89. package/static/licenses.html +341 -1252
  90. package/translations/messages.pot +62 -56
  91. package/views/account/login-redirect.hbs +22 -0
  92. package/views/account/passkeys.hbs +2 -2
  93. package/views/accounts/account.hbs +2 -2
  94. package/views/accounts/browse.hbs +1 -1
  95. package/views/accounts/edit.hbs +1 -1
  96. package/views/accounts/register/imap-server.hbs +1 -1
  97. package/views/config/ai.hbs +1 -1
  98. package/views/config/branding.hbs +2 -2
  99. package/views/config/document-store/chat.hbs +1 -1
  100. package/views/config/document-store/index.hbs +1 -1
  101. package/views/config/imap-proxy.hbs +1 -4
  102. package/views/config/license.hbs +1 -1
  103. package/views/config/mcp.hbs +88 -52
  104. package/views/config/network.hbs +1 -1
  105. package/views/config/oauth/app.hbs +2 -2
  106. package/views/config/service.hbs +1 -1
  107. package/views/config/smtp.hbs +1 -4
  108. package/views/config/tls-upload.hbs +81 -0
  109. package/views/config/tls.hbs +593 -0
  110. package/views/config/webhooks.hbs +2 -2
  111. package/views/internals/index.hbs +1 -1
  112. package/views/layout/app.hbs +6 -6
  113. package/views/layout/login.hbs +5 -5
  114. package/views/layout/main.hbs +2 -2
  115. package/views/layout/prompt.hbs +3 -3
  116. package/views/layout/public.hbs +1 -1
  117. package/views/mcp/authorize.hbs +47 -45
  118. package/views/partials/ace_assets.hbs +1 -1
  119. package/views/partials/add_account_modal.hbs +1 -1
  120. package/views/partials/filter_editor_js.hbs +2 -2
  121. package/views/partials/gateway_js.hbs +1 -1
  122. package/views/partials/mcp_access_levels.hbs +16 -9
  123. package/views/partials/mcp_tool_count.hbs +15 -14
  124. package/views/partials/oauth_form.hbs +1 -1
  125. package/views/partials/public_theme_init.hbs +1 -1
  126. package/views/partials/side_menu.hbs +1 -0
  127. package/views/partials/template_form.hbs +1 -1
  128. package/views/partials/theme_init.hbs +1 -1
  129. package/views/partials/tls_security_card.hbs +25 -53
  130. package/views/partials/ui/alert-banner.hbs +3 -2
  131. package/views/partials/ui/badge.hbs +6 -2
  132. package/views/partials/ui/btn.hbs +5 -2
  133. package/views/partials/webhooks_editor_functions.hbs +1 -1
  134. package/views/reference/index.hbs +1 -1
  135. package/views/reference/redirect.hbs +1 -1
  136. package/views/reference/tag.hbs +1 -1
  137. package/views/reference/token.hbs +1 -1
  138. package/views/templates/template.hbs +1 -1
  139. package/views/tokens/new.hbs +175 -74
  140. package/views/unsubscribe.hbs +1 -1
  141. package/views/webhooks/webhook.hbs +1 -1
  142. package/workers/api.js +102 -142
  143. package/workers/imap-proxy.js +4 -1
  144. package/workers/smtp.js +51 -44
  145. package/views/partials/tls_security_js.hbs +0 -64
  146. package/views/partials/tls_security_modal.hbs +0 -22
package/workers/api.js CHANGED
@@ -35,15 +35,13 @@ const {
35
35
  hasEnvValue,
36
36
  getBoolean,
37
37
  loadTlsConfig,
38
- httpAgent,
39
38
  resolveOAuthErrorStatus,
40
39
  constantTimeEqual,
41
40
  verifyServiceSignature,
42
41
  claimFormNonce,
43
42
  releaseFormNonce,
44
43
  setAdminSession,
45
- isEndedSession,
46
- reloadTlsServers
44
+ isEndedSession
47
45
  } = require('../lib/tools');
48
46
  const { matchIp, resolveClientIp, detectAutomatedRequest } = require('../lib/utils/network');
49
47
 
@@ -77,7 +75,7 @@ const tokenPermissions = require('../lib/token-permissions');
77
75
  const { mcpFeatureEnabled } = require('../lib/mcp');
78
76
  const mcpListen = require('../lib/mcp/listen');
79
77
  const tokenAuditLog = require('../lib/token-audit-log');
80
- const { routeGrant, surfaceAdmits, sessionTokenAdmits } = require('../lib/api-routes/permission-map');
78
+ const { routeGrant, perRequestSurfaceAdmits, sessionTokenAdmits } = require('../lib/api-routes/permission-map');
81
79
  const { mcpOptions } = require('../lib/api-routes/route-metadata');
82
80
 
83
81
  const { redis, documentsQueue } = require('../lib/db');
@@ -94,16 +92,16 @@ const specOptions = require('../lib/swagger-options');
94
92
  const { registerOpenApiRoute } = require('../lib/openapi');
95
93
  const { getModel: getApiReferenceModel, clearServiceUrlCache } = require('../lib/api-reference');
96
94
 
97
- const { encrypt, decrypt } = require('../lib/encrypt');
98
- const { Certs, isRenewalDue } = require('@postalsys/certs');
99
- const net = require('net');
95
+ const { createCertHandler } = require('../lib/cert-handler');
96
+ const { createTlsContext, applyTlsContext, apiTlsConfig } = require('../lib/tls/context');
97
+ const { reconcileCertificates, requestProvisioning } = require('../lib/tls/provision');
98
+ const { buildCertificateStatus } = require('../lib/tls/status');
100
99
 
101
100
  const consts = require('../lib/consts');
102
101
  const {
103
102
  TRACK_OPEN_NOTIFY,
104
103
  TRACK_CLICK_NOTIFY,
105
104
  REDIS_PREFIX,
106
- BLOCK_TLS_RENEW,
107
105
  TLS_RENEW_CHECK_INTERVAL,
108
106
  DEFAULT_CORS_MAX_AGE,
109
107
  LIST_UNSUBSCRIBE_NOTIFY,
@@ -200,7 +198,7 @@ const API_PORT =
200
198
  const API_HOST = readEnvValue('EENGINE_HOST') || config.api.host;
201
199
 
202
200
  // Either an object (TLS enabled) or `false` (TLS disabled)
203
- const API_TLS = hasEnvValue('EENGINE_API_TLS') ? getBoolean(readEnvValue('EENGINE_API_TLS')) && (config.api.tls || {}) : config.api.tls || false;
201
+ const API_TLS = apiTlsConfig();
204
202
 
205
203
  // Merge TLS settings from config params and environment
206
204
  loadTlsConfig(API_TLS, 'EENGINE_API_TLS_');
@@ -378,6 +376,12 @@ async function onCommand(command) {
378
376
  switch (command.cmd) {
379
377
  case 'resource-usage':
380
378
  return threadStats.usage();
379
+
380
+ case 'apiReloadCertificates':
381
+ // Every API worker gets this, not just the one that ordered the certificate: the
382
+ // reconciler is a singleton but the HTTPS listeners are not, and a sibling worker that
383
+ // kept its old context would go on serving the certificate that was just replaced.
384
+ return refreshApiTls ? await refreshApiTls() : { updated: false };
381
385
  default:
382
386
  logger.debug({ msg: 'Unhandled command', command });
383
387
  return 999;
@@ -420,6 +424,10 @@ function publishChangeEvent(data) {
420
424
  // strategy that does not exist yet or race the boot-time server.auth.default() call
421
425
  let sessionAuthServer = null;
422
426
 
427
+ // Installs a renewed certificate on this worker's own HTTPS listener. Published by init() when the
428
+ // API is serving TLS, and called through the apiReloadCertificates command.
429
+ let refreshApiTls = null;
430
+
423
431
  parentPort.on('message', message => {
424
432
  if (message && message.cmd === 'resp' && message.mid && callQueue.has(message.mid)) {
425
433
  let { resolve, reject, timer } = callQueue.get(message.mid);
@@ -523,6 +531,25 @@ const init = async () => {
523
531
  }
524
532
  };
525
533
 
534
+ let certHandler = createCertHandler(logger);
535
+
536
+ // The admin UI and REST API over HTTPS. EENGINE_API_TLS_* and [api.tls] supply the certificate
537
+ // when the operator has one; everything they leave out comes from the same sources every other
538
+ // listener uses, so an instance that already holds a Let's Encrypt certificate for its own
539
+ // service domain no longer needs a second, external pipeline to serve it here.
540
+ let apiTlsContext = null;
541
+ if (API_TLS) {
542
+ apiTlsContext = await createTlsContext({
543
+ certs: certHandler,
544
+ logger,
545
+ listener: 'api',
546
+ // The operator's material and handshake settings are snapshotted inside, at entry,
547
+ // before the resolved options are merged back into this same object below
548
+ listenerOptions: API_TLS
549
+ });
550
+ Object.assign(API_TLS, apiTlsContext.options);
551
+ }
552
+
526
553
  // With multiple API workers we provide our own listener and bind it ourselves with
527
554
  // SO_REUSEPORT so the kernel load-balances connections. Hapi forbids port/host when
528
555
  // autoListen is false and needs a truthy `tls` flag to treat a provided HTTPS
@@ -543,108 +570,58 @@ const init = async () => {
543
570
 
544
571
  const server = Hapi.server(serverOptions);
545
572
 
573
+ if (apiTlsContext && typeof server.listener.setSecureContext === 'function') {
574
+ // Connections already established keep the context they negotiated with; the next handshake
575
+ // gets the new one, which is why this does not restart anything.
576
+ refreshApiTls = async () =>
577
+ await applyTlsContext({
578
+ context: apiTlsContext,
579
+ // setSecureContext() replaces the context rather than merging into it: anything
580
+ // left out reverts to Node's default, so a reload that sent only the certificate
581
+ // and key dropped the operator's ca, ciphers and version bounds at the first
582
+ // renewal. SNICallback is a listener option and is not one of them.
583
+ apply: options => {
584
+ const secureContext = Object.assign({}, options);
585
+ delete secureContext.SNICallback;
586
+ server.listener.setSecureContext(secureContext);
587
+ },
588
+ logger
589
+ });
590
+ }
591
+
546
592
  let assertPreconditionResult;
547
593
  server.decorate('toolkit', 'getESClient', async (...args) => await getESClient(...args));
548
594
 
549
- let getServiceDomain = async () => {
550
- let serviceUrl = await settings.get('serviceUrl');
551
- let parsedUrl;
552
-
553
- try {
554
- parsedUrl = new URL(serviceUrl);
555
- } catch (err) {
556
- parsedUrl = {};
557
- }
558
-
559
- let hostname = (parsedUrl.hostname || '').toString().toLowerCase().trim();
560
- if (!hostname || net.isIP(hostname) || ['localhost'].includes(hostname) || /(\.local|\.lan)$/i.test(hostname)) {
561
- // empty string, not false: the value is interpolated into
562
- // templates, where a boolean would render as the text "false"
563
- return '';
564
- }
565
- return hostname;
595
+ // A read-only view of the certificate store for routes. Ordering a certificate is the
596
+ // reconciler's job - it owns the state a page follows, the retry pacing and the listener
597
+ // reload - and the difference between reading and ordering is one argument
598
+ // (`getCertificate(host, false)`), which is not a difference a route should be able to make by
599
+ // accident. Routes that need one ask through requestCertificates() below.
600
+ const readOnlyCerts = {
601
+ getCertificate: async hostname => await certHandler.getCertificate(hostname, true),
602
+ deleteCertificateData: async hostname => await certHandler.deleteCertificateData(hostname),
603
+ routeHandler: async (...args) => await certHandler.routeHandler(...args)
566
604
  };
567
605
 
568
- let certHandler = new Certs({
569
- redis,
570
- namespace: `${REDIS_PREFIX}`,
571
-
572
- acme: {
573
- environment: 'emailengine',
574
- directoryUrl: 'https://acme-v02.api.letsencrypt.org/directory'
575
- //directoryUrl: 'https://acme-staging-v02.api.letsencrypt.org/directory',
576
- },
606
+ server.decorate('toolkit', 'certs', readOnlyCerts);
577
607
 
578
- // long-lived client, see LiveDispatcher in lib/tools.js
579
- dispatcher: httpAgent.live,
580
-
581
- logger: logger.child({ sub: 'acme' }),
582
-
583
- encryptFn: async value => {
584
- const encryptSecret = await getSecret();
585
- return encrypt(value, encryptSecret);
586
- },
587
-
588
- decryptFn: async value => {
589
- const encryptSecret = await getSecret();
590
- return decrypt(value, encryptSecret);
591
- }
592
- });
593
-
594
- server.decorate('toolkit', 'serviceDomain', getServiceDomain);
595
- server.decorate('toolkit', 'certs', certHandler);
608
+ server.decorate(
609
+ 'toolkit',
610
+ 'requestCertificates',
611
+ async (hostnames, requestLogger) => await requestProvisioning({ certs: certHandler, logger: requestLogger || logger, call, hostnames })
612
+ );
596
613
 
597
614
  server.decorate('toolkit', 'checkRateLimit', checkRateLimit);
598
615
 
599
- server.decorate('toolkit', 'getCertificate', async provision => {
600
- let hostname = await getServiceDomain();
601
- let certificateData;
602
-
603
- if (hostname) {
604
- certificateData = await certHandler.getCertificate(hostname, !provision);
605
- }
606
-
607
- if (!certificateData) {
608
- certificateData = {
609
- domain: hostname,
610
- status: 'self_signed',
611
- label: { type: 'warning', text: 'Self-signed', title: 'Using a self-signed certificate' }
612
- };
613
- } else if (certificateData.status !== 'valid') {
614
- switch (certificateData.status) {
615
- case 'pending':
616
- certificateData.label = { type: 'info', text: 'Provisioning...', title: 'Currently provisioning a certificate' };
617
- break;
618
- case 'failed':
619
- certificateData.label = {
620
- type: 'error',
621
- text: 'Failed',
622
- title: (certificateData.lastError && certificateData.lastError.err) || 'Failed to generate a certificate'
623
- };
624
- break;
625
- }
626
- } else if (certificateData.validFrom > new Date()) {
627
- certificateData.label = {
628
- type: 'warning',
629
- text: 'Future certificate',
630
- title: 'Certificate is not yet valid'
631
- };
632
- } else if (certificateData.validTo < new Date()) {
633
- certificateData.label = {
634
- type: 'warning',
635
- text: 'Expired certificate',
636
- title: (certificateData.lastError && certificateData.lastError.err) || 'Certificate has been expired'
637
- };
638
- } else {
639
- certificateData.label = {
640
- type: 'success',
641
- text: 'Valid certificate',
642
- title: certificateData.fingerprint
643
- };
644
- }
616
+ // The certificate model the admin UI renders. Reading it never provisions anything: ordering a
617
+ // certificate is the reconciler's job, and a page render that could start an ACME order was
618
+ // exactly how a checkbox came to hold an HTTP request open for the length of one.
619
+ server.decorate('toolkit', 'tlsStatus', async () => await buildCertificateStatus({ certs: readOnlyCerts }));
645
620
 
646
- return certificateData;
647
- });
621
+ server.decorate('toolkit', 'apiTlsInfo', () => ({
622
+ enabled: !!API_TLS,
623
+ active: apiTlsContext ? apiTlsContext.active : null
624
+ }));
648
625
 
649
626
  server.ext('onPreAuth', async (request, h) => {
650
627
  const tags = (request.route && request.route.settings && request.route.settings.tags) || [];
@@ -955,13 +932,13 @@ const init = async () => {
955
932
  account: (request.params && request.params.account) || queryAccount || tokenData.account || null
956
933
  };
957
934
 
958
- // `mcp` is a surface scope like `smtp`: it admits exactly the API operations the MCP
959
- // tool set wraps (surfaceAdmits over SURFACE_GRANTS.mcp), and only on requests the
960
- // MCP endpoint dispatched itself - request.app.mcpInternal is set by
961
- // lib/mcp/inject.js and cannot be set from the network, so an mcp-scoped token
962
- // presented to plain REST is refused here like any other missing scope.
963
- const mcpSurfaceAdmits =
964
- scopes.includes('api') && tokenData.scopes && tokenData.scopes.includes('mcp') && !!request.app.mcpInternal && surfaceAdmits('mcp', grant);
935
+ // `mcp` and `mcp-manage` are surface scopes like `smtp`: each admits exactly the API
936
+ // operations its half of the MCP tool set wraps (perRequestSurfaceAdmits over
937
+ // SURFACE_GRANTS), and only on requests the MCP endpoint dispatched itself -
938
+ // request.app.mcpInternal is set by lib/mcp/inject.js and cannot be set from the
939
+ // network, so an mcp-scoped token presented to plain REST is refused here like any
940
+ // other missing scope.
941
+ const mcpSurfaceAdmits = scopes.includes('api') && !!request.app.mcpInternal && perRequestSurfaceAdmits(tokenData.scopes, grant);
965
942
 
966
943
  const hasRequiredScope =
967
944
  !scopes.length ||
@@ -3336,12 +3313,21 @@ const init = async () => {
3336
3313
  });
3337
3314
  });
3338
3315
 
3339
- // renew TLS certificates if needed
3316
+ // Keep the configured hostnames supplied with certificates.
3317
+ //
3318
+ // This used to be a renewal timer and nothing else: it read the certificate for the service
3319
+ // domain and, if one existed, asked whether it was due for replacement. A hostname with no
3320
+ // certificate at all was therefore never provisioned by it - not on a fresh install, not after
3321
+ // a flushed Redis, not after a restored backup - and the only way to get a first certificate
3322
+ // was a checkbox in the admin UI that ordered one in the foreground. An instance whose record
3323
+ // was lost stayed down until somebody noticed and clicked it twice.
3324
+ //
3325
+ // The reconciler in lib/tls/provision.js owns the whole decision now, including the renewal
3326
+ // one, and it is the only thing that orders certificates. The admin UI's button asks it to run
3327
+ // immediately rather than doing the work itself. A first order still needs a listener with TLS
3328
+ // switched on, which is what the checkbox used to be; see listenersServeTls() there.
3340
3329
  setInterval(() => {
3341
3330
  async function handler() {
3342
- let serviceDomain = await getServiceDomain();
3343
- let currentCert = await certHandler.getCertificate(serviceDomain, true);
3344
-
3345
3331
  try {
3346
3332
  await runPrechecks(redis);
3347
3333
  assertPreconditionResult = false;
@@ -3349,37 +3335,11 @@ const init = async () => {
3349
3335
  assertPreconditionResult = Boom.boomify(err);
3350
3336
  }
3351
3337
 
3352
- // isRenewalDue() asks whether the certificate is close enough to expiry to replace,
3353
- // scaled to the lifetime the CA issued. This used to compare against
3354
- // Date.now() - RENEW_TLS_AFTER, which is the expiry date thirty days in the past: it
3355
- // read as "renew with thirty days left" but meant "renew thirty days after it died",
3356
- // so the automatic path only ever ran once the certificate had been broken for a
3357
- // month. Let's Encrypt is on the way from 90 day certificates to 45, which would have
3358
- // left a service unreachable for two thirds of every certificate's life.
3359
- if (
3360
- IS_PRIMARY_API_WORKER &&
3361
- currentCert &&
3362
- isRenewalDue(currentCert) &&
3363
- (!currentCert.lastCheck || currentCert.lastCheck < new Date(Date.now() - BLOCK_TLS_RENEW))
3364
- ) {
3365
- try {
3366
- let renewedCert = await certHandler.acquireCert(serviceDomain);
3367
-
3368
- // Only when the certificate actually changed, so a renewal that was skipped
3369
- // or failed does not restart both servers for nothing.
3370
- if (renewedCert && renewedCert.fingerprint && renewedCert.fingerprint !== currentCert.fingerprint) {
3371
- await reloadTlsServers(call, logger, { serviceDomain });
3372
- }
3373
- } catch (err) {
3374
- logger.error({ msg: 'Failed to acquire TLS certificate', serviceDomain, err });
3375
- } finally {
3376
- try {
3377
- await certHandler.setCertificateData(serviceDomain, { lastCheck: new Date() });
3378
- } catch (err) {
3379
- logger.error({ msg: 'Failed to set certificate data', serviceDomain, err });
3380
- }
3381
- }
3338
+ if (!IS_PRIMARY_API_WORKER) {
3339
+ return;
3382
3340
  }
3341
+
3342
+ await reconcileCertificates({ certs: certHandler, logger, call });
3383
3343
  }
3384
3344
 
3385
3345
  handler().catch(err => logger.error({ msg: 'Failed to run certificate handler', err }));
@@ -7,7 +7,7 @@ const logger = require('../lib/logger');
7
7
 
8
8
  const { threadStats } = require('../lib/tools');
9
9
 
10
- const { run } = require('../lib/imapproxy/imap-server');
10
+ const { run, reloadCertificates } = require('../lib/imapproxy/imap-server');
11
11
 
12
12
  const { initSentry } = require('../lib/sentry');
13
13
  initSentry('imapProxy');
@@ -16,6 +16,9 @@ async function onCommand(command) {
16
16
  switch (command.cmd) {
17
17
  case 'resource-usage':
18
18
  return threadStats.usage();
19
+
20
+ case 'imapProxyReloadCertificates':
21
+ return await reloadCertificates();
19
22
  default:
20
23
  logger.debug({ msg: 'Unhandled command', command });
21
24
  return 999;
package/workers/smtp.js CHANGED
@@ -6,7 +6,8 @@ const packageData = require('../package.json');
6
6
  const config = require('@zone-eu/wild-config');
7
7
  const logger = require('../lib/logger');
8
8
 
9
- const { getDuration, emitChangeEvent, readEnvValue, threadStats, loadTlsConfig, assertTlsCredentials, getByteSize, httpAgent } = require('../lib/tools');
9
+ const { getDuration, emitChangeEvent, readEnvValue, threadStats, loadTlsConfig, assertTlsCredentials, getByteSize } = require('../lib/tools');
10
+ const { createTlsContext, applyTlsContext } = require('../lib/tls/context');
10
11
  const { createSmtpAuthHandler, createSmtpAccountResolver } = require('../lib/smtp-auth');
11
12
 
12
13
  const { initSentry } = require('../lib/sentry');
@@ -14,13 +15,10 @@ initSentry('smtp');
14
15
 
15
16
  const { SMTPServer } = require('smtp-server');
16
17
  const util = require('util');
17
- const { redis } = require('../lib/db');
18
- const getSecret = require('../lib/get-secret');
19
18
  const { collectMessage } = require('../lib/smtp-message-processor');
20
19
  const settings = require('../lib/settings');
21
20
 
22
- const { encrypt, decrypt } = require('../lib/encrypt');
23
- const { Certs } = require('@postalsys/certs');
21
+ const { createCertHandler } = require('../lib/cert-handler');
24
22
 
25
23
  config.smtp = config.smtp || {
26
24
  enabled: false,
@@ -32,7 +30,7 @@ config.smtp = config.smtp || {
32
30
 
33
31
  config.service = config.service || {};
34
32
 
35
- const { REDIS_PREFIX, DEFAULT_MAX_SMTP_MESSAGE_SIZE } = require('../lib/consts');
33
+ const { DEFAULT_MAX_SMTP_MESSAGE_SIZE } = require('../lib/consts');
36
34
 
37
35
  const DEFAULT_EENGINE_TIMEOUT = 10 * 1000;
38
36
 
@@ -47,6 +45,12 @@ const SMTP_MAX_CLIENTS = Number(readEnvValue('EENGINE_SMTP_MAX_CLIENTS') || conf
47
45
 
48
46
  const ACCOUNT_CACHE = new WeakMap();
49
47
 
48
+ // The running listener and the TLS material it serves, kept at module level so the certificate
49
+ // reload command can reach both. A renewal used to terminate this worker, which cut every
50
+ // submission in flight; the listener can be handed a new secure context instead.
51
+ let smtpServer = null;
52
+ let tlsContext = null;
53
+
50
54
  let callQueue = new Map();
51
55
  let mids = 0;
52
56
 
@@ -132,27 +136,8 @@ async function init() {
132
136
  useProxy: await settings.get('smtpServerProxy')
133
137
  };
134
138
 
135
- let certs = new Certs({
136
- redis,
137
- namespace: `${REDIS_PREFIX}`,
138
-
139
- environment: 'ee',
140
-
141
- // long-lived client, see LiveDispatcher in lib/tools.js
142
- dispatcher: httpAgent.live,
143
-
144
- logger: logger.child({ sub: 'acme' }),
145
-
146
- encryptFn: async value => {
147
- const encryptSecret = await getSecret();
148
- return encrypt(value, encryptSecret);
149
- },
150
-
151
- decryptFn: async value => {
152
- const encryptSecret = await getSecret();
153
- return decrypt(value, encryptSecret);
154
- }
155
- });
139
+ // Reads what the API worker provisioned; this one never orders a certificate itself.
140
+ let certs = createCertHandler(logger);
156
141
 
157
142
  // check and update authentication settings on connection
158
143
  serverOptions.onConnect = (session, callback) => {
@@ -258,25 +243,20 @@ async function init() {
258
243
  serverOptions.secure = true;
259
244
  serverOptions.allowInsecureAuth = false;
260
245
 
246
+ // Environment and config-file material first. It used to be loaded here and then
247
+ // overwritten by whatever Let's Encrypt had provisioned, so an operator who pinned a
248
+ // certificate through EENGINE_SMTP_TLS_CERT was silently served a different one.
249
+ // lib/tls/context.js keeps it ahead of every automatic source instead.
261
250
  loadTlsConfig(serverOptions, 'EENGINE_SMTP_TLS_');
262
251
 
263
- // load certificates
264
- let serviceUrl = await settings.get('serviceUrl');
265
- let hostname = (new URL(serviceUrl).hostname || '').toString().toLowerCase().trim();
266
- if (hostname) {
267
- let certificateData = await certs.getCertificate(hostname, true);
268
- if (certificateData && certificateData.status === 'valid') {
269
- serverOptions.cert =
270
- certificateData.cert +
271
- '\n' +
272
- []
273
- .concat(certificateData.ca || [])
274
- .flatMap(entry => entry)
275
- .join('\n');
276
- serverOptions.key = certificateData.privateKey;
277
- }
278
- }
252
+ // The material loaded above is snapshotted inside, at entry. The resolved material is
253
+ // written back into serverOptions below, so a later refresh reading this object again would
254
+ // believe the operator had supplied whatever it resolved through the environment.
255
+ tlsContext = await createTlsContext({ certs, logger, listener: 'smtp', listenerOptions: serverOptions });
256
+ Object.assign(serverOptions, tlsContext.options);
279
257
 
258
+ // Reached only when there is no material at all, which now means the self-signed fallback
259
+ // could not be generated either - a broken instance rather than a missing certificate.
280
260
  assertTlsCredentials(serverOptions, 'The SMTP server');
281
261
  } else {
282
262
  serverOptions.disabledCommands = ['STARTTLS'];
@@ -284,6 +264,7 @@ async function init() {
284
264
  }
285
265
 
286
266
  server = new SMTPServer(serverOptions);
267
+ smtpServer = server;
287
268
 
288
269
  let port = await settings.get('smtpServerPort');
289
270
  let host = await settings.get('smtpServerHost');
@@ -304,7 +285,7 @@ async function init() {
304
285
  resolve();
305
286
  });
306
287
  });
307
- await emitChangeEvent(logger, null, 'smtpServerState', 'listening');
288
+ await emitChangeEvent(logger, null, 'smtpServerState', 'listening', { tls: tlsContext ? tlsContext.active : null });
308
289
  } catch (err) {
309
290
  await emitChangeEvent(logger, null, 'smtpServerState', 'failed', {
310
291
  error: { message: err.message, code: err.code || null }
@@ -315,10 +296,36 @@ async function init() {
315
296
  return server;
316
297
  }
317
298
 
299
+ /**
300
+ * Re-resolves the TLS material and hands it to the running listener.
301
+ *
302
+ * Connections already established keep the context they negotiated with; the next handshake gets
303
+ * the new one. Nothing here restarts the server, which is the whole point: a renewal is not a
304
+ * reason to drop a submission that is halfway through DATA.
305
+ *
306
+ * @returns {Promise<Object>} What the listener is serving after the reload
307
+ */
308
+ async function reloadCertificates() {
309
+ const result = await applyTlsContext({
310
+ context: smtpServer ? tlsContext : null,
311
+ apply: options => smtpServer.updateSecureContext(options),
312
+ logger
313
+ });
314
+
315
+ if (result.updated) {
316
+ await emitChangeEvent(logger, null, 'smtpServerState', 'listening', { tls: result.tls });
317
+ }
318
+
319
+ return result;
320
+ }
321
+
318
322
  async function onCommand(command) {
319
323
  switch (command.cmd) {
320
324
  case 'resource-usage':
321
325
  return threadStats.usage();
326
+
327
+ case 'smtpReloadCertificates':
328
+ return await reloadCertificates();
322
329
  default:
323
330
  logger.debug({ msg: 'Unhandled command', command });
324
331
  return 999;
@@ -1,64 +0,0 @@
1
- {{!-- certificate provisioning logic for tls_security_card; include INSIDE
2
- the page's DOMContentLoaded script block. Both config pages provision
3
- through the same endpoint - the certificate belongs to the service
4
- domain, not to either server. Expects the page to define
5
- renderExamples() (both do).
6
- Params:
7
- field - the TLS checkbox id (matches tls_security_card) --}}
8
- let loadingCertData = false;
9
- let loadedCertData = false;
10
-
11
- function loadCertData() {
12
- loadingCertData = true;
13
-
14
- for (let elm of document.querySelectorAll('#tlsModal .modal-show-error')) {
15
- elm.classList.add('hidden')
16
- }
17
-
18
- for (let elm of document.querySelectorAll('#tlsModal .modal-show-default')) {
19
- elm.classList.remove('hidden')
20
- }
21
-
22
- uiModal.open('#tlsModal');
23
-
24
- uiPostJson('/admin/config/smtp/certificate').then(data => {
25
- if (!data || !data.success) {
26
- throw new Error(data && data.error || 'Request failed')
27
- }
28
- console.log(data)
29
- uiModal.close('#tlsModal');
30
- loadingCertData = false;
31
- loadedCertData = true;
32
- document.getElementById('{{field}}').dataset.certificate = data.fingerprint
33
-
34
- paintCertData(data);
35
- }).catch(err => {
36
- console.error(err)
37
- loadingCertData = false;
38
-
39
- document.getElementById('{{field}}').checked = false;
40
- renderExamples();
41
-
42
- for (let elm of document.querySelectorAll('#tlsModal .modal-show-error')) {
43
- elm.classList.remove('hidden')
44
- }
45
-
46
- for (let elm of document.querySelectorAll('#tlsModal .modal-show-default')) {
47
- elm.classList.add('hidden')
48
- }
49
-
50
- document.querySelector('#tlsModal .error-content').textContent = err.message;
51
- });
52
- }
53
-
54
- function checkLoadCerts() {
55
- if (document.getElementById('{{field}}').checked &&
56
- !loadingCertData && !loadedCertData &&
57
- document.getElementById('{{field}}').dataset.domain) {
58
-
59
- loadCertData();
60
- }
61
- }
62
-
63
- document.getElementById('{{field}}').addEventListener('click', checkLoadCerts);
64
- document.getElementById('{{field}}').addEventListener('change', checkLoadCerts);
@@ -1,22 +0,0 @@
1
- {{!-- certificate provisioning progress/error modal for tls_security_card;
2
- rendered outside the settings form (its Close button must not submit) --}}
3
- {{#> ui/modal id="tlsModal" hideClose=true dialogClass="max-w-3xl"}}
4
- <div class="modal-body">
5
- <h3 class="modal-title modal-show-default mb-4">Provisioning Certificate <span
6
- class="loading loading-spinner loading-sm align-middle"></span></h3>
7
- <h3 class="modal-title modal-show-error hidden mb-4">Certificate Request Failed</h3>
8
-
9
- <div class="modal-show-default">
10
- Setting up TLS certificate for <em class="show-service-domain">{{#if serviceDomain}}{{serviceDomain}}{{/if}}</em>. This may take a
11
- moment...
12
- </div>
13
- <div class="modal-show-error hidden">
14
- <p class="mb-2">Unable to provision certificate:</p>
15
-
16
- <div class="font-mono error-content alert alert-soft alert-error"></div>
17
- </div>
18
- </div>
19
- <div class="modal-footer modal-show-error hidden">
20
- {{> ui/btn label="Close" variant="neutral" style="soft" overlay="#tlsModal"}}
21
- </div>
22
- {{/ui/modal}}