emailengine-app 2.74.1 → 2.75.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 (60) hide show
  1. package/CHANGELOG.md +41 -0
  2. package/data/google-crawlers.json +1 -1
  3. package/lib/account.js +117 -63
  4. package/lib/api-routes/changes-routes.js +51 -0
  5. package/lib/api-routes/index.js +160 -0
  6. package/lib/api-routes/message-routes.js +3 -1
  7. package/lib/consts.js +21 -0
  8. package/lib/db.js +4 -1
  9. package/lib/egress-filter.js +220 -0
  10. package/lib/email-client/base-client.js +5 -8
  11. package/lib/email-client/gmail/send-request.js +69 -0
  12. package/lib/email-client/gmail-client.js +6 -46
  13. package/lib/email-client/imap/detach-client.js +27 -0
  14. package/lib/email-client/imap/listing-diff.js +165 -0
  15. package/lib/email-client/imap/mailbox.js +35 -22
  16. package/lib/email-client/imap/subconnection.js +2 -4
  17. package/lib/email-client/imap/sync-operations.js +5 -3
  18. package/lib/email-client/imap-client.js +50 -84
  19. package/lib/email-client/notification-handler.js +11 -12
  20. package/lib/email-client/outlook/send-request.js +48 -0
  21. package/lib/email-client/outlook-client.js +7 -19
  22. package/lib/export.js +97 -21
  23. package/lib/imapproxy/imap-core/README.md +69 -0
  24. package/lib/imapproxy/imap-core/lib/imap-connection.js +1 -1
  25. package/lib/logger.js +14 -6
  26. package/lib/oauth/external-account-config.js +41 -1
  27. package/lib/oauth/external-account-signer.js +7 -2
  28. package/lib/oauth/verify-app.js +18 -3
  29. package/lib/queue-retention.js +56 -0
  30. package/lib/rate-limit.js +33 -11
  31. package/lib/respawn-backoff.js +95 -0
  32. package/lib/response-stream.js +138 -0
  33. package/lib/schemas.js +9 -2
  34. package/lib/sentry.js +8 -0
  35. package/lib/settings.js +4 -1
  36. package/lib/smtp-message-processor.js +131 -0
  37. package/lib/tools.js +48 -5
  38. package/lib/ui-routes/admin-config-routes.js +22 -18
  39. package/lib/ui-routes/internals-routes.js +32 -0
  40. package/lib/utils/network.js +122 -3
  41. package/lib/web-safe-html.js +401 -0
  42. package/lib/webhook-request.js +40 -2
  43. package/lib/webhooks.js +2 -3
  44. package/package.json +15 -13
  45. package/sbom.json +1 -1
  46. package/server.js +33 -8
  47. package/static/js/ee-client.js +55 -6
  48. package/static/js/ui.js +13 -0
  49. package/static/licenses.html +336 -286
  50. package/translations/messages.pot +12 -12
  51. package/views/config/webhooks.hbs +2 -2
  52. package/views/internals/index.hbs +8 -0
  53. package/views/partials/webhooks_editor_functions.hbs +1 -1
  54. package/workers/api.js +52 -233
  55. package/workers/documents.js +6 -0
  56. package/workers/export.js +37 -16
  57. package/workers/imap.js +64 -29
  58. package/workers/smtp.js +50 -91
  59. package/workers/submit.js +10 -0
  60. package/workers/webhooks.js +23 -2
package/lib/export.js CHANGED
@@ -30,6 +30,7 @@ local maxConcurrent = tonumber(ARGV[1])
30
30
  local maxGlobal = tonumber(ARGV[2])
31
31
  local accountPrefix = ARGV[3]
32
32
  local activeEntry = ARGV[4]
33
+ local exportIdPrefix = ARGV[5]
33
34
 
34
35
  local members = redis.call('SMEMBERS', activeKey)
35
36
  local globalCount = #members
@@ -39,11 +40,21 @@ if globalCount >= maxGlobal then
39
40
  return 0
40
41
  end
41
42
 
42
- -- Check per-account limit
43
+ -- Check per-account limit. The prefix alone is not enough: account ids may contain colons, so
44
+ -- "user:" is also a prefix of the account "user:sub" entries. Requiring the remainder to be the
45
+ -- export id (the id prefix and no further colon) anchors the match on the same boundary that
46
+ -- parseActiveEntry() splits on, so the limiter and the recovery scan agree on who owns an entry.
47
+ -- The id prefix arrives as an argument rather than being spelled out here, so that changing
48
+ -- EXPORT_ID_PREFIX can not leave this counting nothing and failing the limit OPEN in silence.
49
+ -- Matched with plain string.find (no patterns) so a prefix containing a Lua magic character
50
+ -- would not change the meaning of the comparison either.
43
51
  local accountCount = 0
44
52
  for _, member in ipairs(members) do
