emailengine-app 2.84.2 → 2.86.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 (164) hide show
  1. package/.ncurc.js +29 -9
  2. package/.prettierignore +5 -1
  3. package/.prettierrc.js +2 -0
  4. package/.release-please-manifest.json +1 -1
  5. package/CHANGELOG.md +107 -0
  6. package/Dockerfile +20 -1
  7. package/ENVIRONMENT.md +139 -0
  8. package/README.md +2 -2
  9. package/bin/emailengine.js +434 -408
  10. package/config/default.toml +2 -0
  11. package/copy-static-files.sh +41 -14
  12. package/data/google-crawlers.json +1 -1
  13. package/data/public_suffix_list.dat +16563 -0
  14. package/eslint.config.js +81 -99
  15. package/lib/account-assignment.js +19 -0
  16. package/lib/account.js +230 -170
  17. package/lib/api-error-codes.js +49 -0
  18. package/lib/api-reference/format.js +4 -3
  19. package/lib/api-reference/model.js +6 -1
  20. package/lib/api-routes/account-routes.js +255 -38
  21. package/lib/api-routes/blocklist-routes.js +91 -4
  22. package/lib/api-routes/delivery-test-routes.js +27 -4
  23. package/lib/api-routes/export-routes.js +28 -2
  24. package/lib/api-routes/gateway-routes.js +110 -12
  25. package/lib/api-routes/index.js +4 -0
  26. package/lib/api-routes/license-routes.js +2 -2
  27. package/lib/api-routes/mailbox-routes.js +44 -5
  28. package/lib/api-routes/message-routes.js +112 -10
  29. package/lib/api-routes/oauth2-app-routes.js +63 -23
  30. package/lib/api-routes/outbox-routes.js +97 -52
  31. package/lib/api-routes/permission-map.js +67 -7
  32. package/lib/api-routes/scoped-routes.js +74 -0
  33. package/lib/api-routes/settings-routes.js +34 -6
  34. package/lib/api-routes/stats-routes.js +5 -1
  35. package/lib/api-routes/submit-routes.js +337 -309
  36. package/lib/api-routes/template-routes.js +45 -8
  37. package/lib/api-routes/token-routes.js +152 -100
  38. package/lib/api-routes/webhook-delivery-routes.js +262 -0
  39. package/lib/api-routes/webhook-route-routes.js +132 -6
  40. package/lib/bounce-detect.js +397 -205
  41. package/lib/calendar-event.js +81 -1
  42. package/lib/consts.js +38 -45
  43. package/lib/db.js +14 -6
  44. package/lib/delivery-error.js +6 -0
  45. package/lib/deprecations.js +270 -0
  46. package/lib/email-client/base-client.js +137 -184
  47. package/lib/email-client/fallback-poll.js +62 -0
  48. package/lib/email-client/gmail-client.js +60 -22
  49. package/lib/email-client/imap/adaptive-idle-store.js +73 -0
  50. package/lib/email-client/imap/adaptive-idle.js +278 -0
  51. package/lib/email-client/imap/connection-errors.js +14 -1
  52. package/lib/email-client/imap/idle-settings.js +31 -5
  53. package/lib/email-client/imap/listing-diff.js +37 -0
  54. package/lib/email-client/imap/mailbox.js +372 -242
  55. package/lib/email-client/imap/subconnection.js +8 -30
  56. package/lib/email-client/imap/sync-operations.js +220 -127
  57. package/lib/email-client/imap-client.js +228 -164
  58. package/lib/email-client/message-builder.js +14 -79
  59. package/lib/email-client/notification-handler.js +1 -2
  60. package/lib/email-client/outlook-client.js +372 -338
  61. package/lib/email-client/smtp-pool-manager.js +16 -13
  62. package/lib/email-client/sync-state-fields.js +19 -0
  63. package/lib/encrypt.js +157 -41
  64. package/lib/enum-descriptions.js +3 -1
  65. package/lib/env-setting-overrides.js +288 -0
  66. package/lib/export-worker.js +751 -0
  67. package/lib/export.js +64 -15
  68. package/lib/gateway.js +19 -4
  69. package/lib/get-raw-email.js +25 -107
  70. package/lib/hapi-request-logger.js +107 -0
  71. package/lib/health.js +75 -0
  72. package/lib/imapproxy/imap-core/README.md +6 -5
  73. package/lib/lock-run.js +119 -0
  74. package/lib/logger-consts.js +48 -0
  75. package/lib/logger.js +1 -1
  76. package/lib/lua/z-head-scores.lua +28 -0
  77. package/lib/mcp/tools.js +37 -8
  78. package/lib/network-errors.js +1 -1
  79. package/lib/node-version.js +24 -0
  80. package/lib/notify-attachments.js +36 -0
  81. package/lib/oauth/outlook-mailbox.js +35 -0
  82. package/lib/oauth/state.js +24 -0
  83. package/lib/oauth2-apps.js +631 -656
  84. package/lib/outbox.js +184 -54
  85. package/lib/parse-message.js +3 -3
  86. package/lib/pbkdf2-phc.js +1 -1
  87. package/lib/privileged-settings.js +2 -2
  88. package/lib/queue-browser/definitions.js +11 -0
  89. package/lib/queue-browser/index.js +68 -19
  90. package/lib/queue-job-actions.js +18 -1
  91. package/lib/queue-retention.js +48 -12
  92. package/lib/queue-stats.js +11 -2
  93. package/lib/read-env-value.js +3 -0
  94. package/lib/redis-memory-warnings.js +99 -0
  95. package/lib/redis-reconnect.js +29 -0
  96. package/lib/request-timing.js +23 -0
  97. package/lib/respawn-backoff.js +35 -0
  98. package/lib/rewrite-text-nodes.js +19 -59
  99. package/lib/schemas.js +164 -40
  100. package/lib/settings.js +6 -2
  101. package/lib/smtp-auth.js +19 -1
  102. package/lib/sso.js +1 -1
  103. package/lib/swagger-options.js +1 -1
  104. package/lib/thread-diagnostics.js +63 -0
  105. package/lib/timezones.js +109 -0
  106. package/lib/tls/provision.js +6 -3
  107. package/lib/token-audit-log.js +19 -20
  108. package/lib/token-permission-view.js +7 -6
  109. package/lib/tools.js +48 -51
  110. package/lib/totp.js +2 -5
  111. package/lib/translations.js +1 -2
  112. package/lib/ui-routes/account-routes.js +475 -454
  113. package/lib/ui-routes/account-setup.js +99 -0
  114. package/lib/ui-routes/admin-config-routes.js +152 -100
  115. package/lib/ui-routes/admin-entities-routes.js +93 -21
  116. package/lib/ui-routes/auth-routes.js +90 -38
  117. package/lib/ui-routes/imap-idle-field.js +1 -1
  118. package/lib/ui-routes/internals-routes.js +5 -0
  119. package/lib/ui-routes/oauth-config-routes.js +124 -82
  120. package/lib/ui-routes/outlook-subscription-view.js +1 -1
  121. package/lib/ui-routes/overridable-fields.js +84 -0
  122. package/lib/ui-routes/queue-routes.js +8 -5
  123. package/lib/ui-routes/route-helpers.js +19 -3
  124. package/lib/ui-routes/settings-page.js +6 -0
  125. package/lib/ui-routes/tls-config-routes.js +58 -15
  126. package/lib/utils/back-off.js +82 -0
  127. package/lib/utils/decode-headers.js +3 -12
  128. package/lib/utils/filter-empty.js +20 -0
  129. package/lib/utils/int-setting.js +48 -0
  130. package/lib/utils/murmurhash3.js +66 -0
  131. package/lib/utils/public-suffix.js +122 -0
  132. package/lib/utils/random-id.js +26 -0
  133. package/lib/utils/tracking-settings.js +35 -0
  134. package/lib/utils/version.js +74 -0
  135. package/lib/web-safe-html.js +18 -105
  136. package/lib/webhook-delivery.js +461 -0
  137. package/lib/webhook-failures.js +132 -0
  138. package/lib/webhook-request.js +29 -1
  139. package/lib/webhook-routing.js +56 -0
  140. package/lib/webhook-test.js +88 -0
  141. package/lib/webhooks.js +93 -45
  142. package/lib/worker-rpc-error.js +2 -1
  143. package/package.json +37 -38
  144. package/sbom.json +7902 -1
  145. package/server.js +784 -518
  146. package/static/js/ace/ace.js +1 -1
  147. package/static/licenses.html +225 -1060
  148. package/translations/messages.pot +62 -63
  149. package/views/config/ai.hbs +1 -1
  150. package/views/config/security.hbs +24 -2
  151. package/views/config/service.hbs +47 -0
  152. package/views/config/webhooks.hbs +36 -0
  153. package/views/internals/index.hbs +8 -0
  154. package/views/partials/queue_retention_note.hbs +12 -8
  155. package/views/partials/ui/env-managed-alert.hbs +16 -7
  156. package/views/partials/webhook_form.hbs +1 -1
  157. package/views/suppression-lists/index.hbs +1 -1
  158. package/workers/api.js +840 -611
  159. package/workers/export.js +17 -632
  160. package/workers/imap.js +13 -0
  161. package/workers/smtp.js +9 -11
  162. package/workers/submit.js +1 -1
  163. package/workers/webhooks.js +18 -448
  164. package/lib/email-client/outlook-fallback-poll.js +0 -30
