emailengine-app 2.81.1 → 2.82.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 (208) hide show
  1. package/.ncurc.js +12 -6
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +52 -0
  4. package/Dockerfile +4 -2
  5. package/bin/emailengine.js +28 -18
  6. package/config/default.toml +0 -5
  7. package/config/test.toml +0 -5
  8. package/data/google-crawlers.json +1 -1
  9. package/encrypt.js +70 -42
  10. package/getswagger.sh +0 -4
  11. package/lib/account/account-state.js +2 -110
  12. package/lib/account/bounce-store-sweep.js +63 -0
  13. package/lib/account/expected-identity.js +1 -1
  14. package/lib/account-assignment.js +207 -0
  15. package/lib/account.js +374 -878
  16. package/lib/api-reference/index.js +2 -3
  17. package/lib/api-reference/schema-tree.js +53 -3
  18. package/lib/api-routes/account-routes.js +18 -29
  19. package/lib/api-routes/blocklist-routes.js +2 -2
  20. package/lib/api-routes/bull-board-routes.js +1 -6
  21. package/lib/api-routes/export-routes.js +2 -22
  22. package/lib/api-routes/gateway-routes.js +5 -14
  23. package/lib/api-routes/index.js +1 -13
  24. package/lib/api-routes/mailbox-routes.js +2 -7
  25. package/lib/api-routes/mcp-oauth-routes.js +2 -1
  26. package/lib/api-routes/mcp-routes.js +7 -7
  27. package/lib/api-routes/message-routes.js +44 -236
  28. package/lib/api-routes/mint-bounds.js +110 -0
  29. package/lib/api-routes/oauth2-app-routes.js +23 -32
  30. package/lib/api-routes/operation-impact.js +1 -1
  31. package/lib/api-routes/outbox-routes.js +2 -2
  32. package/lib/api-routes/permission-map.js +1 -7
  33. package/lib/api-routes/route-helpers.js +11 -5
  34. package/lib/api-routes/settings-routes.js +19 -19
  35. package/lib/api-routes/stats-routes.js +1 -1
  36. package/lib/api-routes/submit-routes.js +17 -18
  37. package/lib/api-routes/template-routes.js +4 -9
  38. package/lib/api-routes/token-routes.js +27 -5
  39. package/lib/api-token-scheme.js +71 -0
  40. package/lib/arf-detect.js +41 -7
  41. package/lib/auth-token.js +44 -24
  42. package/lib/autodetect-imap-settings.js +163 -123
  43. package/lib/bounce-detect.js +25 -16
  44. package/lib/calendar-event.js +78 -0
  45. package/lib/consts.js +51 -5
  46. package/lib/create-imap-client.js +24 -0
  47. package/lib/db.js +76 -17
  48. package/lib/delivery-error.js +2 -1
  49. package/lib/egress-fetch.js +54 -3
  50. package/lib/egress-filter.js +11 -0
  51. package/lib/email-client/api-retry.js +147 -0
  52. package/lib/email-client/base-client.js +628 -615
  53. package/lib/email-client/gmail/gmail-api.js +38 -125
  54. package/lib/email-client/gmail/send-request.js +1 -1
  55. package/lib/email-client/gmail-client.js +170 -84
  56. package/lib/email-client/imap/mailbox.js +244 -535
  57. package/lib/email-client/imap/stale-view.js +109 -0
  58. package/lib/email-client/imap/subconnection.js +46 -9
  59. package/lib/email-client/imap/sync-operations.js +5 -37
  60. package/lib/email-client/imap-client.js +188 -64
  61. package/lib/email-client/message-builder.js +9 -14
  62. package/lib/email-client/notification-handler.js +5 -219
  63. package/lib/email-client/outlook/graph-api.js +147 -126
  64. package/lib/email-client/outlook/send-request.js +10 -4
  65. package/lib/email-client/outlook-client.js +519 -617
  66. package/lib/email-client/smtp-pool-manager.js +3 -2
  67. package/lib/encrypt.js +184 -19
  68. package/lib/enum-descriptions.js +1 -2
  69. package/lib/export.js +144 -41
  70. package/lib/gateway.js +20 -6
  71. package/lib/get-raw-email.js +26 -44
  72. package/lib/handlebars-helpers.js +31 -10
  73. package/lib/imap-proxy-auth.js +13 -29
  74. package/lib/imapproxy/imap-core/README.md +1 -0
  75. package/lib/imapproxy/imap-core/lib/handler/imap-parser.js +12 -0
  76. package/lib/imapproxy/imap-core/lib/imap-command.js +74 -10
  77. package/lib/imapproxy/imap-core/lib/imap-connection.js +9 -1
  78. package/lib/imapproxy/imap-core/lib/imap-server.js +112 -26
  79. package/lib/imapproxy/imap-core/lib/imap-stream.js +41 -1
  80. package/lib/imapproxy/imap-core/lib/imap-tools.js +10 -2
  81. package/lib/imapproxy/imap-core/lib/indexer/indexer.js +4 -2
  82. package/lib/imapproxy/imap-server.js +17 -177
  83. package/lib/imapproxy/proxy-handoff.js +235 -0
  84. package/lib/imapproxy/response-error.js +33 -0
  85. package/lib/imapproxy/upstream-client.js +2 -2
  86. package/lib/license-beacon.js +3 -9
  87. package/lib/llm-pre-process.js +182 -43
  88. package/lib/logger.js +1 -1
  89. package/lib/lua/ee-export-queue-add.lua +39 -0
  90. package/lib/lua/ee-get-idempotency.lua +15 -3
  91. package/lib/lua/ee-release-attempts.lua +23 -0
  92. package/lib/lua/ee-reserve-attempts.lua +42 -0
  93. package/lib/lua/h-set-bigger.lua +12 -2
  94. package/lib/lua/s-list-accounts.lua +6 -3
  95. package/lib/mcp/index.js +1 -2
  96. package/lib/mcp/listen.js +221 -18
  97. package/lib/mcp/oauth.js +44 -5
  98. package/lib/mcp/resources.js +8 -2
  99. package/lib/mcp/tools.js +13 -0
  100. package/lib/message-port-stream.js +64 -6
  101. package/lib/msgpack.js +1 -6
  102. package/lib/oauth/external-account-signer.js +16 -13
  103. package/lib/oauth/gmail.js +22 -20
  104. package/lib/oauth/outlook.js +19 -16
  105. package/lib/oauth/pubsub/google.js +38 -2
  106. package/lib/oauth/scope-checker.js +4 -7
  107. package/lib/oauth/verify-app.js +2 -2
  108. package/lib/oauth2-apps.js +139 -44
  109. package/lib/openapi/build-document.js +1 -1
  110. package/lib/openapi/joi-schema.js +78 -9
  111. package/lib/parse-message.js +21 -0
  112. package/lib/payload-examples-webhooks.json +4 -7
  113. package/lib/pbkdf2-phc.js +101 -0
  114. package/lib/privileged-settings.js +0 -14
  115. package/lib/rate-limit.js +54 -15
  116. package/lib/redis-scan-delete.js +56 -29
  117. package/lib/redis-url.js +3 -1
  118. package/lib/respawn-backoff.js +5 -4
  119. package/lib/response-stream.js +25 -4
  120. package/lib/rewrite-text-nodes.js +27 -40
  121. package/lib/routes-ui.js +0 -5
  122. package/lib/schemas.js +129 -262
  123. package/lib/sentry.js +21 -5
  124. package/lib/settings.js +58 -59
  125. package/lib/smtp-auth.js +6 -2
  126. package/lib/smtp-message-processor.js +28 -7
  127. package/lib/sso.js +7 -3
  128. package/lib/stream-encrypt.js +14 -13
  129. package/lib/swagger-options.js +3 -1
  130. package/lib/tls/provision.js +69 -3
  131. package/lib/tls/store.js +14 -1
  132. package/lib/tools.js +113 -52
  133. package/lib/totp.js +16 -1
  134. package/lib/ui-routes/account-routes.js +27 -63
  135. package/lib/ui-routes/admin-config-routes.js +111 -134
  136. package/lib/ui-routes/admin-entities-routes.js +101 -191
  137. package/lib/ui-routes/ai-options.js +104 -0
  138. package/lib/ui-routes/auth-routes.js +98 -18
  139. package/lib/ui-routes/export-routes.js +3 -23
  140. package/lib/ui-routes/internals-routes.js +12 -9
  141. package/lib/ui-routes/network-config-routes.js +8 -18
  142. package/lib/ui-routes/oauth-config-routes.js +80 -214
  143. package/lib/ui-routes/route-helpers.js +40 -44
  144. package/lib/ui-routes/unsubscribe-routes.js +2 -2
  145. package/lib/utils/decode-headers.js +32 -5
  146. package/lib/utils/header-map.js +62 -1
  147. package/lib/utils/network.js +2 -0
  148. package/lib/web-safe-html.js +77 -4
  149. package/lib/webhook-request.js +9 -1
  150. package/lib/webhook-routing.js +27 -1
  151. package/lib/webhooks.js +120 -43
  152. package/lib/worker-rpc-error.js +43 -2
  153. package/list-generate.js +13 -2
  154. package/package.json +38 -46
  155. package/sbom.json +1 -1
  156. package/scripts/refresh-test-tokens.js +42 -14
  157. package/server.js +340 -336
  158. package/static/css/flyonui.css +1 -1
  159. package/static/css/src/app.tailwind.css +7 -8
  160. package/static/js/ee-client.js +145 -70
  161. package/static/js/ui.js +350 -154
  162. package/static/licenses.html +460 -1861
  163. package/translations/messages.pot +99 -99
  164. package/views/accounts/browse.hbs +10 -4
  165. package/views/config/ai.hbs +49 -41
  166. package/views/config/oauth/app.hbs +2 -1
  167. package/views/dashboard.hbs +18 -16
  168. package/views/layout/app.hbs +0 -22
  169. package/views/layout/login.hbs +2 -1
  170. package/views/partials/filter_editor_js.hbs +4 -3
  171. package/views/partials/side_menu.hbs +0 -4
  172. package/views/partials/ui/account-picker.hbs +6 -32
  173. package/views/partials/ui/model-picker.hbs +31 -0
  174. package/views/partials/ui/pagination.hbs +6 -1
  175. package/views/partials/ui/picker.hbs +47 -0
  176. package/views/unsubscribe.hbs +1 -1
  177. package/workers/api.js +33 -23
  178. package/workers/export.js +55 -60
  179. package/workers/imap.js +134 -47
  180. package/workers/submit.js +3 -1
  181. package/workers/webhooks.js +46 -27
  182. package/.githooks/pre-commit +0 -80
  183. package/.github/CODE_OF_CONDUCT.md +0 -76
  184. package/.github/contributing.md +0 -17
  185. package/.github/dependabot.yml +0 -22
  186. package/.github/docker-smoke-test.sh +0 -61
  187. package/.github/workflows/deploy.yml +0 -215
  188. package/.github/workflows/e2e.yml +0 -55
  189. package/.github/workflows/release.yaml +0 -217
  190. package/.github/workflows/test.yml +0 -307
  191. package/lib/api-routes/chat-routes.js +0 -535
  192. package/lib/append-list.js +0 -63
  193. package/lib/document-store.js +0 -75
  194. package/lib/es.js +0 -757
  195. package/lib/generate-text-preview.js +0 -61
  196. package/lib/imapproxy/imap-core/memory-notifier.js +0 -129
  197. package/lib/lua/h-push.lua +0 -32
  198. package/lib/pre-process.js +0 -196
  199. package/lib/threads.js +0 -155
  200. package/lib/ui-routes/document-store-routes.js +0 -806
  201. package/playwright.config.js +0 -47
  202. package/views/config/document-store/chat.hbs +0 -286
  203. package/views/config/document-store/index.hbs +0 -146
  204. package/views/config/document-store/mappings/index.hbs +0 -108
  205. package/views/config/document-store/mappings/new.hbs +0 -68
  206. package/views/config/document-store/pre-processing/index.hbs +0 -103
  207. package/views/partials/document_store_header.hbs +0 -30
  208. package/workers/documents.js +0 -1128
