emailengine-app 2.85.0 → 2.87.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 (137) hide show
  1. package/.ncurc.js +24 -6
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +97 -0
  4. package/DOCKER_DEPLOYMENT.md +2 -1
  5. package/Dockerfile +16 -3
  6. package/ENVIRONMENT.md +139 -0
  7. package/README.md +5 -1
  8. package/config/default.toml +2 -0
  9. package/copy-static-files.sh +4 -2
  10. package/data/google-crawlers.json +1 -1
  11. package/data/public_suffix_list.dat +4 -3
  12. package/lib/account-assignment.js +19 -0
  13. package/lib/account.js +285 -195
  14. package/lib/api-error-codes.js +49 -0
  15. package/lib/api-reference/model.js +6 -1
  16. package/lib/api-routes/account-routes.js +91 -32
  17. package/lib/api-routes/blocklist-routes.js +68 -2
  18. package/lib/api-routes/delivery-test-routes.js +1 -1
  19. package/lib/api-routes/gateway-routes.js +82 -10
  20. package/lib/api-routes/index.js +4 -0
  21. package/lib/api-routes/license-routes.js +2 -2
  22. package/lib/api-routes/mailbox-routes.js +3 -3
  23. package/lib/api-routes/message-routes.js +15 -7
  24. package/lib/api-routes/oauth2-app-routes.js +15 -8
  25. package/lib/api-routes/outbox-routes.js +77 -66
  26. package/lib/api-routes/permission-map.js +55 -6
  27. package/lib/api-routes/scoped-routes.js +74 -0
  28. package/lib/api-routes/settings-routes.js +11 -4
  29. package/lib/api-routes/stats-routes.js +5 -1
  30. package/lib/api-routes/submit-routes.js +25 -5
  31. package/lib/api-routes/template-routes.js +7 -6
  32. package/lib/api-routes/token-routes.js +11 -5
  33. package/lib/api-routes/webhook-delivery-routes.js +262 -0
  34. package/lib/api-routes/webhook-route-routes.js +119 -4
  35. package/lib/calendar-event.js +81 -1
  36. package/lib/consts.js +38 -46
  37. package/lib/db.js +14 -6
  38. package/lib/delivery-error.js +6 -0
  39. package/lib/deprecations.js +270 -0
  40. package/lib/email-client/base-client.js +134 -158
  41. package/lib/email-client/fallback-poll.js +62 -0
  42. package/lib/email-client/gmail-client.js +59 -11
  43. package/lib/email-client/imap/adaptive-idle-store.js +73 -0
  44. package/lib/email-client/imap/adaptive-idle.js +278 -0
  45. package/lib/email-client/imap/connection-errors.js +14 -1
  46. package/lib/email-client/imap/idle-settings.js +31 -5
  47. package/lib/email-client/imap/listing-diff.js +37 -0
  48. package/lib/email-client/imap/mailbox.js +380 -227
  49. package/lib/email-client/imap/subconnection.js +7 -29
  50. package/lib/email-client/imap/sync-operations.js +220 -127
  51. package/lib/email-client/imap-client.js +227 -163
  52. package/lib/email-client/message-builder.js +14 -79
  53. package/lib/email-client/outlook-client.js +378 -338
  54. package/lib/email-client/smtp-pool-manager.js +16 -13
  55. package/lib/email-client/sync-state-fields.js +19 -0
  56. package/lib/encrypt.js +157 -41
  57. package/lib/enum-descriptions.js +3 -1
  58. package/lib/env-setting-overrides.js +288 -0
  59. package/lib/export-worker.js +751 -0
  60. package/lib/export.js +64 -15
  61. package/lib/field-usage.js +1 -1
  62. package/lib/gateway.js +17 -1
  63. package/lib/get-raw-email.js +35 -108
  64. package/lib/health.js +75 -0
  65. package/lib/lock-run.js +119 -0
  66. package/lib/logger-consts.js +48 -0
  67. package/lib/logger.js +1 -1
  68. package/lib/lua/z-head-scores.lua +28 -0
  69. package/lib/network-errors.js +1 -1
  70. package/lib/node-version.js +24 -0
  71. package/lib/notify-attachments.js +20 -1
  72. package/lib/oauth/gmail.js +54 -29
  73. package/lib/oauth2-apps.js +630 -655
  74. package/lib/otp.js +66 -0
  75. package/lib/outbox.js +184 -54
  76. package/lib/parse-message.js +3 -3
  77. package/lib/privileged-settings.js +2 -2
  78. package/lib/queue-browser/definitions.js +11 -0
  79. package/lib/queue-browser/index.js +68 -19
  80. package/lib/queue-job-actions.js +18 -1
  81. package/lib/queue-retention.js +48 -12
  82. package/lib/queue-stats.js +11 -2
  83. package/lib/read-env-value.js +3 -0
  84. package/lib/redis-memory-warnings.js +99 -0
  85. package/lib/redis-reconnect.js +29 -0
  86. package/lib/request-timing.js +23 -0
  87. package/lib/respawn-backoff.js +35 -0
  88. package/lib/rewrite-text-nodes.js +19 -59
  89. package/lib/schemas.js +225 -41
  90. package/lib/settings.js +6 -2
  91. package/lib/smtp-auth.js +19 -1
  92. package/lib/swagger-options.js +2 -2
  93. package/lib/thread-diagnostics.js +18 -1
  94. package/lib/tls/provision.js +6 -3
  95. package/lib/token-audit-log.js +19 -20
  96. package/lib/token-permission-view.js +4 -3
  97. package/lib/tools.js +8 -41
  98. package/lib/ui-routes/admin-config-routes.js +64 -90
  99. package/lib/ui-routes/admin-entities-routes.js +2 -14
  100. package/lib/ui-routes/imap-idle-field.js +1 -1
  101. package/lib/ui-routes/outlook-subscription-view.js +1 -1
  102. package/lib/ui-routes/overridable-fields.js +84 -0
  103. package/lib/ui-routes/queue-routes.js +8 -5
  104. package/lib/ui-routes/settings-page.js +6 -0
  105. package/lib/utils/decode-headers.js +3 -12
  106. package/lib/utils/filter-empty.js +20 -0
  107. package/lib/utils/int-setting.js +48 -0
  108. package/lib/utils/tracking-settings.js +35 -0
  109. package/lib/web-safe-html.js +18 -105
  110. package/lib/webhook-delivery.js +461 -0
  111. package/lib/webhook-failures.js +132 -0
  112. package/lib/webhook-request.js +29 -1
  113. package/lib/webhook-routing.js +30 -1
  114. package/lib/webhook-test.js +88 -0
  115. package/lib/webhooks.js +59 -41
  116. package/lib/worker-rpc-error.js +2 -1
  117. package/package.json +28 -26
  118. package/sbom.json +600 -678
  119. package/server.js +149 -76
  120. package/static/css/flyonui.css +1 -1
  121. package/static/js/ace/ace.js +1 -1
  122. package/static/js/ee-client.js +650 -196
  123. package/static/licenses.html +49 -59
  124. package/translations/messages.pot +26 -26
  125. package/views/config/security.hbs +22 -0
  126. package/views/config/service.hbs +44 -0
  127. package/views/config/webhooks.hbs +36 -0
  128. package/views/layout/app.hbs +9 -6
  129. package/views/legal.hbs +8 -0
  130. package/views/partials/queue_retention_note.hbs +12 -8
  131. package/views/partials/ui/env-managed-alert.hbs +16 -7
  132. package/workers/api.js +112 -37
  133. package/workers/export.js +16 -631
  134. package/workers/imap.js +13 -0
  135. package/workers/smtp.js +9 -11
  136. package/workers/webhooks.js +18 -432
  137. 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,8 +29,18 @@ 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');
