emailengine-app 2.83.1 → 2.83.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.
@@ -1,3 +1,3 @@
1
1
  {
2
- ".": "2.83.1"
2
+ ".": "2.83.2"
3
3
  }
package/CHANGELOG.md CHANGED
@@ -1,5 +1,15 @@
1
1
  # Changelog
2
2
 
3
+ ## [2.83.2](https://github.com/postalsys/emailengine/compare/v2.83.1...v2.83.2) (2026-10-10)
4
+
5
+
6
+ ### Bug Fixes
7
+
8
+ * close connection and error handling gaps from the TLS/TCP audit ([c858c05](https://github.com/postalsys/emailengine/commit/c858c059eb26be91f485ba0841c306e2fcfae232))
9
+ * **deps:** update nodemailer, imapflow, mailparser and smtp-server ([5e9ef89](https://github.com/postalsys/emailengine/commit/5e9ef89e3a2bb2ff56f8a4b2c355470d2adff171))
10
+ * **deps:** update smtp-server to 3.19.21 ([c53de63](https://github.com/postalsys/emailengine/commit/c53de63f025281ba64e740895a9076097a15c8ae))
11
+ * treat a stalled response body as a transient network failure ([a33a161](https://github.com/postalsys/emailengine/commit/a33a161a71bb795bf8bf8de49d2afd9cac52fe92))
12
+
3
13
  ## [2.83.1](https://github.com/postalsys/emailengine/compare/v2.83.0...v2.83.1) (2026-10-08)
4
14
 
5
15
 
@@ -1,5 +1,5 @@
1
1
  {
2
- "creationTime": "2026-10-07T14:46:45.000000",
2
+ "creationTime": "2026-10-09T14:46:28.000000",
3
3
  "prefixes": [
4
4
  {
5
5
  "ipv6Prefix": "2001:4860:4801:2008::/64"
@@ -1,8 +1,15 @@
1
1
  'use strict';
2
2
 
3
3
  // Extracts translatable strings from JS sources into translations/messages.pot.
4
- // Run via `npm run gettext` after xgettext-template has generated the POT from the
5
- // Handlebars views - this script joins the strings found in JS files into that file.
4
+ // Run via `npm run gettext` after xgettext-template has written the strings of the Handlebars
5
+ // views to translations/messages.pot.tmp - this script joins the strings found in JS files into
6
+ // that catalog and writes the result to translations/messages.pot.
7
+ //
8
+ // The output is canonical: an unchanged source tree produces a byte-identical file. That takes
9
+ // two things xgettext-template does not do. It parses the views in the order their reads
10
+ // complete (async.parallel over fs.readFile), so both the entry order and the order of the
11
+ // reference lines of a string used in several views changed from run to run; both are sorted
12
+ // here. And the creation date is only stamped when the catalog content actually changed.
6
13
  //
7
14
  // Replaces jsxgettext, which bundled acorn 5 and crashed on post-ES2018 syntax
8
15
  // (optional chaining, nullish coalescing, etc.). Files are discovered dynamically,
@@ -16,6 +23,8 @@ const Path = require('path');
16
23
 
17
24
  const ROOT_DIR = __dirname;
18
25
  const POT_PATH = Path.join(ROOT_DIR, 'translations', 'messages.pot');
26
+ // The catalog of the Handlebars views, as written by xgettext-template
27
+ const TEMPLATES_POT_PATH = `${POT_PATH}.tmp`;
19
28
 
20
29
  // All server-side code that may contain gettext()/ngettext() calls
21
30
  const SCAN_DIRS = ['bin', 'lib', 'workers'];
@@ -114,6 +123,65 @@ function extractFromFile(filePath) {
114
123
  return entries;
115
124
  }
116
125
 
126
+ // "views/a.hbs:12" -> ['views/a.hbs', 12], so line 9 sorts before line 10
127
+ function parseReference(reference) {
128
+ let separator = reference.lastIndexOf(':');
129
+ return [reference.slice(0, separator), Number(reference.slice(separator + 1))];
130
+ }
131
+
132
+ function compareReferences(a, b) {
133
+ let [pathA, lineA] = parseReference(a);
134
+ let [pathB, lineB] = parseReference(b);
135
+ if (pathA !== pathB) {
136
+ return pathA < pathB ? -1 : 1;
137
+ }
138
+ return lineA - lineB;
139
+ }
140
+
141
+ // One reference per line as written here, but several to a line in catalogs from GNU tools
142
+ function getReferences(entry) {
143
+ let reference = entry.comments && entry.comments.reference;
144
+ return reference ? reference.split(/\s+/).filter(value => value) : [];
145
+ }
146
+
147
+ const compareStrings = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
148
+
149
+ // Entries in source order: by their first reference, so a file's strings stay together in the
150
+ // order they appear in it. Context, then msgid, break ties (several strings on one line)
151
+ function compareEntries(a, b) {
152
+ let refA = getReferences(a)[0] || '';
153
+ let refB = getReferences(b)[0] || '';
154
+ if (refA !== refB) {
155
+ return compareReferences(refA, refB);
156
+ }
157
+ return compareStrings(a.msgctxt || '', b.msgctxt || '') || compareStrings(a.msgid, b.msgid);
158
+ }
159
+
160
+ /**
161
+ * Compiles a parsed catalog in canonical form: every entry's references sorted, and the entries
162
+ * sorted by their first one. Mutates the reference comments of `pot`
163
+ * @param {Object} pot - Catalog as returned by po.parse()
164
+ * @returns {Buffer} The compiled POT file
165
+ */
166
+ function compileCanonical(pot) {
167
+ for (let entries of Object.values(pot.translations)) {
168
+ for (let entry of Object.values(entries)) {
169
+ let references = getReferences(entry);
170
+ if (references.length) {
171
+ entry.comments.reference = references.sort(compareReferences).join('\n');
172
+ }
173
+ }
174
+ }
175
+ return po.compile(pot, { sort: compareEntries });
176
+ }
177
+
178
+ function formatCreationDate(date) {
179
+ return date
180
+ .toISOString()
181
+ .replace(/T/, ' ')
182
+ .replace(/:\d+\.\d+Z$/, '+0000');
183
+ }
184
+
117
185
  function main() {
118
186
  let files = listScanFiles();
119
187
 
@@ -122,16 +190,9 @@ function main() {
122
190
  extracted = extracted.concat(extractFromFile(filePath));
123
191
  }
124
192
 
125
- let pot = po.parse(fs.readFileSync(POT_PATH));
193
+ let pot = po.parse(fs.readFileSync(TEMPLATES_POT_PATH));
126
194
  let translations = (pot.translations[''] = pot.translations[''] || {});
127
195
 
128
- // xgettext-template does not stamp a creation date, so set it here (jsxgettext used to)
129
- pot.headers = pot.headers || {};
130
- pot.headers['POT-Creation-Date'] = new Date()
131
- .toISOString()
132
- .replace(/T/, ' ')
133
- .replace(/:\d+\.\d+Z$/, '+0000');
134
-
135
196
  for (let { msgid, msgidPlural, reference } of extracted) {
136
197
  let entry = translations[msgid];
137
198
  if (!entry) {
@@ -144,20 +205,39 @@ function main() {
144
205
  }
145
206
 
146
207
  entry.comments = entry.comments || {};
147
- let references = entry.comments.reference ? entry.comments.reference.split('\n') : [];
208
+ let references = getReferences(entry);
148
209
  if (!references.includes(reference)) {
149
210
  references.push(reference);
150
211
  }
151
212
  entry.comments.reference = references.join('\n');
152
213
  }
153
214
 
154
- fs.writeFileSync(POT_PATH, po.compile(pot));
155
- console.log(`Extracted ${extracted.length} gettext strings from ${files.length} JS files into ${Path.relative(ROOT_DIR, POT_PATH)}`);
215
+ // xgettext-template does not stamp a creation date (jsxgettext used to). The previous date is
216
+ // kept unless the content changed, so an unchanged tree leaves the file as it was
217
+ let existing = fs.existsSync(POT_PATH) ? fs.readFileSync(POT_PATH) : Buffer.alloc(0);
218
+ pot.headers = pot.headers || {};
219
+ pot.headers['POT-Creation-Date'] = existing.length ? po.parse(existing).headers['POT-Creation-Date'] : '';
220
+ let output = compileCanonical(pot);
221
+
222
+ let changed = !output.equals(existing);
223
+ if (changed) {
224
+ pot.headers['POT-Creation-Date'] = formatCreationDate(new Date());
225
+ fs.writeFileSync(POT_PATH, compileCanonical(pot));
226
+ }
227
+
228
+ console.log(
229
+ `Extracted ${extracted.length} gettext strings from ${files.length} JS files into ${Path.relative(ROOT_DIR, POT_PATH)}${changed ? '' : ' (unchanged)'}`
230
+ );
156
231
  }
157
232
 
158
233
  if (require.main === module) {
159
- main();
234
+ try {
235
+ main();
236
+ } finally {
237
+ // Also on failure, so a broken run does not leave the intermediate file behind
238
+ fs.rmSync(TEMPLATES_POT_PATH, { force: true });
239
+ }
160
240
  }
161
241
 
162
242
  // Exported for the gettext coverage test, which walks the same scan set with the same helpers
163
- module.exports = { listScanFiles, parseFile, calleeName, extractFromFile };
243
+ module.exports = { listScanFiles, parseFile, calleeName, extractFromFile, compareReferences, compileCanonical };
package/lib/consts.js CHANGED
@@ -423,7 +423,9 @@ module.exports = {
423
423
  'ECONNREFUSED',
424
424
  'UND_ERR_SOCKET',
425
425
  'UND_ERR_CONNECT_TIMEOUT',
426
- 'UND_ERR_HEADERS_TIMEOUT'
426
+ 'UND_ERR_HEADERS_TIMEOUT',
427
+ // a response body that stalled mid-transfer
428
+ 'UND_ERR_BODY_TIMEOUT'
427
429
  ]),
428
430
 
429
431
  // Error codes meaning "the IMAP connection is gone", as opposed to the command itself failing
@@ -3853,6 +3853,29 @@ class BaseClient {
3853
3853
  * @param {Object} context - Error handling context
3854
3854
  */
3855
3855
  async handleSubmitError(err, context) {
3856
+ // Every caller rethrows err once this returns, so nothing in here may throw instead of it:
3857
+ // a Redis failure replacing a permanent 550 was classified and retried as the Redis error
3858
+ try {
3859
+ await this.recordSubmitError(err, context);
3860
+ } catch (recordErr) {
3861
+ this.logger.error({ msg: 'Failed to record the delivery error', queueId: context.queueId, err: recordErr });
3862
+ }
3863
+
3864
+ // Enhance error with additional context. The API clients report their send failures
3865
+ // through here as well, and those arrive with a statusCode and info of their own that
3866
+ // must survive - only an SMTP reply code overrides the status
3867
+ err.code = err.code || 'SubmitFail';
3868
+ err.statusCode = Number(err.responseCode) || err.statusCode || null;
3869
+ err.info = Object.assign({}, err.info, { networkRouting: context.networkRouting });
3870
+ }
3871
+
3872
+ /**
3873
+ * Records a send failure: the account and gateway SMTP status, the feedback key and the
3874
+ * delivery error webhook. Each step is attempted even when an earlier one failed
3875
+ * @param {Error} err - The error that occurred
3876
+ * @param {Object} context - Error handling context
3877
+ */
3878
+ async recordSubmitError(err, context) {
3856
3879
  const { smtpSettings, networkRouting, gatewayData, gatewayObject, data, jobData, queueId, envelope } = context;
3857
3880
 
3858
3881
  // Build SMTP status from error. Only an SMTP attempt has one to report: a provider API send
@@ -3881,29 +3904,30 @@ class BaseClient {
3881
3904
  // Update feedback key with failure status
3882
3905
  if (data.feedbackKey && !jobData.nextAttempt) {
3883
3906
  const errorMessage = (smtpStatus && smtpStatus.description) || 'Failed to send email';
3884
- await this.updateFeedbackKey(data.feedbackKey, false, errorMessage);
3907
+ try {
3908
+ await this.updateFeedbackKey(data.feedbackKey, false, errorMessage);
3909
+ } catch (feedbackErr) {
3910
+ this.logger.error({ msg: 'Failed to update the submission feedback key', queueId, messageId: data.messageId, err: feedbackErr });
3911
+ }
3885
3912
  }
3886
3913
 
3887
3914
  // Send delivery error notification
3888
- await this.notify(
3889
- false,
3890
- EMAIL_DELIVERY_ERROR_NOTIFY,
3891
- NotificationBuilder.buildErrorPayload({
3892
- error: err,
3893
- queueId,
3894
- envelope,
3895
- messageId: data.messageId,
3896
- networkRouting,
3897
- jobData
3898
- })
3899
- );
3900
-
3901
- // Enhance error with additional context. The API clients report their send failures
3902
- // through here as well, and those arrive with a statusCode and info of their own that
3903
- // must survive - only an SMTP reply code overrides the status
3904
- err.code = err.code || 'SubmitFail';
3905
- err.statusCode = Number(err.responseCode) || err.statusCode || null;
3906
- err.info = Object.assign({}, err.info, { networkRouting });
3915
+ try {
3916
+ await this.notify(
3917
+ false,
3918
+ EMAIL_DELIVERY_ERROR_NOTIFY,
3919
+ NotificationBuilder.buildErrorPayload({
3920
+ error: err,
3921
+ queueId,
3922
+ envelope,
3923
+ messageId: data.messageId,
3924
+ networkRouting,
3925
+ jobData
3926
+ })
3927
+ );
3928
+ } catch (notifyErr) {
3929
+ this.logger.error({ msg: 'Failed to queue the delivery error notification', queueId, messageId: data.messageId, err: notifyErr });
3930
+ }
3907
3931
  }
3908
3932
 
3909
3933
  // stub - to be implemented by subclasses
@@ -18,39 +18,11 @@
18
18
  // pure subconnection tests do not inherit the Redis connections this module's imports open.
19
19
 
20
20
  const { resolveCredentials } = require('../tools');
21
- const { AUTH_ERROR_NOTIFY, TRANSIENT_NETWORK_CODES } = require('../consts');
21
+ const { AUTH_ERROR_NOTIFY } = require('../consts');
22
+ // Re-exported: the credential and API retry paths have always imported it from here
23
+ const { isTransientNetworkError } = require('../network-errors');
22
24
  const { ACCOUNT_STATES } = require('../account/account-state');
23
25
 
24
- // How far down a cause chain the transient check looks. A chain is not guaranteed to be finite - an
25
- // error may cite itself - so the walk is bounded rather than trusting it to end.
26
- const MAX_CAUSE_DEPTH = 5;
27
-
28
- /**
29
- * Failing to reach a remote endpoint is a connection problem, not a rejected credential. Both
30
- * OAuth2 credential sources (EmailEngine's own token refresh and an external authentication
31
- * server) use this to avoid reporting an unreachable host as an authentication error, and the API
32
- * transports use it to decide which failed requests to repeat.
33
- *
34
- * The whole cause chain is searched, not one level. undici reports a connection failure as a generic
35
- * TypeError ("fetch failed") with the real DNS/socket error on err.cause, and a caller that wraps THAT
36
- * failure in an error of its own pushes it one level deeper: lib/oauth/external-account-signer.js does
37
- * exactly that for its three Workload Identity Federation requests, so an unreachable Google STS
38
- * endpoint used to be classified as a refused credential and park the account - the one outcome this
39
- * check exists to prevent.
40
- *
41
- * @param {Error} err - The error to check
42
- * @returns {boolean} True if the error, or anything it was caused by, is a transient network failure
43
- */
44
- function isTransientNetworkError(err) {
45
- for (let cause = err, depth = 0; cause && typeof cause === 'object' && depth < MAX_CAUSE_DEPTH; cause = cause.cause, depth++) {
46
- if (TRANSIENT_NETWORK_CODES.has(cause.code)) {
47
- return true;
48
- }
49
- }
50
-
51
- return false;
52
- }
53
-
54
26
  /**
55
27
  * Reads the HTTP status a failed credential request came back with. The OAuth2 clients put it on
56
28
  * the error itself and repeat it in the request record they attach; the Graph and Gmail transports
@@ -133,11 +133,29 @@ function closePooledConnection(poolKey) {
133
133
  }
134
134
  }
135
135
 
136
+ /**
137
+ * Whether a pooled transport still has a message queued or being transmitted. Reads nodemailer's
138
+ * pool internals: isIdle() turns true while a message is still on the wire
139
+ * @param {Object} transporter - Nodemailer transport instance
140
+ * @returns {boolean}
141
+ */
142
+ function hasPendingDeliveries(transporter) {
143
+ const pool = transporter && transporter.transporter;
144
+ if (!pool) {
145
+ return false;
146
+ }
147
+ return (
148
+ (Array.isArray(pool._queue) && pool._queue.length > 0) ||
149
+ (Array.isArray(pool._connections) && pool._connections.some(connection => connection.queueEntry))
150
+ );
151
+ }
152
+
136
153
  /**
137
154
  * Performs cleanup of idle SMTP pool connections
155
+ * @param {number} [now] - Current time, for tests
138
156
  */
139
- function cleanupIdlePools() {
140
- const now = Date.now();
157
+ function cleanupIdlePools(now) {
158
+ now = now || Date.now();
141
159
  const idleKeys = [];
142
160
 
143
161
  for (const [poolKey, lastUsed] of SMTP_POOL_LAST_USED.entries()) {
@@ -149,11 +167,11 @@ function cleanupIdlePools() {
149
167
  for (const poolKey of idleKeys) {
150
168
  const transporter = SMTP_POOLS.get(poolKey);
151
169
  if (transporter) {
152
- // Check if the transporter has active connections
153
- if (transporter._connectionPool && transporter._connectionPool.size > 0) {
154
- // Still has active connections, update last used time
170
+ // "Idle" is measured from the last time a message was handed to the pool, so a single
171
+ // transmission that outlasts the idle window would otherwise be cut off
172
+ if (hasPendingDeliveries(transporter)) {
155
173
  SMTP_POOL_LAST_USED.set(poolKey, now);
156
- logger.trace({ msg: 'SMTP pool still has active connections, skipping cleanup', poolKey });
174
+ logger.trace({ msg: 'SMTP pool still has deliveries in progress, skipping cleanup', poolKey });
157
175
  continue;
158
176
  }
159
177
 
@@ -193,6 +211,7 @@ module.exports = {
193
211
  getPoolSize,
194
212
  // Exported for testing
195
213
  generatePoolKey,
214
+ cleanupIdlePools,
196
215
  SMTP_POOL_MAX_IDLE,
197
216
  SMTP_POOL_CLEANUP_INTERVAL
198
217
  };
package/lib/export.js CHANGED
@@ -400,50 +400,58 @@ class Export {
400
400
  const now = Date.now();
401
401
  const expiresAt = now + maxAge;
402
402
 
403
- const activeEntry = await tryAddToActiveSet(account, exportId);
404
-
405
- await fs.promises.mkdir(exportPath, { recursive: true });
406
-
407
- const secret = await getSecret();
408
- const isEncrypted = !!secret;
409
- const fileExtension = isEncrypted ? EXPORT_FILE_EXTENSION_ENCRYPTED : EXPORT_FILE_EXTENSION;
410
- const filePath = pathlib.join(exportPath, `${exportId}${fileExtension}`);
411
403
  const startDate = toTimestamp(options.startDate);
412
404
  const endDate = toTimestamp(options.endDate);
413
405
 
414
- const exportData = {
415
- exportId,
416
- account,
417
- status: 'queued',
418
- phase: 'pending',
419
- folders: JSON.stringify(options.folders || []),
420
- startDate,
421
- endDate,
422
- textType: options.textType || '*',
423
- // Preserve an explicit 0 ("unlimited" per the API contract); only fall back when unset.
424
- maxBytes: Number.isInteger(options.maxBytes) ? options.maxBytes : 5 * 1024 * 1024,
425
- includeAttachments: options.includeAttachments ? '1' : '0',
426
- isEncrypted: isEncrypted ? '1' : '0',
427
- foldersScanned: 0,
428
- foldersTotal: 0,
429
- messagesQueued: 0,
430
- messagesExported: 0,
431
- messagesSkipped: 0,
432
- bytesWritten: 0,
433
- filePath,
434
- created: now,
435
- expiresAt,
436
- error: ''
437
- };
406
+ const activeEntry = await tryAddToActiveSet(account, exportId);
438
407
 
439
- const ttl = Math.ceil(maxAge / 1000);
408
+ // Anything that fails after taking the slot has to give it back, or the account reads as
409
+ // busy (429) until the sweeper notices
410
+ try {
411
+ await fs.promises.mkdir(exportPath, { recursive: true });
412
+
413
+ const secret = await getSecret();
414
+ const isEncrypted = !!secret;
415
+ const fileExtension = isEncrypted ? EXPORT_FILE_EXTENSION_ENCRYPTED : EXPORT_FILE_EXTENSION;
416
+ const filePath = pathlib.join(exportPath, `${exportId}${fileExtension}`);
417
+
418
+ const exportData = {
419
+ exportId,
420
+ account,
421
+ status: 'queued',
422
+ phase: 'pending',
423
+ folders: JSON.stringify(options.folders || []),
424
+ startDate,
425
+ endDate,
426
+ textType: options.textType || '*',
427
+ // Preserve an explicit 0 ("unlimited" per the API contract); only fall back when unset.
428
+ maxBytes: Number.isInteger(options.maxBytes) ? options.maxBytes : 5 * 1024 * 1024,
429
+ includeAttachments: options.includeAttachments ? '1' : '0',
430
+ isEncrypted: isEncrypted ? '1' : '0',
431
+ foldersScanned: 0,
432
+ foldersTotal: 0,
433
+ messagesQueued: 0,
434
+ messagesExported: 0,
435
+ messagesSkipped: 0,
436
+ bytesWritten: 0,
437
+ filePath,
438
+ created: now,
439
+ expiresAt,
440
+ error: ''
441
+ };
440
442
 
441
- await redis.multi().hmset(exportKey, exportData).expire(exportKey, ttl).exec();
443
+ const ttl = Math.ceil(maxAge / 1000);
444
+
445
+ await redis.multi().hmset(exportKey, exportData).expire(exportKey, ttl).exec();
442
446
 
443
- try {
444
447
  await exportQueue.add('export', { account, exportId }, { jobId: exportId, removeOnComplete: true, removeOnFail: true });
445
448
  } catch (err) {
446
- await redis.multi().srem(ACTIVE_EXPORTS_KEY, activeEntry).del(exportKey).exec();
449
+ try {
450
+ await redis.multi().srem(ACTIVE_EXPORTS_KEY, activeEntry).del(exportKey).exec();
451
+ } catch (cleanupErr) {
452
+ // the sweeper releases the slot eventually; the caller needs the original error
453
+ logger.error({ msg: 'Failed to release the export slot', account, exportId, err: cleanupErr });
454
+ }
447
455
  throw err;
448
456
  }
449
457
 
@@ -70,8 +70,10 @@ function upgrade(connection) {
70
70
  }
71
71
  };
72
72
 
73
- // Apply additional socket options if these are set in the server options
74
- ['requestCert', 'rejectUnauthorized', 'NPNProtocols', 'SNICallback', 'session', 'requestOCSP'].forEach(key => {
73
+ // Apply additional socket options if these are set in the server options. SNICallback is not
74
+ // copied: the wrapper above already defers to it, and copying it over discarded the wrapper's
75
+ // error logging and its fallback to the default context
76
+ ['requestCert', 'rejectUnauthorized', 'NPNProtocols', 'session', 'requestOCSP'].forEach(key => {
75
77
  if (key in connection._server.options) {
76
78
  socketOptions[key] = connection._server.options[key];
77
79
  }
@@ -20,6 +20,9 @@ const MAX_PROXY_HEADER_SIZE = 256;
20
20
  // has not produced it by then is not a proxy we are waiting on, and it must not hold an fd forever.
21
21
  const PROXY_HEADER_TIMEOUT = 10 * 1000;
22
22
 
23
+ // How long an implicit TLS client has to complete its handshake
24
+ const TLS_HANDSHAKE_TIMEOUT = 30 * 1000;
25
+
23
26
  /**
24
27
  * Creates a IMAP server instance.
25
28
  *
@@ -258,6 +261,20 @@ class IMAPServer extends EventEmitter {
258
261
  socket.once('close', () => {
259
262
  this._socketCount--;
260
263
  });
264
+
265
+ // The non-PROXY path hands the socket over a tick later, with no error listener on it until
266
+ // then; a reset in that window would be uncaught and take down the whole worker
267
+ socket.on('error', err => {
268
+ this.logger.debug(
269
+ {
270
+ tnx: 'connect',
271
+ remoteAddress: socket.remoteAddress,
272
+ err
273
+ },
274
+ 'Socket error on accepted connection: %s',
275
+ err && err.message
276
+ );
277
+ });
261
278
  return true;
262
279
  }
263
280
 
@@ -414,10 +431,24 @@ class IMAPServer extends EventEmitter {
414
431
 
415
432
  let remoteAddress = socket.remoteAddress;
416
433
 
417
- let errorTimer = false;
434
+ // A client-side failure to establish the session, logged quietly
435
+ let socketError = message => {
436
+ let err = new Error(message);
437
+ err.responseCode = 500;
438
+ err.code = 'SocketError';
439
+ err.report = false;
440
+ err.meta = {
441
+ protocol: 'imap',
442
+ stage: 'connect',
443
+ remoteAddress
444
+ };
445
+ return err;
446
+ };
447
+
448
+ let handshakeTimer = false;
418
449
  let returned = false;
419
450
  let onError = err => {
420
- clearTimeout(errorTimer);
451
+ clearTimeout(handshakeTimer);
421
452
  if (returned) {
422
453
  return;
423
454
  }
@@ -435,15 +466,7 @@ class IMAPServer extends EventEmitter {
435
466
  };
436
467
  }
437
468
  if (!err || !err.message) {
438
- err = new Error('Socket closed while initiating TLS');
439
- err.responseCode = 500;
440
- err.code = 'SocketError';
441
- err.report = false;
442
- err.meta = {
443
- protocol: 'imap',
444
- stage: 'connect',
445
- remoteAddress
446
- };
469
+ err = socketError('Socket closed while initiating TLS');
447
470
  }
448
471
  callback(err);
449
472
  };
@@ -466,7 +489,17 @@ class IMAPServer extends EventEmitter {
466
489
  tlsSocket.once('clientError', onError);
467
490
  tlsSocket.once('tlsClientError', onError);
468
491
 
492
+ // Without this a client that never completes the handshake holds its socket and its
493
+ // maxConnections slot for good: the PROXY header timeout is already cleared, and the
494
+ // session's own socket timeout only starts after the handshake
495
+ handshakeTimer = setTimeout(() => {
496
+ onError(socketError('TLS handshake timed out'));
497
+ tlsSocket.destroy();
498
+ socket.destroy();
499
+ }, Number(this.options.tlsHandshakeTimeout) || TLS_HANDSHAKE_TIMEOUT);
500
+
469
501
  tlsSocket.on('secure', () => {
502
+ clearTimeout(handshakeTimer);
470
503
  socket.removeListener('error', onError);
471
504
  tlsSocket.removeListener('close', onCloseError);
472
505
  tlsSocket.removeListener('error', onError);
@@ -200,8 +200,9 @@ function createProxyAuthHandler({ onAuth, createProxy, logger, serverLogger, met
200
200
  // stored account data (the login name is the same id, kept as a fallback).
201
201
  const account = (accountData && accountData.account) || login.username;
202
202
 
203
+ let downstream;
203
204
  try {
204
- const downstream = await createProxy({ imapConfig, id: session.id, logger: logger.child({ property: 'upstream', account }) });
205
+ downstream = await createProxy({ imapConfig, id: session.id, logger: logger.child({ property: 'upstream', account }) });
205
206
 
206
207
  session.onProxy = upstream => attachProxy({ session, account, downstream, upstream });
207
208
 
@@ -215,6 +216,14 @@ function createProxyAuthHandler({ onAuth, createProxy, logger, serverLogger, met
215
216
  );
216
217
  }
217
218
  } catch (err) {
219
+ // The client is refused, so an upstream session already opened has no one to serve
220
+ if (downstream && downstream.imapClient) {
221
+ try {
222
+ downstream.imapClient.close();
223
+ } catch (closeErr) {
224
+ logger.warn({ msg: 'Failed to close upstream connection', account, cid: session.id, err: closeErr });
225
+ }
226
+ }
218
227
  throw loginFailure(err, { account, cid: session.id }, { response: 'Upstream authentication failed', fault: 'Failed to create proxy' });
219
228
  }
220
229
 
package/lib/logger.js CHANGED
@@ -7,7 +7,8 @@ if (!process.env.EE_ENV_LOADED) {
7
7
 
8
8
  const config = require('@zone-eu/wild-config');
9
9
  const pino = require('pino');
10
- const { TRANSIENT_NETWORK_CODES, REDACTED_LOG_KEYS } = require('./consts');
10
+ const { REDACTED_LOG_KEYS } = require('./consts');
11
+ const { isTransientNetworkError } = require('./network-errors');
11
12
 
12
13
  config.log = config.log || {
13
14
  level: 'trace'
@@ -21,7 +22,7 @@ config.log.level = config.log.level || 'trace';
21
22
  // error tracking, where they pile up as useless "fetch failed" reports. Genuine
22
23
  // TypeError/RangeError bugs have no network errno cause and still get reported.
23
24
  function isTransientFetchError(err) {
24
- return err && err.name === 'TypeError' && err.cause && TRANSIENT_NETWORK_CODES.has(err.cause.code);
25
+ return err && err.name === 'TypeError' && isTransientNetworkError(err);
25
26
  }
26
27
 
27
28
  let logger = pino({