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
@@ -1,21 +1,41 @@
1
1
  'use strict';
2
2
 
3
3
  const MailComposer = require('nodemailer/lib/mail-composer');
4
+ const { pipeline } = require('stream');
4
5
  const { Splitter, Joiner } = require('@zone-eu/mailsplit');
5
6
  const { HeadersRewriter } = require('./headers-rewriter');
7
+ const { markParseFailure } = require('./smtp-message-processor');
6
8
  const mimeFuncs = require('nodemailer/lib/mime-funcs');
7
9
  const MimeNode = require('nodemailer/lib/mime-node');
8
10
  const addressparser = require('nodemailer/lib/addressparser');
9
11
  const { randomUUID: uuid } = require('crypto');
10
12
  const os = require('os');
11
13
  const libmime = require('libmime');
12
- const { getBoolean, genBaseBoundary } = require('./tools');
14
+ const { getBoolean, genBaseBoundary, download } = require('./tools');
13
15
  const msgpack = require('./msgpack');
14
16
  const crypto = require('crypto');
15
- const simpleParser = require('mailparser').simpleParser;
17
+ const { parseMessage } = require('./parse-message');
16
18
 
17
19
  const { MIME_BOUNDARY_PREFIX } = require('./consts');
18
20
 
21
+ // Runs a message through the splitter and the headers rewriter and collects the result.
22
+ //
23
+ // pipeline() rather than pipe(): Readable.pipe() only listens for errors on the destination, so a
24
+ // failure in the splitter or the rewriter used to be an uncaught exception that took the whole
25
+ // IMAP worker (every account on it) down. pipeline() listens on every stage and tears the chain
26
+ // down on the first error, which download() then rejects with. The splitter's failures (its 1MB
27
+ // header block and MIME node caps, both EMAXLEN) recur on every attempt, so they are marked
28
+ // permanent before pipeline() hands them on; a headers-rewriter error can only come from our own
29
+ // callback, so it keeps the retryable default, like on the SMTP path.
30
+ function collectRewritten(splitter, headersRewriter, joiner, raw) {
31
+ splitter.once('error', markParseFailure);
32
+ pipeline(splitter, headersRewriter, joiner, () => {
33
+ // every failure reaches the joiner, where download() rejects with it
34
+ });
35
+ splitter.end(raw);
36
+ return download(joiner);
37
+ }
38
+
19
39
  function getKeyHeader(licenseInfo) {
20
40
  if (!licenseInfo?.details?.key) {
21
41
  return 'UNLICENSED_COPY';
@@ -244,26 +264,7 @@ async function processMessage(data, licenseInfo) {
244
264
  }
245
265
  });
246
266
 
247
- let message = await new Promise((resolve, reject) => {
248
- let chunks = [];
249
- let chunklen = 0;
250
-
251
- joiner.on('readable', () => {
252
- let chunk;
253
- while ((chunk = joiner.read()) !== null) {
254
- chunks.push(chunk);
255
- chunklen += chunk.length;
256
- }
257
- });
258
-
259
- joiner.once('end', () => {
260
- resolve(Buffer.concat(chunks, chunklen));
261
- });
262
-
263
- joiner.once('error', err => reject(err));
264
- splitter.pipe(headersRewriter).pipe(joiner);
265
- splitter.end(raw);
266
- });
267
+ let message = await collectRewritten(splitter, headersRewriter, joiner, raw);
267
268
 
268
269
  let trackClicks = typeof data.trackClicks === 'boolean' ? data.trackClicks : trackingEnabled;
269
270
  let trackOpens = typeof data.trackOpens === 'boolean' ? data.trackOpens : trackingEnabled;
@@ -290,26 +291,7 @@ async function removeBcc(raw) {
290
291
  headers.remove('bcc');
291
292
  });
292
293
 
293
- return new Promise((resolve, reject) => {
294
- let chunks = [];
295
- let chunklen = 0;
296
-
297
- joiner.on('readable', () => {
298
- let chunk;
299
- while ((chunk = joiner.read()) !== null) {
300
- chunks.push(chunk);
301
- chunklen += chunk.length;
302
- }
303
- });
304
-
305
- joiner.once('end', () => {
306
- resolve(Buffer.concat(chunks, chunklen));
307
- });
308
-
309
- joiner.once('error', err => reject(err));
310
- splitter.pipe(headersRewriter).pipe(joiner);
311
- splitter.end(raw);
312
- });
294
+ return collectRewritten(splitter, headersRewriter, joiner, raw);
313
295
  }
