emailengine-app 2.78.0 → 2.79.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 (155) hide show
  1. package/.ncurc.js +23 -13
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +68 -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 +112 -36
  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 +401 -0
  24. package/lib/api-routes/route-helpers.js +294 -9
  25. package/lib/api-routes/route-metadata.js +28 -0
  26. package/lib/api-routes/settings-routes.js +66 -38
  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 +526 -72
  31. package/lib/api-routes/webhook-route-routes.js +14 -4
  32. package/lib/arf-detect.js +17 -4
  33. package/lib/auth-token.js +80 -8
  34. package/lib/bounce-detect.js +28 -17
  35. package/lib/consts.js +16 -0
  36. package/lib/db.js +26 -2
  37. package/lib/delivery-error.js +30 -1
  38. package/lib/email-client/base-client.js +27 -41
  39. package/lib/email-client/gmail-client.js +23 -17
  40. package/lib/email-client/imap/mailbox.js +58 -59
  41. package/lib/email-client/imap/subconnection.js +10 -7
  42. package/lib/email-client/imap/sync-operations.js +46 -46
  43. package/lib/email-client/imap-client.js +85 -28
  44. package/lib/email-client/message-builder.js +3 -3
  45. package/lib/email-client/notification-handler.js +1 -1
  46. package/lib/email-client/outlook/graph-api.js +10 -4
  47. package/lib/email-client/outlook-client.js +56 -64
  48. package/lib/email-client/smtp-pool-manager.js +1 -1
  49. package/lib/enum-descriptions.js +92 -2
  50. package/lib/export.js +1 -1
  51. package/lib/field-usage.js +133 -0
  52. package/lib/gateway.js +1 -1
  53. package/lib/imapproxy/imap-core/lib/commands/authenticate-plain.js +3 -3
  54. package/lib/imapproxy/imap-core/lib/commands/id.js +2 -13
  55. package/lib/imapproxy/imap-core/lib/commands/starttls.js +1 -1
  56. package/lib/imapproxy/imap-core/lib/imap-command.js +21 -5
  57. package/lib/imapproxy/imap-core/lib/imap-connection.js +15 -5
  58. package/lib/imapproxy/imap-server.js +27 -7
  59. package/lib/license-beacon.js +4 -9
  60. package/lib/lists.js +49 -1
  61. package/lib/llm-pre-process.js +5 -5
  62. package/lib/logger.js +5 -1
  63. package/lib/lua/h-set-new-mark.lua +36 -0
  64. package/lib/message-port-stream.js +84 -1
  65. package/lib/metrics-collector.js +2 -2
  66. package/lib/oauth/gmail.js +9 -12
  67. package/lib/oauth/mail-ru.js +5 -7
  68. package/lib/oauth/outlook.js +9 -9
  69. package/lib/oauth/pubsub/google.js +25 -10
  70. package/lib/oauth/scope-checker.js +1 -1
  71. package/lib/oauth2-apps.js +290 -292
  72. package/lib/openapi/build-document.js +20 -8
  73. package/lib/openapi/joi-schema.js +20 -0
  74. package/lib/outbox.js +85 -17
  75. package/lib/pre-process.js +8 -8
  76. package/lib/queue-stats.js +49 -0
  77. package/lib/read-env-value.js +1 -1
  78. package/lib/reconnection-manager.js +2 -2
  79. package/lib/rewrite-text-nodes.js +4 -3
  80. package/lib/routes-ui.js +4 -0
  81. package/lib/schemas.js +218 -162
  82. package/lib/settings.js +98 -5
  83. package/lib/sub-script.js +2 -1
  84. package/lib/swagger-options.js +2 -1
  85. package/lib/templates.js +4 -4
  86. package/lib/threads.js +2 -2
  87. package/lib/token-audit-log.js +231 -0
  88. package/lib/token-permission-view.js +219 -0
  89. package/lib/token-permissions.js +172 -0
  90. package/lib/tokens.js +247 -66
  91. package/lib/tools.js +142 -37
  92. package/lib/ui-routes/account-routes.js +42 -15
  93. package/lib/ui-routes/admin-config-routes.js +18 -10
  94. package/lib/ui-routes/admin-entities-routes.js +117 -38
  95. package/lib/ui-routes/auth-routes.js +30 -24
  96. package/lib/ui-routes/export-routes.js +10 -4
  97. package/lib/ui-routes/oauth-config-routes.js +12 -12
  98. package/lib/ui-routes/reference-routes.js +3 -3
  99. package/lib/ui-routes/route-helpers.js +78 -2
  100. package/lib/ui-routes/settings-page.js +1 -1
  101. package/lib/ui-routes/smtp-test-routes.js +1 -1
  102. package/lib/ui-routes/suppression-list-routes.js +299 -0
  103. package/lib/ui-routes/unsubscribe-routes.js +19 -29
  104. package/lib/utils/decode-headers.js +42 -0
  105. package/lib/utils/header-map.js +48 -0
  106. package/lib/utils/network.js +2 -2
  107. package/lib/utils/unsafe-key.js +59 -0
  108. package/lib/web-safe-html.js +1 -1
  109. package/lib/webhook-routing.js +84 -0
  110. package/lib/webhooks.js +48 -14
  111. package/package.json +11 -10
  112. package/sbom.json +1 -1
  113. package/server.js +116 -55
  114. package/static/css/flyonui.css +1 -1
  115. package/static/css/src/app.tailwind.css +136 -9
  116. package/static/js/reference.js +456 -10
  117. package/static/js/ui.js +43 -0
  118. package/static/licenses.html +51 -41
  119. package/translations/messages.pot +59 -59
  120. package/views/accounts/account.hbs +75 -13
  121. package/views/accounts/browse.hbs +19 -36
  122. package/views/accounts/edit.hbs +2 -2
  123. package/views/config/logging.hbs +6 -0
  124. package/views/config/oauth/app.hbs +0 -2
  125. package/views/config/security.hbs +13 -0
  126. package/views/gateways/edit.hbs +1 -1
  127. package/views/gateways/gateway.hbs +2 -2
  128. package/views/gateways/index.hbs +7 -7
  129. package/views/partials/accounts_table.hbs +7 -7
  130. package/views/partials/oauth_form.hbs +0 -15
  131. package/views/partials/reference/disclosure.hbs +8 -2
  132. package/views/partials/reference/operation.hbs +47 -13
  133. package/views/partials/reference/params.hbs +17 -1
  134. package/views/partials/reference/schema-node.hbs +110 -52
  135. package/views/partials/reference/schema-tools.hbs +25 -0
  136. package/views/partials/reference/try-it.hbs +84 -11
  137. package/views/partials/side_menu.hbs +1 -0
  138. package/views/partials/ui/checkbox.hbs +2 -2
  139. package/views/partials/ui/tabs.hbs +7 -1
  140. package/views/reference/token.hbs +4 -0
  141. package/views/suppression-lists/index.hbs +85 -0
  142. package/views/suppression-lists/list.hbs +87 -0
  143. package/views/templates/index.hbs +10 -4
  144. package/views/templates/template.hbs +1 -1
  145. package/views/tokens/index.hbs +53 -6
  146. package/views/tokens/new.hbs +334 -5
  147. package/workers/api.js +185 -102
  148. package/workers/documents.js +46 -26
  149. package/workers/export.js +20 -8
  150. package/workers/imap-proxy.js +2 -2
  151. package/workers/imap.js +77 -78
  152. package/workers/smtp.js +13 -7
  153. package/workers/submit.js +40 -30
  154. package/workers/webhooks.js +80 -26
  155. package/lib/feature-flags.js +0 -48