45
53
  if string.sub(member, 1, #accountPrefix) == accountPrefix then
46
- accountCount = accountCount + 1
54
+ local remainder = string.sub(member, #accountPrefix + 1)
55
+ if string.sub(remainder, 1, #exportIdPrefix) == exportIdPrefix and not string.find(remainder, ':', 1, true) then
56
+ accountCount = accountCount + 1
57
+ end
47
58
  end
48
59
  end
49
60
 
@@ -56,6 +67,28 @@ redis.call('SADD', activeKey, activeEntry)
56
67
  return 1
57
68
  `;
58
69
 
70
+ // The active-set membership encoding. Written by tryAddToActiveSet(), read back by
71
+ // markInterruptedAsFailed() and counted by CONCURRENT_CHECK_AND_ADD_SCRIPT - defined here once so
72
+ // the three can not disagree about where the account ends and the export id begins.
73
+ function buildActiveEntry(account, exportId) {
74
+ return `${account}:${exportId}`;
75
+ }
76
+
77
+ // Account ids may contain colons, so split on the LAST ':exp_' - the export id is always the
78
+ // trailing ':exp_<hex>' segment.
79
+ function parseActiveEntry(entry) {
80
+ const separatorIndex = entry.lastIndexOf(`:${EXPORT_ID_PREFIX}`);
81
+ if (separatorIndex === -1) {
82
+ return false;
83
+ }
84
+ const account = entry.substring(0, separatorIndex);
85
+ const exportId = entry.substring(separatorIndex + 1);
86
+ if (!account || !exportId) {
87
+ return false;
88
+ }
89
+ return { account, exportId };
90
+ }
91
+
59
92
  function generateExportId() {
60
93
  return EXPORT_ID_PREFIX + crypto.randomBytes(12).toString('hex');
61
94
  }
@@ -100,6 +133,27 @@ function isFolderMissingError(err) {
100
133
  return ['FolderNotFound', 'NotFound'].includes(errCode);
101
134
  }
102
135
 
136
+ // Export truncation limits (max messages while indexing, max total bytes while exporting).
137
+ //
138
+ // Extracted from workers/export.js because the worker applies the same rule in three places and
139
+ // none of them can be reached from a test in place (they sit inside the BullMQ job body, behind
140
+ // a live account and a real folder listing). The rules:
141
+ //
142
+ // * an unset, zero, non-numeric or negative stored setting means "use the default" - a negative
143
+ // limit used to survive `Number(value) || DEFAULT` and then truncate every export at zero
144
+ // messages, because `totalIndexed >= -1` is true from the start
145
+ // * the comparison is `>=`, so the limit itself is the last value that still fits
146
+ // * a limit of 0 passed in explicitly means unlimited, never "export nothing"
147
+
148
+ function resolveExportLimit(value, defaultValue) {
149
+ const limit = Number(value);
150
+ return Number.isFinite(limit) && limit > 0 ? limit : defaultValue;
151
+ }
152
+
153
+ function isExportLimitReached(current, limit) {
154
+ return !!limit && current >= limit;
155
+ }
156
+
103
157
  // Per-message errors worth retrying during a batch export: rate limits, a dropped batch response
104
158
  // (Outlook reports these as EMISSING_RESPONSE), and the same transient network/5xx/timeout errors
105
159
  // isTransientError already covers. Used by the export worker's API-account batch fetch path so a
@@ -111,14 +165,32 @@ function isRetryableError(err) {
111
165
  return isTransientError(err);
112
166
  }
113
167
 
114
- async function tryAddToActiveSet(account, exportId) {
115
- const maxConcurrent = (await settings.get('exportMaxConcurrent')) || DEFAULT_EXPORT_MAX_CONCURRENT;
116
- const maxGlobalConcurrent = (await settings.get('exportMaxGlobalConcurrent')) || DEFAULT_EXPORT_MAX_GLOBAL_CONCURRENT;
168
+ // `opts` exists so tests can drive this against a scoped key with explicit limits instead of
169
+ // re-implementing the EVAL. Production always calls it with no overrides.
170
+ //
171
+ // An explicit override wins even when it is 0; a stored setting goes through
172
+ // resolveExportLimit() like every other numeric limit, because a stored 0 or '' is not a usable
173
+ // concurrency limit (`0 >= 0` refuses every export with 429 forever, and a non-numeric value
174
+ // makes the EVAL raise "attempt to compare nil with number").
175
+ async function tryAddToActiveSet(account, exportId, opts) {
176
+ const { activeKey = ACTIVE_EXPORTS_KEY } = opts || {};
177
+ const maxConcurrent = opts?.maxConcurrent ?? resolveExportLimit(await settings.get('exportMaxConcurrent'), DEFAULT_EXPORT_MAX_CONCURRENT);
178
+ const maxGlobalConcurrent =
179
+ opts?.maxGlobalConcurrent ?? resolveExportLimit(await settings.get('exportMaxGlobalConcurrent'), DEFAULT_EXPORT_MAX_GLOBAL_CONCURRENT);
117
180
 
118
181
  const accountPrefix = `${account}:`;
119
- const activeEntry = `${account}:${exportId}`;
120
-
121
- const added = await redis.eval(CONCURRENT_CHECK_AND_ADD_SCRIPT, 1, ACTIVE_EXPORTS_KEY, maxConcurrent, maxGlobalConcurrent, accountPrefix, activeEntry);
182
+ const activeEntry = buildActiveEntry(account, exportId);
183
+
184
+ const added = await redis.eval(
185
+ CONCURRENT_CHECK_AND_ADD_SCRIPT,
186
+ 1,
187
+ activeKey,
188
+ maxConcurrent,
189
+ maxGlobalConcurrent,
190
+ accountPrefix,
191
+ activeEntry,
192
+ EXPORT_ID_PREFIX
193
+ );
122
194
 
123
195
  if (!added) {
124
196
  throw createError('Maximum concurrent exports reached', 'TooManyExports', 429);
@@ -358,7 +430,7 @@ class Export {
358
430
  // Active exports: worker will clean up when it detects cancellation
359
431
  // Non-active exports: clean up immediately
360
432
  if (!isActive) {
361
- await redis.multi().del(exportKey).del(queueKey).srem(ACTIVE_EXPORTS_KEY, `${account}:${exportId}`).exec();
433
+ await redis.multi().del(exportKey).del(queueKey).srem(ACTIVE_EXPORTS_KEY, buildActiveEntry(account, exportId)).exec();
362
434
 
363
435
  if (data.filePath) {
364
436
  await fs.promises.unlink(data.filePath).catch(() => {});
@@ -479,7 +551,7 @@ class Export {
479
551
  .multi()
480
552
  .hmset(exportKey, { status: 'completed', phase: 'complete', expiresAt })
481
553
  .del(queueKey)
482
- .srem(ACTIVE_EXPORTS_KEY, `${account}:${exportId}`)
554
+ .srem(ACTIVE_EXPORTS_KEY, buildActiveEntry(account, exportId))
483
555
  .expire(exportKey, ttl)
484
556
  .exec();
485
557
 
@@ -493,7 +565,7 @@ class Export {
493
565
  const exportData = await redis.hgetall(exportKey);
494
566
  if (!exportData || !exportData.exportId) {
495
567
  // Key already deleted, just clean up active set
496
- await redis.srem(ACTIVE_EXPORTS_KEY, `${account}:${exportId}`);
568
+ await redis.srem(ACTIVE_EXPORTS_KEY, buildActiveEntry(account, exportId));
497
569
  return;
498
570
  }
499
571
 
@@ -504,7 +576,7 @@ class Export {
504
576
  error: error || 'Unknown error'
505
577
  })
506
578
  .del(queueKey)
507
- .srem(ACTIVE_EXPORTS_KEY, `${account}:${exportId}`)
579
+ .srem(ACTIVE_EXPORTS_KEY, buildActiveEntry(account, exportId))
508
580
  .exec();
509
581
 
510
582
  logger.error({ msg: 'Export failed', account, exportId, error });
@@ -514,7 +586,7 @@ class Export {
514
586
  const exportKey = getExportKey(account, exportId);
515
587
  const queueKey = getExportQueueKey(account, exportId);
516
588
 
517
- await redis.multi().del(exportKey).del(queueKey).srem(ACTIVE_EXPORTS_KEY, `${account}:${exportId}`).exec();
589
+ await redis.multi().del(exportKey).del(queueKey).srem(ACTIVE_EXPORTS_KEY, buildActiveEntry(account, exportId)).exec();
518
590
  }
519
591
 
520
592
  static async markInterruptedAsFailed() {
@@ -522,13 +594,9 @@ class Export {
522
594
 
523
595
  for (const entry of activeExports) {
524
596
  try {
525
- // Find ':exp_' as separator since account IDs may contain colons. The export id is
526
- // always the trailing ':exp_<hex>' segment, so match the last occurrence.
527
- const separatorIndex = entry.lastIndexOf(':exp_');
528
- if (separatorIndex === -1) continue;
529
- const account = entry.substring(0, separatorIndex);
530
- const exportId = entry.substring(separatorIndex + 1);
531
- if (!account || !exportId) continue;
597
+ const parsed = parseActiveEntry(entry);
598
+ if (!parsed) continue;
599
+ const { account, exportId } = parsed;
532
600
 
533
601
  const data = await redis.hgetall(getExportKey(account, exportId));
534
602
 
@@ -631,5 +699,13 @@ module.exports = {
631
699
  isSkippableError,
632
700
  isFolderMissingError,
633
701
  isRetryableError,
634
- DEFAULT_EXPORT_MAX_MESSAGE_SIZE
702
+ resolveExportLimit,
703
+ isExportLimitReached,
704
+ DEFAULT_EXPORT_MAX_MESSAGE_SIZE,
705
+ // Exported so test/export-concurrency-test.js drives the real limiter (and the real entry
706
+ // encoding) rather than re-implementing the EVAL, which a copy could never keep in step with.
707
+ tryAddToActiveSet,
708
+ buildActiveEntry,
709
+ parseActiveEntry,
710
+ ACTIVE_EXPORTS_KEY
635
711
  };
@@ -0,0 +1,69 @@
1
+ # imap-core (vendored fork)
2
+
3
+ This directory is a **vendored fork**, not a dependency. It is not listed in `package.json`, so
4
+ `npm update` never touches it and `npm audit` never sees it.
5
+
6
+ ## Provenance
7
+
8
+ Upstream: the `imap-core` module of [WildDuck](https://github.com/nodemailer/wildduck)
9
+ (`lib/imap-core` in that repository).
10
+
11
+ Imported into EmailEngine in `dd0d6e34` ("Added IMAP proxy server", 2022-08-23) and patched in
12
+ place since. It provides the IMAP protocol server that `lib/imapproxy/imap-server.js` builds on:
13
+ the command parser/compiler, the connection and command state machines, and the message indexer.
14
+
15
+ The WildDuck-specific parts of upstream (MongoDB-backed mailbox storage, the `test/prepare.sh`
16
+ fixture loader that talks to a WildDuck REST API) came along with the import and are not used
17
+ here.
18
+
19
+ ## Local patches
20
+
21
+ Everything below is EmailEngine-only and has no upstream equivalent. Re-syncing with upstream
22
+ means re-applying these.
23
+
24
+ | Commit | Date | Change |
25
+ | --- | --- | --- |
26
+ | `4453330a` | 2026-06-01 | Prevent IMAP proxy worker crashes and connection leaks (#596) |
27
+ | `3661dddb` | 2026-06-05 | Harden STARTTLS against command injection: reject pipelined data buffered before the TLS upgrade |
28
+ | `9fb8a5e3` | 2026-06-05 | Bound inbound line length in the parser, so an unterminated line cannot grow without limit |
29
+ | `627c6d47` | 2026-06-05 | Re-arm a generous idle timeout for proxied connections |
30
+ | `e97950e7` | 2026-06-05 | Close leaks and a worker crash found in the connection hardening review |
31
+ | `d51e92d2` | 2026-06-06 | Prevent post-BYE command dispatch during teardown |
32
+ | `31f6a590` | 2026-07-26 | Fix the dead teardown guard in the notification listener |
33
+
34
+ Earlier local changes (`09085d12`, `0a389560`, `7e2e94f3`, `04c2aa90`, `1d6df05e`, `612d9f96`,
35
+ `13edec58`, `2e0bf1ce`, `b9a3e06c`, `b58a827e`, `1813f089`) are maintenance: dependency swaps
36
+ (`punycode` to `punycode.js`, `wild-config` to `@zone-eu/wild-config`), the `fast` IMAP indexing
37
+ option, OAuth `useAuthServer` support, formatting and lint-glob fixes.
38
+
39
+ `git log -- lib/imapproxy/imap-core/` is the authoritative list; this table is a summary.
40
+
41
+ ## Tests
42
+
43
+ The `test/` directory is upstream's mocha suite. It is written for mocha, which is not a
44
+ dependency here, and had never been executed after the import.
45
+
46
+ The hermetic specs now run as part of the normal unit tier through
47
+ `test/imap-core-vendored-test.js`, which installs the mocha globals the specs expect and requires
48
+ them. **Do not edit the files under `test/` to make them run** - keeping them byte-identical to
49
+ upstream is what makes the patch list above reviewable. Adapt them from the EmailEngine side
50
+ instead.
51
+
52
+ Wired up and running:
53
+
54
+ - `imap-parser-test.js`
55
+ - `imap-compiler-test.js`
56
+ - `imap-compile-stream-test.js`
57
+ - `imap-indexer-test.js` (upstream has its `#rebuild` block commented out)
58
+ - `tools-test.js`
59
+
60
+ Not wired up, because they drive a live server via `test-server.js` and need MongoDB plus a
61
+ WildDuck REST API that does not exist in this repository:
62
+
63
+ - `protocol-test.js`
64
+ - `search-test.js`
65
+
66
+ That is a real coverage gap: `protocol-test.js` is the suite that exercises the connection and
67
+ command state machines, which is where most of the local patches above landed. The connection
68
+ handling that EmailEngine actually ships is covered instead by `test/dovecot/` (live IMAP against
69
+ Dovecot) and the IMAP proxy's own integration tests.
@@ -646,7 +646,7 @@ class IMAPConnection extends EventEmitter {
646
646
  cleared: false,
647
647
  callback(message) {
648
648
  let selectedMailbox = conn.selected && conn.selected.mailbox;
649
- if (this._closing || this._closed) {
649
+ if (conn._closing || conn._closed) {
650
650
  conn.clearNotificationListener();
651
651
  return;
652
652
  }
package/lib/logger.js CHANGED
@@ -50,15 +50,23 @@ if (threadId) {
50
50
  logger = logger.child({ tid: threadId });
51
51
  }
52
52
 
53
+ const FATAL_EXIT_CODES = {
54
+ uncaughtException: 1,
55
+ unhandledRejection: 2
56
+ };
57
+
53
58
  // An error that reaches the global handlers leaves the process in an unknown state,
54
59
  // so the process must always exit. If error tracking is enabled, report the error
55
- // first and allow a short flush window for the delivery.
56
- function fatalShutdown(code, err) {
60
+ // first and allow a short flush window for the delivery. The report is tagged with
61
+ // the handler that caught it because a crash carries no call site of its own - a
62
+ // bare socket error arrives with nothing but a `node:internal` frame, so without the
63
+ // tag there is no way to tell a dead worker apart from a handled error.
64
+ function fatalShutdown(handler, err) {
57
65
  if (logger.notifyError) {
58
- logger.notifyError(err);
66
+ logger.notifyError(err, { level: 'fatal', tags: { handler } });
59
67
  }
60
68
 
61
- let exit = () => process.exit(code);
69
+ let exit = () => process.exit(FATAL_EXIT_CODES[handler]);
62
70
  if (logger.flushNotifications) {
63
71
  logger.flushNotifications().then(exit, exit);
64
72
  } else {
@@ -73,7 +81,7 @@ process.on('uncaughtException', err => {
73
81
  err
74
82
  });
75
83
 
76
- fatalShutdown(1, err);
84
+ fatalShutdown('uncaughtException', err);
77
85
  });
78
86
 
79
87
  process.on('unhandledRejection', err => {
@@ -83,7 +91,7 @@ process.on('unhandledRejection', err => {
83
91
  err
84
92
  });
85
93
 
86
- fatalShutdown(2, err);
94
+ fatalShutdown('unhandledRejection', err);
87
95
  });
88
96
 
89
97
  module.exports = logger;
@@ -9,6 +9,42 @@
9
9
  const ACCEPTED_SUBJECT_TOKEN_TYPES = new Set(['urn:ietf:params:oauth:token-type:jwt', 'urn:ietf:params:oauth:token-type:id_token']);
10
10
  const IMPERSONATION_URL_RE = /\/v1\/projects\/-\/serviceAccounts\/([^/]+):generateAccessToken$/;
11
11
 
12
+ // Google STS is the only endpoint allowed to receive the subject token.
13
+ //
14
+ // The subject token is read from this host - a projected OIDC token file, or a metadata endpoint -
15
+ // and POSTed verbatim as the `subject_token` form field. A caller-chosen token_url therefore turns
16
+ // the credential source into an exfiltration channel: point it at your own server and whatever the
17
+ // configured file contains is delivered to you, and the response comes back in-band because
18
+ // /v1/oauth2/{app}/verify reports the endpoint's error_description. Pinning the host closes that
19
+ // channel, so the credential source can only ever be delivered to Google.
20
+ const STS_HOST = 'sts.googleapis.com';
21
+
22
+ // Regional STS endpoints, e.g. sts.europe-west1.rep.googleapis.com
23
+ const REGIONAL_STS_HOST_RE = /^sts\.[a-z0-9-]+\.rep\.googleapis\.com$/;
24
+
25
+ // Validates token_url against the Google STS endpoints. `allowedTokenHosts` is an injection point
26
+ // for tests that stand up a local STS double; production callers never pass it, which is the same
27
+ // arrangement as the signer's iamCredentialsBaseUrl option.
28
+ function assertTokenUrl(rawUrl, allowedTokenHosts) {
29
+ let url;
30
+ try {
31
+ url = new URL(rawUrl);
32
+ } catch (err) {
33
+ throw makeError('External account token_url is not a valid URL', 'EExternalAccountConfig');
34
+ }
35
+
36
+ if (allowedTokenHosts && allowedTokenHosts.includes(url.hostname)) {
37
+ return;
38
+ }
39
+
40
+ if (url.protocol !== 'https:' || !(url.hostname === STS_HOST || REGIONAL_STS_HOST_RE.test(url.hostname))) {
41
+ throw makeError(
42
+ `External account token_url must be a Google STS endpoint (https://${STS_HOST}/v1/token), got ${JSON.stringify(url.protocol + '//' + url.hostname)}`,
43
+ 'EExternalAccountConfig'
44
+ );
45
+ }
46
+ }
47
+
12
48
  function makeError(message, code, statusCode, extra) {
13
49
  let err = new Error(message);
14
50
  err.code = code;
@@ -25,7 +61,9 @@ function makeError(message, code, statusCode, extra) {
25
61
  // returns the derived target service account email. Throws an error tagged with
26
62
  // code 'EExternalAccountConfig' on any problem so callers can surface a clean
27
63
  // validation message instead of a late runtime failure.
28
- function validateConfig(config) {
64
+ function validateConfig(config, opts) {
65
+ const { allowedTokenHosts } = opts || {};
66
+
29
67
  if (!config || typeof config !== 'object') {
30
68
  throw makeError('External account configuration must be a JSON object', 'EExternalAccountConfig');
31
69
  }
@@ -41,6 +79,8 @@ function validateConfig(config) {
41
79
  }
42
80
  }
43
81
 
82
+ assertTokenUrl(config.token_url, allowedTokenHosts);
83
+
44
84
  if (!ACCEPTED_SUBJECT_TOKEN_TYPES.has(config.subject_token_type)) {
45
85
  throw makeError(
46
86
  `External account subject_token_type ${JSON.stringify(config.subject_token_type)} is not supported. ` +
@@ -19,7 +19,7 @@ class ExternalAccountSigner {
19
19
  constructor(opts) {
20
20
  opts = opts || {};
21
21
 
22
- let { targetServiceAccountEmail } = validateConfig(opts.config);
22
+ let { targetServiceAccountEmail } = validateConfig(opts.config, { allowedTokenHosts: opts.allowedTokenHosts });
23
23
 
24
24
  this.config = opts.config;
25
25
  // The service account whose Google-managed key signs the JWT. Exposed so
@@ -59,7 +59,12 @@ class ExternalAccountSigner {
59
59
  try {
60
60
  rawText = await this._readFile(source.file, 'utf8');
61
61
  } catch (err) {
62
- throw makeError(`Failed to read subject token file ${source.file}: ${err.message}`, 'ESubjectTokenRead', null, { cause: err });
62
+ // Report the errno rather than the raw message: the path came from the operator so
63
+ // echoing it back is useful, but the full fs message adds nothing and this string
64
+ // is surfaced in the verify report.
65
+ throw makeError(`Failed to read subject token file ${source.file}${err.code ? ` (${err.code})` : ''}`, 'ESubjectTokenRead', null, {
66
+ cause: err
67
+ });
63
68
  }
64
69
  return extractFromFormat(rawText, format);
65
70
  }
@@ -29,17 +29,29 @@ const withTimeout = (promise, ms, label) =>
29
29
  new Promise((resolve, reject) => setTimeout(() => reject(new Error(`${label} timed out after ${Math.round(ms / 1000)}s`)), ms).unref())
30
30
  ]);
31
31
 
32
+ // Upper bound on remote error text echoed into the verify report. These strings come from the
33
+ // remote endpoint, so they are reflected content: bound them rather than passing an
34
+ // arbitrarily long body through into the API response.
35
+ const MAX_REMOTE_DETAIL_LENGTH = 512;
36
+
37
+ function truncateDetail(value) {
38
+ if (typeof value !== 'string') {
39
+ return null;
40
+ }
41
+ return value.length > MAX_REMOTE_DETAIL_LENGTH ? `${value.slice(0, MAX_REMOTE_DETAIL_LENGTH)}...` : value;
42
+ }
43
+
32
44
  function describeResponse(err) {
33
45
  let resp = err && (err.response || (err.tokenRequest && err.tokenRequest.response));
34
46
  if (resp && typeof resp === 'object') {
35
47
  // Google API errors nest the detail under error.message; OAuth/STS errors
36
48
  // use top-level string error/error_description fields.
37
49
  if (resp.error && typeof resp.error === 'object' && resp.error.message) {
38
- return resp.error.message;
50
+ return truncateDetail(resp.error.message);
39
51
  }
40
- let parts = [resp.error, resp.error_description].filter(Boolean);
52
+ let parts = [resp.error, resp.error_description].filter(part => typeof part === 'string' && part);
41
53
  if (parts.length) {
42
- return parts.join(': ');
54
+ return truncateDetail(parts.join(': '));
43
55
  }
44
56
  }
45
57
  return null;
@@ -395,3 +407,6 @@ async function verifyOAuth2App(appId, opts) {
395
407
  }
396
408
 
397
409
  module.exports = { verifyOAuth2App };
410
+
411
+ // Exported for tests only; describeResponse reflects remote content into the verify report.
412
+ module.exports.__test__ = { describeResponse, MAX_REMOTE_DETAIL_LENGTH };
@@ -0,0 +1,56 @@
1
+ 'use strict';
2
+
3
+ // Retention policies for BullMQ job entries.
4
+ //
5
+ // This module is deliberately dependency-free (no Redis, no settings) so it can be unit tested
6
+ // directly. Four call sites used to build these policies inline from the `queueKeep` setting and
7
+ // had already drifted apart: three read the setting with `?? true` and one with `|| true`, which
8
+ // silently turned an explicit `queueKeep = 0` into "keep everything".
9
+
10
+ // How long a completed entry is kept when the operator asked for a bounded count. Completed jobs
11
+ // are purely for debugging, so a day is plenty.
12
+ const COMPLETED_JOB_RETENTION_AGE = 24 * 3600;
13
+
14
+ // Failed entries are the only record that a delivery was given up on, so they outlive completed
15
+ // ones. Bounded on both axes because webhook payloads can carry up to `notifyTextSize` (2MB by
16
+ // default) of message text and an endpoint that is down fails every event it is sent.
17
+ // Both are overridable because the right bound depends on payload size: a `messageNew` webhook
18
+ // carries up to `notifyTextSize` (2MB by default) of message text, and a receiver that is down
19
+ // turns every event into a retained entry.
20
+ const FAILED_JOB_RETENTION_AGE = Number(process.env.EENGINE_QUEUE_KEEP_FAILED_AGE) || 7 * 24 * 3600;
21
+ const FAILED_JOB_RETENTION_COUNT = Number(process.env.EENGINE_QUEUE_KEEP_FAILED) || 500;
22
+
23
+ /**
24
+ * Builds the `removeOnComplete` / `removeOnFail` pair for a queue job.
25
+ *
26
+ * A job reaches the failed set only after every retry is exhausted, which for a webhook means the
27
+ * event is gone. `queueKeep` defaults to 0, so applying it to failures too (the previous behavior)
28
+ * deleted that record the moment it was written and left nothing but a log line behind. Failures
29
+ * therefore get their own floor: at least `FAILED_JOB_RETENTION_COUNT` entries for
30
+ * `FAILED_JOB_RETENTION_AGE` seconds, regardless of how few completed entries are wanted.
31
+ *
32
+ * BullMQ reads these values as "when to remove", not "how much to keep": `true` removes the entry
33
+ * immediately, `false` keeps it forever, a number keeps the last N, and `{age, count}` keeps
34
+ * entries younger than `age` up to `count` of them.
35
+ *
36
+ * @param {boolean|number} queueKeep - The `queueKeep` setting: entries to retain, or a boolean
37
+ * @returns {{removeOnComplete: boolean|Object, removeOnFail: boolean|Object}} BullMQ job options
38
+ */
39
+ function buildRetentionPolicy(queueKeep) {
40
+ const removeOnComplete = typeof queueKeep === 'number' ? { age: COMPLETED_JOB_RETENTION_AGE, count: queueKeep } : queueKeep;
41
+
42
+ // Always bounded, and widened when the operator asked to keep more entries than the floor
43
+ const removeOnFail = {
44
+ age: FAILED_JOB_RETENTION_AGE,
45
+ count: typeof queueKeep === 'number' ? Math.max(queueKeep, FAILED_JOB_RETENTION_COUNT) : FAILED_JOB_RETENTION_COUNT
46
+ };
47
+
48
+ return { removeOnComplete, removeOnFail };
49
+ }
50
+
51
+ module.exports = {
52
+ buildRetentionPolicy,
53
+ COMPLETED_JOB_RETENTION_AGE,
54
+ FAILED_JOB_RETENTION_AGE,
55
+ FAILED_JOB_RETENTION_COUNT
56
+ };
package/lib/rate-limit.js CHANGED
@@ -3,18 +3,40 @@
3
3
  const { redis } = require('../lib/db');
4
4
  const { REDIS_PREFIX } = require('../lib/consts');
5
5
 
6
+ // Fixed epoch for the window bucket arithmetic: "2000-01-01T00:00:00.000Z"
7
+ const EPOCH_TIME = 946684800000;
8
+
9
+ const DEFAULT_WINDOW_SIZE = 180;
10
+
11
+ // Derives the Redis counter key for a rate-limit window. The window size is part of the key, so
12
+ // the same subject can be limited over several windows at once (e.g. per-minute login attempts
13
+ // and the 12 minute TOTP code replay guard) without the counters interfering.
14
+ //
15
+ // The normalization lives here rather than in the caller so that every consumer of the key
16
+ // derives the same bucket: a missing window would otherwise produce an "rl:undefined:NaN:" key
17
+ // while checkRateLimit() counted under the 180 second one, and the two would never meet.
18
+ // The end of the bucket is computed here too, so the bucket arithmetic and its inverse stay in
19
+ // one place instead of the caller reconstructing it from a leaked bucket number.
20
+ const rateLimitWindowKey = (key, windowSize, now) => {
21
+ windowSize = Math.abs(Number(windowSize) || DEFAULT_WINDOW_SIZE);
22
+ let timeBucket = Math.floor(((now || Date.now()) - EPOCH_TIME) / (windowSize * 1000));
23
+ return {
24
+ windowKey: `${REDIS_PREFIX}rl:${windowSize}:${timeBucket}:${key}`,
25
+ windowSize,
26
+ windowEnds: (timeBucket + 1) * windowSize * 1000 + EPOCH_TIME
27
+ };
28
+ };
29
+
6
30
  const checkRateLimit = async (key, count, allowed, windowSize) => {
7
- count = Math.max(Number(count) || 1);
8
- windowSize = Math.abs(Number(windowSize) || 180);
31
+ // The lower bound is what keeps a negative cost from DECREMENTING the counter, i.e. from
32
+ // buying back attempts against a brute-force guard. Math.max() with a single argument is a
33
+ // no-op and passed one straight through.
34
+ count = Math.max(Number(count) || 1, 1);
9
35
 
10
36
  let now = Date.now();
11
- let epochTime = 946684800000; // "2000-01-01T00:00:00.000Z"
12
- let timeBucket = Math.floor((now - epochTime) / (windowSize * 1000));
13
- let ttl = new Date((timeBucket + 1) * windowSize * 1000 + epochTime);
14
-
15
- let windowKey = `${REDIS_PREFIX}rl:${windowSize}:${timeBucket}:${key}`;
37
+ let { windowKey, windowSize: normalizedWindowSize, windowEnds } = rateLimitWindowKey(key, windowSize, now);
16
38
 
17
- let [[resErr, resVal], [expireErr]] = await redis.multi().incrby(windowKey, count).expire(windowKey, windowSize).exec();
39
+ let [[resErr, resVal], [expireErr]] = await redis.multi().incrby(windowKey, count).expire(windowKey, normalizedWindowSize).exec();
18
40
  if (resErr || expireErr) {
19
41
  throw resErr || expireErr;
20
42
  }
@@ -24,9 +46,9 @@ const checkRateLimit = async (key, count, allowed, windowSize) => {
24
46
  success: resVal <= allowed,
25
47
  count: resVal,
26
48
  allowed,
27
- ttl: (ttl.getTime() - now) / 1000,
28
- ttlReset: new Date(ttl.getTime()).toISOString()
49
+ ttl: (windowEnds - now) / 1000,
50
+ ttlReset: new Date(windowEnds).toISOString()
29
51
  };
30
52
  };
31
53
 
32
- module.exports = { checkRateLimit };
54
+ module.exports = { checkRateLimit, rateLimitWindowKey };
@@ -0,0 +1,95 @@
1
+ 'use strict';
2
+
3
+ // Respawn pacing for supervised worker threads.
4
+ //
5
+ // A worker that dies deterministically (bad config, an unsatisfiable dependency, a crash on
6
+ // startup) used to be respawned on a flat 1s timer forever: roughly one thread start per second,
7
+ // indefinitely, pinning a core and burying every other log line under the same repeating stack.
8
+ //
9
+ // This is pacing, not a circuit breaker. Respawning never stops and is never blocked by another
10
+ // worker's failures - the delay only grows while a given worker type keeps dying quickly, and a
11
+ // worker that stays up resets its own type immediately.
12
+
13
+ const DEFAULT_BASE_DELAY = 1000;
14
+ const DEFAULT_MAX_DELAY = 60 * 1000;
15
+
16
+ // How long a worker must survive before its start counts as successful. Longer than any plausible
17
+ // startup crash, shorter than any real workload, so a genuine crash loop cannot look healthy.
18
+ const DEFAULT_STABLE_UPTIME = 60 * 1000;
19
+
20
+ const DEFAULT_JITTER = 0.2;
21
+
22
+ /**
23
+ * Tracks per-type crash streaks and derives how long to wait before the next respawn.
24
+ */
25
+ class RespawnTracker {
26
+ constructor(opts) {
27
+ const {
28
+ baseDelay = DEFAULT_BASE_DELAY,
29
+ maxDelay = DEFAULT_MAX_DELAY,
30
+ stableUptime = DEFAULT_STABLE_UPTIME,
31
+ jitter = DEFAULT_JITTER,
32
+ random = Math.random
33
+ } = opts || {};
34
+
35
+ this.baseDelay = baseDelay;
36
+ this.maxDelay = maxDelay;
37
+ this.stableUptime = stableUptime;
38
+ this.jitter = jitter;
39
+ this.random = random;
40
+
41
+ // worker type -> count of consecutive short-lived exits
42
+ this.failures = new Map();
43
+ }
44
+
45
+ /**
46
+ * Records that a worker of the given type exited and returns the delay before respawning it.
47
+ *
48
+ * @param {string} type - Worker type (imap, api, webhooks, ...)
49
+ * @param {number} uptimeMs - How long the worker had been running
50
+ * @returns {number} Milliseconds to wait before respawning
51
+ */
52
+ recordExit(type, uptimeMs) {
53
+ if (uptimeMs >= this.stableUptime) {
54
+ // The worker did real work before dying, so this is not a crash loop. Start over so a
55
+ // long-lived worker that finally crashes restarts as promptly as a fresh one.
56
+ this.failures.delete(type);
57
+ return this.delayFor(1);
58
+ }
59
+
60
+ const failures = (this.failures.get(type) || 0) + 1;
61
+ this.failures.set(type, failures);
62
+
63
+ return this.delayFor(failures);
64
+ }
65
+
66
+ /**
67
+ * Delay for the nth consecutive failure. The first failure keeps the historical 1s delay.
68
+ * @param {number} failures - Consecutive short-lived exits, 1 based
69
+ * @returns {number} Milliseconds to wait
70
+ */
71
+ delayFor(failures) {
72
+ const delay = Math.min(this.baseDelay * Math.pow(2, failures - 1), this.maxDelay);
73
+
74
+ // Spread respawns so a fleet-wide crash (Redis went away) does not come back in lockstep
75
+ const spread = 1 - this.jitter + this.jitter * 2 * this.random();
76
+
77
+ return Math.round(delay * spread);
78
+ }
79
+
80
+ /**
81
+ * Consecutive short-lived exits recorded for a type, for logging.
82
+ * @param {string} type - Worker type
83
+ * @returns {number} Current streak
84
+ */
85
+ streakFor(type) {
86
+ return this.failures.get(type) || 0;
87
+ }
88
+ }
89
+
90
+ module.exports = {
91
+ RespawnTracker,
92
+ DEFAULT_BASE_DELAY,
93
+ DEFAULT_MAX_DELAY,
94
+ DEFAULT_STABLE_UPTIME
95
+ };