emailengine-app 2.84.1 → 2.85.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 (147) hide show
  1. package/.dockerignore +6 -0
  2. package/.ncurc.js +5 -3
  3. package/.prettierignore +5 -1
  4. package/.prettierrc.js +2 -0
  5. package/.release-please-manifest.json +1 -1
  6. package/CHANGELOG.md +61 -0
  7. package/Dockerfile +8 -2
  8. package/README.md +1 -1
  9. package/bin/emailengine.js +444 -403
  10. package/copy-static-files.sh +39 -14
  11. package/data/google-crawlers.json +1 -1
  12. package/data/public_suffix_list.dat +16562 -0
  13. package/docker-compose.yml +1 -1
  14. package/eslint.config.js +81 -99
  15. package/lib/account/own-account-key.js +42 -0
  16. package/lib/account-assignment.js +1 -33
  17. package/lib/account.js +68 -24
  18. package/lib/add-trackers.js +11 -4
  19. package/lib/api-reference/format.js +4 -3
  20. package/lib/api-routes/account-routes.js +244 -26
  21. package/lib/api-routes/blocklist-routes.js +23 -2
  22. package/lib/api-routes/delivery-test-routes.js +26 -3
  23. package/lib/api-routes/export-routes.js +28 -2
  24. package/lib/api-routes/gateway-routes.js +37 -5
  25. package/lib/api-routes/mailbox-routes.js +41 -2
  26. package/lib/api-routes/message-routes.js +104 -4
  27. package/lib/api-routes/mint-bounds.js +11 -0
  28. package/lib/api-routes/oauth2-app-routes.js +48 -15
  29. package/lib/api-routes/outbox-routes.js +45 -11
  30. package/lib/api-routes/permission-map.js +12 -1
  31. package/lib/api-routes/route-helpers.js +125 -3
  32. package/lib/api-routes/settings-routes.js +23 -2
  33. package/lib/api-routes/submit-routes.js +338 -309
  34. package/lib/api-routes/template-routes.js +38 -2
  35. package/lib/api-routes/token-routes.js +142 -96
  36. package/lib/api-routes/webhook-route-routes.js +13 -2
  37. package/lib/auth-token.js +23 -10
  38. package/lib/bounce-detect.js +414 -210
  39. package/lib/consts.js +39 -4
  40. package/lib/create-imap-client.js +41 -2
  41. package/lib/email-client/base-client.js +30 -41
  42. package/lib/email-client/gmail-client.js +30 -18
  43. package/lib/email-client/imap/mailbox.js +13 -23
  44. package/lib/email-client/imap/response-metrics.js +75 -0
  45. package/lib/email-client/imap/subconnection.js +1 -1
  46. package/lib/email-client/imap-client.js +6 -3
  47. package/lib/email-client/message-builder.js +7 -2
  48. package/lib/email-client/notification-handler.js +1 -2
  49. package/lib/email-client/outlook/graph-api.js +17 -2
  50. package/lib/email-client/outlook-client.js +6 -3
  51. package/lib/email-client/smtp-pool-manager.js +6 -0
  52. package/lib/encrypt.js +9 -0
  53. package/lib/export.js +3 -1
  54. package/lib/gateway.js +2 -3
  55. package/lib/get-raw-email.js +4 -2
  56. package/lib/hapi-request-logger.js +107 -0
  57. package/lib/imap-proxy-auth.js +14 -1
  58. package/lib/imapproxy/imap-core/README.md +6 -5
  59. package/lib/imapproxy/imap-core/lib/commands/authenticate-plain.js +1 -0
  60. package/lib/imapproxy/imap-core/lib/commands/login.js +1 -0
  61. package/lib/imapproxy/imap-core/lib/imap-command.js +86 -43
  62. package/lib/imapproxy/imap-core/lib/imap-stream.js +58 -13
  63. package/lib/imapproxy/imap-core/lib/indexer/indexer.js +3 -1
  64. package/lib/mcp/listen.js +10 -1
  65. package/lib/mcp/tools.js +37 -8
  66. package/lib/notify-attachments.js +17 -0
  67. package/lib/oauth/external-account-config.js +3 -1
  68. package/lib/oauth/gmail.js +21 -48
  69. package/lib/oauth/mail-ru.js +5 -38
  70. package/lib/oauth/outlook-mailbox.js +35 -0
  71. package/lib/oauth/outlook.js +26 -44
  72. package/lib/oauth/state.js +24 -0
  73. package/lib/oauth2-apps.js +1 -1
  74. package/lib/pbkdf2-phc.js +19 -2
  75. package/lib/privileged-settings.js +6 -3
  76. package/lib/redis-scan-delete.js +15 -1
  77. package/lib/schemas.js +79 -33
  78. package/lib/settings.js +13 -1
  79. package/lib/smtp-auth.js +23 -0
  80. package/lib/sso.js +1 -1
  81. package/lib/swagger-options.js +1 -1
  82. package/lib/thread-diagnostics.js +46 -0
  83. package/lib/timezones.js +109 -0
  84. package/lib/token-permission-view.js +3 -3
  85. package/lib/tools.js +285 -66
  86. package/lib/totp.js +2 -5
  87. package/lib/translations.js +1 -2
  88. package/lib/ui-routes/account-routes.js +491 -491
  89. package/lib/ui-routes/account-setup.js +99 -0
  90. package/lib/ui-routes/admin-config-routes.js +98 -48
  91. package/lib/ui-routes/admin-entities-routes.js +113 -31
  92. package/lib/ui-routes/auth-routes.js +137 -62
  93. package/lib/ui-routes/connection-security-form.js +74 -0
  94. package/lib/ui-routes/form-lists.js +46 -0
  95. package/lib/ui-routes/internals-routes.js +5 -0
  96. package/lib/ui-routes/mcp-consent-routes.js +5 -1
  97. package/lib/ui-routes/oauth-config-routes.js +133 -100
  98. package/lib/ui-routes/route-helpers.js +19 -3
  99. package/lib/ui-routes/sign-in-helpers.js +59 -0
  100. package/lib/ui-routes/tls-config-routes.js +58 -15
  101. package/lib/ui-routes/unsubscribe-routes.js +6 -3
  102. package/lib/utils/back-off.js +82 -0
  103. package/lib/utils/map-concurrent.js +36 -0
  104. package/lib/utils/murmurhash3.js +66 -0
  105. package/lib/utils/network.js +28 -0
  106. package/lib/utils/provider-id.js +27 -0
  107. package/lib/utils/public-suffix.js +122 -0
  108. package/lib/utils/random-id.js +26 -0
  109. package/lib/utils/require-tls.js +33 -0
  110. package/lib/utils/version.js +74 -0
  111. package/lib/web-safe-html.js +5 -6
  112. package/lib/webhook-penalty.js +75 -0
  113. package/lib/webhook-routing.js +49 -2
  114. package/lib/webhooks.js +41 -6
  115. package/package.json +37 -39
  116. package/sbom.json +7980 -1
  117. package/server.js +659 -455
  118. package/static/js/ace/ace.js +1 -1
  119. package/static/js/ace/mode-handlebars.js +1 -1
  120. package/static/js/ace/mode-html.js +1 -1
  121. package/static/js/ace/mode-javascript.js +1 -1
  122. package/static/js/ace/mode-markdown.js +1 -1
  123. package/static/js/ace/worker-html.js +1 -1
  124. package/static/js/ace/worker-javascript.js +1 -1
  125. package/static/js/ace/worker-json.js +1 -1
  126. package/static/js/ee-client.js +5 -0
  127. package/static/licenses.html +191 -1016
  128. package/translations/messages.pot +70 -71
  129. package/views/account/security.hbs +10 -0
  130. package/views/accounts/account.hbs +11 -11
  131. package/views/accounts/edit.hbs +6 -2
  132. package/views/config/ai.hbs +1 -1
  133. package/views/config/security.hbs +2 -2
  134. package/views/config/service.hbs +3 -0
  135. package/views/internals/index.hbs +8 -0
  136. package/views/partials/gateway_form.hbs +3 -1
  137. package/views/partials/webhook_form.hbs +1 -1
  138. package/views/suppression-lists/index.hbs +1 -1
  139. package/workers/api.js +780 -585
  140. package/workers/export.js +1 -1
  141. package/workers/submit.js +1 -1
  142. package/workers/webhooks.js +54 -34
  143. package/config/test.toml +0 -46
  144. package/install.sh +0 -428
  145. package/setup-production.sh +0 -215
  146. package/systemd/emailengine.service +0 -97
  147. package/systemd/nginx-proxy.conf +0 -77
