emailengine-app 2.79.4 → 2.79.5

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.
@@ -149,7 +149,9 @@ jobs:
149
149
  name: digests-${{ matrix.arch }}
150
150
  path: /tmp/digests/*
151
151
  if-no-files-found: error
152
- retention-days: 1
152
+ # Long enough for "Re-run failed jobs" on a later working day to still find the
153
+ # digest of the leg that passed; the check below refuses to publish without it
154
+ retention-days: 7
153
155
 
154
156
  docker-manifest:
155
157
  name: Publish Docker Manifest
@@ -168,6 +170,20 @@ jobs:
168
170
  pattern: digests-*
169
171
  merge-multiple: true
170
172
 
173
+ # One digest file per platform in the build matrix. With fail-fast off, one leg can
174
+ # push its digest while the other fails, and a re-run that finds only the surviving
175
+ # artifact (or none, once they expire) would otherwise publish a single-platform
176
+ # manifest list under every tag as if it were complete.
177
+ - name: Check that every platform produced a digest
178
+ working-directory: /tmp/digests
179
+ run: |
180
+ count=$(ls -1 | wc -l)
181
+ if [ "$count" -ne 2 ]; then
182
+ echo "Expected 2 digests (linux/amd64, linux/arm64), found $count:"
183
+ ls -1
184
+ exit 1
185
+ fi
186
+
171
187
  - name: Set up Docker Buildx
172
188
  uses: docker/setup-buildx-action@v4
173
189
 
@@ -146,7 +146,9 @@ jobs:
146
146
  name: digests-${{ matrix.arch }}
147
147
  path: /tmp/digests/*
148
148
  if-no-files-found: error
149
- retention-days: 1
149
+ # Long enough for "Re-run failed jobs" on a later working day to still find the
150
+ # digest of the leg that passed; the check below refuses to publish without it
151
+ retention-days: 7
150
152
 
151
153
  publish_docker_manifest:
152
154
  name: Publish Tagged Docker Manifest
@@ -164,6 +166,20 @@ jobs:
164
166
  pattern: digests-*
165
167
  merge-multiple: true
166
168
 
169
+ # One digest file per platform in the build matrix. With fail-fast off, one leg can
170
+ # push its digest while the other fails, and a re-run that finds only the surviving
171
+ # artifact (or none, once they expire) would otherwise publish a single-platform
172
+ # manifest list under every tag as if it were complete.
173
+ - name: Check that every platform produced a digest
174
+ working-directory: /tmp/digests
175
+ run: |
176
+ count=$(ls -1 | wc -l)
177
+ if [ "$count" -ne 2 ]; then
178
+ echo "Expected 2 digests (linux/amd64, linux/arm64), found $count:"
179
+ ls -1
180
+ exit 1
181
+ fi
182
+
167
183
  - name: Set up Docker Buildx
168
184
  uses: docker/setup-buildx-action@v4
169
185
 
@@ -1,3 +1,3 @@
1
1
  {
2
- ".": "2.79.4"
2
+ ".": "2.79.5"
3
3
  }
package/CHANGELOG.md CHANGED
@@ -1,5 +1,13 @@
1
1
  # Changelog
2
2
 
3
+ ## [2.79.5](https://github.com/postalsys/emailengine/compare/v2.79.4...v2.79.5) (2026-08-26)
4
+
5
+
6
+ ### Bug Fixes
7
+
8
+ * **accounts:** bring back the OAuth2 accounts 2.79.3 switched off ([e55520c](https://github.com/postalsys/emailengine/commit/e55520c8a669677a5af3e4ed726ecc0e329ad84a))
9
+ * **accounts:** close the gaps in the auth-failure park for OAuth2 accounts ([6a015b6](https://github.com/postalsys/emailengine/commit/6a015b6ba10a1e6a39575fa96539d311c00aa958))
10
+
3
11
  ## [2.79.4](https://github.com/postalsys/emailengine/compare/v2.79.3...v2.79.4) (2026-08-25)
4
12
 
5
13
 
@@ -0,0 +1,176 @@
1
+ 'use strict';
2
+
3
+ // One-time bridge for the OAuth2 accounts 2.79.3 switched off and 2.79.4 cannot recognise.
4
+ //
5
+ // 2.79.3 extended the auth-failure safety net to OAuth2 accounts, which until then it had skipped in
6
+ // silence, and its release note predicted the result: on upgrade, every account whose refresh token
7
+ // had already been dead for longer than the threshold was parked in one burst. It recorded that park
8
+ // as `imap.disabled` and nothing else.
9
+ //
10
+ // 2.79.4 then gave the automatic park its own provenance marker, because `imap.disabled` is also the
11
+ // operator's deliberate send-only switch and the two must not share one boolean. Every recovery and
12
+ // reporting surface reads the marker: the API's `authFailureDisabledAt`, the account page's
13
+ // "Syncing was switched off" alert and its "Resume syncing" action, the listing's state badge, the
14
+ // reconnect refusal, and - the one that matters here - the lift that re-authorization performs
15
+ // through Account.create() and Account.update().
16
+ //
17
+ // So an account parked during the roughly nineteen hours 2.79.3 was the current release reads as one
18
+ // the operator switched off on purpose. Re-authorizing it, through the hosted authentication form or
19
+ // POST /v1/account, reports success and lifts nothing. That is unrecoverable rather than merely
20
+ // wrong for an OAuth2 account: its page renders no IMAP settings card, so there is no disable
21
+ // checkbox to clear, and "Resume syncing" is marker-gated like everything else.
22
+ //
23
+ // The signature is therefore the synthesized blob 2.79.3 wrote for exactly that population, not the
24
+ // park in general: the bare flag, an OAuth2 credential, and an authentication error beside them
25
+ // (see isLegacyPark() for why the error is not required to be the park's own text). A password
26
+ // account carries a real IMAP configuration and has been wearing this same threshold error state
27
+ // since v2.46.0 (2024-08-28), where the safety net first shipped; it is deliberately not matched,
28
+ // because it was never stuck - clearing its checkbox is an explicit `disabled: false`, which is not
29
+ // marker-gated - and matching it would stamp accounts nobody has touched in two years with a park
30
+ // time of today.
31
+ //
32
+ // The true park time is not recoverable, since 2.79.3 stored none, so the marker holds the time of
33
+ // this run and the log says so. It overstates how recently the account stopped syncing, by however
34
+ // long the instance sat on 2.79.3, and that is the only cost of making it recoverable.
35
+ //
36
+ // Retire this once no supported upgrade path starts below 2.79.4. Until then a completion key says
37
+ // it has run, because a successful backfill leaves nothing behind to re-detect. An instance rolled
38
+ // back onto 2.79.3 afterwards, or a 2.79.3 sibling still parking accounts on the same Redis during a
39
+ // rolling upgrade, would leave a second batch that the key then hides; re-arming means deleting
40
+ // BACKFILL_KEY and restarting.
41
+
42
+ const { redis } = require('../db');
43
+ const logger = require('../logger');
44
+ const { parseImapData } = require('./imap-data');
45
+ const { REDIS_PREFIX, AUTH_FAILURE_DISABLED_FIELD, AUTH_FAILURE_DISABLED_LEGACY_DESCRIPTION } = require('../consts');
46
+
47
+ // Marks the backfill as done for this Redis. Value is the ISO time of the run.
48
+ const BACKFILL_KEY = `${REDIS_PREFIX}migration:authFailureDisabled`;
49
+
50
+ // Accounts read per pipeline. Large installs hold tens of thousands, and sequential reads would
51
+ // stall startup; matches the chunking oauth2Apps.migrateLegacyApps() uses for its own backfill.
52
+ const CHUNK_SIZE = 500;
53
+
54
+ // Fields the scan reads per account, in the order isLegacyPark() destructures them
55
+ const SCAN_FIELDS = ['imap', AUTH_FAILURE_DISABLED_FIELD, 'lastErrorState', 'oauth2'];
56
+
57
+ /**
58
+ * Whether an account hash carries the park 2.79.3 wrote for an OAuth2 account.
59
+ *
60
+ * @param {Array} row - The SCAN_FIELDS values as stored, any of them null
61
+ * @returns {Boolean} True when the marker should be backfilled for this account
62
+ */
63
+ function isLegacyPark([imapInfo, marker, errorStateInfo, oauth2Info]) {
64
+ // Ordered cheapest first, so a healthy fleet is rejected without parsing anything. A successful
65
+ // connection deletes lastErrorState outright, and only an OAuth2 credential could have been
66
+ // parked into an `imap` blob the account does not otherwise own.
67
+ if (marker || !imapInfo || !errorStateInfo || !oauth2Info) {
68
+ return false;
69
+ }
70
+
71
+ const { imapData } = parseImapData(imapInfo);
72
+
73
+ // The whole blob 2.79.3 synthesized was the flag. A `host` means a real IMAP configuration that
74
+ // the operator can re-enable from the account page, which is the population deliberately left
75
+ // out; anything that did not parse to a usable object was never written by the safety net.
76
+ if (!imapData || imapData.disabled !== true || imapData.host) {
77
+ return false;
78
+ }
79
+
80
+ let errorState;
81
+ try {
82
+ errorState = JSON.parse(errorStateInfo);
83
+ } catch (err) {
84
+ return false;
85
+ }
86
+
87
+ // The threshold text is what 2.79.3 wrote at the park, and it does not always survive: a parked
88
+ // account still serves send requests and, for Gmail, push notifications, and each of those runs
89
+ // the same failing token refresh through setErrorState(), which overwrites the stored error with
90
+ // the refresh failure that caused the park. That failure carries a serverResponseCode
91
+ // ('TokenGenerationError', 'OauthRenewError') where the park text carries none, so either shape
92
+ // counts. The operator's send-only switch is still told apart by what sits beside the bare
93
+ // flag: a deliberately switched-off account has no reason to carry a coded authentication error.
94
+ return !!errorState && (errorState.description === AUTH_FAILURE_DISABLED_LEGACY_DESCRIPTION || !!errorState.serverResponseCode);
95
+ }
96
+
97
+ /**
98
+ * Backfills AUTH_FAILURE_DISABLED_FIELD onto the OAuth2 accounts 2.79.3 parked, so the 2.79.4
99
+ * recovery paths can see them.
100
+ *
101
+ * No lock, unlike oauth2Apps.migrateLegacyApps(): every write here is an idempotent set of the same
102
+ * field on an account already carrying the signature, so two instances sharing one Redis can both
103
+ * run it and the worst that happens is the scan being done twice. Taking a lock would cost every
104
+ * instance a permanent second Redis connection - ioredfour duplicates one for its subscriber and
105
+ * offers no way to close it - to serialize something that does not need serializing.
106
+ *
107
+ * @param {Object} [opts] - Overrides for tests; the defaults are the shared clients
108
+ * @param {Object} [opts.redis] - ioredis client, carrying the hSetExists custom command
109
+ * @param {Object} [opts.logger] - Logger
110
+ * @returns {Promise<Number>} How many accounts were backfilled
111
+ */
112
+ async function backfillAuthFailureDisabled(opts = {}) {
113
+ const { redis: client = redis, logger: log = logger } = opts;
114
+
115
+ // The common case is an instance that never ran 2.79.3, and this is the whole cost for it
116
+ if (await client.exists(BACKFILL_KEY)) {
117
+ return 0;
118
+ }
119
+
120
+ const stamp = new Date().toISOString();
121
+ const accounts = await client.smembers(`${REDIS_PREFIX}ia:accounts`);
122
+
123
+ // One write pipeline for the whole scan rather than one per chunk: matches are a small subset by
124
+ // definition, and a round trip per chunk would double what the scan costs at startup.
125
+ const writeReq = client.pipeline();
126
+ let queued = 0;
127
+
128
+ for (let i = 0; i < accounts.length; i += CHUNK_SIZE) {
129
+ const chunk = accounts.slice(i, i + CHUNK_SIZE);
130
+
131
+ const readReq = client.pipeline();
132
+ for (const account of chunk) {
133
+ readReq.hmget(`${REDIS_PREFIX}iad:${account}`, ...SCAN_FIELDS);
134
+ }
135
+ const rows = await readReq.exec();
136
+
137
+ for (let j = 0; j < chunk.length; j++) {
138
+ const [err, row] = rows[j];
139
+ if (err || !row || !isLegacyPark(row)) {
140
+ continue;
141
+ }
142
+ // hSetExists rather than hset, for the same reason the safety net writes it that way: an
143
+ // account deleted between the read above and this write must not come back as a hash
144
+ // holding nothing but a marker.
145
+ writeReq.hSetExists(`${REDIS_PREFIX}iad:${chunk[j]}`, AUTH_FAILURE_DISABLED_FIELD, stamp);
146
+ queued++;
147
+ }
148
+ }
149
+
150
+ // Counted from the replies rather than from what was queued: hSetExists writes nothing to an
151
+ // account deleted since the read, and a marker the log claims but Redis does not hold would send
152
+ // whoever reads that number looking for accounts that are still invisible.
153
+ let backfilled = 0;
154
+ if (queued) {
155
+ const results = await writeReq.exec();
156
+ backfilled = (results || []).filter(([err, written]) => !err && written).length;
157
+ }
158
+
159
+ // Written last, so a crash mid-scan re-enters and repeats it. Every write is idempotent, so
160
+ // repeating costs nothing.
161
+ await client.set(BACKFILL_KEY, stamp);
162
+
163
+ if (queued) {
164
+ log.info({
165
+ msg: 'Backfilled the auth-failure disable marker for accounts switched off by an earlier version',
166
+ accounts: backfilled,
167
+ skipped: queued - backfilled,
168
+ disabledAt: stamp,
169
+ note: 'the recorded time is when this ran, not when the accounts were switched off'
170
+ });
171
+ }
172
+
173
+ return backfilled;
174
+ }
175
+
176
+ module.exports = { backfillAuthFailureDisabled, isLegacyPark, BACKFILL_KEY };
@@ -1,5 +1,51 @@
1
1
  'use strict';