43
+ const { getMessageOtp } = require('../otp');
34
44
 
35
45
  const MAX_GMAIL_BATCH_SIZE = 50;
36
46
 
@@ -99,9 +109,9 @@ function extractMessageIdHeader(raw) {
99
109
  const RENEW_WATCH_TTL = 60 * 60 * 1000; // 1h - how often to check if watch needs renewal
100
110
  const MIN_WATCH_TTL = 24 * 3600 * 1000; // 1day - minimum time before renewing watch
101
111
  // 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;
112
+ // EENGINE_GMAIL_FALLBACK_POLL_INTERVAL (a duration, or milliseconds) so integration tests can
113
+ // exercise the poller without waiting the full interval.
114
+ const { GMAIL_FALLBACK_POLL_INTERVAL: FALLBACK_POLLING_INTERVAL } = require('./fallback-poll');
105
115
 
106
116
  /*
107
117
  Gmail API implementation status:
@@ -276,6 +286,8 @@ class PageCursor {
276
286
  class GmailClient extends BaseClient {
277
287
  constructor(account, options) {
278
288
  super(account, options);
289
+ // what the AI summary's and the OTP-Token's authentication trust rule key on, see summaryProvider()
290
+ this.type = 'gmail';
279
291
 
280
292
  // A failed init() is scheduled again by the worker, see BaseClient.scheduleInitRetry()
281
293
  this.retriesInit = true;
@@ -476,7 +488,7 @@ class GmailClient extends BaseClient {
476
488
  let historyId = Number(profileRes?.historyId) || null;
477
489
  if (!accountData.googleHistoryId) {
478
490
  // set as initial
479
- await this.redis.hset(this.getAccountKey(), 'googleHistoryId', historyId.toString());
491
+ await this.redis.hSetExists(this.getAccountKey(), 'googleHistoryId', historyId.toString());
480
492
  accountData.googleHistoryId = historyId;
481
493
  this.logger.info({ msg: 'Re-set missing Google History ID', account: this.account, historyId });
482
494
  }
@@ -582,8 +594,30 @@ class GmailClient extends BaseClient {
582
594
  return true;
583
595
  }
584
596
 
585
- async currentState() {
586
- return (await this.redis.hget(this.getAccountKey(), 'state')) || 'disconnected';
597
+ /**
598
+ * Stops the account's Gmail Pub/Sub watch. Without this a deleted account's watch went on
599
+ * publishing every mailbox change to the topic until it lapsed, up to seven days later
600
+ * @returns {Promise<boolean>} True when a watch was stopped
601
+ */
602
+ async releaseRemoteResources() {
603
+ try {
604
+ // Most accounts have no watch to stop, which the one stored field tells without loading
605
+ // and decrypting the whole account
606
+ if (!(await this.accountObject.getStoredField('watchResponse'))) {
607
+ return false;
608
+ }
609
+ const accountData = await this.accountObject.loadAccountData(this.account, false);
610
+ if (!accountData._app?.pubSubApp || !accountData.watchResponse) {
611
+ return false;
612
+ }
613
+ await this.prepare();
614
+ await this.request(`${GMAIL_API_BASE}/gmail/v1/users/me/stop`, 'post', Buffer.alloc(0));
615
+ this.logger.info({ msg: 'Stopped Gmail pubsub watch', account: this.account });
616
+ return true;
617
+ } catch (err) {
618
+ this.logger.warn({ msg: 'Failed to stop Gmail pubsub watch', account: this.account, err });
619
+ return false;
620
+ }
587
621
  }
588
622
 
589
623
  async delete() {
@@ -891,6 +925,12 @@ class GmailClient extends BaseClient {
891
925
  let resultList = await Promise.allSettled(promises);
892
926
  for (let entry of resultList) {
893
927
  if (entry.status === 'rejected') {
928
+ if (isGmailNotFound(entry.reason)) {
929
+ // Deleted between the listing and this fetch. Skipped like a message that
930
+ // moved out of the page, instead of failing every other message on it
931
+ this.logger.debug({ msg: 'Listed message no longer exists', account: this.account, err: entry.reason });
932
+ continue;
933
+ }
894
934
  throw entry.reason;
895
935
  }
896
936
  if (entry.value) {
@@ -951,6 +991,8 @@ class GmailClient extends BaseClient {
951
991
  return {
952
992
  deleted: result && result.labelIds?.includes('TRASH'),
953
993
  moved: {
994
+ // the same shape IMAP and Graph answer with, deleteMessages() already named it
995
+ destination: SYSTEM_NAMES.TRASH,
954
996
  message: result.id
955
997
  }
956
998
  };
@@ -1594,7 +1636,7 @@ class GmailClient extends BaseClient {
1594
1636
  try {
1595
1637
  messageData = await this.request(`${GMAIL_API_BASE}/gmail/v1/users/me/messages/${emailId}`, 'get', { format: 'raw' });
1596
1638
  } catch (err) {
1597
- if (err?.oauthRequest?.status === 404 || err?.oauthRequest?.response?.error?.code === 404) {
1639
+ if (isGmailNotFound(err)) {
1598
1640
  let error = new Error('Requested message was not found');
1599
1641
  error.code = 'MessageNotFound';
1600
1642
  error.statusCode = 404;
@@ -2694,6 +2736,11 @@ class GmailClient extends BaseClient {
2694
2736
  result.isAutoReply = true;
2695
2737
  }
2696
2738
 
2739
+ const otp = getMessageOtp(result.headers, this.summaryProvider());
2740
+ if (otp) {
2741
+ result.otp = otp;
2742
+ }
2743
+
2697
2744
  // Set special-use based on labels
2698
2745
  for (let specialUseTag of ['\\Junk', '\\Sent', '\\Trash', '\\Inbox', '\\Drafts']) {
2699
2746
  if (result.labels && result.labels.includes(specialUseTag)) {
@@ -3212,7 +3259,7 @@ class GmailClient extends BaseClient {
3212
3259
  // advance the durable cursor once an entry is handled (processed or skipped)
3213
3260
  let advanceHistoryCursor = async historyEntryId => {
3214
3261
  if (historyEntryId && historyEntryId > lastHistoryId) {
3215
- await this.redis.hset(this.getAccountKey(), 'googleHistoryId', historyEntryId.toString());
3262
+ await this.redis.hSetExists(this.getAccountKey(), 'googleHistoryId', historyEntryId.toString());
3216
3263
  lastHistoryId = historyEntryId;
3217
3264
  }
3218
3265
  };
@@ -3303,7 +3350,7 @@ class GmailClient extends BaseClient {
3303
3350
  if (entry?.id) {
3304
3351
  // mark the entry as in flight before touching it, so a
3305
3352
  // worker death mid-entry is attributable on restart
3306
- await this.redis.hset(this.getAccountKey(), 'googleHistoryProcessing', JSON.stringify({ id: entry.id, count: attempts + 1 }));
3353
+ await this.redis.hSetExists(this.getAccountKey(), 'googleHistoryProcessing', JSON.stringify({ id: entry.id, count: attempts + 1 }));
3307
3354
  }
3308
3355
 
3309
3356
  try {
@@ -3343,7 +3390,7 @@ class GmailClient extends BaseClient {
3343
3390
 
3344
3391
  // Update to newest history ID
3345
3392
  if (newestHistoryId && newestHistoryId > currentHistoryId) {
3346
- await this.redis.hset(this.getAccountKey(), 'googleHistoryId', newestHistoryId.toString());
3393
+ await this.redis.hSetExists(this.getAccountKey(), 'googleHistoryId', newestHistoryId.toString());
3347
3394
  }
3348
3395
 
3349
3396
  // the run finished without dying, drop the in-flight marker
@@ -3447,6 +3494,7 @@ class GmailClient extends BaseClient {
3447
3494
  module.exports = {
3448
3495
  GmailClient,
3449
3496
  PageCursor,
3497
+ isGmailNotFound,
3450
3498
  SKIP_LABELS: Object.freeze([...SKIP_LABELS]),
3451
3499
  SYSTEM_LABELS: Object.freeze({ ...SYSTEM_LABELS }),
3452
3500
  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,