@@ -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,
@@ -237,12 +238,38 @@ class IMAPClient extends BaseClient {
237
238
  /**
238
239
  * Called when a task is completed - ensures we return to the main mailbox
239
240
  * This prevents the connection from staying in a rarely-used mailbox
241
+ *
242
+ * Only the primary connection has a mailbox worth returning to. A task served by a pooled
243
+ * secondary never moved the primary, so scheduling a re-select for it is at best wasted work
244
+ * and at worst pulls the primary out of a mailbox it is still using. getMailboxLock() makes
245
+ * the same distinction when it clears this timer, so the two sides agree.
246
+ *
247
+ * @param {Object} [connectionClient] - IMAP client that completed the task (defaults to the primary)
240
248
  */
241
- onTaskCompleted() {
249
+ onTaskCompleted(connectionClient) {
250
+ if (connectionClient && connectionClient !== this.imapClient) {
251
+ return;
252
+ }
253
+
254
+ // A download reports its task from a stream callback that can fire long after the account
255
+ // was paused or deleted. close() clears this timer but leaves this.imapClient pointing at
256
+ // the closed client, so without this a late callback arms a fresh one against a connection
257
+ // that is gone - and if a reconnect has since replaced the client, the re-select lands on
258
+ // the new connection mid-walk.
259
+ if (this.isClosing || this.isClosed) {
260
+ return;
261
+ }
262
+
242
263
  // check if we need to re-select main mailbox
264
+ clearTimeout(this.completedTimer);
243
265
  this.completedTimer = setTimeout(() => {
244
- clearTimeout(this.completedTimer);
245
- this.ensureMainMailbox().catch(err => this.logger.error({ msg: 'Failed to select main mailbox', err }));
266
+ this.ensureMainMailbox().catch(err => {
267
+ if (CONNECTION_CLOSING_CODES.has(err.code)) {
268
+ this.logger.debug({ msg: 'Select skipped, connection closing', err });
269
+ } else {
270
+ this.logger.error({ msg: 'Failed to select main mailbox', err });
271
+ }
272
+ });
246
273
  }, ENSURE_MAIN_TTL);
247
274
  }
248
275
 
@@ -288,7 +315,7 @@ class IMAPClient extends BaseClient {
288
315
  return connectionClient;
289
316
  }
290
317
  } catch (err) {
291
- this.logger.error({ msg: 'Failed to acquire command connection', reason, err });
318
+ this.logger.warn({ msg: 'Failed to acquire command connection', reason, err });
292
319
  }
293
320
 
294
321
  // Fall back to primary connection
@@ -324,7 +351,6 @@ class IMAPClient extends BaseClient {
324
351
  this.logger.debug({ msg: 'Acquiring connection lock', lockKey });
325
352
  connectLock = await lock.waitAcquireLock(lockKey, 5 * 60 * 1000, 1 * 60 * 1000);
326
353
  if (!connectLock.success) {
327
- this.logger.error({ msg: 'Failed to get lock', lockKey });
328
354
  throw new Error('Failed to get connection lock');
329
355
  }
330
356
  this.logger.debug({ msg: 'Acquired connection lock', lockKey, index: connectLock.index });
@@ -1002,7 +1028,7 @@ class IMAPClient extends BaseClient {
1002
1028
  }
1003
1029
  await mailbox.onExists(event);
1004
1030
  } catch (err) {
1005
- imapClient.log.error({ msg: 'Exists error', err });
1031
+ imapClient.log.error({ msg: 'Failed to process EXISTS notification', path: event?.path, err });
1006
1032
  }
1007
1033
  }