2
2
 
3
+ /**
4
+ * Decides what a stored `imap` blob is, without reading it.
5
+ *
6
+ * Split out from readImapData() so a caller that already holds the raw field, and cannot await or
7
+ * afford a log line per account, still shares the one definition of a usable blob. The scan in
8
+ * auth-failure-backfill.js is that caller.
9
+ *
10
+ * @param {String} imapInfo - The raw field as stored
11
+ * @param {Object} [logger] - Logger for a blob that cannot be used; silent when omitted
12
+ * @returns {{imapData: Object|null, invalid: Boolean}} See readImapData()
13
+ */
14
+ function parseImapData(imapInfo, logger) {
15
+ if (!imapInfo) {
16
+ return { imapData: null, invalid: false };
17
+ }
18
+
19
+ let imapData;
20
+ try {
21
+ imapData = JSON.parse(imapInfo);
22
+ } catch (err) {
23
+ logger?.error({ msg: 'Failed parsing IMAP data', err });
24
+ return { imapData: null, invalid: true };
25
+ }
26
+
27
+ // `null` parses fine and is an absent blob, which is what it is. So is `false`: it is what POST
28
+ // and PUT /v1/account store when the payload says there is no IMAP access to configure
29
+ // (`imap: false`), the documented way to register an OAuth2 account without one. Reporting it
30
+ // as unreadable would exempt exactly those accounts from the safety net and log an error on
31
+ // every init.
32
+ if (imapData === null || imapData === false) {
33
+ return { imapData: null, invalid: false };
34
+ }
35
+
36
+ // Parsing is not enough: every caller goes on to read or set `disabled` on what comes back, and
37
+ // a blob that parsed to a scalar throws on the assignment while one that parsed to an array
38
+ // takes the flag and loses it again at the next JSON.stringify. Only an object is usable, so a
39
+ // stored value that is anything else counts as unreadable and is left alone rather than
40
+ // replaced with a bare flag.
41
+ if (typeof imapData !== 'object' || Array.isArray(imapData)) {
42
+ logger?.error({ msg: 'Unexpected IMAP data type', type: Array.isArray(imapData) ? 'array' : typeof imapData });
43
+ return { imapData: null, invalid: true };
44
+ }
45
+
46
+ return { imapData, invalid: false };
47
+ }
48
+
3
49
  /**
4
50
  * Reads an account's stored `imap` blob.
5
51
  *
@@ -14,23 +60,15 @@
14
60
  * @param {Object} logger - Logger for the parse failure
15
61
  * @param {String} [imapInfo] - The raw field when the caller has already read it, to save a round trip
16
62
  * @returns {Promise<{imapData: Object|null, invalid: Boolean}>} The parsed blob, or null with
17
- * `invalid` telling an absent field (an OAuth2 account has none) apart from an unreadable one
63
+ * `invalid` telling an absent field (an OAuth2 account has none) apart from an unreadable one.
64
+ * Unreadable covers anything the callers cannot use, not only text that fails to parse
18
65
  */
