emailengine-app 2.85.0 → 2.87.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 +24 -6
- package/.release-please-manifest.json +1 -1
- package/CHANGELOG.md +97 -0
- package/DOCKER_DEPLOYMENT.md +2 -1
- package/Dockerfile +16 -3
- package/ENVIRONMENT.md +139 -0
- package/README.md +5 -1
- package/config/default.toml +2 -0
- package/copy-static-files.sh +4 -2
- package/data/google-crawlers.json +1 -1
- package/data/public_suffix_list.dat +4 -3
- package/lib/account-assignment.js +19 -0
- package/lib/account.js +285 -195
- package/lib/api-error-codes.js +49 -0
- package/lib/api-reference/model.js +6 -1
- package/lib/api-routes/account-routes.js +91 -32
- package/lib/api-routes/blocklist-routes.js +68 -2
- package/lib/api-routes/delivery-test-routes.js +1 -1
- package/lib/api-routes/gateway-routes.js +82 -10
- package/lib/api-routes/index.js +4 -0
- package/lib/api-routes/license-routes.js +2 -2
- package/lib/api-routes/mailbox-routes.js +3 -3
- package/lib/api-routes/message-routes.js +15 -7
- package/lib/api-routes/oauth2-app-routes.js +15 -8
- package/lib/api-routes/outbox-routes.js +77 -66
- package/lib/api-routes/permission-map.js +55 -6
- package/lib/api-routes/scoped-routes.js +74 -0
- package/lib/api-routes/settings-routes.js +11 -4
- package/lib/api-routes/stats-routes.js +5 -1
- package/lib/api-routes/submit-routes.js +25 -5
- package/lib/api-routes/template-routes.js +7 -6
- package/lib/api-routes/token-routes.js +11 -5
- package/lib/api-routes/webhook-delivery-routes.js +262 -0
- package/lib/api-routes/webhook-route-routes.js +119 -4
- package/lib/calendar-event.js +81 -1
- package/lib/consts.js +38 -46
- package/lib/db.js +14 -6
- package/lib/delivery-error.js +6 -0
- package/lib/deprecations.js +270 -0
- package/lib/email-client/base-client.js +134 -158
- package/lib/email-client/fallback-poll.js +62 -0
- package/lib/email-client/gmail-client.js +59 -11
- package/lib/email-client/imap/adaptive-idle-store.js +73 -0
- package/lib/email-client/imap/adaptive-idle.js +278 -0
- package/lib/email-client/imap/connection-errors.js +14 -1
- package/lib/email-client/imap/idle-settings.js +31 -5
- package/lib/email-client/imap/listing-diff.js +37 -0
- package/lib/email-client/imap/mailbox.js +380 -227
- package/lib/email-client/imap/subconnection.js +7 -29
- package/lib/email-client/imap/sync-operations.js +220 -127
- package/lib/email-client/imap-client.js +227 -163
- package/lib/email-client/message-builder.js +14 -79
- package/lib/email-client/outlook-client.js +378 -338
- package/lib/email-client/smtp-pool-manager.js +16 -13
- package/lib/email-client/sync-state-fields.js +19 -0
- package/lib/encrypt.js +157 -41
- package/lib/enum-descriptions.js +3 -1
- package/lib/env-setting-overrides.js +288 -0
- package/lib/export-worker.js +751 -0
- package/lib/export.js +64 -15
- package/lib/field-usage.js +1 -1
- package/lib/gateway.js +17 -1
- package/lib/get-raw-email.js +35 -108
- package/lib/health.js +75 -0
- package/lib/lock-run.js +119 -0
- package/lib/logger-consts.js +48 -0
- package/lib/logger.js +1 -1
- package/lib/lua/z-head-scores.lua +28 -0
- package/lib/network-errors.js +1 -1
- package/lib/node-version.js +24 -0
- package/lib/notify-attachments.js +20 -1
- package/lib/oauth/gmail.js +54 -29
- package/lib/oauth2-apps.js +630 -655
- package/lib/otp.js +66 -0
- package/lib/outbox.js +184 -54
- package/lib/parse-message.js +3 -3
- package/lib/privileged-settings.js +2 -2
- package/lib/queue-browser/definitions.js +11 -0
- package/lib/queue-browser/index.js +68 -19
- package/lib/queue-job-actions.js +18 -1
- package/lib/queue-retention.js +48 -12
- package/lib/queue-stats.js +11 -2
- package/lib/read-env-value.js +3 -0
- package/lib/redis-memory-warnings.js +99 -0
- package/lib/redis-reconnect.js +29 -0
- package/lib/request-timing.js +23 -0
- package/lib/respawn-backoff.js +35 -0
- package/lib/rewrite-text-nodes.js +19 -59
- package/lib/schemas.js +225 -41
- package/lib/settings.js +6 -2
- package/lib/smtp-auth.js +19 -1
- package/lib/swagger-options.js +2 -2
- package/lib/thread-diagnostics.js +18 -1
- package/lib/tls/provision.js +6 -3
- package/lib/token-audit-log.js +19 -20
- package/lib/token-permission-view.js +4 -3
- package/lib/tools.js +8 -41
- package/lib/ui-routes/admin-config-routes.js +64 -90
- package/lib/ui-routes/admin-entities-routes.js +2 -14
- package/lib/ui-routes/imap-idle-field.js +1 -1
- package/lib/ui-routes/outlook-subscription-view.js +1 -1
- package/lib/ui-routes/overridable-fields.js +84 -0
- package/lib/ui-routes/queue-routes.js +8 -5
- package/lib/ui-routes/settings-page.js +6 -0
- package/lib/utils/decode-headers.js +3 -12
- package/lib/utils/filter-empty.js +20 -0
- package/lib/utils/int-setting.js +48 -0
- package/lib/utils/tracking-settings.js +35 -0
- package/lib/web-safe-html.js +18 -105
- package/lib/webhook-delivery.js +461 -0
- package/lib/webhook-failures.js +132 -0
- package/lib/webhook-request.js +29 -1
- package/lib/webhook-routing.js +30 -1
- package/lib/webhook-test.js +88 -0
- package/lib/webhooks.js +59 -41
- package/lib/worker-rpc-error.js +2 -1
- package/package.json +28 -26
- package/sbom.json +600 -678
- package/server.js +149 -76
- package/static/css/flyonui.css +1 -1
- package/static/js/ace/ace.js +1 -1
- package/static/js/ee-client.js +650 -196
- package/static/licenses.html +49 -59
- package/translations/messages.pot +26 -26
- package/views/config/security.hbs +22 -0
- package/views/config/service.hbs +44 -0
- package/views/config/webhooks.hbs +36 -0
- package/views/layout/app.hbs +9 -6
- package/views/legal.hbs +8 -0
- package/views/partials/queue_retention_note.hbs +12 -8
- package/views/partials/ui/env-managed-alert.hbs +16 -7
- package/workers/api.js +112 -37
- package/workers/export.js +16 -631
- package/workers/imap.js +13 -0
- package/workers/smtp.js +9 -11
- package/workers/webhooks.js +18 -432
- package/lib/email-client/outlook-fallback-poll.js +0 -30
|
@@ -45,12 +45,20 @@ function generatePoolKey(smtpSettings) {
|
|
|
45
45
|
* @param {string} poolKey - Pool key for this transport
|
|
46
46
|
*/
|
|
47
47
|
function setupTransporterHandlers(transporter, poolKey) {
|
|
48
|
+
// A pool that was already replaced under this key must not take its successor out of the map
|
|
49
|
+
// on a late event, or the live transporter is no longer reused nor closed by the idle sweep
|
|
50
|
+
const forget = () => {
|
|
51
|
+
if (SMTP_POOLS.get(poolKey) === transporter) {
|
|
52
|
+
SMTP_POOLS.delete(poolKey);
|
|
53
|
+
SMTP_POOL_LAST_USED.delete(poolKey);
|
|
54
|
+
}
|
|
55
|
+
};
|
|
56
|
+
|
|
48
57
|
// Handle connection pool cleanup when idle
|
|
49
58
|
transporter.once('clear', () => {
|
|
50
59
|
// All emails processed and connection timed out
|
|
51
60
|
logger.trace({ msg: 'Clearing disconnected SMTP pool', poolKey });
|
|
52
|
-
|
|
53
|
-
SMTP_POOL_LAST_USED.delete(poolKey);
|
|
61
|
+
forget();
|
|
54
62
|
try {
|
|
55
63
|
transporter.close();
|
|
56
64
|
} catch (closeErr) {
|
|
@@ -62,8 +70,7 @@ function setupTransporterHandlers(transporter, poolKey) {
|
|
|
62
70
|
transporter.once('error', err => {
|
|
63
71
|
// Not sure what happened, but do not re-use this transporter object anymore
|
|
64
72
|
logger.warn({ msg: 'Transporter failed', err });
|
|
65
|
-
|
|
66
|
-
SMTP_POOL_LAST_USED.delete(poolKey);
|
|
73
|
+
forget();
|
|
67
74
|
try {
|
|
68
75
|
transporter.close();
|
|
69
76
|
} catch (closeErr) {
|
|
@@ -140,20 +147,16 @@ function closePooledConnection(poolKey) {
|
|
|
140
147
|
}
|
|
141
148
|
|
|
142
149
|
/**
|
|
143
|
-
* Whether a pooled transport still has a message queued or being transmitted.
|
|
144
|
-
*
|
|
150
|
+
* Whether a pooled transport still has a message queued or being transmitted. isIdle() turns true
|
|
151
|
+
* while a message is still on the wire, so it can not tell. nodemailer (10.2.0) counts them itself,
|
|
152
|
+
* including a message between a dropped connection and its requeue, which reading the pool's queue
|
|
153
|
+
* and connections used to miss
|
|
145
154
|
* @param {Object} transporter - Nodemailer transport instance
|
|
146
155
|
* @returns {boolean}
|
|
147
156
|
*/
|
|
148
157
|
function hasPendingDeliveries(transporter) {
|
|
149
158
|
const pool = transporter && transporter.transporter;
|
|
150
|
-
|
|
151
|
-
return false;
|
|
152
|
-
}
|
|
153
|
-
return (
|
|
154
|
-
(Array.isArray(pool._queue) && pool._queue.length > 0) ||
|
|
155
|
-
(Array.isArray(pool._connections) && pool._connections.some(connection => connection.queueEntry))
|
|
156
|
-
);
|
|
159
|
+
return !!pool && typeof pool.pendingCount === 'function' && pool.pendingCount() > 0;
|
|
157
160
|
}
|
|
158
161
|
|
|
159
162
|
/**
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// The fields of the account hash the Gmail API and Graph clients write for themselves. Kept in one
|
|
4
|
+
// leaf module (the clients require lib/account.js, so it can not import them) so a flush clears
|
|
5
|
+
// every field that holds a client's position in the mailbox: the list used to live in the Account
|
|
6
|
+
// model, where a field a client added later would not have been cleared, which is exactly how a
|
|
7
|
+
// flush came to leave a Gmail account on its old history ID. test/sync-state-fields-test.js fails
|
|
8
|
+
// when a client writes a field listed in neither group.
|
|
9
|
+
|
|
10
|
+
// Where the client is in the mailbox; a flush clears these and the client starts over from now
|
|
11
|
+
const SYNC_STATE_FIELDS = {
|
|
12
|
+
gmail: ['googleHistoryId', 'googleHistoryProcessing'],
|
|
13
|
+
outlook: ['outlookAnnouncedInSince', 'outlookRecoveredUntil']
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
// Written by the clients too, but not a position in the mailbox, so a flush keeps them
|
|
17
|
+
const OTHER_CLIENT_FIELDS = ['outlookSubscription', 'outlookLastNotification', 'outlookMailFoldersDeltaUrl'];
|
|
18
|
+
|
|
19
|
+
module.exports = { SYNC_STATE_FIELDS, OTHER_CLIENT_FIELDS };
|
package/lib/encrypt.js
CHANGED
|
@@ -38,6 +38,11 @@
|
|
|
38
38
|
|
|
39
39
|
const crypto = require('crypto');
|
|
40
40
|
const assert = require('assert');
|
|
41
|
+
const { promisify } = require('util');
|
|
42
|
+
|
|
43
|
+
// Looked up on each call rather than bound at load, so a test can count the derivations
|
|
44
|
+
const pbkdf2Async = (...args) => promisify(crypto.pbkdf2)(...args);
|
|
45
|
+
const scryptAsync = (...args) => promisify(crypto.scrypt)(...args);
|
|
41
46
|
|
|
42
47
|
const WD_ENCRYPTION_SCHEME_KEY_1 = 'wd01';
|
|
43
48
|
const WD_ENCRYPTION_SCHEME_KEY_2 = 'wd02';
|
|
@@ -73,11 +78,14 @@ function getProcessSalt() {
|
|
|
73
78
|
return processSalt;
|
|
74
79
|
}
|
|
75
80
|
|
|
76
|
-
//
|
|
77
|
-
//
|
|
78
|
-
function
|
|
79
|
-
|
|
81
|
+
// The scheme is part of the cache key: a wd01 and a wd02 value sharing a salt derive different keys
|
|
82
|
+
// from the same secret
|
|
83
|
+
function cacheKeyFor(scheme, password, salt) {
|
|
84
|
+
return crypto.createHmac('sha256', password).update(scheme).update(salt).digest('hex');
|
|
85
|
+
}
|
|
80
86
|
|
|
87
|
+
// Simple LRU cache for storing secrets in a WeakMap, keyed by cacheKeyFor()
|
|
88
|
+
function saltCache(cacheKeyStr, salt, key) {
|
|
81
89
|
// Get path
|
|
82
90
|
if (!key) {
|
|
83
91
|
const cacheKeyObj = CACHED_SALT_OBJ.get(cacheKeyStr);
|
|
@@ -166,57 +174,154 @@ function deriveKey(scheme, password, salt) {
|
|
|
166
174
|
}
|
|
167
175
|
|
|
168
176
|
function getKeyFromPassword(scheme, password, salt) {
|
|
169
|
-
|
|
177
|
+
const cacheKey = cacheKeyFor(scheme, password, salt);
|
|
178
|
+
let cachedKey = saltCache(cacheKey, salt);
|
|
170
179
|
if (cachedKey) {
|
|
171
180
|
return cachedKey;
|
|
172
181
|
}
|
|
173
182
|
const key = deriveKey(scheme, password, salt);
|
|
174
|
-
saltCache(
|
|
183
|
+
saltCache(cacheKey, salt, key); // update cache
|
|
175
184
|
return key;
|
|
176
185
|
}
|
|
177
186
|
|
|
178
|
-
|
|
187
|
+
// Derivations in flight, so values sharing a salt (every value one process wrote) wait for one
|
|
188
|
+
// derivation instead of starting one each
|
|
189
|
+
const PENDING_KEYS = new Map();
|
|
190
|
+
|
|
191
|
+
function deriveKeyAsync(scheme, password, salt) {
|
|
192
|
+
switch (scheme) {
|
|
193
|
+
case WD_ENCRYPTION_SCHEME_KEY_1:
|
|
194
|
+
return scryptAsync(password, salt, 32);
|
|
195
|
+
case WD_ENCRYPTION_SCHEME_KEY_2:
|
|
196
|
+
return pbkdf2Async(password, salt, PBKDF2_ITERATIONS, 32, PBKDF2_DIGEST);
|
|
197
|
+
default:
|
|
198
|
+
return Promise.reject(new Error(`Unknown encryption scheme ${scheme}`));
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
// How many derivations run on the libuv thread pool at once. The pool is shared with dns.lookup()
|
|
203
|
+
// and file system calls, and at startup every account with a salt of its own asks for a derivation
|
|
204
|
+
// of about 40 ms, so an unbounded burst would hold up the IMAP connects waiting behind it
|
|
205
|
+
const MAX_PARALLEL_DERIVATIONS = 2;
|
|
206
|
+
let runningDerivations = 0;
|
|
207
|
+
const waitingDerivations = [];
|
|
208
|
+
|
|
209
|
+
async function limitedDerivation(fn) {
|
|
210
|
+
if (runningDerivations >= MAX_PARALLEL_DERIVATIONS) {
|
|
211
|
+
await new Promise(resolve => waitingDerivations.push(resolve));
|
|
212
|
+
}
|
|
213
|
+
runningDerivations++;
|
|
214
|
+
try {
|
|
215
|
+
return await fn();
|
|
216
|
+
} finally {
|
|
217
|
+
runningDerivations--;
|
|
218
|
+
const next = waitingDerivations.shift();
|
|
219
|
+
if (next) {
|
|
220
|
+
next();
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
// The asynchronous counterpart of getKeyFromPassword(), sharing its cache
|
|
226
|
+
async function getKeyFromPasswordAsync(scheme, password, salt) {
|
|
227
|
+
const cacheKey = cacheKeyFor(scheme, password, salt);
|
|
228
|
+
let cachedKey = saltCache(cacheKey, salt);
|
|
229
|
+
if (cachedKey) {
|
|
230
|
+
return cachedKey;
|
|
231
|
+
}
|
|
232
|
+
if (!PENDING_KEYS.has(cacheKey)) {
|
|
233
|
+
PENDING_KEYS.set(
|
|
234
|
+
cacheKey,
|
|
235
|
+
limitedDerivation(() => deriveKeyAsync(scheme, password, salt))
|
|
236
|
+
.then(key => saltCache(cacheKey, salt, key))
|
|
237
|
+
.finally(() => PENDING_KEYS.delete(cacheKey))
|
|
238
|
+
);
|
|
239
|
+
}
|
|
240
|
+
return await PENDING_KEYS.get(cacheKey);
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/**
|
|
244
|
+
* Parses a stored value for decryption
|
|
245
|
+
* @returns {{cleartext: string}|{decryptData: Object}} The value itself when there is nothing to decrypt
|
|
246
|
+
*/
|
|
247
|
+
function parseForDecrypt(encryptedData, secret) {
|
|
179
248
|
const raw = (encryptedData || '').toString('utf-8');
|
|
180
249
|
|
|
181
250
|
if (!secret || !raw) {
|
|
182
|
-
return raw;
|
|
251
|
+
return { cleartext: raw };
|
|
183
252
|
}
|
|
184
253
|
|
|
185
254
|
const decryptData = parseEncryptedData(raw);
|
|
255
|
+
if (![WD_ENCRYPTION_SCHEME_KEY_1, WD_ENCRYPTION_SCHEME_KEY_2].includes(decryptData.format)) {
|
|
256
|
+
// cleartext, or a format this version does not know, which is treated as cleartext
|
|
257
|
+
return { cleartext: raw };
|
|
258
|
+
}
|
|
186
259
|
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
return raw;
|
|
260
|
+
return { decryptData };
|
|
261
|
+
}
|
|
190
262
|
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
263
|
+
function decryptError(E) {
|
|
264
|
+
let err = new Error('Failed to decrypt data. ' + E.message);
|
|
265
|
+
err.responseCode = 500;
|
|
266
|
+
err.code = 'InternalConfigError';
|
|
267
|
+
return err;
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
function checkDecryptData(decryptData) {
|
|
271
|
+
assert.strictEqual(decryptData.authTag.length, 16, 'Invalid auth tag length');
|
|
272
|
+
assert.strictEqual(decryptData.iv.length, IV_LENGTH, 'Invalid iv length');
|
|
273
|
+
assert.strictEqual(decryptData.salt.length, SALT_LENGTH, 'Invalid salt length');
|
|
274
|
+
assert.strictEqual(decryptData.cipher, WD_CIPHER_1, 'Unsupported cipher');
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
function decipherWith(decryptData, key) {
|
|
278
|
+
const decipher = crypto.createDecipheriv(decryptData.cipher, key, decryptData.iv, {
|
|
279
|
+
authTagLength: decryptData.authTag.length
|
|
280
|
+
});
|
|
281
|
+
decipher.setAuthTag(decryptData.authTag);
|
|
282
|
+
|
|
283
|
+
// try to decipher
|
|
284
|
+
return Buffer.concat([decipher.update(decryptData.data), decipher.final()]).toString('utf-8');
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
function decrypt(encryptedData, secret) {
|
|
288
|
+
const { cleartext, decryptData } = parseForDecrypt(encryptedData, secret);
|
|
289
|
+
if (!decryptData) {
|
|
290
|
+
return cleartext;
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
try {
|
|
294
|
+
checkDecryptData(decryptData);
|
|
295
|
+
// convert password to 32B key, the way the value's scheme says
|
|
296
|
+
const key = getKeyFromPassword(decryptData.format, secret, decryptData.salt);
|
|
297
|
+
return decipherWith(decryptData, key);
|
|
298
|
+
} catch (E) {
|
|
299
|
+
throw decryptError(E);
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
/**
|
|
304
|
+
* decrypt() with the key derivation run on the libuv thread pool. A key that is not cached costs a
|
|
305
|
+
* 600000 iteration PBKDF2 (or a scrypt for wd01), about 40 ms that the synchronous decrypt() spends
|
|
306
|
+
* with the event loop blocked. A worker loading many accounts at startup whose values each carry
|
|
307
|
+
* their own salt (written before the salt became per process) used to do that once per account,
|
|
308
|
+
* one after another. Same result and errors as decrypt(), same key cache
|
|
309
|
+
* @param {string|Buffer} encryptedData
|
|
310
|
+
* @param {string} secret
|
|
311
|
+
* @returns {Promise<string>}
|
|
312
|
+
*/
|
|
313
|
+
async function decryptAsync(encryptedData, secret) {
|
|
314
|
+
const { cleartext, decryptData } = parseForDecrypt(encryptedData, secret);
|
|
315
|
+
if (!decryptData) {
|
|
316
|
+
return cleartext;
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
try {
|
|
320
|
+
checkDecryptData(decryptData);
|
|
321
|
+
const key = await getKeyFromPasswordAsync(decryptData.format, secret, decryptData.salt);
|
|
322
|
+
return decipherWith(decryptData, key);
|
|
323
|
+
} catch (E) {
|
|
324
|
+
throw decryptError(E);
|
|
220
325
|
}
|
|
221
326
|
}
|
|
222
327
|
|
|
@@ -342,4 +447,15 @@ function reencrypt(value, decryptSecrets, encryptSecret) {
|
|
|
342
447
|
throw lastErr || new Error('Could not decrypt encrypted value');
|
|
343
448
|
}
|
|
344
449
|
|
|
345
|
-
module.exports = {
|
|
450
|
+
module.exports = {
|
|
451
|
+
encrypt,
|
|
452
|
+
decrypt,
|
|
453
|
+
decryptAsync,
|
|
454
|
+
encryptField,
|
|
455
|
+
decryptField,
|
|
456
|
+
parseEncryptedData,
|
|
457
|
+
isCurrentScheme,
|
|
458
|
+
reencrypt,
|
|
459
|
+
PBKDF2_ITERATIONS,
|
|
460
|
+
PBKDF2_DIGEST
|
|
461
|
+
};
|
package/lib/enum-descriptions.js
CHANGED
|
@@ -143,7 +143,9 @@ const ENUM_DESCRIPTIONS = {
|
|
|
143
143
|
license: 'Read, apply and remove the license key',
|
|
144
144
|
token: 'List, inspect and revoke access tokens and read their audit logs, which record who read which account. Cannot create tokens',
|
|
145
145
|
provisioning:
|
|
146
|
-
'Add and reconfigure email accounts and SMTP gateways, including where they connect. A stored credential is sent to whatever host the record names after the change'
|
|
146
|
+
'Add and reconfigure email accounts and SMTP gateways, including where they connect. A stored credential is sent to whatever host the record names after the change',
|
|
147
|
+
'webhook-deliveries':
|
|
148
|
+
'List, retry and remove the webhook deliveries that failed for good. A listing names the account, folder and message each failed event was about, across every account'
|
|
147
149
|
},
|
|
148
150
|
|
|
149
151
|
queueId: {
|
|
@@ -0,0 +1,288 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// Limits that used to exist only as environment variables and are now settings as well, so an
|
|
4
|
+
// operator without access to the process environment (a hosted instance, a managed container) can
|
|
5
|
+
// change them from the admin UI or the settings API.
|
|
6
|
+
//
|
|
7
|
+
// The environment variable still wins. It was the only way to set these for years, deployments
|
|
8
|
+
// rely on it, and an operator who put a value in the environment meant it: a setting saved in the
|
|
9
|
+
// UI must not silently override a pinned deployment value. The settings pages flag a field whose
|
|
10
|
+
// variable is set (envOverriddenSettings()), so a value saved there is not mistaken for one in
|
|
11
|
+
// effect. An environment value that does not parse is ignored as before, which now means the
|
|
12
|
+
// setting applies rather than the default.
|
|
13
|
+
//
|
|
14
|
+
// Reads are cached per process for a few seconds. Two of these sit on hot paths (the job options
|
|
15
|
+
// of every webhook and every queued message, and every audit log write), where a settings round
|
|
16
|
+
// trip per call would add up; the cost is that a saved change takes effect within the window.
|
|
17
|
+
|
|
18
|
+
const settings = require('./settings');
|
|
19
|
+
const { readEnvValue, hasEnvValue, getBoolean, getByteSize } = require('./tools');
|
|
20
|
+
const { asPositiveInt, asNonNegativeInt } = require('./utils/int-setting');
|
|
21
|
+
const { TOKEN_LOG_ENTRIES_DEFAULT, TOKEN_LOG_AGE_DEFAULT } = require('./consts');
|
|
22
|
+
const {
|
|
23
|
+
FAILED_JOB_RETENTION_AGE_DEFAULT,
|
|
24
|
+
FAILED_JOB_RETENTION_COUNT_DEFAULT,
|
|
25
|
+
DEFAULT_FAILED_CONTENT_RETENTION_COUNT,
|
|
26
|
+
DEFAULT_FAILED_CONTENT_RETENTION_SIZE
|
|
27
|
+
} = require('./queue-retention');
|
|
28
|
+
|
|
29
|
+
const CACHE_MS = 10 * 1000;
|
|
30
|
+
|
|
31
|
+
const asByteSize = value => asNonNegativeInt(getByteSize(value));
|
|
32
|
+
|
|
33
|
+
const asBoolean = value => (typeof value === 'boolean' ? value : undefined);
|
|
34
|
+
|
|
35
|
+
// key -> the environment variable that overrides it, how each source is read, and the default.
|
|
36
|
+
// `fromEnv` reads the raw environment string, `fromSetting` the stored value; either returns
|
|
37
|
+
// undefined for a value it cannot use.
|
|
38
|
+
const OVERRIDABLE_SETTINGS = {
|
|
39
|
+
disableThreadCollapse: {
|
|
40
|
+
env: 'EENGINE_DISABLE_THREAD_COLLAPSE',
|
|
41
|
+
fromEnv: value => getBoolean(value),
|
|
42
|
+
fromSetting: asBoolean,
|
|
43
|
+
defaultValue: false
|
|
44
|
+
},
|
|
45
|
+
queueKeepFailed: {
|
|
46
|
+
env: 'EENGINE_QUEUE_KEEP_FAILED',
|
|
47
|
+
fromEnv: asPositiveInt,
|
|
48
|
+
fromSetting: asPositiveInt,
|
|
49
|
+
defaultValue: FAILED_JOB_RETENTION_COUNT_DEFAULT
|
|
50
|
+
},
|
|
51
|
+
queueKeepFailedAge: {
|
|
52
|
+
env: 'EENGINE_QUEUE_KEEP_FAILED_AGE',
|
|
53
|
+
fromEnv: asPositiveInt,
|
|
54
|
+
fromSetting: asPositiveInt,
|
|
55
|
+
defaultValue: FAILED_JOB_RETENTION_AGE_DEFAULT
|
|
56
|
+
},
|
|
57
|
+
queueKeepFailedContent: {
|
|
58
|
+
env: 'EENGINE_QUEUE_KEEP_FAILED_CONTENT',
|
|
59
|
+
fromEnv: asNonNegativeInt,
|
|
60
|
+
fromSetting: asNonNegativeInt,
|
|
61
|
+
defaultValue: DEFAULT_FAILED_CONTENT_RETENTION_COUNT
|
|
62
|
+
},
|
|
63
|
+
queueKeepFailedContentSize: {
|
|
64
|
+
env: 'EENGINE_QUEUE_KEEP_FAILED_CONTENT_SIZE',
|
|
65
|
+
fromEnv: asByteSize,
|
|
66
|
+
fromSetting: asNonNegativeInt,
|
|
67
|
+
defaultValue: DEFAULT_FAILED_CONTENT_RETENTION_SIZE
|
|
68
|
+
},
|
|
69
|
+
tokenLogEntries: {
|
|
70
|
+
env: 'EENGINE_TOKEN_LOG_ENTRIES',
|
|
71
|
+
fromEnv: asPositiveInt,
|
|
72
|
+
fromSetting: asPositiveInt,
|
|
73
|
+
defaultValue: TOKEN_LOG_ENTRIES_DEFAULT
|
|
74
|
+
},
|
|
75
|
+
tokenLogAge: {
|
|
76
|
+
env: 'EENGINE_TOKEN_LOG_AGE',
|
|
77
|
+
fromEnv: asPositiveInt,
|
|
78
|
+
fromSetting: asPositiveInt,
|
|
79
|
+
defaultValue: TOKEN_LOG_AGE_DEFAULT
|
|
80
|
+
}
|
|
81
|
+
};
|
|
82
|
+
|
|
83
|
+
const isOverridableSetting = key => Object.hasOwn(OVERRIDABLE_SETTINGS, key);
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* The value in effect for one overridable setting. Pure: the environment and the stored value are
|
|
87
|
+
* passed in.
|
|
88
|
+
*
|
|
89
|
+
* @param {string} key - A key of OVERRIDABLE_SETTINGS
|
|
90
|
+
* @param {Object} sources
|
|
91
|
+
* @param {boolean} sources.envSet - Whether the environment variable (or its _FILE form) is set
|
|
92
|
+
* @param {*} sources.envValue - The environment value, when set
|
|
93
|
+
* @param {*} sources.storedValue - The stored setting, if any
|
|
94
|
+
* @returns {{value: *, source: 'env'|'setting'|'default'}}
|
|
95
|
+
*/
|
|
96
|
+
function resolveOverridableSetting(key, { envSet, envValue, storedValue }) {
|
|
97
|
+
const definition = OVERRIDABLE_SETTINGS[key];
|
|
98
|
+
if (!definition) {
|
|
99
|
+
throw new Error(`Unknown overridable setting ${key}`);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
if (envSet) {
|
|
103
|
+
const fromEnv = definition.fromEnv(envValue);
|
|
104
|
+
if (fromEnv !== undefined) {
|
|
105
|
+
return { value: fromEnv, source: 'env' };
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
const fromSetting = definition.fromSetting(storedValue);
|
|
110
|
+
if (fromSetting !== undefined) {
|
|
111
|
+
return { value: fromSetting, source: 'setting' };
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
return { value: definition.defaultValue, source: 'default' };
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
function envSource(key) {
|
|
118
|
+
const { env } = OVERRIDABLE_SETTINGS[key];
|
|
119
|
+
const envSet = hasEnvValue(env);
|
|
120
|
+
return { envSet, envValue: envSet ? readEnvValue(env) : undefined };
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* The environment value or the default, without the stored setting, for the few readers that are
|
|
125
|
+
* fixed when a module loads (the token log route's page size bound) and so can not wait on a read
|
|
126
|
+
* @param {string} key - A key of OVERRIDABLE_SETTINGS
|
|
127
|
+
* @returns {*}
|
|
128
|
+
*/
|
|
129
|
+
function envOrDefault(key) {
|
|
130
|
+
return resolveOverridableSetting(key, envSource(key)).value;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* The keys whose environment variable is set and readable, for the settings pages to flag.
|
|
135
|
+
* @param {string[]} [keys] - Limit the answer to these keys
|
|
136
|
+
* @returns {Array<{key: string, env: string}>}
|
|
137
|
+
*/
|
|
138
|
+
function envOverriddenSettings(keys) {
|
|
139
|
+
return Object.keys(OVERRIDABLE_SETTINGS)
|
|
140
|
+
.filter(key => !keys || keys.includes(key))
|
|
141
|
+
.filter(key => {
|
|
142
|
+
const { envSet, envValue } = envSource(key);
|
|
143
|
+
return envSet && OVERRIDABLE_SETTINGS[key].fromEnv(envValue) !== undefined;
|
|
144
|
+
})
|
|
145
|
+
.map(key => ({ key, env: OVERRIDABLE_SETTINGS[key].env }));
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
// key -> { at, value }, where value is the promise of the read that fetched it, so callers that
|
|
149
|
+
// arrive while a read is in flight share it instead of each issuing their own
|
|
150
|
+
let cache = new Map();
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* Reads the stored values of the given keys and resolves what is in effect for each
|
|
154
|
+
* @param {string[]} keys
|
|
155
|
+
* @returns {Promise<{values: Object, failed: boolean}>} Never rejects
|
|
156
|
+
*/
|
|
157
|
+
async function readOverridableSettings(keys) {
|
|
158
|
+
let stored;
|
|
159
|
+
let failed = false;
|
|
160
|
+
try {
|
|
161
|
+
stored = (await settings.getMulti(...keys)) || {};
|
|
162
|
+
} catch (err) {
|
|
163
|
+
// A settings read must not decide whether a job is queued or a request is logged; the
|
|
164
|
+
// environment and the defaults still apply, and are not cached, so the next call asks again
|
|
165
|
+
stored = {};
|
|
166
|
+
failed = true;
|
|
167
|
+
}
|
|
168
|
+
const values = {};
|
|
169
|
+
for (const key of keys) {
|
|
170
|
+
values[key] = resolveOverridableSetting(key, Object.assign(envSource(key), { storedValue: stored[key] })).value;
|
|
171
|
+
}
|
|
172
|
+
return { values, failed };
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* The values in effect for the given overridable settings, read through a short per-process cache.
|
|
177
|
+
* @param {...string} keys - Keys of OVERRIDABLE_SETTINGS
|
|
178
|
+
* @returns {Promise<Object>} key -> value
|
|
179
|
+
*/
|
|
180
|
+
async function getOverridableSettings(...keys) {
|
|
181
|
+
const now = Date.now();
|
|
182
|
+
const missing = keys.filter(key => {
|
|
183
|
+
const cached = cache.get(key);
|
|
184
|
+
return !(cached && now - cached.at < CACHE_MS);
|
|
185
|
+
});
|
|
186
|
+
|
|
187
|
+
if (missing.length) {
|
|
188
|
+
const read = readOverridableSettings(missing);
|
|
189
|
+
const entries = missing.map(key => {
|
|
190
|
+
const entry = { at: now, value: read.then(({ values }) => values[key]) };
|
|
191
|
+
cache.set(key, entry);
|
|
192
|
+
return [key, entry];
|
|
193
|
+
});
|
|
194
|
+
read.then(({ failed }) => {
|
|
195
|
+
if (failed) {
|
|
196
|
+
for (const [key, entry] of entries) {
|
|
197
|
+
if (cache.get(key) === entry) {
|
|
198
|
+
cache.delete(key);
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
});
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
const result = {};
|
|
206
|
+
for (const key of keys) {
|
|
207
|
+
result[key] = await cache.get(key).value;
|
|
208
|
+
}
|
|
209
|
+
return result;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/**
|
|
213
|
+
* The failed-job bounds for BullMQ's removeOnFail and the periodic queue cleanup.
|
|
214
|
+
* @returns {Promise<{age: number, count: number}>} Age in seconds, and count
|
|
215
|
+
*/
|
|
216
|
+
async function getFailedJobRetention() {
|
|
217
|
+
const values = await getOverridableSettings('queueKeepFailed', 'queueKeepFailedAge');
|
|
218
|
+
return { age: values.queueKeepFailedAge, count: values.queueKeepFailed };
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
// Exposed so tests, and a settings write in this process, can drop the cache
|
|
222
|
+
function resetOverridableSettingsCache() {
|
|
223
|
+
cache = new Map();
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/**
|
|
227
|
+
* Writes a settings form's values, treating the overridable keys the way their pages show them:
|
|
228
|
+
* an overridable key whose environment variable is in effect is not written, because the form
|
|
229
|
+
* shows the environment value and saving it would copy that value into a setting that outlives
|
|
230
|
+
* the variable; null clears an overridable key, so the environment or the default applies again.
|
|
231
|
+
* Every other key is written as given. Drops the cache, so this process sees the change at once.
|
|
232
|
+
*
|
|
233
|
+
* @param {Object} data - key -> value, as settings.setMulti() takes it
|
|
234
|
+
* @returns {Promise<void>}
|
|
235
|
+
*/
|
|
236
|
+
async function writeOverridableSettings(data) {
|
|
237
|
+
const pinned = new Set(envOverriddenSettings().map(entry => entry.key));
|
|
238
|
+
const write = {};
|
|
239
|
+
const clear = [];
|
|
240
|
+
for (const [key, value] of Object.entries(data)) {
|
|
241
|
+
if (!isOverridableSetting(key)) {
|
|
242
|
+
write[key] = value;
|
|
243
|
+
} else if (pinned.has(key)) {
|
|
244
|
+
continue;
|
|
245
|
+
} else if (value === null || value === undefined) {
|
|
246
|
+
clear.push(key);
|
|
247
|
+
} else {
|
|
248
|
+
write[key] = value;
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
if (Object.keys(write).length) {
|
|
253
|
+
await settings.setMulti(write);
|
|
254
|
+
}
|
|
255
|
+
await settings.clear(...clear);
|
|
256
|
+
resetOverridableSettingsCache();
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/**
|
|
260
|
+
* Writes one overridable setting through the API, where null (or nothing) clears it, so the
|
|
261
|
+
* environment value or the default applies again. Unlike the settings forms, a key whose
|
|
262
|
+
* environment variable is set is still written when a client sends it: the request names the
|
|
263
|
+
* value, and the environment keeps winning while it is set.
|
|
264
|
+
* @param {string} key - A key of OVERRIDABLE_SETTINGS
|
|
265
|
+
* @param {*} value
|
|
266
|
+
* @returns {Promise<void>}
|
|
267
|
+
*/
|
|
268
|
+
async function storeOverridableSetting(key, value) {
|
|
269
|
+
if (value === null || value === undefined) {
|
|
270
|
+
await settings.clear(key);
|
|
271
|
+
} else {
|
|
272
|
+
await settings.set(key, value);
|
|
273
|
+
}
|
|
274
|
+
resetOverridableSettingsCache();
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
module.exports = {
|
|
278
|
+
OVERRIDABLE_SETTINGS,
|
|
279
|
+
isOverridableSetting,
|
|
280
|
+
envOrDefault,
|
|
281
|
+
storeOverridableSetting,
|
|
282
|
+
resolveOverridableSetting,
|
|
283
|
+
envOverriddenSettings,
|
|
284
|
+
getOverridableSettings,
|
|
285
|
+
getFailedJobRetention,
|
|
286
|
+
resetOverridableSettingsCache,
|
|
287
|
+
writeOverridableSettings
|
|
288
|
+
};
|