emailengine-app 2.81.1 → 2.82.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 (208) hide show
  1. package/.ncurc.js +12 -6
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +52 -0
  4. package/Dockerfile +4 -2
  5. package/bin/emailengine.js +28 -18
  6. package/config/default.toml +0 -5
  7. package/config/test.toml +0 -5
  8. package/data/google-crawlers.json +1 -1
  9. package/encrypt.js +70 -42
  10. package/getswagger.sh +0 -4
  11. package/lib/account/account-state.js +2 -110
  12. package/lib/account/bounce-store-sweep.js +63 -0
  13. package/lib/account/expected-identity.js +1 -1
  14. package/lib/account-assignment.js +207 -0
  15. package/lib/account.js +374 -878
  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-routes.js +18 -29
  19. package/lib/api-routes/blocklist-routes.js +2 -2
  20. package/lib/api-routes/bull-board-routes.js +1 -6
  21. package/lib/api-routes/export-routes.js +2 -22
  22. package/lib/api-routes/gateway-routes.js +5 -14
  23. package/lib/api-routes/index.js +1 -13
  24. package/lib/api-routes/mailbox-routes.js +2 -7
  25. package/lib/api-routes/mcp-oauth-routes.js +2 -1
  26. package/lib/api-routes/mcp-routes.js +7 -7
  27. package/lib/api-routes/message-routes.js +44 -236
  28. package/lib/api-routes/mint-bounds.js +110 -0
  29. package/lib/api-routes/oauth2-app-routes.js +23 -32
  30. package/lib/api-routes/operation-impact.js +1 -1
  31. package/lib/api-routes/outbox-routes.js +2 -2
  32. package/lib/api-routes/permission-map.js +1 -7
  33. package/lib/api-routes/route-helpers.js +11 -5
  34. package/lib/api-routes/settings-routes.js +19 -19
  35. package/lib/api-routes/stats-routes.js +1 -1
  36. package/lib/api-routes/submit-routes.js +17 -18
  37. package/lib/api-routes/template-routes.js +4 -9
  38. package/lib/api-routes/token-routes.js +27 -5
  39. package/lib/api-token-scheme.js +71 -0
  40. package/lib/arf-detect.js +41 -7
  41. package/lib/auth-token.js +44 -24
  42. package/lib/autodetect-imap-settings.js +163 -123
  43. package/lib/bounce-detect.js +25 -16
  44. package/lib/calendar-event.js +78 -0
  45. package/lib/consts.js +51 -5
  46. package/lib/create-imap-client.js +24 -0
  47. package/lib/db.js +76 -17
  48. package/lib/delivery-error.js +2 -1
  49. package/lib/egress-fetch.js +54 -3
  50. package/lib/egress-filter.js +11 -0
  51. package/lib/email-client/api-retry.js +147 -0
  52. package/lib/email-client/base-client.js +628 -615
  53. package/lib/email-client/gmail/gmail-api.js +38 -125
  54. package/lib/email-client/gmail/send-request.js +1 -1
  55. package/lib/email-client/gmail-client.js +170 -84
  56. package/lib/email-client/imap/mailbox.js +244 -535
  57. package/lib/email-client/imap/stale-view.js +109 -0
  58. package/lib/email-client/imap/subconnection.js +46 -9
  59. package/lib/email-client/imap/sync-operations.js +5 -37
  60. package/lib/email-client/imap-client.js +188 -64
  61. package/lib/email-client/message-builder.js +9 -14
  62. package/lib/email-client/notification-handler.js +5 -219
  63. package/lib/email-client/outlook/graph-api.js +147 -126
  64. package/lib/email-client/outlook/send-request.js +10 -4
  65. package/lib/email-client/outlook-client.js +519 -617
  66. package/lib/email-client/smtp-pool-manager.js +3 -2
  67. package/lib/encrypt.js +184 -19
  68. package/lib/enum-descriptions.js +1 -2
  69. package/lib/export.js +144 -41
  70. package/lib/gateway.js +20 -6
  71. package/lib/get-raw-email.js +26 -44
  72. package/lib/handlebars-helpers.js +31 -10
  73. package/lib/imap-proxy-auth.js +13 -29
  74. package/lib/imapproxy/imap-core/README.md +1 -0
  75. package/lib/imapproxy/imap-core/lib/handler/imap-parser.js +12 -0
  76. package/lib/imapproxy/imap-core/lib/imap-command.js +74 -10
  77. package/lib/imapproxy/imap-core/lib/imap-connection.js +9 -1
  78. package/lib/imapproxy/imap-core/lib/imap-server.js +112 -26
  79. package/lib/imapproxy/imap-core/lib/imap-stream.js +41 -1
  80. package/lib/imapproxy/imap-core/lib/imap-tools.js +10 -2
  81. package/lib/imapproxy/imap-core/lib/indexer/indexer.js +4 -2
  82. package/lib/imapproxy/imap-server.js +17 -177
  83. package/lib/imapproxy/proxy-handoff.js +235 -0
  84. package/lib/imapproxy/response-error.js +33 -0
  85. package/lib/imapproxy/upstream-client.js +2 -2
  86. package/lib/license-beacon.js +3 -9
  87. package/lib/llm-pre-process.js +182 -43
  88. package/lib/logger.js +1 -1
  89. package/lib/lua/ee-export-queue-add.lua +39 -0
  90. package/lib/lua/ee-get-idempotency.lua +15 -3
  91. package/lib/lua/ee-release-attempts.lua +23 -0
  92. package/lib/lua/ee-reserve-attempts.lua +42 -0
  93. package/lib/lua/h-set-bigger.lua +12 -2
  94. package/lib/lua/s-list-accounts.lua +6 -3
  95. package/lib/mcp/index.js +1 -2
  96. package/lib/mcp/listen.js +221 -18
  97. package/lib/mcp/oauth.js +44 -5
  98. package/lib/mcp/resources.js +8 -2
  99. package/lib/mcp/tools.js +13 -0
  100. package/lib/message-port-stream.js +64 -6
  101. package/lib/msgpack.js +1 -6
  102. package/lib/oauth/external-account-signer.js +16 -13
  103. package/lib/oauth/gmail.js +22 -20
  104. package/lib/oauth/outlook.js +19 -16
  105. package/lib/oauth/pubsub/google.js +38 -2
  106. package/lib/oauth/scope-checker.js +4 -7
  107. package/lib/oauth/verify-app.js +2 -2
  108. package/lib/oauth2-apps.js +139 -44
  109. package/lib/openapi/build-document.js +1 -1
  110. package/lib/openapi/joi-schema.js +78 -9
  111. package/lib/parse-message.js +21 -0
  112. package/lib/payload-examples-webhooks.json +4 -7
  113. package/lib/pbkdf2-phc.js +101 -0
  114. package/lib/privileged-settings.js +0 -14
  115. package/lib/rate-limit.js +54 -15
  116. package/lib/redis-scan-delete.js +56 -29
  117. package/lib/redis-url.js +3 -1
  118. package/lib/respawn-backoff.js +5 -4
  119. package/lib/response-stream.js +25 -4
  120. package/lib/rewrite-text-nodes.js +27 -40
  121. package/lib/routes-ui.js +0 -5
  122. package/lib/schemas.js +129 -262
  123. package/lib/sentry.js +21 -5
  124. package/lib/settings.js +58 -59
  125. package/lib/smtp-auth.js +6 -2
  126. package/lib/smtp-message-processor.js +28 -7
  127. package/lib/sso.js +7 -3
  128. package/lib/stream-encrypt.js +14 -13
  129. package/lib/swagger-options.js +3 -1
  130. package/lib/tls/provision.js +69 -3
  131. package/lib/tls/store.js +14 -1
  132. package/lib/tools.js +113 -52
  133. package/lib/totp.js +16 -1
  134. package/lib/ui-routes/account-routes.js +27 -63
  135. package/lib/ui-routes/admin-config-routes.js +111 -134
  136. package/lib/ui-routes/admin-entities-routes.js +101 -191
  137. package/lib/ui-routes/ai-options.js +104 -0
  138. package/lib/ui-routes/auth-routes.js +98 -18
  139. package/lib/ui-routes/export-routes.js +3 -23
  140. package/lib/ui-routes/internals-routes.js +12 -9
  141. package/lib/ui-routes/network-config-routes.js +8 -18
  142. package/lib/ui-routes/oauth-config-routes.js +80 -214
  143. package/lib/ui-routes/route-helpers.js +40 -44
  144. package/lib/ui-routes/unsubscribe-routes.js +2 -2
  145. package/lib/utils/decode-headers.js +32 -5
  146. package/lib/utils/header-map.js +62 -1
  147. package/lib/utils/network.js +2 -0
  148. package/lib/web-safe-html.js +77 -4
  149. package/lib/webhook-request.js +9 -1
  150. package/lib/webhook-routing.js +27 -1
  151. package/lib/webhooks.js +120 -43
  152. package/lib/worker-rpc-error.js +43 -2
  153. package/list-generate.js +13 -2
  154. package/package.json +38 -46
  155. package/sbom.json +1 -1
  156. package/scripts/refresh-test-tokens.js +42 -14
  157. package/server.js +340 -336
  158. package/static/css/flyonui.css +1 -1
  159. package/static/css/src/app.tailwind.css +7 -8
  160. package/static/js/ee-client.js +145 -70
  161. package/static/js/ui.js +350 -154
  162. package/static/licenses.html +460 -1861
  163. package/translations/messages.pot +99 -99
  164. package/views/accounts/browse.hbs +10 -4
  165. package/views/config/ai.hbs +49 -41
  166. package/views/config/oauth/app.hbs +2 -1
  167. package/views/dashboard.hbs +18 -16
  168. package/views/layout/app.hbs +0 -22
  169. package/views/layout/login.hbs +2 -1
  170. package/views/partials/filter_editor_js.hbs +4 -3
  171. package/views/partials/side_menu.hbs +0 -4
  172. package/views/partials/ui/account-picker.hbs +6 -32
  173. package/views/partials/ui/model-picker.hbs +31 -0
  174. package/views/partials/ui/pagination.hbs +6 -1
  175. package/views/partials/ui/picker.hbs +47 -0
  176. package/views/unsubscribe.hbs +1 -1
  177. package/workers/api.js +33 -23
  178. package/workers/export.js +55 -60
  179. package/workers/imap.js +134 -47
  180. package/workers/submit.js +3 -1
  181. package/workers/webhooks.js +46 -27
  182. package/.githooks/pre-commit +0 -80
  183. package/.github/CODE_OF_CONDUCT.md +0 -76
  184. package/.github/contributing.md +0 -17
  185. package/.github/dependabot.yml +0 -22
  186. package/.github/docker-smoke-test.sh +0 -61
  187. package/.github/workflows/deploy.yml +0 -215
  188. package/.github/workflows/e2e.yml +0 -55
  189. package/.github/workflows/release.yaml +0 -217
  190. package/.github/workflows/test.yml +0 -307
  191. package/lib/api-routes/chat-routes.js +0 -535
  192. package/lib/append-list.js +0 -63
  193. package/lib/document-store.js +0 -75
  194. package/lib/es.js +0 -757
  195. package/lib/generate-text-preview.js +0 -61
  196. package/lib/imapproxy/imap-core/memory-notifier.js +0 -129
  197. package/lib/lua/h-push.lua +0 -32
  198. package/lib/pre-process.js +0 -196
  199. package/lib/threads.js +0 -155
  200. package/lib/ui-routes/document-store-routes.js +0 -806
  201. package/playwright.config.js +0 -47
  202. package/views/config/document-store/chat.hbs +0 -286
  203. package/views/config/document-store/index.hbs +0 -146
  204. package/views/config/document-store/mappings/index.hbs +0 -108
  205. package/views/config/document-store/mappings/new.hbs +0 -68
  206. package/views/config/document-store/pre-processing/index.hbs +0 -103
  207. package/views/partials/document_store_header.hbs +0 -30
  208. 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 };
