emailengine-app 2.81.2 → 2.82.1

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 (226) hide show
  1. package/.ncurc.js +33 -10
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +71 -0
  4. package/DOCKER_DEPLOYMENT.md +13 -12
  5. package/Dockerfile +2 -0
  6. package/bin/emailengine.js +105 -25
  7. package/config/default.toml +0 -5
  8. package/config/test.toml +0 -5
  9. package/data/google-crawlers.json +1 -1
  10. package/encrypt.js +70 -42
  11. package/getswagger.sh +0 -4
  12. package/lib/account/account-state.js +2 -110
  13. package/lib/account/expected-identity.js +1 -1
  14. package/lib/account-assignment.js +138 -1
  15. package/lib/account.js +289 -869
  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-binding.js +58 -0
  19. package/lib/api-routes/account-routes.js +65 -37
  20. package/lib/api-routes/behavior-notes.js +4 -0
  21. package/lib/api-routes/blocklist-routes.js +2 -2
  22. package/lib/api-routes/bull-board-routes.js +1 -6
  23. package/lib/api-routes/export-routes.js +2 -22
  24. package/lib/api-routes/gateway-routes.js +15 -16
  25. package/lib/api-routes/index.js +1 -13
  26. package/lib/api-routes/mailbox-routes.js +2 -7
  27. package/lib/api-routes/mcp-oauth-routes.js +2 -1
  28. package/lib/api-routes/mcp-routes.js +7 -7
  29. package/lib/api-routes/message-routes.js +50 -238
  30. package/lib/api-routes/mint-bounds.js +110 -0
  31. package/lib/api-routes/oauth2-app-routes.js +23 -32
  32. package/lib/api-routes/operation-impact.js +1 -1
  33. package/lib/api-routes/outbox-routes.js +3 -3
  34. package/lib/api-routes/permission-map.js +1 -7
  35. package/lib/api-routes/route-helpers.js +11 -5
  36. package/lib/api-routes/settings-routes.js +20 -21
  37. package/lib/api-routes/stats-routes.js +1 -1
  38. package/lib/api-routes/submit-routes.js +17 -18
  39. package/lib/api-routes/template-routes.js +4 -9
  40. package/lib/api-routes/token-routes.js +28 -6
  41. package/lib/api-token-scheme.js +71 -0
  42. package/lib/arf-detect.js +33 -6
  43. package/lib/auth-token.js +44 -24
  44. package/lib/autodetect-imap-settings.js +305 -123
  45. package/lib/bounce-detect.js +25 -16
  46. package/lib/calendar-event.js +78 -0
  47. package/lib/consts.js +54 -5
  48. package/lib/create-imap-client.js +24 -0
  49. package/lib/db.js +77 -30
  50. package/lib/delivery-error.js +70 -2
  51. package/lib/egress-fetch.js +54 -3
  52. package/lib/egress-filter.js +11 -0
  53. package/lib/email-client/api-retry.js +147 -0
  54. package/lib/email-client/base-client.js +383 -536
  55. package/lib/email-client/credential-errors.js +21 -5
  56. package/lib/email-client/gmail/gmail-api.js +38 -125
  57. package/lib/email-client/gmail/send-request.js +1 -1
  58. package/lib/email-client/gmail-client.js +77 -51
  59. package/lib/email-client/imap/mailbox.js +158 -324
  60. package/lib/email-client/imap/stale-view.js +109 -0
  61. package/lib/email-client/imap/subconnection.js +46 -9
  62. package/lib/email-client/imap/sync-operations.js +5 -37
  63. package/lib/email-client/imap-client.js +190 -65
  64. package/lib/email-client/message-builder.js +50 -25
  65. package/lib/email-client/notification-handler.js +5 -219
  66. package/lib/email-client/outlook/graph-api.js +147 -126
  67. package/lib/email-client/outlook/send-request.js +10 -4
  68. package/lib/email-client/outlook-client.js +389 -463
  69. package/lib/email-client/smtp-pool-manager.js +3 -2
  70. package/lib/encrypt.js +184 -19
  71. package/lib/enum-descriptions.js +6 -3
  72. package/lib/export.js +141 -41
  73. package/lib/gateway.js +25 -6
  74. package/lib/get-raw-email.js +26 -44
  75. package/lib/get-secret.js +1 -21
  76. package/lib/handlebars-helpers.js +31 -10
  77. package/lib/imap-proxy-auth.js +13 -29
  78. package/lib/imapproxy/imap-core/README.md +1 -0
  79. package/lib/imapproxy/imap-core/lib/handler/imap-parser.js +12 -0
  80. package/lib/imapproxy/imap-core/lib/imap-command.js +74 -10
  81. package/lib/imapproxy/imap-core/lib/imap-connection.js +9 -1
  82. package/lib/imapproxy/imap-core/lib/imap-server.js +112 -26
  83. package/lib/imapproxy/imap-core/lib/imap-stream.js +41 -1
  84. package/lib/imapproxy/imap-core/lib/imap-tools.js +10 -2
  85. package/lib/imapproxy/imap-core/lib/indexer/indexer.js +4 -2
  86. package/lib/imapproxy/imap-server.js +17 -177
  87. package/lib/imapproxy/proxy-handoff.js +235 -0
  88. package/lib/imapproxy/response-error.js +33 -0
  89. package/lib/imapproxy/upstream-client.js +2 -2
  90. package/lib/license-beacon.js +3 -9
  91. package/lib/llm-pre-process.js +182 -43
  92. package/lib/logger.js +1 -1
  93. package/lib/lua/ee-export-queue-add.lua +39 -0
  94. package/lib/lua/ee-get-idempotency.lua +15 -3
  95. package/lib/lua/ee-release-attempts.lua +23 -0
  96. package/lib/lua/ee-reserve-attempts.lua +42 -0
  97. package/lib/lua/h-set-bigger.lua +12 -2
  98. package/lib/lua/s-list-accounts.lua +6 -3
  99. package/lib/mcp/index.js +1 -2
  100. package/lib/mcp/listen.js +221 -18
  101. package/lib/mcp/oauth.js +44 -5
  102. package/lib/mcp/resources.js +8 -2
  103. package/lib/mcp/tools.js +108 -36
  104. package/lib/message-port-stream.js +64 -6
  105. package/lib/oauth/external-account-signer.js +16 -13
  106. package/lib/oauth/gmail.js +64 -32
  107. package/lib/oauth/mail-ru.js +24 -17
  108. package/lib/oauth/outlook.js +53 -40
  109. package/lib/oauth/pubsub/google.js +38 -2
  110. package/lib/oauth/scope-checker.js +39 -8
  111. package/lib/oauth/scope-list.js +55 -0
  112. package/lib/oauth/token-fetch.js +47 -0
  113. package/lib/oauth/verify-app.js +2 -2
  114. package/lib/oauth2-apps.js +154 -90
  115. package/lib/openapi/build-document.js +1 -1
  116. package/lib/openapi/joi-schema.js +78 -9
  117. package/lib/outbox.js +2 -7
  118. package/lib/parse-message.js +21 -0
  119. package/lib/payload-examples-webhooks.json +4 -7
  120. package/lib/pbkdf2-phc.js +101 -0
  121. package/lib/privileged-settings.js +0 -14
  122. package/lib/queue-retention.js +4 -2
  123. package/lib/rate-limit.js +54 -15
  124. package/lib/read-env-value.js +33 -2
  125. package/lib/redis-scan-delete.js +56 -29
  126. package/lib/redis-url.js +3 -1
  127. package/lib/respawn-backoff.js +5 -4
  128. package/lib/response-stream.js +25 -4
  129. package/lib/rewrite-text-nodes.js +27 -40
  130. package/lib/routes-ui.js +0 -5
  131. package/lib/schemas.js +180 -253
  132. package/lib/sentry.js +21 -5
  133. package/lib/settings.js +58 -59
  134. package/lib/smtp-auth.js +6 -2
  135. package/lib/smtp-message-processor.js +28 -7
  136. package/lib/sso.js +7 -3
  137. package/lib/stream-encrypt.js +14 -13
  138. package/lib/swagger-options.js +3 -1
  139. package/lib/tls/provision.js +69 -3
  140. package/lib/tls/store.js +14 -1
  141. package/lib/token-audit-log.js +3 -2
  142. package/lib/tools.js +114 -53
  143. package/lib/totp.js +16 -1
  144. package/lib/ui-routes/account-routes.js +67 -70
  145. package/lib/ui-routes/admin-config-routes.js +111 -134
  146. package/lib/ui-routes/admin-entities-routes.js +101 -191
  147. package/lib/ui-routes/ai-options.js +104 -0
  148. package/lib/ui-routes/auth-routes.js +98 -18
  149. package/lib/ui-routes/export-routes.js +3 -23
  150. package/lib/ui-routes/internals-routes.js +12 -9
  151. package/lib/ui-routes/network-config-routes.js +8 -18
  152. package/lib/ui-routes/oauth-config-routes.js +83 -228
  153. package/lib/ui-routes/route-helpers.js +63 -67
  154. package/lib/ui-routes/special-use-paths.js +33 -0
  155. package/lib/ui-routes/unsubscribe-routes.js +2 -2
  156. package/lib/utils/decode-headers.js +32 -5
  157. package/lib/utils/header-map.js +62 -1
  158. package/lib/utils/network.js +11 -17
  159. package/lib/web-safe-html.js +77 -4
  160. package/lib/webhook-request.js +9 -1
  161. package/lib/webhook-routing.js +27 -1
  162. package/lib/webhooks.js +120 -43
  163. package/lib/worker-rpc-error.js +43 -2
  164. package/list-generate.js +13 -2
  165. package/package.json +38 -46
  166. package/sbom.json +1 -1
  167. package/scripts/refresh-test-tokens.js +42 -14
  168. package/server.js +338 -292
  169. package/setup-production.sh +16 -7
  170. package/static/css/flyonui.css +1 -1
  171. package/static/css/src/app.tailwind.css +7 -8
  172. package/static/js/ee-client.js +145 -70
  173. package/static/js/ui.js +350 -154
  174. package/static/licenses.html +349 -1740
  175. package/translations/messages.pot +129 -111
  176. package/views/account-workspace-error.hbs +30 -0
  177. package/views/accounts/account.hbs +9 -4
  178. package/views/accounts/browse.hbs +10 -4
  179. package/views/accounts/edit.hbs +11 -2
  180. package/views/config/ai.hbs +49 -41
  181. package/views/config/oauth/app.hbs +2 -1
  182. package/views/dashboard.hbs +18 -16
  183. package/views/internals/index.hbs +1 -1
  184. package/views/layout/app.hbs +0 -22
  185. package/views/layout/login.hbs +2 -1
  186. package/views/partials/filter_editor_js.hbs +4 -3
  187. package/views/partials/gmail_api_scopes.hbs +16 -0
  188. package/views/partials/oauth_form.hbs +67 -94
  189. package/views/partials/oauth_pubsub_app_select.hbs +43 -0
  190. package/views/partials/scope_info.hbs +14 -23
  191. package/views/partials/side_menu.hbs +0 -4
  192. package/views/partials/ui/account-picker.hbs +6 -32
  193. package/views/partials/ui/model-picker.hbs +31 -0
  194. package/views/partials/ui/pagination.hbs +6 -1
  195. package/views/partials/ui/picker.hbs +47 -0
  196. package/views/unsubscribe.hbs +1 -1
  197. package/workers/api.js +82 -47
  198. package/workers/export.js +55 -60
  199. package/workers/imap.js +132 -49
  200. package/workers/submit.js +5 -6
  201. package/workers/webhooks.js +46 -27
  202. package/.githooks/pre-commit +0 -80
  203. package/.github/CODE_OF_CONDUCT.md +0 -76
  204. package/.github/contributing.md +0 -17
  205. package/.github/dependabot.yml +0 -22
  206. package/.github/docker-smoke-test.sh +0 -61
  207. package/.github/workflows/deploy.yml +0 -215
  208. package/.github/workflows/e2e.yml +0 -55
  209. package/.github/workflows/release.yaml +0 -217
  210. package/.github/workflows/test.yml +0 -307
  211. package/lib/api-routes/chat-routes.js +0 -535
  212. package/lib/document-store.js +0 -75
  213. package/lib/es.js +0 -757
  214. package/lib/generate-text-preview.js +0 -61
  215. package/lib/imapproxy/imap-core/memory-notifier.js +0 -129
  216. package/lib/pre-process.js +0 -196
  217. package/lib/threads.js +0 -155
  218. package/lib/ui-routes/document-store-routes.js +0 -806
  219. package/playwright.config.js +0 -47
  220. package/views/config/document-store/chat.hbs +0 -286
  221. package/views/config/document-store/index.hbs +0 -146
  222. package/views/config/document-store/mappings/index.hbs +0 -108
  223. package/views/config/document-store/mappings/new.hbs +0 -68
  224. package/views/config/document-store/pre-processing/index.hbs +0 -103
  225. package/views/partials/document_store_header.hbs +0 -30
  226. package/workers/documents.js +0 -1128
