emailengine-app 2.81.1 → 2.82.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 (208) hide show
  1. package/.ncurc.js +12 -6
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +52 -0
  4. package/Dockerfile +4 -2
  5. package/bin/emailengine.js +28 -18
  6. package/config/default.toml +0 -5
  7. package/config/test.toml +0 -5
  8. package/data/google-crawlers.json +1 -1
  9. package/encrypt.js +70 -42
  10. package/getswagger.sh +0 -4
  11. package/lib/account/account-state.js +2 -110
  12. package/lib/account/bounce-store-sweep.js +63 -0
  13. package/lib/account/expected-identity.js +1 -1
  14. package/lib/account-assignment.js +207 -0
  15. package/lib/account.js +374 -878
  16. package/lib/api-reference/index.js +2 -3
  17. package/lib/api-reference/schema-tree.js +53 -3
  18. package/lib/api-routes/account-routes.js +18 -29
  19. package/lib/api-routes/blocklist-routes.js +2 -2
  20. package/lib/api-routes/bull-board-routes.js +1 -6
  21. package/lib/api-routes/export-routes.js +2 -22
  22. package/lib/api-routes/gateway-routes.js +5 -14
  23. package/lib/api-routes/index.js +1 -13
  24. package/lib/api-routes/mailbox-routes.js +2 -7
  25. package/lib/api-routes/mcp-oauth-routes.js +2 -1
  26. package/lib/api-routes/mcp-routes.js +7 -7
  27. package/lib/api-routes/message-routes.js +44 -236
  28. package/lib/api-routes/mint-bounds.js +110 -0
  29. package/lib/api-routes/oauth2-app-routes.js +23 -32
  30. package/lib/api-routes/operation-impact.js +1 -1
  31. package/lib/api-routes/outbox-routes.js +2 -2
  32. package/lib/api-routes/permission-map.js +1 -7
  33. package/lib/api-routes/route-helpers.js +11 -5
  34. package/lib/api-routes/settings-routes.js +19 -19
  35. package/lib/api-routes/stats-routes.js +1 -1
  36. package/lib/api-routes/submit-routes.js +17 -18
  37. package/lib/api-routes/template-routes.js +4 -9
  38. package/lib/api-routes/token-routes.js +27 -5
  39. package/lib/api-token-scheme.js +71 -0
  40. package/lib/arf-detect.js +41 -7
  41. package/lib/auth-token.js +44 -24
  42. package/lib/autodetect-imap-settings.js +163 -123
  43. package/lib/bounce-detect.js +25 -16
  44. package/lib/calendar-event.js +78 -0
  45. package/lib/consts.js +51 -5
  46. package/lib/create-imap-client.js +24 -0
  47. package/lib/db.js +76 -17
  48. package/lib/delivery-error.js +2 -1
  49. package/lib/egress-fetch.js +54 -3
  50. package/lib/egress-filter.js +11 -0
  51. package/lib/email-client/api-retry.js +147 -0
  52. package/lib/email-client/base-client.js +628 -615
  53. package/lib/email-client/gmail/gmail-api.js +38 -125
  54. package/lib/email-client/gmail/send-request.js +1 -1
  55. package/lib/email-client/gmail-client.js +170 -84
  56. package/lib/email-client/imap/mailbox.js +244 -535
  57. package/lib/email-client/imap/stale-view.js +109 -0
  58. package/lib/email-client/imap/subconnection.js +46 -9
  59. package/lib/email-client/imap/sync-operations.js +5 -37
  60. package/lib/email-client/imap-client.js +188 -64
  61. package/lib/email-client/message-builder.js +9 -14
  62. package/lib/email-client/notification-handler.js +5 -219
  63. package/lib/email-client/outlook/graph-api.js +147 -126
  64. package/lib/email-client/outlook/send-request.js +10 -4
  65. package/lib/email-client/outlook-client.js +519 -617
  66. package/lib/email-client/smtp-pool-manager.js +3 -2
  67. package/lib/encrypt.js +184 -19
  68. package/lib/enum-descriptions.js +1 -2
  69. package/lib/export.js +144 -41
  70. package/lib/gateway.js +20 -6
  71. package/lib/get-raw-email.js +26 -44
  72. package/lib/handlebars-helpers.js +31 -10
  73. package/lib/imap-proxy-auth.js +13 -29
  74. package/lib/imapproxy/imap-core/README.md +1 -0
  75. package/lib/imapproxy/imap-core/lib/handler/imap-parser.js +12 -0
  76. package/lib/imapproxy/imap-core/lib/imap-command.js +74 -10
  77. package/lib/imapproxy/imap-core/lib/imap-connection.js +9 -1
  78. package/lib/imapproxy/imap-core/lib/imap-server.js +112 -26
  79. package/lib/imapproxy/imap-core/lib/imap-stream.js +41 -1
  80. package/lib/imapproxy/imap-core/lib/imap-tools.js +10 -2
  81. package/lib/imapproxy/imap-core/lib/indexer/indexer.js +4 -2
  82. package/lib/imapproxy/imap-server.js +17 -177
  83. package/lib/imapproxy/proxy-handoff.js +235 -0
  84. package/lib/imapproxy/response-error.js +33 -0
  85. package/lib/imapproxy/upstream-client.js +2 -2
  86. package/lib/license-beacon.js +3 -9
  87. package/lib/llm-pre-process.js +182 -43
  88. package/lib/logger.js +1 -1
  89. package/lib/lua/ee-export-queue-add.lua +39 -0
  90. package/lib/lua/ee-get-idempotency.lua +15 -3
  91. package/lib/lua/ee-release-attempts.lua +23 -0
  92. package/lib/lua/ee-reserve-attempts.lua +42 -0
  93. package/lib/lua/h-set-bigger.lua +12 -2
  94. package/lib/lua/s-list-accounts.lua +6 -3
  95. package/lib/mcp/index.js +1 -2
  96. package/lib/mcp/listen.js +221 -18
  97. package/lib/mcp/oauth.js +44 -5
  98. package/lib/mcp/resources.js +8 -2
  99. package/lib/mcp/tools.js +13 -0
  100. package/lib/message-port-stream.js +64 -6
  101. package/lib/msgpack.js +1 -6
  102. package/lib/oauth/external-account-signer.js +16 -13
  103. package/lib/oauth/gmail.js +22 -20
  104. package/lib/oauth/outlook.js +19 -16
  105. package/lib/oauth/pubsub/google.js +38 -2
  106. package/lib/oauth/scope-checker.js +4 -7
  107. package/lib/oauth/verify-app.js +2 -2
  108. package/lib/oauth2-apps.js +139 -44
  109. package/lib/openapi/build-document.js +1 -1
  110. package/lib/openapi/joi-schema.js +78 -9
  111. package/lib/parse-message.js +21 -0
  112. package/lib/payload-examples-webhooks.json +4 -7
  113. package/lib/pbkdf2-phc.js +101 -0
  114. package/lib/privileged-settings.js +0 -14
  115. package/lib/rate-limit.js +54 -15
  116. package/lib/redis-scan-delete.js +56 -29
  117. package/lib/redis-url.js +3 -1
  118. package/lib/respawn-backoff.js +5 -4
  119. package/lib/response-stream.js +25 -4
  120. package/lib/rewrite-text-nodes.js +27 -40
  121. package/lib/routes-ui.js +0 -5
  122. package/lib/schemas.js +129 -262
  123. package/lib/sentry.js +21 -5
  124. package/lib/settings.js +58 -59
  125. package/lib/smtp-auth.js +6 -2
  126. package/lib/smtp-message-processor.js +28 -7
  127. package/lib/sso.js +7 -3
  128. package/lib/stream-encrypt.js +14 -13
  129. package/lib/swagger-options.js +3 -1
  130. package/lib/tls/provision.js +69 -3
  131. package/lib/tls/store.js +14 -1
  132. package/lib/tools.js +113 -52
  133. package/lib/totp.js +16 -1
  134. package/lib/ui-routes/account-routes.js +27 -63
  135. package/lib/ui-routes/admin-config-routes.js +111 -134
  136. package/lib/ui-routes/admin-entities-routes.js +101 -191
  137. package/lib/ui-routes/ai-options.js +104 -0
  138. package/lib/ui-routes/auth-routes.js +98 -18
  139. package/lib/ui-routes/export-routes.js +3 -23
  140. package/lib/ui-routes/internals-routes.js +12 -9
  141. package/lib/ui-routes/network-config-routes.js +8 -18
  142. package/lib/ui-routes/oauth-config-routes.js +80 -214
  143. package/lib/ui-routes/route-helpers.js +40 -44
  144. package/lib/ui-routes/unsubscribe-routes.js +2 -2
  145. package/lib/utils/decode-headers.js +32 -5
  146. package/lib/utils/header-map.js +62 -1
  147. package/lib/utils/network.js +2 -0
  148. package/lib/web-safe-html.js +77 -4
  149. package/lib/webhook-request.js +9 -1
  150. package/lib/webhook-routing.js +27 -1
  151. package/lib/webhooks.js +120 -43
  152. package/lib/worker-rpc-error.js +43 -2
  153. package/list-generate.js +13 -2
  154. package/package.json +38 -46
  155. package/sbom.json +1 -1
  156. package/scripts/refresh-test-tokens.js +42 -14
  157. package/server.js +340 -336
  158. package/static/css/flyonui.css +1 -1
  159. package/static/css/src/app.tailwind.css +7 -8
  160. package/static/js/ee-client.js +145 -70
  161. package/static/js/ui.js +350 -154
  162. package/static/licenses.html +460 -1861
  163. package/translations/messages.pot +99 -99
  164. package/views/accounts/browse.hbs +10 -4
  165. package/views/config/ai.hbs +49 -41
  166. package/views/config/oauth/app.hbs +2 -1
  167. package/views/dashboard.hbs +18 -16
  168. package/views/layout/app.hbs +0 -22
  169. package/views/layout/login.hbs +2 -1
  170. package/views/partials/filter_editor_js.hbs +4 -3
  171. package/views/partials/side_menu.hbs +0 -4
  172. package/views/partials/ui/account-picker.hbs +6 -32
  173. package/views/partials/ui/model-picker.hbs +31 -0
  174. package/views/partials/ui/pagination.hbs +6 -1
  175. package/views/partials/ui/picker.hbs +47 -0
  176. package/views/unsubscribe.hbs +1 -1
  177. package/workers/api.js +33 -23
  178. package/workers/export.js +55 -60
  179. package/workers/imap.js +134 -47
  180. package/workers/submit.js +3 -1
  181. package/workers/webhooks.js +46 -27
  182. package/.githooks/pre-commit +0 -80
  183. package/.github/CODE_OF_CONDUCT.md +0 -76
  184. package/.github/contributing.md +0 -17
  185. package/.github/dependabot.yml +0 -22
  186. package/.github/docker-smoke-test.sh +0 -61
  187. package/.github/workflows/deploy.yml +0 -215
  188. package/.github/workflows/e2e.yml +0 -55
  189. package/.github/workflows/release.yaml +0 -217
  190. package/.github/workflows/test.yml +0 -307
  191. package/lib/api-routes/chat-routes.js +0 -535
  192. package/lib/append-list.js +0 -63
  193. package/lib/document-store.js +0 -75
  194. package/lib/es.js +0 -757
  195. package/lib/generate-text-preview.js +0 -61
  196. package/lib/imapproxy/imap-core/memory-notifier.js +0 -129
  197. package/lib/lua/h-push.lua +0 -32
  198. package/lib/pre-process.js +0 -196
  199. package/lib/threads.js +0 -155
  200. package/lib/ui-routes/document-store-routes.js +0 -806
  201. package/playwright.config.js +0 -47
  202. package/views/config/document-store/chat.hbs +0 -286
  203. package/views/config/document-store/index.hbs +0 -146
  204. package/views/config/document-store/mappings/index.hbs +0 -108
  205. package/views/config/document-store/mappings/new.hbs +0 -68
  206. package/views/config/document-store/pre-processing/index.hbs +0 -103
  207. package/views/partials/document_store_header.hbs +0 -30
  208. package/workers/documents.js +0 -1128
