emailengine-app 2.81.2 → 2.82.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 (226) hide show
  1. package/.ncurc.js +33 -10
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +71 -0
  4. package/DOCKER_DEPLOYMENT.md +13 -12
  5. package/Dockerfile +2 -0
  6. package/bin/emailengine.js +105 -25
  7. package/config/default.toml +0 -5
  8. package/config/test.toml +0 -5
  9. package/data/google-crawlers.json +1 -1
  10. package/encrypt.js +70 -42
  11. package/getswagger.sh +0 -4
  12. package/lib/account/account-state.js +2 -110
  13. package/lib/account/expected-identity.js +1 -1
  14. package/lib/account-assignment.js +138 -1
  15. package/lib/account.js +289 -869
  16. package/lib/api-reference/index.js +2 -3
  17. package/lib/api-reference/schema-tree.js +53 -3
  18. package/lib/api-routes/account-binding.js +58 -0
  19. package/lib/api-routes/account-routes.js +65 -37
  20. package/lib/api-routes/behavior-notes.js +4 -0
  21. package/lib/api-routes/blocklist-routes.js +2 -2
  22. package/lib/api-routes/bull-board-routes.js +1 -6
  23. package/lib/api-routes/export-routes.js +2 -22
  24. package/lib/api-routes/gateway-routes.js +15 -16
  25. package/lib/api-routes/index.js +1 -13
  26. package/lib/api-routes/mailbox-routes.js +2 -7
  27. package/lib/api-routes/mcp-oauth-routes.js +2 -1
  28. package/lib/api-routes/mcp-routes.js +7 -7
  29. package/lib/api-routes/message-routes.js +50 -238
  30. package/lib/api-routes/mint-bounds.js +110 -0
  31. package/lib/api-routes/oauth2-app-routes.js +23 -32
  32. package/lib/api-routes/operation-impact.js +1 -1
  33. package/lib/api-routes/outbox-routes.js +3 -3
  34. package/lib/api-routes/permission-map.js +1 -7
  35. package/lib/api-routes/route-helpers.js +11 -5
  36. package/lib/api-routes/settings-routes.js +20 -21
  37. package/lib/api-routes/stats-routes.js +1 -1
  38. package/lib/api-routes/submit-routes.js +17 -18
  39. package/lib/api-routes/template-routes.js +4 -9
  40. package/lib/api-routes/token-routes.js +28 -6
  41. package/lib/api-token-scheme.js +71 -0
  42. package/lib/arf-detect.js +33 -6
  43. package/lib/auth-token.js +44 -24
  44. package/lib/autodetect-imap-settings.js +305 -123
  45. package/lib/bounce-detect.js +25 -16
  46. package/lib/calendar-event.js +78 -0
  47. package/lib/consts.js +54 -5
  48. package/lib/create-imap-client.js +24 -0
  49. package/lib/db.js +77 -30
  50. package/lib/delivery-error.js +70 -2
  51. package/lib/egress-fetch.js +54 -3
  52. package/lib/egress-filter.js +11 -0
  53. package/lib/email-client/api-retry.js +147 -0
  54. package/lib/email-client/base-client.js +383 -536
  55. package/lib/email-client/credential-errors.js +21 -5
  56. package/lib/email-client/gmail/gmail-api.js +38 -125
  57. package/lib/email-client/gmail/send-request.js +1 -1
  58. package/lib/email-client/gmail-client.js +77 -51
  59. package/lib/email-client/imap/mailbox.js +158 -324
  60. package/lib/email-client/imap/stale-view.js +109 -0
  61. package/lib/email-client/imap/subconnection.js +46 -9
  62. package/lib/email-client/imap/sync-operations.js +5 -37
  63. package/lib/email-client/imap-client.js +190 -65
  64. package/lib/email-client/message-builder.js +50 -25
  65. package/lib/email-client/notification-handler.js +5 -219
  66. package/lib/email-client/outlook/graph-api.js +147 -126
  67. package/lib/email-client/outlook/send-request.js +10 -4
  68. package/lib/email-client/outlook-client.js +389 -463
  69. package/lib/email-client/smtp-pool-manager.js +3 -2
  70. package/lib/encrypt.js +184 -19
  71. package/lib/enum-descriptions.js +6 -3
  72. package/lib/export.js +141 -41
  73. package/lib/gateway.js +25 -6
  74. package/lib/get-raw-email.js +26 -44
  75. package/lib/get-secret.js +1 -21
  76. package/lib/handlebars-helpers.js +31 -10
  77. package/lib/imap-proxy-auth.js +13 -29
  78. package/lib/imapproxy/imap-core/README.md +1 -0
  79. package/lib/imapproxy/imap-core/lib/handler/imap-parser.js +12 -0
  80. package/lib/imapproxy/imap-core/lib/imap-command.js +74 -10
  81. package/lib/imapproxy/imap-core/lib/imap-connection.js +9 -1
  82. package/lib/imapproxy/imap-core/lib/imap-server.js +112 -26
  83. package/lib/imapproxy/imap-core/lib/imap-stream.js +41 -1
  84. package/lib/imapproxy/imap-core/lib/imap-tools.js +10 -2
  85. package/lib/imapproxy/imap-core/lib/indexer/indexer.js +4 -2
  86. package/lib/imapproxy/imap-server.js +17 -177
  87. package/lib/imapproxy/proxy-handoff.js +235 -0
  88. package/lib/imapproxy/response-error.js +33 -0
  89. package/lib/imapproxy/upstream-client.js +2 -2
  90. package/lib/license-beacon.js +3 -9
  91. package/lib/llm-pre-process.js +182 -43
  92. package/lib/logger.js +1 -1
  93. package/lib/lua/ee-export-queue-add.lua +39 -0
  94. package/lib/lua/ee-get-idempotency.lua +15 -3
  95. package/lib/lua/ee-release-attempts.lua +23 -0
  96. package/lib/lua/ee-reserve-attempts.lua +42 -0
  97. package/lib/lua/h-set-bigger.lua +12 -2
  98. package/lib/lua/s-list-accounts.lua +6 -3
  99. package/lib/mcp/index.js +1 -2
  100. package/lib/mcp/listen.js +221 -18
  101. package/lib/mcp/oauth.js +44 -5
  102. package/lib/mcp/resources.js +8 -2
  103. package/lib/mcp/tools.js +108 -36
  104. package/lib/message-port-stream.js +64 -6
  105. package/lib/oauth/external-account-signer.js +16 -13
  106. package/lib/oauth/gmail.js +64 -32
  107. package/lib/oauth/mail-ru.js +24 -17
  108. package/lib/oauth/outlook.js +53 -40
  109. package/lib/oauth/pubsub/google.js +38 -2
  110. package/lib/oauth/scope-checker.js +39 -8
  111. package/lib/oauth/scope-list.js +55 -0
  112. package/lib/oauth/token-fetch.js +47 -0
  113. package/lib/oauth/verify-app.js +2 -2
  114. package/lib/oauth2-apps.js +154 -90
  115. package/lib/openapi/build-document.js +1 -1
  116. package/lib/openapi/joi-schema.js +78 -9
  117. package/lib/outbox.js +2 -7
  118. package/lib/parse-message.js +21 -0
  119. package/lib/payload-examples-webhooks.json +4 -7
  120. package/lib/pbkdf2-phc.js +101 -0
  121. package/lib/privileged-settings.js +0 -14
  122. package/lib/queue-retention.js +4 -2
  123. package/lib/rate-limit.js +54 -15
  124. package/lib/read-env-value.js +33 -2
  125. package/lib/redis-scan-delete.js +56 -29
  126. package/lib/redis-url.js +3 -1
  127. package/lib/respawn-backoff.js +5 -4
  128. package/lib/response-stream.js +25 -4
  129. package/lib/rewrite-text-nodes.js +27 -40
  130. package/lib/routes-ui.js +0 -5
  131. package/lib/schemas.js +180 -253
  132. package/lib/sentry.js +21 -5
  133. package/lib/settings.js +58 -59
  134. package/lib/smtp-auth.js +6 -2
  135. package/lib/smtp-message-processor.js +28 -7
  136. package/lib/sso.js +7 -3
  137. package/lib/stream-encrypt.js +14 -13
  138. package/lib/swagger-options.js +3 -1
  139. package/lib/tls/provision.js +69 -3
  140. package/lib/tls/store.js +14 -1
  141. package/lib/token-audit-log.js +3 -2
  142. package/lib/tools.js +114 -53
  143. package/lib/totp.js +16 -1
  144. package/lib/ui-routes/account-routes.js +67 -70
  145. package/lib/ui-routes/admin-config-routes.js +111 -134
  146. package/lib/ui-routes/admin-entities-routes.js +101 -191
  147. package/lib/ui-routes/ai-options.js +104 -0
  148. package/lib/ui-routes/auth-routes.js +98 -18
  149. package/lib/ui-routes/export-routes.js +3 -23
  150. package/lib/ui-routes/internals-routes.js +12 -9
  151. package/lib/ui-routes/network-config-routes.js +8 -18
  152. package/lib/ui-routes/oauth-config-routes.js +83 -228
  153. package/lib/ui-routes/route-helpers.js +63 -67
  154. package/lib/ui-routes/special-use-paths.js +33 -0
  155. package/lib/ui-routes/unsubscribe-routes.js +2 -2
  156. package/lib/utils/decode-headers.js +32 -5
  157. package/lib/utils/header-map.js +62 -1
  158. package/lib/utils/network.js +11 -17
  159. package/lib/web-safe-html.js +77 -4
  160. package/lib/webhook-request.js +9 -1
  161. package/lib/webhook-routing.js +27 -1
  162. package/lib/webhooks.js +120 -43
  163. package/lib/worker-rpc-error.js +43 -2
  164. package/list-generate.js +13 -2
  165. package/package.json +38 -46
  166. package/sbom.json +1 -1
  167. package/scripts/refresh-test-tokens.js +42 -14
  168. package/server.js +338 -292
  169. package/setup-production.sh +16 -7
  170. package/static/css/flyonui.css +1 -1
  171. package/static/css/src/app.tailwind.css +7 -8
  172. package/static/js/ee-client.js +145 -70
  173. package/static/js/ui.js +350 -154
  174. package/static/licenses.html +349 -1740
  175. package/translations/messages.pot +129 -111
  176. package/views/account-workspace-error.hbs +30 -0
  177. package/views/accounts/account.hbs +9 -4
  178. package/views/accounts/browse.hbs +10 -4
  179. package/views/accounts/edit.hbs +11 -2
  180. package/views/config/ai.hbs +49 -41
  181. package/views/config/oauth/app.hbs +2 -1
  182. package/views/dashboard.hbs +18 -16
  183. package/views/internals/index.hbs +1 -1
  184. package/views/layout/app.hbs +0 -22
  185. package/views/layout/login.hbs +2 -1
  186. package/views/partials/filter_editor_js.hbs +4 -3
  187. package/views/partials/gmail_api_scopes.hbs +16 -0
  188. package/views/partials/oauth_form.hbs +67 -94
  189. package/views/partials/oauth_pubsub_app_select.hbs +43 -0
  190. package/views/partials/scope_info.hbs +14 -23
  191. package/views/partials/side_menu.hbs +0 -4
  192. package/views/partials/ui/account-picker.hbs +6 -32
  193. package/views/partials/ui/model-picker.hbs +31 -0
  194. package/views/partials/ui/pagination.hbs +6 -1
  195. package/views/partials/ui/picker.hbs +47 -0
  196. package/views/unsubscribe.hbs +1 -1
  197. package/workers/api.js +82 -47
  198. package/workers/export.js +55 -60
  199. package/workers/imap.js +132 -49
  200. package/workers/submit.js +5 -6
  201. package/workers/webhooks.js +46 -27
  202. package/.githooks/pre-commit +0 -80
  203. package/.github/CODE_OF_CONDUCT.md +0 -76
  204. package/.github/contributing.md +0 -17
  205. package/.github/dependabot.yml +0 -22
  206. package/.github/docker-smoke-test.sh +0 -61
  207. package/.github/workflows/deploy.yml +0 -215
  208. package/.github/workflows/e2e.yml +0 -55
  209. package/.github/workflows/release.yaml +0 -217
  210. package/.github/workflows/test.yml +0 -307
  211. package/lib/api-routes/chat-routes.js +0 -535
  212. package/lib/document-store.js +0 -75
  213. package/lib/es.js +0 -757
  214. package/lib/generate-text-preview.js +0 -61
  215. package/lib/imapproxy/imap-core/memory-notifier.js +0 -129
  216. package/lib/pre-process.js +0 -196
  217. package/lib/threads.js +0 -155
  218. package/lib/ui-routes/document-store-routes.js +0 -806
  219. package/playwright.config.js +0 -47
  220. package/views/config/document-store/chat.hbs +0 -286
  221. package/views/config/document-store/index.hbs +0 -146
  222. package/views/config/document-store/mappings/index.hbs +0 -108
  223. package/views/config/document-store/mappings/new.hbs +0 -68
  224. package/views/config/document-store/pre-processing/index.hbs +0 -103
  225. package/views/partials/document_store_header.hbs +0 -30
  226. package/workers/documents.js +0 -1128
