emailengine-app 2.81.2 → 2.82.1

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 (226) hide show
  1. package/.ncurc.js +33 -10
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +71 -0
  4. package/DOCKER_DEPLOYMENT.md +13 -12
  5. package/Dockerfile +2 -0
  6. package/bin/emailengine.js +105 -25
  7. package/config/default.toml +0 -5
  8. package/config/test.toml +0 -5
  9. package/data/google-crawlers.json +1 -1
  10. package/encrypt.js +70 -42
  11. package/getswagger.sh +0 -4
  12. package/lib/account/account-state.js +2 -110
  13. package/lib/account/expected-identity.js +1 -1
  14. package/lib/account-assignment.js +138 -1
  15. package/lib/account.js +289 -869
  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-binding.js +58 -0
  19. package/lib/api-routes/account-routes.js +65 -37
  20. package/lib/api-routes/behavior-notes.js +4 -0
  21. package/lib/api-routes/blocklist-routes.js +2 -2
  22. package/lib/api-routes/bull-board-routes.js +1 -6
  23. package/lib/api-routes/export-routes.js +2 -22
  24. package/lib/api-routes/gateway-routes.js +15 -16
  25. package/lib/api-routes/index.js +1 -13
  26. package/lib/api-routes/mailbox-routes.js +2 -7
  27. package/lib/api-routes/mcp-oauth-routes.js +2 -1
  28. package/lib/api-routes/mcp-routes.js +7 -7
  29. package/lib/api-routes/message-routes.js +50 -238
  30. package/lib/api-routes/mint-bounds.js +110 -0
  31. package/lib/api-routes/oauth2-app-routes.js +23 -32
  32. package/lib/api-routes/operation-impact.js +1 -1
  33. package/lib/api-routes/outbox-routes.js +3 -3
  34. package/lib/api-routes/permission-map.js +1 -7
  35. package/lib/api-routes/route-helpers.js +11 -5
  36. package/lib/api-routes/settings-routes.js +20 -21
  37. package/lib/api-routes/stats-routes.js +1 -1
  38. package/lib/api-routes/submit-routes.js +17 -18
  39. package/lib/api-routes/template-routes.js +4 -9
  40. package/lib/api-routes/token-routes.js +28 -6
  41. package/lib/api-token-scheme.js +71 -0
  42. package/lib/arf-detect.js +33 -6
  43. package/lib/auth-token.js +44 -24
  44. package/lib/autodetect-imap-settings.js +305 -123
  45. package/lib/bounce-detect.js +25 -16
  46. package/lib/calendar-event.js +78 -0
  47. package/lib/consts.js +54 -5
  48. package/lib/create-imap-client.js +24 -0
  49. package/lib/db.js +77 -30
  50. package/lib/delivery-error.js +70 -2
  51. package/lib/egress-fetch.js +54 -3
  52. package/lib/egress-filter.js +11 -0
  53. package/lib/email-client/api-retry.js +147 -0
  54. package/lib/email-client/base-client.js +383 -536
  55. package/lib/email-client/credential-errors.js +21 -5
  56. package/lib/email-client/gmail/gmail-api.js +38 -125
  57. package/lib/email-client/gmail/send-request.js +1 -1
  58. package/lib/email-client/gmail-client.js +77 -51
  59. package/lib/email-client/imap/mailbox.js +158 -324
  60. package/lib/email-client/imap/stale-view.js +109 -0
  61. package/lib/email-client/imap/subconnection.js +46 -9
  62. package/lib/email-client/imap/sync-operations.js +5 -37
  63. package/lib/email-client/imap-client.js +190 -65
  64. package/lib/email-client/message-builder.js +50 -25
  65. package/lib/email-client/notification-handler.js +5 -219
  66. package/lib/email-client/outlook/graph-api.js +147 -126
  67. package/lib/email-client/outlook/send-request.js +10 -4
  68. package/lib/email-client/outlook-client.js +389 -463
  69. package/lib/email-client/smtp-pool-manager.js +3 -2
  70. package/lib/encrypt.js +184 -19
  71. package/lib/enum-descriptions.js +6 -3
  72. package/lib/export.js +141 -41
  73. package/lib/gateway.js +25 -6
  74. package/lib/get-raw-email.js +26 -44
  75. package/lib/get-secret.js +1 -21
  76. package/lib/handlebars-helpers.js +31 -10
  77. package/lib/imap-proxy-auth.js +13 -29
  78. package/lib/imapproxy/imap-core/README.md +1 -0
  79. package/lib/imapproxy/imap-core/lib/handler/imap-parser.js +12 -0
  80. package/lib/imapproxy/imap-core/lib/imap-command.js +74 -10
  81. package/lib/imapproxy/imap-core/lib/imap-connection.js +9 -1
  82. package/lib/imapproxy/imap-core/lib/imap-server.js +112 -26
  83. package/lib/imapproxy/imap-core/lib/imap-stream.js +41 -1
  84. package/lib/imapproxy/imap-core/lib/imap-tools.js +10 -2
  85. package/lib/imapproxy/imap-core/lib/indexer/indexer.js +4 -2
  86. package/lib/imapproxy/imap-server.js +17 -177
  87. package/lib/imapproxy/proxy-handoff.js +235 -0
  88. package/lib/imapproxy/response-error.js +33 -0
  89. package/lib/imapproxy/upstream-client.js +2 -2
  90. package/lib/license-beacon.js +3 -9
  91. package/lib/llm-pre-process.js +182 -43
  92. package/lib/logger.js +1 -1
  93. package/lib/lua/ee-export-queue-add.lua +39 -0
  94. package/lib/lua/ee-get-idempotency.lua +15 -3
  95. package/lib/lua/ee-release-attempts.lua +23 -0
  96. package/lib/lua/ee-reserve-attempts.lua +42 -0
  97. package/lib/lua/h-set-bigger.lua +12 -2
  98. package/lib/lua/s-list-accounts.lua +6 -3
  99. package/lib/mcp/index.js +1 -2
  100. package/lib/mcp/listen.js +221 -18
  101. package/lib/mcp/oauth.js +44 -5
  102. package/lib/mcp/resources.js +8 -2
  103. package/lib/mcp/tools.js +108 -36
  104. package/lib/message-port-stream.js +64 -6
  105. package/lib/oauth/external-account-signer.js +16 -13
  106. package/lib/oauth/gmail.js +64 -32
  107. package/lib/oauth/mail-ru.js +24 -17
  108. package/lib/oauth/outlook.js +53 -40
  109. package/lib/oauth/pubsub/google.js +38 -2
  110. package/lib/oauth/scope-checker.js +39 -8
  111. package/lib/oauth/scope-list.js +55 -0
  112. package/lib/oauth/token-fetch.js +47 -0
  113. package/lib/oauth/verify-app.js +2 -2
  114. package/lib/oauth2-apps.js +154 -90
  115. package/lib/openapi/build-document.js +1 -1
  116. package/lib/openapi/joi-schema.js +78 -9
  117. package/lib/outbox.js +2 -7
  118. package/lib/parse-message.js +21 -0
  119. package/lib/payload-examples-webhooks.json +4 -7
  120. package/lib/pbkdf2-phc.js +101 -0
  121. package/lib/privileged-settings.js +0 -14
  122. package/lib/queue-retention.js +4 -2
  123. package/lib/rate-limit.js +54 -15
  124. package/lib/read-env-value.js +33 -2
  125. package/lib/redis-scan-delete.js +56 -29
  126. package/lib/redis-url.js +3 -1
  127. package/lib/respawn-backoff.js +5 -4
  128. package/lib/response-stream.js +25 -4
  129. package/lib/rewrite-text-nodes.js +27 -40
  130. package/lib/routes-ui.js +0 -5
  131. package/lib/schemas.js +180 -253
  132. package/lib/sentry.js +21 -5
  133. package/lib/settings.js +58 -59
  134. package/lib/smtp-auth.js +6 -2
  135. package/lib/smtp-message-processor.js +28 -7
  136. package/lib/sso.js +7 -3
  137. package/lib/stream-encrypt.js +14 -13
  138. package/lib/swagger-options.js +3 -1
  139. package/lib/tls/provision.js +69 -3
  140. package/lib/tls/store.js +14 -1
  141. package/lib/token-audit-log.js +3 -2
  142. package/lib/tools.js +114 -53
  143. package/lib/totp.js +16 -1
  144. package/lib/ui-routes/account-routes.js +67 -70
  145. package/lib/ui-routes/admin-config-routes.js +111 -134
  146. package/lib/ui-routes/admin-entities-routes.js +101 -191
  147. package/lib/ui-routes/ai-options.js +104 -0
  148. package/lib/ui-routes/auth-routes.js +98 -18
  149. package/lib/ui-routes/export-routes.js +3 -23
  150. package/lib/ui-routes/internals-routes.js +12 -9
  151. package/lib/ui-routes/network-config-routes.js +8 -18
  152. package/lib/ui-routes/oauth-config-routes.js +83 -228
  153. package/lib/ui-routes/route-helpers.js +63 -67
  154. package/lib/ui-routes/special-use-paths.js +33 -0
  155. package/lib/ui-routes/unsubscribe-routes.js +2 -2
  156. package/lib/utils/decode-headers.js +32 -5
  157. package/lib/utils/header-map.js +62 -1
  158. package/lib/utils/network.js +11 -17
  159. package/lib/web-safe-html.js +77 -4
  160. package/lib/webhook-request.js +9 -1
  161. package/lib/webhook-routing.js +27 -1
  162. package/lib/webhooks.js +120 -43
  163. package/lib/worker-rpc-error.js +43 -2
  164. package/list-generate.js +13 -2
  165. package/package.json +38 -46
  166. package/sbom.json +1 -1
  167. package/scripts/refresh-test-tokens.js +42 -14
  168. package/server.js +338 -292
  169. package/setup-production.sh +16 -7
  170. package/static/css/flyonui.css +1 -1
  171. package/static/css/src/app.tailwind.css +7 -8
  172. package/static/js/ee-client.js +145 -70
  173. package/static/js/ui.js +350 -154
  174. package/static/licenses.html +349 -1740
  175. package/translations/messages.pot +129 -111
  176. package/views/account-workspace-error.hbs +30 -0
  177. package/views/accounts/account.hbs +9 -4
  178. package/views/accounts/browse.hbs +10 -4
  179. package/views/accounts/edit.hbs +11 -2
  180. package/views/config/ai.hbs +49 -41
  181. package/views/config/oauth/app.hbs +2 -1
  182. package/views/dashboard.hbs +18 -16
  183. package/views/internals/index.hbs +1 -1
  184. package/views/layout/app.hbs +0 -22
  185. package/views/layout/login.hbs +2 -1
  186. package/views/partials/filter_editor_js.hbs +4 -3
  187. package/views/partials/gmail_api_scopes.hbs +16 -0
  188. package/views/partials/oauth_form.hbs +67 -94
  189. package/views/partials/oauth_pubsub_app_select.hbs +43 -0
  190. package/views/partials/scope_info.hbs +14 -23
  191. package/views/partials/side_menu.hbs +0 -4
  192. package/views/partials/ui/account-picker.hbs +6 -32
  193. package/views/partials/ui/model-picker.hbs +31 -0
  194. package/views/partials/ui/pagination.hbs +6 -1
  195. package/views/partials/ui/picker.hbs +47 -0
  196. package/views/unsubscribe.hbs +1 -1
  197. package/workers/api.js +82 -47
  198. package/workers/export.js +55 -60
  199. package/workers/imap.js +132 -49
  200. package/workers/submit.js +5 -6
  201. package/workers/webhooks.js +46 -27
  202. package/.githooks/pre-commit +0 -80
  203. package/.github/CODE_OF_CONDUCT.md +0 -76
  204. package/.github/contributing.md +0 -17
  205. package/.github/dependabot.yml +0 -22
  206. package/.github/docker-smoke-test.sh +0 -61
  207. package/.github/workflows/deploy.yml +0 -215
  208. package/.github/workflows/e2e.yml +0 -55
  209. package/.github/workflows/release.yaml +0 -217
  210. package/.github/workflows/test.yml +0 -307
  211. package/lib/api-routes/chat-routes.js +0 -535
  212. package/lib/document-store.js +0 -75
  213. package/lib/es.js +0 -757
  214. package/lib/generate-text-preview.js +0 -61
  215. package/lib/imapproxy/imap-core/memory-notifier.js +0 -129
  216. package/lib/pre-process.js +0 -196
  217. package/lib/threads.js +0 -155
  218. package/lib/ui-routes/document-store-routes.js +0 -806
  219. package/playwright.config.js +0 -47
  220. package/views/config/document-store/chat.hbs +0 -286
  221. package/views/config/document-store/index.hbs +0 -146
  222. package/views/config/document-store/mappings/index.hbs +0 -108
  223. package/views/config/document-store/mappings/new.hbs +0 -68
  224. package/views/config/document-store/pre-processing/index.hbs +0 -103
  225. package/views/partials/document_store_header.hbs +0 -30
  226. package/workers/documents.js +0 -1128