19
66
  async function readImapData(redis, accountKey, logger, imapInfo) {
20
67
  if (imapInfo === undefined) {
21
68
  imapInfo = await redis.hget(accountKey, 'imap');
22
69
  }
23
70
 
24
- if (!imapInfo) {
25
- return { imapData: null, invalid: false };
26
- }
27
-
28
- try {
29
- return { imapData: JSON.parse(imapInfo), invalid: false };
30
- } catch (err) {
31
- logger.error({ msg: 'Failed parsing IMAP data', err });
32
- return { imapData: null, invalid: true };
33
- }
71
+ return parseImapData(imapInfo, logger);
34
72
  }
35
73
 
36
- module.exports = { readImapData };
74
+ module.exports = { readImapData, parseImapData };
package/lib/account.js CHANGED
@@ -19,7 +19,7 @@ const {
19
19
  } = require('./tools');
20
20
  const { MessageChannel } = require('worker_threads');
21
21
  const { MessagePortReadable } = require('./message-port-stream');
22
- const { deepStrictEqual, strictEqual } = require('assert');
22
+ const { isDeepStrictEqual } = require('util');
23
23
  const { encrypt, decrypt } = require('./encrypt');
24
24
  const { oauth2Apps, isApiBasedApp } = require('./oauth2-apps');