package/lib/sentry.js CHANGED
@@ -1,5 +1,6 @@
1
1
  'use strict';
2
2
 
3
+ const crypto = require('crypto');
3
4
  const packageData = require('../package.json');
4
5
  const logger = require('./logger');
5
6
  const { readEnvValue, httpAgent } = require('./tools');
@@ -29,7 +30,7 @@ const SENTRY_RELEASE = `${packageData.name}@${packageData.version}`;
29
30
  // settings change applies to the next event without a restart. Only the two headers Sentry's
30
31
  // rate limiting reads are handed back.
31
32
  function makeTransport(options) {
32
- const { createTransport } = require('@sentry/node');
33
+ const { createTransport } = require('@sentry/node-core/light');
33
34
 
34
35
  return createTransport(options, async request => {
35
36
  let res = await fetchCmd(options.url, {
@@ -54,9 +55,12 @@ function makeTransport(options) {
54
55
 
55
56
  function startSentry(dsn) {
56
57
  // require lazily, the SDK loads several hundred modules in every worker thread,
57
- // so only pay that cost when error tracking is actually enabled
58
+ // so only pay that cost when error tracking is actually enabled. The light entry of
59
+ // @sentry/node-core is the SDK without the OpenTelemetry setup and the automatic
60
+ // instrumentation @sentry/node layers on top - both switched off below anyway - which
61
+ // keeps that closure out of the tree and the binary.
58
62
  if (!Sentry) {
59
- Sentry = require('@sentry/node');
63
+ Sentry = require('@sentry/node-core/light');
60
64
  }
61
65
 
62
66
  Sentry.init({
@@ -106,6 +110,18 @@ function startSentry(dsn) {
106
110
  logger.flushNotifications = () => Sentry.flush(2000);
107
111
  }
108
112
 
113
+ /**
114
+ * The license identity sent with error reports: a short SHA-256 digest of the key rather than the
115
+ * key itself. Tags are indexed and searchable by anyone with access to the Sentry project (the
116
+ * community one is shared), while the logs carefully keep the key out. A known key still maps to
117
+ * its digest, so reports stay attributable to a customer.
118
+ * @param {string} key - License key
119
+ * @returns {string}
120
+ */
121
+ function licenseTag(key) {
122
+ return crypto.createHash('sha256').update(String(key)).digest('hex').slice(0, 16);
123
+ }
124
+
109
125
  // Tag all events with the installation identity, so reports from different
110
126
  // EmailEngine instances sharing the same DSN can be told apart. Read once per
111
127
  // SDK start - a license swapped at runtime is reflected after the next restart.
@@ -117,7 +133,7 @@ async function applyIdentityTags() {
117
133
  tags.instance = serviceId;
118
134
  }
119
135
  if (tract?.key) {
120
- tags.license = tract.key;
136
+ tags.license = licenseTag(tract.key);
121
137
  }
122
138
  Sentry.getGlobalScope().setTags(tags);
123
139
  }
@@ -187,4 +203,4 @@ function initSentry(worker) {
187
203
  setImmediate(checkSettings);
188
204
  }
189
205
 
190
- module.exports = { initSentry, makeTransport, SENTRY_RELEASE };
206
+ module.exports = { initSentry, makeTransport, licenseTag, SENTRY_RELEASE };
package/lib/settings.js CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  const { redis } = require('./db');
4
4
  const logger = require('./logger');
5
- const { encrypt, decrypt } = require('./encrypt');
5
+ const { encrypt, decryptField } = require('./encrypt');
6
6
  const config = require('@zone-eu/wild-config');
7
7
  const getSecret = require('./get-secret');
8
8
 
@@ -26,18 +26,30 @@ const SECRET_KEYS = [
26
26
  'serviceSecret',
27
27
  'gmailServiceKey',
28
28
  'gmailServiceExternalAccount',
29
+ // The Document Store was removed in 2.82.0, but the stored password stays listed so a
30
+ // secret rotation on this version keeps it readable for a downgrade to the last release
31
+ // that had the feature
29
32
  'documentStorePassword',
30
33
  'openAiAPIKey',
31
34
  'totpSeed'
32
35
  ];
33
36
 
37
+ // The settings the workers' summary handler is built from
38
+ const AI_HANDLER_KEYS = new Set(['generateEmailSummary', 'openAiAPIKey', 'openAiPreProcessingFn']);
39
+
34
40
  // Values that carry a secret without being one: URLs that may embed `user:pass@` credentials
35
41
  // (a SOCKS or HTTP proxy, a webhook target, a Sentry DSN with its key) and the custom webhook
36
42
  // headers, whose example is an Authorization bearer. Encrypted at rest like the secrets, but the
37
- // API reads them back with only the credential part masked (route-helpers maskSecrets()), so they
38
- // are not in the list it turns into booleans. Encryption applies to the JSON encoding, so the
39
- // header list being an array rather than a string makes no difference.
40
- const CREDENTIAL_BEARING_KEYS = ['webhooks', 'webhooksCustomHeaders', 'proxyUrl', 'httpProxyUrl', 'sentryDsn'];
43
+ // API reads them back with only the credential part masked (route-helpers maskSecrets(), which
44
+ // derives its masking lists from these two so a key added here is masked without a second edit),
45
+ // so they are not in the list it turns into booleans. Encryption applies to the JSON encoding, so
46
+ // the header list being an array rather than a string makes no difference. `authServer` belongs
47
+ // here too: resolveCredentials() honors `user:pass@` in it. A value stored before it joined the
48
+ // list is cleartext, which decrypt() passes through, so it keeps reading until the next save or
49
+ // rotation.
50
+ const CREDENTIAL_BEARING_URL_KEYS = ['webhooks', 'proxyUrl', 'httpProxyUrl', 'sentryDsn', 'authServer'];
51
+ const CREDENTIAL_BEARING_HEADER_KEYS = ['webhooksCustomHeaders'];
52
+ const CREDENTIAL_BEARING_KEYS = CREDENTIAL_BEARING_URL_KEYS.concat(CREDENTIAL_BEARING_HEADER_KEYS);
41
53
 
42
54
  const ENCRYPTED_KEYS = SECRET_KEYS.concat(CREDENTIAL_BEARING_KEYS);
43
55
 
@@ -69,6 +81,11 @@ module.exports = {
69
81
  // What a narrowed token may never read or write, see lib/privileged-settings.js
70
82
  privilegedKeys: PRIVILEGED_SETTINGS_KEYS,
71
83
 
84
+ // The credential-bearing subset, split by shape for the masking in route-helpers: URLs whose
85
+ // userinfo is masked, and {key, value} header lists whose values are
86
+ credentialBearingUrlKeys: CREDENTIAL_BEARING_URL_KEYS,
87
+ credentialBearingHeaderKeys: CREDENTIAL_BEARING_HEADER_KEYS,
88
+
72
89
  /**
73
90
  * Whether admin authentication is configured for this instance.
74
91
  *
@@ -88,34 +105,46 @@ module.exports = {
88
105
  }
89
106
 
90
107
  if (typeof value === 'string') {
91
- try {
92
- if (encryptSecret && ENCRYPTED_KEYS.includes(key) && typeof value === 'string') {
93
- // NB! throws if password is invalid
94
- value = decrypt(value, encryptSecret);
108
+ const encrypted = ENCRYPTED_KEYS.includes(key);
109
+
110
+ // NB! never log `value` here. By the parse step a value for an encrypted key has
111
+ // already been decrypted, so on a parse failure this would write the plaintext
112
+ // secret (OAuth2 client secrets, the SMTP/IMAP proxy passwords) into the log.
113
+ // The error object is not safe either: a JSON.parse SyntaxError quotes the head of
114
+ // its input, which for an encrypted key is that same plaintext.
115
+ const report = err => {
116
+ if (reportedParseFailures.has(key)) {
117
+ return;
118
+ }
119
+ reportedParseFailures.add(key);
120
+ if (encrypted) {
121
+ logger.warn({ msg: 'Failed to parse stored setting', key, encrypted, errorType: err.name });
122
+ } else {
123
+ logger.warn({ msg: 'Failed to parse stored setting', key, encrypted, err });
95
124
  }
125
+ };
96
126
 
97
- value = JSON.parse(value);
127
+ if (encrypted) {
128
+ value = decryptField(value, encryptSecret, report);
129
+ if (typeof value === 'undefined') {
130
+ return null;
131
+ }
132
+ }
98
133
 
134
+ try {
135
+ value = JSON.parse(value);
99
136
  reportedParseFailures.delete(key);
100
137
  } catch (err) {
101
- // NB! never log `value` here. By this point a value for an encrypted key has
102
- // already been decrypted, so on a parse failure this would write the plaintext
103
- // secret (OAuth2 client secrets, the SMTP/IMAP proxy passwords) into the log.
104
- // The error object is not safe either: a JSON.parse SyntaxError quotes the head of
105
- // its input, which for an encrypted key is that same plaintext.
106
- let encrypted = ENCRYPTED_KEYS.includes(key);
107
- if (!reportedParseFailures.has(key)) {
108
- reportedParseFailures.add(key);
109
- if (encrypted) {
110
- logger.warn({ msg: 'Failed to parse stored setting', key, encrypted, errorType: err.name });
111
- } else {
112
- logger.warn({ msg: 'Failed to parse stored setting', key, encrypted, err });
113
- }
114
- }
138
+ report(err);
115
139
  return null;
116
140
  }
117
141
  }
118
142
 
143
+ // Reached with a falsy value only when the stored JSON itself is falsy (an empty string
144
+ // saved from a form); an unset key returned null above. The redirect URL default still
145
+ // matters there, for the legacy OAuth2 settings migration. The `logs` default that used to
146
+ // sit beside it is gone: it never ran for an unset key, and every caller of
147
+ // settings.get('logs') supplies its own fallback.
119
148
  switch (key) {
120
149
  case 'gmailRedirectUrl':
121
150
  case 'outlookRedirectUrl':
@@ -132,15 +161,6 @@ module.exports = {
132
161
  }
133
162
  }
134
163
  break;
135
-
136
- case 'logs':
137
- if (!value) {
138
- value = {
139
- all: false,
140
- maxLogLines: DEFAULT_MAX_LOG_LINES
141
- };
142
- }
143
- break;
144
164
  }
145
165
 
146
166
  return value;
@@ -247,22 +267,15 @@ module.exports = {
247
267
  let formattedValue = module.exports.formatSettingValue(key, value);
248
268
  value = module.exports.encodeSettingValue(key, formattedValue, encryptSecret);
249
269
 
250
- if (/^documentStore/.test(key)) {
251
- // increase version for documentStore settings
252
- try {
253
- await redis.hincrby(`${REDIS_PREFIX}settings`, 'documentStoreVersion', 1);
254
- } catch (err) {
255
- logger.debug({ msg: 'Failed to increase document store settings version', key, err });
256
- }
257
- }
258
-
259
- if (['generateEmailSummary', 'openAiGenerateEmbeddings'].includes(key) && formattedValue) {
270
+ if (key === 'generateEmailSummary' && formattedValue) {
260
271
  // AI processing needs access to message text content, so make sure `notifyText` is enabled as well
261
272
  await module.exports.set('notifyText', true);
262
273
  }
263
274
 
264
- if (/^openAi/.test(key) || key === 'generateEmailSummary') {
265
- // increase version for OpenAI settings
275
+ // Bumping the version has every worker rebuild its summary handler, which reads exactly
276
+ // these keys (see getHandler() in lib/llm-pre-process.js). The other AI settings are read
277
+ // fresh by the main thread for every request, so a change to them needs no rebuild
278
+ if (AI_HANDLER_KEYS.has(key)) {
266
279
  try {
267
280
  await redis.hincrby(`${REDIS_PREFIX}settings`, 'openAiSettingsVersion', 1);
268
281
  } catch (err) {
@@ -300,7 +313,6 @@ module.exports = {
300
313
 
301
314
  async setMulti(obj) {
302
315
  const encryptSecret = await getSecret();
303
- let docStoreUpdated = false;
304
316
  const storeObj = {};
305
317
  for (let key of Object.keys(obj)) {
306
318
  // See set(): never persist a blank serviceSecret - a blank value means "keep the current one".
@@ -310,19 +322,6 @@ module.exports = {
310
322
 
311
323
  let formattedValue = module.exports.formatSettingValue(key, obj[key]);
312
324
  storeObj[key] = module.exports.encodeSettingValue(key, formattedValue, encryptSecret);
313
-
314
- if (/^documentStore/.test(key)) {
315
- docStoreUpdated = true;
316
- }
317
- }
318
-
319
- if (docStoreUpdated) {
320
- // increase version for documentStore settings
321
- try {
322
- await redis.hincrby(`${REDIS_PREFIX}settings`, 'documentStoreVersion', 1);
323
- } catch (err) {
324
- logger.debug({ msg: 'Failed to increase document store settings version', err });
325
- }
326
325
  }
327
326
 
328
327
  // see set(): an explicit sentryEnabled write ends the trial-managed Sentry state
package/lib/smtp-auth.js CHANGED
@@ -51,7 +51,9 @@ function createSmtpAuthHandler({ accountCache, call }) {
51
51
  if (!err.output || err.output.statusCode !== 404) {
52
52
  // only log non-obvious errors
53
53
  logger.error({ msg: 'Failed to load account data', account: auth.username, err });
54
- respErr.statusCode = 454;
54
+ // smtp-server reads responseCode; 454 tells the client to retry later instead of
55
+ // treating its credentials as wrong (535)
56
+ respErr.responseCode = 454;
55
57
  }
56
58
 
57
59
  throw respErr;
@@ -71,7 +73,9 @@ function createSmtpAuthHandler({ accountCache, call }) {
71
73
  }
72
74
 
73
75
  return await withAuthFailureBudget(
74
- { remoteAddress: session.remoteAddress, account: auth.username },
76
+ // The password opts in to the per-address budget, which ignores the username, so a
77
+ // client can not spread its guesses of the global password across account names
78
+ { remoteAddress: session.remoteAddress, account: auth.username, password: auth.password },
75
79
  () => authenticate(auth, session),
76
80
  () => {
77
81
  let err = new Error(REASON_MESSAGES.limited);
@@ -26,6 +26,32 @@ const IDEMPOTENCY_HEADER = 'x-ee-idempotency-key';
26
26
  // workers/smtp.js - both are "this message is too big in some dimension".
27
27
  const PARSE_FAILURE_RESPONSE_CODE = 552;
28
28
 
29
+ /**
30
+ * Marks a MIME splitter failure as a verdict on the message rather than a transient fault, in
31
+ * place. The splitter is a pure parser over the message bytes, so every failure it raises recurs
32
+ * on every attempt: responseCode is what the SMTP server answers with and what
33
+ * lib/delivery-error.js reads as a permanent rejection on the delivery path, and statusCode 400 is
34
+ * what the API answers for a submitted raw message. The one place the marking lives, shared with
35
+ * lib/get-raw-email.js and lib/rewrite-text-nodes.js.
36
+ *
37
+ * @param {Error} err - The splitter's error
38
+ * @returns {Error} The same error
39
+ */
40
+ function markParseFailure(err) {
41
+ if (err && typeof err === 'object') {
42
+ if (err.code === 'EMAXLEN' && !/^Failed to parse message/.test(err.message || '')) {
43
+ err.message = `Failed to parse message: ${err.message}`;
44
+ }
45
+ if (!err.responseCode) {
46
+ err.responseCode = PARSE_FAILURE_RESPONSE_CODE;
47
+ }
48
+ if (!err.statusCode) {
49
+ err.statusCode = 400;
50
+ }
51
+ }
52
+ return err;
53
+ }
54
+
29
55
  /**
30
56
  * Pipes a submitted message through the MIME splitter, strips the EmailEngine control headers
31
57
  * into `meta`, and rejoins it.
@@ -68,12 +94,7 @@ function processMessage(stream, meta) {
68
94
  source.once('error', err => joiner.emit('error', err));
69
95
  }
70
96
 
71
- splitter.once('error', err => {
72
- if (!err.responseCode) {
73
- err.responseCode = PARSE_FAILURE_RESPONSE_CODE;
74
- }
75
- joiner.emit('error', err);
76
- });
97
+ splitter.once('error', err => joiner.emit('error', markParseFailure(err)));
77
98
 
78
99
  return stream.pipe(splitter).pipe(headersRewriter).pipe(joiner);
79
100
  }
@@ -128,4 +149,4 @@ function collectMessage(rawStream, meta) {
128
149
  });
129
150
  }
130
151
 
131
- module.exports = { processMessage, collectMessage, ACCOUNT_HEADER, IDEMPOTENCY_HEADER, PARSE_FAILURE_RESPONSE_CODE };
152
+ module.exports = { processMessage, collectMessage, markParseFailure, ACCOUNT_HEADER, IDEMPOTENCY_HEADER, PARSE_FAILURE_RESPONSE_CODE };
package/lib/sso.js CHANGED
@@ -159,8 +159,8 @@ function extractGroups(userinfo, groupsClaim) {
159
159
  .filter(group => group);
160
160
  }
161
161
 
162
- // True when the profile's email (or username fallback) matches the email/domain
163
- // allow-list. Assumes the list is non-empty.
162
+ // True when the profile's email claim matches the email/domain allow-list. Assumes
163
+ // the list is non-empty.
164
164
  function matchesEmailAllowList(profile, allowList) {
165
165
  // Never honor an email/domain match for an address the IdP explicitly reports as
166
166
  // unverified - otherwise an IdP that allows self-registration (or unverified email
@@ -171,7 +171,11 @@ function matchesEmailAllowList(profile, allowList) {
171
171
  return false;
172
172
  }
173
173
 
174
- let email = ((profile && (profile.email || profile.username)) || '').trim().toLowerCase();
174
+ // The email claim only. The username falls back to preferred_username, which on an
175
+ // IdP with self-registration is whatever the user typed, so a user named
176
+ // "admin@company.com" with no email claim matched an allow-list entry for it. No
177
+ // email claim is no match; groups can still authorize.
178
+ let email = (profile && typeof profile.email === 'string' ? profile.email : '').trim().toLowerCase();
175
179
  if (!email) {
176
180
  return false;
177
181
  }
@@ -2,9 +2,18 @@
2
2
 
3
3
  const crypto = require('crypto');
4
4
  const { Transform } = require('stream');
5
+ const { promisify } = require('util');
6
+ const { PBKDF2_ITERATIONS, PBKDF2_DIGEST } = require('./encrypt');
5
7
 
6
8
  const MAGIC = Buffer.from('EE01');
7
- const VERSION = 1;
9
+ // How the key is derived, by header version. Version 1 used scrypt, which an OpenSSL FIPS provider
10
+ // does not offer; everything written is version 2 (PBKDF2-HMAC-SHA256, with the parameters of the
11
+ // field encryption's wd02 scheme), and a version 1 file still decrypts
12
+ const VERSION = 2;
13
+ const KDF = {
14
+ 1: (password, salt, callback) => crypto.scrypt(password, salt, 32, callback),
15
+ 2: (password, salt, callback) => crypto.pbkdf2(password, salt, PBKDF2_ITERATIONS, 32, PBKDF2_DIGEST, callback)
16
+ };
8
17
  const CHUNK_SIZE = 64 * 1024;
9
18
  const IV_LENGTH = 12;
10
19
  const AUTH_TAG_LENGTH = 16;
@@ -12,15 +21,6 @@ const SALT_LENGTH = 16;
12
21
  const HEADER_SIZE = MAGIC.length + 4 + 4 + SALT_LENGTH;
13
22
  const MAX_CHUNK_SIZE = CHUNK_SIZE * 4;
14
23
 
15
- function deriveKeyAsync(password, salt) {
16
- return new Promise((resolve, reject) => {
17
- crypto.scrypt(password, salt, 32, (err, key) => {
18
- if (err) reject(err);
19
- else resolve(key);
20
- });
21
- });
22
- }
23
-
24
24
  class EncryptStream extends Transform {
25
25
  constructor({ key, salt }) {
26
26
  super();
@@ -115,9 +115,10 @@ class DecryptStream extends Transform {
115
115
  offset += MAGIC.length;
116
116
 
117
117
  const version = this.buffer.readUInt32LE(offset);
118
- if (version !== VERSION) {
118
+ if (!KDF[version]) {
119
119
  throw new Error(`Unsupported encryption version: ${version}`);
120
120
  }
121
+ this.version = version;
121
122
  offset += 4;
122
123
 
123
124
  this.chunkSize = this.buffer.readUInt32LE(offset);
@@ -197,7 +198,7 @@ class DecryptStream extends Transform {
197
198
  callback(err);
198
199
  return;
199
200
  }
200
- crypto.scrypt(this.secret, this.salt, 32, (err, key) => {
201
+ KDF[this.version](this.secret, this.salt, (err, key) => {
201
202
  if (err) {
202
203
  callback(err);
203
204
  return;
@@ -242,7 +243,7 @@ async function createEncryptStream(secret) {
242
243
  throw new Error('Encryption secret is required');
243
244
  }
244
245
  const salt = crypto.randomBytes(SALT_LENGTH);
245
- const key = await deriveKeyAsync(secret, salt);
246
+ const key = await promisify(KDF[VERSION])(secret, salt);
246
247
  return new EncryptStream({ key, salt });
247
248
  }
248
249
 
@@ -61,7 +61,9 @@ Full documentation: https://learn.emailengine.app/`
61
61
  bearerAuth: {
62
62
  type: 'http',
63
63
  scheme: 'bearer',
64
- bearerFormat: 'JWT',
64
+ // Access tokens are 64 hex characters with no internal structure. `JWT` told
65
+ // generated clients and API tools to parse and validate one, which no token passes.
66
+ bearerFormat: 'opaque',
65
67
  description: 'Enter your access token'
66
68
  }
67
69
  },
@@ -22,7 +22,7 @@ const settings = require('../settings');
22
22
  const { REDIS_PREFIX, BLOCK_TLS_RENEW, TLS_RETRY_AFTER_FAILURE, TLS_PREFLIGHT_TTL, TLS_PREFLIGHT_TIMEOUT } = require('../consts');
23
23
  const { emitChangeEvent, reloadTlsCertificates, httpAgent } = require('../tools');
24
24
  const { validateWebhookTarget } = require('../webhook-egress');
25
- const { hostnamesFrom, acmeEligibleHostnames, LISTENER_TLS_SETTINGS, listenerTlsFrom } = require('./store');
25
+ const { hostnamesFrom, acmeEligibleHostnames, LISTENER_TLS_SETTINGS, listenerTlsFrom, peekSelfSignedCertificate, selfSignedExpiring } = require('./store');
26
26
  const { apiTlsConfig } = require('./context');
27
27
 
28
28
  const STATUS_KEY = `${REDIS_PREFIX}tls:status`;
@@ -33,6 +33,42 @@ const PROBE_KEY = `${REDIS_PREFIX}tls:probe`;
33
33
  // stacking background tasks for the same name while an order is running.
34
34
  const inFlight = new Set();
35
35
 
36
+ // The self-signed certificate the reconciler last asked the listeners to replace. The listeners
37
+ // replace an expiring one whenever they refresh, but they only refresh on start and on a reload,
38
+ // and outside an ACME order nothing sent one: a listener up for a year served an expired
39
+ // certificate. One reload per expiring certificate: a listener that needs it replaces it (new
40
+ // fingerprint), and one that is not stored because nothing serves it is not asked about again.
41
+ let selfSignedReloadRequestedFor = null;
42
+
43
+ /**
44
+ * Sends the listeners a reload when the stored self-signed certificate is about to expire.
45
+ *
46
+ * @param {Object} opts `{ logger, call }`
47
+ * @returns {Promise<boolean>} Whether a reload was sent
48
+ */
49
+ async function refreshExpiringSelfSigned({ logger, call }) {
50
+ let material;
51
+ try {
52
+ material = await peekSelfSignedCertificate();
53
+ } catch (err) {
54
+ logger.error({ msg: 'Failed to read the self-signed TLS certificate', err });
55
+ return false;
56
+ }
57
+
58
+ if (!selfSignedExpiring(material) || selfSignedReloadRequestedFor === material.fingerprint) {
59
+ return false;
60
+ }
61
+
62
+ selfSignedReloadRequestedFor = material.fingerprint;
63
+ logger.info({
64
+ msg: 'The self-signed TLS certificate is about to expire, reloading the listeners',
65
+ fingerprint: material.fingerprint,
66
+ validTo: material.validTo
67
+ });
68
+ await reloadTlsCertificates(call, logger, { reason: 'self-signed-expiring' });
69
+ return true;
70
+ }
71
+
36
72
  /**
37
73
  * Reads the recorded provisioning state for every hostname.
38
74
  *
@@ -441,7 +477,7 @@ async function requestProvisioning(opts) {
441
477
  }
442
478
 
443
479
  if (scheduled.length) {
444
- reconcileCertificates({ certs, logger, call, hostnames: scheduled, force: true })
480
+ reconcileCertificates({ certs, logger, call, hostnames: scheduled, force: true, claimed: true })
445
481
  .catch(err => logger.error({ msg: 'Certificate provisioning failed', err }))
446
482
  .finally(() => {
447
483
  // Only the names this call added, so a second click does not release the first
@@ -465,6 +501,7 @@ async function requestProvisioning(opts) {
465
501
  * @param {Function} opts.call Worker call function, for the listener reload
466
502
  * @param {string[]} [opts.hostnames] Names to reconcile; defaults to the configured ones
467
503
  * @param {boolean} [opts.force] Order even when the recorded state says to wait
504
+ * @param {boolean} [opts.claimed] The caller has already put `hostnames` in flight
468
505
  * @returns {Promise<Object>} `{ results, changed }`
469
506
  */
470
507
  async function reconcileCertificates(opts) {
@@ -497,12 +534,40 @@ async function reconcileCertificates(opts) {
497
534
  await clearProvisioningStatus(hostname);
498
535
  }
499
536
  }
537
+
538
+ // Ahead of the mode check: the self-signed fallback is served in every mode
539
+ await refreshExpiringSelfSigned({ logger, call });
500
540
  }
501
541
 
502
542
  if (mode !== 'acme' || !hostnames.length) {
503
543
  return { results: [], changed: false, skipped: mode !== 'acme' ? mode : 'no-eligible-hostname' };
504
544
  }
505
545
 
546
+ // A timer pass leaves alone the names a button-triggered order is running for, and holds the
547
+ // ones it orders itself against the button: a status record of `queued` or `ordering` carries
548
+ // no `attempted`, so without this the timer saw such a name as never tried, started a second
549
+ // order behind the library's per-domain lock and wrote its lock timeout over the running one.
550
+ // requestProvisioning() has already claimed the names it passes in.
551
+ const claimed = [];
552
+ if (!opts.claimed) {
553
+ for (const hostname of hostnames) {
554
+ if (!inFlight.has(hostname)) {
555
+ inFlight.add(hostname);
556
+ claimed.push(hostname);
557
+ }
558
+ }
559
+ }
560
+
561
+ try {
562
+ return await reconcileHostnames({ certs, logger, call, force, wanted, status, hostnames: opts.claimed ? hostnames : claimed });
563
+ } finally {
564
+ for (const hostname of claimed) {
565
+ inFlight.delete(hostname);
566
+ }
567
+ }
568
+ }
569
+
570
+ async function reconcileHostnames({ certs, logger, call, force, wanted, status, hostnames }) {
506
571
  const results = [];
507
572
  let changed = false;
508
573
 
@@ -551,5 +616,6 @@ module.exports = {
551
616
  provisionHostname,
552
617
  listenersServeTls,
553
618
  needsProvisioning,
554
- reconcileCertificates
619
+ reconcileCertificates,
620
+ refreshExpiringSelfSigned
555
621
  };
package/lib/tls/store.js CHANGED
@@ -563,7 +563,19 @@ function selfSignedIsStale(record, hostnames) {
563
563
  return true;
564
564
  }
565
565
 
566
- return parsed.validTo.getTime() - Date.now() < SELF_SIGNED_RENEW_BEFORE;
566
+ return selfSignedExpiring(parsed);
567
+ }
568
+
569
+ /**
570
+ * Whether stored self-signed material is inside its replacement window. Expiry only: a change of
571
+ * names already reaches the listeners through the settings write that made it.
572
+ *
573
+ * @param {Object|false} material From peekSelfSignedCertificate()
574
+ * @returns {boolean}
575
+ */
576
+ function selfSignedExpiring(material) {
577
+ const validTo = material && material.validTo ? new Date(material.validTo).getTime() : NaN;
578
+ return Number.isFinite(validTo) && validTo - Date.now() < SELF_SIGNED_RENEW_BEFORE;
567
579
  }
568
580
 
569
581
  async function deleteSelfSignedCertificate() {
@@ -660,6 +672,7 @@ module.exports = {
660
672
  deleteManualCertificate,
661
673
  getSelfSignedCertificate,
662
674
  peekSelfSignedCertificate,
675
+ selfSignedExpiring,
663
676
  deleteSelfSignedCertificate,
664
677
  getAcmeCertificate,
665
678
  LISTENER_TLS_SETTINGS,
@@ -24,6 +24,7 @@ const msgpack = require('./msgpack');
24
24
  const settings = require('./settings');
25
25
  const { REDIS_PREFIX, MAX_ACCOUNT_ID_LENGTH } = require('./consts');
26
26
  const { extractMultiError } = require('./redis-operations');
27
+ const { readEnvValue } = require('./read-env-value');
27
28
 
28
29
  // Both overrides below are whole counts that have to be at least 1, and anything else falls back to
29
30
  // the default rather than being clamped towards it - "0" is not a request for the smallest possible
@@ -42,12 +43,12 @@ function positiveInt(value, fallback) {
42
43
  // per token, so a thousand active tokens cost about 170MB - entries carrying a maximum-length
43
44
  // account run some three times that. Raise it against those figures, and against the fact that a log
44
45
  // of who read whose mail carries the sensitivity of the mail itself.
45
- const LOG_ENTRIES = positiveInt(process.env.EENGINE_TOKEN_LOG_ENTRIES, 1000);
46
+ const LOG_ENTRIES = positiveInt(readEnvValue('EENGINE_TOKEN_LOG_ENTRIES'), 1000);
46
47
 
47
48
  // How long a token's log survives its last use, in seconds. Refreshed on every write, so this bounds
48
49
  // how long a log outlives the credential's activity rather than how long each entry lives - which is
49
50
  // the useful bound, because a token nobody has used is a log nobody needs.
50
- const LOG_AGE = positiveInt(process.env.EENGINE_TOKEN_LOG_AGE, 7 * 24 * 3600);
51
+ const LOG_AGE = positiveInt(readEnvValue('EENGINE_TOKEN_LOG_AGE'), 7 * 24 * 3600);
51
52
 
52
53
  // The largest page the log route will serve. Deliberately not the retention cap: one bounds a single
53
54
  // response, the other bounds stored data, and while they were the same constant raising retention