1008
1034
 
@@ -1022,10 +1048,10 @@ class IMAPClient extends BaseClient {
1022
1048
  // that arrived from a replacement connection after a reconnect
1023
1049
  await mailbox.onOpen(event, imapClient);
1024
1050
  } catch (err) {
1025
- if (err.code === 'IMAPConnectionClosing') {
1051
+ if (CONNECTION_CLOSING_CODES.has(err.code)) {
1026
1052
  imapClient.log.debug({ msg: 'Open skipped, connection closing', err });
1027
1053
  } else {
1028
- imapClient.log.error({ msg: 'Open error', err });
1054
+ imapClient.log.error({ msg: 'Failed to process mailbox open notification', path: event?.path, err });
1029
1055
  }
1030
1056
  }
1031
1057
  }
@@ -1043,7 +1069,7 @@ class IMAPClient extends BaseClient {
1043
1069
  }
1044
1070
  await mailbox.onClose(event);
1045
1071
  } catch (err) {
1046
- imapClient.log.error({ msg: 'Close error', err });
1072
+ imapClient.log.error({ msg: 'Failed to process mailbox close notification', path: event?.path, err });
1047
1073
  }
1048
1074
  }
1049
1075
 
@@ -1060,7 +1086,7 @@ class IMAPClient extends BaseClient {
1060
1086
  }
