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
@@ -12,7 +12,7 @@ const { BaseClient, metricsMeta } = require('./base-client');
12
12
  const { isSafePathSegment } = require('../utils/provider-id');
13
13
  const { isTransientCredentialError } = require('./credential-errors');
14
14
  const { messageWebSafeHtml, applyWebSafeHtmlOptions } = require('../web-safe-html');
15
- const { emitChangeEvent, toCamelCase, collectCidReferences, embedCidImages, truncateTextContents, readEnvValue } = require('../tools');
15
+ const { emitChangeEvent, toCamelCase, collectCidReferences, embedCidImages, truncateTextContents } = require('../tools');
16
16
  const { Gateway } = require('../gateway');
17
17
 
18
18
  const {
@@ -29,6 +29,15 @@ const {
29
29
  const settings = require('../settings');
30
30
 
31
31
  const { GMAIL_API_BASE, LIST_BATCH_SIZE, request: gmailApiRequest, executeBatchRequests } = require('./gmail/gmail-api');
32
+
33
+ /**
34
+ * Whether a Gmail API request failed because the resource does not exist
35
+ * @param {Error} err - Error thrown by request()
36
+ * @returns {boolean}
37
+ */
38
+ function isGmailNotFound(err) {
39
+ return err?.oauthRequest?.status === 404 || err?.oauthRequest?.response?.error?.code === 404;
40
+ }
32
41
  const { buildSendRequest, buildDraftSendRequest } = require('./gmail/send-request');
33
42
  const { pushHeaderValue } = require('../utils/header-map');
34
43
 
@@ -99,9 +108,9 @@ function extractMessageIdHeader(raw) {
99
108
  const RENEW_WATCH_TTL = 60 * 60 * 1000; // 1h - how often to check if watch needs renewal
100
109
  const MIN_WATCH_TTL = 24 * 3600 * 1000; // 1day - minimum time before renewing watch
101
110
  // 10min default - fallback polling if no Pub/Sub notifications. Overridable via
102
- // EENGINE_GMAIL_FALLBACK_POLL_INTERVAL (ms) so integration tests can exercise the poller
103
- // without waiting the full interval.
104
- const FALLBACK_POLLING_INTERVAL = Number((readEnvValue('EENGINE_GMAIL_FALLBACK_POLL_INTERVAL') || '').toString().trim()) || 10 * 60 * 1000;
111
+ // EENGINE_GMAIL_FALLBACK_POLL_INTERVAL (a duration, or milliseconds) so integration tests can
112
+ // exercise the poller without waiting the full interval.
113
+ const { GMAIL_FALLBACK_POLL_INTERVAL: FALLBACK_POLLING_INTERVAL } = require('./fallback-poll');
105
114
 
106
115
  /*
107
116
  Gmail API implementation status:
@@ -422,18 +431,16 @@ class GmailClient extends BaseClient {
422
431
  })
423
432
  };
424
433
  }
425
- } else {
434
+ } else if (profileRes.emailAddress && accountData.oauth2.auth?.user !== profileRes.emailAddress) {
426
435
  // Extract email from profile for full access accounts
427
- if (profileRes.emailAddress && accountData.oauth2.auth?.user !== profileRes.emailAddress) {
428
- updates._oldOAuth2User = accountData.oauth2.auth?.user; // needed for cleanups
429
- updates.oauth2 = {
430
- partial: true,
431
- auth: Object.assign(accountData.oauth2.auth || {}, {
432
- // update username
433
- user: profileRes.emailAddress
434
- })
435
- };
436
- }
436
+ updates._oldOAuth2User = accountData.oauth2.auth?.user; // needed for cleanups
437
+ updates.oauth2 = {
438
+ partial: true,
439
+ auth: Object.assign(accountData.oauth2.auth || {}, {
440
+ // update username
441
+ user: profileRes.emailAddress
442
+ })
443
+ };
437
444
  }
438
445
 
439
446
  // Detect and store user locale (only for full access accounts)
@@ -478,7 +485,7 @@ class GmailClient extends BaseClient {
478
485
  let historyId = Number(profileRes?.historyId) || null;
479
486
  if (!accountData.googleHistoryId) {
480
487
  // set as initial
481
- await this.redis.hset(this.getAccountKey(), 'googleHistoryId', historyId.toString());
488
+ await this.redis.hSetExists(this.getAccountKey(), 'googleHistoryId', historyId.toString());
482
489
  accountData.googleHistoryId = historyId;
483
490
  this.logger.info({ msg: 'Re-set missing Google History ID', account: this.account, historyId });
484
491
  }
@@ -584,8 +591,30 @@ class GmailClient extends BaseClient {
584
591
  return true;
585
592
  }
586
593
 
587
- async currentState() {
588
- return (await this.redis.hget(this.getAccountKey(), 'state')) || 'disconnected';
594
+ /**
595
+ * Stops the account's Gmail Pub/Sub watch. Without this a deleted account's watch went on
596
+ * publishing every mailbox change to the topic until it lapsed, up to seven days later
597
+ * @returns {Promise<boolean>} True when a watch was stopped
598
+ */
599
+ async releaseRemoteResources() {
600
+ try {
601
+ // Most accounts have no watch to stop, which the one stored field tells without loading
602
+ // and decrypting the whole account
603
+ if (!(await this.accountObject.getStoredField('watchResponse'))) {
604
+ return false;
605
+ }
606
+ const accountData = await this.accountObject.loadAccountData(this.account, false);
607
+ if (!accountData._app?.pubSubApp || !accountData.watchResponse) {
608
+ return false;
609
+ }
610
+ await this.prepare();
611
+ await this.request(`${GMAIL_API_BASE}/gmail/v1/users/me/stop`, 'post', Buffer.alloc(0));
612
+ this.logger.info({ msg: 'Stopped Gmail pubsub watch', account: this.account });
613
+ return true;
614
+ } catch (err) {
615
+ this.logger.warn({ msg: 'Failed to stop Gmail pubsub watch', account: this.account, err });
616
+ return false;
617
+ }
589
618
  }
590
619
 
591
620
  async delete() {
@@ -893,6 +922,12 @@ class GmailClient extends BaseClient {
893
922
  let resultList = await Promise.allSettled(promises);
894
923
  for (let entry of resultList) {
895
924
  if (entry.status === 'rejected') {
925
+ if (isGmailNotFound(entry.reason)) {
926
+ // Deleted between the listing and this fetch. Skipped like a message that
927
+ // moved out of the page, instead of failing every other message on it
928
+ this.logger.debug({ msg: 'Listed message no longer exists', account: this.account, err: entry.reason });
929
+ continue;
930
+ }
896
931
  throw entry.reason;
897
932
  }
898
933
  if (entry.value) {
@@ -953,6 +988,8 @@ class GmailClient extends BaseClient {
953
988
  return {
954
989
  deleted: result && result.labelIds?.includes('TRASH'),
955
990
  moved: {
991
+ // the same shape IMAP and Graph answer with, deleteMessages() already named it
992
+ destination: SYSTEM_NAMES.TRASH,
956
993
  message: result.id
957
994
  }
958
995
  };
@@ -1596,7 +1633,7 @@ class GmailClient extends BaseClient {
1596
1633
  try {
1597
1634
  messageData = await this.request(`${GMAIL_API_BASE}/gmail/v1/users/me/messages/${emailId}`, 'get', { format: 'raw' });
1598
1635
  } catch (err) {
1599
- if (err?.oauthRequest?.status === 404 || err?.oauthRequest?.response?.error?.code === 404) {
1636
+ if (isGmailNotFound(err)) {
1600
1637
  let error = new Error('Requested message was not found');
1601
1638
  error.code = 'MessageNotFound';
1602
1639
  error.statusCode = 404;
@@ -3214,7 +3251,7 @@ class GmailClient extends BaseClient {
3214
3251
  // advance the durable cursor once an entry is handled (processed or skipped)
3215
3252
  let advanceHistoryCursor = async historyEntryId => {
3216
3253
  if (historyEntryId && historyEntryId > lastHistoryId) {
3217
- await this.redis.hset(this.getAccountKey(), 'googleHistoryId', historyEntryId.toString());
3254
+ await this.redis.hSetExists(this.getAccountKey(), 'googleHistoryId', historyEntryId.toString());
3218
3255
  lastHistoryId = historyEntryId;
3219
3256
  }
3220
3257
  };
@@ -3305,7 +3342,7 @@ class GmailClient extends BaseClient {
3305
3342
  if (entry?.id) {
3306
3343
  // mark the entry as in flight before touching it, so a
3307
3344
  // worker death mid-entry is attributable on restart
3308
- await this.redis.hset(this.getAccountKey(), 'googleHistoryProcessing', JSON.stringify({ id: entry.id, count: attempts + 1 }));
3345
+ await this.redis.hSetExists(this.getAccountKey(), 'googleHistoryProcessing', JSON.stringify({ id: entry.id, count: attempts + 1 }));
3309
3346
  }
3310
3347
 
3311
3348
  try {
@@ -3345,7 +3382,7 @@ class GmailClient extends BaseClient {
3345
3382
 
3346
3383
  // Update to newest history ID
3347
3384
  if (newestHistoryId && newestHistoryId > currentHistoryId) {
3348
- await this.redis.hset(this.getAccountKey(), 'googleHistoryId', newestHistoryId.toString());
3385
+ await this.redis.hSetExists(this.getAccountKey(), 'googleHistoryId', newestHistoryId.toString());
3349
3386
  }
3350
3387
 
3351
3388
  // the run finished without dying, drop the in-flight marker
@@ -3449,6 +3486,7 @@ class GmailClient extends BaseClient {
3449
3486
  module.exports = {
3450
3487
  GmailClient,
3451
3488
  PageCursor,
3489
+ isGmailNotFound,
3452
3490
  SKIP_LABELS: Object.freeze([...SKIP_LABELS]),
3453
3491
  SYSTEM_LABELS: Object.freeze({ ...SYSTEM_LABELS }),
3454
3492
  SYSTEM_NAMES: Object.freeze({ ...SYSTEM_NAMES })
@@ -0,0 +1,73 @@
1
+ 'use strict';
2
+
3
+ // Where the IDLE intervals lib/email-client/imap/adaptive-idle.js learns are kept: one hash for the
4
+ // instance, a field per server host, so every account on a host shares what any of them saw.
5
+ // Two workers recording at once can lose one observation; the learning is a running estimate and
6
+ // recovers on the next one.
7
+
8
+ const { REDIS_PREFIX } = require('../../consts');
9
+ const { observe, observationFor, initialState } = require('./adaptive-idle');
10
+
11
+ const LEARNED_KEY = `${REDIS_PREFIX}idle:learned`;
12
+
13
+ const hostKey = host => (host || '').toString().trim().toLowerCase();
14
+
15
+ async function readState(redis, host) {
16
+ const raw = await redis.hget(LEARNED_KEY, hostKey(host));
17
+ if (!raw) {
18
+ return null;
19
+ }
20
+ try {
21
+ return JSON.parse(raw);
22
+ } catch (err) {
23
+ return null;
24
+ }
25
+ }
26
+
27
+ /**
28
+ * The interval learned for a host, or null
29
+ * @param {Object} redis - ioredis client
30
+ * @param {string} host - IMAP server host
31
+ * @returns {Promise<number|null>} Milliseconds
32
+ */
33
+ async function learnedInterval(redis, host) {
34
+ if (!hostKey(host)) {
35
+ return null;
36
+ }
37
+ const state = await readState(redis, host);
38
+ return (state && state.interval) || null;
39
+ }
40
+
41
+ /**
42
+ * Records what a closed primary connection tells about its server
43
+ * @param {Object} redis - ioredis client
44
+ * @param {string} host - IMAP server host
45
+ * @param {Object} imapClient - The closed ImapFlow client
46
+ * @param {number} [now] - Epoch ms
47
+ * @returns {Promise<Object|null>} `{ before, after }` intervals when something was recorded
48
+ */
49
+ async function recordClose(redis, host, imapClient, now = Date.now()) {
50
+ const observation = observationFor(imapClient, now);
51
+ if (!observation || !hostKey(host)) {
52
+ return null;
53
+ }
54
+ const state = await readState(redis, host);
55
+ if (!state && observation.type === 'stable') {
56
+ // the common case on every well-behaved server: nothing learned, nothing to learn
57
+ return null;
58
+ }
59
+ const next = observe(state, observation, now);
60
+ const serialized = JSON.stringify(next);
61
+ if (serialized === JSON.stringify(initialState())) {
62
+ // back to nothing learned: the host takes no field, so the hash does not grow with every
63
+ // server any account ever connected to
64
+ if (state) {
65
+ await redis.hdel(LEARNED_KEY, hostKey(host));
66
+ }
67
+ } else if (!state || serialized !== JSON.stringify(Object.assign(initialState(), state))) {
68
+ await redis.hset(LEARNED_KEY, hostKey(host), serialized);
69
+ }
70
+ return { before: (state && state.interval) || null, after: next.interval, observation };
71
+ }
72
+
73
+ module.exports = { learnedInterval, recordClose, LEARNED_KEY };
@@ -0,0 +1,278 @@
1
+ 'use strict';
2
+
3
+ // Learns how often to restart IDLE for a server that drops idle sessions without saying so.
4
+ //
5
+ // Some servers, or a proxy in front of them, close a session that has been quiet for a while with
6
+ // no BYE: TransIP cuts one 30 seconds after the client last wrote, far below the 30 minutes RFC 9051
7
+ // asks for. Restarting IDLE before that point is a write, which keeps the session alive, and an
8
+ // operator can set the interval per account (imap.maxIdleTime) once they have found the number by
9
+ // hand. This finds it from the drops themselves, per server host, so every account on the host
10
+ // benefits from what one of them saw.
11
+ //
12
+ // The signal is a primary connection that closed while it was idling, after a quiet time (since
13
+ // the client last wrote) that is well short of what a server may legitimately allow. Two such drops
14
+ // with a similar quiet time set the interval to a fraction of it, and lowering a learned interval
15
+ // takes three. A session cap is the other way a server ends sessions: Vimexx ends every one after
16
+ // about six minutes however often the client writes. Shortening the interval does not help there,
17
+ // which shows as sessions (two of them) still ending at the same age as before the interval was
18
+ // learned, and the host then goes back to the default and is left alone for a day. Only a
19
+ // connection that ran the learned interval can show that: one opened before it was learned, or by an
20
+ // account with its own interval, ends at the old age because it never restarted IDLE any sooner. A
21
+ // learned interval relaxes again after a run of long stable sessions, and a relaxed interval the
22
+ // server cuts goes back to the one it relaxed from, which is then as far as relaxing goes.
23
+ //
24
+ // Pure: the state is a plain object the caller stores, so every rule is testable on its own.
25
+
26
+ const { IMAP_MAX_IDLE_TIME_MIN } = require('../../consts');
27
+
28
+ // Fraction of the observed quiet time to restart IDLE at, leaving room for timers and latency
29
+ const LEARN_RATIO = 0.6;
30
+ // A drop after this much quiet is within what a server may do (RFC 9051 allows 30 minutes)
31
+ const LEARN_CEILING = 25 * 60 * 1000;
32
+ // Drops with a similar quiet time needed before an interval is learned, and before a learned one is
33
+ // lowered. Lowering asks for more: a connection running an interval is never quiet for longer than
34
+ // it, so a network blip on it always looks like a shorter timer, and two blips can happen to agree
35
+ const CONFIRM_DROPS = 2;
36
+ const LOWER_CONFIRM_DROPS = 3;
37
+ // A run of similar drops, or of cap or revert evidence, older than this confirms nothing: a timer
38
+ // that cuts sessions does so on every session, not once a week
39
+ const PENDING_WINDOW = 60 * 60 * 1000;
40
+ // How close two quiet times or two session ages must be to count as the same. Drops that would lower
41
+ // a learned interval have to agree more closely: a timer that got shorter cuts at the same quiet time
42
+ // every time, while blips land anywhere up to the interval
43
+ const SIMILAR = 0.25;
44
+ const LOWER_SIMILAR = 0.1;
45
+ // A session this long is evidence the interval works
46
+ const STABLE_SESSION = 30 * 60 * 1000;
47
+ // Stable sessions in a row before the interval relaxes, and by how much
48
+ const RELAX_AFTER = 3;
49
+ const RELAX_FACTOR = 1.5;
50
+ // How long a host that turned out to cap sessions is left alone
51
+ const CAP_COOLDOWN = 24 * 3600 * 1000;
52
+ // Drops closer together than this are one event (a proxy restart, a network blip) seen by several
53
+ // accounts on the host, and can not confirm each other
54
+ const SAME_EVENT_WINDOW = 10 * 1000;
55
+
56
+ const similar = (a, b, ratio = SIMILAR) => a > 0 && b > 0 && Math.abs(a - b) <= ratio * Math.max(a, b);
57
+
58
+ /**
59
+ * The state of a host nothing has been learned for
60
+ * @returns {Object}
61
+ */
62
+ function initialState() {
63
+ return {
64
+ interval: null,
65
+ pendingQuiet: null,
66
+ pendingAt: 0,
67
+ drops: 0,
68
+ stable: 0,
69
+ ageWhenLearned: null,
70
+ cappedUntil: 0,
71
+ // the interval the last relaxing step started from, and a relaxed interval the server cut
72
+ relaxedFrom: null,
73
+ relaxLimit: null,
74
+ // sessions on the learned interval that look like a session cap, or (after a relaxing step,
75
+ // which clears the learning age, so never both) that the server cut on the relaxed interval,
76
+ // and when the last one was seen; CONFIRM_DROPS of them are acted on
77
+ evidenceDrops: 0,
78
+ evidenceAt: 0
79
+ };
80
+ }
81
+
82
+ /**
83
+ * One relaxing step after a run of stable sessions, in place: half as long again, unless that
84
+ * reaches an interval the server already cut (`relaxLimit`), and back to the default once near what
85
+ * a server may allow. Clears the age the interval was learned at, since sessions this long are not
86
+ * capped
87
+ * @param {Object} state
88
+ */
89
+ function relax(state) {
90
+ state.stable = 0;
91
+ const relaxed = Math.round(state.interval * RELAX_FACTOR);
92
+ if (state.relaxLimit && relaxed >= state.relaxLimit) {
93
+ return;
94
+ }
95
+ state.ageWhenLearned = null;
96
+ if (relaxed >= LEARN_CEILING) {
97
+ Object.assign(state, initialState());
98
+ return;
99
+ }
100
+ state.relaxedFrom = state.interval;
101
+ state.interval = relaxed;
102
+ }
103
+
104
+ /**
105
+ * Applies one observation to a host's state
106
+ * @param {Object|null} state - Stored state, or null for a host with none
107
+ * @param {Object} observation - `{ type: 'drop', quietMs, ageMs, idling, ranInterval }` for a
108
+ * connection that closed unexpectedly (`ranInterval` is the IDLE restart interval it ran with,
109
+ * null for none), `{ type: 'stable', ageMs, ranInterval }` for one that lived long and closed
110
+ * @param {number} now - Epoch ms
111
+ * @returns {Object} The new state (a new object, the input is left alone)
112
+ */
113
+ function observe(state, observation, now) {
114
+ const next = Object.assign(initialState(), state || {});
115
+ if (next.cappedUntil && now >= next.cappedUntil) {
116
+ // a cooldown that is over is nothing to keep, and leaves the host free to learn again
117
+ next.cappedUntil = 0;
118
+ }
119
+ if (next.pendingAt && now - next.pendingAt >= PENDING_WINDOW) {
120
+ clearPending(next);
121
+ }
122
+ if (next.evidenceAt && now - next.evidenceAt >= PENDING_WINDOW) {
123
+ clearEvidence(next);
124
+ }
125
+
126
+ if (observation.type === 'stable') {
127
+ return observeStable(next, observation);
128
+ }
129
+
130
+ if (observation.type !== 'drop' || !observation.idling || now < next.cappedUntil) {
131
+ return next;
132
+ }
133
+ const { quietMs, ageMs, ranInterval } = observation;
134
+ if (!(quietMs > 0) || quietMs >= LEARN_CEILING) {
135
+ return next;
136
+ }
137
+
138
+ next.stable = 0;
139
+ // whether this connection restarted IDLE at least as often as the learned interval asks
140
+ const ranLearned = !!(next.interval && ranInterval > 0 && ranInterval <= next.interval);
141
+
142
+ // Whether the session restarted IDLE on its interval before the cut: its last write came more
143
+ // than one interval into the session. A cut before the first restart is a quiet timer shorter
144
+ // than the interval; one after it is not about the interval at all (a blip, a session cap)
145
+ const restarted = ageMs - quietMs > ranInterval;
146
+
147
+ // A relaxed interval the server cuts before the first restart: back to the one that held, and no
148
+ // further. A session that did restart on it says nothing against it
149
+ if (next.relaxedFrom && ranInterval === next.interval && !restarted) {
150
+ if (countEvidence(next, now)) {
151
+ next.relaxLimit = next.interval;
152
+ next.interval = next.relaxedFrom;
153
+ next.relaxedFrom = null;
154
+ clearPending(next);
155
+ }
156
+ return next;
157
+ }
158
+
159
+ // Sessions that ran the learned interval, restarted IDLE on it and still end at the age they ended
160
+ // at before: a cap on the session, not on its quiet time, which no interval can get under. A cut
161
+ // before the first restart is a quiet timer shorter than the interval, left to the lowering below
162
+ if (ranLearned && restarted && next.ageWhenLearned && similar(ageMs, next.ageWhenLearned)) {
163
+ return countEvidence(next, now) ? Object.assign(initialState(), { cappedUntil: now + CAP_COOLDOWN }) : next;
164
+ }
165
+
166
+ if (next.pendingAt && now - next.pendingAt < SAME_EVENT_WINDOW) {
167
+ // the same event, seen through another account of the host
168
+ return next;
169
+ }
170
+
171
+ const confirming = next.pendingQuiet && similar(quietMs, next.pendingQuiet, next.interval ? LOWER_SIMILAR : SIMILAR);
172
+ next.drops = confirming ? next.drops + 1 : 1;
173
+ // the shortest quiet time of the run of similar drops: the timer is at most that long
174
+ next.pendingQuiet = confirming ? Math.min(quietMs, next.pendingQuiet) : quietMs;
175
+ next.pendingAt = now;
176
+
177
+ if (next.drops >= (next.interval ? LOWER_CONFIRM_DROPS : CONFIRM_DROPS)) {
178
+ const candidate = Math.max(IMAP_MAX_IDLE_TIME_MIN, Math.floor(next.pendingQuiet * LEARN_RATIO));
179
+ if (!next.interval || candidate < next.interval) {
180
+ if (!next.interval) {
181
+ next.ageWhenLearned = ageMs;
182
+ }
183
+ next.interval = candidate;
184
+ // a relaxing step this undercuts is no longer the one to go back to
185
+ next.relaxedFrom = null;
186
+ }
187
+ clearPending(next);
188
+ }
189
+
190
+ return next;
191
+ }
192
+
193
+ /**
194
+ * A long session closing: evidence the interval works. Counts towards relaxing, and a session that
195
+ * ran a relaxed interval proves it, so later drops are no longer a reason to go back
196
+ * @param {Object} next - State, changed in place
197
+ * @param {Object} observation - `{ type: 'stable', ageMs, ranInterval }`
198
+ * @returns {Object} next
199
+ */
200
+ function observeStable(next, observation) {
201
+ if (!(observation.ageMs >= STABLE_SESSION)) {
202
+ return next;
203
+ }
204
+ clearPending(next);
205
+ clearEvidence(next);
206
+ if (next.interval) {
207
+ if (next.relaxedFrom && observation.ranInterval === next.interval) {
208
+ next.relaxedFrom = null;
209
+ }
210
+ next.stable++;
211
+ if (next.stable >= RELAX_AFTER) {
212
+ relax(next);
213
+ }
214
+ }
215
+ return next;
216
+ }
217
+
218
+ /**
219
+ * Counts one session of evidence for the cap or the relax-revert rule, sessions closer together
220
+ * than SAME_EVENT_WINDOW counting once
221
+ * @param {Object} next - State, changed in place
222
+ * @param {number} now
223
+ * @returns {boolean} Whether there is now enough to act on (the count is then reset)
224
+ */
225
+ function countEvidence(next, now) {
226
+ if (!(next.evidenceAt && now - next.evidenceAt < SAME_EVENT_WINDOW)) {
227
+ next.evidenceDrops++;
228
+ next.evidenceAt = now;
229
+ }
230
+ if (next.evidenceDrops < CONFIRM_DROPS) {
231
+ return false;
232
+ }
233
+ clearEvidence(next);
234
+ return true;
235
+ }
236
+
237
+ function clearEvidence(next) {
238
+ next.evidenceDrops = 0;
239
+ next.evidenceAt = 0;
240
+ }
241
+
242
+ function clearPending(next) {
243
+ next.drops = 0;
244
+ next.pendingQuiet = null;
245
+ next.pendingAt = 0;
246
+ }
247
+
248
+ /**
249
+ * The observation a closed primary connection makes, or null when its close says nothing about the
250
+ * server's timers (a close EmailEngine asked for, which ImapFlow reports as closedByClient, a
251
+ * connection that never got a socket)
252
+ * @param {Object} imapClient - The closed ImapFlow client
253
+ * @param {number} now - Epoch ms
254
+ * @returns {Object|null}
255
+ */
256
+ function observationFor(imapClient, now) {
257
+ if (!imapClient || imapClient.closedByClient || imapClient.context?.disabled || !imapClient.connectedAt) {
258
+ return null;
259
+ }
260
+ const ageMs = now - imapClient.connectedAt;
261
+ // ImapFlow's IDLE restart interval for this connection (ImapFlow keeps false for none)
262
+ const ranInterval = imapClient.maxIdleTime > 0 ? imapClient.maxIdleTime : null;
263
+ if (ageMs >= STABLE_SESSION) {
264
+ return { type: 'stable', ageMs, ranInterval };
265
+ }
266
+ if (!imapClient.lastClientWrite) {
267
+ return null;
268
+ }
269
+ return {
270
+ type: 'drop',
271
+ quietMs: now - imapClient.lastClientWrite,
272
+ ageMs,
273
+ idling: !!imapClient.idlingAtClose,
274
+ ranInterval
275
+ };
276
+ }
277
+
278
+ module.exports = { observe, observationFor, initialState, LEARN_CEILING, STABLE_SESSION, RELAX_AFTER, CAP_COOLDOWN, SAME_EVENT_WINDOW, PENDING_WINDOW };
@@ -49,4 +49,17 @@ function connectionUnavailableError() {
49
49
  return err;
50
50
  }
51
51
 
52
- module.exports = { connectionNotAvailableError, connectionClosedError, connectionUnavailableError };
52
+ /**
53
+ * Whether a failed FETCH in a sync loop ends the pass instead of being retried: the connection is
54
+ * no longer usable, or the folder the loop locked is no longer the one selected. ImapFlow used to
55
+ * answer a FETCH with no mailbox selected by returning no rows, which a full sync took for an empty
56
+ * folder; since 2.6.0 it throws NoMailboxSelected, and retrying would only throw it again
57
+ * @param {Object} imapClient - The connection the loop fetches on
58
+ * @param {Error} err - The FETCH failure
59
+ * @returns {boolean}
60
+ */
61
+ function syncInterrupted(imapClient, err) {
62
+ return !imapClient.usable || err?.code === 'NoMailboxSelected';
63
+ }
64
+
65
+ module.exports = { connectionNotAvailableError, connectionClosedError, connectionUnavailableError, syncInterrupted };
@@ -4,9 +4,10 @@
4
4
  * How often an IMAP connection restarts IDLE (ImapFlow's `maxIdleTime`) and which command keeps it
5
5
  * alive on a server without IDLE (`missingIdleCommand`).
6
6
  *
7
- * A few providers get a built-in value, and an account can set its own `imap.maxIdleTime` for a
8
- * server, or something in front of it, that drops a connection left idle for a few minutes without
9
- * sending BYE. The account value wins over the built-in one.
7
+ * A few providers get a built-in value, an interval learned from the host's dropped idle sessions
8
+ * (lib/email-client/imap/adaptive-idle.js) can shorten it, and an account can set its own
9
+ * `imap.maxIdleTime` for a server, or something in front of it, that drops a connection left idle
10
+ * for a few minutes without sending BYE. The account value wins over both.
10
11
  *
11
12
  * Kept free of connection and Redis code so the rules can be tested on their own.
12
13
  */
@@ -26,8 +27,9 @@ const PROVIDER_IDLE_SETTINGS = [
26
27
  * @param {Object} imapConfig - The ImapFlow config, modified in place
27
28
  * @param {Object} [accountImap] - The account's stored `imap` object. Read on its own because an
28
29
  * OAuth2 account builds its connection config without it
30
+ * @param {number} [learned] - The interval learned for the host, see adaptive-idle-store.js
29
31
  */
30
- function applyIdleSettings(imapConfig, accountImap) {
32
+ function applyIdleSettings(imapConfig, accountImap, learned) {
31
33
  const provider = PROVIDER_IDLE_SETTINGS.find(entry => entry.host.test(imapConfig.host || ''));
32
34
  if (provider) {
33
35
  imapConfig.maxIdleTime = provider.maxIdleTime;
@@ -36,9 +38,33 @@ function applyIdleSettings(imapConfig, accountImap) {
36
38
  }
37
39
  }
38
40
 
41
+ // What the drops of this host taught (lib/email-client/imap/adaptive-idle.js), only ever shorter
42
+ // than what would apply without it
43
+ if (learned > 0) {
44
+ imapConfig.maxIdleTime = imapConfig.maxIdleTime > 0 ? Math.min(imapConfig.maxIdleTime, learned) : learned;
45
+ }
46
+
47
+ // An interval the operator set for the account wins over anything learned
39
48
  if (accountImap?.maxIdleTime) {
40
49
  imapConfig.maxIdleTime = accountImap.maxIdleTime;
41
50
  }
42
51
  }
43
52
 
44
- module.exports = { applyIdleSettings };
53
+ // How long the command connection may sit unused before it closes itself (ImapFlow's socket
54
+ // inactivity timeout, answered by a quiet close and a reconnect on the next command)
55
+ const COMMAND_SOCKET_TIMEOUT = 60 * 1000;
56
+
57
+ /**
58
+ * Inactivity timeout for the command connection. That connection never IDLEs, so a server or a
59
+ * proxy in front of it that drops a session left quiet for less than a minute (TransIP's cuts one at
60
+ * 30 seconds, without BYE) used to tear it down from the other end, logged as a connection error.
61
+ * When an IDLE restart interval is set for the account or its provider, that is the time the server
62
+ * is known to tolerate, so the command connection closes itself by then instead
63
+ * @param {number} [maxIdleTime] - The connection's ImapFlow `maxIdleTime`
64
+ * @returns {number} Milliseconds
65
+ */
66
+ function commandSocketTimeout(maxIdleTime) {
67
+ return maxIdleTime > 0 ? Math.min(COMMAND_SOCKET_TIMEOUT, maxIdleTime) : COMMAND_SOCKET_TIMEOUT;
68
+ }
69
+
70
+ module.exports = { applyIdleSettings, commandSocketTimeout, COMMAND_SOCKET_TIMEOUT };
@@ -54,6 +54,40 @@ function configuredPathIndex(configuredPaths, entry) {
54
54
  return configuredPaths.findIndex(configuredPath => matchesListingEntry(configuredPath, entry));
55
55
  }
56
56
 
57
+ // On Gmail every label is a folder, and All Mail already holds every message that carries one.
58
+ // Watching every folder there would see each message once per label, so only All Mail, and the
59
+ // two folders whose messages All Mail leaves out, are synced when the account watches everything
60
+ const GMAIL_MONITORED_SPECIAL_USE = ['\\All', '\\Junk', '\\Trash'];
61
+
62
+ /**
63
+ * An account's `path` setting as a list, `*` (every folder) when it is unset or empty
64
+ *
65
+ * @param {Object} accountData - Stored account data
66
+ * @returns {Array} Configured selectors
67
+ */
68
+ function accountPathList(accountData) {
69
+ const accountPaths = [].concat((accountData && accountData.path) || '*');
70
+ return accountPaths.length ? accountPaths : ['*'];
71
+ }
72
+
73
+ /**
74
+ * Which listed folders an account syncs. The primary connection's setup and every later listing
75
+ * pass decide it for each folder they register, and used to carry a copy of the rule each
76
+ *
77
+ * @param {Array} accountPaths - From accountPathList()
78
+ * @param {Object} entry - Mailbox entry from the server listing
79
+ * @param {Boolean} isGmail - Whether the account is on Gmail (with All Mail listed)
80
+ * @returns {{monitored: Boolean, index: Number}} `index` is the position of the configured
81
+ * selector that picked the folder (see configuredPathIndex()), -1 when every folder is watched
82
+ */
83
+ function folderMonitoring(accountPaths, entry, isGmail) {
84
+ if (!accountPaths.includes('*')) {
85
+ const index = configuredPathIndex(accountPaths, entry);
86
+ return { monitored: index >= 0, index };
87
+ }
88
+ return { monitored: !isGmail || GMAIL_MONITORED_SPECIAL_USE.includes(entry.specialUse), index: -1 };
89
+ }
90
+
57
91
  /**
58
92
  * Decodes one msgpack-encoded entry of the stored mailbox listing hash, or returns false if the
59
93
  * value is unusable. Callers drop a false entry rather than failing: a single corrupt value must
@@ -199,6 +233,9 @@ function buildStoredListingObject(listing) {
199
233
  module.exports = {
200
234
  matchesListingEntry,
201
235
  configuredPathIndex,
236
+ accountPathList,
237
+ folderMonitoring,
238
+ GMAIL_MONITORED_SPECIAL_USE,
202
239
  decodeStoredMailboxEntry,
203
240
  decodeStoredListing,
204
241
  diffMailboxListing,