emailengine-app 2.74.1 → 2.74.2

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.
package/lib/export.js CHANGED
@@ -30,6 +30,7 @@ local maxConcurrent = tonumber(ARGV[1])
30
30
  local maxGlobal = tonumber(ARGV[2])
31
31
  local accountPrefix = ARGV[3]
32
32
  local activeEntry = ARGV[4]
33
+ local exportIdPrefix = ARGV[5]
33
34
 
34
35
  local members = redis.call('SMEMBERS', activeKey)
35
36
  local globalCount = #members
@@ -39,11 +40,21 @@ if globalCount >= maxGlobal then
39
40
  return 0
40
41
  end
41
42
 
42
- -- Check per-account limit
43
+ -- Check per-account limit. The prefix alone is not enough: account ids may contain colons, so
44
+ -- "user:" is also a prefix of the account "user:sub" entries. Requiring the remainder to be the
45
+ -- export id (the id prefix and no further colon) anchors the match on the same boundary that
46
+ -- parseActiveEntry() splits on, so the limiter and the recovery scan agree on who owns an entry.
47
+ -- The id prefix arrives as an argument rather than being spelled out here, so that changing
48
+ -- EXPORT_ID_PREFIX can not leave this counting nothing and failing the limit OPEN in silence.
49
+ -- Matched with plain string.find (no patterns) so a prefix containing a Lua magic character
50
+ -- would not change the meaning of the comparison either.
43
51
  local accountCount = 0
44
52
  for _, member in ipairs(members) do
