emailengine-app 2.83.0 → 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.
Files changed (52) hide show
  1. package/.release-please-manifest.json +1 -1
  2. package/CHANGELOG.md +21 -0
  3. package/data/google-crawlers.json +1 -1
  4. package/gettext-extract.js +95 -15
  5. package/lib/api-reference/format.js +1 -1
  6. package/lib/api-routes/export-routes.js +5 -5
  7. package/lib/api-routes/oauth2-app-routes.js +4 -1
  8. package/lib/api-routes/route-helpers.js +11 -5
  9. package/lib/consts.js +3 -1
  10. package/lib/email-client/base-client.js +44 -20
  11. package/lib/email-client/credential-errors.js +3 -31
  12. package/lib/email-client/smtp-pool-manager.js +25 -6
  13. package/lib/export.js +44 -36
  14. package/lib/imapproxy/imap-core/lib/commands/starttls.js +4 -2
  15. package/lib/imapproxy/imap-core/lib/imap-server.js +44 -11
  16. package/lib/imapproxy/proxy-handoff.js +10 -1
  17. package/lib/logger.js +3 -2
  18. package/lib/message-port-stream.js +23 -0
  19. package/lib/network-errors.js +50 -0
  20. package/lib/oauth/gcp-metadata.js +50 -13
  21. package/lib/oauth/gmail.js +17 -7
  22. package/lib/oauth/mail-ru.js +5 -1
  23. package/lib/oauth/outlook.js +5 -1
  24. package/lib/oauth/pubsub/google.js +3 -2
  25. package/lib/oauth/token-fetch.js +2 -3
  26. package/lib/oauth/verify-app.js +8 -2
  27. package/lib/oauth2-apps.js +26 -6
  28. package/lib/sub-script.js +10 -3
  29. package/lib/swagger-options.js +2 -3
  30. package/lib/tools.js +16 -2
  31. package/lib/ui-routes/oauth-config-routes.js +14 -15
  32. package/lib/ui-routes/oauth-form-context.js +19 -0
  33. package/package.json +10 -10
  34. package/sbom.json +1 -1
  35. package/static/css/flyonui.css +1 -1
  36. package/static/licenses.html +12 -12
  37. package/translations/README.md +3 -2
  38. package/translations/messages.pot +257 -257
  39. package/views/accounts/account.hbs +0 -5
  40. package/views/config/oauth/edit.hbs +0 -10
  41. package/views/config/oauth/new.hbs +0 -10
  42. package/views/partials/oauth_form.hbs +426 -928
  43. package/views/partials/oauth_graph_endpoints.hbs +12 -0
  44. package/views/partials/oauth_pubsub_app_select.hbs +11 -20
  45. package/views/partials/oauth_scope_presets.hbs +21 -0
  46. package/views/partials/ui/choice-tab.hbs +23 -0
  47. package/views/partials/ui/choice-tabs.hbs +32 -0
  48. package/views/partials/ui/radio.hbs +2 -2
  49. package/views/partials/ui/secret-field.hbs +2 -1
  50. package/views/partials/ui/tabs.hbs +1 -2
  51. package/workers/imap.js +10 -3
  52. package/workers/smtp.js +16 -1
@@ -1,3 +1,3 @@
1
1
  {
2
- ".": "2.83.0"
2
+ ".": "2.83.2"
3
3
  }
