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
@@ -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, readEnvValue, getDuration } = 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,
@@ -46,12 +46,52 @@ const MAX_BATCH_SIZE = graphApi.MAX_BATCH_SIZE;
46
46
  // Subscription is renewed automatically. But just in case, check once in an hour
47
47
  const RENEW_WATCH_TTL = 60 * 60 * 1000; // 1h
48
48
 
49
+ const DEFAULT_FALLBACK_POLL_INTERVAL = 10 * 60 * 1000;
50
+ const MIN_FALLBACK_POLL_INTERVAL = 10 * 1000;
51
+
52
+ /**
53
+ * Reads EENGINE_OUTLOOK_FALLBACK_POLL_INTERVAL: a duration, 0 switching the periodic pass off.
54
+ * Anything unreadable gets the default, and a positive value is never shorter than ten seconds, so
55
+ * a typo cannot point every account at Graph in a loop
56
+ * @param {*} value - The raw environment value
57
+ * @returns {number} Milliseconds, 0 when the pass is off
58
+ */
59
+ function parseFallbackPollInterval(value) {
60
+ // blank is "unset", which getDuration() would read as 0, the value that switches the pass off
61
+ const raw = String(value ?? '').trim();
62
+ const duration = raw ? getDuration(raw) : DEFAULT_FALLBACK_POLL_INTERVAL;
63
+ if (!Number.isFinite(duration) || duration < 0) {
64
+ return DEFAULT_FALLBACK_POLL_INTERVAL;
65
+ }
66
+ return duration && Math.max(duration, MIN_FALLBACK_POLL_INTERVAL);
67
+ }
68
+
69
+ // When the announced set (see OutlookClient.getAnnouncedKey()) started being kept, the point a
70
+ // recovery pass never looks back past. Renamed along with the set when it became keyed by folder,
71
+ // so the first pass after an upgrade does not take the messages recorded in the old format for
72
+ // unannounced ones and announce hours of mail again
73
+ const ANNOUNCED_SINCE_FIELD = 'outlookAnnouncedInSince';
74
+
75
+ // See setupFallbackPollTimer()
76
+ const FALLBACK_POLL_INTERVAL = parseFallbackPollInterval(readEnvValue('EENGINE_OUTLOOK_FALLBACK_POLL_INTERVAL'));
77
+
49
78
  // The `serverResponseCode` a failed change subscription is reported with, and the marker that
50
79
  // tells the report apart from anything else the account may have stored. Only this client reads
51
80
  // it: reportSubscriptionFailure() writes it, clearSubscriptionFailure() lifts it, and
52
81
  // isSelfClearedErrorState() is what keeps a login from taking it along
53
82
  const SUBSCRIPTION_SETUP_ERROR_CODE = 'SubscriptionSetupError';
54
83
 
84
+ // Graph accepts only x- prefixed names in internetMessageHeaders and rejects the whole message
85
+ // over any other one, so the threading headers of a reply or a forward are set through the
86
+ // MAPI properties Exchange builds them from (PidTagInReplyToId, PidTagInternetReferences)
87
+ const GRAPH_THREADING_PROPERTIES = new Map([
88
+ ['in-reply-to', 'String 0x1042'],
89
+ ['references', 'String 0x1039']
90
+ ]);
91
+
92
+ // MS Graph API only allows up to 5 custom headers
93
+ const MAX_GRAPH_CUSTOM_HEADERS = 5;
94
+
55
95
  // MS Graph folder hierarchy is defined by id/parentFolderId, not by "/" in folder
56
96
  // names. To build an unambiguous, reversible pathName we percent-encode "%" and "/"
57
97
  // inside a single displayName segment, keeping the real "/" as the delimiter BETWEEN
@@ -92,7 +132,7 @@ Supported operations status:
92
132
  ✅ deleteMailbox
93
133
  ✅ getAttachment
94
134
  ✅ submitMessage
95
- ✅ uploadMessage - only drafts. Cannot change draft status
135
+ ✅ uploadMessage - Graph creates a draft; the \Draft flag then sets PR_MESSAGE_FLAGS mfUnsent
96
136
  🟡 subconnections - not supported
97
137
  */
98
138
 