@@ -137,8 +137,7 @@ const ENUM_DESCRIPTIONS = {
137
137
 
138
138
  queueId: {
139
139
  notify: 'Webhook delivery queue',
140
- submit: 'Outbound email delivery queue',
141
- documents: 'Document Store indexing queue (deprecated feature)'
140
+ submit: 'Outbound email delivery queue'
142
141
  },
143
142
 
144
143
  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 { ImapFlowErrorCode } = require('imapflow');
13
16
 
14
17
  const {
15
18
  REDIS_PREFIX,
@@ -93,25 +96,111 @@ const EXPORT_FILE_EXTENSION = '.ndjson.gz';
93
96
  const EXPORT_FILE_EXTENSION_ENCRYPTED = '.ndjson.gz.enc';
94
97
 
95
98
  /**
96
- * Tells whether a stored file path is the export's own file.
99
+ * The file of an export, from its stored record.
97
100
  *
98
- * `filePath` is read back from Redis by the download and delete paths. Nothing but this module
99
- * writes it, but a path trusted only because it was stored is exactly the field a later bug, or
100
- * write access to Redis, would use to make the download route serve or the delete route unlink
101
- * an arbitrary file. The basename is checked rather than the directory, because the export
102
- * directory setting can change between an export and its download, and an older export still
103
- * lives where it was written.
101
+ * The file name is always derived from the export id, never taken from the record. `filePath` is
102
+ * read back from Redis by the download and delete paths, and nothing but this module writes it,
103
+ * but a path trusted only because it was stored is exactly the field a later bug, or write access
104
+ * to Redis, would use to make the download route serve or the delete route unlink an arbitrary
105
+ * file. Only the directory comes from the record, because the export directory setting can change
106
+ * between an export and its download, and an older export still lives where it was written.
104
107
  *
105
108
  * @param {string} exportId - Export id the record belongs to
106
- * @param {string} filePath - Stored path
107
- * @returns {boolean} true when the path names the export's own file
109
+ * @param {Object} data - The export record as stored (`filePath`, `isEncrypted`)
110
+ * @returns {string|null} The path of the export's own file, or null for a record that names none
108
111
  */
109
- function isOwnExportFile(exportId, filePath) {
110
- if (!exportId || typeof filePath !== 'string') {
111
- return false;
112
+ function exportFilePath(exportId, data) {
113
+ if (!exportId || !data || typeof data.filePath !== 'string' || !data.filePath) {
114
+ return null;
115
+ }
116
+ const extension = data.isEncrypted === '1' ? EXPORT_FILE_EXTENSION_ENCRYPTED : EXPORT_FILE_EXTENSION;
117
+ return pathlib.join(pathlib.dirname(data.filePath), `${exportId}${extension}`);
118
+ }
119
+
120
+ /**
121
+ * Opens the output chain of an export: gzip, optionally encrypt, then the file.
122
+ *
123
+ * The encryption key is derived (PBKDF2) BEFORE the file is opened and the chain is joined by
124
+ * pipeline() in the same tick the file stream is created, so an open failure (export directory
125
+ * removed or unwritable, EMFILE) always has a listener. The file used to be opened first and left
126
+ * without one while the key was derived, which crashed the export worker thread, and BullMQ re-ran
127
+ * the job into the same crash.
128
+ *
129
+ * @param {string} filePath - Output file
130
+ * @param {string|null} secret - Encryption secret, null for an unencrypted export
131
+ * @returns {Promise<Object>} `input` (write NDJSON here), `output` (the file stream), `error()`
132
+ * (the first stream error, if any) and `destroy()` (closes every stream, for an early exit)
133
+ */
134
+ async function openExportOutput(filePath, secret) {
135
+ let encryptStream = null;
136
+ if (secret) {
137
+ const { createEncryptStream } = require('./stream-encrypt');
138
+ encryptStream = await createEncryptStream(secret);
139
+ }
140
+
141
+ const gzipStream = zlib.createGzip();
142
+ const fileStream = fs.createWriteStream(filePath, { mode: 0o600 });
143
+ const streams = [gzipStream, encryptStream, fileStream].filter(Boolean);
144
+
145
+ let streamError = null;
146
+ pipeline(...streams, err => {
147
+ if (err && !streamError) {
148
+ streamError = err;
149
+ }
150
+ });
151
+
152
+ return {
153
+ input: gzipStream,
154
+ output: fileStream,
155
+ error: () => streamError,
156
+ destroy() {
157
+ for (const stream of streams) {
158
+ stream.destroy();
159
+ }
160
+ }
161
+ };
162
+ }
163
+
164
+ /**
165
+ * Opens the download chain of a completed export: the file, then decryption when it is encrypted.
166
+ *
167
+ * pipeline() rather than pipe(): hapi destroys the stream it was handed when the client goes
168
+ * away, and pipe() never passed that upstream, so every aborted download kept the file descriptor
169
+ * open. It also carries a read error down to the response, which pipe() did not, leaving the
170
+ * download hanging until the socket timed out.
171
+ *
172
+ * @param {Object} fileInfo - From Export.getFile()
173
+ * @param {Function} onError - Called with a read or decryption error; the client going away is not one
174
+ * @returns {Promise<stream.Readable>} The stream to respond with
175
+ */
176
+ async function openExportReadStream(fileInfo, onError) {
177
+ const fileReadStream = fs.createReadStream(fileInfo.filePath);
178
+
179
+ if (!fileInfo.isEncrypted) {
180
+ fileReadStream.on('error', err => onError(err));
181
+ return fileReadStream;
182
+ }
183
+
184
+ const secret = await getSecret();
185
+ if (!secret) {
186
+ fileReadStream.destroy();
187
+ throw createError('Encryption secret not available for decryption', 'EncryptionSecretMissing', 503);
188
+ }
189
+
190
+ let decryptStream;
191
+ try {
192
+ const { createDecryptStream } = require('./stream-encrypt');
193
+ decryptStream = await createDecryptStream(secret);
194
+ } catch (err) {
195
+ fileReadStream.destroy();
196
+ throw err;
112
197
  }
113
- const base = pathlib.basename(filePath);
114
- return [EXPORT_FILE_EXTENSION, EXPORT_FILE_EXTENSION_ENCRYPTED].some(ext => base === `${exportId}${ext}`);
198
+
199
+ return pipeline(fileReadStream, decryptStream, err => {
200
+ if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') {
201
+ onError(err);
202
+ }
203
+ });
115
204
  }
116
205
 
117
206
  function generateExportId() {
@@ -132,7 +221,9 @@ function isTransientError(err) {
132
221
  if (['ETIMEDOUT', 'ECONNRESET', 'ENOTFOUND', 'EAI_AGAIN', 'ECONNREFUSED', 'EPIPE', 'EHOSTUNREACH'].includes(err.code)) {
133
222
  return true;
134
223
  }
135
- if (err.statusCode >= 500 && err.statusCode < 600) {
224
+ // 429: a throttled Gmail or Graph request, or an IMAP server throttling every FETCH retry
225
+ // (the IMAP worker reports ImapFlow's ETHROTTLE as 429)
226
+ if (err.statusCode === 429 || (err.statusCode >= 500 && err.statusCode < 600)) {
136
227
  return true;
137
228
  }
138
229
  if (err.code === 'Timeout' || err.message?.includes('timeout')) {
@@ -144,10 +235,16 @@ function isTransientError(err) {
144
235
  // Account.assertMessageFound reports a missing message as a Boom 404 that carries the
145
236
  // machine-readable code and status only in err.output, while client/RPC errors set plain
146
237
  // err.code/err.statusCode - check both shapes
238
+ // DownloadIncomplete is ImapFlow reporting that the message disappeared while it was being read
147
239
  function isSkippableError(err) {
148
240
  let errCode = err.output?.payload?.code || err.code;
149
241
  let statusCode = err.statusCode || err.output?.statusCode;
150
- return errCode === 'MessageNotFound' || statusCode === 404 || err.message?.includes('Failed to generate message ID');
242
+ return (
243
+ errCode === 'MessageNotFound' ||
244
+ errCode === ImapFlowErrorCode.DownloadIncomplete ||
245
+ statusCode === 404 ||
246
+ err.message?.includes('Failed to generate message ID')
247
+ );
151
248
  }
152
249
 
153
250
  // Account.listMessages reports unknown folders as FolderNotFound (Boom error with the code in
@@ -402,7 +499,7 @@ class Export {
402
499
  const page = Number(options.page) || 0;
403
500
  const pageSize = Number(options.pageSize) || 20;
404
501
 
405
- const pattern = `${REDIS_PREFIX}exp:${escapeRedisGlob(account)}:${EXPORT_ID_PREFIX}*`;
502
+ const pattern = `${escapeRedisGlob(REDIS_PREFIX)}exp:${escapeRedisGlob(account)}:${EXPORT_ID_PREFIX}*`;
406
503
  const keys = await scanKeys(pattern);
407
504
 
408
505
  const exports = [];
@@ -457,17 +554,27 @@ class Export {
457
554
  if (!isActive) {
458
555
  await redis.multi().del(exportKey).del(queueKey).srem(ACTIVE_EXPORTS_KEY, buildActiveEntry(account, exportId)).exec();
459
556
 
460
- if (isOwnExportFile(exportId, data.filePath)) {
461
- await fs.promises.unlink(data.filePath).catch(() => {});
462
- } else if (data.filePath) {
463
- logger.error({ msg: 'Refusing to delete a file that is not the export file', account, exportId, filePath: data.filePath });
464
- }
557
+ await Export.removeFile(exportId, data);
465
558
  }
466
559
 
467
560
  logger.info({ msg: 'Export deleted', account, exportId });
468
561
  return true;
469
562
  }
470
563
 
564
+ /**
565
+ * Unlinks the export's own file, if its record names one. The path is derived from the id,
566
+ * never taken as stored (see exportFilePath()); a file that is already gone is not an error.
567
+ *
568
+ * @param {string} exportId - Export id
569
+ * @param {Object} data - The export record as stored
570
+ */
571
+ static async removeFile(exportId, data) {
572
+ const filePath = exportFilePath(exportId, data);
573
+ if (filePath) {
574
+ await fs.promises.unlink(filePath).catch(() => {});
575
+ }
576
+ }
577
+
471
578
  static async update(account, exportId, updates) {
472
579
  if (Object.keys(updates).length > 0) {
473
580
  await redis.hmset(getExportKey(account, exportId), updates);
@@ -526,12 +633,11 @@ class Export {
526
633
  })
527
634
  .toString('base64url');
528
635
 
529
- const ttl = await redis.ttl(exportKey);
530
- const multi = redis.multi().zadd(queueKey, score, value).hincrby(exportKey, 'messagesQueued', 1);
531
- if (ttl > 0) {
532
- multi.expire(queueKey, ttl);
533
- }
534
- await multi.exec();
636
+ // ZADD, the count of a new member and the queue's expiry (copied from the record's) in one
637
+ // round trip; this runs once per message of an export. A retried folder queues the
638
+ // messages its failed attempt already queued, and only a new member counts, see the script.
639
+ const added = await redis.eeExportQueueAdd(exportKey, queueKey, score, value, 'messagesQueued');
640
+ return !!added;
535
641
  }
536
642
 
537
643
  static async getNextBatch(account, exportId, limit) {
@@ -642,9 +748,7 @@ class Export {
642
748
 
643
749
  await Export.fail(account, exportId, 'Export interrupted by application restart');
644
750
 
645
- if (data.filePath) {
646
- await fs.promises.unlink(data.filePath).catch(() => {});
647
- }
751
+ await Export.removeFile(exportId, data);
648
752
  }
649
753
  } catch (err) {
650
754
  logger.error({ msg: 'Failed to mark interrupted export as failed', entry, err });
@@ -663,7 +767,7 @@ class Export {
663
767
  if (!file.startsWith(EXPORT_ID_PREFIX)) continue;
664
768
 
665
769
  const exportId = file.split('.')[0];
666
- const pattern = `${REDIS_PREFIX}exp:*:${escapeRedisGlob(exportId)}`;
770
+ const pattern = `${escapeRedisGlob(REDIS_PREFIX)}exp:*:${escapeRedisGlob(exportId)}`;
667
771
  const keys = await scanKeys(pattern);
668
772
 
669
773
  if (keys.length === 0) {
@@ -694,17 +798,14 @@ class Export {
694
798
  throw createError('Export not completed', 'ExportNotReady', 400);
695
799
  }
696
800
 
697
- if (!data.filePath) {
698
- throw createError('Export file not found', 'FileNotFound', 404);
699
- }
700
-
701
- if (!isOwnExportFile(exportId, data.filePath)) {
702
- logger.error({ msg: 'Refusing to serve a file that is not the export file', account, exportId, filePath: data.filePath });
801
+ // The export's own file, whatever the record says (see exportFilePath())
802
+ const filePath = exportFilePath(exportId, data);
803
+ if (!filePath) {
703
804
  throw createError('Export file not found', 'FileNotFound', 404);
704
805
  }
705
806
 
706
807
  try {
707
- await fs.promises.access(data.filePath, fs.constants.R_OK);
808
+ await fs.promises.access(filePath, fs.constants.R_OK);
708
809
  } catch {
709
810
  throw createError('Export file not found', 'FileNotFound', 404);
710
811
  }
@@ -712,7 +813,7 @@ class Export {
712
813
  const isEncrypted = data.isEncrypted === '1';
713
814
 
714
815
  return {
715
- filePath: data.filePath,
816
+ filePath,
716
817
  filename: `${exportId}.ndjson.gz`,
717
818
  isEncrypted
718
819
  };
@@ -722,7 +823,9 @@ class Export {
722
823
  module.exports = {
723
824
  Export,
724
825
  generateExportId,
725
- isOwnExportFile,
826
+ exportFilePath,
827
+ openExportOutput,
828
+ openExportReadStream,
726
829
  calculateScore,
727
830
  getExportKey,
728
831
  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,14 @@ 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 keeps the status in output.statusCode, which the worker RPC hop does not carry
173
+ // (lib/worker-rpc-error.js), so the submit worker and the API caller get it here too
174
+ error.statusCode = 404;
161
175
  throw error;
162
176
  }
163
177