emailengine-app 2.78.0 → 2.79.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 (142) hide show
  1. package/.ncurc.js +23 -13
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +29 -0
  4. package/config/e2e.toml +2 -1
  5. package/config/test.toml +2 -1
  6. package/data/google-crawlers.json +1 -1
  7. package/lib/account.js +70 -35
  8. package/lib/api-reference/format.js +91 -4
  9. package/lib/api-reference/model.js +144 -19
  10. package/lib/api-reference/schema-tree.js +282 -28
  11. package/lib/api-routes/account-routes.js +80 -34
  12. package/lib/api-routes/blocklist-routes.js +21 -47
  13. package/lib/api-routes/chat-routes.js +10 -12
  14. package/lib/api-routes/delivery-test-routes.js +6 -26
  15. package/lib/api-routes/export-routes.js +2 -0
  16. package/lib/api-routes/gateway-routes.js +52 -11
  17. package/lib/api-routes/license-routes.js +2 -0
  18. package/lib/api-routes/mailbox-routes.js +29 -26
  19. package/lib/api-routes/message-routes.js +27 -21
  20. package/lib/api-routes/oauth2-app-routes.js +11 -29
  21. package/lib/api-routes/operation-impact.js +80 -0
  22. package/lib/api-routes/outbox-routes.js +15 -5
  23. package/lib/api-routes/permission-map.js +397 -0
  24. package/lib/api-routes/route-helpers.js +223 -9
  25. package/lib/api-routes/route-metadata.js +28 -0
  26. package/lib/api-routes/settings-routes.js +30 -25
  27. package/lib/api-routes/stats-routes.js +2 -2
  28. package/lib/api-routes/submit-routes.js +53 -31
  29. package/lib/api-routes/template-routes.js +3 -0
  30. package/lib/api-routes/token-routes.js +319 -33
  31. package/lib/api-routes/webhook-route-routes.js +14 -4
  32. package/lib/auth-token.js +80 -8
  33. package/lib/consts.js +10 -0
  34. package/lib/db.js +20 -2
  35. package/lib/delivery-error.js +30 -1
  36. package/lib/email-client/base-client.js +27 -41
  37. package/lib/email-client/gmail-client.js +19 -10
  38. package/lib/email-client/imap/mailbox.js +23 -24
  39. package/lib/email-client/imap/subconnection.js +10 -7
  40. package/lib/email-client/imap/sync-operations.js +46 -46
  41. package/lib/email-client/imap-client.js +36 -26
  42. package/lib/email-client/message-builder.js +3 -3
  43. package/lib/email-client/notification-handler.js +1 -1
  44. package/lib/email-client/outlook/graph-api.js +10 -4
  45. package/lib/email-client/outlook-client.js +53 -54
  46. package/lib/email-client/smtp-pool-manager.js +1 -1
  47. package/lib/enum-descriptions.js +92 -2
  48. package/lib/export.js +1 -1
  49. package/lib/field-usage.js +133 -0
  50. package/lib/gateway.js +1 -1
  51. package/lib/imapproxy/imap-core/lib/commands/authenticate-plain.js +3 -3
  52. package/lib/imapproxy/imap-core/lib/commands/id.js +2 -13
  53. package/lib/imapproxy/imap-core/lib/commands/starttls.js +1 -1
  54. package/lib/imapproxy/imap-core/lib/imap-command.js +21 -5
  55. package/lib/imapproxy/imap-core/lib/imap-connection.js +15 -5
  56. package/lib/imapproxy/imap-server.js +27 -7
  57. package/lib/license-beacon.js +4 -9
  58. package/lib/lists.js +49 -1
  59. package/lib/llm-pre-process.js +5 -5
  60. package/lib/logger.js +5 -1
  61. package/lib/metrics-collector.js +2 -2
  62. package/lib/oauth/gmail.js +9 -12
  63. package/lib/oauth/mail-ru.js +5 -7
  64. package/lib/oauth/outlook.js +9 -9
  65. package/lib/oauth/pubsub/google.js +25 -10
  66. package/lib/oauth/scope-checker.js +1 -1
  67. package/lib/oauth2-apps.js +223 -294
  68. package/lib/openapi/build-document.js +15 -7
  69. package/lib/openapi/joi-schema.js +20 -0
  70. package/lib/outbox.js +85 -17
  71. package/lib/pre-process.js +8 -8
  72. package/lib/queue-stats.js +49 -0
  73. package/lib/read-env-value.js +1 -1
  74. package/lib/reconnection-manager.js +2 -2
  75. package/lib/rewrite-text-nodes.js +4 -3
  76. package/lib/routes-ui.js +4 -0
  77. package/lib/schemas.js +216 -160
  78. package/lib/settings.js +84 -5
  79. package/lib/sub-script.js +2 -1
  80. package/lib/swagger-options.js +2 -1
  81. package/lib/templates.js +4 -4
  82. package/lib/threads.js +2 -2
  83. package/lib/token-audit-log.js +208 -0
  84. package/lib/token-permission-view.js +219 -0
  85. package/lib/token-permissions.js +172 -0
  86. package/lib/tokens.js +99 -15
  87. package/lib/tools.js +142 -37
  88. package/lib/ui-routes/account-routes.js +31 -11
  89. package/lib/ui-routes/admin-config-routes.js +18 -10
  90. package/lib/ui-routes/admin-entities-routes.js +66 -22
  91. package/lib/ui-routes/auth-routes.js +30 -24
  92. package/lib/ui-routes/export-routes.js +10 -4
  93. package/lib/ui-routes/oauth-config-routes.js +5 -5
  94. package/lib/ui-routes/reference-routes.js +3 -3
  95. package/lib/ui-routes/route-helpers.js +51 -2
  96. package/lib/ui-routes/settings-page.js +1 -1
  97. package/lib/ui-routes/smtp-test-routes.js +1 -1
  98. package/lib/ui-routes/suppression-list-routes.js +294 -0
  99. package/lib/ui-routes/unsubscribe-routes.js +19 -29
  100. package/lib/utils/network.js +2 -2
  101. package/lib/web-safe-html.js +1 -1
  102. package/lib/webhook-routing.js +80 -0
  103. package/lib/webhooks.js +20 -14
  104. package/package.json +11 -10
  105. package/sbom.json +1 -1
  106. package/server.js +80 -41
  107. package/static/css/flyonui.css +1 -1
  108. package/static/css/src/app.tailwind.css +136 -9
  109. package/static/js/reference.js +456 -10
  110. package/static/js/ui.js +43 -0
  111. package/static/licenses.html +51 -41
  112. package/translations/messages.pot +59 -59
  113. package/views/accounts/account.hbs +69 -7
  114. package/views/accounts/browse.hbs +18 -35
  115. package/views/config/logging.hbs +6 -0
  116. package/views/config/oauth/app.hbs +0 -2
  117. package/views/config/security.hbs +13 -0
  118. package/views/partials/oauth_form.hbs +0 -15
  119. package/views/partials/reference/disclosure.hbs +8 -2
  120. package/views/partials/reference/operation.hbs +47 -13
  121. package/views/partials/reference/params.hbs +17 -1
  122. package/views/partials/reference/schema-node.hbs +110 -52
  123. package/views/partials/reference/schema-tools.hbs +25 -0
  124. package/views/partials/reference/try-it.hbs +84 -11
  125. package/views/partials/side_menu.hbs +1 -0
  126. package/views/partials/ui/checkbox.hbs +2 -2
  127. package/views/partials/ui/tabs.hbs +7 -1
  128. package/views/reference/token.hbs +4 -0
  129. package/views/suppression-lists/index.hbs +85 -0
  130. package/views/suppression-lists/list.hbs +87 -0
  131. package/views/templates/index.hbs +8 -2
  132. package/views/tokens/index.hbs +31 -4
  133. package/views/tokens/new.hbs +324 -2
  134. package/workers/api.js +146 -57
  135. package/workers/documents.js +46 -26
  136. package/workers/export.js +20 -8
  137. package/workers/imap-proxy.js +2 -2
  138. package/workers/imap.js +12 -6
  139. package/workers/smtp.js +13 -7
  140. package/workers/submit.js +40 -30
  141. package/workers/webhooks.js +59 -25
  142. package/lib/feature-flags.js +0 -48
