emailengine-app 2.84.2 → 2.86.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 +29 -9
- package/.prettierignore +5 -1
- package/.prettierrc.js +2 -0
- package/.release-please-manifest.json +1 -1
- package/CHANGELOG.md +107 -0
- package/Dockerfile +20 -1
- package/ENVIRONMENT.md +139 -0
- package/README.md +2 -2
- package/bin/emailengine.js +434 -408
- package/config/default.toml +2 -0
- package/copy-static-files.sh +41 -14
- package/data/google-crawlers.json +1 -1
- package/data/public_suffix_list.dat +16563 -0
- package/eslint.config.js +81 -99
- package/lib/account-assignment.js +19 -0
- package/lib/account.js +230 -170
- package/lib/api-error-codes.js +49 -0
- package/lib/api-reference/format.js +4 -3
- package/lib/api-reference/model.js +6 -1
- package/lib/api-routes/account-routes.js +255 -38
- package/lib/api-routes/blocklist-routes.js +91 -4
- package/lib/api-routes/delivery-test-routes.js +27 -4
- package/lib/api-routes/export-routes.js +28 -2
- package/lib/api-routes/gateway-routes.js +110 -12
- package/lib/api-routes/index.js +4 -0
- package/lib/api-routes/license-routes.js +2 -2
- package/lib/api-routes/mailbox-routes.js +44 -5
- package/lib/api-routes/message-routes.js +112 -10
- package/lib/api-routes/oauth2-app-routes.js +63 -23
- package/lib/api-routes/outbox-routes.js +97 -52
- package/lib/api-routes/permission-map.js +67 -7
- package/lib/api-routes/scoped-routes.js +74 -0
- package/lib/api-routes/settings-routes.js +34 -6
- package/lib/api-routes/stats-routes.js +5 -1
- package/lib/api-routes/submit-routes.js +337 -309
- package/lib/api-routes/template-routes.js +45 -8
- package/lib/api-routes/token-routes.js +152 -100
- package/lib/api-routes/webhook-delivery-routes.js +262 -0
- package/lib/api-routes/webhook-route-routes.js +132 -6
- package/lib/bounce-detect.js +397 -205
- package/lib/calendar-event.js +81 -1
- package/lib/consts.js +38 -45
- 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 +137 -184
- package/lib/email-client/fallback-poll.js +62 -0
- package/lib/email-client/gmail-client.js +60 -22
- 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 +372 -242
- package/lib/email-client/imap/subconnection.js +8 -30
- package/lib/email-client/imap/sync-operations.js +220 -127
- package/lib/email-client/imap-client.js +228 -164
- package/lib/email-client/message-builder.js +14 -79
- package/lib/email-client/notification-handler.js +1 -2
- package/lib/email-client/outlook-client.js +372 -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/gateway.js +19 -4
- package/lib/get-raw-email.js +25 -107
- package/lib/hapi-request-logger.js +107 -0
- package/lib/health.js +75 -0
- package/lib/imapproxy/imap-core/README.md +6 -5
- 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/mcp/tools.js +37 -8
- package/lib/network-errors.js +1 -1
- package/lib/node-version.js +24 -0
- package/lib/notify-attachments.js +36 -0
- package/lib/oauth/outlook-mailbox.js +35 -0
- package/lib/oauth/state.js +24 -0
- package/lib/oauth2-apps.js +631 -656
- package/lib/outbox.js +184 -54
- package/lib/parse-message.js +3 -3
- package/lib/pbkdf2-phc.js +1 -1
- 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 +164 -40
- package/lib/settings.js +6 -2
- package/lib/smtp-auth.js +19 -1
- package/lib/sso.js +1 -1
- package/lib/swagger-options.js +1 -1
- package/lib/thread-diagnostics.js +63 -0
- package/lib/timezones.js +109 -0
- package/lib/tls/provision.js +6 -3
- package/lib/token-audit-log.js +19 -20
- package/lib/token-permission-view.js +7 -6
- package/lib/tools.js +48 -51
- package/lib/totp.js +2 -5
- package/lib/translations.js +1 -2
- package/lib/ui-routes/account-routes.js +475 -454
- package/lib/ui-routes/account-setup.js +99 -0
- package/lib/ui-routes/admin-config-routes.js +152 -100
- package/lib/ui-routes/admin-entities-routes.js +93 -21
- package/lib/ui-routes/auth-routes.js +90 -38
- package/lib/ui-routes/imap-idle-field.js +1 -1
- package/lib/ui-routes/internals-routes.js +5 -0
- package/lib/ui-routes/oauth-config-routes.js +124 -82
- 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/route-helpers.js +19 -3
- package/lib/ui-routes/settings-page.js +6 -0
- package/lib/ui-routes/tls-config-routes.js +58 -15
- package/lib/utils/back-off.js +82 -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/murmurhash3.js +66 -0
- package/lib/utils/public-suffix.js +122 -0
- package/lib/utils/random-id.js +26 -0
- package/lib/utils/tracking-settings.js +35 -0
- package/lib/utils/version.js +74 -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 +56 -0
- package/lib/webhook-test.js +88 -0
- package/lib/webhooks.js +93 -45
- package/lib/worker-rpc-error.js +2 -1
- package/package.json +37 -38
- package/sbom.json +7902 -1
- package/server.js +784 -518
- package/static/js/ace/ace.js +1 -1
- package/static/licenses.html +225 -1060
- package/translations/messages.pot +62 -63
- package/views/config/ai.hbs +1 -1
- package/views/config/security.hbs +24 -2
- package/views/config/service.hbs +47 -0
- package/views/config/webhooks.hbs +36 -0
- package/views/internals/index.hbs +8 -0
- package/views/partials/queue_retention_note.hbs +12 -8
- package/views/partials/ui/env-managed-alert.hbs +16 -7
- package/views/partials/webhook_form.hbs +1 -1
- package/views/suppression-lists/index.hbs +1 -1
- package/workers/api.js +840 -611
- package/workers/export.js +17 -632
- package/workers/imap.js +13 -0
- package/workers/smtp.js +9 -11
- package/workers/submit.js +1 -1
- package/workers/webhooks.js +18 -448
- 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');
|
|
@@ -25,25 +25,21 @@ const { ownAccountKeyFilter } = require('./account/own-account-key');
|
|
|
25
25
|
const { extractMultiValues, createTransaction } = require('./redis-operations');
|
|
26
26
|
const outbox = require('./outbox');
|
|
27
27
|
const tokens = require('./tokens');
|
|
28
|
-
const {
|
|
29
|
-
const Lock = require('ioredfour');
|
|
30
|
-
const { redis } = require('./db');
|
|
31
|
-
const nanoid = customAlphabet('0123456789abcdefghijklmnopqrstuvwxyz', 16);
|
|
28
|
+
const { randomId } = require('./utils/random-id');
|
|
32
29
|
const { REDIS_PREFIX, AUTH_FAILURE_DISABLED_FIELD, AUTH_FAILURE_DISABLED_LEGACY_DESCRIPTION } = require('./consts');
|
|
33
30
|
const { webSafeTextResponse, applyWebSafeHtmlOptions } = require('./web-safe-html');
|
|
34
31
|
const { checkAccountScopes: checkScopes } = require('./oauth/scope-checker');
|
|
35
32
|
const { ACCOUNT_STATES, ERROR_STATES, calculateEffectiveState, validateAccountState, getDisplayState, formatLastError } = require('./account/account-state');
|
|
36
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');
|
|
37
36
|
const { readImapData } = require('./account/imap-data');
|
|
38
37
|
const { isTransientCredentialError, credentialErrorStatus } = require('./email-client/credential-errors');
|
|
39
38
|
const { getAccountHttpRoute } = require('./utils/network');
|
|
40
39
|
|
|
41
|
-
//
|
|
42
|
-
//
|
|
43
|
-
|
|
44
|
-
redis,
|
|
45
|
-
namespace: 'ee'
|
|
46
|
-
});
|
|
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
|
|
47
43
|
|
|
48
44
|
// Serialization window for Account.update(). The critical section is a few Redis round trips, so
|
|
49
45
|
// the TTL only has to cover a stalled writer, and the wait only has to outlast a normal one.
|
|
@@ -58,6 +54,33 @@ const ACCOUNT_UPDATE_LOCK_WAIT = 5 * 1000;
|
|
|
58
54
|
// re-encrypts exactly this list.
|
|
59
55
|
const ENCRYPTED_ACCOUNT_FIELDS = ['webhooks', 'webhooksCustomHeaders', 'proxy'];
|
|
60
56
|
|
|
57
|
+
/**
|
|
58
|
+
* The encrypted credential fields of an unserialized account, as [holder, key] pairs: a credential
|
|
59
|
+
* is under `auth` when the configuration has one, otherwise on the configuration itself
|
|
60
|
+
* @param {Object} accountData
|
|
61
|
+
* @returns {Array<[Object, string]>}
|
|
62
|
+
*/
|
|
63
|
+
function credentialFields(accountData) {
|
|
64
|
+
const fields = [];
|
|
65
|
+
for (const type of ['imap', 'smtp', 'oauth2']) {
|
|
66
|
+
const config = accountData[type];
|
|
67
|
+
if (!config || !config.auth) {
|
|
68
|
+
continue;
|
|
69
|
+
}
|
|
70
|
+
for (const key of ['pass', 'accessToken', 'refreshToken']) {
|
|
71
|
+
if (key in config.auth) {
|
|
72
|
+
fields.push([config.auth, key]);
|
|
73
|
+
} else if (key in config) {
|
|
74
|
+
fields.push([config, key]);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
return fields;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// Sync positions the Gmail API and Graph clients keep in the account hash, cleared by a flush
|
|
82
|
+
const FLUSHED_SYNC_FIELDS = Object.values(SYNC_STATE_FIELDS).flat();
|
|
83
|
+
|
|
61
84
|
/**
|
|
62
85
|
* What an incoming account payload asks of `imap.disabled`.
|
|
63
86
|
*
|
|
@@ -150,7 +173,7 @@ class Account {
|
|
|
150
173
|
}
|
|
151
174
|
|
|
152
175
|
getLock() {
|
|
153
|
-
return this.lock ||
|
|
176
|
+
return this.lock || getSharedLock();
|
|
154
177
|
}
|
|
155
178
|
|
|
156
179
|
/**
|
|
@@ -453,10 +476,13 @@ class Account {
|
|
|
453
476
|
* the non-secret structure (listings, delegated-row lookups): the credentials and the
|
|
454
477
|
* ENCRYPTED_ACCOUNT_FIELDS stay ciphertext, and an encrypted custom header list is left out
|
|
455
478
|
* rather than failing to parse. decryptAccountField() opens the few such values a caller needs.
|
|
479
|
+
* @param {boolean} [opts.deferCredentials] - Leave only the credentials (passwords, tokens) as
|
|
480
|
+
* stored, for a caller that decrypts them with decryptCredentials()
|
|
456
481
|
* @returns {Object} The unserialized account
|
|
457
482
|
*/
|
|
458
483
|
unserializeAccountData(accountData, opts) {
|
|
459
484
|
const skipDecrypt = !!(opts && opts.skipDecrypt);
|
|
485
|
+
const deferCredentials = !!(opts && opts.deferCredentials);
|
|
460
486
|
const result = {};
|
|
461
487
|
|
|
462
488
|
// The loop below drops every `_`-prefixed field, which is what keeps the auth-failure marker
|
|
@@ -660,26 +686,13 @@ class Account {
|
|
|
660
686
|
});
|
|
661
687
|
|
|
662
688
|
// decrypt secrets
|
|
663
|
-
if (this.secret && !skipDecrypt) {
|
|
664
|
-
for (
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
} catch (err) {
|
|
671
|
-
// ignore??
|
|
672
|
-
this.logUnserializeFailure('Failed to decrypt value', key, result[type].auth[key], result.account, err);
|
|
673
|
-
}
|
|
674
|
-
} else if (key in result[type]) {
|
|
675
|
-
try {
|
|
676
|
-
result[type][key] = decrypt(result[type][key], this.secret);
|
|
677
|
-
} catch (err) {
|
|
678
|
-
// ignore??
|
|
679
|
-
this.logUnserializeFailure('Failed to decrypt value', key, result[type][key], result.account, err);
|
|
680
|
-
}
|
|
681
|
-
}
|
|
682
|
-
}
|
|
689
|
+
if (this.secret && !skipDecrypt && !deferCredentials) {
|
|
690
|
+
for (const [holder, key] of credentialFields(result)) {
|
|
691
|
+
try {
|
|
692
|
+
holder[key] = decrypt(holder[key], this.secret);
|
|
693
|
+
} catch (err) {
|
|
694
|
+
// ignore??
|
|
695
|
+
this.logUnserializeFailure('Failed to decrypt value', key, holder[key], result.account, err);
|
|
683
696
|
}
|
|
684
697
|
}
|
|
685
698
|
}
|
|
@@ -703,6 +716,27 @@ class Account {
|
|
|
703
716
|
return result;
|
|
704
717
|
}
|
|
705
718
|
|
|
719
|
+
/**
|
|
720
|
+
* Decrypts the stored credentials of an unserialized account in place, the asynchronous
|
|
721
|
+
* counterpart of the decrypt step in unserializeAccountData(). A value that does not decrypt is
|
|
722
|
+
* logged and left as it is, as the synchronous path does
|
|
723
|
+
* @param {Object} accountData - From unserializeAccountData() with deferCredentials
|
|
724
|
+
*/
|
|
725
|
+
async decryptCredentials(accountData) {
|
|
726
|
+
if (!this.secret) {
|
|
727
|
+
return;
|
|
728
|
+
}
|
|
729
|
+
await Promise.all(
|
|
730
|
+
credentialFields(accountData).map(async ([holder, key]) => {
|
|
731
|
+
try {
|
|
732
|
+
holder[key] = await decryptAsync(holder[key], this.secret);
|
|
733
|
+
} catch (err) {
|
|
734
|
+
this.logUnserializeFailure('Failed to decrypt value', key, holder[key], accountData.account, err);
|
|
735
|
+
}
|
|
736
|
+
})
|
|
737
|
+
);
|
|
738
|
+
}
|
|
739
|
+
|
|
706
740
|
/**
|
|
707
741
|
* Decrypts one of ENCRYPTED_ACCOUNT_FIELDS. Cleartext (a value stored before the field was
|
|
708
742
|
* encrypted, or written without a secret) passes through unchanged.
|
|
@@ -916,6 +950,20 @@ class Account {
|
|
|
916
950
|
return result;
|
|
917
951
|
}
|
|
918
952
|
|
|
953
|
+
/**
|
|
954
|
+
* Reads one stored field of the account, decoded the way loadAccountData() decodes it, without
|
|
955
|
+
* loading the rest of the record. Not for credential fields, which stay encrypted here
|
|
956
|
+
* @param {string} field
|
|
957
|
+
* @returns {Promise<*>} The value, undefined when the field is not stored or holds nothing
|
|
958
|
+
*/
|
|
959
|
+
async getStoredField(field) {
|
|
960
|
+
const stored = await this.redis.hget(this.getAccountKey(), field);
|
|
961
|
+
if (stored === null) {
|
|
962
|
+
return undefined;
|
|
963
|
+
}
|
|
964
|
+
return this.unserializeAccountData({ [field]: stored }, { skipDecrypt: true })[field];
|
|
965
|
+
}
|
|
966
|
+
|
|
919
967
|
async loadAccountData(account, requireValid, runIndex) {
|
|
920
968
|
if (!this.account || (account && account !== this.account)) {
|
|
921
969
|
let message = 'Invalid account ID';
|
|
@@ -931,7 +979,11 @@ class Account {
|
|
|
931
979
|
throw error;
|
|
932
980
|
}
|
|
933
981
|
|
|
934
|
-
|
|
982
|
+
// Decrypted asynchronously, see decryptAsync(): a key that is not cached yet is a 600000
|
|
983
|
+
// iteration PBKDF2, and the synchronous decrypt blocked the worker's event loop for it once
|
|
984
|
+
// per account loaded at startup
|
|
985
|
+
let accountData = this.unserializeAccountData(result, { deferCredentials: true });
|
|
986
|
+
await this.decryptCredentials(accountData);
|
|
935
987
|
|
|
936
988
|
if (accountData.oauth2 && accountData.oauth2.provider) {
|
|
937
989
|
let app = await oauth2Apps.get(accountData.oauth2.provider);
|
|
@@ -1059,32 +1111,27 @@ class Account {
|
|
|
1059
1111
|
* @returns {Promise<*>} Whatever `fn` resolves to
|
|
1060
1112
|
*/
|
|
1061
1113
|
async withUpdateLock(account, fn) {
|
|
1062
|
-
const lock = this.getLock();
|
|
1063
1114
|
const lockKey = `account:update:${account}`;
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
} catch (err) {
|
|
1070
|
-
lockErr = err;
|
|
1071
|
-
}
|
|
1115
|
+
return await runLocked(this.getLock(), lockKey, { ttl: ACCOUNT_UPDATE_LOCK_TTL, wait: ACCOUNT_UPDATE_LOCK_WAIT }, fn, async err => {
|
|
1116
|
+
this.logger.warn({ msg: 'Failed to get account update lock, proceeding unserialized', account, lockKey, err });
|
|
1117
|
+
return await fn();
|
|
1118
|
+
});
|
|
1119
|
+
}
|
|
1072
1120
|
|
|
1073
|
-
|
|
1074
|
-
|
|
1121
|
+
/**
|
|
1122
|
+
* Asks the worker holding the account to remove what the provider keeps for it, and waits.
|
|
1123
|
+
* Best effort: a deletion must not fail because a provider or the worker did not answer
|
|
1124
|
+
* @returns {Promise<boolean>} True when something was removed
|
|
1125
|
+
*/
|
|
1126
|
+
async releaseRemoteResources() {
|
|
1127
|
+
if (typeof this.call !== 'function') {
|
|
1128
|
+
return false;
|
|
1075
1129
|
}
|
|
1076
|
-
|
|
1077
1130
|
try {
|
|
1078
|
-
return await
|
|
1079
|
-
}
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
await lock.releaseLock(updateLock);
|
|
1083
|
-
} catch (err) {
|
|
1084
|
-
// The lock expires on its own, so a failed release must not mask the result
|
|
1085
|
-
this.logger.warn({ msg: 'Failed to release account update lock', account, lockKey, err });
|
|
1086
|
-
}
|
|
1087
|
-
}
|
|
1131
|
+
return !!(await this.call({ cmd: 'teardown', account: this.account, timeout: this.timeout }));
|
|
1132
|
+
} catch (err) {
|
|
1133
|
+
this.logger.warn({ msg: 'Failed to release provider resources before account delete', account: this.account, err });
|
|
1134
|
+
return false;
|
|
1088
1135
|
}
|
|
1089
1136
|
}
|
|
1090
1137
|
|
|
@@ -1329,7 +1376,7 @@ class Account {
|
|
|
1329
1376
|
let id;
|
|
1330
1377
|
let retries = 0;
|
|
1331
1378
|
while (retries++ < 20) {
|
|
1332
|
-
id =
|
|
1379
|
+
id = randomId();
|
|
1333
1380
|
let alreadyExists = await this.redis.hexists(`${REDIS_PREFIX}iad:${id}`, 'account');
|
|
1334
1381
|
if (alreadyExists) {
|
|
1335
1382
|
id = false;
|
|
@@ -1387,7 +1434,7 @@ class Account {
|
|
|
1387
1434
|
*
|
|
1388
1435
|
* @returns {Promise<Boolean>} True when a disable flag was actually lifted
|
|
1389
1436
|
*/
|
|
1390
|
-
async clearAuthFailureDisable() {
|
|
1437
|
+
async clearAuthFailureDisable(trigger) {
|
|
1391
1438
|
const accountKey = this.getAccountKey();
|
|
1392
1439
|
|
|
1393
1440
|
const [disabledAt, imapInfo] = await this.redis.hmget(accountKey, AUTH_FAILURE_DISABLED_FIELD, 'imap');
|
|
@@ -1427,7 +1474,39 @@ class Account {
|
|
|
1427
1474
|
return false;
|
|
1428
1475
|
}
|
|
1429
1476
|
|
|
1430
|
-
|
|
1477
|
+
// `trigger` is 'resume' for the "Resume syncing" action, which retries the stored credentials
|
|
1478
|
+
this.logger.info({
|
|
1479
|
+
msg:
|
|
1480
|
+
trigger === 'resume'
|
|
1481
|
+
? 'Resumed an account that was switched off after authentication failures'
|
|
1482
|
+
: 'Re-enabled IMAP for account after re-authorization',
|
|
1483
|
+
account: this.account,
|
|
1484
|
+
disabledAt
|
|
1485
|
+
});
|
|
1486
|
+
|
|
1487
|
+
return true;
|
|
1488
|
+
}
|
|
1489
|
+
|
|
1490
|
+
/**
|
|
1491
|
+
* "Resume syncing": turns an account back on after the auth-failure safety net switched it
|
|
1492
|
+
* off, and asks its worker to connect it again. The one implementation behind the admin UI
|
|
1493
|
+
* action and PUT /v1/account/{account}/resume.
|
|
1494
|
+
*
|
|
1495
|
+
* Lifts nothing but the safety net's own disable (see clearAuthFailureDisable), so it cannot
|
|
1496
|
+
* be used to undo an operator's deliberate send-only switch.
|
|
1497
|
+
*
|
|
1498
|
+
* @returns {Promise<Boolean>} True when the account was switched off and has been resumed,
|
|
1499
|
+
* false when there was no such disable to lift
|
|
1500
|
+
*/
|
|
1501
|
+
async resumeAfterAuthFailure() {
|
|
1502
|
+
if (!(await this.clearAuthFailureDisable('resume'))) {
|
|
1503
|
+
return false;
|
|
1504
|
+
}
|
|
1505
|
+
|
|
1506
|
+
// The flag is already lifted, so the account is no longer parked whatever the dispatch
|
|
1507
|
+
// does. Losing it only delays the connection until the next periodic reconnect, which is
|
|
1508
|
+
// why notifyWorker() logs a failure rather than throwing it.
|
|
1509
|
+
await this.notifyWorker('reconnect');
|
|
1431
1510
|
|
|
1432
1511
|
return true;
|
|
1433
1512
|
}
|
|
@@ -1624,6 +1703,11 @@ class Account {
|
|
|
1624
1703
|
|
|
1625
1704
|
let accountData = await this.loadAccountData(this.account);
|
|
1626
1705
|
|
|
1706
|
+
// First, while the record and its token still exist: the worker's own teardown after the
|
|
1707
|
+
// unlink below has no token left, so the Graph subscription and the Gmail watch used to
|
|
1708
|
+
// outlive the account. Ahead of the revoke for the same reason
|
|
1709
|
+
await this.releaseRemoteResources();
|
|
1710
|
+
|
|
1627
1711
|
if (opts.revoke && accountData.oauth2?.provider) {
|
|
1628
1712
|
// Prefer refresh token over access token: revoking either invalidates the grant per Google's docs,
|
|
1629
1713
|
// but the stored access token may be expired (a 400 from the provider would leave the grant intact),
|
|
@@ -1648,12 +1732,6 @@ class Account {
|
|
|
1648
1732
|
}
|
|
1649
1733
|
}
|
|
1650
1734
|
|
|
1651
|
-
const dateKeyTdy = new Date().toISOString().substring(0, 10).replace(/-/g, '');
|
|
1652
|
-
const dateKeyYdy = new Date(Date.now() - 24 * 3600 * 1000).toISOString().substring(0, 10).replace(/-/g, '');
|
|
1653
|
-
|
|
1654
|
-
const tombstoneTdy = `${REDIS_PREFIX}tomb:${this.account}:${dateKeyTdy}`;
|
|
1655
|
-
const tombstoneYdy = `${REDIS_PREFIX}tomb:${this.account}:${dateKeyYdy}`;
|
|
1656
|
-
|
|
1657
1735
|
// UNLINK rather than DEL throughout: none of these need the memory reclaimed synchronously,
|
|
1658
1736
|
// and the outbox and the message ID index can hold enough entries that freeing them inline
|
|
1659
1737
|
// would block Redis for every other worker.
|
|
@@ -1676,9 +1754,6 @@ class Account {
|
|
|
1676
1754
|
.unlink(`${REDIS_PREFIX}iap:${this.account}`) // external event notification queue
|
|
1677
1755
|
.unlink(this.getDeferredQueueKey()) // mailbox changes waiting for a retry
|
|
1678
1756
|
|
|
1679
|
-
.unlink(tombstoneTdy)
|
|
1680
|
-
.unlink(tombstoneYdy)
|
|
1681
|
-
|
|
1682
1757
|
.unlink(`${REDIS_PREFIX}tpl:${this.account}:i`) // stored templates index
|
|
1683
1758
|
.unlink(`${REDIS_PREFIX}tpl:${this.account}:c`); // stored templates index
|
|
1684
1759
|
|
|
@@ -2333,92 +2408,87 @@ class Account {
|
|
|
2333
2408
|
// use a global lock to decrease Redis scanning operations
|
|
2334
2409
|
let lockKey = ['flush' /*, this.account*/].join(':');
|
|
2335
2410
|
|
|
2336
|
-
|
|
2337
|
-
|
|
2411
|
+
// One flush at a time across the instance, and no waiting for it
|
|
2412
|
+
return await runLocked(
|
|
2413
|
+
this.getLock(),
|
|
2414
|
+
lockKey,
|
|
2415
|
+
// extended while the flush runs, so a stalled process frees it in minutes rather than half an hour
|
|
2416
|
+
{ ttl: 2 * 60 * 1000, wait: false, extend: true },
|
|
2417
|
+
() => this.flushLocked(data),
|
|
2418
|
+
refuseUnavailableLock(
|
|
2419
|
+
this.logger,
|
|
2420
|
+
'Failed to get flush lock',
|
|
2421
|
+
{ account: this.account, lockKey },
|
|
2422
|
+
{
|
|
2423
|
+
statusCode: 429,
|
|
2424
|
+
code: 'LockFail',
|
|
2425
|
+
message: 'One flush operation at a time allowed, try again later',
|
|
2426
|
+
logMessage: 'Failed to get flush lock, another flush is already running',
|
|
2427
|
+
failureMessage: 'Failed to get flush lock, try again later'
|
|
2428
|
+
}
|
|
2429
|
+
)
|
|
2430
|
+
);
|
|
2431
|
+
}
|
|
2338
2432
|
|
|
2339
|
-
|
|
2340
|
-
|
|
2341
|
-
|
|
2342
|
-
|
|
2343
|
-
|
|
2433
|
+
/**
|
|
2434
|
+
* The part of flush() that runs under the flush lock: pauses the account, clears its sync
|
|
2435
|
+
* state and resumes it a few seconds later
|
|
2436
|
+
* @param {Object} data - The flush request
|
|
2437
|
+
*/
|
|
2438
|
+
async flushLocked(data) {
|
|
2439
|
+
await this.call({
|
|
2440
|
+
cmd: 'pause',
|
|
2441
|
+
account: this.account,
|
|
2442
|
+
timeout: this.timeout
|
|
2443
|
+
});
|
|
2344
2444
|
|
|
2345
|
-
|
|
2346
|
-
|
|
2347
|
-
throw error;
|
|
2348
|
-
}
|
|
2349
|
-
} catch (err) {
|
|
2350
|
-
if (Boom.isBoom(err)) {
|
|
2351
|
-
// contention was already logged above
|
|
2352
|
-
throw err;
|
|
2353
|
-
}
|
|
2354
|
-
this.logger.error({ msg: 'Failed to get flush lock', account: this.account, lockKey, err });
|
|
2355
|
-
let error = Boom.boomify(new Error('Failed to get flush lock, try again later'), { statusCode: 500 });
|
|
2356
|
-
if (err.code) {
|
|
2357
|
-
error.output.payload.code = err.code || 'LockFail';
|
|
2358
|
-
}
|
|
2359
|
-
throw error;
|
|
2360
|
-
}
|
|
2445
|
+
let notifyFrom = data.notifyFrom && data.notifyFrom !== 'now' ? data.notifyFrom : new Date();
|
|
2446
|
+
let imapIndexer = data.imapIndexer;
|
|
2361
2447
|
|
|
2362
2448
|
try {
|
|
2363
|
-
|
|
2364
|
-
|
|
2365
|
-
|
|
2366
|
-
|
|
2367
|
-
|
|
2368
|
-
|
|
2369
|
-
|
|
2370
|
-
|
|
2371
|
-
|
|
2372
|
-
|
|
2373
|
-
|
|
2374
|
-
|
|
2375
|
-
|
|
2376
|
-
|
|
2377
|
-
|
|
2378
|
-
|
|
2379
|
-
|
|
2380
|
-
|
|
2381
|
-
|
|
2382
|
-
|
|
2383
|
-
|
|
2384
|
-
|
|
2385
|
-
|
|
2386
|
-
// Note: mailbox ID hash (iah:) and listRegistry are intentionally NOT deleted
|
|
2387
|
-
// to preserve message ID stability across reconnections. Message IDs depend on
|
|
2388
|
-
// the specific mailbox ID entries, so deleting them would invalidate existing IDs.
|
|
2389
|
-
.del(`${REDIS_PREFIX}iar:b:${this.account}`) // retired bounce store, an older version sharing this Redis may still write it
|
|
2390
|
-
.del(`${REDIS_PREFIX}iar:s:${this.account}`) // seen messages list
|
|
2391
|
-
.del(tombstoneTdy)
|
|
2392
|
-
.del(tombstoneYdy);
|
|
2393
|
-
|
|
2394
|
-
if (imapIndexer) {
|
|
2395
|
-
pipeline = pipeline.hset(this.getAccountKey(), 'imapIndexer', imapIndexer);
|
|
2396
|
-
}
|
|
2449
|
+
let pipeline = this.redis
|
|
2450
|
+
.multi()
|
|
2451
|
+
// start syncing new messages from current time
|
|
2452
|
+
.hset(this.getAccountKey(), 'notifyFrom', notifyFrom.toISOString())
|
|
2453
|
+
// mark connection count to 0 to trigger `accountInitialized` event
|
|
2454
|
+
.hset(this.getAccountKey(), `state:count:${ACCOUNT_STATES.CONNECTED}`, '0')
|
|
2455
|
+
// The Gmail API and Graph clients keep their sync position in the account hash
|
|
2456
|
+
// rather than in the keys removed below. Without these a flushed Gmail account
|
|
2457
|
+
// went on from its old history ID, and a flushed Graph account kept the point
|
|
2458
|
+
// its announced set started from while the set itself was removed, so the next
|
|
2459
|
+
// recovery pass took every message since then for unannounced and announced it
|
|
2460
|
+
// again. Each client sets a fresh value when it starts.
|
|
2461
|
+
.hdel(this.getAccountKey(), ...FLUSHED_SYNC_FIELDS)
|
|
2462
|
+
.del(this.getMailboxListKey()) // mailbox list
|
|
2463
|
+
// Note: mailbox ID hash (iah:) and listRegistry are intentionally NOT deleted
|
|
2464
|
+
// to preserve message ID stability across reconnections. Message IDs depend on
|
|
2465
|
+
// the specific mailbox ID entries, so deleting them would invalidate existing IDs.
|
|
2466
|
+
.del(`${REDIS_PREFIX}iar:b:${this.account}`) // retired bounce store, an older version sharing this Redis may still write it
|
|
2467
|
+
.del(`${REDIS_PREFIX}iar:s:${this.account}`); // seen messages list
|
|
2468
|
+
|
|
2469
|
+
if (imapIndexer) {
|
|
2470
|
+
pipeline = pipeline.hset(this.getAccountKey(), 'imapIndexer', imapIndexer);
|
|
2471
|
+
}
|
|
2397
2472
|
|
|
2398
|
-
|
|
2473
|
+
await pipeline.exec();
|
|
2399
2474
|
|
|
2400
|
-
|
|
2401
|
-
|
|
2475
|
+
// scan and delete keys
|
|
2476
|
+
await this.deleteOwnAccountKeys();
|
|
2402
2477
|
|
|
2403
|
-
|
|
2404
|
-
} finally {
|
|
2405
|
-
let finalize = async () => {
|
|
2406
|
-
// Wait a bit before resuming. Just to be sure all pending processes have been completed.
|
|
2407
|
-
await new Promise(r => setTimeout(r, 5 * 1000));
|
|
2408
|
-
await this.call({
|
|
2409
|
-
cmd: 'resume',
|
|
2410
|
-
account: this.account,
|
|
2411
|
-
timeout: this.timeout
|
|
2412
|
-
});
|
|
2413
|
-
};
|
|
2414
|
-
finalize().catch(err => {
|
|
2415
|
-
this.logger.error({ msg: 'Failed to finish flushing', account: this.account, err });
|
|
2416
|
-
});
|
|
2417
|
-
}
|
|
2478
|
+
return true;
|
|
2418
2479
|
} finally {
|
|
2419
|
-
|
|
2420
|
-
|
|
2421
|
-
|
|
2480
|
+
let finalize = async () => {
|
|
2481
|
+
// Wait a bit before resuming. Just to be sure all pending processes have been completed.
|
|
2482
|
+
await new Promise(r => setTimeout(r, 5 * 1000));
|
|
2483
|
+
await this.call({
|
|
2484
|
+
cmd: 'resume',
|
|
2485
|
+
account: this.account,
|
|
2486
|
+
timeout: this.timeout
|
|
2487
|
+
});
|
|
2488
|
+
};
|
|
2489
|
+
finalize().catch(err => {
|
|
2490
|
+
this.logger.error({ msg: 'Failed to finish flushing', account: this.account, err });
|
|
2491
|
+
});
|
|
2422
2492
|
}
|
|
2423
2493
|
}
|
|
2424
2494
|
|
|
@@ -2430,28 +2500,21 @@ class Account {
|
|
|
2430
2500
|
return accountData;
|
|
2431
2501
|
}
|
|
2432
2502
|
|
|
2433
|
-
|
|
2434
|
-
|
|
2435
|
-
|
|
2436
|
-
|
|
2437
|
-
|
|
2438
|
-
|
|
2439
|
-
|
|
2440
|
-
|
|
2441
|
-
throw new Error('Failed to get renewal lock');
|
|
2442
|
-
}
|
|
2443
|
-
} catch (err) {
|
|
2444
|
-
if (!renewLock) {
|
|
2445
|
-
// unexpected lock-layer error; contention was already logged above
|
|
2446
|
-
this.logger.error({ msg: 'Failed to get renewal lock', account: this.account, lockKey, err });
|
|
2447
|
-
}
|
|
2448
|
-
let error = Boom.boomify(new Error('Failed to get renewal lock'), { statusCode: 500 });
|
|
2449
|
-
if (err.code) {
|
|
2450
|
-
error.output.payload.code = err.code || 'LockFail';
|
|
2451
|
-
}
|
|
2452
|
-
throw error;
|
|
2453
|
-
}
|
|
2503
|
+
return await runLocked(
|
|
2504
|
+
this.getLock(),
|
|
2505
|
+
lockKey,
|
|
2506
|
+
{ ttl: 5 * 60 * 1000, wait: 1 * 60 * 1000 },
|
|
2507
|
+
() => this.renewAccessTokenLocked(oauth2Opts),
|
|
2508
|
+
refuseUnavailableLock(this.logger, 'Failed to get renewal lock', { account: this.account, lockKey })
|
|
2509
|
+
);
|
|
2510
|
+
}
|
|
2454
2511
|
|
|
2512
|
+
/**
|
|
2513
|
+
* The part of renewAccessToken() that runs under the renewal lock: renews unless another
|
|
2514
|
+
* holder renewed meanwhile
|
|
2515
|
+
* @param {Object} oauth2Opts
|
|
2516
|
+
*/
|
|
2517
|
+
async renewAccessTokenLocked(oauth2Opts) {
|
|
2455
2518
|
try {
|
|
2456
2519
|
let accountData = await this.loadAccountData(this.account, false);
|
|
2457
2520
|
|
|
@@ -2559,10 +2622,6 @@ class Account {
|
|
|
2559
2622
|
}
|
|
2560
2623
|
|
|
2561
2624
|
throw err;
|
|
2562
|
-
} finally {
|
|
2563
|
-
if (renewLock?.success) {
|
|
2564
|
-
await lock.releaseLock(renewLock);
|
|
2565
|
-
}
|
|
2566
2625
|
}
|
|
2567
2626
|
}
|
|
2568
2627
|
|
|
@@ -2964,6 +3023,7 @@ function isAccessTokenInvalidated(oauth2) {
|
|
|
2964
3023
|
|
|
2965
3024
|
module.exports = {
|
|
2966
3025
|
ENCRYPTED_ACCOUNT_FIELDS,
|
|
3026
|
+
FLUSHED_SYNC_FIELDS,
|
|
2967
3027
|
Account,
|
|
2968
3028
|
accountExists,
|
|
2969
3029
|
accountsExist,
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// Machine-readable `code` values for API error responses whose throw site did not set one.
|
|
4
|
+
// Dependency-free, so workers/api.js and the tests can share it.
|
|
5
|
+
//
|
|
6
|
+
// A 404 used to carry `code: 'NotFound'` only when it came from throwNotFound() or one of the
|
|
7
|
+
// lib-level update() methods. The others - an unknown export, queued message, blocklist entry,
|
|
8
|
+
// account log or account (lib/account.js throws a bare Boom 404) - came back without a code,
|
|
9
|
+
// because handleError() passes Boom errors through untouched, so a client could not branch on
|
|
10
|
+
// `code` for the most common error there is. Filled in once, where the JSON error body is built,
|
|
11
|
+
// so a 404 thrown by any route, now or later, carries it.
|
|
12
|
+
|
|
13
|
+
const DEFAULT_ERROR_CODES = {
|
|
14
|
+
404: 'NotFound'
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Sets the default `code` on an API error payload that has none
|
|
19
|
+
* @param {Object} payload - Boom output payload ({ statusCode, error, message, ... }), modified in place
|
|
20
|
+
* @returns {Object} The same payload
|
|
21
|
+
*/
|
|
22
|
+
function addDefaultErrorCode(payload) {
|
|
23
|
+
if (!payload || typeof payload !== 'object' || payload.code) {
|
|
24
|
+
return payload;
|
|
25
|
+
}
|
|
26
|
+
const code = DEFAULT_ERROR_CODES[payload.statusCode];
|
|
27
|
+
if (code) {
|
|
28
|
+
payload.code = code;
|
|
29
|
+
}
|
|
30
|
+
return payload;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Hapi onPreResponse step that fills in the default code of an error response. Registered by
|
|
35
|
+
* workers/api.js ahead of the handler that renders error pages and JSON errors, and by the route
|
|
36
|
+
* tests' bare servers, so a route test sees the same error body a client does
|
|
37
|
+
* @param {Object} request - Hapi request
|
|
38
|
+
* @param {Object} h - Hapi response toolkit
|
|
39
|
+
* @returns {Symbol} h.continue
|
|
40
|
+
*/
|
|
41
|
+
function errorCodeExt(request, h) {
|
|
42
|
+
const response = request.response;
|
|
43
|
+
if (response && response.isBoom) {
|
|
44
|
+
addDefaultErrorCode(response.output.payload);
|
|
45
|
+
}
|
|
46
|
+
return h.continue;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
module.exports = { addDefaultErrorCode, errorCodeExt, DEFAULT_ERROR_CODES };
|
|
@@ -50,9 +50,10 @@ function formatDescription(text) {
|
|
|
50
50
|
});
|
|
51
51
|
|
|
52
52
|
// Bare URLs, skipping ones already inside an href="..." emitted above
|
|
53
|
-
html = html.replace(
|
|
54
|
-
|
|
55
|
-
|
|
53
|
+
html = html.replace(
|
|
54
|
+
/(^|[\s(])(https?:\/\/[^\s<>"')]+)/g,
|
|
55
|
+
(match, prefix, url) => `${prefix}<a href="${url}" target="_blank" rel="noopener noreferrer" class="link link-primary">${url}</a>`
|
|
56
|
+
);
|
|
56
57
|
|
|
57
58
|
return html
|
|
58
59
|
.split(/\n{2,}/)
|
|
@@ -107,6 +107,7 @@ function buildParameter(spec, parameter, operationId) {
|
|
|
107
107
|
in: parameter.in,
|
|
108
108
|
required: !!parameter.required,
|
|
109
109
|
typeLabel: typeLabel(spec, schema),
|
|
110
|
+
description: parameter.description || schema.description,
|
|
110
111
|
descriptionHtml: formatDescription(parameter.description || schema.description),
|
|
111
112
|
usageHtml: formatDescription(schema['x-meta'] && schema['x-meta'].usage),
|
|
112
113
|
constraints: constraintList(schema),
|
|
@@ -156,6 +157,10 @@ function buildParameter(spec, parameter, operationId) {
|
|
|
156
157
|
// looser than that sentence would eventually match a group of undocumented strings and
|
|
157
158
|
// describe it wrongly, having also dropped each member's type, default and anchor. Predicate
|
|
158
159
|
// and prose have to mean the same thing.
|
|
160
|
+
// A description that says no more than the chip sentence does ("Include the `x` setting in the
|
|
161
|
+
// response"), which the settings flags carry for code generators and readers of the raw document
|
|
162
|
+
const INCLUDE_FLAG_DESCRIPTION = /^Include the .+ in the response$/;
|
|
163
|
+
|
|
159
164
|
function flagNames(parameters) {
|
|
160
165
|
if (parameters.length < FLAG_GROUP_MIN) {
|
|
161
166
|
return null;
|
|
@@ -165,7 +170,7 @@ function flagNames(parameters) {
|
|
|
165
170
|
parameter =>
|
|
166
171
|
parameter.typeLabel === 'boolean' &&
|
|
167
172
|
parameter.defaultValue === 'false' &&
|
|
168
|
-
!parameter.descriptionHtml &&
|
|
173
|
+
(!parameter.descriptionHtml || INCLUDE_FLAG_DESCRIPTION.test(parameter.description)) &&
|
|
169
174
|
!parameter.required &&
|
|
170
175
|
!parameter.deprecated &&
|
|
171
176
|
!parameter.enumValues
|