@@ -13,7 +13,7 @@ const {
13
13
  mailboxPathHash,
14
14
  getMailboxStatusKey,
15
15
  collectCidReferences,
16
- cidReferenceRegex
16
+ embedCidImages
17
17
  } = require('../../tools');
18
18
  const { samePath } = require('../../utils/mailbox-path');
19
19
  const { connectionNotAvailableError } = require('./connection-errors');
@@ -21,17 +21,17 @@ const msgpack = require('../../msgpack');
21
21
  const he = require('he');
22
22
  const libmime = require('libmime');
23
23
  const settings = require('../../settings');
24
- const { bounceDetect, applyDeliveryReport } = require('../../bounce-detect');
24
+ const { bounceDetect, applyDeliveryReport, PARSER_OPTIONS: DSN_PARSER_OPTIONS } = require('../../bounce-detect');
25
25
  const { decodeHeaders } = require('../../utils/decode-headers');
26
26
  const { isUnsafeKey } = require('../../utils/unsafe-key');
27
27
  const { arfDetect, camelCaseComplaint, COMPLAINT_ATTACHMENT_TYPES } = require('../../arf-detect');
28
28
  const { messageWebSafeHtml } = require('../../web-safe-html');
29
- const simpleParser = require('mailparser').simpleParser;
30
- const ical = require('ical.js');
29
+ const { parseMessage } = require('../../parse-message');
30
+ const { parseCalendarEvent, sortCalendarAttachments, CALENDAR_CONTENT_TYPES } = require('../../calendar-event');
31
31
  const addressparser = require('nodemailer/lib/addressparser');
