emailengine-app 2.79.4 → 2.79.6

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.6"
3
3
  }
package/CHANGELOG.md CHANGED
@@ -1,5 +1,22 @@
1
1
  # Changelog
2
2
 
3
+ ## [2.79.6](https://github.com/postalsys/emailengine/compare/v2.79.5...v2.79.6) (2026-08-27)
4
+
5
+
6
+ ### Bug Fixes
7
+
8
+ * **deps:** update nodemailer to 9.0.6 and refresh dependencies ([85ce711](https://github.com/postalsys/emailengine/commit/85ce7116d766d3c9b81b77b3d39496ca6119c2d2))
9
+ * **imap:** recover addresses when the ENVELOPE reports an unusable one ([78d5fbd](https://github.com/postalsys/emailengine/commit/78d5fbd62211d79b4c108622e1ad771b34156d06))
10
+ * **reference:** correct three wrong provider claims in the API documentation ([df9fa95](https://github.com/postalsys/emailengine/commit/df9fa95bf542cf086f34d215edd48bb2007e84d6))
11
+
12
+ ## [2.79.5](https://github.com/postalsys/emailengine/compare/v2.79.4...v2.79.5) (2026-08-26)
13
+
14
+
15
+ ### Bug Fixes
16
+
17
+ * **accounts:** bring back the OAuth2 accounts 2.79.3 switched off ([e55520c](https://github.com/postalsys/emailengine/commit/e55520c8a669677a5af3e4ed726ecc0e329ad84a))
18
+ * **accounts:** close the gaps in the auth-failure park for OAuth2 accounts ([6a015b6](https://github.com/postalsys/emailengine/commit/6a015b6ba10a1e6a39575fa96539d311c00aa958))
19
+
3
20
  ## [2.79.4](https://github.com/postalsys/emailengine/compare/v2.79.3...v2.79.4) (2026-08-25)
4
21
 
5
22
 
@@ -1,5 +1,5 @@
1
1
  {
2
- "creationTime": "2026-08-21T14:46:19.000000",
2
+ "creationTime": "2026-08-27T14:46:47.000000",
3
3
  "prefixes": [
4
4
  {
5
5
  "ipv6Prefix": "2001:4860:4801:2008::/64"
@@ -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 };
@@ -1584,8 +1584,11 @@ async function init(args) {
1584
1584
  return getLogs(redis, request.params.account);
1585
1585
  },
1586
1586
  options: {
1587
- description: 'Return IMAP logs for an account',
1588
- notes: ['Output is a downloadable text file', BEHAVIOR.IMAP_ONLY],
1587
+ description: 'Return stored logs for an account',
1588
+ notes: [
1589
+ 'Output is a downloadable text file with one JSON log entry per line, or a plain-text notice when nothing is stored',
1590
+ BEHAVIOR.ACCOUNT_LOG_SCOPE
1591
+ ],
1589
1592
  tags: ['api', 'Logs'],
1590
1593
 
1591
1594
  auth: {
@@ -1596,7 +1599,7 @@ async function init(args) {
1596
1599
 
1597
1600
  plugins: {
1598
1601
  openapi: {
1599
- 'x-ee-behavior': [BEHAVIOR.IMAP_ONLY],
1602
+ 'x-ee-behavior': [BEHAVIOR.ACCOUNT_LOG_SCOPE],
1600
1603
  produces: ['text/plain'],
1601
1604
  responses: apiResponses('Returns the account log as a plain text stream.', 400, 401, 403, 429, 500)
1602
1605
  }
@@ -16,10 +16,11 @@
16
16
  // The provider notes are transcribed by hand from the transports, and nothing enforces the
17
17
  // copy. When changing one, check the code that actually implements the limit - not the
18
18
  // ASCII capability matrices at the top of those files, which are comments too:
19
- // NO_LABEL_SET_ON_GMAIL lib/email-client/gmail-client.js, prepareLabelUpdate throw
19
+ // NO_LABEL_SET_ON_GMAIL lib/email-client/gmail-client.js, assertLabelSetSupported throw
20
20
  // GMAIL_DELETE_IS_TRASH lib/email-client/gmail-client.js, deleteMessage
21
21
  // UPLOAD_DRAFTS_ONLY_GRAPH lib/email-client/outlook-client.js, uploadMessage
22
22
  // NO_QUOTA_ON_API_ACCOUNTS getQuota on both clients
23
+ // ACCOUNT_LOG_SCOPE lib/email-client/base-client.js, getLogger; workers/imap.js, getAccountLogger
23
24
 
24
25
  module.exports = {
25
26
  // --- asynchronous work -------------------------------------------------------------
@@ -43,7 +44,8 @@ module.exports = {
43
44
  'Removes the account, its credentials, its cached data and any messages still queued for delivery. Webhook events generated before the deletion are never delivered afterwards and are discarded once the queue reaches them. Records of deliveries that had already failed permanently are not removed here; they expire on the queue retention window, seven days by default.',
44
45
 
45
46
  // --- provider differences ----------------------------------------------------------
46
- NO_QUOTA_ON_API_ACCOUNTS: 'Quota reporting is not available for Gmail API or MS Graph accounts; the quota field is omitted for those.',
47
+ NO_QUOTA_ON_API_ACCOUNTS:
48
+ 'Quota reporting is not available for Gmail API or MS Graph accounts; the quota field is returned as false for those, the same value an IMAP server without QUOTA support produces.',
47
49
 
48
50
  UPLOAD_DRAFTS_ONLY_GRAPH: 'For MS Graph accounts only drafts can be uploaded, and the draft flag cannot be changed afterwards.',
49
51
 
@@ -53,5 +55,6 @@ module.exports = {
53
55
  GMAIL_DELETE_IS_TRASH:
54
56
  'For Gmail API accounts the message is always moved to Trash. The force option, which permanently deletes on IMAP accounts, has no effect.',
55
57
 
56
- IMAP_ONLY: 'Only available for IMAP accounts. Gmail API and MS Graph accounts have no equivalent.'
58
+ ACCOUNT_LOG_SCOPE:
59
+ 'Nothing is stored unless logging is enabled for the account, either with the account logs flag or the global logs.all setting. IMAP accounts record the protocol trace, Gmail API and MS Graph accounts record their API requests, and SMTP transactions are recorded for any account that sends over SMTP.'
57
60
  };