emailengine-app 2.79.0 → 2.79.2

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 (110) hide show
  1. package/.release-please-manifest.json +1 -1
  2. package/CHANGELOG.md +79 -0
  3. package/bin/emailengine.js +8 -1
  4. package/config/default.toml +6 -0
  5. package/data/google-crawlers.json +1 -1
  6. package/lib/account.js +137 -19
  7. package/lib/api-routes/account-routes.js +13 -1
  8. package/lib/api-routes/index.js +12 -0
  9. package/lib/api-routes/mailbox-routes.js +6 -0
  10. package/lib/api-routes/mcp-oauth-routes.js +259 -0
  11. package/lib/api-routes/mcp-routes.js +172 -0
  12. package/lib/api-routes/message-routes.js +125 -4
  13. package/lib/api-routes/outbox-routes.js +7 -0
  14. package/lib/api-routes/permission-map.js +101 -1
  15. package/lib/api-routes/route-helpers.js +87 -4
  16. package/lib/api-routes/route-metadata.js +24 -4
  17. package/lib/api-routes/settings-routes.js +37 -14
  18. package/lib/api-routes/submit-routes.js +41 -0
  19. package/lib/api-routes/template-routes.js +7 -0
  20. package/lib/api-routes/token-routes.js +292 -122
  21. package/lib/arf-detect.js +17 -4
  22. package/lib/bounce-detect.js +28 -17
  23. package/lib/consts.js +36 -1
  24. package/lib/db.js +6 -0
  25. package/lib/email-client/base-client.js +102 -117
  26. package/lib/email-client/gmail-client.js +91 -29
  27. package/lib/email-client/imap/mailbox.js +175 -101
  28. package/lib/email-client/imap-client.js +49 -2
  29. package/lib/email-client/outlook-client.js +20 -24
  30. package/lib/enum-descriptions.js +2 -1
  31. package/lib/field-usage.js +17 -1
  32. package/lib/lua/h-set-new-mark.lua +36 -0
  33. package/lib/lua/s-list-accounts.lua +5 -2
  34. package/lib/mcp/index.js +29 -0
  35. package/lib/mcp/inject.js +70 -0
  36. package/lib/mcp/json-schema.js +120 -0
  37. package/lib/mcp/listen.js +171 -0
  38. package/lib/mcp/oauth.js +324 -0
  39. package/lib/mcp/protocol.js +489 -0
  40. package/lib/mcp/resources.js +139 -0
  41. package/lib/mcp/tools.js +655 -0
  42. package/lib/message-port-stream.js +84 -1
  43. package/lib/oauth2-apps.js +84 -15
  44. package/lib/openapi/build-document.js +5 -1
  45. package/lib/openapi/index.js +3 -1
  46. package/lib/response-stream.js +52 -21
  47. package/lib/routes-ui.js +4 -0
  48. package/lib/schemas.js +26 -5
  49. package/lib/settings.js +23 -9
  50. package/lib/token-audit-log.js +32 -9
  51. package/lib/token-permission-view.js +104 -8
  52. package/lib/tokens.js +194 -68
  53. package/lib/tools.js +96 -0
  54. package/lib/ui-routes/account-routes.js +55 -6
  55. package/lib/ui-routes/admin-config-routes.js +114 -1
  56. package/lib/ui-routes/admin-entities-routes.js +103 -19
  57. package/lib/ui-routes/auth-routes.js +13 -0
  58. package/lib/ui-routes/mcp-consent-routes.js +330 -0
  59. package/lib/ui-routes/oauth-config-routes.js +7 -7
  60. package/lib/ui-routes/route-helpers.js +143 -1
  61. package/lib/ui-routes/suppression-list-routes.js +14 -9
  62. package/lib/utils/decode-headers.js +42 -0
  63. package/lib/utils/header-map.js +48 -0
  64. package/lib/utils/network.js +9 -1
  65. package/lib/utils/unsafe-key.js +59 -0
  66. package/lib/web-safe-html.js +61 -0
  67. package/lib/webhook-routing.js +6 -2
  68. package/lib/webhooks.js +31 -8
  69. package/package.json +9 -8
  70. package/sbom.json +1 -1
  71. package/scripts/README.md +25 -0
  72. package/scripts/build-icon.js +77 -0
  73. package/server.js +39 -17
  74. package/static/css/flyonui.css +1 -1
  75. package/static/css/src/app.tailwind.css +98 -0
  76. package/static/emailengine.ico +0 -0
  77. package/static/js/ui.js +465 -1
  78. package/static/licenses.html +42 -22
  79. package/translations/messages.pot +57 -57
  80. package/views/accounts/account.hbs +8 -8
  81. package/views/accounts/browse.hbs +1 -1
  82. package/views/accounts/edit.hbs +2 -2
  83. package/views/config/mcp.hbs +361 -0
  84. package/views/config/oauth/index.hbs +7 -0
  85. package/views/gateways/edit.hbs +1 -1
  86. package/views/gateways/gateway.hbs +2 -2
  87. package/views/gateways/index.hbs +7 -7
  88. package/views/layout/prompt.hbs +62 -0
  89. package/views/mcp/authorize.hbs +136 -0
  90. package/views/partials/accounts_table.hbs +7 -7
  91. package/views/partials/head_assets.hbs +3 -3
  92. package/views/partials/mcp_access_levels.hbs +13 -0
  93. package/views/partials/mcp_account_limit.hbs +14 -0
  94. package/views/partials/mcp_tool_count.hbs +19 -0
  95. package/views/partials/side_menu.hbs +1 -0
  96. package/views/partials/ui/account-picker.hbs +59 -0
  97. package/views/partials/ui/code-block.hbs +26 -0
  98. package/views/partials/ui/menu-item.hbs +5 -0
  99. package/views/partials/ui/radio.hbs +41 -0
  100. package/views/partials/ui/tab.hbs +15 -10
  101. package/views/partials/ui/tabs.hbs +8 -5
  102. package/views/suppression-lists/list.hbs +1 -1
  103. package/views/templates/index.hbs +2 -2
  104. package/views/templates/template.hbs +5 -4
  105. package/views/tokens/index.hbs +30 -4
  106. package/views/tokens/new.hbs +517 -239
  107. package/winconf.js +148 -48
  108. package/workers/api.js +239 -95
  109. package/workers/imap.js +65 -72
  110. package/workers/webhooks.js +21 -1
