emailengine-app 2.84.2 → 2.86.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 (164) hide show
  1. package/.ncurc.js +29 -9
  2. package/.prettierignore +5 -1
  3. package/.prettierrc.js +2 -0
  4. package/.release-please-manifest.json +1 -1
  5. package/CHANGELOG.md +107 -0
  6. package/Dockerfile +20 -1
  7. package/ENVIRONMENT.md +139 -0
  8. package/README.md +2 -2
  9. package/bin/emailengine.js +434 -408
  10. package/config/default.toml +2 -0
  11. package/copy-static-files.sh +41 -14
  12. package/data/google-crawlers.json +1 -1
  13. package/data/public_suffix_list.dat +16563 -0
  14. package/eslint.config.js +81 -99
  15. package/lib/account-assignment.js +19 -0
  16. package/lib/account.js +230 -170
  17. package/lib/api-error-codes.js +49 -0
  18. package/lib/api-reference/format.js +4 -3
  19. package/lib/api-reference/model.js +6 -1
  20. package/lib/api-routes/account-routes.js +255 -38
  21. package/lib/api-routes/blocklist-routes.js +91 -4
  22. package/lib/api-routes/delivery-test-routes.js +27 -4
  23. package/lib/api-routes/export-routes.js +28 -2
  24. package/lib/api-routes/gateway-routes.js +110 -12
  25. package/lib/api-routes/index.js +4 -0
  26. package/lib/api-routes/license-routes.js +2 -2
  27. package/lib/api-routes/mailbox-routes.js +44 -5
  28. package/lib/api-routes/message-routes.js +112 -10
  29. package/lib/api-routes/oauth2-app-routes.js +63 -23
  30. package/lib/api-routes/outbox-routes.js +97 -52
  31. package/lib/api-routes/permission-map.js +67 -7
  32. package/lib/api-routes/scoped-routes.js +74 -0
  33. package/lib/api-routes/settings-routes.js +34 -6
  34. package/lib/api-routes/stats-routes.js +5 -1
  35. package/lib/api-routes/submit-routes.js +337 -309
  36. package/lib/api-routes/template-routes.js +45 -8
  37. package/lib/api-routes/token-routes.js +152 -100
  38. package/lib/api-routes/webhook-delivery-routes.js +262 -0
  39. package/lib/api-routes/webhook-route-routes.js +132 -6
  40. package/lib/bounce-detect.js +397 -205
  41. package/lib/calendar-event.js +81 -1
  42. package/lib/consts.js +38 -45
  43. package/lib/db.js +14 -6
  44. package/lib/delivery-error.js +6 -0
  45. package/lib/deprecations.js +270 -0
  46. package/lib/email-client/base-client.js +137 -184
  47. package/lib/email-client/fallback-poll.js +62 -0
  48. package/lib/email-client/gmail-client.js +60 -22
  49. package/lib/email-client/imap/adaptive-idle-store.js +73 -0
  50. package/lib/email-client/imap/adaptive-idle.js +278 -0
  51. package/lib/email-client/imap/connection-errors.js +14 -1
  52. package/lib/email-client/imap/idle-settings.js +31 -5
  53. package/lib/email-client/imap/listing-diff.js +37 -0
  54. package/lib/email-client/imap/mailbox.js +372 -242
  55. package/lib/email-client/imap/subconnection.js +8 -30
  56. package/lib/email-client/imap/sync-operations.js +220 -127
  57. package/lib/email-client/imap-client.js +228 -164
  58. package/lib/email-client/message-builder.js +14 -79
  59. package/lib/email-client/notification-handler.js +1 -2
  60. package/lib/email-client/outlook-client.js +372 -338
  61. package/lib/email-client/smtp-pool-manager.js +16 -13
  62. package/lib/email-client/sync-state-fields.js +19 -0
  63. package/lib/encrypt.js +157 -41
  64. package/lib/enum-descriptions.js +3 -1
  65. package/lib/env-setting-overrides.js +288 -0
  66. package/lib/export-worker.js +751 -0
  67. package/lib/export.js +64 -15
  68. package/lib/gateway.js +19 -4
  69. package/lib/get-raw-email.js +25 -107
  70. package/lib/hapi-request-logger.js +107 -0
  71. package/lib/health.js +75 -0
  72. package/lib/imapproxy/imap-core/README.md +6 -5
  73. package/lib/lock-run.js +119 -0
  74. package/lib/logger-consts.js +48 -0
  75. package/lib/logger.js +1 -1
  76. package/lib/lua/z-head-scores.lua +28 -0
  77. package/lib/mcp/tools.js +37 -8
  78. package/lib/network-errors.js +1 -1
  79. package/lib/node-version.js +24 -0
  80. package/lib/notify-attachments.js +36 -0
  81. package/lib/oauth/outlook-mailbox.js +35 -0
  82. package/lib/oauth/state.js +24 -0
  83. package/lib/oauth2-apps.js +631 -656
  84. package/lib/outbox.js +184 -54
  85. package/lib/parse-message.js +3 -3
  86. package/lib/pbkdf2-phc.js +1 -1
  87. package/lib/privileged-settings.js +2 -2
  88. package/lib/queue-browser/definitions.js +11 -0
  89. package/lib/queue-browser/index.js +68 -19
  90. package/lib/queue-job-actions.js +18 -1
  91. package/lib/queue-retention.js +48 -12
  92. package/lib/queue-stats.js +11 -2
  93. package/lib/read-env-value.js +3 -0
  94. package/lib/redis-memory-warnings.js +99 -0
  95. package/lib/redis-reconnect.js +29 -0
  96. package/lib/request-timing.js +23 -0
  97. package/lib/respawn-backoff.js +35 -0
  98. package/lib/rewrite-text-nodes.js +19 -59
  99. package/lib/schemas.js +164 -40
  100. package/lib/settings.js +6 -2
  101. package/lib/smtp-auth.js +19 -1
  102. package/lib/sso.js +1 -1
  103. package/lib/swagger-options.js +1 -1
  104. package/lib/thread-diagnostics.js +63 -0
  105. package/lib/timezones.js +109 -0
  106. package/lib/tls/provision.js +6 -3
  107. package/lib/token-audit-log.js +19 -20
  108. package/lib/token-permission-view.js +7 -6
  109. package/lib/tools.js +48 -51
  110. package/lib/totp.js +2 -5
  111. package/lib/translations.js +1 -2
  112. package/lib/ui-routes/account-routes.js +475 -454
  113. package/lib/ui-routes/account-setup.js +99 -0
  114. package/lib/ui-routes/admin-config-routes.js +152 -100
  115. package/lib/ui-routes/admin-entities-routes.js +93 -21
  116. package/lib/ui-routes/auth-routes.js +90 -38
  117. package/lib/ui-routes/imap-idle-field.js +1 -1
  118. package/lib/ui-routes/internals-routes.js +5 -0
  119. package/lib/ui-routes/oauth-config-routes.js +124 -82
  120. package/lib/ui-routes/outlook-subscription-view.js +1 -1
  121. package/lib/ui-routes/overridable-fields.js +84 -0
  122. package/lib/ui-routes/queue-routes.js +8 -5
  123. package/lib/ui-routes/route-helpers.js +19 -3
  124. package/lib/ui-routes/settings-page.js +6 -0
  125. package/lib/ui-routes/tls-config-routes.js +58 -15
  126. package/lib/utils/back-off.js +82 -0
  127. package/lib/utils/decode-headers.js +3 -12
  128. package/lib/utils/filter-empty.js +20 -0
  129. package/lib/utils/int-setting.js +48 -0
  130. package/lib/utils/murmurhash3.js +66 -0
  131. package/lib/utils/public-suffix.js +122 -0
  132. package/lib/utils/random-id.js +26 -0
  133. package/lib/utils/tracking-settings.js +35 -0
  134. package/lib/utils/version.js +74 -0
  135. package/lib/web-safe-html.js +18 -105
  136. package/lib/webhook-delivery.js +461 -0
  137. package/lib/webhook-failures.js +132 -0
  138. package/lib/webhook-request.js +29 -1
  139. package/lib/webhook-routing.js +56 -0
  140. package/lib/webhook-test.js +88 -0
  141. package/lib/webhooks.js +93 -45
  142. package/lib/worker-rpc-error.js +2 -1
  143. package/package.json +37 -38
  144. package/sbom.json +7902 -1
  145. package/server.js +784 -518
  146. package/static/js/ace/ace.js +1 -1
  147. package/static/licenses.html +225 -1060
  148. package/translations/messages.pot +62 -63
  149. package/views/config/ai.hbs +1 -1
  150. package/views/config/security.hbs +24 -2
  151. package/views/config/service.hbs +47 -0
  152. package/views/config/webhooks.hbs +36 -0
  153. package/views/internals/index.hbs +8 -0
  154. package/views/partials/queue_retention_note.hbs +12 -8
  155. package/views/partials/ui/env-managed-alert.hbs +16 -7
  156. package/views/partials/webhook_form.hbs +1 -1
  157. package/views/suppression-lists/index.hbs +1 -1
  158. package/workers/api.js +840 -611
  159. package/workers/export.js +17 -632
  160. package/workers/imap.js +13 -0
  161. package/workers/smtp.js +9 -11
  162. package/workers/submit.js +1 -1
  163. package/workers/webhooks.js +18 -448
  164. 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
