emailengine-app 2.82.1 → 2.82.2

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.
@@ -1,3 +1,3 @@
1
1
  {
2
- ".": "2.82.1"
2
+ ".": "2.82.2"
3
3
  }
package/CHANGELOG.md CHANGED
@@ -1,5 +1,12 @@
1
1
  # Changelog
2
2
 
3
+ ## [2.82.2](https://github.com/postalsys/emailengine/compare/v2.82.1...v2.82.2) (2026-10-05)
4
+
5
+
6
+ ### Bug Fixes
7
+
8
+ * **outlook:** keep polling an account whose subscription fails but whose mailbox can be read ([a563624](https://github.com/postalsys/emailengine/commit/a563624137b14c66b0c10bf431139656c5da0c7c))
9
+
3
10
  ## [2.82.1](https://github.com/postalsys/emailengine/compare/v2.82.0...v2.82.1) (2026-10-05)
4
11
 
5
12
 
@@ -9,7 +9,8 @@ const { oauth2Apps } = require('../oauth2-apps');
9
9
  const getSecret = require('../get-secret');
10
10
  const msgpack = require('../msgpack');
11
11
  const he = require('he');
12
- const { emitChangeEvent, prepareUrl, collectCidReferences, embedCidImages, truncateTextContents, readEnvValue, getDuration } = require('../tools');
12
+ const { emitChangeEvent, prepareUrl, collectCidReferences, embedCidImages, truncateTextContents } = require('../tools');
13
+ const { parseFallbackPollInterval, FALLBACK_POLL_INTERVAL } = require('./outlook-fallback-poll');
13
14
  const { messageWebSafeHtml, applyWebSafeHtmlOptions } = require('../web-safe-html');
14
15
  const crypto = require('crypto');
15
16
  const { Gateway } = require('../gateway');
@@ -46,41 +47,21 @@ const MAX_BATCH_SIZE = graphApi.MAX_BATCH_SIZE;
46
47
  // Subscription is renewed automatically. But just in case, check once in an hour
47
48
  const RENEW_WATCH_TTL = 60 * 60 * 1000; // 1h
48
49
 
49
- const DEFAULT_FALLBACK_POLL_INTERVAL = 10 * 60 * 1000;
50
- const MIN_FALLBACK_POLL_INTERVAL = 10 * 1000;
51
-
52
- /**
53
- * Reads EENGINE_OUTLOOK_FALLBACK_POLL_INTERVAL: a duration, 0 switching the periodic pass off.
54
- * Anything unreadable gets the default, and a positive value is never shorter than ten seconds, so
55
- * a typo cannot point every account at Graph in a loop
56
- * @param {*} value - The raw environment value
57
- * @returns {number} Milliseconds, 0 when the pass is off
58
- */
59
- function parseFallbackPollInterval(value) {
60
- // blank is "unset", which getDuration() would read as 0, the value that switches the pass off
61
- const raw = String(value ?? '').trim();
62
- const duration = raw ? getDuration(raw) : DEFAULT_FALLBACK_POLL_INTERVAL;
63
- if (!Number.isFinite(duration) || duration < 0) {
64
- return DEFAULT_FALLBACK_POLL_INTERVAL;
65
- }
66
- return duration && Math.max(duration, MIN_FALLBACK_POLL_INTERVAL);
67
- }
68
-
69
50
  // When the announced set (see OutlookClient.getAnnouncedKey()) started being kept, the point a
70
51
  // recovery pass never looks back past. Renamed along with the set when it became keyed by folder,
71
52
  // so the first pass after an upgrade does not take the messages recorded in the old format for
72
53
  // unannounced ones and announce hours of mail again
73
54
  const ANNOUNCED_SINCE_FIELD = 'outlookAnnouncedInSince';
74
55
 
75
- // See setupFallbackPollTimer()
76
- const FALLBACK_POLL_INTERVAL = parseFallbackPollInterval(readEnvValue('EENGINE_OUTLOOK_FALLBACK_POLL_INTERVAL'));
77
-
78
56
  // The `serverResponseCode` a failed change subscription is reported with, and the marker that
79
57
  // tells the report apart from anything else the account may have stored. Only this client reads
80
58
  // it: reportSubscriptionFailure() writes it, clearSubscriptionFailure() lifts it, and
81
59
  // isSelfClearedErrorState() is what keeps a login from taking it along
82
60
  const SUBSCRIPTION_SETUP_ERROR_CODE = 'SubscriptionSetupError';
83
61
 
62
+ // What the stored subscription state says while no Service URL is set, see recordMissingServiceUrl()
63
+ const MISSING_SERVICE_URL_ERROR = 'Subscription failed: the Service URL is not set';
64
+
84
65
  // Graph accepts only x- prefixed names in internetMessageHeaders and rejects the whole message
85
66
  // over any other one, so the threading headers of a reply or a forward are set through the
86
67
  // MAPI properties Exchange builds them from (PidTagInReplyToId, PidTagInternetReferences)
@@ -2945,14 +2926,21 @@ class OutlookClient extends BaseClient {
2945
2926
  }
2946
2927
 
2947
2928
  /**
2948
- * Reports that the account has no working change subscription left to fall back on - and for a
2949
- * Graph account there is no fallback: unlike the Gmail client there is no polling timer, so a
2950
- * subscription that cannot be established means the account never sees new mail again. Both the
2951
- * creation and the renewal paths retry with backoff and then give up; giving up used to write a
2952
- * log line and nothing else, so the account went on reporting `connected`. A tenant that
2953
- * disables the Exchange Online service principal (AADSTS500014) hits this without ever failing a
2954
- * token refresh, so no authentication error fires either - reported in the field after nine
2955
- * months of accounts looking healthy and syncing nothing.
2929
+ * Reports that the account has no working change subscription left. Both the creation and the
2930
+ * renewal paths retry with backoff and then give up here.
2931
+ *
2932
+ * What that means depends on whether the mailbox can still be read. When it can, the periodic
2933
+ * recovery pass (setupFallbackPollTimer()) keeps finding new messages without a subscription,
2934
+ * so the account stays `connected` - the same treatment a Gmail account with a dead Pub/Sub
2935
+ * watch gets - and the failure stays visible on the stored subscription state, which the API
2936
+ * and the account page report. Changes to and deletions of existing messages are only ever
2937
+ * learned from notifications, so they go unreported until a subscription works again.
2938
+ *
2939
+ * When the mailbox cannot be read, or the periodic pass is switched off, nothing syncs at all,
2940
+ * and the account is reported as a `connectError`. Before that existed, giving up wrote a log
2941
+ * line and nothing else: a tenant that disables the Exchange Online service principal
2942
+ * (AADSTS500014) fails every Graph mail call without ever failing a token refresh, and was
2943
+ * reported in the field after nine months of accounts looking healthy and syncing nothing.
2956
2944
  *
2957
2945
  * Sent as `connectError` rather than `authenticationError` on purpose: the credential is fine,
2958
2946
  * and re-authorizing does not lift a disabled service principal. It also keeps the failure away
@@ -2960,9 +2948,9 @@ class OutlookClient extends BaseClient {
2960
2948
  * offer the operator only a re-authorization that cannot help.
2961
2949
  *
2962
2950
  * NB! `connectError` is not in VALID_STATES, so this also makes the account's own operations
2963
- * (reading a message, moving one) answer 503 until a subscription works again. That is the
2964
- * intended reading for an account that cannot sync at all, and it is the only reading this
2965
- * state machine offers - there is no degraded-but-usable state.
2951
+ * (reading a message, moving one) answer 503 until the mailbox can be read again. The hourly
2952
+ * renewOrCreateSubscription() pass comes back through here while the subscription keeps
2953
+ * failing, so an account moves between the two outcomes as the tenant changes.
2966
2954
  *
2967
2955
  * setErrorState() suppresses a repeat of the same code, so a permanently broken tenant produces
2968
2956
  * one webhook per distinct failure rather than one per renewal cycle
@@ -2972,7 +2960,21 @@ class OutlookClient extends BaseClient {
2972
2960
  * @returns {Promise<void>}
2973
2961
  */
2974
2962
  async reportSubscriptionFailure(stage, state, retryCount) {
2975
- this.logger.error({ msg: `Max subscription ${stage} retries exceeded`, account: this.account, retryCount });
2963
+ const probe = await this.probeMailboxWithoutSubscription();
2964
+ if (probe.readable) {
2965
+ this.logger.warn({
2966
+ msg: `MS Graph subscription ${stage} failed, new messages are found by the periodic recovery pass until it works`,
2967
+ account: this.account,
2968
+ retryCount,
2969
+ error: state?.error
2970
+ });
2971
+
2972
+ // An earlier pass may have reported the account while its mailbox could not be read
2973
+ await this.clearSubscriptionFailure();
2974
+ return;
2975
+ }
2976
+
2977
+ this.logger.error({ msg: `Max subscription ${stage} retries exceeded`, account: this.account, retryCount, err: probe.err });
2976
2978
 
2977
2979
  try {
2978
2980
  await this.notify(false, CONNECT_ERROR_NOTIFY, {
@@ -2987,6 +2989,25 @@ class OutlookClient extends BaseClient {
2987
2989
  }
2988
2990
  }
2989
2991
 
2992
+ /**
2993
+ * Whether the periodic recovery pass can stand in for the subscription: it has to be on, and
2994
+ * Graph has to list the resource the pass reads. Any failure counts, a transient one included;
2995
+ * the next hourly pass asks again
2996
+ * @returns {Promise<{readable: boolean, err?: Error}>}
2997
+ */
2998
+ async probeMailboxWithoutSubscription() {
2999
+ if (!this.fallbackPollInterval) {
3000
+ return { readable: false };
3001
+ }
3002
+
3003
+ try {
3004
+ await this.request(`/${this.oauth2UserPath}/messages`, 'get', { $select: 'id', $top: 1 });
3005
+ return { readable: true };
3006
+ } catch (err) {
3007
+ return { readable: false, err };
3008
+ }
3009
+ }
3010
+
2990
3011
  /**
2991
3012
  * A failed change subscription is this client's own report to lift. A tenant that disabled the
2992
3013
  * Exchange Online service principal keeps refreshing tokens and logging in perfectly while no
@@ -3002,9 +3023,9 @@ class OutlookClient extends BaseClient {
3002
3023
  /**
3003
3024
  * Lifts the error state reportSubscriptionFailure() left behind, once a subscription is working
3004
3025
  * again - which is every path that concludes there is a working one, not only a renewal that
3005
- * had to make a request. A subscription 60 hours from expiry is checked hourly and renewed
3006
- * once, so an account reported while it had one would have stayed in `connectError` for two
3007
- * days with notifications arriving the whole time.
3026
+ * had to make a request - or once the mailbox can be read without one. A subscription 60 hours
3027
+ * from expiry is checked hourly and renewed once, so an account reported while it had one would
3028
+ * have stayed in `connectError` for two days with notifications arriving the whole time.
3008
3029
  *
3009
3030
  * Only touches a failure this client reported, so an unrelated error state is left for whatever
3010
3031
  * owns it. A report this process wrote is visible in `this.state`; the one way a standing
@@ -3170,17 +3191,18 @@ class OutlookClient extends BaseClient {
3170
3191
  * revoked - exhausts them within minutes and leaves the account with no subscription at all.
3171
3192
  * This pass used to read that count, find it at the cap and give up, waiting for a reconnect
3172
3193
  * that only a worker restart, an account update or a re-authorization brings; a tenant that
3173
- * fixed the cause an hour later was never noticed. A failed subscription reports
3174
- * `connectError`, which pauses the periodic recovery pass too, so an account left unsubscribed
3175
- * syncs nothing at all while it waits. The counters are cleared before anything else is attempted, so an hour that could have
3194
+ * fixed the cause an hour later was never noticed. It is also what moves an account between
3195
+ * the two outcomes of reportSubscriptionFailure() while the subscription keeps failing.
3196
+ *
3197
+ * The counters are cleared before anything else is attempted, so an hour that could have
3176
3198
  * recovered gets the fast ladder back instead of one attempt every hour forever - a renewal
3177
3199
  * ladder as much as a creation one, since a subscription inside the renew window whose retries
3178
3200
  * are spent is not recreated by this pass at all and would otherwise never get another.
3179
3201
  *
3180
3202
  * A failing account is not heard twice, but it is logged twice: reportSubscriptionFailure()
3181
3203
  * stores the same serverResponseCode every pass, which is what setErrorState() suppresses a
3182
- * repeat notification on, while the log line it writes recurs hourly. The account stays in
3183
- * `connectError` until a creation actually succeeds.
3204
+ * repeat notification on, while the log line it writes recurs hourly. A reported account stays
3205
+ * in `connectError` until a creation succeeds or its mailbox can be listed again.
3184
3206
  *
3185
3207
  * @returns {Promise<void>}
3186
3208
  */
@@ -3682,6 +3704,33 @@ class OutlookClient extends BaseClient {
3682
3704
  }
3683
3705
  }
3684
3706
 
3707
+ /**
3708
+ * A subscription cannot be created without a Service URL, since Graph has nowhere to deliver
3709
+ * notifications to. That used to be a log line and nothing else, so the account page showed no
3710
+ * subscription problem at all; it is recorded on the stored subscription state now, which the
3711
+ * API and the page report. It is not reported as an account error: one instance-wide setting
3712
+ * would put every Outlook account into `connectError` at once, while each of them keeps finding
3713
+ * new messages through the periodic recovery pass. A subscription that already exists is left
3714
+ * alone, since it keeps notifying the address it was created with and renewing it needs no
3715
+ * Service URL, and an unchanged record is not written again on every hourly pass
3716
+ * @returns {Promise<void>}
3717
+ */
3718
+ async recordMissingServiceUrl() {
3719
+ try {
3720
+ const outlookSubscription = await this.getStoredSubscription();
3721
+ if (outlookSubscription.id || outlookSubscription.state?.error === MISSING_SERVICE_URL_ERROR) {
3722
+ return;
3723
+ }
3724
+
3725
+ outlookSubscription.state = { state: 'error', error: MISSING_SERVICE_URL_ERROR, time: Date.now() };
3726
+ await this.saveStoredSubscription(outlookSubscription);
3727
+ this.subscriptionState = 'failed';
3728
+ } catch (err) {
3729
+ // Best effort: init() awaits ensureSubscription()
3730
+ this.logger.error({ msg: 'Failed to record the missing Service URL', account: this.account, err });
3731
+ }
3732
+ }
3733
+
3685
3734
  /**
3686
3735
  * Ensure webhook subscription exists and is valid
3687
3736
  * Creates new subscription or renews existing one
@@ -3695,7 +3744,8 @@ class OutlookClient extends BaseClient {
3695
3744
  let notificationBaseUrl = (await settings.get('notificationBaseUrl')) || serviceUrl || '';
3696
3745
 
3697
3746
  if (!serviceUrl) {
3698
- this.logger.error({ msg: 'Cannot create MS Graph subscription, service URL is not set' });
3747
+ this.logger.error({ msg: 'Cannot create MS Graph subscription, service URL is not set', account: this.account });
3748
+ await this.recordMissingServiceUrl();
3699
3749
  return false;
3700
3750
  }
3701
3751
 
@@ -0,0 +1,30 @@
1
+ 'use strict';
2
+
3
+ const { readEnvValue, getDuration } = require('../tools');
4
+
5
+ const DEFAULT_FALLBACK_POLL_INTERVAL = 10 * 60 * 1000;
6
+ const MIN_FALLBACK_POLL_INTERVAL = 10 * 1000;
7
+
8
+ /**
9
+ * Reads EENGINE_OUTLOOK_FALLBACK_POLL_INTERVAL: a duration, 0 switching the periodic pass off.
10
+ * Anything unreadable gets the default, and a positive value is never shorter than ten seconds, so
11
+ * a typo cannot point every account at Graph in a loop
12
+ * @param {*} value - The raw environment value
13
+ * @returns {number} Milliseconds, 0 when the pass is off
14
+ */
15
+ function parseFallbackPollInterval(value) {
16
+ // blank is "unset", which getDuration() would read as 0, the value that switches the pass off
17
+ const raw = String(value ?? '').trim();
18
+ const duration = raw ? getDuration(raw) : DEFAULT_FALLBACK_POLL_INTERVAL;
19
+ if (!Number.isFinite(duration) || duration < 0) {
20
+ return DEFAULT_FALLBACK_POLL_INTERVAL;
21
+ }
22
+ return duration && Math.max(duration, MIN_FALLBACK_POLL_INTERVAL);
23
+ }
24
+
25
+ // The interval of the periodic missed-notification recovery pass (OutlookClient.setupFallbackPollTimer()).
26
+ // Its own module so the admin UI, which runs in the API worker, reads the same value the account
27
+ // workers run with
28
+ const FALLBACK_POLL_INTERVAL = parseFallbackPollInterval(readEnvValue('EENGINE_OUTLOOK_FALLBACK_POLL_INTERVAL'));
29
+
30
+ module.exports = { parseFallbackPollInterval, FALLBACK_POLL_INTERVAL };
@@ -0,0 +1,36 @@
1
+ 'use strict';
2
+
3
+ const { FALLBACK_POLL_INTERVAL } = require('../email-client/outlook-fallback-poll');
4
+
5
+ /**
6
+ * Adds the fields the account page renders for a Graph change subscription, in place
7
+ * @param {Object} subscription - The account's stored `outlookSubscription`
8
+ * @param {string} accountState - The account's connection state
9
+ * @returns {Object} The same subscription object
10
+ */
11
+ function formatOutlookSubscription(subscription, accountState) {
12
+ const state = subscription.state || {};
13
+ const expires = subscription.expirationDateTime;
14
+
15
+ subscription.subscriptionExpiresStr = expires ? expires.toISOString() : false;
16
+ subscription.isValid = state.state !== 'error' && expires && expires > new Date();
17
+
18
+ subscription.stateLabel = (state.state || '').replace(/^./, c => c.toUpperCase());
19
+ if ((state.state === 'created' && !expires) || expires < new Date()) {
20
+ subscription.stateLabel = 'Expired';
21
+ }
22
+
23
+ // See OutlookClient.reportSubscriptionFailure()
24
+ subscription.polling = state.state === 'error' && accountState === 'connected' && !!FALLBACK_POLL_INTERVAL;
25
+
26
+ // One severity for the badge and the alert: a failure the poller stands in for is a warning
27
+ if (subscription.isValid) {
28
+ subscription.variant = 'success';
29
+ } else {
30
+ subscription.variant = state.state === 'error' && !subscription.polling ? 'error' : 'warning';
31
+ }
32
+
33
+ return subscription;
34
+ }
35
+
36
+ module.exports = { formatOutlookSubscription };
@@ -20,6 +20,7 @@ const { redis } = require('../db');
20
20
  const { toolGrants } = require('../mcp/tools');
21
21
  const { Account, accountsExist, accountSummary, isAuthFailureDisabled, isAccessTokenInvalidated } = require('../account');
22
22
  const { REDIS_PREFIX, DEFAULT_PAGE_SIZE } = require('../consts');
23
+ const { formatOutlookSubscription } = require('./outlook-subscription-view');
23
24
  const { oauth2ProviderData } = require('../oauth2-apps');
24
25
  const exampleDocumentsPayloads = require('../payload-examples-documents.json');
25
26
 
@@ -224,20 +225,7 @@ function formatAccountData(account, gt) {
224
225
  account.oauth2.accessTokenInvalidated = isAccessTokenInvalidated(account.oauth2);
225
226
 
226
227
  if (account.outlookSubscription) {
227
- account.outlookSubscription.subscriptionExpiresStr = account.outlookSubscription.expirationDateTime
228
- ? account.outlookSubscription.expirationDateTime.toISOString()
229
- : false;
230
-
231
- let state = account.outlookSubscription.state || {};
232
-
233
- account.outlookSubscription.isValid =
234
- state.state !== 'error' && account.outlookSubscription.expirationDateTime && account.outlookSubscription.expirationDateTime > new Date();
235
-
236
- account.outlookSubscription.stateLabel = (state.state || '').replace(/^./, c => c.toUpperCase());
237
-
238
- if ((state.state === 'created' && !account.outlookSubscription.expirationDateTime) || account.outlookSubscription.expirationDateTime < new Date()) {
239
- account.outlookSubscription.stateLabel = 'Expired';
240
- }
228
+ formatOutlookSubscription(account.outlookSubscription, account.state);
241
229
  }
242
230
  }
243
231
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "emailengine-app",
3
- "version": "2.82.1",
3
+ "version": "2.82.2",
4
4
  "private": false,
5
5
  "productTitle": "EmailEngine",
6
6
  "description": "Email Sync Engine",
@@ -351,7 +351,7 @@
351
351
  <dd>
352
352
 
353
353
  {{#*inline "outlookWatchBadge"}}
354
- <span class="badge badge-{{#if account.outlookSubscription.isValid}}success{{else}}{{#if account.outlookSubscription.state.error}}error{{else}}warning{{/if}}{{/if}}">
354
+ <span class="badge badge-{{account.outlookSubscription.variant}}">
355
355
  {{account.outlookSubscription.stateLabel}}
356
356
  </span>
357
357
  {{/inline}}
@@ -368,8 +368,11 @@
368
368
  {{/if}}
369
369
 
370
370
  {{#if account.outlookSubscription.state.error}}
371
- <div class="alert alert-soft alert-error">
371
+ <div class="alert alert-soft alert-{{account.outlookSubscription.variant}}">
372
372
  {{account.outlookSubscription.state.error}}
373
+ {{#if account.outlookSubscription.polling}}
374
+ <p class="mt-1">New messages are still found by a periodic check, but changes to and deletions of existing messages are not reported until a subscription can be created.</p>
375
+ {{/if}}
373
376
 
374
377
  {{#if account.outlookSubscription.state.time}}
375
378
  <small>(last checked <span class="local-date-time"