@@ -0,0 +1,109 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Decisions for the stale view check of the main mailbox (EENGINE_IMAP_STALE_CHECK_INTERVAL).
5
+ *
6
+ * Some servers keep a long-lived session healthy on the wire - IDLE, NOOP, LIST and STATUS of
7
+ * other folders all answer OK - while the session's view of the selected mailbox stops moving.
8
+ * No EXISTS arrives, and a FETCH or SEARCH on that connection answers from the frozen view, so
9
+ * nothing the primary connection can do reveals it. A new session sees the messages, which is
10
+ * why the check asks a second connection and why the only remedy is reconnecting.
11
+ *
12
+ * Kept free of connection and Redis code so the rules can be tested on their own.
13
+ */
14
+
15
+ // A probe that finds the server ahead has to be confirmed by the next one before the primary
16
+ // connection is dropped. A message that landed just before the probe is normally still on its
17
+ // way through EXISTS and the partial sync it triggers, and the next probe no longer sees it
18
+ const STALE_CONFIRMATIONS = 2;
19
+
20
+ /**
21
+ * What the primary connection knows of the main mailbox's UIDNEXT: the higher of the stored value
22
+ * and the one its session reports. Neither is enough alone. A partial sync stores the snapshot it
23
+ * took before fetching, while ImapFlow moves the session's UIDNEXT once a FETCH returns a newer
24
+ * UID, so the stored value trails a healthy session by one fetch. And a message delivered and
25
+ * expunged before the primary fetched it leaves the stored value behind the server's for good on
26
+ * a CONDSTORE server whose HIGHESTMODSEQ did not move, while the SELECT of the next session reports
27
+ * the server's value. A frozen session's UIDNEXT is as frozen as the rest of its view
28
+ * @param {Number|false} storedUidNext - uidNext the sync state machine last stored
29
+ * @param {Number|false} sessionUidNext - UIDNEXT the primary connection's session reports
30
+ * @returns {Number|false} The known UIDNEXT, false when neither is available
31
+ */
32
+ function knownUidNext(storedUidNext, sessionUidNext) {
33
+ const values = [storedUidNext, sessionUidNext].filter(value => typeof value === 'number' && value > 0);
34
+ return values.length ? Math.max(...values) : false;
35
+ }
36
+
37
+ // Fresh state: the quiet period starts at `now` from this UIDNEXT
38
+ const baseline = (now, uidNext) => ({ checkedAt: now, uidNext, confirmations: 0 });
39
+
40
+ /**
41
+ * Decides whether this resync pass should look at the main mailbox over a second connection.
42
+ * Only a connection whose known UIDNEXT has not moved for a whole interval is probed, so an
43
+ * account that keeps receiving mail never pays for the extra login
44
+ * @param {Object|null} state - State returned by the previous call on this connection, or null
45
+ * @param {Number|false} uidNext - Known UIDNEXT of the main mailbox, see knownUidNext()
46
+ * @param {Number} now - Current time in milliseconds
47
+ * @param {Number} interval - Quiet period before probing, in milliseconds. Falsy disables the check
48
+ * @returns {{ probe: Boolean, state: Object|null }} Whether to probe, and the state to keep
49
+ */
50
+ function planStaleViewProbe(state, uidNext, now, interval) {
51
+ if (!interval || !uidNext) {
52
+ // Disabled, or a server that reports no UIDNEXT - there is nothing to compare against
53
+ return { probe: false, state: null };
54
+ }
55
+
56
+ if (!state || state.uidNext !== uidNext) {
57
+ // First pass on this connection, or something arrived since the last look. Either way
58
+ // it is not stale, and the quiet period starts over
59
+ return { probe: false, state: baseline(now, uidNext) };
60
+ }
61
+
62
+ if (now - state.checkedAt < interval) {
63
+ return { probe: false, state };
64
+ }
65
+
66
+ // The clock restarts as the probe is decided, not when it answers: a probe that fails (the
67
+ // second login refused, another folder open on the primary) must wait out a whole interval
68
+ // like any other, not log in again on the next resync pass
69
+ return { probe: true, state: Object.assign({}, state, { checkedAt: now }) };
70
+ }
71
+
72
+ /**
73
+ * Compares the STATUS answer of a second connection with what the primary connection knows
74
+ * @param {Object} state - State returned by planStaleViewProbe() for the pass that probed
75
+ * @param {Object} known - { uidNext, uidValidity } the primary knows, read after the probe answered
76
+ * @param {Object|null} serverStatus - STATUS answer (uidNext, uidValidity) from the second connection
77
+ * @param {Number} now - Current time in milliseconds
78
+ * @returns {{ stale: Boolean, ahead: Boolean, state: Object|null }} Whether to drop the primary
79
+ * connection, whether this probe found the server ahead, and the state to keep
80
+ */
81
+ function evaluateStaleViewProbe(state, known, serverStatus, now) {
82
+ if (!known.uidNext) {
83
+ return { stale: false, ahead: false, state: null };
84
+ }
85
+
86
+ if (!state || state.uidNext !== known.uidNext) {
87
+ // Something arrived on the primary connection while the probe was running - it is alive
88
+ return { stale: false, ahead: false, state: baseline(now, known.uidNext) };
89
+ }
90
+
91
+ const ahead =
92
+ typeof serverStatus?.uidNext === 'number' &&
93
+ serverStatus.uidNext > known.uidNext &&
94
+ // A different UIDVALIDITY is another folder incarnation, which the open handler deals
95
+ // with - UIDs of two incarnations say nothing about each other
96
+ !!known.uidValidity &&
97
+ known.uidValidity === serverStatus.uidValidity;
98
+
99
+ const confirmations = ahead ? state.confirmations + 1 : 0;
100
+ const stale = confirmations >= STALE_CONFIRMATIONS;
101
+
102
+ return {
103
+ stale,
104
+ ahead,
105
+ state: { checkedAt: now, uidNext: known.uidNext, confirmations: stale ? 0 : confirmations }
106
+ };
107
+ }
108
+
109
+ module.exports = { knownUidNext, planStaleViewProbe, evaluateStaleViewProbe, STALE_CONFIRMATIONS };
@@ -1,6 +1,6 @@
1
1
  'use strict';