package/CHANGELOG.md CHANGED
@@ -1,5 +1,26 @@
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
+
13
+ ## [2.83.1](https://github.com/postalsys/emailengine/compare/v2.83.0...v2.83.1) (2026-10-08)
14
+
15
+
16
+ ### Bug Fixes
17
+
18
+ * ask a service account app's purpose before its authentication method ([42ac521](https://github.com/postalsys/emailengine/commit/42ac521021fabe8976fd86f13da6e8c6d1707ac3))
19
+ * close the attached service account review findings ([d567ad8](https://github.com/postalsys/emailengine/commit/d567ad866f90e0ced6b2b1d8fa722e7a74d6ac25))
20
+ * drop the beta label from the export API ([21df0b0](https://github.com/postalsys/emailengine/commit/21df0b0e4ad5bb1ef18ce3eb916fa77e9028075d))
21
+ * keep the OAuth2 app routes inside their size budget ([8a72c20](https://github.com/postalsys/emailengine/commit/8a72c20188aad62d7cb32401d98869c1ed96a75a))
22
+ * rework the OAuth2 app form around what each app connects with ([a000412](https://github.com/postalsys/emailengine/commit/a000412ecc2c233f9fb4cc50fe8486904692a8ba))
23
+
3
24
  ## [2.83.0](https://github.com/postalsys/emailengine/compare/v2.82.2...v2.83.0) (2026-10-08)
4
25
 
5
26
 
@@ -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 };
@@ -60,7 +60,7 @@ function formatDescription(text) {
60
60
  .join('</p><p class="mt-2">');
61
61
  }
62
62
 
63
- // URL segment for a tag name: "Export (Beta)" -> "export-beta"
63
+ // URL segment for a tag name: "Multi Message Actions" -> "multi-message-actions"
64
64
  function slugify(value) {
65
65
  return String(value || '')
66
66
  .toLowerCase()
@@ -34,7 +34,7 @@ async function init(args) {
34
34
  options: {
35
35
  description: 'Create export',
36
36
  notes: ['Creates a new bulk message export job. The export runs asynchronously and notifies via webhook when complete.', BEHAVIOR.BACKGROUND_JOB],
37
- tags: ['api', 'Export (Beta)'],
37
+ tags: ['api', 'Export'],
38
38
 
39
39
  plugins: {
40
40
  openapi: {
@@ -94,7 +94,7 @@ async function init(args) {
94
94
  options: {
95
95
  description: 'Get export status',
96
96
  notes: 'Returns the status and progress of an export job.',
97
- tags: ['api', 'Export (Beta)'],
97
+ tags: ['api', 'Export'],
98
98
 
99
99
  plugins: {
100
100
  openapi: {
@@ -158,7 +158,7 @@ async function init(args) {
158
158
  options: {
159
159
  description: 'Download export file',
160
160
  notes: 'Downloads the completed export file as gzip-compressed NDJSON.',
161
- tags: ['api', 'Export (Beta)'],
161
+ tags: ['api', 'Export'],
162
162
 
163
163
  plugins: {
164
164
  openapi: {
@@ -208,7 +208,7 @@ async function init(args) {
208
208
  options: {
209
209
  description: 'Delete export',
210
210
  notes: 'Cancels a pending export or deletes a completed export. Removes both Redis data and the export file.',
211
- tags: ['api', 'Export (Beta)'],
211
+ tags: ['api', 'Export'],
212
212
 
213
213
  plugins: {
214
214
  openapi: {
@@ -264,7 +264,7 @@ async function init(args) {
264
264
  options: {
265
265
  description: 'List exports',
266
266
  notes: 'Lists all exports for an account with pagination.',
267
- tags: ['api', 'Export (Beta)'],
267
+ tags: ['api', 'Export'],
268
268
 
269
269
  plugins: {
270
270
  openapi: {
@@ -345,7 +345,7 @@ async function init(args) {
345
345
 
346
346
  async handler(request) {
347
347
  try {
348
- assertNoAttachedIdentity(request);
348
+ assertNoAttachedIdentity(request, request.payload.authMethod, 'create');
349
349
  let result = await oauth2Apps.create(request.payload);
350
350
  return await applyPubSubUpdates(result);
351
351
  } catch (err) {
@@ -413,6 +413,9 @@ async function init(args) {
413
413
  );
414
414
  }
415
415
 
416
+ let storedApp = await oauth2Apps.get(request.params.app);
417
+ assertNoAttachedIdentity(request, storedApp && storedApp.authMethod, 'modify');
418
+
416
419
  let result = await oauth2Apps.update(request.params.app, request.payload);
417
420
  return await applyPubSubUpdates(result);
418
421
  } catch (err) {
@@ -420,18 +420,24 @@ function assertNoPrivilegedSettings(request, keys, verb = 'change') {
420
420
  * than an app field, so a token narrowed to `oauth2` may manage applications but not lend itself
421
421
  * the deployment's identity. The admin interface and an unrestricted token still create these apps.
422
422
  *
423
- * Only creation needs the check: the update payload carries no authMethod, and a saved app's method
424
- * is pinned (isAuthMethodLocked() in lib/oauth2-apps.js).
423
+ * Creating one is not the only way in: an update of a saved app re-runs its Pub/Sub setup as that same
424
+ * identity, so moving the project, topic or subscription of an existing attached service account app
425
+ * lends it just the same. Any update of such an app is refused, not only one naming those fields: an
426
+ * allow-list of harmless fields would be one more list to keep right, and the admin interface and an
427
+ * unrestricted token remain. A saved app's method is pinned (isAuthMethodLocked() in
428
+ * lib/oauth2-apps.js), so the stored one is what an update checks.
425
429
  *
426
430
  * @param {Object} request - the Hapi request
431
+ * @param {string} [authMethod] - the method of the app being created (the payload's) or modified (the stored one's)
432
+ * @param {string} verb - 'create' or 'modify', for the refusal message
427
433
  */
428
- function assertNoAttachedIdentity(request) {
429
- if (!request.payload || request.payload.authMethod !== 'metadataServer' || !isRestrictedCredential(request)) {
434
+ function assertNoAttachedIdentity(request, authMethod, verb) {
435
+ if (authMethod !== 'metadataServer' || !isRestrictedCredential(request)) {
430
436
  return;
431
437
  }
432
438
 
433
439
  throw Boom.forbidden(
434
- 'A token with restricted permissions can not create an application that uses the attached service account (metadataServer). Create it from the admin interface or with an unrestricted token'
440
+ `A token with restricted permissions can not ${verb} an application that uses the attached service account (metadataServer). Use the admin interface or an unrestricted token`
435
441
  );
436
442
  }
437
443
 
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
  }