@@ -313,54 +313,65 @@ function parseDeliveryHeaders(entries) {
313
313
  }
314
314
 
315
315
  /**
316
- * Main bounce detection function that analyzes email messages for bounce information
316
+ * Finds the first attachment of a content type, compared case-insensitively per RFC 2045
317
317
  *
318
- * @async
319
- * @param {Stream|Object} sourceStream - Email stream or object with parsed email
320
- * @param {Object} [sourceStream.parsed] - Pre-parsed email object (avoids re-parsing)
321
- * @returns {Promise<Object>} Bounce detection results
322
- * @returns {string} [returns.recipient] - Failed recipient email address
323
- * @returns {string} [returns.action] - Bounce action (typically 'failed')
324
- * @returns {Object} [returns.response] - SMTP response details
325
- * @returns {string} [returns.response.message] - The error message from the remote server
326
- * @returns {string} [returns.response.status] - Enhanced status code (X.X.X format)
327
- * @returns {string} [returns.response.source] - Source of the diagnostic code
328
- * @returns {string} [returns.mta] - Mail server that reported the failure
329
- * @returns {string} [returns.queueId] - Queue ID from the sending MTA
330
- * @returns {string} [returns.messageId] - Original message ID that bounced
331
- * @returns {Object} [returns.messageHeaders] - Headers from the original message
318
+ * @param {Object[]} attachments - Parsed attachments
319
+ * @param {string} contentType - Lowercase content type to look for
320
+ * @returns {Object|undefined} The first matching attachment
332
321
  */
