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.
Files changed (137) hide show
  1. package/.ncurc.js +24 -6
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +97 -0
  4. package/DOCKER_DEPLOYMENT.md +2 -1
  5. package/Dockerfile +16 -3
  6. package/ENVIRONMENT.md +139 -0
  7. package/README.md +5 -1
  8. package/config/default.toml +2 -0
  9. package/copy-static-files.sh +4 -2
  10. package/data/google-crawlers.json +1 -1
  11. package/data/public_suffix_list.dat +4 -3
  12. package/lib/account-assignment.js +19 -0
  13. package/lib/account.js +285 -195
  14. package/lib/api-error-codes.js +49 -0
  15. package/lib/api-reference/model.js +6 -1
  16. package/lib/api-routes/account-routes.js +91 -32
  17. package/lib/api-routes/blocklist-routes.js +68 -2
  18. package/lib/api-routes/delivery-test-routes.js +1 -1
  19. package/lib/api-routes/gateway-routes.js +82 -10
  20. package/lib/api-routes/index.js +4 -0
  21. package/lib/api-routes/license-routes.js +2 -2
  22. package/lib/api-routes/mailbox-routes.js +3 -3
  23. package/lib/api-routes/message-routes.js +15 -7
  24. package/lib/api-routes/oauth2-app-routes.js +15 -8
  25. package/lib/api-routes/outbox-routes.js +77 -66
  26. package/lib/api-routes/permission-map.js +55 -6
  27. package/lib/api-routes/scoped-routes.js +74 -0
  28. package/lib/api-routes/settings-routes.js +11 -4
  29. package/lib/api-routes/stats-routes.js +5 -1
  30. package/lib/api-routes/submit-routes.js +25 -5
  31. package/lib/api-routes/template-routes.js +7 -6
  32. package/lib/api-routes/token-routes.js +11 -5
  33. package/lib/api-routes/webhook-delivery-routes.js +262 -0
  34. package/lib/api-routes/webhook-route-routes.js +119 -4
  35. package/lib/calendar-event.js +81 -1
  36. package/lib/consts.js +38 -46
  37. package/lib/db.js +14 -6
  38. package/lib/delivery-error.js +6 -0
  39. package/lib/deprecations.js +270 -0
  40. package/lib/email-client/base-client.js +134 -158
  41. package/lib/email-client/fallback-poll.js +62 -0
  42. package/lib/email-client/gmail-client.js +59 -11
  43. package/lib/email-client/imap/adaptive-idle-store.js +73 -0
  44. package/lib/email-client/imap/adaptive-idle.js +278 -0
  45. package/lib/email-client/imap/connection-errors.js +14 -1
  46. package/lib/email-client/imap/idle-settings.js +31 -5
  47. package/lib/email-client/imap/listing-diff.js +37 -0
  48. package/lib/email-client/imap/mailbox.js +380 -227
  49. package/lib/email-client/imap/subconnection.js +7 -29
  50. package/lib/email-client/imap/sync-operations.js +220 -127
  51. package/lib/email-client/imap-client.js +227 -163
  52. package/lib/email-client/message-builder.js +14 -79
  53. package/lib/email-client/outlook-client.js +378 -338
  54. package/lib/email-client/smtp-pool-manager.js +16 -13
  55. package/lib/email-client/sync-state-fields.js +19 -0
  56. package/lib/encrypt.js +157 -41
  57. package/lib/enum-descriptions.js +3 -1
  58. package/lib/env-setting-overrides.js +288 -0
  59. package/lib/export-worker.js +751 -0
  60. package/lib/export.js +64 -15
  61. package/lib/field-usage.js +1 -1
  62. package/lib/gateway.js +17 -1
  63. package/lib/get-raw-email.js +35 -108
  64. package/lib/health.js +75 -0
  65. package/lib/lock-run.js +119 -0
  66. package/lib/logger-consts.js +48 -0
  67. package/lib/logger.js +1 -1
  68. package/lib/lua/z-head-scores.lua +28 -0
  69. package/lib/network-errors.js +1 -1
  70. package/lib/node-version.js +24 -0
  71. package/lib/notify-attachments.js +20 -1
  72. package/lib/oauth/gmail.js +54 -29
  73. package/lib/oauth2-apps.js +630 -655
  74. package/lib/otp.js +66 -0
  75. package/lib/outbox.js +184 -54
  76. package/lib/parse-message.js +3 -3
  77. package/lib/privileged-settings.js +2 -2
  78. package/lib/queue-browser/definitions.js +11 -0
  79. package/lib/queue-browser/index.js +68 -19
  80. package/lib/queue-job-actions.js +18 -1
  81. package/lib/queue-retention.js +48 -12
  82. package/lib/queue-stats.js +11 -2
  83. package/lib/read-env-value.js +3 -0
  84. package/lib/redis-memory-warnings.js +99 -0
  85. package/lib/redis-reconnect.js +29 -0
  86. package/lib/request-timing.js +23 -0
  87. package/lib/respawn-backoff.js +35 -0
  88. package/lib/rewrite-text-nodes.js +19 -59
  89. package/lib/schemas.js +225 -41
  90. package/lib/settings.js +6 -2
  91. package/lib/smtp-auth.js +19 -1
  92. package/lib/swagger-options.js +2 -2
  93. package/lib/thread-diagnostics.js +18 -1
  94. package/lib/tls/provision.js +6 -3
  95. package/lib/token-audit-log.js +19 -20
  96. package/lib/token-permission-view.js +4 -3
  97. package/lib/tools.js +8 -41
  98. package/lib/ui-routes/admin-config-routes.js +64 -90
  99. package/lib/ui-routes/admin-entities-routes.js +2 -14
  100. package/lib/ui-routes/imap-idle-field.js +1 -1
  101. package/lib/ui-routes/outlook-subscription-view.js +1 -1
  102. package/lib/ui-routes/overridable-fields.js +84 -0
  103. package/lib/ui-routes/queue-routes.js +8 -5
  104. package/lib/ui-routes/settings-page.js +6 -0
  105. package/lib/utils/decode-headers.js +3 -12
  106. package/lib/utils/filter-empty.js +20 -0
  107. package/lib/utils/int-setting.js +48 -0
  108. package/lib/utils/tracking-settings.js +35 -0
  109. package/lib/web-safe-html.js +18 -105
  110. package/lib/webhook-delivery.js +461 -0
  111. package/lib/webhook-failures.js +132 -0
  112. package/lib/webhook-request.js +29 -1
  113. package/lib/webhook-routing.js +30 -1
  114. package/lib/webhook-test.js +88 -0
  115. package/lib/webhooks.js +59 -41
  116. package/lib/worker-rpc-error.js +2 -1
  117. package/package.json +28 -26
  118. package/sbom.json +600 -678
  119. package/server.js +149 -76
  120. package/static/css/flyonui.css +1 -1
  121. package/static/js/ace/ace.js +1 -1
  122. package/static/js/ee-client.js +650 -196
  123. package/static/licenses.html +49 -59
  124. package/translations/messages.pot +26 -26
  125. package/views/config/security.hbs +22 -0
  126. package/views/config/service.hbs +44 -0
  127. package/views/config/webhooks.hbs +36 -0
  128. package/views/layout/app.hbs +9 -6
  129. package/views/legal.hbs +8 -0
  130. package/views/partials/queue_retention_note.hbs +12 -8
  131. package/views/partials/ui/env-managed-alert.hbs +16 -7
  132. package/workers/api.js +112 -37
  133. package/workers/export.js +16 -631
  134. package/workers/imap.js +13 -0
  135. package/workers/smtp.js +9 -11
  136. package/workers/webhooks.js +18 -432
  137. package/lib/email-client/outlook-fallback-poll.js +0 -30
