emailengine-app 2.81.1 → 2.82.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 (208) hide show
  1. package/.ncurc.js +12 -6
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +52 -0
  4. package/Dockerfile +4 -2
  5. package/bin/emailengine.js +28 -18
  6. package/config/default.toml +0 -5
  7. package/config/test.toml +0 -5
  8. package/data/google-crawlers.json +1 -1
  9. package/encrypt.js +70 -42
  10. package/getswagger.sh +0 -4
  11. package/lib/account/account-state.js +2 -110
  12. package/lib/account/bounce-store-sweep.js +63 -0
  13. package/lib/account/expected-identity.js +1 -1
  14. package/lib/account-assignment.js +207 -0
  15. package/lib/account.js +374 -878
  16. package/lib/api-reference/index.js +2 -3
  17. package/lib/api-reference/schema-tree.js +53 -3
  18. package/lib/api-routes/account-routes.js +18 -29
  19. package/lib/api-routes/blocklist-routes.js +2 -2
  20. package/lib/api-routes/bull-board-routes.js +1 -6
  21. package/lib/api-routes/export-routes.js +2 -22
  22. package/lib/api-routes/gateway-routes.js +5 -14
  23. package/lib/api-routes/index.js +1 -13
  24. package/lib/api-routes/mailbox-routes.js +2 -7
  25. package/lib/api-routes/mcp-oauth-routes.js +2 -1
  26. package/lib/api-routes/mcp-routes.js +7 -7
  27. package/lib/api-routes/message-routes.js +44 -236
  28. package/lib/api-routes/mint-bounds.js +110 -0
  29. package/lib/api-routes/oauth2-app-routes.js +23 -32
  30. package/lib/api-routes/operation-impact.js +1 -1
  31. package/lib/api-routes/outbox-routes.js +2 -2
  32. package/lib/api-routes/permission-map.js +1 -7
  33. package/lib/api-routes/route-helpers.js +11 -5
  34. package/lib/api-routes/settings-routes.js +19 -19
  35. package/lib/api-routes/stats-routes.js +1 -1
  36. package/lib/api-routes/submit-routes.js +17 -18
  37. package/lib/api-routes/template-routes.js +4 -9
  38. package/lib/api-routes/token-routes.js +27 -5
  39. package/lib/api-token-scheme.js +71 -0
  40. package/lib/arf-detect.js +41 -7
  41. package/lib/auth-token.js +44 -24
  42. package/lib/autodetect-imap-settings.js +163 -123
  43. package/lib/bounce-detect.js +25 -16
  44. package/lib/calendar-event.js +78 -0
  45. package/lib/consts.js +51 -5
  46. package/lib/create-imap-client.js +24 -0
  47. package/lib/db.js +76 -17
  48. package/lib/delivery-error.js +2 -1
  49. package/lib/egress-fetch.js +54 -3
  50. package/lib/egress-filter.js +11 -0
  51. package/lib/email-client/api-retry.js +147 -0
  52. package/lib/email-client/base-client.js +628 -615
  53. package/lib/email-client/gmail/gmail-api.js +38 -125
  54. package/lib/email-client/gmail/send-request.js +1 -1
  55. package/lib/email-client/gmail-client.js +170 -84
  56. package/lib/email-client/imap/mailbox.js +244 -535
  57. package/lib/email-client/imap/stale-view.js +109 -0
  58. package/lib/email-client/imap/subconnection.js +46 -9
  59. package/lib/email-client/imap/sync-operations.js +5 -37
  60. package/lib/email-client/imap-client.js +188 -64
  61. package/lib/email-client/message-builder.js +9 -14
  62. package/lib/email-client/notification-handler.js +5 -219
  63. package/lib/email-client/outlook/graph-api.js +147 -126
  64. package/lib/email-client/outlook/send-request.js +10 -4
  65. package/lib/email-client/outlook-client.js +519 -617
  66. package/lib/email-client/smtp-pool-manager.js +3 -2
  67. package/lib/encrypt.js +184 -19
  68. package/lib/enum-descriptions.js +1 -2
  69. package/lib/export.js +144 -41
  70. package/lib/gateway.js +20 -6
  71. package/lib/get-raw-email.js +26 -44
  72. package/lib/handlebars-helpers.js +31 -10
  73. package/lib/imap-proxy-auth.js +13 -29
  74. package/lib/imapproxy/imap-core/README.md +1 -0
  75. package/lib/imapproxy/imap-core/lib/handler/imap-parser.js +12 -0
  76. package/lib/imapproxy/imap-core/lib/imap-command.js +74 -10
  77. package/lib/imapproxy/imap-core/lib/imap-connection.js +9 -1
  78. package/lib/imapproxy/imap-core/lib/imap-server.js +112 -26
  79. package/lib/imapproxy/imap-core/lib/imap-stream.js +41 -1
  80. package/lib/imapproxy/imap-core/lib/imap-tools.js +10 -2
  81. package/lib/imapproxy/imap-core/lib/indexer/indexer.js +4 -2
  82. package/lib/imapproxy/imap-server.js +17 -177
  83. package/lib/imapproxy/proxy-handoff.js +235 -0
  84. package/lib/imapproxy/response-error.js +33 -0
  85. package/lib/imapproxy/upstream-client.js +2 -2
  86. package/lib/license-beacon.js +3 -9
  87. package/lib/llm-pre-process.js +182 -43
  88. package/lib/logger.js +1 -1
  89. package/lib/lua/ee-export-queue-add.lua +39 -0
  90. package/lib/lua/ee-get-idempotency.lua +15 -3
  91. package/lib/lua/ee-release-attempts.lua +23 -0
  92. package/lib/lua/ee-reserve-attempts.lua +42 -0
  93. package/lib/lua/h-set-bigger.lua +12 -2
  94. package/lib/lua/s-list-accounts.lua +6 -3
  95. package/lib/mcp/index.js +1 -2
  96. package/lib/mcp/listen.js +221 -18
  97. package/lib/mcp/oauth.js +44 -5
  98. package/lib/mcp/resources.js +8 -2
  99. package/lib/mcp/tools.js +13 -0
  100. package/lib/message-port-stream.js +64 -6
  101. package/lib/msgpack.js +1 -6
  102. package/lib/oauth/external-account-signer.js +16 -13
  103. package/lib/oauth/gmail.js +22 -20
  104. package/lib/oauth/outlook.js +19 -16
  105. package/lib/oauth/pubsub/google.js +38 -2
  106. package/lib/oauth/scope-checker.js +4 -7
  107. package/lib/oauth/verify-app.js +2 -2
  108. package/lib/oauth2-apps.js +139 -44
  109. package/lib/openapi/build-document.js +1 -1
  110. package/lib/openapi/joi-schema.js +78 -9
  111. package/lib/parse-message.js +21 -0
  112. package/lib/payload-examples-webhooks.json +4 -7
  113. package/lib/pbkdf2-phc.js +101 -0
  114. package/lib/privileged-settings.js +0 -14
  115. package/lib/rate-limit.js +54 -15
  116. package/lib/redis-scan-delete.js +56 -29
  117. package/lib/redis-url.js +3 -1
  118. package/lib/respawn-backoff.js +5 -4
  119. package/lib/response-stream.js +25 -4
  120. package/lib/rewrite-text-nodes.js +27 -40
  121. package/lib/routes-ui.js +0 -5
  122. package/lib/schemas.js +129 -262
  123. package/lib/sentry.js +21 -5
  124. package/lib/settings.js +58 -59
  125. package/lib/smtp-auth.js +6 -2
  126. package/lib/smtp-message-processor.js +28 -7
  127. package/lib/sso.js +7 -3
  128. package/lib/stream-encrypt.js +14 -13
  129. package/lib/swagger-options.js +3 -1
  130. package/lib/tls/provision.js +69 -3
  131. package/lib/tls/store.js +14 -1
  132. package/lib/tools.js +113 -52
  133. package/lib/totp.js +16 -1
  134. package/lib/ui-routes/account-routes.js +27 -63
  135. package/lib/ui-routes/admin-config-routes.js +111 -134
  136. package/lib/ui-routes/admin-entities-routes.js +101 -191
  137. package/lib/ui-routes/ai-options.js +104 -0
  138. package/lib/ui-routes/auth-routes.js +98 -18
  139. package/lib/ui-routes/export-routes.js +3 -23
  140. package/lib/ui-routes/internals-routes.js +12 -9
  141. package/lib/ui-routes/network-config-routes.js +8 -18
  142. package/lib/ui-routes/oauth-config-routes.js +80 -214
  143. package/lib/ui-routes/route-helpers.js +40 -44
  144. package/lib/ui-routes/unsubscribe-routes.js +2 -2
  145. package/lib/utils/decode-headers.js +32 -5
  146. package/lib/utils/header-map.js +62 -1
  147. package/lib/utils/network.js +2 -0
  148. package/lib/web-safe-html.js +77 -4
  149. package/lib/webhook-request.js +9 -1
  150. package/lib/webhook-routing.js +27 -1
  151. package/lib/webhooks.js +120 -43
  152. package/lib/worker-rpc-error.js +43 -2
  153. package/list-generate.js +13 -2
  154. package/package.json +38 -46
  155. package/sbom.json +1 -1
  156. package/scripts/refresh-test-tokens.js +42 -14
  157. package/server.js +340 -336
  158. package/static/css/flyonui.css +1 -1
  159. package/static/css/src/app.tailwind.css +7 -8
  160. package/static/js/ee-client.js +145 -70
  161. package/static/js/ui.js +350 -154
  162. package/static/licenses.html +460 -1861
  163. package/translations/messages.pot +99 -99
  164. package/views/accounts/browse.hbs +10 -4
  165. package/views/config/ai.hbs +49 -41
  166. package/views/config/oauth/app.hbs +2 -1
  167. package/views/dashboard.hbs +18 -16
  168. package/views/layout/app.hbs +0 -22
  169. package/views/layout/login.hbs +2 -1
  170. package/views/partials/filter_editor_js.hbs +4 -3
  171. package/views/partials/side_menu.hbs +0 -4
  172. package/views/partials/ui/account-picker.hbs +6 -32
  173. package/views/partials/ui/model-picker.hbs +31 -0
  174. package/views/partials/ui/pagination.hbs +6 -1
  175. package/views/partials/ui/picker.hbs +47 -0
  176. package/views/unsubscribe.hbs +1 -1
  177. package/workers/api.js +33 -23
  178. package/workers/export.js +55 -60
  179. package/workers/imap.js +134 -47
  180. package/workers/submit.js +3 -1
  181. package/workers/webhooks.js +46 -27
  182. package/.githooks/pre-commit +0 -80
  183. package/.github/CODE_OF_CONDUCT.md +0 -76
  184. package/.github/contributing.md +0 -17
  185. package/.github/dependabot.yml +0 -22
  186. package/.github/docker-smoke-test.sh +0 -61
  187. package/.github/workflows/deploy.yml +0 -215
  188. package/.github/workflows/e2e.yml +0 -55
  189. package/.github/workflows/release.yaml +0 -217
  190. package/.github/workflows/test.yml +0 -307
  191. package/lib/api-routes/chat-routes.js +0 -535
  192. package/lib/append-list.js +0 -63
  193. package/lib/document-store.js +0 -75
  194. package/lib/es.js +0 -757
  195. package/lib/generate-text-preview.js +0 -61
  196. package/lib/imapproxy/imap-core/memory-notifier.js +0 -129
  197. package/lib/lua/h-push.lua +0 -32
  198. package/lib/pre-process.js +0 -196
  199. package/lib/threads.js +0 -155
  200. package/lib/ui-routes/document-store-routes.js +0 -806
  201. package/playwright.config.js +0 -47
  202. package/views/config/document-store/chat.hbs +0 -286
  203. package/views/config/document-store/index.hbs +0 -146
  204. package/views/config/document-store/mappings/index.hbs +0 -108
  205. package/views/config/document-store/mappings/new.hbs +0 -68
  206. package/views/config/document-store/pre-processing/index.hbs +0 -103
  207. package/views/partials/document_store_header.hbs +0 -30
  208. package/workers/documents.js +0 -1128