1061
1087
  await mailbox.onFlags(event);
1062
1088
  } catch (err) {
1063
- imapClient.log.error({ msg: 'Flags error', err });
1089
+ imapClient.log.error({ msg: 'Failed to process flag change notification', path: event?.path, err });
1064
1090
  }
1065
1091
  }
1066
1092
 
@@ -1323,11 +1349,10 @@ class IMAPClient extends BaseClient {
1323
1349
  retryCount = 0;
1324
1350
  })
1325
1351
  .catch(err => {
1326
- this.logger.error({ msg: 'Mailbox Sync Error', err, retryCount });
1327
1352
  retryCount++;
1328
1353
  // Exponential backoff with max delay of 30 seconds
1329
1354
  const retryDelay = Math.min(30000, 2000 * Math.pow(2, retryCount));
1330
- this.logger.warn({ msg: 'Scheduling sync retry with backoff', retryDelay, retryCount });
1355
+ this.logger.warn({ msg: 'Failed to sync mailboxes, will retry', err, retryCount, retryDelay });
1331
1356
  setTimeout(setSyncTimer, retryDelay);
1332
1357
  });
1333
1358
  }, this.resyncDelay);
@@ -1398,7 +1423,7 @@ class IMAPClient extends BaseClient {
1398
1423
  serverResponseCode: 'HTTPRequestError'
1399
1424
  });
1400
1425
  ctx.logger.error({
1401
- account: this.account,
1426
+ msg: 'Failed to resolve credentials from authentication server',
1402
1427
  err
1403
1428
  });
1404
1429
  ctx.state = AUTH_ERROR_NOTIFY;
