emailengine-app 2.84.2 → 2.86.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (164) hide show
  1. package/.ncurc.js +29 -9
  2. package/.prettierignore +5 -1
  3. package/.prettierrc.js +2 -0
  4. package/.release-please-manifest.json +1 -1
  5. package/CHANGELOG.md +107 -0
  6. package/Dockerfile +20 -1
  7. package/ENVIRONMENT.md +139 -0
  8. package/README.md +2 -2
  9. package/bin/emailengine.js +434 -408
  10. package/config/default.toml +2 -0
  11. package/copy-static-files.sh +41 -14
  12. package/data/google-crawlers.json +1 -1
  13. package/data/public_suffix_list.dat +16563 -0
  14. package/eslint.config.js +81 -99
  15. package/lib/account-assignment.js +19 -0
  16. package/lib/account.js +230 -170
  17. package/lib/api-error-codes.js +49 -0
  18. package/lib/api-reference/format.js +4 -3
  19. package/lib/api-reference/model.js +6 -1
  20. package/lib/api-routes/account-routes.js +255 -38
  21. package/lib/api-routes/blocklist-routes.js +91 -4
  22. package/lib/api-routes/delivery-test-routes.js +27 -4
  23. package/lib/api-routes/export-routes.js +28 -2
  24. package/lib/api-routes/gateway-routes.js +110 -12
  25. package/lib/api-routes/index.js +4 -0
  26. package/lib/api-routes/license-routes.js +2 -2
  27. package/lib/api-routes/mailbox-routes.js +44 -5
  28. package/lib/api-routes/message-routes.js +112 -10
  29. package/lib/api-routes/oauth2-app-routes.js +63 -23
  30. package/lib/api-routes/outbox-routes.js +97 -52
  31. package/lib/api-routes/permission-map.js +67 -7
  32. package/lib/api-routes/scoped-routes.js +74 -0
  33. package/lib/api-routes/settings-routes.js +34 -6
  34. package/lib/api-routes/stats-routes.js +5 -1
  35. package/lib/api-routes/submit-routes.js +337 -309
  36. package/lib/api-routes/template-routes.js +45 -8
  37. package/lib/api-routes/token-routes.js +152 -100
  38. package/lib/api-routes/webhook-delivery-routes.js +262 -0
  39. package/lib/api-routes/webhook-route-routes.js +132 -6
  40. package/lib/bounce-detect.js +397 -205
  41. package/lib/calendar-event.js +81 -1
  42. package/lib/consts.js +38 -45
  43. package/lib/db.js +14 -6
  44. package/lib/delivery-error.js +6 -0
  45. package/lib/deprecations.js +270 -0
  46. package/lib/email-client/base-client.js +137 -184
  47. package/lib/email-client/fallback-poll.js +62 -0
  48. package/lib/email-client/gmail-client.js +60 -22
  49. package/lib/email-client/imap/adaptive-idle-store.js +73 -0
  50. package/lib/email-client/imap/adaptive-idle.js +278 -0
  51. package/lib/email-client/imap/connection-errors.js +14 -1
  52. package/lib/email-client/imap/idle-settings.js +31 -5
  53. package/lib/email-client/imap/listing-diff.js +37 -0
  54. package/lib/email-client/imap/mailbox.js +372 -242
  55. package/lib/email-client/imap/subconnection.js +8 -30
  56. package/lib/email-client/imap/sync-operations.js +220 -127
  57. package/lib/email-client/imap-client.js +228 -164
  58. package/lib/email-client/message-builder.js +14 -79
  59. package/lib/email-client/notification-handler.js +1 -2
  60. package/lib/email-client/outlook-client.js +372 -338
  61. package/lib/email-client/smtp-pool-manager.js +16 -13
  62. package/lib/email-client/sync-state-fields.js +19 -0
  63. package/lib/encrypt.js +157 -41
  64. package/lib/enum-descriptions.js +3 -1
  65. package/lib/env-setting-overrides.js +288 -0
  66. package/lib/export-worker.js +751 -0
  67. package/lib/export.js +64 -15
  68. package/lib/gateway.js +19 -4
  69. package/lib/get-raw-email.js +25 -107
  70. package/lib/hapi-request-logger.js +107 -0
  71. package/lib/health.js +75 -0
  72. package/lib/imapproxy/imap-core/README.md +6 -5
  73. package/lib/lock-run.js +119 -0
  74. package/lib/logger-consts.js +48 -0
  75. package/lib/logger.js +1 -1
  76. package/lib/lua/z-head-scores.lua +28 -0
  77. package/lib/mcp/tools.js +37 -8
  78. package/lib/network-errors.js +1 -1
  79. package/lib/node-version.js +24 -0
  80. package/lib/notify-attachments.js +36 -0
  81. package/lib/oauth/outlook-mailbox.js +35 -0
  82. package/lib/oauth/state.js +24 -0
  83. package/lib/oauth2-apps.js +631 -656
  84. package/lib/outbox.js +184 -54
  85. package/lib/parse-message.js +3 -3
  86. package/lib/pbkdf2-phc.js +1 -1
  87. package/lib/privileged-settings.js +2 -2
  88. package/lib/queue-browser/definitions.js +11 -0
  89. package/lib/queue-browser/index.js +68 -19
  90. package/lib/queue-job-actions.js +18 -1
  91. package/lib/queue-retention.js +48 -12
  92. package/lib/queue-stats.js +11 -2
  93. package/lib/read-env-value.js +3 -0
  94. package/lib/redis-memory-warnings.js +99 -0
  95. package/lib/redis-reconnect.js +29 -0
  96. package/lib/request-timing.js +23 -0
  97. package/lib/respawn-backoff.js +35 -0
  98. package/lib/rewrite-text-nodes.js +19 -59
  99. package/lib/schemas.js +164 -40
  100. package/lib/settings.js +6 -2
  101. package/lib/smtp-auth.js +19 -1
  102. package/lib/sso.js +1 -1
  103. package/lib/swagger-options.js +1 -1
  104. package/lib/thread-diagnostics.js +63 -0
  105. package/lib/timezones.js +109 -0
  106. package/lib/tls/provision.js +6 -3
  107. package/lib/token-audit-log.js +19 -20
  108. package/lib/token-permission-view.js +7 -6
  109. package/lib/tools.js +48 -51
  110. package/lib/totp.js +2 -5
  111. package/lib/translations.js +1 -2
  112. package/lib/ui-routes/account-routes.js +475 -454
  113. package/lib/ui-routes/account-setup.js +99 -0
  114. package/lib/ui-routes/admin-config-routes.js +152 -100
  115. package/lib/ui-routes/admin-entities-routes.js +93 -21
  116. package/lib/ui-routes/auth-routes.js +90 -38
  117. package/lib/ui-routes/imap-idle-field.js +1 -1
  118. package/lib/ui-routes/internals-routes.js +5 -0
  119. package/lib/ui-routes/oauth-config-routes.js +124 -82
  120. package/lib/ui-routes/outlook-subscription-view.js +1 -1
  121. package/lib/ui-routes/overridable-fields.js +84 -0
  122. package/lib/ui-routes/queue-routes.js +8 -5
  123. package/lib/ui-routes/route-helpers.js +19 -3
  124. package/lib/ui-routes/settings-page.js +6 -0
  125. package/lib/ui-routes/tls-config-routes.js +58 -15
  126. package/lib/utils/back-off.js +82 -0
  127. package/lib/utils/decode-headers.js +3 -12
  128. package/lib/utils/filter-empty.js +20 -0
  129. package/lib/utils/int-setting.js +48 -0
  130. package/lib/utils/murmurhash3.js +66 -0
  131. package/lib/utils/public-suffix.js +122 -0
  132. package/lib/utils/random-id.js +26 -0
  133. package/lib/utils/tracking-settings.js +35 -0
  134. package/lib/utils/version.js +74 -0
  135. package/lib/web-safe-html.js +18 -105
  136. package/lib/webhook-delivery.js +461 -0
  137. package/lib/webhook-failures.js +132 -0
  138. package/lib/webhook-request.js +29 -1
  139. package/lib/webhook-routing.js +56 -0
  140. package/lib/webhook-test.js +88 -0
  141. package/lib/webhooks.js +93 -45
  142. package/lib/worker-rpc-error.js +2 -1
  143. package/package.json +37 -38
  144. package/sbom.json +7902 -1
  145. package/server.js +784 -518
  146. package/static/js/ace/ace.js +1 -1
  147. package/static/licenses.html +225 -1060
  148. package/translations/messages.pot +62 -63
  149. package/views/config/ai.hbs +1 -1
  150. package/views/config/security.hbs +24 -2
  151. package/views/config/service.hbs +47 -0
  152. package/views/config/webhooks.hbs +36 -0
  153. package/views/internals/index.hbs +8 -0
  154. package/views/partials/queue_retention_note.hbs +12 -8
  155. package/views/partials/ui/env-managed-alert.hbs +16 -7
  156. package/views/partials/webhook_form.hbs +1 -1
  157. package/views/suppression-lists/index.hbs +1 -1
  158. package/workers/api.js +840 -611
  159. package/workers/export.js +17 -632
  160. package/workers/imap.js +13 -0
  161. package/workers/smtp.js +9 -11
  162. package/workers/submit.js +1 -1
  163. package/workers/webhooks.js +18 -448
  164. package/lib/email-client/outlook-fallback-poll.js +0 -30
