emailengine-app 2.84.1 → 2.85.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 (147) hide show
  1. package/.dockerignore +6 -0
  2. package/.ncurc.js +5 -3
  3. package/.prettierignore +5 -1
  4. package/.prettierrc.js +2 -0
  5. package/.release-please-manifest.json +1 -1
  6. package/CHANGELOG.md +61 -0
  7. package/Dockerfile +8 -2
  8. package/README.md +1 -1
  9. package/bin/emailengine.js +444 -403
  10. package/copy-static-files.sh +39 -14
  11. package/data/google-crawlers.json +1 -1
  12. package/data/public_suffix_list.dat +16562 -0
  13. package/docker-compose.yml +1 -1
  14. package/eslint.config.js +81 -99
  15. package/lib/account/own-account-key.js +42 -0
  16. package/lib/account-assignment.js +1 -33
  17. package/lib/account.js +68 -24
  18. package/lib/add-trackers.js +11 -4
  19. package/lib/api-reference/format.js +4 -3
  20. package/lib/api-routes/account-routes.js +244 -26
  21. package/lib/api-routes/blocklist-routes.js +23 -2
  22. package/lib/api-routes/delivery-test-routes.js +26 -3
  23. package/lib/api-routes/export-routes.js +28 -2
  24. package/lib/api-routes/gateway-routes.js +37 -5
  25. package/lib/api-routes/mailbox-routes.js +41 -2
  26. package/lib/api-routes/message-routes.js +104 -4
  27. package/lib/api-routes/mint-bounds.js +11 -0
  28. package/lib/api-routes/oauth2-app-routes.js +48 -15
  29. package/lib/api-routes/outbox-routes.js +45 -11
  30. package/lib/api-routes/permission-map.js +12 -1
  31. package/lib/api-routes/route-helpers.js +125 -3
  32. package/lib/api-routes/settings-routes.js +23 -2
  33. package/lib/api-routes/submit-routes.js +338 -309
  34. package/lib/api-routes/template-routes.js +38 -2
  35. package/lib/api-routes/token-routes.js +142 -96
  36. package/lib/api-routes/webhook-route-routes.js +13 -2
  37. package/lib/auth-token.js +23 -10
  38. package/lib/bounce-detect.js +414 -210
  39. package/lib/consts.js +39 -4
  40. package/lib/create-imap-client.js +41 -2
  41. package/lib/email-client/base-client.js +30 -41
  42. package/lib/email-client/gmail-client.js +30 -18
  43. package/lib/email-client/imap/mailbox.js +13 -23
  44. package/lib/email-client/imap/response-metrics.js +75 -0
  45. package/lib/email-client/imap/subconnection.js +1 -1
  46. package/lib/email-client/imap-client.js +6 -3
  47. package/lib/email-client/message-builder.js +7 -2
  48. package/lib/email-client/notification-handler.js +1 -2
  49. package/lib/email-client/outlook/graph-api.js +17 -2
  50. package/lib/email-client/outlook-client.js +6 -3
  51. package/lib/email-client/smtp-pool-manager.js +6 -0
  52. package/lib/encrypt.js +9 -0
  53. package/lib/export.js +3 -1
  54. package/lib/gateway.js +2 -3
  55. package/lib/get-raw-email.js +4 -2
  56. package/lib/hapi-request-logger.js +107 -0
  57. package/lib/imap-proxy-auth.js +14 -1
  58. package/lib/imapproxy/imap-core/README.md +6 -5
  59. package/lib/imapproxy/imap-core/lib/commands/authenticate-plain.js +1 -0
  60. package/lib/imapproxy/imap-core/lib/commands/login.js +1 -0
  61. package/lib/imapproxy/imap-core/lib/imap-command.js +86 -43
  62. package/lib/imapproxy/imap-core/lib/imap-stream.js +58 -13
  63. package/lib/imapproxy/imap-core/lib/indexer/indexer.js +3 -1
  64. package/lib/mcp/listen.js +10 -1
  65. package/lib/mcp/tools.js +37 -8
  66. package/lib/notify-attachments.js +17 -0
  67. package/lib/oauth/external-account-config.js +3 -1
  68. package/lib/oauth/gmail.js +21 -48
  69. package/lib/oauth/mail-ru.js +5 -38
  70. package/lib/oauth/outlook-mailbox.js +35 -0
  71. package/lib/oauth/outlook.js +26 -44
  72. package/lib/oauth/state.js +24 -0
  73. package/lib/oauth2-apps.js +1 -1
  74. package/lib/pbkdf2-phc.js +19 -2
  75. package/lib/privileged-settings.js +6 -3
  76. package/lib/redis-scan-delete.js +15 -1
  77. package/lib/schemas.js +79 -33
  78. package/lib/settings.js +13 -1
  79. package/lib/smtp-auth.js +23 -0
  80. package/lib/sso.js +1 -1
  81. package/lib/swagger-options.js +1 -1
  82. package/lib/thread-diagnostics.js +46 -0
  83. package/lib/timezones.js +109 -0
  84. package/lib/token-permission-view.js +3 -3
  85. package/lib/tools.js +285 -66
  86. package/lib/totp.js +2 -5
  87. package/lib/translations.js +1 -2
  88. package/lib/ui-routes/account-routes.js +491 -491
  89. package/lib/ui-routes/account-setup.js +99 -0
  90. package/lib/ui-routes/admin-config-routes.js +98 -48
  91. package/lib/ui-routes/admin-entities-routes.js +113 -31
  92. package/lib/ui-routes/auth-routes.js +137 -62
  93. package/lib/ui-routes/connection-security-form.js +74 -0
  94. package/lib/ui-routes/form-lists.js +46 -0
  95. package/lib/ui-routes/internals-routes.js +5 -0
  96. package/lib/ui-routes/mcp-consent-routes.js +5 -1
  97. package/lib/ui-routes/oauth-config-routes.js +133 -100
  98. package/lib/ui-routes/route-helpers.js +19 -3
  99. package/lib/ui-routes/sign-in-helpers.js +59 -0
  100. package/lib/ui-routes/tls-config-routes.js +58 -15
  101. package/lib/ui-routes/unsubscribe-routes.js +6 -3
  102. package/lib/utils/back-off.js +82 -0
  103. package/lib/utils/map-concurrent.js +36 -0
  104. package/lib/utils/murmurhash3.js +66 -0
  105. package/lib/utils/network.js +28 -0
  106. package/lib/utils/provider-id.js +27 -0
  107. package/lib/utils/public-suffix.js +122 -0
  108. package/lib/utils/random-id.js +26 -0
  109. package/lib/utils/require-tls.js +33 -0
  110. package/lib/utils/version.js +74 -0
  111. package/lib/web-safe-html.js +5 -6
  112. package/lib/webhook-penalty.js +75 -0
  113. package/lib/webhook-routing.js +49 -2
  114. package/lib/webhooks.js +41 -6
  115. package/package.json +37 -39
  116. package/sbom.json +7980 -1
  117. package/server.js +659 -455
  118. package/static/js/ace/ace.js +1 -1
  119. package/static/js/ace/mode-handlebars.js +1 -1
  120. package/static/js/ace/mode-html.js +1 -1
  121. package/static/js/ace/mode-javascript.js +1 -1
  122. package/static/js/ace/mode-markdown.js +1 -1
  123. package/static/js/ace/worker-html.js +1 -1
  124. package/static/js/ace/worker-javascript.js +1 -1
  125. package/static/js/ace/worker-json.js +1 -1
  126. package/static/js/ee-client.js +5 -0
  127. package/static/licenses.html +191 -1016
  128. package/translations/messages.pot +70 -71
  129. package/views/account/security.hbs +10 -0
  130. package/views/accounts/account.hbs +11 -11
  131. package/views/accounts/edit.hbs +6 -2
  132. package/views/config/ai.hbs +1 -1
  133. package/views/config/security.hbs +2 -2
  134. package/views/config/service.hbs +3 -0
  135. package/views/internals/index.hbs +8 -0
  136. package/views/partials/gateway_form.hbs +3 -1
  137. package/views/partials/webhook_form.hbs +1 -1
  138. package/views/suppression-lists/index.hbs +1 -1
  139. package/workers/api.js +780 -585
  140. package/workers/export.js +1 -1
  141. package/workers/submit.js +1 -1
  142. package/workers/webhooks.js +54 -34
  143. package/config/test.toml +0 -46
  144. package/install.sh +0 -428
  145. package/setup-production.sh +0 -215
  146. package/systemd/emailengine.service +0 -97
  147. package/systemd/nginx-proxy.conf +0 -77
