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
@@ -16,11 +16,15 @@ const CLOSE_TIMEOUT = 1 * 1000; // how much to wait until pending connections ar
16
16
  // proxy source that never sends a newline cannot grow memory without limit.
17
17
  const MAX_PROXY_HEADER_SIZE = 256;
18
18
 
19
+ // A PROXY header is the first thing a load balancer sends, right after connecting. A socket that
20
+ // has not produced it by then is not a proxy we are waiting on, and it must not hold an fd forever.
21
+ const PROXY_HEADER_TIMEOUT = 10 * 1000;
22
+
19
23
  /**
20
24
  * Creates a IMAP server instance.
21
25
  *
22
26
  * @constructor
23
- * @param {Object} options Connection and IMAP optionsž
27
+ * @param {Object} options Connection and IMAP options
24
28
  */
25
29
  class IMAPServer extends EventEmitter {
26
30
  constructor(options) {
@@ -44,12 +48,21 @@ class IMAPServer extends EventEmitter {
44
48
  */
45
49
  this.connections = new Set();
46
50
 
51
+ // Accepted sockets that have not closed yet, counted from accept so connections still
52
+ // waiting for a PROXY header or a TLS handshake are included. Checked against the
53
+ // maxConnections option; every accepted socket is buffered in memory until its first
54
+ // command completes, so the number of them has to be bounded.
55
+ this._socketCount = 0;
56
+
47
57
  // setup server listener and connection handler
48
58
  //this.server = (this.options.secure ? tls : net).createServer(this.options, 1);
49
59
 
50
60
  // setup server listener and connection handler
51
61
  if (this.options.secure && !this.options.needsUpgrade) {
52
62
  this.server = net.createServer(this.options, socket => {
63
+ if (!this._acceptSocket(socket)) {
64
+ return;
65
+ }
53
66
  socket.setKeepAlive(true, 5 * 1000);
54
67
  this._handleProxy(socket, (err, socketOptions) => {
55
68
  if (err) {
@@ -67,15 +80,18 @@ class IMAPServer extends EventEmitter {
67
80
  });
68
81
  });
69
82
  } else {
70
- this.server = net.createServer(this.options, socket =>
83
+ this.server = net.createServer(this.options, socket => {
84
+ if (!this._acceptSocket(socket)) {
85
+ return;
86
+ }
71
87
  this._handleProxy(socket, (err, socketOptions) => {
72
88
  if (err) {
73
89
  // ignore, should not happen
74
90
  }
75
91
  socket.setKeepAlive(true, 5 * 1000);
76
92
  this.connect(socket, socketOptions);
77
- })
78
- );
93
+ });
94
+ });
79
95
  }
80
96
 
81
97
  this.skipFetchLog = options.skipFetchLog;
@@ -206,6 +222,61 @@ class IMAPServer extends EventEmitter {
206
222
  this.emit('error', err);
207
223
  }
208
224
 
225
+ /**
226
+ * Counts an accepted socket and refuses it when the maxConnections option is exceeded.
227
+ *
228
+ * @param {net.Socket} socket Freshly accepted socket
229
+ * @returns {Boolean} true if the socket may be served
230
+ */
231
+ _acceptSocket(socket) {
232
+ let maxConnections = Number(this.options.maxConnections) || 0;
233
+ if (maxConnections && this._socketCount >= maxConnections) {
234
+ this.logger.info(
235
+ {
236
+ tnx: 'connect',
237
+ remoteAddress: socket.remoteAddress
238
+ },
239
+ 'Refusing connection from %s: too many connections (%s)',
240
+ socket.remoteAddress,
241
+ maxConnections
242
+ );
243
+ if (this.options.secure && !this.options.needsUpgrade) {
244
+ // an implicit TLS client could not read a plaintext response
245
+ socket.on('error', () => false);
246
+ try {
247
+ socket.destroy();
248
+ } catch (err) {
249
+ // ignore
250
+ }
251
+ } else {
252
+ this._rejectSocket(socket, '* BYE Too many connections, try again later\r\n');
253
+ }
254
+ return false;
255
+ }
256
+
257
+ this._socketCount++;
258
+ socket.once('close', () => {
259
+ this._socketCount--;
260
+ });
261
+ return true;
262
+ }
263
+
264
+ /**
265
+ * Ends a socket refused before the protocol starts, with a one-line reason. end() only
266
+ * half-closes, so a short timeout releases the fd even when the peer never closes its side
267
+ * @param {net.Socket} socket
268
+ * @param {string} line - The response line, CRLF included
269
+ */
270
+ _rejectSocket(socket, line) {
271
+ socket.on('error', () => false);
272
+ try {
273
+ socket.end(line);
274
+ socket.setTimeout(CLOSE_TIMEOUT, () => socket.destroy());
275
+ } catch (err) {
276
+ // ignore
277
+ }
278
+ }
279
+
209
280
  _handleProxy(socket, callback) {
210
281
  let socketOptions = {
211
282
  id: base32Encode(crypto.randomBytes(10)).toLowerCase()
@@ -221,13 +292,43 @@ class IMAPServer extends EventEmitter {
221
292
 
222
293
  let chunks = [];
223
294
  let chunklen = 0;
295
+
296
+ // Nothing else listens on the raw socket until the header is read, so a reset from the
297
+ // peer (a load balancer health check does exactly that) would be an uncaught 'error'.
298
+ let onProxyTimeout = () => {
299
+ stopWaiting();
300
+ try {
301
+ socket.destroy();
302
+ } catch (E) {
303
+ // ignore
304
+ }
305
+ };
306
+ let onProxyError = err => {
307
+ this.logger.debug(
308
+ {
309
+ tnx: 'proxy',
310
+ cid: socketOptions.id,
311
+ err
312
+ },
313
+ 'Socket error while waiting for PROXY header: %s',
314
+ err && err.message
315
+ );
316
+ onProxyTimeout();
317
+ };
318
+ let stopWaiting = () => {
319
+ socket.removeListener('readable', socketReader);
320
+ socket.removeListener('error', onProxyError);
321
+ socket.removeListener('timeout', onProxyTimeout);
322
+ socket.setTimeout(0);
323
+ };
324
+
224
325
  let socketReader = () => {
225
326
  let chunk;
226
327
  while ((chunk = socket.read()) !== null) {
227
328
  for (let i = 0, len = chunk.length; i < len; i++) {
228
329
  let chr = chunk[i];
229
330
  if (chr === 0x0a) {
230
- socket.removeListener('readable', socketReader);
331
+ stopWaiting();
231
332
  chunks.push(chunk.slice(0, i + 1));
232
333
  chunklen += i + 1;
233
334
  let remainder = chunk.slice(i + 1);
@@ -240,11 +341,7 @@ class IMAPServer extends EventEmitter {
240
341
  let params = (header || '').toString().split(' ');
241
342
  let commandName = params.shift().toUpperCase();
242
343
  if (commandName !== 'PROXY') {
243
- try {
244
- socket.end('* BAD Invalid PROXY header\r\n');
245
- } catch (E) {
246
- // ignore
247
- }
344
+ this._rejectSocket(socket, '* BAD Invalid PROXY header\r\n');
248
345
  return;
249
346
  }
250
347
 
@@ -279,27 +376,16 @@ class IMAPServer extends EventEmitter {
279
376
  chunklen += chunk.length;
280
377
 
281
378
  if (chunklen > MAX_PROXY_HEADER_SIZE) {
282
- socket.removeListener('readable', socketReader);
283
- try {
284
- socket.end('* BAD Invalid PROXY header\r\n');
285
- } catch (E) {
286
- // ignore
287
- }
288
- // end() only half-closes the socket; arm a short timeout so the fd is
289
- // released even if the peer never closes its side (fd exhaustion).
290
- socket.setTimeout(CLOSE_TIMEOUT);
291
- socket.once('timeout', () => {
292
- try {
293
- socket.destroy();
294
- } catch (E) {
295
- // ignore
296
- }
297
- });
379
+ stopWaiting();
380
+ this._rejectSocket(socket, '* BAD Invalid PROXY header\r\n');
298
381
  return;
299
382
  }
300
383
  }
301
384
  };
302
385
  socket.on('readable', socketReader);
386
+ socket.on('error', onProxyError);
387
+ socket.setTimeout(Number(this.options.proxyHeaderTimeout) || PROXY_HEADER_TIMEOUT);
388
+ socket.on('timeout', onProxyTimeout);
303
389
  }
304
390
 
305
391
  _upgrade(socket, callback) {
@@ -34,6 +34,9 @@ class IMAPStream extends Writable {
34
34
  this._literal = false;
35
35
  this._literalReady = false;
36
36
 
37
+ // unparsed rest of the chunk the currently running command came in
38
+ this._pending = null;
39
+
37
40
  // how many literal bytes to wait for
38
41
  this._expecting = 0;
39
42
 
@@ -172,15 +175,52 @@ class IMAPStream extends Writable {
172
175
  }
173
176
  }
174
177
 
178
+ // Remember what is left of this chunk while the command runs. A LOGIN that switches the
179
+ // connection to proxy mode never calls back, and whatever the client pipelined after it
180
+ // has to be handed to the upstream server instead of being dropped (see takeRemainder).
181
+ this._pending = { data, pos };
175
182
  this.oncommand(
176
183
  {
177
184
  value: line,
178
185
  final: true
179
186
  },
180
- this._readValue.bind(this, regex, data, pos, done)
187
+ () => {
188
+ this._pending = null;
189
+ this._readValue(regex, data, pos, done);
190
+ }
181
191
  );
182
192
  }
183
193
 
194
+ /**
195
+ * Returns every byte received but not yet parsed: the rest of the chunk the current command
196
+ * came in, and any chunks written while that command was running. Used when the connection is
197
+ * handed off to the proxy, after which this parser is never fed again.
198
+ *
199
+ * @returns {Buffer} Unparsed input, possibly empty
200
+ */
201
+ takeRemainder() {
202
+ let chunks = [];
203
+
204
+ if (this._pending && this._pending.pos < this._pending.data.length) {
205
+ chunks.push(Buffer.from(this._pending.data.substr(this._pending.pos), 'binary'));
206
+ }
207
+ this._pending = null;
208
+
209
+ if (this._remainder) {
210
+ chunks.push(Buffer.from(this._remainder, 'binary'));
211
+ this._remainder = '';
212
+ }
213
+
214
+ let buffered = this.writableBuffer || (this._writableState && typeof this._writableState.getBuffer === 'function' && this._writableState.getBuffer()) || [];
215
+ for (let entry of buffered) {
216
+ if (entry && entry.chunk && entry.chunk.length) {
217
+ chunks.push(Buffer.isBuffer(entry.chunk) ? entry.chunk : Buffer.from(entry.chunk, entry.encoding === 'buffer' ? undefined : entry.encoding));
218
+ }
219
+ }
220
+
221
+ return Buffer.concat(chunks);
222
+ }
223
+
184
224
  /**
185
225
  * Flushes remaining bytes
186
226
  */
@@ -1,6 +1,14 @@
1
1
  'use strict';
2
2
 
3
- const Indexer = require('./indexer/indexer');
3
+ // The indexer (and html-to-text, he, libqp behind it) is only needed to answer FETCH, which the
4
+ // proxy never runs itself, so it is loaded on first use instead of with the proxy worker.
5
+ let Indexer;
6
+ const getIndexer = () => {
7
+ if (!Indexer) {
8
+ Indexer = require('./indexer/indexer');
9
+ }
10
+ return Indexer;
11
+ };
4
12
  const libmime = require('libmime');
5
13
  const punycode = require('punycode.js');
6
14
  const iconv = require('iconv-lite');
@@ -498,7 +506,7 @@ module.exports.getQueryResponse = function (query, message, options) {
498
506
  // If these values are missing then generate these when first time required
499
507
  // So if the query is for (UID FLAGS) then mimeTree is never generated
500
508
  let mimeTree = message.mimeTree;
501
- let indexer = new Indexer(options);
509
+ let indexer = new (getIndexer())(options);
502
510
 
503
511
  // generate response object
504
512
  let values = [];
@@ -198,7 +198,7 @@ class Indexer {
198
198
 
199
199
  if (output.write(chunk) === false) {
200
200
  await new Promise(resolve => {
201
- output.once('drain', resolve());
201
+ output.once('drain', resolve);
202
202
  });
203
203
  }
204
204
  };
@@ -473,7 +473,9 @@ class Indexer {
473
473
  if (transferEncoding === 'base64') {
474
474
  content = libbase64.decode(content.toString());
475
475
  } else if (transferEncoding === 'quoted-printable') {
476
- content = libqp.decode(content.toString());
476
+ // libqp.decode() stringifies its input, so hand it the raw bytes as a
477
+ // binary string: a UTF-8 decode here would mangle 8-bit bytes in the body
478
+ content = libqp.decode(content.toString('binary'));
477
479
  }
478
480
 
479
481
  if (
@@ -21,7 +21,7 @@ const {
21
21
  const { getLocalAddress } = require('../utils/network');
22
22
 
23
23
  const { redis } = require('../db');
24
- const { createImapProxyAuthHandler, classifyCredentialFailure, isImapResponseError, toImapResponseError } = require('../imap-proxy-auth');
24
+ const { createImapProxyAuthHandler, classifyCredentialFailure } = require('../imap-proxy-auth');
25
25
  const settings = require('../settings');
26
26
 
27
27
  const { createCertHandler } = require('../cert-handler');
@@ -42,6 +42,11 @@ const EENGINE_TIMEOUT = getDuration(readEnvValue('EENGINE_TIMEOUT') || config.se
42
42
  const EENGINE_LOG_RAW = hasEnvValue('EENGINE_LOG_RAW') ? getBoolean(readEnvValue('EENGINE_LOG_RAW')) : getBoolean(config.log.raw);
43
43
  const DISABLE_IMAP_COMPRESSION = getBoolean(readEnvValue('EENGINE_DISABLE_COMPRESSION'));
44
44
 
45
+ // Every connection can buffer up to a 1MB command line before it authenticates, so the number of
46
+ // open connections bounds the worker's memory. Excess connections get a BYE and are closed.
47
+ const DEFAULT_IMAP_PROXY_MAX_CLIENTS = 1000;
48
+ const IMAP_PROXY_MAX_CLIENTS = Number(readEnvValue('EENGINE_IMAPPROXY_MAX_CLIENTS') || config.imap.maxClients) || DEFAULT_IMAP_PROXY_MAX_CLIENTS;
49
+
45
50
  const { TLS_DEFAULTS } = require('../consts');
46
51
 
47
52
  let callQueue = new Map();
@@ -118,8 +123,8 @@ async function metrics(logger, key, method, ...args) {
118
123
  }
119
124
 
120
125
  const { createUpstreamClient } = require('./upstream-client');
121
- const { IMAPServer, imapHandler } = require('./imap-core/index.js');
122
- const { PassThrough } = require('stream');
126
+ const { IMAPServer } = require('./imap-core/index.js');
127
+ const { createProxyAuthHandler } = require('./proxy-handoff');
123
128
 
124
129
  const packageInfo = require('../../package.json');
125
130
  const util = require('util');
@@ -130,35 +135,6 @@ const CLIENT_INFO = {
130
135
  vendor: packageInfo.author
131
136
  };
132
137
 
133
- class PassThroughLogger extends PassThrough {
134
- constructor(opts = {}) {
135
- super();
136
- this.logger = opts.logger;
137
- this.src = opts.src;
138
- this.cid = opts.cid;
139
- this.imapClient = opts.imapClient;
140
- }
141
- _transform(chunk, encoding, next) {
142
- if (EENGINE_LOG_RAW) {
143
- this.logger.trace({
144
- src: this.src,
145
- msg: 'write to socket',
146
- data: chunk.toString('base64'),
147
- compress: !!this.imapClient._deflate,
148
- secure: !!this.imapClient.secureConnection,
149
- cid: this.cid
150
- });
151
- }
152
-
153
- this.push(chunk);
154
- next();
155
- }
156
-
157
- _flush(next) {
158
- next();
159
- }
160
- }
161
-
162
138
  // Authentication logic lives in lib/imap-proxy-auth.js so it can be unit tested
163
139
  // without booting this worker. call() is injected for the Account instance.
164
140
  const authenticateImapProxy = createImapProxyAuthHandler({ call });
@@ -328,151 +304,14 @@ const createServer = function (options = {}) {
328
304
  }
329
305
  });
330
306
 
331
- server.onAuth = function (login, session, callback) {
332
- onAuth(login, session)
333
- .then(accountData => {
334
- let { account, imapConfig } = accountData;
335
- if (!imapConfig) {
336
- throw new Error('IMAP not enabled for account');
337
- }
338
-
339
- createProxy({ imapConfig, id: session.id, logger: logger.child({ property: 'upstream', account }) })
340
- .then(downstream => {
341
- session.onProxy = upstream => {
342
- metrics(logger, 'events', 'inc', {
343
- event: 'imapProxyConnected'
344
- });
345
-
346
- const proxyLogger = logger.child({ property: 'proxy', account, cid: session.id });
347
-
348
- let upstreamLogger = new PassThroughLogger({
349
- src: 's',
350
- cid: session.id,
351
- imapClient: downstream.imapClient,
352
- logger: proxyLogger.child({ src: 'S' })
353
- });
354
-
355
- let downstreamLogger = new PassThroughLogger({
356
- src: 'c',
357
- cid: session.id,
358
- imapClient: downstream.imapClient,
359
- logger: proxyLogger.child({ src: 'C' })
360
- });
361
-
362
- // Idempotent teardown for both legs of the proxy. ImapFlow.close() is
363
- // safe after unbind(): it sends no LOGOUT, clears timers (including
364
- // autoidle), removes the deflate/writeSocket error forwarders and
365
- // destroys the upstream socket. Without it the upstream connection and
366
- // its idle timer would leak (most visibly with COMPRESS enabled).
367
- let proxyClosed = false;
368
- const closeProxy = () => {
369
- if (proxyClosed) {
370
- return;
371
- }
372
- proxyClosed = true;
373
-
374
- try {
375
- downstream.imapClient.close();
376
- } catch (err) {
377
- proxyLogger.warn({ msg: 'Failed to close upstream connection', err });
378
- }
379
-
380
- try {
381
- if (upstream.socket && !upstream.socket.destroyed) {
382
- upstream.socket.end();
383
- }
384
- } catch (err) {
385
- // ignore
386
- }
387
- };
388
-
389
- // Every terminal event from either leg funnels into the idempotent
390
- // closeProxy(). The helper keeps that wiring declarative; pass a message
391
- // to log (level defaults to 'warn', use 'info' for graceful closes).
392
- const teardownOn = (emitter, event, msg, level = 'warn') => {
393
- emitter.on(event, err => {
394
- if (msg) {
395
- let entry = { msg };
396
- if (err) {
397
- entry.err = err;
398
- }
399
- proxyLogger[level](entry);
400
- }
401
- closeProxy();
402
- });
403
- };
404
-
405
- downstream.readSocket.pipe(upstreamLogger).pipe(upstream.socket);
406
- upstream.socket.pipe(downstreamLogger).pipe(downstream.writeSocket);
407
-
408
- teardownOn(upstreamLogger, 'error', 'Proxy stream error (to client)');
409
- teardownOn(downstreamLogger, 'error', 'Proxy stream error (to upstream)');
410
- teardownOn(upstream.socket, 'error', 'Client socket error');
411
- teardownOn(upstream.socket, 'end', 'Client connection closed', 'info');
412
- teardownOn(upstream.socket, 'close');
413
- teardownOn(downstream.readSocket, 'end', 'Upstream connection closed', 'info');
414
-
415
- downstream.readSocket.on('error', err => {
416
- proxyLogger.warn({ msg: 'Upstream read error', err });
417
- try {
418
- // best-effort notice to the client before tearing down
419
- upstream.socket.write('* BYE Upstream connection error\r\n');
420
- } catch (e) {
421
- // ignore
422
- }
423
- closeProxy();
424
- });
425
-
426
- // With COMPRESS enabled, readSocket/writeSocket are the inflate/deflate
427
- // streams, not the raw upstream socket, and unbind() removed ImapFlow's
428
- // own listeners from that socket. An upstream reset would then emit an
429
- // 'error' with no listener and crash the worker - guard it explicitly.
430
- if (downstream.imapClient.socket && downstream.imapClient.socket !== downstream.readSocket) {
431
- teardownOn(downstream.imapClient.socket, 'error', 'Upstream socket error');
432
- teardownOn(downstream.imapClient.socket, 'close');
433
- }
434
-
435
- proxyLogger.info({ msg: 'Proxy mode enabled' });
436
- };
437
-
438
- if (downstream.imapClient.rawCapabilities) {
439
- login.connection.send(
440
- imapHandler.compiler({
441
- tag: '*',
442
- command: 'CAPABILITY',
443
- attributes: downstream.imapClient.rawCapabilities
444
- })
445
- );
446
- }
447
-
448
- callback(null, {
449
- user: {
450
- id: 'id.' + login.username,
451
- username: login.username
452
- }
453
- });
454
- })
455
- .catch(err => {
456
- if (isImapResponseError(err)) {
457
- serverLogger.warn({ msg: 'Upstream authentication failed', account, cid: session.id, err });
458
- return callback(toImapResponseError(err));
459
- } else {
460
- serverLogger.error({ msg: 'Failed to create proxy', account, cid: session.id, err });
461
- return callback(err);
462
- }
463
- });
464
- })
465
- .catch(err => {
466
- let entry = { msg: 'Authentication check failed', username: login.username, cid: session.id, remoteAddress: session.remoteAddress, err };
467
- if (isImapResponseError(err)) {
468
- // a refused login or a temporary failure the client is told to retry, not a proxy fault
469
- serverLogger.warn(entry);
470
- return callback(toImapResponseError(err));
471
- }
472
- serverLogger.error(entry);
473
- return callback(err);
474
- });
475
- };
307
+ server.onAuth = createProxyAuthHandler({
308
+ onAuth,
309
+ createProxy,
310
+ logger,
311
+ serverLogger,
312
+ metrics,
313
+ logRaw: EENGINE_LOG_RAW
314
+ });
476
315
 
477
316
  return server;
478
317
  };
@@ -488,6 +327,7 @@ module.exports.run = async () => {
488
327
  secure: false,
489
328
  disableSTARTTLS: true,
490
329
  proxyMode: true,
330
+ maxConnections: IMAP_PROXY_MAX_CLIENTS,
491
331
  id: Object.assign({}, CLIENT_INFO, {
492
332
  name: 'EmailEngine IMAP Proxy'
493
333
  })