- SMTP_POOLS.delete(poolKey);
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
- SMTP_POOLS.delete(poolKey);
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. Reads nodemailer's
144
- * pool internals: isIdle() turns true while a message is still on the wire
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
- if (!pool) {
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
- // 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');
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
- let cachedKey = saltCache(scheme, password, salt);
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(scheme, password, salt, key); // update cache
183
+ saltCache(cacheKey, salt, key); // update cache
175
184
  return key;
176
185
  }
177
186
 
178
- function decrypt(encryptedData, secret) {
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
- switch (decryptData.format) {
188
- case 'cleartext':
189
- return raw;
260
+ return { decryptData };
261
+ }
190
262
 
191
- case WD_ENCRYPTION_SCHEME_KEY_1:
192
- case WD_ENCRYPTION_SCHEME_KEY_2:
193
- try {
194
- assert.strictEqual(decryptData.authTag.length, 16, 'Invalid auth tag length');
195
- assert.strictEqual(decryptData.iv.length, IV_LENGTH, 'Invalid iv length');
196
- assert.strictEqual(decryptData.salt.length, SALT_LENGTH, 'Invalid salt length');
197
- assert.strictEqual(decryptData.cipher, WD_CIPHER_1, 'Unsupported cipher');
198
-
199
- // convert password to 32B key, the way the value's scheme says
200
- const key = getKeyFromPassword(decryptData.format, secret, decryptData.salt);
201
-
202
- const decipher = crypto.createDecipheriv(decryptData.cipher, key, decryptData.iv, {
203
- authTagLength: decryptData.authTag.length
204
- });
205
- decipher.setAuthTag(decryptData.authTag);
206
-
207
- // try to decipher
208
- return Buffer.concat([decipher.update(decryptData.data), decipher.final()]).toString('utf-8');
209
- } catch (E) {
210
- let err = new Error('Failed to decrypt data. ' + E.message);
211
- err.responseCode = 500;
212
- err.code = 'InternalConfigError';
213
- throw err;
214
- }
215
-
216
- default: {
217
- // assume cleartext
218
- return raw;
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 = { encrypt, decrypt, encryptField, decryptField, parseEncryptedData, isCurrentScheme, reencrypt, PBKDF2_ITERATIONS, PBKDF2_DIGEST };
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
+ };
@@ -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
+ };