emailengine-app 2.85.0 → 2.86.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 (128) hide show
  1. package/.ncurc.js +24 -6
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +74 -0
  4. package/Dockerfile +14 -1
  5. package/ENVIRONMENT.md +139 -0
  6. package/README.md +1 -1
  7. package/config/default.toml +2 -0
  8. package/copy-static-files.sh +4 -2
  9. package/data/google-crawlers.json +1 -1
  10. package/data/public_suffix_list.dat +4 -3
  11. package/lib/account-assignment.js +19 -0
  12. package/lib/account.js +194 -165
  13. package/lib/api-error-codes.js +49 -0
  14. package/lib/api-reference/model.js +6 -1
  15. package/lib/api-routes/account-routes.js +78 -26
  16. package/lib/api-routes/blocklist-routes.js +68 -2
  17. package/lib/api-routes/delivery-test-routes.js +1 -1
  18. package/lib/api-routes/gateway-routes.js +82 -10
  19. package/lib/api-routes/index.js +4 -0
  20. package/lib/api-routes/license-routes.js +2 -2
  21. package/lib/api-routes/mailbox-routes.js +3 -3
  22. package/lib/api-routes/message-routes.js +15 -7
  23. package/lib/api-routes/oauth2-app-routes.js +15 -8
  24. package/lib/api-routes/outbox-routes.js +77 -66
  25. package/lib/api-routes/permission-map.js +55 -6
  26. package/lib/api-routes/scoped-routes.js +74 -0
  27. package/lib/api-routes/settings-routes.js +11 -4
  28. package/lib/api-routes/stats-routes.js +5 -1
  29. package/lib/api-routes/submit-routes.js +4 -3
  30. package/lib/api-routes/template-routes.js +7 -6
  31. package/lib/api-routes/token-routes.js +11 -5
  32. package/lib/api-routes/webhook-delivery-routes.js +262 -0
  33. package/lib/api-routes/webhook-route-routes.js +119 -4
  34. package/lib/calendar-event.js +81 -1
  35. package/lib/consts.js +38 -46
  36. package/lib/db.js +14 -6
  37. package/lib/delivery-error.js +6 -0
  38. package/lib/deprecations.js +270 -0
  39. package/lib/email-client/base-client.js +130 -156
  40. package/lib/email-client/fallback-poll.js +62 -0
  41. package/lib/email-client/gmail-client.js +51 -11
  42. package/lib/email-client/imap/adaptive-idle-store.js +73 -0
  43. package/lib/email-client/imap/adaptive-idle.js +278 -0
  44. package/lib/email-client/imap/connection-errors.js +14 -1
  45. package/lib/email-client/imap/idle-settings.js +31 -5
  46. package/lib/email-client/imap/listing-diff.js +37 -0
  47. package/lib/email-client/imap/mailbox.js +372 -226
  48. package/lib/email-client/imap/subconnection.js +7 -29
  49. package/lib/email-client/imap/sync-operations.js +220 -127
  50. package/lib/email-client/imap-client.js +227 -163
  51. package/lib/email-client/message-builder.js +14 -79
  52. package/lib/email-client/outlook-client.js +372 -338
  53. package/lib/email-client/smtp-pool-manager.js +16 -13
  54. package/lib/email-client/sync-state-fields.js +19 -0
  55. package/lib/encrypt.js +157 -41
  56. package/lib/enum-descriptions.js +3 -1
  57. package/lib/env-setting-overrides.js +288 -0
  58. package/lib/export-worker.js +751 -0
  59. package/lib/export.js +64 -15
  60. package/lib/gateway.js +17 -1
  61. package/lib/get-raw-email.js +25 -107
  62. package/lib/health.js +75 -0
  63. package/lib/lock-run.js +119 -0
  64. package/lib/logger-consts.js +48 -0
  65. package/lib/logger.js +1 -1
  66. package/lib/lua/z-head-scores.lua +28 -0
  67. package/lib/network-errors.js +1 -1
  68. package/lib/node-version.js +24 -0
  69. package/lib/notify-attachments.js +20 -1
  70. package/lib/oauth2-apps.js +630 -655
  71. package/lib/outbox.js +184 -54
  72. package/lib/parse-message.js +3 -3
  73. package/lib/privileged-settings.js +2 -2
  74. package/lib/queue-browser/definitions.js +11 -0
  75. package/lib/queue-browser/index.js +68 -19
  76. package/lib/queue-job-actions.js +18 -1
  77. package/lib/queue-retention.js +48 -12
  78. package/lib/queue-stats.js +11 -2
  79. package/lib/read-env-value.js +3 -0
  80. package/lib/redis-memory-warnings.js +99 -0
  81. package/lib/redis-reconnect.js +29 -0
  82. package/lib/request-timing.js +23 -0
  83. package/lib/respawn-backoff.js +35 -0
  84. package/lib/rewrite-text-nodes.js +19 -59
  85. package/lib/schemas.js +163 -39
  86. package/lib/settings.js +6 -2
  87. package/lib/smtp-auth.js +19 -1
  88. package/lib/thread-diagnostics.js +18 -1
  89. package/lib/tls/provision.js +6 -3
  90. package/lib/token-audit-log.js +19 -20
  91. package/lib/token-permission-view.js +4 -3
  92. package/lib/tools.js +8 -41
  93. package/lib/ui-routes/admin-config-routes.js +64 -90
  94. package/lib/ui-routes/admin-entities-routes.js +2 -14
  95. package/lib/ui-routes/imap-idle-field.js +1 -1
  96. package/lib/ui-routes/outlook-subscription-view.js +1 -1
  97. package/lib/ui-routes/overridable-fields.js +84 -0
  98. package/lib/ui-routes/queue-routes.js +8 -5
  99. package/lib/ui-routes/settings-page.js +6 -0
  100. package/lib/utils/decode-headers.js +3 -12
  101. package/lib/utils/filter-empty.js +20 -0
  102. package/lib/utils/int-setting.js +48 -0
  103. package/lib/utils/tracking-settings.js +35 -0
  104. package/lib/web-safe-html.js +18 -105
  105. package/lib/webhook-delivery.js +461 -0
  106. package/lib/webhook-failures.js +132 -0
  107. package/lib/webhook-request.js +29 -1
  108. package/lib/webhook-routing.js +30 -1
  109. package/lib/webhook-test.js +88 -0
  110. package/lib/webhooks.js +54 -41
  111. package/lib/worker-rpc-error.js +2 -1
  112. package/package.json +21 -20
  113. package/sbom.json +304 -382
  114. package/server.js +149 -76
  115. package/static/js/ace/ace.js +1 -1
  116. package/static/licenses.html +21 -31
  117. package/translations/messages.pot +26 -26
  118. package/views/config/security.hbs +22 -0
  119. package/views/config/service.hbs +44 -0
  120. package/views/config/webhooks.hbs +36 -0
  121. package/views/partials/queue_retention_note.hbs +12 -8
  122. package/views/partials/ui/env-managed-alert.hbs +16 -7
  123. package/workers/api.js +102 -28
  124. package/workers/export.js +16 -631
  125. package/workers/imap.js +13 -0
  126. package/workers/smtp.js +9 -11
  127. package/workers/webhooks.js +18 -432
  128. package/lib/email-client/outlook-fallback-poll.js +0 -30
