emailengine-app 2.81.1 → 2.81.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.
@@ -1,6 +1,7 @@
1
1
  'use strict';
2
2
 
3
3
  const { finished } = require('stream');
4
+ const { ImapFlowErrorCode } = require('imapflow');
4
5
  const {
5
6
  serialize,
6
7
  unserialize,
@@ -23,7 +24,7 @@ const settings = require('../../settings');
23
24
  const { bounceDetect, applyDeliveryReport } = require('../../bounce-detect');
24
25
  const { decodeHeaders } = require('../../utils/decode-headers');
25
26
  const { isUnsafeKey } = require('../../utils/unsafe-key');
26
- const { arfDetect, camelCaseComplaint } = require('../../arf-detect');
27
+ const { arfDetect, camelCaseComplaint, COMPLAINT_ATTACHMENT_TYPES } = require('../../arf-detect');
27
28
  const { messageWebSafeHtml } = require('../../web-safe-html');
28
29
  const simpleParser = require('mailparser').simpleParser;
29
30
  const ical = require('ical.js');
@@ -75,9 +76,9 @@ const {
75
76
  * it in the folder for good.
76
77
  *
77
78
  * Work earlier in the pass does run twice when a later step re-queues the message: the seen-messages
78
- * HyperLogLog (so the retry reports `seemsLikeNew: false`, an informational field), a stored bounce
79
- * record (a duplicate row in the message's `bounces` array), and, the expensive one, the LLM summary
80
- * and embeddings, which sit just before the inline-image download. All of it needs the connection to
79
+ * HyperLogLog (so the retry reports `seemsLikeNew: false`, an informational field) and, the
80
+ * expensive one, the LLM summary and embeddings, which sit just before the inline-image download.
81
+ * All of it needs the connection to
81
82
  * die in one narrow window, and a re-queue was already reachable from every error thrown outside
82
83
  * these catches
83
84
  * @param {Error} err - The error to check
@@ -87,6 +88,24 @@ function isConnectionGone(err) {
87
88
  return !!err && CONNECTION_CLOSING_CODES.has(err.code);
88
89
  }
89
90
 
91
+ /**
92
+ * Whether a message that failed to process should stay queued for the next pass rather than be
93
+ * dropped: the connection went away, the network failed, or the server throttled every FETCH retry.
94
+ * ImapFlow throws ETHROTTLE since 2.0.8 (it used to resolve undefined, which read as "not found"
95
+ * and ended in messageMissing). A server can throttle one message every time (Microsoft 365
96
+ * throttles by bandwidth), so publishSyncedEvents() keeps a throttled one for a bounded number of
97
+ * passes only, see MAX_THROTTLED_ARRIVAL_PASSES
98
+ * @param {Error} err - The error to check
99
+ * @returns {Boolean}
100
+ */
101
+ function keepsArrivalQueued(err) {
102
+ return isConnectionGone(err) || TRANSIENT_NETWORK_CODES.has(err?.code) || err?.code === ImapFlowErrorCode.ETHROTTLE;
103
+ }
104
+
105
+ // Passes a queued arrival may be throttled on before it is dropped, so a message the server
106
+ // throttles every time cannot hold up every later arrival in its folder
107
+ const MAX_THROTTLED_ARRIVAL_PASSES = 5;
108
+
90
109
  /**
91
110
  * Compact fingerprint of the STATUS counters stored in the phantom folder
92
111
  * marker - a parked phantom folder is re-probed as soon as this changes
@@ -101,8 +120,8 @@ function phantomStatusKey(status) {
101
120
  * Headers the notification path needs for its own processing, whatever the notifyHeaders
102
121
  * setting asks for. They travel in the one BODY.PEEK[HEADER.FIELDS (...)] section that path
103
122
  * already requests, and are filtered back down before anything is published: processNew()
104
- * narrows the exposed set to what the caller asked for, and Webhooks.formatPayload() drops
105
- * the block entirely unless notifyHeaders names something.
123
+ * narrows the exposed set to what the caller asked for once its own checks have run, and
124
+ * Webhooks.formatPayload() drops the block entirely unless notifyHeaders names something.
106
125
  */
107
126
  const NOTIFICATION_HEADERS = [
108
127
  // Auto-reply detection
@@ -1103,37 +1122,12 @@ class Mailbox {
1103
1122
  }
1104
1123
 
1105
1124
  /**
1106
- * Processes a deleted message - clears bounces and sends notification
1125
+ * Processes a deleted message and sends the notification
1107
1126
  * @param {Object} messageData - Deleted message data
1108
1127
  */
1109
1128
  async processDeleted(messageData) {
1110
1129
  this.logger.debug({ msg: 'Message deleted', uid: messageData.uid });
1111
1130
 
1112
- //FIXME: does not work as there is no messageId property
1113
- /*
1114
- if (messageData.messageId) {
1115
- try {
1116
- let deleted = await appendList.clear(this.connection.redis, this.connection.getBounceKey(), messageData.messageId);
1117
- if (deleted) {
1118
- this.logger.error({
1119
- msg: 'Cleared bounce log for message',
1120
- id: messageData.id,
1121
- uid: messageData.uid,
1122
- messageId: messageData.messageId
1123
- });
1124
- }
1125
- } catch (err) {
1126
- this.logger.error({
1127
- msg: 'Failed to clear bounce log',
1128
- id: messageData.id,
1129
- uid: messageData.uid,
1130
- messageId: messageData.messageId,
1131
- err
1132
- });
1133
- }
1134
- }
1135
- */
1136
-
1137
1131
  // Generate packed UID for external reference
1138
1132
  let packedUid = await this.packUidWithLogging(messageData.uid, 'delete');
1139
1133
  if (!packedUid) {
@@ -1262,19 +1256,6 @@ class Mailbox {
1262
1256
  this.logger.debug({ msg: 'Missing message', status: 'found', uid: messageData.uid, missingRetries, missingDelay });
1263
1257
  }
1264
1258
 
1265
- // Filter headers based on what was requested
1266
- if (options.headers && Array.isArray(requestedHeaders)) {
1267
- let filteredHeaders = {};
1268
- for (let key of Object.keys(messageInfo.headers)) {
1269
- if (requestedHeaders.includes(key)) {
1270
- filteredHeaders[key] = messageInfo.headers[key];
1271
- }
1272
- }
1273
- messageInfo.headers = filteredHeaders;
1274
- } else if (options.headers && requestedHeaders === false) {
1275
- delete messageInfo.headers;
1276
- }
1277
-
1278
1259
  // Check if message is too old to notify about
1279
1260
  let date = new Date(messageInfo.date);
1280
1261
  if (this.connection.notifyFrom && date < this.connection.notifyFrom && !canSync) {
@@ -1300,11 +1281,11 @@ class Mailbox {
1300
1281
  let content;
1301
1282
 
1302
1283
  // Check if this might be an ARF (Abuse Reporting Format) complaint
1303
- if (this.mightBeAComplaint(messageInfo)) {
1284
+ if (this.connection.mightBeAComplaint(messageInfo)) {
1304
1285
  try {
1305
1286
  // Download relevant attachments for ARF parsing
1306
1287
  for (let attachment of messageInfo.attachments || []) {
1307
- if (!['message/feedback-report', 'message/rfc822-headers', 'message/rfc822'].includes(attachment.contentType)) {
1288
+ if (!COMPLAINT_ATTACHMENT_TYPES.includes(attachment.contentType)) {
1308
1289
  continue;
1309
1290
  }
1310
1291
 
@@ -1356,7 +1337,7 @@ class Mailbox {
1356
1337
  }
1357
1338
 
1358
1339
  // Check if this might be a DSN (Delivery Status Notification)
1359
- if (this.mightBeDSNResponse(messageInfo)) {
1340
+ if (this.connection.mightBeDSNResponse(messageInfo)) {
1360
1341
  try {
1361
1342
  let { content: sourceStream } = await this.requireImapClient().download(messageInfo.uid, false, {
1362
1343
  uid: true,
@@ -1384,7 +1365,7 @@ class Mailbox {
1384
1365
  }
1385
1366
 
1386
1367
  // Check if this could be a bounce message
1387
- if (this.mightBeABounce(messageInfo)) {
1368
+ if (this.connection.mightBeABounce(messageInfo)) {
1388
1369
  // Parse for bounce information
1389
1370
  try {
1390
1371
  if (!content) {
@@ -1432,11 +1413,7 @@ class Mailbox {
1432
1413
  }
1433
1414
  }
1434
1415
 
1435
- let stored = 0;
1436
1416
  if (bounce.action && bounce.recipient && bounce.messageId) {
1437
- // Store bounce info associated with original message ID
1438
- stored = await this.connection.storeBounce(messageInfo.id, bounce);
1439
-
1440
1417
  bounceNotifyInfo = Object.assign({ bounceMessage: messageInfo.id }, bounce);
1441
1418
 
1442
1419
  messageInfo.isBounce = true;
@@ -1448,8 +1425,7 @@ class Mailbox {
1448
1425
  id: messageInfo.id,
1449
1426
  uid: messageInfo.uid,
1450
1427
  messageId: messageInfo.messageId,
1451
- bounce,
1452
- stored
1428
+ bounce
1453
1429
  });
1454
1430
  }
1455
1431
  } catch (err) {
@@ -1466,6 +1442,21 @@ class Mailbox {
1466
1442
  }
1467
1443
  }
1468
1444
 
1445
+ // Narrow the headers to what the caller asked for. This runs after the complaint, delivery
1446
+ // report and bounce checks above: they read headers fetched for them (see
1447
+ // notificationHeaderFields()) that the published payload may not carry
1448
+ if (options.headers && Array.isArray(requestedHeaders)) {
1449
+ let filteredHeaders = {};
1450
+ for (let key of Object.keys(messageInfo.headers)) {
1451
+ if (requestedHeaders.includes(key)) {
1452
+ filteredHeaders[key] = messageInfo.headers[key];
1453
+ }
1454
+ }
1455
+ messageInfo.headers = filteredHeaders;
1456
+ } else if (options.headers && requestedHeaders === false) {
1457
+ delete messageInfo.headers;
1458
+ }
1459
+
1469
1460
  // Resolve Gmail category for inbox messages
1470
1461
  if (
1471
1462
  this.connection.imapClient?.capabilities?.has('X-GM-EXT-1') &&
@@ -1672,14 +1663,6 @@ class Mailbox {
1672
1663
  !(messageInfo.labels && messageInfo.labels.includes('\\Sent')) &&
1673
1664
  !!(await this.connection.redis.pfadd(this.getSeenMessagesKey(), messageInfo.emailId || messageInfo.messageId));
1674
1665
 
1675
- // Determine special use folder for the message
1676
- for (let specialUseTag of ['\\Junk', '\\Sent', '\\Trash', '\\Inbox', '\\Drafts']) {
1677
- if (this.listingEntry.specialUse === specialUseTag || (messageInfo.labels && messageInfo.labels.includes(specialUseTag))) {
1678
- messageInfo.messageSpecialUse = specialUseTag;
1679
- break;
1680
- }
1681
- }
1682
-
1683
1666
  // Process with LLM if configured for inbox messages
1684
1667
  if (messageInfo.messageSpecialUse === '\\Inbox' && (!this.connection.notifyFrom || messageData.internalDate >= this.connection.notifyFrom)) {
1685
1668
  let messageData = Object.assign({ account: this.connection.account }, messageInfo);
@@ -1916,6 +1899,33 @@ class Mailbox {
1916
1899
  }
1917
1900
  }
1918
1901
 
1902
+ /**
1903
+ * Counts the passes a queued arrival was throttled on. Kept in memory: a restart starting the
1904
+ * count over only costs a few more passes
1905
+ * @param {string} rawMember - The queued entry
1906
+ * @returns {number} Passes so far, this one included
1907
+ */
1908
+ countThrottledArrival(rawMember) {
1909
+ this.throttledArrivals = this.throttledArrivals || new Map();
1910
+ const passes = (this.throttledArrivals.get(rawMember) || 0) + 1;
1911
+ this.throttledArrivals.set(rawMember, passes);
1912
+ return passes;
1913
+ }
1914
+
1915
+ /**
1916
+ * Sets the special use of the folder a message belongs to: the mailbox's own, or for Gmail
1917
+ * over IMAP the label, since the message lives in All Mail there. Junk wins over Inbox
1918
+ * @param {Object} messageInfo - Formatted message, updated in place
1919
+ */
1920
+ setMessageSpecialUse(messageInfo) {
1921
+ for (let specialUseTag of ['\\Junk', '\\Sent', '\\Trash', '\\Inbox', '\\Drafts']) {
1922
+ if (this.listingEntry.specialUse === specialUseTag || (messageInfo.labels && messageInfo.labels.includes(specialUseTag))) {
1923
+ messageInfo.messageSpecialUse = specialUseTag;
1924
+ break;
1925
+ }
1926
+ }
1927
+ }
1928
+
1919
1929
  /**
1920
1930
  * Builds message info object from raw IMAP data
1921
1931
  * @param {Object} messageData - Raw message data from IMAP
@@ -2046,9 +2056,6 @@ class Mailbox {
2046
2056
  result.isAutoReply = true;
2047
2057
  }
2048
2058
 
2049
- // Fetch associated bounce information
2050
- await this.connection.attachBounces(result);
2051
-
2052
2059
  return result;
2053
2060
  }
2054
2061
 
@@ -2260,13 +2267,18 @@ class Mailbox {
2260
2267
  try {
2261
2268
  await this.processNew(messageData, messageFetchOptions, canSync, storedStatus);
2262
2269
  await this.connection.redis.zrem(notificationsKey, rawMember);
2270
+ this.throttledArrivals?.delete(rawMember);
2263
2271
  } catch (err) {
2264
2272
  // Wider than the enrichment steps on purpose: this is the last chance to keep a
2265
2273
  // message that failed on a transient network error, and it is not a step that can
2266
2274
  // re-run the same failure indefinitely - the pass ends here either way
2267
- if (isConnectionGone(err) || TRANSIENT_NETWORK_CODES.has(err.code)) {
2268
- throw err;
2275
+ if (keepsArrivalQueued(err)) {
2276
+ const throttledPasses = err.code === ImapFlowErrorCode.ETHROTTLE ? this.countThrottledArrival(rawMember) : 0;
2277
+ if (throttledPasses <= MAX_THROTTLED_ARRIVAL_PASSES) {
2278
+ throw err;
2279
+ }
2269
2280
  }
2281
+ this.throttledArrivals?.delete(rawMember);
2270
2282
  await this.connection.redis.zrem(notificationsKey, rawMember);
2271
2283
  this.logger.error({ msg: 'Failed to process new message', uid, id: messageData.id, err });
2272
2284
  }
@@ -2635,7 +2647,8 @@ class Mailbox {
2635
2647
  }
2636
2648
 
2637
2649
  /**
2638
- * Fetches complete message details
2650
+ * Fetches complete message details. Every message it returns carries `messageSpecialUse`,
2651
+ * which the arrival checks in processNew() and the fetch-time bounce check gate on
2639
2652
  * @param {Object} message - Message object with uid
2640
2653
  * @param {Object} options - Fetch options
2641
2654
  * @param {Object} connectionOptions - Connection options
@@ -2694,6 +2707,28 @@ class Mailbox {
2694
2707
  }
2695
2708
 
2696
2709
  messageInfo = await this.getMessageInfo(messageData, true);
2710
+
2711
+ if (messageInfo) {
2712
+ // Add mailbox special use information
2713
+ if (this.listingEntry.specialUse) {
2714
+ messageInfo.specialUse = this.listingEntry.specialUse;
2715
+ }
2716
+ this.setMessageSpecialUse(messageInfo);
2717
+
2718
+ // The details route asks for the content check; its download rides on this lock
2719
+ // instead of taking one of its own, which on the primary connection is a SELECT
2720
+ // away from the watched folder and back
2721
+ if (options.detectBounce) {
2722
+ await this.connection.detectBounce(messageInfo, async () => {
2723
+ let { content } = await connectionClient.download(message.uid, false, {
2724
+ uid: true,
2725
+ maxBytes: MAX_ALLOWED_DOWNLOAD_SIZE,
2726
+ chunkSize: options.chunkSize
2727
+ });
2728
+ return content;
2729
+ });
2730
+ }
2731
+ }
2697
2732
  } finally {
2698
2733
  if (lock) {
2699
2734
  lock.release();
@@ -2812,19 +2847,6 @@ class Mailbox {
2812
2847
  }
2813
2848
  }
2814
2849
 
2815
- // Add mailbox special use information
2816
- if (this.listingEntry.specialUse) {
2817
- messageInfo.specialUse = this.listingEntry.specialUse;
2818
- }
2819
-
2820
- // Determine message's special use folder
2821
- for (let specialUseTag of ['\\Junk', '\\Sent', '\\Trash', '\\Inbox', '\\Drafts']) {
2822
- if (this.listingEntry.specialUse === specialUseTag || (messageInfo.labels && messageInfo.labels.includes(specialUseTag))) {
2823
- messageInfo.messageSpecialUse = specialUseTag;
2824
- break;
2825
- }
2826
- }
2827
-
2828
2850
  return messageInfo;
2829
2851
  }
2830
2852
 
@@ -3328,154 +3350,6 @@ class Mailbox {
3328
3350
  }
3329
3351
  }
3330
3352
 
3331
- /**
3332
- * Heuristic check if message might be a bounce
3333
- * @param {Object} messageInfo - Message information
3334
- * @returns {Boolean} True if likely a bounce
3335
- */
3336
- mightBeABounce(messageInfo) {
3337
- // Only check messages in Inbox or Junk
3338
- if (
3339
- !['\\Inbox', '\\Junk'].includes(this.listingEntry.specialUse) &&
3340
- !(messageInfo.labels?.includes('\\Inbox') || messageInfo.labels?.includes('\\Junk'))
3341
- ) {
3342
- return false;
3343
- }
3344
-
3345
- // Skip if already identified as delivery report
3346
- if (messageInfo.deliveryReport) {
3347
- // already processed
3348
- return false;
3349
- }
3350
-
3351
- let name = (messageInfo.from && messageInfo.from.name) || '';
3352
- let address = (messageInfo.from && messageInfo.from.address) || '';
3353
-
3354
- // Check common bounce sender names
3355
- if (/Mail Delivery System|Mail Delivery Subsystem|Internet Mail Delivery|Mailer[- ]?Daemon|NDR Administrator/i.test(name)) {
3356
- return true;
3357
- }
3358
-
3359
- // Check common bounce sender addresses (including mailer-daemon without @)
3360
- // Note: Some MTAs use "mailerdaemon" without hyphen (e.g., ZoneMTA)
3361
- if (/mailer-?daemon@|postmaster@|^mailer-?daemon$/i.test(address)) {
3362
- return true;
3363
- }
3364
-
3365
- // Check for delivery-status attachment + subject pattern
3366
- let hasDeliveryStatus = false;
3367
- let hasOriginalMessage = false;
3368
- for (let attachment of messageInfo.attachments || []) {
3369
- if (attachment.contentType === 'message/delivery-status') {
3370
- hasDeliveryStatus = true;
3371
- }
3372
- if (attachment.contentType === 'message/rfc822') {
3373
- hasOriginalMessage = true;
3374
- }
3375
- }
3376
-
3377
- if (hasDeliveryStatus && /Undeliver(able|ed)/i.test(messageInfo.subject)) {
3378
- return true;
3379
- }
3380
-
3381
- // Has delivery-status attachment (strong indicator)
3382
- if (hasDeliveryStatus) {
3383
- return true;
3384
- }
3385
-
3386
- // Has original message attachment with bounce-like subject
3387
- if (hasOriginalMessage && /Undeliver|Failed|Returned|Failure|Error/i.test(messageInfo.subject)) {
3388
- return true;
3389
- }
3390
-
3391
- // Additional subject patterns for various bounce formats
3392
- // Includes Japanese carrier patterns and generic NDR subjects
3393
- if (
3394
- /^Undeliverable\s+Message$|Mail delivery failed|Delivery Status Notification|Returned mail|Failure Notice|error sending your mail/i.test(
3395
- messageInfo.subject
3396
- )
3397
- ) {
3398
- return true;
3399
- }
3400
-
3401
- return false;
3402
- }
3403
-
3404
- /**
3405
- * Heuristic check if message might be an ARF complaint
3406
- * @param {Object} messageInfo - Message information
3407
- * @returns {Boolean} True if likely a complaint
3408
- */
3409
- mightBeAComplaint(messageInfo) {
3410
- // Only check inbox messages
3411
- if (!samePath(this.path, 'INBOX') && !(this.isAllMail && messageInfo.labels && messageInfo.labels.includes('\\Inbox'))) {
3412
- return false;
3413
- }
3414
-
3415
- let hasEmbeddedMessage = false;
3416
- for (let attachment of messageInfo.attachments || []) {
3417
- // Direct ARF indicator
3418
- if (attachment.contentType === 'message/feedback-report') {
3419
- return true;
3420
- }
3421
-
3422
- // Check for embedded message (complaint might contain original)
3423
- // Include text/rfc822-headers variant used by some senders
3424
- if (['message/rfc822', 'message/rfc822-headers', 'text/rfc822-headers', 'text/rfc822-header'].includes(attachment.contentType)) {
3425
- hasEmbeddedMessage = true;
3426
- }
3427
- }
3428
-
3429
- let fromAddress = (messageInfo.from && messageInfo.from.address) || '';
3430
-
3431
- // Hotmail/Microsoft complaint pattern (may not have parsed attachments)
3432
- if (fromAddress === 'staff@hotmail.com' && /complaint/i.test(messageInfo.subject)) {
3433
- return true;
3434
- }
3435
-
3436
- // Generic feedback loop sender patterns
3437
- if (/^(feedbackloop|fbl|complaints|abuse)@/i.test(fromAddress)) {
3438
- // Common FBL sender addresses indicate likely complaint
3439
- if (hasEmbeddedMessage || /abuse|complaint|feedback|report/i.test(messageInfo.subject)) {
3440
- return true;
3441
- }
3442
- }
3443
-
3444
- // ARF-style subject patterns with embedded message
3445
- if (hasEmbeddedMessage && /abuse report|feedback report|spam report/i.test(messageInfo.subject)) {
3446
- return true;
3447
- }
3448
-
3449
- return false;
3450
- }
3451
-
3452
- /**
3453
- * Heuristic check if message might be a DSN (Delivery Status Notification)
3454
- * @param {Object} messageInfo - Message information
3455
- * @returns {Boolean} True if likely a DSN
3456
- */
3457
- mightBeDSNResponse(messageInfo) {
3458
- // Only check inbox messages
3459
- if (!samePath(this.path, 'INBOX') && !(this.isAllMail && messageInfo.labels && messageInfo.labels.includes('\\Inbox'))) {
3460
- return false;
3461
- }
3462
-
3463
- // Check Content-Type header for multipart/report with delivery-status
3464
- if (messageInfo.headers && messageInfo.headers['content-type'] && messageInfo.headers['content-type'].length) {
3465
- let parsedContentType = libmime.parseHeaderValue(messageInfo.headers['content-type'].at(-1));
3466
- if (
3467
- parsedContentType &&
3468
- parsedContentType.value &&
3469
- parsedContentType.value.toLowerCase().trim() === 'multipart/report' &&
3470
- parsedContentType.params['report-type'] === 'delivery-status'
3471
- ) {
3472
- return true;
3473
- }
3474
- }
3475
-
3476
- return false;
3477
- }
3478
-
3479
3353
  /**
3480
3354
  * Decodes a cursor string for pagination
3481
3355
  * @param {String} cursorStr - Base64-encoded cursor string
@@ -3538,3 +3412,4 @@ class Mailbox {
3538
3412
  module.exports.Mailbox = Mailbox;
3539
3413
  // Exported for tests: publishSyncedEvents() cannot be driven without a live connection
3540
3414
  module.exports.notificationHeaderFields = notificationHeaderFields;
3415
+ module.exports.keepsArrivalQueued = keepsArrivalQueued;