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
@@ -15,8 +15,9 @@ const SMTP_POOL_MAX_IDLE = 10 * 60 * 1000;
15
15
  // Cleanup interval for idle SMTP pools (2 minutes)
16
16
  const SMTP_POOL_CLEANUP_INTERVAL = 2 * 60 * 1000;
17
17
 
18
- // Keys that affect SMTP connection identity
19
- const CONNECTION_IDENTITY_KEYS = ['name', 'localAddress', 'auth', 'host', 'port', 'secure', 'transactionLog', 'proxy'];
18
+ // Keys that affect SMTP connection identity. The TLS options are part of it: two accounts on the
19
+ // same server that differ only in certificate checking or STARTTLS policy must not share a pool.
20
+ const CONNECTION_IDENTITY_KEYS = ['name', 'localAddress', 'auth', 'host', 'port', 'secure', 'transactionLog', 'proxy', 'tls', 'requireTLS', 'ignoreTLS'];
20
21
 
21
22
  /**
22
23
  * Generates a unique pool key from SMTP settings
package/lib/encrypt.js CHANGED
@@ -1,13 +1,55 @@
1
1
  'use strict';
2
2
 
3
+ // Encryption at rest for stored credentials (account passwords and tokens, the credential-bearing
4
+ // settings and account fields, webhook route targets, TLS private keys). A value is stored as
5
+ //
6
+ // $wd01$aes-256-gcm$<authTag>$<iv>$<salt>$<ciphertext> (every part hex)
7
+ //
8
+ // with the AES-256 key derived from the instance secret and the salt. Two schemes exist, told
9
+ // apart by the first part: wd01 derives the key with scrypt(secret, salt, 32) and wd02 with
10
+ // PBKDF2-HMAC-SHA256 over 600000 iterations (a count fixed by the scheme id, never stored, so
11
+ // changing it means a new scheme). Everything written is wd02: scrypt is not among the primitives
12
+ // an OpenSSL FIPS provider offers, PBKDF2 is the password-based KDF it approves of, and a host in
13
+ // FIPS mode could not start otherwise. A wd01 value written by an earlier release still decrypts,
14
+ // and any rewrite of it (a credential update, a settings save, `emailengine encrypt`) moves it to
15
+ // wd02. Nothing rewrites on read, so an instance about to be moved to a FIPS host runs
16
+ // `emailengine encrypt` first: once there, a wd01 value is unreadable. Derivation is the
17
+ // expensive part on purpose (it is what makes an offline brute force of the secret slow), so the
18
+ // derived key is cached per (scheme, secret, salt) in an LRU of LRU_CACHE_MAX entries.
19
+ //
20
+ // The salt is per PROCESS, not per value. Every value this process writes carries the same random
21
+ // salt and is therefore encrypted under one derived key, one cache entry, so a save or a hot-path
22
+ // decrypt of a recently written value never pays for a derivation after the first. Values used to
23
+ // get a salt each, which made the cache useless past LRU_CACHE_MAX stored values: the webhooks
24
+ // worker decrypts four fields per delivery, and past a few hundred accounts every delivery ran a
25
+ // cold scrypt (tens of milliseconds with the event loop blocked). Values written before this
26
+ // change keep their own salt and still decrypt through the same cache.
27
+ //
28
+ // Sharing a salt across values is safe because the salt protects nothing on its own: the KDF only
29
+ // stands between an attacker and the secret, and every value is encrypted under keys derived from
30
+ // that one secret, so a salt per value adds nothing against a brute force of it. What must never
31
+ // repeat under one key is the AES-GCM IV, and that stays random per value: 96 random bits collide
32
+ // with negligible probability for far more values than an instance will ever hold. The salt is
33
+ // random rather than derived from the secret for two reasons: a fast derivation (an HMAC of the
34
+ // secret, say) would let an attacker holding the ciphertexts test a candidate secret at the cost of
35
+ // one HMAC instead of one scrypt, and a slow one keyed on a fixed label would make the salt a
36
+ // deterministic function of the secret, so a table computed once could be checked against every
37
+ // instance. A random salt reveals nothing and costs the attacker the same scrypt per guess as before.
38
+
3
39
  const crypto = require('crypto');
4
40
  const assert = require('assert');
5
41
 
6
42
  const WD_ENCRYPTION_SCHEME_KEY_1 = 'wd01';
43
+ const WD_ENCRYPTION_SCHEME_KEY_2 = 'wd02';
7
44
  const WD_CIPHER_1 = 'aes-256-gcm';
8
45
 
46
+ // The PBKDF2 parameters of wd02, shared with the export file encryption (lib/stream-encrypt.js).
47
+ // The iteration count follows the OWASP figure for SHA-256
48
+ const PBKDF2_ITERATIONS = 600000;
49
+ const PBKDF2_DIGEST = 'sha256';
50
+
9
51
  // defaults
10
- const WD_ENCRYPTION_SCHEME = WD_ENCRYPTION_SCHEME_KEY_1;
52
+ const WD_ENCRYPTION_SCHEME = WD_ENCRYPTION_SCHEME_KEY_2;
11
53
  const WD_CIPHER = WD_CIPHER_1;
12
54
 
13
55
  // Store cached password keys in a Weak Map to prevent accidental leakage
@@ -17,9 +59,24 @@ const CACHED_SALT_OBJ = new Map();
17
59
  // Max items to keep in the LRU cache
18
60
  const LRU_CACHE_MAX = 1500;
19
61
 
20
- // Simple LRU cache for storing secrets in a WeakMap
21
- function saltCache(password, salt, key) {
22
- const cacheKeyStr = crypto.createHmac('sha256', password).update(salt).digest('hex');
62
+ const SALT_LENGTH = 16;
63
+ const IV_LENGTH = 12;
64
+
65
+ // The salt every value written by this process carries, see the note at the top. Generated on the
66
+ // first write rather than at load so a process that only reads never draws one.
67
+ let processSalt = null;
68
+
69
+ function getProcessSalt() {
70
+ if (!processSalt) {
71
+ processSalt = crypto.randomBytes(SALT_LENGTH);
72
+ }
73
+ return processSalt;
74
+ }
75
+
76
+ // Simple LRU cache for storing secrets in a WeakMap. The scheme is part of the cache key: a
77
+ // wd01 and a wd02 value sharing a salt derive different keys from the same secret
78
+ function saltCache(scheme, password, salt, key) {
79
+ const cacheKeyStr = crypto.createHmac('sha256', password).update(scheme).update(salt).digest('hex');
23
80
 
24
81
  // Get path
25
82
  if (!key) {
@@ -38,8 +95,12 @@ function saltCache(password, salt, key) {
38
95
  return existing;
39
96
  }
40
97
 
41
- // Set path: we know we’re storing a new key
42
- let cacheKeyObj = CACHED_SALT_OBJ.get(cacheKeyStr) || salt;
98
+ // Set path: we know we're storing a new key. The WeakMap key is an object of this entry's
99
+ // own, never the caller's salt buffer: every value this process writes shares one salt
100
+ // buffer, so keying on it would let a key derived for one secret overwrite the key derived
101
+ // for another under the same salt, and a value would then be encrypted or decrypted with
102
+ // the wrong secret's key.
103
+ let cacheKeyObj = CACHED_SALT_OBJ.get(cacheKeyStr) || Buffer.from(salt);
43
104
  CACHED_KEYS_WM.set(cacheKeyObj, key);
44
105
 
45
106
  // Bump/inject into recency Map
@@ -93,13 +154,24 @@ function parseEncryptedData(encryptedData) {
93
154
  };
94
155
  }
95
156
 
96
- function getKeyFromPassword(password, salt) {
97
- let cachedKey = saltCache(password, salt);
157
+ function deriveKey(scheme, password, salt) {
158
+ switch (scheme) {
159
+ case WD_ENCRYPTION_SCHEME_KEY_1:
160
+ return crypto.scryptSync(password, salt, 32);
161
+ case WD_ENCRYPTION_SCHEME_KEY_2:
162
+ return crypto.pbkdf2Sync(password, salt, PBKDF2_ITERATIONS, 32, PBKDF2_DIGEST);
163
+ default:
164
+ throw new Error(`Unknown encryption scheme ${scheme}`);
165
+ }
166
+ }
167
+
168
+ function getKeyFromPassword(scheme, password, salt) {
169
+ let cachedKey = saltCache(scheme, password, salt);
98
170
  if (cachedKey) {
99
171
  return cachedKey;
100
172
  }
101
- const key = crypto.scryptSync(password, salt, 32);
102
- saltCache(password, salt, key); // update cache
173
+ const key = deriveKey(scheme, password, salt);
174
+ saltCache(scheme, password, salt, key); // update cache
103
175
  return key;
104
176
  }
105
177
 
@@ -117,14 +189,15 @@ function decrypt(encryptedData, secret) {
117
189
  return raw;
118
190
 
119
191
  case WD_ENCRYPTION_SCHEME_KEY_1:
192
+ case WD_ENCRYPTION_SCHEME_KEY_2:
120
193
  try {
121
194
  assert.strictEqual(decryptData.authTag.length, 16, 'Invalid auth tag length');
122
- assert.strictEqual(decryptData.iv.length, 12, 'Invalid iv length');
123
- assert.strictEqual(decryptData.salt.length, 16, 'Invalid salt length');
195
+ assert.strictEqual(decryptData.iv.length, IV_LENGTH, 'Invalid iv length');
196
+ assert.strictEqual(decryptData.salt.length, SALT_LENGTH, 'Invalid salt length');
124
197
  assert.strictEqual(decryptData.cipher, WD_CIPHER_1, 'Unsupported cipher');
125
198
 
126
- // convert password to 32B key
127
- const key = getKeyFromPassword(secret, decryptData.salt);
199
+ // convert password to 32B key, the way the value's scheme says
200
+ const key = getKeyFromPassword(decryptData.format, secret, decryptData.salt);
128
201
 
129
202
  const decipher = crypto.createDecipheriv(decryptData.cipher, key, decryptData.iv, {
130
203
  authTagLength: decryptData.authTag.length
@@ -152,14 +225,17 @@ function encrypt(cleartext, secret) {
152
225
  return cleartext;
153
226
  }
154
227
 
155
- const iv = crypto.randomBytes(12);
156
- const salt = crypto.randomBytes(16);
157
-
158
- const key = getKeyFromPassword(secret, salt);
228
+ // Random per value: GCM is only secure while no IV repeats under a key, and every value this
229
+ // process writes shares one key
230
+ const iv = crypto.randomBytes(IV_LENGTH);
231
+ const salt = getProcessSalt();
159
232
 
160
233
  const format = WD_ENCRYPTION_SCHEME;
161
234
  const algo = WD_CIPHER;
162
235
 
236
+ // Cached after the first write of this process
237
+ const key = getKeyFromPassword(format, secret, salt);
238
+
163
239
  const cipher = crypto.createCipheriv(algo, key, iv, { authTagLength: 16 });
164
240
  const encryptedText = Buffer.concat([cipher.update(cleartext), cipher.final()]);
165
241
 
@@ -168,4 +244,93 @@ function encrypt(cleartext, secret) {
168
244
  return ['', format, algo].concat([authTag, iv, salt, encryptedText].map(buf => buf.toString('hex'))).join('$');
169
245
  }
170
246
 
171
- module.exports = { encrypt, decrypt, parseEncryptedData };
247
+ /**
248
+ * Encrypts a stored field for writing. Nothing to do without a secret, and an empty value is left
249
+ * as it is: several fields use the empty string as a "cleared" marker.
250
+ *
251
+ * @param {String} value - Cleartext
252
+ * @param {String} secret - Instance secret
253
+ * @returns {String} The value as it is to be stored
254
+ */
255
+ function encryptField(value, secret) {
256
+ if (!secret || !value) {
257
+ return value;
258
+ }
259
+ return encrypt(value, secret);
260
+ }
261
+
262
+ /**
263
+ * Decrypts a stored field, or treats it as unset. A value that does not decrypt with this secret
264
+ * (the secret was rotated without `emailengine encrypt`, the value is corrupt) is reported through
265
+ * `onError` and read as undefined, so the field is missing rather than the whole record failing.
266
+ * Cleartext (a value stored before its field was encrypted) passes through, as decrypt() does.
267
+ *
268
+ * @param {String} value - The stored value
269
+ * @param {String} secret - Instance secret
270
+ * @param {Function} [onError] - Called with the error when the value does not decrypt
271
+ * @returns {String|undefined} The cleartext, or undefined when it could not be read
272
+ */
273
+ function decryptField(value, secret, onError) {
274
+ if (!secret || !value) {
275
+ return value;
276
+ }
277
+ try {
278
+ return decrypt(value, secret);
279
+ } catch (err) {
280
+ if (typeof onError === 'function') {
281
+ onError(err);
282
+ }
283
+ return undefined;
284
+ }
285
+ }
286
+
287
+ /**
288
+ * Tells whether a stored value is encrypted under the scheme encrypt() writes today. A value under
289
+ * an older scheme still decrypts, and is what `emailengine encrypt` rewrites
290
+ *
291
+ * @param {String} value - The stored value
292
+ * @returns {Boolean}
293
+ */
294
+ function isCurrentScheme(value) {
295
+ return parseEncryptedData(value).format === WD_ENCRYPTION_SCHEME;
296
+ }
297
+
298
+ /**
299
+ * The value `emailengine encrypt` stores for one it found: unchanged when it is already under the
300
+ * current secret and scheme, otherwise decrypted with whichever of the secrets reads it and written
301
+ * again with the current secret, or as cleartext when there is none. Throws when no secret reads
302
+ * it, so nothing is overwritten with a guess
303
+ *
304
+ * @param {String} value - The stored value
305
+ * @param {String[]} decryptSecrets - Secrets the value may have been written with
306
+ * @param {String} [encryptSecret] - The secret to write with; nothing removes the encryption
307
+ * @returns {String} The value to store
308
+ */
309
+ function reencrypt(value, decryptSecrets, encryptSecret) {
310
+ if (parseEncryptedData(value).format === 'cleartext') {
311
+ return encryptSecret ? encrypt(value, encryptSecret) : value;
312
+ }
313
+
314
+ let lastErr;
315
+ // the current secret first: a value already under it is the common case
316
+ for (const secret of new Set([encryptSecret, ...decryptSecrets].filter(Boolean))) {
317
+ let decrypted;
318
+ try {
319
+ decrypted = decrypt(value, secret);
320
+ } catch (err) {
321
+ lastErr = err;
322
+ continue;
323
+ }
324
+ if (parseEncryptedData(decrypted).format !== 'cleartext') {
325
+ // a scheme decrypt() does not know comes back as it was
326
+ break;
327
+ }
328
+ if (secret === encryptSecret && isCurrentScheme(value)) {
329
+ return value;
330
+ }
331
+ return encryptSecret ? encrypt(decrypted, encryptSecret) : decrypted;
332
+ }
333
+ throw lastErr || new Error('Could not decrypt encrypted value');
334
+ }
335
+
336
+ module.exports = { encrypt, decrypt, encryptField, decryptField, parseEncryptedData, isCurrentScheme, reencrypt, PBKDF2_ITERATIONS, PBKDF2_DIGEST };
@@ -27,7 +27,11 @@ const ENUM_DESCRIPTIONS = {
27
27
  disconnected: 'The connection dropped and EmailEngine is retrying with backoff',
28
28
  paused: 'Syncing was paused through the API. No connection is maintained',
29
29
  authenticationError: 'The credentials were rejected. Requires re-authentication before syncing resumes',
30
- connectError: 'The server could not be reached or the TLS handshake failed. Retried with backoff',
30
+ // No note here about account operations answering 503: every state outside connected,
31
+ // connecting and syncing does that, so saying it under one of them reads as if the others
32
+ // did not
33
+ connectError:
34
+ 'The server could not be reached, the TLS handshake failed, or - for an MS Graph account - its change subscription could not be created or renewed, which leaves the account with no way to learn about new mail. Retried with backoff',
31
35
  unset: 'The account is not syncing: either no IMAP or OAuth2 configuration is set, or syncing was switched off - by the operator, or automatically after repeated authentication failures'
32
36
  },
