emailengine-app 2.77.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 (189) hide show
  1. package/.github/workflows/test.yml +80 -0
  2. package/.ncurc.js +23 -13
  3. package/.release-please-manifest.json +1 -1
  4. package/CHANGELOG.md +60 -0
  5. package/bin/emailengine.js +1 -1
  6. package/config/e2e.toml +2 -1
  7. package/config/test.toml +2 -1
  8. package/data/google-crawlers.json +1 -1
  9. package/encrypt.js +1 -1
  10. package/lib/account/expected-identity.js +88 -0
  11. package/lib/account.js +145 -61
  12. package/lib/api-reference/format.js +105 -4
  13. package/lib/api-reference/index.js +24 -7
  14. package/lib/api-reference/model.js +148 -21
  15. package/lib/api-reference/schema-tree.js +282 -28
  16. package/lib/api-routes/account-routes.js +99 -36
  17. package/lib/api-routes/behavior-notes.js +3 -0
  18. package/lib/api-routes/blocklist-routes.js +21 -47
  19. package/lib/api-routes/chat-routes.js +10 -12
  20. package/lib/api-routes/delivery-test-routes.js +6 -26
  21. package/lib/api-routes/export-routes.js +2 -0
  22. package/lib/api-routes/gateway-routes.js +52 -11
  23. package/lib/api-routes/license-routes.js +2 -0
  24. package/lib/api-routes/mailbox-routes.js +29 -26
  25. package/lib/api-routes/message-routes.js +27 -21
  26. package/lib/api-routes/oauth2-app-routes.js +11 -29
  27. package/lib/api-routes/operation-impact.js +80 -0
  28. package/lib/api-routes/outbox-routes.js +15 -5
  29. package/lib/api-routes/permission-map.js +397 -0
  30. package/lib/api-routes/route-helpers.js +223 -9
  31. package/lib/api-routes/route-metadata.js +28 -0
  32. package/lib/api-routes/settings-routes.js +30 -25
  33. package/lib/api-routes/stats-routes.js +2 -2
  34. package/lib/api-routes/submit-routes.js +53 -31
  35. package/lib/api-routes/template-routes.js +3 -0
  36. package/lib/api-routes/token-routes.js +319 -33
  37. package/lib/api-routes/webhook-route-routes.js +14 -4
  38. package/lib/append-list.js +3 -14
  39. package/lib/arf-detect.js +23 -1
  40. package/lib/auth-token.js +80 -8
  41. package/lib/autodetect-imap-settings.js +40 -16
  42. package/lib/base32.js +30 -0
  43. package/lib/bounce-detect.js +182 -62
  44. package/lib/consts.js +10 -0
  45. package/lib/db.js +20 -2
  46. package/lib/delivery-error.js +30 -1
  47. package/lib/egress-filter.js +89 -8
  48. package/lib/email-client/base-client.js +35 -113
  49. package/lib/email-client/gmail-client.js +22 -13
  50. package/lib/email-client/imap/listing-diff.js +3 -3
  51. package/lib/email-client/imap/mailbox.js +28 -93
  52. package/lib/email-client/imap/subconnection.js +10 -7
  53. package/lib/email-client/imap/sync-operations.js +46 -46
  54. package/lib/email-client/imap-client.js +39 -28
  55. package/lib/email-client/message-builder.js +15 -15
  56. package/lib/email-client/notification-handler.js +1 -1
  57. package/lib/email-client/outlook/graph-api.js +10 -4
  58. package/lib/email-client/outlook-client.js +54 -55
  59. package/lib/email-client/smtp-pool-manager.js +1 -1
  60. package/lib/enum-descriptions.js +92 -2
  61. package/lib/export.js +2 -2
  62. package/lib/field-usage.js +133 -0
  63. package/lib/gateway.js +2 -2
  64. package/lib/get-raw-email.js +1 -1
  65. package/lib/imapproxy/imap-core/lib/commands/authenticate-plain.js +3 -3
  66. package/lib/imapproxy/imap-core/lib/commands/id.js +2 -13
  67. package/lib/imapproxy/imap-core/lib/commands/starttls.js +1 -1
  68. package/lib/imapproxy/imap-core/lib/imap-command.js +21 -5
  69. package/lib/imapproxy/imap-core/lib/imap-connection.js +17 -7
  70. package/lib/imapproxy/imap-core/lib/imap-server.js +2 -2
  71. package/lib/imapproxy/imap-server.js +40 -10
  72. package/lib/license-beacon.js +5 -10
  73. package/lib/lists.js +49 -1
  74. package/lib/llm-pre-process.js +6 -6
  75. package/lib/logger.js +5 -1
  76. package/lib/metrics-collector.js +2 -2
  77. package/lib/msgpack.js +62 -0
  78. package/lib/oauth/decode-jwt-payload.js +39 -0
  79. package/lib/oauth/gmail.js +9 -12
  80. package/lib/oauth/mail-ru.js +5 -7
  81. package/lib/oauth/outlook-identity.js +61 -0
  82. package/lib/oauth/outlook.js +9 -9
  83. package/lib/oauth/pubsub/google.js +25 -10
  84. package/lib/oauth/retry-setup.js +38 -0
  85. package/lib/oauth/scope-checker.js +1 -1
  86. package/lib/oauth2-apps.js +224 -295
  87. package/lib/openapi/build-document.js +15 -7
  88. package/lib/openapi/joi-schema.js +20 -0
  89. package/lib/outbox.js +145 -14
  90. package/lib/pre-process.js +9 -9
  91. package/lib/queue-stats.js +49 -0
  92. package/lib/read-env-value.js +37 -0
  93. package/lib/reconnection-manager.js +2 -2
  94. package/lib/rewrite-text-nodes.js +4 -3
  95. package/lib/routes-ui.js +4 -0
  96. package/lib/schemas.js +223 -155
  97. package/lib/settings.js +84 -5
  98. package/lib/sub-script.js +2 -1
  99. package/lib/swagger-options.js +2 -1
  100. package/lib/templates.js +5 -5
  101. package/lib/threads.js +2 -2
  102. package/lib/token-audit-log.js +208 -0
  103. package/lib/token-permission-view.js +219 -0
  104. package/lib/token-permissions.js +172 -0
  105. package/lib/tokens.js +100 -16
  106. package/lib/tools.js +259 -85
  107. package/lib/totp.js +67 -0
  108. package/lib/ui-routes/account-routes.js +122 -26
  109. package/lib/ui-routes/admin-config-routes.js +20 -17
  110. package/lib/ui-routes/admin-entities-routes.js +66 -22
  111. package/lib/ui-routes/auth-routes.js +36 -48
  112. package/lib/ui-routes/export-routes.js +10 -4
  113. package/lib/ui-routes/oauth-config-routes.js +5 -5
  114. package/lib/ui-routes/reference-routes.js +11 -8
  115. package/lib/ui-routes/route-helpers.js +79 -2
  116. package/lib/ui-routes/settings-page.js +1 -1
  117. package/lib/ui-routes/smtp-test-routes.js +1 -1
  118. package/lib/ui-routes/suppression-list-routes.js +294 -0
  119. package/lib/ui-routes/unsubscribe-routes.js +19 -29
  120. package/lib/utils/is-email.js +34 -0
  121. package/lib/utils/network.js +2 -2
  122. package/lib/utils/to-camel-case.js +17 -0
  123. package/lib/web-safe-html.js +1 -1
  124. package/lib/webhook-egress.js +37 -0
  125. package/lib/webhook-routing.js +80 -0
  126. package/lib/webhooks.js +21 -15
  127. package/package.json +26 -27
  128. package/sbom.json +1 -0
  129. package/server.js +81 -42
  130. package/static/css/flyonui.css +1 -1
  131. package/static/css/public.css +3 -0
  132. package/static/css/src/app.tailwind.css +159 -9
  133. package/static/js/app.js +69 -0
  134. package/static/js/reference.js +741 -10
  135. package/static/js/ui.js +43 -0
  136. package/static/licenses.html +698 -1590
  137. package/translations/README.md +64 -0
  138. package/translations/de.mo +0 -0
  139. package/translations/de.po +164 -120
  140. package/translations/en.po +200 -161
  141. package/translations/et.mo +0 -0
  142. package/translations/et.po +163 -120
  143. package/translations/fr.mo +0 -0
  144. package/translations/fr.po +163 -120
  145. package/translations/ja.mo +0 -0
  146. package/translations/ja.po +163 -120
  147. package/translations/messages.pot +94 -64
  148. package/translations/nl.mo +0 -0
  149. package/translations/nl.po +164 -120
  150. package/translations/pl.mo +0 -0
  151. package/translations/pl.po +163 -120
  152. package/views/account-identity-error.hbs +34 -0
  153. package/views/accounts/account.hbs +69 -7
  154. package/views/accounts/browse.hbs +18 -35
  155. package/views/accounts/edit.hbs +1 -0
  156. package/views/accounts/register/imap.hbs +12 -2
  157. package/views/config/logging.hbs +6 -0
  158. package/views/config/oauth/app.hbs +0 -2
  159. package/views/config/security.hbs +13 -0
  160. package/views/layout/app.hbs +29 -5
  161. package/views/oauth-scope-error.hbs +1 -1
  162. package/views/partials/oauth_form.hbs +0 -15
  163. package/views/partials/reference/disclosure.hbs +8 -2
  164. package/views/partials/reference/nav.hbs +36 -9
  165. package/views/partials/reference/operation.hbs +48 -14
  166. package/views/partials/reference/params.hbs +17 -1
  167. package/views/partials/reference/schema-node.hbs +112 -54
  168. package/views/partials/reference/schema-tools.hbs +25 -0
  169. package/views/partials/reference/token-alert.hbs +35 -10
  170. package/views/partials/reference/try-it.hbs +84 -11
  171. package/views/partials/side_menu.hbs +1 -0
  172. package/views/partials/ui/checkbox.hbs +2 -2
  173. package/views/partials/ui/tabs.hbs +7 -1
  174. package/views/reference/index.hbs +1 -1
  175. package/views/reference/token.hbs +4 -0
  176. package/views/suppression-lists/index.hbs +85 -0
  177. package/views/suppression-lists/list.hbs +87 -0
  178. package/views/templates/index.hbs +8 -2
  179. package/views/tokens/index.hbs +31 -4
  180. package/views/tokens/new.hbs +324 -2
  181. package/workers/api.js +299 -140
  182. package/workers/documents.js +46 -26
  183. package/workers/export.js +20 -8
  184. package/workers/imap-proxy.js +2 -2
  185. package/workers/imap.js +13 -7
  186. package/workers/smtp.js +13 -7
  187. package/workers/submit.js +41 -31
  188. package/workers/webhooks.js +60 -37
  189. package/lib/feature-flags.js +0 -48
