emailengine-app 2.79.1 → 2.79.3

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 (87) hide show
  1. package/.github/workflows/deploy.yml +92 -39
  2. package/.github/workflows/release.yaml +94 -34
  3. package/.release-please-manifest.json +1 -1
  4. package/CHANGELOG.md +85 -0
  5. package/bin/emailengine.js +8 -1
  6. package/config/default.toml +6 -0
  7. package/copy-static-files.sh +23 -2
  8. package/data/google-crawlers.json +1 -1
  9. package/lib/account.js +138 -18
  10. package/lib/api-routes/account-routes.js +13 -1
  11. package/lib/api-routes/index.js +12 -0
  12. package/lib/api-routes/mailbox-routes.js +6 -0
  13. package/lib/api-routes/mcp-oauth-routes.js +259 -0
  14. package/lib/api-routes/mcp-routes.js +172 -0
  15. package/lib/api-routes/message-routes.js +125 -4
  16. package/lib/api-routes/outbox-routes.js +7 -0
  17. package/lib/api-routes/permission-map.js +97 -1
  18. package/lib/api-routes/route-helpers.js +16 -4
  19. package/lib/api-routes/route-metadata.js +24 -4
  20. package/lib/api-routes/submit-routes.js +41 -0
  21. package/lib/api-routes/template-routes.js +7 -0
  22. package/lib/api-routes/token-routes.js +4 -2
  23. package/lib/consts.js +30 -1
  24. package/lib/email-client/base-client.js +235 -163
  25. package/lib/email-client/gmail-client.js +99 -22
  26. package/lib/email-client/imap/mailbox.js +140 -66
  27. package/lib/email-client/imap-client.js +74 -68
  28. package/lib/email-client/outlook-client.js +29 -14
  29. package/lib/enum-descriptions.js +2 -1
  30. package/lib/field-usage.js +17 -1
  31. package/lib/logger.js +43 -3
  32. package/lib/lua/s-list-accounts.lua +5 -2
  33. package/lib/mcp/index.js +29 -0
  34. package/lib/mcp/inject.js +70 -0
  35. package/lib/mcp/json-schema.js +120 -0
  36. package/lib/mcp/listen.js +171 -0
  37. package/lib/mcp/oauth.js +324 -0
  38. package/lib/mcp/protocol.js +489 -0
  39. package/lib/mcp/resources.js +139 -0
  40. package/lib/mcp/tools.js +655 -0
  41. package/lib/openapi/index.js +3 -1
  42. package/lib/response-stream.js +52 -21
  43. package/lib/routes-ui.js +4 -0
  44. package/lib/schemas.js +24 -3
  45. package/lib/token-permission-view.js +104 -8
  46. package/lib/tokens.js +34 -5
  47. package/lib/tools.js +96 -0
  48. package/lib/ui-routes/account-routes.js +43 -1
  49. package/lib/ui-routes/admin-config-routes.js +114 -1
  50. package/lib/ui-routes/admin-entities-routes.js +54 -5
  51. package/lib/ui-routes/auth-routes.js +13 -0
  52. package/lib/ui-routes/mcp-consent-routes.js +330 -0
  53. package/lib/ui-routes/route-helpers.js +116 -1
  54. package/lib/utils/network.js +9 -1
  55. package/lib/web-safe-html.js +61 -0
  56. package/lib/webhooks.js +3 -8
  57. package/package.json +15 -14
  58. package/sbom.json +1 -1
  59. package/scripts/README.md +25 -0
  60. package/scripts/build-icon.js +77 -0
  61. package/server.js +21 -9
  62. package/static/css/flyonui.css +1 -1
  63. package/static/css/src/app.tailwind.css +98 -0
  64. package/static/emailengine.ico +0 -0
  65. package/static/js/ui.js +465 -1
  66. package/static/licenses.html +85 -135
  67. package/translations/messages.pot +103 -103
  68. package/views/config/mcp.hbs +361 -0
  69. package/views/config/oauth/index.hbs +7 -0
  70. package/views/layout/prompt.hbs +62 -0
  71. package/views/mcp/authorize.hbs +136 -0
  72. package/views/partials/head_assets.hbs +3 -3
  73. package/views/partials/mcp_access_levels.hbs +13 -0
  74. package/views/partials/mcp_account_limit.hbs +14 -0
  75. package/views/partials/mcp_tool_count.hbs +19 -0
  76. package/views/partials/side_menu.hbs +1 -0
  77. package/views/partials/ui/account-picker.hbs +59 -0
  78. package/views/partials/ui/code-block.hbs +26 -0
  79. package/views/partials/ui/menu-item.hbs +5 -0
  80. package/views/partials/ui/radio.hbs +41 -0
  81. package/views/partials/ui/tab.hbs +15 -10
  82. package/views/partials/ui/tabs.hbs +8 -5
  83. package/views/templates/template.hbs +4 -3
  84. package/views/tokens/index.hbs +8 -2
  85. package/views/tokens/new.hbs +514 -243
  86. package/winconf.js +148 -48
  87. package/workers/api.js +198 -48