package/lib/otp.js ADDED
@@ -0,0 +1,66 @@
1
+ 'use strict';
2
+
3
+ // One-time passcodes from the OTP-Token header (draft-goto-otp-token), see "One-time passcodes"
4
+ // in CLAUDE.md. mailparser applies the draft's parsing rules; the header itself is not
5
+ // authenticated, so the code is reported together with whether the receiving server vouches for
6
+ // its origin.
7
+
8
+ const { parseOtpToken } = require('mailparser');
9
+ const { parseAuthenticationResults, isTrustedAuthservId } = require('@postalsys/email-ai-tools/lib/authentication.js');
10
+ const { authenticationTrust } = require('./llm-pre-process');
11
+ const { getRegistrableDomain } = require('./utils/public-suffix');
12
+
13
+ // What the fetch paths ask for besides the configured headers when messageNew carries otp: the
14
+ // header itself, and what authenticationTrust() reads (Received for a Microsoft mailbox)
15
+ const OTP_FETCH_HEADERS = ['otp-token', 'authentication-results', 'received'];
16
+
17
+ /**
18
+ * Tells whether the receiving server recorded a passing DKIM signature aligned with the origin:
19
+ * from the same organizational domain, the way DMARC's relaxed alignment compares domains. Only
20
+ * the topmost Authentication-Results header counts, written by a server authenticationTrust() names
21
+ *
22
+ * @param {string} origin - The origin the code is bound to, as parseOtpToken() returns it
23
+ * @param {Object} headers - The message headers, lower-case names to value lists
24
+ * @param {string|null} provider - As summaryProvider() names it
25
+ * @returns {boolean}
26
+ */
27
+ function isAuthenticatedOrigin(origin, headers, provider) {
28
+ const trust = authenticationTrust(provider, headers);
29
+ const parsed = parseAuthenticationResults([].concat(headers['authentication-results'] || [])[0]);
30
+ if (!parsed || !parsed.dkimDomains.length || !isTrustedAuthservId(parsed.authservId, trust.trustedAuthservIds, trust.acceptUnnamedAuthentication)) {
31
+ return false;
32
+ }
33
+
34
+ // an IP address, a loopback name or a public suffix has no organizational domain to match
35
+ const originDomain = getRegistrableDomain(new URL(origin).hostname);
36
+ return !!originDomain && parsed.dkimDomains.some(domain => getRegistrableDomain(domain) === originDomain);
37
+ }
38
+
39
+ /**
40
+ * The one-time passcode of a message, from its OTP-Token header
41
+ *
42
+ * @param {Object} [headers] - The message headers, lower-case names to value lists
43
+ * @param {string|null} provider - As summaryProvider() names it, decides which Authentication-Results header counts
44
+ * @returns {{code: string, origin: string, authenticated: boolean}|undefined}
45
+ */
46
+ function getMessageOtp(headers, provider) {
47
+ const otp = headers && headers['otp-token'] && parseOtpToken([].concat(headers['otp-token']));
48
+ if (!otp) {
49
+ return undefined;
50
+ }
51
+
52
+ return { code: otp.code, origin: otp.origin, authenticated: isAuthenticatedOrigin(otp.origin, headers, provider) };
53
+ }
54
+
55
+ /**
56
+ * Tells whether the notifyHeaders setting asks for the OTP-Token header, the only case the
57
+ * messageNew payload carries the otp field
58
+ *
59
+ * @param {string[]} [notifyHeaders] - The notifyHeaders setting
60
+ * @returns {boolean}
61
+ */
62
+ function notifyHeadersIncludeOtp(notifyHeaders) {
63
+ return [].concat(notifyHeaders || []).some(header => header === '*' || String(header).toLowerCase() === 'otp-token');
64
+ }
65
+
66
+ module.exports = { getMessageOtp, notifyHeadersIncludeOtp, OTP_FETCH_HEADERS };
package/lib/outbox.js CHANGED
@@ -4,17 +4,10 @@ const { submitQueue, redis } = require('./db');
4
4
  const { REDIS_PREFIX } = require('../lib/consts');
