emailengine-app 2.79.9 → 2.80.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/.release-please-manifest.json +1 -1
  2. package/CHANGELOG.md +49 -0
  3. package/config/default.toml +5 -1
  4. package/data/google-crawlers.json +1 -1
  5. package/encrypt.js +43 -0
  6. package/lib/account/account-state.js +62 -0
  7. package/lib/account.js +34 -2
  8. package/lib/api-routes/account-routes.js +20 -0
  9. package/lib/api-routes/index.js +1 -1
  10. package/lib/api-routes/settings-routes.js +17 -2
  11. package/lib/autodetect-imap-settings.js +349 -47
  12. package/lib/cert-handler.js +62 -0
  13. package/lib/consts.js +50 -6
  14. package/lib/db.js +12 -0
  15. package/lib/egress-fetch.js +21 -9
  16. package/lib/email-client/base-client.js +234 -66
  17. package/lib/email-client/credential-errors.js +118 -0
  18. package/lib/email-client/gmail/gmail-api.js +2 -1
  19. package/lib/email-client/gmail-client.js +70 -64
  20. package/lib/email-client/imap/connection-errors.js +52 -0
  21. package/lib/email-client/imap/listing-diff.js +47 -6
  22. package/lib/email-client/imap/mailbox.js +457 -379
  23. package/lib/email-client/imap/subconnection.js +15 -11
  24. package/lib/email-client/imap/sync-operations.js +46 -59
  25. package/lib/email-client/imap-client.js +136 -95
  26. package/lib/email-client/message-builder.js +11 -11
  27. package/lib/email-client/outlook/graph-api.js +2 -1
  28. package/lib/email-client/outlook-client.js +219 -106
  29. package/lib/imap-proxy-auth.js +58 -3
  30. package/lib/imapproxy/imap-server.js +53 -62
  31. package/lib/lua/h-del-if-equals.lua +39 -0
  32. package/lib/lua/h-set-if-equals.lua +39 -0
  33. package/lib/routes-ui.js +4 -34
  34. package/lib/schemas.js +32 -0
  35. package/lib/security-headers.js +15 -0
  36. package/lib/tls/context.js +376 -0
  37. package/lib/tls/der.js +223 -0
  38. package/lib/tls/provision.js +555 -0
  39. package/lib/tls/self-signed.js +282 -0
  40. package/lib/tls/status.js +431 -0
  41. package/lib/tls/store.js +666 -0
  42. package/lib/tools.js +72 -27
  43. package/lib/ui-routes/account-routes.js +43 -30
  44. package/lib/ui-routes/admin-config-routes.js +22 -1
  45. package/lib/ui-routes/auth-routes.js +16 -1
  46. package/lib/ui-routes/internals-routes.js +3 -5
  47. package/lib/ui-routes/network-config-routes.js +54 -45
  48. package/lib/ui-routes/tls-config-routes.js +581 -0
  49. package/lib/utils/mailbox-path.js +51 -0
  50. package/lib/utils/severity.js +31 -0
  51. package/package.json +4 -4
  52. package/sbom.json +1 -1
  53. package/server.js +16 -0
  54. package/static/css/flyonui.css +1 -1
  55. package/static/css/src/app.tailwind.css +11 -0
  56. package/static/js/app.js +34 -0
  57. package/static/js/public.js +6 -2
  58. package/static/js/ui.js +8 -25
  59. package/static/licenses.html +328 -1257
  60. package/translations/messages.pot +87 -87
  61. package/views/account/login-redirect.hbs +22 -0
  62. package/views/config/imap-proxy.hbs +0 -3
  63. package/views/config/smtp.hbs +0 -3
  64. package/views/config/tls-upload.hbs +81 -0
  65. package/views/config/tls.hbs +492 -0
  66. package/views/partials/side_menu.hbs +1 -0
  67. package/views/partials/tls_security_card.hbs +25 -53
  68. package/views/partials/ui/alert-banner.hbs +3 -2
  69. package/views/partials/ui/badge.hbs +6 -2
  70. package/views/partials/ui/btn.hbs +5 -2
  71. package/workers/api.js +93 -134
  72. package/workers/imap-proxy.js +4 -1
  73. package/workers/smtp.js +51 -44
  74. package/views/partials/tls_security_js.hbs +0 -64
  75. package/views/partials/tls_security_modal.hbs +0 -22
