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
@@ -40,7 +40,7 @@ const { getMailTransport } = require('./smtp-pool-manager');
40
40
 
41
41
  // Import various utility functions and constants
42
42
  const {
43
- getSignedFormDataSync,
43
+ buildUnsubscribeUrl,
44
44
  getServiceSecret,
45
45
  convertDataUrisToAttachments,
46
46
  genBaseBoundary,
@@ -158,7 +158,7 @@ async function retryOnTransientError(fn, options = {}) {
158
158
  attempt,
159
159
  maxAttempts,
160
160
  delay,
161
- err: err.message,
161
+ err,
162
162
  statusCode: err.statusCode || err.oauthRequest?.status
163
163
  });
164
164
  }
@@ -501,7 +501,7 @@ class BaseClient {
501
501
  );
502
502
  await disableTxn.exec();
503
503
 
504
- this.logger.info({
504
+ this.logger.warn({
505
505
  msg: 'IMAP was disabled for the account due to exceeding the authentication error threshold',
506
506
  errorEvent: event,
507
507
  firstError: firstError.toISOString(),
@@ -597,7 +597,7 @@ class BaseClient {
597
597
  // rejected credential. Reporting it as an authentication error would webhook every
598
598
  // account on the instance and park them in an error state over a brief blip.
599
599
  if (isTransientNetworkError(err)) {
600
- ctx.logger.error({
600
+ ctx.logger.warn({
601
601
  msg: 'Network error while resolving credentials from the authentication server',
602
602
  account: accountObject.account,
603
603
  target,
@@ -635,7 +635,7 @@ class BaseClient {
635
635
  } catch (err) {
636
636
  // Transient network errors are not authentication failures
637
637
  if (isTransientNetworkError(err)) {
638
- ctx.logger.error({
638
+ ctx.logger.warn({
639
639
  msg: 'Network error during OAuth2 token refresh',
640
640
  account: accountObject.account,
641
641
  code: err.code,
@@ -654,7 +654,8 @@ class BaseClient {
654
654
  notifyData.tokenRequest = err.tokenRequest;
655
655
  }
656
656
  await ctx.notify(false, AUTH_ERROR_NOTIFY, notifyData);
657
- ctx.logger.error({
657
+ ctx.logger.warn({
658
+ msg: 'Failed to renew OAuth2 access token',
658
659
  account: accountObject.account,
659
660
  err
660
661
  });
@@ -663,11 +664,10 @@ class BaseClient {
663
664
  }
664
665
  } else {
665
666
  // Use cached token
666
- this.logger.info({
667
+ this.logger.debug({
667
668
  msg: 'Using cached OAuth2 access token',
668
669
  action: 'ensureAccessToken',
669
670
  target,
670
- error: null,
671
671
  user: accountData.oauth2.auth.user,
672
672
  expires: accountData.oauth2.expires,
673
673
  scopes: accountData.oauth2.scope,
@@ -952,7 +952,7 @@ class BaseClient {
952
952
  try {
953
953
  gatewayData = await gatewayObject.loadGatewayData();
954
954
  } catch (err) {
955
- this.logger.info({ msg: 'Failed to load gateway data', messageId: data.messageId, gateway: data.gateway, err });
955
+ this.logger.warn({ msg: 'Failed to load gateway data', messageId: data.messageId, gateway: data.gateway, err });
956
956
  }
957
957
  }
958
958
 
@@ -1201,7 +1201,7 @@ class BaseClient {
1201
1201
  this.logger.warn({
1202
1202
  msg: 'Failed to fetch referenced message due to transient error, continuing without reference',
1203
1203
  messageId: data.reference.message,
1204
- err: err.message,
1204
+ err,
1205
1205
  statusCode: err.statusCode || (err.oauthRequest && err.oauthRequest.status)
1206
1206
  });
1207
1207
  referencedMessage = null;
@@ -1403,7 +1403,7 @@ class BaseClient {
1403
1403
  if (attachmentsToDownload && attachmentsToDownload.length) {
1404
1404
  this.checkIMAPConnection(connectionOptions);
1405
1405
 
1406
- this.logger.info({
1406
+ this.logger.debug({
1407
1407
  msg: 'Fetching attachments from the referenced email',
1408
1408
  attachments: attachmentsToDownload.map(a => ({ id: a.id, hasContent: !!a.content }))
1409
1409
  });
@@ -1567,8 +1567,6 @@ class BaseClient {
1567
1567
  baseDomain = baseDomain || (os.hostname() || '').toLowerCase().trim() || 'localhost';
1568
1568
 
1569
1569
  if (baseDomain) {
1570
- let unsubscribeUrlObj = new URL('/unsubscribe', baseUrl);
1571
-
1572
1570
  const serviceSecret = await getServiceSecret();
1573
1571
 
1574
1572
  let fromDomain = ((data.from && data.from.address) || '').split('@').pop().trim().toLowerCase() || baseDomain;
@@ -1585,24 +1583,14 @@ class BaseClient {
1585
1583
  }
1586
1584
 
1587
1585
  // Create signed unsubscribe URL
1588
- let { data: signedData, signature } = getSignedFormDataSync(
1589
- serviceSecret,
1590
- {
1591
- act: 'unsub',
1592
- acc: accountData.account,
1593
- list: data.listId,
1594
- rcpt: data.to[0].address,
1595
- msg: data.messageId
1596
- },
1597
- true
1598
- );
1599
-
1600
- unsubscribeUrlObj.searchParams.append('data', signedData);
1601
- if (signature) {
1602
- unsubscribeUrlObj.searchParams.append('sig', signature);
1603
- }
1586
+ let unsubscribeUrl = buildUnsubscribeUrl(serviceSecret, baseUrl, {
1587
+ account: accountData.account,
1588
+ list: data.listId,
1589
+ recipient: data.to[0].address,
1590
+ messageId: data.messageId
1591
+ });
1604
1592
 
1605
- context.rcpt = Object.assign({}, data.to[0], { unsubscribeUrl: unsubscribeUrlObj.href });
1593
+ context.rcpt = Object.assign({}, data.to[0], { unsubscribeUrl });
1606
1594
 
1607
1595
  // Add RFC 8058 compliant unsubscribe headers
1608
1596
  data.headers['List-Unsubscribe'] = `<${context.rcpt.unsubscribeUrl}>`;
@@ -1633,7 +1621,7 @@ class BaseClient {
1633
1621
  try {
1634
1622
  data.text = htmlToText(data.html);
1635
1623
  } catch (err) {
1636
- this.logger.error({ msg: 'Failed to generate plaintext content from html', err });
1624
+ this.logger.warn({ msg: 'Failed to generate plaintext content from html', err });
1637
1625
  }
1638
1626
  }
1639
1627
 
@@ -1705,7 +1693,7 @@ class BaseClient {
1705
1693
  this.logger.warn({
1706
1694
  msg: 'Failed to fetch referenced message due to transient error, continuing without reference',
1707
1695
  messageId: data.reference.message,
1708
- err: err.message,
1696
+ err,
1709
1697
  statusCode: err.statusCode || (err.oauthRequest && err.oauthRequest.status)
1710
1698
  });
1711
1699
  referencedMessage = null;
@@ -1918,7 +1906,7 @@ class BaseClient {
1918
1906
  if (attachmentsToDownload && attachmentsToDownload.length) {
1919
1907
  this.checkIMAPConnection(connectionOptions);
1920
1908
 
1921
- this.logger.info({
1909
+ this.logger.debug({
1922
1910
  msg: 'Fetching attachments from the referenced email',
1923
1911
  attachments: attachmentsToDownload.map(a => ({ id: a.id, hasContent: !!a.content }))
1924
1912
  });
@@ -2025,7 +2013,7 @@ class BaseClient {
2025
2013
  try {
2026
2014
  gatewayData = await gatewayObject.loadGatewayData();
2027
2015
  } catch (err) {
2028
- this.logger.info({ msg: 'Failed to load gateway data', envelope, messageId, gateway, err });
2016
+ this.logger.warn({ msg: 'Failed to load gateway data', envelope, messageId, gateway, err });
2029
2017
  }
2030
2018
  }
2031
2019
 
@@ -2250,7 +2238,7 @@ class BaseClient {
2250
2238
  try {
2251
2239
  gatewayData = await gatewayObject.loadGatewayData();
2252
2240
  } catch (err) {
2253
- this.logger.info({ msg: 'Failed to load gateway data', envelope, messageId, gateway, err });
2241
+ this.logger.warn({ msg: 'Failed to load gateway data', envelope, messageId, gateway, err });
2254
2242
  }
2255
2243
  }
2256
2244
 
@@ -2321,7 +2309,7 @@ class BaseClient {
2321
2309
 
2322
2310
  return compiledTemplate(data);
2323
2311
  } catch (err) {
2324
- logger.error({ msg: `Failed rendering ${key} template`, err });
2312
+ this.logger.error({ msg: 'Failed to render template', templateKey: key, err });
2325
2313
  let error = new Error(`Failed rendering ${key} template`);
2326
2314
  error.code = err.code || 'SubmitFail';
2327
2315
  error.statusCode = 422;
@@ -2535,7 +2523,7 @@ class BaseClient {
2535
2523
  }
2536
2524
  } catch (err) {
2537
2525
  // ignore, just do not include this information
2538
- this.logger.error({
2526
+ this.logger.warn({
2539
2527
  msg: 'Failed to classify bounce response',
2540
2528
  bounceResponse: bounce?.response?.message,
2541
2529
  err
@@ -2543,7 +2531,6 @@ class BaseClient {
2543
2531
  }
2544
2532
  }
2545
2533
 
2546
- let stored = 0;
2547
2534
  if (bounce.action && bounce.recipient && bounce.messageId) {
2548
2535
  bounceNotifyInfo = Object.assign({ bounceMessage: messageData.id }, bounce);
2549
2536
 
@@ -2556,8 +2543,7 @@ class BaseClient {
2556
2543
  id: messageData.id,
2557
2544
  uid: messageData.uid,
2558
2545
  messageId: messageData.messageId,
2559
- bounce,
2560
- stored
2546
+ bounce
2561
2547
  });
2562
2548
  }
2563
2549
  } catch (err) {
@@ -2825,7 +2811,7 @@ class BaseClient {
2825
2811
  time: Date.now()
2826
2812
  })
2827
2813
  );
2828
- this.logger.error({ msg: 'Failed to fetch embeddings OpenAI', err });
2814
+ this.logger.error({ msg: 'Failed to fetch embeddings from OpenAI', err });
2829
2815
  }
2830
2816
  }
2831
2817
  }
@@ -28,6 +28,7 @@ const settings = require('../settings');
28
28
 
29
29
  const { GMAIL_API_BASE, LIST_BATCH_SIZE, request: gmailApiRequest, executeBatchRequests } = require('./gmail/gmail-api');
30
30
  const { buildSendRequest, buildDraftSendRequest } = require('./gmail/send-request');
31
+ const { pushHeaderValue } = require('../utils/header-map');
31
32
 
32
33
  const MAX_GMAIL_BATCH_SIZE = 50;
33
34
 
@@ -320,7 +321,7 @@ class GmailClient extends BaseClient {
320
321
  // Reload account data after getting access token to ensure we have the latest OAuth2 scopes
321
322
  accountData = await this.accountObject.loadAccountData(this.account);
322
323
  } catch (err) {
323
- this.logger.error({
324
+ this.logger.warn({
324
325
  msg: 'Failed to get token or reload account data during init',
325
326
  account: this.account,
326
327
  err
@@ -333,7 +334,7 @@ class GmailClient extends BaseClient {
333
334
  const { hasSendScope, hasReadScope } = checkAccountScopes('gmail', scopes);
334
335
  const isSendOnly = hasSendScope && !hasReadScope;
335
336
 
336
- this.logger.info({
337
+ this.logger.debug({
337
338
  msg: 'Account scopes loaded',
338
339
  account: this.account,
339
340
  scopes,
@@ -412,7 +413,7 @@ class GmailClient extends BaseClient {
412
413
  }
413
414
  } catch (err) {
414
415
  // not very important if succeeds or not
415
- this.logger.error({
416
+ this.logger.warn({
416
417
  msg: 'Failed to resolve locale for account',
417
418
  err
418
419
  });
@@ -470,7 +471,7 @@ class GmailClient extends BaseClient {
470
471
  this.state = 'connected';
471
472
  await this.setStateVal();
472
473
 
473
- let isiInitial = !!isFirstSuccessfulConnection;
474
+ let isInitial = !!isFirstSuccessfulConnection;
474
475
 
475
476
  if (!isFirstSuccessfulConnection) {
476
477
  // check if the connection was previously in an errored state
@@ -491,12 +492,12 @@ class GmailClient extends BaseClient {
491
492
 
492
493
  // Send appropriate authentication success notification
493
494
  if (isFirstSuccessfulConnection) {
494
- this.logger.info({ msg: 'Successful login without a previous active session', account: this.account, isiInitial, prevActive: false });
495
+ this.logger.info({ msg: 'Successful login without a previous active session', account: this.account, isInitial, prevActive: false });
495
496
  await this.notify(false, AUTH_SUCCESS_NOTIFY, {
496
497
  user: accountData.oauth2?.auth?.user
497
498
  });
498
499
  } else {
499
- this.logger.info({ msg: 'Successful login with a previous active session', account: this.account, isiInitial, prevActive: true });
500
+ this.logger.info({ msg: 'Successful login with a previous active session', account: this.account, isInitial, prevActive: true });
500
501
  }
501
502
 
502
503
  // Clear any previous error state
@@ -1603,7 +1604,7 @@ class GmailClient extends BaseClient {
1603
1604
  draftId = listing?.drafts?.find(draftEntry => draftEntry?.message?.id === emailId)?.id || null;
1604
1605
  } catch (err) {
1605
1606
  // draft id resolution is best effort - fall back to sending the raw copy
1606
- this.logger.info({ msg: 'Failed to resolve Gmail draft id', emailId, err });
1607
+ this.logger.warn({ msg: 'Failed to resolve Gmail draft id', emailId, err });
1607
1608
  }
1608
1609
  }
1609
1610
 
@@ -1642,7 +1643,7 @@ class GmailClient extends BaseClient {
1642
1643
  try {
1643
1644
  gatewayData = await gatewayObject.loadGatewayData();
1644
1645
  } catch (err) {
1645
- this.logger.info({ msg: 'Failed to load gateway data', messageId: data.messageId, gateway: data.gateway, err });
1646
+ this.logger.warn({ msg: 'Failed to load gateway data', messageId: data.messageId, gateway: data.gateway, err });
1646
1647
  }
1647
1648
  }
1648
1649
 
@@ -2074,7 +2075,7 @@ class GmailClient extends BaseClient {
2074
2075
  const timeSinceNotification = Date.now() - (this.lastNotificationTime || 0);
2075
2076
  if (timeSinceNotification >= FALLBACK_POLLING_INTERVAL) {
2076
2077
  // No notifications received within the interval, do a proactive sync
2077
- this.logger.info({
2078
+ this.logger.debug({
2078
2079
  msg: 'No Pub/Sub notifications received, triggering fallback sync',
2079
2080
  account: this.account,
2080
2081
  timeSinceNotification
@@ -2529,15 +2530,11 @@ class GmailClient extends BaseClient {
2529
2530
 
2530
2531
  let envelope = this.getEnvelope(messageData);
2531
2532
 
2532
- // Extract all headers
2533
+ // Extract all headers. pushHeaderValue() guards against names that resolve to
2534
+ // Object.prototype members, which would otherwise throw for every fetch of that message
2533
2535
  let headers = {};
2534
2536
  for (let header of messageData.payload.headers) {
2535
- let key = header.name.toLowerCase();
2536
- if (!headers[key]) {
2537
- headers[key] = [header.value];
2538
- } else {
2539
- headers[key].push(header.value);
2540
- }
2537
+ pushHeaderValue(headers, header.name.toLowerCase(), header.value);
2541
2538
  }
2542
2539
 
2543
2540
  const { attachments, textId, encodedTextSize, textContents } = this.getAttachmentList(messageData, { textType });
@@ -3085,7 +3082,16 @@ class GmailClient extends BaseClient {
3085
3082
  lastHistoryId = historyEntryId;
3086
3083
  }
3087
3084
  } catch (err) {
3088
- this.logger.error({ msg: 'Failed to process history entry', account: this.account, entry, err });
3085
+ this.logger.error({
3086
+ msg: 'Failed to process history entry',
3087
+ account: this.account,
3088
+ entryId: entry?.id,
3089
+ messagesAdded: entry?.messagesAdded?.length,
3090
+ messagesDeleted: entry?.messagesDeleted?.length,
3091
+ labelsAdded: entry?.labelsAdded?.length,
3092
+ labelsRemoved: entry?.labelsRemoved?.length,
3093
+ err
3094
+ });
3089
3095
  }
3090
3096
  }
3091
3097
 
@@ -1,5 +1,6 @@
1
1
  'use strict';
2
2
 
3
+ const { finished } = require('stream');
3
4
  const {
4
5
  serialize,
5
6
  unserialize,
@@ -16,6 +17,8 @@ const he = require('he');
16
17
  const libmime = require('libmime');
17
18
  const settings = require('../../settings');
18
19
  const { bounceDetect, applyDeliveryReport } = require('../../bounce-detect');
20
+ const { decodeHeaders } = require('../../utils/decode-headers');
21
+ const { isUnsafeKey } = require('../../utils/unsafe-key');
19
22
  const { arfDetect, camelCaseComplaint } = require('../../arf-detect');
20
23
  const appendList = require('../../append-list');
21
24
  const { messageWebSafeHtml } = require('../../web-safe-html');
@@ -39,6 +42,7 @@ const {
39
42
  MAX_INLINE_ATTACHMENT_SIZE,
40
43
  MAX_ALLOWED_DOWNLOAD_SIZE,
41
44
  TRANSIENT_NETWORK_CODES,
45
+ CONNECTION_CLOSING_CODES,
42
46
  PHANTOM_SELECT_FAIL_THRESHOLD,
43
47
  PHANTOM_REPROBE_INTERVAL
44
48
  } = require('../../consts');
@@ -184,8 +188,10 @@ class Mailbox {
184
188
 
185
189
  let hasStoredState = Object.keys(data).length > 0;
186
190
 
187
- // Log diagnostic info if stored uidValidity is invalid or missing
188
- if (!validUidValidity(data.uidValidity)) {
191
+ // Log diagnostic info if the stored status exists but its uidValidity is invalid
192
+ // or missing. A folder that has never been synced has no stored state at all,
193
+ // which is expected and not worth a warning
194
+ if (hasStoredState && !validUidValidity(data.uidValidity)) {
189
195
  this.logger.warn({
190
196
  msg: 'Invalid or missing uidValidity in stored status',
191
197
  path: this.path,
@@ -224,7 +230,8 @@ class Mailbox {
224
230
  let packedUid = await this.connection.packUid(this, uid);
225
231
  if (!packedUid) {
226
232
  this.logger.warn({
227
- msg: `Skipping ${notificationType} notification - packUid returned invalid result`,
233
+ msg: 'Skipping notification, packUid returned invalid result',
234
+ notificationType,
228
235
  uid,
229
236
  path: this.path
230
237
  });
@@ -413,7 +420,7 @@ class Mailbox {
413
420
  return;
414
421
  }
415
422
  this.connection.imapClient.idle().catch(err => {
416
- this.logger.error({ msg: 'IDLE error', err });
423
+ this.logger.warn({ msg: 'IDLE error', err });
417
424
  });
418
425
  }
419
426
 
@@ -754,17 +761,6 @@ class Mailbox {
754
761
  return lock;
755
762
  }
756
763
 
757
- /**
758
- * Marks task as completed and potentially starts idle timer
759
- * @param {Object} connectionClient - IMAP client that completed the task
760
- */
761
- onTaskCompleted(connectionClient) {
762
- connectionClient = connectionClient || this.connection.imapClient;
763
- if (connectionClient === this.connection.imapClient) {
764
- this.connection.onTaskCompleted();
765
- }
766
- }
767
-
768
764
  /**
769
765
  * Helper to log IMAP events with proper formatting
770
766
  * @param {String} msg - Log message
@@ -777,7 +773,7 @@ class Mailbox {
777
773
  if (typeof logObj[key] === 'bigint') {
778
774
  logObj[key] = logObj[key].toString();
779
775
  }
780
- if (typeof logObj[key].has === 'function') {
776
+ if (logObj[key] && typeof logObj[key].has === 'function') {
781
777
  logObj[key] = Array.from(logObj[key]);
782
778
  }
783
779
  });
@@ -804,10 +800,10 @@ class Mailbox {
804
800
  })
805
801
  .then(() => this.select())
806
802
  .catch(err => {
807
- if (err.code === 'IMAPConnectionClosing') {
803
+ if (CONNECTION_CLOSING_CODES.has(err.code)) {
808
804
  this.logger.debug({ msg: 'Sync skipped, connection closing', err });
809
805
  } else {
810
- this.logger.error({ msg: 'Sync error', err });
806
+ this.logger.warn({ msg: 'Failed to sync mailbox after EXISTS', err });
811
807
  }
812
808
  });
813
809
  }, 1000);
@@ -902,7 +898,7 @@ class Mailbox {
902
898
  * @param {Object} messageData - Deleted message data
903
899
  */
904
900
  async processDeleted(messageData) {
905
- this.logger.debug({ msg: 'Deleted', uid: messageData.uid });
901
+ this.logger.debug({ msg: 'Message deleted', uid: messageData.uid });
906
902
 
907
903
  //FIXME: does not work as there is no messageId property
908
904
  /*
@@ -943,7 +939,7 @@ class Mailbox {
943
939
  // Remove from notifications queue since message no longer exists
944
940
  await this.connection.redis.zremrangebyscore(this.getNotificationsKey(), messageData.uid, messageData.uid);
945
941
  } catch (err) {
946
- this.logger.error({ msg: 'Failed removing deleted message from notifications set', uid: messageData.uid, err });
942
+ this.logger.error({ msg: 'Failed to remove deleted message from notifications set', uid: messageData.uid, err });
947
943
  }
948
944
  }
949
945
 
@@ -1263,7 +1259,7 @@ class Mailbox {
1263
1259
  break;
1264
1260
  }
1265
1261
  } catch (err) {
1266
- this.logger.error({ msg: 'Failed to resolve category for message', err, category, uid: messageData.uid, id: messageInfo.id });
1262
+ this.logger.warn({ msg: 'Failed to resolve category for message', err, category, uid: messageData.uid, id: messageInfo.id });
1267
1263
  break;
1268
1264
  }
1269
1265
  }
@@ -1444,7 +1440,7 @@ class Mailbox {
1444
1440
  })
1445
1441
  );
1446
1442
  } catch (err) {
1447
- this.logger.error({
1443
+ this.logger.warn({
1448
1444
  msg: 'Failed to parse calendar event',
1449
1445
  attachment: Object.assign({}, attachment, { content: `${contentBuf.length} bytes` }),
1450
1446
  err
@@ -1572,7 +1568,7 @@ class Mailbox {
1572
1568
  time: Date.now()
1573
1569
  })
1574
1570
  );
1575
- this.logger.error({ msg: 'Failed to fetch embeddings OpenAI', err });
1571
+ this.logger.error({ msg: 'Failed to fetch embeddings from OpenAI', err });
1576
1572
  }
1577
1573
  }
1578
1574
  }
@@ -1634,7 +1630,7 @@ class Mailbox {
1634
1630
  }
1635
1631
  }
1636
1632
  } catch (err) {
1637
- this.logger.error({ msg: 'Attachment error', uid: messageInfo.uid, partList, err });
1633
+ this.logger.error({ msg: 'Failed to download attachments', uid: messageInfo.uid, partList, err });
1638
1634
  }
1639
1635
  }
1640
1636
 
@@ -1788,7 +1784,7 @@ class Mailbox {
1788
1784
  // Normally, these headers are not fetched from the server and only ENVELOPE is used
1789
1785
  let parsedAddresses = {};
1790
1786
  if (messageData.headers) {
1791
- headers = libmime.decodeHeaders(messageData.headers.toString().trim());
1787
+ headers = decodeHeaders(messageData.headers.toString().trim());
1792
1788
  for (let key of ['from', 'to', 'cc', 'bcc']) {
1793
1789
  if (headers[key]?.length) {
1794
1790
  try {
@@ -2144,12 +2140,7 @@ class Mailbox {
2144
2140
  await this.processNew(messageData, messageFetchOptions, canSync, storedStatus);
2145
2141
  await this.connection.redis.zrem(notificationsKey, rawMember);
2146
2142
  } catch (err) {
2147
- if (
2148
- err.code === 'NoConnection' ||
2149
- err.code === 'IMAPConnectionClosing' ||
2150
- err.code === 'EConnectionClosed' ||
2151
- TRANSIENT_NETWORK_CODES.has(err.code)
2152
- ) {
2143
+ if (CONNECTION_CLOSING_CODES.has(err.code) || TRANSIENT_NETWORK_CODES.has(err.code)) {
2153
2144
  throw err;
2154
2145
  }
2155
2146
  await this.connection.redis.zrem(notificationsKey, rawMember);
@@ -2295,7 +2286,7 @@ class Mailbox {
2295
2286
  try {
2296
2287
  await this.connection.refreshAndProcessListing();
2297
2288
  } catch (E) {
2298
- this.logger.error({ msg: 'Missing mailbox', err, E });
2289
+ this.logger.error({ msg: 'Failed to refresh listing after missing mailbox', err: E });
2299
2290
  }
2300
2291
  }
2301
2292
  throw err;
@@ -2352,8 +2343,8 @@ class Mailbox {
2352
2343
  }
2353
2344
 
2354
2345
  // User methods
2355
- // Call `clearTimeout(this.connection.completedTimer);` after locking mailbox
2356
- // Call this.onTaskCompleted() after selected mailbox is processed and lock is released
2346
+ // getMailboxLock() clears connection.completedTimer for the primary connection
2347
+ // Call this.connection.onTaskCompleted(connectionClient) after the selected mailbox is processed and the lock is released
2357
2348
 
2358
2349
  /**
2359
2350
  * Fetches text content for a message
@@ -2396,8 +2387,16 @@ class Mailbox {
2396
2387
  let text = await download(content);
2397
2388
  text = text.toString().replace(/\r?\n/g, '\n');
2398
2389
 
2399
- // Group by content type (plain, html, etc)
2390
+ // Group by content type (plain, html, etc). The subtype comes from the message,
2391
+ // so a sender picks it: for "text/__proto__" the `!result[typeKey]` probe below
2392
+ // finds Object.prototype rather than an array, skips the initializer and then
2393
+ // throws on .reduce() - the same shape lib/utils/header-map.js exists to guard.
2394
+ // Neither name is a real MIME subtype, so the part is grouped as plain text
2395
+ // instead of being dropped.
2400
2396
  let typeKey = (meta.contentType && meta.contentType.split('/')[1]) || 'plain';
2397
+ if (isUnsafeKey(typeKey)) {
2398
+ typeKey = 'plain';
2399
+ }
2401
2400
  if (!result[typeKey]) {
2402
2401
  result[typeKey] = [];
2403
2402
  }
@@ -2415,8 +2414,11 @@ class Mailbox {
2415
2414
  result[typeKey].push(text);
2416
2415
  }
2417
2416
  } finally {
2417
+ // Paired with the lock: a FETCH that throws still selected a mailbox on this
2418
+ // connection, so it still has to be sent back to the one it is watching.
2418
2419
  if (lock) {
2419
2420
  lock.release();
2421
+ this.connection.onTaskCompleted(connectionClient);
2420
2422
  }
2421
2423
  }
2422
2424
 
@@ -2427,10 +2429,6 @@ class Mailbox {
2427
2429
 
2428
2430
  result.hasMore = hasMore;
2429
2431
 
2430
- if (!options.skipLock) {
2431
- this.onTaskCompleted(connectionClient);
2432
- }
2433
-
2434
2432
  return result;
2435
2433
  }
2436
2434
 
@@ -2450,7 +2448,6 @@ class Mailbox {
2450
2448
  let lock = await this.getMailboxLock(connectionClient, { description: `Get attachment: ${message.uid}/${part}` });
2451
2449
 
2452
2450
  let streaming = false;
2453
- let released = false;
2454
2451
  try {
2455
2452
  let { meta, content } = await connectionClient.download(message.uid, part, {
2456
2453
  uid: true,
@@ -2458,7 +2455,9 @@ class Mailbox {
2458
2455
  chunkSize: options.chunkSize
2459
2456
  });
2460
2457
 
2461
- if (!meta) {
2458
+ // Both halves are required: meta describes the part, content is what finished() is
2459
+ // handed below, and getText() already guards the same pair
2460
+ if (!meta || !content) {
2462
2461
  return false;
2463
2462
  }
2464
2463
 
@@ -2483,23 +2482,23 @@ class Mailbox {
2483
2482
  content.contentType = meta.contentType;
2484
2483
  content.filename = meta.filename;
2485
2484
  content.disposition = meta.disposition;
2486
- streaming = true;
2487
2485
 
2488
- // Release lock when stream ends
2489
- content.once('end', () => {
2490
- if (!released) {
2491
- released = true;
2492
- lock.release();
2493
- }
2486
+ // The lock is held for the lifetime of the stream, so it can only be given back once the
2487
+ // stream is done - by any route. Enumerating those routes by hand is what let a consumer
2488
+ // that simply destroys the stream hold the lock forever: an abort emits neither 'end' nor
2489
+ // 'error', only 'close'. finished() covers end, error, destroy and premature close by
2490
+ // contract, and fires exactly once, so there is no set of terminal events left to get
2491
+ // wrong. Reporting the task either way is what every other method here does: however the
2492
+ // download ended, the connection has to go back to the mailbox it is watching.
2493
+ finished(content, () => {
2494
+ lock.release();
2495
+ this.connection.onTaskCompleted(connectionClient);
2494
2496
  });
2495
2497
 
2496
- content.once('error', () => {
2497
- if (!released) {
2498
- released = true;
2499
- lock.release();
2500
- this.connection.onTaskCompleted(connectionClient);
2501
- }
2502
- });
2498
+ // Only once finished() has taken over. Set before the call, a synchronous throw from it
2499
+ // - anything not a stream reaching this far - would leave the finally below believing
2500
+ // the stream owns the lock, and nothing would ever release it.
2501
+ streaming = true;
2503
2502
 
2504
2503
  return content;
2505
2504
  } finally {
@@ -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';