emailengine-app 2.89.0 → 2.91.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 (120) hide show
  1. package/.ncurc.js +19 -8
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +73 -0
  4. package/Dockerfile +7 -3
  5. package/ENVIRONMENT.md +24 -23
  6. package/README.md +1 -1
  7. package/bin/healthcheck.js +1 -1
  8. package/copy-static-files.sh +0 -8
  9. package/data/google-crawlers.json +1 -1
  10. package/encrypt.js +1 -4
  11. package/lib/account/field-codec.js +396 -0
  12. package/lib/account-assignment.js +26 -9
  13. package/lib/account.js +196 -462
  14. package/lib/api-routes/account-routes.js +49 -6
  15. package/lib/api-routes/route-metadata.js +5 -2
  16. package/lib/api-routes/submit-routes.js +15 -2
  17. package/lib/api-token-auth.js +342 -274
  18. package/lib/arf-detect.js +174 -149
  19. package/lib/attachment-size.js +29 -0
  20. package/lib/autodetect-imap-settings.js +482 -296
  21. package/lib/consts.js +5 -5
  22. package/lib/db.js +1 -4
  23. package/lib/email-client/base-client.js +907 -780
  24. package/lib/email-client/gmail-client.js +557 -450
  25. package/lib/email-client/imap/cid-parts.js +61 -0
  26. package/lib/email-client/imap/mailbox.js +376 -422
  27. package/lib/email-client/imap/sync-operations.js +239 -178
  28. package/lib/email-client/imap-client.js +5 -5
  29. package/lib/email-client/message-builder.js +4 -5
  30. package/lib/email-client/new-message-steps.js +168 -2
  31. package/lib/email-client/outlook/graph-message.js +266 -0
  32. package/lib/email-client/outlook/subscription-expiry.js +30 -0
  33. package/lib/email-client/outlook-client.js +652 -808
  34. package/lib/get-raw-email.js +338 -232
  35. package/lib/get-secret.js +1 -4
  36. package/lib/imapproxy/imap-server.js +5 -5
  37. package/lib/license-subscription.js +60 -0
  38. package/lib/load-env.js +48 -0
  39. package/lib/logger-consts.js +37 -1
  40. package/lib/logger.js +1 -4
  41. package/lib/mail-probe.js +157 -0
  42. package/lib/mcp/tools.js +244 -207
  43. package/lib/metric-values.js +76 -0
  44. package/lib/metrics.js +320 -0
  45. package/lib/oauth/gmail.js +39 -120
  46. package/lib/oauth/http-request.js +195 -0
  47. package/lib/oauth/mail-ru.js +33 -60
  48. package/lib/oauth/outlook.js +37 -137
  49. package/lib/oauth/pubsub/google.js +176 -117
  50. package/lib/oauth2-apps.js +440 -463
  51. package/lib/openapi/build-document.js +10 -10
  52. package/lib/read-env-value.js +31 -7
  53. package/lib/redis-backend-warnings.js +70 -0
  54. package/lib/route-descriptors.js +78 -0
  55. package/lib/schemas.js +10 -1
  56. package/lib/sentry-integrations.js +299 -0
  57. package/lib/sentry.js +75 -27
  58. package/lib/sso-routes.js +249 -0
  59. package/lib/sso.js +29 -6
  60. package/lib/tools.js +17 -28
  61. package/lib/ui-routes/account-edit-form.js +198 -0
  62. package/lib/ui-routes/account-page.js +241 -0
  63. package/lib/ui-routes/account-routes.js +46 -349
  64. package/lib/ui-routes/account-setup.js +1 -1
  65. package/lib/ui-routes/auth-routes.js +10 -10
  66. package/lib/ui-routes/provider-signin.js +187 -0
  67. package/lib/ui-routes/route-helpers.js +1 -1
  68. package/lib/ui-routes/unsubscribe-routes.js +2 -2
  69. package/lib/ui-view-context.js +328 -0
  70. package/lib/utils/public-suffix.js +22 -101
  71. package/lib/web-safe-html.js +20 -7
  72. package/lib/worker-metrics.js +82 -0
  73. package/list-generate.js +2 -5
  74. package/package.json +28 -24
  75. package/sbom.json +360 -1030
  76. package/scripts/refresh-test-tokens.js +1 -1
  77. package/server.js +400 -677
  78. package/static/css/flyonui.css +1 -1
  79. package/static/css/public.css +55 -1
  80. package/static/css/src/app.tailwind.css +18 -0
  81. package/static/js/ee-client.js +2619 -645
  82. package/static/js/ui.js +12 -2
  83. package/static/licenses.html +224 -764
  84. package/translations/de.mo +0 -0
  85. package/translations/de.po +429 -390
  86. package/translations/en.mo +0 -0
  87. package/translations/en.po +342 -257
  88. package/translations/es.mo +0 -0
  89. package/translations/es.po +440 -395
  90. package/translations/et.mo +0 -0
  91. package/translations/et.po +425 -375
  92. package/translations/fr.mo +0 -0
  93. package/translations/fr.po +425 -383
  94. package/translations/it.mo +0 -0
  95. package/translations/it.po +441 -394
  96. package/translations/ja.mo +0 -0
  97. package/translations/ja.po +408 -335
  98. package/translations/messages.pot +188 -130
  99. package/translations/nl.mo +0 -0
  100. package/translations/nl.po +419 -382
  101. package/translations/pl.mo +0 -0
  102. package/translations/pl.po +425 -379
  103. package/translations/sv.mo +0 -0
  104. package/translations/sv.po +440 -388
  105. package/translations/tr.mo +0 -0
  106. package/translations/tr.po +441 -387
  107. package/views/account-identity-error.hbs +1 -1
  108. package/views/account-workspace-error.hbs +2 -2
  109. package/views/accounts/browse.hbs +19 -1
  110. package/views/accounts/register/imap-server.hbs +22 -7
  111. package/views/accounts/register/imap.hbs +3 -0
  112. package/views/accounts/register/index.hbs +1 -27
  113. package/views/accounts/register/provider-signin.hbs +58 -0
  114. package/views/oauth-scope-error.hbs +1 -1
  115. package/views/partials/provider_signin_button.hbs +30 -0
  116. package/views/queues/index.hbs +1 -1
  117. package/views/redirect.hbs +1 -1
  118. package/views/unsubscribe.hbs +6 -6
  119. package/workers/api.js +20 -451
  120. package/data/public_suffix_list.dat +0 -16698
@@ -4,7 +4,6 @@ const { accountDataKey } = require('../redis-keys');
4
4
  const { isOwnSent } = require('./new-message-steps');
5
5
  const { BaseClient, metricsMeta } = require('./base-client');
6
6
  const { isSafePathSegment } = require('../utils/provider-id');
7
- const { isTransientCredentialError } = require('./credential-errors');
8
7
  const { Account } = require('../account');
9
8
  const { runLocked, isContention } = require('../lock-run');
10
9
  const { checkAccountScopes } = require('../oauth/scope-checker');