32
- const { llmPreProcess } = require('../../llm-pre-process');
33
-
34
- 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');
35
35
 
36
36
  const {
37
37
  MESSAGE_NEW_NOTIFY,
@@ -77,7 +77,7 @@ const {
77
77
  *
78
78
  * Work earlier in the pass does run twice when a later step re-queues the message: the seen-messages
79
79
  * HyperLogLog (so the retry reports `seemsLikeNew: false`, an informational field) and, the
80
- * expensive one, the LLM summary and embeddings, which sit just before the inline-image download.
80
+ * expensive one, the LLM summary, which sits just before the inline-image download.
81
81
  * All of it needs the connection to
82
82
  * die in one narrow window, and a re-queue was already reachable from every error thrown outside
83
83
  * these catches
@@ -106,6 +106,27 @@ function keepsArrivalQueued(err) {
106
106
  // throttles every time cannot hold up every later arrival in its folder
107
107
  const MAX_THROTTLED_ARRIVAL_PASSES = 5;
108
108
 
109
+ /**
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
119
+ */
120
+ function matchesOpenUidValidity(message, mailboxInfo) {
121
+ if (!message || message.uidValidity === undefined || message.uidValidity === null || message.uidValidity === false) {
122
+ return true;
123
+ }
124
+ if (!mailboxInfo || !validUidValidity(mailboxInfo.uidValidity)) {
125
+ return true;
126
+ }
127
+ return mailboxInfo.uidValidity.toString() === message.uidValidity.toString();
128
+ }
129
+
109
130
  /**
110
131
  * Compact fingerprint of the STATUS counters stored in the phantom folder
111
132
  * marker - a parked phantom folder is re-probed as soon as this changes
@@ -116,52 +137,6 @@ function phantomStatusKey(status) {
116
137
  return `${status.uidValidity || ''}:${status.uidNext || 0}:${status.messages || 0}`;
117
138
  }
118
139
 
119
- /**
120
- * Headers the notification path needs for its own processing, whatever the notifyHeaders
121
- * setting asks for. They travel in the one BODY.PEEK[HEADER.FIELDS (...)] section that path
122
- * already requests, and are filtered back down before anything is published: processNew()
123
- * narrows the exposed set to what the caller asked for once its own checks have run, and
124
- * Webhooks.formatPayload() drops the block entirely unless notifyHeaders names something.
125
- */
126
- const NOTIFICATION_HEADERS = [
127
- // Auto-reply detection
128
- 'x-autoreply',
129
- 'x-autorespond',
130
- 'auto-submitted',
131
- 'precedence',
132
-
133
- // Threading
134
- 'in-reply-to',
135
- 'references',
136
-
137
- // Bounce and complaint detection
138
- 'content-type',
139
-
140
- // Fallback for an ENVELOPE that carries no usable address. Lark Mail omits the address
141
- // fields outright, and any server can mis-parse a malformed header into a display name
142
- // with no address - see preferAddressList()
143
- 'from',
144
- 'to',
145
- 'cc',
146
- 'bcc'
147
- ];
148
-
149
- /**
150
- * Builds the header field list for a notification fetch.
151
- *
152
- * @param {String[]|Boolean} configuredHeaders - Headers the notifyHeaders setting asks for
153
- * @returns {String[]} Header names to request from the server
154
- */
155
- function notificationHeaderFields(configuredHeaders) {
156
- let fetchHeaders = new Set(Array.isArray(configuredHeaders) ? configuredHeaders : []);
157
-
158
- for (let key of NOTIFICATION_HEADERS) {
159
- fetchHeaders.add(key);
160
- }
161
-
162
- return Array.from(fetchHeaders);
163
- }
164
-
165
140
  // Runs for every address of every message, so both patterns are built once
166
141
  const HAS_WHITESPACE = /\s/;
167
142
  // An addr-spec that carries its whitespace legally, inside a quoted local part
@@ -952,6 +927,30 @@ class Mailbox {
952
927
  * @param {Object} options - Lock options
953
928
  * @returns {Object} Lock object with release() method
954
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
+
955
954
  async getMailboxLock(connectionClient, options) {
956
955
  connectionClient = connectionClient || this.requireImapClient();
957
956
 
@@ -1190,10 +1189,9 @@ class Mailbox {
1190
1189
  * Processes a new message - fetches details, detects bounces/complaints, sends notifications
1191
1190
  * @param {Object} messageData - Basic message data (uid, flags, etc)
1192
1191
  * @param {Object} options - Processing options
1193
- * @param {Boolean} canSync - Whether message should be synced to document store
1194
1192
  * @param {Object} storedStatus - Current mailbox status
1195
1193
  */
1196
- async processNew(messageData, options, canSync, storedStatus) {
1194
+ async processNew(messageData, options, storedStatus) {
1197
1195
  this.logger.debug({ msg: 'New message', uid: messageData.uid, flags: Array.from(messageData.flags) });
1198
1196
 
1199
1197
  options.skipLock = true;
@@ -1258,7 +1256,7 @@ class Mailbox {
1258
1256
 
1259
1257
  // Check if message is too old to notify about
1260
1258
  let date = new Date(messageInfo.date);
1261
- if (this.connection.notifyFrom && date < this.connection.notifyFrom && !canSync) {
1259
+ if (this.connection.notifyFrom && date < this.connection.notifyFrom) {
1262
1260
  // skip too old messages
1263
1261
  return;
1264
1262
  }
@@ -1345,7 +1343,7 @@ class Mailbox {
1345
1343
  maxBytes: MAX_ALLOWED_DOWNLOAD_SIZE
1346
1344
  });
1347
1345
 
1348
- let parsed = await simpleParser(sourceStream, { keepDeliveryStatus: true });
1346
+ let parsed = await parseMessage(sourceStream, DSN_PARSER_OPTIONS);
1349
1347
  if (parsed) {
1350
1348
  content = { parsed };
1351
1349
  applyDeliveryReport(parsed, messageInfo, this.logger);
@@ -1413,7 +1411,7 @@ class Mailbox {
1413
1411
  }
1414
1412
  }
1415
1413
 
1416
- if (bounce.action && bounce.recipient && bounce.messageId) {
1414
+ if (isFailedDelivery(bounce)) {
1417
1415
  bounceNotifyInfo = Object.assign({ bounceMessage: messageInfo.id }, bounce);
1418
1416
 
1419
1417
  messageInfo.isBounce = true;
@@ -1442,21 +1440,6 @@ class Mailbox {
1442
1440
  }
1443
1441
  }
1444
1442
 
1445
- // Narrow the headers to what the caller asked for. This runs after the complaint, delivery
1446
- // report and bounce checks above: they read headers fetched for them (see
1447
- // notificationHeaderFields()) that the published payload may not carry
1448
- if (options.headers && Array.isArray(requestedHeaders)) {
1449
- let filteredHeaders = {};
1450
- for (let key of Object.keys(messageInfo.headers)) {
1451
- if (requestedHeaders.includes(key)) {
1452
- filteredHeaders[key] = messageInfo.headers[key];
1453
- }
1454
- }
1455
- messageInfo.headers = filteredHeaders;
1456
- } else if (options.headers && requestedHeaders === false) {
1457
- delete messageInfo.headers;
1458
- }
1459
-
1460
1443
  // Resolve Gmail category for inbox messages
1461
1444
  if (
1462
1445
  this.connection.imapClient?.capabilities?.has('X-GM-EXT-1') &&
@@ -1538,21 +1521,9 @@ class Mailbox {
1538
1521
  if (notifyCalendarEvents && messageInfo.attachments && messageInfo.attachments.length) {
1539
1522
  let calendarEventMap = new Map();
1540
1523
 
1541
- // Process text/calendar before application/ics
1542
- let sortCalendarAttachments = (a, b) => {
1543
- if (a.contentType !== b.contentType) {
1544
- if (a.contentType === 'text/calendar') {
1545
- return -1;
1546
- }
1547
- if (b.contentType === 'text/calendar') {
1548
- return 1;
1549
- }
1550
- }
1551
- return a.contentType.localeCompare(b.contentType);
1552
- };
1553
-
1524
+ // Process calendar attachments, text/calendar before application/ics
1554
1525
  for (let attachment of [...messageInfo.attachments].sort(sortCalendarAttachments)) {
1555
- if (['text/calendar', 'application/ics'].includes(attachment.contentType)) {
1526
+ if (CALENDAR_CONTENT_TYPES.includes(attachment.contentType)) {
1556
1527
  // Download calendar attachment if not already loaded
1557
1528
  if (!attachment.content) {
1558
1529
  await this.loadAttachmentContent(messageInfo, attachment, options);
@@ -1560,33 +1531,15 @@ class Mailbox {
1560
1531
  if (attachment.content) {
1561
1532
  let contentBuf = Buffer.from(attachment.content, 'base64');
1562
1533
  try {
1563
- // Parse iCalendar data
1564
- const jcalData = ical.parse(contentBuf.toString());
1565
-
1566
- const comp = new ical.Component(jcalData);
1567
- if (!comp) {
1534
+ const event = parseCalendarEvent(contentBuf);
1535
+ if (!event) {
1568
1536
  continue;
1569
1537
  }
1570
1538
 
1571
- const vevent = comp.getFirstSubcomponent('vevent');
1572
- if (!vevent) {
1573
- continue;
1574
- }
1575
-
1576
- // Extract method (REQUEST, CANCEL, etc.)
1577
- let eventMethodProp = comp.getFirstProperty('method');
1578
- let eventMethodValue = eventMethodProp ? eventMethodProp.getFirstValue() : null;
1579
-
1580
- const event = new ical.Event(vevent);
1581
-
1582
- if (!event || !event.uid) {
1583
- continue;
1584
- }
1585
-
1586
- // Skip duplicate events, prefer ones with filenames
1587
- if (calendarEventMap.has(event.uid)) {
1539
+ // Skip if we already processed this event
1540
+ if (calendarEventMap.has(event.eventId)) {
1588
1541
  if (attachment.filename) {
1589
- let existingEntry = calendarEventMap.get(event.uid);
1542
+ let existingEntry = calendarEventMap.get(event.eventId);
1590
1543
  if (!existingEntry.filename) {
1591
1544
  // inject filename
1592
1545
  existingEntry.filename = attachment.filename;
@@ -1595,31 +1548,20 @@ class Mailbox {
1595
1548
  continue;
1596
1549
  }
1597
1550
 
1598
- // Extract timezone information
1599
- let timezone;
1600
- const vtz = comp.getFirstSubcomponent('vtimezone');
1601
- if (vtz) {
1602
- const tz = new ical.Timezone(vtz);
1603
- timezone = tz && tz.tzid;
1604
- }
1605
-
1606
- let startDate = event.startDate && event.startDate.toJSDate();
1607
- let endDate = event.endDate && event.endDate.toJSDate();
1608
-
1609
- // Store parsed calendar event
1551
+ // Store calendar event data
1610
1552
  calendarEventMap.set(
1611
- event.uid,
1553
+ event.eventId,
1612
1554
  filterEmptyObjectValues({
1613
- eventId: event.uid,
1555
+ eventId: event.eventId,
1614
1556
  attachment: attachment.id,
1615
- method: attachment.method || eventMethodValue || null,
1557
+ method: attachment.method || event.method || null,
1616
1558
 
1617
- summary: event.summary || null,
1618
- description: event.description || null,
1619
- timezone: timezone || null,
1620
- startDate: startDate ? startDate.toISOString() : null,
1621
- endDate: endDate ? endDate.toISOString() : null,
1622
- 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,
1623
1565
 
1624
1566
  filename: attachment.filename,
1625
1567
  contentType: attachment.contentType,
@@ -1663,94 +1605,19 @@ class Mailbox {
1663
1605
  !(messageInfo.labels && messageInfo.labels.includes('\\Sent')) &&
1664
1606
  !!(await this.connection.redis.pfadd(this.getSeenMessagesKey(), messageInfo.emailId || messageInfo.messageId));
1665
1607
 
1666
- // Process with LLM if configured for inbox messages
1667
- 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)) {
1668
1611
  let messageData = Object.assign({ account: this.connection.account }, messageInfo);
1669
1612
 
1670
- let canUseLLM = await llmPreProcess.run(messageData);
1671
-
1672
- if (canUseLLM && (messageInfo.text.plain || messageInfo.text.html)) {
1673
- // Generate AI summary if enabled
1674
- if (canUseLLM.generateEmailSummary) {
1675
- try {
1676
- messageInfo.summary = await this.connection.call({
1677
- cmd: 'generateSummary',
1678
- data: {
1679
- message: {
1680
- headers: Object.keys(messageInfo.headers || {}).map(key => ({ key, value: [].concat(messageInfo.headers[key] || []) })),
1681
- attachments: messageInfo.attachments,
1682
- from: messageInfo.from,
1683
- subject: messageInfo.subject,
1684
- text: messageInfo.text.plain,
1685
- html: messageInfo.text.html
1686
- },
1687
- account: this.connection.account
1688
- },
1689
- timeout: 2 * 60 * 1000
1690
- });
1691
-
1692
- if (messageInfo.summary) {
1693
- // Clean up summary output
1694
- for (let key of Object.keys(messageInfo.summary)) {
1695
- // remove meta keys from output
1696
- if (key.charAt(0) === '_' || messageInfo.summary[key] === '') {
1697
- delete messageInfo.summary[key];
1698
- }
1699
- if (key === 'riskAssessment') {
1700
- messageInfo.riskAssessment = messageInfo.summary.riskAssessment;
1701
- delete messageInfo.summary.riskAssessment;
1702
- }
1703
- }
1704
-
1705
- this.logger.trace({ msg: 'Fetched summary from OpenAI', summary: messageInfo.summary });
1706
- }
1707
-
1708
- await this.connection.redis.del(`${REDIS_PREFIX}:openai:error`);
1709
- } catch (err) {
1710
- await this.connection.redis.set(
1711
- `${REDIS_PREFIX}:openai:error`,
1712
- JSON.stringify({
1713
- message: err.message,
1714
- code: err.code,
1715
- statusCode: err.statusCode,
1716
- created: Date.now()
1717
- })
1718
- );
1719
- this.logger.error({ msg: 'Failed to fetch summary from OpenAI', err });
1720
- }
1721
- }
1722
-
1723
- // Generate embeddings if enabled
1724
- if (canUseLLM.generateEmbeddings) {
1725
- try {
1726
- messageInfo.embeddings = await this.connection.call({
1727
- cmd: 'generateEmbeddings',
1728
- data: {
1729
- message: {
1730
- headers: Object.keys(messageInfo.headers || {}).map(key => ({ key, value: [].concat(messageInfo.headers[key] || []) })),
1731
- attachments: messageInfo.attachments,
1732
- from: messageInfo.from,
1733
- subject: messageInfo.subject,
1734
- text: messageInfo.text.plain,
1735
- html: messageInfo.text.html
1736
- },
1737
- account: this.connection.account
1738
- },
1739
- timeout: 2 * 60 * 1000
1740
- });
1741
- } catch (err) {
1742
- await this.connection.redis.set(
1743
- `${REDIS_PREFIX}:openai:error`,
1744
- JSON.stringify({
1745
- message: err.message,
1746
- code: err.code,
1747
- statusCode: err.statusCode,
1748
- time: Date.now()
1749
- })
1750
- );
1751
- this.logger.error({ msg: 'Failed to fetch embeddings from OpenAI', err });
1752
- }
1753
- }
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
+ });
1754
1621
  }
1755
1622
  }
1756
1623
 
@@ -1776,8 +1643,8 @@ class Mailbox {
1776
1643
  content: attachment.content || null
1777
1644
  });
1778
1645
 
1779
- if (attachment.content) {
1780
- // 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
1781
1648
  continue;
1782
1649
  }
1783
1650
 
@@ -1818,84 +1685,42 @@ class Mailbox {
1818
1685
  }
1819
1686
  }
1820
1687
 
1821
- // Replace CID references with data URIs
1822
- messageInfo.text.html = messageInfo.text.html.replace(cidReferenceRegex(), (fullMatch, cidMatch) => {
1823
- if (attachmentList.has(cidMatch)) {
1824
- let { attachment, content } = attachmentList.get(cidMatch);
1825
- if (content) {
1826
- return `data:${attachment.contentType || 'application/octet-stream'};base64,${content}`;
1827
- }
1828
- }
1829
- return fullMatch;
1830
- });
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
+ }
1831
1700
  }
1832
1701
  }
1833
1702
  }
1834
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
+
1835
1711
  // Send new message notification
1836
- await this.connection.notify(this, MESSAGE_NEW_NOTIFY, messageInfo, {
1837
- skipWebhook: this.connection.notifyFrom && date < this.connection.notifyFrom,
1838
- canSync
1839
- });
1712
+ await this.connection.notify(this, MESSAGE_NEW_NOTIFY, messageInfo);
1840
1713
 
1841
1714
  // Send bounce notification if detected
1842
1715
  if (bounceNotifyInfo) {
1843
- let { index, client } = await getESClient(this.logger);
1844
- if (client) {
1845
- // Find the originating message this bounce applies for
1846
- let searchResult = await client.search({
1847
- index,
1848
- size: 20,
1849
- from: 0,
1850
- query: {
1851
- bool: {
1852
- must: [
1853
- {
1854
- term: {
1855
- account: this.connection.account
1856
- }
1857
- },
1858
- {
1859
- term: {
1860
- messageId: bounceNotifyInfo.messageId
1861
- }
1862
- }
1863
- ]
1864
- }
1865
- },
1866
- sort: { uid: 'desc' },
1867
- _source_excludes: 'headers,text'
1868
- });
1869
-
1870
- if (searchResult && searchResult.hits && searchResult.hits.hits && searchResult.hits.hits.length) {
1871
- // Prefer sent messages, then earliest message
1872
- let message = searchResult.hits.hits
1873
- .sort((a, b) => {
1874
- if (a._source.specialUse === '\\Sent') {
1875
- return -1;
1876
- }
1877
- if (b._source.specialUse === '\\Sent') {
1878
- return 1;
1879
- }
1880
- return new Date(a._source.date || a._source.created) - new Date(b._source.date || b._source.created);
1881
- })
1882
- .shift()._source;
1883
- bounceNotifyInfo = Object.assign({ id: message.id }, bounceNotifyInfo);
1884
- }
1885
- }
1886
-
1887
1716
  // send bounce notification _after_ bounce email notification
1888
- await this.connection.notify(false, EMAIL_BOUNCE_NOTIFY, bounceNotifyInfo, {
1889
- skipWebhook: this.connection.notifyFrom && date < this.connection.notifyFrom
1890
- });
1717
+ await this.connection.notify(false, EMAIL_BOUNCE_NOTIFY, bounceNotifyInfo);
1891
1718
  }
1892
1719
 
1893
1720
  // Send complaint notification if detected
1894
1721
  if (complaintNotifyInfo) {
1895
1722
  // send complaint notification _after_ complaint email notification
1896
- await this.connection.notify(false, EMAIL_COMPLAINT_NOTIFY, complaintNotifyInfo, {
1897
- skipWebhook: this.connection.notifyFrom && date < this.connection.notifyFrom
1898
- });
1723
+ await this.connection.notify(false, EMAIL_COMPLAINT_NOTIFY, complaintNotifyInfo);
1899
1724
  }
1900
1725
  }
1901
1726
 
@@ -2205,18 +2030,11 @@ class Mailbox {
2205
2030
  async publishSyncedEvents(storedStatus) {
2206
2031
  let messageFetchOptions = {};
2207
2032
 
2208
- let documentStoreEnabled = await isDocumentStoreEnabled();
2033
+ const { notifyText, notifyTextSize, notifyHeaders: notifyHeadersSetting } = await settings.getMulti('notifyText', 'notifyTextSize', 'notifyHeaders');
2209
2034
 
2210
2035
  // Configure text fetching
2211
- let notifyText = await settings.get('notifyText');
2212
- if (documentStoreEnabled || notifyText) {
2036
+ if (notifyText) {
2213
2037
  messageFetchOptions.textType = '*';
2214
- let notifyTextSize = await settings.get('notifyTextSize');
2215
-
2216
- if (documentStoreEnabled && notifyTextSize) {
2217
- // Ensure at least 1MB for document store
2218
- notifyTextSize = Math.max(notifyTextSize, 1024 * 1024);
2219
- }
2220
2038
 
2221
2039
  if (notifyTextSize) {
2222
2040
  messageFetchOptions.maxBytes = notifyTextSize;
@@ -2224,15 +2042,20 @@ class Mailbox {
2224
2042
  }
2225
2043
 
2226
2044
  // Configure header fetching
2227
- let notifyHeaders = (await settings.get('notifyHeaders')) || [];
2228
- if (documentStoreEnabled || notifyHeaders.length) {
2229
- 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;
2230
2048
  }
2231
2049
 
2232
- // Also request the headers this path needs for its own processing. Skipped when the
2233
- // 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
2234
2053
  if (messageFetchOptions.headers !== true) {
2235
- 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);
2236
2059
  }
2237
2060
 
2238
2061
  // Peek-then-remove: read entries without removing so that connection errors
@@ -2256,16 +2079,13 @@ class Mailbox {
2256
2079
  continue;
2257
2080
  }
2258
2081
 
2259
- // Check if message should be synced to document store
2260
- let canSync = documentStoreEnabled && (!this.connection.syncFrom || messageData.internalDate >= this.connection.syncFrom);
2261
-
2262
- if (this.connection.notifyFrom && messageData.internalDate < this.connection.notifyFrom && !canSync) {
2082
+ if (this.connection.notifyFrom && messageData.internalDate < this.connection.notifyFrom) {
2263
2083
  await this.connection.redis.zrem(notificationsKey, rawMember);
2264
2084
  continue;
2265
2085
  }
2266
2086
 
2267
2087
  try {
2268
- await this.processNew(messageData, messageFetchOptions, canSync, storedStatus);
2088
+ await this.processNew(messageData, messageFetchOptions, storedStatus);
2269
2089
  await this.connection.redis.zrem(notificationsKey, rawMember);
2270
2090
  this.throttledArrivals?.delete(rawMember);
2271
2091
  } catch (err) {
@@ -2507,9 +2327,10 @@ class Mailbox {
2507
2327
 
2508
2328
  let hasMore = false;
2509
2329
 
2510
- let lock;
2511
- if (!options.skipLock) {
2512
- 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;
2513
2334
  }
2514
2335
 
2515
2336
  try {
@@ -2584,13 +2405,19 @@ class Mailbox {
2584
2405
 
2585
2406
  const connectionClient = await this.connection.getImapConnection(connectionOptions);
2586
2407
 
2587
- 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
+ }
2588
2413
 
2589
2414
  let streaming = false;
2590
2415
  try {
2591
2416
  let { meta, content } = await connectionClient.download(message.uid, part, {
2592
2417
  uid: true,
2593
- 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),
2594
2421
  chunkSize: options.chunkSize
2595
2422
  });
2596
2423
 
@@ -2661,9 +2488,10 @@ class Mailbox {
2661
2488
 
2662
2489
  const connectionClient = await this.connection.getImapConnection(connectionOptions);
2663
2490
 
2664
- let lock;
2665
- if (!options.skipLock) {
2666
- 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;
2667
2495
  }
2668
2496
 
2669
2497
  try {
@@ -2827,14 +2655,9 @@ class Mailbox {
2827
2655
  }
2828
2656
 
2829
2657
  // Replace CID references with data URIs
2830
- messageInfo.text.html = messageInfo.text.html.replace(cidReferenceRegex(), (fullMatch, cidMatch) => {
2831
- if (attachmentList.has(cidMatch)) {
2832
- let { attachment } = attachmentList.get(cidMatch);
2833
- if (attachment.content) {
2834
- return `data:${attachment.contentType || 'application/octet-stream'};base64,${attachment.content.toString('base64')}`;
2835
- }
2836
- }
2837
- 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') };
2838
2661
  });
2839
2662
  }
2840
2663
  } catch (err) {
@@ -2862,7 +2685,11 @@ class Mailbox {
2862
2685
 
2863
2686
  const connectionClient = await this.connection.getImapConnection(connectionOptions);
2864
2687
 
2865
- 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
+ }
2866
2693
 
2867
2694
  try {
2868
2695
  let result = {};
@@ -3017,7 +2844,11 @@ class Mailbox {
3017
2844
 
3018
2845
  const connectionClient = await this.connection.getImapConnection(connectionOptions);
3019
2846
 
3020
- 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
+ }
3021
2852
 
3022
2853
  try {
3023
2854
  let result = {};
@@ -3090,7 +2921,11 @@ class Mailbox {
3090
2921
  async deleteMessage(message, force, connectionOptions) {
3091
2922
  const connectionClient = await this.connection.getImapConnection(connectionOptions);
3092
2923
 
3093
- 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
+ }
3094
2929
 
3095
2930
  try {
3096
2931
  let result = {};
@@ -3411,5 +3246,4 @@ class Mailbox {
3411
3246
 
3412
3247
  module.exports.Mailbox = Mailbox;
3413
3248
  // Exported for tests: publishSyncedEvents() cannot be driven without a live connection
3414
- module.exports.notificationHeaderFields = notificationHeaderFields;
3415
3249
  module.exports.keepsArrivalQueued = keepsArrivalQueued;