@@ -39,6 +39,7 @@ const {
39
39
  MAX_INLINE_ATTACHMENT_SIZE,
40
40
  MAX_ALLOWED_DOWNLOAD_SIZE,
41
41
  TRANSIENT_NETWORK_CODES,
42
+ CONNECTION_CLOSING_CODES,
42
43
  PHANTOM_SELECT_FAIL_THRESHOLD,
43
44
  PHANTOM_REPROBE_INTERVAL
44
45
  } = require('../../consts');
@@ -184,8 +185,10 @@ class Mailbox {
184
185
 
185
186
  let hasStoredState = Object.keys(data).length > 0;
186
187
 
187
- // Log diagnostic info if stored uidValidity is invalid or missing
188
- if (!validUidValidity(data.uidValidity)) {
188
+ // Log diagnostic info if the stored status exists but its uidValidity is invalid
189
+ // or missing. A folder that has never been synced has no stored state at all,
190
+ // which is expected and not worth a warning
191
+ if (hasStoredState && !validUidValidity(data.uidValidity)) {
189
192
  this.logger.warn({
190
193
  msg: 'Invalid or missing uidValidity in stored status',
191
194
  path: this.path,
@@ -224,7 +227,8 @@ class Mailbox {
224
227
  let packedUid = await this.connection.packUid(this, uid);
225
228
  if (!packedUid) {
226
229
  this.logger.warn({
227
- msg: `Skipping ${notificationType} notification - packUid returned invalid result`,
230
+ msg: 'Skipping notification, packUid returned invalid result',
231
+ notificationType,
228
232
  uid,
229
233
  path: this.path
230
234
  });
@@ -413,7 +417,7 @@ class Mailbox {
413
417
  return;
414
418
  }
415
419
  this.connection.imapClient.idle().catch(err => {
416
- this.logger.error({ msg: 'IDLE error', err });
420
+ this.logger.warn({ msg: 'IDLE error', err });
417
421
  });
418
422
  }
419
423
 
@@ -777,7 +781,7 @@ class Mailbox {
777
781
  if (typeof logObj[key] === 'bigint') {
778
782
  logObj[key] = logObj[key].toString();
779
783
  }
780
- if (typeof logObj[key].has === 'function') {
784
+ if (logObj[key] && typeof logObj[key].has === 'function') {
781
785
  logObj[key] = Array.from(logObj[key]);
782
786
  }
783
787
  });
@@ -804,10 +808,10 @@ class Mailbox {
804
808
  })
805
809
  .then(() => this.select())
806
810
  .catch(err => {
807
- if (err.code === 'IMAPConnectionClosing') {
811
+ if (CONNECTION_CLOSING_CODES.has(err.code)) {
808
812
  this.logger.debug({ msg: 'Sync skipped, connection closing', err });
809
813
  } else {
810
- this.logger.error({ msg: 'Sync error', err });
814
+ this.logger.warn({ msg: 'Failed to sync mailbox after EXISTS', err });
811
815
  }
812
816
  });
813
817
  }, 1000);
@@ -902,7 +906,7 @@ class Mailbox {
902
906
  * @param {Object} messageData - Deleted message data
903
907
  */
904
908
  async processDeleted(messageData) {
905
- this.logger.debug({ msg: 'Deleted', uid: messageData.uid });
909
+ this.logger.debug({ msg: 'Message deleted', uid: messageData.uid });
906
910
 
907
911
  //FIXME: does not work as there is no messageId property
908
912
  /*
@@ -943,7 +947,7 @@ class Mailbox {
943
947
  // Remove from notifications queue since message no longer exists
944
948
  await this.connection.redis.zremrangebyscore(this.getNotificationsKey(), messageData.uid, messageData.uid);
945
949
  } catch (err) {
946
- this.logger.error({ msg: 'Failed removing deleted message from notifications set', uid: messageData.uid, err });
950
+ this.logger.error({ msg: 'Failed to remove deleted message from notifications set', uid: messageData.uid, err });
947
951
  }
948
952
  }
949
953
 
@@ -1263,7 +1267,7 @@ class Mailbox {
1263
1267
  break;
1264
1268
  }
1265
1269
  } catch (err) {
1266
- this.logger.error({ msg: 'Failed to resolve category for message', err, category, uid: messageData.uid, id: messageInfo.id });
1270
+ this.logger.warn({ msg: 'Failed to resolve category for message', err, category, uid: messageData.uid, id: messageInfo.id });
1267
1271
  break;
1268
1272
  }
1269
1273
  }
@@ -1444,7 +1448,7 @@ class Mailbox {
1444
1448
  })
1445
1449
  );
1446
1450
  } catch (err) {
1447
- this.logger.error({
1451
+ this.logger.warn({
1448
1452
  msg: 'Failed to parse calendar event',
1449
1453
  attachment: Object.assign({}, attachment, { content: `${contentBuf.length} bytes` }),
1450
1454
  err
@@ -1572,7 +1576,7 @@ class Mailbox {
1572
1576
  time: Date.now()
1573
1577
  })
1574
1578
  );
1575
- this.logger.error({ msg: 'Failed to fetch embeddings OpenAI', err });
1579
+ this.logger.error({ msg: 'Failed to fetch embeddings from OpenAI', err });
1576
1580
  }
1577
1581
  }
1578
1582
  }
@@ -1634,7 +1638,7 @@ class Mailbox {
1634
1638
  }
1635
1639
  }
1636
1640
  } catch (err) {
1637
- this.logger.error({ msg: 'Attachment error', uid: messageInfo.uid, partList, err });
1641
+ this.logger.error({ msg: 'Failed to download attachments', uid: messageInfo.uid, partList, err });
1638
1642
  }
1639
1643
  }
1640
1644
 
@@ -2144,12 +2148,7 @@ class Mailbox {
2144
2148
  await this.processNew(messageData, messageFetchOptions, canSync, storedStatus);
2145
2149
  await this.connection.redis.zrem(notificationsKey, rawMember);
2146
2150
  } catch (err) {
2147
- if (
2148
- err.code === 'NoConnection' ||
2149
- err.code === 'IMAPConnectionClosing' ||
2150
- err.code === 'EConnectionClosed' ||
2151
- TRANSIENT_NETWORK_CODES.has(err.code)
2152
- ) {
2151
+ if (CONNECTION_CLOSING_CODES.has(err.code) || TRANSIENT_NETWORK_CODES.has(err.code)) {
2153
2152
  throw err;
2154
2153
  }
2155
2154
  await this.connection.redis.zrem(notificationsKey, rawMember);
@@ -2295,7 +2294,7 @@ class Mailbox {
2295
2294
  try {
2296
2295
  await this.connection.refreshAndProcessListing();
2297
2296
  } catch (E) {
2298
- this.logger.error({ msg: 'Missing mailbox', err, E });
2297
+ this.logger.error({ msg: 'Failed to refresh listing after missing mailbox', err: E });
2299
2298
  }
2300
2299
  }
2301
2300
  throw err;
@@ -2566,7 +2565,7 @@ class Mailbox {
2566
2565
  messageData.flags.add('\\Seen');
2567
2566
  }
2568
2567
  } catch (err) {
2569
- this.logger.debug({ msg: 'Failed to mark message as Seen', message: message.uid, err });
2568
+ this.logger.debug({ msg: 'Failed to mark message as Seen', uid: message.uid, err });
2570
2569
  }
2571
2570
  }
2572
2571
 
@@ -2671,7 +2670,7 @@ class Mailbox {
2671
2670
  });
2672
2671
  }
2673
2672
  } catch (err) {
2674
- this.logger.error({ msg: 'Attachment error', uid: messageInfo.uid, partList, err });
2673
+ this.logger.error({ msg: 'Failed to download attachments', uid: messageInfo.uid, partList, err });
2675
2674
  }
2676
2675
  }
2677
2676
  }
@@ -3195,7 +3194,7 @@ class Mailbox {
3195
3194
  try {
3196
3195
  await this.connection.redis.hSetExists(this.connection.getAccountKey(), 'sync', new Date().toISOString());
3197
3196
  } catch (err) {
3198
- this.logger.error({ msg: 'Redis error', err });
3197
+ this.logger.error({ msg: 'Failed to update sync timestamp', err });
3199
3198
  }
3200
3199
  }
3201
3200
 
@@ -3375,7 +3374,7 @@ class Mailbox {
3375
3374
  return cursorPage;
3376
3375
  }
3377
3376
  } catch (err) {
3378
- this.logger.error({ msg: 'Cursor parsing error', cursorStr, err });
3377
+ this.logger.warn({ msg: 'Failed to parse paging cursor', cursorStr, err });
3379
3378
 
3380
3379
  let error = new Error('Invalid paging cursor');
3381
3380
  error.code = 'InvalidCursorValue';
@@ -225,7 +225,7 @@ class Subconnection extends EventEmitter {
225
225
  await this.parent.untrackConnection(imapClient);
226
226
  imapClient.log.info({ msg: 'Connection closed', account: this.account });
227
227
  } catch (err) {
228
- this.logger.error({ msg: 'Error updating connection count on close', account: this.account, err });
228
+ this.logger.error({ msg: 'Failed to update connection count on close', account: this.account, err });
229
229
  }
230
230
 
231
231
  try {
@@ -233,7 +233,10 @@ class Subconnection extends EventEmitter {
233
233
  await this.reconnect();
234
234
  }
235
235
  } catch (err) {
236
- this.logger.error({ msg: 'Reconnection error', err });
236
+ // Nothing else re-arms a subconnection after an unexpected close, so a failure
237
+ // here leaves this mailbox without its own IDLE channel until the account is
238
+ // reconnected - never demote this below error.
239
+ this.logger.error({ msg: 'Reconnection error', account: this.account, err });
237
240
  }
238
241
 
239
242
  imapClient = null;
@@ -250,11 +253,11 @@ class Subconnection extends EventEmitter {
250
253
  }
251
254
  } catch (err) {
252
255
  if (err.authenticationFailed) {
253
- this.logger.error({ msg: 'Failed to authenticate subconnection', account: this.account, err });
256
+ this.logger.warn({ msg: 'Failed to authenticate subconnection', account: this.account, err });
254
257
  this.state = 'authenticationError';
255
258
  this.disabledReason = 'Authentication failed';
256
259
  } else {
257
- this.logger.error({ msg: 'Failed to connect subconnection', account: this.account, err });
260
+ this.logger.warn({ msg: 'Failed to connect subconnection', account: this.account, err });
258
261
  this.state = 'connectError';
259
262
  this.disabledReason = 'Failed to connect';
260
263
  }
@@ -279,7 +282,7 @@ class Subconnection extends EventEmitter {
279
282
  return; //?
280
283
  }
281
284
 
282
- this.logger.info({ msg: 'Exists notification', account: this.account, event });
285
+ this.logger.trace({ msg: 'Exists notification', account: this.account, event });
283
286
 
284
287
  this.requestSync();
285
288
  } catch (err) {
@@ -293,7 +296,7 @@ class Subconnection extends EventEmitter {
293
296
  return; //?
294
297
  }
295
298
 
296
- this.logger.info({ msg: 'Flags notification', account: this.account, event });
299
+ this.logger.trace({ msg: 'Flags notification', account: this.account, event });
297
300
 
298
301
  this.requestSync();
299
302
  } catch (err) {
@@ -305,7 +308,7 @@ class Subconnection extends EventEmitter {
305
308
  }
306
309
 
307
310
  async expungeHandler(payload) {
308
- this.logger.info({ msg: 'Expunge notification', account: this.account, payload });
311
+ this.logger.trace({ msg: 'Expunge notification', account: this.account, payload });
309
312
 
310
313
  this.requestSync();
311
314
  }
@@ -11,6 +11,16 @@ const FETCH_BATCH_SIZE = Number(readEnvValue('EENGINE_FETCH_BATCH_SIZE') || conf
11
11
  // Do not check for flag updates using full sync more often than this value (30 minutes)
12
12
  const FULL_SYNC_DELAY = 30 * 60 * 1000;
13
13
 
14
+ // Signals that the sync was interrupted rather than that the command itself failed. The original
15
+ // failure is kept as `cause`, because on this path it is the only record of why the server dropped
16
+ // the connection (NO [OVERQUOTA], * BYE Too many connections, [SERVERBUG]).
17
+ function connectionClosedError(cause) {
18
+ const err = new Error('IMAP connection closed during sync', { cause });
19
+ err.code = 'IMAPConnectionClosing';
20
+ err.statusCode = 503;
21
+ return err;
22
+ }
23
+
14
24
  function checkFetchRetryTimeout(retryCount, startTime) {
15
25
  if (retryCount >= FETCH_RETRY_MIN_ATTEMPTS && Date.now() - startTime > FETCH_RETRY_MAX_TIME) {
16
26
  const err = new Error('FETCH retry time limit exceeded');
@@ -452,22 +462,16 @@ class SyncOperations {
452
462
  // Retry with exponential backoff
453
463
  if (!imapClient.usable) {
454
464
  // connection closed, throw so callers know sync was interrupted
455
- const connErr = new Error('IMAP connection closed during sync');
456
- connErr.code = 'IMAPConnectionClosing';
457
- connErr.statusCode = 503;
458
- throw connErr;
465
+ throw connectionClosedError(err);
459
466
  }
460
467
 
461
468
  const fetchRetryDelay = calculateFetchBackoff(++fetchRetryCount);
462
- this.logger.error({ msg: `FETCH failed, retrying in ${Math.round(fetchRetryDelay / 1000)}s`, err });
469
+ this.logger.warn({ msg: 'FETCH failed, retrying', retryDelay: Math.round(fetchRetryDelay), err });
463
470
  await new Promise(r => setTimeout(r, fetchRetryDelay));
464
471
 
465
472
  if (!imapClient.usable) {
466
473
  // connection closed, throw so callers know sync was interrupted
467
- const connErr = new Error('IMAP connection closed during sync');
468
- connErr.code = 'IMAPConnectionClosing';
469
- connErr.statusCode = 503;
470
- throw connErr;
474
+ throw connectionClosedError(err);
471
475
  }
472
476
 
473
477
  checkFetchRetryTimeout(fetchRetryCount, fetchStartTime);
@@ -531,7 +535,7 @@ class SyncOperations {
531
535
  // Get fresh imapClient reference inside retry loop
532
536
  let imapClient = this.connection.imapClient;
533
537
  if (!imapClient || !imapClient.usable) {
534
- this.logger.error({ msg: 'IMAP client not available for partial sync' });
538
+ this.logger.debug({ msg: 'IMAP client not available for partial sync' });
535
539
  let err = new Error('IMAP connection not available');
536
540
  err.code = 'IMAPConnectionClosing';
537
541
  err.statusCode = 503;
@@ -610,22 +614,16 @@ class SyncOperations {
610
614
  // Retry with exponential backoff
611
615
  if (!imapClient.usable) {
612
616
  // connection closed, throw so callers know sync was interrupted
613
- const connErr = new Error('IMAP connection closed during sync');
614
- connErr.code = 'IMAPConnectionClosing';
615
- connErr.statusCode = 503;
616
- throw connErr;
617
+ throw connectionClosedError(err);
617
618
  }
618
619
 
619
620
  const fetchRetryDelay = calculateFetchBackoff(++fetchRetryCount);
620
- this.logger.error({ msg: `FETCH failed, retrying in ${Math.round(fetchRetryDelay / 1000)}s` });
621
+ this.logger.warn({ msg: 'FETCH failed, retrying', retryDelay: Math.round(fetchRetryDelay), err });
621
622
  await new Promise(r => setTimeout(r, fetchRetryDelay));
622
623
 
623
624
  if (!imapClient.usable) {
624
625
  // connection closed, throw so callers know sync was interrupted
625
- const connErr = new Error('IMAP connection closed during sync');
626
- connErr.code = 'IMAPConnectionClosing';
627
- connErr.statusCode = 503;
628
- throw connErr;
626
+ throw connectionClosedError(err);
629
627
  }
630
628
 
631
629
  checkFetchRetryTimeout(fetchRetryCount, fetchStartTime);
@@ -669,8 +667,7 @@ class SyncOperations {
669
667
  msg: 'Starting full sync',
670
668
  code: 'full_sync_start',
671
669
  loopId,
672
- mailboxStatus,
673
- imapClientExists: mailboxStatus.messages
670
+ mailboxStatus
674
671
  });
675
672
 
676
673
  // Track highest sequence number seen
@@ -722,7 +719,7 @@ class SyncOperations {
722
719
  // This ensures we use the current connection state
723
720
  const imapClient = this.connection.imapClient;
724
721
  if (!imapClient || !imapClient.usable) {
725
- this.logger.error({ msg: 'IMAP client not available for FETCH' });
722
+ this.logger.debug({ msg: 'IMAP client not available for FETCH' });
726
723
  let err = new Error('IMAP connection not available');
727
724
  err.code = 'IMAPConnectionClosing';
728
725
  err.statusCode = 503;
@@ -847,25 +844,21 @@ class SyncOperations {
847
844
 
848
845
  fetchCompleted = true;
849
846
  } catch (err) {
850
- this.logger.error({
851
- msg: 'FETCH failed',
852
- code: 'fetch_error',
853
- loopId,
854
- batchNumber,
855
- range,
856
- retryCount: fetchRetryCount,
857
- totalMessages: mailboxStatus.messages,
858
- error: err.message,
859
- responseStatus: err.responseStatus,
860
- responseText: err.responseText
861
- });
862
-
863
847
  if (!imapClient.usable) {
864
- // connection closed, throw so callers know sync was interrupted
865
- const connErr = new Error('IMAP connection closed during sync');
866
- connErr.code = 'IMAPConnectionClosing';
867
- connErr.statusCode = 503;
868
- throw connErr;
848
+ // A connection dropped mid-FETCH is the most common way a full sync
849
+ // dies, and this path sets no syncError flag, so report it here
850
+ this.logger.warn({
851
+ msg: 'FETCH failed, connection is no longer usable',
852
+ code: 'fetch_error',
853
+ loopId,
854
+ batchNumber,
855
+ range,
856
+ retryCount: fetchRetryCount,
857
+ totalMessages: mailboxStatus.messages,
858
+ err
859
+ });
860
+
861
+ throw connectionClosedError(err);
869
862
  }
870
863
 
871
864
  try {
@@ -890,22 +883,29 @@ class SyncOperations {
890
883
  // Retry with exponential backoff
891
884
  totalFetchRetryCount++;
892
885
  const fetchRetryDelay = calculateFetchBackoff(++fetchRetryCount);
893
- this.logger.error({ msg: `FETCH failed, retrying in ${Math.round(fetchRetryDelay / 1000)}s`, loopId, batchNumber });
886
+ this.logger.warn({
887
+ msg: 'FETCH failed, retrying',
888
+ code: 'fetch_error',
889
+ loopId,
890
+ batchNumber,
891
+ range,
892
+ retryCount: fetchRetryCount,
893
+ totalMessages: mailboxStatus.messages,
894
+ retryDelay: Math.round(fetchRetryDelay),
895
+ err
896
+ });
894
897
  await new Promise(r => setTimeout(r, fetchRetryDelay));
895
898
 
896
899
  if (!imapClient.usable) {
897
900
  // connection closed, throw so callers know sync was interrupted
898
- const connErr = new Error('IMAP connection closed during sync');
899
- connErr.code = 'IMAPConnectionClosing';
900
- connErr.statusCode = 503;
901
- throw connErr;
901
+ throw connectionClosedError(err);
902
902
  }
903
903
 
904
904
  // Verify we're still on the correct mailbox after the delay
905
905
  // Another operation might have changed the mailbox while we were waiting
906
906
  const currentMailbox = this.connection.imapClient?.mailbox;
907
907
  if (!currentMailbox || currentMailbox.path !== this.mailbox.path) {
908
- this.logger.error({
908
+ this.logger.warn({
909
909
  msg: 'Mailbox changed during retry delay, aborting sync',
910
910
  expectedPath: this.mailbox.path,
911
911
  currentPath: currentMailbox ? currentMailbox.path : 'none',
@@ -41,6 +41,7 @@ const {
41
41
  AUTH_ERROR_NOTIFY,
42
42
  AUTH_SUCCESS_NOTIFY,
43
43
  CONNECT_ERROR_NOTIFY,
44
+ CONNECTION_CLOSING_CODES,
44
45
  DEFAULT_DOWNLOAD_CHUNK_SIZE,
45
46
  MAX_BACKOFF_DELAY,
46
47
  STABLE_CONNECTION_TIME,
@@ -242,7 +243,13 @@ class IMAPClient extends BaseClient {
242
243
  // check if we need to re-select main mailbox
243
244
  this.completedTimer = setTimeout(() => {
244
245
  clearTimeout(this.completedTimer);
245
- this.ensureMainMailbox().catch(err => this.logger.error({ msg: 'Failed to select main mailbox', err }));
246
+ this.ensureMainMailbox().catch(err => {
247
+ if (CONNECTION_CLOSING_CODES.has(err.code)) {
248
+ this.logger.debug({ msg: 'Select skipped, connection closing', err });
249
+ } else {
250
+ this.logger.error({ msg: 'Failed to select main mailbox', err });
251
+ }
252
+ });
246
253
  }, ENSURE_MAIN_TTL);
247
254
  }
248
255
 
@@ -288,7 +295,7 @@ class IMAPClient extends BaseClient {
288
295
  return connectionClient;
289
296
  }
290
297
  } catch (err) {
291
- this.logger.error({ msg: 'Failed to acquire command connection', reason, err });
298
+ this.logger.warn({ msg: 'Failed to acquire command connection', reason, err });
292
299
  }
293
300
 
294
301
  // Fall back to primary connection
@@ -324,7 +331,6 @@ class IMAPClient extends BaseClient {
324
331
  this.logger.debug({ msg: 'Acquiring connection lock', lockKey });
325
332
  connectLock = await lock.waitAcquireLock(lockKey, 5 * 60 * 1000, 1 * 60 * 1000);
326
333
  if (!connectLock.success) {
327
- this.logger.error({ msg: 'Failed to get lock', lockKey });
328
334
  throw new Error('Failed to get connection lock');
329
335
  }
330
336
  this.logger.debug({ msg: 'Acquired connection lock', lockKey, index: connectLock.index });
@@ -1002,7 +1008,7 @@ class IMAPClient extends BaseClient {
1002
1008
  }
1003
1009
  await mailbox.onExists(event);
1004
1010
  } catch (err) {
1005
- imapClient.log.error({ msg: 'Exists error', err });
1011
+ imapClient.log.error({ msg: 'Failed to process EXISTS notification', path: event?.path, err });
1006
1012
  }
1007
1013
  }
1008
1014
 
@@ -1022,10 +1028,10 @@ class IMAPClient extends BaseClient {
1022
1028
  // that arrived from a replacement connection after a reconnect
1023
1029
  await mailbox.onOpen(event, imapClient);
1024
1030
  } catch (err) {
1025
- if (err.code === 'IMAPConnectionClosing') {
1031
+ if (CONNECTION_CLOSING_CODES.has(err.code)) {
1026
1032
  imapClient.log.debug({ msg: 'Open skipped, connection closing', err });
1027
1033
  } else {
1028
- imapClient.log.error({ msg: 'Open error', err });
1034
+ imapClient.log.error({ msg: 'Failed to process mailbox open notification', path: event?.path, err });
1029
1035
  }
1030
1036
  }
1031
1037
  }
@@ -1043,7 +1049,7 @@ class IMAPClient extends BaseClient {
1043
1049
  }
1044
1050
  await mailbox.onClose(event);
1045
1051
  } catch (err) {
1046
- imapClient.log.error({ msg: 'Close error', err });
1052
+ imapClient.log.error({ msg: 'Failed to process mailbox close notification', path: event?.path, err });
1047
1053
  }
1048
1054
  }
1049
1055
 
@@ -1060,7 +1066,7 @@ class IMAPClient extends BaseClient {
1060
1066
  }
1061
1067
  await mailbox.onFlags(event);
1062
1068
  } catch (err) {
1063
- imapClient.log.error({ msg: 'Flags error', err });
1069
+ imapClient.log.error({ msg: 'Failed to process flag change notification', path: event?.path, err });
1064
1070
  }
1065
1071
  }
1066
1072
 
@@ -1323,11 +1329,10 @@ class IMAPClient extends BaseClient {
1323
1329
  retryCount = 0;
1324
1330
  })
1325
1331
  .catch(err => {
1326
- this.logger.error({ msg: 'Mailbox Sync Error', err, retryCount });
1327
1332
  retryCount++;
1328
1333
  // Exponential backoff with max delay of 30 seconds
1329
1334
  const retryDelay = Math.min(30000, 2000 * Math.pow(2, retryCount));
1330
- this.logger.warn({ msg: 'Scheduling sync retry with backoff', retryDelay, retryCount });
1335
+ this.logger.warn({ msg: 'Failed to sync mailboxes, will retry', err, retryCount, retryDelay });
1331
1336
  setTimeout(setSyncTimer, retryDelay);
1332
1337
  });
1333
1338
  }, this.resyncDelay);
@@ -1398,7 +1403,7 @@ class IMAPClient extends BaseClient {
1398
1403
  serverResponseCode: 'HTTPRequestError'
1399
1404
  });
1400
1405
  ctx.logger.error({
1401
- account: this.account,
1406
+ msg: 'Failed to resolve credentials from authentication server',
1402
1407
  err
1403
1408
  });
1404
1409
  ctx.state = AUTH_ERROR_NOTIFY;
@@ -1414,7 +1419,7 @@ class IMAPClient extends BaseClient {
1414
1419
  // Set local address for outgoing connections (for IP rotation)
1415
1420
  const localAddress = await getLocalAddress(redis, 'imap', this.account);
1416
1421
  imapConnectionConfig.tls.localAddress = localAddress.localAddress;
1417
- this.logger.info({
1422
+ this.logger.debug({
1418
1423
  msg: 'Selected local address',
1419
1424
  account: this.account,
1420
1425
  proto: 'IMAP',
@@ -1706,7 +1711,10 @@ class IMAPClient extends BaseClient {
1706
1711
  }
1707
1712
  }
1708
1713
  } catch (err) {
1709
- imapClient.log.error({ msg: 'Reconnection error', err });
1714
+ // This is the only path that re-arms the connection after an unexpected close.
1715
+ // If it throws, nothing else reconnects the account, so it stays offline until
1716
+ // the worker restarts - never demote this below error.
1717
+ imapClient.log.error({ msg: 'Reconnection error', account: this.account, err });
1710
1718
  }
1711
1719
 
1712
1720
  imapClient = null;
@@ -1736,7 +1744,7 @@ class IMAPClient extends BaseClient {
1736
1744
  let prevConnectedCount = await this.redis.hget(this.getAccountKey(), `state:count:connected`);
1737
1745
  let isFirstSuccessfulConnection = prevConnectedCount === '0'; // string zero means the account has been initialized but not yet connected
1738
1746
 
1739
- let isiInitial = !!isFirstSuccessfulConnection;
1747
+ let isInitial = !!isFirstSuccessfulConnection;
1740
1748
 
1741
1749
  if (!isFirstSuccessfulConnection) {
1742
1750
  // check if the connection was previously in an errored state
@@ -1757,18 +1765,20 @@ class IMAPClient extends BaseClient {
1757
1765
 
1758
1766
  // Send appropriate notifications based on connection history
1759
1767
  if (isFirstSuccessfulConnection) {
1760
- this.logger.info({ msg: 'Successful login without a previous active session', account: this.account, isiInitial, prevActive: false });
1768
+ this.logger.info({ msg: 'Successful login without a previous active session', account: this.account, isInitial, prevActive: false });
1761
1769
  await this.notify(false, AUTH_SUCCESS_NOTIFY, {
1762
1770
  user: imapConfig.auth.user
1763
1771
  });
1764
1772
  } else {
1765
- this.logger.info({ msg: 'Successful login with a previous active session', account: this.account, isiInitial, prevActive: true });
1773
+ this.logger.info({ msg: 'Successful login with a previous active session', account: this.account, isInitial, prevActive: true });
1766
1774
  }
1767
1775
 
1768
1776
  // Set up subconnections for monitoring multiple folders
1769
1777
  this.setupSubConnections()
1770
1778
  .then(result => {
1771
- this.logger.info({ msg: 'Set up subconnections', account: this.account, result });
1779
+ if (result !== null) {
1780
+ this.logger.info({ msg: 'Set up subconnections', account: this.account, result });
1781
+ }
1772
1782
  })
1773
1783
  .catch(err => {
1774
1784
  this.logger.error({ msg: 'Failed to set up subconnections', account: this.account, err });
@@ -1809,14 +1819,14 @@ class IMAPClient extends BaseClient {
1809
1819
  // webhook payloads never render as "[object Object]"
1810
1820
  let errorResponse = (typeof err.response === 'string' && err.response) || err.responseText;
1811
1821
  if (err.authenticationFailed) {
1812
- this.logger.error({ msg: 'Failed to authenticate', account: this.account, err });
1822
+ this.logger.warn({ msg: 'Failed to authenticate', account: this.account, err });
1813
1823
  await this.notify(false, AUTH_ERROR_NOTIFY, {
1814
1824
  response: errorResponse,
1815
1825
  serverResponseCode: err.serverResponseCode
1816
1826
  });
1817
1827
  this.state = 'authenticationError';
1818
1828
  } else {
1819
- this.logger.error({ msg: 'Failed to connect', account: this.account, err });
1829
+ this.logger.warn({ msg: 'Failed to connect', account: this.account, err });
1820
1830
  await this.notify(false, CONNECT_ERROR_NOTIFY, {
1821
1831
  response: errorResponse || err.message,
1822
1832
  serverResponseCode: err.serverResponseCode || err.code
@@ -1903,7 +1913,7 @@ class IMAPClient extends BaseClient {
1903
1913
  this.closeSubconnections();
1904
1914
  }
1905
1915
 
1906
- this.logger.info({ msg: 'Closed account', account: this.account });
1916
+ this.logger.info({ msg: 'Deleted account', account: this.account });
1907
1917
  }
1908
1918
 
1909
1919
  /**
@@ -2191,7 +2201,7 @@ class IMAPClient extends BaseClient {
2191
2201
  // force sync target mailbox to show moved messages
2192
2202
  let targetMailbox = this.mailboxes.get(normalizePath(target.path));
2193
2203
  if (targetMailbox) {
2194
- targetMailbox.sync().catch(err => this.logger.error({ msg: 'Mailbox sync error', path: target.path, err }));
2204
+ targetMailbox.sync().catch(err => this.logger.warn({ msg: 'Failed to sync mailbox', path: target.path, err }));
2195
2205
  }
2196
2206
 
2197
2207
  return res;
@@ -2250,7 +2260,7 @@ class IMAPClient extends BaseClient {
2250
2260
  if (res && res.moved && res.moved.destination) {
2251
2261
  let targetMailbox = this.mailboxes.get(normalizePath(res.moved.destination));
2252
2262
  if (targetMailbox) {
2253
- targetMailbox.sync().catch(err => this.logger.error({ msg: 'Mailbox sync error', path: res && res.moved && res.moved.destination, err }));
2263
+ targetMailbox.sync().catch(err => this.logger.warn({ msg: 'Failed to sync mailbox', path: res && res.moved && res.moved.destination, err }));
2254
2264
  }
2255
2265
  }
2256
2266
 
@@ -2489,7 +2499,7 @@ class IMAPClient extends BaseClient {
2489
2499
  */
2490
2500
  runPostListing() {
2491
2501
  this.refreshAndProcessListing().catch(err => {
2492
- this.logger.error({ msg: 'List refresh error', err });
2502
+ this.logger.warn({ msg: 'Failed to refresh folder listing', err });
2493
2503
  });
2494
2504
  }
2495
2505
 
@@ -2713,7 +2723,7 @@ class IMAPClient extends BaseClient {
2713
2723
  if (this.imapClient && connectionClient === this.imapClient && this.imapClient.mailbox && !this.imapClient.idling) {
2714
2724
  // force back to IDLE
2715
2725
  this.imapClient.idle().catch(err => {
2716
- this.logger.error({ msg: 'IDLE error', err });
2726
+ this.logger.warn({ msg: 'IDLE error', err });
2717
2727
  });
2718
2728
  }
2719
2729
 
@@ -2772,7 +2782,7 @@ class IMAPClient extends BaseClient {
2772
2782
  this.logger.error({ msg: 'Failed to process listing', err: listingErr });
2773
2783
  });
2774
2784
  } catch (E) {
2775
- this.logger.error({ msg: 'Missing mailbox', err, E });
2785
+ this.logger.error({ msg: 'Failed to refresh listing after missing mailbox', err: E });
2776
2786
  }
2777
2787
  }
2778
2788
 
@@ -2794,7 +2804,7 @@ class IMAPClient extends BaseClient {
2794
2804
  }
2795
2805
  await mailbox.onExpunge(payload);
2796
2806
  } catch (err) {
2797
- this.logger.error({ msg: 'Expunge error', err });
2807
+ this.logger.error({ msg: 'Failed to process EXPUNGE notification', path: payload?.path, err });
2798
2808
  }
2799
2809
  }
2800
2810
 
@@ -48,7 +48,7 @@ class SmtpConfigBuilder {
48
48
  const gatewayData = await gatewayObject.loadGatewayData();
49
49
  return { gatewayData, gatewayObject };
50
50
  } catch (err) {
51
- this.logger.info({
51
+ this.logger.warn({
52
52
  msg: 'Failed to load gateway data',
53
53
  messageId,
54
54
  gateway: gatewayId,
@@ -139,7 +139,7 @@ class SmtpConfigBuilder {
139
139
  } catch (err) {
140
140
  err.authenticationFailed = true;
141
141
  this.logger.error({
142
- account: this.account,
142
+ msg: 'Failed to resolve SMTP credentials from the authentication server',
143
143
  err
144
144
  });
145
145
  throw err;
@@ -164,7 +164,7 @@ class SmtpConfigBuilder {
164
164
  // Get local address for outbound connection
165
165
  const { localAddress: address, name, addressSelector: selector } = await getLocalAddress(this.redis, 'smtp', this.account, data.localAddress);
166
166
 
167
- this.logger.info({
167
+ this.logger.debug({
168
168
  msg: 'Selected local address',
169
169
  account: this.account,
170
170
  proto: 'SMTP',