333
- async function bounceDetect(sourceStream) {
334
- // Validate input parameter
335
- if (!sourceStream) {
336
- return {};
337
- }
338
-
339
- let parsed;
322
+ function findAttachmentByType(attachments, contentType) {
323
+ return attachments.find(attachment => attachment.contentType?.toLowerCase() === contentType);
324
+ }
340
325
 
326
+ /**
327
+ * Parses the bounce unless the caller already did
328
+ *
329
+ * @param {Stream|Buffer|string|Object} sourceStream - Email source, or an object carrying `parsed`
330
+ * @returns {Promise<Object>} Parsed message
331
+ */
332
+ async function loadParsedMessage(sourceStream) {
341
333
  // Use pre-parsed email if available to avoid parsing twice
342
334
  if (sourceStream.parsed) {
343
- parsed = sourceStream.parsed;
344
- } else {
345
- // Parse the email, keeping delivery status attachments intact
346
- parsed = await parseMessage(sourceStream, PARSER_OPTIONS);
335
+ return sourceStream.parsed;
347
336
  }
337
+ // Parse the email, keeping delivery status attachments intact
338
+ return await parseMessage(sourceStream, PARSER_OPTIONS);
339
+ }
348
340
 
349
- let result = {};
350
-
341
+ /**
342
+ * Builds the state one bounceDetect() run works on
343
+ *
344
+ * Every reader below updates this object rather than closing over shared variables: `result` is
345
+ * the detection result being filled in, `parsedMessageHeaders` the headers of the bounced message
346
+ * once some part has supplied them.
347
+ *
348
+ * @param {Object} parsed - Parsed bounce message
349
+ * @returns {Object} Detection context
350
+ */
351
+ function createDetectContext(parsed) {
351
352
  // Look for standard bounce attachments as defined in RFC 3464
352
- // Use case-insensitive comparison per RFC 2045 and handle missing attachments array
353
+ // A message without attachments has no attachments array
353
354
  const attachments = parsed.attachments || [];
354
- let deliveryStatus = attachments.find(attachment => attachment.contentType?.toLowerCase() === 'message/delivery-status');
355
- let messageHeaders = attachments.find(attachment => attachment.contentType?.toLowerCase() === 'text/rfc822-headers');
356
- let originalMessage = attachments.find(attachment => attachment.contentType?.toLowerCase() === 'message/rfc822');
357
-
358
- // Zoho Mail uses non-standard content type for original message
359
- let zohoOriginalMessage = attachments.find(attachment => attachment.contentType?.toLowerCase() === 'text/rfc822');
360
-
361
- let parsedMessageHeaders;
355
+ return {
356
+ parsed,
357
+ attachments,
358
+ result: {},
359
+ deliveryStatus: findAttachmentByType(attachments, 'message/delivery-status'),
360
+ messageHeaders: findAttachmentByType(attachments, 'text/rfc822-headers'),
361
+ originalMessage: findAttachmentByType(attachments, 'message/rfc822'),
362
+ // Zoho Mail uses non-standard content type for original message
363
+ zohoOriginalMessage: findAttachmentByType(attachments, 'text/rfc822'),
364
+ parsedMessageHeaders: undefined
365
+ };
366
+ }
362
367
 
363
- // Handle Exchange/Outlook specific header for failed recipients
368
+ /**
369
+ * Handles the Exchange/Outlook specific header for failed recipients
370
+ *
371
+ * @param {Object} ctx - Detection context
372
+ */
373
+ function readFailedRecipientsHeader(ctx) {
374
+ let { parsed, result } = ctx;
364
375
  if (parsed.headers && parsed.headers.has('x-failed-recipients')) {
365
376
  // Parse comma and space separated list of failed recipients
366
377
  let list = []
@@ -375,9 +386,16 @@ async function bounceDetect(sourceStream) {
375
386
  result.recipient = list[0];
376
387
  }
377
388
  }
389
+ }
378
390
 
379
- // Special handling for Amazon WorkMail bounces
380
- // WorkMail doesn't use standard delivery-status attachments
391
+ /**
392
+ * Special handling for Amazon WorkMail bounces
393
+ * WorkMail doesn't use standard delivery-status attachments
394
+ *
395
+ * @param {Object} ctx - Detection context
396
+ */
397
+ function readWorkMailReport(ctx) {
398
+ let { parsed } = ctx;
381
399
  if (parsed.headers && parsed.headers.has('x-mailer')) {
382
400
  let xMailer = []
383
401
  .concat(parsed.headers.get('x-mailer') || '')
@@ -397,137 +415,187 @@ async function bounceDetect(sourceStream) {
397
415
  if (splitPos >= 0) {
398
416
  let bounceDetails = parsed.text.substr(splitPos + splitMarker.length).trim();
399
417
  // Parse the technical report section as if it were a delivery-status
400
- result = Object.assign(result, parseDeliveryStatus(bounceDetails) || {});
418
+ Object.assign(ctx.result, parseDeliveryStatus(bounceDetails) || {});
401
419
  }
402
420
  }
403
421
  }
422
+ }
404
423
 
424
+ /**
425
+ * Processes the standard delivery-status attachment and the RFC822 headers attachment
426
+ * (the latter contains headers of the original message)
427
+ *
428
+ * @param {Object} ctx - Detection context
429
+ */
430
+ function readReportParts(ctx) {
405
431
  // Process standard delivery-status attachment
406
- if (deliveryStatus) {
407
- result = Object.assign(result, parseDeliveryStatus(deliveryStatus.content) || {});
432
+ if (ctx.deliveryStatus) {
433
+ Object.assign(ctx.result, parseDeliveryStatus(ctx.deliveryStatus.content) || {});
408
434
  }
409
435
 
410
436
  // Process RFC822 headers attachment (contains headers of the original message)
411
- if (messageHeaders) {
412
- parsedMessageHeaders = decodeHeaders(messageHeaders.content);
413
- result = Object.assign(result, parseDeliveryHeaders(parsedMessageHeaders));
437
+ if (ctx.messageHeaders) {
438
+ ctx.parsedMessageHeaders = decodeHeaders(ctx.messageHeaders.content);
439
+ Object.assign(ctx.result, parseDeliveryHeaders(ctx.parsedMessageHeaders));
414
440
  }
441
+ }
415
442
 
416
- // Process complete original message attachment
417
- if (originalMessage) {
418
- try {
419
- // Parse the original message to extract its headers
420
- let parsedOriginal = await parseMessage(originalMessage.content, PARSER_OPTIONS);
421
- if (parsedOriginal) {
422
- // Build headers object from headerLines for consistent access
423
- let headers = {};
424
-
425
- if (parsedOriginal.headerLines && Array.isArray(parsedOriginal.headerLines)) {
426
- parsedOriginal.headerLines.forEach(entry => {
427
- // Preserve the original header value (after the key and colon).
428
- // pushHeaderValue() skips names that resolve to an Object.prototype member,
429
- // which a bare `!headers[key]` probe would have pushed onto, throwing out of
430
- // the whole block and losing every header of the bounced message
431
- pushHeaderValue(headers, entry.key, entry.line.substring(entry.key.length + 1).trim());
432
- });
433
- }
443
+ /**
444
+ * Builds a headers object from headerLines for consistent access
445
+ *
446
+ * @param {Object} parsedOriginal - Parsed original message
447
+ * @returns {Object} Header keys mapped to arrays of raw values
448
+ */
449
+ function collectOriginalHeaders(parsedOriginal) {
450
+ let headers = {};
451
+
452
+ if (parsedOriginal.headerLines && Array.isArray(parsedOriginal.headerLines)) {
453
+ parsedOriginal.headerLines.forEach(entry => {
454
+ // Preserve the original header value (after the key and colon).
455
+ // pushHeaderValue() skips names that resolve to an Object.prototype member,
456
+ // which a bare `!headers[key]` probe would have pushed onto, throwing out of
457
+ // the whole block and losing every header of the bounced message
458
+ pushHeaderValue(headers, entry.key, entry.line.substring(entry.key.length + 1).trim());
459
+ });
460
+ }
434
461
 
435
- parsedMessageHeaders = headers;
462
+ return headers;
463
+ }
436
464
 
437
- // Extract Message-ID if not already found
438
- if (!result.messageId && parsedOriginal.messageId) {
439
- result.messageId = parsedOriginal.messageId;
440
- }
465
+ /**
466
+ * Applies a parsed original message attachment to the detection context
467
+ *
468
+ * @param {Object} ctx - Detection context
469
+ * @param {Object} parsedOriginal - Parsed message/rfc822 attachment
470
+ */
471
+ function applyOriginalMessage(ctx, parsedOriginal) {
472
+ ctx.parsedMessageHeaders = collectOriginalHeaders(parsedOriginal);
441
473
 
442
- // Some bounces include delivery-status within the original message attachment
443
- const originalAttachments = parsedOriginal.attachments || [];
444
- if (!deliveryStatus) {
445
- deliveryStatus = originalAttachments.find(attachment => attachment.contentType?.toLowerCase() === 'message/delivery-status');
446
- if (deliveryStatus) {
447
- result = Object.assign(result, parseDeliveryStatus(deliveryStatus.content) || {});
448
- }
449
- }
474
+ // Extract Message-ID if not already found
475
+ if (!ctx.result.messageId && parsedOriginal.messageId) {
476
+ ctx.result.messageId = parsedOriginal.messageId;
477
+ }
450
478
 
451
- // Similarly for headers attachment
452
- if (!messageHeaders) {
453
- messageHeaders = originalAttachments.find(attachment => attachment.contentType?.toLowerCase() === 'text/rfc822-headers');
454
- if (messageHeaders) {
455
- let headerEntries = decodeHeaders(messageHeaders.content);
456
- result = Object.assign(result, parseDeliveryHeaders(headerEntries));
457
- }
458
- }
459
- }
460
- } catch (E) {
461
- // Failed to parse original message attachment
462
- // Continue processing as this is not critical
463
- // TODO: Consider logging this error for debugging
479
+ // Some bounces include delivery-status within the original message attachment
480
+ const originalAttachments = parsedOriginal.attachments || [];
481
+ if (!ctx.deliveryStatus) {
482
+ let deliveryStatus = findAttachmentByType(originalAttachments, 'message/delivery-status');
483
+ if (deliveryStatus) {
484
+ Object.assign(ctx.result, parseDeliveryStatus(deliveryStatus.content) || {});
464
485
  }
465
486
  }
466
487
 
467
- // Handle Zoho's non-standard bounce format
468
- // Zoho uses text/rfc822 content type (instead of standard message/rfc822)
469
- // and includes original message headers in a non-standard format
470
- if (zohoOriginalMessage) {
471
- // Verify this is actually a Zoho bounce to prevent false positives
472
- let isZohoBounce = false;
473
-
474
- // Check for Zoho-specific indicators in the bounce email headers
475
- if (parsed.headers) {
476
- // Check X-Mailer header
477
- const xMailer = parsed.headers.has('x-mailer')
478
- ? []
479
- .concat(parsed.headers.get('x-mailer') || '')
480
- .join(' ')
481
- .toLowerCase()
482
- : '';
483
- // Check From header for Zoho domain
484
- const fromHeader = parsed.headers.has('from')
485
- ? []
486
- .concat(parsed.headers.get('from') || '')
487
- .map(f => (f.address || f.text || f || '').toLowerCase())
488
- .join(' ')
489
- : '';
490
- // Check User-Agent header
491
- const userAgent = parsed.headers.has('user-agent')
492
- ? []
493
- .concat(parsed.headers.get('user-agent') || '')
494
- .join(' ')
495
- .toLowerCase()
496
- : '';
497
-
498
- isZohoBounce = xMailer.includes('zoho') || fromHeader.includes('zoho') || userAgent.includes('zoho');
488
+ // Similarly for headers attachment
489
+ if (!ctx.messageHeaders) {
490
+ let messageHeaders = findAttachmentByType(originalAttachments, 'text/rfc822-headers');
491
+ if (messageHeaders) {
492
+ let headerEntries = decodeHeaders(messageHeaders.content);
493
+ Object.assign(ctx.result, parseDeliveryHeaders(headerEntries));
499
494
  }
495
+ }
496
+ }
500
497
 
501
- if (isZohoBounce) {
502
- try {
503
- let parsedOriginal = await parseMessage(zohoOriginalMessage.content, PARSER_OPTIONS);
504
- // Zoho sometimes includes headers in the text body with no actual header structure
505
- if (parsedOriginal && parsedOriginal.text && (!parsedOriginal.headerLines || !parsedOriginal.headerLines.filter(h => h.key).length)) {
506
- // Remove leading spaces that indicate header continuation
507
- let headerContent = capHeaderBlock(parsedOriginal.text).replace(/^ (?=[^ ])/gm, '');
508
-
509
- // Additional validation: content should look like email headers
510
- // Check for common header patterns (Received:, Message-ID:, Date:, From:)
511
- if (/^\s*(Received|Message-ID|Date|From):/im.test(headerContent)) {
512
- let headers = decodeHeaders(headerContent);
513
- if (headers && headers['message-id']) {
514
- parsedMessageHeaders = headers;
515
- result = Object.assign(result, parseDeliveryHeaders(headers));
516
- }
517
- }
498
+ /**
499
+ * Processes the complete original message attachment
500
+ *
501
+ * @param {Object} ctx - Detection context
502
+ */
503
+ async function readOriginalMessage(ctx) {
504
+ if (!ctx.originalMessage) {
505
+ return;
506
+ }
507
+ try {
508
+ // Parse the original message to extract its headers
509
+ let parsedOriginal = await parseMessage(ctx.originalMessage.content, PARSER_OPTIONS);
510
+ if (parsedOriginal) {
511
+ applyOriginalMessage(ctx, parsedOriginal);
512
+ }
513
+ } catch (E) {
514
+ // Failed to parse original message attachment
515
+ // Continue processing as this is not critical
516
+ // TODO: Consider logging this error for debugging
517
+ }
518
+ }
519
+
520
+ /**
521
+ * Verifies a text/rfc822 attachment comes from an actual Zoho bounce to prevent false positives
522
+ *
523
+ * @param {Object} parsed - Parsed bounce message
524
+ * @returns {Boolean} True when the bounce headers carry a Zoho indicator
525
+ */
526
+ function isZohoBounce(parsed) {
527
+ // Check for Zoho-specific indicators in the bounce email headers
528
+ if (!parsed.headers) {
529
+ return false;
530
+ }
531
+
532
+ // Check X-Mailer header
533
+ const xMailer = parsed.headers.has('x-mailer')
534
+ ? []
535
+ .concat(parsed.headers.get('x-mailer') || '')
536
+ .join(' ')
537
+ .toLowerCase()
538
+ : '';
539
+ // Check From header for Zoho domain
540
+ const fromHeader = parsed.headers.has('from')
541
+ ? []
542
+ .concat(parsed.headers.get('from') || '')
543
+ .map(f => (f.address || f.text || f || '').toLowerCase())
544
+ .join(' ')
545
+ : '';
546
+ // Check User-Agent header
547
+ const userAgent = parsed.headers.has('user-agent')
548
+ ? []
549
+ .concat(parsed.headers.get('user-agent') || '')
550
+ .join(' ')
551
+ .toLowerCase()
552
+ : '';
553
+
554
+ return xMailer.includes('zoho') || fromHeader.includes('zoho') || userAgent.includes('zoho');
555
+ }
556
+
557
+ /**
558
+ * Handles Zoho's non-standard bounce format
559
+ * Zoho uses text/rfc822 content type (instead of standard message/rfc822)
560
+ * and includes original message headers in a non-standard format
561
+ *
562
+ * @param {Object} ctx - Detection context
563
+ */
564
+ async function readZohoOriginalMessage(ctx) {
565
+ if (!ctx.zohoOriginalMessage || !isZohoBounce(ctx.parsed)) {
566
+ return;
567
+ }
568
+ try {
569
+ let parsedOriginal = await parseMessage(ctx.zohoOriginalMessage.content, PARSER_OPTIONS);
570
+ // Zoho sometimes includes headers in the text body with no actual header structure
571
+ if (parsedOriginal && parsedOriginal.text && (!parsedOriginal.headerLines || !parsedOriginal.headerLines.filter(h => h.key).length)) {
572
+ // Remove leading spaces that indicate header continuation
573
+ let headerContent = capHeaderBlock(parsedOriginal.text).replace(/^ (?=[^ ])/gm, '');
574
+
575
+ // Additional validation: content should look like email headers
576
+ // Check for common header patterns (Received:, Message-ID:, Date:, From:)
577
+ if (/^\s*(Received|Message-ID|Date|From):/im.test(headerContent)) {
578
+ let headers = decodeHeaders(headerContent);
579
+ if (headers && headers['message-id']) {
580
+ ctx.parsedMessageHeaders = headers;
581
+ Object.assign(ctx.result, parseDeliveryHeaders(headers));
518
582
  }
519
- } catch (E) {
520
- // Failed to parse Zoho attachment
521
- // Continue processing as this is not critical
522
583
  }
523
584
  }
585
+ } catch (E) {
586
+ // Failed to parse Zoho attachment
587
+ // Continue processing as this is not critical
524
588
  }
589
+ }
525
590
 
526
- // What the structured parts said, if anything; the text heuristics below only fill gaps, and
527
- // only a claim they made is reconsidered at the end
528
- let structuredAction = result.action;
529
-
530
- // Extract text content for pattern matching
591
+ /**
592
+ * Extracts the text content the pattern matching runs over
593
+ *
594
+ * @param {Object} parsed - Parsed bounce message
595
+ * @param {Object[]} attachments - Its attachments
596
+ * @returns {string} Text, capped in length
597
+ */
598
+ function extractHeuristicText(parsed, attachments) {
531
599
  let text = (parsed.text || '').toString();
532
600
 
533
601
  // Some bounces put the content in an attachment with no content-type
@@ -545,9 +613,29 @@ async function bounceDetect(sourceStream) {
545
613
  text = text.substring(0, MAX_TEXT_LENGTH);
546
614
  }
547
615
 
548
- // Pattern matching for non-standard bounce formats
549
- // Only proceed if we haven't found the recipient or response message yet
616
+ return text;
617
+ }
618
+
619
+ /**
620
+ * Tries to extract an enhanced status code (X.X.X) from an SMTP reply, unless one is already set
621
+ *
622
+ * @param {Object} response - Response object to fill in
623
+ * @param {string} message - SMTP reply text
624
+ */
625
+ function fillEnhancedStatus(response, message) {
626
+ if (!response.status) {
627
+ let statusMatch = message.match(/[45]\d{2}[\s-](\d+\.\d+\.\d+)[\s-]/);
628
+ if (statusMatch && statusMatch[1]) {
629
+ response.status = statusMatch[1];
630
+ }
631
+ }
632
+ }
550
633
 
634
+ // Pattern matching for non-standard bounce formats. Each heuristic below only fills gaps the
635
+ // structured parts (and the heuristics before it) left, and they run in this order.
636
+
637
+ function matchHostSaid(result, text) {
638
+ // Only proceed if we haven't found the recipient or response message yet
551
639
  if (!result.recipient || !result.response || !result.response.message) {
552
640
  /*
553
641
  * Match pattern like:
@@ -582,16 +670,13 @@ async function bounceDetect(sourceStream) {
582
670
  }
583
671
 
584
672
  // Try to extract enhanced status code from the message
585
- if (!result.response.status) {
586
- let statusMatch = message.match(/[45]\d{2}[\s-](\d+\.\d+\.\d+)[\s-]/);
587
- if (statusMatch && statusMatch[1]) {
588
- result.response.status = statusMatch[1];
589
- }
590
- }
673
+ fillEnhancedStatus(result.response, message);
591
674
  }
592
675
  }
593
676
  }
677
+ }
594
678
 
679
+ function matchDeliveryFailedRecipient(result, text) {
595
680
  if (!result.recipient) {
596
681
  /*
597
682
  * Match pattern like:
@@ -610,7 +695,9 @@ async function bounceDetect(sourceStream) {
610
695
  }
611
696
  }
612
697
  }
698
+ }
613
699
 
700
+ function matchAffectedRecipients(result, text) {
614
701
  if (!result.recipient) {
615
702
  /*
616
703
  * Match pattern like:
@@ -625,7 +712,9 @@ async function bounceDetect(sourceStream) {
625
712
  }
626
713
  }
627
714
  }
715
+ }
628
716
 
717
+ function matchLeadingSmtpReply(result, text) {
629
718
  if (!result.response || !result.response.message) {
630
719
  /*
631
720
  * Match SMTP response at the beginning of a line
@@ -650,17 +739,14 @@ async function bounceDetect(sourceStream) {
650
739
  result.response.message = result.response.message || message;
651
740
 
652
741
  // Extract enhanced status code
653
- if (!result.response.status) {
654
- let statusMatch = message.match(/[45]\d{2}[\s-](\d+\.\d+\.\d+)[\s-]/);
655
- if (statusMatch && statusMatch[1]) {
656
- result.response.status = statusMatch[1];
657
- }
658
- }
742
+ fillEnhancedStatus(result.response, message);
659
743
  }
660
744
  }
661
745
  }
746
+ }
662
747
 
663
- // Another non-standard format
748
+ // Another non-standard format
749
+ function matchRecipientBlock(result, text) {
664
750
  if (!result.recipient || !result.response || !result.response.message) {
665
751
  /*
666
752
  * Match pattern like:
@@ -687,12 +773,7 @@ async function bounceDetect(sourceStream) {
687
773
  result.response.message = result.response.message || message;
688
774
 
689
775
  // Try X.X.X format
690
- if (!result.response.status) {
691
- let statusMatch = message.match(/[45]\d{2}[\s-](\d+\.\d+\.\d+)[\s-]/);
692
- if (statusMatch && statusMatch[1]) {
693
- result.response.status = statusMatch[1];
694
- }
695
- }
776
+ fillEnhancedStatus(result.response, message);
696
777
 
697
778
  // Also try (#X.X.X) format
698
779
  if (!result.response.status) {
@@ -704,7 +785,9 @@ async function bounceDetect(sourceStream) {
704
785
  }
705
786
  }
706
787
  }
788
+ }
707
789
 
790
+ function matchUndeliverableMessageTo(result, text) {
708
791
  if (!result.recipient) {
709
792
  /*
710
793
  * Match pattern like:
@@ -717,8 +800,10 @@ async function bounceDetect(sourceStream) {
717
800
  result.recipient = m[1];
718
801
  }
719
802
  }
803
+ }
720
804
 
721
- // Google's old bounce format (pre-2015 style)
805
+ // Google's old bounce format (pre-2015 style)
806
+ function matchGoogleLegacy(result, text) {
722
807
  if (!result.action || !result.response || !result.response.message) {
723
808
  /*
724
809
  * Match pattern like:
@@ -750,7 +835,9 @@ async function bounceDetect(sourceStream) {
750
835
  }
751
836
  }
752
837
  }
838
+ }
753
839
 
840
+ function matchReasonForProblem(result, text) {
754
841
  if (!result.response || !result.response.message) {
755
842
  /*
756
843
  * Match pattern like:
@@ -779,7 +866,9 @@ async function bounceDetect(sourceStream) {
779
866
  }
780
867
  }
781
868
  }
869
+ }
782
870
 
871
+ function matchRemoteHostSaid(result, text) {
783
872
  if (!result.recipient && (!result.response || !result.response.message)) {
784
873
  /*
785
874
  * Match pattern like:
@@ -800,8 +889,10 @@ async function bounceDetect(sourceStream) {
800
889
  }
801
890
  }
802
891
  }
892
+ }
803
893
 
804
- // Complex pattern for certain MTA formats (Postfix style)
894
+ // Complex pattern for certain MTA formats (Postfix style)
895
+ function matchRecipientHostBlock(result, text) {
805
896
  if (result.recipient && result.response && !result.response.message && /A message that you sent could not be delivered/.test(text)) {
806
897
  /*
807
898
  * Match pattern like:
@@ -830,8 +921,45 @@ async function bounceDetect(sourceStream) {
830
921
  }
831
922
  }
832
923
  }
924
+ }
925
+
926
+ /**
927
+ * Collects the indented error lines that follow the recipient line in an Exim block
928
+ *
929
+ * @param {string} block - One blank-line separated block of the bounce text
930
+ * @param {string} recipient - Recipient address to look for
931
+ * @returns {string[]} Trimmed error lines, empty when none follow the recipient
932
+ */
933
+ function collectEximMessageLines(block, recipient) {
934
+ // Split block into lines and find the recipient line
935
+ const lines = block.split(/\r?\n/);
936
+ let foundRecipient = false;
937
+ let messageLines = [];
938
+
939
+ for (const line of lines) {
940
+ if (!foundRecipient) {
941
+ // Look for line containing recipient email
942
+ if (line.includes(recipient)) {
943
+ foundRecipient = true;
944
+ }
945
+ } else if (/^\s{2,}/.test(line) && line.trim()) {
946
+ // After recipient line, collect indented lines as error message
947
+ // Error lines typically start with more indentation than the recipient
948
+ messageLines.push(line.trim());
949
+ } else if (line.trim() === '') {
950
+ // Empty line might separate multiple errors, stop here
951
+ break;
952
+ } else {
953
+ // Non-indented non-empty line means end of this recipient's block
954
+ break;
955
+ }
956
+ }
957
+
958
+ return messageLines;
959
+ }
833
960
 
834
- // Exim-style bounce format
961
+ // Exim-style bounce format
962
+ function matchEximFailedAddresses(result, text) {
835
963
  if (result.recipient && (!result.response || !result.response.message) && /The following address\(?es\)? failed:/i.test(text)) {
836
964
  /*
837
965
  * Match pattern like (Exim MTA):
@@ -846,31 +974,7 @@ async function bounceDetect(sourceStream) {
846
974
  for (const block of blocks) {
847
975
  // Check if this block contains our recipient email
848
976
  if (block.includes(result.recipient)) {
849
- // Split block into lines and find the recipient line
850
- const lines = block.split(/\r?\n/);
851
- let foundRecipient = false;
852
- let messageLines = [];
853
-
854
- for (const line of lines) {
855
- if (!foundRecipient) {
856
- // Look for line containing recipient email
857
- if (line.includes(result.recipient)) {
858
- foundRecipient = true;
859
- }
860
- } else {
861
- // After recipient line, collect indented lines as error message
862
- // Error lines typically start with more indentation than the recipient
863
- if (/^\s{2,}/.test(line) && line.trim()) {
864
- messageLines.push(line.trim());
865
- } else if (line.trim() === '') {
866
- // Empty line might separate multiple errors, stop here
867
- break;
868
- } else {
869
- // Non-indented non-empty line means end of this recipient's block
870
- break;
871
- }
872
- }
873
- }
977
+ let messageLines = collectEximMessageLines(block, result.recipient);
874
978
 
875
979
  if (messageLines.length > 0) {
876
980
  const message = messageLines.join(' ').replace(/\s+/g, ' ').trim();
@@ -884,8 +988,10 @@ async function bounceDetect(sourceStream) {
884
988
  }
885
989
  }
886
990
  }
991
+ }
887
992
 
888
- // KDDI / Japanese carrier style bounce
993
+ // KDDI / Japanese carrier style bounce
994
+ function matchCouldNotBeDeliveredTo(result, text) {
889
995
  if (!result.recipient) {
890
996
  /*
891
997
  * Match pattern like:
@@ -897,8 +1003,10 @@ async function bounceDetect(sourceStream) {
897
1003
  result.action = result.action || 'failed';
898
1004
  }
899
1005
  }
1006
+ }
900
1007
 
901
- // X6 / Generic MTA style with "permanent errors"
1008
+ // X6 / Generic MTA style with "permanent errors"
1009
+ function matchPermanentErrors(result, text) {
902
1010
  if (!result.recipient) {
903
1011
  /*
904
1012
  * Match pattern like:
@@ -910,8 +1018,10 @@ async function bounceDetect(sourceStream) {
910
1018
  result.action = result.action || 'failed';
911
1019
  }
912
1020
  }
1021
+ }
913
1022
 
914
- // Extract error message from Verizon MMS / mobile carrier style
1023
+ // Extract error message from Verizon MMS / mobile carrier style
1024
+ function matchCarrierError(result, text) {
915
1025
  if (!result.response || !result.response.message) {
916
1026
  /*
917
1027
  * Match pattern like:
@@ -926,8 +1036,10 @@ async function bounceDetect(sourceStream) {
926
1036
  result.response.message = result.response.message || m[0].replace(/\s+/g, ' ').trim();
927
1037
  }
928
1038
  }
1039
+ }
929
1040
 
930
- // Apache James / Verizon text style with RCPT TO
1041
+ // Apache James / Verizon text style with RCPT TO
1042
+ function matchRcptTo(result, text) {
931
1043
  if (!result.recipient) {
932
1044
  /*
933
1045
  * Match pattern like:
@@ -938,8 +1050,10 @@ async function bounceDetect(sourceStream) {
938
1050
  result.recipient = m[1].trim();
939
1051
  }
940
1052
  }
1053
+ }
941
1054
 
942
- // Generic error code extraction (550, 551, 552, etc.)
1055
+ // Generic error code extraction (550, 551, 552, etc.)
1056
+ function matchGenericSmtpCode(result, text) {
943
1057
  if (!result.response || !result.response.message) {
944
1058
  /*
945
1059
  * Match pattern like:
@@ -961,9 +1075,37 @@ async function bounceDetect(sourceStream) {
961
1075
  }
962
1076
  }
963
1077
  }
1078
+ }
964
1079
 
965
- // Try to find embedded message headers in the bounce body
966
- // Some MTAs include the original headers inline
1080
+ // The text heuristics in the order they run
1081
+ const TEXT_HEURISTICS = [
1082
+ matchHostSaid,
1083
+ matchDeliveryFailedRecipient,
1084
+ matchAffectedRecipients,
1085
+ matchLeadingSmtpReply,
1086
+ matchRecipientBlock,
1087
+ matchUndeliverableMessageTo,
1088
+ matchGoogleLegacy,
1089
+ matchReasonForProblem,
1090
+ matchRemoteHostSaid,
1091
+ matchRecipientHostBlock,
1092
+ matchEximFailedAddresses,
1093
+ matchCouldNotBeDeliveredTo,
1094
+ matchPermanentErrors,
1095
+ matchCarrierError,
1096
+ matchRcptTo,
1097
+ matchGenericSmtpCode
1098
+ ];
1099
+
1100
+ /**
1101
+ * Tries to find embedded message headers in the bounce body
1102
+ * Some MTAs include the original headers inline
1103
+ *
1104
+ * @param {Object} ctx - Detection context
1105
+ * @param {string} text - Bounce text
1106
+ */
1107
+ function readEmbeddedHeaders(ctx, text) {
1108
+ let { result } = ctx;
967
1109
  if (!result.messageId && text) {
968
1110
  // Look for the start of email headers (Received or Return-Path)
969
1111
  let m = text.match(/^(Received|Return-Path):/im);
@@ -977,12 +1119,62 @@ async function bounceDetect(sourceStream) {
977
1119
  result.messageId = entries['message-id'][0].trim();
978
1120
  // Only use these headers if we haven't found headers elsewhere
979
1121
  if (!result.headers) {
980
- parsedMessageHeaders = entries;
1122
+ ctx.parsedMessageHeaders = entries;
981
1123
  }
982
1124
  }
983
1125
  }
984
1126
  }
985
1127
  }
1128
+ }
1129
+
1130
+ /**
1131
+ * Main bounce detection function that analyzes email messages for bounce information
1132
+ *
1133
+ * @async
1134
+ * @param {Stream|Object} sourceStream - Email stream or object with parsed email
1135
+ * @param {Object} [sourceStream.parsed] - Pre-parsed email object (avoids re-parsing)
1136
+ * @returns {Promise<Object>} Bounce detection results
1137
+ * @returns {string} [returns.recipient] - Failed recipient email address
1138
+ * @returns {string} [returns.action] - Bounce action (typically 'failed')
1139
+ * @returns {Object} [returns.response] - SMTP response details
1140
+ * @returns {string} [returns.response.message] - The error message from the remote server
1141
+ * @returns {string} [returns.response.status] - Enhanced status code (X.X.X format)
1142
+ * @returns {string} [returns.response.source] - Source of the diagnostic code
1143
+ * @returns {string} [returns.mta] - Mail server that reported the failure
1144
+ * @returns {string} [returns.queueId] - Queue ID from the sending MTA
1145
+ * @returns {string} [returns.messageId] - Original message ID that bounced
1146
+ * @returns {Object} [returns.messageHeaders] - Headers from the original message
1147
+ */
1148
+ async function bounceDetect(sourceStream) {
1149
+ // Validate input parameter
1150
+ if (!sourceStream) {
1151
+ return {};
1152
+ }
1153
+
1154
+ let parsed = await loadParsedMessage(sourceStream);
1155
+ let ctx = createDetectContext(parsed);
1156
+
1157
+ // Structured sources first, in order of precedence
1158
+ readFailedRecipientsHeader(ctx);
1159
+ readWorkMailReport(ctx);
1160
+ readReportParts(ctx);
1161
+ await readOriginalMessage(ctx);
1162
+ await readZohoOriginalMessage(ctx);
1163
+
1164
+ let result = ctx.result;
1165
+
1166
+ // What the structured parts said, if anything; the text heuristics below only fill gaps, and
1167
+ // only a claim they made is reconsidered at the end
1168
+ let structuredAction = result.action;
1169
+
1170
+ // Extract text content for pattern matching
1171
+ let text = extractHeuristicText(parsed, ctx.attachments);
1172
+
1173
+ for (let heuristic of TEXT_HEURISTICS) {
1174
+ heuristic(result, text);
1175
+ }
1176
+
1177
+ readEmbeddedHeaders(ctx, text);
986
1178
 
987
1179
  // The heuristics above claim 'failed' for any recipient block or quoted reply they recognize,
988
1180
  // but a delay notice has the same shape: a Sendmail-style "THIS IS A WARNING MESSAGE ONLY"
@@ -997,7 +1189,7 @@ async function bounceDetect(sourceStream) {
997
1189
  }
998
1190
 
999
1191
  // Include parsed message headers in the result
1000
- result.messageHeaders = parsedMessageHeaders || null;
1192
+ result.messageHeaders = ctx.parsedMessageHeaders || null;
1001
1193
 
1002
1194
  return result;
1003
1195
  }