emailengine-app 2.81.2 → 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 (204) hide show
  1. package/.ncurc.js +12 -11
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +27 -0
  4. package/Dockerfile +2 -0
  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/expected-identity.js +1 -1
  13. package/lib/account-assignment.js +138 -1
  14. package/lib/account.js +254 -859
  15. package/lib/api-reference/index.js +2 -3
  16. package/lib/api-reference/schema-tree.js +53 -3
  17. package/lib/api-routes/account-routes.js +18 -29
  18. package/lib/api-routes/blocklist-routes.js +2 -2
  19. package/lib/api-routes/bull-board-routes.js +1 -6
  20. package/lib/api-routes/export-routes.js +2 -22
  21. package/lib/api-routes/gateway-routes.js +5 -14
  22. package/lib/api-routes/index.js +1 -13
  23. package/lib/api-routes/mailbox-routes.js +2 -7
  24. package/lib/api-routes/mcp-oauth-routes.js +2 -1
  25. package/lib/api-routes/mcp-routes.js +7 -7
  26. package/lib/api-routes/message-routes.js +40 -235
  27. package/lib/api-routes/mint-bounds.js +110 -0
  28. package/lib/api-routes/oauth2-app-routes.js +23 -32
  29. package/lib/api-routes/operation-impact.js +1 -1
  30. package/lib/api-routes/outbox-routes.js +2 -2
  31. package/lib/api-routes/permission-map.js +1 -7
  32. package/lib/api-routes/route-helpers.js +11 -5
  33. package/lib/api-routes/settings-routes.js +19 -19
  34. package/lib/api-routes/stats-routes.js +1 -1
  35. package/lib/api-routes/submit-routes.js +17 -18
  36. package/lib/api-routes/template-routes.js +4 -9
  37. package/lib/api-routes/token-routes.js +27 -5
  38. package/lib/api-token-scheme.js +71 -0
  39. package/lib/arf-detect.js +33 -6
  40. package/lib/auth-token.js +44 -24
  41. package/lib/autodetect-imap-settings.js +163 -123
  42. package/lib/bounce-detect.js +25 -16
  43. package/lib/calendar-event.js +78 -0
  44. package/lib/consts.js +42 -5
  45. package/lib/create-imap-client.js +24 -0
  46. package/lib/db.js +76 -11
  47. package/lib/delivery-error.js +2 -1
  48. package/lib/egress-fetch.js +54 -3
  49. package/lib/egress-filter.js +11 -0
  50. package/lib/email-client/api-retry.js +147 -0
  51. package/lib/email-client/base-client.js +377 -523
  52. package/lib/email-client/gmail/gmail-api.js +38 -125
  53. package/lib/email-client/gmail/send-request.js +1 -1
  54. package/lib/email-client/gmail-client.js +76 -50
  55. package/lib/email-client/imap/mailbox.js +158 -324
  56. package/lib/email-client/imap/stale-view.js +109 -0
  57. package/lib/email-client/imap/subconnection.js +46 -9
  58. package/lib/email-client/imap/sync-operations.js +5 -37
  59. package/lib/email-client/imap-client.js +188 -64
  60. package/lib/email-client/message-builder.js +9 -14
  61. package/lib/email-client/notification-handler.js +5 -219
  62. package/lib/email-client/outlook/graph-api.js +147 -126
  63. package/lib/email-client/outlook/send-request.js +10 -4
  64. package/lib/email-client/outlook-client.js +194 -397
  65. package/lib/email-client/smtp-pool-manager.js +3 -2
  66. package/lib/encrypt.js +184 -19
  67. package/lib/enum-descriptions.js +1 -2
  68. package/lib/export.js +133 -39
  69. package/lib/gateway.js +20 -6
  70. package/lib/get-raw-email.js +26 -44
  71. package/lib/handlebars-helpers.js +31 -10
  72. package/lib/imap-proxy-auth.js +13 -29
  73. package/lib/imapproxy/imap-core/README.md +1 -0
  74. package/lib/imapproxy/imap-core/lib/handler/imap-parser.js +12 -0
  75. package/lib/imapproxy/imap-core/lib/imap-command.js +74 -10
  76. package/lib/imapproxy/imap-core/lib/imap-connection.js +9 -1
  77. package/lib/imapproxy/imap-core/lib/imap-server.js +112 -26
  78. package/lib/imapproxy/imap-core/lib/imap-stream.js +41 -1
  79. package/lib/imapproxy/imap-core/lib/imap-tools.js +10 -2
  80. package/lib/imapproxy/imap-core/lib/indexer/indexer.js +4 -2
  81. package/lib/imapproxy/imap-server.js +17 -177
  82. package/lib/imapproxy/proxy-handoff.js +235 -0
  83. package/lib/imapproxy/response-error.js +33 -0
  84. package/lib/imapproxy/upstream-client.js +2 -2
  85. package/lib/license-beacon.js +3 -9
  86. package/lib/llm-pre-process.js +182 -43
  87. package/lib/logger.js +1 -1
  88. package/lib/lua/ee-export-queue-add.lua +39 -0
  89. package/lib/lua/ee-get-idempotency.lua +15 -3
  90. package/lib/lua/ee-release-attempts.lua +23 -0
  91. package/lib/lua/ee-reserve-attempts.lua +42 -0
  92. package/lib/lua/h-set-bigger.lua +12 -2
  93. package/lib/lua/s-list-accounts.lua +6 -3
  94. package/lib/mcp/index.js +1 -2
  95. package/lib/mcp/listen.js +221 -18
  96. package/lib/mcp/oauth.js +44 -5
  97. package/lib/mcp/resources.js +8 -2
  98. package/lib/mcp/tools.js +13 -0
  99. package/lib/message-port-stream.js +64 -6
  100. package/lib/oauth/external-account-signer.js +16 -13
  101. package/lib/oauth/gmail.js +22 -20
  102. package/lib/oauth/outlook.js +19 -16
  103. package/lib/oauth/pubsub/google.js +38 -2
  104. package/lib/oauth/scope-checker.js +4 -7
  105. package/lib/oauth/verify-app.js +2 -2
  106. package/lib/oauth2-apps.js +139 -44
  107. package/lib/openapi/build-document.js +1 -1
  108. package/lib/openapi/joi-schema.js +78 -9
  109. package/lib/parse-message.js +21 -0
  110. package/lib/payload-examples-webhooks.json +4 -7
  111. package/lib/pbkdf2-phc.js +101 -0
  112. package/lib/privileged-settings.js +0 -14
  113. package/lib/rate-limit.js +54 -15
  114. package/lib/redis-scan-delete.js +56 -29
  115. package/lib/redis-url.js +3 -1
  116. package/lib/respawn-backoff.js +5 -4
  117. package/lib/response-stream.js +25 -4
  118. package/lib/rewrite-text-nodes.js +27 -40
  119. package/lib/routes-ui.js +0 -5
  120. package/lib/schemas.js +122 -242
  121. package/lib/sentry.js +21 -5
  122. package/lib/settings.js +58 -59
  123. package/lib/smtp-auth.js +6 -2
  124. package/lib/smtp-message-processor.js +28 -7
  125. package/lib/sso.js +7 -3
  126. package/lib/stream-encrypt.js +14 -13
  127. package/lib/swagger-options.js +3 -1
  128. package/lib/tls/provision.js +69 -3
  129. package/lib/tls/store.js +14 -1
  130. package/lib/tools.js +113 -52
  131. package/lib/totp.js +16 -1
  132. package/lib/ui-routes/account-routes.js +27 -63
  133. package/lib/ui-routes/admin-config-routes.js +111 -134
  134. package/lib/ui-routes/admin-entities-routes.js +101 -191
  135. package/lib/ui-routes/ai-options.js +104 -0
  136. package/lib/ui-routes/auth-routes.js +98 -18
  137. package/lib/ui-routes/export-routes.js +3 -23
  138. package/lib/ui-routes/internals-routes.js +12 -9
  139. package/lib/ui-routes/network-config-routes.js +8 -18
  140. package/lib/ui-routes/oauth-config-routes.js +80 -214
  141. package/lib/ui-routes/route-helpers.js +40 -44
  142. package/lib/ui-routes/unsubscribe-routes.js +2 -2
  143. package/lib/utils/decode-headers.js +32 -5
  144. package/lib/utils/header-map.js +62 -1
  145. package/lib/utils/network.js +2 -0
  146. package/lib/web-safe-html.js +77 -4
  147. package/lib/webhook-request.js +9 -1
  148. package/lib/webhook-routing.js +27 -1
  149. package/lib/webhooks.js +120 -43
  150. package/lib/worker-rpc-error.js +43 -2
  151. package/list-generate.js +13 -2
  152. package/package.json +33 -41
  153. package/sbom.json +1 -1
  154. package/scripts/refresh-test-tokens.js +42 -14
  155. package/server.js +317 -289
  156. package/static/css/flyonui.css +1 -1
  157. package/static/css/src/app.tailwind.css +7 -8
  158. package/static/js/ee-client.js +145 -70
  159. package/static/js/ui.js +350 -154
  160. package/static/licenses.html +434 -1835
  161. package/translations/messages.pot +97 -97
  162. package/views/accounts/browse.hbs +10 -4
  163. package/views/config/ai.hbs +49 -41
  164. package/views/config/oauth/app.hbs +2 -1
  165. package/views/dashboard.hbs +18 -16
  166. package/views/layout/app.hbs +0 -22
  167. package/views/layout/login.hbs +2 -1
  168. package/views/partials/filter_editor_js.hbs +4 -3
  169. package/views/partials/side_menu.hbs +0 -4
  170. package/views/partials/ui/account-picker.hbs +6 -32
  171. package/views/partials/ui/model-picker.hbs +31 -0
  172. package/views/partials/ui/pagination.hbs +6 -1
  173. package/views/partials/ui/picker.hbs +47 -0
  174. package/views/unsubscribe.hbs +1 -1
  175. package/workers/api.js +20 -20
  176. package/workers/export.js +55 -60
  177. package/workers/imap.js +126 -46
  178. package/workers/submit.js +3 -1
  179. package/workers/webhooks.js +46 -27
  180. package/.githooks/pre-commit +0 -80
  181. package/.github/CODE_OF_CONDUCT.md +0 -76
  182. package/.github/contributing.md +0 -17
  183. package/.github/dependabot.yml +0 -22
  184. package/.github/docker-smoke-test.sh +0 -61
  185. package/.github/workflows/deploy.yml +0 -215
  186. package/.github/workflows/e2e.yml +0 -55
  187. package/.github/workflows/release.yaml +0 -217
  188. package/.github/workflows/test.yml +0 -307
  189. package/lib/api-routes/chat-routes.js +0 -535
  190. package/lib/document-store.js +0 -75
  191. package/lib/es.js +0 -757
  192. package/lib/generate-text-preview.js +0 -61
  193. package/lib/imapproxy/imap-core/memory-notifier.js +0 -129
  194. package/lib/pre-process.js +0 -196
  195. package/lib/threads.js +0 -155
  196. package/lib/ui-routes/document-store-routes.js +0 -806
  197. package/playwright.config.js +0 -47
  198. package/views/config/document-store/chat.hbs +0 -286
  199. package/views/config/document-store/index.hbs +0 -146
  200. package/views/config/document-store/mappings/index.hbs +0 -108
  201. package/views/config/document-store/mappings/new.hbs +0 -68
  202. package/views/config/document-store/pre-processing/index.hbs +0 -103
  203. package/views/partials/document_store_header.hbs +0 -30
  204. package/workers/documents.js +0 -1128