package/lib/schemas.js CHANGED
@@ -34,6 +34,7 @@ function formBoolean() {
34
34
  const config = require('@zone-eu/wild-config');
35
35
  const { getByteSize, readEnvValue } = require('./tools');
36
36
  const { COLLAPSE_CLASS, MAX_ACCOUNT_ID_LENGTH } = require('./consts');
37
+ const { PROVIDER_ID_SEGMENT } = require('./utils/provider-id');
37
38
  const { locales } = require('./translations');
38
39
  const { OAUTH_PROVIDERS } = require('./oauth2-apps');
39
40
  const { ACCOUNT_STATES } = require('./account/account-state');
@@ -686,6 +687,63 @@ const imapMaxIdleTimeSchema = Joi.number()
686
687
  .description('Restart IDLE after this many milliseconds. Also caps the polling interval for servers without IDLE support.')
687
688
  .meta({ usage: FIELD_USAGE.maxIdleTime });
688
689
 
690
+ // The `tls` object of an IMAP or SMTP configuration is merged as it is into the options the
691
+ // connection is opened with, so it names Node's TLS options and nothing else. It used to accept
692
+ // any key, which made it a second place to say where the connection goes: `path` connects to a
693
+ // Unix socket, `host` and `port` override the validated host and port, `lookup` and
694
+ // `localAddress` reroute it. The keys below are the ones that configure the TLS session itself
695
+ // (plus the client certificate for servers that ask for one).
696
+ const PEM_MAX = 64 * 1024;
697
+ const pemSchema = Joi.string().max(PEM_MAX);
698
+ const PEM_CERT_EXAMPLE = '-----BEGIN CERTIFICATE-----\nMIIB...\n-----END CERTIFICATE-----';
699
+ const PEM_KEY_EXAMPLE = '-----BEGIN PRIVATE KEY-----\nMIIE...\n-----END PRIVATE KEY-----';
700
+
701
+ // Whether a connection that starts in cleartext (`secure: false`) must upgrade with STARTTLS.
702
+ // Required unless set to false: left to chance, a server that does not advertise STARTTLS, or an
703
+ // attacker on the path who strips the advertisement, gets the password in cleartext. False is for
704
+ // a server on a trusted network that has no TLS at all. No default, so an update that does not
705
+ // mention the field keeps the stored value and a stored account without it reads as required.
706
+ function requireTlsSchema(label, base) {
707
+ return (base || Joi.boolean())
708
+ .example(true)
709
+ .description(
710
+ 'Require STARTTLS when secure is false. Defaults to true: the connection fails if the server does not offer STARTTLS or the upgrade fails. Set to false only for a server on a trusted network that has no TLS at all'
711
+ )
712
+ .label(label);
713
+ }
714
+
715
+ function tlsOptionsSchema(label, opts) {
716
+ opts = opts || {};
717
+ let rejectUnauthorized = Joi.boolean().example(true).description('Reject connections to servers with invalid TLS certificates');
718
+ if (opts.withDefaults) {
719
+ rejectUnauthorized = rejectUnauthorized.default(true);
720
+ }
721
+
722
+ return Joi.object({
723
+ rejectUnauthorized,
724
+ minVersion: Joi.string().max(256).example('TLSv1.2').description('Minimum TLS version to accept (e.g., "TLSv1.2", "TLSv1.3")'),
725
+ maxVersion: Joi.string().max(256).example('TLSv1.3').description('Maximum TLS version to accept'),
726
+ servername: Joi.string()
727
+ .max(256)
728
+ .example('imap.example.com')
729
+ .description('Server name for SNI and certificate validation, when it differs from the host'),
730
+ ciphers: Joi.string().max(1024).example('HIGH:!aNULL:!MD5').description('Cipher suite specification, in OpenSSL format'),
731
+ ca: Joi.alternatives()
732
+ .try(pemSchema.example(PEM_CERT_EXAMPLE), Joi.array().items(pemSchema.example(PEM_CERT_EXAMPLE)).max(32).example([PEM_CERT_EXAMPLE]))
733
+ .example(PEM_CERT_EXAMPLE)
734
+ .description('Trusted CA certificates in PEM format, replacing the default trust store'),
735
+ cert: pemSchema.example(PEM_CERT_EXAMPLE).description('Client certificate in PEM format, for servers that require one'),
736
+ key: pemSchema.example(PEM_KEY_EXAMPLE).description('Private key of the client certificate in PEM format'),
737
+ passphrase: Joi.string().max(1024).example('key passphrase').description('Passphrase of the client certificate private key'),
738
+ honorCipherOrder: Joi.boolean().example(false).description('Prefer the ciphers in the order given rather than the order the server lists them'),
739
+ ecdhCurve: Joi.string().max(256).example('auto').description('ECDH curve name or list for key agreement'),
740
+ sigalgs: Joi.string().max(1024).example('RSA-PSS+SHA256:ECDSA+SHA256').description('Supported signature algorithms, colon separated'),
741
+ secureOptions: Joi.number().integer().example(0).description('OpenSSL option flags, as a number')
742
+ })
743
+ .description('Advanced TLS configuration options')
744
+ .label(label);
745
+ }
746
+
689
747
  const imapSchema = {
690
748
  auth: Joi.object({
691
749
  user: Joi.string().max(256).required().example('myuser@gmail.com').description('Username or email address for IMAP authentication'),
@@ -741,13 +799,8 @@ const imapSchema = {
741
799
  .example(993)
742
800
  .description('IMAP server port (typically 993 for IMAP over TLS, 143 for STARTTLS)'),
743
801
  secure: Joi.boolean().default(false).example(true).description('Use TLS encryption for the connection (true for port 993, false for STARTTLS on port 143)'),
744
- tls: Joi.object({
745
- rejectUnauthorized: Joi.boolean().default(true).example(true).description('Reject connections to servers with invalid TLS certificates'),
746
- minVersion: Joi.string().max(256).example('TLSv1.2').description('Minimum TLS version to accept (e.g., "TLSv1.2", "TLSv1.3")')
747
- })
748
- .unknown()
749
- .description('Advanced TLS configuration options')
750
- .label('ImapTlsOptions'),
802
+ requireTLS: requireTlsSchema('ImapRequireTLS'),
803
+ tls: tlsOptionsSchema('ImapTlsOptions', { withDefaults: true }),
751
804
  // the field name deliberately matches the ImapFlow option name - the stored
752
805
  // imap object is merged verbatim into the ImapFlow connection config
753
806
  disableIMAP4rev2: Joi.boolean()
@@ -831,13 +884,8 @@ const smtpSchema = {
831
884
  .default(false)
832
885
  .example(false)
833
886
  .description('Use TLS encryption from the start (true for port 465, false for STARTTLS on ports 587/25)'),
834
- tls: Joi.object({
835
- rejectUnauthorized: Joi.boolean().default(true).example(true).description('Reject connections to servers with invalid TLS certificates'),
836
- minVersion: Joi.string().max(256).example('TLSv1.2').description('Minimum TLS version to accept (e.g., "TLSv1.2", "TLSv1.3")')
837
- })
838
- .unknown()
839
- .description('Advanced TLS configuration options')
840
- .label('SmtpTlsOptions')
887
+ requireTLS: requireTlsSchema('SmtpRequireTLS'),
888
+ tls: tlsOptionsSchema('SmtpTlsOptions', { withDefaults: true })
841
889
  };
842
890
 
843
891
  const oauth2AuthSchema = Joi.object({
@@ -950,13 +998,8 @@ const imapUpdateSchema = {
950
998
  host: Joi.string().hostname().example('imap.gmail.com').description('IMAP server hostname'),
951
999
  port: Joi.number().integer().min(1).max(65535).example(993).description('IMAP server port'),
952
1000
  secure: Joi.boolean().example(true).description('Use TLS encryption for the connection'),
953
- tls: Joi.object({
954
- rejectUnauthorized: Joi.boolean().example(true).description('Reject connections to servers with invalid TLS certificates'),
955
- minVersion: Joi.string().max(256).example('TLSv1.2').description('Minimum TLS version to accept')
956
- })
957
- .unknown()
958
- .description('Advanced TLS configuration options')
959
- .label('ImapUpdateTlsOptions'),
1001
+ requireTLS: requireTlsSchema('ImapUpdateRequireTLS'),
1002
+ tls: tlsOptionsSchema('ImapUpdateTlsOptions'),
960
1003
  disableIMAP4rev2: Joi.boolean()
961
1004
  .example(false)
962
1005
  .description('Do not use IMAP4rev2 even if the server supports it')
@@ -1011,13 +1054,8 @@ const smtpUpdateSchema = {
1011
1054
  host: Joi.string().hostname().example('smtp.gmail.com').description('SMTP server hostname'),
1012
1055
  port: Joi.number().integer().min(1).max(65535).example(587).description('SMTP server port'),
1013
1056
  secure: Joi.boolean().example(false).description('Use TLS encryption from the start'),
1014
- tls: Joi.object({
1015
- rejectUnauthorized: Joi.boolean().example(true).description('Reject connections to servers with invalid TLS certificates'),
1016
- minVersion: Joi.string().max(256).example('TLSv1.2').description('Minimum TLS version to accept')
1017
- })
1018
- .unknown()
1019
- .description('Advanced TLS configuration options')
1020
- .label('SmtpUpdateTlsOptions')
1057
+ requireTLS: requireTlsSchema('SmtpUpdateRequireTLS'),
1058
+ tls: tlsOptionsSchema('SmtpUpdateTlsOptions')
1021
1059
  };
1022
1060
 
1023
1061
  const oauth2UpdateSchema = {
@@ -1104,6 +1142,13 @@ const threadIdSchema = Joi.string()
1104
1142
  .description('Thread identifier for email conversations (when supported by the email server)')
1105
1143
  .label('MessageThreadId');
1106
1144
 
1145
+ // A provider id the caller supplies (a search by emailId or threadId, a reference threadId) is
1146
+ // interpolated into a path segment of the provider's API URL. The response schemas above report
1147
+ // whatever the provider handed out; the request-side ids below additionally have to stay inside
1148
+ // their segment, see lib/utils/provider-id.js.
1149
+ const requestEmailIdSchema = emailIdSchema.pattern(PROVIDER_ID_SEGMENT, 'provider id');
1150
+ const requestThreadIdSchema = threadIdSchema.max(256).pattern(PROVIDER_ID_SEGMENT, 'provider id');
1151
+
1107
1152
  const messageSpecialUseSchema = Joi.string()
1108
1153
  .example('\\Sent')
1109
1154
  .valid('\\Drafts', '\\Junk', '\\Sent', '\\Trash', '\\Inbox')
@@ -1543,8 +1588,8 @@ const searchSchema = Joi.object({
1543
1588
  sentBefore: Joi.date().example('2024-08-09').description('Find messages sent before this date').label('HeaderBefore'),
1544
1589
  sentSince: Joi.date().example('2022-08-09').description('Find messages sent after this date').label('HeaderSince'),
1545
1590
 
1546
- emailId: emailIdSchema,
1547
- threadId: threadIdSchema,
1591
+ emailId: requestEmailIdSchema,
1592
+ threadId: requestThreadIdSchema,
1548
1593
 
1549
1594
  header: Joi.object().description('Search specific email headers').label('Headers').unknown().example({ 'Message-ID': '<1DAF52A51E674A2@example.com>' }),
1550
1595
 
@@ -1568,7 +1613,7 @@ const searchSchema = Joi.object({
1568
1613
  .label('LabelFilter'),
1569
1614
 
1570
1615
  emailIds: Joi.array()
1571
- .items(emailIdSchema)
1616
+ .items(requestEmailIdSchema)
1572
1617
  .single()
1573
1618
  .description('List of specific email IDs to fetch')
1574
1619
  .meta({ usage: FIELD_USAGE.searchEmailIds })
@@ -1758,7 +1803,7 @@ const oauthCreateSchema = {
1758
1803
  then: Joi.required(),
1759
1804
  otherwise: Joi.optional().valid(false, null)
1760
1805
  })
1761
- .example('boT7Q~dUljnfFdVuqpC11g8nGMjO8kpRAv-ZB')
1806
+ .example('example-client-secret')
1762
1807
  .description('OAuth2 client secret from the provider'),
1763
1808
 
1764
1809
  baseScopes: Joi.string()
@@ -2404,7 +2449,7 @@ const messageReferenceSchema = Joi.object({
2404
2449
  .example('<test123@example.com>')
2405
2450
  .description('Verify the Message-ID of the referenced email matches this value before proceeding'),
2406
2451
 
2407
- threadId: threadIdSchema.description('Gmail thread ID to attach the outgoing message to').meta({ usage: FIELD_USAGE.referenceThreadId }),
2452
+ threadId: requestThreadIdSchema.description('Gmail thread ID to attach the outgoing message to').meta({ usage: FIELD_USAGE.referenceThreadId }),
2408
2453
 
2409
2454
  documentStore: documentStoreSchema
2410
2455
  })
@@ -2717,6 +2762,7 @@ function apiResponses(description, ...statusCodes) {
2717
2762
  }
2718
2763
 
2719
2764
  module.exports = {
2765
+ requireTlsSchema,
2720
2766
  apiBoolean,
2721
2767
  formBoolean,
2722
2768
  MAX_MESSAGE_ATTACHMENTS,
package/lib/settings.js CHANGED
@@ -49,7 +49,12 @@ const AI_HANDLER_KEYS = new Set(['generateEmailSummary', 'openAiAPIKey', 'openAi
49
49
  // rotation.
50
50
  const CREDENTIAL_BEARING_URL_KEYS = ['webhooks', 'proxyUrl', 'httpProxyUrl', 'sentryDsn', 'authServer'];
51
51
  const CREDENTIAL_BEARING_HEADER_KEYS = ['webhooksCustomHeaders'];
52
- const CREDENTIAL_BEARING_KEYS = CREDENTIAL_BEARING_URL_KEYS.concat(CREDENTIAL_BEARING_HEADER_KEYS);
52
+ // The environment the operator's webhook and pre-processing scripts read: the settings page tells
53
+ // them to keep the API keys and tokens their scripts use in it. Encrypted at rest like the lists
54
+ // above; read back whole, since the page edits it as JSON, and masking is not what a free-form
55
+ // value can get. Privileged already, so a narrowed credential never sees it
56
+ const CREDENTIAL_BEARING_TEXT_KEYS = ['scriptEnv'];
57
+ const CREDENTIAL_BEARING_KEYS = CREDENTIAL_BEARING_URL_KEYS.concat(CREDENTIAL_BEARING_HEADER_KEYS, CREDENTIAL_BEARING_TEXT_KEYS);
53
58
 
54
59
  const ENCRYPTED_KEYS = SECRET_KEYS.concat(CREDENTIAL_BEARING_KEYS);
55
60
 
@@ -188,6 +193,13 @@ module.exports = {
188
193
  return await this.getValue(encryptSecret, key, value);
189
194
  },
190
195
 
196
+ // The stored string as it is in Redis, without decryption or parsing. For a caller that has
197
+ // to tell a missing value from one that is present but does not decrypt: get() answers null
198
+ // for both
199
+ async getRaw(key) {
200
+ return await redis.hget(`${REDIS_PREFIX}settings`, key);
201
+ },
202
+
191
203
  formatSettingValue(key, value) {
192
204
  switch (key) {
193
205
  case 'serviceUrl': {
package/lib/smtp-auth.js CHANGED
@@ -39,6 +39,12 @@ function createSmtpAuthHandler({ accountCache, call }) {
39
39
  if (!result.authenticated) {
40
40
  throw new Error(REASON_MESSAGES[result.reason] || 'Failed to authenticate user');
41
41
  }
42
+
43
+ // Kept on the session (in memory, never stored) so each submission can ask whether
44
+ // the token is still what it was at login: a session can stay open for as long as
45
+ // the client likes, and a token deleted or narrowed in the meantime must not keep
46
+ // sending through it
47
+ session.eeTokenAuth = { password: auth.password, account: auth.username };
42
48
  }
43
49
 
44
50
  let accountObject = new Account({ account, redis, call, secret: await getSecret() });
@@ -133,6 +139,23 @@ function createSmtpAccountResolver({ accountCache, call }) {
133
139
  }
134
140
  } else {
135
141
  accountObject = accountCache.get(session);
142
+
143
+ if (accountObject && session.eeTokenAuth) {
144
+ // The token that opened this session has to still admit it, see onAuth()
145
+ let result = await validateAuthToken({
146
+ password: session.eeTokenAuth.password,
147
+ account: session.eeTokenAuth.account,
148
+ requiredScope: 'smtp',
149
+ remoteAddress: session.remoteAddress,
150
+ recheck: true
151
+ });
152
+ if (!result.authenticated) {
153
+ accountCache.delete(session);
154
+ let err = new Error('Authentication required');
155
+ err.responseCode = 530;
156
+ throw err;
157
+ }
158
+ }
136
159
  }
137
160
 
138
161
  if (!session.eeAuthEnabled && !messageMeta.requestedAccount && !accountObject) {
package/lib/sso.js CHANGED
@@ -35,7 +35,7 @@
35
35
  // dotted path (e.g. "realm_access.roles") for IdPs that nest it.
36
36
 
37
37
  const { fetch: fetchCmd } = require('undici');
38
- const { backOff } = require('exponential-backoff');
38
+ const { backOff } = require('./utils/back-off');
39
39
  const { readEnvValue, httpAgent, getBoolean } = require('./tools');
40
40
  const packageData = require('../package.json');
41
41
 
@@ -145,7 +145,7 @@ Full documentation: https://learn.emailengine.app/`
145
145
  description: 'Configure OAuth2 applications for Gmail, Outlook, and other providers. Manage client credentials and authentication flows',
146
146
  externalDocs: {
147
147
  description: 'OAuth2 Configuration Guide',
148
- url: 'https://learn.emailengine.app/docs/configuration/oauth2-configuration'
148
+ url: 'https://learn.emailengine.app/docs/accounts/oauth2-setup'
149
149
  }
150
150
  },
151
151
  {
@@ -0,0 +1,46 @@
1
+ 'use strict';
2
+
3
+ // What the main thread reports about its worker threads beyond their counts: the fields the
4
+ // heartbeat log lines carry and the per-thread event loop delay gauges. Kept free of server.js
5
+ // state so both can be tested without starting the process.
6
+
7
+ /**
8
+ * Fields for a heartbeat log line (unhealthy, restarting, recovered).
9
+ * @param {Object} args
10
+ * @param {number} args.now - Current time in milliseconds
11
+ * @param {number} [args.lastHeartbeat] - When the thread last reported in
12
+ * @param {number} [args.accounts] - Accounts assigned to the thread, for an account worker
13
+ * @param {Object} [args.threadInfo] - The thread's last resource reading. A thread that has gone quiet
14
+ * cannot answer, so this is the one taken before that, at most one collection interval earlier.
15
+ * @returns {Object} Fields to spread into the log entry
16
+ */
17
+ function heartbeatDiagnostics({ now, lastHeartbeat, accounts, threadInfo }) {
18
+ let details = {};
19
+ if (typeof lastHeartbeat === 'number') {
20
+ details.timeSinceHeartbeat = Math.round((now - lastHeartbeat) / 1000) + 's';
21
+ }
22
+ if (typeof accounts === 'number') {
23
+ details.accounts = accounts;
24
+ }
25
+ if (threadInfo?.eventLoopDelay) {
26
+ details.lastEventLoopDelay = Math.round(threadInfo.eventLoopDelay.max) + 'ms';
27
+ }
28
+ return details;
29
+ }
30
+
31
+ /**
32
+ * The per-thread event loop delay gauge values, in seconds, for every thread that has a reading.
33
+ * @param {Array<Object>} threadsInfo - Thread readings as the metrics collector returns them
34
+ * @returns {Array<{labels: Object, max: number, p99: number}>}
35
+ */
36
+ function eventLoopDelaySeries(threadsInfo) {
37
+ return (threadsInfo || [])
38
+ .filter(threadInfo => threadInfo.eventLoopDelay)
39
+ .map(threadInfo => ({
40
+ labels: { type: threadInfo.type, thread: String(threadInfo.threadId) },
41
+ max: threadInfo.eventLoopDelay.max / 1000,
42
+ p99: threadInfo.eventLoopDelay.p99 / 1000
43
+ }));
44
+ }
45
+
46
+ module.exports = { heartbeatDiagnostics, eventLoopDelaySeries };
@@ -0,0 +1,109 @@
1
+ 'use strict';
2
+
3
+ // The timezone choices on the admin Service page, built from the runtime's own ICU data instead of
4
+ // a static package. Node (and the pkg binaries, which carry full ICU) list zones under their CLDR
5
+ // ids, and CLDR keeps the old spelling for zones IANA has since renamed: Intl answers
6
+ // "Europe/Kiev" and "Asia/Calcutta", never "Europe/Kyiv" or "Asia/Kolkata". Those are shown and
7
+ // stored under their IANA names, which is also what the replaced timezones-list package offered, so
8
+ // a value saved from the old list stays selected. Intl accepts both spellings as a timeZone.
9
+
10
+ // CLDR id -> current IANA name, for every id Intl.supportedValuesOf('timeZone') returns in its
11
+ // legacy form (checked on Node 20, 24 and 26, all ICU 78)
12
+ const IANA_NAMES = new Map([
13
+ ['Africa/Asmera', 'Africa/Asmara'],
14
+ ['America/Buenos_Aires', 'America/Argentina/Buenos_Aires'],
15
+ ['America/Catamarca', 'America/Argentina/Catamarca'],
16
+ ['America/Coral_Harbour', 'America/Atikokan'],
17
+ ['America/Cordoba', 'America/Argentina/Cordoba'],
18
+ ['America/Indianapolis', 'America/Indiana/Indianapolis'],
19
+ ['America/Jujuy', 'America/Argentina/Jujuy'],
20
+ ['America/Louisville', 'America/Kentucky/Louisville'],
21
+ ['America/Mendoza', 'America/Argentina/Mendoza'],
22
+ ['Asia/Calcutta', 'Asia/Kolkata'],
23
+ ['Asia/Katmandu', 'Asia/Kathmandu'],
24
+ ['Asia/Rangoon', 'Asia/Yangon'],
25
+ ['Asia/Saigon', 'Asia/Ho_Chi_Minh'],
26
+ ['Atlantic/Faeroe', 'Atlantic/Faroe'],
27
+ ['Europe/Kiev', 'Europe/Kyiv'],
28
+ ['Pacific/Ponape', 'Pacific/Pohnpei'],
29
+ ['Pacific/Truk', 'Pacific/Chuuk']
30
+ ]);
31
+
32
+ // Offsets are read on these dates so the label shows the standard offset all year round instead
33
+ // of moving with daylight saving time: the smaller of a January and a July offset is the standard
34
+ // one in both hemispheres
35
+ const SAMPLE_DATES = [new Date(Date.UTC(2026, 0, 1)), new Date(Date.UTC(2026, 6, 1))];
36
+
37
+ /**
38
+ * @param {string} timeZone
39
+ * @param {Date} date
40
+ * @returns {number|null} UTC offset in minutes, or null for an unknown zone
41
+ */
42
+ function getOffsetMinutes(timeZone, date) {
43
+ let name;
44
+ try {
45
+ name = new Intl.DateTimeFormat('en-US', { timeZone, timeZoneName: 'longOffset' }).formatToParts(date).find(part => part.type === 'timeZoneName').value;
46
+ } catch {
47
+ return null;
48
+ }
49
+ // "GMT" alone is UTC, otherwise "GMT+05:30" / "GMT-03:00"
50
+ const match = name.match(/^GMT(?:([+-])(\d{2}):(\d{2}))?$/);
51
+ if (!match) {
52
+ return null;
53
+ }
54
+ return match[1] ? (match[1] === '-' ? -1 : 1) * (Number(match[2]) * 60 + Number(match[3])) : 0;
55
+ }
56
+
57
+ // The standard offset of a zone, null when the runtime does not know it
58
+ function getStandardOffset(timeZone) {
59
+ const offsets = SAMPLE_DATES.map(date => getOffsetMinutes(timeZone, date)).filter(offset => offset !== null);
60
+ return offsets.length ? Math.min(...offsets) : null;
61
+ }
62
+
63
+ function formatOffset(minutes) {
64
+ const sign = minutes < 0 ? '-' : '+';
65
+ const abs = Math.abs(minutes);
66
+ return `GMT${sign}${String(Math.floor(abs / 60)).padStart(2, '0')}:${String(abs % 60).padStart(2, '0')}`;
67
+ }
68
+
69
+ let cachedZones = null;
70
+
71
+ /**
72
+ * Every zone the runtime knows under its IANA name, ordered by standard offset and then by name.
73
+ *
74
+ * @returns {{ timezone: string, offset: number, label: string }[]}
75
+ */
76
+ function listTimezones() {
77
+ if (!cachedZones) {
78
+ const zones = new Map();
79
+ for (const id of Intl.supportedValuesOf('timeZone')) {
80
+ const timezone = IANA_NAMES.get(id) || id;
81
+ const offset = getStandardOffset(id);
82
+ if (offset === null || zones.has(timezone)) {
83
+ continue;
84
+ }
85
+ zones.set(timezone, { timezone, offset, label: `${timezone} (${formatOffset(offset)})` });
86
+ }
87
+ cachedZones = [...zones.values()].sort((a, b) => a.offset - b.offset || a.timezone.localeCompare(b.timezone));
88
+ }
89
+ return cachedZones;
90
+ }
91
+
92
+ /**
93
+ * Options for the timezone select. A stored value the runtime does not list (a zone IANA has
94
+ * since merged into another, like America/Yellowknife) is kept as an option of its own, so opening
95
+ * and saving the page never changes it.
96
+ *
97
+ * @param {string|false|null|undefined} selected The stored timezone
98
+ * @returns {{ name: string, timezone: string, selected: boolean }[]}
99
+ */
100
+ function timezoneOptions(selected) {
101
+ const options = listTimezones().map(zone => ({ name: zone.label, timezone: zone.timezone, selected: zone.timezone === selected }));
102
+ if (selected && !options.some(option => option.selected)) {
103
+ const offset = getStandardOffset(selected);
104
+ options.unshift({ name: offset === null ? selected : `${selected} (${formatOffset(offset)})`, timezone: selected, selected: true });
105
+ }
106
+ return options;
107
+ }
108
+
109
+ module.exports = { listTimezones, timezoneOptions, IANA_NAMES };
@@ -205,14 +205,14 @@ const MCP_SECTIONS = {
205
205
  {
206
206
  value: 'mail',
207
207
  label: 'Mail agent',
208
- hint: 'Read, organize, draft and send mail - everything except the delete tool.',
209
- caveat: 'Everything except the delete tool. Instructions inside received mail are a real prompt-injection risk once sending is granted.',
208
+ hint: 'Read, organize, draft and send mail, and create and rename folders - everything except deleting.',
209
+ caveat: 'Everything except deleting messages and folders. Instructions inside received mail are a real prompt-injection risk once sending is granted.',
210
210
  pairs: pairsOf(MCP_SCOPES.mail, grant => grant.action !== ACTION.DESTRUCTIVE)
211
211
  },
212
212
  {
213
213
  value: 'full',
214
214
  label: 'Full access',
215
- hint: 'Every mail tool, including deleting messages.',
215
+ hint: 'Every mail tool, including deleting messages and folders.',
216
216
  caveat: 'Instructions inside received mail are a real prompt-injection risk once sending is granted.',
217
217
  pairs: pairsOf(MCP_SCOPES.mail, () => true)
218
218
  }