25
25
  const settings = require('./settings');
@@ -33,7 +33,7 @@ const { customAlphabet } = require('nanoid');
33
33
  const Lock = require('ioredfour');
34
34
  const { redis } = require('./db');
35
35
  const nanoid = customAlphabet('0123456789abcdefghijklmnopqrstuvwxyz', 16);
36
- const { REDIS_PREFIX, ACCOUNT_DELETED_NOTIFY, AUTH_FAILURE_DISABLED_FIELD } = require('./consts');
36
+ const { REDIS_PREFIX, ACCOUNT_DELETED_NOTIFY, AUTH_FAILURE_DISABLED_FIELD, AUTH_FAILURE_DISABLED_LEGACY_DESCRIPTION } = require('./consts');
37
37
  const { messageWebSafeHtml, webSafeTextResponse, applyWebSafeHtmlOptions } = require('./web-safe-html');
38
38
  const { checkAccountScopes: checkScopes } = require('./oauth/scope-checker');
39
39
  const { ACCOUNT_STATES, ERROR_STATES, calculateEffectiveState, validateAccountState, getDisplayState, formatLastError } = require('./account/account-state');
@@ -100,6 +100,35 @@ function authFailureDisabledAt(accountData) {
100
100
  return accountData._authFailureDisabledAt;
101
101
  }
102
102
 