@@ -9,7 +9,7 @@ const { oauth2Apps } = require('../oauth2-apps');
9
9
  const getSecret = require('../get-secret');
10
10
  const msgpack = require('../msgpack');
11
11
  const he = require('he');
12
- const { emitChangeEvent, prepareUrl, collectCidReferences, cidReferenceRegex, truncateTextContents } = require('../tools');
12
+ const { emitChangeEvent, prepareUrl, collectCidReferences, embedCidImages, truncateTextContents } = require('../tools');
13
13
  const { messageWebSafeHtml, applyWebSafeHtmlOptions } = require('../web-safe-html');
14
14
  const crypto = require('crypto');
15
15
  const { Gateway } = require('../gateway');
@@ -29,8 +29,8 @@ const {
29
29
  OUTLOOK_EXPIRATION_RENEW_TIME,
30
30
  OUTLOOK_SUBSCRIPTION_LOCK_TTL,
31
31
  OUTLOOK_MAX_RETRY_ATTEMPTS,
32
- OUTLOOK_RETRY_BASE_DELAY,
33
- OUTLOOK_RETRY_MAX_DELAY,
32
+ OUTLOOK_SUBSCRIPTION_RETRY_BASE_DELAY,
33
+ OUTLOOK_SUBSCRIPTION_RETRY_MAX_DELAY,
34
34
  OUTLOOK_CLOCK_SKEW_BUFFER,
35
35
  OUTLOOK_MISSED_LOOKBACK,
36
36
  OUTLOOK_ANNOUNCED_RETENTION,
@@ -52,6 +52,17 @@ const RENEW_WATCH_TTL = 60 * 60 * 1000; // 1h
52
52
  // isSelfClearedErrorState() is what keeps a login from taking it along
53
53
  const SUBSCRIPTION_SETUP_ERROR_CODE = 'SubscriptionSetupError';
54
54
 
55
+ // Graph accepts only x- prefixed names in internetMessageHeaders and rejects the whole message
56
+ // over any other one, so the threading headers of a reply or a forward are set through the
57
+ // MAPI properties Exchange builds them from (PidTagInReplyToId, PidTagInternetReferences)
58
+ const GRAPH_THREADING_PROPERTIES = new Map([
59
+ ['in-reply-to', 'String 0x1042'],
60
+ ['references', 'String 0x1039']
61
+ ]);
62
+
63
+ // MS Graph API only allows up to 5 custom headers
64
+ const MAX_GRAPH_CUSTOM_HEADERS = 5;
65
+
55
66
  // MS Graph folder hierarchy is defined by id/parentFolderId, not by "/" in folder
56
67
  // names. To build an unambiguous, reversible pathName we percent-encode "%" and "/"
57
68
  // inside a single displayName segment, keeping the real "/" as the delimiter BETWEEN
@@ -113,6 +124,8 @@ const LISTING_REFRESH_INTERVAL = 5 * 60 * 1000;
113
124
  class OutlookClient extends BaseClient {
114
125
  constructor(account, options) {
115
126
  super(account, options);
127
+ // what the AI summary's authentication trust rule keys on, the way GmailClient sets its own
128
+ this.type = 'outlook';
116
129
 
117
130
  // A failed init() is scheduled again by the worker, see BaseClient.scheduleInitRetry()
118
131
  this.retriesInit = true;
@@ -850,7 +863,7 @@ class OutlookClient extends BaseClient {
850
863
  let raw;
851
864
 
852
865
  try {
853
- raw = await this.request(`/${this.oauth2UserPath}/messages/${emailId}/$value`, 'get', Buffer.alloc(0), { returnText: true });
866
+ raw = await this.request(`/${this.oauth2UserPath}/messages/${emailId}/$value`, 'get', Buffer.alloc(0), { returnBuffer: true });
854
867
  } catch (err) {
855
868
  switch (err.oauthRequest?.status) {
856
869
  case 404: {
@@ -883,7 +896,7 @@ class OutlookClient extends BaseClient {
883
896
  }
884
897
  }
885
898
 
886
- return raw ? Buffer.from(raw) : null;
899
+ return raw && raw.length ? raw : null;
887
900
  }
888
901
 
889
902
  /**
@@ -1028,102 +1041,40 @@ class OutlookClient extends BaseClient {
1028
1041
  return { deleted: false };
1029
1042
  }
1030
1043
 
1031
- // Prepare batch operation variables
1032
- let batch = [];
1033
- let idGen = 0;
1034
- let updatedEmailIds = [];
1035
- let messageMap = new Map();
1036
-
1037
- /**
1038
- * Submit a batch of delete operations to Graph API
1039
- * Uses requestWithRetry for automatic retry on rate limiting
1040
- */
1041
- let submitBatch = async () => {
1042
- let responseData;
1043
- try {
1044
- responseData = await this.requestWithRetry(`/$batch`, 'post', {
1045
- requests: batch
1046
- });
1047
- for (let response of responseData?.responses || []) {
1048
- let emailId = messageMap.get(response.id);
1049
- if (response?.status >= 200 && response?.status < 300) {
1050
- if (emailId) {
1051
- updatedEmailIds.push(emailId);
1052
- }
1053
- } else {
1054
- // Log individual batch item failures for debugging
1055
- this.logger.warn({
1056
- msg: 'Batch item failed',
1057
- account: this.account,
1058
- operation: 'delete',
1059
- emailId,
1060
- status: response?.status,
1061
- error: response?.body?.error
1062
- });
1063
- }
1064
- }
1065
- } catch (err) {
1066
- this.logger.error({
1067
- msg: 'Failed to run batch operation',
1068
- account: this.account,
1069
- operation: 'delete',
1070
- err
1071
- });
1072
- throw err;
1073
- } finally {
1074
- batch = [];
1075
- messageMap = new Map();
1076
- }
1077
- };
1078
-
1079
- /**
1080
- * Format a single delete request for the batch
1081
- */
1082
- let formatRequest = emailId => {
1083
- let reqId = `msg_${++idGen}`;
1084
- messageMap.set(reqId, emailId);
1085
-
1086
- // Common headers for batch requests - include ImmutableId preference
1087
- const batchHeaders = {
1088
- 'Content-Type': 'application/json',
1089
- Prefer: 'IdType="ImmutableId"'
1090
- };
1091
-
1092
- if (force) {
1093
- // Permanent delete
1094
- return {
1095
- id: reqId,
1096
- method: 'DELETE',
1097
- url: `/${this.oauth2UserPath}/messages/${emailId}`,
1098
- headers: batchHeaders
1099
- };
1100
- } else {
1101
- // Move to trash
1102
- return {
1103
- id: reqId,
1104
- method: 'POST',
1105
- url: `/${this.oauth2UserPath}/messages/${emailId}/move`,
1106
- body: { destinationId: 'deleteditems' },
1107
- headers: batchHeaders
1108
- };
1109
- }
1044
+ // Common headers for batch requests - include ImmutableId preference
1045
+ const batchHeaders = {
1046
+ 'Content-Type': 'application/json',
1047
+ Prefer: 'IdType="ImmutableId"'
1110
1048
  };
1111
1049
 
1112
- // Process messages in batches
1113
- for (let emailId of emailIds) {
1114
- batch.push(formatRequest(emailId));
1115
- // submit batch when it reaches max size
1116
- if (batch.length >= MAX_BATCH_SIZE) {
1117
- await submitBatch(batch);
1118
- }
1119
- }
1120
- if (batch.length) {
1121
- // submit remaining batch
1122
- await submitBatch(batch);
1123
- }
1050
+ // Throttled items are retried by the batch helper; whatever still fails is reported
1051
+ const { successIds: updatedEmailIds, failedIds } = await graphApi.executeBatchOperation(
1052
+ this,
1053
+ emailIds,
1054
+ (emailId, reqId) =>
1055
+ force
1056
+ ? // Permanent delete
1057
+ {
1058
+ id: reqId,
1059
+ method: 'DELETE',
1060
+ url: `/${this.oauth2UserPath}/messages/${emailId}`,
1061
+ headers: batchHeaders
1062
+ }
1063
+ : // Move to trash
1064
+ {
1065
+ id: reqId,
1066
+ method: 'POST',
1067
+ url: `/${this.oauth2UserPath}/messages/${emailId}/move`,
1068
+ body: { destinationId: 'deleteditems' },
1069
+ headers: batchHeaders
1070
+ },
1071
+ 'delete'
1072
+ );
1124
1073
 
1125
1074
  return Object.assign(
1126
- { deleted: true },
1075
+ // Nothing was deleted when every item failed
1076
+ { deleted: updatedEmailIds.length > 0 },
1077
+ failedIds.length ? { failed: { emailIds: failedIds } } : {},
1127
1078
  !force
1128
1079
  ? {
1129
1080
  moved: {
@@ -1286,120 +1237,40 @@ class OutlookClient extends BaseClient {
1286
1237
  let currentCategories = new Map();
1287
1238
 
1288
1239
  if (needsCurrentCategories) {
1289
- // Fetch current categories for all messages in batches
1290
- let fetchBatch = [];
1291
- let fetchIdGen = 0;
1292
- let fetchMessageMap = new Map();
1293
-
1294
- let submitFetchBatch = async () => {
1295
- let responseData;
1296
- try {
1297
- responseData = await this.requestWithRetry(`/$batch`, 'post', {
1298
- requests: fetchBatch
1299
- });
1300
- for (let response of responseData?.responses || []) {
1301
- let emailId = fetchMessageMap.get(response.id);
1302
- if (response?.status >= 200 && response?.status < 300 && response.body) {
1303
- if (emailId) {
1304
- currentCategories.set(emailId, response.body.categories || []);
1305
- }
1306
- } else if (emailId) {
1307
- // Log individual batch item failures
1308
- this.logger.warn({
1309
- msg: 'Batch item failed',
1310
- account: this.account,
1311
- operation: 'fetchCategories',
1312
- emailId,
1313
- status: response?.status,
1314
- error: response?.body?.error
1315
- });
1316
- }
1317
- }
1318
- } catch (err) {
1319
- // Without the current categories the PATCH below would replace every
1320
- // message's category list with just the added labels, so a failed fetch
1321
- // has to abort the update instead of being logged past
1322
- this.logger.error({
1323
- msg: 'Failed to fetch current categories',
1324
- account: this.account,
1325
- err
1326
- });
1327
- throw err;
1328
- } finally {
1329
- fetchBatch = [];
1330
- fetchMessageMap = new Map();
1331
- }
1332
- };
1333
-
1334
- for (let emailId of emailIds) {
1335
- let reqId = `fetch_${++fetchIdGen}`;
1336
- fetchMessageMap.set(reqId, emailId);
1337
- fetchBatch.push({
1338
- id: reqId,
1339
- method: 'GET',
1340
- url: `/${this.oauth2UserPath}/messages/${emailId}?$select=categories`,
1341
- headers: {
1342
- Prefer: 'IdType="ImmutableId"'
1343
- }
1344
- });
1345
-
1346
- if (fetchBatch.length >= MAX_BATCH_SIZE) {
1347
- await submitFetchBatch();
1348
- }
1349
- }
1350
- if (fetchBatch.length) {
1351
- await submitFetchBatch();
1352
- }
1353
- }
1354
-
1355
- // Batch operation setup
1356
- let batch = [];
1357
- let idGen = 0;
1358
- let updatedEmailIds = [];
1359
- let messageMap = new Map();
1360
-
1361
- let submitBatch = async () => {
1362
- let responseData;
1240
+ // Fetch current categories for all messages in batches. A failed batch request has
1241
+ // to abort the update: without the current categories the PATCH below would replace
1242
+ // every message's category list with just the added labels
1243
+ let fetched;
1363
1244
  try {
1364
- responseData = await this.requestWithRetry(`/$batch`, 'post', {
1365
- requests: batch
1366
- });
1367
- for (let response of responseData?.responses || []) {
1368
- let emailId = messageMap.get(response.id);
1369
- if (response?.status >= 200 && response?.status < 300) {
1370
- if (emailId) {
1371
- updatedEmailIds.push(emailId);
1245
+ fetched = await graphApi.executeBatchOperation(
1246
+ this,
1247
+ emailIds,
1248
+ (emailId, reqId) => ({
1249
+ id: reqId,
1250
+ method: 'GET',
1251
+ url: `/${this.oauth2UserPath}/messages/${emailId}?$select=categories`,
1252
+ headers: {
1253
+ Prefer: 'IdType="ImmutableId"'
1372
1254
  }
1373
- } else {
1374
- // Log individual batch item failures for debugging
1375
- this.logger.warn({
1376
- msg: 'Batch item failed',
1377
- account: this.account,
1378
- operation: 'update',
1379
- emailId,
1380
- status: response?.status,
1381
- error: response?.body?.error
1382
- });
1383
- }
1384
- }
1255
+ }),
1256
+ 'fetchCategories'
1257
+ );
1385
1258
  } catch (err) {
1386
1259
  this.logger.error({
1387
- msg: 'Failed to run batch operation',
1260
+ msg: 'Failed to fetch current categories',
1388
1261
  account: this.account,
1389
- operation: 'update',
1390
1262
  err
1391
1263
  });
1392
1264
  throw err;
1393
- } finally {
1394
- batch = [];
1395
- messageMap = new Map();
1396
1265
  }
1397
- };
1398
-
1399
- let formatRequest = emailId => {
1400
- let reqId = `msg_${++idGen}`;
1401
- messageMap.set(reqId, emailId);
1266
+ for (let [emailId, body] of fetched.bodies) {
1267
+ if (body) {
1268
+ currentCategories.set(emailId, body.categories || []);
1269
+ }
1270
+ }
1271
+ }
1402
1272
 
1273
+ let formatRequest = (emailId, reqId) => {
1403
1274
  let bodyUpdates = { ...flagUpdates };
1404
1275
 
1405
1276
  // Handle categories for this specific message
@@ -1437,25 +1308,15 @@ class OutlookClient extends BaseClient {
1437
1308
  };
1438
1309
  };
1439
1310
 
1440
- // Process messages in batches
1441
- for (let emailId of emailIds) {
1442
- if (needsCurrentCategories && !currentCategories.has(emailId)) {
1443
- // The category fetch for this message failed (logged above) - skipping it
1444
- // keeps its existing categories instead of overwriting them with the additions
1445
- continue;
1446
- }
1447
- batch.push(formatRequest(emailId));
1448
- // submit batch when it reaches max size
1449
- if (batch.length >= MAX_BATCH_SIZE) {
1450
- await submitBatch(batch);
1451
- }
1452
- }
1453
- if (batch.length) {
1454
- // submit remaining batch
1455
- await submitBatch(batch);
1456
- }
1311
+ // The category fetch for a message may have failed (logged above) - skipping it keeps its
1312
+ // existing categories instead of overwriting them with the additions
1313
+ let targetIds = needsCurrentCategories ? emailIds.filter(emailId => currentCategories.has(emailId)) : emailIds;
1314
+ let skippedIds = needsCurrentCategories ? emailIds.filter(emailId => !currentCategories.has(emailId)) : [];
1315
+
1316
+ const { successIds: updatedEmailIds, failedIds: updateFailedIds } = await graphApi.executeBatchOperation(this, targetIds, formatRequest, 'update');
1317
+ const failedIds = skippedIds.concat(updateFailedIds);
1457
1318
 
1458
- return Object.assign({}, updates, { emailIds: updatedEmailIds });
1319
+ return Object.assign({}, updates, { emailIds: updatedEmailIds }, failedIds.length ? { failed: { emailIds: failedIds } } : {});
1459
1320
  }
1460
1321
 
1461
1322
  /**
@@ -1549,54 +1410,10 @@ class OutlookClient extends BaseClient {
1549
1410
  return { path: targetFolder.pathName };
1550
1411
  }
1551
1412
 
1552
- // Batch operation setup
1553
- let batch = [];
1554
- let idGen = 0;
1555
- let updatedEmailIds = [];
1556
- let messageMap = new Map();
1557
-
1558
- let submitBatch = async () => {
1559
- let responseData;
1560
- try {
1561
- responseData = await this.requestWithRetry(`/$batch`, 'post', {
1562
- requests: batch
1563
- });
1564
- for (let response of responseData?.responses || []) {
1565
- let emailId = messageMap.get(response.id);
1566
- if (response?.status >= 200 && response?.status < 300) {
1567
- if (emailId) {
1568
- updatedEmailIds.push(emailId);
1569
- }
1570
- } else {
1571
- // Log individual batch item failures for debugging
1572
- this.logger.warn({
1573
- msg: 'Batch item failed',
1574
- account: this.account,
1575
- operation: 'move',
1576
- emailId,
1577
- status: response?.status,
1578
- error: response?.body?.error
1579
- });
1580
- }
1581
- }
1582
- } catch (err) {
1583
- this.logger.error({
1584
- msg: 'Failed to run batch operation',
1585
- account: this.account,
1586
- operation: 'move',
1587
- err
1588
- });
1589
- throw err;
1590
- } finally {
1591
- batch = [];
1592
- messageMap = new Map();
1593
- }
1594
- };
1595
-
1596
- let formatRequest = emailId => {
1597
- let reqId = `msg_${++idGen}`;
1598
- messageMap.set(reqId, emailId);
1599
- return {
1413
+ const { successIds: updatedEmailIds, failedIds } = await graphApi.executeBatchOperation(
1414
+ this,
1415
+ emailIds,
1416
+ (emailId, reqId) => ({
1600
1417
  id: reqId,
1601
1418
  method: 'POST',
1602
1419
  url: `/${this.oauth2UserPath}/messages/${emailId}/move`,
@@ -1605,23 +1422,11 @@ class OutlookClient extends BaseClient {
1605
1422
  'Content-Type': 'application/json',
1606
1423
  Prefer: 'IdType="ImmutableId"'
1607
1424
  }
1608
- };
1609
- };
1610
-
1611
- // Process messages in batches
1612
- for (let emailId of emailIds) {
1613
- batch.push(formatRequest(emailId));
1614
- // submit batch
1615
- if (batch.length >= MAX_BATCH_SIZE) {
1616
- await submitBatch(batch);
1617
- }
1618
- }
1619
- if (batch.length) {
1620
- // submit batch
1621
- await submitBatch(batch);
1622
- }
1425
+ }),
1426
+ 'move'
1427
+ );
1623
1428
 
1624
- return Object.assign({ path: targetFolder.pathName }, { emailIds: updatedEmailIds });
1429
+ return Object.assign({ path: targetFolder.pathName }, { emailIds: updatedEmailIds }, failedIds.length ? { failed: { emailIds: failedIds } } : {});
1625
1430
  }
1626
1431
 
1627
1432
  /**
@@ -1753,21 +1558,17 @@ class OutlookClient extends BaseClient {
1753
1558
  }
1754
1559
  }
1755
1560
 
1756
- // Resolve the folder path and special use
1561
+ // Resolve the folder path and special use. The message exists even when its folder is not
1562
+ // in the listing (a hidden folder, one the crawl skips): it is returned without a path.
1563
+ // Answering 404 here made new-message processing report an existing message as missing
1757
1564
  if (messageData.parentFolderId) {
1758
1565
  let folder = await this.resolveFolder(messageData.parentFolderId, { byId: true });
1759
- if (!folder) {
1760
- let error = new Error('Listing failed');
1761
- error.info = {
1762
- response: 'Not able to find mailbox folder'
1763
- };
1764
- error.code = 'NotFound';
1765
- error.statusCode = 404;
1766
- throw error;
1566
+ if (folder) {
1567
+ path = folder.pathName;
1568
+ specialUse = folder.specialUse;
1569
+ } else {
1570
+ this.logger.debug({ msg: 'Message folder is not in the mailbox listing', emailId, folderId: messageData.parentFolderId });
1767
1571
  }
1768
-
1769
- path = folder.pathName;
1770
- specialUse = folder.specialUse;
1771
1572
  }
1772
1573
 
1773
1574
  // Process email headers
@@ -1849,14 +1650,9 @@ class OutlookClient extends BaseClient {
1849
1650
  }
1850
1651
 
1851
1652
  // Replace cid: references with data URLs
1852
- formattedMessage.text.html = formattedMessage.text.html.replace(cidReferenceRegex(), (fullMatch, cidMatch) => {
1853
- if (attachmentMap.has(cidMatch)) {
1854
- let { content } = attachmentMap.get(cidMatch);
1855
- if (content.content) {
1856
- return `data:${content.contentType || 'application/octet-stream'};base64,${content.content}`;
1857
- }
1858
- }
1859
- return fullMatch;
1653
+ formattedMessage.text.html = embedCidImages(formattedMessage.text.html, contentId => {
1654
+ let { content } = attachmentMap.get(contentId) || {};
1655
+ return content?.content && { contentType: content.contentType, content: content.content };
1860
1656
  });
1861
1657
  }
1862
1658
 
@@ -1874,9 +1670,25 @@ class OutlookClient extends BaseClient {
1874
1670
  options = options || {};
1875
1671
  await this.prepare();
1876
1672
 
1877
- // Pre-fetch folder listing once for all messages to avoid repeated lookups
1878
- const mailboxListing = await this.getMailboxListing();
1673
+ // The export calls this once per batch of messages, so the cached listing is used when
1674
+ // there is one: a live listing is a full folder crawl, and doing that per batch burned the
1675
+ // account's Graph throttling budget on a large export. Folders missing from it are
1676
+ // resolved one by one below, which refreshes the cache when the folder is new
1677
+ const mailboxListing = (await this.getCachedMailboxListing()) || (await this.getMailboxListing());
1879
1678
  const folderMap = new Map(mailboxListing.map(f => [f.id, f]));
1679
+ const lookupFolder = async folderId => {
1680
+ if (!folderMap.has(folderId)) {
1681
+ let folder = null;
1682
+ try {
1683
+ folder = (await this.resolveFolder(folderId, { byId: true })) || null;
1684
+ } catch (err) {
1685
+ this.logger.warn({ msg: 'Failed to resolve message folder', account: this.account, folderId, err });
1686
+ }
1687
+ // remembered either way, so a folder the listing never includes costs one lookup
1688
+ folderMap.set(folderId, folder);
1689
+ }
1690
+ return folderMap.get(folderId);
1691
+ };
1880
1692
 
1881
1693
  const results = [];
1882
1694
  let idGen = 0;
@@ -2005,7 +1817,7 @@ class OutlookClient extends BaseClient {
2005
1817
  // Resolve folder from pre-fetched map (O(1) lookup)
2006
1818
  let path, specialUse;
2007
1819
  if (messageData.parentFolderId) {
2008
- const folder = folderMap.get(messageData.parentFolderId);
1820
+ const folder = await lookupFolder(messageData.parentFolderId);
2009
1821
  if (folder) {
2010
1822
  path = folder.pathName;
2011
1823
  specialUse = folder.specialUse;
@@ -2185,87 +1997,74 @@ class OutlookClient extends BaseClient {
2185
1997
  convertMessageToUploadObject(emailObject) {
2186
1998
  let messageUploadObj = {};
2187
1999
 
2000
+ let addHeader = (name, value) => {
2001
+ if (!name || !value) {
2002
+ return;
2003
+ }
2004
+
2005
+ if (GRAPH_THREADING_PROPERTIES.has(name)) {
2006
+ let id = GRAPH_THREADING_PROPERTIES.get(name);
2007
+ // a caller-supplied In-Reply-To can sit next to the lowercase one a reference adds
2008
+ messageUploadObj.singleValueExtendedProperties = (messageUploadObj.singleValueExtendedProperties || []).filter(entry => entry.id !== id);
2009
+ messageUploadObj.singleValueExtendedProperties.push({ id, value: String(value) });
2010
+ return;
2011
+ }
2012
+
2013
+ // Everything else Graph either fills in from message fields (From, Reply-To, Date, ...)
2014
+ // or refuses outright
2015
+ if (!/^x-/i.test(name)) {
2016
+ return;
2017
+ }
2018
+
2019
+ messageUploadObj.internetMessageHeaders = messageUploadObj.internetMessageHeaders || [];
2020
+ messageUploadObj.internetMessageHeaders.push({ name, value });
2021
+ };
2022
+
2023
+ let toGraphAddress = entry => ({
2024
+ emailAddress: entry.name ? { address: entry.address, name: entry.name } : { address: entry.address }
2025
+ });
2026
+
2188
2027
  for (let key of Object.keys(emailObject)) {
2189
2028
  switch (key) {
2190
2029
  case 'from':
2191
- messageUploadObj.from = {
2192
- emailAddress: {
2193
- address: emailObject.from.address
2194
- }
2195
- };
2196
- if (emailObject.from.name) {
2197
- messageUploadObj.from.emailAddress.name = emailObject.from.name;
2198
- }
2030
+ messageUploadObj.from = toGraphAddress(emailObject.from);
2199
2031
  break;
2200
2032
 
2201
2033
  case 'to':
2202
2034
  case 'cc':
2203
- case 'bcc': {
2204
- let entryKey = `${key}Recipients`;
2205
- messageUploadObj[entryKey] = [];
2206
- for (let addressEntry of emailObject[key] || []) {
2207
- let addressObj = {
2208
- emailAddress: {
2209
- address: addressEntry.address
2210
- }
2211
- };
2212
- if (addressEntry.name) {
2213
- addressObj.emailAddress.name = addressEntry.name;
2214
- }
2215
- messageUploadObj[entryKey].push(addressObj);
2216
- }
2035
+ case 'bcc':
2036
+ messageUploadObj[`${key}Recipients`] = (emailObject[key] || []).map(toGraphAddress);
2217
2037
  break;
2218
- }
2219
2038
 
2220
2039
  case 'subject':
2221
2040
  messageUploadObj[key] = emailObject[key];
2222
2041
  break;
2223
2042
 
2224
2043
  case 'headers': {
2225
- messageUploadObj.internetMessageHeaders = messageUploadObj.internetMessageHeaders || [];
2226
2044
  for (let header of Object.keys(emailObject.headers)) {
2227
- messageUploadObj.internetMessageHeaders.push({
2228
- name: header.toLowerCase(),
2229
- value: emailObject.headers[header]
2230
- });
2045
+ addHeader(header.toLowerCase(), emailObject.headers[header]);
2231
2046
  }
2232
2047
  break;
2233
2048
  }
2234
2049
 
2235
2050
  case 'headerLines': {
2236
- messageUploadObj.internetMessageHeaders = messageUploadObj.internetMessageHeaders || [];
2237
- for (let i = emailObject.headerLines.length - 1; i >= 0; i--) {
2238
- let header = emailObject.headerLines[i];
2239
- // Skip headers that Graph API handles automatically
2240
- if (
2241
- [
2242
- 'date',
2243
- 'content-transfer-encoding',
2244
- 'from',
2245
- 'to',
2246
- 'cc',
2247
- 'bcc',
2248
- 'subject',
2249
- 'mime-version',
2250
- 'content-type',
2251
- 'content-disposition',
2252
- 'message-id',
2253
- 'content-id'
2254
- ].includes(header.key) ||
2255
- // MS Graph API only allows up to 5 custom headers
2256
- messageUploadObj.internetMessageHeaders.length >= 5
2257
- ) {
2258
- continue;
2259
- }
2051
+ for (let header of emailObject.headerLines) {
2052
+ // mailparser keeps the whole line; unfold it, a long References header arrives split over several lines
2053
+ let value = header.line
2054
+ ? header.line
2055
+ .substring(header.line.indexOf(':') + 1)
2056
+ .replace(/\r?\n[ \t]+/g, ' ')
2057
+ .trim()
2058
+ : '';
2059
+ addHeader(header.key, value);
2060
+ }
2061
+ break;
2062
+ }
2260
2063
 
2261
- let name = header.key;
2262
- let value = header.value ? header.value.substring(header.value.indexOf(':') + 1).trim() : '';
2263
- if (name && value) {
2264
- messageUploadObj.internetMessageHeaders.unshift({
2265
- name,
2266
- value
2267
- });
2268
- }
2064
+ case 'replyTo': {
2065
+ let entries = [].concat(emailObject.replyTo || []).filter(entry => entry?.address);
2066
+ if (entries.length) {
2067
+ messageUploadObj.replyTo = entries.map(toGraphAddress);
2269
2068
  }
2270
2069
  break;
2271
2070
  }
@@ -2295,9 +2094,12 @@ class OutlookClient extends BaseClient {
2295
2094
  if (attachment.cid) {
2296
2095
  // make sure that cid links to not use <content-id> format, otherwise this will be replaced
2297
2096
  attachmentEntry.contentId = attachment.cid.replace(/^[\s<]*|[\s>]*$/g, '');
2298
- if (cidReferences.has(attachmentEntry.contentId)) {
2097
+ // the reference grammar keeps a leading "<", so cid:<id> is collected as "<id"
2098
+ if (cidReferences.has(attachmentEntry.contentId) || cidReferences.has(`<${attachmentEntry.contentId}`)) {
2299
2099
  attachmentEntry.isInline = true;
2300
- emailObject.html.replace(new RegExp(`cid:<${attachment.cid}>`, 'g'), `cid:${attachment.cid}`);
2100
+ // A literal replace: the Content-ID is caller input, and as a RegExp
2101
+ // source a ( [ or \ in it threw a SyntaxError
2102
+ emailObject.html = emailObject.html.replaceAll(`cid:<${attachmentEntry.contentId}>`, `cid:${attachmentEntry.contentId}`);
2301
2103
  }
2302
2104
  }
2303
2105
  if (attachment.contentDisposition === 'inline') {
@@ -2323,8 +2125,9 @@ class OutlookClient extends BaseClient {
2323
2125
  };
2324
2126
  }
2325
2127
 
2326
- if (messageUploadObj.internetMessageHeaders && !messageUploadObj.internetMessageHeaders.length) {
2327
- delete messageUploadObj.internetMessageHeaders;
2128
+ if (messageUploadObj.internetMessageHeaders?.length > MAX_GRAPH_CUSTOM_HEADERS) {
2129
+ // keep the last ones, the headers added closest to sending
2130
+ messageUploadObj.internetMessageHeaders = messageUploadObj.internetMessageHeaders.slice(-MAX_GRAPH_CUSTOM_HEADERS);
2328
2131
  }
2329
2132
 
2330
2133
  return messageUploadObj;
@@ -2351,13 +2154,14 @@ class OutlookClient extends BaseClient {
2351
2154
  }
2352
2155
 
2353
2156
  // Parse raw message into structured format
2354
- let { emailObject, messageId, referencedMessage, documentStoreUsed } = await this.prepareRawMessage(data, {
2157
+ let { emailObject, messageId, referencedMessage } = await this.prepareRawMessage(data, {
2355
2158
  returnObject: true
2356
2159
  });
2357
2160
 
2358
2161
  let messageUploadObj = this.convertMessageToUploadObject(emailObject);
2359
2162
 
2360
- messageUploadObj.singleValueExtendedProperties = [];
2163
+ // may already hold the threading properties of a reply or a forward
2164
+ messageUploadObj.singleValueExtendedProperties = messageUploadObj.singleValueExtendedProperties || [];
2361
2165
 
2362
2166
  // Set message flags using MAPI properties
2363
2167
  // https://learn.microsoft.com/en-us/office/client-developer/outlook/mapi/pidtagmessageflags-canonical-property
@@ -2399,7 +2203,8 @@ class OutlookClient extends BaseClient {
2399
2203
  response: err.oauthRequest?.response?.error?.message || `Invalid message format`
2400
2204
  };
2401
2205
  error.code = err.oauthRequest?.response?.error?.code || 'InvalidMessage';
2402
- error.statusCode = 500; // do not retry sending
2206
+ // Graph refused the content, which is the caller's to fix, not a server fault
2207
+ error.statusCode = 400;
2403
2208
  throw error;
2404
2209
  }
2405
2210
 
@@ -2423,7 +2228,6 @@ class OutlookClient extends BaseClient {
2423
2228
  if (data.reference && data.reference.message) {
2424
2229
  response.reference = {
2425
2230
  message: data.reference.message,
2426
- documentStore: documentStoreUsed,
2427
2231
  success: referencedMessage ? true : false
2428
2232
  };
2429
2233
 
@@ -2627,11 +2431,10 @@ class OutlookClient extends BaseClient {
2627
2431
  let gatewayObject;
2628
2432
  if (data.gateway) {
2629
2433
  gatewayObject = new Gateway({ gateway: data.gateway, redis: this.redis, secret: this.secret });
2630
- try {
2631
- gatewayData = await gatewayObject.loadGatewayData();
2632
- } catch (err) {
2633
- this.logger.warn({ msg: 'Failed to load gateway data', messageId: data.messageId, gateway: data.gateway, err });
2634
- }
2434
+ // The message was queued for this gateway, so it must not go out through the
2435
+ // provider API instead: a missing gateway throws GatewayNotFound and the job is
2436
+ // discarded, a Redis failure is thrown as is and the job retries
2437
+ gatewayData = await gatewayObject.loadGatewayData();
2635
2438
  }
2636
2439
 
2637
2440
  if (gatewayData) {
@@ -3607,7 +3410,7 @@ class OutlookClient extends BaseClient {
3607
3410
  } catch (err) {
3608
3411
  this.logger.error({ msg: 'Failed to acquire subscription renew lock', account: this.account, err });
3609
3412
  this.scheduleSubscriptionRetry({
3610
- delayMs: OUTLOOK_RETRY_BASE_DELAY * 1000,
3413
+ delayMs: OUTLOOK_SUBSCRIPTION_RETRY_BASE_DELAY * 1000,
3611
3414
  reason: 'lock_error',
3612
3415
  errorMsg: 'Subscription renew retry after lock error failed',
3613
3416
  fn: () => this.renewSubscription({ force: false })
@@ -3741,7 +3544,8 @@ class OutlookClient extends BaseClient {
3741
3544
  // Schedule retry with exponential backoff
3742
3545
  const retryCount = outlookSubscription.state.retryCount;
3743
3546
  if (retryCount < OUTLOOK_MAX_RETRY_ATTEMPTS) {
3744
- const retryDelay = Math.min(OUTLOOK_RETRY_BASE_DELAY * Math.pow(2, retryCount - 1), OUTLOOK_RETRY_MAX_DELAY) * 1000;
3547
+ const retryDelay =
3548
+ Math.min(OUTLOOK_SUBSCRIPTION_RETRY_BASE_DELAY * Math.pow(2, retryCount - 1), OUTLOOK_SUBSCRIPTION_RETRY_MAX_DELAY) * 1000;
3745
3549
 
3746
3550
  this.scheduleSubscriptionRetry({
3747
3551
  delayMs: retryDelay,
@@ -3805,7 +3609,7 @@ class OutlookClient extends BaseClient {
3805
3609
  // Do not forward clearExisting on retry: by the time the retry fires,
3806
3610
  // another path may have created a valid subscription that should not be cleared.
3807
3611
  this.scheduleSubscriptionRetry({
3808
- delayMs: OUTLOOK_RETRY_BASE_DELAY * 1000,
3612
+ delayMs: OUTLOOK_SUBSCRIPTION_RETRY_BASE_DELAY * 1000,
3809
3613
  reason: 'lock_error',
3810
3614
  errorMsg: 'Subscription ensure retry after lock error failed',
3811
3615
  fn: () => this.ensureSubscription()
@@ -3958,7 +3762,8 @@ class OutlookClient extends BaseClient {
3958
3762
  if (outlookSubscription.state?.state === 'error') {
3959
3763
  const createRetryCount = outlookSubscription.state.createRetryCount || 0;
3960
3764
  if (createRetryCount < OUTLOOK_MAX_RETRY_ATTEMPTS) {
3961
- const retryDelay = Math.min(OUTLOOK_RETRY_BASE_DELAY * Math.pow(2, createRetryCount - 1), OUTLOOK_RETRY_MAX_DELAY) * 1000;
3765
+ const retryDelay =
3766
+ Math.min(OUTLOOK_SUBSCRIPTION_RETRY_BASE_DELAY * Math.pow(2, createRetryCount - 1), OUTLOOK_SUBSCRIPTION_RETRY_MAX_DELAY) * 1000;
3962
3767
 
3963
3768
  this.scheduleSubscriptionRetry({
3964
3769
  delayMs: retryDelay,
@@ -4212,20 +4017,12 @@ class OutlookClient extends BaseClient {
4212
4017
  if (attachmentResponse?.contentType && !attachmentResponse?.contentBytes) {
4213
4018
  // fetch raw value instead, happens with message/rfc822 attachments
4214
4019
  try {
4215
- let rawAttachmentContentStr = await this.request(
4216
- `/${this.oauth2UserPath}/messages/${emailId}/attachments/${id}/$value`,
4217
- 'get',
4218
- Buffer.alloc(0),
4219
- {
4220
- returnText: true
4221
- }
4222
- );
4223
- if (rawAttachmentContentStr) {
4224
- if (options.returnBase64) {
4225
- content = Buffer.from(rawAttachmentContentStr).toString('base64');
4226
- } else {
4227
- content = Buffer.from(rawAttachmentContentStr);
4228
- }
4020
+ // Raw bytes: a text round-trip would corrupt every non-UTF-8 byte of the message
4021
+ let rawAttachmentContent = await this.request(`/${this.oauth2UserPath}/messages/${emailId}/attachments/${id}/$value`, 'get', Buffer.alloc(0), {
4022
+ returnBuffer: true
4023
+ });
4024
+ if (rawAttachmentContent?.length) {
4025
+ content = options.returnBase64 ? rawAttachmentContent.toString('base64') : rawAttachmentContent;
4229
4026
  }
4230
4027
  } catch (err) {
4231
4028
  throw attachmentErrorHandler(err);