@@ -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,12 +40,17 @@ 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,
45
50
  CONNECTION_CLOSING_CODES,
46
51
  DEFAULT_DOWNLOAD_CHUNK_SIZE,
47
52
  MAX_BACKOFF_DELAY,
53
+ SPECIAL_USE_PATH_TYPES,
48
54
  STABLE_CONNECTION_TIME,
49
55
  TLS_DEFAULTS
50
56
  } = require('../consts');
@@ -55,11 +61,14 @@ const DOWNLOAD_CHUNK_SIZE = getByteSize(readEnvValue('EENGINE_CHUNK_SIZE')) || D
55
61
  const DISABLE_IMAP_COMPRESSION = getBoolean(readEnvValue('EENGINE_DISABLE_COMPRESSION'));
56
62
  // Custom socket timeout for IMAP connections
57
63
  const IMAP_SOCKET_TIMEOUT = getDuration(readEnvValue('EENGINE_IMAP_SOCKET_TIMEOUT'));
64
+ // How long the main mailbox may stay quiet before a second connection checks the primary's view
65
+ // of it, see checkStaleMainView(). Disabled when not set
66
+ const IMAP_STALE_CHECK_INTERVAL = getDuration(readEnvValue('EENGINE_IMAP_STALE_CHECK_INTERVAL'));
58
67
 