@@ -23,12 +22,25 @@ const { detectMimeType, detectExtension } = require('nodemailer/lib/mime-funcs/m
23
22
  // Import Graph API module for MS Graph API handling
24
23
  const graphApi = require('./outlook/graph-api');
25
24
  const { buildRawSendMailRequest, buildStructuredSendMailRequest, buildDraftSendRequest } = require('./outlook/send-request');
26
- const { pushHeaderValue } = require('../utils/header-map');
27
- const { getMessageOtp } = require('../otp');
25
+ const { classifyExistingSubscription } = require('./outlook/subscription-expiry');
26
+ const {
27
+ GRAPH_MESSAGE_SELECT,
28
+ GRAPH_ATTACHMENT_EXPAND,
29
+ BATCH_MAX_RETRIES,
30
+ BATCH_RETRY_BASE_DELAY,
31
+ bodyPreferHeader,
32
+ buildListSelect,
33
+ isInefficientFilterError,
34
+ parseGraphHeaders,
35
+ mapGetMessageError,
36
+ buildMessageBatchRequests,
37
+ isRetryableBatchError,
38
+ reconcileMissingBatchResponses
39
+ } = require('./outlook/graph-message');
40
+ const { statusError } = require('../utils/status-error');
28
41
 
29
42
  const {
30
43
  REDIS_PREFIX,
31
- AUTH_ERROR_NOTIFY,
32
44
  CONNECT_ERROR_NOTIFY,
33
45
  EMAIL_SENT_NOTIFY,
34
46
  OUTLOOK_EXPIRATION_TIME,
@@ -150,9 +162,166 @@ function graphFailureStatus(err) {
150
162
  return Number(err?.statusCode) >= 400 ? Number(err.statusCode) : 400;
151
163
  }
152
164
 
165
+ // Search terms an OData filter cannot express. Refused by presence, whatever the value, and the
166
+ // first one in this order is the one reported.
167
+ const FILTER_UNSUPPORTED_KEYS = [
168
+ 'seq',
169
+ 'uid',
170
+ 'paths',
171
+ 'answered',
172
+ 'deleted',
173
+ 'modseq',
174
+
175
+ //
176
+ 'to',
177
+ 'cc',
178
+ 'bcc',
179
+ 'larger',
180
+ 'smaller'
181
+ ];
182
+
183
+ // Flag terms, only applied when the value is a boolean. The order is the order of the filter parts.
184
+ const BOOLEAN_FILTERS = [
185
+ ['unseen', value => `isRead eq ${value ? 'false' : 'true'}`],
186
+ ['seen', value => `isRead eq ${value ? 'true' : 'false'}`],
187
+ ['draft', value => `isDraft eq ${value ? 'true' : 'false'}`],
188
+ ['flagged', value => `flag/flagStatus eq '${value ? 'flagged' : 'notFlagged'}'`]
189
+ ];
190
+
191
+ // String terms, applied when the value is truthy, given the quoted term
192
+ const TERM_FILTERS = [
193
+ ['from', term => `(from/emailAddress/address eq ${term} or contains(from/emailAddress/name, ${term}))`],
194
+ ['subject', term => `contains(subject, ${term})`],
195
+ ['body', term => `contains(body/content, ${term})`],
196
+ ['emailId', term => `id eq ${term}`],
197
+ ['threadId', term => `conversationId eq ${term}`]
198
+ ];
199
+
200
+ // Date terms, applied when the value is truthy, compared unquoted
201
+ const DATE_FILTERS = [
202
+ ['before', 'receivedDateTime lt'],
203
+ ['sentBefore', 'sentDateTime lt'],
204
+ ['since', 'receivedDateTime gt'],
205
+ ['sentSince', 'sentDateTime gt']
206
+ ];
207
+
153
208
  // How often the same folder id missing from the cached listing may trigger a listing refresh
154
209
  const LISTING_REFRESH_INTERVAL = 5 * 60 * 1000;
155
210
 
211
+ /**
212
+ * The message shape of a minimalFields listing, for export indexing. Graph has no IMAP-style
213
+ * UIDs, so a numeric uid for the score tiebreaker is hashed from the message id
214
+ * @param {Object} messageData - Graph message
215
+ * @param {Date} [date] - Its receivedDateTime, when valid
216
+ */
217
+ function graphMinimalMessage(messageData, date) {
218
+ let uid = 0;
219
+ if (messageData.id) {
220
+ for (let i = 0; i < messageData.id.length; i++) {
221
+ uid = ((uid << 5) - uid + messageData.id.charCodeAt(i)) | 0;
222
+ }
223
+ uid = Math.abs(uid);
224
+ }
225
+
226
+ return {
227
+ id: messageData.id,
228
+ emailId: messageData.id,
229
+ threadId: messageData.conversationId || undefined,
230
+ date: date ? date.toISOString() : undefined,
231
+ uid,
232
+ size: 0 // Graph API doesn't provide size in minimal listing
233
+ };
234
+ }
235
+
236
+ // Graph message properties as IMAP flags
237
+ function graphFlags(messageData) {
238
+ const flags = [];
239
+ if (messageData.isRead) {
240
+ flags.push('\\Seen');
241
+ }
242
+ if (messageData.isDraft) {
243
+ flags.push('\\Draft');
244
+ }
245
+ if (messageData.flag?.flagStatus === 'flagged') {
246
+ flags.push('\\Flagged');
247
+ }
248
+ return flags;
249
+ }
250
+
251
+ /**
252
+ * Fills in the body text of a message: its encoded size by type, and its content when the
253
+ * requested text type includes it. A requested type the message does not have reads as empty
254
+ * @param {Object} messageData - Graph message
255
+ * @param {string} [textType] - 'plain', 'html' or '*'
256
+ * @param {Object} textContents - Filled in place, by type
257
+ * @param {Object} encodedTextSize - Filled in place, by type
258
+ */
259
+ function collectGraphText(messageData, textType, textContents, encodedTextSize) {
260
+ // set defaults for requested text type
261
+ if (textType && textType !== '*') {
262
+ textContents[textType] = '';
263
+ encodedTextSize[textType] = 0;
264
+ }
265
+
266
+ if (!messageData.body?.contentType) {
267
+ return;
268
+ }
269
+
270
+ let textContent = messageData.body.content || '';
271
+ // Graph names the plain text type 'text'
272
+ let textContentType = messageData.body.contentType === 'text' ? 'plain' : messageData.body.contentType;
273
+ encodedTextSize[textContentType] = Buffer.byteLength(textContent);
274
+ if (textType === textContentType || textType === '*') {
275
+ textContents[textContentType] = textContent;
276
+ }
277
+ }
278
+
279
+ function graphEmailAddress(entry) {
280
+ return entry.emailAddress;
281
+ }
282
+
283
+ // The addresses of a Graph recipient list, or undefined when it is missing or empty
284
+ function graphAddresses(recipients) {
285
+ return recipients?.length ? recipients.map(graphEmailAddress).filter(Boolean) : undefined;
286
+ }
287
+
288
+ /**
289
+ * The attachments of a message as the API lists them
290
+ * @param {Object} messageData - Graph message with a non-empty attachments list
291
+ * @param {string} [html] - The html text, when it was fetched: an inline image it references is embedded
292
+ */
293
+ function graphAttachments(messageData, html) {
294
+ const cidReferences = collectCidReferences(html);
295
+ const attachments = [];
296
+ for (const entry of messageData.attachments) {
297
+ const attachment = {
298
+ // Encode both message ID and attachment ID for later retrieval
299
+ id: msgpack.encode([messageData.id, entry.id]).toString('base64url'),
300
+ contentType: entry.contentType,
301
+ encodedSize: entry.size,
302
+ // MS Graph reports the size of the attachment item: the decoded file plus a little overhead
303
+ size: entry.size,
304
+ inline: !!entry.isInline
305
+ };
306
+
307
+ if (entry.name) {
308
+ attachment.filename = entry.name;
309
+ }
310
+
311
+ if (entry.contentId) {
312
+ // Normalize content ID format
313
+ attachment.contentId = entry.contentId.replace(/^<*/, '<').replace(/>*$/, '>');
314
+ // Check if attachment is embedded in HTML
315
+ if (cidReferences.has(attachment.contentId.replace(/^[\s<]*|[\s>]*$/g, ''))) {
316
+ attachment.embedded = true;
317
+ }
318
+ }
319
+
320
+ attachments.push(attachment);
321
+ }
322
+ return attachments;
323
+ }
324
+
156
325
  class OutlookClient extends BaseClient {
157
326
  constructor(account, options) {
158
327
  super(account, options);
@@ -313,18 +482,7 @@ class OutlookClient extends BaseClient {
313
482
  async init() {
314
483
  this.state = 'connecting';
315
484
  this.clearTimers();
316
- await this.setStateVal();
317
-
318
- await this.getAccount();
319
-
320
- // The auth-failure safety net switches an account off by setting `imap.disabled`, and
321
- // an API-backed account reaches it the same way an IMAP one does - its failures run
322
- // through the same setErrorState(). Checked before any credential work, because the
323
- // work that keeps failing for these accounts is the token refresh below.
324
- if (await this.isSyncDisabled()) {
325
- this.logger.info({ msg: 'Skipped connection setup', account: this.account, reason: 'disabled' });
326
- this.state = 'unset';
327
- await this.setStateVal();
485
+ if (!(await this.beginApiInit())) {
328
486
  return;
329
487
  }
330
488
 
@@ -337,60 +495,59 @@ class OutlookClient extends BaseClient {
337
495
 
338
496
  let accountData = await this.accountObject.loadAccountData();
339
497
 
340
- // Check if send-only mode
341
- // For outlookService (client_credentials), app permissions are configured in Entra.
342
- // The .default scope doesn't enumerate individual permissions, so assume full access.
343
- // For delegated accounts, scopes are checked at initialization and after account updates.
344
- const scopes = accountData.oauth2?.accessToken?.scope || accountData.oauth2?.scope || [];
345
- let hasSendScope, hasReadScope;
346
- if (this.oAuth2Client?.useClientCredentials) {
347
- hasSendScope = true;
348
- hasReadScope = true;
349
- } else {
350
- ({ hasSendScope, hasReadScope } = checkAccountScopes('outlook', scopes, this.logger));
351
- }
498
+ const isSendOnly = this.computeSendOnly(accountData);
499
+
500
+ // Verify authentication by fetching user profile
501
+ const profileRes = await this.probeApiAuth(() => this.request(`/${this.oauth2UserPath}`, 'get', {}));
352
502
 
353
- const isSendOnly = hasSendScope && !hasReadScope;
503
+ const updates = this.collectProfileUpdates(accountData, profileRes, isSendOnly);
504
+ if (Object.keys(updates).length) {
505
+ await this.accountObject.update(updates);
506
+ // Note: Metadata updates (name, locale) don't affect OAuth2 scopes
507
+ // No need to reload account data or recalculate scope-based flags
508
+ }
354
509
 
355
510
  this.logger.debug({
356
- msg: 'Account scopes loaded',
357
- account: this.account,
358
- scopes,
359
- hasSendScope,
360
- hasReadScope,
361
- isSendOnly
511
+ msg: isSendOnly ? 'Initializing Outlook send-only account' : 'Initializing Outlook account',
512
+ provider: accountData.oauth2.provider,
513
+ user: accountData.oauth2.auth?.user,
514
+ sendOnly: isSendOnly
362
515
  });
363
516
 
364
- // Verify authentication by fetching user profile
365
- let profileRes;
366
- try {
367
- profileRes = await this.request(`/${this.oauth2UserPath}`, 'get', {});
368
- } catch (err) {
369
- if (isTransientCredentialError(err)) {
370
- // Not a refused credential - left unflagged so the worker retries init() instead of
371
- // reporting an authentication error only re-authorization could clear
372
- throw err;
373
- }
374
-
375
- this.state = 'authenticationError';
376
- await this.setStateVal();
377
-
378
- err.authenticationFailed = true;
517
+ await this.finishApiInit(accountData.oauth2?.auth?.user);
379
518
 
380
- if (!err.errorNotified) {
381
- err.errorNotified = true;
382
- await this.notify(false, AUTH_ERROR_NOTIFY, {
383
- response: err.oauthRequest?.response?.error?.message || err.response,
384
- serverResponseCode: 'ApiRequestError'
385
- });
386
- }
519
+ if (!isSendOnly) {
520
+ await this.startFullAccessServices();
521
+ }
522
+ }
387
523
 
388
- throw err;
524
+ /**
525
+ * Which of the send and read scopes the account holds. For outlookService (client_credentials),
526
+ * app permissions are configured in Entra and the .default scope doesn't enumerate individual
527
+ * permissions, so full access is assumed. For delegated accounts, scopes are checked at
528
+ * initialization and after account updates.
529
+ * @param {Array<String>} scopes - Granted scopes
530
+ * @returns {{hasSendScope: Boolean, hasReadScope: Boolean}}
531
+ */
532
+ checkScopes(scopes) {
533
+ if (this.oAuth2Client?.useClientCredentials) {
534
+ return { hasSendScope: true, hasReadScope: true };
389
535
  }
536
+ return checkAccountScopes('outlook', scopes, this.logger);
537
+ }
390
538
 
539
+ /**
540
+ * Account updates the profile probe calls for: a locale that was never stored (full access
541
+ * only), and a changed user principal name (e.g., after an email address change), except for a
542
+ * delegated mailbox or a client credentials app, whose user is not the profile's
543
+ * @param {Object} accountData - Loaded account data
544
+ * @param {Object} profileRes - The Graph user profile
545
+ * @param {Boolean} isSendOnly - Whether the account is send-only
546
+ * @returns {Object} Updates for Account.update(), empty when nothing changed
547
+ */
548
+ collectProfileUpdates(accountData, profileRes, isSendOnly) {
391
549
  let updates = {};
392
550
 
393
- // Set locale from user preferences if not already set
394
551
  if (!accountData.locale && !isSendOnly) {
395
552
  let locale = (profileRes.preferredLanguage || '').toString().split(/[-_]/).shift().trim().toLowerCase();
396
553
  if (locale) {
@@ -398,70 +555,45 @@ class OutlookClient extends BaseClient {
398
555
  }
399
556
  }
400
557
 
401
- // Update username if it has changed (e.g., after email address change)
402
558
  if (
403
559
  profileRes.userPrincipalName &&
404
560
  accountData.oauth2.auth?.user !== profileRes.userPrincipalName &&
405
561
  !accountData.oauth2.auth?.delegatedUser &&
406
562
  !this.oAuth2Client?.useClientCredentials
407
563
  ) {
408
- updates.oauth2 = {
409
- partial: true,
410
- auth: Object.assign(accountData.oauth2.auth || {}, {
411
- // update username
412
- user: profileRes.userPrincipalName
413
- })
414
- };
415
- }
416
-
417
- if (Object.keys(updates).length) {
418
- await this.accountObject.update(updates);
419
- // Note: Metadata updates (name, locale) don't affect OAuth2 scopes
420
- // No need to reload account data or recalculate scope-based flags
564
+ updates.oauth2 = this.oauthUserUpdate(accountData.oauth2.auth, profileRes.userPrincipalName);
421
565
  }
422
566
 
423
- this.logger.debug({
424
- msg: isSendOnly ? 'Initializing Outlook send-only account' : 'Initializing Outlook account',
425
- provider: accountData.oauth2.provider,
426
- user: accountData.oauth2.auth?.user,
427
- sendOnly: isSendOnly
428
- });
429
-
430
- // Before the state flip below - see notifyAuthenticationSuccess(). This used to run after
431
- // it, which is why a Graph account never announced its first login at all
432
- await this.notifyAuthenticationSuccess(accountData.oauth2?.auth?.user);
433
-
434
- this.state = 'connected';
435
- await this.setStateVal();
436
-
437
- await emitChangeEvent(this.logger, this.account, 'state', this.state);
438
-
439
- if (!isSendOnly) {
440
- // additional operations for full access accounts
441
-
442
- // Reset subscription retry counts on reconnect - fresh auth = fresh slate
443
- await this.resetSubscriptionRetryState();
567
+ return updates;
568
+ }
444
569
 
445
- // A recovery pass must not look back past the point announced messages were first
446
- // recorded, or its first run after an upgrade would announce hours of mail again
447
- await this.redis.hsetnx(this.getAccountKey(), ANNOUNCED_SINCE_FIELD, Date.now().toString());
570
+ /**
571
+ * Starts what only a full access account runs, once it is connected: the change subscription,
572
+ * its renewal and the periodic recovery timers, the folder cache and the first sync
573
+ */
574
+ async startFullAccessServices() {
575
+ // Reset subscription retry counts on reconnect - fresh auth = fresh slate
576
+ await this.resetSubscriptionRetryState();
448
577
 
449
- // Set up webhook subscription for real-time updates
450
- await this.ensureSubscription();
451
- this.setupRenewWatchTimer();
452
- this.setupFallbackPollTimer({ first: true });
578
+ // A recovery pass must not look back past the point announced messages were first
579
+ // recorded, or its first run after an upgrade would announce hours of mail again
580
+ await this.redis.hsetnx(this.getAccountKey(), ANNOUNCED_SINCE_FIELD, Date.now().toString());
453
581
 
454
- // Cache mailbox folder structure
455
- try {
456
- await this.listMailboxes();
457
- } catch (err) {
458
- this.logger.warn({ msg: 'Failed to renew mailbox folder cache', err });
459
- }
582
+ // Set up webhook subscription for real-time updates
583
+ await this.ensureSubscription();
584
+ this.setupRenewWatchTimer();
585
+ this.setupFallbackPollTimer({ first: true });
460
586
 
461
- // Start processing any pending webhook notifications
462
- // (this also picks up the ones deferred for a retry before a restart)
463
- this.triggerSync();
587
+ // Cache mailbox folder structure
588
+ try {
589
+ await this.listMailboxes();
590
+ } catch (err) {
591
+ this.logger.warn({ msg: 'Failed to renew mailbox folder cache', err });
464
592
  }
593
+
594
+ // Start processing any pending webhook notifications
595
+ // (this also picks up the ones deferred for a retry before a restart)
596
+ this.triggerSync();
465
597
  }
466
598
 
467
599
  // Every background timer of the client, stopped on connect, close and delete
@@ -767,30 +899,7 @@ class OutlookClient extends BaseClient {
767
899
 
768
900
  await this.prepare();
769
901
 
770
- let path = [].concat(query.path || []).join('/');
771
-
772
- let folder;
773
- let cachedListing;
774
- let mailboxListing;
775
-
776
- // Handle special "\\All" path for cross-folder searches
777
- if (path === '\\All') {
778
- folder = null;
779
- cachedListing = await this.getCachedMailboxListing();
780
- mailboxListing = cachedListing || (await this.getMailboxListing());
781
- } else {
782
- folder = await this.resolveFolder(path);
783
- if (!folder) {
784
- let error = new Error('Listing failed');
785
- error.info = {
786
- response: 'Not able to find mailbox folder'
787
- };
788
- error.code = 'NotFound';
789
- error.statusCode = 404;
790
- throw error;
791
- }
792
- path = folder.pathName;
793
- }
902
+ let { path, folder, mailboxListing } = await this.resolveListingScope([].concat(query.path || []).join('/'));
794
903
 
795
904
  // Helper to resolve folder from parentFolderId
796
905
  let quickResolveFolder = parentFolderId => {
@@ -800,113 +909,25 @@ class OutlookClient extends BaseClient {
800
909
  return mailboxListing.find(entry => entry.id === parentFolderId);
801
910
  };
802
911
 
803
- // Pagination setup
804
- let page = Number(query.page) || 0;
805
- let pageSize = Math.abs(Number(query.pageSize) || 20);
806
- let $skiptoken;
807
-
808
- // Decode cursor if provided
809
- if (query.cursor) {
810
- let { cursorPage, skipToken } = this.decodeCursorStr(query.cursor);
811
- if (typeof cursorPage === 'number' && cursorPage >= 0) {
812
- page = cursorPage;
813
- }
814
- if (skipToken) {
815
- $skiptoken = skipToken;
816
- }
817
- }
818
-
819
- // Build select fields based on detail level
820
- let selectFields;
821
- let expandFields;
822
-
823
- if (options.minimalFields) {
824
- selectFields = ['id', 'conversationId', 'receivedDateTime'];
825
- } else if (options.metadataOnly) {
826
- selectFields = [
827
- 'id',
828
- 'conversationId',
829
- 'receivedDateTime',
830
- 'isRead',
831
- 'isDraft',
832
- 'flag',
833
- 'body',
834
- 'subject',
835
- 'from',
836
- 'replyTo',
837
- 'sender',
838
- 'internetMessageId'
839
- ];
840
- } else {
841
- selectFields = [
842
- 'id',
843
- 'conversationId',
844
- 'receivedDateTime',
845
- 'isRead',
846
- 'isDraft',
847
- 'flag',
848
- 'body',
849
- 'subject',
850
- 'from',
851
- 'replyTo',
852
- 'sender',
853
- 'toRecipients',
854
- 'ccRecipients',
855
- 'bccRecipients',
856
- 'internetMessageId',
857
- 'bodyPreview',
858
- 'categories'
859
- ];
860
- expandFields = 'attachments($select=id,name,contentType,size,isInline,microsoft.graph.fileAttachment/contentId)';
861
- }
862
-
863
- if (!folder) {
864
- selectFields.push('parentFolderId');
865
- }
912
+ let { page, pageSize, $skiptoken } = this.parseListPaging(query);
866
913
 
867
914
  // Build Graph API query parameters
915
+ let { $select, $expand } = buildListSelect(options, !folder);
868
916
  let requestQuery = {
869
917
  $count: true,
870
918
  $top: pageSize,
871
919
  $skip: page * pageSize,
872
920
  $skiptoken,
873
921
  $orderBy: 'receivedDateTime desc',
874
- $select: selectFields.join(','),
875
- $expand: expandFields
922
+ $select,
923
+ $expand
876
924
  };
877
925
 
878
- let useOutlookSearch = false;
879
- let skipToken = null;
880
- let labelFilterActive = false;
881
-
882
- // Handle search queries
883
- if (query.search) {
884
- if (query.useOutlookSearch) {
885
- // Use Outlook's native search syntax
886
- const $search = this.prepareSearchQuery(query.search);
887
- if ($search) {
888
- requestQuery.$search = `"${$search}"`;
889
- // remove unsupported request arguments for search
890
- for (let disabledParam of ['$skip', '$orderBy', '$count']) {
891
- delete requestQuery[disabledParam];
892
- }
893
- useOutlookSearch = true;
894
- }
895
- } else {
896
- // Use OData filters for more precise searching
897
- const $filter = this.prepareFilterQuery(query.search);
898
- if ($filter) {
899
- // we need to have receivedDateTime as the first filtering property, otherwise ordering will fail
900
- requestQuery.$filter = `receivedDateTime gt 1970-01-01T00:00:00.000Z and ${$filter}`;
901
- }
902
- // Category (label) filters compile to a categories/any() lambda. Some mailboxes refuse
903
- // to combine that with $orderBy; remember it so we can retry without ordering below.
904
- labelFilterActive = !!(query.search.labels && [].concat(query.search.labels.has || [], query.search.labels.not || []).some(Boolean));
905
- }
906
- }
926
+ let { useOutlookSearch, labelFilterActive } = this.applyListSearch(requestQuery, query.search, query.useOutlookSearch);
907
927
 
908
928
  let messages;
909
929
  let totalMessages;
930
+ let skipToken = null;
910
931
 
911
932
  let messagesUrl = `/${this.oauth2UserPath}/${folder ? `mailFolders/${folder.id}/` : ''}messages`;
912
933
  // The "not" form of a category filter may require advanced query capabilities; the header is
@@ -915,32 +936,7 @@ class OutlookClient extends BaseClient {
915
936
 
916
937
  // Execute the message list request
917
938
  try {
918
- let listing;
919
- try {
920
- listing = await this.request(messagesUrl, 'get', requestQuery, requestOptions);
921
- } catch (err) {
922
- // A categories/any() filter combined with $orderBy can be rejected as too complex
923
- // ("InefficientFilter"). Retry once without server-side ordering and sort the page locally.
924
- let graphCode = err?.oauthRequest?.response?.error?.code || '';
925
- let graphMessage = err?.oauthRequest?.response?.error?.message || '';
926
- let inefficientFilter = /inefficientfilter/i.test(graphCode) || /restriction or sort order is too complex/i.test(graphMessage);
927
-
928
- if (labelFilterActive && requestQuery.$orderBy && inefficientFilter) {
929
- this.logger.warn({
930
- msg: 'Graph rejected ordered category filter, retrying without server-side ordering',
931
- account: this.account,
932
- path
933
- });
934
- delete requestQuery.$orderBy;
935
- listing = await this.request(messagesUrl, 'get', requestQuery, requestOptions);
936
- // Without $orderBy the server no longer guarantees order; sort this page newest-first
937
- if (listing && Array.isArray(listing.value)) {
938
- listing.value.sort((a, b) => new Date(b.receivedDateTime) - new Date(a.receivedDateTime));
939
- }
940
- } else {
941
- throw err;
942
- }
943
- }
939
+ let listing = await this.requestListingWithFallback(messagesUrl, requestQuery, requestOptions, labelFilterActive, path);
944
940
 
945
941
  totalMessages = !isNaN(listing['@odata.count']) ? Number(listing['@odata.count']) : undefined;
946
942
 
@@ -975,9 +971,7 @@ class OutlookClient extends BaseClient {
975
971
  page = 0;
976
972
  }
977
973
 
978
- let nextPageCursor = page < pages - 1 || skipToken ? this.encodeCursorString(page + 1, skipToken) : null;
979
- // no previous page cursor if we are using skip token for paging
980
- let prevPageCursor = skipToken ? undefined : page > 0 ? this.encodeCursorString(Math.min(page - 1, pages - 1)) : null;
974
+ let { nextPageCursor, prevPageCursor } = this.buildListCursors(page, pages, skipToken);
981
975
 
982
976
  return {
983
977
  total: totalMessages,
@@ -989,6 +983,147 @@ class OutlookClient extends BaseClient {
989
983
  };
990
984
  }
991
985
 
986
+ /**
987
+ * Resolves what a listing covers: one folder, or for the special "\\All" path the whole
988
+ * mailbox, with the folder listing each message's parentFolderId is looked up in
989
+ * @param {string} path - Requested folder path
990
+ * @returns {Promise<{path: string, folder: (Object|null), mailboxListing: (Array|undefined)}>}
991
+ */
992
+ async resolveListingScope(path) {
993
+ if (path === '\\All') {
994
+ let mailboxListing = (await this.getCachedMailboxListing()) || (await this.getMailboxListing());
995
+ return { path, folder: null, mailboxListing };
996
+ }
997
+
998
+ let folder = await this.resolveFolder(path);
999
+ if (!folder) {
1000
+ let error = new Error('Listing failed');
1001
+ error.info = {
1002
+ response: 'Not able to find mailbox folder'
1003
+ };
1004
+ error.code = 'NotFound';
1005
+ error.statusCode = 404;
1006
+ throw error;
1007
+ }
1008
+
1009
+ return { path: folder.pathName, folder };
1010
+ }
1011
+
1012
+ /**
1013
+ * Reads the page, the page size and a Graph skip token off a listing query. A cursor, when
1014
+ * given, wins over the page number
1015
+ * @param {Object} query - Listing query
1016
+ * @returns {{page: number, pageSize: number, $skiptoken: (string|undefined)}}
1017
+ */
1018
+ parseListPaging(query) {
1019
+ let page = Number(query.page) || 0;
1020
+ let pageSize = Math.abs(Number(query.pageSize) || 20);
1021
+ let $skiptoken;
1022
+
1023
+ // Decode cursor if provided
1024
+ if (query.cursor) {
1025
+ let { cursorPage, skipToken } = this.decodeCursorStr(query.cursor);
1026
+ if (typeof cursorPage === 'number' && cursorPage >= 0) {
1027
+ page = cursorPage;
1028
+ }
1029
+ if (skipToken) {
1030
+ $skiptoken = skipToken;
1031
+ }
1032
+ }
1033
+
1034
+ return { page, pageSize, $skiptoken };
1035
+ }
1036
+
1037
+ /**
1038
+ * Adds a search to the listing query, as Outlook's own $search syntax or as an OData filter
1039
+ * @param {Object} requestQuery - The listing query, modified in place
1040
+ * @param {Object} [search] - Search terms
1041
+ * @param {boolean} [useOutlookSearch] - Use $search instead of $filter
1042
+ * @returns {{useOutlookSearch: boolean, labelFilterActive: boolean}} Whether $search went out,
1043
+ * and whether the filter carries a category (label) term
1044
+ */
1045
+ applyListSearch(requestQuery, search, useOutlookSearch) {
1046
+ let result = { useOutlookSearch: false, labelFilterActive: false };
1047
+
1048
+ if (!search) {
1049
+ return result;
1050
+ }
1051
+
1052
+ if (useOutlookSearch) {
1053
+ // Use Outlook's native search syntax
1054
+ const $search = this.prepareSearchQuery(search);
1055
+ if ($search) {
1056
+ requestQuery.$search = `"${$search}"`;
1057
+ // remove unsupported request arguments for search
1058
+ for (let disabledParam of ['$skip', '$orderBy', '$count']) {
1059
+ delete requestQuery[disabledParam];
1060
+ }
1061
+ result.useOutlookSearch = true;
1062
+ }
1063
+ return result;
1064
+ }
1065
+
1066
+ // Use OData filters for more precise searching
1067
+ const $filter = this.prepareFilterQuery(search);
1068
+ if ($filter) {
1069
+ // we need to have receivedDateTime as the first filtering property, otherwise ordering will fail
1070
+ requestQuery.$filter = `receivedDateTime gt 1970-01-01T00:00:00.000Z and ${$filter}`;
1071
+ }
1072
+ // Category (label) filters compile to a categories/any() lambda. Some mailboxes refuse
1073
+ // to combine that with $orderBy; remember it so we can retry without ordering.
1074
+ result.labelFilterActive = !!(search.labels && [].concat(search.labels.has || [], search.labels.not || []).some(Boolean));
1075
+
1076
+ return result;
1077
+ }
1078
+
1079
+ /**
1080
+ * Runs the listing request. A categories/any() filter combined with $orderBy can be rejected
1081
+ * as too complex ("InefficientFilter"); that is retried once without server-side ordering and
1082
+ * the page sorted locally
1083
+ * @param {string} messagesUrl - Listing URL
1084
+ * @param {Object} requestQuery - Listing query, loses $orderBy on a retry
1085
+ * @param {Object} [requestOptions] - Request options
1086
+ * @param {boolean} labelFilterActive - Whether the filter carries a category term
1087
+ * @param {string} path - Listed path, for the log
1088
+ * @returns {Promise<Object>} Graph listing response
1089
+ */
1090
+ async requestListingWithFallback(messagesUrl, requestQuery, requestOptions, labelFilterActive, path) {
1091
+ try {
1092
+ return await this.request(messagesUrl, 'get', requestQuery, requestOptions);
1093
+ } catch (err) {
1094
+ if (!labelFilterActive || !requestQuery.$orderBy || !isInefficientFilterError(err)) {
1095
+ throw err;
1096
+ }
1097
+
1098
+ this.logger.warn({
1099
+ msg: 'Graph rejected ordered category filter, retrying without server-side ordering',
1100
+ account: this.account,
1101
+ path
1102
+ });
1103
+ delete requestQuery.$orderBy;
1104
+ let listing = await this.request(messagesUrl, 'get', requestQuery, requestOptions);
1105
+ // Without $orderBy the server no longer guarantees order; sort this page newest-first
1106
+ if (listing && Array.isArray(listing.value)) {
1107
+ listing.value.sort((a, b) => new Date(b.receivedDateTime) - new Date(a.receivedDateTime));
1108
+ }
1109
+ return listing;
1110
+ }
1111
+ }
1112
+
1113
+ /**
1114
+ * The paging cursors of a listing page. A skip token pages forward only
1115
+ * @param {number} page - Current page
1116
+ * @param {number} [pages] - Page count, unknown for a $search
1117
+ * @param {string|null} skipToken - Graph skip token of the next page
1118
+ * @returns {{nextPageCursor: (string|null), prevPageCursor: (string|null|undefined)}}
1119
+ */
1120
+ buildListCursors(page, pages, skipToken) {
1121
+ let nextPageCursor = page < pages - 1 || skipToken ? this.encodeCursorString(page + 1, skipToken) : null;
1122
+ // no previous page cursor if we are using skip token for paging
1123
+ let prevPageCursor = skipToken ? undefined : page > 0 ? this.encodeCursorString(Math.min(page - 1, pages - 1)) : null;
1124
+ return { nextPageCursor, prevPageCursor };
1125
+ }
1126
+
992
1127
  /**
993
1128
  * Get the raw RFC822 message content
994
1129
  */
@@ -1000,35 +1135,16 @@ class OutlookClient extends BaseClient {
1000
1135
  try {
1001
1136
  raw = await this.request(`/${this.oauth2UserPath}/messages/${emailId}/$value`, 'get', Buffer.alloc(0), { returnBuffer: true });
1002
1137
  } catch (err) {
1003
- switch (err.oauthRequest?.status) {
1004
- case 404: {
1005
- let error = new Error('Unknown message');
1006
- error.info = {
1007
- response: `Message does not exist`
1008
- };
1009
- error.code = 'NotFound';
1010
- error.statusCode = 404;
1011
- throw error;
1012
- }
1013
-
1014
- case 400: {
1015
- let error = new Error('Invalid request');
1016
- error.info = {
1017
- response: err.oauthRequest?.response?.error?.message || `Invalid request`
1018
- };
1019
- error.code = err.oauthRequest?.response?.error?.code || 'InvalidRequest';
1020
- error.statusCode = 400;
1021
- throw error;
1022
- }
1023
-
1024
- default:
1025
- this.logger.error({
1026
- msg: 'Failed to fetch raw message',
1027
- emailId,
1028
- err
1029
- });
1030
- throw err;
1138
+ let error = mapGetMessageError(err);
1139
+ if (error) {
1140
+ throw error;
1031
1141
  }
1142
+ this.logger.error({
1143
+ msg: 'Failed to fetch raw message',
1144
+ emailId,
1145
+ err
1146
+ });
1147
+ throw err;
1032
1148
  }
1033
1149
 
1034
1150
  return raw && raw.length ? raw : null;
@@ -1615,133 +1731,51 @@ class OutlookClient extends BaseClient {
1615
1731
 
1616
1732
  let messageData, path, specialUse;
1617
1733
 
1618
- // Prepare request options with appropriate Prefer header for body content type
1619
- let requestOptions = {};
1620
- if (options.textType === 'plain') {
1621
- // Request plain text format from MS Graph API
1622
- requestOptions.headers = {
1623
- Prefer: 'outlook.body-content-type="text"'
1624
- };
1625
- } else if (options.textType === 'html') {
1626
- // Request HTML format from MS Graph API
1627
- requestOptions.headers = {
1628
- Prefer: 'outlook.body-content-type="html"'
1629
- };
1630
- }
1734
+ // Prepare request options with appropriate Prefer header for body content type.
1631
1735
  // If textType is '*' or undefined, don't set the preference and let MS Graph return the default format
1736
+ let preferHeader = bodyPreferHeader(options.textType);
1737
+ let requestOptions = preferHeader ? { headers: { Prefer: preferHeader } } : {};
1632
1738
 
1633
1739
  try {
1634
1740
  messageData = await this.request(
1635
1741
  `/${this.oauth2UserPath}/messages/${emailId}`,
1636
1742
  'get',
1637
1743
  {
1638
- // 'internetMessageHeaders' is not included by default, so have to list all required fields
1639
- $select: [
1640
- 'id',
1641
- 'conversationId',
1642
- 'receivedDateTime',
1643
- 'isRead',
1644
- 'isDraft',
1645
- 'flag',
1646
- 'body',
1647
- 'subject',
1648
- 'from',
1649
- 'replyTo',
1650
- 'sender',
1651
- 'toRecipients',
1652
- 'ccRecipients',
1653
- 'bccRecipients',
1654
- 'internetMessageId',
1655
- 'bodyPreview',
1656
- 'internetMessageHeaders',
1657
- 'parentFolderId',
1658
- 'categories'
1659
- ].join(','),
1660
- $expand: 'attachments($select=id,name,contentType,size,isInline,microsoft.graph.fileAttachment/contentId)'
1744
+ $select: GRAPH_MESSAGE_SELECT,
1745
+ $expand: GRAPH_ATTACHMENT_EXPAND
1661
1746
  },
1662
1747
  requestOptions
1663
1748
  );
1664
1749
  } catch (err) {
1665
- switch (err.oauthRequest?.status) {
1666
- case 404: {
1667
- let error = new Error('Unknown message');
1668
- error.info = {
1669
- response: `Message does not exist`
1670
- };
1671
- error.code = 'NotFound';
1672
- error.statusCode = 404;
1673
- throw error;
1674
- }
1675
-
1676
- case 400: {
1677
- let error = new Error('Invalid request');
1678
- error.info = {
1679
- response: err.oauthRequest?.response?.error?.message || `Invalid request`
1680
- };
1681
- error.code = err.oauthRequest?.response?.error?.code || 'InvalidRequest';
1682
- error.statusCode = 400;
1683
- throw error;
1684
- }
1685
-
1686
- default:
1687
- this.logger.error({
1688
- msg: 'Failed to fetch message data',
1689
- emailId,
1690
- err
1691
- });
1692
- throw err;
1750
+ let error = mapGetMessageError(err);
1751
+ if (error) {
1752
+ throw error;
1693
1753
  }
1754
+ this.logger.error({
1755
+ msg: 'Failed to fetch message data',
1756
+ emailId,
1757
+ err
1758
+ });
1759
+ throw err;
1694
1760
  }
1695
1761
 
1696
1762
  // Resolve the folder path and special use. The message exists even when its folder is not
1697
1763
  // in the listing (a hidden folder, one the crawl skips): it is returned without a path.
1698
1764
  // Answering 404 here made new-message processing report an existing message as missing
1699
- if (messageData.parentFolderId) {
1700
- let folder = await this.resolveFolder(messageData.parentFolderId, { byId: true });
1701
- if (folder) {
1702
- path = folder.pathName;
1703
- specialUse = folder.specialUse;
1704
- } else {
1705
- this.logger.debug({ msg: 'Message folder is not in the mailbox listing', emailId, folderId: messageData.parentFolderId });
1706
- }
1707
- }
1708
-
1709
- // Process email headers
1710
- if (messageData.internetMessageHeaders) {
1711
- let headers = {};
1712
-
1713
- for (let header of messageData?.internetMessageHeaders || []) {
1714
- let { name, value } = header;
1715
- name = (name || '').toString().trim().toLowerCase();
1716
-
1717
- value = (value || '').toString().trim();
1718
- if (!pushHeaderValue(headers, name, value)) {
1719
- continue;
1720
- }
1721
-
1722
- // Extract specific headers for easier access
1723
- switch (name) {
1724
- case 'in-reply-to': {
1725
- messageData.inReplyTo = value;
1726
- break;
1727
- }
1728
- }
1765
+ if (messageData.parentFolderId) {
1766
+ let folder = await this.resolveFolder(messageData.parentFolderId, { byId: true });
1767
+ if (folder) {
1768
+ path = folder.pathName;
1769
+ specialUse = folder.specialUse;
1770
+ } else {
1771
+ this.logger.debug({ msg: 'Message folder is not in the mailbox listing', emailId, folderId: messageData.parentFolderId });
1729
1772
  }
1730
-
1731
- messageData.headers = headers;
1732
1773
  }
1733
1774
 
1734
- const formattedMessage = this.formatMessage(messageData, {
1735
- extended: true,
1736
- path,
1737
- textType: options.textType,
1738
- maxBytes: options.maxBytes,
1739
- showPath: options.showPath
1740
- });
1775
+ // Process email headers
1776
+ parseGraphHeaders(messageData);
1741
1777
 
1742
- if (specialUse) {
1743
- formattedMessage.messageSpecialUse = specialUse;
1744
- }
1778
+ const formattedMessage = this.formatFetchedGraphMessage(messageData, path, specialUse, options);
1745
1779
 
1746
1780
  // Mark as seen if requested
1747
1781
  if (options.markAsSeen && (!formattedMessage.flags || !formattedMessage.flags.includes('\\Seen'))) {
@@ -1768,32 +1802,67 @@ class OutlookClient extends BaseClient {
1768
1802
 
1769
1803
  // Embed attached images as data URLs
1770
1804
  if (options.embedAttachedImages && formattedMessage.text?.html && formattedMessage.attachments) {
1771
- let attachmentMap = new Map();
1772
- let cidReferences = collectCidReferences(formattedMessage.text.html);
1773
-
1774
- // Collect all referenced inline attachments
1775
- for (let attachment of formattedMessage.attachments) {
1776
- let contentId = attachment.contentId && attachment.contentId.replace(/^<|>$/g, '');
1777
- if (contentId && !attachmentMap.has(contentId) && cidReferences.has(contentId)) {
1778
- attachmentMap.set(contentId, {
1779
- attachment,
1780
- content: await this.getAttachmentContent(attachment.id, {
1781
- returnBase64: true
1782
- })
1783
- });
1784
- }
1785
- }
1805
+ formattedMessage.text.html = await this.embedInlineAttachments(formattedMessage.text.html, formattedMessage.attachments);
1806
+ }
1786
1807
 
1787
- // Replace cid: references with data URLs
1788
- formattedMessage.text.html = embedCidImages(formattedMessage.text.html, contentId => {
1789
- let { content } = attachmentMap.get(contentId) || {};
1790
- return content?.content && { contentType: content.contentType, content: content.content };
1791
- });
1808
+ return formattedMessage;
1809
+ }
1810
+
1811
+ /**
1812
+ * Formats a fetched Graph message the way the message details are returned
1813
+ * @param {Object} messageData - Graph message with its headers parsed
1814
+ * @param {string} [path] - Folder path
1815
+ * @param {string} [specialUse] - Special use of the folder
1816
+ * @param {Object} options - Fetch options (textType, maxBytes, showPath)
1817
+ * @returns {Object} Formatted message
1818
+ */
1819
+ formatFetchedGraphMessage(messageData, path, specialUse, options) {
1820
+ const formattedMessage = this.formatMessage(messageData, {
1821
+ extended: true,
1822
+ path,
1823
+ textType: options.textType,
1824
+ maxBytes: options.maxBytes,
1825
+ showPath: options.showPath
1826
+ });
1827
+
1828
+ if (specialUse) {
1829
+ formattedMessage.messageSpecialUse = specialUse;
1792
1830
  }
1793
1831
 
1794
1832
  return formattedMessage;
1795
1833
  }
1796
1834
 
1835
+ /**
1836
+ * Replaces cid: references in html with data URLs of the attachments they point to. Each
1837
+ * referenced content id is downloaded once
1838
+ * @param {string} html - Message html
1839
+ * @param {Object[]} attachments - Attachments of the formatted message
1840
+ * @returns {Promise<string>} The html with the images embedded
1841
+ */
1842
+ async embedInlineAttachments(html, attachments) {
1843
+ let attachmentMap = new Map();
1844
+ let cidReferences = collectCidReferences(html);
1845
+
1846
+ // Collect all referenced inline attachments
1847
+ for (let attachment of attachments) {
1848
+ let contentId = attachment.contentId && attachment.contentId.replace(/^<|>$/g, '');
1849
+ if (contentId && !attachmentMap.has(contentId) && cidReferences.has(contentId)) {
1850
+ attachmentMap.set(contentId, {
1851
+ attachment,
1852
+ content: await this.getAttachmentContent(attachment.id, {
1853
+ returnBase64: true
1854
+ })
1855
+ });
1856
+ }
1857
+ }
1858
+
1859
+ // Replace cid: references with data URLs
1860
+ return embedCidImages(html, contentId => {
1861
+ let { content } = attachmentMap.get(contentId) || {};
1862
+ return content?.content && { contentType: content.contentType, content: content.content };
1863
+ });
1864
+ }
1865
+
1797
1866
  /**
1798
1867
  * Fetches multiple messages using MS Graph batch API for efficient export operations
1799
1868
  * Uses /$batch endpoint to send up to 20 message requests in a single HTTP call
@@ -1827,40 +1896,11 @@ class OutlookClient extends BaseClient {
1827
1896
 
1828
1897
  const results = [];
1829
1898
  let idGen = 0;
1830
-
1831
- // Build select fields for batch request
1832
- const selectFields = [
1833
- 'id',
1834
- 'conversationId',
1835
- 'receivedDateTime',
1836
- 'isRead',
1837
- 'isDraft',
1838
- 'flag',
1839
- 'body',
1840
- 'subject',
1841
- 'from',
1842
- 'replyTo',
1843
- 'sender',
1844
- 'toRecipients',
1845
- 'ccRecipients',
1846
- 'bccRecipients',
1847
- 'internetMessageId',
1848
- 'bodyPreview',
1849
- 'internetMessageHeaders',
1850
- 'parentFolderId',
1851
- 'categories'
1852
- ].join(',');
1853
-
1854
- const expandFields = 'attachments($select=id,name,contentType,size,isInline,microsoft.graph.fileAttachment/contentId)';
1899
+ const nextRequestId = () => `msg_${++idGen}`;
1855
1900
 
1856
1901
  // Build Prefer header for body content type
1857
1902
  // Note: IdType="ImmutableId" is added by requestWithRetry automatically
1858
- let preferHeader = '';
1859
- if (options.textType === 'plain') {
1860
- preferHeader = 'outlook.body-content-type="text"';
1861
- } else if (options.textType === 'html') {
1862
- preferHeader = 'outlook.body-content-type="html"';
1863
- }
1903
+ const preferHeader = bodyPreferHeader(options.textType);
1864
1904
 
1865
1905
  // Get configured batch size, capped at MS Graph API limit
1866
1906
  const settingsBatchSize = await settings.get('outlookExportBatchSize');
@@ -1868,166 +1908,137 @@ class OutlookClient extends BaseClient {
1868
1908
 
1869
1909
  for (let i = 0; i < emailIds.length; i += batchSize) {
1870
1910
  const batch = emailIds.slice(i, i + batchSize);
1871
- const messageMap = new Map();
1872
1911
 
1873
1912
  // Build batch request with up to MAX_BATCH_SIZE individual requests
1874
- const requests = batch.map(emailId => {
1875
- const reqId = `msg_${++idGen}`;
1876
- messageMap.set(reqId, emailId);
1877
-
1878
- const request = {
1879
- id: reqId,
1880
- method: 'GET',
1881
- url: `/${this.oauth2UserPath}/messages/${emailId}?$select=${selectFields}&$expand=${expandFields}`
1882
- };
1883
-
1884
- // Add Prefer header for body content type if specified
1885
- if (preferHeader) {
1886
- request.headers = { Prefer: preferHeader };
1887
- }
1888
-
1889
- return request;
1890
- });
1913
+ const { requests, messageMap } = buildMessageBatchRequests(batch, this.oauth2UserPath, preferHeader, nextRequestId);
1891
1914
 
1892
1915
  // Submit batch request - single HTTP call for up to 20 messages
1893
- // Retry on transient errors (429 rate limit, 5xx server errors)
1894
- const BATCH_MAX_RETRIES = 3;
1895
- const BATCH_RETRY_BASE_DELAY = 5000;
1896
-
1897
- let responseData;
1898
- let batchSuccess = false;
1899
-
1900
- for (let attempt = 0; attempt <= BATCH_MAX_RETRIES; attempt++) {
1901
- try {
1902
- responseData = await this.request('/$batch', 'post', { requests });
1903
- batchSuccess = true;
1904
- break;
1905
- } catch (err) {
1906
- const isRetryable = err.oauthRequest?.status === 429 || (err.oauthRequest?.status >= 500 && err.oauthRequest?.status < 600);
1907
-
1908
- if (!isRetryable || attempt === BATCH_MAX_RETRIES) {
1909
- // Non-retryable error or max retries reached - return errors for all messages in this batch
1910
- for (const emailId of batch) {
1911
- results.push({
1912
- messageId: emailId,
1913
- data: null,
1914
- error: { message: err.message, code: err.code, statusCode: err.oauthRequest?.status }
1915
- });
1916
- }
1917
- break;
1918
- }
1919
-
1920
- // Wait before retrying with exponential backoff + jitter
1921
- const delay = BATCH_RETRY_BASE_DELAY * Math.pow(2, attempt) + Math.random() * 1000;
1922
- this.logger.warn({
1923
- msg: 'Batch request failed, retrying',
1924
- account: this.account,
1925
- attempt: attempt + 1,
1926
- maxAttempts: BATCH_MAX_RETRIES + 1,
1927
- statusCode: err.oauthRequest?.status,
1928
- delayMs: Math.round(delay)
1929
- });
1930
- await new Promise(resolve => setTimeout(resolve, delay));
1931
- }
1932
- }
1933
-
1916
+ const { responseData, batchSuccess } = await this.postBatchWithRetry(requests, batch, results);
1934
1917
  if (!batchSuccess) {
1935
1918
  continue;
1936
1919
  }
1937
1920
 
1938
1921
  // Process batch responses - match by request ID and track which were received
1939
- const respondedIds = new Set();
1940
- for (const response of responseData?.responses || []) {
1941
- const emailId = messageMap.get(response.id);
1942
- if (!emailId) {
1943
- continue;
1944
- }
1945
-
1946
- respondedIds.add(response.id);
1947
-
1948
- if (response.status >= 200 && response.status < 300 && response.body) {
1949
- try {
1950
- const messageData = response.body;
1922
+ const respondedIds = await this.processBatchResponse(responseData, messageMap, lookupFolder, options, results);
1951
1923
 
1952
- // Resolve folder from pre-fetched map (O(1) lookup)
1953
- let path, specialUse;
1954
- if (messageData.parentFolderId) {
1955
- const folder = await lookupFolder(messageData.parentFolderId);
1956
- if (folder) {
1957
- path = folder.pathName;
1958
- specialUse = folder.specialUse;
1959
- }
1960
- }
1961
-
1962
- // Process email headers
1963
- if (messageData.internetMessageHeaders) {
1964
- let headers = {};
1965
- for (let header of messageData.internetMessageHeaders || []) {
1966
- let { name, value } = header;
1967
- name = (name || '').toString().trim().toLowerCase();
1968
- value = (value || '').toString().trim();
1969
- if (!pushHeaderValue(headers, name, value)) {
1970
- continue;
1971
- }
1972
- if (name === 'in-reply-to') {
1973
- messageData.inReplyTo = value;
1974
- }
1975
- }
1976
- messageData.headers = headers;
1977
- }
1924
+ // Reconcile: detect messages that got no response from the batch API
1925
+ reconcileMissingBatchResponses(messageMap, respondedIds, results);
1926
+ }
1978
1927
 
1979
- const formattedMessage = this.formatMessage(messageData, {
1980
- extended: true,
1981
- path,
1982
- textType: options.textType,
1983
- maxBytes: options.maxBytes,
1984
- showPath: options.showPath
1985
- });
1928
+ return results;
1929
+ }
1986
1930
 
1987
- if (specialUse) {
1988
- formattedMessage.messageSpecialUse = specialUse;
1989
- }
1931
+ /**
1932
+ * Posts a /$batch request, retrying throttled (429) and server (5xx) failures with an
1933
+ * exponential backoff plus jitter. When it gives up every message of the batch is reported
1934
+ * as failed with the error of the last attempt
1935
+ * @param {Object[]} requests - The batch requests
1936
+ * @param {string[]} batch - Message ids of the batch
1937
+ * @param {Object[]} results - Results, appended to on failure
1938
+ * @param {Function} [sleep] - Waits the given milliseconds
1939
+ * @returns {Promise<{responseData: Object, batchSuccess: boolean}>}
1940
+ */
1941
+ async postBatchWithRetry(requests, batch, results, sleep) {
1942
+ sleep = sleep || (delay => new Promise(resolve => setTimeout(resolve, delay)));
1990
1943
 
1991
- results.push({
1992
- messageId: emailId,
1993
- data: formattedMessage,
1994
- error: null
1995
- });
1996
- } catch (err) {
1944
+ for (let attempt = 0; attempt <= BATCH_MAX_RETRIES; attempt++) {
1945
+ try {
1946
+ const responseData = await this.request('/$batch', 'post', { requests });
1947
+ return { responseData, batchSuccess: true };
1948
+ } catch (err) {
1949
+ if (!isRetryableBatchError(err) || attempt === BATCH_MAX_RETRIES) {
1950
+ // Non-retryable error or max retries reached - return errors for all messages in this batch
1951
+ for (const emailId of batch) {
1997
1952
  results.push({
1998
1953
  messageId: emailId,
1999
1954
  data: null,
2000
- error: { message: err.message, code: err.code }
1955
+ error: { message: err.message, code: err.code, statusCode: err.oauthRequest?.status }
2001
1956
  });
2002
1957
  }
2003
- } else {
2004
- // Individual message error within the batch
2005
- const graphError = response.body?.error;
2006
- results.push({
2007
- messageId: emailId,
2008
- data: null,
2009
- error: {
2010
- message: graphError?.message || 'Request failed',
2011
- code: graphError?.code,
2012
- statusCode: response.status
2013
- }
2014
- });
1958
+ break;
2015
1959
  }
1960
+
1961
+ // Wait before retrying with exponential backoff + jitter
1962
+ const delay = BATCH_RETRY_BASE_DELAY * Math.pow(2, attempt) + Math.random() * 1000;
1963
+ this.logger.warn({
1964
+ msg: 'Batch request failed, retrying',
1965
+ account: this.account,
1966
+ attempt: attempt + 1,
1967
+ maxAttempts: BATCH_MAX_RETRIES + 1,
1968
+ statusCode: err.oauthRequest?.status,
1969
+ delayMs: Math.round(delay)
1970
+ });
1971
+ await sleep(delay);
2016
1972
  }
1973
+ }
2017
1974
 
2018
- // Reconcile: detect messages that got no response from the batch API
2019
- for (const [reqId, emailId] of messageMap) {
2020
- if (!respondedIds.has(reqId)) {
1975
+ return { responseData: undefined, batchSuccess: false };
1976
+ }
1977
+
1978
+ /**
1979
+ * Turns the responses of a /$batch call into results, one per message. A response for a
1980
+ * request id the batch did not send is ignored
1981
+ * @param {Object} responseData - The /$batch answer
1982
+ * @param {Map<string, string>} messageMap - Message id of each request id
1983
+ * @param {Function} lookupFolder - Resolves a folder id to a listing entry
1984
+ * @param {Object} options - Fetch options
1985
+ * @param {Object[]} results - Results, appended to
1986
+ * @returns {Promise<Set<string>>} Request ids a response was received for
1987
+ */
1988
+ async processBatchResponse(responseData, messageMap, lookupFolder, options, results) {
1989
+ const respondedIds = new Set();
1990
+ for (const response of responseData?.responses || []) {
1991
+ const emailId = messageMap.get(response.id);
1992
+ if (!emailId) {
1993
+ continue;
1994
+ }
1995
+
1996
+ respondedIds.add(response.id);
1997
+
1998
+ if (response.status >= 200 && response.status < 300 && response.body) {
1999
+ try {
2000
+ const messageData = response.body;
2001
+
2002
+ // Resolve folder from pre-fetched map (O(1) lookup)
2003
+ let path, specialUse;
2004
+ if (messageData.parentFolderId) {
2005
+ const folder = await lookupFolder(messageData.parentFolderId);
2006
+ if (folder) {
2007
+ path = folder.pathName;
2008
+ specialUse = folder.specialUse;
2009
+ }
2010
+ }
2011
+
2012
+ // Process email headers
2013
+ parseGraphHeaders(messageData);
2014
+
2015
+ results.push({
2016
+ messageId: emailId,
2017
+ data: this.formatFetchedGraphMessage(messageData, path, specialUse, options),
2018
+ error: null
2019
+ });
2020
+ } catch (err) {
2021
2021
  results.push({
2022
2022
  messageId: emailId,
2023
2023
  data: null,
2024
- error: { message: 'No response received from batch API', code: 'EMISSING_RESPONSE' }
2024
+ error: { message: err.message, code: err.code }
2025
2025
  });
2026
2026
  }
2027
+ } else {
2028
+ // Individual message error within the batch
2029
+ const graphError = response.body?.error;
2030
+ results.push({
2031
+ messageId: emailId,
2032
+ data: null,
2033
+ error: {
2034
+ message: graphError?.message || 'Request failed',
2035
+ code: graphError?.code,
2036
+ statusCode: response.status
2037
+ }
2038
+ });
2027
2039
  }
2028
2040
  }
2029
-
2030
- return results;
2041
+ return respondedIds;
2031
2042
  }
2032
2043
 
2033
2044
  /**
@@ -2042,18 +2053,8 @@ class OutlookClient extends BaseClient {
2042
2053
  let messageData;
2043
2054
 
2044
2055
  // Prepare request options with appropriate Prefer header for body content type
2045
- let requestOptions = {};
2046
- if (options.textType === 'plain') {
2047
- // Request plain text format from MS Graph API
2048
- requestOptions.headers = {
2049
- Prefer: 'outlook.body-content-type="text"'
2050
- };
2051
- } else if (options.textType === 'html') {
2052
- // Request HTML format from MS Graph API
2053
- requestOptions.headers = {
2054
- Prefer: 'outlook.body-content-type="html"'
2055
- };
2056
- }
2056
+ let preferHeader = bodyPreferHeader(options.textType);
2057
+ let requestOptions = preferHeader ? { headers: { Prefer: preferHeader } } : {};
2057
2058
 
2058
2059
  try {
2059
2060
  messageData = await this.request(
@@ -2065,35 +2066,16 @@ class OutlookClient extends BaseClient {
2065
2066
  requestOptions
2066
2067
  );
2067
2068
  } catch (err) {
2068
- switch (err.oauthRequest?.status) {
2069
- case 404: {
2070
- let error = new Error('Unknown message');
2071
- error.info = {
2072
- response: `Message does not exist`
2073
- };
2074
- error.code = 'NotFound';
2075
- error.statusCode = 404;
2076
- throw error;
2077
- }
2078
-
2079
- case 400: {
2080
- let error = new Error('Invalid request');
2081
- error.info = {
2082
- response: err.oauthRequest?.response?.error?.message || `Invalid request`
2083
- };
2084
- error.code = err.oauthRequest?.response?.error?.code || 'InvalidRequest';
2085
- error.statusCode = 400;
2086
- throw error;
2087
- }
2088
-
2089
- default:
2090
- this.logger.error({
2091
- msg: 'Failed to fetch message data',
2092
- emailId: textId,
2093
- err
2094
- });
2095
- throw err;
2069
+ let error = mapGetMessageError(err);
2070
+ if (error) {
2071
+ throw error;
2096
2072
  }
2073
+ this.logger.error({
2074
+ msg: 'Failed to fetch message data',
2075
+ emailId: textId,
2076
+ err
2077
+ });
2078
+ throw err;
2097
2079
  }
2098
2080
 
2099
2081
  let response = {};
@@ -3867,11 +3849,12 @@ class OutlookClient extends BaseClient {
3867
3849
  // Renew existing subscription if needed
3868
3850
  if (outlookSubscription.id) {
3869
3851
  let existingExpirationDateTime = this.parseExpirationDate(outlookSubscription.expirationDateTime);
3852
+ let expiry = classifyExistingSubscription(existingExpirationDateTime, now);
3870
3853
 
3871
- if (existingExpirationDateTime && existingExpirationDateTime.getTime() < now + OUTLOOK_CLOCK_SKEW_BUFFER) {
3854
+ if (expiry === 'expired') {
3872
3855
  // already expired (with buffer for clock skew)
3873
3856
  outlookSubscription = {};
3874
- } else if (existingExpirationDateTime && existingExpirationDateTime.getTime() < now + OUTLOOK_EXPIRATION_RENEW_TIME) {
3857
+ } else if (expiry === 'renew') {
3875
3858
  // Use the unified renewal method (skip lock since we already hold it)
3876
3859
  const renewalResult = await this.renewSubscription({ force: false, skipLock: true });
3877
3860
  if (!renewalResult.success && renewalResult.reason === 'expired') {
@@ -4010,67 +3993,14 @@ class OutlookClient extends BaseClient {
4010
3993
 
4011
3994
  // For minimalFields mode, return only essential fields for export indexing
4012
3995
  if (minimalFields) {
4013
- // Derive a numeric uid from message ID for score tiebreaker
4014
- // Graph API doesn't have IMAP-style UIDs, so we hash the ID
4015
- let uid = 0;
4016
- if (messageData.id) {
4017
- for (let i = 0; i < messageData.id.length; i++) {
4018
- uid = ((uid << 5) - uid + messageData.id.charCodeAt(i)) | 0;
4019
- }
4020
- uid = Math.abs(uid);
4021
- }
4022
-
4023
- return {
4024
- id: messageData.id,
4025
- emailId: messageData.id,
4026
- threadId: messageData.conversationId || undefined,
4027
- date: date ? date.toISOString() : undefined,
4028
- uid,
4029
- size: 0 // Graph API doesn't provide size in minimal listing
4030
- };
4031
- }
4032
-
4033
- // Map Graph API flags to IMAP flags
4034
- const flags = [];
4035
- if (messageData.isRead) {
4036
- flags.push('\\Seen');
4037
- }
4038
- if (messageData.isDraft) {
4039
- flags.push('\\Draft');
4040
- }
4041
- if (messageData.flag?.flagStatus === 'flagged') {
4042
- flags.push('\\Flagged');
3996
+ return graphMinimalMessage(messageData, date);
4043
3997
  }
4044
3998
 
4045
- let encodedTextSize = {};
4046
- let textContents = {};
4047
-
4048
- // set defaults for requested text type
4049
- if (textType && textType !== '*') {
4050
- textContents[options.textType] = '';
4051
- encodedTextSize[options.textType] = 0;
4052
- }
4053
-
4054
- // Process message body content
4055
- if (messageData?.body?.contentType) {
4056
- let textContent = messageData.body.content || '';
4057
- let textContentType;
4058
- switch (messageData.body.contentType) {
4059
- case 'text':
4060
- textContentType = 'plain';
4061
- break;
4062
-
4063
- case 'html':
4064
- default:
4065
- textContentType = messageData.body.contentType;
4066
- break;
4067
- }
4068
- encodedTextSize[textContentType] = Buffer.byteLength(textContent);
4069
- if ([textContentType, '*'].includes(textType)) {
4070
- textContents[textContentType] = textContent;
4071
- }
4072
- }
3999
+ const flags = graphFlags(messageData);
4073
4000
 
4001
+ const encodedTextSize = {};
4002
+ const textContents = {};
4003
+ collectGraphText(messageData, textType, textContents, encodedTextSize);
4074
4004
  const textHasMore = truncateTextContents(textContents, maxBytes);
4075
4005
 
4076
4006
  let message = {
@@ -4094,12 +4024,12 @@ class OutlookClient extends BaseClient {
4094
4024
  subject: messageData.subject || undefined,
4095
4025
  from: messageData.from?.emailAddress || undefined,
4096
4026
 
4097
- replyTo: messageData.replyTo?.length ? messageData.replyTo.map(entry => entry.emailAddress).filter(entry => entry) : undefined,
4027
+ replyTo: graphAddresses(messageData.replyTo),
4098
4028
  sender: (extended && messageData.sender?.emailAddress) || undefined,
4099
4029
 
4100
- to: messageData.toRecipients?.length ? messageData.toRecipients.map(entry => entry.emailAddress).filter(entry => entry) : undefined,
4101
- cc: messageData.ccRecipients?.length ? messageData.ccRecipients.map(entry => entry.emailAddress).filter(entry => entry) : undefined,
4102
- bcc: extended && messageData.bccRecipients?.length ? messageData.bccRecipients.map(entry => entry.emailAddress).filter(entry => entry) : undefined,
4030
+ to: graphAddresses(messageData.toRecipients),
4031
+ cc: graphAddresses(messageData.ccRecipients),
4032
+ bcc: extended ? graphAddresses(messageData.bccRecipients) : undefined,
4103
4033
 
4104
4034
  messageId: messageData.internetMessageId,
4105
4035
  inReplyTo: messageData.inReplyTo || undefined,
@@ -4109,51 +4039,19 @@ class OutlookClient extends BaseClient {
4109
4039
  text: {
4110
4040
  id: messageData.id,
4111
4041
  encodedSize: encodedTextSize,
4112
- plain: textContents?.plain?.toString(),
4113
- html: textContents?.html?.toString(),
4114
- hasMore: textContents?.plain || textContents?.html ? textHasMore : undefined
4042
+ plain: textContents.plain?.toString(),
4043
+ html: textContents.html?.toString(),
4044
+ hasMore: textContents.plain || textContents.html ? textHasMore : undefined
4115
4045
  },
4116
4046
 
4117
4047
  preview: messageData.bodyPreview
4118
4048
  };
4119
4049
 
4120
- // Check for auto-reply based on headers
4121
- if (message.headers && this.isAutoreply(message)) {
4122
- message.isAutoReply = true;
4123
- }
4124
-
4125
- const otp = getMessageOtp(message.headers, this.summaryProvider());
4126
- if (otp) {
4127
- message.otp = otp;
4128
- }
4050
+ // Headers are only listed on an extended fetch, and only then is a message checked for an auto-reply
4051
+ this.finalizeApiMessage(message, true);
4129
4052
 
4130
- // Process attachments
4131
4053
  if (messageData.attachments?.length) {
4132
- let cidReferences = collectCidReferences(message.text.html);
4133
- message.attachments = messageData.attachments.map(entry => {
4134
- const attachment = {
4135
- // Encode both message ID and attachment ID for later retrieval
4136
- id: msgpack.encode([messageData.id, entry.id]).toString('base64url'),
4137
- contentType: entry.contentType,
4138
- encodedSize: entry.size,
4139
- inline: !!entry.isInline
4140
- };
4141
-
4142
- if (entry.name) {
4143
- attachment.filename = entry.name;
4144
- }
4145
-
4146
- if (entry.contentId) {
4147
- // Normalize content ID format
4148
- attachment.contentId = entry.contentId.replace(/^<*/, '<').replace(/>*$/, '>');
4149
- // Check if attachment is embedded in HTML
4150
- if (cidReferences.has(attachment.contentId.replace(/^[\s<]*|[\s>]*$/g, ''))) {
4151
- attachment.embedded = true;
4152
- }
4153
- }
4154
-
4155
- return attachment;
4156
- });
4054
+ message.attachments = graphAttachments(messageData, message.text.html);
4157
4055
  }
4158
4056
 
4159
4057
  return message;
@@ -4757,128 +4655,74 @@ class OutlookClient extends BaseClient {
4757
4655
  prepareFilterQuery(search) {
4758
4656
  search = search || {};
4759
4657
 
4760
- const filterParts = [];
4761
-
4762
- // Fields not supported by OData filters
4763
- const disabledKeys = [
4764
- 'seq',
4765
- 'uid',
4766
- 'paths',
4767
- 'answered',
4768
- 'deleted',
4769
- 'modseq',
4770
-
4771
- //
4772
- 'to',
4773
- 'cc',
4774
- 'bcc',
4775
- 'larger',
4776
- 'smaller'
4777
- ];
4778
-
4779
4658
  // not supported search terms
4780
- for (let disabledKey of disabledKeys) {
4659
+ for (let disabledKey of FILTER_UNSUPPORTED_KEYS) {
4781
4660
  if (disabledKey in search) {
4782
- let error = new Error(`Unsupported search term "${disabledKey}"`);
4783
- error.code = 'UnsupportedSearchTerm';
4784
- error.statusCode = 400;
4785
- throw error;
4661
+ throw statusError(`Unsupported search term "${disabledKey}"`, 'UnsupportedSearchTerm', 400);
4786
4662
  }
4787
4663
  }
4788
4664
 
4789
4665
  // Build OData filter expressions
4666
+ const filterParts = [];
4790
4667
 
4791
- // unseen
4792
- if (typeof search.unseen === 'boolean') {
4793
- filterParts.push(`isRead eq ${search.unseen ? 'false' : 'true'}`);
4794
- }
4795
-
4796
- // seen
4797
- if (typeof search.seen === 'boolean') {
4798
- filterParts.push(`isRead eq ${search.seen ? 'true' : 'false'}`);
4799
- }
4800
-
4801
- // draft
4802
- if (typeof search.draft === 'boolean') {
4803
- filterParts.push(`isDraft eq ${search.draft ? 'true' : 'false'}`);
4804
- }
4805
-
4806
- // flagged
4807
- if (typeof search.flagged === 'boolean') {
4808
- filterParts.push(`flag/flagStatus eq '${search.flagged ? 'flagged' : 'notFlagged'}'`);
4809
- }
4810
-
4811
- // from
4812
- if (search.from) {
4813
- filterParts.push(
4814
- `(from/emailAddress/address eq ${this.formatSearchTerm(search.from)} or contains(from/emailAddress/name, ${this.formatSearchTerm(
4815
- search.from
4816
- )}))`
4817
- );
4818
- }
4819
-
4820
- if (search.subject) {
4821
- filterParts.push(`contains(subject, ${this.formatSearchTerm(search.subject)})`);
4822
- }
4823
-
4824
- if (search.body) {
4825
- filterParts.push(`contains(body/content, ${this.formatSearchTerm(search.body)})`);
4826
- }
4827
-
4828
- if (search.emailId) {
4829
- filterParts.push(`id eq ${this.formatSearchTerm(search.emailId)}`);
4830
- }
4831
-
4832
- if (search.threadId) {
4833
- filterParts.push(`conversationId eq ${this.formatSearchTerm(search.threadId)}`);
4668
+ for (let [key, filter] of BOOLEAN_FILTERS) {
4669
+ if (typeof search[key] === 'boolean') {
4670
+ filterParts.push(filter(search[key]));
4671
+ }
4834
4672
  }
4835
4673
 
4836
- if (search.before) {
4837
- filterParts.push(`receivedDateTime lt ${this.formatSearchTerm(search.before, false)}`);
4674
+ for (let [key, filter] of TERM_FILTERS) {
4675
+ if (search[key]) {
4676
+ filterParts.push(filter(this.formatSearchTerm(search[key])));
4677
+ }
4838
4678
  }
4839
4679
 
4840
- if (search.sentBefore) {
4841
- filterParts.push(`sentDateTime lt ${this.formatSearchTerm(search.sentBefore, false)}`);
4680
+ for (let [key, comparison] of DATE_FILTERS) {
4681
+ if (search[key]) {
4682
+ filterParts.push(`${comparison} ${this.formatSearchTerm(search[key], false)}`);
4683
+ }
4842
4684
  }
4843
4685
 
4844
- if (search.since) {
4845
- filterParts.push(`receivedDateTime gt ${this.formatSearchTerm(search.since, false)}`);
4846
- }
4686
+ filterParts.push(...this.labelFilters(search.labels), ...this.headerFilters(search.header));
4847
4687
 
4848
- if (search.sentSince) {
4849
- filterParts.push(`sentDateTime gt ${this.formatSearchTerm(search.sentSince, false)}`);
4850
- }
4688
+ return filterParts.join(' and ').trim();
4689
+ }
4851
4690
 
4852
- // Category (label) filters - "has" matches messages tagged with the category, "not" excludes them
4853
- if (search.labels && typeof search.labels === 'object') {
4854
- for (let category of [].concat(search.labels.has || [])) {
4691
+ /**
4692
+ * Category (label) filters - "has" matches messages tagged with the category, "not" excludes them
4693
+ */
4694
+ labelFilters(labels) {
4695
+ const filterParts = [];
4696
+ if (labels && typeof labels === 'object') {
4697
+ for (let category of [].concat(labels.has || [])) {
4855
4698
  if (category) {
4856
4699
  filterParts.push(`categories/any(c:c eq ${this.formatSearchTerm(category)})`);
4857
4700
  }
4858
4701
  }
4859
- for (let category of [].concat(search.labels.not || [])) {
4702
+ for (let category of [].concat(labels.not || [])) {
4860
4703
  if (category) {
4861
4704
  filterParts.push(`not (categories/any(c:c eq ${this.formatSearchTerm(category)}))`);
4862
4705
  }
4863
4706
  }
4864
4707
  }
4708
+ return filterParts;
4709
+ }
4865
4710
 
4866
- // Limited header search support
4867
- for (let headerKey of Object.keys(search.header || {})) {
4711
+ /**
4712
+ * Limited header search support: Message-ID only, anything else is refused
4713
+ */
4714
+ headerFilters(header) {
4715
+ const filterParts = [];
4716
+ for (let headerKey of Object.keys(header || {})) {
4868
4717
  switch (headerKey.toLowerCase().trim()) {
4869
4718
  case 'message-id':
4870
- filterParts.push(`internetMessageId eq ${this.formatSearchTerm(search.header[headerKey])}`);
4719
+ filterParts.push(`internetMessageId eq ${this.formatSearchTerm(header[headerKey])}`);
4871
4720
  break;
4872
- default: {
4873
- let error = new Error(`Unsupported search header "${headerKey}"`);
4874
- error.code = 'UnsupportedSearchTerm';
4875
- error.statusCode = 400;
4876
- throw error;
4877
- }
4721
+ default:
4722
+ throw statusError(`Unsupported search header "${headerKey}"`, 'UnsupportedSearchTerm', 400);
4878
4723
  }
4879
4724
  }
4880
-
4881
- return filterParts.join(' and ').trim();
4725
+ return filterParts;
4882
4726
  }
4883
4727
 
4884
4728
  /**