314
296
 
315
297
  function addPreviev(html, previewText) {
@@ -364,7 +346,7 @@ async function getRawEmail(data, licenseInfo, options) {
364
346
 
365
347
  if (options.returnObject) {
366
348
  // parse email into a structured object
367
- const parsed = await simpleParser(response.raw, {
349
+ const parsed = await parseMessage(response.raw, {
368
350
  skipHtmlToText: true,
369
351
  skipImageLinks: true,
370
352
  skipTextToHtml: true,
@@ -380,7 +362,7 @@ async function getRawEmail(data, licenseInfo, options) {
380
362
  parsed.from = parsed.from.value?.[0];
381
363
  }
382
364
 
383
- for (let key of ['to', 'cc', 'bcc']) {
365
+ for (let key of ['to', 'cc', 'bcc', 'replyTo']) {
384
366
  if (parsed[key]) {
385
367
  parsed[key] = parsed[key].value;
386
368
  }
@@ -15,6 +15,10 @@ const util = require('util');
15
15
  * @param {Object} options.gt - Gettext instance for the translation helpers
16
16
  */
17
17
  function registerHandlebarsHelpers(handlebars, { gt }) {
18
+ // The translated message is markup (catalog strings carry <a>, <em> and entities), so the
19
+ // result is a SafeString. Its %s parameters are data, often user-supplied (a redirect URL,
20
+ // an email address), so every parameter is HTML-escaped unless it already is a SafeString.
21
+ // A parameter that has to carry markup is passed through the `markup` helper instead.
18
22
  handlebars.registerHelper('_', (...args) => {
19
23
  let params = args.slice(1, args.length - 1);
20
24
 
@@ -24,16 +28,23 @@ function registerHandlebarsHelpers(handlebars, { gt }) {
24
28
 
25
29
  let translated = localGt.gettext(args[0]);
26
30
  if (params.length) {
27
- translated = util.format(translated, ...params);
31
+ translated = util.format(
32
+ translated,
33
+ ...params.map(param => (param instanceof handlebars.SafeString ? param.toHTML() : handlebars.escapeExpression(param)))
34
+ );
28
35
  }
29
36
 
30
37
  return new handlebars.SafeString(translated);
31
38
  });
32
39
 
33
- // HTML-escape a value for safe interpolation into an otherwise-unescaped context - e.g. a
34
- // dynamic `%s` argument to the SafeString-returning `_` helper. Returns a plain string so
35
- // the surrounding markup stays live while the value itself is entity-escaped.
36
- handlebars.registerHelper('escapeHtml', value => handlebars.escapeExpression(value));
40
+ // HTML-escape a value. Returns a SafeString of the escaped text, so the value is escaped
41
+ // exactly once whether it is rendered directly or handed to the `_` helper as a parameter.
42
+ handlebars.registerHelper('escapeHtml', value => new handlebars.SafeString(handlebars.escapeExpression(value)));
43
+
44
+ // Marks a template-authored string literal as markup, for the rare `_` parameter that is an
45
+ // attribute list rather than data. test/views-csp-guardrail-test.js only admits a quoted
46
+ // literal as its argument, so no variable can reach the page through it.
47
+ handlebars.registerHelper('markup', value => new handlebars.SafeString(typeof value === 'string' ? value : ''));
37
48
 
38
49
  // Translate Bootstrap-era color names emitted by server code (flash types,
39
50
  // systemAlerts levels) into the FlyonUI color vocabulary used by the admin
@@ -54,9 +65,19 @@ function registerHandlebarsHelpers(handlebars, { gt }) {
54
65
  // Ternary for subexpressions: placeholder=(when hasPass "set..." "")
55
66
  handlebars.registerHelper('when', (cond, truthyValue, falsyValue) => (cond ? truthyValue : typeof falsyValue === 'string' ? falsyValue : ''));
56
67
 
57
- handlebars.registerHelper('isodate', time => new Date(Number(time)).toISOString());
68
+ // An unset or unparseable time renders as nothing rather than throwing a RangeError that
69
+ // takes the whole page down
70
+ handlebars.registerHelper('isodate', time => {
71
+ const date = new Date(Number(time));
72
+ return isNaN(date.getTime()) ? '' : date.toISOString();
73
+ });
58
74
 
59
- handlebars.registerHelper('ngettext', (msgid, plural, count) => util.format(gt.ngettext(msgid, plural, count), count));
75
+ // {{ngettext "%d day" "%d days" count [locale]}}; the locale is optional, as for `_`
76
+ handlebars.registerHelper('ngettext', (msgid, plural, count, ...rest) => {
77
+ const locale = rest.length > 1 ? rest[0] : null;
78
+ const localGt = locale && typeof locale === 'string' ? gt.useLocale(locale) : gt;
79
+ return util.format(localGt.ngettext(msgid, plural, count), count);
80
+ });
60
81
 
61
82
  handlebars.registerHelper('equals', function (compareVal, baseVal, options) {
62
83
  if (baseVal === compareVal) {
@@ -102,9 +123,9 @@ function registerHandlebarsHelpers(handlebars, { gt }) {
102
123
  handlebars.registerHelper('lastVal', (value, separator) => {
103
124
  separator = separator || '/';
104
125
 
105
- let res = (value || '').toString().split(separator).pop();
106
-
107
- return new handlebars.SafeString(res);
126
+ // A plain string, so Handlebars escapes it like any other value: the input is a stored
127
+ // Pub/Sub resource name, not markup
128
+ return (value || '').toString().split(separator).pop();
108
129
  });
109
130
 
110
131
  handlebars.registerHelper('formatInteger', (intVal, locale) => {
@@ -14,6 +14,9 @@ const { isApiBasedApp } = require('./oauth2-apps');
14
14
  const { validateAuthToken, withAuthFailureBudget, REASON_MESSAGES } = require('./auth-token');
15
15
  const { constantTimeEqual } = require('./tools');
16
16
  const { isTransientCredentialError } = require('./email-client/credential-errors');
17
+ // Re-exported below: the classifiers live in a leaf module so the proxy handoff can use them
18
+ // without this module's Redis connection
19
+ const { isImapResponseError, toImapResponseError } = require('./imapproxy/response-error');
17
20
 
18
21
  /**
19
22
  * Tags an error as an IMAP authentication rejection for the proxy client.
@@ -30,6 +33,12 @@ function failImapAuth(err) {
30
33
 
31
34
  const authenticationFailedError = message => failImapAuth(new Error(message));
32
35
 
36
+ // One text for every refusal that is about the credential. The shared password is checked before
37
+ // the account is looked up, so if "wrong password" and "right password, no such account" read
38
+ // differently, the difference tells a guesser when the password is right without needing a real
39
+ // account id. The SMTP server answers both with the same text too.
40
+ const FAILED_TO_AUTHENTICATE = 'Failed to authenticate user';
41
+
33
42
  /**
34
43
  * Tags an error as a temporary failure the client should retry rather than a rejected password.
35
44
  * Deliberately without the authenticationFailed flag: nothing refused the credential, the service
@@ -58,31 +67,6 @@ function classifyCredentialFailure(err) {
58
67
  return isTransientCredentialError(err) ? failImapUnavailable(err) : failImapAuth(err);
59
68
  }
60
69
 
61
- /**
62
- * Whether an error already names the IMAP response to answer the client with, as opposed to being
63
- * an internal proxy fault. Both a refusal and a temporary failure carry one.
64
- *
65
- * @param {Error} err - The error to check
66
- * @returns {boolean} True when the error carries an IMAP response
67
- */
68
- function isImapResponseError(err) {
69
- return !!err && (!!err.authenticationFailed || err.serverResponseCode === 'AUTHENTICATIONFAILED' || err.serverResponseCode === 'UNAVAILABLE');
70
- }
71
-
72
- /**
73
- * Renders a tagged failure as the error the IMAP server answers the client with. imap-core reads
74
- * the status off `response`, and an error that carries none is answered BAD, which counts against
75
- * the connection's bad-command budget instead of telling the client what happened.
76
- *
77
- * @param {Error} err - The tagged failure
78
- * @returns {Error} A new error carrying the response line to send
79
- */
80
- function toImapResponseError(err) {
81
- let error = new Error(`${err.serverResponseCode ? `[${err.serverResponseCode}] ` : ''}${err.responseText || err.message || 'Authentication failed'}`);
82
- error.response = err.responseStatus || 'NO';
83
- return error;
84
- }
85
-
86
70
  /**
87
71
  * Builds the IMAP proxy authentication handler.
88
72
  *
@@ -107,7 +91,7 @@ function createImapProxyAuthHandler({ call }) {
107
91
  });
108
92
 
109
93
  if (!result.authenticated) {
110
- throw authenticationFailedError(REASON_MESSAGES[result.reason] || 'Access denied, failed to authenticate user');
94
+ throw authenticationFailedError(REASON_MESSAGES[result.reason] || FAILED_TO_AUTHENTICATE);
111
95
  }
112
96
  }
113
97
 
@@ -121,11 +105,11 @@ function createImapProxyAuthHandler({ call }) {
121
105
  logger.error({ msg: 'Failed to load account data', account: auth.username, err });
122
106
  }
123
107
 
124
- throw authenticationFailedError('Failed to authenticate user');
108
+ throw authenticationFailedError(FAILED_TO_AUTHENTICATE);
125
109
  }
126
110
 
127
111
  if (!accountData) {
128
- throw authenticationFailedError('Access denied, failed to authenticate user');
112
+ throw authenticationFailedError(FAILED_TO_AUTHENTICATE);
129
113
  }
130
114
 
131
115
  return { accountObject, accountData };
@@ -133,7 +117,7 @@ function createImapProxyAuthHandler({ call }) {
133
117
 
134
118
  return async function authenticate(auth, session) {
135
119
  let verified = await withAuthFailureBudget(
136
- { remoteAddress: session.remoteAddress, account: auth.username },
120
+ { remoteAddress: session.remoteAddress, account: auth.username, password: auth.password },
137
121
  () => verifyCredentials(auth, session),
138
122
  () => authenticationFailedError(REASON_MESSAGES.limited)
139
123
  );
@@ -31,6 +31,7 @@ means re-applying these.
31
31
  | `d51e92d2` | 2026-06-06 | Prevent post-BYE command dispatch during teardown |
32
32
  | `31f6a590` | 2026-07-26 | Fix the dead teardown guard in the notification listener |
33
33
  | `74856cf6` | 2026-09-02 | Drop the built-in self-signed key/certificate pair from `tls-options.js`; a listener with TLS and no certificate is refused at startup instead of served with a key that ships in every copy |
34
+ | `2db748fc` | 2026-09-28 | Cap list nesting depth in the parser and guard the debug-log compile; check the command state before accepting a literal and cap literal count/bytes per command; `maxConnections`; error listener and timeout while waiting for the PROXY header; hand bytes pipelined after LOGIN to the proxy (`unbind()` returns `head` and `closed`); lazy indexer load in `imap-tools.js`; indexer `drain` wait and quoted-printable decoding fixes; removed the unused root `memory-notifier.js` |
34
35
 
35
36
  Earlier local changes (`09085d12`, `0a389560`, `7e2e94f3`, `04c2aa90`, `1d6df05e`, `612d9f96`,
36
37
  `13edec58`, `2e0bf1ce`, `b9a3e06c`, `b58a827e`, `1813f089`) are maintenance: dependency swaps
@@ -4,6 +4,12 @@
4
4
 
5
5
  const imapFormalSyntax = require('./imap-formal-syntax');
6
6
 
7
+ // Legitimate commands nest a handful of levels at most (FETCH BODY[HEADER.FIELDS (...)]<0.10>).
8
+ // Anything deeper is hostile, and the recursive walkers (getAttributes() below, the compiler used
9
+ // for the debug log) run out of stack on a few thousand levels, which is a synchronous throw far
10
+ // from any try/catch. Refusing the input here turns it into an ordinary parse error.
11
+ const MAX_NESTING_DEPTH = 100;
12
+
7
13
  class TokenParser {
8
14
  constructor(parent, startPos, str, options) {
9
15
  this.str = (str || '').toString();
@@ -99,6 +105,10 @@ class TokenParser {
99
105
 
100
106
  if (parentNode) {
101
107
  node.parentNode = parentNode;
108
+ node.depth = (parentNode.depth || 0) + 1;
109
+ if (node.depth > MAX_NESTING_DEPTH) {
110
+ throw new Error('Too deep nesting at position ' + (typeof startPos === 'number' ? startPos : this.pos));
111
+ }
102
112
  }
103
113
 
104
114
  if (typeof startPos === 'number') {
@@ -676,3 +686,5 @@ module.exports = function (command, options) {
676
686
 
677
687
  return response;
678
688
  };
689
+
690
+ module.exports.MAX_NESTING_DEPTH = MAX_NESTING_DEPTH;
@@ -5,6 +5,13 @@ const imapHandler = require('./handler/imap-handler');
5
5
  const MAX_MESSAGE_SIZE = 1 * 1024 * 1024;
6
6
  const MAX_BAD_COMMANDS = 50;
7
7
 
8
+ // Every literal is buffered in memory until the command line is complete, so a single command must
9
+ // not be able to announce literals without bound. Real commands carry a few at most (LOGIN has two).
10
+ const MAX_LITERALS_PER_COMMAND = 32;
11
+ // Literal bytes a single command may buffer on top of the largest literal it is allowed to send
12
+ // (the message of an APPEND); covers the small literals that can accompany it.
13
+ const LITERAL_BYTES_SLACK = 64 * 1024;
14
+
8
15
  const commands = new Map([
9
16
 
10
17
  // require must normally be on top of the module
@@ -58,10 +65,48 @@ class IMAPCommand {
58
65
  this.connection = connection;
59
66
  this.payload = '';
60
67
  this.literals = [];
68
+ this.literalBytes = 0;
69
+ // announced literals, counted when the continuation is sent: this.literals only fills
70
+ // once a literal's data has arrived, and a payload announcing many literals in one
71
+ // chunk got continuations past the cap before that count caught up
72
+ this.literalCount = 0;
61
73
  this.first = true;
62
74
  this.connection._badCount = this.connection._badCount || 0;
63
75
  }
64
76
 
77
+ // Drops everything buffered for a command whose literal was refused, so the next line the
78
+ // client sends starts a new command instead of being appended to this one.
79
+ abortCommand() {
80
+ this.payload = '';
81
+ this.literals = [];
82
+ this.literalBytes = 0;
83
+ this.literalCount = 0;
84
+ this.first = true;
85
+ if (this.connection._currentCommand === this) {
86
+ this.connection._currentCommand = false;
87
+ }
88
+ }
89
+
90
+ /**
91
+ * Refuses a literal the command may not send: answers the client, drops what was buffered for
92
+ * the command and hands the error to the caller. Not counted against the protocol-error
93
+ * budget here, because append()'s caller counts every error it is handed; counting here as
94
+ * well charged a refused literal twice
95
+ * @param {string} status - NO or BAD
96
+ * @param {string} message - Response text, also the error message
97
+ * @param {string} code - Error code
98
+ * @param {number} responseCode - HTTP-style code the error carries
99
+ * @param {Function} callback
100
+ */
101
+ refuseLiteral(status, message, code, responseCode, callback) {
102
+ this.connection.send(this.tag + ' ' + status + ' ' + message);
103
+ this.abortCommand();
104
+ let err = new Error(message);
105
+ err.responseCode = responseCode;
106
+ err.code = code;
107
+ return callback(err);
108
+ }
109
+
65
110
  append(command, callback) {
66
111
  let chunks = [];
67
112
  let chunklen = 0;
@@ -98,18 +143,24 @@ class IMAPCommand {
98
143
 
99
144
  if (command.literal) {
100
145
  // check if the literal size is in acceptable bounds
101
- if (isNaN(command.expecting) || isNaN(command.expecting) < 0 || command.expecting > Number.MAX_SAFE_INTEGER) {
102
- let err = new Error('Invalid literal size');
103
- err.responseCode = 400;
104
- err.code = 'InvalidLiteralSize';
105
- this.connection.send(this.tag + ' BAD Invalid literal size');
106
- this.payload = '';
107
- this.literals = [];
108
- this.first = true;
109
- return callback(err);
146
+ if (isNaN(command.expecting) || command.expecting < 0 || command.expecting > Number.MAX_SAFE_INTEGER) {
147
+ return this.refuseLiteral('BAD', 'Invalid literal size', 'InvalidLiteralSize', 400, callback);
148
+ }
149
+
150
+ // Run the state rule before accepting any literal data. It otherwise only runs once the
151
+ // whole command has been buffered, which let an unauthenticated client stream literals
152
+ // for commands it could never run (APPEND before login).
153
+ let handler = typeof this.connection._nextHandler !== 'function' && commands.get(this.command);
154
+ if (handler && handler.state && [].concat(handler.state).indexOf(this.connection.state) < 0) {
155
+ return this.refuseLiteral('BAD', this.command + ' not allowed now', 'InvalidState', 500, callback);
110
156
  }
111
157
 
112
158
  let maxAllowed = Math.max(Number(this.connection._server.options.maxMessage) || 0, MAX_MESSAGE_SIZE);
159
+
160
+ if (this.literalCount >= MAX_LITERALS_PER_COMMAND || this.literalBytes + command.expecting > maxAllowed + LITERAL_BYTES_SLACK) {
161
+ return this.refuseLiteral('NO', 'Too much literal data', 'InvalidLiteralSize', 400, callback);
162
+ }
163
+
113
164
  if (
114
165
  // Allow large literals for selected commands only
115
166
  (!['APPEND'].includes(this.command) && command.expecting > 1024) ||
@@ -143,6 +194,8 @@ class IMAPCommand {
143
194
  }
144
195
 
145
196
  // Accept literal input
197
+ this.literalBytes += command.expecting;
198
+ this.literalCount++;
146
199
  this.connection.send('+ Go ahead');
147
200
 
148
201
  // currently the stream is buffered into a large string and thats it.
@@ -244,7 +297,7 @@ class IMAPCommand {
244
297
  cid: this.connection.id,
245
298
  src: 'C'
246
299
  },
247
- imapHandler.compiler(this.parsed, false, true)
300
+ this.compileForLog()
248
301
  );
249
302
 
250
303
  this.validateCommand(this.parsed, handler, err => {
@@ -334,6 +387,17 @@ class IMAPCommand {
334
387
  return this.payload || '';
335
388
  }
336
389
 
390
+ // The compiler walks the parsed tree recursively and runs here outside the parser's try/catch,
391
+ // from inside the socket's data handler, so a throw would be an uncaught exception. The parser
392
+ // caps the nesting depth, this keeps any other compile failure a logging problem only.
393
+ compileForLog() {
394
+ try {
395
+ return imapHandler.compiler(this.parsed, false, true);
396
+ } catch (err) {
397
+ return [this.tag, this.command, '(* payload not loggable *)'].filter(v => v).join(' ');
398
+ }
399
+ }
400
+
337
401
  sendNotifications(handler, callback) {
338
402
  if (this.connection.state !== 'Selected' || !!handler.disableNotifications) {
339
403
  // nothing to advertise if not in Selected state
@@ -208,9 +208,17 @@ class IMAPConnection extends EventEmitter {
208
208
  // have handed it off to the proxy backend.
209
209
  clearTimeout(this._closingTimeout);
210
210
 
211
+ // The client may already be gone: LOGIN waits on the upstream connection, and the socket
212
+ // can close meanwhile. The proxy then has to close the upstream instead of piping into it.
213
+ let closed = !!(this._closed || this._closing || this._socket.destroyed || !this._socket.readable);
214
+
211
215
  this.writeStream.unpipe(this._socket);
212
216
  this._stopReading();
213
217
 
218
+ // Bytes the client sent after LOGIN, before it saw the OK, were read off the socket but
219
+ // never parsed. They belong to the upstream session.
220
+ let head = this._parser && typeof this._parser.takeRemainder === 'function' ? this._parser.takeRemainder() : Buffer.alloc(0);
221
+
214
222
  if (this._onCloseHandler) {
215
223
  this._socket.removeListener('close', this._onCloseHandler);
216
224
  }
@@ -252,7 +260,7 @@ class IMAPConnection extends EventEmitter {
252
260
  this._server.connections.delete(this);
253
261
  });
254
262
 
255
- return { socket: this._socket };
263
+ return { socket: this._socket, head, closed };
256
264
  }
257
265
 
258
266
  /**