@@ -4,6 +4,7 @@ const { BaseClient, metricsMeta } = require('./base-client');
4
4
  const { isSafePathSegment } = require('../utils/provider-id');
5
5
  const { isTransientCredentialError } = require('./credential-errors');
6
6
  const { Account } = require('../account');
7
+ const { runLocked, isContention } = require('../lock-run');
7
8
  const { checkAccountScopes } = require('../oauth/scope-checker');
8
9
  const settings = require('../settings');
9
10
  const { oauth2Apps } = require('../oauth2-apps');
@@ -11,7 +12,7 @@ const getSecret = require('../get-secret');
11
12
  const msgpack = require('../msgpack');
12
13
  const he = require('he');
13
14
  const { emitChangeEvent, prepareUrl, collectCidReferences, embedCidImages, truncateTextContents } = require('../tools');
14
- const { parseFallbackPollInterval, FALLBACK_POLL_INTERVAL } = require('./outlook-fallback-poll');
15
+ const { parseFallbackPollInterval, OUTLOOK_FALLBACK_POLL_INTERVAL: FALLBACK_POLL_INTERVAL } = require('./fallback-poll');
15
16
  const { messageWebSafeHtml, applyWebSafeHtmlOptions } = require('../web-safe-html');
16
17
  const crypto = require('crypto');
17
18
  const { Gateway } = require('../gateway');