59
68
  // Gmail API configuration
60
69
  const GMAIL_API_BASE = 'https://gmail.googleapis.com';
61
70
 
62
- logger.trace({ msg: 'Worker configuration', DOWNLOAD_CHUNK_SIZE, DISABLE_IMAP_COMPRESSION, IMAP_SOCKET_TIMEOUT });
71
+ logger.trace({ msg: 'Worker configuration', DOWNLOAD_CHUNK_SIZE, DISABLE_IMAP_COMPRESSION, IMAP_SOCKET_TIMEOUT, IMAP_STALE_CHECK_INTERVAL });
63
72
 
64
73
  const settings = require('../settings');
65
74
  const { redis } = require('../db');
@@ -118,13 +127,11 @@ class IMAPClient extends BaseClient {
118
127
  // Map of normalized mailbox paths to Mailbox instances
119
128
  this.mailboxes = new Map();
120
129
 
121
- // Timer for handling untagged EXPUNGE responses
122
- this.untaggedExpungeTimer = false;
123
-
124
- // Timer for periodic mailbox listing refresh
125
- this.refreshListingTimer = false;
126
130
  // Timer for periodic mailbox resynchronization
127
131
  this.resyncTimer = false;
132
+ // Retry backoff of a failed resync pass (scheduleResync()): 4, 8, 16 seconds, then the
133
+ // 30 second cap
134
+ this.resyncBackoff = new ReconnectBackoff({ baseDelay: 4000, maxDelay: 30000, factor: 2 });
128
135
 
129
136
  // Timer to ensure we return to the main mailbox after operations
130
137
  this.completedTimer = false;
@@ -155,6 +162,10 @@ class IMAPClient extends BaseClient {
155
162
  // as an operator-requested one, skip its refresh
156
163
  this.listedClient = null;
157
164
 
165
+ // Stale view check of the main mailbox: the id of the primary connection it describes, its
166
+ // jittered interval and the state stale-view.js carries between passes. See checkStaleMainView()
167
+ this.staleView = null;
168
+
158
169
  // Flag indicating if mailbox synchronization is in progress
159
170
  this.syncing = false;
160
171
 
@@ -375,7 +386,7 @@ class IMAPClient extends BaseClient {
375
386
  let imapConfig = await this.getImapConfig(accountData);
376
387
 
377
388
  // Create new IMAP connection with specific settings for command operations
378
- let commandClient = new ImapFlow(
389
+ let commandClient = createImapClient(
379
390
  Object.assign({}, imapConfig, {
380
391
  disableAutoIdle: true, // Don't automatically IDLE on this connection
381
392
  id: commandCid,
@@ -400,9 +411,17 @@ class IMAPClient extends BaseClient {
400
411
  const onErr = err => {
401
412
  // Idle timeout (ETIMEOUT) is expected - the command client has no keepalive
402
413
  const logLevel = err.code === 'ETIMEOUT' ? 'debug' : 'warn';
403
- commandClient?.log[logLevel]({ msg: 'IMAP connection error', cid: commandCid, channel: 'command', account: this.account, err });
414
+ if (!commandClient) {
415
+ // the close handler already let go of this client
416
+ return;
417
+ }
418
+ commandClient.log[logLevel]({ msg: 'IMAP connection error', cid: commandCid, channel: 'command', account: this.account, err });
404
419
  commandClient.close();
405
- this.commandClient = null;
420
+ // A late event from a replaced client must not drop the reference to its successor,
421
+ // which would then stay open until its own socket timeout
422
+ if (this.commandClient === commandClient) {
423
+ this.commandClient = null;
424
+ }
406
425
  };
407
426
  commandClient.on('error', onErr);
408
427
 
@@ -427,7 +446,9 @@ class IMAPClient extends BaseClient {
427
446
  this.logger.error({ msg: 'Error in command client close handler', cid: commandCid, account: this.account, err });
428
447
  }
429
448
 
430
- this.commandClient = null;
449
+ if (this.commandClient === commandClient) {
450
+ this.commandClient = null;
451
+ }
431
452
  detachImapClient(commandClient, this.logger, { type: 'commandClient', cid: commandCid, account: this.account });
432
453
  commandClient = null;
433
454
  });
@@ -666,7 +687,7 @@ class IMAPClient extends BaseClient {
666
687
 
667
688
  // Build hints for special-use folders from account configuration
668
689
  let specialUseHints = {};
669
- for (let type of ['sent', 'drafts', 'junk', 'trash', 'archive']) {
690
+ for (let type of SPECIAL_USE_PATH_TYPES) {
670
691
  if (accountData.imap && accountData.imap[`${type}MailPath`]) {
671
692
  specialUseHints[type] = accountData.imap[`${type}MailPath`];
672
693
  }
@@ -1270,26 +1291,12 @@ class IMAPClient extends BaseClient {
1270
1291
  // ended in an unconncted state
1271
1292
  this.logger.warn({ msg: 'Failed to set up connection, will retry', err });
1272
1293
 
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);
1294
+ // Through the shared reconnectTimer slot: a bare timer here was neither debounced
1295
+ // against the close handler's own retry (two start() calls, the second tearing down
1296
+ // the healthy connection the first made) nor cleared by close()/pause(), so it
1297
+ // survived a pause and tore down the resumed connection
1298
+ this.scheduleReconnect(this.reconnectBackoff, 'Scheduling reconnection attempt');
1299
+ return;
1293
1300
  }
1294
1301
 
1295
1302
  this.logger.debug({
@@ -1306,7 +1313,6 @@ class IMAPClient extends BaseClient {
1306
1313
  */
1307
1314
  async syncMailboxes() {
1308
1315
  // Clear any pending timers
1309
- clearTimeout(this.untaggedExpungeTimer);
1310
1316
  clearTimeout(this.resyncTimer);
1311
1317
  clearTimeout(this.completedTimer);
1312
1318
 
@@ -1404,8 +1410,12 @@ class IMAPClient extends BaseClient {
1404
1410
  // setupSubConnections() is otherwise only invoked from start(), so on
1405
1411
  // a stable long-lived connection a re-created folder would never get
1406
1412
  // 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))) {
1413
+ // by the primary connection etc.) are left alone. A subconnection whose login was
1414
+ // refused is revived here too: it stops retrying on its own, so this pass (once per
1415
+ // resync interval) is its slow retry
1416
+ if (
1417
+ this.subconnections.some(subconnection => subconnection.loginRefused || (subconnection.mailboxMissing && this.hasListedMailbox(subconnection.path)))
1418
+ ) {
1409
1419
  this.setupSubConnections()
1410
1420
  .then(result => {
1411
1421
  this.logger.info({ msg: 'Reconciled subconnections after a folder change', account: this.account, result });
@@ -1428,26 +1438,141 @@ class IMAPClient extends BaseClient {
1428
1438
  // start waiting for changes
1429
1439
  await this.select(mainPath);
1430
1440
 
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);
1441
+ // Schedule next sync cycle. The pass completed, so a retry streak is over
1442
+ this.resyncBackoff.reset();
1443
+ this.scheduleResync(this.resyncDelay);
1444
+
1445
+ // The walk above skips the main mailbox, the selected one, whose changes only arrive
1446
+ // through the primary connection. A failed check is not a failed pass
1447
+ try {
1448
+ await this.checkStaleMainView();
1449
+ } catch (err) {
1450
+ this.logger.warn({ msg: 'Failed to check the main mailbox view', account: this.account, err });
1451
+ }
1452
+ }
1453
+
1454
+ /**
1455
+ * Checks that the primary connection still sees what the server holds in the main mailbox,
1456
+ * and drops the connection when it does not (EENGINE_IMAP_STALE_CHECK_INTERVAL, off by default).
1457
+ *
1458
+ * Some servers keep a long-lived session alive - IDLE, NOOP, LIST and STATUS of other folders
1459
+ * all answer OK - while its view of the selected mailbox stops moving, so the account reports
1460
+ * "connected" and receives nothing until it reconnects. Nothing on that connection reveals it,
1461
+ * so once the primary has seen nothing new in the main mailbox for the interval, the command
1462
+ * connection asks for its STATUS. A UIDNEXT ahead of what the primary knows on two probes in a
1463
+ * row closes the primary connection, and the close handler reconnects it like any dropped
1464
+ * connection. The decisions live in stale-view.js
1465
+ */
1466
+ async checkStaleMainView() {
1467
+ if (!IMAP_STALE_CHECK_INTERVAL || !this.main) {
1468
+ return;
1469
+ }
1470
+
1471
+ const imapClient = this.imapClient;
1472
+ const mailbox = this.mailboxes.get(normalizePath(this.main.path));
1473
+ if (!imapClient || !imapClient.usable || !mailbox || mailbox.syncDisabled) {
1474
+ return;
1475
+ }
1476
+
1477
+ // What the primary knows of the main mailbox, see knownUidNext(). Only while it is the
1478
+ // folder open there: otherwise getMailboxStatus() throws, and the next pass looks again
1479
+ const readKnown = async () => {
1480
+ if (this.imapClient !== imapClient || !imapClient.usable || !mailbox.isSelected()) {
1481
+ return null;
1482
+ }
1483
+ const storedStatus = await mailbox.getStoredStatus();
1484
+ const sessionStatus = mailbox.getMailboxStatus(imapClient);
1485
+ return {
1486
+ uidNext: knownUidNext(storedStatus.uidNext, sessionStatus.uidNext),
1487
+ uidValidity: storedStatus.uidValidity,
1488
+ storedUidNext: storedStatus.uidNext,
1489
+ sessionUidNext: sessionStatus.uidNext
1490
+ };
1449
1491
  };
1450
- setSyncTimer();
1492
+
1493
+ // The state belongs to one connection, a reconnect starts the quiet period over. Keyed on
1494
+ // the connection id, so a dropped client is not kept alive by it. Each connection stretches
1495
+ // the interval by up to a quarter at random: a worker restart connects every account within
1496
+ // minutes, and without it their probes would all fall due in the same resync window
1497
+ if (!this.staleView || this.staleView.clientId !== imapClient.id) {
1498
+ this.staleView = { clientId: imapClient.id, state: null, interval: Math.round(IMAP_STALE_CHECK_INTERVAL * (1 + Math.random() / 4)) };
1499
+ }
1500
+
1501
+ const before = await readKnown();
1502
+ if (!before) {
1503
+ return;
1504
+ }
1505
+
1506
+ const plan = planStaleViewProbe(this.staleView.state, before.uidNext, Date.now(), this.staleView.interval);
1507
+ this.staleView.state = plan.state;
1508
+ if (!plan.probe) {
1509
+ return;
1510
+ }
1511
+
1512
+ const commandClient = await this.getCommandConnection('staleViewCheck');
1513
+ if (!commandClient || !commandClient.usable) {
1514
+ return;
1515
+ }
1516
+
1517
+ const serverStatus = await commandClient.status(mailbox.path, { uidNext: true, uidValidity: true });
1518
+
1519
+ // Read again: an arrival while the probe was running proves the connection alive
1520
+ const known = await readKnown();
1521
+ if (!known) {
1522
+ // replaced, dropped or moved to another folder while the probe was running
1523
+ return;
1524
+ }
1525
+
1526
+ const result = evaluateStaleViewProbe(this.staleView.state, known, serverStatus, Date.now());
1527
+ this.staleView.state = result.state;
1528
+
1529
+ if (!result.ahead) {
1530
+ return;
1531
+ }
1532
+
1533
+ const details = {
1534
+ account: this.account,
1535
+ path: mailbox.path,
1536
+ storedUidNext: known.storedUidNext,
1537
+ sessionUidNext: known.sessionUidNext,
1538
+ serverUidNext: serverStatus.uidNext
1539
+ };
1540
+
1541
+ if (!result.stale) {
1542
+ this.logger.info({ msg: 'Main mailbox view is behind the server, confirming on the next check', ...details });
1543
+ return;
1544
+ }
1545
+
1546
+ this.logger.warn({ msg: 'Main mailbox view is stale, reconnecting', ...details });
1547
+ imapClient.close();
1548
+ }
1549
+
1550
+ /**
1551
+ * Arms the periodic resync. A failed pass is retried after a short capped backoff rather
1552
+ * than a full resync interval, and the retry lives in the same tracked slot, so close() and
1553
+ * pause() clear it and a later setup replaces it instead of racing it
1554
+ * @param {Number} delay - Delay in milliseconds before the next pass
1555
+ */
1556
+ scheduleResync(delay) {
1557
+ clearTimeout(this.resyncTimer);
1558
+ this.resyncTimer = setTimeout(() => {
1559
+ this.resyncTimer = null;
1560
+ // A completed pass re-arms the regular interval by itself
1561
+ this.syncMailboxes().catch(err => {
1562
+ // A pass that keeps failing the same way goes back to the regular interval after
1563
+ // the fast retries, so a persistent failure does not turn into a full folder walk
1564
+ // every 30 seconds. The backoff still counts the attempt, so the log keeps saying
1565
+ // how long the streak is
1566
+ const backoffDelay = this.resyncBackoff.nextDelay();
1567
+ const retryCount = this.resyncBackoff.attempts;
1568
+ const retryDelay = retryCount > RESYNC_FAST_RETRIES ? this.resyncDelay : backoffDelay;
1569
+ this.logger.warn({ msg: 'Failed to sync mailboxes, will retry', err, retryCount, retryDelay });
1570
+ if (this.isClosed || this.isClosing || this.paused) {
1571
+ return;
1572
+ }
1573
+ this.scheduleResync(retryDelay);
1574
+ });
1575
+ }, delay);
1451
1576
  }
1452
1577
 
1453
1578
  /**
@@ -1658,7 +1783,6 @@ class IMAPClient extends BaseClient {
1658
1783
 
1659
1784
  // Load notification settings
1660
1785
  this.notifyFrom = accountData.notifyFrom;
1661
- this.syncFrom = accountData.syncFrom;
1662
1786
 
1663
1787
  // Get indexing strategy for this account
1664
1788
  this.imapIndexer = typeof accountData.imapIndexer === 'string' && accountData.imapIndexer ? accountData.imapIndexer : 'full';
@@ -1675,7 +1799,7 @@ class IMAPClient extends BaseClient {
1675
1799
  imapConfig.id = `${imapConfig.id}:m:${this.connectionCount++}`;
1676
1800
 
1677
1801
  // Create new IMAP connection instance
1678
- let imapClient = new ImapFlow(
1802
+ let imapClient = createImapClient(
1679
1803
  Object.assign({}, imapConfig, {
1680
1804
  expungeHandler: async payload => await this.expungeHandler(payload)
1681
1805
  })
@@ -1947,8 +2071,6 @@ class IMAPClient extends BaseClient {
1947
2071
  }
1948
2072
 
1949
2073
  // Clear all timers
1950
- clearTimeout(this.refreshListingTimer);
1951
- clearTimeout(this.untaggedExpungeTimer);
1952
2074
  clearTimeout(this.resyncTimer);
1953
2075
  clearTimeout(this.completedTimer);
1954
2076
  clearTimeout(this.reconnectTimer);
@@ -2003,8 +2125,6 @@ class IMAPClient extends BaseClient {
2003
2125
  this.commandClient.close();
2004
2126
  }
2005
2127
 
2006
- clearTimeout(this.refreshListingTimer);
2007
- clearTimeout(this.untaggedExpungeTimer);
2008
2128
  clearTimeout(this.resyncTimer);
2009
2129
  clearTimeout(this.completedTimer);
2010
2130
  clearTimeout(this.reconnectTimer);
@@ -2104,6 +2224,10 @@ class IMAPClient extends BaseClient {
2104
2224
  }
2105
2225
 
2106
2226
  let result = await mailbox.getText(message, textParts, options, connectionOptions);
2227
+ if (!result) {
2228
+ // the id was issued for a previous incarnation of the folder
2229
+ return false;
2230
+ }
2107
2231
 
2108
2232
  // Filter result based on requested type
2109
2233
  if (textType && textType !== '*') {
@@ -2828,7 +2952,7 @@ class IMAPClient extends BaseClient {
2828
2952
  const connectionClient = await this.getImapConnection(connectionOptions, 'uploadMessage');
2829
2953
 
2830
2954
  // Prepare raw message for upload
2831
- let { raw, messageId, documentStoreUsed, referencedMessage } = await this.prepareRawMessage(data, null, { connectionClient });
2955
+ let { raw, messageId, referencedMessage } = await this.prepareRawMessage(data, null, { connectionClient });
2832
2956
 
2833
2957
  // Upload message to selected folder
2834
2958
  try {
@@ -2877,7 +3001,6 @@ class IMAPClient extends BaseClient {
2877
3001
  if (data.reference && data.reference.message) {
2878
3002
  response.reference = {
2879
3003
  message: data.reference.message,
2880
- documentStore: documentStoreUsed,
2881
3004
  success: referencedMessage ? true : false
2882
3005
  };
2883
3006
 
@@ -2971,11 +3094,13 @@ class IMAPClient extends BaseClient {
2971
3094
 
2972
3095
  const mailboxes = [];
2973
3096
 
3097
+ const commandClientBefore = this.commandClient;
2974
3098
  const listing = await this.getCurrentListing(false, { allowSecondary: true });
2975
3099
  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;
3100
+ // Only a command client the listing call itself created is ours to close afterwards. One
3101
+ // that existed before is shared with API requests routed to it while the account is
3102
+ // syncing, and closing it would cut a concurrent download short
3103
+ const commandClientForListing = this.commandClient !== commandClientBefore ? this.commandClient : null;
2979
3104
 
2980
3105
  // Process each configured subconnection
2981
3106
  for (const path of accountData.subconnections || []) {
@@ -2,7 +2,7 @@
2
2
 
3
3
  const { Gateway } = require('../gateway');
4
4
  const { oauth2ProviderData } = require('../oauth2-apps');
5
- const { useAuthServerForConnection } = require('../tools');
5
+ const { useAuthServerForConnection, redactUrlCredentials } = require('../tools');
6
6
  const { resolveAuthServerCredentials } = require('./credential-errors');
7
7
  const { getLocalAddress } = require('../utils/network');
8
8
  const settings = require('../settings');
@@ -45,18 +45,11 @@ class SmtpConfigBuilder {
45
45
  secret: this.secret
46
46
  });
47
47
 
48
- try {
49
- const gatewayData = await gatewayObject.loadGatewayData();
50
- return { gatewayData, gatewayObject };
51
- } catch (err) {
52
- this.logger.warn({
53
- msg: 'Failed to load gateway data',
54
- messageId,
55
- gateway: gatewayId,
56
- err
57
- });
58
- return { gatewayData: null, gatewayObject };
59
- }
48
+ // The message was queued for this gateway, so it must not go out through the account's
49
+ // own SMTP server instead: a Redis failure is thrown as is and the job retries, a gateway
50
+ // that no longer exists throws GatewayNotFound and the job is discarded
51
+ const gatewayData = await gatewayObject.loadGatewayData();
52
+ return { gatewayData, gatewayObject };
60
53
  }
61
54
 
62
55
  /**
@@ -305,7 +298,9 @@ class NetworkRoutingBuilder {
305
298
  }
306
299
 
307
300
  if (smtpSettings.proxy) {
308
- networkRouting.proxy = smtpSettings.proxy;
301
+ // This object ends up in messageSent / messageDeliveryError webhooks, job progress and
302
+ // the gateway's lastError, so the proxy password must not travel with it.
303
+ networkRouting.proxy = redactUrlCredentials(smtpSettings.proxy);
309
304
  }
310
305
 
311
306
  if (smtpSettings.name) {
@@ -450,7 +445,9 @@ class ProviderMessageIdHandler {
450
445
  }
451
446
 
452
447
  /**
453
- * Error code to description mapping for SMTP errors
448
+ * Error code to description mapping for SMTP errors. A code that is absent here, or whose entry
449
+ * returns nothing, falls back to the error's own message in buildStatus() - the table turns a
450
+ * known failure into a sentence an operator can act on, it does not decide what gets recorded.
454
451
  */
455
452
  const SMTP_ERROR_DESCRIPTIONS = {
456
453
  ESOCKET: (settings, err) => {
@@ -477,22 +474,19 @@ const SMTP_ERROR_DESCRIPTIONS = {
477
474
  */
478
475
  class SmtpErrorBuilder {
479
476
  /**
480
- * Builds SMTP status object from error
477
+ * Builds SMTP status object from error. Always produces a status: it used to return null for
478
+ * any error SMTP_ERROR_DESCRIPTIONS could not describe (a 5xx rejection arriving without the
479
+ * EENVELOPE marker, a nodemailer code added since the table was written), and the caller then
480
+ * left the gateway's lastError and the account's smtpStatus showing the previous attempt. The
481
+ * caller decides whether there is an SMTP attempt to describe at all.
481
482
  * @param {Error} err - The error that occurred
482
483
  * @param {Object} smtpSettings - SMTP settings for context
483
484
  * @param {Object} networkRouting - Network routing info
484
- * @returns {Object|null} SMTP status object or null
485
+ * @returns {Object} SMTP status object
485
486
  */
486
487
  static buildStatus(err, smtpSettings, networkRouting) {
487
488
  const descriptionBuilder = SMTP_ERROR_DESCRIPTIONS[err.code];
488
- if (!descriptionBuilder) {
489
- return null;
490
- }
491
-
492
- const description = descriptionBuilder(smtpSettings, err);
493
- if (!description) {
494
- return null;
495
- }
489
+ const description = (descriptionBuilder && descriptionBuilder(smtpSettings, err)) || err.message || 'Failed to send email';
496
490
 
497
491
  return {
498
492
  created: Date.now(),
@@ -575,7 +569,38 @@ class SentMailCopyDecider {
575
569
  }
576
570
  }
577
571
 
572
+ /**
573
+ * Merges a stored template into the message being queued.
574
+ *
575
+ * `render: false` is the documented way to send a template as-is, and the format carried by the
576
+ * template used to be applied with `data.render = data.render || {}`, which turned that explicit false
577
+ * into an empty options object - and an options object renders. So the one value that asked for no
578
+ * rendering was the one value that could not be expressed. Extracted from queueMessageHandler(),
579
+ * which a test cannot reach without a connection, an account record and a license answer.
580
+ *
581
+ * Mutates `data`, as the caller's own merge did.
582
+ *
583
+ * @param {Object} data - the message being queued, carrying `template` and optionally `render`
584
+ * @param {Object} templateData - the stored template
585
+ * @returns {Object} the same `data`
586
+ */
587
+ function applyTemplate(data, templateData) {
588
+ if (data.render !== false && templateData.content && templateData.content.html && templateData.format) {
589
+ data.render = data.render || {};
590
+ data.render.format = templateData.format;
591
+ }
592
+
593
+ for (let key of Object.keys(templateData.content || {})) {
594
+ data[key] = templateData.content[key];
595
+ }
596
+
597
+ delete data.template;
598
+
599
+ return data;
600
+ }
601
+
578
602
  module.exports = {
603
+ applyTemplate,
579
604
  SmtpConfigBuilder,
580
605
  NetworkRoutingBuilder,
581
606
  NotificationBuilder,