emailengine-app 2.72.2 → 2.72.4

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/CHANGELOG.md CHANGED
@@ -1,5 +1,57 @@
1
1
  # Changelog
2
2
 
3
+ ## [2.72.4](https://github.com/postalsys/emailengine/compare/v2.72.3...v2.72.4) (2026-07-11)
4
+
5
+
6
+ ### Bug Fixes
7
+
8
+ * bump imapflow/bullmq/bull-board/sentry-node/eerawlog/prettier ([8f7b6bf](https://github.com/postalsys/emailengine/commit/8f7b6bf21eae70b1f3c8e0856a6c0f0a0d641317))
9
+ * clear the connecting flag if loading account data fails during reconnect ([8d82167](https://github.com/postalsys/emailengine/commit/8d8216730f809eebdc8a0762e38f93f0084de038))
10
+ * clear the pending changes debounce when closing a subconnection ([a286f89](https://github.com/postalsys/emailengine/commit/a286f89e721336b64a9c16737cf30d161f52fe22))
11
+ * disable subconnection when the monitored mailbox no longer exists ([e1895d6](https://github.com/postalsys/emailengine/commit/e1895d64b5fd17912f582406c7c352b9176364c6))
12
+ * do not report connectError when pause() interrupts a connection attempt ([4d38e4f](https://github.com/postalsys/emailengine/commit/4d38e4f047be16f4f5a16a0274c5240346c2b50f))
13
+ * drop the reconnect timer handle when closing an IMAP connection ([9f46c77](https://github.com/postalsys/emailengine/commit/9f46c77afef8217a8b6b69e736cb0cd38b27429b))
14
+ * ignore \NonExistent folders in mailbox listing ([7ec96cf](https://github.com/postalsys/emailengine/commit/7ec96cfaaf5425c16479151e66ef3285c854b49a))
15
+ * prevent overlapping and revived subconnection reconnect cycles ([5754c07](https://github.com/postalsys/emailengine/commit/5754c074f0f8c89222008e4c1d331b66891b3c16))
16
+ * process refreshed folder listings so new folders emit mailboxNew ([247c325](https://github.com/postalsys/emailengine/commit/247c325cc71f1842cc8083c7fd025792217c77d8))
17
+ * reconcile disabled and active subconnections in setupSubConnections ([85ebb54](https://github.com/postalsys/emailengine/commit/85ebb54bae8d4d7321a7362bb20e570a149fe892))
18
+ * refresh folder listing when a listed mailbox is missing on SELECT ([1e54d32](https://github.com/postalsys/emailengine/commit/1e54d32c1c74cb1f6d3d085a75d5b5ecc1cf5ff2))
19
+ * require an exact path match in the missing-mailbox verification LIST ([54e23c4](https://github.com/postalsys/emailengine/commit/54e23c4f6f13d3d834348df4bf15cf11206dc58b))
20
+ * reset IMAP reconnection backoff only after a successful sync ([7138dab](https://github.com/postalsys/emailengine/commit/7138dabab866483818440478d3584a46dfc8de12))
21
+ * reset subconnection backoff only after the monitored mailbox is opened ([f2bf297](https://github.com/postalsys/emailengine/commit/f2bf297883c38f4d1f61197ae75bdd7ae3976a53))
22
+ * resolve the mailbox sync promise when a concurrent operation already selected the mailbox ([7327dcc](https://github.com/postalsys/emailengine/commit/7327dcc9479a991881d3ddafdd0f36cc69e3411d))
23
+ * resolve the mailbox sync promise when opening fails before the sync starts ([c2268af](https://github.com/postalsys/emailengine/commit/c2268af90bea13d5b804c0a84945801cd9d74e45))
24
+ * retry transient account data load failures during reconnect ([7f18d4b](https://github.com/postalsys/emailengine/commit/7f18d4b16ccdfcfde77eb433530636b8657a354a))
25
+ * revive missing-folder subconnections when the folder is re-created ([254fce4](https://github.com/postalsys/emailengine/commit/254fce4f0eca59bc52ed4a8235f581b8107b97a7))
26
+ * scope the re-entrant open latch to the connection that emitted the event ([627b6ee](https://github.com/postalsys/emailengine/commit/627b6eeaf9ed493f6a4d81adcbe5b766eba54682))
27
+ * skip mailboxes that can not be selected during account sync ([eaf09c1](https://github.com/postalsys/emailengine/commit/eaf09c1700eca77e27fada20371bad193e0665c8))
28
+ * skip re-entrant mailbox open events while onOpen is already running ([6d06b09](https://github.com/postalsys/emailengine/commit/6d06b09c0c573a2f8ca554ba85c75d6b7be87002))
29
+ * stop opening IMAP connections for accounts paused while connecting ([128aef3](https://github.com/postalsys/emailengine/commit/128aef3cf2b7f1485a2e3d291436e88183255c0e))
30
+ * untrack bailed subconnection clients and harden the revival trigger ([086a585](https://github.com/postalsys/emailengine/commit/086a585541d3c6d751ebfbfc34f8f15397d51407))
31
+ * untrack the IMAP client when connect() bails for a paused account ([cface66](https://github.com/postalsys/emailengine/commit/cface665f16d7ad00f7b657e07f3c3f77c3401ef))
32
+ * update connection tracking when replacing a previous IMAP client ([8e143c2](https://github.com/postalsys/emailengine/commit/8e143c281d03d3d226e65eaae32eab96b1db0671))
33
+
34
+ ## [2.72.3](https://github.com/postalsys/emailengine/compare/v2.72.2...v2.72.3) (2026-07-06)
35
+
36
+
37
+ ### Bug Fixes
38
+
39
+ * bump imapflow to 1.4.4 (dedupe nodemailer/iconv-lite) ([5acc8cd](https://github.com/postalsys/emailengine/commit/5acc8cd99f9179fabb8d8486cf23b0558e4514bf))
40
+ * bump imapflow/mailparser/mailsplit/email-ai-tools (collapse iconv-lite) ([51dcffb](https://github.com/postalsys/emailengine/commit/51dcffb3ff0f22f9b9634d078e58b35aaf7a0312))
41
+ * bump libmime/mailparser/smtp-server/pubface (uniform nodemailer) ([eee89bb](https://github.com/postalsys/emailengine/commit/eee89bb716655519c72fb922849272c1058cbc9a))
42
+ * constant-time MS Graph clientState check and escape unsubscribe email ([3def225](https://github.com/postalsys/emailengine/commit/3def225ab1d598dec4f0b44443ff842295736039))
43
+ * escape Redis glob metacharacters in account-scoped SCAN patterns ([603d9db](https://github.com/postalsys/emailengine/commit/603d9dbce9c4e21b390e10dc7499f2cc5989c875))
44
+ * escape untrusted email fields in message browser to prevent stored XSS ([1159cc1](https://github.com/postalsys/emailengine/commit/1159cc193a98eb972454a5ae61ec01d7df77f06a))
45
+ * gate hosted auth form with a single-use nonce and probe cap, harden serviceSecret ([7ea4ff7](https://github.com/postalsys/emailengine/commit/7ea4ff7e6ca4d9239201f556b24ebd9cf8ab8250))
46
+ * harden hosted authentication form (SSRF gate, fail-closed HMAC, XSS) ([4267df7](https://github.com/postalsys/emailengine/commit/4267df7fd0252aa84ff1d257846126a8f943bf1a))
47
+ * HTML-escape json Handlebars helper to prevent stored XSS in error logs ([af2c153](https://github.com/postalsys/emailengine/commit/af2c153eb4d7de06b2730da6fdeb17bbe868472b))
48
+ * override grunt's transitive js-yaml to 3.15.0 (GHSA-h67p-54hq-rp68) ([024a923](https://github.com/postalsys/emailengine/commit/024a923de3ff2a880e79c7ddbf34bbc058fcbea3))
49
+ * stop logging the MS Graph access token on HTTP 401 ([f2f0300](https://github.com/postalsys/emailengine/commit/f2f03008cbcbaba8b7c2ff9c043ede7930c5c4ef))
50
+ * update dependencies (@postalsys/ee-client 1.3.2, nodemailer 9.0.3, bullmq 5.79.2, @sentry/node 10.63.0, [@bull-board](https://github.com/bull-board) 8.0.2) ([b954f67](https://github.com/postalsys/emailengine/commit/b954f67e1250d8a0029d355a5a8c6fc9d7f00e8e))
51
+ * update dependencies (email-text-tools 2.4.10, email-ai-tools 1.13.10) ([73df05c](https://github.com/postalsys/emailengine/commit/73df05c02db79fc47623ee41e27a315952c289b1))
52
+ * use constant-time comparison for secret and MAC checks ([453caf3](https://github.com/postalsys/emailengine/commit/453caf3ac01e58248a3a7019aa4ec3c2179b3abc))
53
+ * verify HMAC signature on the human-facing unsubscribe routes ([e30be83](https://github.com/postalsys/emailengine/commit/e30be836a71bc7e96baee19e5b019da5b0de40fa))
54
+
3
55
  ## [2.72.2](https://github.com/postalsys/emailengine/compare/v2.72.1...v2.72.2) (2026-06-26)
4
56
 
5
57
 
package/Gruntfile.js CHANGED
@@ -12,7 +12,10 @@ module.exports = function (grunt) {
12
12
  command: "npx eslint 'lib/**/*.js' 'workers/**/*.js' server.js Gruntfile.js"
13
13
  },
14
14
  server: {
15
- command: 'node server.js',
15
+ // Short Gmail fallback-poll interval so gmail-polling-test can exercise the poller
16
+ // quickly. Harmless for push-based Gmail accounts in api-test: notifications keep
17
+ // resetting the timer, and a stray fallback sync is coalesced/idempotent.
18
+ command: 'EENGINE_GMAIL_FALLBACK_POLL_INTERVAL=15000 node server.js',
16
19
  options: {
17
20
  async: true
18
21
  }
@@ -1,5 +1,5 @@
1
1
  {
2
- "creationTime": "2026-06-25T14:46:07.000000",
2
+ "creationTime": "2026-07-09T14:46:28.000000",
3
3
  "prefixes": [
4
4
  {
5
5
  "ipv6Prefix": "2001:4860:4801:2008::/64"
package/lib/account.js CHANGED
@@ -11,7 +11,8 @@ const {
11
11
  download,
12
12
  resolveCredentials,
13
13
  isEmail,
14
- resolveDelegatedAccount
14
+ resolveDelegatedAccount,
15
+ escapeRedisGlob
15
16
  } = require('./tools');
16
17
  const crypto = require('crypto');
17
18
  const { MessageChannel } = require('worker_threads');
@@ -1104,7 +1105,7 @@ class Account {
1104
1105
 
1105
1106
  // scan and delete keys
1106
1107
  // should we wait though? might take a lot of time
1107
- await redisScanDelete(this.redis, this.logger, `${REDIS_PREFIX}iam:${this.account}:*`);
1108
+ await redisScanDelete(this.redis, this.logger, `${REDIS_PREFIX}iam:${escapeRedisGlob(this.account)}:*`);
1108
1109
 
1109
1110
  if (!result || !result[0] || !result[0][1]) {
1110
1111
  return {
@@ -2469,7 +2470,7 @@ class Account {
2469
2470
  await pipeline.exec();
2470
2471
 
2471
2472
  // scan and delete keys
2472
- await redisScanDelete(this.redis, this.logger, `${REDIS_PREFIX}iam:${this.account}:*`);
2473
+ await redisScanDelete(this.redis, this.logger, `${REDIS_PREFIX}iam:${escapeRedisGlob(this.account)}:*`);
2473
2474
 
2474
2475
  if (await isDocumentStoreEnabled()) {
2475
2476
  // Flush ElasticSearch index for this account
@@ -24,10 +24,18 @@ const { httpAgent } = require('./tools');
24
24
 
25
25
  const RESOLV_TIMEOUT = 5 * 1000;
26
26
 
27
+ // Shorter cap for the app-password hint MX lookup: it runs on the hosted form's validation-error
28
+ // re-render and only produces a cosmetic label, so it must not stall the page for the full RESOLV_TIMEOUT.
29
+ const APP_PASSWORD_MX_TIMEOUT = 1500;
30
+
27
31
  // use a function instead of const to prevent translations before locale is set
32
+ // The canonical consumer domains are listed alongside the exchange regexes so a plain domain match
33
+ // (getAppPassword with exchange=false) resolves the big providers without any MX lookup - each listed
34
+ // domain's MX points at the same entry the regex would select, so autodetect results do not change.
28
35
  const getAppPasswords = gt => [
29
36
  {
30
37
  trigger: {
38
+ domains: ['gmail.com', 'googlemail.com'],
31
39
  exchange: /\bl\.google\.com$/i
32
40
  },
33
41
  value: {
@@ -39,6 +47,7 @@ const getAppPasswords = gt => [
39
47
 
40
48
  {
41
49
  trigger: {
50
+ domains: ['icloud.com', 'me.com', 'mac.com'],
42
51
  exchange: /\.icloud\.com$/i
43
52
  },
44
53
  value: {
@@ -73,6 +82,7 @@ const getAppPasswords = gt => [
73
82
 
74
83
  {
75
84
  trigger: {
85
+ domains: ['outlook.com', 'hotmail.com', 'live.com'],
76
86
  exchange: /\.outlook\.com$/i
77
87
  },
78
88
  value: {
@@ -87,6 +97,7 @@ const getAppPasswords = gt => [
87
97
 
88
98
  {
89
99
  trigger: {
100
+ domains: ['t-online.de'],
90
101
  exchange: /\.t-online\.de$/i
91
102
  },
92
103
  value: {
@@ -111,6 +122,53 @@ function getAppPassword(email, exchange, gt) {
111
122
  return false;
112
123
  }
113
124
 
125
+ // Resolve the lowest-priority MX exchange for a domain (lowercased). Throws if the domain has no MX
126
+ // record (callers decide whether that is fatal or just "no exchange-based match").
127
+ async function resolveExchange(domain) {
128
+ let srvList = await dns.resolveMx(domain);
129
+ if (!srvList || !srvList.length) {
130
+ throw new Error('No MX record found for domain');
131
+ }
132
+
133
+ const firstItem = srvList.sort((a, b) => a.priority - b.priority).shift();
134
+ return firstItem && firstItem.exchange ? firstItem.exchange.trim().toLowerCase() : undefined;
135
+ }
136
+
137
+ // Resolve only the app-password hint for an email address - a domain match plus, for exchange-based
138
+ // providers (Gmail, iCloud, Outlook, ...), a single MX lookup. Much cheaper than autodetectImapSettings
139
+ // (one DNS query, no HTTP). The hosted form's failAction re-render uses this to restore the
140
+ // app-password label/instructions server-side rather than trusting the submitted (client-controlled)
141
+ // hidden fields, which feed unescaped template sinks. Returns the trusted hint object or false; the
142
+ // returned values are static table constants, so they are safe to render. Never throws.
143
+ async function resolveAppPassword(email, gt) {
144
+ if (!email || typeof email !== 'string' || email.indexOf('@') < 0) {
145
+ return false;
146
+ }
147
+
148
+ // Fast path: a domain-only match (e.g. aol.com) needs no network.
149
+ let hint = getAppPassword(email, false, gt);
150
+ if (hint) {
151
+ return hint;
152
+ }
153
+
154
+ let domain = email.split('@').pop().trim().toLowerCase();
155
+ try {
156
+ domain = punycode.toASCII(domain);
157
+ } catch (err) {
158
+ // ignore - use the raw domain
159
+ }
160
+
161
+ let exchange;
162
+ try {
163
+ exchange = await timedFunction(resolveExchange(domain), APP_PASSWORD_MX_TIMEOUT, 'mx');
164
+ } catch (err) {
165
+ // No MX record / lookup failed / timed out - no exchange-based hint to add.
166
+ return false;
167
+ }
168
+
169
+ return getAppPassword(email, exchange, gt);
170
+ }
171
+
114
172
  async function processAutoconfigFile(email, domain, text, source) {
115
173
  domain = domain || email.split('@').pop().trim().toLowerCase();
116
174
  let user = email.split('@').shift().trim();
@@ -335,17 +393,7 @@ async function resolveUsingMX(email, domain, gt) {
335
393
  }
336
394
 
337
395
  // do not catch potential error as there's nothing to do if we do not find the MX record
338
- let srvList = await dns.resolveMx(domain);
339
- if (!srvList || !srvList.length) {
340
- throw new Error('No MX record found for domain');
341
- }
342
-
343
- let exchange;
344
- const firstItem = srvList.sort((a, b) => a.priority - b.priority).shift();
345
-
346
- if (firstItem && firstItem.exchange) {
347
- exchange = firstItem.exchange.trim().toLowerCase();
348
- }
396
+ let exchange = await resolveExchange(domain);
349
397
 
350
398
  let resolveConfig = async () => {
351
399
  // look for some well known MX servers
@@ -782,4 +830,5 @@ module.exports.autodetectImapSettings = autodetectImapSettings;
782
830
  // network side effects, so they can be exercised directly without mocking DNS or HTTP.
783
831
  module.exports.processAutoconfigFile = processAutoconfigFile;
784
832
  module.exports.getAppPassword = getAppPassword;
833
+ module.exports.resolveAppPassword = resolveAppPassword;
785
834
  module.exports.escapeXml = escapeXml;
package/lib/consts.js CHANGED
@@ -184,6 +184,13 @@ module.exports = {
184
184
  // how long is an authentication form valid
185
185
  MAX_FORM_TTL: 1 * 24 * 3600 * 1000,
186
186
 
187
+ // Max number of outbound-probe requests (email autodiscovery + "Verify connection" tests) allowed per
188
+ // issued form blob. These hosted-form endpoints authorize the caller by signature but do not consume
189
+ // the single-use nonce (a form autodetects/tests several times before submitting), so this shared cap
190
+ // bounds a leaked signed link from being replayed as an unlimited outbound-probe / SSRF oracle.
191
+ // Generous enough not to impede real use.
192
+ MAX_FORM_PROBE_ATTEMPTS: 50,
193
+
187
194
  NONCE_BYTES: 16,
188
195
 
189
196
  // We are using a legacy hash function in caching operations
@@ -72,7 +72,10 @@ function toGmailLabelId(label) {
72
72
  // Timing constants for Gmail Pub/Sub watch
73
73
  const RENEW_WATCH_TTL = 60 * 60 * 1000; // 1h - how often to check if watch needs renewal
74
74
  const MIN_WATCH_TTL = 24 * 3600 * 1000; // 1day - minimum time before renewing watch
75
- const FALLBACK_POLLING_INTERVAL = 10 * 60 * 1000; // 10min - fallback polling if no Pub/Sub notifications
75
+ // 10min default - fallback polling if no Pub/Sub notifications. Overridable via
76
+ // EENGINE_GMAIL_FALLBACK_POLL_INTERVAL (ms) so integration tests can exercise the poller
77
+ // without waiting the full interval.
78
+ const FALLBACK_POLLING_INTERVAL = Number((process.env.EENGINE_GMAIL_FALLBACK_POLL_INTERVAL || '').toString().trim()) || 10 * 60 * 1000;
76
79
 
77
80
  /*
78
81
  Gmail API implementation status:
@@ -82,6 +82,8 @@ class Mailbox {
82
82
 
83
83
  this.synced = false; // Whether initial sync is complete
84
84
  this.syncing = false; // Whether currently syncing
85
+ this.processingOpen = false; // Whether onOpen() is currently running for this mailbox
86
+ this.processingOpenClient = null; // The IMAP client whose open event holds the processingOpen latch
85
87
 
86
88
  // Sync operations handler
87
89
  this.syncOps = new SyncOperations(this);
@@ -442,8 +444,10 @@ class Mailbox {
442
444
  });
443
445
  } catch (err) {
444
446
  if (err.code === 'NotFound') {
445
- // folder is missing, refresh folder listing
446
- await this.connection.getCurrentListing();
447
+ // Folder is missing, refresh the folder listing and process the
448
+ // result so deletions get cleared and newly found folders are
449
+ // registered and synced (emitting their mailboxNew notification)
450
+ await this.connection.refreshAndProcessListing();
447
451
  return;
448
452
  } else {
449
453
  throw err;
@@ -488,13 +492,55 @@ class Mailbox {
488
492
  }
489
493
  }
490
494
 
495
+ // Re-check after the awaits above: a concurrent operation may have
496
+ // selected this mailbox while we were reading STATUS / stored state.
497
+ // In that case onOpen() owns the sync work, and select(true) below
498
+ // would skip the SELECT without another mailboxOpen event ever firing
499
+ if (this.selected || !this.connection.imapClient) {
500
+ // expect current folder to be already synced
501
+ return false;
502
+ }
503
+
491
504
  // Need to sync - create promise that resolves when sync is complete
492
505
  let syncedPromise = new Promise((resolve, reject) => {
493
506
  this.synced = resolve;
494
507
  this.select(true).catch(err => reject(err));
495
508
  });
496
509
 
497
- await syncedPromise;
510
+ try {
511
+ await syncedPromise;
512
+ } catch (err) {
513
+ if (err.mailboxMissing) {
514
+ // The folder was deleted after it was listed (e.g. by another client
515
+ // between LIST and SELECT). Refresh the listing right away so the
516
+ // deletion gets processed instead of waiting for the next resync cycle,
517
+ // and process the result so folders that appeared in the same change
518
+ // (e.g. a rename) are registered and emit their mailboxNew notification.
519
+ // A failing refresh is a connection-level error and propagates, same
520
+ // as in the NotFound branch above.
521
+ this.logger.info({ msg: 'Mailbox is missing, refreshing folder listing', path: this.path });
522
+ this.synced = false;
523
+ await this.connection.refreshAndProcessListing();
524
+ return;
525
+ }
526
+ if (err.responseStatus === 'NO') {
527
+ // The folder is listed but can not be selected. Either a permanent
528
+ // phantom folder (e.g. a shared namespace root that the server lists
529
+ // without \Noselect) or a transient RFC 5530 condition like INUSE -
530
+ // both are skipped and retried on the next resync cycle instead of
531
+ // failing the entire account sync. Network-level errors do not have
532
+ // responseStatus set and keep propagating.
533
+ this.logger.warn({
534
+ msg: 'Skipped mailbox that can not be selected',
535
+ path: this.path,
536
+ serverResponseCode: err.serverResponseCode,
537
+ responseText: err.responseText
538
+ });
539
+ this.synced = false;
540
+ return;
541
+ }
542
+ throw err;
543
+ }
498
544
  }
499
545
 
500
546
  /**
@@ -521,6 +567,14 @@ class Mailbox {
521
567
  ...(currentLock.options?.description && { description: currentLock.options?.description })
522
568
  }
523
569
  });
570
+ if (this.synced) {
571
+ // Locks are only granted after the mailbox is open, so no
572
+ // further mailboxOpen event is coming for this path. Settle
573
+ // the resolver armed by sync() instead of leaving it waiting
574
+ // forever. If the open's onOpen() is still running, its own
575
+ // resolve call later is a no-op on the settled promise
576
+ this.synced();
577
+ }
524
578
  return;
525
579
  }
526
580
  // Different mailbox is locked - queue this select to run after lock is released
@@ -543,6 +597,12 @@ class Mailbox {
543
597
  msg: 'Mailbox already selected after lock acquired',
544
598
  path: this.path
545
599
  });
600
+ if (this.synced) {
601
+ // The lock was granted against the already-open mailbox without
602
+ // a new SELECT, so no mailboxOpen event fires - settle the
603
+ // resolver armed by sync() instead of leaving it waiting forever
604
+ this.synced();
605
+ }
546
606
  lock.release();
547
607
  return;
548
608
  }
@@ -2064,16 +2124,48 @@ class Mailbox {
2064
2124
  * Called when mailbox is opened/selected
2065
2125
  * Determines what type of sync is needed based on current state
2066
2126
  */
2067
- async onOpen() {
2127
+ async onOpen(event, openedClient) {
2068
2128
  clearTimeout(this.runPartialSyncTimer);
2069
2129
  this.selected = true;
2070
2130
 
2071
- // Track connection count to detect reconnects
2072
- this.previouslyConnected = Number(await this.connection.redis.hget(this.connection.getAccountKey(), `state:count:connected`)) || 0;
2131
+ // The latch is scoped to the connection that emitted the open event.
2132
+ // A re-entrant event from the SAME connection must bail out, but an
2133
+ // event from a NEW connection must not be swallowed while a previous
2134
+ // connection's handler is still unwinding (its Redis-heavy phases keep
2135
+ // running after the socket died) - settling the fresh resolver here
2136
+ // would mark the post-reconnect sync as done without any sync work
2137
+ openedClient = openedClient || this.connection.imapClient;
2138
+
2139
+ if (this.processingOpen && this.processingOpenClient === openedClient) {
2140
+ // Re-entrant open event: a sync operation running inside this very
2141
+ // handler (e.g. seedMailboxIndex acquiring its mailbox lock)
2142
+ // re-SELECTed this mailbox. Running the state machine again from
2143
+ // here recurses - on a server where the seeding FETCH keeps
2144
+ // failing it becomes an endless reseed storm of back-to-back
2145
+ // SELECTs. The outer invocation owns the sync work; settle an
2146
+ // armed sync() resolver and bail out
2147
+ if (this.synced) {
2148
+ this.synced();
2149
+ }
2150
+ return false;
2151
+ }
2152
+ // Take the latch (over) - if a previous connection's handler is still
2153
+ // unwinding, it detects the new owner in its finally and backs off
2154
+ this.processingOpen = true;
2155
+ this.processingOpenClient = openedClient;
2073
2156
 
2074
- let mailboxStatus = this.getMailboxStatus();
2157
+ // Assigned inside the try - everything that can throw must run there,
2158
+ // because the finally below is the sole resolver of the sync() promise
2159
+ // (this.synced). A throw before the try would skip the finally and
2160
+ // permanently wedge the awaiting sync()
2161
+ let mailboxStatus;
2075
2162
 
2076
2163
  try {
2164
+ // Track connection count to detect reconnects
2165
+ this.previouslyConnected = Number(await this.connection.redis.hget(this.connection.getAccountKey(), `state:count:connected`)) || 0;
2166
+
2167
+ mailboxStatus = this.getMailboxStatus();
2168
+
2077
2169
  let storedStatus = await this.getStoredStatus();
2078
2170
 
2079
2171
  // Lost-index recovery: the account has synced in a previous session but this folder
@@ -2159,36 +2251,51 @@ class Mailbox {
2159
2251
  if (err.mailboxMissing) {
2160
2252
  // this mailbox is missing, refresh listing
2161
2253
  try {
2162
- await this.connection.getCurrentListing();
2254
+ await this.connection.refreshAndProcessListing();
2163
2255
  } catch (E) {
2164
2256
  this.logger.error({ msg: 'Missing mailbox', err, E });
2165
2257
  }
2166
2258
  }
2167
2259
  throw err;
2168
2260
  } finally {
2169
- // Send new mailbox notification if this is the first sync
2170
- if (this.listingEntry.isNew) {
2171
- // fully synced, so not new anymore
2172
- this.listingEntry.isNew = false;
2173
- this.logger.debug({ msg: 'New mailbox', path: this.listingEntry.path });
2174
- this.connection
2175
- .notify(this, MAILBOX_NEW_NOTIFY, {
2176
- path: this.listingEntry.path,
2177
- name: this.listingEntry.name,
2178
- specialUse: this.listingEntry.specialUse || false,
2179
- uidValidity: mailboxStatus.uidValidity.toString()
2180
- })
2181
- .catch(err => this.logger.error({ msg: 'Failed to send new mailbox notification', err }));
2182
- }
2183
-
2184
- // Resolve sync promise or start IDLE
2185
- if (this.synced) {
2186
- this.synced();
2261
+ if (this.processingOpenClient !== openedClient) {
2262
+ // A newer connection's open handler took the latch over while
2263
+ // this invocation was unwinding. The new owner runs the actual
2264
+ // sync now, so leave the latch, the isNew notification and the
2265
+ // sync promise settlement to it - settling here would resolve
2266
+ // the new owner's freshly armed promise before its work ran
2267
+ this.logger.debug({ msg: 'Mailbox open handler superseded by a newer connection', path: this.path });
2187
2268
  } else {
2188
- try {
2189
- await this.select();
2190
- } catch (err) {
2191
- this.logger.warn({ msg: 'Failed to select after sync', err });
2269
+ this.processingOpen = false;
2270
+ this.processingOpenClient = null;
2271
+
2272
+ // Send new mailbox notification if this is the first sync. When the
2273
+ // open failed before the mailbox state could be read, mailboxStatus
2274
+ // is undefined - keep isNew set so the notification is emitted on
2275
+ // the next successful open instead of sending a broken payload now
2276
+ if (this.listingEntry.isNew && mailboxStatus) {
2277
+ // fully synced, so not new anymore
2278
+ this.listingEntry.isNew = false;
2279
+ this.logger.debug({ msg: 'New mailbox', path: this.listingEntry.path });
2280
+ this.connection
2281
+ .notify(this, MAILBOX_NEW_NOTIFY, {
2282
+ path: this.listingEntry.path,
2283
+ name: this.listingEntry.name,
2284
+ specialUse: this.listingEntry.specialUse || false,
2285
+ uidValidity: mailboxStatus.uidValidity.toString()
2286
+ })
2287
+ .catch(err => this.logger.error({ msg: 'Failed to send new mailbox notification', err }));
2288
+ }
2289
+
2290
+ // Resolve sync promise or start IDLE
2291
+ if (this.synced) {
2292
+ this.synced();
2293
+ } else {
2294
+ try {
2295
+ await this.select();
2296
+ } catch (err) {
2297
+ this.logger.warn({ msg: 'Failed to select after sync', err });
2298
+ }
2192
2299
  }
2193
2300
  }
2194
2301
  }