@@ -113,6 +153,8 @@ const LISTING_REFRESH_INTERVAL = 5 * 60 * 1000;
113
153
  class OutlookClient extends BaseClient {
114
154
  constructor(account, options) {
115
155
  super(account, options);
156
+ // what the AI summary's authentication trust rule keys on, the way GmailClient sets its own
157
+ this.type = 'outlook';
116
158
 
117
159
  // A failed init() is scheduled again by the worker, see BaseClient.scheduleInitRetry()
118
160
  this.retriesInit = true;
@@ -139,6 +181,11 @@ class OutlookClient extends BaseClient {
139
181
  this.renewRetryTimer = null;
140
182
  this.renewalInProgress = false; // In-memory flag to prevent concurrent subscription renewals
141
183
 
184
+ // Periodic missed-notification recovery, see setupFallbackPollTimer()
185
+ this.fallbackPollTimer = null;
186
+ this.fallbackPollInterval = FALLBACK_POLL_INTERVAL;
187
+ this.periodicRecoveryDue = false;
188
+
142
189
  // MS Graph webhook subscription state (for metrics)
143
190
  // Possible values: 'unset', 'valid', 'expired', 'failed', 'pending'
144
191
  this.subscriptionState = 'unset';
@@ -262,10 +309,7 @@ class OutlookClient extends BaseClient {
262
309
  */
263
310
  async init() {
264
311
  this.state = 'connecting';
265
- clearTimeout(this.renewWatchTimer);
266
- clearTimeout(this.renewRetryTimer);
267
- this.cancelDeferredRetryTimer();
268
- this.cancelInitRetry();
312
+ this.clearTimers();
269
313
  await this.setStateVal();
270
314
 
271
315
  await this.getAccount();
@@ -393,11 +437,12 @@ class OutlookClient extends BaseClient {
393
437
 
394
438
  // A recovery pass must not look back past the point announced messages were first
395
439
  // recorded, or its first run after an upgrade would announce hours of mail again
396
- await this.redis.hsetnx(this.getAccountKey(), 'outlookAnnouncedSince', Date.now().toString());
440
+ await this.redis.hsetnx(this.getAccountKey(), ANNOUNCED_SINCE_FIELD, Date.now().toString());
397
441
 
398
442
  // Set up webhook subscription for real-time updates
399
443
  await this.ensureSubscription();
400
444
  this.setupRenewWatchTimer();
445
+ this.setupFallbackPollTimer({ first: true });
401
446
 
402
447
  // Cache mailbox folder structure
403
448
  try {
@@ -412,14 +457,20 @@ class OutlookClient extends BaseClient {
412
457
  }
413
458
  }
414
459
 
415
- /**
416
- * Close the client connection and clean up resources
417
- */
418
- async close() {
460
+ // Every background timer of the client, stopped on connect, close and delete
461
+ clearTimers() {
419
462
  clearTimeout(this.renewWatchTimer);
420
463
  clearTimeout(this.renewRetryTimer);
464
+ clearTimeout(this.fallbackPollTimer);
421
465
  this.cancelDeferredRetryTimer();
422
466
  this.cancelInitRetry();
467
+ }
468
+
469
+ /**
470
+ * Close the client connection and clean up resources
471
+ */
472
+ async close() {
473
+ this.clearTimers();
423
474
  this.closed = true;
424
475
 
425
476
  if (['init', 'connecting', 'syncing', 'connected'].includes(this.state)) {
@@ -436,8 +487,11 @@ class OutlookClient extends BaseClient {
436
487
  * (PUT /v1/account/{account}/sync). Outlook syncs via webhook subscriptions and delta
437
488
  * queries rather than a folder walk, so a manual sync refreshes the folder cache and queues
438
489
  * the missed-notification recovery, which then runs and is retried like any other change.
490
+ * @param {Object} [opts]
491
+ * @param {number} [opts.since] - Epoch ms to look back to instead of the usual window. Reaches
492
+ * past what announced messages are remembered for, so it may announce messages again
439
493
  */
440
- async syncMailboxes() {
494
+ async syncMailboxes({ since } = {}) {
441
495
  if (this.closed) {
442
496
  return null;
443
497
  }
@@ -448,7 +502,7 @@ class OutlookClient extends BaseClient {
448
502
  this.logger.warn({ msg: 'Failed to refresh folder cache for manual sync', account: this.account, err });
449
503
  }
450
504
 
451
- await this.accountObject.queueMissedRecovery();
505
+ await this.accountObject.queueMissedRecovery({ reason: 'manual', since });
452
506
  this.recoverMissedNotifications();
453
507
 
454
508
  return true;
@@ -464,6 +518,70 @@ class OutlookClient extends BaseClient {
464
518
  return true;
465
519
  }
466
520
 
521
+ /**
522
+ * Arms the periodic missed-notification recovery (EENGINE_OUTLOOK_FALLBACK_POLL_INTERVAL).
523
+ * Graph loses change notifications without reporting it - a `missed` lifecycle event only
524
+ * covers the deliveries our endpoint failed - and a lost one interleaves with deliveries that
525
+ * do arrive, so the pass runs on every interval rather than after a quiet spell. Each pass
526
+ * starts where the previous one finished, so one that missed nothing is one listing request.
527
+ * The request lives in memory, not in the deferred store: a restart re-arms the timer, and a
528
+ * failed pass is left to the next one, which covers its window too.
529
+ * @param {Object} [opts]
530
+ * @param {boolean} [opts.first] - The first pass after a connect, which runs at a random point
531
+ * of the interval so a restart does not send every account's pass to Graph at once
532
+ */
533
+ setupFallbackPollTimer({ first = false } = {}) {
534
+ clearTimeout(this.fallbackPollTimer);
535
+ if (this.closed || !this.fallbackPollInterval) {
536
+ return;
537
+ }
538
+
539
+ const delay = first ? Math.floor(Math.random() * this.fallbackPollInterval) : this.fallbackPollInterval;
540
+ this.fallbackPollTimer = setTimeout(() => {
541
+ this.requestPeriodicRecovery();
542
+ this.setupFallbackPollTimer();
543
+ }, delay);
544
+ this.fallbackPollTimer.unref();
545
+ }
546
+
547
+ /**
548
+ * One tick of the periodic recovery. Only a connected account is checked: in any other state
549
+ * Graph either refuses the request (an authentication error, a tenant that disabled the
550
+ * service) or nothing should be syncing (a parked or closed account), and the timer keeps
551
+ * running so the pass resumes once the account recovers
552
+ */
553
+ requestPeriodicRecovery() {
554
+ if (this.closed || this.state !== 'connected') {
555
+ this.logger.debug({ msg: 'Skipped periodic missed notification recovery', account: this.account, state: this.state });
556
+ return;
557
+ }
558
+ this.periodicRecoveryDue = true;
559
+ this.triggerSync();
560
+ }
561
+
562
+ /**
563
+ * Runs the periodic recovery pass the timer asked for, if any, unless a recovery earlier in the
564
+ * same drain already covered its window
565
+ * @param {Object} context - The drain's shared context
566
+ */
567
+ async runPeriodicRecovery(context) {
568
+ if (!this.periodicRecoveryDue) {
569
+ return;
570
+ }
571
+ this.periodicRecoveryDue = false;
572
+
573
+ try {
574
+ const since = await this.missedRecoveryStart(Date.now());
575
+ if (context.recoveredSince && context.recoveredSince <= since) {
576
+ return;
577
+ }
578
+ await this.syncMissedMessages({ since, options: () => this.getDrainFetchOptions(context), reason: 'periodic' });
579
+ context.recoveredSince = since;
580
+ } catch (err) {
581
+ this.logger.warn({ msg: 'Periodic missed notification recovery failed', account: this.account, err });
582
+ }
583
+ }
584
+
467
585
  /**
468
586
  * Get the current connection state from Redis
469
587
  */
@@ -475,10 +593,7 @@ class OutlookClient extends BaseClient {
475
593
  * Delete the account and clean up resources
476
594
  */
477
595
  async delete() {
478
- clearTimeout(this.renewWatchTimer);
479
- clearTimeout(this.renewRetryTimer);
480
- this.cancelDeferredRetryTimer();
481
- this.cancelInitRetry();
596
+ this.clearTimers();
482
597
  this.closed = true;
483
598
 
484
599
  // Best-effort: delete MS Graph subscription
@@ -850,7 +965,7 @@ class OutlookClient extends BaseClient {
850
965
  let raw;
851
966
 
852
967
  try {
853
- raw = await this.request(`/${this.oauth2UserPath}/messages/${emailId}/$value`, 'get', Buffer.alloc(0), { returnText: true });
968
+ raw = await this.request(`/${this.oauth2UserPath}/messages/${emailId}/$value`, 'get', Buffer.alloc(0), { returnBuffer: true });
854
969
  } catch (err) {
855
970
  switch (err.oauthRequest?.status) {
856
971
  case 404: {
@@ -883,7 +998,7 @@ class OutlookClient extends BaseClient {
883
998
  }
884
999
  }
885
1000
 
886
- return raw ? Buffer.from(raw) : null;
1001
+ return raw && raw.length ? raw : null;
887
1002
  }
888
1003
 
889
1004
  /**
@@ -1028,102 +1143,40 @@ class OutlookClient extends BaseClient {
1028
1143
  return { deleted: false };
1029
1144
  }
1030
1145
 
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
- }
1146
+ // Common headers for batch requests - include ImmutableId preference
1147
+ const batchHeaders = {
1148
+ 'Content-Type': 'application/json',
1149
+ Prefer: 'IdType="ImmutableId"'
1110
1150
  };
1111
1151
 
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
- }
1152
+ // Throttled items are retried by the batch helper; whatever still fails is reported
1153
+ const { successIds: updatedEmailIds, failedIds } = await graphApi.executeBatchOperation(
1154
+ this,
1155
+ emailIds,
1156
+ (emailId, reqId) =>
1157
+ force
1158
+ ? // Permanent delete
1159
+ {
1160
+ id: reqId,
1161
+ method: 'DELETE',
1162
+ url: `/${this.oauth2UserPath}/messages/${emailId}`,
1163
+ headers: batchHeaders
1164
+ }
1165
+ : // Move to trash
1166
+ {
1167
+ id: reqId,
1168
+ method: 'POST',
1169
+ url: `/${this.oauth2UserPath}/messages/${emailId}/move`,
1170
+ body: { destinationId: 'deleteditems' },
1171
+ headers: batchHeaders
1172
+ },
1173
+ 'delete'
1174
+ );
1124
1175
 
1125
1176
  return Object.assign(
1126
- { deleted: true },
1177
+ // Nothing was deleted when every item failed
1178
+ { deleted: updatedEmailIds.length > 0 },
1179
+ failedIds.length ? { failed: { emailIds: failedIds } } : {},
1127
1180
  !force
1128
1181
  ? {
1129
1182
  moved: {
@@ -1286,120 +1339,40 @@ class OutlookClient extends BaseClient {
1286
1339
  let currentCategories = new Map();
1287
1340
 
1288
1341
  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;
1342
+ // Fetch current categories for all messages in batches. A failed batch request has
1343
+ // to abort the update: without the current categories the PATCH below would replace
1344
+ // every message's category list with just the added labels
1345
+ let fetched;
1363
1346
  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);
1347
+ fetched = await graphApi.executeBatchOperation(
1348
+ this,
1349
+ emailIds,
1350
+ (emailId, reqId) => ({
1351
+ id: reqId,
1352
+ method: 'GET',
1353
+ url: `/${this.oauth2UserPath}/messages/${emailId}?$select=categories`,
1354
+ headers: {
1355
+ Prefer: 'IdType="ImmutableId"'
1372
1356
  }
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
- }
1357
+ }),
1358
+ 'fetchCategories'
1359
+ );
1385
1360
  } catch (err) {
1386
1361
  this.logger.error({
1387
- msg: 'Failed to run batch operation',
1362
+ msg: 'Failed to fetch current categories',
1388
1363
  account: this.account,
1389
- operation: 'update',
1390
1364
  err
1391
1365
  });
1392
1366
  throw err;
1393
- } finally {
1394
- batch = [];
1395
- messageMap = new Map();
1396
1367
  }
1397
- };
1398
-
1399
- let formatRequest = emailId => {
1400
- let reqId = `msg_${++idGen}`;
1401
- messageMap.set(reqId, emailId);
1368
+ for (let [emailId, body] of fetched.bodies) {
1369
+ if (body) {
1370
+ currentCategories.set(emailId, body.categories || []);
1371
+ }
1372
+ }
1373
+ }
1402
1374
 
1375
+ let formatRequest = (emailId, reqId) => {
1403
1376
  let bodyUpdates = { ...flagUpdates };
1404
1377
 
1405
1378
  // Handle categories for this specific message
@@ -1437,25 +1410,15 @@ class OutlookClient extends BaseClient {
1437
1410
  };
1438
1411
  };
1439
1412
 
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
- }
1413
+ // The category fetch for a message may have failed (logged above) - skipping it keeps its
1414
+ // existing categories instead of overwriting them with the additions
1415
+ let targetIds = needsCurrentCategories ? emailIds.filter(emailId => currentCategories.has(emailId)) : emailIds;
1416
+ let skippedIds = needsCurrentCategories ? emailIds.filter(emailId => !currentCategories.has(emailId)) : [];
1457
1417
 
1458
- return Object.assign({}, updates, { emailIds: updatedEmailIds });
1418
+ const { successIds: updatedEmailIds, failedIds: updateFailedIds } = await graphApi.executeBatchOperation(this, targetIds, formatRequest, 'update');
1419
+ const failedIds = skippedIds.concat(updateFailedIds);
1420
+
1421
+ return Object.assign({}, updates, { emailIds: updatedEmailIds }, failedIds.length ? { failed: { emailIds: failedIds } } : {});
1459
1422
  }
1460
1423
 
1461
1424
  /**
@@ -1549,54 +1512,10 @@ class OutlookClient extends BaseClient {
1549
1512
  return { path: targetFolder.pathName };
1550
1513
  }
1551
1514
 
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 {
1515
+ const { successIds: updatedEmailIds, failedIds } = await graphApi.executeBatchOperation(
1516
+ this,
1517
+ emailIds,
1518
+ (emailId, reqId) => ({
1600
1519
  id: reqId,
1601
1520
  method: 'POST',
1602
1521
  url: `/${this.oauth2UserPath}/messages/${emailId}/move`,
@@ -1605,23 +1524,11 @@ class OutlookClient extends BaseClient {
1605
1524
  'Content-Type': 'application/json',
1606
1525
  Prefer: 'IdType="ImmutableId"'
1607
1526
  }
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
- }
1527
+ }),
1528
+ 'move'
1529
+ );
1623
1530
 
1624
- return Object.assign({ path: targetFolder.pathName }, { emailIds: updatedEmailIds });
1531
+ return Object.assign({ path: targetFolder.pathName }, { emailIds: updatedEmailIds }, failedIds.length ? { failed: { emailIds: failedIds } } : {});
1625
1532
  }
1626
1533
 
1627
1534
  /**
@@ -1753,21 +1660,17 @@ class OutlookClient extends BaseClient {
1753
1660
  }
1754
1661
  }
1755
1662
 
1756
- // Resolve the folder path and special use
1663
+ // Resolve the folder path and special use. The message exists even when its folder is not
1664
+ // in the listing (a hidden folder, one the crawl skips): it is returned without a path.
1665
+ // Answering 404 here made new-message processing report an existing message as missing
1757
1666
  if (messageData.parentFolderId) {
1758
1667
  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;
1668
+ if (folder) {
1669
+ path = folder.pathName;
1670
+ specialUse = folder.specialUse;
1671
+ } else {
1672
+ this.logger.debug({ msg: 'Message folder is not in the mailbox listing', emailId, folderId: messageData.parentFolderId });
1767
1673
  }
1768
-
1769
- path = folder.pathName;
1770
- specialUse = folder.specialUse;
1771
1674
  }
1772
1675
 
1773
1676
  // Process email headers
@@ -1849,14 +1752,9 @@ class OutlookClient extends BaseClient {
1849
1752
  }
1850
1753
 
1851
1754
  // 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;
1755
+ formattedMessage.text.html = embedCidImages(formattedMessage.text.html, contentId => {
1756
+ let { content } = attachmentMap.get(contentId) || {};
1757
+ return content?.content && { contentType: content.contentType, content: content.content };
1860
1758
  });
1861
1759
  }
1862
1760
 
@@ -1874,9 +1772,25 @@ class OutlookClient extends BaseClient {
1874
1772
  options = options || {};
1875
1773
  await this.prepare();
1876
1774
 
1877
- // Pre-fetch folder listing once for all messages to avoid repeated lookups
1878
- const mailboxListing = await this.getMailboxListing();
1775
+ // The export calls this once per batch of messages, so the cached listing is used when
1776
+ // there is one: a live listing is a full folder crawl, and doing that per batch burned the
1777
+ // account's Graph throttling budget on a large export. Folders missing from it are
1778
+ // resolved one by one below, which refreshes the cache when the folder is new
1779
+ const mailboxListing = (await this.getCachedMailboxListing()) || (await this.getMailboxListing());
1879
1780
  const folderMap = new Map(mailboxListing.map(f => [f.id, f]));
1781
+ const lookupFolder = async folderId => {
1782
+ if (!folderMap.has(folderId)) {
1783
+ let folder = null;
1784
+ try {
1785
+ folder = (await this.resolveFolder(folderId, { byId: true })) || null;
1786
+ } catch (err) {
1787
+ this.logger.warn({ msg: 'Failed to resolve message folder', account: this.account, folderId, err });
1788
+ }
1789
+ // remembered either way, so a folder the listing never includes costs one lookup
1790
+ folderMap.set(folderId, folder);
1791
+ }
1792
+ return folderMap.get(folderId);
1793
+ };
1880
1794
 
1881
1795
  const results = [];
1882
1796
  let idGen = 0;
@@ -2005,7 +1919,7 @@ class OutlookClient extends BaseClient {
2005
1919
  // Resolve folder from pre-fetched map (O(1) lookup)
2006
1920
  let path, specialUse;
2007
1921
  if (messageData.parentFolderId) {
2008
- const folder = folderMap.get(messageData.parentFolderId);
1922
+ const folder = await lookupFolder(messageData.parentFolderId);
2009
1923
  if (folder) {
2010
1924
  path = folder.pathName;
2011
1925
  specialUse = folder.specialUse;
@@ -2185,87 +2099,74 @@ class OutlookClient extends BaseClient {
2185
2099
  convertMessageToUploadObject(emailObject) {
2186
2100
  let messageUploadObj = {};
2187
2101
 
2102
+ let addHeader = (name, value) => {
2103
+ if (!name || !value) {
2104
+ return;
2105
+ }
2106
+
2107
+ if (GRAPH_THREADING_PROPERTIES.has(name)) {
2108
+ let id = GRAPH_THREADING_PROPERTIES.get(name);
2109
+ // a caller-supplied In-Reply-To can sit next to the lowercase one a reference adds
2110
+ messageUploadObj.singleValueExtendedProperties = (messageUploadObj.singleValueExtendedProperties || []).filter(entry => entry.id !== id);
2111
+ messageUploadObj.singleValueExtendedProperties.push({ id, value: String(value) });
2112
+ return;
2113
+ }
2114
+
2115
+ // Everything else Graph either fills in from message fields (From, Reply-To, Date, ...)
2116
+ // or refuses outright
2117
+ if (!/^x-/i.test(name)) {
2118
+ return;
2119
+ }
2120
+
2121
+ messageUploadObj.internetMessageHeaders = messageUploadObj.internetMessageHeaders || [];
2122
+ messageUploadObj.internetMessageHeaders.push({ name, value });
2123
+ };
2124
+
2125
+ let toGraphAddress = entry => ({
2126
+ emailAddress: entry.name ? { address: entry.address, name: entry.name } : { address: entry.address }
2127
+ });
2128
+
2188
2129
  for (let key of Object.keys(emailObject)) {
2189
2130
  switch (key) {
2190
2131
  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
- }
2132
+ messageUploadObj.from = toGraphAddress(emailObject.from);
2199
2133
  break;
2200
2134
 
2201
2135
  case 'to':
2202
2136
  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
- }
2137
+ case 'bcc':
2138
+ messageUploadObj[`${key}Recipients`] = (emailObject[key] || []).map(toGraphAddress);
2217
2139
  break;
2218
- }
2219
2140
 
2220
2141
  case 'subject':
2221
2142
  messageUploadObj[key] = emailObject[key];
2222
2143
  break;
2223
2144
 
2224
2145
  case 'headers': {
2225
- messageUploadObj.internetMessageHeaders = messageUploadObj.internetMessageHeaders || [];
2226
2146
  for (let header of Object.keys(emailObject.headers)) {
2227
- messageUploadObj.internetMessageHeaders.push({
2228
- name: header.toLowerCase(),
2229
- value: emailObject.headers[header]
2230
- });
2147
+ addHeader(header.toLowerCase(), emailObject.headers[header]);
2231
2148
  }
2232
2149
  break;
2233
2150
  }
2234
2151
 
2235
2152
  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
- }
2153
+ for (let header of emailObject.headerLines) {
2154
+ // mailparser keeps the whole line; unfold it, a long References header arrives split over several lines
2155
+ let value = header.line
2156
+ ? header.line
2157
+ .substring(header.line.indexOf(':') + 1)
2158
+ .replace(/\r?\n[ \t]+/g, ' ')
2159
+ .trim()
2160
+ : '';
2161
+ addHeader(header.key, value);
2162
+ }
2163
+ break;
2164
+ }
2260
2165
 
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
- }
2166
+ case 'replyTo': {
2167
+ let entries = [].concat(emailObject.replyTo || []).filter(entry => entry?.address);
2168
+ if (entries.length) {
2169
+ messageUploadObj.replyTo = entries.map(toGraphAddress);
2269
2170
  }
2270
2171
  break;
2271
2172
  }
@@ -2295,9 +2196,12 @@ class OutlookClient extends BaseClient {
2295
2196
  if (attachment.cid) {
2296
2197
  // make sure that cid links to not use <content-id> format, otherwise this will be replaced
2297
2198
  attachmentEntry.contentId = attachment.cid.replace(/^[\s<]*|[\s>]*$/g, '');
2298
- if (cidReferences.has(attachmentEntry.contentId)) {
2199
+ // the reference grammar keeps a leading "<", so cid:<id> is collected as "<id"
2200
+ if (cidReferences.has(attachmentEntry.contentId) || cidReferences.has(`<${attachmentEntry.contentId}`)) {
2299
2201
  attachmentEntry.isInline = true;
2300
- emailObject.html.replace(new RegExp(`cid:<${attachment.cid}>`, 'g'), `cid:${attachment.cid}`);
2202
+ // A literal replace: the Content-ID is caller input, and as a RegExp
2203
+ // source a ( [ or \ in it threw a SyntaxError
2204
+ emailObject.html = emailObject.html.replaceAll(`cid:<${attachmentEntry.contentId}>`, `cid:${attachmentEntry.contentId}`);
2301
2205
  }
2302
2206
  }
2303
2207
  if (attachment.contentDisposition === 'inline') {
@@ -2323,8 +2227,9 @@ class OutlookClient extends BaseClient {
2323
2227
  };
2324
2228
  }
2325
2229
 
2326
- if (messageUploadObj.internetMessageHeaders && !messageUploadObj.internetMessageHeaders.length) {
2327
- delete messageUploadObj.internetMessageHeaders;
2230
+ if (messageUploadObj.internetMessageHeaders?.length > MAX_GRAPH_CUSTOM_HEADERS) {
2231
+ // keep the last ones, the headers added closest to sending
2232
+ messageUploadObj.internetMessageHeaders = messageUploadObj.internetMessageHeaders.slice(-MAX_GRAPH_CUSTOM_HEADERS);
2328
2233
  }
2329
2234
 
2330
2235
  return messageUploadObj;
@@ -2351,13 +2256,14 @@ class OutlookClient extends BaseClient {
2351
2256
  }
2352
2257
 
2353
2258
  // Parse raw message into structured format
2354
- let { emailObject, messageId, referencedMessage, documentStoreUsed } = await this.prepareRawMessage(data, {
2259
+ let { emailObject, messageId, referencedMessage } = await this.prepareRawMessage(data, {
2355
2260
  returnObject: true
2356
2261
  });
2357
2262
 
2358
2263
  let messageUploadObj = this.convertMessageToUploadObject(emailObject);
2359
2264
 
2360
- messageUploadObj.singleValueExtendedProperties = [];
2265
+ // may already hold the threading properties of a reply or a forward
2266
+ messageUploadObj.singleValueExtendedProperties = messageUploadObj.singleValueExtendedProperties || [];
2361
2267
 
2362
2268
  // Set message flags using MAPI properties
2363
2269
  // https://learn.microsoft.com/en-us/office/client-developer/outlook/mapi/pidtagmessageflags-canonical-property
@@ -2399,7 +2305,8 @@ class OutlookClient extends BaseClient {
2399
2305
  response: err.oauthRequest?.response?.error?.message || `Invalid message format`
2400
2306
  };
2401
2307
  error.code = err.oauthRequest?.response?.error?.code || 'InvalidMessage';
2402
- error.statusCode = 500; // do not retry sending
2308
+ // Graph refused the content, which is the caller's to fix, not a server fault
2309
+ error.statusCode = 400;
2403
2310
  throw error;
2404
2311
  }
2405
2312
 
@@ -2423,7 +2330,6 @@ class OutlookClient extends BaseClient {
2423
2330
  if (data.reference && data.reference.message) {
2424
2331
  response.reference = {
2425
2332
  message: data.reference.message,
2426
- documentStore: documentStoreUsed,
2427
2333
  success: referencedMessage ? true : false
2428
2334
  };
2429
2335
 
@@ -2627,11 +2533,10 @@ class OutlookClient extends BaseClient {
2627
2533
  let gatewayObject;
2628
2534
  if (data.gateway) {
2629
2535
  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
- }
2536
+ // The message was queued for this gateway, so it must not go out through the
2537
+ // provider API instead: a missing gateway throws GatewayNotFound and the job is
2538
+ // discarded, a Redis failure is thrown as is and the job retries
2539
+ gatewayData = await gatewayObject.loadGatewayData();
2635
2540
  }
2636
2541
 
2637
2542
  if (gatewayData) {
@@ -3265,9 +3170,9 @@ class OutlookClient extends BaseClient {
3265
3170
  * revoked - exhausts them within minutes and leaves the account with no subscription at all.
3266
3171
  * This pass used to read that count, find it at the cap and give up, waiting for a reconnect
3267
3172
  * that only a worker restart, an account update or a re-authorization brings; a tenant that
3268
- * fixed the cause an hour later was never noticed. Unlike the Gmail client there is no poller
3269
- * behind this to fall back on, so an account left unsubscribed syncs nothing at all while it
3270
- * waits. The counters are cleared before anything else is attempted, so an hour that could have
3173
+ * fixed the cause an hour later was never noticed. A failed subscription reports
3174
+ * `connectError`, which pauses the periodic recovery pass too, so an account left unsubscribed
3175
+ * syncs nothing at all while it waits. The counters are cleared before anything else is attempted, so an hour that could have
3271
3176
  * recovered gets the fast ladder back instead of one attempt every hour forever - a renewal
3272
3177
  * ladder as much as a creation one, since a subscription inside the renew window whose retries
3273
3178
  * are spent is not recreated by this pass at all and would otherwise never get another.
@@ -3607,7 +3512,7 @@ class OutlookClient extends BaseClient {
3607
3512
  } catch (err) {
3608
3513
  this.logger.error({ msg: 'Failed to acquire subscription renew lock', account: this.account, err });
3609
3514
  this.scheduleSubscriptionRetry({
3610
- delayMs: OUTLOOK_RETRY_BASE_DELAY * 1000,
3515
+ delayMs: OUTLOOK_SUBSCRIPTION_RETRY_BASE_DELAY * 1000,
3611
3516
  reason: 'lock_error',
3612
3517
  errorMsg: 'Subscription renew retry after lock error failed',
3613
3518
  fn: () => this.renewSubscription({ force: false })
@@ -3741,7 +3646,8 @@ class OutlookClient extends BaseClient {
3741
3646
  // Schedule retry with exponential backoff
3742
3647
  const retryCount = outlookSubscription.state.retryCount;
3743
3648
  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;
3649
+ const retryDelay =
3650
+ Math.min(OUTLOOK_SUBSCRIPTION_RETRY_BASE_DELAY * Math.pow(2, retryCount - 1), OUTLOOK_SUBSCRIPTION_RETRY_MAX_DELAY) * 1000;
3745
3651
 
3746
3652
  this.scheduleSubscriptionRetry({
3747
3653
  delayMs: retryDelay,
@@ -3805,7 +3711,7 @@ class OutlookClient extends BaseClient {
3805
3711
  // Do not forward clearExisting on retry: by the time the retry fires,
3806
3712
  // another path may have created a valid subscription that should not be cleared.
3807
3713
  this.scheduleSubscriptionRetry({
3808
- delayMs: OUTLOOK_RETRY_BASE_DELAY * 1000,
3714
+ delayMs: OUTLOOK_SUBSCRIPTION_RETRY_BASE_DELAY * 1000,
3809
3715
  reason: 'lock_error',
3810
3716
  errorMsg: 'Subscription ensure retry after lock error failed',
3811
3717
  fn: () => this.ensureSubscription()
@@ -3958,7 +3864,8 @@ class OutlookClient extends BaseClient {
3958
3864
  if (outlookSubscription.state?.state === 'error') {
3959
3865
  const createRetryCount = outlookSubscription.state.createRetryCount || 0;
3960
3866
  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;
3867
+ const retryDelay =
3868
+ Math.min(OUTLOOK_SUBSCRIPTION_RETRY_BASE_DELAY * Math.pow(2, createRetryCount - 1), OUTLOOK_SUBSCRIPTION_RETRY_MAX_DELAY) * 1000;
3962
3869
 
3963
3870
  this.scheduleSubscriptionRetry({
3964
3871
  delayMs: retryDelay,
@@ -4212,20 +4119,12 @@ class OutlookClient extends BaseClient {
4212
4119
  if (attachmentResponse?.contentType && !attachmentResponse?.contentBytes) {
4213
4120
  // fetch raw value instead, happens with message/rfc822 attachments
4214
4121
  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
- }
4122
+ // Raw bytes: a text round-trip would corrupt every non-UTF-8 byte of the message
4123
+ let rawAttachmentContent = await this.request(`/${this.oauth2UserPath}/messages/${emailId}/attachments/${id}/$value`, 'get', Buffer.alloc(0), {
4124
+ returnBuffer: true
4125
+ });
4126
+ if (rawAttachmentContent?.length) {
4127
+ content = options.returnBase64 ? rawAttachmentContent.toString('base64') : rawAttachmentContent;
4229
4128
  }
4230
4129
  } catch (err) {
4231
4130
  throw attachmentErrorHandler(err);
@@ -4286,13 +4185,15 @@ class OutlookClient extends BaseClient {
4286
4185
  }
4287
4186
  };
4288
4187
 
4289
- // Changes deferred for a retry go first, then the queue
4188
+ // Changes deferred for a retry go first, then the periodic recovery, then the queue
4290
4189
  try {
4291
4190
  await this.processDueDeferredEvents(handle);
4292
4191
  } catch (err) {
4293
4192
  this.logger.error({ msg: 'Failed to process deferred mailbox changes', account: this.account, err });
4294
4193
  }
4295
4194
 
4195
+ await this.runPeriodicRecovery(context);
4196
+
4296
4197
  while ((event = await this.accountObject.pullQueueEvent()) !== null) {
4297
4198
  processedAny = true;
4298
4199
  await handle(event);
@@ -4321,17 +4222,11 @@ class OutlookClient extends BaseClient {
4321
4222
  case 'created': {
4322
4223
  let messageData = await this.prepareNewMessage(event.message, await this.getDrainFetchOptions(context));
4323
4224
  if (messageData) {
4324
- // When an email is sent, multiple "created" events are triggered: one for the draft and one for the sent mail folder.
4325
- // However, since we process the event with a delay, we only observe the message stored in the Sent Mail folder.
4326
- // This happens because the message was already moved there by the time we began processing the initial event from the drafts folder.
4327
-
4328
- // Check rolling bucket lock to see if we recently processed the same new email event for the same folder
4329
- // A retry runs up to an hour later, past the short-lived dedupe buckets, while a
4330
- // recovery pass may have announced the message in the meantime
4331
- if (
4332
- (await this.isRecentlySeen(`${messageData.id}:created`, messageData.path)) ||
4333
- (event.attempt && (await this.getAnnounced([messageData.id])).has(messageData.id))
4334
- ) {
4225
+ // The announced set catches a duplicate notification, a retry, and a delivery
4226
+ // Graph kept retrying for hours after a recovery pass announced the message.
4227
+ // It is checked after the fetch because it is keyed by folder too, see
4228
+ // getAnnouncedKey()
4229
+ if ((await this.getAnnounced([messageData])).has(messageData.id)) {
4335
4230
  this.logger.debug({ msg: 'Ignore recently seen new email event', type: 'history-event', emailId: event.message });
4336
4231
  break;
4337
4232
  }
@@ -4345,12 +4240,14 @@ class OutlookClient extends BaseClient {
4345
4240
  }
4346
4241
 
4347
4242
  case 'missedRecovery': {
4348
- const since = await this.missedRecoveryStart(event.receivedAt);
4243
+ // An explicit start (Run sync `since`) is the operator's call and skips every floor
4244
+ const since = event.since || (await this.missedRecoveryStart(event.receivedAt));
4349
4245
  if (context.recoveredSince && context.recoveredSince <= since) {
4350
4246
  // an earlier request in the same drain already covered this window
4351
4247
  break;
4352
4248
  }
4353
- await this.syncMissedMessages({ since, options: await this.getDrainFetchOptions(context) });
4249
+ // a request stored before the reason was recorded came from the lifecycle webhook
4250
+ await this.syncMissedMessages({ since, options: () => this.getDrainFetchOptions(context), reason: event.reason || 'missed' });
4354
4251
  context.recoveredSince = since;
4355
4252
  break;
4356
4253
  }
@@ -4392,7 +4289,7 @@ class OutlookClient extends BaseClient {
4392
4289
  */
4393
4290
  async missedRecoveryStart(receivedAt) {
4394
4291
  const [lastNotification, announcedSince, recoveredUntil] = (
4395
- await this.redis.hmget(this.getAccountKey(), 'outlookLastNotification', 'outlookAnnouncedSince', 'outlookRecoveredUntil')
4292
+ await this.redis.hmget(this.getAccountKey(), 'outlookLastNotification', ANNOUNCED_SINCE_FIELD, 'outlookRecoveredUntil')
4396
4293
  ).map(Number);
4397
4294
 
4398
4295
  // 2-minute safety margin before the last known good notification and the last pass
@@ -4415,20 +4312,27 @@ class OutlookClient extends BaseClient {
4415
4312
 
4416
4313
  /**
4417
4314
  * Recover messages missed due to failed webhook delivery. Queued by the Graph 'missed'
4418
- * lifecycle event and by "Run sync" (see Account.queueMissedRecovery()), and run from the
4419
- * change drain, so a failure is retried like any other change. Lists the messages received
4420
- * since `since` oldest first, a page at a time, and announces the ones not announced yet
4315
+ * lifecycle event, by "Run sync" and by the periodic pass (see Account.queueMissedRecovery()),
4316
+ * and run from the change drain, so a failure is retried like any other change. Lists the
4317
+ * messages received since `since` oldest first, a page at a time, and announces the ones not
4318
+ * announced yet
4421
4319
  * @param {Object} opts
4422
4320
  * @param {number} opts.since - Epoch ms to look back to
4423
- * @param {Object} opts.options - Message fetch options
4321
+ * @param {Object|Function} opts.options - Message fetch options, or an async function returning
4322
+ * them, called only once a message needs fetching (a pass usually finds none)
4323
+ * @param {string} [opts.reason] - What asked for the pass: 'missed', 'manual' or 'periodic'
4424
4324
  */
4425
- async syncMissedMessages({ since, options }) {
4325
+ async syncMissedMessages({ since, options, reason = 'missed' }) {
4426
4326
  const startedAt = Date.now();
4427
4327
  const sinceTime = new Date(since);
4328
+ // a periodic pass that found nothing logs at debug, or every account would log each interval
4329
+ const periodic = reason === 'periodic';
4330
+ let fetchOptions = typeof options === 'function' ? null : options || {};
4428
4331
 
4429
- this.logger.info({
4332
+ this.logger[periodic ? 'debug' : 'info']({
4430
4333
  msg: 'Recovering missed notifications',
4431
4334
  account: this.account,
4335
+ reason,
4432
4336
  since: sinceTime.toISOString()
4433
4337
  });
4434
4338
 
@@ -4450,25 +4354,32 @@ class OutlookClient extends BaseClient {
4450
4354
  let messages = pageResult?.value || [];
4451
4355
  checked += messages.length;
4452
4356
 
4453
- let announced = await this.getAnnounced(messages.map(msg => msg.id));
4357
+ // The folder of each listed message, from the cached listing, so the ones already
4358
+ // announced are skipped without a fetch. One whose folder is not in the listing yet is
4359
+ // fetched and checked by the folder the fetch resolved
4360
+ const listing = messages.length ? (await this.getCachedMailboxListing()) || (await this.getMailboxListing()) : [];
4361
+ const folderPaths = new Map(listing.map(entry => [entry.id, entry.pathName]));
4362
+ const candidates = messages.map(msg => ({ id: msg.id, path: folderPaths.get(msg.parentFolderId) }));
4363
+ const announced = await this.getAnnounced(candidates.filter(candidate => candidate.path));
4454
4364
 
4455
- for (const msg of messages) {
4456
- if (announced.has(msg.id)) {
4365
+ for (const candidate of candidates) {
4366
+ if (announced.has(candidate.id)) {
4457
4367
  continue;
4458
4368
  }
4459
4369
  try {
4460
- let messageData = await this.prepareNewMessage(msg.id, options);
4461
- if (!messageData) {
4370
+ fetchOptions = fetchOptions || (await options());
4371
+ let messageData = await this.prepareNewMessage(candidate.id, fetchOptions);
4372
+ if (!messageData || (!candidate.path && (await this.getAnnounced([messageData])).has(messageData.id))) {
4462
4373
  continue;
4463
4374
  }
4464
4375
 
4465
4376
  // processNew() clears messageData.path
4466
4377
  const path = messageData.path;
4467
- await this.processNew(messageData, options);
4378
+ await this.processNew(messageData, fetchOptions);
4468
4379
  await this.markAnnounced(messageData.id, path);
4469
4380
  recoveredCount++;
4470
4381
  } catch (err) {
4471
- await this.deferFailedChangeEvent({ type: 'created', message: msg.id }, err);
4382
+ await this.deferFailedChangeEvent({ type: 'created', message: candidate.id }, err);
4472
4383
  }
4473
4384
  }
4474
4385
 
@@ -4476,13 +4387,20 @@ class OutlookClient extends BaseClient {
4476
4387
  reqPayload = null; // nextLink includes all query params
4477
4388
  }
4478
4389
 
4479
- this.logger.info({
4390
+ this.logger[periodic && !recoveredCount ? 'debug' : 'info']({
4480
4391
  msg: 'Missed notification recovery completed',
4481
4392
  account: this.account,
4393
+ reason,
4394
+ since: sinceTime.toISOString(),
4482
4395
  checked,
4483
4396
  recovered: recoveredCount
4484
4397
  });
4485
4398
 
4399
+ metricsMeta({ account: this.account }, this.logger, 'outlookMissedRecovery', 'inc', { reason, outcome: recoveredCount ? 'recovered' : 'none' });
4400
+ if (recoveredCount) {
4401
+ metricsMeta({ account: this.account }, this.logger, 'outlookMissedRecoveredMessages', 'inc', { reason }, recoveredCount);
4402
+ }
4403
+
4486
4404
  // Everything received before the pass started has been looked at. hSetExists, so a pass
4487
4405
  // that outlives a deleted account does not recreate its record
4488
4406
  await this.redis.hSetExists(this.getAccountKey(), 'outlookRecoveredUntil', startedAt.toString());
@@ -4901,47 +4819,55 @@ class OutlookClient extends BaseClient {
4901
4819
  .exec();
4902
4820
  }
4903
4821
 
4904
- // Messages announced as new over the last OUTLOOK_ANNOUNCED_RETENTION, by message ID. The
4905
- // short-lived dedupe buckets cover a burst of duplicate notifications; this covers a recovery
4906
- // pass that looks back hours
4822
+ // Messages announced as new over the last OUTLOOK_ANNOUNCED_RETENTION - the one record a
4823
+ // `created` notification and a recovery pass are both checked against. Keyed by message ID and
4824
+ // folder: an immutable ID survives the move from Drafts to Sent Items when a draft is sent, and
4825
+ // the sent copy is announced as new in its own folder, as it always was. The folder in the
4826
+ // member is why this is not the `announced` set earlier versions kept by ID alone, see
4827
+ // ANNOUNCED_SINCE_FIELD
4907
4828
  getAnnouncedKey() {
4908
- return `${REDIS_PREFIX}iam:${this.account}:announced`;
4829
+ return `${REDIS_PREFIX}iam:${this.account}:announced-in`;
4830
+ }
4831
+
4832
+ announcedMember(messageId, path) {
4833
+ // a Graph ID never contains a tab, a folder path may contain anything
4834
+ return `${messageId}\t${path || ''}`;
4909
4835
  }
4910
4836
 
4911
4837
  /**
4912
- * Marks a new message as announced, for both the dedupe buckets and the recovery pass
4838
+ * Marks a new message as announced in a folder, see getAnnounced()
4839
+ * @param {string} messageId
4840
+ * @param {string} path - The folder it was announced in
4913
4841
  */
4914
4842
  async markAnnounced(messageId, path) {
4915
4843
  const now = Date.now();
4916
4844
  const announcedKey = this.getAnnouncedKey();
4917
- const bucketKey = this.dedupeBucketKeys()[1];
4918
4845
  await this.redis
4919
4846
  .multi()
4920
- .hset(bucketKey, `${messageId}:created`, path)
4921
- .expire(bucketKey, 12 * 60)
4922
- .zadd(announcedKey, now, messageId)
4847
+ .zadd(announcedKey, now, this.announcedMember(messageId, path))
4923
4848
  .zremrangebyscore(announcedKey, '-inf', now - OUTLOOK_ANNOUNCED_RETENTION)
4924
4849
  .pexpire(announcedKey, OUTLOOK_ANNOUNCED_RETENTION)
4925
4850
  .exec();
4926
4851
  }
4927
4852
 
4928
4853
  /**
4929
- * @param {string[]} messageIds
4930
- * @returns {Promise<Set<string>>} The ones announced within OUTLOOK_ANNOUNCED_RETENTION
4854
+ * @param {{id: string, path: string}[]} messages - Messages and the folder each is in now
4855
+ * @returns {Promise<Set<string>>} The IDs of the ones announced in that folder within
4856
+ * OUTLOOK_ANNOUNCED_RETENTION
4931
4857
  */
4932
- async getAnnounced(messageIds) {
4933
- if (!messageIds.length) {
4858
+ async getAnnounced(messages) {
4859
+ if (!messages.length) {
4934
4860
  return new Set();
4935
4861
  }
4936
4862
  const announcedKey = this.getAnnouncedKey();
4937
4863
  const cutoff = Date.now() - OUTLOOK_ANNOUNCED_RETENTION;
4938
- // ZSCORE per ID rather than ZMSCORE, which needs Redis 6.2
4864
+ // ZSCORE per message rather than ZMSCORE, which needs Redis 6.2
4939
4865
  let pipeline = this.redis.pipeline();
4940
- for (const messageId of messageIds) {
4941
- pipeline = pipeline.zscore(announcedKey, messageId);
4866
+ for (const { id, path } of messages) {
4867
+ pipeline = pipeline.zscore(announcedKey, this.announcedMember(id, path));
4942
4868
  }
4943
4869
  const results = await pipeline.exec();
4944
- return new Set(messageIds.filter((id, i) => results[i][1] !== null && Number(results[i][1]) > cutoff));
4870
+ return new Set(messages.filter((message, i) => results[i][1] !== null && Number(results[i][1]) > cutoff).map(message => message.id));
4945
4871
  }
4946
4872
 
4947
4873
  /**
@@ -5023,4 +4949,4 @@ class OutlookClient extends BaseClient {
5023
4949
  }
5024
4950
  }
5025
4951
 
5026
- module.exports = { OutlookClient, encodeFolderSegment, decodeFolderSegment };
4952
+ module.exports = { OutlookClient, encodeFolderSegment, decodeFolderSegment, parseFallbackPollInterval };