@@ -36,6 +37,7 @@ const {
36
37
  OUTLOOK_CLOCK_SKEW_BUFFER,
37
38
  OUTLOOK_MISSED_LOOKBACK,
38
39
  OUTLOOK_ANNOUNCED_RETENTION,
40
+ OUTLOOK_SYNC_MAX_LOOKBACK,
39
41
  MESSAGE_UPDATED_NOTIFY,
40
42
  MESSAGE_DELETED_NOTIFY,
41
43
  MESSAGE_MISSING_NOTIFY,
@@ -54,6 +56,22 @@ const RENEW_WATCH_TTL = 60 * 60 * 1000; // 1h
54
56
  // unannounced ones and announce hours of mail again
55
57
  const ANNOUNCED_SINCE_FIELD = 'outlookAnnouncedInSince';
56
58
 
59
+ /**
60
+ * Where the recovery pass after a flush starts: the flush's `notifyFrom` when it lies in the past,
61
+ * no further back than "Run sync" may look. Null when there is nothing before now to recover
62
+ * @param {string|Date} [notifyFrom] - Stored notifyFrom value
63
+ * @param {number} now - Epoch ms
64
+ * @returns {number|null} Epoch ms
65
+ */
66
+ function flushRecoveryStart(notifyFrom, now) {
67
+ const time = notifyFrom ? new Date(notifyFrom).getTime() : NaN;
68
+ // a minute of slack, so the default flush ("now", stored a few seconds ago) needs no pass
69
+ if (!Number.isFinite(time) || time >= now - 60 * 1000) {
70
+ return null;
71
+ }
72
+ return Math.max(time, now - OUTLOOK_SYNC_MAX_LOOKBACK);
73
+ }
74
+
57
75
  // The `serverResponseCode` a failed change subscription is reported with, and the marker that
58
76
  // tells the report apart from anything else the account may have stored. Only this client reads
59
77
  // it: reportSubscriptionFailure() writes it, clearSubscriptionFailure() lifts it, and
@@ -569,10 +587,25 @@ class OutlookClient extends BaseClient {
569
587
  }
570
588
 
571
589
  /**
572
- * Get the current connection state from Redis
590
+ * Deletes the account's Graph subscription. Best effort: Graph lets an orphaned subscription
591
+ * expire within three days on its own, it only keeps posting to the notification endpoint and
592
+ * counting against the tenant's subscription quota until then
593
+ * @returns {Promise<boolean>} True when a subscription was deleted
573
594
  */
574
- async currentState() {
575
- return (await this.redis.hget(this.getAccountKey(), 'state')) || 'disconnected';
595
+ async releaseRemoteResources() {
596
+ try {
597
+ const outlookSubscription = await this.getStoredSubscription();
598
+ if (!outlookSubscription.id) {
599
+ return false;
600
+ }
601
+ await this.request(`/subscriptions/${outlookSubscription.id}`, 'DELETE');
602
+ await this.redis.hdel(this.getAccountKey(), 'outlookSubscription');
603
+ this.logger.info({ msg: 'Deleted MS Graph subscription', account: this.account, subscription: outlookSubscription.id });
604
+ return true;
605
+ } catch (err) {
606
+ this.logger.warn({ msg: 'Failed to delete MS Graph subscription', account: this.account, err });
607
+ return false;
608
+ }
576
609
  }
577
610
 
578
611
  /**
@@ -582,15 +615,9 @@ class OutlookClient extends BaseClient {
582
615
  this.clearTimers();
583
616
  this.closed = true;
584
617
 
585
- // Best-effort: delete MS Graph subscription
586
- try {
587
- let outlookSubscription = await this.getStoredSubscription();
588
- if (outlookSubscription.id) {
589
- await this.request(`/subscriptions/${outlookSubscription.id}`, 'DELETE');
590
- }
591
- } catch (err) {
592
- this.logger.warn({ msg: 'Failed to delete MS Graph subscription', account: this.account, err });
593
- }
618
+ // Normally done already by the teardown that runs before the account record is removed,
619
+ // and then a no-op here
620
+ await this.releaseRemoteResources();
594
621
 
595
622
  if (['init', 'connecting', 'syncing', 'connected'].includes(this.state)) {
596
623
  this.state = 'disconnected';
@@ -601,6 +628,23 @@ class OutlookClient extends BaseClient {
601
628
  return null;
602
629
  }
603
630
 
631
+ /**
632
+ * Starts syncing again after a flush. The subscription only reports changes made from now on,
633
+ * so a flush that asked for messages from an earlier `notifyFrom` also gets the pass "Run sync"
634
+ * makes, from that point and bounded the same way. A flush clears the announced set, so the
635
+ * messages it finds are announced again, as on an IMAP account
636
+ */
637
+ async resumeAfterFlush() {
638
+ await this.reconnect();
639
+
640
+ // the one field this needs, read on its own: reconnect() has just loaded the whole account
641
+ const notifyFrom = await this.redis.hget(this.getAccountKey(), 'notifyFrom');
642
+ const since = flushRecoveryStart(notifyFrom, Date.now());
643
+ if (since && !this.closed && this.state === 'connected') {
644
+ await this.syncMailboxes({ since });
645
+ }
646
+ }
647
+
604
648
  /**
605
649
  * Reconnect to the account (re-initialize)
606
650
  */
@@ -3535,183 +3579,163 @@ class OutlookClient extends BaseClient {
3535
3579
  return { success: false, reason: 'renewal_in_progress' };
3536
3580
  }
3537
3581
 
3538
- const lock = this.accountObject.getLock();
3539
- const lockId = this.getSubscriptionLockId();
3540
- let renewLock;
3541
- if (!skipLock) {
3542
- try {
3543
- renewLock = await lock.acquireLock(lockId, OUTLOOK_SUBSCRIPTION_LOCK_TTL);
3544
- } catch (err) {
3545
- this.logger.error({ msg: 'Failed to acquire subscription renew lock', account: this.account, err });
3546
- this.scheduleSubscriptionRetry({
3547
- delayMs: OUTLOOK_SUBSCRIPTION_RETRY_BASE_DELAY * 1000,
3548
- reason: 'lock_error',
3549
- errorMsg: 'Subscription renew retry after lock error failed',
3550
- fn: () => this.renewSubscription({ force: false })
3551
- });
3552
- return { success: false, reason: 'lock_error' };
3553
- }
3554
-
3555
- if (!renewLock.success) {
3556
- this.logger.info({
3557
- msg: 'Subscription renewal skipped',
3558
- reason: 'lock_exists',
3559
- account: this.account
3560
- });
3561
- return { success: false, reason: 'lock_exists' };
3562
- }
3563
- }
3582
+ const renew = async () => {
3583
+ // Set in-memory flag to prevent concurrent calls
3584
+ this.renewalInProgress = true;
3564
3585
 
3565
- // Set in-memory flag to prevent concurrent calls
3566
- this.renewalInProgress = true;
3586
+ try {
3587
+ // Get current subscription
3588
+ let outlookSubscription = await this.getStoredSubscription();
3567
3589
 
3568
- try {
3569
- // Get current subscription
3570
- let outlookSubscription = await this.getStoredSubscription();
3590
+ // Check if subscription exists and is valid
3591
+ if (!outlookSubscription.id) {
3592
+ this.subscriptionState = 'unset';
3593
+ return { success: false, reason: 'no_subscription' };
3594
+ }
3571
3595
 
3572
- // Check if subscription exists and is valid
3573
- if (!outlookSubscription.id) {
3574
- this.subscriptionState = 'unset';
3575
- return { success: false, reason: 'no_subscription' };
3576
- }
3596
+ let existingExpirationDateTime = this.parseExpirationDate(outlookSubscription.expirationDateTime);
3577
3597
 
3578
- let existingExpirationDateTime = this.parseExpirationDate(outlookSubscription.expirationDateTime);
3598
+ const now = Date.now();
3579
3599
 
3580
- const now = Date.now();
3600
+ // Check if already expired (with buffer for clock skew)
3601
+ if (existingExpirationDateTime && existingExpirationDateTime.getTime() < now + OUTLOOK_CLOCK_SKEW_BUFFER) {
3602
+ this.logger.warn({
3603
+ msg: 'Subscription already expired or expiring imminently',
3604
+ subscriptionId: outlookSubscription.id,
3605
+ expirationDateTime: outlookSubscription.expirationDateTime,
3606
+ account: this.account,
3607
+ msUntilExpiry: existingExpirationDateTime.getTime() - now
3608
+ });
3609
+ // Clear the expired subscription
3610
+ await this.redis.hdel(this.getAccountKey(), 'outlookSubscription');
3611
+ this.subscriptionState = 'expired';
3612
+ return { success: false, reason: 'expired' };
3613
+ }
3581
3614
 
3582
- // Check if already expired (with buffer for clock skew)
3583
- if (existingExpirationDateTime && existingExpirationDateTime.getTime() < now + OUTLOOK_CLOCK_SKEW_BUFFER) {
3584
- this.logger.warn({
3585
- msg: 'Subscription already expired or expiring imminently',
3586
- subscriptionId: outlookSubscription.id,
3587
- expirationDateTime: outlookSubscription.expirationDateTime,
3588
- account: this.account,
3589
- msUntilExpiry: existingExpirationDateTime.getTime() - now
3590
- });
3591
- // Clear the expired subscription
3592
- await this.redis.hdel(this.getAccountKey(), 'outlookSubscription');
3593
- this.subscriptionState = 'expired';
3594
- return { success: false, reason: 'expired' };
3595
- }
3615
+ // Check if renewal is needed
3616
+ const shouldRenew = force || (existingExpirationDateTime && existingExpirationDateTime.getTime() < now + OUTLOOK_EXPIRATION_RENEW_TIME);
3596
3617
 
3597
- // Check if renewal is needed
3598
- const shouldRenew = force || (existingExpirationDateTime && existingExpirationDateTime.getTime() < now + OUTLOOK_EXPIRATION_RENEW_TIME);
3618
+ if (!shouldRenew) {
3619
+ this.logger.debug({
3620
+ msg: 'Subscription renewal not needed',
3621
+ subscriptionId: outlookSubscription.id,
3622
+ expirationDateTime: outlookSubscription.expirationDateTime,
3623
+ account: this.account
3624
+ });
3625
+ this.subscriptionState = 'valid';
3626
+ // A subscription that is still good is the same recovery as one just renewed
3627
+ await this.clearSubscriptionFailure();
3628
+ return { success: true, reason: 'not_needed' };
3629
+ }
3599
3630
 
3600
- if (!shouldRenew) {
3601
- this.logger.debug({
3602
- msg: 'Subscription renewal not needed',
3603
- subscriptionId: outlookSubscription.id,
3604
- expirationDateTime: outlookSubscription.expirationDateTime,
3605
- account: this.account
3606
- });
3607
- this.subscriptionState = 'valid';
3608
- // A subscription that is still good is the same recovery as one just renewed
3609
- await this.clearSubscriptionFailure();
3610
- return { success: true, reason: 'not_needed' };
3611
- }
3631
+ // Perform renewal
3632
+ const expirationDateTime = new Date(now + OUTLOOK_EXPIRATION_TIME);
3633
+ const subscriptionPayload = {
3634
+ expirationDateTime: expirationDateTime.toISOString()
3635
+ };
3612
3636
 
3613
- // Perform renewal
3614
- const expirationDateTime = new Date(now + OUTLOOK_EXPIRATION_TIME);
3615
- const subscriptionPayload = {
3616
- expirationDateTime: expirationDateTime.toISOString()
3617
- };
3637
+ // Capture previous retry counts before overwriting state
3638
+ const previousRetryCount = outlookSubscription.state?.retryCount || 0;
3639
+ const previousCreateRetryCount = outlookSubscription.state?.createRetryCount || 0;
3618
3640
 
3619
- // Capture previous retry counts before overwriting state
3620
- const previousRetryCount = outlookSubscription.state?.retryCount || 0;
3621
- const previousCreateRetryCount = outlookSubscription.state?.createRetryCount || 0;
3641
+ // Update state to renewing
3642
+ outlookSubscription.state = {
3643
+ state: 'renewing',
3644
+ time: Date.now()
3645
+ };
3646
+ await this.saveStoredSubscription(outlookSubscription);
3647
+ this.subscriptionState = 'pending';
3622
3648
 
3623
- // Update state to renewing
3624
- outlookSubscription.state = {
3625
- state: 'renewing',
3626
- time: Date.now()
3627
- };
3628
- await this.saveStoredSubscription(outlookSubscription);
3629
- this.subscriptionState = 'pending';
3649
+ try {
3650
+ const subscriptionRes = await this.request(`/subscriptions/${outlookSubscription.id}`, 'PATCH', subscriptionPayload);
3630
3651
 
3631
- try {
3632
- const subscriptionRes = await this.request(`/subscriptions/${outlookSubscription.id}`, 'PATCH', subscriptionPayload);
3652
+ if (subscriptionRes?.expirationDateTime) {
3653
+ outlookSubscription.expirationDateTime = subscriptionRes.expirationDateTime;
3654
+ outlookSubscription.state = {
3655
+ state: 'created',
3656
+ time: Date.now(),
3657
+ retryCount: 0,
3658
+ createRetryCount: 0,
3659
+ error: null
3660
+ };
3633
3661
 
3634
- if (subscriptionRes?.expirationDateTime) {
3635
- outlookSubscription.expirationDateTime = subscriptionRes.expirationDateTime;
3636
- outlookSubscription.state = {
3637
- state: 'created',
3638
- time: Date.now(),
3639
- retryCount: 0,
3640
- createRetryCount: 0,
3641
- error: null
3642
- };
3662
+ await this.saveStoredSubscription(outlookSubscription);
3663
+ this.subscriptionState = 'valid';
3664
+ await this.clearSubscriptionFailure();
3643
3665
 
3644
- await this.saveStoredSubscription(outlookSubscription);
3645
- this.subscriptionState = 'valid';
3646
- await this.clearSubscriptionFailure();
3666
+ this.logger.info({
3667
+ msg: previousRetryCount > 0 ? 'Subscription renewed successfully after retry' : 'Subscription renewed successfully',
3668
+ subscriptionId: outlookSubscription.id,
3669
+ newExpirationDateTime: subscriptionRes.expirationDateTime,
3670
+ account: this.account,
3671
+ previousRetryCount
3672
+ });
3647
3673
 
3648
- this.logger.info({
3649
- msg: previousRetryCount > 0 ? 'Subscription renewed successfully after retry' : 'Subscription renewed successfully',
3674
+ return { success: true, expirationDateTime: subscriptionRes.expirationDateTime };
3675
+ } else {
3676
+ throw new Error('Empty server response');
3677
+ }
3678
+ } catch (err) {
3679
+ this.logger.warn({
3680
+ msg: 'Subscription renewal failed',
3650
3681
  subscriptionId: outlookSubscription.id,
3651
- newExpirationDateTime: subscriptionRes.expirationDateTime,
3652
3682
  account: this.account,
3653
- previousRetryCount
3683
+ err
3654
3684
  });
3655
3685
 
3656
- return { success: true, expirationDateTime: subscriptionRes.expirationDateTime };
3657
- } else {
3658
- throw new Error('Empty server response');
3659
- }
3660
- } catch (err) {
3661
- this.logger.warn({
3662
- msg: 'Subscription renewal failed',
3663
- subscriptionId: outlookSubscription.id,
3664
- account: this.account,
3665
- err
3666
- });
3667
-
3668
- outlookSubscription.state = {
3669
- state: 'error',
3670
- error: `Subscription renewal failed: ${err.oauthRequest?.response?.error?.message || err.message}`,
3671
- time: Date.now(),
3672
- retryCount: previousRetryCount + 1,
3673
- createRetryCount: previousCreateRetryCount
3674
- };
3675
- await this.saveStoredSubscription(outlookSubscription);
3676
- this.subscriptionState = 'failed';
3686
+ outlookSubscription.state = {
3687
+ state: 'error',
3688
+ error: `Subscription renewal failed: ${err.oauthRequest?.response?.error?.message || err.message}`,
3689
+ time: Date.now(),
3690
+ retryCount: previousRetryCount + 1,
3691
+ createRetryCount: previousCreateRetryCount
3692
+ };
3693
+ await this.saveStoredSubscription(outlookSubscription);
3694
+ this.subscriptionState = 'failed';
3677
3695
 
3678
- // Schedule retry with exponential backoff
3679
- const retryCount = outlookSubscription.state.retryCount;
3680
- if (retryCount < OUTLOOK_MAX_RETRY_ATTEMPTS) {
3681
- const retryDelay =
3682
- Math.min(OUTLOOK_SUBSCRIPTION_RETRY_BASE_DELAY * Math.pow(2, retryCount - 1), OUTLOOK_SUBSCRIPTION_RETRY_MAX_DELAY) * 1000;
3696
+ // Schedule retry with exponential backoff
3697
+ const retryCount = outlookSubscription.state.retryCount;
3698
+ if (retryCount < OUTLOOK_MAX_RETRY_ATTEMPTS) {
3699
+ const retryDelay =
3700
+ Math.min(OUTLOOK_SUBSCRIPTION_RETRY_BASE_DELAY * Math.pow(2, retryCount - 1), OUTLOOK_SUBSCRIPTION_RETRY_MAX_DELAY) * 1000;
3683
3701
 
3684
- this.scheduleSubscriptionRetry({
3685
- delayMs: retryDelay,
3686
- reason: 'renewal_failure',
3687
- errorMsg: 'Subscription renewal retry failed',
3688
- fn: () => this.renewSubscription({ force }),
3689
- retryAttempt: retryCount
3690
- });
3702
+ this.scheduleSubscriptionRetry({
3703
+ delayMs: retryDelay,
3704
+ reason: 'renewal_failure',
3705
+ errorMsg: 'Subscription renewal retry failed',
3706
+ fn: () => this.renewSubscription({ force }),
3707
+ retryAttempt: retryCount
3708
+ });
3691
3709
 
3692
- this.logger.info({
3693
- msg: 'Scheduling subscription renewal retry',
3694
- account: this.account,
3695
- retryAttempt: retryCount,
3696
- retryDelayMs: retryDelay
3697
- });
3698
- } else {
3699
- await this.reportSubscriptionFailure('renewal', outlookSubscription.state, retryCount);
3700
- }
3710
+ this.logger.info({
3711
+ msg: 'Scheduling subscription renewal retry',
3712
+ account: this.account,
3713
+ retryAttempt: retryCount,
3714
+ retryDelayMs: retryDelay
3715
+ });
3716
+ } else {
3717
+ await this.reportSubscriptionFailure('renewal', outlookSubscription.state, retryCount);
3718
+ }
3701
3719
 
3702
- return { success: false, reason: 'renewal_failed', error: err.message };
3703
- }
3704
- } finally {
3705
- // Always release the lock and clear in-memory flag
3706
- this.renewalInProgress = false;
3707
- if (!skipLock && renewLock?.success) {
3708
- try {
3709
- await lock.releaseLock(renewLock);
3710
- } catch (err) {
3711
- this.logger.error({ msg: 'Failed to release subscription renew lock', account: this.account, err });
3720
+ return { success: false, reason: 'renewal_failed', error: err.message };
3712
3721
  }
3722
+ } finally {
3723
+ this.renewalInProgress = false;
3713
3724
  }
3725
+ };
3726
+
3727
+ if (skipLock) {
3728
+ return await renew();
3714
3729
  }
3730
+
3731
+ // One try at the lock: a renewal already running elsewhere is left to finish
3732
+ return await this.withSubscriptionLock(renew, {
3733
+ action: 'renew',
3734
+ skippedMsg: 'Subscription renewal skipped',
3735
+ retry: () => this.renewSubscription({ force: false }),
3736
+ skipped: { success: false, reason: 'lock_exists' },
3737
+ failed: { success: false, reason: 'lock_error' }
3738
+ });
3715
3739
  }
3716
3740
 
3717
3741
  /**
@@ -3741,6 +3765,35 @@ class OutlookClient extends BaseClient {
3741
3765
  }
3742
3766
  }
3743
3767
 
3768
+ /**
3769
+ * Runs fn under the account's subscription lock, with one try at it: a renewal or creation
3770
+ * already running elsewhere is left to finish (answered with `skipped`), and a lock that could
3771
+ * not be taken at all schedules `retry` (answered with `failed`)
3772
+ * @param {Function} fn
3773
+ * @param {Object} opts
3774
+ * @param {string} opts.action - 'renew' or 'ensure', for the log
3775
+ * @param {string} opts.skippedMsg - Log message when another holder has the lock
3776
+ * @param {Function} opts.retry - What to retry after a lock error
3777
+ * @param {*} [opts.skipped] - Result when another holder has the lock
3778
+ * @param {*} [opts.failed] - Result when the lock could not be taken
3779
+ */
3780
+ async withSubscriptionLock(fn, { action, skippedMsg, retry, skipped, failed }) {
3781
+ return await runLocked(this.accountObject.getLock(), this.getSubscriptionLockId(), { ttl: OUTLOOK_SUBSCRIPTION_LOCK_TTL, wait: false }, fn, err => {
3782
+ if (isContention(err)) {
3783
+ this.logger.info({ msg: skippedMsg, reason: 'lock_exists', account: this.account });
3784
+ return skipped;
3785
+ }
3786
+ this.logger.error({ msg: `Failed to acquire subscription ${action} lock`, account: this.account, err });
3787
+ this.scheduleSubscriptionRetry({
3788
+ delayMs: OUTLOOK_SUBSCRIPTION_RETRY_BASE_DELAY * 1000,
3789
+ reason: 'lock_error',
3790
+ errorMsg: `Subscription ${action} retry after lock error failed`,
3791
+ fn: retry
3792
+ });
3793
+ return failed;
3794
+ });
3795
+ }
3796
+
3744
3797
  /**
3745
3798
  * Ensure webhook subscription exists and is valid
3746
3799
  * Creates new subscription or renews existing one
@@ -3750,8 +3803,9 @@ class OutlookClient extends BaseClient {
3750
3803
  return;
3751
3804
  }
3752
3805
 
3753
- let serviceUrl = (await settings.get('serviceUrl')) || null;
3754
- let notificationBaseUrl = (await settings.get('notificationBaseUrl')) || serviceUrl || '';
3806
+ const urls = await settings.getMulti('serviceUrl', 'notificationBaseUrl');
3807
+ let serviceUrl = urls.serviceUrl || null;
3808
+ let notificationBaseUrl = urls.notificationBaseUrl || serviceUrl || '';
3755
3809
 
3756
3810
  if (!serviceUrl) {
3757
3811
  this.logger.error({ msg: 'Cannot create MS Graph subscription, service URL is not set', account: this.account });
@@ -3759,201 +3813,181 @@ class OutlookClient extends BaseClient {
3759
3813
  return false;
3760
3814
  }
3761
3815
 
3762
- // Acquire distributed lock to prevent concurrent subscription operations
3763
- const lock = this.accountObject.getLock();
3764
- const lockId = this.getSubscriptionLockId();
3765
- let ensureLock;
3766
- try {
3767
- ensureLock = await lock.acquireLock(lockId, OUTLOOK_SUBSCRIPTION_LOCK_TTL);
3768
- } catch (err) {
3769
- this.logger.error({ msg: 'Failed to acquire subscription ensure lock', account: this.account, err });
3770
- // Schedule retry for transient lock errors (e.g., Redis connectivity).
3771
- // Do not forward clearExisting on retry: by the time the retry fires,
3772
- // another path may have created a valid subscription that should not be cleared.
3773
- this.scheduleSubscriptionRetry({
3774
- delayMs: OUTLOOK_SUBSCRIPTION_RETRY_BASE_DELAY * 1000,
3775
- reason: 'lock_error',
3776
- errorMsg: 'Subscription ensure retry after lock error failed',
3777
- fn: () => this.ensureSubscription()
3778
- });
3779
- return;
3780
- }
3781
- if (!ensureLock.success) {
3816
+ // A creation already running elsewhere is left to finish. Do not forward clearExisting on a
3817
+ // retry after a lock error: by the time it fires, another path may have created a valid
3818
+ // subscription that should not be cleared
3819
+ return await this.withSubscriptionLock(() => this.ensureSubscriptionLocked({ clearExisting, serviceUrl, notificationBaseUrl }), {
3820
+ action: 'ensure',
3821
+ skippedMsg: 'Subscription creation skipped',
3822
+ retry: () => this.ensureSubscription()
3823
+ });
3824
+ }
3825
+
3826
+ /**
3827
+ * The part of ensureSubscription() that runs under the subscription lock
3828
+ * @param {Object} opts
3829
+ * @param {boolean} opts.clearExisting
3830
+ * @param {string|null} opts.serviceUrl
3831
+ * @param {string} opts.notificationBaseUrl
3832
+ */
3833
+ async ensureSubscriptionLocked({ clearExisting, serviceUrl, notificationBaseUrl }) {
3834
+ if (clearExisting) {
3835
+ await this.redis.hdel(this.getAccountKey(), 'outlookSubscription');
3782
3836
  this.logger.info({
3783
- msg: 'Subscription creation skipped',
3784
- reason: 'lock_exists',
3837
+ msg: 'Cleared existing subscription data for re-creation',
3785
3838
  account: this.account
3786
3839
  });
3787
- return;
3788
3840
  }
3789
3841
 
3790
- try {
3791
- if (clearExisting) {
3792
- await this.redis.hdel(this.getAccountKey(), 'outlookSubscription');
3793
- this.logger.info({
3794
- msg: 'Cleared existing subscription data for re-creation',
3795
- account: this.account
3796
- });
3797
- }
3842
+ let outlookSubscription = await this.getStoredSubscription();
3798
3843
 
3799
- let outlookSubscription = await this.getStoredSubscription();
3800
-
3801
- // If state is creating/renewing, the previous lock holder crashed before completing.
3802
- // Since we hold the lock, no other operation is in progress — reset to a clean state.
3803
- if (['creating', 'renewing'].includes(outlookSubscription.state?.state)) {
3804
- this.logger.warn({
3805
- msg: 'Found stale subscription state from crashed operation, resetting state',
3806
- subscriptionId: outlookSubscription?.id,
3807
- state: outlookSubscription.state?.state,
3808
- stateTime: outlookSubscription.state?.time,
3809
- account: this.account
3810
- });
3844
+ // If state is creating/renewing, the previous lock holder crashed before completing.
3845
+ // Since we hold the lock, no other operation is in progress — reset to a clean state.
3846
+ if (['creating', 'renewing'].includes(outlookSubscription.state?.state)) {
3847
+ this.logger.warn({
3848
+ msg: 'Found stale subscription state from crashed operation, resetting state',
3849
+ subscriptionId: outlookSubscription?.id,
3850
+ state: outlookSubscription.state?.state,
3851
+ stateTime: outlookSubscription.state?.time,
3852
+ account: this.account
3853
+ });
3811
3854
 
3812
- // Reset transient state so downstream logic sees a clean state
3813
- outlookSubscription.state.state = outlookSubscription.id ? 'created' : 'error';
3814
- outlookSubscription.state.time = Date.now();
3815
- await this.saveStoredSubscription(outlookSubscription);
3816
- }
3855
+ // Reset transient state so downstream logic sees a clean state
3856
+ outlookSubscription.state.state = outlookSubscription.id ? 'created' : 'error';
3857
+ outlookSubscription.state.time = Date.now();
3858
+ await this.saveStoredSubscription(outlookSubscription);
3859
+ }
3817
3860
 
3818
- let now = Date.now();
3819
- let expirationDateTime = new Date(now + OUTLOOK_EXPIRATION_TIME);
3861
+ let now = Date.now();
3862
+ let expirationDateTime = new Date(now + OUTLOOK_EXPIRATION_TIME);
3820
3863
 
3821
- // Renew existing subscription if needed
3822
- if (outlookSubscription.id) {
3823
- let existingExpirationDateTime = this.parseExpirationDate(outlookSubscription.expirationDateTime);
3864
+ // Renew existing subscription if needed
3865
+ if (outlookSubscription.id) {
3866
+ let existingExpirationDateTime = this.parseExpirationDate(outlookSubscription.expirationDateTime);
3824
3867
 
3825
- if (existingExpirationDateTime && existingExpirationDateTime.getTime() < now + OUTLOOK_CLOCK_SKEW_BUFFER) {
3826
- // already expired (with buffer for clock skew)
3868
+ if (existingExpirationDateTime && existingExpirationDateTime.getTime() < now + OUTLOOK_CLOCK_SKEW_BUFFER) {
3869
+ // already expired (with buffer for clock skew)
3870
+ outlookSubscription = {};
3871
+ } else if (existingExpirationDateTime && existingExpirationDateTime.getTime() < now + OUTLOOK_EXPIRATION_RENEW_TIME) {
3872
+ // Use the unified renewal method (skip lock since we already hold it)
3873
+ const renewalResult = await this.renewSubscription({ force: false, skipLock: true });
3874
+ if (!renewalResult.success && renewalResult.reason === 'expired') {
3875
+ // Subscription expired, clear it to create a new one
3827
3876
  outlookSubscription = {};
3828
- } else if (existingExpirationDateTime && existingExpirationDateTime.getTime() < now + OUTLOOK_EXPIRATION_RENEW_TIME) {
3829
- // Use the unified renewal method (skip lock since we already hold it)
3830
- const renewalResult = await this.renewSubscription({ force: false, skipLock: true });
3831
- if (!renewalResult.success && renewalResult.reason === 'expired') {
3832
- // Subscription expired, clear it to create a new one
3833
- outlookSubscription = {};
3834
- } else {
3835
- return renewalResult.success;
3836
- }
3837
3877
  } else {
3838
- // Subscription is valid, do nothing
3839
- this.logger.debug({
3840
- msg: 'Subscription renewal skipped',
3841
- reason: 'valid',
3842
- subscriptionId: outlookSubscription?.id,
3843
- state: outlookSubscription.state?.state,
3844
- created: outlookSubscription.state?.time,
3845
- expirationDateTime: outlookSubscription.expirationDateTime
3846
- });
3847
- this.subscriptionState = 'valid';
3848
- // A subscription that is still good is the same recovery as one just created
3849
- await this.clearSubscriptionFailure();
3850
- return;
3878
+ return renewalResult.success;
3851
3879
  }
3880
+ } else {
3881
+ // Subscription is valid, do nothing
3882
+ this.logger.debug({
3883
+ msg: 'Subscription renewal skipped',
3884
+ reason: 'valid',
3885
+ subscriptionId: outlookSubscription?.id,
3886
+ state: outlookSubscription.state?.state,
3887
+ created: outlookSubscription.state?.time,
3888
+ expirationDateTime: outlookSubscription.expirationDateTime
3889
+ });
3890
+ this.subscriptionState = 'valid';
3891
+ // A subscription that is still good is the same recovery as one just created
3892
+ await this.clearSubscriptionFailure();
3893
+ return;
3852
3894
  }
3895
+ }
3853
3896
 
3854
- // Create new subscription if needed
3855
- if (!outlookSubscription.id) {
3856
- const notificationUrl = prepareUrl('/oauth/msg/notification', notificationBaseUrl, {
3857
- account: this.account
3858
- });
3897
+ // Create new subscription if needed
3898
+ if (!outlookSubscription.id) {
3899
+ const notificationUrl = prepareUrl('/oauth/msg/notification', notificationBaseUrl, {
3900
+ account: this.account
3901
+ });
3859
3902
 
3860
- const lifecycleNotificationUrl = prepareUrl('/oauth/msg/lifecycle', notificationBaseUrl, {
3861
- account: this.account
3862
- });
3903
+ const lifecycleNotificationUrl = prepareUrl('/oauth/msg/lifecycle', notificationBaseUrl, {
3904
+ account: this.account
3905
+ });
3863
3906
 
3864
- const subscriptionPayload = {
3865
- changeType: 'created,updated,deleted',
3866
- notificationUrl,
3867
- lifecycleNotificationUrl,
3868
- resource: `/${this.oauth2UserPath}/messages`,
3869
- expirationDateTime: expirationDateTime.toISOString(),
3870
- clientState: crypto.randomUUID()
3871
- };
3907
+ const subscriptionPayload = {
3908
+ changeType: 'created,updated,deleted',
3909
+ notificationUrl,
3910
+ lifecycleNotificationUrl,
3911
+ resource: `/${this.oauth2UserPath}/messages`,
3912
+ expirationDateTime: expirationDateTime.toISOString(),
3913
+ clientState: crypto.randomUUID()
3914
+ };
3872
3915
 
3873
- // Capture previous create retry count before overwriting state
3874
- const previousCreateRetryCount = outlookSubscription.state?.createRetryCount || 0;
3916
+ // Capture previous create retry count before overwriting state
3917
+ const previousCreateRetryCount = outlookSubscription.state?.createRetryCount || 0;
3875
3918
 
3876
- outlookSubscription.state = {
3877
- state: 'creating',
3878
- time: Date.now()
3879
- };
3880
- await this.saveStoredSubscription(outlookSubscription);
3881
- this.subscriptionState = 'pending';
3919
+ outlookSubscription.state = {
3920
+ state: 'creating',
3921
+ time: Date.now()
3922
+ };
3923
+ await this.saveStoredSubscription(outlookSubscription);
3924
+ this.subscriptionState = 'pending';
3882
3925
 
3883
- let subscriptionRes;
3884
- try {
3885
- subscriptionRes = await this.request(`/subscriptions`, 'post', subscriptionPayload);
3886
- if (subscriptionRes?.expirationDateTime) {
3887
- outlookSubscription = {
3888
- id: subscriptionRes.id,
3889
- expirationDateTime: subscriptionRes.expirationDateTime,
3890
- clientState: subscriptionRes.clientState,
3891
- state: {
3892
- state: 'created',
3893
- time: Date.now(),
3894
- createRetryCount: 0,
3895
- retryCount: 0
3896
- }
3897
- };
3898
- this.subscriptionState = 'valid';
3899
- await this.clearSubscriptionFailure();
3900
- } else {
3901
- throw new Error('Empty server response');
3902
- }
3903
- } catch (err) {
3904
- const errorMessage = err.oauthRequest?.response?.error?.message || err.message;
3905
- this.logger.warn({
3906
- msg: 'Failed to create MS Graph subscription',
3907
- account: this.account,
3908
- error: errorMessage,
3909
- code: err.oauthRequest?.response?.error?.code,
3910
- statusCode: err.oauthRequest?.status
3911
- });
3912
- outlookSubscription.state = {
3913
- state: 'error',
3914
- error: `Subscription failed: ${errorMessage}`,
3915
- time: Date.now(),
3916
- createRetryCount: previousCreateRetryCount + 1
3926
+ let subscriptionRes;
3927
+ try {
3928
+ subscriptionRes = await this.request(`/subscriptions`, 'post', subscriptionPayload);
3929
+ if (subscriptionRes?.expirationDateTime) {
3930
+ outlookSubscription = {
3931
+ id: subscriptionRes.id,
3932
+ expirationDateTime: subscriptionRes.expirationDateTime,
3933
+ clientState: subscriptionRes.clientState,
3934
+ state: {
3935
+ state: 'created',
3936
+ time: Date.now(),
3937
+ createRetryCount: 0,
3938
+ retryCount: 0
3939
+ }
3917
3940
  };
3918
- this.subscriptionState = 'failed';
3919
- } finally {
3920
- await this.saveStoredSubscription(outlookSubscription);
3941
+ this.subscriptionState = 'valid';
3942
+ await this.clearSubscriptionFailure();
3943
+ } else {
3944
+ throw new Error('Empty server response');
3921
3945
  }
3946
+ } catch (err) {
3947
+ const errorMessage = err.oauthRequest?.response?.error?.message || err.message;
3948
+ this.logger.warn({
3949
+ msg: 'Failed to create MS Graph subscription',
3950
+ account: this.account,
3951
+ error: errorMessage,
3952
+ code: err.oauthRequest?.response?.error?.code,
3953
+ statusCode: err.oauthRequest?.status
3954
+ });
3955
+ outlookSubscription.state = {
3956
+ state: 'error',
3957
+ error: `Subscription failed: ${errorMessage}`,
3958
+ time: Date.now(),
3959
+ createRetryCount: previousCreateRetryCount + 1
3960
+ };
3961
+ this.subscriptionState = 'failed';
3962
+ } finally {
3963
+ await this.saveStoredSubscription(outlookSubscription);
3964
+ }
3922
3965
 
3923
- // Schedule retry with exponential backoff if creation failed
3924
- if (outlookSubscription.state?.state === 'error') {
3925
- const createRetryCount = outlookSubscription.state.createRetryCount || 0;
3926
- if (createRetryCount < OUTLOOK_MAX_RETRY_ATTEMPTS) {
3927
- const retryDelay =
3928
- Math.min(OUTLOOK_SUBSCRIPTION_RETRY_BASE_DELAY * Math.pow(2, createRetryCount - 1), OUTLOOK_SUBSCRIPTION_RETRY_MAX_DELAY) * 1000;
3966
+ // Schedule retry with exponential backoff if creation failed
3967
+ if (outlookSubscription.state?.state === 'error') {
3968
+ const createRetryCount = outlookSubscription.state.createRetryCount || 0;
3969
+ if (createRetryCount < OUTLOOK_MAX_RETRY_ATTEMPTS) {
3970
+ const retryDelay =
3971
+ Math.min(OUTLOOK_SUBSCRIPTION_RETRY_BASE_DELAY * Math.pow(2, createRetryCount - 1), OUTLOOK_SUBSCRIPTION_RETRY_MAX_DELAY) * 1000;
3929
3972
 
3930
- this.scheduleSubscriptionRetry({
3931
- delayMs: retryDelay,
3932
- reason: 'creation_failure',
3933
- errorMsg: 'Subscription creation retry failed',
3934
- fn: () => this.ensureSubscription(),
3935
- retryAttempt: createRetryCount
3936
- });
3973
+ this.scheduleSubscriptionRetry({
3974
+ delayMs: retryDelay,
3975
+ reason: 'creation_failure',
3976
+ errorMsg: 'Subscription creation retry failed',
3977
+ fn: () => this.ensureSubscription(),
3978
+ retryAttempt: createRetryCount
3979
+ });
3937
3980
 
3938
- this.logger.info({
3939
- msg: 'Scheduling subscription creation retry',
3940
- account: this.account,
3941
- retryAttempt: createRetryCount,
3942
- retryDelayMs: retryDelay
3943
- });
3944
- } else {
3945
- // End of the fast ladder, not the end of trying: renewOrCreateSubscription()
3946
- // clears the counters and starts a new one on the next hourly pass
3947
- await this.reportSubscriptionFailure('creation', outlookSubscription.state, createRetryCount);
3948
- }
3949
- }
3950
- }
3951
- } finally {
3952
- if (ensureLock?.success) {
3953
- try {
3954
- await lock.releaseLock(ensureLock);
3955
- } catch (err) {
3956
- this.logger.error({ msg: 'Failed to release subscription ensure lock', account: this.account, err });
3981
+ this.logger.info({
3982
+ msg: 'Scheduling subscription creation retry',
3983
+ account: this.account,
3984
+ retryAttempt: createRetryCount,
3985
+ retryDelayMs: retryDelay
3986
+ });
3987
+ } else {
3988
+ // End of the fast ladder, not the end of trying: renewOrCreateSubscription()
3989
+ // clears the counters and starts a new one on the next hourly pass
3990
+ await this.reportSubscriptionFailure('creation', outlookSubscription.state, createRetryCount);
3957
3991
  }
3958
3992
  }
3959
3993
  }
@@ -4322,7 +4356,7 @@ class OutlookClient extends BaseClient {
4322
4356
 
4323
4357
  async _updateLastNotificationTime() {
4324
4358
  try {
4325
- await this.redis.hset(this.getAccountKey(), 'outlookLastNotification', Date.now().toString());
4359
+ await this.redis.hSetExists(this.getAccountKey(), 'outlookLastNotification', Date.now().toString());
4326
4360
  } catch (err) {
4327
4361
  this.logger.error({ msg: 'Failed to update last notification time', err });
4328
4362
  }
@@ -5011,4 +5045,4 @@ class OutlookClient extends BaseClient {
5011
5045
  }
5012
5046
  }
5013
5047
 
5014
- module.exports = { OutlookClient, encodeFolderSegment, decodeFolderSegment, parseFallbackPollInterval };
5048
+ module.exports = { OutlookClient, encodeFolderSegment, decodeFolderSegment, parseFallbackPollInterval, flushRecoveryStart };