emailengine-app 2.89.0 → 2.91.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 (120) hide show
  1. package/.ncurc.js +19 -8
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +73 -0
  4. package/Dockerfile +7 -3
  5. package/ENVIRONMENT.md +24 -23
  6. package/README.md +1 -1
  7. package/bin/healthcheck.js +1 -1
  8. package/copy-static-files.sh +0 -8
  9. package/data/google-crawlers.json +1 -1
  10. package/encrypt.js +1 -4
  11. package/lib/account/field-codec.js +396 -0
  12. package/lib/account-assignment.js +26 -9
  13. package/lib/account.js +196 -462
  14. package/lib/api-routes/account-routes.js +49 -6
  15. package/lib/api-routes/route-metadata.js +5 -2
  16. package/lib/api-routes/submit-routes.js +15 -2
  17. package/lib/api-token-auth.js +342 -274
  18. package/lib/arf-detect.js +174 -149
  19. package/lib/attachment-size.js +29 -0
  20. package/lib/autodetect-imap-settings.js +482 -296
  21. package/lib/consts.js +5 -5
  22. package/lib/db.js +1 -4
  23. package/lib/email-client/base-client.js +907 -780
  24. package/lib/email-client/gmail-client.js +557 -450
  25. package/lib/email-client/imap/cid-parts.js +61 -0
  26. package/lib/email-client/imap/mailbox.js +376 -422
  27. package/lib/email-client/imap/sync-operations.js +239 -178
  28. package/lib/email-client/imap-client.js +5 -5
  29. package/lib/email-client/message-builder.js +4 -5
  30. package/lib/email-client/new-message-steps.js +168 -2
  31. package/lib/email-client/outlook/graph-message.js +266 -0
  32. package/lib/email-client/outlook/subscription-expiry.js +30 -0
  33. package/lib/email-client/outlook-client.js +652 -808
  34. package/lib/get-raw-email.js +338 -232
  35. package/lib/get-secret.js +1 -4
  36. package/lib/imapproxy/imap-server.js +5 -5
  37. package/lib/license-subscription.js +60 -0
  38. package/lib/load-env.js +48 -0
  39. package/lib/logger-consts.js +37 -1
  40. package/lib/logger.js +1 -4
  41. package/lib/mail-probe.js +157 -0
  42. package/lib/mcp/tools.js +244 -207
  43. package/lib/metric-values.js +76 -0
  44. package/lib/metrics.js +320 -0
  45. package/lib/oauth/gmail.js +39 -120
  46. package/lib/oauth/http-request.js +195 -0
  47. package/lib/oauth/mail-ru.js +33 -60
  48. package/lib/oauth/outlook.js +37 -137
  49. package/lib/oauth/pubsub/google.js +176 -117
  50. package/lib/oauth2-apps.js +440 -463
  51. package/lib/openapi/build-document.js +10 -10
  52. package/lib/read-env-value.js +31 -7
  53. package/lib/redis-backend-warnings.js +70 -0
  54. package/lib/route-descriptors.js +78 -0
  55. package/lib/schemas.js +10 -1
  56. package/lib/sentry-integrations.js +299 -0
  57. package/lib/sentry.js +75 -27
  58. package/lib/sso-routes.js +249 -0
  59. package/lib/sso.js +29 -6
  60. package/lib/tools.js +17 -28
  61. package/lib/ui-routes/account-edit-form.js +198 -0
  62. package/lib/ui-routes/account-page.js +241 -0
  63. package/lib/ui-routes/account-routes.js +46 -349
  64. package/lib/ui-routes/account-setup.js +1 -1
  65. package/lib/ui-routes/auth-routes.js +10 -10
  66. package/lib/ui-routes/provider-signin.js +187 -0
  67. package/lib/ui-routes/route-helpers.js +1 -1
  68. package/lib/ui-routes/unsubscribe-routes.js +2 -2
  69. package/lib/ui-view-context.js +328 -0
  70. package/lib/utils/public-suffix.js +22 -101
  71. package/lib/web-safe-html.js +20 -7
  72. package/lib/worker-metrics.js +82 -0
  73. package/list-generate.js +2 -5
  74. package/package.json +28 -24
  75. package/sbom.json +360 -1030
  76. package/scripts/refresh-test-tokens.js +1 -1
  77. package/server.js +400 -677
  78. package/static/css/flyonui.css +1 -1
  79. package/static/css/public.css +55 -1
  80. package/static/css/src/app.tailwind.css +18 -0
  81. package/static/js/ee-client.js +2619 -645
  82. package/static/js/ui.js +12 -2
  83. package/static/licenses.html +224 -764
  84. package/translations/de.mo +0 -0
  85. package/translations/de.po +429 -390
  86. package/translations/en.mo +0 -0
  87. package/translations/en.po +342 -257
  88. package/translations/es.mo +0 -0
  89. package/translations/es.po +440 -395
  90. package/translations/et.mo +0 -0
  91. package/translations/et.po +425 -375
  92. package/translations/fr.mo +0 -0
  93. package/translations/fr.po +425 -383
  94. package/translations/it.mo +0 -0
  95. package/translations/it.po +441 -394
  96. package/translations/ja.mo +0 -0
  97. package/translations/ja.po +408 -335
  98. package/translations/messages.pot +188 -130
  99. package/translations/nl.mo +0 -0
  100. package/translations/nl.po +419 -382
  101. package/translations/pl.mo +0 -0
  102. package/translations/pl.po +425 -379
  103. package/translations/sv.mo +0 -0
  104. package/translations/sv.po +440 -388
  105. package/translations/tr.mo +0 -0
  106. package/translations/tr.po +441 -387
  107. package/views/account-identity-error.hbs +1 -1
  108. package/views/account-workspace-error.hbs +2 -2
  109. package/views/accounts/browse.hbs +19 -1
  110. package/views/accounts/register/imap-server.hbs +22 -7
  111. package/views/accounts/register/imap.hbs +3 -0
  112. package/views/accounts/register/index.hbs +1 -27
  113. package/views/accounts/register/provider-signin.hbs +58 -0
  114. package/views/oauth-scope-error.hbs +1 -1
  115. package/views/partials/provider_signin_button.hbs +30 -0
  116. package/views/queues/index.hbs +1 -1
  117. package/views/redirect.hbs +1 -1
  118. package/views/unsubscribe.hbs +6 -6
  119. package/workers/api.js +20 -451
  120. package/data/public_suffix_list.dat +0 -16698
@@ -12,35 +12,25 @@ const {
12
12
  validUidValidity,
13
13
  mailboxPathHash,
14
14
  getMailboxStatusKey,
15
- collectCidReferences,
16
15
  embedCidImages
17
16
  } = require('../../tools');