5
5
  const msgpack = require('./msgpack');
6
6
  const { nextAttemptOfStoredJob } = require('./delivery-error');
7
- const { readEnvValue } = require('./read-env-value');
8
- const { getByteSize } = require('./tools');
9
7
  const { statusError } = require('./utils/status-error');
10
- const { retryFailedJob, promoteDelayedJob, assertJobState } = require('./queue-job-actions');
11
- const {
12
- selectFailedContentToDrop,
13
- FAILED_JOB_RETENTION_AGE,
14
- FAILED_JOB_RETENTION_COUNT,
15
- DEFAULT_FAILED_CONTENT_RETENTION_COUNT,
16
- DEFAULT_FAILED_CONTENT_RETENTION_SIZE
17
- } = require('./queue-retention');
8
+ const { retryFailedJob, promoteDelayedJob, assertJobState, getAccountJob } = require('./queue-job-actions');
9
+ const { selectFailedContentToDrop } = require('./queue-retention');
10
+ const { getOverridableSettings } = require('./env-setting-overrides');
18
11
 
19
12
  // Job reads and removals are issued in bounded batches. ioredis writes each command as it is
20
13
  // issued, so a batch costs one round trip rather than one per job, while the bound keeps an account
@@ -45,33 +38,26 @@ function retainedField(account, queueId) {
45
38
  }
46
39
 
47
40
  /**
48
- * An environment bound, with `0` meaning "none" rather than "the default".
41
+ * How much failed content is kept. Setting either count or size to 0 keeps none, which is the
42
+ * behavior before retries existed: the content went the moment the last attempt failed. The
43
+ * count is capped at the failed-job retention count and the age is the failed-job age, so
44
+ * BullMQ's own `removeOnFail` policy never removes a job before its content is dropped here -
45
+ * the record of a failure always outlives the content it would need to retry.
49
46
  *
50
- * @param {string} key - Environment variable
51
- * @param {Function} parse - Parser for a value that is set
52
- * @param {number} defaultValue - Used when the variable is unset or unparsable
53
- * @returns {number}
47
+ * Each bound is a setting as well as an environment variable, the environment winning (see
48
+ * lib/env-setting-overrides.js), so the limits are read per call rather than fixed at load.
49
+ *
50
+ * @returns {Promise<{maxCount: number, maxBytes: number, maxAge: number}>} maxAge in seconds
54
51
  */