@@ -1414,7 +1439,7 @@ class IMAPClient extends BaseClient {
1414
1439
  // Set local address for outgoing connections (for IP rotation)
1415
1440
  const localAddress = await getLocalAddress(redis, 'imap', this.account);
1416
1441
  imapConnectionConfig.tls.localAddress = localAddress.localAddress;
1417
- this.logger.info({
1442
+ this.logger.debug({
1418
1443
  msg: 'Selected local address',
1419
1444
  account: this.account,
1420
1445
  proto: 'IMAP',
@@ -1706,7 +1731,10 @@ class IMAPClient extends BaseClient {
1706
1731
  }
1707
1732
  }
1708
1733
  } catch (err) {
1709
- imapClient.log.error({ msg: 'Reconnection error', err });
1734
+ // This is the only path that re-arms the connection after an unexpected close.
1735
+ // If it throws, nothing else reconnects the account, so it stays offline until
1736
+ // the worker restarts - never demote this below error.
1737
+ imapClient.log.error({ msg: 'Reconnection error', account: this.account, err });
1710
1738
  }
1711
1739
 
1712
1740
  imapClient = null;
@@ -1736,7 +1764,7 @@ class IMAPClient extends BaseClient {
1736
1764
  let prevConnectedCount = await this.redis.hget(this.getAccountKey(), `state:count:connected`);
1737
1765
  let isFirstSuccessfulConnection = prevConnectedCount === '0'; // string zero means the account has been initialized but not yet connected
1738
1766
 
1739
- let isiInitial = !!isFirstSuccessfulConnection;
1767
+ let isInitial = !!isFirstSuccessfulConnection;
1740
1768
 
1741
1769
  if (!isFirstSuccessfulConnection) {
1742
1770
  // check if the connection was previously in an errored state
@@ -1757,18 +1785,20 @@ class IMAPClient extends BaseClient {
1757
1785
 
1758
1786
  // Send appropriate notifications based on connection history
1759
1787
  if (isFirstSuccessfulConnection) {
1760
- this.logger.info({ msg: 'Successful login without a previous active session', account: this.account, isiInitial, prevActive: false });
1788
+ this.logger.info({ msg: 'Successful login without a previous active session', account: this.account, isInitial, prevActive: false });
1761
1789
  await this.notify(false, AUTH_SUCCESS_NOTIFY, {
1762
1790
  user: imapConfig.auth.user
1763
1791
  });
1764
1792
  } else {
1765
- this.logger.info({ msg: 'Successful login with a previous active session', account: this.account, isiInitial, prevActive: true });
1793
+ this.logger.info({ msg: 'Successful login with a previous active session', account: this.account, isInitial, prevActive: true });
1766
1794
  }
1767
1795
 
1768
1796
  // Set up subconnections for monitoring multiple folders
1769
1797
  this.setupSubConnections()
1770
1798
  .then(result => {
1771
- this.logger.info({ msg: 'Set up subconnections', account: this.account, result });
1799
+ if (result !== null) {
1800
+ this.logger.info({ msg: 'Set up subconnections', account: this.account, result });
1801
+ }
1772
1802
  })
1773
1803
  .catch(err => {
1774
1804
  this.logger.error({ msg: 'Failed to set up subconnections', account: this.account, err });
@@ -1809,14 +1839,14 @@ class IMAPClient extends BaseClient {
1809
1839
  // webhook payloads never render as "[object Object]"
1810
1840
  let errorResponse = (typeof err.response === 'string' && err.response) || err.responseText;
1811
1841
  if (err.authenticationFailed) {
1812
- this.logger.error({ msg: 'Failed to authenticate', account: this.account, err });
1842
+ this.logger.warn({ msg: 'Failed to authenticate', account: this.account, err });
1813
1843
  await this.notify(false, AUTH_ERROR_NOTIFY, {
1814
1844
  response: errorResponse,
1815
1845
  serverResponseCode: err.serverResponseCode
1816
1846
  });
1817
1847
  this.state = 'authenticationError';
1818
1848
  } else {
1819
- this.logger.error({ msg: 'Failed to connect', account: this.account, err });
1849
+ this.logger.warn({ msg: 'Failed to connect', account: this.account, err });
1820
1850
  await this.notify(false, CONNECT_ERROR_NOTIFY, {
1821
1851
  response: errorResponse || err.message,
1822
1852
  serverResponseCode: err.serverResponseCode || err.code
@@ -1903,7 +1933,7 @@ class IMAPClient extends BaseClient {
1903
1933
  this.closeSubconnections();
1904
1934
  }
1905
1935
 
1906
- this.logger.info({ msg: 'Closed account', account: this.account });
1936
+ this.logger.info({ msg: 'Deleted account', account: this.account });
1907
1937
  }
1908
1938
 
1909
1939
  /**
@@ -2191,7 +2221,7 @@ class IMAPClient extends BaseClient {
2191
2221
  // force sync target mailbox to show moved messages
2192
2222
  let targetMailbox = this.mailboxes.get(normalizePath(target.path));
2193
2223
  if (targetMailbox) {
2194
- targetMailbox.sync().catch(err => this.logger.error({ msg: 'Mailbox sync error', path: target.path, err }));
2224
+ targetMailbox.sync().catch(err => this.logger.warn({ msg: 'Failed to sync mailbox', path: target.path, err }));
2195
2225
  }
2196
2226
 
2197
2227
  return res;
@@ -2250,7 +2280,7 @@ class IMAPClient extends BaseClient {
2250
2280
  if (res && res.moved && res.moved.destination) {
2251
2281
  let targetMailbox = this.mailboxes.get(normalizePath(res.moved.destination));
2252
2282
  if (targetMailbox) {
2253
- targetMailbox.sync().catch(err => this.logger.error({ msg: 'Mailbox sync error', path: res && res.moved && res.moved.destination, err }));
2283
+ targetMailbox.sync().catch(err => this.logger.warn({ msg: 'Failed to sync mailbox', path: res && res.moved && res.moved.destination, err }));
2254
2284
  }
2255
2285
  }
2256
2286
 
@@ -2470,6 +2500,12 @@ class IMAPClient extends BaseClient {
2470
2500
  }
2471
2501
  } finally {
2472
2502
  lock.release();
2503
+ // mailboxClose() leaves the connection with no mailbox selected, and ImapFlow can
2504
+ // only re-arm IDLE for a mailbox it is in - so on the primary this is what puts the
2505
+ // account back to watching for new mail. The lock here is ImapFlow's own rather
2506
+ // than Mailbox.getMailboxLock(), which is the one that clears completedTimer, so
2507
+ // nothing else on this path would report the task.
2508
+ this.onTaskCompleted(connectionClient);
2473
2509
  }
2474
2510
  } catch (err) {
2475
2511
  this.logger.debug({ msg: 'Mailbox select error', path, err });
@@ -2489,7 +2525,7 @@ class IMAPClient extends BaseClient {
2489
2525
  */
2490
2526
  runPostListing() {
2491
2527
  this.refreshAndProcessListing().catch(err => {
2492
- this.logger.error({ msg: 'List refresh error', err });
2528
+ this.logger.warn({ msg: 'Failed to refresh folder listing', err });
2493
2529
  });
2494
2530
  }
2495
2531
 
@@ -2591,6 +2627,19 @@ class IMAPClient extends BaseClient {
2591
2627
  let normalizedPath = [].concat(path || []).join('/');
2592
2628
 
2593
2629
  if (normalizedNewPath !== normalizedPath) {
2630
+ // Acquire lock to prevent concurrent operations on the mailbox. ImapFlow's RENAME
2631
+ // first CLOSEs the mailbox when it is the selected one, which leaves the connection
2632
+ // with no mailbox selected - the same deselection deleteMailbox() goes through - so
2633
+ // the lock/onTaskCompleted pair below is what re-arms IDLE on the primary
2634
+ // connection afterwards. Without it a rename of the watched mailbox left the
2635
+ // account deaf to new mail until the next resync.
2636
+ let lock;
2637
+ try {
2638
+ lock = await connectionClient.getMailboxLock(path, { description: `Rename mailbox ${path}` });
2639
+ } catch (err) {
2640
+ this.logger.debug({ msg: 'Mailbox select error', path, err });
2641
+ }
2642
+
2594
2643
  try {
2595
2644
  let renameResult = await connectionClient.mailboxRename(path, newPath);
2596
2645
  if (renameResult) {
@@ -2628,6 +2677,14 @@ class IMAPClient extends BaseClient {
2628
2677
  } else {
2629
2678
  throw err;
2630
2679
  }
2680
+ } finally {
2681
+ if (lock) {
2682
+ lock.release();
2683
+ }
2684
+ // See deleteMailbox(): the RENAME may have left the connection with no mailbox
2685
+ // selected, and on the primary this is what schedules the re-select that puts
2686
+ // the account back to watching for new mail
2687
+ this.onTaskCompleted(connectionClient);
2631
2688
  }
2632
2689
  } else {
2633
2690
  result.path = normalizedPath;
@@ -2713,7 +2770,7 @@ class IMAPClient extends BaseClient {
2713
2770
  if (this.imapClient && connectionClient === this.imapClient && this.imapClient.mailbox && !this.imapClient.idling) {
2714
2771
  // force back to IDLE
2715
2772
  this.imapClient.idle().catch(err => {
2716
- this.logger.error({ msg: 'IDLE error', err });
2773
+ this.logger.warn({ msg: 'IDLE error', err });
2717
2774
  });
2718
2775
  }
2719
2776
 
@@ -2772,7 +2829,7 @@ class IMAPClient extends BaseClient {
2772
2829
  this.logger.error({ msg: 'Failed to process listing', err: listingErr });
2773
2830
  });
2774
2831
  } catch (E) {
2775
- this.logger.error({ msg: 'Missing mailbox', err, E });
2832
+ this.logger.error({ msg: 'Failed to refresh listing after missing mailbox', err: E });
2776
2833
  }
2777
2834
  }
2778
2835
 
@@ -2794,7 +2851,7 @@ class IMAPClient extends BaseClient {
2794
2851
  }
2795
2852
  await mailbox.onExpunge(payload);
2796
2853
  } catch (err) {
2797
- this.logger.error({ msg: 'Expunge error', err });
2854
+ this.logger.error({ msg: 'Failed to process EXPUNGE notification', path: payload?.path, err });
2798
2855
  }
2799
2856
  }
2800
2857
 
@@ -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',
@@ -149,7 +149,7 @@ class NotificationHandler {
149
149
  const thread = await getThread(client, index, this.account, payload.data, logger);
150
150
  if (thread) {
151
151
  payload.data.threadId = thread;
152
- this.logger.info({
152
+ this.logger.debug({
153
153
  msg: 'Provisioned thread ID for a message',
154
154
  account: this.account,
155
155
  message: payload.data.id,
@@ -63,7 +63,7 @@ async function request(context, url, method, payload, options = {}) {
63
63
  try {
64
64
  accessToken = await context.getToken();
65
65
  } catch (err) {
66
- context.logger.error({ msg: 'Failed to load access token', account: context.account, err });
66
+ context.logger.warn({ msg: 'Failed to load access token', account: context.account, err });
67
67
  throw err;
68
68
  }
69
69
 
@@ -111,6 +111,12 @@ async function request(context, url, method, payload, options = {}) {
111
111
  const graphError = createGraphError(err.oauthRequest?.response?.error, graphErrorCode);
112
112
 
113
113
  if (graphError) {
114
+ // Carry the raw Graph exchange over to the mapped error. Callers in outlook-client.js
115
+ // build their own responses by switching on `err.oauthRequest.response.error.code` and
116
+ // `err.oauthRequest.status`, so dropping it here silently disables every one of those
117
+ // branches and turns a mapped 404 into a generic 400 with an undefined code.
118
+ graphError.oauthRequest = err.oauthRequest;
119
+
114
120
  context.logger.debug({
115
121
  msg: 'Graph API error mapped to internal code',
116
122
  account: context.account,
@@ -128,12 +134,12 @@ async function request(context, url, method, payload, options = {}) {
128
134
  case 401:
129
135
  // NOTE: never include `accessToken` here - this logger persists to the per-account
130
136
  // log store (exposed via the account logs API/UI) and to Sentry (security review M3).
131
- context.logger.error({ msg: 'Failed to authenticate API request', account: context.account, err });
137
+ context.logger.warn({ msg: 'Failed to authenticate API request', account: context.account, err });
132
138
  throw err;
133
139
 
134
140
  case 429:
135
141
  // Rate limiting
136
- context.logger.error({ msg: 'API request was throttled', account: context.account, err });
142
+ context.logger.warn({ msg: 'API request was throttled', account: context.account, err });
137
143
  throw err;
138
144
 
139
145
  default:
@@ -200,7 +206,7 @@ async function requestWithRetry(context, url, method, payload, options = {}) {
200
206
  // Use Retry-After header if available, otherwise use exponential backoff
201
207
  const retryAfter = err.retryAfter || Math.min(OUTLOOK_RETRY_BASE_DELAY * Math.pow(2, attempt), OUTLOOK_RETRY_MAX_DELAY);
202
208
 
203
- context.logger.info({
209
+ context.logger.debug({
204
210
  msg: 'Rate limited, retrying after delay',
205
211
  account: context.account,
206
212
  attempt: attempt + 1,