18
17
  const { samePath } = require('../../utils/mailbox-path');
19
18
  const { loadNotifyAttachments } = require('../../notify-attachments');
20
19
  const { connectionNotAvailableError } = require('./connection-errors');
20
+ const { collectCidParts } = require('./cid-parts');
21
21
  const msgpack = require('../../msgpack');
22
22
  const he = require('he');
23
23
  const settings = require('../../settings');
24
- const { bounceDetect, applyDeliveryReport, PARSER_OPTIONS: DSN_PARSER_OPTIONS } = require('../../bounce-detect');
25
24
  const { decodeHeaders } = require('../../utils/decode-headers');
26
25
  const { isUnsafeKey } = require('../../utils/unsafe-key');
27
- const { arfDetect, COMPLAINT_ATTACHMENT_TYPES } = require('../../arf-detect');
28
26
  const { messageWebSafeHtml } = require('../../web-safe-html');
29
- const { parseMessage } = require('../../parse-message');
30
27
  const { collectCalendarEvents } = require('../../calendar-event');
31
28
  const { parseAddressHeader: parseMailboxes } = require('mailparser');
32
29
  const { llmPreProcess, summaryFetchHeaders, summaryProvider } = require('../../llm-pre-process');
33
30
  const { notificationHeaderFields, narrowHeaders } = require('../../utils/header-map');
34
31
  const { getMessageOtp, notifyHeadersIncludeOtp, OTP_FETCH_HEADERS } = require('../../otp');
35
- const {
36
- isOwnSent,
37
- classifyBounce,
38
- bounceNotification,
39
- complaintNotification,
40
- embedInlineImages,
41
- markWebSafe,
42
- notifyNewMessage
43
- } = require('../new-message-steps');
32
+ const { decodedAttachmentSize } = require('../../attachment-size');
33
+ const { isOwnSent, embedInlineImages, markWebSafe, notifyNewMessage, setHiddenContent, runArrivalChecks, runLlmSummary } = require('../new-message-steps');
44
34
  const { isTransientRedisError } = require('../../utils/redis-errors');
45
35
  const { getDelay } = require('../../utils/back-off');
46
36
 