@@ -1,5 +1,6 @@
1
1
  'use strict';
2
2
 
3
+ const { finished } = require('stream');
3
4
  const {
4
5
  serialize,
5
6
  unserialize,
@@ -9,13 +10,17 @@ const {
9
10
  filterEmptyObjectValues,
10
11
  validUidValidity,
11
12
  mailboxPathHash,
12
- getMailboxStatusKey
13
+ getMailboxStatusKey,
14
+ collectCidReferences,
15
+ cidReferenceRegex
13
16
  } = require('../../tools');
14
17
  const msgpack = require('../../msgpack');
15
18
  const he = require('he');
16
19
  const libmime = require('libmime');
17
20
  const settings = require('../../settings');
18
21
  const { bounceDetect, applyDeliveryReport } = require('../../bounce-detect');
22
+ const { decodeHeaders } = require('../../utils/decode-headers');
23
+ const { isUnsafeKey } = require('../../utils/unsafe-key');
19
24
  const { arfDetect, camelCaseComplaint } = require('../../arf-detect');
20
25
  const appendList = require('../../append-list');
21
26
  const { messageWebSafeHtml } = require('../../web-safe-html');
@@ -65,6 +70,115 @@ function phantomStatusKey(status) {
65
70
  return `${status.uidValidity || ''}:${status.uidNext || 0}:${status.messages || 0}`;
66
71
  }
67
72
 
73
+ /**
74
+ * Headers the notification path needs for its own processing, whatever the notifyHeaders
75
+ * setting asks for. They travel in the one BODY.PEEK[HEADER.FIELDS (...)] section that path
76
+ * already requests, and are filtered back down before anything is published: processNew()
77
+ * narrows the exposed set to what the caller asked for, and Webhooks.formatPayload() drops
78
+ * the block entirely unless notifyHeaders names something.
79
+ */
80
+ const NOTIFICATION_HEADERS = [
81
+ // Auto-reply detection
82
+ 'x-autoreply',
83
+ 'x-autorespond',
84
+ 'auto-submitted',
85
+ 'precedence',
86
+
87
+ // Threading
88
+ 'in-reply-to',
89
+ 'references',
90
+
91
+ // Bounce and complaint detection
92
+ 'content-type',
93
+
94
+ // Fallback for an ENVELOPE that carries no usable address. Lark Mail omits the address
95
+ // fields outright, and any server can mis-parse a malformed header into a display name
96
+ // with no address - see preferAddressList()
97
+ 'from',
98
+ 'to',
99
+ 'cc',
100
+ 'bcc'
101
+ ];
102
+
103
+ /**
104
+ * Builds the header field list for a notification fetch.
105
+ *
106
+ * @param {String[]|Boolean} configuredHeaders - Headers the notifyHeaders setting asks for
107
+ * @returns {String[]} Header names to request from the server
108
+ */
109
+ function notificationHeaderFields(configuredHeaders) {
110
+ let fetchHeaders = new Set(Array.isArray(configuredHeaders) ? configuredHeaders : []);
111
+
112
+ for (let key of NOTIFICATION_HEADERS) {
113
+ fetchHeaders.add(key);
114
+ }
115
+
116
+ return Array.from(fetchHeaders);
117
+ }
118
+
119
+ /**
120
+ * Parses a raw address header into the address objects the API exposes.
121
+ *
122
+ * @param {String[]} values - Raw header values for one address field
123
+ * @returns {Object[]|undefined} Parsed addresses, or undefined if none could be read
124
+ */
125
+ function parseAddressHeader(values) {
126
+ if (!values?.length) {
127
+ return undefined;
128
+ }
129
+
130
+ try {
131
+ let addressList = addressparser(values)
132
+ .filter(address => !!address.address)
133
+ .map(address => {
134
+ let name = address.name;
135
+ try {
136
+ name = libmime.decodeWords(name);
137
+ } catch (err) {
138
+ // keep the undecoded name
139
+ }
140
+ return { name, address: address.address };
141
+ });
142
+
143
+ return addressList.length ? addressList : undefined;
144
+ } catch (err) {
145
+ // a header we cannot read is worth no more than one that is not there
146
+ return undefined;
147
+ }
148
+ }
149
+
150
+ /**
151
+ * Picks the address list to expose for a header, preferring the server's ENVELOPE.
152
+ *
153
+ * An ENVELOPE list can come back holding no usable address at all: RFC 9051 7.5.2 group
154
+ * markers carry a group name and nothing else, and a server that failed to parse a
155
+ * malformed header reports the wreckage the same way, as a display name with an empty
156
+ * address. The raw header is the better answer in that case, because addressparser sees
157
+ * the original value and can still recover the recipient. Falling back on emptiness alone
158
+ * was not enough - the broken list is not empty, just useless.
159
+ *
160
+ * The header is parsed only when the ENVELOPE turns out to be unusable, which is rare.
161
+ * Parsing all four address fields up front would be work discarded on every message.
162
+ *
163
+ * @param {Object[]} envelopeList - Address list from the IMAP ENVELOPE
164
+ * @param {Object} headers - Decoded message headers, if any were fetched
165
+ * @param {String} key - Header name to fall back to
166
+ * @returns {Object[]|undefined} The list to expose, or undefined if neither source has one
167
+ */
168
+ function preferAddressList(envelopeList, headers, key) {
169
+ if (envelopeList?.some(entry => entry.address)) {
170
+ return envelopeList;
171
+ }
172
+
173
+ let headerList = parseAddressHeader(headers?.[key]);
174
+ if (headerList?.length) {
175
+ return headerList;
176
+ }
177
+
178
+ // Nothing usable anywhere - keep the ENVELOPE entries so a group name still shows up
179
+ return envelopeList?.length ? envelopeList : undefined;
180
+ }
181
+
68
182
  /**
69
183
  * Represents a single IMAP mailbox/folder and handles all operations on it
70
184
  */
@@ -758,17 +872,6 @@ class Mailbox {
758
872
  return lock;
759
873
  }
760
874
 
761
- /**
762
- * Marks task as completed and potentially starts idle timer
763
- * @param {Object} connectionClient - IMAP client that completed the task
764
- */
765
- onTaskCompleted(connectionClient) {
766
- connectionClient = connectionClient || this.connection.imapClient;
767
- if (connectionClient === this.connection.imapClient) {
768
- this.connection.onTaskCompleted();
769
- }
770
- }
771
-
772
875
  /**
773
876
  * Helper to log IMAP events with proper formatting
774
877
  * @param {String} msg - Log message
@@ -1306,6 +1409,7 @@ class Mailbox {
1306
1409
  // Fetch inline attachments referenced in HTML
1307
1410
  if (messageInfo.attachments?.length && messageInfo.text?.html) {
1308
1411
  // fetch inline attachments
1412
+ let cidReferences = collectCidReferences(messageInfo.text.html);
1309
1413
  for (let attachment of messageInfo.attachments || []) {
1310
1414
  if (attachment.encodedSize && attachment.encodedSize > MAX_INLINE_ATTACHMENT_SIZE) {
1311
1415
  // skip large attachments
@@ -1313,7 +1417,7 @@ class Mailbox {
1313
1417
  }
1314
1418
 
1315
1419
  // Check if attachment is referenced by Content-ID in HTML
1316
- if (!attachment.content && attachment.contentId && messageInfo.text.html.indexOf(`cid:${attachment.contentId.replace(/^<|>$/g, '')}`) >= 0) {
1420
+ if (!attachment.content && attachment.contentId && cidReferences.has(attachment.contentId.replace(/^<|>$/g, ''))) {
1317
1421
  try {
1318
1422
  let buf = Buffer.from(attachment.id, 'base64url');
1319
1423
  let part = buf.subarray(8).toString();
@@ -1593,11 +1697,12 @@ class Mailbox {
1593
1697
  if (messageInfo.text.html && messageInfo.attachments) {
1594
1698
  let attachmentList = new Map();
1595
1699
  let partList = [];
1700
+ let cidReferences = collectCidReferences(messageInfo.text.html);
1596
1701
 
1597
1702
  // Collect CID-referenced attachments
1598
1703
  for (let attachment of messageInfo.attachments || []) {
1599
1704
  let contentId = attachment.contentId && attachment.contentId.replace(/^<|>$/g, '');
1600
- if (contentId && messageInfo.text.html.indexOf(contentId) >= 0) {
1705
+ if (contentId && cidReferences.has(contentId)) {
1601
1706
  attachmentList.set(contentId, {
1602
1707
  attachment,
1603
1708
  content: attachment.content || null
@@ -1643,7 +1748,7 @@ class Mailbox {
1643
1748
  }
1644
1749
 
1645
1750
  // Replace CID references with data URIs
1646
- messageInfo.text.html = messageInfo.text.html.replace(/\bcid:([^"'\s>]+)/g, (fullMatch, cidMatch) => {
1751
+ messageInfo.text.html = messageInfo.text.html.replace(cidReferenceRegex(), (fullMatch, cidMatch) => {
1647
1752
  if (attachmentList.has(cidMatch)) {
1648
1753
  let { attachment, content } = attachmentList.get(cidMatch);
1649
1754
  if (content) {
@@ -1785,39 +1890,13 @@ class Mailbox {
1785
1890
  isDraft = true;
1786
1891
  }
1787
1892
 
1893
+ // The address fields fall back to these when the ENVELOPE carries no usable address,
1894
+ // which Lark Mail does by omitting them and any server can do by mis-parsing a
1895
+ // malformed header. See preferAddressList(). Normally only the ENVELOPE is used, and
1896
+ // a message listing fetches no headers at all
1788
1897
  let headers;
1789
-
1790
- // This section is needed for Lark Mail as some address fields might be missing
1791
- // from the ENVELOPE section, so fall back to the header instead.
1792
- // Normally, these headers are not fetched from the server and only ENVELOPE is used
1793
- let parsedAddresses = {};
1794
1898
  if (messageData.headers) {
1795
- headers = libmime.decodeHeaders(messageData.headers.toString().trim());
1796
- for (let key of ['from', 'to', 'cc', 'bcc']) {
1797
- if (headers[key]?.length) {
1798
- try {
1799
- const addressList = addressparser(headers[key])
1800
- .filter(address => !!address.address)
1801
- .map(address => {
1802
- let name = address.name;
1803
- try {
1804
- name = libmime.decodeWords(name);
1805
- } catch (err) {
1806
- // ignore
1807
- }
1808
- return {
1809
- name,
1810
- address: address.address
1811
- };
1812
- });
1813
- if (addressList?.length) {
1814
- parsedAddresses[key] = addressList;
1815
- }
1816
- } catch (err) {
1817
- // just ignore
1818
- }
1819
- }
1820
- }
1899
+ headers = decodeHeaders(messageData.headers.toString().trim());
1821
1900
  }
1822
1901
 
1823
1902
  // Build message info object
@@ -1843,16 +1922,16 @@ class Mailbox {
1843
1922
 
1844
1923
  size: messageData.size || undefined,
1845
1924
  subject: envelope.subject || undefined,
1846
- // Prefer envelope from, fall back to parsed header
1847
- from: envelope.from?.[0] ? envelope.from[0] : parsedAddresses.from?.[0] || undefined,
1925
+ // Prefer the ENVELOPE, fall back to the raw header when it holds no usable address
1926
+ from: preferAddressList(envelope.from, headers, 'from')?.[0] || undefined,
1848
1927
 
1849
1928
  replyTo: envelope.replyTo && envelope.replyTo.length ? envelope.replyTo : undefined,
1850
1929
  sender: extended && envelope.sender && envelope.sender[0] ? envelope.sender[0] : undefined,
1851
1930
 
1852
- to: envelope.to?.length ? envelope.to : parsedAddresses.to || undefined,
1853
- cc: envelope.cc?.length ? envelope.cc : parsedAddresses.cc || undefined,
1931
+ to: preferAddressList(envelope.to, headers, 'to'),
1932
+ cc: preferAddressList(envelope.cc, headers, 'cc'),
1854
1933
 
1855
- bcc: extended && envelope.bcc && envelope.bcc.length ? envelope.bcc : undefined,
1934
+ bcc: extended ? preferAddressList(envelope.bcc, headers, 'bcc') : undefined,
1856
1935
 
1857
1936
  attachments: attachments && attachments.length ? attachments : undefined,
1858
1937
  messageId: (envelope.messageId && envelope.messageId.toString().trim()) || undefined,
@@ -2088,31 +2167,10 @@ class Mailbox {
2088
2167
  messageFetchOptions.headers = notifyHeaders.includes('*') || documentStoreEnabled ? true : notifyHeaders.length ? notifyHeaders : false;
2089
2168
  }
2090
2169
 
2091
- // Also request autoresponse headers
2170
+ // Also request the headers this path needs for its own processing. Skipped when the
2171
+ // setting already asks for every header, since there is nothing left to add
2092
2172
  if (messageFetchOptions.headers !== true) {
2093
- let fetchHeaders = new Set(messageFetchOptions.headers || []);
2094
-
2095
- // Auto-reply detection headers
2096
- fetchHeaders.add('x-autoreply');
2097
- fetchHeaders.add('x-autorespond');
2098
- fetchHeaders.add('auto-submitted');
2099
- fetchHeaders.add('precedence');
2100
-
2101
- // Threading headers
2102
- fetchHeaders.add('in-reply-to');
2103
- fetchHeaders.add('references');
2104
-
2105
- // Content type for bounce/complaint detection
2106
- fetchHeaders.add('content-type');
2107
-
2108
- if (this.isLarkSuite) {
2109
- // Add address headers as a fallback for unreliable ENVELOPE
2110
- fetchHeaders.add('from');
2111
- fetchHeaders.add('to');
2112
- fetchHeaders.add('cc');
2113
- }
2114
-
2115
- messageFetchOptions.fetchHeaders = Array.from(fetchHeaders);
2173
+ messageFetchOptions.fetchHeaders = notificationHeaderFields(messageFetchOptions.headers);
2116
2174
  }
2117
2175
 
2118
2176
  // Peek-then-remove: read entries without removing so that connection errors
@@ -2351,8 +2409,8 @@ class Mailbox {
2351
2409
  }
2352
2410
 
2353
2411
  // User methods
2354
- // Call `clearTimeout(this.connection.completedTimer);` after locking mailbox
2355
- // Call this.onTaskCompleted() after selected mailbox is processed and lock is released
2412
+ // getMailboxLock() clears connection.completedTimer for the primary connection
2413
+ // Call this.connection.onTaskCompleted(connectionClient) after the selected mailbox is processed and the lock is released
2356
2414
 
2357
2415
  /**
2358
2416
  * Fetches text content for a message
@@ -2395,8 +2453,16 @@ class Mailbox {
2395
2453
  let text = await download(content);
2396
2454
  text = text.toString().replace(/\r?\n/g, '\n');
2397
2455
 
2398
- // Group by content type (plain, html, etc)
2456
+ // Group by content type (plain, html, etc). The subtype comes from the message,
2457
+ // so a sender picks it: for "text/__proto__" the `!result[typeKey]` probe below
2458
+ // finds Object.prototype rather than an array, skips the initializer and then
2459
+ // throws on .reduce() - the same shape lib/utils/header-map.js exists to guard.
2460
+ // Neither name is a real MIME subtype, so the part is grouped as plain text
2461
+ // instead of being dropped.
2399
2462
  let typeKey = (meta.contentType && meta.contentType.split('/')[1]) || 'plain';
2463
+ if (isUnsafeKey(typeKey)) {
2464
+ typeKey = 'plain';
2465
+ }
2400
2466
  if (!result[typeKey]) {
2401
2467
  result[typeKey] = [];
2402
2468
  }
@@ -2414,8 +2480,11 @@ class Mailbox {
2414
2480
  result[typeKey].push(text);
2415
2481
  }
2416
2482
  } finally {
2483
+ // Paired with the lock: a FETCH that throws still selected a mailbox on this
2484
+ // connection, so it still has to be sent back to the one it is watching.
2417
2485
  if (lock) {
2418
2486
  lock.release();
2487
+ this.connection.onTaskCompleted(connectionClient);
2419
2488
  }
2420
2489
  }
2421
2490
 
@@ -2426,10 +2495,6 @@ class Mailbox {
2426
2495
 
2427
2496
  result.hasMore = hasMore;
2428
2497
 
2429
- if (!options.skipLock) {
2430
- this.onTaskCompleted(connectionClient);
2431
- }
2432
-
2433
2498
  return result;
2434
2499
  }
2435
2500
 
@@ -2449,7 +2514,6 @@ class Mailbox {
2449
2514
  let lock = await this.getMailboxLock(connectionClient, { description: `Get attachment: ${message.uid}/${part}` });
2450
2515
 
2451
2516
  let streaming = false;
2452
- let released = false;
2453
2517
  try {
2454
2518
  let { meta, content } = await connectionClient.download(message.uid, part, {
2455
2519
  uid: true,
@@ -2457,7 +2521,9 @@ class Mailbox {
2457
2521
  chunkSize: options.chunkSize
2458
2522
  });
2459
2523
 
2460
- if (!meta) {
2524
+ // Both halves are required: meta describes the part, content is what finished() is
2525
+ // handed below, and getText() already guards the same pair
2526
+ if (!meta || !content) {
2461
2527
  return false;
2462
2528
  }
2463
2529
 
@@ -2482,23 +2548,23 @@ class Mailbox {
2482
2548
  content.contentType = meta.contentType;
2483
2549
  content.filename = meta.filename;
2484
2550
  content.disposition = meta.disposition;
2485
- streaming = true;
2486
2551
 
2487
- // Release lock when stream ends
2488
- content.once('end', () => {
2489
- if (!released) {
2490
- released = true;
2491
- lock.release();
2492
- }
2552
+ // The lock is held for the lifetime of the stream, so it can only be given back once the
2553
+ // stream is done - by any route. Enumerating those routes by hand is what let a consumer
2554
+ // that simply destroys the stream hold the lock forever: an abort emits neither 'end' nor
2555
+ // 'error', only 'close'. finished() covers end, error, destroy and premature close by
2556
+ // contract, and fires exactly once, so there is no set of terminal events left to get
2557
+ // wrong. Reporting the task either way is what every other method here does: however the
2558
+ // download ended, the connection has to go back to the mailbox it is watching.
2559
+ finished(content, () => {
2560
+ lock.release();
2561
+ this.connection.onTaskCompleted(connectionClient);
2493
2562
  });
2494
2563
 
2495
- content.once('error', () => {
2496
- if (!released) {
2497
- released = true;
2498
- lock.release();
2499
- this.connection.onTaskCompleted(connectionClient);
2500
- }
2501
- });
2564
+ // Only once finished() has taken over. Set before the call, a synchronous throw from it
2565
+ // - anything not a stream reaching this far - would leave the finally below believing
2566
+ // the stream owns the lock, and nothing would ever release it.
2567
+ streaming = true;
2502
2568
 
2503
2569
  return content;
2504
2570
  } finally {
@@ -2620,11 +2686,12 @@ class Mailbox {
2620
2686
  if (options.embedAttachedImages && messageInfo.text && messageInfo.text.html && messageInfo.attachments) {
2621
2687
  let attachmentList = new Map();
2622
2688
  let partList = [];
2689
+ let cidReferences = collectCidReferences(messageInfo.text.html);
2623
2690
 
2624
2691
  // Find images referenced by CID
2625
2692
  for (let attachment of messageInfo.attachments || []) {
2626
2693
  let contentId = attachment.contentId && attachment.contentId.replace(/^<|>$/g, '');
2627
- if (contentId && messageInfo.text.html.indexOf(contentId) >= 0) {
2694
+ if (contentId && cidReferences.has(contentId)) {
2628
2695
  attachmentList.set(contentId, { attachment, content: null });
2629
2696
 
2630
2697
  let buf = Buffer.from(attachment.id, 'base64url');
@@ -2659,7 +2726,7 @@ class Mailbox {
2659
2726
  }
2660
2727
 
2661
2728
  // Replace CID references with data URIs
2662
- messageInfo.text.html = messageInfo.text.html.replace(/\bcid:([^"'\s>]+)/g, (fullMatch, cidMatch) => {
2729
+ messageInfo.text.html = messageInfo.text.html.replace(cidReferenceRegex(), (fullMatch, cidMatch) => {
2663
2730
  if (attachmentList.has(cidMatch)) {
2664
2731
  let { attachment } = attachmentList.get(cidMatch);
2665
2732
  if (attachment.content) {
@@ -3135,7 +3202,12 @@ class Mailbox {
3135
3202
  labels: true
3136
3203
  };
3137
3204
 
3138
- // LarkSuite specific handling - ensure address headers are fetched
3205
+ // LarkSuite specific handling - ensure address headers are fetched.
3206
+ // This stays provider-gated, unlike the notification path: a listing fetches no
3207
+ // headers at all otherwise, so asking for them here adds a BODY.PEEK section to
3208
+ // every message of every page. Lark needs it because its ENVELOPE omits addresses
3209
+ // outright; for everyone else a mis-parsed header still yields a display name, and
3210
+ // paying for it on every listing is not worth the rare recovery.
3139
3211
  if (this.isLarkSuite) {
3140
3212
  if (!fields.headers && fields.headers !== true) {
3141
3213
  fields.headers = [];
@@ -3403,3 +3475,5 @@ class Mailbox {
3403
3475
  }
3404
3476
 
3405
3477
  module.exports.Mailbox = Mailbox;
3478
+ // Exported for tests: publishSyncedEvents() cannot be driven without a live connection
3479
+ module.exports.notificationHeaderFields = notificationHeaderFields;
@@ -238,11 +238,31 @@ class IMAPClient extends BaseClient {
238
238
  /**
239
239
  * Called when a task is completed - ensures we return to the main mailbox
240
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)
241
248
  */
242
- 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
+
243
263
  // check if we need to re-select main mailbox
264
+ clearTimeout(this.completedTimer);
244
265
  this.completedTimer = setTimeout(() => {
245
- clearTimeout(this.completedTimer);
246
266
  this.ensureMainMailbox().catch(err => {
247
267
  if (CONNECTION_CLOSING_CODES.has(err.code)) {
248
268
  this.logger.debug({ msg: 'Select skipped, connection closing', err });
@@ -2480,6 +2500,12 @@ class IMAPClient extends BaseClient {
2480
2500
  }
2481
2501
  } finally {
2482
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);
2483
2509
  }
2484
2510
  } catch (err) {
2485
2511
  this.logger.debug({ msg: 'Mailbox select error', path, err });
@@ -2601,6 +2627,19 @@ class IMAPClient extends BaseClient {
2601
2627
  let normalizedPath = [].concat(path || []).join('/');
2602
2628
 
2603
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
+
2604
2643
  try {
2605
2644
  let renameResult = await connectionClient.mailboxRename(path, newPath);
2606
2645
  if (renameResult) {
@@ -2638,6 +2677,14 @@ class IMAPClient extends BaseClient {
2638
2677
  } else {
2639
2678
  throw err;
2640
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);
2641
2688
  }
2642
2689
  } else {
2643
2690
  result.path = normalizedPath;