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/CHANGELOG.md CHANGED
@@ -1,5 +1,46 @@
1
1
  # Changelog
2
2
 
3
+ ## [2.75.0](https://github.com/postalsys/emailengine/compare/v2.74.2...v2.75.0) (2026-07-28)
4
+
5
+
6
+ ### Features
7
+
8
+ * **web-safe-html:** fold quoted thread history into a collapse marker ([25d45bf](https://github.com/postalsys/emailengine/commit/25d45bf5b8dcc64443272f4b85178ee2c497d79c))
9
+
10
+
11
+ ### Bug Fixes
12
+
13
+ * **account:** serialize account updates so a refreshed token is not lost ([e577825](https://github.com/postalsys/emailengine/commit/e5778255710b1be912e6b259073ec963c2da03a2))
14
+ * **api:** match IPv4-mapped peer addresses against the address allowlists ([5acff06](https://github.com/postalsys/emailengine/commit/5acff061b31af6db49ffe9d856a5017bdfcaf4e7))
15
+ * **api:** trust X-Forwarded-For only from declared proxies ([6e93ea7](https://github.com/postalsys/emailengine/commit/6e93ea714cd75aa876f713345d675a5416b36aeb))
16
+ * **api:** warn about a spoofable admin allowlist when the proxy list is empty ([4309abe](https://github.com/postalsys/emailengine/commit/4309abe2d45652699f76b4adc31ff37e79802a53))
17
+ * **deps:** bump imapflow to 1.6.1 to restore IMAP account verification ([c2a5437](https://github.com/postalsys/emailengine/commit/c2a543779b29c369d35bfbbc175810fc1d96f02c))
18
+ * **deps:** update @postalsys/email-ai-tools to 1.13.15 ([89ec145](https://github.com/postalsys/emailengine/commit/89ec145a8f43a29405cf154825601dd8ba10fae6))
19
+ * **deps:** update dependencies ([@bull-board](https://github.com/bull-board) 8.3.2) ([a5644f3](https://github.com/postalsys/emailengine/commit/a5644f34e56128451c642d2034ddf7db0d1cc7a8))
20
+ * **logging:** stop logging decrypted setting values and lower Redis reconnect noise ([5c62ac4](https://github.com/postalsys/emailengine/commit/5c62ac486112688e8a964c66a43eb609abe7c8da))
21
+ * **oauth:** pin external account token_url to Google STS ([27ade81](https://github.com/postalsys/emailengine/commit/27ade8183cd31b503077ebefd5724f2f0620947d))
22
+ * **queue:** retain failed queue entries instead of deleting them on arrival ([e83af35](https://github.com/postalsys/emailengine/commit/e83af359aafc49d584cd0c234e089e9dceb83f3b))
23
+ * **server:** drain workers on shutdown and back off crash-looping respawns ([29b3b5d](https://github.com/postalsys/emailengine/commit/29b3b5d0d7b76793ea2852c9a37a8c622217a6ea))
24
+ * **webhooks:** filter webhook egress and stop following redirects ([e44bed5](https://github.com/postalsys/emailengine/commit/e44bed549848d8eb2b04bb991aa2c6cee0bb47c2))
25
+ * **webhooks:** report the refused redirect status and probe through the delivery path ([9f7c666](https://github.com/postalsys/emailengine/commit/9f7c666f5e2a0bfae069a0c43c33a75d04922747))
26
+ * **webhooks:** stop retrying an endpoint that answers with a redirect ([bbb6055](https://github.com/postalsys/emailengine/commit/bbb605560d31bb494495b46a57cd233a78024d99))
27
+
28
+ ## [2.74.2](https://github.com/postalsys/emailengine/compare/v2.74.1...v2.74.2) (2026-07-26)
29
+
30
+
31
+ ### Bug Fixes
32
+
33
+ * **api:** bring /v1/changes under the route-table guardrail ([d685ad8](https://github.com/postalsys/emailengine/commit/d685ad849fd46d0c15837278b9d30a7f195400a2))
34
+ * **auth:** normalize the rate-limit window and reject a negative cost ([4c58678](https://github.com/postalsys/emailengine/commit/4c586783b350c38e9dd016f334b00c3d7c29cfd4))
35
+ * **export:** correct the concurrency limits and the active-set ownership ([690934a](https://github.com/postalsys/emailengine/commit/690934a0ecf8cbaa5374f0d44ae6881f708ff914))
36
+ * **imap:** keep an error sink on abandoned IMAP connections ([a9ef9e3](https://github.com/postalsys/emailengine/commit/a9ef9e3fe380cd3752a1121a0741559fbd8229b7))
37
+ * **imap:** report account log write failures instead of crashing the worker ([e881e65](https://github.com/postalsys/emailengine/commit/e881e6593ffa0f4ace027e9287124b3bde3a3edb))
38
+ * **imap:** stop wiping the folder listing on an unusable LIST response ([f6229bb](https://github.com/postalsys/emailengine/commit/f6229bb72a8a6cd415a3c738740b9dc64dfbfb9d))
39
+ * **imap:** tolerate a FETCH response that omits FLAGS ([b78b314](https://github.com/postalsys/emailengine/commit/b78b314396ea6eec7e23d707044cf46d1f51899c))
40
+ * **smtp:** handle MIME parse errors and enforce the message size limit ([e70eb7d](https://github.com/postalsys/emailengine/commit/e70eb7df40245118752cf276cb70090647573216))
41
+ * **smtp:** reject an unparseable message permanently instead of with a 450 ([ef77542](https://github.com/postalsys/emailengine/commit/ef775420a15d94c6a46d6eefe6d37413b5330e6c))
42
+ * **ui:** flag recently restarted workers on the internals page ([435a932](https://github.com/postalsys/emailengine/commit/435a93233ca56c61c42f17d80fb2d4d39fb88381))
43
+
3
44
  ## [2.74.1](https://github.com/postalsys/emailengine/compare/v2.74.0...v2.74.1) (2026-07-24)
4
45
 
5
46
 
@@ -1,5 +1,5 @@
1
1
  {
2
- "creationTime": "2026-07-22T14:46:01.000000",
2
+ "creationTime": "2026-07-27T14:45:52.000000",
3
3
  "prefixes": [
4
4
  {
5
5
  "ipv6Prefix": "2001:4860:4801:2008::/64"
package/lib/account.js CHANGED
@@ -12,25 +12,27 @@ const {
12
12
  resolveCredentials,
13
13
  isEmail,
14
14
  resolveDelegatedAccount,
15
- escapeRedisGlob
15
+ escapeRedisGlob,
16
+ getMailboxStatusKey
16
17
  } = require('./tools');
17
- const crypto = require('crypto');
18
18
  const { MessageChannel } = require('worker_threads');
19
19
  const { MessagePortReadable } = require('./message-port-stream');
20
20
  const { deepStrictEqual, strictEqual } = require('assert');
21
21
  const { encrypt, decrypt } = require('./encrypt');
22
22
  const { oauth2Apps, LEGACY_KEYS, isApiBasedApp } = require('./oauth2-apps');
23
23
  const settings = require('./settings');
24
+ const { buildRetentionPolicy } = require('./queue-retention');
24
25
  const { isDocumentStoreEnabled, documentStoreFeatureEnabled } = require('./document-store');
25
26
  const redisScanDelete = require('./redis-scan-delete');
26
27
  const { customAlphabet } = require('nanoid');
27
28
  const Lock = require('ioredfour');
28
29
  const { redis } = require('./db');
29
30
  const nanoid = customAlphabet('0123456789abcdefghijklmnopqrstuvwxyz', 16);
30
- const { REDIS_PREFIX, ACCOUNT_DELETED_NOTIFY, MAILBOX_HASH } = require('./consts');
31
- const { mimeHtml } = require('@postalsys/email-text-tools');
31
+ const { REDIS_PREFIX, ACCOUNT_DELETED_NOTIFY } = require('./consts');
32
+ const { messageWebSafeHtml } = require('./web-safe-html');
32
33
  const { checkAccountScopes: checkScopes } = require('./oauth/scope-checker');
33
34
  const { ACCOUNT_STATES, ERROR_STATES, calculateEffectiveState, validateAccountState, getDisplayState, formatLastError } = require('./account/account-state');
35
+ const { decodeStoredMailboxEntry } = require('./email-client/imap/listing-diff');
34
36
 
35
37
  // Shared Lock instance to prevent Redis connection leak (one subscriber per Lock instance)
36
38
  // Previously, each Account created its own Lock, causing ~30k connections with 30k accounts
@@ -39,6 +41,11 @@ const defaultLock = new Lock({
39
41
  namespace: 'ee'
40
42
  });
41
43
 
44
+ // Serialization window for Account.update(). The critical section is a few Redis round trips, so
45
+ // the TTL only has to cover a stalled writer, and the wait only has to outlast a normal one.
46
+ const ACCOUNT_UPDATE_LOCK_TTL = 10 * 1000;
47
+ const ACCOUNT_UPDATE_LOCK_WAIT = 5 * 1000;
48
+
42
49
  class Account {
43
50
  constructor(options) {
44
51
  this.redis = options.redis;
@@ -724,11 +731,74 @@ class Account {
724
731
  return accountData;
725
732
  }
726
733
 
727
- // `reauthorized` marks an update that carries credentials supplied by an external caller,
728
- // i.e. possible operator re-authorization. Only the public account-update API route sets it;
729
- // every unattended writer (token renewal, client initialize(), invalidateAccessToken) leaves
730
- // it false and can therefore never trigger the reconnect gate below.
734
+ /**
735
+ * Applies an account update, serialized per account.
736
+ *
737
+ * persistUpdate() is a read-modify-write: it loads the stored account, merges partial
738
+ * `imap`/`smtp`/`oauth2` objects into what it read, and writes the result back. Two writers
739
+ * interleaving there silently lose one of the merges - the case that matters is an unattended
740
+ * OAuth2 token refresh landing between an admin update's read and its write, which puts the
741
+ * stale refreshToken back and leaves the account unable to authenticate until someone
742
+ * reauthorizes it by hand. The same check-then-set applies to the OAuth2 user uniqueness
743
+ * check inside. The lock covers that half only; see dispatchPostUpdateCommands().
744
+ *
745
+ * Lock acquisition failing is not treated as an error. The critical section is a handful of
746
+ * Redis round trips, so a timeout here means Redis is already in trouble; refusing the write
747
+ * would take out token refreshes for every account rather than losing a rare merge.
748
+ *
749
+ * @param {Object} accountData - Account fields to write
750
+ * @param {Object} [opts]
751
+ * @param {boolean} [opts.reauthorized] - Marks an update carrying credentials supplied by an
752
+ * external caller, i.e. possible operator re-authorization. Only the public account-update
753
+ * API route sets it; every unattended writer (token renewal, client initialize(),
754
+ * invalidateAccessToken) leaves it false and can therefore never trigger the reconnect gate.
755
+ * @returns {Promise<Object>} `{ account }`
756
+ */
731
757
  async update(accountData, { reauthorized = false } = {}) {
758
+ const lock = this.getLock();
759
+ const lockKey = `account:update:${accountData.account}`;
760
+ let updateLock;
761
+
762
+ let lockErr;
763
+ try {
764
+ updateLock = await lock.waitAcquireLock(lockKey, ACCOUNT_UPDATE_LOCK_TTL, ACCOUNT_UPDATE_LOCK_WAIT);
765
+ } catch (err) {
766
+ lockErr = err;
767
+ }
768
+
769
+ if (!updateLock?.success) {
770
+ this.logger.warn({ msg: 'Failed to get account update lock, proceeding unserialized', account: accountData.account, lockKey, err: lockErr });
771
+ }
772
+
773
+ let oldAccountData;
774
+ try {
775
+ oldAccountData = await this.persistUpdate(accountData);
776
+ } finally {
777
+ if (updateLock?.success) {
778
+ try {
779
+ await lock.releaseLock(updateLock);
780
+ } catch (err) {
781
+ // The lock expires on its own, so a failed release must not mask the result
782
+ this.logger.error({ msg: 'Failed to release account update lock', account: accountData.account, lockKey, err });
783
+ }
784
+ }
785
+ }
786
+
787
+ await this.dispatchPostUpdateCommands(accountData, oldAccountData, reauthorized);
788
+
789
+ return {
790
+ account: this.account
791
+ };
792
+ }
793
+
794
+ /**
795
+ * The read-modify-write half of update(): loads the stored account, merges partial credential
796
+ * objects into it and writes the result back. Runs under the update lock.
797
+ *
798
+ * @param {Object} accountData - Account fields to write
799
+ * @returns {Promise<Object>} The account as it was before the write
800
+ */
801
+ async persistUpdate(accountData) {
732
802
  let oldAccountData = await this.loadAccountData(accountData.account);
733
803
 
734
804
  if (accountData.oauth2?.provider) {
@@ -821,6 +891,23 @@ class Account {
821
891
  throw error;
822
892
  }
823
893
 
894
+ return oldAccountData;
895
+ }
896
+
897
+ /**
898
+ * Dispatches the reconnect/update commands a persisted change implies.
899
+ *
900
+ * Deliberately runs outside the update lock. These are RPCs into the IMAP worker, and the
901
+ * connection setup they trigger can itself persist an account change (a token renewal during
902
+ * connect), so holding the lock across them would make a writer wait on its own dispatch.
903
+ * Nothing here writes account data; it only compares what was read against what was written.
904
+ *
905
+ * @param {Object} accountData - The fields that were just written
906
+ * @param {Object} oldAccountData - The account as it was before the write
907
+ * @param {boolean} reauthorized - Whether the caller supplied fresh operator credentials
908
+ * @returns {Promise<void>} Resolves once the dispatch has been attempted
909
+ */
910
+ async dispatchPostUpdateCommands(accountData, oldAccountData, reauthorized) {
824
911
  let reconnectRequested = false;
825
912
 
826
913
  if ('imap' in accountData && !reconnectRequested) {
@@ -914,10 +1001,6 @@ class Account {
914
1001
  });
915
1002
  }
916
1003
  }
917
-
918
- return {
919
- account: this.account
920
- };
921
1004
  }
922
1005
 
923
1006
  async genId() {
@@ -1152,7 +1235,7 @@ class Account {
1152
1235
  // consumed and would pile up in Redis.
1153
1236
  if (documentStoreFeatureEnabled) {
1154
1237
  try {
1155
- let queueKeep = (await settings.get('queueKeep')) || true;
1238
+ let queueKeep = (await settings.get('queueKeep')) ?? true;
1156
1239
  let serviceUrl = (await settings.get('serviceUrl')) || null;
1157
1240
 
1158
1241
  let payload = {
@@ -1163,8 +1246,7 @@ class Account {
1163
1246
  };
1164
1247
 
1165
1248
  await this.documentsQueue.add(ACCOUNT_DELETED_NOTIFY, payload, {
1166
- removeOnComplete: queueKeep,
1167
- removeOnFail: queueKeep,
1249
+ ...buildRetentionPolicy(queueKeep),
1168
1250
  attempts: 10,
1169
1251
  backoff: {
1170
1252
  type: 'exponential',
@@ -1331,15 +1413,25 @@ class Account {
1331
1413
  // Batch into a single round-trip to avoid per-mailbox latency with many folders
1332
1414
  let pipeline = this.redis.pipeline();
1333
1415
  for (let path of paths) {
1334
- let redisKey = BigInt('0x' + crypto.createHash(MAILBOX_HASH).update(normalizePath(path)).digest('hex')).toString(36);
1335
- pipeline.hgetall(`${REDIS_PREFIX}iam:${this.account}:h:${redisKey}`);
1416
+ pipeline.hgetall(getMailboxStatusKey(this.account, path));
1336
1417
  }
1337
1418
  let pipelineResults = await pipeline.exec();
1338
1419
 
1339
1420
  for (let i = 0; i < paths.length; i++) {
1340
1421
  let path = paths[i];
1341
1422
  try {
1342
- let decoded = msgpack.decode(storedListing[path]);
1423
+ // Returns false for a corrupt value. Skipping the folder (rather than pushing a
1424
+ // boxed primitive into the response) keeps the rest of the listing usable; the
1425
+ // IMAP sync purges the entry on its next pass (see getCurrentListing), which is
1426
+ // also where the corruption is escalated to the error tracker - once, with every
1427
+ // affected folder, instead of once per request from here. Until that pass runs
1428
+ // the folder is simply missing from a 200 response, which a client reconciling
1429
+ // its own state against this endpoint reads as a deletion.
1430
+ let decoded = decodeStoredMailboxEntry(storedListing[path]);
1431
+ if (!decoded) {
1432
+ this.logger.error({ msg: 'Skipping corrupt stored mailbox listing entry', path, account: this.account });
1433
+ continue;
1434
+ }
1343
1435
 
1344
1436
  if (decoded.path && decoded.delimiter && decoded.path.indexOf(decoded.delimiter) >= 0) {
1345
1437
  decoded.parentPath = decoded.path.substring(0, decoded.path.lastIndexOf(decoded.delimiter));
@@ -1680,12 +1772,7 @@ class Account {
1680
1772
 
1681
1773
  if (options.preProcessHtml && messageData.text && (messageData.text.html || messageData.text.plain)) {
1682
1774
  // If available, use the cached version
1683
- messageData.text.html =
1684
- messageData.text._generatedHtml ||
1685
- mimeHtml({
1686
- html: messageData.text.html,
1687
- text: messageData.text.plain
1688
- });
1775
+ messageData.text.html = messageData.text._generatedHtml || (await messageWebSafeHtml(messageData));
1689
1776
  messageData.text.webSafe = true;
1690
1777
  messageData.text._cachedWebSafe = !!messageData.text._generatedHtml;
1691
1778
  }
@@ -1809,17 +1896,8 @@ class Account {
1809
1896
 
1810
1897
  const { index, client } = this.esClient;
1811
1898
 
1812
- let inboxData = await this.redis.hgetBuffer(this.getMailboxListKey(), 'INBOX');
1813
- let delimiter;
1814
- if (inboxData) {
1815
- try {
1816
- inboxData = msgpack.decode(inboxData);
1817
- delimiter = inboxData.delimiter;
1818
- } catch (err) {
1819
- delimiter = '/'; // hope for the best
1820
- inboxData = false;
1821
- }
1822
- }
1899
+ let inboxData = decodeStoredMailboxEntry(await this.redis.hgetBuffer(this.getMailboxListKey(), 'INBOX'));
1900
+ let delimiter = inboxData ? inboxData.delimiter : '/'; // hope for the best
1823
1901
 
1824
1902
  inboxData = inboxData || {
1825
1903
  path: 'INBOX',
@@ -1831,14 +1909,7 @@ class Account {
1831
1909
  let path = normalizePath(query.path, delimiter);
1832
1910
  let mailboxData = path === 'INBOX' ? inboxData : false;
1833
1911
  if (!mailboxData) {
1834
- mailboxData = await this.redis.hgetBuffer(this.getMailboxListKey(), path);
1835
- if (mailboxData) {
1836
- try {
1837
- mailboxData = msgpack.decode(mailboxData);
1838
- } catch (err) {
1839
- mailboxData = false;
1840
- }
1841
- }
1912
+ mailboxData = decodeStoredMailboxEntry(await this.redis.hgetBuffer(this.getMailboxListKey(), path));
1842
1913
  }
1843
1914
 
1844
1915
  let searchQuery = {
@@ -1975,18 +2046,8 @@ class Account {
1975
2046
  }
1976
2047
 
1977
2048
  if (query.path) {
1978
- let inboxData = await this.redis.hgetBuffer(this.getMailboxListKey(), 'INBOX');
1979
- let delimiter;
1980
-
1981
- if (inboxData) {
1982
- try {
1983
- inboxData = msgpack.decode(inboxData);
1984
- delimiter = inboxData.delimiter;
1985
- } catch (err) {
1986
- delimiter = '/'; // hope for the best
1987
- inboxData = false;
1988
- }
1989
- }
2049
+ let inboxData = decodeStoredMailboxEntry(await this.redis.hgetBuffer(this.getMailboxListKey(), 'INBOX'));
2050
+ let delimiter = inboxData ? inboxData.delimiter : '/'; // hope for the best
1990
2051
 
1991
2052
  inboxData = inboxData || {
1992
2053
  path: 'INBOX',
@@ -1998,14 +2059,7 @@ class Account {
1998
2059
  let path = normalizePath(query.path, delimiter);
1999
2060
  let mailboxData = path === 'INBOX' ? inboxData : false;
2000
2061
  if (!mailboxData) {
2001
- mailboxData = await this.redis.hgetBuffer(this.getMailboxListKey(), path);
2002
- if (mailboxData) {
2003
- try {
2004
- mailboxData = msgpack.decode(mailboxData);
2005
- } catch (err) {
2006
- mailboxData = false;
2007
- }
2008
- }
2062
+ mailboxData = decodeStoredMailboxEntry(await this.redis.hgetBuffer(this.getMailboxListKey(), path));
2009
2063
  }
2010
2064
 
2011
2065
  searchQuery.bool.must.push({
@@ -0,0 +1,51 @@
1
+ 'use strict';
2
+
3
+ // Server-Sent Events feed of account state changes.
4
+ //
5
+ // Registered here rather than inline in workers/api.js so that it is part of the captured route
6
+ // table (test/api-routes-table-test.js): this endpoint streams every account's state transitions
7
+ // and error strings, and it was the one /v1 route no guardrail could see - a dropped auth block
8
+ // on it would have been invisible.
9
+
10
+ const { openChangeStream } = require('../response-stream');
11
+ const { errorResponses } = require('../schemas');
12
+
13
+ /**
14
+ * Registers the change-stream route.
15
+ *
16
+ * @param {Object} args
17
+ * @param {Object} args.server - Hapi server (or a route-recording mock)
18
+ * @param {Object|Boolean} args.CORS_CONFIG
19
+ */
20
+ async function init(args) {
21
+ const { server, CORS_CONFIG } = args;
22
+
23
+ server.route({
24
+ method: 'GET',
25
+ path: '/v1/changes',
26
+
27
+ // Shared with the admin feed (/admin/changes in workers/api.js)
28
+ handler: openChangeStream,
29
+
30
+ options: {
31
+ description: 'Stream state changes',
32
+ notes: 'Stream account state changes as an EventSource',
33
+ tags: ['api', 'Account'],
34
+
35
+ plugins: {
36
+ 'hapi-swagger': {
37
+ produces: ['text/event-stream'],
38
+ responses: errorResponses(401, 403, 429, 500)
39
+ }
40
+ },
41
+
42
+ auth: {
43
+ strategy: 'api-token',
44
+ mode: 'required'
45
+ },
46
+ cors: CORS_CONFIG
47
+ }
48
+ });
49
+ }
50
+
51
+ module.exports = init;
@@ -0,0 +1,160 @@
1
+ 'use strict';
2
+
3
+ // Single registration point for every REST API route module.
4
+ //
5
+ // workers/api.js used to inline this wiring, which meant nothing could enumerate the API surface
6
+ // without booting a Hapi server (the worker joins the worker-thread message port on require).
7
+ // The admin UI half already had this shape - lib/routes-ui.js is a plain module that
8
+ // test/helpers/capture-ui-routes.js can call against a mock server - and this brings the API half
9
+ // in line, so test/api-routes-table-test.js checks the REAL wiring instead of a hand-maintained
10
+ // mirror of it.
11
+ //
12
+ // Every module receives only the arguments it actually reads. Keep it that way: handing all of
13
+ // them the same bag hides which module depends on what, and hides it from the route-table test too.
14
+
15
+ const templateRoutes = require('./template-routes');
16
+ const chatRoutes = require('./chat-routes');
17
+ const accountRoutes = require('./account-routes');
18
+ const messageRoutes = require('./message-routes');
19
+ const exportRoutes = require('./export-routes');
20
+ const pubsubRoutes = require('./pubsub-routes');
21
+ const tokenRoutes = require('./token-routes');
22
+ const mailboxRoutes = require('./mailbox-routes');
23
+ const settingsRoutes = require('./settings-routes');
24
+ const statsRoutes = require('./stats-routes');
25
+ const licenseRoutes = require('./license-routes');
26
+ const outboxRoutes = require('./outbox-routes');
27
+ const webhookRouteRoutes = require('./webhook-route-routes');
28
+ const oauth2AppRoutes = require('./oauth2-app-routes');
29
+ const gatewayRoutes = require('./gateway-routes');
30
+ const deliveryTestRoutes = require('./delivery-test-routes');
31
+ const blocklistRoutes = require('./blocklist-routes');
32
+ const submitRoutes = require('./submit-routes');
33
+ const changesRoutes = require('./changes-routes');
34
+
35
+ /**
36
+ * Registers every /v1 route module on the supplied Hapi server.
37
+ *
38
+ * @param {Object} args
39
+ * @param {Object} args.server - Hapi server (or a route-recording mock)
40
+ * @param {Function} args.call - RPC helper for talking to the main thread
41
+ * @param {Object} args.notify - notify (webhooks) BullMQ queue
42
+ * @param {Object} args.documentsQueue - documents BullMQ queue
43
+ * @param {Object} args.metrics - Prometheus metrics registry
44
+ * @param {Object|Boolean} args.CORS_CONFIG
45
+ * @param {Array} args.FLAG_SORT_ORDER
46
+ * @param {String} args.SMTP_TEST_HOST
47
+ * @param {Number} args.MAX_ATTACHMENT_SIZE
48
+ * @param {Number} args.MAX_BODY_SIZE
49
+ * @param {Number} args.MAX_PAYLOAD_TIMEOUT
50
+ * @param {Boolean} args.documentStoreFeatureEnabled - gate for the deprecated Document Store
51
+ * @param {Object} args.oauth2Schema
52
+ * @param {Object} args.imapSchema
53
+ * @param {Object} args.smtpSchema
54
+ * @param {Object} args.AccountTypeSchema
55
+ * @param {Object} args.OAuth2ProviderSchema
56
+ */
57
+ async function registerApiRoutes(args) {
58
+ const {
59
+ server,
60
+ call,
61
+ notify,
62
+ documentsQueue,
63
+ metrics,
64
+ CORS_CONFIG,
65
+ FLAG_SORT_ORDER,
66
+ SMTP_TEST_HOST,
67
+ MAX_ATTACHMENT_SIZE,
68
+ MAX_BODY_SIZE,
69
+ MAX_PAYLOAD_TIMEOUT,
70
+ documentStoreFeatureEnabled,
71
+ oauth2Schema,
72
+ imapSchema,
73
+ smtpSchema,
74
+ AccountTypeSchema,
75
+ OAuth2ProviderSchema
76
+ } = args;
77
+
78
+ // setup template routes
79
+ await templateRoutes({ server, call, CORS_CONFIG });
80
+
81
+ // setup "chat with email" routes (deprecated Document Store feature; only when enabled)
82
+ if (documentStoreFeatureEnabled) {
83
+ await chatRoutes({ server, call, CORS_CONFIG });
84
+ }
85
+
86
+ // setup account CRUD routes
87
+ await accountRoutes({
88
+ server,
89
+ call,
90
+ documentsQueue,
91
+ oauth2Schema,
92
+ imapSchema,
93
+ smtpSchema,
94
+ CORS_CONFIG,
95
+ AccountTypeSchema,
96
+ OAuth2ProviderSchema,
97
+ metrics
98
+ });
99
+
100
+ // setup message routes
101
+ await messageRoutes({
102
+ server,
103
+ call,
104
+ CORS_CONFIG,
105
+ MAX_ATTACHMENT_SIZE,
106
+ MAX_BODY_SIZE,
107
+ MAX_PAYLOAD_TIMEOUT,
108
+ documentStoreFeatureEnabled
109
+ });
110
+
111
+ // setup export routes
112
+ await exportRoutes({
113
+ server,
114
+ CORS_CONFIG
115
+ });
116
+
117
+ // setup Pub/Sub status route
118
+ await pubsubRoutes({ server, CORS_CONFIG });
119
+
120
+ // setup access token routes
121
+ await tokenRoutes({ server, call, CORS_CONFIG });
122
+
123
+ // setup mailbox routes
124
+ await mailboxRoutes({ server, call, CORS_CONFIG, FLAG_SORT_ORDER });
125
+
126
+ // setup settings routes
127
+ await settingsRoutes({ server, notify, CORS_CONFIG });
128
+
129
+ // setup stats route
130
+ await statsRoutes({ server, call, CORS_CONFIG });
131
+
132
+ // setup license routes
133
+ await licenseRoutes({ server, call, CORS_CONFIG });
134
+
135
+ // setup outbox routes
136
+ await outboxRoutes({ server, CORS_CONFIG });
137
+
138
+ // setup webhook route management routes
139
+ await webhookRouteRoutes({ server, CORS_CONFIG });
140
+
141
+ // setup OAuth2 application routes
142
+ await oauth2AppRoutes({ server, call, CORS_CONFIG, OAuth2ProviderSchema });
143
+
144
+ // setup SMTP gateway routes
145
+ await gatewayRoutes({ server, call, CORS_CONFIG });
146
+
147
+ // setup delivery test routes
148
+ await deliveryTestRoutes({ server, call, CORS_CONFIG, SMTP_TEST_HOST });
149
+
150
+ // setup blocklist routes
151
+ await blocklistRoutes({ server, call, CORS_CONFIG });
152
+
153
+ // setup message submit route
154
+ await submitRoutes({ server, call, CORS_CONFIG, MAX_ATTACHMENT_SIZE, MAX_BODY_SIZE, MAX_PAYLOAD_TIMEOUT });
155
+
156
+ // setup the account state change stream (SSE)
157
+ await changesRoutes({ server, CORS_CONFIG });
158
+ }
159
+
160
+ module.exports = registerApiRoutes;
@@ -6,6 +6,7 @@ const getSecret = require('../get-secret');
6
6
  const settings = require('../settings');
7
7
  const Joi = require('joi');
8
8
  const { failAction } = require('../tools');
9
+ const { COLLAPSE_CLASS } = require('../consts');
9
10
  const { handleError } = require('./route-helpers');
10
11
 
11
12
  const {
@@ -168,7 +169,8 @@ async function init(args) {
168
169
  .falsy('N', 'false', 0)
169
170
  .default(false)
170
171
  .description(
171
- 'Shorthand option to fetch and preprocess HTML and inline images. Overrides `textType`, `preProcessHtml`, and `embedAttachedImages` options.'
172
+ 'Shorthand option to fetch and preprocess HTML and inline images. Overrides `textType`, `preProcessHtml`, and `embedAttachedImages` options. ' +
173
+ `Quoted thread history is folded into a single collapsed <details class="${COLLAPSE_CLASS}"> element.`
172
174
  )
173
175
  .label('WebSafeHtml'),
174
176
 
package/lib/consts.js CHANGED
@@ -200,10 +200,31 @@ module.exports = {
200
200
 
201
201
  NONCE_BYTES: 16,
202
202
 
203
+ // Class names on the collapse marker web-safe HTML wraps quoted thread history in. Part of the
204
+ // output contract - consumers select on them to style or hide the block - so they are defined
205
+ // once here and referenced by both the generator (lib/web-safe-html.js) and the API docs.
206
+ COLLAPSE_CLASS: 'ee-collapsed-thread',
207
+ COLLAPSE_TOGGLE_CLASS: 'ee-collapsed-thread-toggle',
208
+
203
209
  // We are using a legacy hash function in caching operations
204
210
  // This is not insecure but it pops out in security scanners, so we need to mask the name of the hash
205
211
  MAILBOX_HASH: Buffer.from('c2hhMQ', 'base64url').toString(),
206
212
 
213
+ // The only fields persisted for each mailbox in the stored listing hash. Anything else
214
+ // ImapFlow reports (flags, status counters, ...) is derived state that lives elsewhere.
215
+ // Used by lib/email-client/imap/listing-diff.js, which also derives its comparison set from
216
+ // this list so that a newly persisted field is automatically compared too.
217
+ STORED_MAILBOX_FIELDS: ['path', 'specialUse', 'name', 'listed', 'subscribed', 'delimiter', 'specialUseSource', 'noInferiors'],
218
+
219
+ // The mailbox fields the /v1/verifyAccount response carries (lib/tools.js). Deliberately a
220
+ // separate list from STORED_MAILBOX_FIELDS even though the two happen to match today: this
221
+ // one is an API contract, declared as `mailboxBaseFields` in lib/schemas.js and validated
222
+ // against `shortMailboxesSchema`, while the other is a storage decision. Sharing one list
223
+ // means adding a persisted field silently publishes it in a documented response that its
224
+ // schema does not declare. `parentPath` is in the schema but not here - it is derived from
225
+ // the path and delimiter after the pick.
226
+ MAILBOX_RESPONSE_FIELDS: ['path', 'specialUse', 'name', 'listed', 'subscribed', 'delimiter', 'specialUseSource', 'noInferiors'],
227
+
207
228
  // nanoseconds
208
229
  ALLOWED_REDIS_LATENCY: 5 * 1000000,
209
230
 
package/lib/db.js CHANGED
@@ -54,7 +54,10 @@ const REDIS_CONF = Object.assign(
54
54
  return delay;
55
55
  },
56
56
  reconnectOnError(err) {
57
- logger.fatal({ msg: 'Redis connection error', isMainThread, threadId, err });
57
+ // Not fatal: this fires on every transient connection error and we always reconnect,
58
+ // so logging it at fatal turned an ordinary Redis failover into a burst of top
59
+ // severity alerts. The retryStrategy above reports the actual retry cadence.
60
+ logger.warn({ msg: 'Redis connection error', isMainThread, threadId, err });
58
61
  // always try to reconnect
59
62
  return true;
60
63
  },