@@ -5,7 +5,7 @@ const { createImapClient } = require('../create-imap-client');
5
5
  const { Mailbox } = require('./imap/mailbox');
6
6
  const logger = require('../logger');
7
7
  const packageData = require('../../package.json');
8
- const { backOff } = require('exponential-backoff');
8
+ const { backOff } = require('../utils/back-off');
9
9
  const msgpack = require('../msgpack');
10
10
 
11
11
  const { oauth2ProviderData } = require('../oauth2-apps');
@@ -14,14 +14,26 @@ const { oauth2Apps } = require('../oauth2-apps');
14
14
 
15
15
  const { Subconnection } = require('./imap/subconnection');
16
16
  const { imapResponseLabels } = require('./imap/response-metrics');
17
- const { decodeStoredListing, diffMailboxListing, buildStoredListingObject, matchesListingEntry, configuredPathIndex } = require('./imap/listing-diff');
17
+ const {
18
+ decodeStoredListing,
19
+ diffMailboxListing,
20
+ buildStoredListingObject,
21
+ matchesListingEntry,
22
+ accountPathList,
23
+ folderMonitoring
24
+ } = require('./imap/listing-diff');
18
25
  const { samePath } = require('../utils/mailbox-path');
19
26
  const { detachImapClient } = require('./imap/detach-client');