@@ -87,8 +87,23 @@ async function request(context, url, method, payload, options = {}) {
87
87
 
88
88
  options.headers.Prefer = preferValues.join(', ');
89
89
 
90
- // Construct full API URL if not already absolute
91
- let apiUrl = /^https:/.test(url) ? url : new URL(`/v1.0${url}`, context.oAuth2Client.apiBase).href;
90
+ // Construct full API URL if not already absolute. An absolute URL comes from a Graph
91
+ // response (@odata.nextLink, @odata.deltaLink) and is only followed on the Graph origin
92
+ // the app is configured for: the bearer token goes with the request, and a response is
93
+ // not a place to take a new host from
94
+ let apiUrl;
95
+ if (/^https:/.test(url)) {
96
+ let graphOrigin = new URL(context.oAuth2Client.apiBase).origin;
97
+ if (new URL(url).origin !== graphOrigin) {
98
+ let error = new Error('Refusing to follow a Graph link outside the configured API origin');
99
+ error.code = 'InvalidGraphUrl';
100
+ error.statusCode = 502;
101
+ throw error;
102
+ }
103
+ apiUrl = url;
104
+ } else {
105
+ apiUrl = new URL(`/v1.0${url}`, context.oAuth2Client.apiBase).href;
106
+ }
92
107
 
93
108
  let result = await context.oAuth2Client.request(tokenData.accessToken, apiUrl, method, payload, options);
94
109
 
@@ -1,6 +1,7 @@
1
1
  'use strict';
2
2
 
3
3
  const { BaseClient, metricsMeta } = require('./base-client');
4
+ const { isSafePathSegment } = require('../utils/provider-id');
4
5
  const { isTransientCredentialError } = require('./credential-errors');
5
6
  const { Account } = require('../account');
6
7
  const { checkAccountScopes } = require('../oauth/scope-checker');
@@ -4123,8 +4124,10 @@ class OutlookClient extends BaseClient {
4123
4124
  async getAttachmentContent(attachmentId, options) {
4124
4125
  options = options || {};
4125
4126
 
4126
- // Decode compound attachment ID
4127
- const [emailId, id] = this.unpackApiId(attachmentId, parts => parts.length >= 2);
4127
+ // Decode compound attachment ID. Both parts become path segments of the Graph URL, so a
4128
+ // part that would leave its segment (`..`, a slash) is an invalid id rather than a request
4129
+ // for a different resource
4130
+ const [emailId, id] = this.unpackApiId(attachmentId, parts => parts.length >= 2 && isSafePathSegment(parts[0]) && isSafePathSegment(parts[1]));
4128
4131
 
4129
4132
  await this.prepare();
4130
4133
 
@@ -4163,7 +4166,7 @@ class OutlookClient extends BaseClient {
4163
4166
  let attachmentResponse;
4164
4167
 
4165
4168
  try {
4166
- attachmentResponse = await this.request(`/${this.oauth2UserPath}/messages/${emailId}/attachments/${id}`);
4169
+ attachmentResponse = await this.request(`/${this.oauth2UserPath}/messages/${encodeURIComponent(emailId)}/attachments/${encodeURIComponent(id)}`);
4167
4170
  } catch (err) {
4168
4171
  throw attachmentErrorHandler(err);
4169
4172
  }
@@ -29,6 +29,12 @@ function generatePoolKey(smtpSettings) {
29
29
  for (const key of CONNECTION_IDENTITY_KEYS) {
30
30
  limitedSettings[key] = smtpSettings[key];
31
31
  }
32
+ // A transaction log is written through the account's own logger, so two accounts on the same
33
+ // gateway must not share a logged pool: the first account's log used to receive the envelopes
34
+ // and server replies of every account sending through it
35
+ if (smtpSettings.transactionLog && smtpSettings.account) {
36
+ limitedSettings.account = smtpSettings.account;
37
+ }
32
38
  const serializedSettings = JSON.stringify(limitedSettings);
33
39
  return crypto.createHash('sha256').update(serializedSettings).digest('hex');
34
40
  }
package/lib/encrypt.js CHANGED
@@ -225,6 +225,15 @@ function encrypt(cleartext, secret) {
225
225
  return cleartext;
226
226
  }
227
227
 
228
+ // Never encrypted twice. A stored value that did not decrypt (the secret was rotated without
229
+ // `emailengine encrypt`) is read back as the ciphertext it is, and a partial update of the
230
+ // record used to write it back encrypted again, which put the only recoverable copy of the
231
+ // credential beyond the rotation CLI. Ciphertext is left as it is, so a later run with the
232
+ // right secret still opens it
233
+ if (typeof cleartext === 'string' && parseEncryptedData(cleartext).format !== 'cleartext') {
234
+ return cleartext;
235
+ }
236
+
228
237
  // Random per value: GCM is only secure while no IV repeats under a key, and every value this
229
238
  // process writes shares one key
230
239
  const iv = crypto.randomBytes(IV_LENGTH);
package/lib/export.js CHANGED
@@ -515,7 +515,9 @@ class Export {
515
515
  const exports = [];
516
516
  for (const key of keys) {
517
517
  const data = await redis.hgetall(key);
518
- if (data && data.exportId) {
518
+ // the glob also matches the exports of an account whose id begins with this one and
519
+ // a colon, so the record's own account field decides
520
+ if (data && data.exportId && data.account === account) {
519
521
  exports.push({
520
522
  exportId: data.exportId,
521
523
  status: data.status,
package/lib/gateway.js CHANGED
@@ -5,8 +5,7 @@ const Boom = require('@hapi/boom');
5
5
  const { REDIS_PREFIX } = require('./consts');
6
6
  const logger = require('./logger');
7
7
  const { encrypt, decrypt } = require('./encrypt');
8
- const { customAlphabet } = require('nanoid');
9
- const nanoid = customAlphabet('0123456789abcdefghijklmnopqrstuvwxyz', 16);
8
+ const { randomId } = require('./utils/random-id');
10
9
  const { mergeObjects, filterListPage } = require('./tools');
11
10
 
12
11
  class Gateway {
@@ -87,7 +86,7 @@ class Gateway {
87
86
  let id;
88
87
  let retries = 0;
89
88
  while (retries++ < 20) {
90
- id = nanoid();
89
+ id = randomId();
91
90
  let alreadyExists = await this.redis.hexists(`${REDIS_PREFIX}gateway:${id}`, 'gateway');
92
91
  if (alreadyExists) {
93
92
  id = false;
@@ -16,7 +16,7 @@ const msgpack = require('./msgpack');
16
16
  const crypto = require('crypto');
17
17
  const { parseMessage } = require('./parse-message');
18
18
 
19
- const { MIME_BOUNDARY_PREFIX } = require('./consts');
19
+ const { MIME_BOUNDARY_PREFIX, MAX_DELIVERY_ATTEMPTS } = require('./consts');
20
20
 
21
21
  // Runs a message through the splitter and the headers rewriter and collects the result.
22
22
  //
@@ -89,7 +89,9 @@ async function processMessage(data, licenseInfo) {
89
89
  }
90
90
 
91
91
  if (deliveryAttemptsVal && !isNaN(deliveryAttemptsVal)) {
92
- deliveryAttempts = Number(deliveryAttemptsVal);
92
+ // within the bounds the API schema gives the same option; the header is what a stored
93
+ // draft or an SMTP submission carries, and nothing else validates it
94
+ deliveryAttempts = Math.min(Math.max(Math.round(Number(deliveryAttemptsVal)), 1), MAX_DELIVERY_ATTEMPTS);
93
95
  }
94
96
 
95
97
  if (gatewayVal) {
@@ -0,0 +1,107 @@
1
+ 'use strict';
2
+
3
+ // Request logging for the API server, in place of the hapi-pino plugin (which pulled a second pino
4
+ // major into the tree). It writes the same records hapi-pino did, because operators parse them:
5
+ //
6
+ // - every request gets `request.logger`, a child bound to the serialized request (`req`)
7
+ // - "[response] <method> <path> <status> (<ms>ms)" at info with `res` and `responseTime` when a
8
+ // response is sent, "-" in place of the status when the client went away first
9
+ // - a request error event at error level with `err` and `tags`, its message as the line
10
+ // - server.log() and request.log() events with `tags` and `data`, at the most severe level named
11
+ // among the tags (info when none is)
12
+ // - "server started" / "server stopped" carrying server.info
13
+ //
14
+ // The server is decorated with `server.logger`.
15
+
16
+ const { stdSerializers } = require('pino');
17
+
18
+ const LEVEL_TAGS = new Set(['trace', 'debug', 'info', 'warn', 'error', 'fatal']);
19
+
20
+ const SERIALIZERS = {
21
+ req: stdSerializers.wrapRequestSerializer(stdSerializers.req),
22
+ res: stdSerializers.wrapResponseSerializer(stdSerializers.res),
23
+ err: stdSerializers.err
24
+ };
25
+
26
+ function logEvent(logger, event) {
27
+ const tags = event.tags || [];
28
+
29
+ let level = 'info';
30
+ let highest = 0;
31
+ for (const tag of tags) {
32
+ if (LEVEL_TAGS.has(tag) && logger.levels.values[tag] > highest) {
33
+ highest = logger.levels.values[tag];
34
+ level = tag;
35
+ }
36
+ }
37
+
38
+ logger[level]({ tags, data: event.data });
39
+ }
40
+
41
+ function getRequestLogger(logger, request) {
42
+ if (!request.logger) {
43
+ request.logger = logger.child({ req: request });
44
+ }
45
+ return request.logger;
46
+ }
47
+
48
+ module.exports = {
49
+ name: 'request-logger',
50
+
51
+ /**
52
+ * @param {Object} server Hapi server
53
+ * @param {Object} options
54
+ * @param {Object} options.logger Pino logger to write through
55
+ */
56
+ register(server, options) {
57
+ // Serializers the logger already carries win, the way hapi-pino merged them
58
+ const logger = options.logger.child({}, { serializers: SERIALIZERS });
59
+
60
+ server.decorate('server', 'logger', logger);
61
+
62
+ server.ext('onRequest', (request, h) => {
63
+ request.logger = logger.child({ req: request });
64
+ return h.continue;
65
+ });
66
+
67
+ server.events.on('log', event => {
68
+ if (event.error) {
69
+ logger.error({ err: event.error, tags: event.tags });
70
+ } else {
71
+ logEvent(logger, event);
72
+ }
73
+ });
74
+
75
+ server.events.on('request', (request, event, tags) => {
76
+ // hapi's internal channel is noise apart from a malformed Accept-Encoding header
77
+ if (event.channel === 'internal' && !tags['accept-encoding']) {
78
+ return;
79
+ }
80
+
81
+ if (event.error) {
82
+ getRequestLogger(logger, request).error({ tags: event.tags, err: event.error }, event.error.message);
83
+ } else if (event.channel === 'app') {
84
+ logEvent(getRequestLogger(logger, request), event);
85
+ }
86
+ });
87
+
88
+ server.events.on('response', request => {
89
+ const { info, raw } = request;
90
+ const responseTime = (info.completed !== undefined ? info.completed : info.responded) - info.received;
91
+ const status = raw.res.headersSent ? raw.res.statusCode : '-';
92
+
93
+ getRequestLogger(logger, request).info(
94
+ { res: raw.res, responseTime },
95
+ `[response] ${request.method} ${request.path} ${status} (${responseTime}ms)`
96
+ );
97
+ });
98
+
99
+ server.ext('onPostStart', async () => {
100
+ logger.info(server.info, 'server started');
101
+ });
102
+
103
+ server.ext('onPostStop', async () => {
104
+ logger.info(server.info, 'server stopped');
105
+ });
106
+ }
107
+ };
@@ -8,7 +8,7 @@
8
8
  const logger = require('./logger');
9
9
  const settings = require('./settings');
10
10
  const { redis } = require('./db');
11
- const { Account } = require('./account');
11
+ const { Account, isImapDisabled, authFailureDisabledAt } = require('./account');
12
12
  const getSecret = require('./get-secret');
13
13
  const { isApiBasedApp } = require('./oauth2-apps');
14
14
  const { validateAuthToken, withAuthFailureBudget, REASON_MESSAGES } = require('./auth-token');
@@ -132,6 +132,19 @@ function createImapProxyAuthHandler({ call }) {
132
132
  throw respErr;
133
133
  }
134
134
 
135
+ // An account whose IMAP the operator switched off (send-only), or that the auth-failure
136
+ // safety net parked, is not reachable through the proxy either: a proxy session is an
137
+ // IMAP connection made with the account's credentials, the very thing both switches stop
138
+ if (isImapDisabled(verified.accountData)) {
139
+ let respErr = new Error(
140
+ authFailureDisabledAt(verified.accountData) ? 'Account is disabled after repeated authentication failures' : 'IMAP is disabled for this account'
141
+ );
142
+ respErr.authenticationFailed = true;
143
+ respErr.serverResponseCode = 'ACCOUNTDISABLED';
144
+ respErr.responseStatus = 'NO';
145
+ throw respErr;
146
+ }
147
+
135
148
  return verified;
136
149
  };
137
150
  }
@@ -47,8 +47,9 @@ The `test/` directory is upstream's mocha suite. It is written for mocha, which
47
47
  dependency here, and had never been executed after the import.
48
48
 
49
49
  The hermetic specs now run as part of the normal unit tier through
50
- `test/imap-core-vendored-test.js`, which installs the mocha globals the specs expect and requires
51
- them. **Do not edit the files under `test/` to make them run** - keeping them byte-identical to
50
+ `test/imap-core-vendored-test.js`, which installs the mocha globals the specs expect, routes their
51
+ `require('chai')` to a node:assert-backed stand-in (`test/helpers/chai-stand-in.js`, covering only
52
+ the chains these files use; chai itself is not a dependency), and requires them. **Do not edit the files under `test/` to make them run** - keeping them byte-identical to
52
53
  upstream is what makes the patch list above reviewable. Adapt them from the EmailEngine side
53
54
  instead.
54
55
 
@@ -59,12 +60,12 @@ Wired up and running:
59
60
  - `imap-compile-stream-test.js`
60
61
  - `imap-indexer-test.js` (upstream has its `#rebuild` block commented out)
61
62
  - `tools-test.js`
63
+ - `search-test.js` (unit tests for the SEARCH query parser and matcher)
62
64
 
63
- Not wired up, because they drive a live server via `test-server.js` and need MongoDB plus a
64
- WildDuck REST API that does not exist in this repository:
65
+ Not wired up, because it drives a live WildDuck server and needs MongoDB plus a WildDuck REST API
66
+ (`prepare.sh` loads its fixtures through both) that do not exist in this repository:
65
67
 
66
68
  - `protocol-test.js`
67
- - `search-test.js`
68
69
 
69
70
  That is a real coverage gap: `protocol-test.js` is the suite that exercises the connection and
70
71
  command state machines, which is where most of the local patches above landed. The connection
@@ -4,6 +4,7 @@ const imapTools = require('../imap-tools');
4
4
 
5
5
  module.exports = {
6
6
  state: 'Not Authenticated',
7
+ authenticates: true,
7
8
 
8
9
  schema: [
9
10
  {
@@ -4,6 +4,7 @@ const imapTools = require('../imap-tools');
4
4
 
5
5
  module.exports = {
6
6
  state: 'Not Authenticated',
7
+ authenticates: true,
7
8
 
8
9
  schema: [
9
10
  {
@@ -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
+ // Longest command text one command may accumulate across its literal-terminated segments. The
9
+ // parser caps one line at 1 MB, but a command may announce up to 32 literals before login and
10
+ // every segment that ends in `{N}` is appended to the same payload, so one unauthenticated
11
+ // connection could hold about 33 MB while trickling its final line; a thousand of them is the
12
+ // worker's memory. The same bound as the line, for the whole command
13
+ const MAX_COMMAND_PAYLOAD = 1024 * 1024;
14
+
8
15
  // Every literal is buffered in memory until the command line is complete, so a single command must
9
16
  // not be able to announce literals without bound. Real commands carry a few at most (LOGIN has two).
10
17
  const MAX_LITERALS_PER_COMMAND = 32;
@@ -113,6 +120,15 @@ class IMAPCommand {
113
120
 
114
121
  this.payload += command.value;
115
122
 
123
+ if (this.payload.length > MAX_COMMAND_PAYLOAD) {
124
+ this.connection.send((this.tag || '*') + ' BAD Command too long');
125
+ this.abortCommand();
126
+ let err = new Error('Command too long');
127
+ err.responseCode = 400;
128
+ err.code = 'CommandTooLong';
129
+ return callback(err);
130
+ }
131
+
116
132
  if (this.first) {
117
133
  // fetch tag and command name
118
134
  this.first = false;
@@ -311,54 +327,81 @@ class IMAPCommand {
311
327
  }
312
328
 
313
329
  if (typeof handler.handler === 'function') {
314
- handler.handler.call(
315
- this.connection,
316
- this.parsed,
317
- (err, response) => {
318
- if (err) {
319
- this.connection.send(this.tag + ' ' + (err.response || 'BAD') + ' ' + err.message);
320
- if (!err.response || err.response === 'BAD') {
321
- if (!this.countBadResponses()) {
322
- // stop processing
323
- return;
324
- }
330
+ const complete = (err, response) => {
331
+ if (err) {
332
+ this.connection.send(this.tag + ' ' + (err.response || 'BAD') + ' ' + err.message);
333
+ if (!err.response || err.response === 'BAD') {
334
+ if (!this.countBadResponses()) {
335
+ // stop processing
336
+ return;
325
337
  }
326
- return next(err);
327
338
  }
339
+ return next(err);
340
+ }
341
+
342
+ // send EXPUNGE, EXISTS etc queued notices
343
+ this.sendNotifications(handler, () => {
344
+ // send command ready response
345
+ this.connection.writeStream.write({
346
+ tag: this.tag,
347
+ command: response.response,
348
+ attributes: []
349
+ .concat(
350
+ response.code
351
+ ? {
352
+ type: 'SECTION',
353
+ section: [
354
+ {
355
+ type: 'TEXT',
356
+ value: response.code
357
+ }
358
+ ]
359
+ }
360
+ : []
361
+ )
362
+ .concat({
363
+ type: 'TEXT',
364
+ value: response.message || this.command + ' completed'
365
+ })
366
+ });
328
367
 
329
- // send EXPUNGE, EXISTS etc queued notices
330
- this.sendNotifications(handler, () => {
331
- // send command ready response
332
- this.connection.writeStream.write({
333
- tag: this.tag,
334
- command: response.response,
335
- attributes: []
336
- .concat(
337
- response.code
338
- ? {
339
- type: 'SECTION',
340
- section: [
341
- {
342
- type: 'TEXT',
343
- value: response.code
344
- }
345
- ]
346
- }
347
- : []
348
- )
349
- .concat({
350
- type: 'TEXT',
351
- value: response.message || this.command + ' completed'
352
- })
353
- });
354
-
355
- if (this.connection.state === 'Proxy') {
356
- // switch to proxy mode
357
- return this.connection.session.onProxy(this.connection.unbind());
368
+ if (this.connection.state === 'Proxy') {
369
+ // switch to proxy mode, once: the client socket is handed to
370
+ // exactly one upstream session, the one of the login that
371
+ // moved the connection into this state
372
+ if (this.connection._proxyHandedOff) {
373
+ return;
358
374
  }
375
+ this.connection._proxyHandedOff = true;
376
+ return this.connection.session.onProxy(this.connection.unbind());
377
+ }
359
378
 
360
- next();
361
- });
379
+ next();
380
+ });
381
+ };
382
+
383
+ if (!handler.authenticates) {
384
+ return handler.handler.call(this.connection, this.parsed, complete, next);
385
+ }
386
+
387
+ // One credential check at a time per connection. A client that pipelines several
388
+ // LOGIN or AUTHENTICATE commands used to have them all run at once: each success
389
+ // opened its own upstream session and the socket ended up attached to several of
390
+ // them, with the rest leaked. Set before the handler runs (an AUTHENTICATE waiting
391
+ // for its SASL continuation holds it too); a success moves the connection out of
392
+ // the state these commands are allowed in, so only a refused attempt clears it
393
+ if (this.connection._authInFlight) {
394
+ return complete(null, { response: 'NO', message: 'Authentication already in progress' });
395
+ }
396
+ this.connection._authInFlight = true;
397
+ handler.handler.call(
398
+ this.connection,
399
+ this.parsed,
400
+ (err, response) => {
401
+ if (err || !response || response.response !== 'OK') {
402
+ this.connection._authInFlight = false;
403
+ }
404
+ return complete(err, response);
362
405
  },
363
406
  next
364
407
  );
@@ -31,6 +31,11 @@ class IMAPStream extends Writable {
31
31
 
32
32
  // unprocessed chars from the last parsing iteration
33
33
  this._remainder = '';
34
+ // chunks of an unfinished line that arrived with no line break in them, kept apart until
35
+ // one arrives so that a line trickled in small segments is not re-joined and re-scanned
36
+ // from its start for every segment (that was quadratic in the line length)
37
+ this._remainderParts = [];
38
+ this._remainderLength = 0;
34
39
  this._literal = false;
35
40
  this._literalReady = false;
36
41
 
@@ -57,7 +62,7 @@ class IMAPStream extends Writable {
57
62
  * encrypted session (STARTTLS command injection).
58
63
  */
59
64
  reset() {
60
- this._remainder = '';
65
+ this._clearRemainder();
61
66
  this._literal = false;
62
67
  this._literalReady = false;
63
68
  this._expecting = 0;
@@ -73,12 +78,31 @@ class IMAPStream extends Writable {
73
78
  return done();
74
79
  }
75
80
 
76
- let data = this._remainder + chunk.toString('binary');
77
- this._remainder = '';
81
+ let str = chunk.toString('binary');
82
+
83
+ if (!this._expecting && !this._literalReady && str.indexOf('\n') < 0) {
84
+ // No line ends in this chunk and no literal is being read, so nothing can be parsed
85
+ // yet: keep the chunk and scan it once the line break arrives. The cap applies to
86
+ // what is kept, so a line that never ends is refused the same as before
87
+ if (this._remainder.length + this._remainderLength + str.length > this._maxLineLength) {
88
+ this._clearRemainder();
89
+ return done(new Error('Command line too long'));
90
+ }
91
+ this._remainderParts.push(str);
92
+ this._remainderLength += str.length;
93
+ return done();
94
+ }
95
+
96
+ let prefix = this._clearRemainder();
97
+ let data = prefix + str;
78
98
 
79
99
  // start reading data
80
- // regex is passed as an argument because we need to keep count of the lastIndex property
81
- this._readValue(/\r?\n/g, data, 0, done);
100
+ // regex is passed as an argument because we need to keep count of the lastIndex property.
101
+ // The prefix was already scanned for a line break and has none, so the search starts at
102
+ // its end (one character back, in case a CR LF straddles the two)
103
+ let regex = /\r?\n/g;
104
+ regex.lastIndex = Math.max(0, prefix.length - 1);
105
+ this._readValue(regex, data, 0, done);
82
106
  }
83
107
 
84
108
  /**
@@ -179,6 +203,7 @@ class IMAPStream extends Writable {
179
203
  // connection to proxy mode never calls back, and whatever the client pipelined after it
180
204
  // has to be handed to the upstream server instead of being dropped (see takeRemainder).
181
205
  this._pending = { data, pos };
206
+ let sync = true;
182
207
  this.oncommand(
183
208
  {
184
209
  value: line,
@@ -186,9 +211,31 @@ class IMAPStream extends Writable {
186
211
  },
187
212
  () => {
188
213
  this._pending = null;
189
- this._readValue(regex, data, pos, done);
214
+ // A command that completes synchronously (NOOP, CAPABILITY, ID) used to call back
215
+ // into this method from inside it, so one chunk of a few thousand pipelined
216
+ // commands grew the stack until it overflowed and the RangeError, thrown inside
217
+ // the socket's data handler, took the whole worker down. Only that case is
218
+ // deferred; a command that went through I/O calls back on a fresh stack
219
+ if (sync) {
220
+ setImmediate(() => this._readValue(regex, data, pos, done));
221
+ } else {
222
+ this._readValue(regex, data, pos, done);
223
+ }
190
224
  }
191
225
  );
226
+ sync = false;
227
+ }
228
+
229
+ /**
230
+ * Takes the unfinished line out of the buffers
231
+ * @returns {String} what was kept
232
+ */
233
+ _clearRemainder() {
234
+ let line = this._remainder + this._remainderParts.join('');
235
+ this._remainder = '';
236
+ this._remainderParts = [];
237
+ this._remainderLength = 0;
238
+ return line;
192
239
  }
193
240
 
194
241
  /**
@@ -206,9 +253,9 @@ class IMAPStream extends Writable {
206
253
  }
207
254
  this._pending = null;
208
255
 
209
- if (this._remainder) {
210
- chunks.push(Buffer.from(this._remainder, 'binary'));
211
- this._remainder = '';
256
+ let kept = this._clearRemainder();
257
+ if (kept) {
258
+ chunks.push(Buffer.from(kept, 'binary'));
212
259
  }
213
260
 
214
261
  let buffered = this.writableBuffer || (this._writableState && typeof this._writableState.getBuffer === 'function' && this._writableState.getBuffer()) || [];
@@ -225,10 +272,8 @@ class IMAPStream extends Writable {
225
272
  * Flushes remaining bytes
226
273
  */
227
274
  _flushData() {
228
- let line;
229
- if (this._remainder) {
230
- line = this._remainder;
231
- this._remainder = '';
275
+ let line = this._clearRemainder();
276
+ if (line) {
232
277
  this.oncommand(Buffer.from(line, 'binary'));
233
278
  }
234
279
  }
@@ -889,7 +889,9 @@ function textToHtml(str) {
889
889
  encoded
890
890
  .replace(/\r?\n/g, '\n')
891
891
  .trim() // normalize line endings
892
- .replace(/[ \t]+$/gm, '')
892
+ // rtrim every line. The group keeps this linear: /[ \t]+$/gm retried a run of
893
+ // spaces inside a line from every position in it, quadratic in the run
894
+ .replace(/(^|[^ \t])[ \t]+$/gm, '$1')
893
895
  .trim() // trim empty line endings
894
896
  .replace(/\n\n+/g, '</p><p>')
895
897
  .trim() // insert <p> to multiple linebreaks
package/lib/mcp/listen.js CHANGED
@@ -182,7 +182,16 @@ async function runRecheckPass() {
182
182
  const groups = new Map();
183
183
  for (const stream of mcpListenStreams) {
184
184
  const subscription = stream.mcpSubscription;
185
- if (!subscription || !subscription.recheck || !subscription.resourceUris.size) {
185
+ if (!subscription || !subscription.recheck) {
186
+ continue;
187
+ }
188
+ if (!subscription.resourceUris.size) {
189
+ // Nothing left to deliver, and nothing left to re-check the credential against: a
190
+ // stream in this state used to stay open past a token revocation for as long as the
191
+ // client kept it. The client resubscribes if it wants more
192
+ if (!stream._finalized && !stream.destroyed) {
193
+ stream.finalize();
194
+ }
186
195
  continue;
187
196
  }
188
197
  let group = groups.get(subscription.credentialId);