emailengine-app 2.79.3 → 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.
- package/.github/workflows/deploy.yml +17 -1
- package/.github/workflows/release.yaml +17 -1
- package/.release-please-manifest.json +1 -1
- package/CHANGELOG.md +17 -0
- package/lib/account/auth-failure-backfill.js +176 -0
- package/lib/account/imap-data.js +74 -0
- package/lib/account.js +315 -108
- package/lib/api-routes/account-routes.js +7 -1
- package/lib/consts.js +23 -0
- package/lib/email-client/base-client.js +61 -31
- package/lib/email-client/gmail-client.js +6 -0
- package/lib/email-client/outlook-client.js +7 -0
- package/lib/enum-descriptions.js +1 -1
- package/lib/schemas.js +11 -1
- package/lib/ui-routes/account-routes.js +90 -7
- package/lib/ui-routes/dashboard-routes.js +22 -0
- package/lib/ui-routes/route-helpers.js +11 -5
- package/package.json +1 -1
- package/server.js +10 -0
- package/views/accounts/account.hbs +47 -2
- package/views/legal.hbs +1 -1
package/lib/account.js
CHANGED
|
@@ -19,25 +19,26 @@ const {
|
|
|
19
19
|
} = require('./tools');
|
|
20
20
|
const { MessageChannel } = require('worker_threads');
|
|
21
21
|
const { MessagePortReadable } = require('./message-port-stream');
|
|
22
|
-
const {
|
|
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');
|
|
26
26
|
const { buildRetentionPolicy } = require('./queue-retention');
|
|
27
27
|
const { isDocumentStoreEnabled, documentStoreFeatureEnabled } = require('./document-store');
|
|
28
28
|
const redisScanDelete = require('./redis-scan-delete');
|
|
29
|
-
const { extractMultiValues } = require('./redis-operations');
|
|
29
|
+
const { extractMultiValues, createTransaction } = require('./redis-operations');
|
|
30
30
|
const outbox = require('./outbox');
|
|
31
31
|
const tokens = require('./tokens');
|
|
32
32
|
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 } = 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');
|
|
40
40
|
const { decodeStoredMailboxEntry } = require('./email-client/imap/listing-diff');
|
|
41
|
+
const { readImapData } = require('./account/imap-data');
|
|
41
42
|
|
|
42
43
|
// Shared Lock instance to prevent Redis connection leak (one subscriber per Lock instance)
|
|
43
44
|
// Previously, each Account created its own Lock, causing ~30k connections with 30k accounts
|
|
@@ -51,6 +52,83 @@ const defaultLock = new Lock({
|
|
|
51
52
|
const ACCOUNT_UPDATE_LOCK_TTL = 10 * 1000;
|
|
52
53
|
const ACCOUNT_UPDATE_LOCK_WAIT = 5 * 1000;
|
|
53
54
|
|
|
55
|
+
/**
|
|
56
|
+
* What an incoming account payload asks of `imap.disabled`.
|
|
57
|
+
*
|
|
58
|
+
* Must be read before persistUpdate() merges a `partial` payload into the stored object, which
|
|
59
|
+
* would otherwise pull `disabled` in from the old blob and make every partial update look like a
|
|
60
|
+
* decision about the flag.
|
|
61
|
+
*
|
|
62
|
+
* @param {Object} accountData - Account fields about to be written
|
|
63
|
+
* @returns {Boolean|null} What the payload sets the flag to, or null when it says nothing about it
|
|
64
|
+
*/
|
|
65
|
+
function imapDisabledIntent(accountData) {
|
|
66
|
+
if (!accountData.imap || typeof accountData.imap !== 'object' || !('disabled' in accountData.imap)) {
|
|
67
|
+
return null;
|
|
68
|
+
}
|
|
69
|
+
return !!accountData.imap.disabled;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Whether syncing was switched off for an account, by either route.
|
|
74
|
+
*
|
|
75
|
+
* @param {Object} accountData - An unserialized account
|
|
76
|
+
* @returns {Boolean} True when `imap.disabled` is set
|
|
77
|
+
*/
|
|
78
|
+
function isImapDisabled(accountData) {
|
|
79
|
+
return !!(accountData && accountData.imap && accountData.imap.disabled);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* When the auth-failure safety net switched an account off, as opposed to the operator doing it.
|
|
84
|
+
*
|
|
85
|
+
* The single answer to "is this account parked", used by every surface that reports one: the API
|
|
86
|
+
* field, the admin state badge, the page alert, and the reconnect dispatches in create()/update().
|
|
87
|
+
*
|
|
88
|
+
* Both halves of the test matter. The marker can outlive the flag - an operator re-enables the
|
|
89
|
+
* account by hand and the stale marker is only retired on the next recovery pass - so reading it
|
|
90
|
+
* alone would report a healthy, syncing account as switched off. And re-authorizing a healthy
|
|
91
|
+
* account must not trigger the reconnect that un-parking one does.
|
|
92
|
+
*
|
|
93
|
+
* @param {Object} accountData - An unserialized account, carrying `_authFailureDisabledAt`
|
|
94
|
+
* @returns {String|null} ISO timestamp of the disable, or null when the safety net did not park it
|
|
95
|
+
*/
|
|
96
|
+
function authFailureDisabledAt(accountData) {
|
|
97
|
+
if (!accountData || !accountData._authFailureDisabledAt || !isImapDisabled(accountData)) {
|
|
98
|
+
return null;
|
|
99
|
+
}
|
|
100
|
+
return accountData._authFailureDisabledAt;
|
|
101
|
+
}
|
|
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
|
+
|
|
54
132
|
class Account {
|
|
55
133
|
constructor(options) {
|
|
56
134
|
this.redis = options.redis;
|
|
@@ -146,8 +224,10 @@ class Account {
|
|
|
146
224
|
// - IMAP is explicitly disabled, OR
|
|
147
225
|
// - IMAP is not configured (missing or empty)
|
|
148
226
|
if (accountData.imap) {
|
|
149
|
-
// IMAP exists - check if it
|
|
150
|
-
|
|
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);
|
|
151
231
|
}
|
|
152
232
|
|
|
153
233
|
// No IMAP configuration at all
|
|
@@ -267,7 +347,8 @@ class Account {
|
|
|
267
347
|
accountData.type = 'invalid';
|
|
268
348
|
accountData.delegationError = err.message;
|
|
269
349
|
}
|
|
270
|
-
} else if (accountData.imap && !accountData
|
|
350
|
+
} else if (accountData.imap && !isOperatorDisabled(accountData)) {
|
|
351
|
+
// A parked account is still an IMAP account, only switched off
|
|
271
352
|
accountData.type = 'imap';
|
|
272
353
|
} else {
|
|
273
354
|
// Default to 'sending' type for accounts without IMAP
|
|
@@ -302,6 +383,10 @@ class Account {
|
|
|
302
383
|
|
|
303
384
|
syncTime: accountData.sync,
|
|
304
385
|
|
|
386
|
+
// Lets a caller find every account the safety net parked without opening each one.
|
|
387
|
+
// Omitted rather than null when it did not, like the optional fields above.
|
|
388
|
+
authFailureDisabledAt: authFailureDisabledAt(accountData) || undefined,
|
|
389
|
+
|
|
305
390
|
lastError: formatLastError(accountData),
|
|
306
391
|
|
|
307
392
|
delegationError: accountData.delegationError || undefined
|
|
@@ -349,6 +434,15 @@ class Account {
|
|
|
349
434
|
unserializeAccountData(accountData) {
|
|
350
435
|
const result = {};
|
|
351
436
|
|
|
437
|
+
// The loop below drops every `_`-prefixed field, which is what keeps the auth-failure marker
|
|
438
|
+
// out of API responses - but the state label and the recovery paths both need it, and it is
|
|
439
|
+
// already in every hash read. Carry it across explicitly, under a name that is NOT the
|
|
440
|
+
// stored field's: a loaded account fed back through serializeAccountData then cannot
|
|
441
|
+
// resurrect a marker that has since been retired.
|
|
442
|
+
if (accountData[AUTH_FAILURE_DISABLED_FIELD]) {
|
|
443
|
+
result._authFailureDisabledAt = accountData[AUTH_FAILURE_DISABLED_FIELD];
|
|
444
|
+
}
|
|
445
|
+
|
|
352
446
|
const counters = {};
|
|
353
447
|
|
|
354
448
|
Object.keys(accountData).forEach(key => {
|
|
@@ -820,6 +914,9 @@ class Account {
|
|
|
820
914
|
* @returns {Promise<Object>} `{ account }`
|
|
821
915
|
*/
|
|
822
916
|
async update(accountData, { reauthorized = false } = {}) {
|
|
917
|
+
// Captured before persistUpdate() merges a `partial` payload into the stored object
|
|
918
|
+
const disabledIntent = imapDisabledIntent(accountData);
|
|
919
|
+
|
|
823
920
|
const lock = this.getLock();
|
|
824
921
|
const lockKey = `account:update:${accountData.account}`;
|
|
825
922
|
let updateLock;
|
|
@@ -849,7 +946,7 @@ class Account {
|
|
|
849
946
|
}
|
|
850
947
|
}
|
|
851
948
|
|
|
852
|
-
await this.dispatchPostUpdateCommands(accountData, oldAccountData, reauthorized);
|
|
949
|
+
await this.dispatchPostUpdateCommands(accountData, oldAccountData, reauthorized, disabledIntent);
|
|
853
950
|
|
|
854
951
|
return {
|
|
855
952
|
account: this.account
|
|
@@ -976,85 +1073,62 @@ class Account {
|
|
|
976
1073
|
* @param {Object} accountData - The fields that were just written
|
|
977
1074
|
* @param {Object} oldAccountData - The account as it was before the write
|
|
978
1075
|
* @param {boolean} reauthorized - Whether the caller supplied fresh operator credentials
|
|
1076
|
+
* @param {Boolean|null} disabledIntent - What the payload asked of `imap.disabled`, read before
|
|
1077
|
+
* persistUpdate() merged it
|
|
979
1078
|
* @returns {Promise<void>} Resolves once the dispatch has been attempted
|
|
980
1079
|
*/
|
|
981
|
-
async dispatchPostUpdateCommands(accountData, oldAccountData, reauthorized) {
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
if ('path' in accountData && !reconnectRequested) {
|
|
994
|
-
try {
|
|
995
|
-
strictEqual(JSON.stringify(oldAccountData.path || '*'), JSON.stringify(accountData.path || '*'));
|
|
996
|
-
} catch (err) {
|
|
997
|
-
// changes detected!
|
|
998
|
-
reconnectRequested = true;
|
|
999
|
-
}
|
|
1000
|
-
}
|
|
1001
|
-
|
|
1002
|
-
if ('subconnections' in accountData && !reconnectRequested) {
|
|
1003
|
-
try {
|
|
1004
|
-
deepStrictEqual(oldAccountData.subconnections, accountData.subconnections);
|
|
1005
|
-
} catch (err) {
|
|
1006
|
-
// changes detected!
|
|
1007
|
-
reconnectRequested = true;
|
|
1008
|
-
}
|
|
1009
|
-
}
|
|
1010
|
-
|
|
1011
|
-
if (reconnectRequested) {
|
|
1012
|
-
// changes detected!
|
|
1013
|
-
this.logger.info({ msg: 'IMAP configuration changed for account', account: this.account });
|
|
1014
|
-
if (typeof this.call === 'function') {
|
|
1015
|
-
await this.call({
|
|
1016
|
-
cmd: 'update',
|
|
1017
|
-
account: this.account,
|
|
1018
|
-
timeout: this.timeout
|
|
1019
|
-
});
|
|
1020
|
-
} else {
|
|
1021
|
-
// This Account instance has no parent RPC channel (constructed without `call`).
|
|
1022
|
-
// Skip the dispatch instead of throwing - the persisted change stands.
|
|
1023
|
-
this.logger.warn({ msg: 'Skipping update command dispatch, no parent RPC channel', account: this.account });
|
|
1024
|
-
}
|
|
1025
|
-
}
|
|
1026
|
-
|
|
1027
|
-
// When OAuth2 credentials are re-authorized for an account that is currently in a
|
|
1028
|
-
// non-operational error state, trigger a full reconnect so syncing resumes without a
|
|
1029
|
-
// manual "Reconnect".
|
|
1030
|
-
//
|
|
1031
|
-
// Requires explicit `reauthorized` intent from the caller. Account state cannot be used
|
|
1032
|
-
// to infer it: unattended token renewal persists through update() as well, and it runs
|
|
1033
|
-
// while the stored state is still the error state, so a state-only gate re-fired on every
|
|
1034
|
-
// renewal and dispatched cmd:'reconnect'. That rebuilt the client, discarding its backoff,
|
|
1035
|
-
// and invalidateAccessToken() forced the next cycle to renew again - latching a reconnect
|
|
1080
|
+
async dispatchPostUpdateCommands(accountData, oldAccountData, reauthorized, disabledIntent) {
|
|
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));
|
|
1085
|
+
|
|
1086
|
+
// Whether this update carries OAuth2 credentials the operator just re-authorized. The
|
|
1087
|
+
// `reauthorized` intent has to be explicit: account state cannot be used to infer it,
|
|
1088
|
+
// because unattended token renewal persists through update() as well, and it runs while
|
|
1089
|
+
// the stored state is still the error state. A state-only gate re-fired on every renewal
|
|
1090
|
+
// and dispatched cmd:'reconnect'. That rebuilt the client, discarding its backoff, and
|
|
1091
|
+
// invalidateAccessToken() forced the next cycle to renew again - latching a reconnect
|
|
1036
1092
|
// loop that pinned the CPU at ~100%.
|
|
1037
|
-
|
|
1093
|
+
const oauth2Reauthorized =
|
|
1038
1094
|
reauthorized &&
|
|
1039
|
-
|
|
1040
|
-
accountData.oauth2?.accessToken
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
)
|
|
1095
|
+
!!accountData.oauth2?.accessToken &&
|
|
1096
|
+
(accountData.oauth2.accessToken !== oldAccountData.oauth2?.accessToken || accountData.oauth2.refreshToken !== oldAccountData.oauth2?.refreshToken);
|
|
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
|
+
|
|
1105
|
+
// A reconnect cannot resume an account the auth-failure safety net has switched off, so
|
|
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.
|
|
1111
|
+
//
|
|
1112
|
+
// The lift is deliberately NOT gated on the account state, unlike the reconnect below: a
|
|
1113
|
+
// parked account does not sit in an error state, it reports `unset` (persisted on every
|
|
1114
|
+
// init for Gmail API and Outlook accounts), so by the time the operator re-authorizes, the
|
|
1115
|
+
// error state the old gate required is long gone.
|
|
1116
|
+
await this.resolveAuthFailureDisable(disabledIntent, oldAccountData, oauth2Reauthorized || imapReauthorized);
|
|
1117
|
+
|
|
1118
|
+
// Re-authorization for an account that is currently non-operational triggers a full
|
|
1119
|
+
// reconnect so syncing resumes without a manual "Reconnect". Being switched off is such a
|
|
1120
|
+
// state, and one the account cannot leave on its own. Read off the account as it stood
|
|
1121
|
+
// before the write, for the same reason as in create().
|
|
1122
|
+
const wasParked = !!authFailureDisabledAt(oldAccountData);
|
|
1123
|
+
|
|
1124
|
+
if (oauth2Reauthorized && (ERROR_STATES.includes(oldAccountData.state) || wasParked)) {
|
|
1045
1125
|
this.logger.info({
|
|
1046
|
-
msg: 'OAuth2 credentials re-authorized for account
|
|
1126
|
+
msg: 'OAuth2 credentials re-authorized for non-operational account, requesting reconnect',
|
|
1047
1127
|
account: this.account,
|
|
1048
|
-
state: oldAccountData.state
|
|
1128
|
+
state: oldAccountData.state,
|
|
1129
|
+
wasParked
|
|
1049
1130
|
});
|
|
1050
1131
|
|
|
1051
|
-
// A reconnect cannot resume an account that the auth-failure safety net has switched
|
|
1052
|
-
// off, so lift that first. For a password account the operator clears the flag by
|
|
1053
|
-
// saving new IMAP settings, but an OAuth2 account has no IMAP settings to save - the
|
|
1054
|
-
// re-authorization IS the fix, and without this the account would stay off until
|
|
1055
|
-
// somebody hand-edited it through the API.
|
|
1056
|
-
await this.clearAuthFailureDisable();
|
|
1057
|
-
|
|
1058
1132
|
if (typeof this.call === 'function') {
|
|
1059
1133
|
try {
|
|
1060
1134
|
await this.call({
|
|
@@ -1079,6 +1153,21 @@ class Account {
|
|
|
1079
1153
|
state: oldAccountData.state
|
|
1080
1154
|
});
|
|
1081
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
|
+
}
|
|
1082
1171
|
}
|
|
1083
1172
|
}
|
|
1084
1173
|
|
|
@@ -1097,37 +1186,94 @@ class Account {
|
|
|
1097
1186
|
return id;
|
|
1098
1187
|
}
|
|
1099
1188
|
|
|
1189
|
+
/**
|
|
1190
|
+
* Resolves the auth-failure disable against an account write that has just been persisted.
|
|
1191
|
+
*
|
|
1192
|
+
* @param {Boolean|null} disabledIntent - What the write asked of `imap.disabled`, from
|
|
1193
|
+
* imapDisabledIntent(), read before any partial merge
|
|
1194
|
+
* @param {Object} oldAccountData - The account as it stood before the write
|
|
1195
|
+
* @param {Boolean} mayLift - Whether this write is an explicit re-authorization, the only kind
|
|
1196
|
+
* that may resume a parked account on its own
|
|
1197
|
+
* @returns {Promise<Boolean>} True when this call re-enabled the account
|
|
1198
|
+
*/
|
|
1199
|
+
async resolveAuthFailureDisable(disabledIntent, oldAccountData, mayLift) {
|
|
1200
|
+
if (disabledIntent === true) {
|
|
1201
|
+
// The write asks for IMAP to stay off, so there is nothing to lift. It takes ownership
|
|
1202
|
+
// of the flag only when it is what turned it on: the admin edit form submits its
|
|
1203
|
+
// "Disable IMAP" checkbox on every save, pre-checked from the stored flag, so treating
|
|
1204
|
+
// that restatement as a decision would let an unrelated save silently convert an
|
|
1205
|
+
// automatic park into a deliberate one - taking the page alert, the state badge and
|
|
1206
|
+
// "Resume syncing" with it, and leaving the account unrecoverable by re-authorization.
|
|
1207
|
+
if (!isImapDisabled(oldAccountData)) {
|
|
1208
|
+
await this.redis.hdel(this.getAccountKey(), AUTH_FAILURE_DISABLED_FIELD);
|
|
1209
|
+
}
|
|
1210
|
+
return false;
|
|
1211
|
+
}
|
|
1212
|
+
|
|
1213
|
+
// An explicit `disabled: false` has already re-enabled the account by itself, and the call
|
|
1214
|
+
// below retires the marker it leaves behind. Anything else may only lift a park when the
|
|
1215
|
+
// operator actually re-authorized.
|
|
1216
|
+
if (disabledIntent === false || mayLift) {
|
|
1217
|
+
return await this.clearAuthFailureDisable();
|
|
1218
|
+
}
|
|
1219
|
+
|
|
1220
|
+
return false;
|
|
1221
|
+
}
|
|
1222
|
+
|
|
1100
1223
|
/**
|
|
1101
1224
|
* Re-enables an account that setErrorState() switched off after a run of authentication
|
|
1102
|
-
* failures. Called
|
|
1225
|
+
* failures. Called whenever fresh credentials arrive for the account, and by the admin UI's
|
|
1226
|
+
* "Resume syncing" action.
|
|
1227
|
+
*
|
|
1228
|
+
* Only ever lifts the safety net's own disable, never the operator's send-only switch - see
|
|
1229
|
+
* AUTH_FAILURE_DISABLED_FIELD for why the two need telling apart.
|
|
1103
1230
|
*
|
|
1104
|
-
* Reads the stored
|
|
1231
|
+
* Reads the stored values rather than trusting the copy loaded before the update, because the
|
|
1105
1232
|
* same update may have rewritten the `imap` field.
|
|
1106
1233
|
*
|
|
1107
1234
|
* @returns {Promise<Boolean>} True when a disable flag was actually lifted
|
|
1108
1235
|
*/
|
|
1109
1236
|
async clearAuthFailureDisable() {
|
|
1110
|
-
|
|
1111
|
-
|
|
1237
|
+
const accountKey = this.getAccountKey();
|
|
1238
|
+
|
|
1239
|
+
const [disabledAt, imapInfo] = await this.redis.hmget(accountKey, AUTH_FAILURE_DISABLED_FIELD, 'imap');
|
|
1240
|
+
if (!disabledAt) {
|
|
1241
|
+
// Either never parked, or an operator has already dealt with it. Not ours to lift.
|
|
1112
1242
|
return false;
|
|
1113
1243
|
}
|
|
1114
1244
|
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
} catch (err) {
|
|
1119
|
-
this.logger.error({ msg: 'Failed parsing IMAP data', account: this.account, err });
|
|
1245
|
+
const { imapData, invalid } = await readImapData(this.redis, accountKey, this.logger, imapInfo);
|
|
1246
|
+
if (invalid) {
|
|
1247
|
+
// Leave an unreadable configuration alone rather than replacing it with a bare flag.
|
|
1120
1248
|
return false;
|
|
1121
1249
|
}
|
|
1122
1250
|
|
|
1123
1251
|
if (!imapData || !imapData.disabled) {
|
|
1252
|
+
// The flag is already gone - an operator re-enabled the account by hand, or a full
|
|
1253
|
+
// `imap` rewrite dropped it. Retire the marker so it cannot authorize lifting a
|
|
1254
|
+
// later, deliberate disable.
|
|
1255
|
+
await this.redis.hdel(accountKey, AUTH_FAILURE_DISABLED_FIELD);
|
|
1124
1256
|
return false;
|
|
1125
1257
|
}
|
|
1126
1258
|
|
|
1127
1259
|
imapData.disabled = false;
|
|
1128
|
-
await this.redis.hset(this.getAccountKey(), 'imap', JSON.stringify(imapData));
|
|
1129
1260
|
|
|
1130
|
-
|
|
1261
|
+
// hSetExists rather than hset, so a concurrent account delete cannot be resurrected as a
|
|
1262
|
+
// hash holding nothing but this flag. Same reason disableAfterAuthFailures() writes it
|
|
1263
|
+
// that way.
|
|
1264
|
+
const clearTxn = createTransaction(this.redis, { logger: this.logger });
|
|
1265
|
+
clearTxn.add('hSetExists', accountKey, 'imap', JSON.stringify(imapData));
|
|
1266
|
+
clearTxn.add('hdel', accountKey, AUTH_FAILURE_DISABLED_FIELD);
|
|
1267
|
+
const { error } = await clearTxn.exec();
|
|
1268
|
+
|
|
1269
|
+
if (error) {
|
|
1270
|
+
// Report what happened rather than a lifted flag the caller would follow with a
|
|
1271
|
+
// reconnect into an account that is still switched off.
|
|
1272
|
+
this.logger.error({ msg: 'Failed to re-enable IMAP for account', account: this.account, err: error });
|
|
1273
|
+
return false;
|
|
1274
|
+
}
|
|
1275
|
+
|
|
1276
|
+
this.logger.info({ msg: 'Re-enabled IMAP for account after re-authorization', account: this.account, disabledAt });
|
|
1131
1277
|
|
|
1132
1278
|
return true;
|
|
1133
1279
|
}
|
|
@@ -1215,8 +1361,17 @@ class Account {
|
|
|
1215
1361
|
// existing user
|
|
1216
1362
|
state = 'existing';
|
|
1217
1363
|
|
|
1364
|
+
// The account as it stood before the hmset above, from the snapshot the same pipeline
|
|
1365
|
+
// took. Read twice below - for the provider rebinding and for the recovery dispatch -
|
|
1366
|
+
// so it is unserialized once, outside the guard that only covers the rebinding.
|
|
1367
|
+
let oldAccountData = {};
|
|
1368
|
+
try {
|
|
1369
|
+
oldAccountData = this.unserializeAccountData(result[0][1]);
|
|
1370
|
+
} catch (err) {
|
|
1371
|
+
this.logger.error({ msg: 'Failed to read the stored account', account: this.account, err });
|
|
1372
|
+
}
|
|
1373
|
+
|
|
1218
1374
|
try {
|
|
1219
|
-
let oldAccountData = this.unserializeAccountData(result[0][1]);
|
|
1220
1375
|
if (oldAccountData?.oauth2?.provider && oldAccountData?.oauth2?.auth?.user && oldAccountData.oauth2.provider !== accountData.oauth2?.provider) {
|
|
1221
1376
|
// remove previous entry if provider was updated
|
|
1222
1377
|
await this.redis.hdel(`${REDIS_PREFIX}oapp:h:${oldAccountData.oauth2.provider}`, oldAccountData.oauth2.auth?.user?.toLowerCase());
|
|
@@ -1225,22 +1380,54 @@ class Account {
|
|
|
1225
1380
|
// ignore
|
|
1226
1381
|
}
|
|
1227
1382
|
|
|
1383
|
+
// Re-registration is the operator supplying fresh credentials, and for an account the
|
|
1384
|
+
// auth-failure safety net has switched off it is the whole fix: the hosted
|
|
1385
|
+
// authentication form and POST /v1/account both land here, and neither has any other
|
|
1386
|
+
// way to reach the flag. Without this an OAuth2 account stayed parked no matter how
|
|
1387
|
+
// many times it was re-authorized, because create() writes no `imap` field of its own
|
|
1388
|
+
// and the synthesized `{"disabled":true}` blob survived untouched.
|
|
1389
|
+
//
|
|
1390
|
+
// The reconnect is decided by what was stored BEFORE this write, not by whether the
|
|
1391
|
+
// flag ended up lifted: a payload asking for IMAP to stay off lifts nothing, and either
|
|
1392
|
+
// way the account was not connecting and this write is what changed that.
|
|
1393
|
+
const wasParked = !!authFailureDisabledAt(oldAccountData);
|
|
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
|
+
}
|
|
1411
|
+
|
|
1228
1412
|
const oldState = result[0][1].state;
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
|
|
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) {
|
|
1416
|
+
// Re-registration of an account that is not operational (the interactive OAuth
|
|
1417
|
+
// re-auth redirect and the IMAP re-credentials form both land here).
|
|
1232
1418
|
// cmd:'update' only calls reconnect() on the existing client instance, which cannot
|
|
1233
1419
|
// switch client type (IMAP to API or back) and is a no-op against a torn-down
|
|
1234
1420
|
// connection, so syncing would not resume without a manual "Reconnect". cmd:'reconnect'
|
|
1235
1421
|
// closes and re-assigns a fresh client of the correct provider type. assignConnection
|
|
1236
1422
|
// sets the state to "connecting" before any network work, so this cannot loop.
|
|
1237
|
-
//
|
|
1238
|
-
//
|
|
1239
|
-
//
|
|
1423
|
+
// Needs no credential-change check (unlike update()): create() runs only on explicit
|
|
1424
|
+
// re-registration, never on routine token renewal, so there is no healthy-account
|
|
1425
|
+
// churn to suppress here.
|
|
1240
1426
|
this.logger.info({
|
|
1241
|
-
msg: 'Account re-created while
|
|
1427
|
+
msg: 'Account re-created while not operational, requesting full reconnect',
|
|
1242
1428
|
account: this.account,
|
|
1243
|
-
state: oldState
|
|
1429
|
+
state: oldState,
|
|
1430
|
+
wasParked
|
|
1244
1431
|
});
|
|
1245
1432
|
try {
|
|
1246
1433
|
await this.call({
|
|
@@ -2629,18 +2816,38 @@ class Account {
|
|
|
2629
2816
|
);
|
|
2630
2817
|
}
|
|
2631
2818
|
|
|
2819
|
+
/**
|
|
2820
|
+
* Requests a fresh connection for the account.
|
|
2821
|
+
*
|
|
2822
|
+
* Answers false rather than reporting a reconnect it knows will not happen. A reconnect
|
|
2823
|
+
* rebuilds the client, but init() checks the auth-failure disable before it dials out and
|
|
2824
|
+
* returns without connecting, so for a parked account the dispatch is a no-op - and saying
|
|
2825
|
+
* "reconnecting" to a caller whose account then stays offline is worse than saying no.
|
|
2826
|
+
* Recovering it takes fresh credentials, or the admin UI's "Resume syncing".
|
|
2827
|
+
*
|
|
2828
|
+
* @param {Object} data
|
|
2829
|
+
* @param {Boolean} data.reconnect - Only reconnect when true
|
|
2830
|
+
* @returns {Promise<Boolean>} Whether a reconnect was actually requested
|
|
2831
|
+
*/
|
|
2632
2832
|
async requestReconnect(data) {
|
|
2633
|
-
await this.loadAccountData(this.account, false);
|
|
2833
|
+
const accountData = await this.loadAccountData(this.account, false);
|
|
2634
2834
|
|
|
2635
|
-
if (data.reconnect) {
|
|
2636
|
-
|
|
2637
|
-
cmd: 'reconnect',
|
|
2638
|
-
account: this.account,
|
|
2639
|
-
timeout: this.timeout
|
|
2640
|
-
});
|
|
2641
|
-
return true;
|
|
2835
|
+
if (!data.reconnect) {
|
|
2836
|
+
return false;
|
|
2642
2837
|
}
|
|
2643
|
-
|
|
2838
|
+
|
|
2839
|
+
const disabledAt = authFailureDisabledAt(accountData);
|
|
2840
|
+
if (disabledAt) {
|
|
2841
|
+
this.logger.info({ msg: 'Skipped reconnect request for an account that is switched off', account: this.account, disabledAt });
|
|
2842
|
+
return false;
|
|
2843
|
+
}
|
|
2844
|
+
|
|
2845
|
+
await this.call({
|
|
2846
|
+
cmd: 'reconnect',
|
|
2847
|
+
account: this.account,
|
|
2848
|
+
timeout: this.timeout
|
|
2849
|
+
});
|
|
2850
|
+
return true;
|
|
2644
2851
|
}
|
|
2645
2852
|
|
|
2646
2853
|
async requestSync(data) {
|
|
@@ -3162,4 +3369,4 @@ async function accountSummary(redis, account) {
|
|
|
3162
3369
|
return { account, name: name || '', email: email || '', state: state || 'init' };
|
|
3163
3370
|
}
|
|
3164
3371
|
|
|
3165
|
-
module.exports = { Account, accountExists, accountsExist, accountSummary };
|
|
3372
|
+
module.exports = { Account, accountExists, accountsExist, accountSummary, authFailureDisabledAt, isAuthFailureDisabled, isOperatorDisabled };
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
const crypto = require('crypto');
|
|
4
4
|
const { redis } = require('../db');
|
|
5
|
-
const { Account } = require('../account');
|
|
5
|
+
const { Account, authFailureDisabledAt } = require('../account');
|
|
6
6
|
const getSecret = require('../get-secret');
|
|
7
7
|
const { oauth2Apps, SERVICE_ACCOUNT_PROVIDERS } = require('../oauth2-apps');
|
|
8
8
|
const settings = require('../settings');
|
|
@@ -888,6 +888,7 @@ async function init(args) {
|
|
|
888
888
|
counters: accountCountersSchema,
|
|
889
889
|
|
|
890
890
|
syncTime: Joi.date().iso().example('2021-02-17T13:43:18.860Z').description('Last sync time (IMAP accounts only)'),
|
|
891
|
+
authFailureDisabledAt: accountSchemas.authFailureDisabledAt,
|
|
891
892
|
lastError: lastErrorSchema.allow(null),
|
|
892
893
|
delegationError: Joi.string()
|
|
893
894
|
.example('Delegated account was not found')
|
|
@@ -1033,6 +1034,9 @@ async function init(args) {
|
|
|
1033
1034
|
result.lastError = accountData.state === 'connected' ? null : accountData.lastErrorState;
|
|
1034
1035
|
}
|
|
1035
1036
|
|
|
1037
|
+
// Stated rather than inferred; see the field's description in lib/schemas.js
|
|
1038
|
+
result.authFailureDisabledAt = authFailureDisabledAt(accountData);
|
|
1039
|
+
|
|
1036
1040
|
if (accountData.counters) {
|
|
1037
1041
|
result.counters = accountData.counters;
|
|
1038
1042
|
}
|
|
@@ -1110,6 +1114,8 @@ async function init(args) {
|
|
|
1110
1114
|
|
|
1111
1115
|
imapIndexer: accountSchemas.imapIndexer,
|
|
1112
1116
|
|
|
1117
|
+
authFailureDisabledAt: accountSchemas.authFailureDisabledAt,
|
|
1118
|
+
|
|
1113
1119
|
subconnections: accountSchemas.subconnections,
|
|
1114
1120
|
|
|
1115
1121
|
webhooks: Joi.string()
|
package/lib/consts.js
CHANGED
|
@@ -133,6 +133,29 @@ module.exports = {
|
|
|
133
133
|
// IF IMAP authentications fail more than provided value, then disable IMAP for the account
|
|
134
134
|
DEFAULT_MAX_IMAP_AUTH_FAILURE_TIME: 3 * 24 * 3600 * 1000, // 3 days
|
|
135
135
|
|
|
136
|
+
// Account hash field recording that the auth-failure safety net, rather than the operator, is
|
|
137
|
+
// what set `imap.disabled`. The two are the same flag - every connection gate already reads it -
|
|
138
|
+
// so without this marker nothing could tell an account parked after repeated authentication
|
|
139
|
+
// failures from one an operator deliberately made send-only, and the recovery paths would
|
|
140
|
+
// silently start syncing a mailbox somebody had switched off on purpose.
|
|
141
|
+
//
|
|
142
|
+
// Its value is the ISO timestamp of the disable. The leading underscore is the convention for a
|
|
143
|
+
// field unserializeAccountData() does not surface under its own name, so it can never ride an
|
|
144
|
+
// account object out into an API response or the OpenAPI document; what a loaded account does
|
|
145
|
+
// carry is the separate, read-only `_authFailureDisabledAt`.
|
|
146
|
+
AUTH_FAILURE_DISABLED_FIELD: '_authFailureDisabled',
|
|
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
|
+
|
|
136
159
|
REDIS_PREFIX: ((process.env.EENGINE_REDIS_PREFIX || '').toString().trim() + ':').replace(/^:/, ''),
|
|
137
160
|
|
|
138
161
|
REDIS_BATCH_DELETE_SIZE: 1000,
|