@@ -9,8 +9,8 @@ const addressparser = require('nodemailer/lib/addressparser');
9
9
  const libmime = require('libmime');
10
10
  const he = require('he');
11
11
  const { BaseClient, metricsMeta } = require('./base-client');
12
- const { messageWebSafeHtml } = require('../web-safe-html');
13
- const { emitChangeEvent, toCamelCase } = require('../tools');
12
+ const { messageWebSafeHtml, applyWebSafeHtmlOptions } = require('../web-safe-html');
13
+ const { emitChangeEvent, toCamelCase, collectCidReferences, cidReferenceRegex, truncateTextContents } = require('../tools');
14
14
  const { Gateway } = require('../gateway');
15
15
 
16
16
  const {
@@ -21,7 +21,8 @@ const {
21
21
  REDIS_PREFIX,
22
22
  AUTH_ERROR_NOTIFY,
23
23
  AUTH_SUCCESS_NOTIFY,
24
- DEFAULT_GMAIL_EXPORT_BATCH_SIZE
24
+ DEFAULT_GMAIL_EXPORT_BATCH_SIZE,
25
+ GMAIL_MAX_HISTORY_ENTRY_ATTEMPTS
25
26
  } = require('../consts');
26
27
 
27
28
  const settings = require('../settings');
@@ -312,6 +313,18 @@ class GmailClient extends BaseClient {
312
313
  await this.setStateVal();
313
314
 
314
315
  await this.getAccount();
316
+
317
+ // The auth-failure safety net switches an account off by setting `imap.disabled`, and
318
+ // an API-backed account reaches it the same way an IMAP one does - its failures run
319
+ // through the same setErrorState(). Checked before any credential work, because the
320
+ // work that keeps failing for these accounts is the token refresh below.
321
+ if (await this.isSyncDisabled()) {
322
+ this.logger.info({ msg: 'Skipped connection setup', account: this.account, reason: 'disabled' });
323
+ this.state = 'unset';
324
+ await this.setStateVal();
325
+ return;
326
+ }
327
+
315
328
  await this.getClient(true);
316
329
 
317
330
  // Ensure access token exists to get scopes
@@ -513,6 +526,16 @@ class GmailClient extends BaseClient {
513
526
  clearTimeout(this.fallbackPollingTimer);
514
527
  this.closed = true;
515
528
 
529
+ // A graceful close means the in-flight history entry did not kill this
530
+ // worker, so it must not keep the strike a deploy or a pause would
531
+ // otherwise leave behind. Guarded because the caller does not await
532
+ // close() - a rejection here would surface as an unhandled rejection
533
+ try {
534
+ await this.redis.hdel(this.getAccountKey(), 'googleHistoryProcessing');
535
+ } catch (err) {
536
+ this.logger.debug({ msg: 'Failed to clear history processing marker', account: this.account, err });
537
+ }
538
+
516
539
  // Clean up cached data
517
540
  this.cachedLabels = null;
518
541
  this.cachedLabelsTime = null;
@@ -1286,18 +1309,14 @@ class GmailClient extends BaseClient {
1286
1309
  await this.prepare();
1287
1310
 
1288
1311
  // Enable all enhancements for web-safe HTML
1289
- if (options.webSafeHtml) {
1290
- options.textType = '*';
1291
- options.embedAttachedImages = true;
1292
- options.preProcessHtml = true;
1293
- }
1312
+ applyWebSafeHtmlOptions(options);
1294
1313
 
1295
1314
  const requestQuery = {
1296
1315
  format: 'full'
1297
1316
  };
1298
1317
  const messageData = await this.request(`${GMAIL_API_BASE}/gmail/v1/users/me/messages/${emailId}`, 'get', requestQuery);
1299
1318
 
1300
- let formattedMessage = this.formatMessage(messageData, { extended: true, textType: options.textType });
1319
+ let formattedMessage = this.formatMessage(messageData, { extended: true, textType: options.textType, maxBytes: options.maxBytes });
1301
1320
 
1302
1321
  // Resolve label IDs to human-readable names
1303
1322
  await this.resolveLabels(formattedMessage);
@@ -1324,11 +1343,12 @@ class GmailClient extends BaseClient {
1324
1343
  // Embed inline images as data URIs
1325
1344
  if (options.embedAttachedImages && formattedMessage.text?.html && formattedMessage.attachments) {
1326
1345
  let attachmentMap = new Map();
1346
+ let cidReferences = collectCidReferences(formattedMessage.text.html);
1327
1347
 
1328
1348
  // Find CID references in HTML
1329
1349
  for (let attachment of formattedMessage.attachments) {
1330
1350
  let contentId = attachment.contentId && attachment.contentId.replace(/^<|>$/g, '');
1331
- if (contentId && formattedMessage.text.html.indexOf(contentId) >= 0) {
1351
+ if (contentId && cidReferences.has(contentId)) {
1332
1352
  attachmentMap.set(contentId, { attachment, content: null });
1333
1353
  }
1334
1354
  }
@@ -1341,7 +1361,7 @@ class GmailClient extends BaseClient {
1341
1361
  }
1342
1362
 
1343
1363
  // Replace CID references with data URIs
1344
- formattedMessage.text.html = formattedMessage.text.html.replace(/\bcid:([^"'\s>]+)/g, (fullMatch, cidMatch) => {
1364
+ formattedMessage.text.html = formattedMessage.text.html.replace(cidReferenceRegex(), (fullMatch, cidMatch) => {
1345
1365
  if (attachmentMap.has(cidMatch)) {
1346
1366
  let { content } = attachmentMap.get(cidMatch);
1347
1367
  if (content.content) {
@@ -1388,7 +1408,7 @@ class GmailClient extends BaseClient {
1388
1408
  try {
1389
1409
  const requestQuery = { format: 'full' };
1390
1410
  const messageData = await this.request(`${GMAIL_API_BASE}/gmail/v1/users/me/messages/${emailId}`, 'get', requestQuery);
1391
- const formattedMessage = this.formatMessage(messageData, { extended: true, textType: options.textType });
1411
+ const formattedMessage = this.formatMessage(messageData, { extended: true, textType: options.textType, maxBytes: options.maxBytes });
1392
1412
 
1393
1413
  await this.resolveLabels(formattedMessage, labelMap);
1394
1414
 
@@ -1473,7 +1493,7 @@ class GmailClient extends BaseClient {
1473
1493
  response[key] = textContent[key].map(buf => buf.toString()).join('\n');
1474
1494
  }
1475
1495
 
1476
- response.hasMore = false;
1496
+ response.hasMore = truncateTextContents(response, options.maxBytes);
1477
1497
 
1478
1498
  return response;
1479
1499
  }
@@ -2491,7 +2511,7 @@ class GmailClient extends BaseClient {
2491
2511
  * @returns {Object} Formatted message
2492
2512
  */
2493
2513
  formatMessage(messageData, options) {
2494
- let { extended, path, textType, minimalFields } = options || {};
2514
+ let { extended, path, textType, minimalFields, maxBytes } = options || {};
2495
2515
 
2496
2516
  let date = messageData.internalDate && !isNaN(messageData.internalDate) ? new Date(Number(messageData.internalDate)) : undefined;
2497
2517
  if (date?.toString() === 'Invalid Date') {
@@ -2539,6 +2559,12 @@ class GmailClient extends BaseClient {
2539
2559
 
2540
2560
  const { attachments, textId, encodedTextSize, textContents } = this.getAttachmentList(messageData, { textType });
2541
2561
 
2562
+ const textValues = {
2563
+ plain: textContents?.[0]?.toString(),
2564
+ html: textContents?.[1]?.toString()
2565
+ };
2566
+ const textHasMore = truncateTextContents(textValues, maxBytes);
2567
+
2542
2568
  // Decode snippet preview
2543
2569
  let preview;
2544
2570
  try {
@@ -2588,9 +2614,9 @@ class GmailClient extends BaseClient {
2588
2614
  ? {
2589
2615
  id: textId,
2590
2616
  encodedSize: encodedTextSize,
2591
- plain: textContents?.[0]?.toString(),
2592
- html: textContents?.[1]?.toString(),
2593
- hasMore: textContents?.[0] || textContents?.[1] ? false : undefined
2617
+ plain: textValues.plain,
2618
+ html: textValues.html,
2619
+ hasMore: textContents?.[0] || textContents?.[1] ? textHasMore : undefined
2594
2620
  }
2595
2621
  : undefined,
2596
2622
 
@@ -3030,6 +3056,26 @@ class GmailClient extends BaseClient {
3030
3056
  let newestHistoryId = currentHistoryId;
3031
3057
  let lastHistoryId = currentHistoryId;
3032
3058
 
3059
+ // The history cursor only advances after an entry is processed, so an
3060
+ // entry that kills the worker (OOM, heartbeat restart) is refetched by
3061
+ // the restarted worker and would loop forever. The in-flight marker
3062
+ // records which entry processing last started on and how many times;
3063
+ // once the limit is hit the entry is skipped with a syncWarning
3064
+ let processingMarker = null;
3065
+ try {
3066
+ processingMarker = JSON.parse(await this.redis.hget(this.getAccountKey(), 'googleHistoryProcessing'));
3067
+ } catch (err) {
3068
+ // no marker or an unreadable one, nothing to resume
3069
+ }
3070
+
3071
+ // advance the durable cursor once an entry is handled (processed or skipped)
3072
+ let advanceHistoryCursor = async historyEntryId => {
3073
+ if (historyEntryId && historyEntryId > lastHistoryId) {
3074
+ await this.redis.hset(this.getAccountKey(), 'googleHistoryId', historyEntryId.toString());
3075
+ lastHistoryId = historyEntryId;
3076
+ }
3077
+ };
3078
+
3033
3079
  /**
3034
3080
  * Fetches and processes a page of history
3035
3081
  * @param {string} pageToken - Pagination token
@@ -3074,13 +3120,41 @@ class GmailClient extends BaseClient {
3074
3120
 
3075
3121
  // Process each history entry
3076
3122
  for (let entry of historyRes?.history || []) {
3123
+ let historyEntryId = Number(entry?.id) || null;
3124
+
3125
+ let attempts = processingMarker && entry?.id && String(processingMarker.id) === String(entry.id) ? Number(processingMarker.count) || 0 : 0;
3126
+ if (attempts >= GMAIL_MAX_HISTORY_ENTRY_ATTEMPTS) {
3127
+ // Every attempt to process this entry has taken the worker
3128
+ // down with it. Skip it and advance the cursor so the
3129
+ // account can make progress; the warning names the messages
3130
+ // whose events were lost so they can be recovered manually
3131
+ let messageIds = (entry?.messagesAdded || []).map(added => added?.message?.id).filter(id => id);
3132
+ this.logger.error({
3133
+ msg: 'Skipping history entry that repeatedly killed the worker',
3134
+ account: this.account,
3135
+ entryId: entry?.id,
3136
+ attempts,
3137
+ messageIds
3138
+ });
3139
+ await emitChangeEvent(this.logger, this.account, 'syncWarning', {
3140
+ type: 'historyEntrySkipped',
3141
+ message: 'Processing a history entry repeatedly killed the sync worker, its changes were skipped',
3142
+ historyId: entry?.id,
3143
+ messageIds
3144
+ });
3145
+ await advanceHistoryCursor(historyEntryId);
3146
+ continue;
3147
+ }
3148
+
3149
+ if (entry?.id) {
3150
+ // mark the entry as in flight before touching it, so a
3151
+ // worker death mid-entry is attributable on restart
3152
+ await this.redis.hset(this.getAccountKey(), 'googleHistoryProcessing', JSON.stringify({ id: entry.id, count: attempts + 1 }));
3153
+ }
3154
+
3077
3155
  try {
3078
3156
  await this.processHistoryEntry(entry);
3079
- let historyEntryId = Number(entry?.id) || null;
3080
- if (historyEntryId && historyEntryId > lastHistoryId) {
3081
- await this.redis.hset(this.getAccountKey(), 'googleHistoryId', historyEntryId.toString());
3082
- lastHistoryId = historyEntryId;
3083
- }
3157
+ await advanceHistoryCursor(historyEntryId);
3084
3158
  } catch (err) {
3085
3159
  this.logger.error({
3086
3160
  msg: 'Failed to process history entry',
@@ -3111,6 +3185,9 @@ class GmailClient extends BaseClient {
3111
3185
  if (newestHistoryId && newestHistoryId > currentHistoryId) {
3112
3186
  await this.redis.hset(this.getAccountKey(), 'googleHistoryId', newestHistoryId.toString());
3113
3187
  }
3188
+
3189
+ // the run finished without dying, drop the in-flight marker
3190
+ await this.redis.hdel(this.getAccountKey(), 'googleHistoryProcessing');
3114
3191
  }
3115
3192
 
3116
3193
  /**
@@ -10,7 +10,9 @@ const {
10
10
  filterEmptyObjectValues,
11
11
  validUidValidity,
12
12
  mailboxPathHash,
13
- getMailboxStatusKey
13
+ getMailboxStatusKey,
14
+ collectCidReferences,
15
+ cidReferenceRegex
14
16
  } = require('../../tools');
15
17
  const msgpack = require('../../msgpack');
16
18
  const he = require('he');
@@ -68,6 +70,115 @@ function phantomStatusKey(status) {
68
70
  return `${status.uidValidity || ''}:${status.uidNext || 0}:${status.messages || 0}`;
69
71
  }
70
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
+
71
182
  /**
72
183
  * Represents a single IMAP mailbox/folder and handles all operations on it
73
184
  */
@@ -1298,6 +1409,7 @@ class Mailbox {
1298
1409
  // Fetch inline attachments referenced in HTML
1299
1410
  if (messageInfo.attachments?.length && messageInfo.text?.html) {
1300
1411
  // fetch inline attachments
1412
+ let cidReferences = collectCidReferences(messageInfo.text.html);
1301
1413
  for (let attachment of messageInfo.attachments || []) {
1302
1414
  if (attachment.encodedSize && attachment.encodedSize > MAX_INLINE_ATTACHMENT_SIZE) {
1303
1415
  // skip large attachments
@@ -1305,7 +1417,7 @@ class Mailbox {
1305
1417
  }
1306
1418
 
1307
1419
  // Check if attachment is referenced by Content-ID in HTML
1308
- 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, ''))) {
1309
1421
  try {
1310
1422
  let buf = Buffer.from(attachment.id, 'base64url');
1311
1423
  let part = buf.subarray(8).toString();
@@ -1585,11 +1697,12 @@ class Mailbox {
1585
1697
  if (messageInfo.text.html && messageInfo.attachments) {
1586
1698
  let attachmentList = new Map();
1587
1699
  let partList = [];
1700
+ let cidReferences = collectCidReferences(messageInfo.text.html);
1588
1701
 
1589
1702
  // Collect CID-referenced attachments
1590
1703
  for (let attachment of messageInfo.attachments || []) {
1591
1704
  let contentId = attachment.contentId && attachment.contentId.replace(/^<|>$/g, '');
1592
- if (contentId && messageInfo.text.html.indexOf(contentId) >= 0) {
1705
+ if (contentId && cidReferences.has(contentId)) {
1593
1706
  attachmentList.set(contentId, {
1594
1707
  attachment,
1595
1708
  content: attachment.content || null
@@ -1635,7 +1748,7 @@ class Mailbox {
1635
1748
  }
1636
1749
 
1637
1750
  // Replace CID references with data URIs
1638
- messageInfo.text.html = messageInfo.text.html.replace(/\bcid:([^"'\s>]+)/g, (fullMatch, cidMatch) => {
1751
+ messageInfo.text.html = messageInfo.text.html.replace(cidReferenceRegex(), (fullMatch, cidMatch) => {
1639
1752
  if (attachmentList.has(cidMatch)) {
1640
1753
  let { attachment, content } = attachmentList.get(cidMatch);
1641
1754
  if (content) {
@@ -1777,39 +1890,13 @@ class Mailbox {
1777
1890
  isDraft = true;
1778
1891
  }
1779
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
1780
1897
  let headers;
1781
-
1782
- // This section is needed for Lark Mail as some address fields might be missing
1783
- // from the ENVELOPE section, so fall back to the header instead.
1784
- // Normally, these headers are not fetched from the server and only ENVELOPE is used
1785
- let parsedAddresses = {};
1786
1898
  if (messageData.headers) {
1787
1899
  headers = decodeHeaders(messageData.headers.toString().trim());
1788
- for (let key of ['from', 'to', 'cc', 'bcc']) {
1789
- if (headers[key]?.length) {
1790
- try {
1791
- const addressList = addressparser(headers[key])
1792
- .filter(address => !!address.address)
1793
- .map(address => {
1794
- let name = address.name;
1795
- try {
1796
- name = libmime.decodeWords(name);
1797
- } catch (err) {
1798
- // ignore
1799
- }
1800
- return {
1801
- name,
1802
- address: address.address
1803
- };
1804
- });
1805
- if (addressList?.length) {
1806
- parsedAddresses[key] = addressList;
1807
- }
1808
- } catch (err) {
1809
- // just ignore
1810
- }
1811
- }
1812
- }
1813
1900
  }
1814
1901
 
1815
1902
  // Build message info object
@@ -1835,16 +1922,16 @@ class Mailbox {
1835
1922
 
1836
1923
  size: messageData.size || undefined,
1837
1924
  subject: envelope.subject || undefined,
1838
- // Prefer envelope from, fall back to parsed header
1839
- 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,
1840
1927
 
1841
1928
  replyTo: envelope.replyTo && envelope.replyTo.length ? envelope.replyTo : undefined,
1842
1929
  sender: extended && envelope.sender && envelope.sender[0] ? envelope.sender[0] : undefined,
1843
1930
 
1844
- to: envelope.to?.length ? envelope.to : parsedAddresses.to || undefined,
1845
- cc: envelope.cc?.length ? envelope.cc : parsedAddresses.cc || undefined,
1931
+ to: preferAddressList(envelope.to, headers, 'to'),
1932
+ cc: preferAddressList(envelope.cc, headers, 'cc'),
1846
1933
 
1847
- bcc: extended && envelope.bcc && envelope.bcc.length ? envelope.bcc : undefined,
1934
+ bcc: extended ? preferAddressList(envelope.bcc, headers, 'bcc') : undefined,
1848
1935
 
1849
1936
  attachments: attachments && attachments.length ? attachments : undefined,
1850
1937
  messageId: (envelope.messageId && envelope.messageId.toString().trim()) || undefined,
@@ -2080,31 +2167,10 @@ class Mailbox {
2080
2167
  messageFetchOptions.headers = notifyHeaders.includes('*') || documentStoreEnabled ? true : notifyHeaders.length ? notifyHeaders : false;
2081
2168
  }
2082
2169
 
2083
- // 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
2084
2172
  if (messageFetchOptions.headers !== true) {
2085
- let fetchHeaders = new Set(messageFetchOptions.headers || []);
2086
-
2087
- // Auto-reply detection headers
2088
- fetchHeaders.add('x-autoreply');
2089
- fetchHeaders.add('x-autorespond');
2090
- fetchHeaders.add('auto-submitted');
2091
- fetchHeaders.add('precedence');
2092
-
2093
- // Threading headers
2094
- fetchHeaders.add('in-reply-to');
2095
- fetchHeaders.add('references');
2096
-
2097
- // Content type for bounce/complaint detection
2098
- fetchHeaders.add('content-type');
2099
-
2100
- if (this.isLarkSuite) {
2101
- // Add address headers as a fallback for unreliable ENVELOPE
2102
- fetchHeaders.add('from');
2103
- fetchHeaders.add('to');
2104
- fetchHeaders.add('cc');
2105
- }
2106
-
2107
- messageFetchOptions.fetchHeaders = Array.from(fetchHeaders);
2173
+ messageFetchOptions.fetchHeaders = notificationHeaderFields(messageFetchOptions.headers);
2108
2174
  }
2109
2175
 
2110
2176
  // Peek-then-remove: read entries without removing so that connection errors
@@ -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;