@@ -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,
@@ -12,7 +13,7 @@ const {
12
13
  mailboxPathHash,
13
14
  getMailboxStatusKey,
14
15
  collectCidReferences,
15
- cidReferenceRegex
16
+ embedCidImages
16
17
  } = require('../../tools');
17
18
  const { samePath } = require('../../utils/mailbox-path');
18
19
  const { connectionNotAvailableError } = require('./connection-errors');
@@ -20,17 +21,17 @@ const msgpack = require('../../msgpack');
20
21
  const he = require('he');
21
22
  const libmime = require('libmime');
22
23
  const settings = require('../../settings');
23
- const { bounceDetect, applyDeliveryReport } = require('../../bounce-detect');
24
+ const { bounceDetect, applyDeliveryReport, PARSER_OPTIONS: DSN_PARSER_OPTIONS } = 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
- const simpleParser = require('mailparser').simpleParser;
29
- const ical = require('ical.js');
29
+ const { parseMessage } = require('../../parse-message');
30
+ const { parseCalendarEvent, sortCalendarAttachments, CALENDAR_CONTENT_TYPES } = require('../../calendar-event');
30
31
  const addressparser = require('nodemailer/lib/addressparser');
31
- const { llmPreProcess } = require('../../llm-pre-process');
32
-
33
- const { getESClient, isDocumentStoreEnabled } = require('../../document-store');
32
+ const { llmPreProcess, summaryFetchHeaders, summaryProvider } = require('../../llm-pre-process');
33
+ const { notificationHeaderFields, narrowHeaders } = require('../../utils/header-map');
34
+ const { isFailedDelivery } = require('../base-client');
34
35
 