103
+ /**
104
+ * Whether the safety net switched an account off, counting parks recorded before the marker
105
+ * existed: those left `imap.disabled` plus the threshold description in `lastErrorState`, and
106
+ * nothing but the park writes that description (why only the OAuth2 ones were stamped with a
107
+ * marker is in lib/account/auth-failure-backfill.js). Display only - the reconnect refusal, the API
108
+ * field and "Resume syncing" stay keyed on the marker.
109
+ *
110
+ * @param {Object} accountData - An unserialized account
111
+ * @returns {Boolean} True when either generation of the safety net parked the account
112
+ */
113
+ function isAuthFailureDisabled(accountData) {
114
+ return (
115
+ !!authFailureDisabledAt(accountData) ||
116
+ (isImapDisabled(accountData) && accountData.lastErrorState?.description === AUTH_FAILURE_DISABLED_LEGACY_DESCRIPTION)
117
+ );
118
+ }
119
+
120
+ /**
121
+ * Whether the operator switched IMAP off - the send-only switch - as opposed to the safety net
122
+ * parking the account. Send-only is a configuration, a park is a fault, and the surfaces that
123
+ * present one must not present the other.
124
+ *
125
+ * @param {Object} accountData - An unserialized account
126
+ * @returns {Boolean} True when `imap.disabled` is set and the safety net did not set it
127
+ */
128
+ function isOperatorDisabled(accountData) {
129
+ return isImapDisabled(accountData) && !authFailureDisabledAt(accountData);
130
+ }
131
+
103
132
  class Account {
104
133
  constructor(options) {
105
134
  this.redis = options.redis;
@@ -195,8 +224,10 @@ class Account {
195
224
  // - IMAP is explicitly disabled, OR
196
225
  // - IMAP is not configured (missing or empty)
197
226
  if (accountData.imap) {
198
- // IMAP exists - check if it's disabled
199
- return !!accountData.imap.disabled;
227
+ // IMAP exists - check if the operator switched it off. A park by the safety net is not
228
+ // send-only: reporting it as such hid the IMAP card, and the stored error with it,
229
+ // behind the "API Send-only" presentation.
230
+ return isOperatorDisabled(accountData);
200
231
  }
201
232
 
202
233
  // No IMAP configuration at all
@@ -316,7 +347,8 @@ class Account {
316
347
  accountData.type = 'invalid';
317
348
  accountData.delegationError = err.message;
318
349
  }
319
- } else if (accountData.imap && !accountData.imap.disabled) {
350
+ } else if (accountData.imap && !isOperatorDisabled(accountData)) {
351
+ // A parked account is still an IMAP account, only switched off
320
352
  accountData.type = 'imap';
321
353
  } else {
322
354
  // Default to 'sending' type for accounts without IMAP
@@ -1046,50 +1078,10 @@ class Account {
1046
1078
  * @returns {Promise<void>} Resolves once the dispatch has been attempted
1047
1079
  */
1048
1080
  async dispatchPostUpdateCommands(accountData, oldAccountData, reauthorized, disabledIntent) {
1049
- let reconnectRequested = false;
1050
-
1051
- if ('imap' in accountData && !reconnectRequested) {
1052
- try {
1053
- deepStrictEqual(oldAccountData.imap, accountData.imap);
1054
- } catch (err) {
1055
- // changes detected!
1056
- reconnectRequested = true;
1057
- }
1058
- }
1059
-
1060
- if ('path' in accountData && !reconnectRequested) {
1061
- try {
1062
- strictEqual(JSON.stringify(oldAccountData.path || '*'), JSON.stringify(accountData.path || '*'));
1063
- } catch (err) {
1064
- // changes detected!
1065
- reconnectRequested = true;
1066
- }
1067
- }
1068
-
1069
- if ('subconnections' in accountData && !reconnectRequested) {
1070
- try {
1071
- deepStrictEqual(oldAccountData.subconnections, accountData.subconnections);
1072
- } catch (err) {
1073
- // changes detected!
1074
- reconnectRequested = true;
1075
- }
1076
- }
1077
-
1078
- if (reconnectRequested) {
1079
- // changes detected!
1080
- this.logger.info({ msg: 'IMAP configuration changed for account', account: this.account });
1081
- if (typeof this.call === 'function') {
1082
- await this.call({
1083
- cmd: 'update',
1084
- account: this.account,
1085
- timeout: this.timeout
1086
- });
1087
- } else {
1088
- // This Account instance has no parent RPC channel (constructed without `call`).
1089
- // Skip the dispatch instead of throwing - the persisted change stands.
1090
- this.logger.warn({ msg: 'Skipping update command dispatch, no parent RPC channel', account: this.account });
1091
- }
1092
- }
1081
+ const reconnectRequested =
1082
+ ('imap' in accountData && !isDeepStrictEqual(oldAccountData.imap, accountData.imap)) ||
1083
+ ('path' in accountData && JSON.stringify(oldAccountData.path || '*') !== JSON.stringify(accountData.path || '*')) ||
1084
+ ('subconnections' in accountData && !isDeepStrictEqual(oldAccountData.subconnections, accountData.subconnections));
1093
1085
 
1094
1086
  // Whether this update carries OAuth2 credentials the operator just re-authorized. The
1095
1087
  // `reauthorized` intent has to be explicit: account state cannot be used to infer it,
@@ -1103,16 +1095,25 @@ class Account {
1103
1095
  !!accountData.oauth2?.accessToken &&
1104
1096
  (accountData.oauth2.accessToken !== oldAccountData.oauth2?.accessToken || accountData.oauth2.refreshToken !== oldAccountData.oauth2?.refreshToken);
1105
1097
 
1098
+ // The password-account counterpart: new IMAP credentials from the same flagged route. The
1099
+ // API documents that saving new IMAP settings resumes a switched-off account, and the
1100
+ // documented way to save them is a `partial` write of `imap.auth` - which persistUpdate()
1101
+ // has by now merged the stored `disabled: true` into, so the intent captured before the
1102
+ // merge says nothing and this is what carries the lift.
1103
+ const imapReauthorized = reauthorized && !!accountData.imap?.auth && !isDeepStrictEqual(accountData.imap.auth, oldAccountData.imap?.auth);
1104
+
1106
1105
  // A reconnect cannot resume an account the auth-failure safety net has switched off, so
1107
- // settle that first. For a password account the operator clears the flag by saving new IMAP
1108
- // settings, but an OAuth2 account has none to save - the re-authorization IS the fix, and
1109
- // without this the account stays off until somebody hand-edits it through the API.
1106
+ // settle that first, before any dispatch: the worker acts on the stored flag, so an update
1107
+ // sent ahead of the lift finds the account still switched off and reports `unset`. For a
1108
+ // password account the operator clears the flag by saving new IMAP settings, but an OAuth2
1109
+ // account has none to save - the re-authorization IS the fix, and without this the account
1110
+ // stays off until somebody hand-edits it through the API.
1110
1111
  //
1111
1112
  // The lift is deliberately NOT gated on the account state, unlike the reconnect below: a
1112
1113
  // parked account does not sit in an error state, it reports `unset` (persisted on every
1113
1114
  // init for Gmail API and Outlook accounts), so by the time the operator re-authorizes, the
1114
1115
  // error state the old gate required is long gone.
1115
- await this.resolveAuthFailureDisable(disabledIntent, oldAccountData, oauth2Reauthorized);
1116
+ await this.resolveAuthFailureDisable(disabledIntent, oldAccountData, oauth2Reauthorized || imapReauthorized);
1116
1117
 
1117
1118
  // Re-authorization for an account that is currently non-operational triggers a full
1118
1119
  // reconnect so syncing resumes without a manual "Reconnect". Being switched off is such a
@@ -1120,7 +1121,7 @@ class Account {
1120
1121
  // before the write, for the same reason as in create().
1121
1122
  const wasParked = !!authFailureDisabledAt(oldAccountData);
1122
1123
 
1123
- if (oauth2Reauthorized && !reconnectRequested && (ERROR_STATES.includes(oldAccountData.state) || wasParked)) {
1124
+ if (oauth2Reauthorized && (ERROR_STATES.includes(oldAccountData.state) || wasParked)) {
1124
1125
  this.logger.info({
1125
1126
  msg: 'OAuth2 credentials re-authorized for non-operational account, requesting reconnect',
1126
1127
  account: this.account,
@@ -1152,6 +1153,21 @@ class Account {
1152
1153
  state: oldAccountData.state
1153
1154
  });
1154
1155
  }
1156
+ } else if (reconnectRequested) {
1157
+ // Changes detected. The full reconnect above supersedes this: it assigns a fresh
1158
+ // client, which reads the changed settings on its way in.
1159
+ this.logger.info({ msg: 'IMAP configuration changed for account', account: this.account });
1160
+ if (typeof this.call === 'function') {
1161
+ await this.call({
1162
+ cmd: 'update',
1163
+ account: this.account,
1164
+ timeout: this.timeout
1165
+ });
1166
+ } else {
1167
+ // This Account instance has no parent RPC channel (constructed without `call`).
1168
+ // Skip the dispatch instead of throwing - the persisted change stands.
1169
+ this.logger.warn({ msg: 'Skipping update command dispatch, no parent RPC channel', account: this.account });
1170
+ }
1155
1171
  }
1156
1172
  }
1157
1173
 
@@ -1375,10 +1391,28 @@ class Account {
1375
1391
  // flag ended up lifted: a payload asking for IMAP to stay off lifts nothing, and either
1376
1392
  // way the account was not connecting and this write is what changed that.
1377
1393
  const wasParked = !!authFailureDisabledAt(oldAccountData);
1378
- await this.resolveAuthFailureDisable(imapDisabledIntent(accountData), oldAccountData, true);
1394
+
1395
+ // A password configuration means nothing on an OAuth2 account: getImapConfig() builds
1396
+ // the connection from the provider table and reads `imap` only when there is no OAuth2
1397
+ // credential. So when a re-registration switches the account to OAuth2, the stored one
1398
+ // is left over from the account's previous life, and left in place its `disabled` flag
1399
+ // switches the new account off - the API clients honor the flag since the safety net
1400
+ // started writing it - with no marker, no badge, and no IMAP card to clear it from. A
1401
+ // password account the safety net parked, then re-registered with OAuth2 under the same
1402
+ // id, is exactly that account.
1403
+ const credentialTypeChanged = !!(accountData.oauth2 && !('imap' in accountData) && oldAccountData.imap?.host);
1404
+ if (credentialTypeChanged) {
1405
+ // The marker goes with the blob: a dropped configuration carries no park to lift
1406
+ await this.redis.hdel(this.getAccountKey(), 'imap', AUTH_FAILURE_DISABLED_FIELD);
1407
+ this.logger.info({ msg: 'Dropped the stored IMAP configuration of an account re-registered with OAuth2', account: this.account });
1408
+ } else {
1409
+ await this.resolveAuthFailureDisable(imapDisabledIntent(accountData), oldAccountData, true);
1410
+ }
1379
1411
 
1380
1412
  const oldState = result[0][1].state;
1381
- if (ERROR_STATES.includes(oldState) || wasParked) {
1413
+ // The credential type changing is a reason of its own for the full reconnect: the
1414
+ // assigned client is of the old type, and cmd:'update' cannot switch it.
1415
+ if (ERROR_STATES.includes(oldState) || wasParked || credentialTypeChanged) {
1382
1416
  // Re-registration of an account that is not operational (the interactive OAuth
1383
1417
  // re-auth redirect and the IMAP re-credentials form both land here).
1384
1418
  // cmd:'update' only calls reconnect() on the existing client instance, which cannot
@@ -3335,4 +3369,4 @@ async function accountSummary(redis, account) {
3335
3369
  return { account, name: name || '', email: email || '', state: state || 'init' };
3336
3370
  }
3337
3371
 
3338
- module.exports = { Account, accountExists, accountsExist, accountSummary, authFailureDisabledAt };
3372
+ module.exports = { Account, accountExists, accountsExist, accountSummary, authFailureDisabledAt, isAuthFailureDisabled, isOperatorDisabled };
package/lib/consts.js CHANGED
@@ -145,6 +145,17 @@ module.exports = {
145
145
  // carry is the separate, read-only `_authFailureDisabledAt`.
146
146
  AUTH_FAILURE_DISABLED_FIELD: '_authFailureDisabled',
147
147
 
148
+ // The `lastErrorState.description` the safety net stores when it parks an account, and the log
149
+ // line it writes at the same moment. User-visible copy: reword it freely, nothing matches on it.
150
+ AUTH_FAILURE_DISABLED_DESCRIPTION: 'IMAP was disabled for the account due to exceeding the authentication error threshold',
151
+
152
+ // Frozen copy of the description as every release up to 2.79.4 stored it. Releases before the
153
+ // marker above existed recorded a park as `imap.disabled` plus this text and nothing else, so
154
+ // this is the only signature those parks carry: the startup backfill and the state badge both
155
+ // match on it. It has to keep matching data written by past releases, which is why it is a
156
+ // separate constant from the live description rather than a reference to it.
157
+ AUTH_FAILURE_DISABLED_LEGACY_DESCRIPTION: 'IMAP was disabled for the account due to exceeding the authentication error threshold',
158
+
148
159
  REDIS_PREFIX: ((process.env.EENGINE_REDIS_PREFIX || '').toString().trim() + ':').replace(/^:/, ''),
149
160
 
150
161
  REDIS_BATCH_DELETE_SIZE: 1000,
@@ -70,6 +70,7 @@ const {
70
70
  MAX_INLINE_ATTACHMENT_SIZE,
71
71
  DEFAULT_MAX_IMAP_AUTH_FAILURE_TIME,
72
72
  AUTH_FAILURE_DISABLED_FIELD,
73
+ AUTH_FAILURE_DISABLED_DESCRIPTION,
73
74
  EMAIL_DELIVERY_ERROR_NOTIFY,
74
75
  EMAIL_SENT_NOTIFY
75
76
  } = require('../consts');
@@ -639,10 +640,31 @@ class BaseClient {
639
640
  // No IMAP configuration: an OAuth2 account. Only synthesize the flag when there is an
640
641
  // OAuth2 credential for the failures to be about, so an account still being created
641
642
  // cannot be marked disabled on its way in.
642
- const hasOAuth2 = await this.redis.hexists(accountKey, 'oauth2');
643
- if (!hasOAuth2) {
643
+ const oauth2Info = await this.redis.hget(accountKey, 'oauth2');
644
+ if (!oauth2Info) {
644
645
  return false;
645
646
  }
647
+
648
+ let oauth2Data;
649
+ try {
650
+ oauth2Data = JSON.parse(oauth2Info);
651
+ } catch (err) {
652
+ // an unreadable credential is not a delegation
653
+ }
654
+
655
+ if (oauth2Data?.auth?.delegatedUser && oauth2Data?.auth?.delegatedAccount) {
656
+ // A delegated account (an Outlook shared mailbox, say) has no credential of its
657
+ // own: the failures counted here are those of the account it borrows the token
658
+ // from, and re-authorizing that account would lift nothing here. Leave the park to
659
+ // the account that owns the credential, where re-authorization is the fix.
660
+ this.logger.debug({
661
+ msg: 'Skipped disabling a delegated account after authentication failures',
662
+ account: this.account,
663
+ delegatedAccount: oauth2Data.auth.delegatedAccount
664
+ });
665
+ return false;
666
+ }
667
+
646
668
  imapData = {};
647
669
  }
648
670
 
@@ -665,23 +687,40 @@ class BaseClient {
665
687
  accountKey,
666
688
  'lastErrorState',
667
689
  JSON.stringify({
668
- description: 'IMAP was disabled for the account due to exceeding the authentication error threshold',
690
+ description: AUTH_FAILURE_DISABLED_DESCRIPTION,
669
691
  response: data.response
670
692
  })
671
693
  );
672
- await disableTxn.exec();
694
+ const { error } = await disableTxn.exec();
695
+
696
+ if (error) {
697
+ // exec() reports a command-level failure in `error` rather than throwing it, so an
698
+ // unchecked call would announce a park that was never stored: the caller sends the
699
+ // "account was switched off" notification, the connection is torn down, and the flag
700
+ // the connection gates read is still absent, so the account reconnects and keeps
701
+ // hammering the provider. Say nothing happened and let the next failure retry, the same
702
+ // way clearAuthFailureDisable() treats a failed lift.
703
+ this.logger.error({ msg: 'Failed to disable IMAP for account', account: this.account, err: error });
704
+ return false;
705
+ }
673
706
 
674
707
  this.logger.warn({
675
- msg: 'IMAP was disabled for the account due to exceeding the authentication error threshold',
708
+ msg: AUTH_FAILURE_DISABLED_DESCRIPTION,
676
709
  errorEvent: event,
677
710
  firstError: firstError.toISOString(),
678
711
  timeThreshold: MAX_IMAP_AUTH_FAILURE_TIME,
679
712
  errorCount
680
713
  });
681
714
 
682
- // Close the connection after disabling
683
- setImmediate(() => {
684
- this.close();
715
+ // Close the connection after disabling. Nothing awaits this, and for the Gmail API and
716
+ // Graph clients close() is async and writes the account state, so a rejection here would
717
+ // otherwise reach the global handler and take the whole worker down with it.
718
+ setImmediate(async () => {
719
+ try {
720
+ await this.close();
721
+ } catch (err) {
722
+ this.logger.error({ msg: 'Failed to close the connection of a disabled account', account: this.account, err });
723
+ }
685
724
  });
686
725
 
687
726
  return true;
@@ -618,6 +618,12 @@ class GmailClient extends BaseClient {
618
618
  }
619
619
 
620
620
  async reconnect() {
621
+ // A closed instance can be revived here, as IMAPClient.reconnect(force) does: every timer
622
+ // and the watch setup return on `closed`, and init() does not reset it, so without this a
623
+ // reconnect after close() reported a connected account that never synced. The auth-failure
624
+ // safety net produces exactly that instance - the park closes the client but leaves it
625
+ // assigned, and switching the flag back off through PUT /v1/account reconnects it in place.
626
+ this.closed = false;
621
627
  return await this.init({ forceWatchRenewal: true });
622
628
  }
623
629
 
@@ -483,6 +483,13 @@ class OutlookClient extends BaseClient {
483
483
  * Reconnect to the account (re-initialize)
484
484
  */
485
485
  async reconnect() {
486
+ // A closed instance can be revived here, as IMAPClient.reconnect(force) does: the
487
+ // subscription setup and the sync paths return on `closed`, and init() does not reset it,
488
+ // so without this a reconnect after close() reported a connected account that never
489
+ // received a notification. The auth-failure safety net produces exactly that instance - the
490
+ // park closes the client but leaves it assigned, and switching the flag back off through
491
+ // PUT /v1/account reconnects it in place.
492
+ this.closed = false;
486
493
  return await this.init();
487
494
  }
488
495
 
@@ -16,7 +16,7 @@ const tokens = require('../tokens');
16
16
  const { redis, documentsQueue } = require('../db');
17
17
  const getSecret = require('../get-secret');
18
18
  const capa = require('../capa');
19
- const { Account, authFailureDisabledAt } = require('../account');
19
+ const { Account, authFailureDisabledAt, isOperatorDisabled } = require('../account');
20
20
  const { Gateway } = require('../gateway');
21
21
  const { autodetectImapSettings, resolveAppPassword, getAppPassword } = require('../autodetect-imap-settings');
22
22
  const { atomicIncrement } = require('../redis-operations');
@@ -1912,7 +1912,12 @@ function init(args) {
1912
1912
 
1913
1913
  const values = Object.assign({}, flattenObjectKeys(accountData), {
1914
1914
  imap: true,
1915
- imap_disabled: (!accountData.imap && !accountData.oauth2) || (accountData.imap && accountData.imap.disabled),
1915
+ // The checkbox is the operator's own switch, so a park by the auth-failure safety
1916
+ // net does not pre-check it: the page alert promises that saving new credentials
1917
+ // turns syncing back on, and a pre-checked box would have made every such save an
1918
+ // explicit request to keep the account off. Unchecked, the connection fields are
1919
+ // shown and the save writes `disabled: false`, which lifts the park.
1920
+ imap_disabled: (!accountData.imap && !accountData.oauth2) || isOperatorDisabled(accountData),
1916
1921
  imap_tls_ignoreCertErrors: !!(accountData.imap && accountData.imap.tls && accountData.imap.tls.rejectUnauthorized === false),
1917
1922
  smtp: !!accountData.smtp,
1918
1923
  smtp_tls_ignoreCertErrors: !!(accountData.smtp && accountData.smtp.tls && accountData.smtp.tls.rejectUnauthorized === false),
@@ -19,7 +19,7 @@ const psl = require('psl');
19
19
  const settings = require('../settings');
20
20
  const { redis } = require('../db');
21
21
  const { toolGrants } = require('../mcp/tools');
22
- const { Account, accountsExist, accountSummary, authFailureDisabledAt } = require('../account');
22
+ const { Account, accountsExist, accountSummary, isAuthFailureDisabled } = require('../account');
23
23
  const { REDIS_PREFIX, DEFAULT_PAGE_SIZE } = require('../consts');
24
24
  const { oauth2ProviderData } = require('../oauth2-apps');
25
25
  const exampleDocumentsPayloads = require('../payload-examples-documents.json');
@@ -208,11 +208,11 @@ function formatAccountData(account, gt) {
208
208
  // An account the auth-failure safety net switched off reports the neutral "Not syncing", which
209
209
  // says nothing about why it stopped or that a human has to act. Override the label to say so.
210
210
  //
211
- // Keyed on the marker the safety net writes, not on `imap.disabled` plus a leftover error:
212
- // that flag is also the operator's send-only switch, so the old guess badged a deliberately
213
- // send-only account "Connection failed" if it had ever failed to connect, and stayed silent
214
- // about a parked account whose lastErrorState had been overwritten since.
215
- if (authFailureDisabledAt(account)) {
211
+ // Keyed on the marker the safety net writes, or on the exact signature the releases before the
212
+ // marker left behind, not on `imap.disabled` plus any leftover error: that flag is also the
213
+ // operator's send-only switch, so the old guess badged a deliberately send-only account
214
+ // "Connection failed" if it had ever failed to connect.
215
+ if (isAuthFailureDisabled(account)) {
216
216
  account.stateLabel = {
217
217
  type: 'error',
218
218
  name: 'Syncing switched off',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "emailengine-app",
3
- "version": "2.79.4",
3
+ "version": "2.79.5",
4
4
  "private": false,
5
5
  "productTitle": "EmailEngine",
6
6
  "description": "Email Sync Engine",
package/server.js CHANGED
@@ -125,6 +125,7 @@ const Joi = require('joi');
125
125
  const { settingsSchema } = require('./lib/schemas');
126
126
  const settings = require('./lib/settings');
127
127
  const { oauth2Apps } = require('./lib/oauth2-apps');
128
+ const { backfillAuthFailureDisabled } = require('./lib/account/auth-failure-backfill');
128
129
  const { documentStoreFeatureEnabled } = require('./lib/document-store');
129
130
  const { attachBeacon, persistBeaconMarkers } = require('./lib/license-beacon');
130
131
  const tokens = require('./lib/tokens');
@@ -3254,6 +3255,15 @@ const startApplication = async () => {
3254
3255
  logger.error({ msg: 'Failed to migrate legacy OAuth2 apps', err });
3255
3256
  }
3256
3257
 
3258
+ // Give accounts that 2.79.3 switched off after repeated authentication failures the provenance
3259
+ // marker 2.79.4 recognises, so re-authorizing one resumes it instead of silently doing nothing.
3260
+ // A failure is not fatal: the completion key is written last, so the next startup re-enters.
3261
+ try {
3262
+ await backfillAuthFailureDisabled();
3263
+ } catch (err) {
3264
+ logger.error({ msg: 'Failed to backfill the auth-failure disable marker', err });
3265
+ }
3266
+
3257
3267
  // Apply prepared settings
3258
3268
  if (preparedSettings) {
3259
3269
  logger.debug({ msg: 'Applying configuration', settingsKeys: Object.keys(preparedSettings) });