package/lib/rate-limit.js CHANGED
@@ -27,6 +27,17 @@ const rateLimitWindowKey = (key, windowSize, now) => {
27
27
  };
28
28
  };
29
29
 
30
+ // INCRBY and EXPIRE as one transaction, returning the new count. The counter behind
31
+ // checkRateLimit(), and behind the exact counters that are not windows at all (the failed
32
+ // second-factor codes of one password-stage session), so both spell the write the same way.
33
+ const incrementCounter = async (key, count, ttl) => {
34
+ let [[resErr, resVal], [expireErr]] = await redis.multi().incrby(key, count).expire(key, ttl).exec();
35
+ if (resErr || expireErr) {
36
+ throw resErr || expireErr;
37
+ }
38
+ return resVal;
39
+ };
40
+
30
41
  const checkRateLimit = async (key, count, allowed, windowSize) => {
31
42
  // The lower bound is what keeps a negative cost from DECREMENTING the counter, i.e. from
32
43
  // buying back attempts against a brute-force guard. Math.max() with a single argument is a
@@ -36,29 +47,57 @@ const checkRateLimit = async (key, count, allowed, windowSize) => {
36
47
  let now = Date.now();
37
48
  let { windowKey, windowSize: normalizedWindowSize, windowEnds } = rateLimitWindowKey(key, windowSize, now);
38
49
 
39
- let [[resErr, resVal], [expireErr]] = await redis.multi().incrby(windowKey, count).expire(windowKey, normalizedWindowSize).exec();
40
- if (resErr || expireErr) {
41
- throw resErr || expireErr;
42
- }
50
+ let resVal = await incrementCounter(windowKey, count, normalizedWindowSize);
43
51
 
44
52
  // Inclusive: the request that was just counted is admitted up to and including the limit
45
53
  return windowResult({ key, count: resVal, success: resVal <= allowed, allowed, now, windowEnds });
46
54
  };
47
55
 
48
- // Reads a window's counter without adding to it. For guards that count failures only: the check
49
- // ahead of an authentication attempt must not spend the budget of the client making it, so it
50
- // only looks, and only a refusal is recorded (through checkRateLimit) afterwards.
51
- const peekRateLimit = async (key, allowed, windowSize) => {
52
- let now = Date.now();
53
- let { windowKey, windowEnds } = rateLimitWindowKey(key, windowSize, now);
56
+ // A failure budget over one window, in the shape reserveAttempts() takes: the counter is the
57
+ // window's key, the limit is inclusive, and the counter lives for the window
58
+ const windowBudget = (key, allowed, windowSize, now) => {
59
+ let { windowKey, windowSize: normalizedWindowSize } = rateLimitWindowKey(key, windowSize, now);
60
+ return { key: windowKey, limit: allowed, ttl: normalizedWindowSize };
61
+ };
54
62
 
55
- let count = Number(await redis.get(windowKey)) || 0;
63
+ /**
64
+ * Reserves one attempt in every budget at once, or in none of them.
65
+ *
66
+ * For guards that count failures only: the attempt is reserved before it is checked and given
67
+ * back with releaseAttempts() when it is accepted, so only a refusal stays counted. Reserving is
68
+ * what a look-then-record check left open: parallel attempts all read the same count and each
69
+ * went ahead. A refused reservation is taken back by the script, so a spent budget holds at its
70
+ * limit rather than growing with every refused attempt (lib/lua/ee-reserve-attempts.lua).
71
+ *
72
+ * @param {Array<{key: String, limit: Number, ttl: Number}>} budgets - Full Redis key, inclusive
73
+ * limit and counter lifetime in seconds of each budget, see windowBudget()
74
+ * @returns {Promise<{admitted: Boolean, counts: Number[]}>} The counts include the reservation
75
+ * when it was admitted, and are the counts as they were when it was not
76
+ */
77
+ const reserveAttempts = async budgets => {
78
+ let limitsAndTtls = [];
79
+ for (let budget of budgets) {
80
+ limitsAndTtls.push(budget.limit, budget.ttl);
81
+ }
82
+ let [admitted, ...counts] = await redis.eeReserveAttempts(budgets.length, ...budgets.map(budget => budget.key), ...limitsAndTtls);
83
+ return { admitted: !!admitted, counts };
84
+ };
56
85
 
57
- // Exclusive: nothing was counted, so the question is whether one more attempt still fits
58
- return windowResult({ key, count, success: count < allowed, allowed, now, windowEnds });
86
+ /**
87
+ * Gives back a reservation for an attempt that was accepted. Best effort by design: the caller
88
+ * does not wait for it, and a release that fails only costs that client one attempt of its budget.
89
+ *
90
+ * @param {String[]} keys - The counters that were reserved
91
+ * @returns {Promise<void>}
92
+ */
93
+ const releaseAttempts = async keys => {
94
+ if (!keys.length) {
95
+ return;
96
+ }
97
+ await redis.eeReleaseAttempts(keys.length, ...keys);
59
98
  };
60
99
 
61
- // One result shape for both reads, so a field added to one cannot silently miss the other
100
+ // One result shape for the window check, so a field added to it is added in one place
62
101
  function windowResult({ key, count, success, allowed, now, windowEnds }) {
63
102
  return {
64
103
  key,
@@ -70,4 +109,4 @@ function windowResult({ key, count, success, allowed, now, windowEnds }) {
70
109
  };
71
110
  }
72
111
 
73
- module.exports = { checkRateLimit, peekRateLimit, rateLimitWindowKey };
112
+ module.exports = { checkRateLimit, rateLimitWindowKey, windowBudget, reserveAttempts, releaseAttempts, incrementCounter };
@@ -3,13 +3,33 @@
3
3
  const crypto = require('crypto');
4
4
  const { REDIS_BATCH_DELETE_SIZE } = require('./consts');
5
5
 
6
- async function redisScanDelete(redis, logger, match) {
7
- let deletedKeys = 0;
6
+ // Runs one batch of DELs and resolves to the number of keys Redis reports as removed. Rejects when
7
+ // the pipeline itself fails or any DEL in it answered with an error: counting a key as deleted
8
+ // before (or without) the command running made a failed cleanup look like a complete one.
9
+ function execBatch(pipeline) {
10
+ return new Promise((resolve, reject) => {
11
+ pipeline.exec((err, results) => {
12
+ if (err) {
13
+ return reject(err);
14
+ }
15
+ let removed = 0;
16
+ for (let [cmdErr, reply] of results || []) {
17
+ if (cmdErr) {
18
+ return reject(cmdErr);
19
+ }
20
+ removed += Number(reply) || 0;
21
+ }
22
+ resolve(removed);
23
+ });
24
+ });
25
+ }
8
26
 
27
+ async function redisScanDelete(redis, logger, match) {
9
28
  return new Promise((resolve, reject) => {
10
29
  const stream = redis.scanStream({ match, count: REDIS_BATCH_DELETE_SIZE });
11
30
  let pipeline = redis.pipeline();
12
31
  let batchKeys = [];
32
+ let batches = [];
13
33
 
14
34
  let scanId = crypto.randomBytes(12).toString('base64');
15
35
 
@@ -20,6 +40,33 @@ async function redisScanDelete(redis, logger, match) {
20
40
  batchSize: REDIS_BATCH_DELETE_SIZE
21
41
  });
22
42
 
43
+ const flush = () => {
44
+ const keyCount = batchKeys.length;
45
+ const batch = execBatch(pipeline).then(
46
+ removed => {
47
+ logger.trace({
48
+ msg: `Deleted keys in batch`,
49
+ scanId,
50
+ match,
51
+ keyCount,
52
+ removed
53
+ });
54
+ return removed;
55
+ },
56
+ err => {
57
+ logger.error({ msg: 'Failed to delete scanned keys', scanId, match, keyCount, err });
58
+ throw err;
59
+ }
60
+ );
61
+ // Observed here so a batch failing while the scan is still running is not reported as
62
+ // an unhandled rejection; the settled result is read again on stream end.
63
+ batch.catch(() => {});
64
+ batches.push(batch);
65
+
66
+ batchKeys = [];
67
+ pipeline = redis.pipeline();
68
+ };
69
+
23
70
  stream.on('data', resultKeys => {
24
71
  if (resultKeys.length) {
25
72
  logger.trace({
@@ -33,43 +80,23 @@ async function redisScanDelete(redis, logger, match) {
33
80
 
34
81
  for (let ik = 0; ik < resultKeys.length; ik++) {
35
82
  batchKeys.push(resultKeys[ik]);
36
- deletedKeys++;
37
83
  pipeline.del(resultKeys[ik]);
38
84
  }
39
85
 
40
86
  if (batchKeys.length >= REDIS_BATCH_DELETE_SIZE) {
41
- const keyCount = batchKeys.length;
42
-
43
- pipeline.exec(() => {
44
- logger.trace({
45
- msg: `Deleted keys in batch`,
46
- scanId,
47
- match,
48
- keyCount
49
- });
50
- });
51
-
52
- batchKeys = [];
53
- pipeline = redis.pipeline();
87
+ flush();
54
88
  }
55
89
  });
56
90
 
57
91
  stream.on('end', () => {
58
- const keyCount = batchKeys.length;
59
- if (!keyCount) {
60
- return resolve(deletedKeys);
92
+ if (batchKeys.length) {
93
+ flush();
61
94
  }
62
95
 
63
- pipeline.exec(() => {
64
- logger.trace({
65
- msg: `Deleted keys in batch`,
66
- scanId,
67
- match,
68
- keyCount
69
- });
70
-
71
- resolve(deletedKeys);
72
- });
96
+ Promise.all(batches).then(
97
+ counts => resolve(counts.reduce((sum, count) => sum + count, 0)),
98
+ err => reject(err)
99
+ );
73
100
  });
74
101
 
75
102
  stream.on('error', err => {
package/lib/redis-url.js CHANGED
@@ -41,7 +41,9 @@ module.exports = redisConf => {
41
41
  }
42
42
  switch (key) {
43
43
  case 'hostname':
44
- parsedUrl.host = value;
44
+ // WHATWG URL keeps the brackets around an IPv6 literal, which net.connect() cannot
45
+ // resolve, so redis://[::1]:6379 never connected
46
+ parsedUrl.host = value.replace(/^\[(.*)\]$/, '$1');
45
47
  break;
46
48
 
47
49
  case 'port':
@@ -7,8 +7,9 @@
7
7
  // indefinitely, pinning a core and burying every other log line under the same repeating stack.
8
8
  //
9
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.
10
+ // worker's failures - the delay only grows while a given key keeps dying quickly, and a worker that
11
+ // stays up resets its own key immediately. server.js keys it by spawn slot (one per thread it
12
+ // supervises), so exits of sibling workers of the same type do not add up.
12
13
 
13
14
  const DEFAULT_BASE_DELAY = 1000;
14
15
  const DEFAULT_MAX_DELAY = 60 * 1000;
@@ -20,7 +21,7 @@ const DEFAULT_STABLE_UPTIME = 60 * 1000;
20
21
  const DEFAULT_JITTER = 0.2;
21
22
 
22
23
  /**
23
- * Tracks per-type crash streaks and derives how long to wait before the next respawn.
24
+ * Tracks per-key crash streaks and derives how long to wait before the next respawn.
24
25
  */
25
26
  class RespawnTracker {
26
27
  constructor(opts) {
@@ -38,7 +39,7 @@ class RespawnTracker {
38
39
  this.jitter = jitter;
39
40
  this.random = random;
40
41
 
41
- // worker type -> count of consecutive short-lived exits
42
+ // key (spawn slot or worker type) -> count of consecutive short-lived exits
42
43
  this.failures = new Map();
43
44
  }
44
45
 
@@ -22,6 +22,13 @@ const registeredPublishers = new Set();
22
22
  // intermediate proxies from timing the connection out.
23
23
  const KEEP_ALIVE_INTERVAL = 90 * 1000;
24
24
 
25
+ // How much unsent output a stream may hold before the client is treated as gone. A consumer that
26
+ // keeps the connection open but stops reading (a suspended tab, a stuck proxy, a deliberately
27
+ // idle holder of an `events` grant) applies backpressure, and every change event fanned out to it
28
+ // used to pile up in this Transform's buffers for as long as the socket stayed open. Dropping the
29
+ // stream instead is what an SSE client already knows how to handle: EventSource reconnects.
30
+ const MAX_BUFFERED_BYTES = 2 * 1024 * 1024;
31
+
25
32
  class ResponseStream extends Transform {
26
33
  /**
27
34
  * @param {Object} [options]
@@ -29,9 +36,11 @@ class ResponseStream extends Transform {
29
36
  * Defaults to the shared change-feed set that publishChangeEvent() fans out to; the
30
37
  * MCP listen streams (lib/mcp/listen.js) pass their own set so the two feeds cannot
31
38
  * receive each other's frames.
39
+ * @param {Number} [options.maxBuffered] - unsent bytes tolerated before the stream is dropped
32
40
  */
33
41
  constructor(options) {
34
42
  super();
43
+ this.maxBuffered = (options && options.maxBuffered) || MAX_BUFFERED_BYTES;
35
44
  this.registry = (options && options.registry) || registeredPublishers;
36
45
  this.registry.add(this);
37
46
  this.periodicKeepAliveTimer = false;
@@ -53,9 +62,13 @@ class ResponseStream extends Transform {
53
62
  if (this._finalized || this.destroyed) {
54
63
  return;
55
64
  }
56
- this.write(': still here\n\n');
57
- if (this._compressor) {
58
- this._compressor.flush();
65
+ // A keep-alive exists to show the connection some traffic; while output is already
66
+ // queued behind a client that is not reading, adding one only grows the queue
67
+ if (!this.writableNeedDrain) {
68
+ this.write(': still here\n\n');
69
+ if (this._compressor) {
70
+ this._compressor.flush();
71
+ }
59
72
  }
60
73
  this.updateTimer();
61
74
  }, KEEP_ALIVE_INTERVAL);
@@ -72,6 +85,14 @@ class ResponseStream extends Transform {
72
85
  }
73
86
  let sendData = JSON.stringify(payload);
74
87
  this.write('event: message\ndata:' + sendData + '\n\n');
88
+
89
+ // Both halves count: once the readable side is full the Transform stops consuming, and
90
+ // everything after that waits on the writable side
91
+ if (this.writableLength + this.readableLength > this.maxBuffered) {
92
+ this.finalize();
93
+ return;
94
+ }
95
+
75
96
  if (this._compressor) {
76
97
  this._compressor.flush();
77
98
  }
@@ -166,4 +187,4 @@ function openChangeStream(request, h) {
166
187
  return response;
167
188
  }
168
189
 
169
- module.exports = { ResponseStream, registeredPublishers, openChangeStream, openSseStream };
190
+ module.exports = { ResponseStream, registeredPublishers, openChangeStream, openSseStream, MAX_BUFFERED_BYTES };
@@ -4,9 +4,10 @@ const Rewriter = require('@zone-eu/mailsplit/lib/node-rewriter');
4
4
  const Splitter = require('@zone-eu/mailsplit/lib/message-splitter');
5
5
  const Joiner = require('@zone-eu/mailsplit/lib/message-joiner');
6
6
  const encodingJapanese = require('encoding-japanese');
7
- const { Transform } = require('stream');
7
+ const { Transform, pipeline } = require('stream');
8
8
  const iconv = require('iconv-lite');
9
9
  const LeWindows = require('nodemailer/lib/mime-node/le-windows');
10
+ const { markParseFailure } = require('./smtp-message-processor');
10
11
  const logger = require('./logger').child({ component: 'rewrite-text-nodes' });
11
12
 
12
13
  class JPDecoder extends Transform {
@@ -184,56 +185,42 @@ function rewriteTextNodes(source, options) {
184
185
  });
185
186
  });
186
187
 
187
- // set up pipe chain
188
- splitter.pipe(rewriter).pipe(joiner).pipe(newlines);
189
-
190
- joiner.on('error', err => {
191
- newlines.emit('error', err);
192
- });
193
-
194
188
  const finalChunks = [];
195
189
  let finalChunkLen = 0;
196
190
 
197
- newlines.on('readable', () => {
198
- let chunk;
199
- while ((chunk = newlines.read()) !== null) {
200
- if (typeof chunk === 'string') {
201
- chunk = Buffer.from(chunk, 'utf-8');
202
- }
203
-
204
- finalChunks.push(chunk);
205
- finalChunkLen += chunk.length;
191
+ newlines.on('data', chunk => {
192
+ if (typeof chunk === 'string') {
193
+ chunk = Buffer.from(chunk, 'utf-8');
206
194
  }
207
- });
208
195
 
209
- newlines.on('error', err => {
210
- try {
211
- source.destroy();
212
- } catch (E) {
213
- // ignore
214
- }
215
- reject(err);
196
+ finalChunks.push(chunk);
197
+ finalChunkLen += chunk.length;
216
198
  });
217
199
 
218
200
  newlines.on('end', () => {
219
201
  resolve(Buffer.concat(finalChunks, finalChunkLen));
220
202
  });
221
203
 
222
- if (typeof source === 'string') {
223
- splitter.end(Buffer.from(source));
224
- } else if (Buffer.isBuffer(source)) {
225
- splitter.end(source);
226
- } else {
227
- source
228
- .once('error', err => {
229
- try {
230
- source.destroy();
231
- } catch (E) {
232
- // ignore
233
- }
234
- reject(err);
235
- })
236
- .pipe(splitter);
204
+ // A splitter failure (EMAXLEN: a 1MB header block or too many MIME nodes) is a verdict on
205
+ // the message and recurs on every attempt, so it is marked permanent the same way the
206
+ // SMTP and raw-message paths mark it.
207
+ splitter.once('error', markParseFailure);
208
+
209
+ // pipeline() rather than pipe(): Readable.pipe() only listens for errors on the
210
+ // destination, so a splitter limit used to be an uncaught exception that took the whole
211
+ // worker down. pipeline() listens on every stage, source included, and tears the whole
212
+ // chain down on the first failure. The node decoders are not stages of the chain; their
213
+ // failures are emitted on the tail above, which pipeline() picks up like any other.
214
+ const inline = typeof source === 'string' || Buffer.isBuffer(source);
215
+ const stages = inline ? [splitter, rewriter, joiner, newlines] : [source, splitter, rewriter, joiner, newlines];
216
+ pipeline(...stages, err => {
217
+ if (err) {
218
+ reject(err);
219
+ }
220
+ });
221
+
222
+ if (inline) {
223
+ splitter.end(Buffer.isBuffer(source) ? source : Buffer.from(source));
237
224
  }
238
225
  });
239
226
  }
package/lib/routes-ui.js CHANGED
@@ -9,7 +9,6 @@ const dashboardRoutes = require('./ui-routes/dashboard-routes');
9
9
  const referenceRoutes = require('./ui-routes/reference-routes');
10
10
  const exportRoutes = require('./ui-routes/export-routes');
11
11
  const networkConfigRoutes = require('./ui-routes/network-config-routes');
12
- const documentStoreRoutes = require('./ui-routes/document-store-routes');
13
12
  const authRoutes = require('./ui-routes/auth-routes');
14
13
  const oauthConfigRoutes = require('./ui-routes/oauth-config-routes');
15
14
  const adminConfigRoutes = require('./ui-routes/admin-config-routes');
@@ -48,10 +47,6 @@ function applyRoutes(server, call) {
48
47
  // TLS certificates: the configuration page, and the ACME challenge route the CA calls
49
48
  tlsConfigRoutes({ server, call });
50
49
 
51
- // Document Store (Elasticsearch) config routes (deprecated feature; the module self-gates
52
- // and registers no routes unless the Document Store feature is enabled)
53
- documentStoreRoutes({ server });
54
-
55
50
  // Admin auth and user-profile routes (login, logout, TOTP, passkeys, password)
56
51
  authRoutes({ server });
57
52