@@ -51,7 +41,6 @@ const {
51
41
  MESSAGE_MISSING_NOTIFY,
52
42
  MAILBOX_NEW_NOTIFY,
53
43
  REDIS_PREFIX,
54
- MAX_INLINE_ATTACHMENT_SIZE,
55
44
  MAX_ALLOWED_DOWNLOAD_SIZE,
56
45
  MAX_BOUNCE_DOWNLOAD_SIZE,
57
46
  TRANSIENT_NETWORK_CODES,
@@ -253,6 +242,66 @@ function preferAddressList(envelopeList, headers, key) {
253
242
  return envelopeList?.length ? envelopeList : undefined;
254
243
  }
255
244
 
245
+ /**
246
+ * Throws for a uid whose message id could not be packed: a message without an id cannot be
247
+ * listed or announced. The error message carries the stored mailbox state, read for the purpose.
248
+ * Only called on that failure, so the common path pays for no extra async frame
249
+ * @param {Mailbox} mailbox
250
+ * @param {Object} messageData - Raw message data from IMAP
251
+ */
252
+ async function throwPackUidFailure(mailbox, messageData) {
253
+ let storedStatus;
254
+ try {
255
+ storedStatus = await mailbox.getStoredStatus();
256
+ } catch (err) {
257
+ storedStatus = { err };
258
+ }
259
+
260
+ mailbox.logger.error({
261
+ msg: 'Failed to generate message ID',
262
+ uid: messageData.uid,
263
+ messageId: messageData.messageId,
264
+ mailbox: mailbox.path,
265
+ storedStatus
266
+ });
267
+
268
+ throw new Error(
269
+ `Failed to generate message ID (uid=${messageData.uid};uv=${storedStatus.uidValidity};path=${mailbox.path};n=${
270
+ storedStatus.err ? 'err' : storedStatus.uidNext
271
+ })`
272
+ );
273
+ }
274
+
275
+ // The message date as an ISO string: the envelope date while it is a valid date, the internal date otherwise
276
+ function resolveMessageDate(envelope, internalDate) {
277
+ let date = envelope.date && typeof envelope.date.toISOString === 'function' && envelope.date.toString() !== 'Invalid Date' ? envelope.date : internalDate;
278
+ return (date && typeof date.toISOString === 'function' && date.toISOString()) || undefined;
279
+ }
280
+
281
+ // A draft is flagged as one, or labelled as one on Gmail
282
+ function isDraftMessage(messageData) {
283
+ return !!((messageData.flags && messageData.flags.has('\\Draft')) || (messageData.labels && messageData.labels.has('\\Draft')));
284
+ }
285
+
286
+ // The convenience booleans of a message are true or left out, and say nothing when no flags were fetched
287
+ function flagSet(flags, flag) {
288
+ return flags && flags.has(flag) ? true : undefined;
289
+ }
290
+
291
+ function flagUnset(flags, flag) {
292
+ return flags && !flags.has(flag) ? true : undefined;
293
+ }
294
+
295
+ // Removes the keys holding undefined, in place
296
+ function compact(result) {
297
+ for (const key of Object.keys(result)) {
298
+ if (typeof result[key] === 'undefined') {
299
+ delete result[key];
300
+ }
301
+ }
302
+ return result;
303
+ }
304
+
256
305
  /**
257
306
  * Represents a single IMAP mailbox/folder and handles all operations on it
258
307
  */
@@ -1453,27 +1502,15 @@ class Mailbox {
1453
1502
  }
1454
1503
 
1455
1504
  /**
1456
- * Processes a new message - fetches details, detects bounces/complaints, sends notifications
1505
+ * Fetches a new message, asking again a few times when the server does not return it yet: some
1506
+ * servers list a message before a FETCH can see it (replication lag)
1457
1507
  * @param {Object} messageData - Basic message data (uid, flags, etc)
1458
- * @param {Object} options - Processing options
1459
- * @param {Object} storedStatus - Current mailbox status
1508
+ * @param {Object} options - Fetch options
1509
+ * @returns {Promise<{ messageInfo: Object|false, missingRetries: number, missingDelay: number }>}
1460
1510
  */
1461
- async processNew(messageData, options, storedStatus, categories, passSettings) {
1462
- this.logger.debug({ msg: 'New message', uid: messageData.uid, flags: Array.from(messageData.flags) });
1463
-
1464
- options.skipLock = true;
1465
-
1466
- // Handle header fetching options
1467
- let requestedHeaders = options.headers;
1468
- if (options.fetchHeaders) {
1469
- options.headers = options.fetchHeaders;
1470
- } else {
1471
- options.headers = 'headers' in options ? options.headers : false;
1472
- }
1473
-
1511
+ async fetchWithReplicationRetry(messageData, options) {
1474
1512
  let messageInfo;
1475
1513
 
1476
- // Retry logic for messages that might not be immediately available (replication lag)
1477
1514
  let missingDelay = 0;
1478
1515
  let missingRetries = 0;
1479
1516
  let maxRetries = 3;
@@ -1498,22 +1535,7 @@ class Mailbox {
1498
1535
  }
1499
1536
  }
1500
1537
 
1501
- if (!messageInfo) {
1502
- // Message not found after retries - send missing notification
1503
- let packedUid = await this.packUidWithLogging(messageData.uid, 'missing');
1504
- if (!packedUid) {
1505
- return;
1506
- }
1507
- await this.connection.notify(this, MESSAGE_MISSING_NOTIFY, {
1508
- id: packedUid,
1509
- uid: messageData.uid,
1510
- missingRetries,
1511
- missingDelay
1512
- });
1513
- return;
1514
- }
1515
-
1516
- if (missingRetries) {
1538
+ if (messageInfo && missingRetries) {
1517
1539
  // Log retry statistics if message was eventually found
1518
1540
  messageInfo.missingDelay = missingDelay;
1519
1541
  messageInfo.missingRetries = missingRetries;
@@ -1521,14 +1543,24 @@ class Mailbox {
1521
1543
  this.logger.debug({ msg: 'Missing message', status: 'found', uid: messageData.uid, missingRetries, missingDelay });
1522
1544
  }
1523
1545
 
1524
- // Check if message is too old to notify about
1546
+ return { messageInfo, missingRetries, missingDelay };
1547
+ }
1548
+
1549
+ /**
1550
+ * Whether a fetched new message is not announced: older than notifyFrom, or, after a reconnect,
1551
+ * one that was already in a folder other than the Inbox or All Mail before the connection
1552
+ * @param {Object} messageInfo - The fetched message
1553
+ * @param {Object} messageData - Basic message data (uid, flags, etc)
1554
+ * @param {Object} storedStatus - Current mailbox status
1555
+ * @returns {boolean}
1556
+ */
1557
+ shouldSkipArrival(messageInfo, messageData, storedStatus) {
1525
1558
  let date = new Date(messageInfo.date);
1526
1559
  if (this.connection.notifyFrom && date < this.connection.notifyFrom) {
1527
1560
  // skip too old messages
1528
- return;
1561
+ return true;
1529
1562
  }
1530
1563
 
1531
- // Skip old messages in non-INBOX folders on reconnect
1532
1564
  if (this.previouslyConnected && !samePath(this.path, 'INBOX') && !this.isAllMail && storedStatus.initialUidNext > messageData.uid) {
1533
1565
  this.logger.debug({
1534
1566
  msg: 'Skip old message',
@@ -1538,175 +1570,199 @@ class Mailbox {
1538
1570
  uid: messageInfo.uid,
1539
1571
  connectCount: this.previouslyConnected
1540
1572
  });
1541
- return;
1573
+ return true;
1542
1574
  }
1543
1575
 
1544
- let bounceNotifyInfo;
1545
- let complaintNotifyInfo;
1546
- let content;
1547
- // Set once a download found the message already expunged
1548
- let messageGone = false;
1576
+ return false;
1577
+ }
1549
1578
 
1550
- // Check if this might be an ARF (Abuse Reporting Format) complaint
1551
- if (this.connection.mightBeAComplaint(messageInfo)) {
1552
- try {
1553
- // Download relevant attachments for ARF parsing
1554
- for (let attachment of messageInfo.attachments || []) {
1555
- if (!COMPLAINT_ATTACHMENT_TYPES.includes(attachment.contentType)) {
1556
- continue;
1557
- }
1579
+ /**
1580
+ * Downloads one part a complaint check reads. Headers should fit into 1MB, the check does not
1581
+ * need the rest
1582
+ * @param {Object} messageInfo - The message being checked
1583
+ * @param {Object} attachment - Attachment entry to fill in
1584
+ * @param {Object} options - Processing options, for the download chunk size
1585
+ */
1586
+ async loadComplaintPart(messageInfo, attachment, options) {
1587
+ let buf = Buffer.from(attachment.id, 'base64url');
1588
+ let part = buf.subarray(8).toString();
1558
1589
 
1559
- let buf = Buffer.from(attachment.id, 'base64url');
1560
- let part = buf.subarray(8).toString();
1590
+ let { content: sourceStream } = await this.requireImapClient().download(messageInfo.uid, part, {
1591
+ uid: true,
1592
+ maxBytes: Math.min(1 * 1024 * 1024, MAX_ALLOWED_DOWNLOAD_SIZE),
1593
+ chunkSize: options.chunkSize
1594
+ });
1561
1595
 
1562
- let { content: sourceStream } = await this.requireImapClient().download(messageInfo.uid, part, {
1563
- uid: true,
1564
- // headers should fit into 1MB, don't need all contents
1565
- maxBytes: Math.min(1 * 1024 * 1024, MAX_ALLOWED_DOWNLOAD_SIZE),
1566
- chunkSize: options.chunkSize
1567
- });
1596
+ if (sourceStream) {
1597
+ setHiddenContent(attachment, (await download(sourceStream)).toString());
1598
+ }
1599
+ }
1568
1600
 
1569
- if (sourceStream) {
1570
- Object.defineProperty(attachment, 'content', {
1571
- value: (await download(sourceStream)).toString(),
1572
- enumerable: false
1573
- });
1574
- }
1575
- }
1601
+ /**
1602
+ * Downloads a new message for the delivery report and bounce checks. A delivery report is small
1603
+ * and its status part comes first, so the download is cut well below the general cap: the rest
1604
+ * is the returned original, which the parse does not need and which a sender can make as large
1605
+ * as the server allows
1606
+ * @param {Object} messageInfo - The message being checked
1607
+ * @param {Object} options - Processing options, for the download chunk size
1608
+ * @returns {Promise<Object|undefined>} The content stream, nothing once the message is expunged
1609
+ */
1610
+ async fetchBounceSource(messageInfo, options) {
1611
+ let { content } = await this.requireImapClient().download(messageInfo.uid, false, {
1612
+ uid: true,
1613
+ chunkSize: options.chunkSize,
1614
+ maxBytes: MAX_BOUNCE_DOWNLOAD_SIZE
1615
+ });
1616
+ return content;
1617
+ }
1576
1618
 
1577
- // Parse ARF report
1578
- const report = await arfDetect(messageInfo);
1619
+ /**
1620
+ * Sets the Gmail category of an Inbox message found in All Mail, when resolving categories is on
1621
+ * @param {Object} messageInfo - The new message, changed in place
1622
+ * @param {Object} messageData - Basic message data (uid, flags, etc)
1623
+ * @param {Object} [categories] - The resolver of the pass, see createCategoryResolver()
1624
+ * @param {boolean} resolveGmailCategories - The setting
1625
+ */
1626
+ async resolveGmailCategory(messageInfo, messageData, categories, resolveGmailCategories) {
1627
+ if (
1628
+ !this.connection.imapClient?.capabilities?.has('X-GM-EXT-1') ||
1629
+ !this.isAllMail ||
1630
+ !messageInfo.labels ||
1631
+ !messageInfo.labels.includes('\\Inbox') ||
1632
+ !resolveGmailCategories
1633
+ ) {
1634
+ return;
1635
+ }
1579
1636
 
1580
- complaintNotifyInfo = complaintNotification(report, messageInfo);
1581
- } catch (err) {
1582
- if (isConnectionGone(err)) {
1583
- throw err;
1584
- }
1585
- this.logger.error({
1586
- msg: 'Failed to process ARF',
1587
- id: messageInfo.id,
1588
- uid: messageInfo.uid,
1589
- messageId: messageInfo.messageId,
1590
- err
1637
+ try {
1638
+ const category = await (categories || this.createCategoryResolver()).categoryOf(messageInfo.uid);
1639
+ if (category) {
1640
+ messageInfo.category = category;
1641
+ this.logger.debug({
1642
+ msg: 'Resolved category for incoming email',
1643
+ category,
1644
+ uid: messageData.uid,
1645
+ id: messageInfo.id
1591
1646
  });
1592
1647
  }
1648
+ } catch (err) {
1649
+ if (isConnectionGone(err)) {
1650
+ throw err;
1651
+ }
1652
+ this.logger.warn({ msg: 'Failed to resolve category for message', err, uid: messageData.uid, id: messageInfo.id });
1653
+ }
1654
+ }
1655
+
1656
+ /**
1657
+ * Sets seemsLikeNew from the seen-messages HyperLogLog. A message the account sent itself never
1658
+ * seems new and is not counted
1659
+ * @param {Object} messageInfo - The new message, changed in place
1660
+ */
1661
+ async markSeenLikeNew(messageInfo) {
1662
+ messageInfo.seemsLikeNew =
1663
+ !isOwnSent(messageInfo, this.listingEntry.specialUse) &&
1664
+ !!(await this.connection.redis.pfadd(this.getSeenMessagesKey(), messageInfo.emailId || messageInfo.messageId));
1665
+ }
1666
+
1667
+ /**
1668
+ * Renders the web-safe copy of a new message and embeds the images its HTML references by
1669
+ * Content-ID, downloading the ones not loaded yet in one batch
1670
+ * @param {Object} messageInfo - The new message, changed in place
1671
+ */
1672
+ async buildWebSafeHtml(messageInfo) {
1673
+ messageInfo.text._generatedHtml = await messageWebSafeHtml(messageInfo);
1674
+ markWebSafe(messageInfo.text);
1675
+
1676
+ if (!messageInfo.text.html || !messageInfo.attachments) {
1677
+ return;
1678
+ }
1679
+
1680
+ let { attachmentList, partList } = collectCidParts(messageInfo, { reuseLoaded: true });
1681
+ if (!attachmentList.size) {
1682
+ return;
1593
1683
  }
1594
1684
 
1595
- // Check if this might be a DSN (Delivery Status Notification)
1596
- if (this.connection.mightBeDSNResponse(messageInfo)) {
1597
- let sourceStream;
1685
+ if (partList.length) {
1598
1686
  try {
1599
- // A delivery report is small and its status part comes first, so the download is
1600
- // cut well below the general cap: the rest is the returned original, which the
1601
- // parse does not need and which a sender can make as large as the server allows
1602
- ({ content: sourceStream } = await this.requireImapClient().download(messageInfo.uid, false, {
1687
+ let contentParts = await this.requireImapClient().downloadMany(messageInfo.uid, partList, {
1603
1688
  uid: true,
1604
- chunkSize: options.chunkSize,
1605
- maxBytes: MAX_BOUNCE_DOWNLOAD_SIZE
1606
- }));
1607
-
1608
- // No content means the message was expunged after it was detected (a server-side
1609
- // filter moving it to Junk, for instance), which is a normal race and not a failure.
1610
- // The bounce check below does not ask for it again
1611
- if (!sourceStream) {
1612
- messageGone = true;
1613
- } else {
1614
- let parsed = await parseMessage(sourceStream, DSN_PARSER_OPTIONS);
1615
- if (parsed) {
1616
- content = { parsed };
1617
- applyDeliveryReport(parsed, messageInfo, this.logger);
1689
+ maxBytes: MAX_ALLOWED_DOWNLOAD_SIZE
1690
+ });
1691
+
1692
+ if (contentParts) {
1693
+ for (let [contentId, { attachment }] of attachmentList) {
1694
+ if (attachment.part && contentParts[attachment.part] && contentParts[attachment.part].content) {
1695
+ attachmentList.set(contentId, { attachment, content: contentParts[attachment.part].content.toString('base64') });
1696
+ }
1618
1697
  }
1619
1698
  }
1620
1699
  } catch (err) {
1621
- // A parser failure leaves the IMAP download unconsumed
1622
- sourceStream?.destroy?.();
1623
1700
  if (isConnectionGone(err)) {
1624
1701
  throw err;
1625
1702
  }
1626
- this.logger.error({
1627
- msg: 'Failed to process DSN',
1628
- id: messageInfo.id,
1629
- uid: messageInfo.uid,
1630
- messageId: messageInfo.messageId,
1631
- err
1632
- });
1703
+ this.logger.error({ msg: 'Failed to download attachments', uid: messageInfo.uid, partList, err });
1633
1704
  }
1634
1705
  }
1635
1706
 
1636
- // Check if this could be a bounce message
1637
- if (this.connection.mightBeABounce(messageInfo)) {
1638
- // Parse for bounce information
1639
- try {
1640
- if (!content && !messageGone) {
1641
- let result = await this.requireImapClient().download(messageInfo.uid, false, {
1642
- uid: true,
1643
- chunkSize: options.chunkSize,
1644
- maxBytes: MAX_BOUNCE_DOWNLOAD_SIZE
1645
- });
1646
- content = result.content;
1647
- }
1707
+ embedInlineImages(messageInfo.text, attachmentList);
1708
+ }
1648
1709
 
1649
- if (content) {
1650
- // Detect bounce details
1651
- let bounce = await bounceDetect(content);
1710
+ /**
1711
+ * Processes a new message - fetches details, detects bounces/complaints, sends notifications.
1712
+ * Runs under the caller's lock (options.skipLock), and every step lets a gone connection
1713
+ * propagate so the message stays queued rather than being announced half processed
1714
+ * @param {Object} messageData - Basic message data (uid, flags, etc)
1715
+ * @param {Object} options - Processing options
1716
+ * @param {Object} storedStatus - Current mailbox status
1717
+ */
1718
+ async processNew(messageData, options, storedStatus, categories, passSettings) {
1719
+ this.logger.debug({ msg: 'New message', uid: messageData.uid, flags: Array.from(messageData.flags) });
1652
1720
 
1653
- await classifyBounce(bounce, this.connection.call, this.logger);
1654
- bounceNotifyInfo = bounceNotification(bounce, messageInfo);
1721
+ options.skipLock = true;
1655
1722
 
1656
- this.logger.debug({
1657
- msg: 'Detected bounce message',
1658
- id: messageInfo.id,
1659
- uid: messageInfo.uid,
1660
- messageId: messageInfo.messageId,
1661
- bounce
1662
- });
1663
- }
1664
- } catch (err) {
1665
- // A parser failure leaves the IMAP download unconsumed, as in the DSN branch above
1666
- content?.destroy?.();
1667
- if (isConnectionGone(err)) {
1668
- throw err;
1669
- }
1670
- this.logger.error({
1671
- msg: 'Failed to process potential bounce',
1672
- id: messageInfo.id,
1673
- uid: messageInfo.uid,
1674
- messageId: messageInfo.messageId,
1675
- err
1676
- });
1723
+ // Handle header fetching options
1724
+ let requestedHeaders = options.headers;
1725
+ if (options.fetchHeaders) {
1726
+ options.headers = options.fetchHeaders;
1727
+ } else {
1728
+ options.headers = 'headers' in options ? options.headers : false;
1729
+ }
1730
+
1731
+ let { messageInfo, missingRetries, missingDelay } = await this.fetchWithReplicationRetry(messageData, options);
1732
+
1733
+ if (!messageInfo) {
1734
+ // Message not found after retries - send missing notification
1735
+ let packedUid = await this.packUidWithLogging(messageData.uid, 'missing');
1736
+ if (!packedUid) {
1737
+ return;
1677
1738
  }
1739
+ await this.connection.notify(this, MESSAGE_MISSING_NOTIFY, {
1740
+ id: packedUid,
1741
+ uid: messageData.uid,
1742
+ missingRetries,
1743
+ missingDelay
1744
+ });
1745
+ return;
1746
+ }
1747
+
1748
+ if (this.shouldSkipArrival(messageInfo, messageData, storedStatus)) {
1749
+ return;
1678
1750
  }
1679
1751
 
1752
+ const { bounceNotifyInfo, complaintNotifyInfo } = await runArrivalChecks(messageInfo, {
1753
+ detector: this.connection,
1754
+ loadComplaintPart: attachment => this.loadComplaintPart(messageInfo, attachment, options),
1755
+ fetchSource: () => this.fetchBounceSource(messageInfo, options),
1756
+ rethrow: isConnectionGone,
1757
+ call: this.connection.call,
1758
+ logger: this.logger
1759
+ });
1760
+
1680
1761
  // The settings the rest of this message reads: those the pass read once, or one round trip
1681
1762
  const { notifyAttachments, notifyAttachmentSize, notifyCalendarEvents, notifyWebSafeHtml, resolveGmailCategories } =
1682
1763
  passSettings || (await settings.getMulti(...NEW_MESSAGE_SETTINGS));
1683
1764
 
1684
- // Resolve Gmail category for inbox messages
1685
- if (
1686
- this.connection.imapClient?.capabilities?.has('X-GM-EXT-1') &&
1687
- this.isAllMail &&
1688
- messageInfo.labels &&
1689
- messageInfo.labels.includes('\\Inbox') &&
1690
- resolveGmailCategories
1691
- ) {
1692
- try {
1693
- const category = await (categories || this.createCategoryResolver()).categoryOf(messageInfo.uid);
1694
- if (category) {
1695
- messageInfo.category = category;
1696
- this.logger.debug({
1697
- msg: 'Resolved category for incoming email',
1698
- category,
1699
- uid: messageData.uid,
1700
- id: messageInfo.id
1701
- });
1702
- }
1703
- } catch (err) {
1704
- if (isConnectionGone(err)) {
1705
- throw err;
1706
- }
1707
- this.logger.warn({ msg: 'Failed to resolve category for message', err, uid: messageData.uid, id: messageInfo.id });
1708
- }
1709
- }
1765
+ await this.resolveGmailCategory(messageInfo, messageData, categories, resolveGmailCategories);
1710
1766
 
1711
1767
  const loadAttachment = attachment => this.loadAttachmentContent(messageInfo, attachment, options);
1712
1768
 
@@ -1723,94 +1779,18 @@ class Mailbox {
1723
1779
  }
1724
1780
  }
1725
1781
 
1726
- // Check if we have seen this message before using HyperLogLog
1727
- messageInfo.seemsLikeNew =
1728
- !isOwnSent(messageInfo, this.listingEntry.specialUse) &&
1729
- !!(await this.connection.redis.pfadd(this.getSeenMessagesKey(), messageInfo.emailId || messageInfo.messageId));
1782
+ await this.markSeenLikeNew(messageInfo);
1730
1783
 
1731
- // Process with LLM if configured for inbox messages. A message with no text part has no
1732
- // text object at all, and nothing to summarize
1733
- if (messageInfo.messageSpecialUse === '\\Inbox' && (messageInfo.text?.plain || messageInfo.text?.html)) {
1734
- let messageData = Object.assign({ account: this.connection.account }, messageInfo);
1735
-
1736
- if (await llmPreProcess.run(messageData)) {
1737
- await llmPreProcess.summarize(messageInfo, {
1738
- call: this.connection.call,
1739
- redis: this.connection.redis,
1740
- account: this.connection.account,
1741
- provider: summaryProvider(this.connection),
1742
- logger: this.logger
1743
- });
1744
- }
1745
- }
1784
+ await runLlmSummary(messageInfo, this.connection.account, () => ({
1785
+ call: this.connection.call,
1786
+ redis: this.connection.redis,
1787
+ account: this.connection.account,
1788
+ provider: summaryProvider(this.connection),
1789
+ logger: this.logger
1790
+ }));
1746
1791
 
1747
- // Convert message HTML to web safe HTML
1748
1792
  if (notifyWebSafeHtml && messageInfo.text && (messageInfo.text.html || messageInfo.text.plain)) {
1749
- // convert to web safe
1750
- messageInfo.text._generatedHtml = await messageWebSafeHtml(messageInfo);
1751
- markWebSafe(messageInfo.text);
1752
-
1753
- // Embed images referenced by Content-ID
1754
- if (messageInfo.text.html && messageInfo.attachments) {
1755
- let attachmentList = new Map();
1756
- let partList = [];
1757
- let cidReferences = collectCidReferences(messageInfo.text.html);
1758
-
1759
- // Collect CID-referenced attachments
1760
- for (let attachment of messageInfo.attachments || []) {
1761
- let contentId = attachment.contentId && attachment.contentId.replace(/^<|>$/g, '');
1762
- if (contentId && cidReferences.has(contentId)) {
1763
- attachmentList.set(contentId, {
1764
- attachment,
1765
- content: attachment.content || null
1766
- });
1767
-
1768
- if (attachment.content || (attachment.encodedSize && attachment.encodedSize > MAX_INLINE_ATTACHMENT_SIZE)) {
1769
- // already loaded by notifyAttachments, or too large to inline
1770
- continue;
1771
- }
1772
-
1773
- let buf = Buffer.from(attachment.id, 'base64url');
1774
- let part = buf.subarray(8).toString();
1775
-
1776
- Object.defineProperty(attachment, 'part', {
1777
- value: part,
1778
- enumerable: false
1779
- });
1780
-
1781
- if (!partList.includes(part)) {
1782
- partList.push(part);
1783
- }
1784
- }
1785
- }
1786
-
1787
- if (attachmentList.size) {
1788
- if (partList.length) {
1789
- // Download missing attachments in batch
1790
- try {
1791
- let contentParts = await this.requireImapClient().downloadMany(messageInfo.uid, partList, {
1792
- uid: true,
1793
- maxBytes: MAX_ALLOWED_DOWNLOAD_SIZE
1794
- });
1795
-
1796
- if (contentParts) {
1797
- for (let [contentId, { attachment }] of attachmentList) {
1798
- if (attachment.part && contentParts[attachment.part] && contentParts[attachment.part].content) {
1799
- attachmentList.set(contentId, { attachment, content: contentParts[attachment.part].content.toString('base64') });
1800
- }
1801
- }
1802
- }
1803
- } catch (err) {
1804
- if (isConnectionGone(err)) {
1805
- throw err;
1806
- }
1807
- this.logger.error({ msg: 'Failed to download attachments', uid: messageInfo.uid, partList, err });
1808
- }
1809
- }
1810
-
1811
- embedInlineImages(messageInfo.text, attachmentList);
1812
- }
1813
- }
1793
+ await this.buildWebSafeHtml(messageInfo);
1814
1794
  }
1815
1795
 
1816
1796
  // Narrow the headers to what the caller asked for. This runs last: the complaint, delivery
@@ -1863,28 +1843,8 @@ class Mailbox {
1863
1843
 
1864
1844
  // Generate unique message ID
1865
1845
  let packedUid = await this.connection.packUid(this, messageData.uid, statusCache);
1866
-
1867
1846
  if (!packedUid) {
1868
- let storedStatus;
1869
- try {
1870
- storedStatus = await this.getStoredStatus();
1871
- } catch (err) {
1872
- storedStatus = { err };
1873
- }
1874
-
1875
- this.logger.error({
1876
- msg: 'Failed to generate message ID',
1877
- uid: messageData.uid,
1878
- messageId: messageData.messageId,
1879
- mailbox: this.path,
1880
- storedStatus
1881
- });
1882
-
1883
- throw new Error(
1884
- `Failed to generate message ID (uid=${messageData.uid};uv=${storedStatus.uidValidity};path=${this.path};n=${
1885
- storedStatus.err ? 'err' : storedStatus.uidNext
1886
- })`
1887
- );
1847
+ await throwPackUidFailure(this, messageData);
1888
1848
  }
1889
1849
 
1890
1850
  // Extract attachment information from body structure
@@ -1892,26 +1852,13 @@ class Mailbox {
1892
1852
 
1893
1853
  let envelope = messageData.envelope || {};
1894
1854
 
1895
- // Use envelope date or fall back to internal date
1896
- let date =
1897
- envelope.date && typeof envelope.date.toISOString === 'function' && envelope.date.toString() !== 'Invalid Date'
1898
- ? envelope.date
1899
- : messageData.internalDate;
1900
-
1901
- let isDraft = false;
1902
- if (messageData.flags && messageData.flags.has('\\Draft')) {
1903
- isDraft = true;
1904
- }
1855
+ let isDraft = isDraftMessage(messageData);
1905
1856
 
1906
1857
  // Do not expose the \Recent flag as it is session specific
1907
1858
  if (messageData.flags && messageData.flags.has('\\Recent')) {
1908
1859
  messageData.flags.delete('\\Recent');
1909
1860
  }
1910
1861
 
1911
- if (messageData.labels && messageData.labels.has('\\Draft')) {
1912
- isDraft = true;
1913
- }
1914
-
1915
1862
  // The address fields fall back to these when the ENVELOPE carries no usable address,
1916
1863
  // which Lark Mail does by omitting them and any server can do by mis-parsing a
1917
1864
  // malformed header. See preferAddressList(). Normally only the ENVELOPE is used, and
@@ -1921,8 +1868,8 @@ class Mailbox {
1921
1868
  headers = decodeHeaders(messageData.headers.toString().trim());
1922
1869
  }
1923
1870
 
1924
- // Build message info object
1925
- const result = {
1871
+ // Build message info object, without the properties that hold undefined
1872
+ const result = compact({
1926
1873
  id: packedUid,
1927
1874
  uid: messageData.uid,
1928
1875
 
@@ -1931,14 +1878,14 @@ class Mailbox {
1931
1878
  emailId: messageData.emailId || undefined,
1932
1879
  threadId: messageData.threadId || undefined,
1933
1880
 
1934
- date: (date && typeof date.toISOString === 'function' && date.toISOString()) || undefined,
1881
+ date: resolveMessageDate(envelope, messageData.internalDate),
1935
1882
 
1936
1883
  flags: messageData.flags ? Array.from(messageData.flags) : undefined,
1937
1884
  labels: messageData.labels ? Array.from(messageData.labels) : undefined,
1938
1885
 
1939
- unseen: messageData.flags && !messageData.flags.has('\\Seen') ? true : undefined,
1940
- flagged: messageData.flags && messageData.flags.has('\\Flagged') ? true : undefined,
1941
- answered: messageData.flags && messageData.flags.has('\\Answered') ? true : undefined,
1886
+ unseen: flagUnset(messageData.flags, '\\Seen'),
1887
+ flagged: flagSet(messageData.flags, '\\Flagged'),
1888
+ answered: flagSet(messageData.flags, '\\Answered'),
1942
1889
 
1943
1890
  draft: isDraft ? true : undefined,
1944
1891
 
@@ -1966,13 +1913,6 @@ class Mailbox {
1966
1913
  encodedSize: encodedTextSize
1967
1914
  }
1968
1915
  : undefined
1969
- };
1970
-
1971
- // Remove undefined properties
1972
- Object.keys(result).forEach(key => {
1973
- if (typeof result[key] === 'undefined') {
1974
- delete result[key];
1975
- }
1976
1916
  });
1977
1917
 
1978
1918
  // Check if message is an auto-reply
@@ -1998,7 +1938,8 @@ class Mailbox {
1998
1938
  let attachments = [];
1999
1939
  let textParts = [[], [], []]; // [plain, html, other]
2000
1940
  if (!bodyStructure) {
2001
- return attachments;
1941
+ // The same shape as below, with no text part to point at
1942
+ return { attachments, textId: undefined, encodedTextSize: {} };
2002
1943
  }
2003
1944
 
2004
1945
  let idBuf = Buffer.from(packedUid, 'base64url');
@@ -2020,6 +1961,7 @@ class Mailbox {
2020
1961
  id: Buffer.concat([idBuf, Buffer.from(node.part || '1')]).toString('base64url'),
2021
1962
  contentType: node.type,
2022
1963
  encodedSize: node.size,
1964
+ size: decodedAttachmentSize(node.size, node.encoding),
2023
1965
 
2024
1966
  embedded: isRelated,
2025
1967
  inline: node.disposition === 'inline' || (!node.disposition && isRelated),
@@ -2642,20 +2584,15 @@ class Mailbox {
2642
2584
  }
2643
2585
 
2644
2586
  /**
2645
- * Fetches complete message details. Every message it returns carries `messageSpecialUse`,
2646
- * which the arrival checks in processNew() and the fetch-time bounce check gate on
2587
+ * The FETCH half of getMessage(), all of it under the message lock, which is released on every
2588
+ * way out. Nothing that addresses the message by UID may run after the release without a lock
2589
+ * of its own: another task could select a different folder in between
2590
+ * @param {Object} connectionClient - The connection to fetch on
2647
2591
  * @param {Object} message - Message object with uid
2648
2592
  * @param {Object} options - Fetch options
2649
- * @param {Object} connectionOptions - Connection options
2650
- * @returns {Object} Complete message information
2593
+ * @returns {Promise<Object|false>} The message information, false when there is none
2651
2594
  */
2652
- async getMessage(message, options, connectionOptions) {
2653
- options = options || {};
2654
-
2655
- let messageInfo;
2656
-
2657
- const connectionClient = await this.connection.getImapConnection(connectionOptions);
2658
-
2595
+ async fetchUnderLock(connectionClient, message, options) {
2659
2596
  let lock = await this.lockForMessage(connectionClient, message, { description: `Get message: ${message.uid}`, skipLock: options.skipLock });
2660
2597
  if (!lock) {
2661
2598
  // issued for a previous incarnation of this folder
@@ -2702,7 +2639,7 @@ class Mailbox {
2702
2639
  }
2703
2640
  }
2704
2641
 
2705
- messageInfo = await this.getMessageInfo(messageData, true);
2642
+ let messageInfo = await this.getMessageInfo(messageData, true);
2706
2643
 
2707
2644
  if (messageInfo) {
2708
2645
  // Add mailbox special use information
@@ -2725,44 +2662,124 @@ class Mailbox {
2725
2662
  });
2726
2663
  }
2727
2664
  }
2665
+
2666
+ return messageInfo;
2667
+ } finally {
2668
+ lock.release();
2669
+ }
2670
+ }
2671
+
2672
+ /**
2673
+ * Reads the text parts textType asks for and merges them into the message text
2674
+ * @param {Object} connectionClient - The connection the message was fetched on
2675
+ * @param {Object} message - Message object with uid
2676
+ * @param {Object} messageInfo - The fetched message, changed in place
2677
+ * @param {Object} options - Fetch options
2678
+ */
2679
+ async attachTextContent(connectionClient, message, messageInfo, options) {
2680
+ let { textParts } = await this.connection.getMessageTextPaths(messageInfo.text.id);
2681
+ if (!textParts || !textParts.length) {
2682
+ return;
2683
+ }
2684
+
2685
+ // Select which text parts to fetch
2686
+ switch (options.textType) {
2687
+ case 'plain':
2688
+ textParts = textParts[0];
2689
+ break;
2690
+ case 'html':
2691
+ textParts = textParts[1];
2692
+ break;
2693
+ default:
2694
+ textParts = textParts.flatMap(entry => entry);
2695
+ break;
2696
+ }
2697
+
2698
+ if (!textParts || !textParts.length) {
2699
+ return;
2700
+ }
2701
+
2702
+ let textContent = await this.getText(message, textParts, options, { connectionClient });
2703
+ if (options.textType && options.textType !== '*') {
2704
+ textContent = {
2705
+ [options.textType]: textContent[options.textType] || '',
2706
+ hasMore: textContent.hasMore
2707
+ };
2708
+ }
2709
+ messageInfo.text = Object.assign(messageInfo.text, textContent);
2710
+ }
2711
+
2712
+ /**
2713
+ * Replaces the Content-ID references of the HTML with the images they name, downloaded in one
2714
+ * batch under a lock of its own: the lock taken for the FETCH is released by now, and without
2715
+ * one another task can select a different mailbox on this connection first, so the UID would
2716
+ * address whatever message carries it there
2717
+ * @param {Object} connectionClient - The connection the message was fetched on
2718
+ * @param {Object} message - Message object with uid
2719
+ * @param {Object} messageInfo - The fetched message, changed in place
2720
+ * @param {Object} options - Fetch options
2721
+ */
2722
+ async embedInlineImagesWithLock(connectionClient, message, messageInfo, options) {
2723
+ let { attachmentList, partList } = collectCidParts(messageInfo);
2724
+ if (!partList.length) {
2725
+ return;
2726
+ }
2727
+
2728
+ let lock;
2729
+ try {
2730
+ if (!options.skipLock) {
2731
+ lock = await this.getMailboxLock(connectionClient, { description: `Download inline images: ${message.uid}` });
2732
+ }
2733
+
2734
+ // Download all referenced images in batch
2735
+ let contentParts = await connectionClient.downloadMany(messageInfo.uid, partList, {
2736
+ uid: true,
2737
+ maxBytes: MAX_ALLOWED_DOWNLOAD_SIZE
2738
+ });
2739
+
2740
+ if (contentParts) {
2741
+ for (let { attachment } of attachmentList.values()) {
2742
+ if (attachment.part && contentParts[attachment.part] && contentParts[attachment.part].content) {
2743
+ setHiddenContent(attachment, contentParts[attachment.part].content);
2744
+ }
2745
+ }
2746
+
2747
+ // Replace CID references with data URIs
2748
+ messageInfo.text.html = embedCidImages(messageInfo.text.html, contentId => {
2749
+ let { attachment } = attachmentList.get(contentId) || {};
2750
+ return attachment?.content && { contentType: attachment.contentType, content: attachment.content.toString('base64') };
2751
+ });
2752
+ }
2753
+ } catch (err) {
2754
+ this.logger.error({ msg: 'Failed to download attachments', uid: messageInfo.uid, partList, err });
2728
2755
  } finally {
2729
2756
  if (lock) {
2730
2757
  lock.release();
2731
2758
  }
2732
2759
  }
2760
+ }
2761
+
2762
+ /**
2763
+ * Fetches complete message details. Every message it returns carries `messageSpecialUse`,
2764
+ * which the arrival checks in processNew() and the fetch-time bounce check gate on
2765
+ * @param {Object} message - Message object with uid
2766
+ * @param {Object} options - Fetch options
2767
+ * @param {Object} connectionOptions - Connection options
2768
+ * @returns {Object} Complete message information
2769
+ */
2770
+ async getMessage(message, options, connectionOptions) {
2771
+ options = options || {};
2772
+
2773
+ const connectionClient = await this.connection.getImapConnection(connectionOptions);
2733
2774
 
2775
+ let messageInfo = await this.fetchUnderLock(connectionClient, message, options);
2734
2776
  if (!messageInfo) {
2735
2777
  return false;
2736
2778
  }
2737
2779
 
2738
2780
  // Merge decoded text content with message data (if requested)
2739
2781
  if (options.textType && messageInfo.text && messageInfo.text.id) {
2740
- let { textParts } = await this.connection.getMessageTextPaths(messageInfo.text.id);
2741
- if (textParts && textParts.length) {
2742
- // Select which text parts to fetch
2743
- switch (options.textType) {
2744
- case 'plain':
2745
- textParts = textParts[0];
2746
- break;
2747
- case 'html':
2748
- textParts = textParts[1];
2749
- break;
2750
- default:
2751
- textParts = textParts.flatMap(entry => entry);
2752
- break;
2753
- }
2754
-
2755
- if (textParts && textParts.length) {
2756
- let textContent = await this.getText(message, textParts, options, { connectionClient });
2757
- if (options.textType && options.textType !== '*') {
2758
- textContent = {
2759
- [options.textType]: textContent[options.textType] || '',
2760
- hasMore: textContent.hasMore
2761
- };
2762
- }
2763
- messageInfo.text = Object.assign(messageInfo.text, textContent);
2764
- }
2765
- }
2782
+ await this.attachTextContent(connectionClient, message, messageInfo, options);
2766
2783
  }
2767
2784
 
2768
2785
  // Convert to web-safe HTML if requested
@@ -2773,70 +2790,7 @@ class Mailbox {
2773
2790
 
2774
2791
  // Embed attached images as data URIs if requested
2775
2792
  if (options.embedAttachedImages && messageInfo.text && messageInfo.text.html && messageInfo.attachments) {
2776
- let attachmentList = new Map();
2777
- let partList = [];
2778
- let cidReferences = collectCidReferences(messageInfo.text.html);
2779
-
2780
- // Find images referenced by CID
2781
- for (let attachment of messageInfo.attachments || []) {
2782
- let contentId = attachment.contentId && attachment.contentId.replace(/^<|>$/g, '');
2783
- if (contentId && cidReferences.has(contentId)) {
2784
- attachmentList.set(contentId, { attachment, content: null });
2785
-
2786
- let buf = Buffer.from(attachment.id, 'base64url');
2787
- let part = buf.subarray(8).toString();
2788
-
2789
- Object.defineProperty(attachment, 'part', {
2790
- value: part,
2791
- enumerable: false
2792
- });
2793
-
2794
- if (!partList.includes(part)) {
2795
- partList.push(part);
2796
- }
2797
- }
2798
- }
2799
-
2800
- if (partList.length) {
2801
- let lock;
2802
- try {
2803
- // The lock taken for the FETCH above is released by now. Without one
2804
- // another task can select a different mailbox on this connection first,
2805
- // and the UID would then address whatever message carries it there
2806
- if (!options.skipLock) {
2807
- lock = await this.getMailboxLock(connectionClient, { description: `Download inline images: ${message.uid}` });
2808
- }
2809
-
2810
- // Download all referenced images in batch
2811
- let contentParts = await connectionClient.downloadMany(messageInfo.uid, partList, {
2812
- uid: true,
2813
- maxBytes: MAX_ALLOWED_DOWNLOAD_SIZE
2814
- });
2815
-
2816
- if (contentParts) {
2817
- for (let { attachment } of attachmentList.values()) {
2818
- if (attachment.part && contentParts[attachment.part] && contentParts[attachment.part].content) {
2819
- Object.defineProperty(attachment, 'content', {
2820
- value: contentParts[attachment.part].content,
2821
- enumerable: false
2822
- });
2823
- }
2824
- }
2825
-
2826
- // Replace CID references with data URIs
2827
- messageInfo.text.html = embedCidImages(messageInfo.text.html, contentId => {
2828
- let { attachment } = attachmentList.get(contentId) || {};
2829
- return attachment?.content && { contentType: attachment.contentType, content: attachment.content.toString('base64') };
2830
- });
2831
- }
2832
- } catch (err) {
2833
- this.logger.error({ msg: 'Failed to download attachments', uid: messageInfo.uid, partList, err });
2834
- } finally {
2835
- if (lock) {
2836
- lock.release();
2837
- }
2838
- }
2839
- }
2793
+ await this.embedInlineImagesWithLock(connectionClient, message, messageInfo, options);
2840
2794
  }
2841
2795
 
2842
2796
  return messageInfo;