45
53
  if string.sub(member, 1, #accountPrefix) == accountPrefix then
46
- accountCount = accountCount + 1
54
+ local remainder = string.sub(member, #accountPrefix + 1)
55
+ if string.sub(remainder, 1, #exportIdPrefix) == exportIdPrefix and not string.find(remainder, ':', 1, true) then
56
+ accountCount = accountCount + 1
57
+ end
47
58
  end
48
59
  end
49
60
 
@@ -56,6 +67,28 @@ redis.call('SADD', activeKey, activeEntry)
56
67
  return 1
57
68
  `;
58
69
 
70
+ // The active-set membership encoding. Written by tryAddToActiveSet(), read back by
71
+ // markInterruptedAsFailed() and counted by CONCURRENT_CHECK_AND_ADD_SCRIPT - defined here once so
72
+ // the three can not disagree about where the account ends and the export id begins.
73
+ function buildActiveEntry(account, exportId) {
74
+ return `${account}:${exportId}`;
75
+ }
76
+
77
+ // Account ids may contain colons, so split on the LAST ':exp_' - the export id is always the
78
+ // trailing ':exp_<hex>' segment.
79
+ function parseActiveEntry(entry) {
80
+ const separatorIndex = entry.lastIndexOf(`:${EXPORT_ID_PREFIX}`);
81
+ if (separatorIndex === -1) {
82
+ return false;
83
+ }
84
+ const account = entry.substring(0, separatorIndex);
85
+ const exportId = entry.substring(separatorIndex + 1);
86
+ if (!account || !exportId) {
87
+ return false;
88
+ }
89
+ return { account, exportId };
90
+ }
91
+
59
92
  function generateExportId() {
60
93
  return EXPORT_ID_PREFIX + crypto.randomBytes(12).toString('hex');
61
94
  }
@@ -100,6 +133,27 @@ function isFolderMissingError(err) {
100
133
  return ['FolderNotFound', 'NotFound'].includes(errCode);
101
134
  }
102
135
 
136
+ // Export truncation limits (max messages while indexing, max total bytes while exporting).
137
+ //
138
+ // Extracted from workers/export.js because the worker applies the same rule in three places and
139
+ // none of them can be reached from a test in place (they sit inside the BullMQ job body, behind
140
+ // a live account and a real folder listing). The rules:
141
+ //
142
+ // * an unset, zero, non-numeric or negative stored setting means "use the default" - a negative
143
+ // limit used to survive `Number(value) || DEFAULT` and then truncate every export at zero
144
+ // messages, because `totalIndexed >= -1` is true from the start
145
+ // * the comparison is `>=`, so the limit itself is the last value that still fits
146
+ // * a limit of 0 passed in explicitly means unlimited, never "export nothing"
147
+
148
+ function resolveExportLimit(value, defaultValue) {
149
+ const limit = Number(value);
150
+ return Number.isFinite(limit) && limit > 0 ? limit : defaultValue;
151
+ }
152
+
153
+ function isExportLimitReached(current, limit) {
154
+ return !!limit && current >= limit;
155
+ }
156
+
103
157
  // Per-message errors worth retrying during a batch export: rate limits, a dropped batch response
104
158
  // (Outlook reports these as EMISSING_RESPONSE), and the same transient network/5xx/timeout errors
105
159
  // isTransientError already covers. Used by the export worker's API-account batch fetch path so a
@@ -111,14 +165,32 @@ function isRetryableError(err) {
111
165
  return isTransientError(err);
112
166
  }
113
167
 
114
- async function tryAddToActiveSet(account, exportId) {
115
- const maxConcurrent = (await settings.get('exportMaxConcurrent')) || DEFAULT_EXPORT_MAX_CONCURRENT;
116
- const maxGlobalConcurrent = (await settings.get('exportMaxGlobalConcurrent')) || DEFAULT_EXPORT_MAX_GLOBAL_CONCURRENT;
168
+ // `opts` exists so tests can drive this against a scoped key with explicit limits instead of
169
+ // re-implementing the EVAL. Production always calls it with no overrides.
170
+ //
171
+ // An explicit override wins even when it is 0; a stored setting goes through
172
+ // resolveExportLimit() like every other numeric limit, because a stored 0 or '' is not a usable
173
+ // concurrency limit (`0 >= 0` refuses every export with 429 forever, and a non-numeric value
174
+ // makes the EVAL raise "attempt to compare nil with number").
175
+ async function tryAddToActiveSet(account, exportId, opts) {
176
+ const { activeKey = ACTIVE_EXPORTS_KEY } = opts || {};
177
+ const maxConcurrent = opts?.maxConcurrent ?? resolveExportLimit(await settings.get('exportMaxConcurrent'), DEFAULT_EXPORT_MAX_CONCURRENT);
178
+ const maxGlobalConcurrent =
179
+ opts?.maxGlobalConcurrent ?? resolveExportLimit(await settings.get('exportMaxGlobalConcurrent'), DEFAULT_EXPORT_MAX_GLOBAL_CONCURRENT);
117
180
 
118
181
  const accountPrefix = `${account}:`;
119
- const activeEntry = `${account}:${exportId}`;
120
-
121
- const added = await redis.eval(CONCURRENT_CHECK_AND_ADD_SCRIPT, 1, ACTIVE_EXPORTS_KEY, maxConcurrent, maxGlobalConcurrent, accountPrefix, activeEntry);
182
+ const activeEntry = buildActiveEntry(account, exportId);
183
+
184
+ const added = await redis.eval(
185
+ CONCURRENT_CHECK_AND_ADD_SCRIPT,
186
+ 1,
187
+ activeKey,
188
+ maxConcurrent,
189
+ maxGlobalConcurrent,
190
+ accountPrefix,
191
+ activeEntry,
192
+ EXPORT_ID_PREFIX
193
+ );
122
194
 
123
195
  if (!added) {
124
196
  throw createError('Maximum concurrent exports reached', 'TooManyExports', 429);
@@ -358,7 +430,7 @@ class Export {
358
430
  // Active exports: worker will clean up when it detects cancellation
359
431
  // Non-active exports: clean up immediately
360
432
  if (!isActive) {
361
- await redis.multi().del(exportKey).del(queueKey).srem(ACTIVE_EXPORTS_KEY, `${account}:${exportId}`).exec();
433
+ await redis.multi().del(exportKey).del(queueKey).srem(ACTIVE_EXPORTS_KEY, buildActiveEntry(account, exportId)).exec();
362
434
 
363
435
  if (data.filePath) {
364
436
  await fs.promises.unlink(data.filePath).catch(() => {});
@@ -479,7 +551,7 @@ class Export {
479
551
  .multi()
480
552
  .hmset(exportKey, { status: 'completed', phase: 'complete', expiresAt })
481
553
  .del(queueKey)
482
- .srem(ACTIVE_EXPORTS_KEY, `${account}:${exportId}`)
554
+ .srem(ACTIVE_EXPORTS_KEY, buildActiveEntry(account, exportId))
483
555
  .expire(exportKey, ttl)
484
556
  .exec();
485
557
 
@@ -493,7 +565,7 @@ class Export {
493
565
  const exportData = await redis.hgetall(exportKey);
494
566
  if (!exportData || !exportData.exportId) {
495
567
  // Key already deleted, just clean up active set
496
- await redis.srem(ACTIVE_EXPORTS_KEY, `${account}:${exportId}`);
568
+ await redis.srem(ACTIVE_EXPORTS_KEY, buildActiveEntry(account, exportId));
497
569
  return;
498
570
  }
499
571
 
@@ -504,7 +576,7 @@ class Export {
504
576
  error: error || 'Unknown error'
505
577
  })
506
578
  .del(queueKey)
507
- .srem(ACTIVE_EXPORTS_KEY, `${account}:${exportId}`)
579
+ .srem(ACTIVE_EXPORTS_KEY, buildActiveEntry(account, exportId))
508
580
  .exec();
509
581
 
510
582
  logger.error({ msg: 'Export failed', account, exportId, error });
@@ -514,7 +586,7 @@ class Export {
514
586
  const exportKey = getExportKey(account, exportId);
515
587
  const queueKey = getExportQueueKey(account, exportId);
516
588
 
517
- await redis.multi().del(exportKey).del(queueKey).srem(ACTIVE_EXPORTS_KEY, `${account}:${exportId}`).exec();
589
+ await redis.multi().del(exportKey).del(queueKey).srem(ACTIVE_EXPORTS_KEY, buildActiveEntry(account, exportId)).exec();
518
590
  }
519
591
 
520
592
  static async markInterruptedAsFailed() {
@@ -522,13 +594,9 @@ class Export {
522
594
 
523
595
  for (const entry of activeExports) {
524
596
  try {
525
- // Find ':exp_' as separator since account IDs may contain colons. The export id is
526
- // always the trailing ':exp_<hex>' segment, so match the last occurrence.
527
- const separatorIndex = entry.lastIndexOf(':exp_');
528
- if (separatorIndex === -1) continue;
529
- const account = entry.substring(0, separatorIndex);
530
- const exportId = entry.substring(separatorIndex + 1);
531
- if (!account || !exportId) continue;
597
+ const parsed = parseActiveEntry(entry);
598
+ if (!parsed) continue;
599
+ const { account, exportId } = parsed;
532
600
 
533
601
  const data = await redis.hgetall(getExportKey(account, exportId));
534
602
 
@@ -631,5 +699,13 @@ module.exports = {
631
699
  isSkippableError,
632
700
  isFolderMissingError,
633
701
  isRetryableError,
634
- DEFAULT_EXPORT_MAX_MESSAGE_SIZE
702
+ resolveExportLimit,
703
+ isExportLimitReached,
704
+ DEFAULT_EXPORT_MAX_MESSAGE_SIZE,
705
+ // Exported so test/export-concurrency-test.js drives the real limiter (and the real entry
706
+ // encoding) rather than re-implementing the EVAL, which a copy could never keep in step with.
707
+ tryAddToActiveSet,
708
+ buildActiveEntry,
709
+ parseActiveEntry,
710
+ ACTIVE_EXPORTS_KEY
635
711
  };
@@ -646,7 +646,7 @@ class IMAPConnection extends EventEmitter {
646
646
  cleared: false,
647
647
  callback(message) {
648
648
  let selectedMailbox = conn.selected && conn.selected.mailbox;
649
- if (this._closing || this._closed) {
649
+ if (conn._closing || conn._closed) {
650
650
  conn.clearNotificationListener();
651
651
  return;
652
652
  }
package/lib/logger.js CHANGED
@@ -50,15 +50,23 @@ if (threadId) {
50
50
  logger = logger.child({ tid: threadId });
51
51
  }
52
52
 
53
+ const FATAL_EXIT_CODES = {
54
+ uncaughtException: 1,
55
+ unhandledRejection: 2
56
+ };
57
+
53
58
  // An error that reaches the global handlers leaves the process in an unknown state,
54
59
  // so the process must always exit. If error tracking is enabled, report the error
55
- // first and allow a short flush window for the delivery.
56
- function fatalShutdown(code, err) {
60
+ // first and allow a short flush window for the delivery. The report is tagged with
61
+ // the handler that caught it because a crash carries no call site of its own - a
62
+ // bare socket error arrives with nothing but a `node:internal` frame, so without the
63
+ // tag there is no way to tell a dead worker apart from a handled error.
64
+ function fatalShutdown(handler, err) {
57
65
  if (logger.notifyError) {
58
- logger.notifyError(err);
66
+ logger.notifyError(err, { level: 'fatal', tags: { handler } });
59
67
  }
60
68
 
61
- let exit = () => process.exit(code);
69
+ let exit = () => process.exit(FATAL_EXIT_CODES[handler]);
62
70
  if (logger.flushNotifications) {
63
71
  logger.flushNotifications().then(exit, exit);
64
72
  } else {
@@ -73,7 +81,7 @@ process.on('uncaughtException', err => {
73
81
  err
74
82
  });
75
83
 
76
- fatalShutdown(1, err);
84
+ fatalShutdown('uncaughtException', err);
77
85
  });
78
86
 
79
87
  process.on('unhandledRejection', err => {
@@ -83,7 +91,7 @@ process.on('unhandledRejection', err => {
83
91
  err
84
92
  });
85
93
 
86
- fatalShutdown(2, err);
94
+ fatalShutdown('unhandledRejection', err);
87
95
  });
88
96
 
89
97
  module.exports = logger;
package/lib/rate-limit.js CHANGED
@@ -3,18 +3,40 @@
3
3
  const { redis } = require('../lib/db');
4
4
  const { REDIS_PREFIX } = require('../lib/consts');
5
5
 
6
+ // Fixed epoch for the window bucket arithmetic: "2000-01-01T00:00:00.000Z"
7
+ const EPOCH_TIME = 946684800000;
8
+
9
+ const DEFAULT_WINDOW_SIZE = 180;
10
+
11
+ // Derives the Redis counter key for a rate-limit window. The window size is part of the key, so
12
+ // the same subject can be limited over several windows at once (e.g. per-minute login attempts
13
+ // and the 12 minute TOTP code replay guard) without the counters interfering.
14
+ //
15
+ // The normalization lives here rather than in the caller so that every consumer of the key
16
+ // derives the same bucket: a missing window would otherwise produce an "rl:undefined:NaN:" key
17
+ // while checkRateLimit() counted under the 180 second one, and the two would never meet.
18
+ // The end of the bucket is computed here too, so the bucket arithmetic and its inverse stay in
19
+ // one place instead of the caller reconstructing it from a leaked bucket number.
20
+ const rateLimitWindowKey = (key, windowSize, now) => {
21
+ windowSize = Math.abs(Number(windowSize) || DEFAULT_WINDOW_SIZE);
22
+ let timeBucket = Math.floor(((now || Date.now()) - EPOCH_TIME) / (windowSize * 1000));
23
+ return {
24
+ windowKey: `${REDIS_PREFIX}rl:${windowSize}:${timeBucket}:${key}`,
25
+ windowSize,
26
+ windowEnds: (timeBucket + 1) * windowSize * 1000 + EPOCH_TIME
27
+ };
28
+ };
29
+
6
30
  const checkRateLimit = async (key, count, allowed, windowSize) => {
7
- count = Math.max(Number(count) || 1);
8
- windowSize = Math.abs(Number(windowSize) || 180);
31
+ // The lower bound is what keeps a negative cost from DECREMENTING the counter, i.e. from
32
+ // buying back attempts against a brute-force guard. Math.max() with a single argument is a
33
+ // no-op and passed one straight through.
34
+ count = Math.max(Number(count) || 1, 1);
9
35
 
10
36
  let now = Date.now();
11
- let epochTime = 946684800000; // "2000-01-01T00:00:00.000Z"
12
- let timeBucket = Math.floor((now - epochTime) / (windowSize * 1000));
13
- let ttl = new Date((timeBucket + 1) * windowSize * 1000 + epochTime);
14
-
15
- let windowKey = `${REDIS_PREFIX}rl:${windowSize}:${timeBucket}:${key}`;
37
+ let { windowKey, windowSize: normalizedWindowSize, windowEnds } = rateLimitWindowKey(key, windowSize, now);
16
38
 
17
- let [[resErr, resVal], [expireErr]] = await redis.multi().incrby(windowKey, count).expire(windowKey, windowSize).exec();
39
+ let [[resErr, resVal], [expireErr]] = await redis.multi().incrby(windowKey, count).expire(windowKey, normalizedWindowSize).exec();
18
40
  if (resErr || expireErr) {
19
41
  throw resErr || expireErr;
20
42
  }
@@ -24,9 +46,9 @@ const checkRateLimit = async (key, count, allowed, windowSize) => {
24
46
  success: resVal <= allowed,
25
47
  count: resVal,
26
48
  allowed,
27
- ttl: (ttl.getTime() - now) / 1000,
28
- ttlReset: new Date(ttl.getTime()).toISOString()
49
+ ttl: (windowEnds - now) / 1000,
50
+ ttlReset: new Date(windowEnds).toISOString()
29
51
  };
30
52
  };
31
53
 
32
- module.exports = { checkRateLimit };
54
+ module.exports = { checkRateLimit, rateLimitWindowKey };
@@ -0,0 +1,138 @@
1
+ 'use strict';
2
+
3
+ // Server-Sent Events response stream used by the admin UI change feed (`/admin/changes`)
4
+ // and the API `/v1/changes` endpoint.
5
+ //
6
+ // Lives in its own module (rather than inline in workers/api.js) so the lifecycle
7
+ // guarantees below can be unit tested against the real implementation. Importing
8
+ // workers/api.js from a test is not an option: it boots a Hapi server on require.
9
+ //
10
+ // `registeredPublishers` is the set of live streams the API worker fans change events
11
+ // out to. Every stream adds itself on construction and removes itself in finalize(),
12
+ // so a dropped browser tab can not leak a timer or keep receiving writes.
13
+
14
+ const { Transform, finished } = require('stream');
15
+
16
+ const packageData = require('../package.json');
17
+
18
+ // Every live SSE stream. publishChangeEvent() in workers/api.js iterates this set.
19
+ const registeredPublishers = new Set();
20
+
21
+ // How long a stream may stay silent before a comment frame is written to keep
22
+ // intermediate proxies from timing the connection out.
23
+ const KEEP_ALIVE_INTERVAL = 90 * 1000;
24
+
25
+ class ResponseStream extends Transform {
26
+ constructor() {
27
+ super();
28
+ registeredPublishers.add(this);
29
+ this.periodicKeepAliveTimer = false;
30
+ this.updateTimer();
31
+
32
+ this._finalized = false;
33
+
34
+ // Ensure cleanup on all stream end scenarios. 'error' uses on() rather than once():
35
+ // a destroyed stream can emit more than one error, and a second unhandled 'error'
36
+ // would take the worker down.
37
+ this.on('error', () => this.finalize());
38
+ this.once('close', () => this.finalize());
39
+ this.once('end', () => this.finalize());
40
+ }
41
+
42
+ updateTimer() {
43
+ clearTimeout(this.periodicKeepAliveTimer);
44
+ this.periodicKeepAliveTimer = setTimeout(() => {
45
+ if (this._finalized || this.destroyed) {
46
+ return;
47
+ }
48
+ this.write(': still here\n\n');
49
+ if (this._compressor) {
50
+ this._compressor.flush();
51
+ }
52
+ this.updateTimer();
53
+ }, KEEP_ALIVE_INTERVAL);
54
+ this.periodicKeepAliveTimer.unref();
55
+ }
56
+
57
+ setCompressor(compressor) {
58
+ this._compressor = compressor;
59
+ }
60
+
61
+ sendMessage(payload) {
62
+ if (this._finalized || this.destroyed) {
63
+ return;
64
+ }
65
+ let sendData = JSON.stringify(payload);
66
+ this.write('event: message\ndata:' + sendData + '\n\n');
67
+ if (this._compressor) {
68
+ this._compressor.flush();
69
+ }
70
+ this.updateTimer();
71
+ }
72
+
73
+ finalize() {
74
+ if (this._finalized) {
75
+ // Prevent double cleanup
76
+ return;
77
+ }
78
+ this._finalized = true;
79
+
80
+ clearTimeout(this.periodicKeepAliveTimer);
81
+ registeredPublishers.delete(this);
82
+
83
+ if (!this.destroyed) {
84
+ this.destroy();
85
+ }
86
+ }
87
+
88
+ _transform(data, encoding, done) {
89
+ this.push(data);
90
+ done();
91
+ }
92
+
93
+ _flush(done) {
94
+ // done() first: finalize() destroys the stream, and destroying before the flush callback
95
+ // has returned cuts the readable side short - end() then emits 'close' and never 'end',
96
+ // so anything waiting for end-of-data (a consumer, stream.finished, a pipeline) waits
97
+ // forever. Finalizing straight after is still safe: push(null) has already happened, so
98
+ // the queued 'end' is delivered either way, and an ended stream that nobody reads is
99
+ // still cleaned up rather than leaking its keep-alive timer and its publisher entry.
100
+ done();
101
+ this.finalize();
102
+ }
103
+ }
104
+
105
+ /**
106
+ * Opens an SSE change feed on a Hapi request.
107
+ *
108
+ * Both feeds - the admin UI one (/admin/changes) and the API one (/v1/changes) - are the same
109
+ * stream with the same framing, so the wiring lives here next to the stream it wires up rather
110
+ * than being written out twice. The parts that matter and are easy to get subtly different:
111
+ * finalize() has to run when the response is finished (a dropped tab must not keep its stream in
112
+ * registeredPublishers), the greeting has to be deferred so it is written after the response
113
+ * headers, and X-Accel-Buffering: no is what keeps an intermediate proxy from holding events
114
+ * back until the connection closes.
115
+ *
116
+ * @param {Object} request - Hapi request; the stream is parked on request.app.stream
117
+ * @param {Object} h - Hapi response toolkit
118
+ * @returns {Object} Hapi response
119
+ */
120
+ function openChangeStream(request, h) {
121
+ request.app.stream = new ResponseStream();
122
+ finished(request.app.stream, err => request.app.stream.finalize(err));
123
+ setImmediate(() => {
124
+ try {
125
+ request.app.stream.write(`: EmailEngine v${packageData.version}\n\n`);
126
+ } catch (err) {
127
+ // ignore
128
+ }
129
+ });
130
+ return h
131
+ .response(request.app.stream)
132
+ .header('X-Accel-Buffering', 'no')
133
+ .header('Connection', 'keep-alive')
134
+ .header('Cache-Control', 'no-cache')
135
+ .type('text/event-stream');
136
+ }
137
+
138
+ module.exports = { ResponseStream, registeredPublishers, openChangeStream };
package/lib/sentry.js CHANGED
@@ -49,6 +49,14 @@ function startSentry(dsn) {
49
49
  if (opts?.meta && Object.keys(opts.meta).length) {
50
50
  captureContext.contexts = { ee: opts.meta };
51
51
  }
52
+ // Tags are indexed and searchable, contexts are display-only, so anything
53
+ // worth filtering or alerting on belongs here rather than in `meta`
54
+ if (opts?.tags) {
55
+ captureContext.tags = opts.tags;
56
+ }
57
+ if (opts?.level) {
58
+ captureContext.level = opts.level;
59
+ }
52
60
  Sentry.captureException(err, captureContext);
53
61
  };
54
62
 
@@ -0,0 +1,131 @@
1
+ 'use strict';
2
+
3
+ // Inbound message processing for the built-in SMTP submission server (workers/smtp.js).
4
+ //
5
+ // Lives here rather than inline in the worker for the same reason the auth handler does
6
+ // (lib/smtp-auth.js): the worker requires worker_threads and boots an SMTPServer on load, so
7
+ // nothing inside it can be unit tested. This piece is worth testing on its own because it is
8
+ // the only place the EmailEngine-specific control headers are consumed, and every one of them
9
+ // MUST be stripped before the message goes out - a leaked X-EE-Account header discloses the
10
+ // internal account id to the recipient.
11
+
12
+ const { Splitter, Joiner } = require('@zone-eu/mailsplit');
13
+ const { HeadersRewriter } = require('./headers-rewriter');
14
+
15
+ // Control headers a client may set on a submitted message. Each is read into `meta` and then
16
+ // removed from the message. Header lookups are case-insensitive (mailsplit lowercases keys).
17
+ const ACCOUNT_HEADER = 'x-ee-account';
18
+ const IDEMPOTENCY_HEADER = 'x-ee-idempotency-key';
19
+
20
+ // SMTP reply code for a message the MIME splitter refuses to parse. Permanent, because the
21
+ // splitter is a pure parser over the message bytes: every failure it can raise (today a 1MB
22
+ // per-MIME-node header cap and a child-node cap, both 'EMAXLEN') is a property of the message
23
+ // itself, so redelivering the same bytes can only fail the same way. Without a responseCode
24
+ // smtp-server answers 450 and a conforming client keeps retrying the message until its own
25
+ // queue lifetime runs out. 552 rather than a generic 554 to match the size rejection in
26
+ // workers/smtp.js - both are "this message is too big in some dimension".
27
+ const PARSE_FAILURE_RESPONSE_CODE = 552;
28
+
29
+ /**
30
+ * Pipes a submitted message through the MIME splitter, strips the EmailEngine control headers
31
+ * into `meta`, and rejoins it.
32
+ *
33
+ * @param {Stream} stream - Raw message stream from the SMTP server
34
+ * @param {Object} [meta] - Collector object; receives requestedAccount / idempotencyKey
35
+ * @returns {Stream} Stream of the rewritten message
36
+ */
37
+ function processMessage(stream, meta) {
38
+ meta = meta || {};
39
+ const splitter = new Splitter();
40
+ const joiner = new Joiner();
41
+
42
+ const headersRewriter = new HeadersRewriter(async headers => {
43
+ let requestedAccount = headers.getFirst(ACCOUNT_HEADER);
44
+ headers.remove(ACCOUNT_HEADER);
45
+ if (requestedAccount) {
46
+ meta.requestedAccount = requestedAccount;
47
+ }
48
+
49
+ let idempotencyKey = headers.getFirst(IDEMPOTENCY_HEADER);
50
+ headers.remove(IDEMPOTENCY_HEADER);
51
+ if (idempotencyKey) {
52
+ meta.idempotencyKey = idempotencyKey;
53
+ }
54
+ });
55
+
56
+ // Forward the errors of every stage to the joiner, which is the only stream the caller ever
57
+ // sees. Readable.pipe() attaches an 'error' listener to the destination only, so an error
58
+ // raised anywhere upstream has no listener at all and takes the worker down as an uncaught
59
+ // exception. The splitter must be on this list too: it enforces a 1MB per-MIME-node header
60
+ // cap and a child-node limit (both 'EMAXLEN'), so any client that can reach the submission
61
+ // port can trigger one with a single oversized message.
62
+ //
63
+ // Only the splitter's failures are marked permanent. A raw-stream error is usually the client
64
+ // dropping the connection mid-DATA, and a headers-rewriter error can only come from the
65
+ // callback above, i.e. a bug on our side - neither is a verdict on the message, so both keep
66
+ // the retryable default.
67
+ for (let source of [stream, headersRewriter]) {
68
+ source.once('error', err => joiner.emit('error', err));
69
+ }
70
+
71
+ splitter.once('error', err => {
72
+ if (!err.responseCode) {
73
+ err.responseCode = PARSE_FAILURE_RESPONSE_CODE;
74
+ }
75
+ joiner.emit('error', err);
76
+ });
77
+
78
+ return stream.pipe(splitter).pipe(headersRewriter).pipe(joiner);
79
+ }
80
+
81
+ /**
82
+ * Buffers a submitted message: runs it through processMessage() and collects the result.
83
+ *
84
+ * The size verdict is read from the RAW stream. smtp-server keeps byteLength/sizeExceeded on the
85
+ * DATA stream it hands to onData, not on the rewritten stream returned by processMessage(), and
86
+ * it only refuses an oversized message on its own when the client volunteered a SIZE= parameter
87
+ * with MAIL FROM. Without a SIZE= it truncates the DATA stream and leaves the rejection to the
88
+ * application, so reading the flag off the wrong object means truncated messages get queued and
89
+ * delivered instead of being answered with a 552.
90
+ *
91
+ * @param {Stream} rawStream - Raw DATA stream from the SMTP server
92
+ * @param {Object} [meta] - Collector object; receives requestedAccount / idempotencyKey
93
+ * @returns {Promise<{message: Buffer, sizeExceeded: Boolean}>} Rewritten message and size verdict
94
+ */
95
+ function collectMessage(rawStream, meta) {
96
+ return new Promise((resolve, reject) => {
97
+ const stream = processMessage(rawStream, meta);
98
+
99
+ let chunks = [];
100
+ let chunklen = 0;
101
+
102
+ // Covers the source stream, the MIME splitter and the headers rewriter - processMessage()
103
+ // forwards all three here. A promise settles once, so a stream error arriving after the
104
+ // message was already collected can not produce a second SMTP response.
105
+ stream.on('error', reject);
106
+
107
+ stream.on('readable', () => {
108
+ let chunk;
109
+ while ((chunk = stream.read()) !== null) {
110
+ // Stop buffering once the limit is blown; the message is rejected either way and
111
+ // there is no reason to hold the rest of it in memory.
112
+ if (!rawStream.sizeExceeded) {
113
+ chunks.push(chunk);
114
+ chunklen += chunk.length;
115
+ }
116
+ }
117
+ });
118
+
119
+ stream.on('end', () => {
120
+ const message = Buffer.concat(chunks, chunklen);
121
+ // Release the per-chunk copies right away. The listeners above close over `chunks`
122
+ // and stay attached to the joiner until the submission finishes, so without this the
123
+ // account lookup and the queueing that follow run with two full copies of the message
124
+ // live - up to 2x EENGINE_MAX_SMTP_MESSAGE_SIZE per concurrent submission.
125
+ chunks = null;
126
+ resolve({ message, sizeExceeded: !!rawStream.sizeExceeded });
127
+ });
128
+ });
129
+ }
130
+
131
+ module.exports = { processMessage, collectMessage, ACCOUNT_HEADER, IDEMPOTENCY_HEADER, PARSE_FAILURE_RESPONSE_CODE };