35
36
  const {
36
37
  MESSAGE_NEW_NOTIFY,
@@ -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, which sits 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
@@ -88,59 +89,52 @@ function isConnectionGone(err) {
88
89
  }
89
90
 
90
91
  /**
91
- * Compact fingerprint of the STATUS counters stored in the phantom folder
92
- * marker - a parked phantom folder is re-probed as soon as this changes
93
- * @param {Object} status - STATUS response counters
94
- * @returns {String} Fingerprint string
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}
95
100
  */
96
- function phantomStatusKey(status) {
97
- return `${status.uidValidity || ''}:${status.uidNext || 0}:${status.messages || 0}`;
101
+ function keepsArrivalQueued(err) {
102
+ return isConnectionGone(err) || TRANSIENT_NETWORK_CODES.has(err?.code) || err?.code === ImapFlowErrorCode.ETHROTTLE;
98
103
  }
99
104
 
100
- /**
101
- * Headers the notification path needs for its own processing, whatever the notifyHeaders
102
- * setting asks for. They travel in the one BODY.PEEK[HEADER.FIELDS (...)] section that path
103
- * 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.
106
- */
107
- const NOTIFICATION_HEADERS = [
108
- // Auto-reply detection
109
- 'x-autoreply',
110
- 'x-autorespond',
111
- 'auto-submitted',
112
- 'precedence',
113
-
114
- // Threading
115
- 'in-reply-to',
116
- 'references',
117
-
118
- // Bounce and complaint detection
119
- 'content-type',
120
-
121
- // Fallback for an ENVELOPE that carries no usable address. Lark Mail omits the address
122
- // fields outright, and any server can mis-parse a malformed header into a display name
123
- // with no address - see preferAddressList()
124
- 'from',
125
- 'to',
126
- 'cc',
127
- 'bcc'
128
- ];
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;
129
108
 
130
109
  /**
131
- * Builds the header field list for a notification fetch.
132
- *
133
- * @param {String[]|Boolean} configuredHeaders - Headers the notifyHeaders setting asks for
134
- * @returns {String[]} Header names to request from the server
110
+ * Whether a message reference decoded from an API id still names a message in the folder the
111
+ * connection has open. The id carries the UIDVALIDITY it was issued under, and a folder that was
112
+ * recreated (migration, restore) reuses the same path and UIDs for different messages, so an old
113
+ * id would otherwise fetch, flag, move or delete whatever message holds that UID now. References
114
+ * built internally carry no UIDVALIDITY and are not checked, and neither is a server that reports
115
+ * none, as there is nothing to compare against
116
+ * @param {Object} message - Unpacked message reference ({ path, uidValidity, uid })
117
+ * @param {Object} [mailboxInfo] - ImapFlow mailbox object of the folder the lock opened
118
+ * @returns {Boolean} False only when both sides are known and differ
135
119
  */
136
- function notificationHeaderFields(configuredHeaders) {
137
- let fetchHeaders = new Set(Array.isArray(configuredHeaders) ? configuredHeaders : []);
138
-
139
- for (let key of NOTIFICATION_HEADERS) {
140
- fetchHeaders.add(key);
120
+ function matchesOpenUidValidity(message, mailboxInfo) {
121
+ if (!message || message.uidValidity === undefined || message.uidValidity === null || message.uidValidity === false) {
122
+ return true;
141
123
  }
124
+ if (!mailboxInfo || !validUidValidity(mailboxInfo.uidValidity)) {
125
+ return true;
126
+ }
127
+ return mailboxInfo.uidValidity.toString() === message.uidValidity.toString();
128
+ }
142
129
 
143
- return Array.from(fetchHeaders);
130
+ /**
131
+ * Compact fingerprint of the STATUS counters stored in the phantom folder
132
+ * marker - a parked phantom folder is re-probed as soon as this changes
133
+ * @param {Object} status - STATUS response counters
134
+ * @returns {String} Fingerprint string
135
+ */
136
+ function phantomStatusKey(status) {
137
+ return `${status.uidValidity || ''}:${status.uidNext || 0}:${status.messages || 0}`;
144
138
  }
145
139
 
146
140
  // Runs for every address of every message, so both patterns are built once
@@ -933,6 +927,30 @@ class Mailbox {
933
927
  * @param {Object} options - Lock options
934
928
  * @returns {Object} Lock object with release() method
935
929
  */
930
+ /**
931
+ * Takes the mailbox lock for a command on one message and checks that the folder the lock
932
+ * opened is the incarnation the message reference was issued under. Every method that
933
+ * fetches, flags, moves or deletes a message addressed by an API id goes through here, so
934
+ * none of them can skip the check
935
+ * @param {Object} connectionClient - IMAP client to use
936
+ * @param {Object} message - Unpacked message reference ({ path, uidValidity, uid })
937
+ * @param {Object} options - Lock options; `skipLock` when the caller already holds the lock
938
+ * @returns {Object|null} Lock object with release() (a no-op under `skipLock`), or null when
939
+ * the reference was issued for a previous incarnation of this folder
940
+ */
941
+ async lockForMessage(connectionClient, message, options) {
942
+ options = options || {};
943
+
944
+ let lock = options.skipLock ? { release: () => false } : await this.getMailboxLock(connectionClient, { description: options.description });
945
+
946
+ if (!matchesOpenUidValidity(message, connectionClient.mailbox)) {
947
+ lock.release();
948
+ return null;
949
+ }
950
+
951
+ return lock;
952
+ }
953
+
936
954
  async getMailboxLock(connectionClient, options) {
937
955
  connectionClient = connectionClient || this.requireImapClient();
938
956
 
@@ -1103,37 +1121,12 @@ class Mailbox {
1103
1121
  }
1104
1122
 
1105
1123
  /**
1106
- * Processes a deleted message - clears bounces and sends notification
1124
+ * Processes a deleted message and sends the notification
1107
1125
  * @param {Object} messageData - Deleted message data
1108
1126
  */
1109
1127
  async processDeleted(messageData) {
1110
1128
  this.logger.debug({ msg: 'Message deleted', uid: messageData.uid });
1111
1129
 
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
1130
  // Generate packed UID for external reference
1138
1131
  let packedUid = await this.packUidWithLogging(messageData.uid, 'delete');
1139
1132
  if (!packedUid) {
@@ -1196,10 +1189,9 @@ class Mailbox {
1196
1189
  * Processes a new message - fetches details, detects bounces/complaints, sends notifications
1197
1190
  * @param {Object} messageData - Basic message data (uid, flags, etc)
1198
1191
  * @param {Object} options - Processing options
1199
- * @param {Boolean} canSync - Whether message should be synced to document store
1200
1192
  * @param {Object} storedStatus - Current mailbox status
1201
1193
  */
1202
- async processNew(messageData, options, canSync, storedStatus) {
1194
+ async processNew(messageData, options, storedStatus) {
1203
1195
  this.logger.debug({ msg: 'New message', uid: messageData.uid, flags: Array.from(messageData.flags) });
1204
1196
 
1205
1197
  options.skipLock = true;
@@ -1262,22 +1254,9 @@ class Mailbox {
1262
1254
  this.logger.debug({ msg: 'Missing message', status: 'found', uid: messageData.uid, missingRetries, missingDelay });
1263
1255
  }
1264
1256
 
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
1257
  // Check if message is too old to notify about
1279
1258
  let date = new Date(messageInfo.date);
1280
- if (this.connection.notifyFrom && date < this.connection.notifyFrom && !canSync) {
1259
+ if (this.connection.notifyFrom && date < this.connection.notifyFrom) {
1281
1260
  // skip too old messages
1282
1261
  return;
1283
1262
  }
@@ -1300,11 +1279,11 @@ class Mailbox {
1300
1279
  let content;
1301
1280
 
1302
1281
  // Check if this might be an ARF (Abuse Reporting Format) complaint
1303
- if (this.mightBeAComplaint(messageInfo)) {
1282
+ if (this.connection.mightBeAComplaint(messageInfo)) {
1304
1283
  try {
1305
1284
  // Download relevant attachments for ARF parsing
1306
1285
  for (let attachment of messageInfo.attachments || []) {
1307
- if (!['message/feedback-report', 'message/rfc822-headers', 'message/rfc822'].includes(attachment.contentType)) {
1286
+ if (!COMPLAINT_ATTACHMENT_TYPES.includes(attachment.contentType)) {
1308
1287
  continue;
1309
1288
  }
1310
1289
 
@@ -1356,7 +1335,7 @@ class Mailbox {
1356
1335
  }
1357
1336
 
1358
1337
  // Check if this might be a DSN (Delivery Status Notification)
1359
- if (this.mightBeDSNResponse(messageInfo)) {
1338
+ if (this.connection.mightBeDSNResponse(messageInfo)) {
1360
1339
  try {
1361
1340
  let { content: sourceStream } = await this.requireImapClient().download(messageInfo.uid, false, {
1362
1341
  uid: true,
@@ -1364,7 +1343,7 @@ class Mailbox {
1364
1343
  maxBytes: MAX_ALLOWED_DOWNLOAD_SIZE
1365
1344
  });
1366
1345
 
1367
- let parsed = await simpleParser(sourceStream, { keepDeliveryStatus: true });
1346
+ let parsed = await parseMessage(sourceStream, DSN_PARSER_OPTIONS);
1368
1347
  if (parsed) {
1369
1348
  content = { parsed };
1370
1349
  applyDeliveryReport(parsed, messageInfo, this.logger);
@@ -1384,7 +1363,7 @@ class Mailbox {
1384
1363
  }
1385
1364
 
1386
1365
  // Check if this could be a bounce message
1387
- if (this.mightBeABounce(messageInfo)) {
1366
+ if (this.connection.mightBeABounce(messageInfo)) {
1388
1367
  // Parse for bounce information
1389
1368
  try {
1390
1369
  if (!content) {
@@ -1432,11 +1411,7 @@ class Mailbox {
1432
1411
  }
1433
1412
  }
1434
1413
 
1435
- let stored = 0;
1436
- 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
-
1414
+ if (isFailedDelivery(bounce)) {
1440
1415
  bounceNotifyInfo = Object.assign({ bounceMessage: messageInfo.id }, bounce);
1441
1416
 
1442
1417
  messageInfo.isBounce = true;
@@ -1448,8 +1423,7 @@ class Mailbox {
1448
1423
  id: messageInfo.id,
1449
1424
  uid: messageInfo.uid,
1450
1425
  messageId: messageInfo.messageId,
1451
- bounce,
1452
- stored
1426
+ bounce
1453
1427
  });
1454
1428
  }
1455
1429
  } catch (err) {
@@ -1547,21 +1521,9 @@ class Mailbox {
1547
1521
  if (notifyCalendarEvents && messageInfo.attachments && messageInfo.attachments.length) {
1548
1522
  let calendarEventMap = new Map();
1549
1523
 
1550
- // Process text/calendar before application/ics
1551
- let sortCalendarAttachments = (a, b) => {
1552
- if (a.contentType !== b.contentType) {
1553
- if (a.contentType === 'text/calendar') {
1554
- return -1;
1555
- }
1556
- if (b.contentType === 'text/calendar') {
1557
- return 1;
1558
- }
1559
- }
1560
- return a.contentType.localeCompare(b.contentType);
1561
- };
1562
-
1524
+ // Process calendar attachments, text/calendar before application/ics
1563
1525
  for (let attachment of [...messageInfo.attachments].sort(sortCalendarAttachments)) {
1564
- if (['text/calendar', 'application/ics'].includes(attachment.contentType)) {
1526
+ if (CALENDAR_CONTENT_TYPES.includes(attachment.contentType)) {
1565
1527
  // Download calendar attachment if not already loaded
1566
1528
  if (!attachment.content) {
1567
1529
  await this.loadAttachmentContent(messageInfo, attachment, options);
@@ -1569,33 +1531,15 @@ class Mailbox {
1569
1531
  if (attachment.content) {
1570
1532
  let contentBuf = Buffer.from(attachment.content, 'base64');
1571
1533
  try {
1572
- // Parse iCalendar data
1573
- const jcalData = ical.parse(contentBuf.toString());
1574
-
1575
- const comp = new ical.Component(jcalData);
1576
- if (!comp) {
1577
- continue;
1578
- }
1579
-
1580
- const vevent = comp.getFirstSubcomponent('vevent');
1581
- if (!vevent) {
1534
+ const event = parseCalendarEvent(contentBuf);
1535
+ if (!event) {
1582
1536
  continue;
1583
1537
  }
1584
1538
 
1585
- // Extract method (REQUEST, CANCEL, etc.)
1586
- let eventMethodProp = comp.getFirstProperty('method');
1587
- let eventMethodValue = eventMethodProp ? eventMethodProp.getFirstValue() : null;
1588
-
1589
- const event = new ical.Event(vevent);
1590
-
1591
- if (!event || !event.uid) {
1592
- continue;
1593
- }
1594
-
1595
- // Skip duplicate events, prefer ones with filenames
1596
- if (calendarEventMap.has(event.uid)) {
1539
+ // Skip if we already processed this event
1540
+ if (calendarEventMap.has(event.eventId)) {
1597
1541
  if (attachment.filename) {
1598
- let existingEntry = calendarEventMap.get(event.uid);
1542
+ let existingEntry = calendarEventMap.get(event.eventId);
1599
1543
  if (!existingEntry.filename) {
1600
1544
  // inject filename
1601
1545
  existingEntry.filename = attachment.filename;
@@ -1604,31 +1548,20 @@ class Mailbox {
1604
1548
  continue;
1605
1549
  }
1606
1550
 
1607
- // Extract timezone information
1608
- let timezone;
1609
- const vtz = comp.getFirstSubcomponent('vtimezone');
1610
- if (vtz) {
1611
- const tz = new ical.Timezone(vtz);
1612
- timezone = tz && tz.tzid;
1613
- }
1614
-
1615
- let startDate = event.startDate && event.startDate.toJSDate();
1616
- let endDate = event.endDate && event.endDate.toJSDate();
1617
-
1618
- // Store parsed calendar event
1551
+ // Store calendar event data
1619
1552
  calendarEventMap.set(
1620
- event.uid,
1553
+ event.eventId,
1621
1554
  filterEmptyObjectValues({
1622
- eventId: event.uid,
1555
+ eventId: event.eventId,
1623
1556
  attachment: attachment.id,
1624
- method: attachment.method || eventMethodValue || null,
1557
+ method: attachment.method || event.method || null,
1625
1558
 
1626
- summary: event.summary || null,
1627
- description: event.description || null,
1628
- timezone: timezone || null,
1629
- startDate: startDate ? startDate.toISOString() : null,
1630
- endDate: endDate ? endDate.toISOString() : null,
1631
- organizer: event.organizer && typeof event.organizer === 'string' ? event.organizer : null,
1559
+ summary: event.summary,
1560
+ description: event.description,
1561
+ timezone: event.timezone,
1562
+ startDate: event.startDate,
1563
+ endDate: event.endDate,
1564
+ organizer: event.organizer,
1632
1565
 
1633
1566
  filename: attachment.filename,
1634
1567
  contentType: attachment.contentType,
@@ -1672,102 +1605,19 @@ class Mailbox {
1672
1605
  !(messageInfo.labels && messageInfo.labels.includes('\\Sent')) &&
1673
1606
  !!(await this.connection.redis.pfadd(this.getSeenMessagesKey(), messageInfo.emailId || messageInfo.messageId));
1674
1607
 
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
- // Process with LLM if configured for inbox messages
1684
- if (messageInfo.messageSpecialUse === '\\Inbox' && (!this.connection.notifyFrom || messageData.internalDate >= this.connection.notifyFrom)) {
1608
+ // Process with LLM if configured for inbox messages. A message with no text part has no
1609
+ // text object at all, and nothing to summarize
1610
+ if (messageInfo.messageSpecialUse === '\\Inbox' && (messageInfo.text?.plain || messageInfo.text?.html)) {
1685
1611
  let messageData = Object.assign({ account: this.connection.account }, messageInfo);
1686
1612
 
1687
- let canUseLLM = await llmPreProcess.run(messageData);
1688
-
1689
- if (canUseLLM && (messageInfo.text.plain || messageInfo.text.html)) {
1690
- // Generate AI summary if enabled
1691
- if (canUseLLM.generateEmailSummary) {
1692
- try {
1693
- messageInfo.summary = await this.connection.call({
1694
- cmd: 'generateSummary',
1695
- data: {
1696
- message: {
1697
- headers: Object.keys(messageInfo.headers || {}).map(key => ({ key, value: [].concat(messageInfo.headers[key] || []) })),
1698
- attachments: messageInfo.attachments,
1699
- from: messageInfo.from,
1700
- subject: messageInfo.subject,
1701
- text: messageInfo.text.plain,
1702
- html: messageInfo.text.html
1703
- },
1704
- account: this.connection.account
1705
- },
1706
- timeout: 2 * 60 * 1000
1707
- });
1708
-
1709
- if (messageInfo.summary) {
1710
- // Clean up summary output
1711
- for (let key of Object.keys(messageInfo.summary)) {
1712
- // remove meta keys from output
1713
- if (key.charAt(0) === '_' || messageInfo.summary[key] === '') {
1714
- delete messageInfo.summary[key];
1715
- }
1716
- if (key === 'riskAssessment') {
1717
- messageInfo.riskAssessment = messageInfo.summary.riskAssessment;
1718
- delete messageInfo.summary.riskAssessment;
1719
- }
1720
- }
1721
-
1722
- this.logger.trace({ msg: 'Fetched summary from OpenAI', summary: messageInfo.summary });
1723
- }
1724
-
1725
- await this.connection.redis.del(`${REDIS_PREFIX}:openai:error`);
1726
- } catch (err) {
1727
- await this.connection.redis.set(
1728
- `${REDIS_PREFIX}:openai:error`,
1729
- JSON.stringify({
1730
- message: err.message,
1731
- code: err.code,
1732
- statusCode: err.statusCode,
1733
- created: Date.now()
1734
- })
1735
- );
1736
- this.logger.error({ msg: 'Failed to fetch summary from OpenAI', err });
1737
- }
1738
- }
1739
-
1740
- // Generate embeddings if enabled
1741
- if (canUseLLM.generateEmbeddings) {
1742
- try {
1743
- messageInfo.embeddings = await this.connection.call({
1744
- cmd: 'generateEmbeddings',
1745
- data: {
1746
- message: {
1747
- headers: Object.keys(messageInfo.headers || {}).map(key => ({ key, value: [].concat(messageInfo.headers[key] || []) })),
1748
- attachments: messageInfo.attachments,
1749
- from: messageInfo.from,
1750
- subject: messageInfo.subject,
1751
- text: messageInfo.text.plain,
1752
- html: messageInfo.text.html
1753
- },
1754
- account: this.connection.account
1755
- },
1756
- timeout: 2 * 60 * 1000
1757
- });
1758
- } catch (err) {
1759
- await this.connection.redis.set(
1760
- `${REDIS_PREFIX}:openai:error`,
1761
- JSON.stringify({
1762
- message: err.message,
1763
- code: err.code,
1764
- statusCode: err.statusCode,
1765
- time: Date.now()
1766
- })
1767
- );
1768
- this.logger.error({ msg: 'Failed to fetch embeddings from OpenAI', err });
1769
- }
1770
- }
1613
+ if (await llmPreProcess.run(messageData)) {
1614
+ await llmPreProcess.summarize(messageInfo, {
1615
+ call: this.connection.call,
1616
+ redis: this.connection.redis,
1617
+ account: this.connection.account,
1618
+ provider: summaryProvider(this.connection),
1619
+ logger: this.logger
1620
+ });
1771
1621
  }
1772
1622
  }
1773
1623
 
@@ -1793,8 +1643,8 @@ class Mailbox {
1793
1643
  content: attachment.content || null
1794
1644
  });
1795
1645
 
1796
- if (attachment.content) {
1797
- // already downloaded in a previous step
1646
+ if (attachment.content || (attachment.encodedSize && attachment.encodedSize > MAX_INLINE_ATTACHMENT_SIZE)) {
1647
+ // already downloaded in a previous step, or skipped there as too large to inline
1798
1648
  continue;
1799
1649
  }
1800
1650
 
@@ -1835,84 +1685,69 @@ class Mailbox {
1835
1685
  }
1836
1686
  }
1837
1687
 
1838
- // Replace CID references with data URIs
1839
- messageInfo.text.html = messageInfo.text.html.replace(cidReferenceRegex(), (fullMatch, cidMatch) => {
1840
- if (attachmentList.has(cidMatch)) {
1841
- let { attachment, content } = attachmentList.get(cidMatch);
1842
- if (content) {
1843
- return `data:${attachment.contentType || 'application/octet-stream'};base64,${content}`;
1844
- }
1845
- }
1846
- return fullMatch;
1847
- });
1688
+ // Replace CID references with data URIs. The web safe copy is what webhooks
1689
+ // deliver in place of the HTML, so it gets the same treatment
1690
+ const embedImages = html =>
1691
+ embedCidImages(html, contentId => {
1692
+ let { attachment, content } = attachmentList.get(contentId) || {};
1693
+ return content && { contentType: attachment.contentType, content };
1694
+ });
1695
+
1696
+ messageInfo.text.html = embedImages(messageInfo.text.html);
1697
+ if (messageInfo.text._generatedHtml) {
1698
+ messageInfo.text._generatedHtml = embedImages(messageInfo.text._generatedHtml);
1699
+ }
1848
1700
  }
1849
1701
  }
1850
1702
  }
1851
1703
 
1704
+ // Narrow the headers to what the caller asked for. This runs last: the complaint, delivery
1705
+ // report and bounce checks and the AI summary above read headers fetched for them (see
1706
+ // notificationHeaderFields()) that the published payload may not carry
1707
+ if (options.headers) {
1708
+ narrowHeaders(messageInfo, requestedHeaders);
1709
+ }
1710
+
1852
1711
  // Send new message notification
1853
- await this.connection.notify(this, MESSAGE_NEW_NOTIFY, messageInfo, {
1854
- skipWebhook: this.connection.notifyFrom && date < this.connection.notifyFrom,
1855
- canSync
1856
- });
1712
+ await this.connection.notify(this, MESSAGE_NEW_NOTIFY, messageInfo);
1857
1713
 
1858
1714
  // Send bounce notification if detected
1859
1715
  if (bounceNotifyInfo) {
1860
- let { index, client } = await getESClient(this.logger);
1861
- if (client) {
1862
- // Find the originating message this bounce applies for
1863
- let searchResult = await client.search({
1864
- index,
1865
- size: 20,
1866
- from: 0,
1867
- query: {
1868
- bool: {
1869
- must: [
1870
- {
1871
- term: {
1872
- account: this.connection.account
1873
- }
1874
- },
1875
- {
1876
- term: {
1877
- messageId: bounceNotifyInfo.messageId
1878
- }
1879
- }
1880
- ]
1881
- }
1882
- },
1883
- sort: { uid: 'desc' },
1884
- _source_excludes: 'headers,text'
1885
- });
1886
-
1887
- if (searchResult && searchResult.hits && searchResult.hits.hits && searchResult.hits.hits.length) {
1888
- // Prefer sent messages, then earliest message
1889
- let message = searchResult.hits.hits
1890
- .sort((a, b) => {
1891
- if (a._source.specialUse === '\\Sent') {
1892
- return -1;
1893
- }
1894
- if (b._source.specialUse === '\\Sent') {
1895
- return 1;
1896
- }
1897
- return new Date(a._source.date || a._source.created) - new Date(b._source.date || b._source.created);
1898
- })
1899
- .shift()._source;
1900
- bounceNotifyInfo = Object.assign({ id: message.id }, bounceNotifyInfo);
1901
- }
1902
- }
1903
-
1904
1716
  // send bounce notification _after_ bounce email notification
1905
- await this.connection.notify(false, EMAIL_BOUNCE_NOTIFY, bounceNotifyInfo, {
1906
- skipWebhook: this.connection.notifyFrom && date < this.connection.notifyFrom
1907
- });
1717
+ await this.connection.notify(false, EMAIL_BOUNCE_NOTIFY, bounceNotifyInfo);
1908
1718
  }
1909
1719
 
1910
1720
  // Send complaint notification if detected
1911
1721
  if (complaintNotifyInfo) {
1912
1722
  // send complaint notification _after_ complaint email notification
1913
- await this.connection.notify(false, EMAIL_COMPLAINT_NOTIFY, complaintNotifyInfo, {
1914
- skipWebhook: this.connection.notifyFrom && date < this.connection.notifyFrom
1915
- });
1723
+ await this.connection.notify(false, EMAIL_COMPLAINT_NOTIFY, complaintNotifyInfo);
1724
+ }
1725
+ }
1726
+
1727
+ /**
1728
+ * Counts the passes a queued arrival was throttled on. Kept in memory: a restart starting the
1729
+ * count over only costs a few more passes
1730
+ * @param {string} rawMember - The queued entry
1731
+ * @returns {number} Passes so far, this one included
1732
+ */
1733
+ countThrottledArrival(rawMember) {
1734
+ this.throttledArrivals = this.throttledArrivals || new Map();
1735
+ const passes = (this.throttledArrivals.get(rawMember) || 0) + 1;
1736
+ this.throttledArrivals.set(rawMember, passes);
1737
+ return passes;
1738
+ }
1739
+
1740
+ /**
1741
+ * Sets the special use of the folder a message belongs to: the mailbox's own, or for Gmail
1742
+ * over IMAP the label, since the message lives in All Mail there. Junk wins over Inbox
1743
+ * @param {Object} messageInfo - Formatted message, updated in place
1744
+ */
1745
+ setMessageSpecialUse(messageInfo) {
1746
+ for (let specialUseTag of ['\\Junk', '\\Sent', '\\Trash', '\\Inbox', '\\Drafts']) {
1747
+ if (this.listingEntry.specialUse === specialUseTag || (messageInfo.labels && messageInfo.labels.includes(specialUseTag))) {
1748
+ messageInfo.messageSpecialUse = specialUseTag;
1749
+ break;
1750
+ }
1916
1751
  }
1917
1752
  }
1918
1753
 
@@ -2046,9 +1881,6 @@ class Mailbox {
2046
1881
  result.isAutoReply = true;
2047
1882
  }
2048
1883
 
2049
- // Fetch associated bounce information
2050
- await this.connection.attachBounces(result);
2051
-
2052
1884
  return result;
2053
1885
  }
2054
1886
 
@@ -2198,18 +2030,11 @@ class Mailbox {
2198
2030
  async publishSyncedEvents(storedStatus) {
2199
2031
  let messageFetchOptions = {};
2200
2032
 
2201
- let documentStoreEnabled = await isDocumentStoreEnabled();
2033
+ const { notifyText, notifyTextSize, notifyHeaders: notifyHeadersSetting } = await settings.getMulti('notifyText', 'notifyTextSize', 'notifyHeaders');
2202
2034
 
2203
2035
  // Configure text fetching
2204
- let notifyText = await settings.get('notifyText');
2205
- if (documentStoreEnabled || notifyText) {
2036
+ if (notifyText) {
2206
2037
  messageFetchOptions.textType = '*';
2207
- let notifyTextSize = await settings.get('notifyTextSize');
2208
-
2209
- if (documentStoreEnabled && notifyTextSize) {
2210
- // Ensure at least 1MB for document store
2211
- notifyTextSize = Math.max(notifyTextSize, 1024 * 1024);
2212
- }
2213
2038
 
2214
2039
  if (notifyTextSize) {
2215
2040
  messageFetchOptions.maxBytes = notifyTextSize;
@@ -2217,15 +2042,20 @@ class Mailbox {
2217
2042
  }
2218
2043
 
2219
2044
  // Configure header fetching
2220
- let notifyHeaders = (await settings.get('notifyHeaders')) || [];
2221
- if (documentStoreEnabled || notifyHeaders.length) {
2222
- messageFetchOptions.headers = notifyHeaders.includes('*') || documentStoreEnabled ? true : notifyHeaders.length ? notifyHeaders : false;
2045
+ let notifyHeaders = notifyHeadersSetting || [];
2046
+ if (notifyHeaders.length) {
2047
+ messageFetchOptions.headers = notifyHeaders.includes('*') ? true : notifyHeaders;
2223
2048
  }
2224
2049
 
2225
- // Also request the headers this path needs for its own processing. Skipped when the
2226
- // setting already asks for every header, since there is nothing left to add
2050
+ // Also request the headers this path needs for its own processing, and the summary's
2051
+ // while summaries are on and this folder can hold Inbox messages. Skipped when the setting
2052
+ // already asks for every header, since there is nothing left to add
2227
2053
  if (messageFetchOptions.headers !== true) {
2228
- messageFetchOptions.fetchHeaders = notificationHeaderFields(messageFetchOptions.headers);
2054
+ const summaryHeaders =
2055
+ (this.isAllMail || this.listingEntry.specialUse === '\\Inbox') && (await llmPreProcess.getPreProcessHandler())
2056
+ ? summaryFetchHeaders(summaryProvider(this.connection))
2057
+ : [];
2058
+ messageFetchOptions.fetchHeaders = notificationHeaderFields(messageFetchOptions.headers, summaryHeaders);
2229
2059
  }
2230
2060
 
2231
2061
  // Peek-then-remove: read entries without removing so that connection errors
@@ -2249,24 +2079,26 @@ class Mailbox {
2249
2079
  continue;
2250
2080
  }
2251
2081
 
2252
- // Check if message should be synced to document store
2253
- let canSync = documentStoreEnabled && (!this.connection.syncFrom || messageData.internalDate >= this.connection.syncFrom);
2254
-
2255
- if (this.connection.notifyFrom && messageData.internalDate < this.connection.notifyFrom && !canSync) {
2082
+ if (this.connection.notifyFrom && messageData.internalDate < this.connection.notifyFrom) {
2256
2083
  await this.connection.redis.zrem(notificationsKey, rawMember);
2257
2084
  continue;
2258
2085
  }
2259
2086
 
2260
2087
  try {
2261
- await this.processNew(messageData, messageFetchOptions, canSync, storedStatus);
2088
+ await this.processNew(messageData, messageFetchOptions, storedStatus);
2262
2089
  await this.connection.redis.zrem(notificationsKey, rawMember);
2090
+ this.throttledArrivals?.delete(rawMember);
2263
2091
  } catch (err) {
2264
2092
  // Wider than the enrichment steps on purpose: this is the last chance to keep a
2265
2093
  // message that failed on a transient network error, and it is not a step that can
2266
2094
  // 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;
2095
+ if (keepsArrivalQueued(err)) {
2096
+ const throttledPasses = err.code === ImapFlowErrorCode.ETHROTTLE ? this.countThrottledArrival(rawMember) : 0;
2097
+ if (throttledPasses <= MAX_THROTTLED_ARRIVAL_PASSES) {
2098
+ throw err;
2099
+ }
2269
2100
  }
2101
+ this.throttledArrivals?.delete(rawMember);
2270
2102
  await this.connection.redis.zrem(notificationsKey, rawMember);
2271
2103
  this.logger.error({ msg: 'Failed to process new message', uid, id: messageData.id, err });
2272
2104
  }
@@ -2495,9 +2327,10 @@ class Mailbox {
2495
2327
 
2496
2328
  let hasMore = false;
2497
2329
 
2498
- let lock;
2499
- if (!options.skipLock) {
2500
- lock = await this.getMailboxLock(connectionClient, { description: `Get text: ${message.uid}` });
2330
+ let lock = await this.lockForMessage(connectionClient, message, { description: `Get text: ${message.uid}`, skipLock: options.skipLock });
2331
+ if (!lock) {
2332
+ // issued for a previous incarnation of this folder
2333
+ return false;
2501
2334
  }
2502
2335
 
2503
2336
  try {
@@ -2572,13 +2405,19 @@ class Mailbox {
2572
2405
 
2573
2406
  const connectionClient = await this.connection.getImapConnection(connectionOptions);
2574
2407
 
2575
- let lock = await this.getMailboxLock(connectionClient, { description: `Get attachment: ${message.uid}/${part}` });
2408
+ let lock = await this.lockForMessage(connectionClient, message, { description: `Get attachment: ${message.uid}/${part}` });
2409
+ if (!lock) {
2410
+ // issued for a previous incarnation of this folder
2411
+ return false;
2412
+ }
2576
2413
 
2577
2414
  let streaming = false;
2578
2415
  try {
2579
2416
  let { meta, content } = await connectionClient.download(message.uid, part, {
2580
2417
  uid: true,
2581
- maxBytes: Math.min(options.maxBytes || 0, MAX_ALLOWED_DOWNLOAD_SIZE),
2418
+ // Infinity, not 0, for an absent limit: ImapFlow reads 0 as "no limit", which
2419
+ // turned the cap below off for every caller that did not pass one
2420
+ maxBytes: Math.min(options.maxBytes || Infinity, MAX_ALLOWED_DOWNLOAD_SIZE),
2582
2421
  chunkSize: options.chunkSize
2583
2422
  });
2584
2423
 
@@ -2635,7 +2474,8 @@ class Mailbox {
2635
2474
  }
2636
2475
 
2637
2476
  /**
2638
- * Fetches complete message details
2477
+ * Fetches complete message details. Every message it returns carries `messageSpecialUse`,
2478
+ * which the arrival checks in processNew() and the fetch-time bounce check gate on
2639
2479
  * @param {Object} message - Message object with uid
2640
2480
  * @param {Object} options - Fetch options
2641
2481
  * @param {Object} connectionOptions - Connection options
@@ -2648,9 +2488,10 @@ class Mailbox {
2648
2488
 
2649
2489
  const connectionClient = await this.connection.getImapConnection(connectionOptions);
2650
2490
 
2651
- let lock;
2652
- if (!options.skipLock) {
2653
- lock = await this.getMailboxLock(connectionClient, { description: `Get message: ${message.uid}` });
2491
+ let lock = await this.lockForMessage(connectionClient, message, { description: `Get message: ${message.uid}`, skipLock: options.skipLock });
2492
+ if (!lock) {
2493
+ // issued for a previous incarnation of this folder
2494
+ return false;
2654
2495
  }
2655
2496
 
2656
2497
  try {
@@ -2694,6 +2535,28 @@ class Mailbox {
2694
2535
  }
2695
2536
 
2696
2537
  messageInfo = await this.getMessageInfo(messageData, true);
2538
+
2539
+ if (messageInfo) {
2540
+ // Add mailbox special use information
2541
+ if (this.listingEntry.specialUse) {
2542
+ messageInfo.specialUse = this.listingEntry.specialUse;
2543
+ }
2544
+ this.setMessageSpecialUse(messageInfo);
2545
+
2546
+ // The details route asks for the content check; its download rides on this lock
2547
+ // instead of taking one of its own, which on the primary connection is a SELECT
2548
+ // away from the watched folder and back
2549
+ if (options.detectBounce) {
2550
+ await this.connection.detectBounce(messageInfo, async () => {
2551
+ let { content } = await connectionClient.download(message.uid, false, {
2552
+ uid: true,
2553
+ maxBytes: MAX_ALLOWED_DOWNLOAD_SIZE,
2554
+ chunkSize: options.chunkSize
2555
+ });
2556
+ return content;
2557
+ });
2558
+ }
2559
+ }
2697
2560
  } finally {
2698
2561
  if (lock) {
2699
2562
  lock.release();
@@ -2792,14 +2655,9 @@ class Mailbox {
2792
2655
  }
2793
2656
 
2794
2657
  // Replace CID references with data URIs
2795
- messageInfo.text.html = messageInfo.text.html.replace(cidReferenceRegex(), (fullMatch, cidMatch) => {
2796
- if (attachmentList.has(cidMatch)) {
2797
- let { attachment } = attachmentList.get(cidMatch);
2798
- if (attachment.content) {
2799
- return `data:${attachment.contentType || 'application/octet-stream'};base64,${attachment.content.toString('base64')}`;
2800
- }
2801
- }
2802
- return fullMatch;
2658
+ messageInfo.text.html = embedCidImages(messageInfo.text.html, contentId => {
2659
+ let { attachment } = attachmentList.get(contentId) || {};
2660
+ return attachment?.content && { contentType: attachment.contentType, content: attachment.content.toString('base64') };
2803
2661
  });
2804
2662
  }
2805
2663
  } catch (err) {
@@ -2812,19 +2670,6 @@ class Mailbox {
2812
2670
  }
2813
2671
  }
2814
2672
 
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
2673
  return messageInfo;
2829
2674
  }
2830
2675
 
@@ -2840,7 +2685,11 @@ class Mailbox {
2840
2685
 
2841
2686
  const connectionClient = await this.connection.getImapConnection(connectionOptions);
2842
2687
 
2843
- let lock = await this.getMailboxLock(connectionClient, { description: `Update message: ${message.uid}` });
2688
+ let lock = await this.lockForMessage(connectionClient, message, { description: `Update message: ${message.uid}` });
2689
+ if (!lock) {
2690
+ // issued for a previous incarnation of this folder
2691
+ return false;
2692
+ }
2844
2693
 
2845
2694
  try {
2846
2695
  let result = {};
@@ -2995,7 +2844,11 @@ class Mailbox {
2995
2844
 
2996
2845
  const connectionClient = await this.connection.getImapConnection(connectionOptions);
2997
2846
 
2998
- let lock = await this.getMailboxLock(connectionClient, { description: `Move message: ${message.uid} to: ${target.path}` });
2847
+ let lock = await this.lockForMessage(connectionClient, message, { description: `Move message: ${message.uid} to: ${target.path}` });
2848
+ if (!lock) {
2849
+ // issued for a previous incarnation of this folder
2850
+ return false;
2851
+ }
2999
2852
 
3000
2853
  try {
3001
2854
  let result = {};
@@ -3068,7 +2921,11 @@ class Mailbox {
3068
2921
  async deleteMessage(message, force, connectionOptions) {
3069
2922
  const connectionClient = await this.connection.getImapConnection(connectionOptions);
3070
2923
 
3071
- let lock = await this.getMailboxLock(connectionClient, { description: `Delete message: ${message.uid}` });
2924
+ let lock = await this.lockForMessage(connectionClient, message, { description: `Delete message: ${message.uid}` });
2925
+ if (!lock) {
2926
+ // issued for a previous incarnation of this folder
2927
+ return false;
2928
+ }
3072
2929
 
3073
2930
  try {
3074
2931
  let result = {};
@@ -3328,154 +3185,6 @@ class Mailbox {
3328
3185
  }
3329
3186
  }
3330
3187
 
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
3188
  /**
3480
3189
  * Decodes a cursor string for pagination
3481
3190
  * @param {String} cursorStr - Base64-encoded cursor string
@@ -3537,4 +3246,4 @@ class Mailbox {
3537
3246
 
3538
3247
  module.exports.Mailbox = Mailbox;
3539
3248
  // Exported for tests: publishSyncedEvents() cannot be driven without a live connection
3540
- module.exports.notificationHeaderFields = notificationHeaderFields;
3249
+ module.exports.keepsArrivalQueued = keepsArrivalQueued;