@@ -11,12 +11,12 @@ const {
11
11
  mailboxPathHash,
12
12
  getMailboxStatusKey
13
13
  } = require('../../tools');
14
- const msgpack = require('msgpack5')();
14
+ const msgpack = require('../../msgpack');
15
15
  const he = require('he');
16
16
  const libmime = require('libmime');
17
17
  const settings = require('../../settings');
18
- const { bounceDetect } = require('../../bounce-detect');
19
- const { arfDetect } = require('../../arf-detect');
18
+ const { bounceDetect, applyDeliveryReport } = require('../../bounce-detect');
19
+ const { arfDetect, camelCaseComplaint } = require('../../arf-detect');
20
20
  const appendList = require('../../append-list');
21
21
  const { messageWebSafeHtml } = require('../../web-safe-html');
22
22
  const simpleParser = require('mailparser').simpleParser;
@@ -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
 
@@ -1086,16 +1090,7 @@ class Mailbox {
1086
1090
 
1087
1091
  if (report && report.arf && report.arf['original-rcpt-to'] && report.arf['original-rcpt-to'].length) {
1088
1092
  // Valid complaint found - prepare notification data
1089
- let complaint = {};
1090
- for (let subKey of ['arf', 'headers']) {
1091
- for (let key of Object.keys(report[subKey])) {
1092
- if (!complaint[subKey]) {
1093
- complaint[subKey] = {};
1094
- }
1095
- // Convert kebab-case to camelCase
1096
- complaint[subKey][key.replace(/-(.)/g, (o, c) => c.toUpperCase())] = report[subKey][key];
1097
- }
1098
- }
1093
+ let complaint = camelCaseComplaint(report);
1099
1094
 
1100
1095
  complaintNotifyInfo = Object.assign({ complaintMessage: messageInfo.id }, complaint);
1101
1096
 
@@ -1128,62 +1123,7 @@ class Mailbox {
1128
1123
  let parsed = await simpleParser(sourceStream, { keepDeliveryStatus: true });
1129
1124
  if (parsed) {
1130
1125
  content = { parsed };
1131
-
1132
- // Extract delivery status information
1133
- let deliveryStatus = parsed.attachments.find(attachment => attachment.contentType === 'message/delivery-status');
1134
- if (deliveryStatus) {
1135
- let deliveryEntries = libmime.decodeHeaders((deliveryStatus.content || '').toString().trim());
1136
- let structured = {};
1137
-
1138
- // Parse delivery status headers
1139
- for (let key of Object.keys(deliveryEntries)) {
1140
- if (!key) {
1141
- continue;
1142
- }
1143
- let displayKey = key.replace(/-(.)/g, (m, c) => c.toUpperCase());
1144
- let value = deliveryEntries[key].at(-1);
1145
- if (typeof value === 'string') {
1146
- // Parse structured values like "rfc822;example.com"
1147
- let m = value.match(/^([^\s;]+);/);
1148
- if (m) {
1149
- value = {
1150
- label: m[1],
1151
- value: value.substring(m[0].length).trim()
1152
- };
1153
- } else {
1154
- switch (key) {
1155
- case 'arrival-date': {
1156
- value.trim();
1157
- let date = new Date(value);
1158
- if (date.toString() !== 'Invalid Date') {
1159
- value = date.toISOString();
1160
- }
1161
- structured[displayKey] = value;
1162
- break;
1163
- }
1164
- default:
1165
- structured[displayKey] = value.trim();
1166
- }
1167
- }
1168
- } else {
1169
- // ???
1170
- structured[displayKey] = value;
1171
- }
1172
- }
1173
-
1174
- // Only consider as delivery report if action indicates delivery or delay
1175
- if (/^delivered|^delayed/i.test(structured.action)) {
1176
- this.logger.debug({
1177
- msg: 'Detected delivery report',
1178
- id: messageInfo.id,
1179
- uid: messageInfo.uid,
1180
- messageId: messageInfo.messageId,
1181
- report: structured
1182
- });
1183
-
1184
- messageInfo.deliveryReport = structured;
1185
- }
1186
- }
1126
+ applyDeliveryReport(parsed, messageInfo, this.logger);
1187
1127
  }
1188
1128
  } catch (err) {
1189
1129
  this.logger.error({
@@ -1327,7 +1267,7 @@ class Mailbox {
1327
1267
  break;
1328
1268
  }
1329
1269
  } catch (err) {
1330
- 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 });
1331
1271
  break;
1332
1272
  }
1333
1273
  }
@@ -1508,7 +1448,7 @@ class Mailbox {
1508
1448
  })