55
- function envBound(key, parse, defaultValue) {
56
- const raw = readEnvValue(key);
57
- if (raw === undefined || raw === null || raw === '') {
58
- return defaultValue;
59
- }
60
- const value = parse(raw);
61
- return typeof value === 'number' && value >= 0 && !isNaN(value) ? value : defaultValue;
52
+ async function getFailedContentLimits() {
53
+ const values = await getOverridableSettings('queueKeepFailedContent', 'queueKeepFailedContentSize', 'queueKeepFailed', 'queueKeepFailedAge');
54
+ return {
55
+ maxCount: Math.min(values.queueKeepFailedContent, values.queueKeepFailed),
56
+ maxBytes: values.queueKeepFailedContentSize,
57
+ maxAge: values.queueKeepFailedAge
58
+ };
62
59
  }
63
60
 
64
- // How much failed content is kept. Setting either count or size to 0 keeps none, which is the
65
- // behavior before retries existed: the content went the moment the last attempt failed. The
66
- // count is capped at the failed-job retention count and the age is the failed-job age, so
67
- // BullMQ's own `removeOnFail` policy never removes a job before its content is dropped here -
68
- // the record of a failure always outlives the content it would need to retry.
69
- const FAILED_CONTENT_LIMITS = {
70
- maxCount: Math.min(envBound('EENGINE_QUEUE_KEEP_FAILED_CONTENT', Number, DEFAULT_FAILED_CONTENT_RETENTION_COUNT), FAILED_JOB_RETENTION_COUNT),
71
- maxBytes: envBound('EENGINE_QUEUE_KEEP_FAILED_CONTENT_SIZE', getByteSize, DEFAULT_FAILED_CONTENT_RETENTION_SIZE),
72
- maxAge: FAILED_JOB_RETENTION_AGE
73
- };
74
-
75
61
  /**
76
62
  * Decodes a message stored in an account's outbox hash.
77
63
  *
@@ -158,20 +144,135 @@ function selectPageRanges(jobStates, jobCounts, start, pageSize) {
158
144
  return ranges;
159
145
  }
160
146
 
147
+ /**
148
+ * Loads jobs by ID in bounded batches, skipping the ones that are gone or cannot be read.
149
+ *
150
+ * @param {string[]} jobIds - Job IDs
151
+ * @param {Object} logger - Logger instance
152
+ * @returns {Promise<Object[]>} The jobs that exist
153
+ */
154
+ async function loadJobs(jobIds, logger) {
155
+ let jobs = [];
156
+ for (let i = 0; i < jobIds.length; i += BATCH_SIZE) {
157
+ let batch = await Promise.all(
158
+ jobIds.slice(i, i + BATCH_SIZE).map(async jobId => {
159
+ try {
160
+ return await submitQueue.getJob(jobId);
161
+ } catch (err) {
162
+ logger.error({ msg: 'Failed to retrieve message info from outbox', jobId, err });
163
+ return null;
164
+ }
165
+ })
166
+ );
167
+ jobs.push(...batch.filter(Boolean));
168
+ }
169
+ return jobs;
170
+ }
171
+
172
+ /**
173
+ * The outbox of one account. The submit queue has no index by account, but the account's outbox
174
+ * hash does: every message waiting to be sent has its content there under its queue ID, and so
175
+ * does a failed message whose content is retained for a retry. So the listing reads the queue IDs
176
+ * from that hash rather than scanning the whole queue, and costs what that account has queued.
177
+ * A failed message whose content is already gone cannot be retried and is not listed here; the
178
+ * instance-wide listing still shows it.
179
+ *
180
+ * @param {Object} options
181
+ * @param {string} options.account - Account ID
182
+ * @param {string[]} options.states - Job states to include
183
+ * @param {number} options.page - Zero-based page
184
+ * @param {number} options.pageSize - Entries per page
185
+ * @param {Object} options.logger - Logger instance
186
+ * @returns {Promise<Object>} `{ total, page, pages, messages }`
187
+ */
188
+ async function listAccount(options) {
189
+ let { account, states, page, pageSize, logger } = options;
190
+
191
+ let queueIds = await redis.hkeys(outboxKey(account));
192
+
193
+ // State, creation time and owner of every queued message in batches, the full jobs for the page
194
+ // shown only: an account with thousands of scheduled messages used to cost a job read and a
195
+ // state read for each of them on every page
196
+ let entries = [];
197
+ for (let i = 0; i < queueIds.length; i += BATCH_SIZE) {
198
+ const batch = queueIds.slice(i, i + BATCH_SIZE);
199
+ const [jobStates, fields] = await Promise.all([
200
+ Promise.all(batch.map(queueId => submitQueue.getJobState(queueId))),
201
+ Promise.all(batch.map(queueId => redis.hmget(submitQueue.toKey(queueId), 'timestamp', 'data')))
202
+ ]);
203
+ batch.forEach((queueId, j) => {
204
+ const [timestamp, data] = fields[j] || [];
205
+ if (!states.includes(jobStates[j]) || !data || jobAccount(data) !== account) {
206
+ return;
207
+ }
208
+ entries.push({ queueId, state: jobStates[j], timestamp: Number(timestamp) || 0 });
209
+ });
210
+ }
211
+
212
+ // The same order as the instance-wide listing: by state, then oldest first
213
+ entries.sort((a, b) => states.indexOf(a.state) - states.indexOf(b.state) || a.timestamp - b.timestamp);
214
+
215
+ const pageEntries = entries.slice(page * pageSize, (page + 1) * pageSize);
216
+ const jobs = new Map(
217
+ (
218
+ await loadJobs(
219
+ pageEntries.map(entry => entry.queueId),
220
+ logger
221
+ )
222
+ ).map(job => [job.id, job])
223
+ );
224
+
225
+ return {
226
+ total: entries.length,
227
+ page,
228
+ pages: Math.ceil(entries.length / pageSize),
229
+ messages: pageEntries.filter(entry => jobs.has(entry.queueId)).map(entry => formatQueueEntry(jobs.get(entry.queueId), entry.state))
230
+ };
231
+ }
232
+
233
+ /**
234
+ * The account a stored submit job's data names
235
+ * @param {string} data - The job hash's data field
236
+ * @returns {string|null}
237
+ */
238
+ function jobAccount(data) {
239
+ try {
240
+ return JSON.parse(data).account || null;
241
+ } catch (err) {
242
+ return null;
243
+ }
244
+ }
245
+
246
+ /**
247
+ * One page of the outbox, optionally narrowed to one account and to one state.
248
+ *
249
+ * @param {Object} options
250
+ * @param {number} [options.page] - Zero-based page
251
+ * @param {number} [options.pageSize] - Entries per page
252
+ * @param {string} [options.account] - Only this account's messages
253
+ * @param {string} [options.state] - Only messages in this state, one of JOB_STATES
254
+ * @param {Object} options.logger - Logger instance
255
+ * @returns {Promise<Object>} `{ total, page, pages, messages }`
256
+ */
161
257
  async function list(options) {
162
258
  options = options || {};
163
259
  let page = Number(options.page) || 0;
164
260
  let pageSize = Number(options.pageSize) || 20;
165
261
  let logger = options.logger;
262
+ let states = options.state ? JOB_STATES.filter(state => state === options.state) : JOB_STATES;
166
263
 
167
- let jobCounts = await submitQueue.getJobCounts(...JOB_STATES);
264
+ if (options.account) {
265
+ return await listAccount({ account: options.account, states, page, pageSize, logger });
266
+ }
267
+
268
+ let jobCounts = await submitQueue.getJobCounts(...states);
168
269
 
169
- let totalJobs = JOB_STATES.map(state => Number(jobCounts[state]) || 0).reduce((previousValue, currentValue) => previousValue + currentValue);
270
+ let totalJobs = states.map(state => Number(jobCounts[state]) || 0).reduce((previousValue, currentValue) => previousValue + currentValue, 0);
170
271
 
171
272
  // The counts above and the ranges below are separate reads, so a job that changes state in
172
273
  // between can be listed twice or missed. That is inherent to paging a live queue without
173
274
  // locking it, and the next request reflects the queue as it then stands.
174
- let ranges = selectPageRanges(JOB_STATES, jobCounts, page * pageSize, pageSize);
275
+ let ranges = selectPageRanges(states, jobCounts, page * pageSize, pageSize);
175
276
 
176
277
  let idsPerRange = await Promise.all(ranges.map(range => submitQueue.getRanges([range.state], range.start, range.end, true)));
177
278
  // Each ID is read from a known state's list, which is what the entry reports as its state -
@@ -219,11 +320,7 @@ async function del(options) {
219
320
 
220
321
  let logger = options.logger;
221
322
 
222
- if (!options.queueId) {
223
- return { deleted: false };
224
- }
225
-
226
- let job = await submitQueue.getJob(options.queueId);
323
+ let job = await getAccountJob(submitQueue, options.queueId, options.account);
227
324
  if (!job) {
228
325
  return { deleted: false };
229
326
  }
@@ -267,11 +364,7 @@ async function get(options) {
267
364
 
268
365
  let logger = options.logger;
269
366
 
270
- if (!options.queueId) {
271
- return false;
272
- }
273
-
274
- let job = await submitQueue.getJob(options.queueId);
367
+ let job = await getAccountJob(submitQueue, options.queueId, options.account);
275
368
  if (!job) {
276
369
  return false;
277
370
  }
@@ -418,7 +511,7 @@ async function dropFailedContent(entries, options) {
418
511
  * Keeps the content of a message whose delivery just failed for good, so it can be retried.
419
512
  *
420
513
  * Called from the submit worker's `failed` handler in place of the deletion it used to do. The
421
- * bounds in FAILED_CONTENT_LIMITS are applied on every call, so the set never holds more than
514
+ * bounds from getFailedContentLimits() are applied on every call, so the set never holds more than
422
515
  * `maxCount` entries or `maxBytes` of content: whatever has to go to make room for this one goes
423
516
  * now, oldest first, and this one itself goes at once when it does not fit (a message larger than
424
517
  * the whole size bound, or a bound of zero).
@@ -457,7 +550,7 @@ async function retainFailedContent(options) {
457
550
  }
458
551
  }
459
552
 
460
- const drop = selectFailedContentToDrop(entries, FAILED_CONTENT_LIMITS);
553
+ const drop = selectFailedContentToDrop(entries, await getFailedContentLimits());
461
554
  await dropFailedContent(drop, { logger });
462
555
 
463
556
  return !drop.some(entry => entry.field === field);
@@ -501,7 +594,7 @@ async function pruneFailedContent(options) {
501
594
  const dropping = new Map(entries.filter(entry => entry.unreadable).map(entry => [entry.field, entry]));
502
595
  for (const entry of selectFailedContentToDrop(
503
596
  entries.filter(entry => !entry.unreadable),
504
- FAILED_CONTENT_LIMITS
597
+ await getFailedContentLimits()
505
598
  )) {
506
599
  dropping.set(entry.field, entry);
507
600
  }
@@ -552,9 +645,9 @@ async function pruneFailedContent(options) {
552
645
  * @throws {Error} With `statusCode` 409 and a `code` naming why the message cannot be retried
553
646
  */
554
647
  async function retry(options) {
555
- const { queueId, logger } = options;
648
+ const { queueId, account, logger } = options;
556
649
 
557
- const job = await submitQueue.getJob(queueId);
650
+ const job = await getAccountJob(submitQueue, queueId, account);
558
651
  if (!job) {
559
652
  return false;
560
653
  }
@@ -584,9 +677,9 @@ async function retry(options) {
584
677
  * @throws {Error} With `statusCode` 409 and `code` NotDelayed when the message is not waiting for a time
585
678
  */
586
679
  async function promote(options) {
587
- const { queueId, logger } = options;
680
+ const { queueId, account, logger } = options;
588
681
 
589
- const job = await submitQueue.getJob(queueId);
682
+ const job = await getAccountJob(submitQueue, queueId, account);
590
683
  if (!job) {
591
684
  return false;
592
685
  }
@@ -599,9 +692,46 @@ async function promote(options) {
599
692
  return { promoted: true, queueId: job.id, messageId: job.data.messageId };
600
693
  }
601
694
 
695
+ /**
696
+ * Queues a message for delivery: stores its content in the account's outbox hash, then adds the
697
+ * submit job that points to it. The two halves are written here together, like every other outbox
698
+ * action: a failed add used to leave the content behind with no job referring to it, and nothing
699
+ * sweeps such content up, so it is removed again before the failure is passed on.
700
+ *
701
+ * The client and the queue are the caller's, so a client built for a test or another Redis keeps
702
+ * using its own.
703
+ *
704
+ * @param {Object} options
705
+ * @param {Object} options.redis - ioredis client
706
+ * @param {Object} options.queue - The submit queue
707
+ * @param {string} options.account - Account ID
708
+ * @param {string} options.queueId - Queue ID, also the job ID
709
+ * @param {Buffer} options.content - Encoded queue entry
710
+ * @param {string} options.name - Job name ('queued' or 'delayed')
711
+ * @param {Object} options.data - Job data
712
+ * @param {Object} options.opts - Job options
713
+ * @param {Object} options.logger - Logger
714
+ * @returns {Promise<Object>} The BullMQ job
715
+ */
716
+ async function enqueue({ redis: client, queue, account, queueId, content, name, data, opts, logger }) {
717
+ const key = outboxKey(account);
718
+ await client.hsetBuffer(key, queueId, content);
719
+ try {
720
+ return await queue.add(name, data, opts);
721
+ } catch (err) {
722
+ try {
723
+ await client.hdel(key, queueId);
724
+ } catch (cleanupErr) {
725
+ logger.error({ msg: 'Failed to remove the content of a message that could not be queued', account, queueId, err: cleanupErr });
726
+ }
727
+ throw err;
728
+ }
729
+ }
730
+
602
731
  // selectPageRanges and JOB_STATES are exported for the pagination tests: exercising the arithmetic
603
732
  // through list() alone would need a queue populated across all four states to cover the cases.
604
733
  module.exports = {
734
+ enqueue,
605
735
  list,
606
736
  del,
607
737
  get,
@@ -616,5 +746,5 @@ module.exports = {
616
746
  outboxKey,
617
747
  JOB_STATES,
618
748
  FAILED_CONTENT_KEY,
619
- FAILED_CONTENT_LIMITS
749
+ getFailedContentLimits
620
750
  };
@@ -4,8 +4,8 @@
4
4
  // is set once. test/fips-guardrail-test.js refuses a simpleParser() call anywhere else.
5
5
  //
6
6
  // checksumAlgo: mailparser hashes every attachment, with MD5 unless told otherwise, and an OpenSSL
7
- // FIPS provider refuses MD5. Nothing in EmailEngine reads the checksum, so the algorithm only has
8
- // to exist on every host.
7
+ // FIPS provider refuses MD5. Nothing in EmailEngine reads the checksum, so it is switched off
8
+ // (mailparser 3.11.0), which also saves hashing every attachment of every parsed message.
9
9
 
10
10
  const { simpleParser } = require('mailparser');
11
11
 
@@ -15,7 +15,7 @@ const { simpleParser } = require('mailparser');
15
15
  * @returns {Promise<Object>} The parsed message
16
16
  */
17
17
  function parseMessage(input, options) {
18
- return simpleParser(input, { checksumAlgo: 'sha256', ...options });
18
+ return simpleParser(input, { checksumAlgo: false, ...options });
19
19
  }
20
20
 
21
21
  module.exports = { parseMessage };
@@ -114,9 +114,9 @@ const PRIVILEGED_SETTINGS_GROUPS = [
114
114
  },
115
115
  {
116
116
  // A credential must not change the door it came through, enable credential issuance, or
117
- // switch off its own audit trail
117
+ // switch off its own audit trail - nor shrink that trail until its own requests fall off it
118
118
  label: 'the MCP and audit switches',
119
- keys: ['mcpEnabled', 'mcpOAuthEnabled', 'tokenAuditLog']
119
+ keys: ['mcpEnabled', 'mcpOAuthEnabled', 'tokenAuditLog', 'tokenLogEntries', 'tokenLogAge']
120
120
  },
121
121
  {
122
122
  // The error reporting target
@@ -7,6 +7,8 @@
7
7
  // The job states a queue is browsed by, in the order the tabs show them. BullMQ 6 has no `paused`
8
8
  // state (a paused queue holds its jobs in `waiting`), and `prioritized` and `waiting-children`
9
9
  // are never used here, so they are not offered.
10
+ const { BULL_BOARD_REDIRECTS_DEPRECATED_AT } = require('../deprecations');
11
+
10
12
  const STATES = [
11
13
  {
12
14
  name: 'waiting',
@@ -119,7 +121,16 @@ const SCAN_LIMIT = 500;
119
121
  // Jobs read per round trip while listing or scanning
120
122
  const BATCH_SIZE = 50;
121
123
 
124
+ // The retired /admin/bull-board URLs redirect to the queue browser, and are deprecated: the
125
+ // plugins.deprecation block of those routes (lib/deprecations.js)
126
+ const BULL_BOARD_DEPRECATION = {
127
+ since: BULL_BOARD_REDIRECTS_DEPRECATED_AT,
128
+ successor: 'GET /admin/queues',
129
+ link: '/admin/queues'
130
+ };
131
+
122
132
  module.exports = {
133
+ BULL_BOARD_DEPRECATION,
123
134
  STATES,
124
135
  STATE_NAMES,
125
136
  STATES_BY_NAME,
@@ -18,7 +18,8 @@ const { accountsExist } = require('../account');
18
18
  const { webhooks: Webhooks } = require('../webhooks');
19
19
  const outbox = require('../outbox');
20
20
  const settings = require('../settings');
21
- const { buildRetentionPolicy, FAILED_JOB_RETENTION_COUNT } = require('../queue-retention');
21
+ const { buildRetentionPolicy } = require('../queue-retention');
22
+ const { getFailedJobRetention } = require('../env-setting-overrides');
22
23
  const { maskSecrets } = require('../api-routes/route-helpers');
23
24
  const { statusError } = require('../utils/status-error');
24
25
  const { retryFailedJob, promoteDelayedJob, assertJobState } = require('../queue-job-actions');
@@ -220,15 +221,16 @@ const toDays = seconds => Math.round(seconds / (24 * 3600));
220
221
  * help text says so.)
221
222
  *
222
223
  * @param {number|null} queueKeep - The `queueKeep` setting as stored
224
+ * @param {{age: number, count: number}} failedRetention - The failed-job bounds in effect
223
225
  * @returns {Object} `{ completedCount, failedCount, failedCountFloor, failedCountFromSetting, failedAgeDays }`
224
226
  */
225
- function describeRetention(queueKeep) {
226
- const { removeOnComplete, removeOnFail } = buildRetentionPolicy(queueKeep ?? true);
227
+ function describeRetention(queueKeep, failedRetention) {
228
+ const { removeOnComplete, removeOnFail } = buildRetentionPolicy(queueKeep ?? true, failedRetention);
227
229
  return {
228
- // The failed count is the environment floor or the queueKeep setting, whichever is higher,
230
+ // The failed count is the failed-job limit or the queueKeep setting, whichever is higher,
229
231
  // so a page that says where the number comes from has to know which one won
230
- failedCountFloor: FAILED_JOB_RETENTION_COUNT,
231
- failedCountFromSetting: removeOnFail.count > FAILED_JOB_RETENTION_COUNT,
232
+ failedCountFloor: failedRetention.count,
233
+ failedCountFromSetting: removeOnFail.count > failedRetention.count,
232
234
  // a boolean here is BullMQ's "remove as soon as it completes"; server.js seeds the setting
233
235
  // with a number at boot, so this is the unset case only
234
236
  completedCount: typeof removeOnComplete === 'object' ? removeOnComplete.count : 0,
@@ -240,16 +242,16 @@ function describeRetention(queueKeep) {
240
242
  async function failedContentSummary() {
241
243
  const entries = await outbox.listRetainedFailedContent();
242
244
  const bytes = entries.reduce((sum, entry) => sum + (Number(entry.size) || 0), 0);
243
- return { count: entries.length, bytes, bytesLabel: humanSize(bytes), limits: failedContentLimits() };
245
+ return { count: entries.length, bytes, bytesLabel: humanSize(bytes), limits: await failedContentLimits() };
244
246
  }
245
247
 
246
248
  /**
247
249
  * The bounds on retained failed-message content, for the pages that say what can be retried.
248
250
  *
249
- * @returns {Object} `{ maxCount, maxBytes, maxBytesLabel, maxAgeDays, keepsContent }`
251
+ * @returns {Promise<Object>} `{ maxCount, maxBytes, maxBytesLabel, maxAgeDays, keepsContent }`
250
252
  */
251
- function failedContentLimits() {
252
- const limits = outbox.FAILED_CONTENT_LIMITS;
253
+ async function failedContentLimits() {
254
+ const limits = await outbox.getFailedContentLimits();
253
255
  return {
254
256
  maxCount: limits.maxCount,
255
257
  maxBytes: limits.maxBytes,
@@ -266,7 +268,8 @@ function failedContentLimits() {
266
268
  * @returns {Promise<Object>} See `describeRetention()`
267
269
  */
268
270
  async function retention() {
269
- return describeRetention(await settings.get('queueKeep'));
271
+ const [queueKeep, failedRetention] = await Promise.all([settings.get('queueKeep'), getFailedJobRetention()]);
272
+ return describeRetention(queueKeep, failedRetention);
270
273
  }
271
274
 
272
275
  /**
@@ -344,6 +347,42 @@ async function loadJobs(queueObj, ids, logger) {
344
347
  return jobs;
345
348
  }
346
349
 
350
+ /**
351
+ * The IDs, in order, of the jobs whose data passes a check, reading only each job's data field in
352
+ * pipelined batches. A job that vanished meanwhile or whose data does not parse is left out.
353
+ *
354
+ * @param {Object} queueObj - BullMQ Queue
355
+ * @param {string[]} ids - Job IDs
356
+ * @param {Function} check - data => boolean
357
+ * @param {Object} logger - Logger instance
358
+ * @returns {Promise<string[]>} Matching IDs
359
+ */
360
+ async function idsMatchingData(queueObj, ids, check, logger) {
361
+ const matching = [];
362
+ for (let i = 0; i < ids.length; i += BATCH_SIZE) {
363
+ const batch = ids.slice(i, i + BATCH_SIZE);
364
+ let pipeline = redis.pipeline();
365
+ for (const id of batch) {
366
+ pipeline = pipeline.hget(queueObj.toKey(id), 'data');
367
+ }
368
+ const results = await pipeline.exec();
369
+ batch.forEach((id, index) => {
370
+ const [err, raw] = results[index] || [];
371
+ if (err || !raw) {
372
+ return;
373
+ }
374
+ try {
375
+ if (check(JSON.parse(raw) || {})) {
376
+ matching.push(id);
377
+ }
378
+ } catch (parseErr) {
379
+ logger.debug({ msg: 'Failed to parse queue job data', queue: queueObj.name, job: id, err: parseErr });
380
+ }
381
+ });
382
+ }
383
+ return matching;
384
+ }
385
+
347
386
  /**
348
387
  * Fills in what a row cannot know from the job alone: whether the account still exists, plus
349
388
  * whatever the queue's own decoration adds (a route name, a message's retained content).
@@ -413,18 +452,28 @@ async function listJobs(options) {
413
452
  const jobs = await loadJobs(queueObj, ids, logger);
414
453
  entries = jobs.map(job => formatJob(queueDef, job, state));
415
454
  } else {
416
- // Every ID of the scan window in one read, then the jobs in batches
455
+ // Every ID of the scan window in one read
417
456
  const ids = stateTotal ? await queueObj.getRanges([state], 0, SCAN_LIMIT - 1, asc) : [];
418
- const jobs = await loadJobs(queueObj, ids, logger);
419
457
  scanned = ids.length;
420
458
  scanLimited = scanned >= SCAN_LIMIT && stateTotal > scanned;
421
459
 
422
- const matches = jobs.filter(job => {
423
- const data = job.data || {};
424
- return (!account || data.account === account) && (!route || (data._route && data._route.id === route)) && matchesQuery(queueDef, job, query);
425
- });
426
- total = matches.length;
427
- entries = matches.slice(page * pageSize, (page + 1) * pageSize).map(job => formatJob(queueDef, job, state));
460
+ const matchesData = data => (!account || data.account === account) && (!route || (data._route && data._route.id === route));
461
+
462
+ if (!query) {
463
+ // The account and route filters only need the job data, so the scan reads that one
464
+ // field and the full jobs (progress, stack traces, return values) are read for the page
465
+ // shown alone. The data still carries the event payload; keeping an index of jobs by
466
+ // account would avoid reading it, but would not cover jobs from before it existed
467
+ const matchingIds = await idsMatchingData(queueObj, ids, matchesData, logger);
468
+ total = matchingIds.length;
469
+ const jobs = await loadJobs(queueObj, matchingIds.slice(page * pageSize, (page + 1) * pageSize), logger);
470
+ entries = jobs.map(job => formatJob(queueDef, job, state));
471
+ } else {
472
+ const jobs = await loadJobs(queueObj, ids, logger);
473
+ const matches = jobs.filter(job => matchesData(job.data || {}) && matchesQuery(queueDef, job, query));
474
+ total = matches.length;
475
+ entries = matches.slice(page * pageSize, (page + 1) * pageSize).map(job => formatJob(queueDef, job, state));
476
+ }
428
477
  }
429
478
 
430
479
  await decorateEntries(queueDef, entries, logger);
@@ -72,4 +72,21 @@ async function assertJobState(job, state, noun, verb) {
72
72
  }
73
73
  }
74
74
 
75
- module.exports = { retryFailedJob, promoteDelayedJob, assertJobState };
75
+ /**
76
+ * Loads a job, but only when it belongs to the given account. What keeps a credential bound to
77
+ * one account away from another account's jobs on the account-scoped routes, so it is written once
78
+ * for every queue those routes reach
79
+ * @param {Object} queue - BullMQ queue
80
+ * @param {string} id - Job ID
81
+ * @param {string} [account] - When set, a job of any other account is answered as missing
82
+ * @returns {Promise<Object|null>} The job, or null
83
+ */
84
+ async function getAccountJob(queue, id, account) {
85
+ const job = id ? await queue.getJob(id) : null;
86
+ if (!job || (account && (!job.data || job.data.account !== account))) {
87
+ return null;
88
+ }
89
+ return job;
90
+ }
91
+
92
+ module.exports = { retryFailedJob, promoteDelayedJob, assertJobState, getAccountJob };