2
2
 
3
- const { ImapFlow } = require('imapflow');
3
+ const { createImapClient } = require('../../create-imap-client');
4
4
  const { backOff } = require('exponential-backoff');
5
5
  const { ReconnectBackoff } = require('../reconnect-backoff');
6
6
  const { detachImapClient } = require('./detach-client');
@@ -92,12 +92,23 @@ class Subconnection extends EventEmitter {
92
92
  return false;
93
93
  }
94
94
 
95
- await backOff(() => this.start(), {
96
- maxDelay: this.reconnectBackoff.maxDelay,
97
- numOfAttempts: Infinity,
98
- retry: () => !this.isClosing && !this.isClosed,
99
- startingDelay: 2000
100
- });
95
+ try {
96
+ await backOff(() => this.start(), {
97
+ maxDelay: this.reconnectBackoff.maxDelay,
98
+ numOfAttempts: Infinity,
99
+ // A refused credential is not retried here: every subconnection would repeat
100
+ // the failed login every 30 seconds for the whole auth-failure park window
101
+ // (lockout and fail2ban territory). The primary connection owns that retry
102
+ retry: err => !this.isClosing && !this.isClosed && !isRefusedImapLogin(err),
103
+ startingDelay: 2000
104
+ });
105
+ } catch (err) {
106
+ if (!isRefusedImapLogin(err) || this.isClosing || this.isClosed) {
107
+ throw err;
108
+ }
109
+ this.disableAfterRefusedLogin();
110
+ return false;
111
+ }
101
112
  } finally {
102
113
  // Cleared before the mailbox validation below on purpose: if the
103
114
  // server drops the connection while the monitored mailbox is being
@@ -174,6 +185,25 @@ class Subconnection extends EventEmitter {
174
185
  }
175
186
  }