1509
1449
  );
1510
1450
  } catch (err) {
1511
- this.logger.error({
1451
+ this.logger.warn({
1512
1452
  msg: 'Failed to parse calendar event',
1513
1453
  attachment: Object.assign({}, attachment, { content: `${contentBuf.length} bytes` }),
1514
1454
  err
@@ -1636,7 +1576,7 @@ class Mailbox {
1636
1576
  time: Date.now()
1637
1577
  })
1638
1578
  );
1639
- this.logger.error({ msg: 'Failed to fetch embeddings OpenAI', err });
1579
+ this.logger.error({ msg: 'Failed to fetch embeddings from OpenAI', err });
1640
1580
  }
1641
1581
  }
1642
1582
  }
@@ -1698,7 +1638,7 @@ class Mailbox {
1698
1638
  }
1699
1639
  }
1700
1640
  } catch (err) {
1701
- 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 });
1702
1642
  }
1703
1643
  }
1704
1644
 
@@ -2208,12 +2148,7 @@ class Mailbox {
2208
2148
  await this.processNew(messageData, messageFetchOptions, canSync, storedStatus);
2209
2149
  await this.connection.redis.zrem(notificationsKey, rawMember);
2210
2150
  } catch (err) {
2211
- if (
2212
- err.code === 'NoConnection' ||
2213
- err.code === 'IMAPConnectionClosing' ||
2214
- err.code === 'EConnectionClosed' ||
2215
- TRANSIENT_NETWORK_CODES.has(err.code)
2216
- ) {
2151
+ if (CONNECTION_CLOSING_CODES.has(err.code) || TRANSIENT_NETWORK_CODES.has(err.code)) {
2217
2152
  throw err;
2218
2153
  }
2219
2154
  await this.connection.redis.zrem(notificationsKey, rawMember);
@@ -2359,7 +2294,7 @@ class Mailbox {
2359
2294
  try {
2360
2295
  await this.connection.refreshAndProcessListing();
2361
2296
  } catch (E) {
2362
- this.logger.error({ msg: 'Missing mailbox', err, E });
2297
+ this.logger.error({ msg: 'Failed to refresh listing after missing mailbox', err: E });
2363
2298
  }
2364
2299
  }
2365
2300
  throw err;
@@ -2630,7 +2565,7 @@ class Mailbox {
2630
2565
  messageData.flags.add('\\Seen');
2631
2566
  }
2632
2567
  } catch (err) {
2633
- 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 });
2634
2569
  }
2635
2570
  }
2636
2571
 
@@ -2735,7 +2670,7 @@ class Mailbox {
2735
2670
  });
2736
2671
  }
2737
2672
  } catch (err) {
2738
- 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 });
2739
2674
  }
2740
2675
  }
2741
2676
  }
@@ -3259,7 +3194,7 @@ class Mailbox {
3259
3194
  try {
3260
3195
  await this.connection.redis.hSetExists(this.connection.getAccountKey(), 'sync', new Date().toISOString());
3261
3196
  } catch (err) {
3262
- this.logger.error({ msg: 'Redis error', err });
3197
+ this.logger.error({ msg: 'Failed to update sync timestamp', err });
3263
3198
  }
3264
3199
  }
3265
3200
 
@@ -3439,7 +3374,7 @@ class Mailbox {
3439
3374
  return cursorPage;
3440
3375
  }
3441
3376
  } catch (err) {
3442
- this.logger.error({ msg: 'Cursor parsing error', cursorStr, err });
3377
+ this.logger.warn({ msg: 'Failed to parse paging cursor', cursorStr, err });
3443
3378
 
3444
3379
  let error = new Error('Invalid paging cursor');
3445
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',