emailengine-app 2.85.0 → 2.87.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.ncurc.js +24 -6
- package/.release-please-manifest.json +1 -1
- package/CHANGELOG.md +97 -0
- package/DOCKER_DEPLOYMENT.md +2 -1
- package/Dockerfile +16 -3
- package/ENVIRONMENT.md +139 -0
- package/README.md +5 -1
- package/config/default.toml +2 -0
- package/copy-static-files.sh +4 -2
- package/data/google-crawlers.json +1 -1
- package/data/public_suffix_list.dat +4 -3
- package/lib/account-assignment.js +19 -0
- package/lib/account.js +285 -195
- package/lib/api-error-codes.js +49 -0
- package/lib/api-reference/model.js +6 -1
- package/lib/api-routes/account-routes.js +91 -32
- package/lib/api-routes/blocklist-routes.js +68 -2
- package/lib/api-routes/delivery-test-routes.js +1 -1
- package/lib/api-routes/gateway-routes.js +82 -10
- package/lib/api-routes/index.js +4 -0
- package/lib/api-routes/license-routes.js +2 -2
- package/lib/api-routes/mailbox-routes.js +3 -3
- package/lib/api-routes/message-routes.js +15 -7
- package/lib/api-routes/oauth2-app-routes.js +15 -8
- package/lib/api-routes/outbox-routes.js +77 -66
- package/lib/api-routes/permission-map.js +55 -6
- package/lib/api-routes/scoped-routes.js +74 -0
- package/lib/api-routes/settings-routes.js +11 -4
- package/lib/api-routes/stats-routes.js +5 -1
- package/lib/api-routes/submit-routes.js +25 -5
- package/lib/api-routes/template-routes.js +7 -6
- package/lib/api-routes/token-routes.js +11 -5
- package/lib/api-routes/webhook-delivery-routes.js +262 -0
- package/lib/api-routes/webhook-route-routes.js +119 -4
- package/lib/calendar-event.js +81 -1
- package/lib/consts.js +38 -46
- package/lib/db.js +14 -6
- package/lib/delivery-error.js +6 -0
- package/lib/deprecations.js +270 -0
- package/lib/email-client/base-client.js +134 -158
- package/lib/email-client/fallback-poll.js +62 -0
- package/lib/email-client/gmail-client.js +59 -11
- package/lib/email-client/imap/adaptive-idle-store.js +73 -0
- package/lib/email-client/imap/adaptive-idle.js +278 -0
- package/lib/email-client/imap/connection-errors.js +14 -1
- package/lib/email-client/imap/idle-settings.js +31 -5
- package/lib/email-client/imap/listing-diff.js +37 -0
- package/lib/email-client/imap/mailbox.js +380 -227
- package/lib/email-client/imap/subconnection.js +7 -29
- package/lib/email-client/imap/sync-operations.js +220 -127
- package/lib/email-client/imap-client.js +227 -163
- package/lib/email-client/message-builder.js +14 -79
- package/lib/email-client/outlook-client.js +378 -338
- package/lib/email-client/smtp-pool-manager.js +16 -13
- package/lib/email-client/sync-state-fields.js +19 -0
- package/lib/encrypt.js +157 -41
- package/lib/enum-descriptions.js +3 -1
- package/lib/env-setting-overrides.js +288 -0
- package/lib/export-worker.js +751 -0
- package/lib/export.js +64 -15
- package/lib/field-usage.js +1 -1
- package/lib/gateway.js +17 -1
- package/lib/get-raw-email.js +35 -108
- package/lib/health.js +75 -0
- package/lib/lock-run.js +119 -0
- package/lib/logger-consts.js +48 -0
- package/lib/logger.js +1 -1
- package/lib/lua/z-head-scores.lua +28 -0
- package/lib/network-errors.js +1 -1
- package/lib/node-version.js +24 -0
- package/lib/notify-attachments.js +20 -1
- package/lib/oauth/gmail.js +54 -29
- package/lib/oauth2-apps.js +630 -655
- package/lib/otp.js +66 -0
- package/lib/outbox.js +184 -54
- package/lib/parse-message.js +3 -3
- package/lib/privileged-settings.js +2 -2
- package/lib/queue-browser/definitions.js +11 -0
- package/lib/queue-browser/index.js +68 -19
- package/lib/queue-job-actions.js +18 -1
- package/lib/queue-retention.js +48 -12
- package/lib/queue-stats.js +11 -2
- package/lib/read-env-value.js +3 -0
- package/lib/redis-memory-warnings.js +99 -0
- package/lib/redis-reconnect.js +29 -0
- package/lib/request-timing.js +23 -0
- package/lib/respawn-backoff.js +35 -0
- package/lib/rewrite-text-nodes.js +19 -59
- package/lib/schemas.js +225 -41
- package/lib/settings.js +6 -2
- package/lib/smtp-auth.js +19 -1
- package/lib/swagger-options.js +2 -2
- package/lib/thread-diagnostics.js +18 -1
- package/lib/tls/provision.js +6 -3
- package/lib/token-audit-log.js +19 -20
- package/lib/token-permission-view.js +4 -3
- package/lib/tools.js +8 -41
- package/lib/ui-routes/admin-config-routes.js +64 -90
- package/lib/ui-routes/admin-entities-routes.js +2 -14
- package/lib/ui-routes/imap-idle-field.js +1 -1
- package/lib/ui-routes/outlook-subscription-view.js +1 -1
- package/lib/ui-routes/overridable-fields.js +84 -0
- package/lib/ui-routes/queue-routes.js +8 -5
- package/lib/ui-routes/settings-page.js +6 -0
- package/lib/utils/decode-headers.js +3 -12
- package/lib/utils/filter-empty.js +20 -0
- package/lib/utils/int-setting.js +48 -0
- package/lib/utils/tracking-settings.js +35 -0
- package/lib/web-safe-html.js +18 -105
- package/lib/webhook-delivery.js +461 -0
- package/lib/webhook-failures.js +132 -0
- package/lib/webhook-request.js +29 -1
- package/lib/webhook-routing.js +30 -1
- package/lib/webhook-test.js +88 -0
- package/lib/webhooks.js +59 -41
- package/lib/worker-rpc-error.js +2 -1
- package/package.json +28 -26
- package/sbom.json +600 -678
- package/server.js +149 -76
- package/static/css/flyonui.css +1 -1
- package/static/js/ace/ace.js +1 -1
- package/static/js/ee-client.js +650 -196
- package/static/licenses.html +49 -59
- package/translations/messages.pot +26 -26
- package/views/config/security.hbs +22 -0
- package/views/config/service.hbs +44 -0
- package/views/config/webhooks.hbs +36 -0
- package/views/layout/app.hbs +9 -6
- package/views/legal.hbs +8 -0
- package/views/partials/queue_retention_note.hbs +12 -8
- package/views/partials/ui/env-managed-alert.hbs +16 -7
- package/workers/api.js +112 -37
- package/workers/export.js +16 -631
- package/workers/imap.js +13 -0
- package/workers/smtp.js +9 -11
- package/workers/webhooks.js +18 -432
- package/lib/email-client/outlook-fallback-poll.js +0 -30
package/lib/account.js
CHANGED
|
@@ -17,7 +17,7 @@ const {
|
|
|
17
17
|
const { MessageChannel } = require('worker_threads');
|
|
18
18
|
const { MessagePortReadable } = require('./message-port-stream');
|
|
19
19
|
const { isDeepStrictEqual } = require('util');
|
|
20
|
-
const { encrypt, decrypt, decryptField, parseEncryptedData } = require('./encrypt');
|
|
20
|
+
const { encrypt, decrypt, decryptAsync, decryptField, parseEncryptedData } = require('./encrypt');
|
|
21
21
|
const { oauth2Apps, isApiBasedApp } = require('./oauth2-apps');
|
|
22
22
|
const settings = require('./settings');
|
|
23
23
|
const redisScanDelete = require('./redis-scan-delete');
|
|
@@ -26,23 +26,20 @@ const { extractMultiValues, createTransaction } = require('./redis-operations');
|
|
|
26
26
|
const outbox = require('./outbox');
|
|
27
27
|
const tokens = require('./tokens');
|
|
28
28
|
const { randomId } = require('./utils/random-id');
|
|
29
|
-
const Lock = require('ioredfour');
|
|
30
|
-
const { redis } = require('./db');
|
|
31
29
|
const { REDIS_PREFIX, AUTH_FAILURE_DISABLED_FIELD, AUTH_FAILURE_DISABLED_LEGACY_DESCRIPTION } = require('./consts');
|
|
32
30
|
const { webSafeTextResponse, applyWebSafeHtmlOptions } = require('./web-safe-html');
|
|
33
31
|
const { checkAccountScopes: checkScopes } = require('./oauth/scope-checker');
|
|
34
32
|
const { ACCOUNT_STATES, ERROR_STATES, calculateEffectiveState, validateAccountState, getDisplayState, formatLastError } = require('./account/account-state');
|
|
35
33
|
const { decodeStoredMailboxEntry } = require('./email-client/imap/listing-diff');
|
|
34
|
+
const { SYNC_STATE_FIELDS } = require('./email-client/sync-state-fields');
|
|
35
|
+
const { runLocked, refuseUnavailableLock, getSharedLock } = require('./lock-run');
|
|
36
36
|
const { readImapData } = require('./account/imap-data');
|
|
37
37
|
const { isTransientCredentialError, credentialErrorStatus } = require('./email-client/credential-errors');
|
|
38
38
|
const { getAccountHttpRoute } = require('./utils/network');
|
|
39
39
|
|
|
40
|
-
//
|
|
41
|
-
//
|
|
42
|
-
|
|
43
|
-
redis,
|
|
44
|
-
namespace: 'ee'
|
|
45
|
-
});
|
|
40
|
+
// Every Account takes its locks from the one shared instance (lib/lock-run.js getSharedLock()): each
|
|
41
|
+
// ioredfour Lock opens a subscriber connection, and a Lock per Account once meant ~30k connections
|
|
42
|
+
// with 30k accounts
|
|
46
43
|
|
|
47
44
|
// Serialization window for Account.update(). The critical section is a few Redis round trips, so
|
|
48
45
|
// the TTL only has to cover a stalled writer, and the wait only has to outlast a normal one.
|
|
@@ -57,6 +54,52 @@ const ACCOUNT_UPDATE_LOCK_WAIT = 5 * 1000;
|
|
|
57
54
|
// re-encrypts exactly this list.
|
|
58
55
|
const ENCRYPTED_ACCOUNT_FIELDS = ['webhooks', 'webhooksCustomHeaders', 'proxy'];
|
|
59
56
|
|
|
57
|
+
// Revocation outcomes that leave no grant EmailEngine could revoke, so revoke: 'required' lets the
|
|
58
|
+
// deletion go ahead: not an OAuth2 account, a Workspace service account, or a token the provider
|
|
59
|
+
// already considers revoked or expired
|
|
60
|
+
const NO_GRANT_REASONS = new Set(['NotOAuth2', 'ServiceAccount', 'TokenInvalid']);
|
|
61
|
+
|
|
62
|
+
function grantRemains(revocation) {
|
|
63
|
+
return !revocation.revoked && !NO_GRANT_REASONS.has(revocation.reason);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// The error a deletion with revoke: 'required' fails with. 502 when the provider was asked and did
|
|
67
|
+
// not confirm, which a retry can fix; 409 when there was nothing it could be asked with
|
|
68
|
+
function revocationNotConfirmed(revocation) {
|
|
69
|
+
let err = new Error('The OAuth2 grant was not revoked, so the account was not deleted');
|
|
70
|
+
err.code = 'RevocationNotConfirmed';
|
|
71
|
+
err.statusCode = revocation.attempted ? 502 : 409;
|
|
72
|
+
err.info = { revocation };
|
|
73
|
+
return err;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* The encrypted credential fields of an unserialized account, as [holder, key] pairs: a credential
|
|
78
|
+
* is under `auth` when the configuration has one, otherwise on the configuration itself
|
|
79
|
+
* @param {Object} accountData
|
|
80
|
+
* @returns {Array<[Object, string]>}
|
|
81
|
+
*/
|
|
82
|
+
function credentialFields(accountData) {
|
|
83
|
+
const fields = [];
|
|
84
|
+
for (const type of ['imap', 'smtp', 'oauth2']) {
|
|
85
|
+
const config = accountData[type];
|
|
86
|
+
if (!config || !config.auth) {
|
|
87
|
+
continue;
|
|
88
|
+
}
|
|
89
|
+
for (const key of ['pass', 'accessToken', 'refreshToken']) {
|
|
90
|
+
if (key in config.auth) {
|
|
91
|
+
fields.push([config.auth, key]);
|
|
92
|
+
} else if (key in config) {
|
|
93
|
+
fields.push([config, key]);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
return fields;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// Sync positions the Gmail API and Graph clients keep in the account hash, cleared by a flush
|
|
101
|
+
const FLUSHED_SYNC_FIELDS = Object.values(SYNC_STATE_FIELDS).flat();
|
|
102
|
+
|
|
60
103
|
/**
|
|
61
104
|
* What an incoming account payload asks of `imap.disabled`.
|
|
62
105
|
*
|
|
@@ -149,7 +192,7 @@ class Account {
|
|
|
149
192
|
}
|
|
150
193
|
|
|
151
194
|
getLock() {
|
|
152
|
-
return this.lock ||
|
|
195
|
+
return this.lock || getSharedLock();
|
|
153
196
|
}
|
|
154
197
|
|
|
155
198
|
/**
|
|
@@ -452,10 +495,13 @@ class Account {
|
|
|
452
495
|
* the non-secret structure (listings, delegated-row lookups): the credentials and the
|
|
453
496
|
* ENCRYPTED_ACCOUNT_FIELDS stay ciphertext, and an encrypted custom header list is left out
|
|
454
497
|
* rather than failing to parse. decryptAccountField() opens the few such values a caller needs.
|
|
498
|
+
* @param {boolean} [opts.deferCredentials] - Leave only the credentials (passwords, tokens) as
|
|
499
|
+
* stored, for a caller that decrypts them with decryptCredentials()
|
|
455
500
|
* @returns {Object} The unserialized account
|
|
456
501
|
*/
|
|
457
502
|
unserializeAccountData(accountData, opts) {
|
|
458
503
|
const skipDecrypt = !!(opts && opts.skipDecrypt);
|
|
504
|
+
const deferCredentials = !!(opts && opts.deferCredentials);
|
|
459
505
|
const result = {};
|
|
460
506
|
|
|
461
507
|
// The loop below drops every `_`-prefixed field, which is what keeps the auth-failure marker
|
|
@@ -659,26 +705,13 @@ class Account {
|
|
|
659
705
|
});
|
|
660
706
|
|
|
661
707
|
// decrypt secrets
|
|
662
|
-
if (this.secret && !skipDecrypt) {
|
|
663
|
-
for (
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
} catch (err) {
|
|
670
|
-
// ignore??
|
|
671
|
-
this.logUnserializeFailure('Failed to decrypt value', key, result[type].auth[key], result.account, err);
|
|
672
|
-
}
|
|
673
|
-
} else if (key in result[type]) {
|
|
674
|
-
try {
|
|
675
|
-
result[type][key] = decrypt(result[type][key], this.secret);
|
|
676
|
-
} catch (err) {
|
|
677
|
-
// ignore??
|
|
678
|
-
this.logUnserializeFailure('Failed to decrypt value', key, result[type][key], result.account, err);
|
|
679
|
-
}
|
|
680
|
-
}
|
|
681
|
-
}
|
|
708
|
+
if (this.secret && !skipDecrypt && !deferCredentials) {
|
|
709
|
+
for (const [holder, key] of credentialFields(result)) {
|
|
710
|
+
try {
|
|
711
|
+
holder[key] = decrypt(holder[key], this.secret);
|
|
712
|
+
} catch (err) {
|
|
713
|
+
// ignore??
|
|
714
|
+
this.logUnserializeFailure('Failed to decrypt value', key, holder[key], result.account, err);
|
|
682
715
|
}
|
|
683
716
|
}
|
|
684
717
|
}
|
|
@@ -702,6 +735,27 @@ class Account {
|
|
|
702
735
|
return result;
|
|
703
736
|
}
|
|
704
737
|
|
|
738
|
+
/**
|
|
739
|
+
* Decrypts the stored credentials of an unserialized account in place, the asynchronous
|
|
740
|
+
* counterpart of the decrypt step in unserializeAccountData(). A value that does not decrypt is
|
|
741
|
+
* logged and left as it is, as the synchronous path does
|
|
742
|
+
* @param {Object} accountData - From unserializeAccountData() with deferCredentials
|
|
743
|
+
*/
|
|
744
|
+
async decryptCredentials(accountData) {
|
|
745
|
+
if (!this.secret) {
|
|
746
|
+
return;
|
|
747
|
+
}
|
|
748
|
+
await Promise.all(
|
|
749
|
+
credentialFields(accountData).map(async ([holder, key]) => {
|
|
750
|
+
try {
|
|
751
|
+
holder[key] = await decryptAsync(holder[key], this.secret);
|
|
752
|
+
} catch (err) {
|
|
753
|
+
this.logUnserializeFailure('Failed to decrypt value', key, holder[key], accountData.account, err);
|
|
754
|
+
}
|
|
755
|
+
})
|
|
756
|
+
);
|
|
757
|
+
}
|
|
758
|
+
|
|
705
759
|
/**
|
|
706
760
|
* Decrypts one of ENCRYPTED_ACCOUNT_FIELDS. Cleartext (a value stored before the field was
|
|
707
761
|
* encrypted, or written without a secret) passes through unchanged.
|
|
@@ -915,6 +969,20 @@ class Account {
|
|
|
915
969
|
return result;
|
|
916
970
|
}
|
|
917
971
|
|
|
972
|
+
/**
|
|
973
|
+
* Reads one stored field of the account, decoded the way loadAccountData() decodes it, without
|
|
974
|
+
* loading the rest of the record. Not for credential fields, which stay encrypted here
|
|
975
|
+
* @param {string} field
|
|
976
|
+
* @returns {Promise<*>} The value, undefined when the field is not stored or holds nothing
|
|
977
|
+
*/
|
|
978
|
+
async getStoredField(field) {
|
|
979
|
+
const stored = await this.redis.hget(this.getAccountKey(), field);
|
|
980
|
+
if (stored === null) {
|
|
981
|
+
return undefined;
|
|
982
|
+
}
|
|
983
|
+
return this.unserializeAccountData({ [field]: stored }, { skipDecrypt: true })[field];
|
|
984
|
+
}
|
|
985
|
+
|
|
918
986
|
async loadAccountData(account, requireValid, runIndex) {
|
|
919
987
|
if (!this.account || (account && account !== this.account)) {
|
|
920
988
|
let message = 'Invalid account ID';
|
|
@@ -930,7 +998,11 @@ class Account {
|
|
|
930
998
|
throw error;
|
|
931
999
|
}
|
|
932
1000
|
|
|
933
|
-
|
|
1001
|
+
// Decrypted asynchronously, see decryptAsync(): a key that is not cached yet is a 600000
|
|
1002
|
+
// iteration PBKDF2, and the synchronous decrypt blocked the worker's event loop for it once
|
|
1003
|
+
// per account loaded at startup
|
|
1004
|
+
let accountData = this.unserializeAccountData(result, { deferCredentials: true });
|
|
1005
|
+
await this.decryptCredentials(accountData);
|
|
934
1006
|
|
|
935
1007
|
if (accountData.oauth2 && accountData.oauth2.provider) {
|
|
936
1008
|
let app = await oauth2Apps.get(accountData.oauth2.provider);
|
|
@@ -1058,32 +1130,27 @@ class Account {
|
|
|
1058
1130
|
* @returns {Promise<*>} Whatever `fn` resolves to
|
|
1059
1131
|
*/
|
|
1060
1132
|
async withUpdateLock(account, fn) {
|
|
1061
|
-
const lock = this.getLock();
|
|
1062
1133
|
const lockKey = `account:update:${account}`;
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
} catch (err) {
|
|
1069
|
-
lockErr = err;
|
|
1070
|
-
}
|
|
1134
|
+
return await runLocked(this.getLock(), lockKey, { ttl: ACCOUNT_UPDATE_LOCK_TTL, wait: ACCOUNT_UPDATE_LOCK_WAIT }, fn, async err => {
|
|
1135
|
+
this.logger.warn({ msg: 'Failed to get account update lock, proceeding unserialized', account, lockKey, err });
|
|
1136
|
+
return await fn();
|
|
1137
|
+
});
|
|
1138
|
+
}
|
|
1071
1139
|
|
|
1072
|
-
|
|
1073
|
-
|
|
1140
|
+
/**
|
|
1141
|
+
* Asks the worker holding the account to remove what the provider keeps for it, and waits.
|
|
1142
|
+
* Best effort: a deletion must not fail because a provider or the worker did not answer
|
|
1143
|
+
* @returns {Promise<boolean>} True when something was removed
|
|
1144
|
+
*/
|
|
1145
|
+
async releaseRemoteResources() {
|
|
1146
|
+
if (typeof this.call !== 'function') {
|
|
1147
|
+
return false;
|
|
1074
1148
|
}
|
|
1075
|
-
|
|
1076
1149
|
try {
|
|
1077
|
-
return await
|
|
1078
|
-
}
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
await lock.releaseLock(updateLock);
|
|
1082
|
-
} catch (err) {
|
|
1083
|
-
// The lock expires on its own, so a failed release must not mask the result
|
|
1084
|
-
this.logger.warn({ msg: 'Failed to release account update lock', account, lockKey, err });
|
|
1085
|
-
}
|
|
1086
|
-
}
|
|
1150
|
+
return !!(await this.call({ cmd: 'teardown', account: this.account, timeout: this.timeout }));
|
|
1151
|
+
} catch (err) {
|
|
1152
|
+
this.logger.warn({ msg: 'Failed to release provider resources before account delete', account: this.account, err });
|
|
1153
|
+
return false;
|
|
1087
1154
|
}
|
|
1088
1155
|
}
|
|
1089
1156
|
|
|
@@ -1655,35 +1722,35 @@ class Account {
|
|
|
1655
1722
|
|
|
1656
1723
|
let accountData = await this.loadAccountData(this.account);
|
|
1657
1724
|
|
|
1658
|
-
|
|
1659
|
-
|
|
1660
|
-
|
|
1661
|
-
|
|
1662
|
-
|
|
1663
|
-
|
|
1664
|
-
|
|
1665
|
-
try {
|
|
1666
|
-
let oauth2App = await oauth2Apps.get(accountData.oauth2.provider);
|
|
1667
|
-
if (oauth2App && oauth2App.provider !== 'gmailService') {
|
|
1668
|
-
let oauthClient = await oauth2Apps.getClient(accountData.oauth2.provider, {
|
|
1669
|
-
logger: this.logger,
|
|
1670
|
-
route: await this.getHttpRoute(accountData)
|
|
1671
|
-
});
|
|
1672
|
-
if (oauthClient && typeof oauthClient.revokeToken === 'function') {
|
|
1673
|
-
await oauthClient.revokeToken(token);
|
|
1674
|
-
}
|
|
1675
|
-
}
|
|
1676
|
-
} catch (err) {
|
|
1677
|
-
this.logger.warn({ msg: 'Failed to revoke OAuth2 grant before account delete', account: this.account, err });
|
|
1678
|
-
}
|
|
1679
|
-
}
|
|
1725
|
+
// revoke: 'required' keeps the account unless the grant is gone. A grant that cannot even be
|
|
1726
|
+
// attempted is refused before anything is torn down
|
|
1727
|
+
let required = opts.revoke === 'required';
|
|
1728
|
+
let grant = opts.revoke ? await this.findRevocableGrant(accountData) : null;
|
|
1729
|
+
let revocation = grant?.reason ? { attempted: false, revoked: false, reason: grant.reason } : undefined;
|
|
1730
|
+
if (required && revocation && grantRemains(revocation)) {
|
|
1731
|
+
throw revocationNotConfirmed(revocation);
|
|
1680
1732
|
}
|
|
1681
1733
|
|
|
1682
|
-
|
|
1683
|
-
|
|
1734
|
+
// First, while the record and its token still exist: the worker's own teardown after the
|
|
1735
|
+
// unlink below has no token left, so the Graph subscription and the Gmail watch used to
|
|
1736
|
+
// outlive the account. Ahead of the revoke for the same reason
|
|
1737
|
+
await this.releaseRemoteResources();
|
|
1738
|
+
|
|
1739
|
+
if (grant) {
|
|
1740
|
+
if (!revocation) {
|
|
1741
|
+
revocation = Object.assign({ attempted: true }, await grant.client.revokeToken(grant.token));
|
|
1742
|
+
}
|
|
1684
1743
|
|
|
1685
|
-
|
|
1686
|
-
|
|
1744
|
+
this.logger[revocation.revoked ? 'info' : 'warn']({ msg: 'OAuth2 grant revocation before account delete', account: this.account, revocation });
|
|
1745
|
+
|
|
1746
|
+
if (required && grantRemains(revocation)) {
|
|
1747
|
+
// The teardown above stopped the Gmail watch of an account that now stays. A
|
|
1748
|
+
// reconnect sets it up again; not awaited, the refusal does not depend on it and
|
|
1749
|
+
// notifyWorker() logs its own failure
|
|
1750
|
+
this.notifyWorker('reconnect');
|
|
1751
|
+
throw revocationNotConfirmed(revocation);
|
|
1752
|
+
}
|
|
1753
|
+
}
|
|
1687
1754
|
|
|
1688
1755
|
// UNLINK rather than DEL throughout: none of these need the memory reclaimed synchronously,
|
|
1689
1756
|
// and the outbox and the message ID index can hold enough entries that freeing them inline
|
|
@@ -1707,9 +1774,6 @@ class Account {
|
|
|
1707
1774
|
.unlink(`${REDIS_PREFIX}iap:${this.account}`) // external event notification queue
|
|
1708
1775
|
.unlink(this.getDeferredQueueKey()) // mailbox changes waiting for a retry
|
|
1709
1776
|
|
|
1710
|
-
.unlink(tombstoneTdy)
|
|
1711
|
-
.unlink(tombstoneYdy)
|
|
1712
|
-
|
|
1713
1777
|
.unlink(`${REDIS_PREFIX}tpl:${this.account}:i`) // stored templates index
|
|
1714
1778
|
.unlink(`${REDIS_PREFIX}tpl:${this.account}:c`); // stored templates index
|
|
1715
1779
|
|
|
@@ -1757,19 +1821,60 @@ class Account {
|
|
|
1757
1821
|
this.logger.error({ msg: 'Failed to delete the log keys of a deleted account', account: this.account, err });
|
|
1758
1822
|
}
|
|
1759
1823
|
|
|
1760
|
-
|
|
1761
|
-
|
|
1762
|
-
|
|
1763
|
-
deleted: false
|
|
1764
|
-
};
|
|
1824
|
+
let deleted = !!(result && result[1] && result[1][1]);
|
|
1825
|
+
if (deleted) {
|
|
1826
|
+
await this.notifyWorker('delete');
|
|
1765
1827
|
}
|
|
1766
1828
|
|
|
1767
|
-
|
|
1829
|
+
let response = { account: this.account, deleted };
|
|
1830
|
+
if (revocation) {
|
|
1831
|
+
// Only when revoke was requested, so a plain delete answers exactly as it always has
|
|
1832
|
+
response.revocation = revocation;
|
|
1833
|
+
}
|
|
1834
|
+
return response;
|
|
1835
|
+
}
|
|
1768
1836
|
|
|
1769
|
-
|
|
1770
|
-
|
|
1771
|
-
|
|
1772
|
-
|
|
1837
|
+
/**
|
|
1838
|
+
* Finds the grant a deletion with `revoke` should revoke.
|
|
1839
|
+
*
|
|
1840
|
+
* @returns {Promise<{client: Object, token: string}|{reason: string}>} The client and token to
|
|
1841
|
+
* revoke with, or the reason there is nothing EmailEngine can revoke
|
|
1842
|
+
*/
|
|
1843
|
+
async findRevocableGrant(accountData) {
|
|
1844
|
+
if (!accountData.oauth2?.provider) {
|
|
1845
|
+
return { reason: 'NotOAuth2' };
|
|
1846
|
+
}
|
|
1847
|
+
|
|
1848
|
+
// Prefer refresh token over access token: revoking either invalidates the grant per Google's docs,
|
|
1849
|
+
// but the stored access token may be expired (a 400 from the provider would leave the grant intact),
|
|
1850
|
+
// while the refresh token is long-lived.
|
|
1851
|
+
let token = accountData.oauth2.refreshToken || accountData.oauth2.accessToken;
|
|
1852
|
+
if (!token) {
|
|
1853
|
+
return { reason: 'NoToken' };
|
|
1854
|
+
}
|
|
1855
|
+
|
|
1856
|
+
try {
|
|
1857
|
+
let oauth2App = await oauth2Apps.get(accountData.oauth2.provider);
|
|
1858
|
+
if (!oauth2App) {
|
|
1859
|
+
return { reason: 'AppNotFound' };
|
|
1860
|
+
}
|
|
1861
|
+
// Workspace service accounts have no per-user grant to revoke
|
|
1862
|
+
if (oauth2App.provider === 'gmailService') {
|
|
1863
|
+
return { reason: 'ServiceAccount' };
|
|
1864
|
+
}
|
|
1865
|
+
let client = await oauth2Apps.getClient(accountData.oauth2.provider, {
|
|
1866
|
+
logger: this.logger,
|
|
1867
|
+
route: await this.getHttpRoute(accountData)
|
|
1868
|
+
});
|
|
1869
|
+
// Only GmailOauth implements it. Microsoft offers no endpoint that revokes one grant
|
|
1870
|
+
if (typeof client?.revokeToken !== 'function') {
|
|
1871
|
+
return { reason: 'Unsupported' };
|
|
1872
|
+
}
|
|
1873
|
+
return { client, token };
|
|
1874
|
+
} catch (err) {
|
|
1875
|
+
this.logger.warn({ msg: 'Failed to load the OAuth2 application to revoke a grant', account: this.account, err });
|
|
1876
|
+
return { reason: 'AppError' };
|
|
1877
|
+
}
|
|
1773
1878
|
}
|
|
1774
1879
|
|
|
1775
1880
|
// Creates the consumer side of a cross-thread download stream, with a guard listener:
|
|
@@ -2364,92 +2469,87 @@ class Account {
|
|
|
2364
2469
|
// use a global lock to decrease Redis scanning operations
|
|
2365
2470
|
let lockKey = ['flush' /*, this.account*/].join(':');
|
|
2366
2471
|
|
|
2367
|
-
|
|
2368
|
-
|
|
2472
|
+
// One flush at a time across the instance, and no waiting for it
|
|
2473
|
+
return await runLocked(
|
|
2474
|
+
this.getLock(),
|
|
2475
|
+
lockKey,
|
|
2476
|
+
// extended while the flush runs, so a stalled process frees it in minutes rather than half an hour
|
|
2477
|
+
{ ttl: 2 * 60 * 1000, wait: false, extend: true },
|
|
2478
|
+
() => this.flushLocked(data),
|
|
2479
|
+
refuseUnavailableLock(
|
|
2480
|
+
this.logger,
|
|
2481
|
+
'Failed to get flush lock',
|
|
2482
|
+
{ account: this.account, lockKey },
|
|
2483
|
+
{
|
|
2484
|
+
statusCode: 429,
|
|
2485
|
+
code: 'LockFail',
|
|
2486
|
+
message: 'One flush operation at a time allowed, try again later',
|
|
2487
|
+
logMessage: 'Failed to get flush lock, another flush is already running',
|
|
2488
|
+
failureMessage: 'Failed to get flush lock, try again later'
|
|
2489
|
+
}
|
|
2490
|
+
)
|
|
2491
|
+
);
|
|
2492
|
+
}
|
|
2369
2493
|
|
|
2370
|
-
|
|
2371
|
-
|
|
2372
|
-
|
|
2373
|
-
|
|
2374
|
-
|
|
2494
|
+
/**
|
|
2495
|
+
* The part of flush() that runs under the flush lock: pauses the account, clears its sync
|
|
2496
|
+
* state and resumes it a few seconds later
|
|
2497
|
+
* @param {Object} data - The flush request
|
|
2498
|
+
*/
|
|
2499
|
+
async flushLocked(data) {
|
|
2500
|
+
await this.call({
|
|
2501
|
+
cmd: 'pause',
|
|
2502
|
+
account: this.account,
|
|
2503
|
+
timeout: this.timeout
|
|
2504
|
+
});
|
|
2375
2505
|
|
|
2376
|
-
|
|
2377
|
-
|
|
2378
|
-
throw error;
|
|
2379
|
-
}
|
|
2380
|
-
} catch (err) {
|
|
2381
|
-
if (Boom.isBoom(err)) {
|
|
2382
|
-
// contention was already logged above
|
|
2383
|
-
throw err;
|
|
2384
|
-
}
|
|
2385
|
-
this.logger.error({ msg: 'Failed to get flush lock', account: this.account, lockKey, err });
|
|
2386
|
-
let error = Boom.boomify(new Error('Failed to get flush lock, try again later'), { statusCode: 500 });
|
|
2387
|
-
if (err.code) {
|
|
2388
|
-
error.output.payload.code = err.code || 'LockFail';
|
|
2389
|
-
}
|
|
2390
|
-
throw error;
|
|
2391
|
-
}
|
|
2506
|
+
let notifyFrom = data.notifyFrom && data.notifyFrom !== 'now' ? data.notifyFrom : new Date();
|
|
2507
|
+
let imapIndexer = data.imapIndexer;
|
|
2392
2508
|
|
|
2393
2509
|
try {
|
|
2394
|
-
|
|
2395
|
-
|
|
2396
|
-
|
|
2397
|
-
|
|
2398
|
-
|
|
2399
|
-
|
|
2400
|
-
|
|
2401
|
-
|
|
2402
|
-
|
|
2403
|
-
|
|
2404
|
-
|
|
2405
|
-
|
|
2406
|
-
|
|
2407
|
-
|
|
2408
|
-
|
|
2409
|
-
|
|
2410
|
-
|
|
2411
|
-
|
|
2412
|
-
|
|
2413
|
-
|
|
2414
|
-
|
|
2415
|
-
|
|
2416
|
-
|
|
2417
|
-
// Note: mailbox ID hash (iah:) and listRegistry are intentionally NOT deleted
|
|
2418
|
-
// to preserve message ID stability across reconnections. Message IDs depend on
|
|
2419
|
-
// the specific mailbox ID entries, so deleting them would invalidate existing IDs.
|
|
2420
|
-
.del(`${REDIS_PREFIX}iar:b:${this.account}`) // retired bounce store, an older version sharing this Redis may still write it
|
|
2421
|
-
.del(`${REDIS_PREFIX}iar:s:${this.account}`) // seen messages list
|
|
2422
|
-
.del(tombstoneTdy)
|
|
2423
|
-
.del(tombstoneYdy);
|
|
2424
|
-
|
|
2425
|
-
if (imapIndexer) {
|
|
2426
|
-
pipeline = pipeline.hset(this.getAccountKey(), 'imapIndexer', imapIndexer);
|
|
2427
|
-
}
|
|
2510
|
+
let pipeline = this.redis
|
|
2511
|
+
.multi()
|
|
2512
|
+
// start syncing new messages from current time
|
|
2513
|
+
.hset(this.getAccountKey(), 'notifyFrom', notifyFrom.toISOString())
|
|
2514
|
+
// mark connection count to 0 to trigger `accountInitialized` event
|
|
2515
|
+
.hset(this.getAccountKey(), `state:count:${ACCOUNT_STATES.CONNECTED}`, '0')
|
|
2516
|
+
// The Gmail API and Graph clients keep their sync position in the account hash
|
|
2517
|
+
// rather than in the keys removed below. Without these a flushed Gmail account
|
|
2518
|
+
// went on from its old history ID, and a flushed Graph account kept the point
|
|
2519
|
+
// its announced set started from while the set itself was removed, so the next
|
|
2520
|
+
// recovery pass took every message since then for unannounced and announced it
|
|
2521
|
+
// again. Each client sets a fresh value when it starts.
|
|
2522
|
+
.hdel(this.getAccountKey(), ...FLUSHED_SYNC_FIELDS)
|
|
2523
|
+
.del(this.getMailboxListKey()) // mailbox list
|
|
2524
|
+
// Note: mailbox ID hash (iah:) and listRegistry are intentionally NOT deleted
|
|
2525
|
+
// to preserve message ID stability across reconnections. Message IDs depend on
|
|
2526
|
+
// the specific mailbox ID entries, so deleting them would invalidate existing IDs.
|
|
2527
|
+
.del(`${REDIS_PREFIX}iar:b:${this.account}`) // retired bounce store, an older version sharing this Redis may still write it
|
|
2528
|
+
.del(`${REDIS_PREFIX}iar:s:${this.account}`); // seen messages list
|
|
2529
|
+
|
|
2530
|
+
if (imapIndexer) {
|
|
2531
|
+
pipeline = pipeline.hset(this.getAccountKey(), 'imapIndexer', imapIndexer);
|
|
2532
|
+
}
|
|
2428
2533
|
|
|
2429
|
-
|
|
2534
|
+
await pipeline.exec();
|
|
2430
2535
|
|
|
2431
|
-
|
|
2432
|
-
|
|
2536
|
+
// scan and delete keys
|
|
2537
|
+
await this.deleteOwnAccountKeys();
|
|
2433
2538
|
|
|
2434
|
-
|
|
2435
|
-
} finally {
|
|
2436
|
-
let finalize = async () => {
|
|
2437
|
-
// Wait a bit before resuming. Just to be sure all pending processes have been completed.
|
|
2438
|
-
await new Promise(r => setTimeout(r, 5 * 1000));
|
|
2439
|
-
await this.call({
|
|
2440
|
-
cmd: 'resume',
|
|
2441
|
-
account: this.account,
|
|
2442
|
-
timeout: this.timeout
|
|
2443
|
-
});
|
|
2444
|
-
};
|
|
2445
|
-
finalize().catch(err => {
|
|
2446
|
-
this.logger.error({ msg: 'Failed to finish flushing', account: this.account, err });
|
|
2447
|
-
});
|
|
2448
|
-
}
|
|
2539
|
+
return true;
|
|
2449
2540
|
} finally {
|
|
2450
|
-
|
|
2451
|
-
|
|
2452
|
-
|
|
2541
|
+
let finalize = async () => {
|
|
2542
|
+
// Wait a bit before resuming. Just to be sure all pending processes have been completed.
|
|
2543
|
+
await new Promise(r => setTimeout(r, 5 * 1000));
|
|
2544
|
+
await this.call({
|
|
2545
|
+
cmd: 'resume',
|
|
2546
|
+
account: this.account,
|
|
2547
|
+
timeout: this.timeout
|
|
2548
|
+
});
|
|
2549
|
+
};
|
|
2550
|
+
finalize().catch(err => {
|
|
2551
|
+
this.logger.error({ msg: 'Failed to finish flushing', account: this.account, err });
|
|
2552
|
+
});
|
|
2453
2553
|
}
|
|
2454
2554
|
}
|
|
2455
2555
|
|
|
@@ -2461,28 +2561,21 @@ class Account {
|
|
|
2461
2561
|
return accountData;
|
|
2462
2562
|
}
|
|
2463
2563
|
|
|
2464
|
-
|
|
2465
|
-
|
|
2466
|
-
|
|
2467
|
-
|
|
2468
|
-
|
|
2469
|
-
|
|
2470
|
-
|
|
2471
|
-
|
|
2472
|
-
throw new Error('Failed to get renewal lock');
|
|
2473
|
-
}
|
|
2474
|
-
} catch (err) {
|
|
2475
|
-
if (!renewLock) {
|
|
2476
|
-
// unexpected lock-layer error; contention was already logged above
|
|
2477
|
-
this.logger.error({ msg: 'Failed to get renewal lock', account: this.account, lockKey, err });
|
|
2478
|
-
}
|
|
2479
|
-
let error = Boom.boomify(new Error('Failed to get renewal lock'), { statusCode: 500 });
|
|
2480
|
-
if (err.code) {
|
|
2481
|
-
error.output.payload.code = err.code || 'LockFail';
|
|
2482
|
-
}
|
|
2483
|
-
throw error;
|
|
2484
|
-
}
|
|
2564
|
+
return await runLocked(
|
|
2565
|
+
this.getLock(),
|
|
2566
|
+
lockKey,
|
|
2567
|
+
{ ttl: 5 * 60 * 1000, wait: 1 * 60 * 1000 },
|
|
2568
|
+
() => this.renewAccessTokenLocked(oauth2Opts),
|
|
2569
|
+
refuseUnavailableLock(this.logger, 'Failed to get renewal lock', { account: this.account, lockKey })
|
|
2570
|
+
);
|
|
2571
|
+
}
|
|
2485
2572
|
|
|
2573
|
+
/**
|
|
2574
|
+
* The part of renewAccessToken() that runs under the renewal lock: renews unless another
|
|
2575
|
+
* holder renewed meanwhile
|
|
2576
|
+
* @param {Object} oauth2Opts
|
|
2577
|
+
*/
|
|
2578
|
+
async renewAccessTokenLocked(oauth2Opts) {
|
|
2486
2579
|
try {
|
|
2487
2580
|
let accountData = await this.loadAccountData(this.account, false);
|
|
2488
2581
|
|
|
@@ -2590,10 +2683,6 @@ class Account {
|
|
|
2590
2683
|
}
|
|
2591
2684
|
|
|
2592
2685
|
throw err;
|
|
2593
|
-
} finally {
|
|
2594
|
-
if (renewLock?.success) {
|
|
2595
|
-
await lock.releaseLock(renewLock);
|
|
2596
|
-
}
|
|
2597
2686
|
}
|
|
2598
2687
|
}
|
|
2599
2688
|
|
|
@@ -2995,6 +3084,7 @@ function isAccessTokenInvalidated(oauth2) {
|
|
|
2995
3084
|
|
|
2996
3085
|
module.exports = {
|
|
2997
3086
|
ENCRYPTED_ACCOUNT_FIELDS,
|
|
3087
|
+
FLUSHED_SYNC_FIELDS,
|
|
2998
3088
|
Account,
|
|
2999
3089
|
accountExists,
|
|
3000
3090
|
accountsExist,
|