emailengine-app 2.81.2 → 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.
- package/.ncurc.js +12 -11
- package/.release-please-manifest.json +1 -1
- package/CHANGELOG.md +27 -0
- package/Dockerfile +2 -0
- package/bin/emailengine.js +28 -18
- package/config/default.toml +0 -5
- package/config/test.toml +0 -5
- package/data/google-crawlers.json +1 -1
- package/encrypt.js +70 -42
- package/getswagger.sh +0 -4
- package/lib/account/account-state.js +2 -110
- package/lib/account/expected-identity.js +1 -1
- package/lib/account-assignment.js +138 -1
- package/lib/account.js +254 -859
- package/lib/api-reference/index.js +2 -3
- package/lib/api-reference/schema-tree.js +53 -3
- package/lib/api-routes/account-routes.js +18 -29
- package/lib/api-routes/blocklist-routes.js +2 -2
- package/lib/api-routes/bull-board-routes.js +1 -6
- package/lib/api-routes/export-routes.js +2 -22
- package/lib/api-routes/gateway-routes.js +5 -14
- package/lib/api-routes/index.js +1 -13
- package/lib/api-routes/mailbox-routes.js +2 -7
- package/lib/api-routes/mcp-oauth-routes.js +2 -1
- package/lib/api-routes/mcp-routes.js +7 -7
- package/lib/api-routes/message-routes.js +40 -235
- package/lib/api-routes/mint-bounds.js +110 -0
- package/lib/api-routes/oauth2-app-routes.js +23 -32
- package/lib/api-routes/operation-impact.js +1 -1
- package/lib/api-routes/outbox-routes.js +2 -2
- package/lib/api-routes/permission-map.js +1 -7
- package/lib/api-routes/route-helpers.js +11 -5
- package/lib/api-routes/settings-routes.js +19 -19
- package/lib/api-routes/stats-routes.js +1 -1
- package/lib/api-routes/submit-routes.js +17 -18
- package/lib/api-routes/template-routes.js +4 -9
- package/lib/api-routes/token-routes.js +27 -5
- package/lib/api-token-scheme.js +71 -0
- package/lib/arf-detect.js +33 -6
- package/lib/auth-token.js +44 -24
- package/lib/autodetect-imap-settings.js +163 -123
- package/lib/bounce-detect.js +25 -16
- package/lib/calendar-event.js +78 -0
- package/lib/consts.js +42 -5
- package/lib/create-imap-client.js +24 -0
- package/lib/db.js +76 -11
- package/lib/delivery-error.js +2 -1
- package/lib/egress-fetch.js +54 -3
- package/lib/egress-filter.js +11 -0
- package/lib/email-client/api-retry.js +147 -0
- package/lib/email-client/base-client.js +377 -523
- package/lib/email-client/gmail/gmail-api.js +38 -125
- package/lib/email-client/gmail/send-request.js +1 -1
- package/lib/email-client/gmail-client.js +76 -50
- package/lib/email-client/imap/mailbox.js +158 -324
- package/lib/email-client/imap/stale-view.js +109 -0
- package/lib/email-client/imap/subconnection.js +46 -9
- package/lib/email-client/imap/sync-operations.js +5 -37
- package/lib/email-client/imap-client.js +188 -64
- package/lib/email-client/message-builder.js +9 -14
- package/lib/email-client/notification-handler.js +5 -219
- package/lib/email-client/outlook/graph-api.js +147 -126
- package/lib/email-client/outlook/send-request.js +10 -4
- package/lib/email-client/outlook-client.js +194 -397
- package/lib/email-client/smtp-pool-manager.js +3 -2
- package/lib/encrypt.js +184 -19
- package/lib/enum-descriptions.js +1 -2
- package/lib/export.js +133 -39
- package/lib/gateway.js +20 -6
- package/lib/get-raw-email.js +26 -44
- package/lib/handlebars-helpers.js +31 -10
- package/lib/imap-proxy-auth.js +13 -29
- package/lib/imapproxy/imap-core/README.md +1 -0
- package/lib/imapproxy/imap-core/lib/handler/imap-parser.js +12 -0
- package/lib/imapproxy/imap-core/lib/imap-command.js +74 -10
- package/lib/imapproxy/imap-core/lib/imap-connection.js +9 -1
- package/lib/imapproxy/imap-core/lib/imap-server.js +112 -26
- package/lib/imapproxy/imap-core/lib/imap-stream.js +41 -1
- package/lib/imapproxy/imap-core/lib/imap-tools.js +10 -2
- package/lib/imapproxy/imap-core/lib/indexer/indexer.js +4 -2
- package/lib/imapproxy/imap-server.js +17 -177
- package/lib/imapproxy/proxy-handoff.js +235 -0
- package/lib/imapproxy/response-error.js +33 -0
- package/lib/imapproxy/upstream-client.js +2 -2
- package/lib/license-beacon.js +3 -9
- package/lib/llm-pre-process.js +182 -43
- package/lib/logger.js +1 -1
- package/lib/lua/ee-export-queue-add.lua +39 -0
- package/lib/lua/ee-get-idempotency.lua +15 -3
- package/lib/lua/ee-release-attempts.lua +23 -0
- package/lib/lua/ee-reserve-attempts.lua +42 -0
- package/lib/lua/h-set-bigger.lua +12 -2
- package/lib/lua/s-list-accounts.lua +6 -3
- package/lib/mcp/index.js +1 -2
- package/lib/mcp/listen.js +221 -18
- package/lib/mcp/oauth.js +44 -5
- package/lib/mcp/resources.js +8 -2
- package/lib/mcp/tools.js +13 -0
- package/lib/message-port-stream.js +64 -6
- package/lib/oauth/external-account-signer.js +16 -13
- package/lib/oauth/gmail.js +22 -20
- package/lib/oauth/outlook.js +19 -16
- package/lib/oauth/pubsub/google.js +38 -2
- package/lib/oauth/scope-checker.js +4 -7
- package/lib/oauth/verify-app.js +2 -2
- package/lib/oauth2-apps.js +139 -44
- package/lib/openapi/build-document.js +1 -1
- package/lib/openapi/joi-schema.js +78 -9
- package/lib/parse-message.js +21 -0
- package/lib/payload-examples-webhooks.json +4 -7
- package/lib/pbkdf2-phc.js +101 -0
- package/lib/privileged-settings.js +0 -14
- package/lib/rate-limit.js +54 -15
- package/lib/redis-scan-delete.js +56 -29
- package/lib/redis-url.js +3 -1
- package/lib/respawn-backoff.js +5 -4
- package/lib/response-stream.js +25 -4
- package/lib/rewrite-text-nodes.js +27 -40
- package/lib/routes-ui.js +0 -5
- package/lib/schemas.js +122 -242
- package/lib/sentry.js +21 -5
- package/lib/settings.js +58 -59
- package/lib/smtp-auth.js +6 -2
- package/lib/smtp-message-processor.js +28 -7
- package/lib/sso.js +7 -3
- package/lib/stream-encrypt.js +14 -13
- package/lib/swagger-options.js +3 -1
- package/lib/tls/provision.js +69 -3
- package/lib/tls/store.js +14 -1
- package/lib/tools.js +113 -52
- package/lib/totp.js +16 -1
- package/lib/ui-routes/account-routes.js +27 -63
- package/lib/ui-routes/admin-config-routes.js +111 -134
- package/lib/ui-routes/admin-entities-routes.js +101 -191
- package/lib/ui-routes/ai-options.js +104 -0
- package/lib/ui-routes/auth-routes.js +98 -18
- package/lib/ui-routes/export-routes.js +3 -23
- package/lib/ui-routes/internals-routes.js +12 -9
- package/lib/ui-routes/network-config-routes.js +8 -18
- package/lib/ui-routes/oauth-config-routes.js +80 -214
- package/lib/ui-routes/route-helpers.js +40 -44
- package/lib/ui-routes/unsubscribe-routes.js +2 -2
- package/lib/utils/decode-headers.js +32 -5
- package/lib/utils/header-map.js +62 -1
- package/lib/utils/network.js +2 -0
- package/lib/web-safe-html.js +77 -4
- package/lib/webhook-request.js +9 -1
- package/lib/webhook-routing.js +27 -1
- package/lib/webhooks.js +120 -43
- package/lib/worker-rpc-error.js +43 -2
- package/list-generate.js +13 -2
- package/package.json +33 -41
- package/sbom.json +1 -1
- package/scripts/refresh-test-tokens.js +42 -14
- package/server.js +317 -289
- package/static/css/flyonui.css +1 -1
- package/static/css/src/app.tailwind.css +7 -8
- package/static/js/ee-client.js +145 -70
- package/static/js/ui.js +350 -154
- package/static/licenses.html +434 -1835
- package/translations/messages.pot +97 -97
- package/views/accounts/browse.hbs +10 -4
- package/views/config/ai.hbs +49 -41
- package/views/config/oauth/app.hbs +2 -1
- package/views/dashboard.hbs +18 -16
- package/views/layout/app.hbs +0 -22
- package/views/layout/login.hbs +2 -1
- package/views/partials/filter_editor_js.hbs +4 -3
- package/views/partials/side_menu.hbs +0 -4
- package/views/partials/ui/account-picker.hbs +6 -32
- package/views/partials/ui/model-picker.hbs +31 -0
- package/views/partials/ui/pagination.hbs +6 -1
- package/views/partials/ui/picker.hbs +47 -0
- package/views/unsubscribe.hbs +1 -1
- package/workers/api.js +20 -20
- package/workers/export.js +55 -60
- package/workers/imap.js +126 -46
- package/workers/submit.js +3 -1
- package/workers/webhooks.js +46 -27
- package/.githooks/pre-commit +0 -80
- package/.github/CODE_OF_CONDUCT.md +0 -76
- package/.github/contributing.md +0 -17
- package/.github/dependabot.yml +0 -22
- package/.github/docker-smoke-test.sh +0 -61
- package/.github/workflows/deploy.yml +0 -215
- package/.github/workflows/e2e.yml +0 -55
- package/.github/workflows/release.yaml +0 -217
- package/.github/workflows/test.yml +0 -307
- package/lib/api-routes/chat-routes.js +0 -535
- package/lib/document-store.js +0 -75
- package/lib/es.js +0 -757
- package/lib/generate-text-preview.js +0 -61
- package/lib/imapproxy/imap-core/memory-notifier.js +0 -129
- package/lib/pre-process.js +0 -196
- package/lib/threads.js +0 -155
- package/lib/ui-routes/document-store-routes.js +0 -806
- package/playwright.config.js +0 -47
- package/views/config/document-store/chat.hbs +0 -286
- package/views/config/document-store/index.hbs +0 -146
- package/views/config/document-store/mappings/index.hbs +0 -108
- package/views/config/document-store/mappings/new.hbs +0 -68
- package/views/config/document-store/pre-processing/index.hbs +0 -103
- package/views/partials/document_store_header.hbs +0 -30
- 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
|
-
|
|
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 =
|
|
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
|
-
|
|
21
|
-
|
|
22
|
-
|
|
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
|
|
42
|
-
|
|
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
|
|
97
|
-
|
|
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 =
|
|
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,
|
|
123
|
-
assert.strictEqual(decryptData.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
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
const
|
|
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
|
-
|
|
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 };
|
package/lib/enum-descriptions.js
CHANGED
|
@@ -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,6 +4,8 @@ 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');
|
|
@@ -94,25 +96,111 @@ const EXPORT_FILE_EXTENSION = '.ndjson.gz';
|
|
|
94
96
|
const EXPORT_FILE_EXTENSION_ENCRYPTED = '.ndjson.gz.enc';
|
|
95
97
|
|
|
96
98
|
/**
|
|
97
|
-
*
|
|
99
|
+
* The file of an export, from its stored record.
|
|
98
100
|
*
|
|
99
|
-
*
|
|
100
|
-
*
|
|
101
|
-
*
|
|
102
|
-
*
|
|
103
|
-
*
|
|
104
|
-
* 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.
|
|
105
107
|
*
|
|
106
108
|
* @param {string} exportId - Export id the record belongs to
|
|
107
|
-
* @param {
|
|
108
|
-
* @returns {
|
|
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
|
|
109
111
|
*/
|
|
110
|
-
function
|
|
111
|
-
if (!exportId || typeof filePath !== 'string') {
|
|
112
|
-
return
|
|
112
|
+
function exportFilePath(exportId, data) {
|
|
113
|
+
if (!exportId || !data || typeof data.filePath !== 'string' || !data.filePath) {
|
|
114
|
+
return null;
|
|
113
115
|
}
|
|
114
|
-
const
|
|
115
|
-
return
|
|
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;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
return pipeline(fileReadStream, decryptStream, err => {
|
|
200
|
+
if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') {
|
|
201
|
+
onError(err);
|
|
202
|
+
}
|
|
203
|
+
});
|
|
116
204
|
}
|
|
117
205
|
|
|
118
206
|
function generateExportId() {
|
|
@@ -411,7 +499,7 @@ class Export {
|
|
|
411
499
|
const page = Number(options.page) || 0;
|
|
412
500
|
const pageSize = Number(options.pageSize) || 20;
|
|
413
501
|
|
|
414
|
-
const pattern = `${REDIS_PREFIX}exp:${escapeRedisGlob(account)}:${EXPORT_ID_PREFIX}*`;
|
|
502
|
+
const pattern = `${escapeRedisGlob(REDIS_PREFIX)}exp:${escapeRedisGlob(account)}:${EXPORT_ID_PREFIX}*`;
|
|
415
503
|
const keys = await scanKeys(pattern);
|
|
416
504
|
|
|
417
505
|
const exports = [];
|
|
@@ -466,17 +554,27 @@ class Export {
|
|
|
466
554
|
if (!isActive) {
|
|
467
555
|
await redis.multi().del(exportKey).del(queueKey).srem(ACTIVE_EXPORTS_KEY, buildActiveEntry(account, exportId)).exec();
|
|
468
556
|
|
|
469
|
-
|
|
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
|
-
}
|
|
557
|
+
await Export.removeFile(exportId, data);
|
|
474
558
|
}
|
|
475
559
|
|
|
476
560
|
logger.info({ msg: 'Export deleted', account, exportId });
|
|
477
561
|
return true;
|
|
478
562
|
}
|
|
479
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
|
+
|
|
480
578
|
static async update(account, exportId, updates) {
|
|
481
579
|
if (Object.keys(updates).length > 0) {
|
|
482
580
|
await redis.hmset(getExportKey(account, exportId), updates);
|
|
@@ -535,12 +633,11 @@ class Export {
|
|
|
535
633
|
})
|
|
536
634
|
.toString('base64url');
|
|
537
635
|
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
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;
|
|
544
641
|
}
|
|
545
642
|
|
|
546
643
|
static async getNextBatch(account, exportId, limit) {
|
|
@@ -651,9 +748,7 @@ class Export {
|
|
|
651
748
|
|
|
652
749
|
await Export.fail(account, exportId, 'Export interrupted by application restart');
|
|
653
750
|
|
|
654
|
-
|
|
655
|
-
await fs.promises.unlink(data.filePath).catch(() => {});
|
|
656
|
-
}
|
|
751
|
+
await Export.removeFile(exportId, data);
|
|
657
752
|
}
|
|
658
753
|
} catch (err) {
|
|
659
754
|
logger.error({ msg: 'Failed to mark interrupted export as failed', entry, err });
|
|
@@ -672,7 +767,7 @@ class Export {
|
|
|
672
767
|
if (!file.startsWith(EXPORT_ID_PREFIX)) continue;
|
|
673
768
|
|
|
674
769
|
const exportId = file.split('.')[0];
|
|
675
|
-
const pattern = `${REDIS_PREFIX}exp:*:${escapeRedisGlob(exportId)}`;
|
|
770
|
+
const pattern = `${escapeRedisGlob(REDIS_PREFIX)}exp:*:${escapeRedisGlob(exportId)}`;
|
|
676
771
|
const keys = await scanKeys(pattern);
|
|
677
772
|
|
|
678
773
|
if (keys.length === 0) {
|
|
@@ -703,17 +798,14 @@ class Export {
|
|
|
703
798
|
throw createError('Export not completed', 'ExportNotReady', 400);
|
|
704
799
|
}
|
|
705
800
|
|
|
706
|
-
|
|
707
|
-
|
|
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 });
|
|
801
|
+
// The export's own file, whatever the record says (see exportFilePath())
|
|
802
|
+
const filePath = exportFilePath(exportId, data);
|
|
803
|
+
if (!filePath) {
|
|
712
804
|
throw createError('Export file not found', 'FileNotFound', 404);
|
|
713
805
|
}
|
|
714
806
|
|
|
715
807
|
try {
|
|
716
|
-
await fs.promises.access(
|
|
808
|
+
await fs.promises.access(filePath, fs.constants.R_OK);
|
|
717
809
|
} catch {
|
|
718
810
|
throw createError('Export file not found', 'FileNotFound', 404);
|
|
719
811
|
}
|
|
@@ -721,7 +813,7 @@ class Export {
|
|
|
721
813
|
const isEncrypted = data.isEncrypted === '1';
|
|
722
814
|
|
|
723
815
|
return {
|
|
724
|
-
filePath
|
|
816
|
+
filePath,
|
|
725
817
|
filename: `${exportId}.ndjson.gz`,
|
|
726
818
|
isEncrypted
|
|
727
819
|
};
|
|
@@ -731,7 +823,9 @@ class Export {
|
|
|
731
823
|
module.exports = {
|
|
732
824
|
Export,
|
|
733
825
|
generateExportId,
|
|
734
|
-
|
|
826
|
+
exportFilePath,
|
|
827
|
+
openExportOutput,
|
|
828
|
+
openExportReadStream,
|
|
735
829
|
calculateScore,
|
|
736
830
|
getExportKey,
|
|
737
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
|
-
|
|
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
|
-
|
|
160
|
-
|
|
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
|
|