33
37
 
@@ -137,8 +141,7 @@ const ENUM_DESCRIPTIONS = {
137
141
 
138
142
  queueId: {
139
143
  notify: 'Webhook delivery queue',
140
- submit: 'Outbound email delivery queue',
141
- documents: 'Document Store indexing queue (deprecated feature)'
144
+ submit: 'Outbound email delivery queue'
142
145
  },
143
146
 
144
147
  pubsubState: {
package/lib/export.js CHANGED
@@ -4,12 +4,15 @@ const os = require('os');
4
4
  const crypto = require('crypto');
5
5
  const fs = require('fs');
6
6
  const pathlib = require('path');
7
+ const zlib = require('zlib');
8
+ const { pipeline } = require('stream');
7
9
  const msgpack = require('./msgpack');
8
10
  const { redis, exportQueue } = require('./db');
9
11
  const settings = require('./settings');
10
12
  const logger = require('./logger');
11
13
  const getSecret = require('./get-secret');
12
14
  const { escapeRedisGlob } = require('./tools');
15
+ const { readEnvValue } = require('./read-env-value');
13
16
  const { ImapFlowErrorCode } = require('imapflow');
14
17
 
15
18
  const {
@@ -94,25 +97,111 @@ const EXPORT_FILE_EXTENSION = '.ndjson.gz';
94
97
  const EXPORT_FILE_EXTENSION_ENCRYPTED = '.ndjson.gz.enc';
95
98
 
96
99
  /**
97
- * Tells whether a stored file path is the export's own file.
100
+ * The file of an export, from its stored record.
98
101
  *
99
- * `filePath` is read back from Redis by the download and delete paths. Nothing but this module
100
- * writes it, but a path trusted only because it was stored is exactly the field a later bug, or
101
- * write access to Redis, would use to make the download route serve or the delete route unlink
102
- * an arbitrary file. The basename is checked rather than the directory, because the export
103
- * directory setting can change between an export and its download, and an older export still
104
- * lives where it was written.
102
+ * The file name is always derived from the export id, never taken from the record. `filePath` is
103
+ * read back from Redis by the download and delete paths, and nothing but this module writes it,
104
+ * but a path trusted only because it was stored is exactly the field a later bug, or write access
105
+ * to Redis, would use to make the download route serve or the delete route unlink an arbitrary
106
+ * file. Only the directory comes from the record, because the export directory setting can change
107
+ * between an export and its download, and an older export still lives where it was written.
105
108
  *
106
109
  * @param {string} exportId - Export id the record belongs to
107
- * @param {string} filePath - Stored path
108
- * @returns {boolean} true when the path names the export's own file
110
+ * @param {Object} data - The export record as stored (`filePath`, `isEncrypted`)
111
+ * @returns {string|null} The path of the export's own file, or null for a record that names none
109
112
  */
110
- function isOwnExportFile(exportId, filePath) {
111
- if (!exportId || typeof filePath !== 'string') {
112
- return false;
113
+ function exportFilePath(exportId, data) {
114
+ if (!exportId || !data || typeof data.filePath !== 'string' || !data.filePath) {
115
+ return null;
113
116
  }
114
- const base = pathlib.basename(filePath);
115
- return [EXPORT_FILE_EXTENSION, EXPORT_FILE_EXTENSION_ENCRYPTED].some(ext => base === `${exportId}${ext}`);
117
+ const extension = data.isEncrypted === '1' ? EXPORT_FILE_EXTENSION_ENCRYPTED : EXPORT_FILE_EXTENSION;
118
+ return pathlib.join(pathlib.dirname(data.filePath), `${exportId}${extension}`);
119
+ }
120
+
121
+ /**
122
+ * Opens the output chain of an export: gzip, optionally encrypt, then the file.
123
+ *
124
+ * The encryption key is derived (PBKDF2) BEFORE the file is opened and the chain is joined by
125
+ * pipeline() in the same tick the file stream is created, so an open failure (export directory
126
+ * removed or unwritable, EMFILE) always has a listener. The file used to be opened first and left
127
+ * without one while the key was derived, which crashed the export worker thread, and BullMQ re-ran
128
+ * the job into the same crash.
129
+ *
130
+ * @param {string} filePath - Output file
131
+ * @param {string|null} secret - Encryption secret, null for an unencrypted export
132
+ * @returns {Promise<Object>} `input` (write NDJSON here), `output` (the file stream), `error()`
133
+ * (the first stream error, if any) and `destroy()` (closes every stream, for an early exit)
134
+ */
135
+ async function openExportOutput(filePath, secret) {
136
+ let encryptStream = null;
137
+ if (secret) {
138
+ const { createEncryptStream } = require('./stream-encrypt');
139
+ encryptStream = await createEncryptStream(secret);
140
+ }
141
+
142
+ const gzipStream = zlib.createGzip();
143
+ const fileStream = fs.createWriteStream(filePath, { mode: 0o600 });
144
+ const streams = [gzipStream, encryptStream, fileStream].filter(Boolean);
145
+
146
+ let streamError = null;
147
+ pipeline(...streams, err => {
148
+ if (err && !streamError) {
149
+ streamError = err;
150
+ }
151
+ });
152
+
153
+ return {
154
+ input: gzipStream,
155
+ output: fileStream,
156
+ error: () => streamError,
157
+ destroy() {
158
+ for (const stream of streams) {
159
+ stream.destroy();
160
+ }
161
+ }
162
+ };
163
+ }
164
+
165
+ /**
166
+ * Opens the download chain of a completed export: the file, then decryption when it is encrypted.
167
+ *
168
+ * pipeline() rather than pipe(): hapi destroys the stream it was handed when the client goes
169
+ * away, and pipe() never passed that upstream, so every aborted download kept the file descriptor
170
+ * open. It also carries a read error down to the response, which pipe() did not, leaving the
171
+ * download hanging until the socket timed out.
172
+ *
173
+ * @param {Object} fileInfo - From Export.getFile()
174
+ * @param {Function} onError - Called with a read or decryption error; the client going away is not one
175
+ * @returns {Promise<stream.Readable>} The stream to respond with
176
+ */
177
+ async function openExportReadStream(fileInfo, onError) {
178
+ const fileReadStream = fs.createReadStream(fileInfo.filePath);
179
+
180
+ if (!fileInfo.isEncrypted) {
181
+ fileReadStream.on('error', err => onError(err));
182
+ return fileReadStream;
183
+ }
184
+
185
+ const secret = await getSecret();
186
+ if (!secret) {
187
+ fileReadStream.destroy();
188
+ throw createError('Encryption secret not available for decryption', 'EncryptionSecretMissing', 503);
189
+ }
190
+
191
+ let decryptStream;
192
+ try {
193
+ const { createDecryptStream } = require('./stream-encrypt');
194
+ decryptStream = await createDecryptStream(secret);
195
+ } catch (err) {
196
+ fileReadStream.destroy();
197
+ throw err;
198
+ }
199
+
200
+ return pipeline(fileReadStream, decryptStream, err => {
201
+ if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') {
202
+ onError(err);
203
+ }
204
+ });
116
205
  }
117
206
 
118
207
  function generateExportId() {
@@ -252,13 +341,18 @@ function getExportQueueKey(account, exportId) {
252
341
  return `${REDIS_PREFIX}exq:${account}:${exportId}`;
253
342
  }
254
343
 
344
+ // The directory exports are written to and served from. Deliberately NOT a setting: the value is a
345
+ // filesystem path this process writes files into, so a settings editor that could move it would be an
346
+ // arbitrary file write, and an operator picks a deployment path through the environment anyway. This
347
+ // used to consult an `exportPath` setting first, which no schema declares and so nothing could ever
348
+ // have written.
255
349
  async function getExportPath() {
256
- return (await settings.get('exportPath')) || process.env.EENGINE_EXPORT_PATH || os.tmpdir();
350
+ return readEnvValue('EENGINE_EXPORT_PATH') || os.tmpdir();
257
351
  }
258
352
 
259
353
  async function getExportMaxAge() {
260
354
  const settingsMaxAge = await settings.get('exportMaxAge');
261
- const envMaxAge = process.env.EENGINE_EXPORT_MAX_AGE;
355
+ const envMaxAge = readEnvValue('EENGINE_EXPORT_MAX_AGE');
262
356
 
263
357
  if (settingsMaxAge && !isNaN(settingsMaxAge)) return Number(settingsMaxAge);
264
358
  if (envMaxAge && !isNaN(envMaxAge)) return Number(envMaxAge);
@@ -411,7 +505,7 @@ class Export {
411
505
  const page = Number(options.page) || 0;
412
506
  const pageSize = Number(options.pageSize) || 20;
413
507
 
414
- const pattern = `${REDIS_PREFIX}exp:${escapeRedisGlob(account)}:${EXPORT_ID_PREFIX}*`;
508
+ const pattern = `${escapeRedisGlob(REDIS_PREFIX)}exp:${escapeRedisGlob(account)}:${EXPORT_ID_PREFIX}*`;
415
509
  const keys = await scanKeys(pattern);
416
510
 
417
511
  const exports = [];
@@ -466,17 +560,27 @@ class Export {
466
560
  if (!isActive) {
467
561
  await redis.multi().del(exportKey).del(queueKey).srem(ACTIVE_EXPORTS_KEY, buildActiveEntry(account, exportId)).exec();
468
562
 
469
- if (isOwnExportFile(exportId, data.filePath)) {
470
- await fs.promises.unlink(data.filePath).catch(() => {});
471
- } else if (data.filePath) {
472
- logger.error({ msg: 'Refusing to delete a file that is not the export file', account, exportId, filePath: data.filePath });
473
- }
563
+ await Export.removeFile(exportId, data);
474
564
  }
475
565
 
476
566
  logger.info({ msg: 'Export deleted', account, exportId });
477
567
  return true;
478
568
  }
479
569
 
570
+ /**
571
+ * Unlinks the export's own file, if its record names one. The path is derived from the id,
572
+ * never taken as stored (see exportFilePath()); a file that is already gone is not an error.
573
+ *
574
+ * @param {string} exportId - Export id
575
+ * @param {Object} data - The export record as stored
576
+ */
577
+ static async removeFile(exportId, data) {
578
+ const filePath = exportFilePath(exportId, data);
579
+ if (filePath) {
580
+ await fs.promises.unlink(filePath).catch(() => {});
581
+ }
582
+ }
583
+
480
584
  static async update(account, exportId, updates) {
481
585
  if (Object.keys(updates).length > 0) {
482
586
  await redis.hmset(getExportKey(account, exportId), updates);
@@ -535,12 +639,11 @@ class Export {
535
639
  })
536
640
  .toString('base64url');
537
641
 
538
- const ttl = await redis.ttl(exportKey);
539
- const multi = redis.multi().zadd(queueKey, score, value).hincrby(exportKey, 'messagesQueued', 1);
540
- if (ttl > 0) {
541
- multi.expire(queueKey, ttl);
542
- }
543
- await multi.exec();
642
+ // ZADD, the count of a new member and the queue's expiry (copied from the record's) in one
643
+ // round trip; this runs once per message of an export. A retried folder queues the
644
+ // messages its failed attempt already queued, and only a new member counts, see the script.
645
+ const added = await redis.eeExportQueueAdd(exportKey, queueKey, score, value, 'messagesQueued');
646
+ return !!added;
544
647
  }
545
648
 
546
649
  static async getNextBatch(account, exportId, limit) {
@@ -651,9 +754,7 @@ class Export {
651
754
 
652
755
  await Export.fail(account, exportId, 'Export interrupted by application restart');
653
756
 
654
- if (data.filePath) {
655
- await fs.promises.unlink(data.filePath).catch(() => {});
656
- }
757
+ await Export.removeFile(exportId, data);
657
758
  }
658
759
  } catch (err) {
659
760
  logger.error({ msg: 'Failed to mark interrupted export as failed', entry, err });
@@ -672,7 +773,7 @@ class Export {
672
773
  if (!file.startsWith(EXPORT_ID_PREFIX)) continue;
673
774
 
674
775
  const exportId = file.split('.')[0];
675
- const pattern = `${REDIS_PREFIX}exp:*:${escapeRedisGlob(exportId)}`;
776
+ const pattern = `${escapeRedisGlob(REDIS_PREFIX)}exp:*:${escapeRedisGlob(exportId)}`;
676
777
  const keys = await scanKeys(pattern);
677
778
 
678
779
  if (keys.length === 0) {
@@ -703,17 +804,14 @@ class Export {
703
804
  throw createError('Export not completed', 'ExportNotReady', 400);
704
805
  }
705
806
 
706
- if (!data.filePath) {
707
- throw createError('Export file not found', 'FileNotFound', 404);
708
- }
709
-
710
- if (!isOwnExportFile(exportId, data.filePath)) {
711
- logger.error({ msg: 'Refusing to serve a file that is not the export file', account, exportId, filePath: data.filePath });
807
+ // The export's own file, whatever the record says (see exportFilePath())
808
+ const filePath = exportFilePath(exportId, data);
809
+ if (!filePath) {
712
810
  throw createError('Export file not found', 'FileNotFound', 404);
713
811
  }
714
812
 
715
813
  try {
716
- await fs.promises.access(data.filePath, fs.constants.R_OK);
814
+ await fs.promises.access(filePath, fs.constants.R_OK);
717
815
  } catch {
718
816
  throw createError('Export file not found', 'FileNotFound', 404);
719
817
  }
@@ -721,7 +819,7 @@ class Export {
721
819
  const isEncrypted = data.isEncrypted === '1';
722
820
 
723
821
  return {
724
- filePath: data.filePath,
822
+ filePath,
725
823
  filename: `${exportId}.ndjson.gz`,
726
824
  isEncrypted
727
825
  };
@@ -731,7 +829,9 @@ class Export {
731
829
  module.exports = {
732
830
  Export,
733
831
  generateExportId,
734
- isOwnExportFile,
832
+ exportFilePath,
833
+ openExportOutput,
834
+ openExportReadStream,
735
835
  calculateScore,
736
836
  getExportKey,
737
837
  getExportQueueKey,
package/lib/gateway.js CHANGED
@@ -14,8 +14,6 @@ class Gateway {
14
14
  this.redis = options.redis;
15
15
  this.gateway = options.gateway || false;
16
16
 
17
- this.documentsQueue = options.documentsQueue || false;
18
-
19
17
  this.secret = options.secret;
20
18
 
21
19
  this.logger = options.logger || logger;
@@ -25,10 +23,20 @@ class Gateway {
25
23
  return `${REDIS_PREFIX}gateway:${gateway || this.gateway}`;
26
24
  }
27
25
 
28
- unserialize(data) {
26
+ /**
27
+ * @param {Object} data - The stored hash, as Buffers
28
+ * @param {Object} [opts]
29
+ * @param {boolean} [opts.skipPass] - Leave the password out instead of decrypting it. The
30
+ * listing never outputs it, and one value that no longer decrypts (a rotated secret) used to
31
+ * fail the whole listing with a 500
32
+ */
33
+ unserialize(data, opts) {
29
34
  let obj = {};
30
35
  let value;
31
36
  for (let key of Object.keys(data)) {
37
+ if (key === 'pass' && opts && opts.skipPass) {
38
+ continue;
39
+ }
32
40
  switch (key) {
33
41
  case 'gateway':
34
42
  value = data[key].toString();
@@ -116,7 +124,7 @@ class Gateway {
116
124
  throw entry[0];
117
125
  }
118
126
  if (entry[1]) {
119
- gatewayList.push(this.unserialize(entry[1]));
127
+ gatewayList.push(this.unserialize(entry[1], { skipPass: true }));
120
128
  }
121
129
  }
122
130
  }
@@ -156,8 +164,19 @@ class Gateway {
156
164
  let result = await this.redis.hgetallBuffer(this.getGatewayKey());
157
165
 
158
166
  if (!result || !result.gateway) {
159
- let message = 'Gateway record was not found for requested ID';
160
- let error = Boom.boomify(new Error(message), { statusCode: 404 });
167
+ // Named, so a delivery queued for a gateway that no longer exists fails for good
168
+ // instead of retrying (lib/delivery-error.js) - and never falls through to the
169
+ // account's own SMTP server, which nothing asked for
170
+ let error = Boom.boomify(new Error(`Gateway "${this.gateway}" was not found`), { statusCode: 404 });
171
+ error.code = 'GatewayNotFound';
172
+ // Boom serializes output.payload and not the error's own properties, so the code has to be
173
+ // written there as well or an in-process caller (GET /v1/gateway/{gateway}, the delivery
174
+ // test) answers a 404 without the `code` field every other not-found answer carries.
175
+ // handleError() passes a Boom error through untouched (lib/api-routes/route-helpers.js)
176
+ error.output.payload.code = error.code;
177
+ // Boom keeps the status in output.statusCode, which the worker RPC hop does not carry
178
+ // (lib/worker-rpc-error.js), so the submit worker and the API caller get it here too
179
+ error.statusCode = 404;
161
180
  throw error;
162
181
  }
163
182