176
187
 
188
+ /**
189
+ * Shuts the subconnection down after the server refused its credential. The entry stays
190
+ * disabled until the parent reconciles its subconnections again (on the next primary
191
+ * connection setup, or the next resync pass through the loginRefused marker), which then
192
+ * replaces it with a fresh connection
193
+ */
194
+ disableAfterRefusedLogin() {
195
+ this.logger.warn({ msg: 'Subconnection login was refused, leaving the retry to the primary connection', path: this.path });
196
+
197
+ this.close();
198
+ this.imapClient = null;
199
+
200
+ // close() resets these, so set the disabled state afterwards
201
+ this.disabled = true;
202
+ this.state = 'authenticationError';
203
+ this.disabledReason = 'Authentication failed';
204
+ this.loginRefused = true;
205
+ }
206
+
177
207
  async start() {
178
208
  if (this.imapClient) {
179
209
  // close previous
@@ -201,7 +231,7 @@ class Subconnection extends EventEmitter {
201
231
  // this context
202
232
  let imapConfig = await this.parent.getImapConfig(null, this);
203
233
 
204
- let imapClient = new ImapFlow(
234
+ let imapClient = createImapClient(
205
235
  Object.assign({}, imapConfig, {
206
236
  logger: this.logger,
207
237
  expungeHandler: async payload => await this.expungeHandler(payload)
@@ -215,7 +245,14 @@ class Subconnection extends EventEmitter {
215
245
  imapClient.subConnection = true;
216
246
 
217
247
  imapClient.on('error', err => {
218
- imapClient?.log.warn({ msg: 'IMAP connection error', account: this.account, err });
248
+ if (!imapClient) {
249
+ // The close handler already let go of this client. The missing-mailbox and
250
+ // refused-login shutdowns also null this.imapClient, so the identity check below
251
+ // would read null === null as "still current" and call close() on null
252
+ this.logger.warn({ msg: 'IMAP connection error', account: this.account, err });
253
+ return;
254
+ }
255
+ imapClient.log.warn({ msg: 'IMAP connection error', account: this.account, err });
219
256
  if (imapClient !== this.imapClient || this._connecting) {
220
257
  return;
221
258
  }
@@ -66,7 +66,10 @@ function isRecentFullSync(storedStatus) {
66
66
  * @returns {Boolean} True if UIDVALIDITY changed
67
67
  */
68
68
  function hasUidValidityChanged(storedStatus, mailboxStatus) {
69
- return validUidValidity(storedStatus.uidValidity) && mailboxStatus.uidValidity !== storedStatus.uidValidity;
69
+ // Both sides have to be real values. mailboxStatusFromInfo() reports a missing or malformed
70
+ // UIDVALIDITY in the SELECT answer as false, and reading that as a change wiped the folder
71
+ // index and sent mailboxReset over what is only a non-compliant response
72
+ return validUidValidity(storedStatus.uidValidity) && validUidValidity(mailboxStatus.uidValidity) && mailboxStatus.uidValidity !== storedStatus.uidValidity;
70
73
  }
71
74
 
72
75
  /**
@@ -196,42 +199,6 @@ class SyncOperations {
196
199
  return this.runPartialSync();
197
200
  }
198
201
 
199
- /**
200
- * Determines the appropriate sync strategy based on mailbox state
201
- * @param {Object} storedStatus - Stored mailbox status
202
- * @param {Object} mailboxStatus - Current mailbox status from IMAP
203
- * @returns {Object} Sync decision with type and reason
204
- */
205
- determineSyncStrategy(storedStatus, mailboxStatus) {
206
- // No changes if MODSEQ hasn't changed
207
- if (hasNoModseqChanges(storedStatus, mailboxStatus)) {
208
- return { type: 'none', reason: 'modseq_unchanged' };
209
- }
210
-
211
- // No changes if mailbox is empty
212
- if (storedStatus.messages === 0 && mailboxStatus.messages === 0) {
213
- return { type: 'none', reason: 'empty_mailbox' };
214
- }
215
-
216
- // Partial sync if CONDSTORE indicates only new messages or flag changes
217
- if (canUseCondstorePartialSync(this.connection.imapClient, storedStatus, mailboxStatus)) {
218
- return { type: 'partial', reason: 'condstore_changes' };
219
- }
220
-
221
- // Partial sync if only new messages
222
- if (canUseSimplePartialSync(storedStatus, mailboxStatus)) {
223
- return { type: 'partial', reason: 'new_messages_only' };
224
- }
225
-
226
- // Skip if nothing changed and recent full sync
227
- if (canSkipSync(storedStatus, mailboxStatus)) {
228
- return { type: 'none', reason: 'recent_full_sync' };
229
- }
230
-
231
- // Full sync for all other cases
232
- return { type: 'full', reason: 'changes_detected' };
233
- }
234
-
235
202
  /**
236
203
  * Rebuilds the mailbox baseline from the server's current state WITHOUT emitting
237
204
  * messageNew notifications. Used when the stored sync state was lost (e.g. Redis evicted
@@ -965,6 +932,7 @@ class SyncOperations {
965
932
 
966
933
  module.exports = {
967
934
  SyncOperations,
935
+ checkFetchRetryTimeout,
968
936
  getFetchRange,
969
937
  isRecentFullSync,
970
938
  hasUidValidityChanged,
@@ -1,7 +1,7 @@
1
1
  'use strict';
2
2
 
3
3
  const { parentPort } = require('worker_threads');
4
- const { ImapFlow } = require('imapflow');
4
+ 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');
@@ -19,6 +19,7 @@ const { detachImapClient } = require('./imap/detach-client');
19
19
  const { connectionNotAvailableError, connectionUnavailableError } = require('./imap/connection-errors');
20
20
  const { ReconnectBackoff } = require('./reconnect-backoff');
21
21
  const { isRefusedImapLogin, imapResponseText } = require('./imap/login-failure');
22
+ const { knownUidNext, planStaleViewProbe, evaluateStaleViewProbe } = require('./imap/stale-view');
22
23
 
23
24
  const {
24
25
  normalizePath,
@@ -39,6 +40,10 @@ const RESYNC_DELAY = 15 * 60;
39
40
  // TTL for ensuring main mailbox selection after operations (5 seconds)
40
41
  const ENSURE_MAIN_TTL = 5 * 1000;
41
42
 
43
+ // Consecutive failed resync passes retried on the short backoff before falling back to the
44
+ // regular resync interval
45
+ const RESYNC_FAST_RETRIES = 5;
46
+
42
47
  const {
43
48
  AUTH_ERROR_NOTIFY,
44
49
  CONNECT_ERROR_NOTIFY,
@@ -55,11 +60,14 @@ const DOWNLOAD_CHUNK_SIZE = getByteSize(readEnvValue('EENGINE_CHUNK_SIZE')) || D
55
60
  const DISABLE_IMAP_COMPRESSION = getBoolean(readEnvValue('EENGINE_DISABLE_COMPRESSION'));
56
61
  // Custom socket timeout for IMAP connections
57
62
  const IMAP_SOCKET_TIMEOUT = getDuration(readEnvValue('EENGINE_IMAP_SOCKET_TIMEOUT'));
63
+ // How long the main mailbox may stay quiet before a second connection checks the primary's view
64
+ // of it, see checkStaleMainView(). Disabled when not set
65
+ const IMAP_STALE_CHECK_INTERVAL = getDuration(readEnvValue('EENGINE_IMAP_STALE_CHECK_INTERVAL'));
58
66
 
59
67
  // Gmail API configuration
60
68
  const GMAIL_API_BASE = 'https://gmail.googleapis.com';
61
69
 
62
- logger.trace({ msg: 'Worker configuration', DOWNLOAD_CHUNK_SIZE, DISABLE_IMAP_COMPRESSION, IMAP_SOCKET_TIMEOUT });
70
+ logger.trace({ msg: 'Worker configuration', DOWNLOAD_CHUNK_SIZE, DISABLE_IMAP_COMPRESSION, IMAP_SOCKET_TIMEOUT, IMAP_STALE_CHECK_INTERVAL });
63
71
 
64
72
  const settings = require('../settings');
65
73
  const { redis } = require('../db');
@@ -118,13 +126,11 @@ class IMAPClient extends BaseClient {
118
126
  // Map of normalized mailbox paths to Mailbox instances
119
127
  this.mailboxes = new Map();
120
128
 
121
- // Timer for handling untagged EXPUNGE responses
122
- this.untaggedExpungeTimer = false;
123
-
124
- // Timer for periodic mailbox listing refresh
125
- this.refreshListingTimer = false;
126
129
  // Timer for periodic mailbox resynchronization
127
130
  this.resyncTimer = false;
131
+ // Retry backoff of a failed resync pass (scheduleResync()): 4, 8, 16 seconds, then the
132
+ // 30 second cap
133
+ this.resyncBackoff = new ReconnectBackoff({ baseDelay: 4000, maxDelay: 30000, factor: 2 });
128
134
 
129
135
  // Timer to ensure we return to the main mailbox after operations
130
136
  this.completedTimer = false;
@@ -155,6 +161,10 @@ class IMAPClient extends BaseClient {
155
161
  // as an operator-requested one, skip its refresh
156
162
  this.listedClient = null;
157
163
 
164
+ // Stale view check of the main mailbox: the id of the primary connection it describes, its
165
+ // jittered interval and the state stale-view.js carries between passes. See checkStaleMainView()
166
+ this.staleView = null;
167
+
158
168
  // Flag indicating if mailbox synchronization is in progress
159
169
  this.syncing = false;
160
170
 
@@ -375,7 +385,7 @@ class IMAPClient extends BaseClient {
375
385
  let imapConfig = await this.getImapConfig(accountData);
376
386
 
377
387
  // Create new IMAP connection with specific settings for command operations
378
- let commandClient = new ImapFlow(
388
+ let commandClient = createImapClient(
379
389
  Object.assign({}, imapConfig, {
380
390
  disableAutoIdle: true, // Don't automatically IDLE on this connection
381
391
  id: commandCid,
@@ -400,9 +410,17 @@ class IMAPClient extends BaseClient {
400
410
  const onErr = err => {
401
411
  // Idle timeout (ETIMEOUT) is expected - the command client has no keepalive
402
412
  const logLevel = err.code === 'ETIMEOUT' ? 'debug' : 'warn';
403
- commandClient?.log[logLevel]({ msg: 'IMAP connection error', cid: commandCid, channel: 'command', account: this.account, err });
413
+ if (!commandClient) {
414
+ // the close handler already let go of this client
415
+ return;
416
+ }
417
+ commandClient.log[logLevel]({ msg: 'IMAP connection error', cid: commandCid, channel: 'command', account: this.account, err });
404
418
  commandClient.close();
405
- this.commandClient = null;
419
+ // A late event from a replaced client must not drop the reference to its successor,
420
+ // which would then stay open until its own socket timeout
421
+ if (this.commandClient === commandClient) {
422
+ this.commandClient = null;
423
+ }
406
424
  };
407
425
  commandClient.on('error', onErr);
408
426
 
@@ -427,7 +445,9 @@ class IMAPClient extends BaseClient {
427
445
  this.logger.error({ msg: 'Error in command client close handler', cid: commandCid, account: this.account, err });
428
446
  }
429
447
 
430
- this.commandClient = null;
448
+ if (this.commandClient === commandClient) {
449
+ this.commandClient = null;
450
+ }
431
451
  detachImapClient(commandClient, this.logger, { type: 'commandClient', cid: commandCid, account: this.account });
432
452
  commandClient = null;
433
453
  });
@@ -1270,26 +1290,12 @@ class IMAPClient extends BaseClient {
1270
1290
  // ended in an unconncted state
1271
1291
  this.logger.warn({ msg: 'Failed to set up connection, will retry', err });
1272
1292
 
1273
- // Calculate delay with capped exponential backoff
1274
- const retryDelay = this.reconnectBackoff.nextDelay();
1275
-
1276
- this.logger.info({
1277
- msg: 'Scheduling reconnection attempt',
1278
- attempt: this.reconnectBackoff.attempts,
1279
- delay: retryDelay
1280
- });
1281
-
1282
- return setTimeout(() => {
1283
- // The backoff counter is reset after a successful sync, not here -
1284
- // reconnect() also resolves when the setup failed and was rescheduled
1285
- this.reconnect().catch(err => {
1286
- this.logger.warn({
1287
- msg: 'Connection retry failed',
1288
- err,
1289
- attempt: this.reconnectBackoff.attempts
1290
- });
1291
- });
1292
- }, retryDelay);
1293
+ // Through the shared reconnectTimer slot: a bare timer here was neither debounced
1294
+ // against the close handler's own retry (two start() calls, the second tearing down
1295
+ // the healthy connection the first made) nor cleared by close()/pause(), so it
1296
+ // survived a pause and tore down the resumed connection
1297
+ this.scheduleReconnect(this.reconnectBackoff, 'Scheduling reconnection attempt');
1298
+ return;
1293
1299
  }
1294
1300
 
1295
1301
  this.logger.debug({
@@ -1306,7 +1312,6 @@ class IMAPClient extends BaseClient {
1306
1312
  */
1307
1313
  async syncMailboxes() {
1308
1314
  // Clear any pending timers
1309
- clearTimeout(this.untaggedExpungeTimer);
1310
1315
  clearTimeout(this.resyncTimer);
1311
1316
  clearTimeout(this.completedTimer);
1312
1317
 
@@ -1404,8 +1409,12 @@ class IMAPClient extends BaseClient {
1404
1409
  // setupSubConnections() is otherwise only invoked from start(), so on
1405
1410
  // a stable long-lived connection a re-created folder would never get
1406
1411
  // its subconnection back. Permanently disabled placeholders (covered
1407
- // by the primary connection etc.) are left alone
1408
- if (this.subconnections.some(subconnection => subconnection.mailboxMissing && this.hasListedMailbox(subconnection.path))) {
1412
+ // by the primary connection etc.) are left alone. A subconnection whose login was
1413
+ // refused is revived here too: it stops retrying on its own, so this pass (once per
1414
+ // resync interval) is its slow retry
1415
+ if (
1416
+ this.subconnections.some(subconnection => subconnection.loginRefused || (subconnection.mailboxMissing && this.hasListedMailbox(subconnection.path)))
1417
+ ) {
1409
1418
  this.setupSubConnections()
1410
1419
  .then(result => {
1411
1420
  this.logger.info({ msg: 'Reconciled subconnections after a folder change', account: this.account, result });
@@ -1428,26 +1437,141 @@ class IMAPClient extends BaseClient {
1428
1437
  // start waiting for changes
1429
1438
  await this.select(mainPath);
1430
1439
 
1431
- // Schedule next sync cycle
1432
- let retryCount = 0;
1433
- let setSyncTimer = () => {
1434
- clearTimeout(this.resyncTimer);
1435
- this.resyncTimer = setTimeout(() => {
1436
- this.syncMailboxes()
1437
- .then(() => {
1438
- // Reset retry count on successful sync
1439
- retryCount = 0;
1440
- })
1441
- .catch(err => {
1442
- retryCount++;
1443
- // Exponential backoff with max delay of 30 seconds
1444
- const retryDelay = Math.min(30000, 2000 * Math.pow(2, retryCount));
1445
- this.logger.warn({ msg: 'Failed to sync mailboxes, will retry', err, retryCount, retryDelay });
1446
- setTimeout(setSyncTimer, retryDelay);
1447
- });
1448
- }, this.resyncDelay);
1440
+ // Schedule next sync cycle. The pass completed, so a retry streak is over
1441
+ this.resyncBackoff.reset();
1442
+ this.scheduleResync(this.resyncDelay);
1443
+
1444
+ // The walk above skips the main mailbox, the selected one, whose changes only arrive
1445
+ // through the primary connection. A failed check is not a failed pass
1446
+ try {
1447
+ await this.checkStaleMainView();
1448
+ } catch (err) {
1449
+ this.logger.warn({ msg: 'Failed to check the main mailbox view', account: this.account, err });
1450
+ }
1451
+ }
1452
+
1453
+ /**
1454
+ * Checks that the primary connection still sees what the server holds in the main mailbox,
1455
+ * and drops the connection when it does not (EENGINE_IMAP_STALE_CHECK_INTERVAL, off by default).
1456
+ *
1457
+ * Some servers keep a long-lived session alive - IDLE, NOOP, LIST and STATUS of other folders
1458
+ * all answer OK - while its view of the selected mailbox stops moving, so the account reports
1459
+ * "connected" and receives nothing until it reconnects. Nothing on that connection reveals it,
1460
+ * so once the primary has seen nothing new in the main mailbox for the interval, the command
1461
+ * connection asks for its STATUS. A UIDNEXT ahead of what the primary knows on two probes in a
1462
+ * row closes the primary connection, and the close handler reconnects it like any dropped
1463
+ * connection. The decisions live in stale-view.js
1464
+ */
1465
+ async checkStaleMainView() {
1466
+ if (!IMAP_STALE_CHECK_INTERVAL || !this.main) {
1467
+ return;
1468
+ }
1469
+
1470
+ const imapClient = this.imapClient;
1471
+ const mailbox = this.mailboxes.get(normalizePath(this.main.path));
1472
+ if (!imapClient || !imapClient.usable || !mailbox || mailbox.syncDisabled) {
1473
+ return;
1474
+ }
1475
+
1476
+ // What the primary knows of the main mailbox, see knownUidNext(). Only while it is the
1477
+ // folder open there: otherwise getMailboxStatus() throws, and the next pass looks again
1478
+ const readKnown = async () => {
1479
+ if (this.imapClient !== imapClient || !imapClient.usable || !mailbox.isSelected()) {
1480
+ return null;
1481
+ }
1482
+ const storedStatus = await mailbox.getStoredStatus();
1483
+ const sessionStatus = mailbox.getMailboxStatus(imapClient);
1484
+ return {
1485
+ uidNext: knownUidNext(storedStatus.uidNext, sessionStatus.uidNext),
1486
+ uidValidity: storedStatus.uidValidity,
1487
+ storedUidNext: storedStatus.uidNext,
1488
+ sessionUidNext: sessionStatus.uidNext
1489
+ };
1449
1490
  };
1450
- setSyncTimer();
1491
+
1492
+ // The state belongs to one connection, a reconnect starts the quiet period over. Keyed on
1493
+ // the connection id, so a dropped client is not kept alive by it. Each connection stretches
1494
+ // the interval by up to a quarter at random: a worker restart connects every account within
1495
+ // minutes, and without it their probes would all fall due in the same resync window
1496
+ if (!this.staleView || this.staleView.clientId !== imapClient.id) {
1497
+ this.staleView = { clientId: imapClient.id, state: null, interval: Math.round(IMAP_STALE_CHECK_INTERVAL * (1 + Math.random() / 4)) };
1498
+ }
1499
+
1500
+ const before = await readKnown();
1501
+ if (!before) {
1502
+ return;
1503
+ }
1504
+
1505
+ const plan = planStaleViewProbe(this.staleView.state, before.uidNext, Date.now(), this.staleView.interval);
1506
+ this.staleView.state = plan.state;
1507
+ if (!plan.probe) {
1508
+ return;
1509
+ }
1510
+
1511
+ const commandClient = await this.getCommandConnection('staleViewCheck');
1512
+ if (!commandClient || !commandClient.usable) {
1513
+ return;
1514
+ }
1515
+
1516
+ const serverStatus = await commandClient.status(mailbox.path, { uidNext: true, uidValidity: true });
1517
+
1518
+ // Read again: an arrival while the probe was running proves the connection alive
1519
+ const known = await readKnown();
1520
+ if (!known) {
1521
+ // replaced, dropped or moved to another folder while the probe was running
1522
+ return;
1523
+ }
1524
+
1525
+ const result = evaluateStaleViewProbe(this.staleView.state, known, serverStatus, Date.now());
1526
+ this.staleView.state = result.state;
1527
+
1528
+ if (!result.ahead) {
1529
+ return;
1530
+ }
1531
+
1532
+ const details = {
1533
+ account: this.account,
1534
+ path: mailbox.path,
1535
+ storedUidNext: known.storedUidNext,
1536
+ sessionUidNext: known.sessionUidNext,
1537
+ serverUidNext: serverStatus.uidNext
1538
+ };
1539
+
1540
+ if (!result.stale) {
1541
+ this.logger.info({ msg: 'Main mailbox view is behind the server, confirming on the next check', ...details });
1542
+ return;
1543
+ }
1544
+
1545
+ this.logger.warn({ msg: 'Main mailbox view is stale, reconnecting', ...details });
1546
+ imapClient.close();
1547
+ }
1548
+
1549
+ /**
1550
+ * Arms the periodic resync. A failed pass is retried after a short capped backoff rather
1551
+ * than a full resync interval, and the retry lives in the same tracked slot, so close() and
1552
+ * pause() clear it and a later setup replaces it instead of racing it
1553
+ * @param {Number} delay - Delay in milliseconds before the next pass
1554
+ */
1555
+ scheduleResync(delay) {
1556
+ clearTimeout(this.resyncTimer);
1557
+ this.resyncTimer = setTimeout(() => {
1558
+ this.resyncTimer = null;
1559
+ // A completed pass re-arms the regular interval by itself
1560
+ this.syncMailboxes().catch(err => {
1561
+ // A pass that keeps failing the same way goes back to the regular interval after
1562
+ // the fast retries, so a persistent failure does not turn into a full folder walk
1563
+ // every 30 seconds. The backoff still counts the attempt, so the log keeps saying
1564
+ // how long the streak is
1565
+ const backoffDelay = this.resyncBackoff.nextDelay();
1566
+ const retryCount = this.resyncBackoff.attempts;
1567
+ const retryDelay = retryCount > RESYNC_FAST_RETRIES ? this.resyncDelay : backoffDelay;
1568
+ this.logger.warn({ msg: 'Failed to sync mailboxes, will retry', err, retryCount, retryDelay });
1569
+ if (this.isClosed || this.isClosing || this.paused) {
1570
+ return;
1571
+ }
1572
+ this.scheduleResync(retryDelay);
1573
+ });
1574
+ }, delay);
1451
1575
  }
1452
1576
 
1453
1577
  /**
@@ -1658,7 +1782,6 @@ class IMAPClient extends BaseClient {
1658
1782
 
1659
1783
  // Load notification settings
1660
1784
  this.notifyFrom = accountData.notifyFrom;
1661
- this.syncFrom = accountData.syncFrom;
1662
1785
 
1663
1786
  // Get indexing strategy for this account
1664
1787
  this.imapIndexer = typeof accountData.imapIndexer === 'string' && accountData.imapIndexer ? accountData.imapIndexer : 'full';
@@ -1675,7 +1798,7 @@ class IMAPClient extends BaseClient {
1675
1798
  imapConfig.id = `${imapConfig.id}:m:${this.connectionCount++}`;
1676
1799
 
1677
1800
  // Create new IMAP connection instance
1678
- let imapClient = new ImapFlow(
1801
+ let imapClient = createImapClient(
1679
1802
  Object.assign({}, imapConfig, {
1680
1803
  expungeHandler: async payload => await this.expungeHandler(payload)
1681
1804
  })
@@ -1947,8 +2070,6 @@ class IMAPClient extends BaseClient {
1947
2070
  }
1948
2071
 
1949
2072
  // Clear all timers
1950
- clearTimeout(this.refreshListingTimer);
1951
- clearTimeout(this.untaggedExpungeTimer);
1952
2073
  clearTimeout(this.resyncTimer);
1953
2074
  clearTimeout(this.completedTimer);
1954
2075
  clearTimeout(this.reconnectTimer);
@@ -2003,8 +2124,6 @@ class IMAPClient extends BaseClient {
2003
2124
  this.commandClient.close();
2004
2125
  }
2005
2126
 
2006
- clearTimeout(this.refreshListingTimer);
2007
- clearTimeout(this.untaggedExpungeTimer);
2008
2127
  clearTimeout(this.resyncTimer);
2009
2128
  clearTimeout(this.completedTimer);
2010
2129
  clearTimeout(this.reconnectTimer);
@@ -2104,6 +2223,10 @@ class IMAPClient extends BaseClient {
2104
2223
  }
2105
2224
 
2106
2225
  let result = await mailbox.getText(message, textParts, options, connectionOptions);
2226
+ if (!result) {
2227
+ // the id was issued for a previous incarnation of the folder
2228
+ return false;
2229
+ }
2107
2230
 
2108
2231
  // Filter result based on requested type
2109
2232
  if (textType && textType !== '*') {
@@ -2828,7 +2951,7 @@ class IMAPClient extends BaseClient {
2828
2951
  const connectionClient = await this.getImapConnection(connectionOptions, 'uploadMessage');
2829
2952
 
2830
2953
  // Prepare raw message for upload
2831
- let { raw, messageId, documentStoreUsed, referencedMessage } = await this.prepareRawMessage(data, null, { connectionClient });
2954
+ let { raw, messageId, referencedMessage } = await this.prepareRawMessage(data, null, { connectionClient });
2832
2955
 
2833
2956
  // Upload message to selected folder
2834
2957
  try {
@@ -2877,7 +3000,6 @@ class IMAPClient extends BaseClient {
2877
3000
  if (data.reference && data.reference.message) {
2878
3001
  response.reference = {
2879
3002
  message: data.reference.message,
2880
- documentStore: documentStoreUsed,
2881
3003
  success: referencedMessage ? true : false
2882
3004
  };
2883
3005
 
@@ -2971,11 +3093,13 @@ class IMAPClient extends BaseClient {
2971
3093
 
2972
3094
  const mailboxes = [];
2973
3095
 
3096
+ const commandClientBefore = this.commandClient;
2974
3097
  const listing = await this.getCurrentListing(false, { allowSecondary: true });
2975
3098
  this.processNewListingEntries(listing);
2976
- // Capture reference so we can close it after the await-heavy loop below
2977
- // without risking closure of a different command client obtained by a concurrent caller
2978
- const commandClientForListing = this.commandClient;
3099
+ // Only a command client the listing call itself created is ours to close afterwards. One
3100
+ // that existed before is shared with API requests routed to it while the account is
3101
+ // syncing, and closing it would cut a concurrent download short
3102
+ const commandClientForListing = this.commandClient !== commandClientBefore ? this.commandClient : null;
2979
3103
 
2980
3104
  // Process each configured subconnection
2981
3105
  for (const path of accountData.subconnections || []) {