20
27
  const { connectionNotAvailableError, connectionUnavailableError } = require('./imap/connection-errors');
21
28
  const { ReconnectBackoff } = require('./reconnect-backoff');
22
29
  const { isRefusedImapLogin, imapResponseText } = require('./imap/login-failure');
23
30
  const { knownUidNext, planStaleViewProbe, evaluateStaleViewProbe } = require('./imap/stale-view');
24
- const { applyIdleSettings } = require('./imap/idle-settings');
31
+ const { applyIdleSettings, commandSocketTimeout } = require('./imap/idle-settings');
32
+ const { learnedInterval, recordClose } = require('./imap/adaptive-idle-store');
33
+
34
+ // How long a learned IDLE interval read for one connection is reused for the account's others
35
+ const LEARNED_IDLE_CACHE_TTL = 60 * 1000;
36
+ const { runLocked, rethrowUnavailableLock } = require('../lock-run');
25
37
 
26
38
  const {
27
39
  normalizePath,
@@ -201,6 +213,59 @@ class IMAPClient extends BaseClient {
201
213
  this.closeReconnectBackoff = new ReconnectBackoff({ baseDelay: 2000, maxDelay: 30000, jitter: 1000 });
202
214
  }
203
215
 
216
+ /**
217
+ * The IDLE interval learned for the server, read once for the burst of connections an account
218
+ * opens together (primary, subconnections, command connection) rather than once each
219
+ * @param {string} host - IMAP server host
220
+ * @returns {Promise<number|null>}
221
+ */
222
+ async getLearnedIdleInterval(host) {
223
+ const cached = this.learnedIdleCache;
224
+ if (cached && cached.host === host && Date.now() - cached.time < LEARNED_IDLE_CACHE_TTL) {
225
+ return cached.interval;
226
+ }
227
+ let interval = null;
228
+ try {
229
+ interval = await learnedInterval(this.redis, host);
230
+ } catch (err) {
231
+ this.logger.debug({ msg: 'Failed to read the learned IDLE interval', host, err });
232
+ }
233
+ this.learnedIdleCache = { host, interval, time: Date.now() };
234
+ return interval;
235
+ }
236
+
237
+ /**
238
+ * Records what an unexpected close of the primary connection says about the server's idle
239
+ * timer, see lib/email-client/imap/adaptive-idle.js. Best effort: learning is never a reason for
240
+ * the close handling to fail
241
+ * @param {Object} imapClient - The closed connection
242
+ * @param {number} [closedAt] - When it closed, epoch ms
243
+ */
244
+ async recordIdleClose(imapClient, closedAt = Date.now()) {
245
+ try {
246
+ const host = imapClient.options?.host || this.imapConfig?.host;
247
+ const recorded = await recordClose(this.redis, host, imapClient, closedAt);
248
+ if (recorded && recorded.before !== recorded.after) {
249
+ // this account's next connection uses what it just recorded, not a cached read
250
+ this.learnedIdleCache = { host, interval: recorded.after, time: Date.now() };
251
+ this.logger.info({
252
+ msg: !recorded.after
253
+ ? 'Dropped the learned IDLE restart interval for the server'
254
+ : recorded.before && recorded.after > recorded.before
255
+ ? 'Relaxed the learned IDLE restart interval for the server'
256
+ : 'Learned an IDLE restart interval for the server',
257
+ host,
258
+ account: this.account,
259
+ interval: recorded.after,
260
+ previous: recorded.before,
261
+ observation: recorded.observation
262
+ });
263
+ }
264
+ } catch (err) {
265
+ this.logger.debug({ msg: 'Failed to record the IDLE close', account: this.account, err });
266
+ }
267
+ }
268
+
204
269
  /**
205
270
  * Checks whether a dropped connection had proven itself stable by
206
271
  * surviving STABLE_CONNECTION_TIME, resetting the survival-gated close
@@ -213,7 +278,7 @@ class IMAPClient extends BaseClient {
213
278
  * @returns {Boolean} True when the connection had proven itself stable
214
279
  */
215
280
  validateConnectionAge(imapClient) {
216
- if (Date.now() - imapClient.connectionStartTime >= STABLE_CONNECTION_TIME) {
281
+ if (Date.now() - imapClient.context?.startedAt >= STABLE_CONNECTION_TIME) {
217
282
  this.closeReconnectBackoff.reset();
218
283
  return true;
219
284
  }
@@ -350,120 +415,109 @@ class IMAPClient extends BaseClient {
350
415
  }
351
416
 
352
417
  // Acquire a lock to prevent multiple simultaneous connection attempts
353
- let lock = this.accountObject.getLock();
354
-
355
- let connectLock;
356
418
  let lockKey = ['commandClient', this.account].join(':');
357
419
 
358
- try {
359
- this.logger.debug({ msg: 'Acquiring connection lock', lockKey });
360
- connectLock = await lock.waitAcquireLock(lockKey, 5 * 60 * 1000, 1 * 60 * 1000);
361
- if (!connectLock.success) {
362
- throw new Error('Failed to get connection lock');
363
- }
364
- this.logger.debug({ msg: 'Acquired connection lock', lockKey, index: connectLock.index });
365
- } catch (err) {
366
- this.logger.error({ msg: 'Failed to get lock', lockKey, err });
367
- throw err;
368
- }
420
+ return await runLocked(
421
+ this.accountObject.getLock(),
422
+ lockKey,
423
+ { ttl: 5 * 60 * 1000, wait: 1 * 60 * 1000 },
424
+ () => this.createCommandConnection(reason),
425
+ rethrowUnavailableLock(this.logger, 'Failed to get connection lock', { lockKey })
426
+ );
427
+ }
369
428
 
370
- try {
371
- // create a new connection for the command channel
372
- let accountData = await this.accountObject.loadAccountData();
429
+ /**
430
+ * The part of getCommandConnection() that runs under the connection lock: opens the command
431
+ * connection unless one was created while waiting for the lock
432
+ * @param {string} reason - Why the connection is needed
433
+ * @returns {Promise<Object|null>} The command connection, null when IMAP is not usable
434
+ */
435
+ async createCommandConnection(reason) {
436
+ // create a new connection for the command channel
437
+ let accountData = await this.accountObject.loadAccountData();
373
438
 
374
- // Check if IMAP is configured and enabled
375
- if ((!accountData.imap && !accountData.oauth2) || (accountData.imap && accountData.imap.disabled)) {
376
- return null;
377
- }
439
+ // Check if IMAP is configured and enabled
440
+ if ((!accountData.imap && !accountData.oauth2) || (accountData.imap && accountData.imap.disabled)) {
441
+ return null;
442
+ }
378
443
 
379
- // Check again if command client was created while waiting for lock
380
- if (this.commandClient && this.commandClient.usable) {
381
- // use existing command channel created during the lock
382
- return this.commandClient;
383
- }
444
+ // Check again if command client was created while waiting for lock
445
+ if (this.commandClient && this.commandClient.usable) {
446
+ // use existing command channel created during the lock
447
+ return this.commandClient;
448
+ }
384
449
 
385
- // Generate unique connection ID for tracking
386
- const commandCid = `${this.cid}:c:${this.connectionCount++}`;
450
+ // Generate unique connection ID for tracking
451
+ const commandCid = `${this.cid}:c:${this.connectionCount++}`;
387
452
 
388
- let imapConfig = await this.getImapConfig(accountData);
453
+ let imapConfig = await this.getImapConfig(accountData);
389
454
 
390
- // Create new IMAP connection with specific settings for command operations
391
- let commandClient = createImapClient(
392
- Object.assign({}, imapConfig, {
393
- disableAutoIdle: true, // Don't automatically IDLE on this connection
394
- id: commandCid,
395
- socketTimeout: 60 * 1000, // 60 second timeout for command operations
396
- logger: this.logger.child({
397
- cid: commandCid,
398
- channel: 'command'
399
- })
455
+ // Create new IMAP connection with specific settings for command operations
456
+ let commandClient = createImapClient(
457
+ Object.assign({}, imapConfig, {
458
+ disableAutoIdle: true, // Don't automatically IDLE on this connection
459
+ id: commandCid,
460
+ socketTimeout: commandSocketTimeout(imapConfig.maxIdleTime),
461
+ logger: this.logger.child({
462
+ cid: commandCid,
463
+ channel: 'command'
400
464
  })
401
- );
402
- this.connections.add(commandClient);
403
- await this.redis.hSetExists(this.getAccountKey(), 'connections', this.connections.size.toString());
465
+ })
466
+ );
467
+ this.connections.add(commandClient);
468
+ await this.redis.hSetExists(this.getAccountKey(), 'connections', this.connections.size.toString());
404
469
 
405
- commandClient.log.debug({ msg: 'Created command client', reason });
470
+ commandClient.log.debug({ msg: 'Created command client', reason });
406
471
 
407
- this.commandClient = commandClient;
472
+ this.commandClient = commandClient;
408
473
 
409
- // Mark this as a secondary connection for identification
410
- commandClient.secondaryConnection = true;
474
+ // Set up error handling for the command connection
475
+ const onErr = err => {
476
+ // Idle timeout (ETIMEOUT) is expected - the command client has no keepalive
477
+ const logLevel = err.code === 'ETIMEOUT' ? 'debug' : 'warn';
478
+ if (!commandClient) {
479
+ // the close handler already let go of this client
480
+ return;
481
+ }
482
+ commandClient.log[logLevel]({ msg: 'IMAP connection error', cid: commandCid, channel: 'command', account: this.account, err });
483
+ commandClient.close();
484
+ // A late event from a replaced client must not drop the reference to its successor,
485
+ // which would then stay open until its own socket timeout
486
+ if (this.commandClient === commandClient) {
487
+ this.commandClient = null;
488
+ }
489
+ };
490
+ commandClient.on('error', onErr);
411
491
 
412
- // Set up error handling for the command connection
413
- const onErr = err => {
414
- // Idle timeout (ETIMEOUT) is expected - the command client has no keepalive
415
- const logLevel = err.code === 'ETIMEOUT' ? 'debug' : 'warn';
416
- if (!commandClient) {
417
- // the close handler already let go of this client
418
- return;
419
- }
420
- commandClient.log[logLevel]({ msg: 'IMAP connection error', cid: commandCid, channel: 'command', account: this.account, err });
421
- commandClient.close();
422
- // A late event from a replaced client must not drop the reference to its successor,
423
- // which would then stay open until its own socket timeout
424
- if (this.commandClient === commandClient) {
425
- this.commandClient = null;
426
- }
427
- };
428
- commandClient.on('error', onErr);
492
+ try {
493
+ await commandClient.connect();
494
+ commandClient.log.info({ msg: 'Command channel connected', cid: commandCid, channel: 'command', account: this.account });
495
+ } catch (err) {
496
+ // untrackConnection() swallows its own Redis failure, so the connect error is
497
+ // what the caller sees - a hiccup while updating the count must not replace it
498
+ await this.untrackConnection(commandClient);
499
+ commandClient.log.warn({ msg: 'Failed to connect command client', cid: commandCid, channel: 'command', account: this.account, err });
500
+ throw err;
501
+ }
429
502
 
503
+ // Clean up when connection closes. EventEmitter never observes what an async listener
504
+ // returns, so nothing in this body may escape - see the primary connection's handler
505
+ commandClient.on('close', async () => {
430
506
  try {
431
- await commandClient.connect();
432
- commandClient.log.info({ msg: 'Command channel connected', cid: commandCid, channel: 'command', account: this.account });
433
- } catch (err) {
434
- // untrackConnection() swallows its own Redis failure, so the connect error is
435
- // what the caller sees - a hiccup while updating the count must not replace it
436
507
  await this.untrackConnection(commandClient);
437
- commandClient.log.warn({ msg: 'Failed to connect command client', cid: commandCid, channel: 'command', account: this.account, err });
438
- throw err;
508
+ commandClient.log.info({ msg: 'Connection closed', cid: commandCid, channel: 'command', account: this.account });
509
+ } catch (err) {
510
+ this.logger.error({ msg: 'Error in command client close handler', cid: commandCid, account: this.account, err });
439
511
  }
440
512
 
441
- // Clean up when connection closes. EventEmitter never observes what an async listener
442
- // returns, so nothing in this body may escape - see the primary connection's handler
443
- commandClient.on('close', async () => {
444
- try {
445
- await this.untrackConnection(commandClient);
446
- commandClient.log.info({ msg: 'Connection closed', cid: commandCid, channel: 'command', account: this.account });
447
- } catch (err) {
448
- this.logger.error({ msg: 'Error in command client close handler', cid: commandCid, account: this.account, err });
449
- }
450
-
451
- if (this.commandClient === commandClient) {
452
- this.commandClient = null;
453
- }
454
- detachImapClient(commandClient, this.logger, { type: 'commandClient', cid: commandCid, account: this.account });
455
- commandClient = null;
456
- });
457
-
458
- return commandClient;
459
- } finally {
460
- // Always release the lock
461
- if (connectLock?.success) {
462
- this.logger.debug({ msg: 'Releasing connection lock', lockKey, index: connectLock.index });
463
- await lock.releaseLock(connectLock);
464
- this.logger.debug({ msg: 'Released connection lock', lockKey, index: connectLock.index });
513
+ if (this.commandClient === commandClient) {
514
+ this.commandClient = null;
465
515
  }
466
- }
516
+ detachImapClient(commandClient, this.logger, { type: 'commandClient', cid: commandCid, account: this.account });
517
+ commandClient = null;
518
+ });
519
+
520
+ return commandClient;
467
521
  }
468
522
 
469
523
  /**
@@ -482,9 +536,11 @@ class IMAPClient extends BaseClient {
482
536
  * This creates a unique identifier that can be unpacked later to retrieve the message
483
537
  * @param {Object|string} mailbox - Mailbox object or path
484
538
  * @param {number} uid - Message UID
539
+ * @param {Map} [statusCache] - Stored status by mailbox path, for a caller packing many UIDs
540
+ * of the same folder (a listing): the status is read once instead of one HGETALL per message
485
541
  * @returns {string|false} Base64url encoded ID or false on error
486
542
  */
487
- async packUid(mailbox, uid) {
543
+ async packUid(mailbox, uid, statusCache) {
488
544
  if (isNaN(uid) || !mailbox) {
489
545
  return false;
490
546
  }
@@ -503,7 +559,10 @@ class IMAPClient extends BaseClient {
503
559
  }
504
560
 
505
561
  // Get stored mailbox status including UID validity
506
- let storedStatus = await mailbox.getStoredStatus();
562
+ let storedStatus = statusCache?.get(mailbox.path);
563
+ if (!storedStatus) {
564
+ storedStatus = await mailbox.getStoredStatus();
565
+ }
507
566
 
508
567
  // If stored status missing uidValidity, try live IMAP mailbox status
509
568
  if (!validUidValidity(storedStatus.uidValidity)) {
@@ -547,6 +606,9 @@ class IMAPClient extends BaseClient {
547
606
  return false;
548
607
  }
549
608
 
609
+ // Only a usable status is reused, so a folder whose status is missing is looked at again
610
+ statusCache?.set(mailbox.path, storedStatus);
611
+
550
612
  // Pack UID validity and mailbox path into a buffer
551
613
  let uidValBuf = Buffer.alloc(8);
552
614
  uidValBuf.writeBigUInt64BE(storedStatus.uidValidity, 0);
@@ -841,25 +903,15 @@ class IMAPClient extends BaseClient {
841
903
  let accountData = await this.accountObject.loadAccountData();
842
904
 
843
905
  // Get configured paths to monitor (default to all)
844
- const accountPaths = [].concat(accountData.path || '*');
845
- if (!accountPaths.length) {
846
- accountPaths.push('*');
847
- }
906
+ const accountPaths = accountPathList(accountData);
848
907
 
849
908
  for (let entry of listing || []) {
850
909
  if (
851
910
  // previously unseen
852
911
  !this.mailboxes.has(normalizePath(entry.path))
853
912
  ) {
854
- // Apply filtering rules based on account configuration
855
- if (!accountPaths.includes('*')) {
856
- if (configuredPathIndex(accountPaths, entry) < 0) {
857
- // ignore changes
858
- entry.syncDisabled = true;
859
- }
860
- } else if (this.isGmail && !['\\All', '\\Junk', '\\Trash'].includes(entry.specialUse)) {
861
- // For Gmail, only monitor All Mail, Spam, and Trash folders
862
- // Other folders are just labels and covered by All Mail
913
+ // the same rule connect() applies to the folders it registers
914
+ if (!folderMonitoring(accountPaths, entry, this.isGmail).monitored) {
863
915
  entry.syncDisabled = true;
864
916
  }
865
917
 
@@ -968,8 +1020,8 @@ class IMAPClient extends BaseClient {
968
1020
 
969
1021
  if (this.isClosing || this.isClosed || this.paused) {
970
1022
  // pause() or close() was called while account data was loading. No
971
- // socket exists yet (imapClient.connect() below is what dials out,
972
- // and ImapFlow itself has no closed-state check), so bail out
1023
+ // socket exists yet (imapClient.connect() below is what dials out), so
1024
+ // bail out here rather than let connect() refuse a closed client, and
973
1025
  // without overwriting the paused/closed state
974
1026
  return false;
975
1027
  }
@@ -997,37 +1049,26 @@ class IMAPClient extends BaseClient {
997
1049
  this.isOutlook = /\boffice365\.com$/i.test(imapClient.host); // || /The Microsoft Exchange IMAP4 service is ready/.test(imapClient.greeting);
998
1050
  this.isLarkSuite = /\blarksuite\.com$/i.test(imapClient.host);
999
1051
 
1000
- const accountPaths = [].concat(accountData.path || '*');
1001
- if (!accountPaths.length) {
1002
- accountPaths.push('*');
1003
- }
1052
+ const accountPaths = accountPathList(accountData);
1053
+ const watchesAll = accountPaths.includes('*');
1004
1054
 
1005
1055
  // store synced folder entries
1006
1056
  const mainList = [];
1007
1057
 
1008
1058
  // Process mailbox listing and determine which folders to monitor
1009
1059
  for (let entry of listing) {
1010
- if (!accountPaths.includes('*')) {
1011
- // Limited path monitoring - only specific folders
1012
- let index = configuredPathIndex(accountPaths, entry);
1013
- if (index < 0) {
1014
- entry.syncDisabled = true;
1015
- } else {
1016
- // insert to stored list with the sorting index
1017
- mainList.push({ index, entry });
1018
- }
1019
- } else {
1020
- // Monitor all folders - determine main folder for IDLE
1021
- if ((this.isGmail && entry.specialUse === '\\All') || (!this.isGmail && entry.specialUse === '\\Inbox')) {
1022
- // In case of gmail prefer All mail folder as the folder to actively track, otherwise INBOX
1023
- // idle in this folder
1024
- this.main = entry;
1025
- }
1060
+ let { monitored, index } = folderMonitoring(accountPaths, entry, this.isGmail);
1061
+ if (!monitored) {
1062
+ entry.syncDisabled = true;
1063
+ }
1026
1064
 
1027
- if (this.isGmail && !['\\All', '\\Junk', '\\Trash'].includes(entry.specialUse)) {
1028
- // do not look for changes from this folder
1029
- entry.syncDisabled = true;
1030
- }
1065
+ if (index >= 0) {
1066
+ // limited path monitoring: insert to stored list with the sorting index
1067
+ mainList.push({ index, entry });
1068
+ } else if (watchesAll && ((this.isGmail && entry.specialUse === '\\All') || (!this.isGmail && entry.specialUse === '\\Inbox'))) {
1069
+ // In case of gmail prefer All mail folder as the folder to actively track, otherwise INBOX
1070
+ // idle in this folder
1071
+ this.main = entry;
1031
1072
  }
1032
1073
 
1033
1074
  this.registerMailbox(entry);
@@ -1055,6 +1096,9 @@ class IMAPClient extends BaseClient {
1055
1096
  // Handle flag changes
1056
1097
  imapClient.on('flags', event => this.handleFlagsEvent(imapClient, event));
1057
1098
 
1099
+ // A polling server without IDLE reports flag changes only through its HIGHESTMODSEQ
1100
+ imapClient.on('highestModseq', event => this.handleHighestModseqEvent(imapClient, event));
1101
+
1058
1102
  // The loop above registered a Mailbox for every listed folder, which is what
1059
1103
  // processListing() would have done, so the sync that follows this call has
1060
1104
  // nothing left to discover from a second listing. Keep the two registration
@@ -1143,6 +1187,23 @@ class IMAPClient extends BaseClient {
1143
1187
  }
1144
1188
  }
1145
1189
 
1190
+ /**
1191
+ * Handles a HIGHESTMODSEQ change found by ImapFlow's polling fallback
1192
+ * @param {Object} imapClient - IMAP connection that emitted the event
1193
+ * @param {Object} event - Event payload
1194
+ */
1195
+ async handleHighestModseqEvent(imapClient, event) {
1196
+ try {
1197
+ let mailbox = this.resolveEventMailbox(event);
1198
+ if (!mailbox) {
1199
+ return;
1200
+ }
1201
+ await mailbox.onHighestModseq(event);
1202
+ } catch (err) {
1203
+ imapClient.log.error({ msg: 'Failed to process HIGHESTMODSEQ change', path: event?.path, err });
1204
+ }
1205
+ }
1206
+
1146
1207
  /**
1147
1208
  * Handles a mailbox open notification
1148
1209
  * @param {Object} imapClient - IMAP connection that emitted the event
@@ -1694,8 +1755,9 @@ class IMAPClient extends BaseClient {
1694
1755
  }
1695
1756
  }
1696
1757
 
1697
- // Provider IDLE workarounds, and the account's own IDLE restart interval
1698
- applyIdleSettings(imapConfig, accountData.imap);
1758
+ // Provider IDLE workarounds, what this host's dropped sessions taught, and the account's own
1759
+ // IDLE restart interval
1760
+ applyIdleSettings(imapConfig, accountData.imap, await this.getLearnedIdleInterval(imapConfig.host));
1699
1761
 
1700
1762
  // Apply global settings
1701
1763
  if (DISABLE_IMAP_COMPRESSION) {
@@ -1732,7 +1794,7 @@ class IMAPClient extends BaseClient {
1732
1794
  if (this.imapClient) {
1733
1795
  this.logger.debug({ msg: 'Clearing previous connection' });
1734
1796
  let prevImapClient = this.imapClient;
1735
- prevImapClient.disabled = true;
1797
+ prevImapClient.context.disabled = true;
1736
1798
  try {
1737
1799
  detachImapClient(prevImapClient, this.logger, { type: 'imapClient', previous: true, account: this.account });
1738
1800
  prevImapClient.close();
@@ -1784,13 +1846,14 @@ class IMAPClient extends BaseClient {
1784
1846
  // Create new IMAP connection instance
1785
1847
  let imapClient = createImapClient(
1786
1848
  Object.assign({}, imapConfig, {
1787
- expungeHandler: async payload => await this.expungeHandler(payload)
1849
+ expungeHandler: async payload => await this.expungeHandler(payload),
1850
+ // startedAt is the birth time of this connection attempt: the unexpected-close
1851
+ // handler uses the age to tell a stable connection dropping from a connect/drop
1852
+ // cycle that needs throttling. Not ImapFlow's connectedAt, which stays unset
1853
+ // when the attempt never got a socket. `disabled` marks a replaced client
1854
+ context: { startedAt: Date.now(), disabled: false }
1788
1855
  })
1789
1856
  );
1790
- // Birth time of this connection attempt - the unexpected-close
1791
- // handler uses the age to tell a stable connection dropping from a
1792
- // connect/drop cycle that needs throttling
1793
- imapClient.connectionStartTime = Date.now();
1794
1857
  this.connections.add(imapClient);
1795
1858
  await this.redis.hSetExists(this.getAccountKey(), 'connections', this.connections.size.toString());
1796
1859
 
@@ -1798,9 +1861,6 @@ class IMAPClient extends BaseClient {
1798
1861
 
1799
1862
  this.imapClient = imapClient;
1800
1863
 
1801
- // Mark as primary connection
1802
- imapClient.primaryConnection = true;
1803
-
1804
1864
  // Forward IMAP logs to account logger
1805
1865
  // if emitLogs option is true then separate log event is fired for every log entry
1806
1866
  imapClient.on('log', entry => {
@@ -1853,9 +1913,11 @@ class IMAPClient extends BaseClient {
1853
1913
  // rejection and takes the whole worker down. The steps below carry their own
1854
1914
  // catches; this outer one is what keeps that true for an await added outside them.
1855
1915
  imapClient.on('close', async () => {
1916
+ // before the awaits below, which would otherwise count as quiet time
1917
+ const closedAt = Date.now();
1856
1918
  try {
1857
1919
  await this.untrackConnection(imapClient);
1858
- imapClient?.log.info({ msg: 'Connection closed', type: 'imapClient', account: this.account, disabled: imapClient.disabled });
1920
+ imapClient?.log.info({ msg: 'Connection closed', type: 'imapClient', account: this.account, disabled: imapClient.context?.disabled });
1859
1921
 
1860
1922
  // Update state on unexpected disconnect
1861
1923
  if (['init', 'connecting', 'syncing', 'connected'].includes(this.state)) {
@@ -1899,9 +1961,16 @@ class IMAPClient extends BaseClient {
1899
1961
  imapClient.log.error({ msg: 'Connection close error', err });
1900
1962
  }
1901
1963
 
1964
+ // a close of the live primary connection that nothing here asked for
1965
+ const unexpected = !imapClient.context?.disabled && imapClient === this.imapClient;
1966
+ if (unexpected) {
1967
+ // not awaited: learning must not hold up the reconnect, and handles its own errors
1968
+ this.recordIdleClose(imapClient, closedAt);
1969
+ }
1970
+
1902
1971
  try {
1903
1972
  // Attempt reconnection if this was an unexpected close
1904
- if (!imapClient.disabled && imapClient === this.imapClient && !this._connecting) {
1973
+ if (unexpected && !this._connecting) {
1905
1974
  if (this.validateConnectionAge(imapClient)) {
1906
1975
  // A proven-stable connection dropped - reconnect right away
1907
1976
  if (!this.reconnectTimer) {
@@ -2048,7 +2117,7 @@ class IMAPClient extends BaseClient {
2048
2117
  this.isClosing = true;
2049
2118
 
2050
2119
  if (this.imapClient) {
2051
- this.imapClient.disabled = true;
2120
+ this.imapClient.context.disabled = true;
2052
2121
  this.imapClient.close();
2053
2122
  if (this.commandClient) {
2054
2123
  this.commandClient.close();
@@ -2103,6 +2172,9 @@ class IMAPClient extends BaseClient {
2103
2172
  this.isClosing = true;
2104
2173
 
2105
2174
  if (this.imapClient) {
2175
+ // a close asked for here (pause, shutdown, a move to another worker, a requested
2176
+ // reconnect): the close handler must neither reconnect it nor learn from it
2177
+ this.imapClient.context.disabled = true;
2106
2178
  this.imapClient.close();
2107
2179
  }
2108
2180
 
@@ -2946,12 +3018,7 @@ class IMAPClient extends BaseClient {
2946
3018
  let uploadResponse = await connectionClient.append(data.path, raw, data.flags, data.internalDate);
2947
3019
 
2948
3020
  // Return to IDLE if using primary connection
2949
- if (this.imapClient && connectionClient === this.imapClient && this.imapClient.mailbox && !this.imapClient.idling) {
2950
- // force back to IDLE
2951
- this.imapClient.idle().catch(err => {
2952
- this.logger.warn({ msg: 'IDLE error', err });
2953
- });
2954
- }
3021
+ this.resumeIdle(connectionClient);
2955
3022
 
2956
3023
  // Pack response data. ImapFlow's append() returns `destination` as the
2957
3024
  // append target and `path` as the currently selected mailbox (often the
@@ -3105,10 +3172,7 @@ class IMAPClient extends BaseClient {
3105
3172
  continue;
3106
3173
  }
3107
3174
 
3108
- const accountPaths = [].concat(accountData.path || '*');
3109
- if (!accountPaths.length) {
3110
- accountPaths.push('*');
3111
- }
3175
+ const accountPaths = accountPathList(accountData);
3112
3176
 
3113
3177
  // Check if already covered by primary connection
3114
3178
  if (samePath(accountPaths[0], entry.path)) {