@@ -16,18 +16,16 @@ const {
16
16
  readEnvValue,
17
17
  emitChangeEvent,
18
18
  loadTlsConfig,
19
- assertTlsCredentials,
20
- httpAgent
19
+ assertTlsCredentials
21
20
  } = require('../tools');
22
21
  const { getLocalAddress } = require('../utils/network');
23
22
 
24
23
  const { redis } = require('../db');
25
- const { createImapProxyAuthHandler, failImapAuth } = require('../imap-proxy-auth');
26
- const getSecret = require('../get-secret');
24
+ const { createImapProxyAuthHandler, classifyCredentialFailure, isImapResponseError, toImapResponseError } = require('../imap-proxy-auth');
27
25
  const settings = require('../settings');
28
26
 
29
- const { encrypt, decrypt } = require('../encrypt');
30
- const { Certs } = require('@postalsys/certs');
27
+ const { createCertHandler } = require('../cert-handler');
28
+ const { createTlsContext, applyTlsContext } = require('../tls/context');
31
29
 
32
30
  config.imap = config.imap || {
33
31
  enabled: false,
@@ -44,7 +42,7 @@ const EENGINE_TIMEOUT = getDuration(readEnvValue('EENGINE_TIMEOUT') || config.se
44
42
  const EENGINE_LOG_RAW = hasEnvValue('EENGINE_LOG_RAW') ? getBoolean(readEnvValue('EENGINE_LOG_RAW')) : getBoolean(config.log.raw);
45
43
  const DISABLE_IMAP_COMPRESSION = getBoolean(readEnvValue('EENGINE_DISABLE_COMPRESSION'));
46
44
 
47
- const { REDIS_PREFIX, TLS_DEFAULTS } = require('../consts');
45
+ const { TLS_DEFAULTS } = require('../consts');
48
46
 
49
47
  let callQueue = new Map();
50
48
  let mids = 0;
@@ -187,7 +185,7 @@ async function onAuth(auth, session) {
187
185
  try {
188
186
  imapAuth = await resolveCredentials(account, 'imap');
189
187
  } catch (err) {
190
- throw failImapAuth(err);
188
+ throw classifyCredentialFailure(err);
191
189
  }
192
190
  } else {
193
191
  if (!accountData.oauth2.accessToken || !accountData.oauth2.expires || accountData.oauth2.expires < new Date(Date.now() + 30 * 1000)) {
@@ -195,7 +193,7 @@ async function onAuth(auth, session) {
195
193
  try {
196
194
  accountData = await accountObject.renewAccessToken();
197
195
  } catch (err) {
198
- throw failImapAuth(err);
196
+ throw classifyCredentialFailure(err);
199
197
  }
200
198
  }
201
199
  imapAuth = { user: accountData.oauth2.auth.user, accessToken: accountData.oauth2.accessToken };
@@ -218,7 +216,7 @@ async function onAuth(auth, session) {
218
216
  try {
219
217
  imapConnectionConfig.auth = await resolveCredentials(account, 'imap');
220
218
  } catch (err) {
221
- throw failImapAuth(err);
219
+ throw classifyCredentialFailure(err);
222
220
  }
223
221
  }
224
222
 
@@ -455,13 +453,9 @@ const createServer = function (options = {}) {
455
453
  });
456
454
  })
457
455
  .catch(err => {
458
- if (err.authenticationFailed || err.serverResponseCode === 'AUTHENTICATIONFAILED') {
456
+ if (isImapResponseError(err)) {
459
457
  serverLogger.warn({ msg: 'Upstream authentication failed', account, cid: session.id, err });
460
- let error = new Error(
461
- `${err.serverResponseCode ? `[${err.serverResponseCode}] ` : ''}${err.responseText || err.message || 'Authentication failed'}`
462
- );
463
- error.response = err.responseStatus || 'NO';
464
- return callback(error);
458
+ return callback(toImapResponseError(err));
465
459
  } else {
466
460
  serverLogger.error({ msg: 'Failed to create proxy', account, cid: session.id, err });
467
461
  return callback(err);
@@ -470,14 +464,10 @@ const createServer = function (options = {}) {
470
464
  })
471
465
  .catch(err => {
472
466
  let entry = { msg: 'Authentication check failed', username: login.username, cid: session.id, remoteAddress: session.remoteAddress, err };
473
- if (err.authenticationFailed || err.serverResponseCode === 'AUTHENTICATIONFAILED') {
474
- // routine failed client login, not a proxy fault
467
+ if (isImapResponseError(err)) {
468
+ // a refused login or a temporary failure the client is told to retry, not a proxy fault
475
469
  serverLogger.warn(entry);
476
- let error = new Error(
477
- `${err.serverResponseCode ? `[${err.serverResponseCode}] ` : ''}${err.responseText || err.message || 'Authentication failed'}`
478
- );
479
- error.response = err.responseStatus || 'NO';
480
- return callback(error);
470
+ return callback(toImapResponseError(err));
481
471
  }
482
472
  serverLogger.error(entry);
483
473
  return callback(err);
@@ -487,6 +477,11 @@ const createServer = function (options = {}) {
487
477
  return server;
488
478
  };
489
479
 
480
+ // The running listener and the TLS material it serves, kept at module level so the certificate
481
+ // reload command can reach both without restarting the worker.
482
+ let proxyServer = null;
483
+ let tlsContext = null;
484
+
490
485
  module.exports.run = async () => {
491
486
  const serverOptions = {
492
487
  useProxy: await settings.get('imapProxyServerProxy'),
@@ -501,64 +496,37 @@ module.exports.run = async () => {
501
496
  const port = await settings.get('imapProxyServerPort');
502
497
  const host = await settings.get('imapProxyServerHost');
503
498
 
504
- let certs = new Certs({
505
- redis,
506
- namespace: `${REDIS_PREFIX}`,
507
-
508
- environment: 'ee',
509
-
510
- // long-lived client, see LiveDispatcher in lib/tools.js
511
- dispatcher: httpAgent.live,
512
-
513
- logger: logger.child({ sub: 'acme' }),
514
-
515
- encryptFn: async value => {
516
- const encryptSecret = await getSecret();
517
- return encrypt(value, encryptSecret);
518
- },
519
-
520
- decryptFn: async value => {
521
- const encryptSecret = await getSecret();
522
- return decrypt(value, encryptSecret);
523
- }
524
- });
499
+ // Reads what the API worker provisioned; this one never orders a certificate itself.
500
+ let certs = createCertHandler(logger);
525
501
 
526
502
  let tls = await settings.get('imapProxyServerTLSEnabled');
527
503
 
528
504
  if (tls) {
529
505
  serverOptions.secure = true;
530
506
 
531
- // load certificates
532
- let serviceUrl = await settings.get('serviceUrl');
533
- let hostname = (new URL(serviceUrl).hostname || '').toString().toLowerCase().trim();
534
-
507
+ // Environment and config-file material first, then whatever EmailEngine manages itself.
508
+ // The order used to be the other way round here, so an operator-supplied certificate was
509
+ // overwritten by an automatic one; lib/tls/context.js owns the precedence now.
535
510
  loadTlsConfig(serverOptions, 'EENGINE_IMAPPROXY_TLS_');
536
511
 
537
- if (hostname) {
538
- let certificateData = await certs.getCertificate(hostname, true);
539
- if (certificateData && certificateData.status === 'valid') {
540
- serverOptions.cert =
541
- certificateData.cert +
542
- '\n' +
543
- []
544
- .concat(certificateData.ca || [])
545
- .flatMap(entry => entry)
546
- .join('\n');
547
- serverOptions.key = certificateData.privateKey;
548
- }
549
- }
512
+ // The material loaded above is snapshotted inside, at entry, so a later refresh does not
513
+ // read what this resolution wrote back into serverOptions as if the operator had supplied
514
+ // it.
515
+ tlsContext = await createTlsContext({ certs, logger, listenerOptions: serverOptions });
516
+ Object.assign(serverOptions, tlsContext.options);
550
517
 
551
518
  assertTlsCredentials(serverOptions, 'The IMAP proxy');
552
519
  }
553
520
 
554
521
  const server = createServer(serverOptions);
522
+ proxyServer = server;
555
523
 
556
524
  try {
557
525
  await new Promise((resolve, reject) => {
558
526
  server.once('error', err => reject(err));
559
527
  server.listen(port || config.imap.port, host || config.imap.host, () => resolve(server));
560
528
  });
561
- await emitChangeEvent(logger, null, 'imapProxyServerState', 'listening');
529
+ await emitChangeEvent(logger, null, 'imapProxyServerState', 'listening', { tls: tlsContext ? tlsContext.active : null });
562
530
  } catch (err) {
563
531
  await emitChangeEvent(logger, null, 'imapProxyServerState', 'failed', {
564
532
  error: { message: err.message, code: err.code || null }
@@ -568,3 +536,26 @@ module.exports.run = async () => {
568
536
 
569
537
  return server;
570
538
  };
539
+
540
+ /**
541
+ * Re-resolves the TLS material and hands it to the running proxy.
542
+ *
543
+ * Sessions already established keep the context they negotiated with. An IMAP client can hold a
544
+ * connection open for days, so restarting the worker to install a renewed certificate is the
545
+ * expensive way to do this.
546
+ *
547
+ * @returns {Promise<Object>} What the listener is serving after the reload
548
+ */
549
+ module.exports.reloadCertificates = async () => {
550
+ const result = await applyTlsContext({
551
+ context: proxyServer ? tlsContext : null,
552
+ apply: options => proxyServer.updateSecureContext(options),
553
+ logger
554
+ });
555
+
556
+ if (result.updated) {
557
+ await emitChangeEvent(logger, null, 'imapProxyServerState', 'listening', { tls: result.tls });
558
+ }
559
+
560
+ return result;
561
+ };
@@ -0,0 +1,39 @@
1
+ --[[
2
+ Script: h-del-if-equals.lua
3
+ Purpose: Drops a set of hash fields only when a guard field still holds the value the caller read,
4
+ so a record that was replaced between the read and the delete is left for whoever wrote it.
5
+
6
+ The error state of an account is read, judged and then dropped. Everything in between is
7
+ an await, and another failure written in that window would be deleted by a decision taken
8
+ before it existed - leaving the account reporting a healthy state it is not in.
9
+
10
+ KEYS:
11
+ [1] hashKey - The hash key to operate on
12
+
13
+ ARGV:
14
+ [1] guardKey - The hash field whose value the decision was taken on
15
+ [2] expected - The value the caller read; an empty string means "expect the field to be absent"
16
+ [3..] fields - The fields to delete
17
+
18
+ Returns:
19
+ 1 if the guard matched and the fields were dropped
20
+ 0 if the guard holds something else, meaning the record is no longer the one that was judged
21
+ --]]
22
+
23
+ local hashKey = KEYS[1];
24
+ local guardKey = ARGV[1];
25
+ local expected = ARGV[2];
26
+
27
+ -- HGET answers a missing field with false, which is the same test as any other mismatch once it
28
+ -- is read as the empty string
29
+ local current = redis.call("HGET", hashKey, guardKey) or "";
30
+
31
+ if current ~= expected then
32
+ return 0;
33
+ end
34
+
35
+ if #ARGV > 2 then
36
+ redis.call("HDEL", hashKey, unpack(ARGV, 3));
37
+ end
38
+
39
+ return 1;
@@ -0,0 +1,39 @@
1
+ --[[
2
+ Script: h-set-if-equals.lua
3
+ Purpose: Replaces a hash field only when it still holds the value the caller last read, so two
4
+ processes that both decided to replace the same record converge on one winner instead of
5
+ overwriting each other.
6
+
7
+ HSETNX converges only when the field is absent. Deleting first and then HSETNX looks
8
+ equivalent but is not: between the delete and the set, a second process sees an empty field
9
+ and wins the HSETNX too, and both walk away believing they own the record.
10
+
11
+ KEYS:
12
+ [1] hashKey - The hash key to operate on
13
+
14
+ ARGV:
15
+ [1] entryKey - The hash field name
16
+ [2] value - The value to set
17
+ [3] expected - The value the caller read; an empty string means "expect the field to be absent"
18
+
19
+ Returns:
20
+ 1 if the field matched and was replaced (or was absent as expected and created)
21
+ 0 if the field holds something else, meaning another process got there first
22
+ --]]
23
+
24
+ local hashKey = KEYS[1];
25
+ local entryKey = ARGV[1];
26
+
27
+ local value = ARGV[2];
28
+ local expected = ARGV[3];
29
+
30
+ -- HGET answers a missing field with false, which is the same test as any other mismatch once it
31
+ -- is read as the empty string
32
+ local current = redis.call("HGET", hashKey, entryKey) or "";
33
+
34
+ if current ~= expected then
35
+ return 0;
36
+ end
37
+
38
+ redis.call("HSET", hashKey, entryKey, value);
39
+ return 1;
package/lib/routes-ui.js CHANGED
@@ -15,6 +15,7 @@ const oauthConfigRoutes = require('./ui-routes/oauth-config-routes');
15
15
  const adminConfigRoutes = require('./ui-routes/admin-config-routes');
16
16
  const accountRoutes = require('./ui-routes/account-routes');
17
17
  const mcpConsentRoutes = require('./ui-routes/mcp-consent-routes');
18
+ const tlsConfigRoutes = require('./ui-routes/tls-config-routes');
18
19
 
19
20
  function applyRoutes(server, call) {
20
21
  // Initialize admin entity routes (webhooks, templates, gateways, tokens)
@@ -44,6 +45,9 @@ function applyRoutes(server, call) {
44
45
  // Network, SMTP server, IMAP proxy, and browser config routes
45
46
  networkConfigRoutes({ server, call });
46
47
 
48
+ // TLS certificates: the configuration page, and the ACME challenge route the CA calls
49
+ tlsConfigRoutes({ server, call });
50
+
47
51
  // Document Store (Elasticsearch) config routes (deprecated feature; the module self-gates
48
52
  // and registers no routes unless the Document Store feature is enabled)
49
53
  documentStoreRoutes({ server });
@@ -62,40 +66,6 @@ function applyRoutes(server, call) {
62
66
 
63
67
  // MCP OAuth consent page (self-gates on the MCP feature flag, like the Document Store module)
64
68
  mcpConsentRoutes({ server, call });
65
-
66
- server.route({
67
- method: 'GET',
68
- path: '/.well-known/acme-challenge/{token}',
69
- async handler(request, h) {
70
- let domain = (request.headers.host || '').toString().replace(/:.*$/g, '').trim().toLowerCase();
71
-
72
- let challenge;
73
- try {
74
- challenge = await h.certs.routeHandler(domain, request.params.token);
75
- if (!challenge) {
76
- throw new Error('Challenge not found for the provided token and domain');
77
- }
78
- } catch (err) {
79
- return h
80
- .response(
81
- `Request failed: ${err.message}
82
- Domain: ${JSON.stringify(domain)}
83
- Token: ${JSON.stringify(request.params.token)}`
84
- )
85
- .type('text/plain')
86
- .code(err.statusCode || 500);
87
- }
88
-
89
- const response = h.response('success');
90
- response.type('text/plain');
91
-
92
- return challenge;
93
- },
94
-
95
- options: {
96
- auth: false
97
- }
98
- });
99
69
  }
100
70
 
101
71
  module.exports = (...args) => {
package/lib/schemas.js CHANGED
@@ -1,5 +1,6 @@
1
1
  'use strict';
2
2
 
3
+ const net = require('net');
3
4
  const Joi = require('joi');
4
5
  const config = require('@zone-eu/wild-config');
5
6
  const { getByteSize } = require('./tools');
@@ -483,6 +484,37 @@ const settingsSchema = {
483
484
  .falsy('N', 'false', 0, '')
484
485
  .description('Enable TLS/STARTTLS support for the SMTP server'),
485
486
 
487
+ /* ────────────── TLS Certificates ────────────── */
488
+
489
+ tlsProvisioning: Joi.string()
490
+ .empty('')
491
+ .valid('acme', 'manual', 'self-signed')
492
+ .example('acme')
493
+ .description(
494
+ 'Where the TLS certificate for the built-in listeners comes from: "acme" orders one from Let\'s Encrypt, "manual" uses the certificate uploaded through the admin UI, "self-signed" stops trying to get a real one'
495
+ )
496
+ .label('TlsProvisioning'),
497
+
498
+ tlsHostnames: Joi.array()
499
+ .items(
500
+ Joi.string()
501
+ .max(255)
502
+ .lowercase()
503
+ .pattern(/^[a-z0-9._:-]+$/i)
504
+ // The colon is for a bare IPv6 literal. A host:port pasted out of a mail client's
505
+ // settings is not a name a certificate can be issued for, and it used to be stored
506
+ // as one: a permanently failing order, and a reachability check made against the
507
+ // IMAPS port in plain HTTP.
508
+ .custom((value, helpers) => (value.includes(':') && net.isIP(value) !== 6 ? helpers.message('{{#label}} must not include a port') : value))
509
+ .example('smtp.example.com')
510
+ .label('TlsHostnameEntry')
511
+ )
512
+ .single()
513
+ .description(
514
+ 'Additional hostnames to hold certificates for, beyond the Service URL hostname. Each one is ordered separately and served over SNI, so a mail client connecting to smtp.example.com is offered a certificate for that name'
515
+ )
516
+ .label('TlsHostnames'),
517
+
486
518
  /* ────────────── IMAP Proxy ────────────── */
487
519
 
488
520
  imapProxyServerEnabled: Joi.boolean().truthy('Y', 'true', '1', 'on').falsy('N', 'false', 0, '').description('Enable the IMAP proxy server'),
@@ -132,6 +132,20 @@ const CSP_PRESETS = Object.freeze({
132
132
  })
133
133
  });
134
134
 
135
+ // What an admin page has to declare when it carries a form whose POST is answered with a redirect
136
+ // to an OAuth provider's authorization page. Chrome checks a form submission's redirect target
137
+ // against form-action, so `'self'` blocks the submission even though the form posts to this very
138
+ // instance. The hosted setup form gets the same relaxation from the public preset - an admin page
139
+ // renders the same form and has to ask for it, which is what the account page's "Re-authenticate"
140
+ // button needs.
141
+ //
142
+ // `https:` rather than the five authorization origins the providers actually use today
143
+ // (accounts.google.com, oauth.mail.ru and the three Entra clouds in lib/oauth/outlook.js). Listing
144
+ // them would be accurate right now and would silently reintroduce this very bug the day a provider
145
+ // or a Microsoft cloud is added - as a CSP refusal in the browser console, which is how it was
146
+ // found the first time. It is also the value every public page already carries.
147
+ const OAUTH_REDIRECT_FORM_DIRECTIVES = Object.freeze({ 'form-action': "'self' https:" });
148
+
135
149
  // Refuses MIME sniffing everywhere. An attachment or export served as application/octet-stream
136
150
  // must not be rendered as HTML because the bytes happen to look like it.
137
151
  const COMMON_HEADERS = Object.freeze({
@@ -384,6 +398,7 @@ function securityHeadersExt({ cspMode = 'enforce' } = {}) {
384
398
 
385
399
  module.exports = {
386
400
  securityHeadersExt,
401
+ OAUTH_REDIRECT_FORM_DIRECTIVES,
387
402
  attachSecurityContext,
388
403
  policyFor,
389
404
  profileNameFor,