emailengine-app 2.79.9 → 2.80.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/.release-please-manifest.json +1 -1
- package/CHANGELOG.md +49 -0
- package/config/default.toml +5 -1
- package/data/google-crawlers.json +1 -1
- package/encrypt.js +43 -0
- package/lib/account/account-state.js +62 -0
- package/lib/account.js +34 -2
- package/lib/api-routes/account-routes.js +20 -0
- package/lib/api-routes/index.js +1 -1
- package/lib/api-routes/settings-routes.js +17 -2
- package/lib/autodetect-imap-settings.js +349 -47
- package/lib/cert-handler.js +62 -0
- package/lib/consts.js +50 -6
- package/lib/db.js +12 -0
- package/lib/egress-fetch.js +21 -9
- package/lib/email-client/base-client.js +234 -66
- package/lib/email-client/credential-errors.js +118 -0
- package/lib/email-client/gmail/gmail-api.js +2 -1
- package/lib/email-client/gmail-client.js +70 -64
- package/lib/email-client/imap/connection-errors.js +52 -0
- package/lib/email-client/imap/listing-diff.js +47 -6
- package/lib/email-client/imap/mailbox.js +457 -379
- package/lib/email-client/imap/subconnection.js +15 -11
- package/lib/email-client/imap/sync-operations.js +46 -59
- package/lib/email-client/imap-client.js +136 -95
- package/lib/email-client/message-builder.js +11 -11
- package/lib/email-client/outlook/graph-api.js +2 -1
- package/lib/email-client/outlook-client.js +219 -106
- package/lib/imap-proxy-auth.js +58 -3
- package/lib/imapproxy/imap-server.js +53 -62
- package/lib/lua/h-del-if-equals.lua +39 -0
- package/lib/lua/h-set-if-equals.lua +39 -0
- package/lib/routes-ui.js +4 -34
- package/lib/schemas.js +32 -0
- package/lib/security-headers.js +15 -0
- package/lib/tls/context.js +376 -0
- package/lib/tls/der.js +223 -0
- package/lib/tls/provision.js +555 -0
- package/lib/tls/self-signed.js +282 -0
- package/lib/tls/status.js +431 -0
- package/lib/tls/store.js +666 -0
- package/lib/tools.js +72 -27
- package/lib/ui-routes/account-routes.js +43 -30
- package/lib/ui-routes/admin-config-routes.js +22 -1
- package/lib/ui-routes/auth-routes.js +16 -1
- package/lib/ui-routes/internals-routes.js +3 -5
- package/lib/ui-routes/network-config-routes.js +54 -45
- package/lib/ui-routes/tls-config-routes.js +581 -0
- package/lib/utils/mailbox-path.js +51 -0
- package/lib/utils/severity.js +31 -0
- package/package.json +4 -4
- package/sbom.json +1 -1
- package/server.js +16 -0
- package/static/css/flyonui.css +1 -1
- package/static/css/src/app.tailwind.css +11 -0
- package/static/js/app.js +34 -0
- package/static/js/public.js +6 -2
- package/static/js/ui.js +8 -25
- package/static/licenses.html +328 -1257
- package/translations/messages.pot +87 -87
- package/views/account/login-redirect.hbs +22 -0
- package/views/config/imap-proxy.hbs +0 -3
- package/views/config/smtp.hbs +0 -3
- package/views/config/tls-upload.hbs +81 -0
- package/views/config/tls.hbs +492 -0
- package/views/partials/side_menu.hbs +1 -0
- package/views/partials/tls_security_card.hbs +25 -53
- package/views/partials/ui/alert-banner.hbs +3 -2
- package/views/partials/ui/badge.hbs +6 -2
- package/views/partials/ui/btn.hbs +5 -2
- package/workers/api.js +93 -134
- package/workers/imap-proxy.js +4 -1
- package/workers/smtp.js +51 -44
- package/views/partials/tls_security_js.hbs +0 -64
- package/views/partials/tls_security_modal.hbs +0 -22
package/lib/consts.js
CHANGED
|
@@ -145,6 +145,13 @@ module.exports = {
|
|
|
145
145
|
// carry is the separate, read-only `_authFailureDisabledAt`.
|
|
146
146
|
AUTH_FAILURE_DISABLED_FIELD: '_authFailureDisabled',
|
|
147
147
|
|
|
148
|
+
// Account hash field recording which event wrote the current `lastErrorState`. Both
|
|
149
|
+
// `authenticationError` and `connectError` store their payload there, so without this the
|
|
150
|
+
// recovery path cannot tell them apart. Written next to `lastErrorState` and cleared with it;
|
|
151
|
+
// same leading-underscore convention as AUTH_FAILURE_DISABLED_FIELD, so unserializeAccountData()
|
|
152
|
+
// does not surface it.
|
|
153
|
+
LAST_ERROR_EVENT_FIELD: '_lastErrorEvent',
|
|
154
|
+
|
|
148
155
|
// The `lastErrorState.description` the safety net stores when it parks an account, and the log
|
|
149
156
|
// line it writes at the same moment. User-visible copy: reword it freely, nothing matches on it.
|
|
150
157
|
AUTH_FAILURE_DISABLED_DESCRIPTION: 'IMAP was disabled for the account due to exceeding the authentication error threshold',
|
|
@@ -160,16 +167,53 @@ module.exports = {
|
|
|
160
167
|
|
|
161
168
|
REDIS_BATCH_DELETE_SIZE: 1000,
|
|
162
169
|
|
|
163
|
-
// When renewal becomes due is
|
|
164
|
-
//
|
|
165
|
-
//
|
|
166
|
-
// for exactly one lifetime
|
|
170
|
+
// When renewal becomes due is decided by @postalsys/certs, so there is no constant for it here.
|
|
171
|
+
// It asks Let's Encrypt through ACME Renewal Information where it can, and otherwise renews two
|
|
172
|
+
// thirds of the way through whatever lifetime the certificate was issued with. A fixed "renew
|
|
173
|
+
// when N days remain" threshold is correct for exactly one lifetime, and Let's Encrypt is
|
|
174
|
+
// shortening them from 90 days to 64 and then 45. https://letsencrypt.org/2025/12/02/from-90-to-45
|
|
175
|
+
|
|
176
|
+
// The ACME account and directory that lib/cert-handler.js hands to every worker.
|
|
177
|
+
//
|
|
178
|
+
// These two only make sense as a pair. The environment names the stored ACME account record and
|
|
179
|
+
// the directory names the CA that issued it, so pointing one at Let's Encrypt staging without
|
|
180
|
+
// moving the other presents an account key the staging CA has never seen, and every request is
|
|
181
|
+
// rejected. Override both or neither. Staging is https://acme-staging-v02.api.letsencrypt.org/directory,
|
|
182
|
+
// which is what to test issuance against: same asynchronous finalization as production, no rate
|
|
183
|
+
// limits worth worrying about, and certificates signed by an untrusted root - which is also why
|
|
184
|
+
// the default here has to stay production. A build that shipped staging by default would hand
|
|
185
|
+
// every IMAP, SMTP and HTTPS client a certificate it refuses.
|
|
186
|
+
ACME_ENVIRONMENT: (process.env.EENGINE_ACME_ENVIRONMENT || '').toString().trim() || 'emailengine',
|
|
187
|
+
ACME_DIRECTORY_URL: (process.env.EENGINE_ACME_DIRECTORY_URL || '').toString().trim() || 'https://acme-v02.api.letsencrypt.org/directory',
|
|
188
|
+
|
|
189
|
+
// Exactly one of the two was overridden, which is the combination the paragraph above says
|
|
190
|
+
// cannot work. Derived here, from the same reads the values themselves come from, so it can
|
|
191
|
+
// never disagree with them; lib/cert-handler.js is what reports it, since nothing in the CA's
|
|
192
|
+
// rejection says why every order failed.
|
|
193
|
+
ACME_OVERRIDE_PARTIAL:
|
|
194
|
+
!!(process.env.EENGINE_ACME_ENVIRONMENT || '').toString().trim() !== !!(process.env.EENGINE_ACME_DIRECTORY_URL || '').toString().trim(),
|
|
167
195
|
|
|
168
196
|
// do not attempt certificate renewal more often than once in 8 hours
|
|
169
197
|
BLOCK_TLS_RENEW: 8 * 3600 * 1000,
|
|
170
198
|
|
|
171
|
-
//
|
|
172
|
-
|
|
199
|
+
// How often the reconciler looks at the configured hostnames. Most passes do nothing: a valid
|
|
200
|
+
// certificate that was checked within BLOCK_TLS_RENEW is skipped without a call to anyone. The
|
|
201
|
+
// interval is what bounds how long a first certificate, or one whose record was lost, waits for
|
|
202
|
+
// its automatic attempt, which is why it is minutes rather than the hour renewal alone needs.
|
|
203
|
+
TLS_RENEW_CHECK_INTERVAL: 10 * 60 * 1000,
|
|
204
|
+
|
|
205
|
+
// How long a hostname whose last order failed is left alone by the reconciler. The certificate
|
|
206
|
+
// library arms its own failsafe lock on top of this (an hour after the CA answered, a minute
|
|
207
|
+
// after a transport error); this is the outer bound that also covers a name with no record at
|
|
208
|
+
// all, where the library has nothing to lock on.
|
|
209
|
+
TLS_RETRY_AFTER_FAILURE: 15 * 60 * 1000,
|
|
210
|
+
|
|
211
|
+
// Lifetime of a preflight probe token, in seconds. Long enough for a redirect chain and a slow
|
|
212
|
+
// reverse proxy, short enough that a token is not left answering for the rest of the day.
|
|
213
|
+
TLS_PREFLIGHT_TTL: 120,
|
|
214
|
+
|
|
215
|
+
// How long the preflight waits for the challenge path to answer
|
|
216
|
+
TLS_PREFLIGHT_TIMEOUT: 20 * 1000,
|
|
173
217
|
|
|
174
218
|
// default download chunk size 1MB
|
|
175
219
|
DEFAULT_DOWNLOAD_CHUNK_SIZE: 1000000,
|
package/lib/db.js
CHANGED
|
@@ -133,6 +133,8 @@ const hSetBiggerScript = fs.readFileSync(pathlib.join(__dirname, 'lua/h-set-bigg
|
|
|
133
133
|
const hUpdateBiggerScript = fs.readFileSync(pathlib.join(__dirname, 'lua/h-update-bigger.lua'), 'utf-8');
|
|
134
134
|
const hSetExistsScript = fs.readFileSync(pathlib.join(__dirname, 'lua/h-set-exists.lua'), 'utf-8');
|
|
135
135
|
const hSetNewScript = fs.readFileSync(pathlib.join(__dirname, 'lua/h-set-new.lua'), 'utf-8');
|
|
136
|
+
const hSetIfEqualsScript = fs.readFileSync(pathlib.join(__dirname, 'lua/h-set-if-equals.lua'), 'utf-8');
|
|
137
|
+
const hDelIfEqualsScript = fs.readFileSync(pathlib.join(__dirname, 'lua/h-del-if-equals.lua'), 'utf-8');
|
|
136
138
|
const hSetNewMarkScript = fs.readFileSync(pathlib.join(__dirname, 'lua/h-set-new-mark.lua'), 'utf-8');
|
|
137
139
|
const hIncrbyExistsScript = fs.readFileSync(pathlib.join(__dirname, 'lua/h-incrby-exists.lua'), 'utf-8');
|
|
138
140
|
const eeListAddScript = fs.readFileSync(pathlib.join(__dirname, 'lua/ee-list-add.lua'), 'utf-8');
|
|
@@ -199,6 +201,16 @@ redis.defineCommand('hSetNew', {
|
|
|
199
201
|
lua: hSetNewScript
|
|
200
202
|
});
|
|
201
203
|
|
|
204
|
+
redis.defineCommand('hSetIfEquals', {
|
|
205
|
+
numberOfKeys: 1,
|
|
206
|
+
lua: hSetIfEqualsScript
|
|
207
|
+
});
|
|
208
|
+
|
|
209
|
+
redis.defineCommand('hDelIfEquals', {
|
|
210
|
+
numberOfKeys: 1,
|
|
211
|
+
lua: hDelIfEqualsScript
|
|
212
|
+
});
|
|
213
|
+
|
|
202
214
|
redis.defineCommand('hSetNewMark', {
|
|
203
215
|
numberOfKeys: 1,
|
|
204
216
|
lua: hSetNewMarkScript
|
package/lib/egress-fetch.js
CHANGED
|
@@ -29,6 +29,11 @@ const ALLOWED_PROTOCOLS = new Set(['http:', 'https:']);
|
|
|
29
29
|
// request outright)
|
|
30
30
|
const BODY_HEADERS = new Set(['content-type', 'content-length', 'content-encoding', 'content-language', 'content-location']);
|
|
31
31
|
|
|
32
|
+
// Headers that authenticate a request to one specific origin, and so cannot travel to another one.
|
|
33
|
+
// A credential is issued against the host that asked for it; a redirect naming a different host is
|
|
34
|
+
// not a reason to hand it over. fetch() drops these on a cross-origin hop and so does this.
|
|
35
|
+
const CREDENTIAL_HEADERS = new Set(['authorization', 'cookie', 'proxy-authorization']);
|
|
36
|
+
|
|
32
37
|
function redirectError(message, code) {
|
|
33
38
|
let err = new Error(message);
|
|
34
39
|
err.code = code;
|
|
@@ -40,7 +45,8 @@ function redirectError(message, code) {
|
|
|
40
45
|
*
|
|
41
46
|
* @param {string} location - Raw Location header
|
|
42
47
|
* @param {string} base - URL of the response carrying it
|
|
43
|
-
* @returns {
|
|
48
|
+
* @returns {URL} Absolute URL of the next hop. Returned parsed, so the caller can compare origins
|
|
49
|
+
* without building it a second time
|
|
44
50
|
* @throws {Error} EREDIRECTINVALID for an unparseable target, EREDIRECTSCHEME for a non-web one
|
|
45
51
|
*/
|
|
46
52
|
function resolveRedirect(location, base) {
|
|
@@ -55,17 +61,18 @@ function resolveRedirect(location, base) {
|
|
|
55
61
|
throw redirectError(`Redirect from ${base} points at an unsupported scheme (${next.protocol})`, 'EREDIRECTSCHEME');
|
|
56
62
|
}
|
|
57
63
|
|
|
58
|
-
return next
|
|
64
|
+
return next;
|
|
59
65
|
}
|
|
60
66
|
|
|
61
67
|
/**
|
|
62
|
-
* Drops
|
|
68
|
+
* Drops a set of headers from a plain header object (the only shape the callers pass).
|
|
63
69
|
*
|
|
64
70
|
* @param {Object} [headers] - Header name to value
|
|
71
|
+
* @param {Set} names - Lowercased header names to remove
|
|
65
72
|
* @returns {Object|undefined} Filtered copy
|
|
66
73
|
*/
|
|
67
|
-
function
|
|
68
|
-
return headers && Object.fromEntries(Object.entries(headers).filter(([name]) => !
|
|
74
|
+
function withoutHeaders(headers, names) {
|
|
75
|
+
return headers && Object.fromEntries(Object.entries(headers).filter(([name]) => !names.has(name.toLowerCase())));
|
|
69
76
|
}
|
|
70
77
|
|
|
71
78
|
/**
|
|
@@ -73,8 +80,9 @@ function withoutBodyHeaders(headers) {
|
|
|
73
80
|
*
|
|
74
81
|
* `validateTarget(url)` runs before the first request and before every hop; whatever it throws
|
|
75
82
|
* ends the fetch. Redirect semantics match fetch(): 303 always becomes a bodyless GET, 301 and 302
|
|
76
|
-
* do so for anything but GET and HEAD, 307 and 308 replay the request unchanged
|
|
77
|
-
*
|
|
83
|
+
* do so for anything but GET and HEAD, 307 and 308 replay the request unchanged, and a hop to
|
|
84
|
+
* another origin drops the credential headers. A 3xx without a Location is returned as it is,
|
|
85
|
+
* since it is not a redirect anyone can follow.
|
|
78
86
|
*
|
|
79
87
|
* @param {Function} fetchImpl - fetch implementation (undici fetch)
|
|
80
88
|
* @param {string} url - Destination URL
|
|
@@ -123,10 +131,14 @@ async function fetchWithVettedRedirects(fetchImpl, url, options) {
|
|
|
123
131
|
if (res.status === 303 || ((res.status === 301 || res.status === 302) && method !== 'GET' && method !== 'HEAD')) {
|
|
124
132
|
method = 'GET';
|
|
125
133
|
body = undefined;
|
|
126
|
-
headers =
|
|
134
|
+
headers = withoutHeaders(headers, BODY_HEADERS);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
if (next.origin !== new URL(current).origin) {
|
|
138
|
+
headers = withoutHeaders(headers, CREDENTIAL_HEADERS);
|
|
127
139
|
}
|
|
128
140
|
|
|
129
|
-
current = next;
|
|
141
|
+
current = next.toString();
|
|
130
142
|
}
|
|
131
143
|
}
|
|
132
144
|
|
|
@@ -20,6 +20,8 @@ const { getTemplate } = require('@postalsys/templates');
|
|
|
20
20
|
const { deepEqual } = require('assert');
|
|
21
21
|
const { arfDetect, camelCaseComplaint } = require('../arf-detect');
|
|
22
22
|
const { createTransaction } = require('../redis-operations');
|
|
23
|
+
const { ACCOUNT_STATES } = require('../account/account-state');
|
|
24
|
+
const { credentialErrorStatus, isTransientCredentialError, resolveAuthServerCredentials } = require('./credential-errors');
|
|
23
25
|
const simpleParser = require('mailparser').simpleParser;
|
|
24
26
|
const libmime = require('libmime');
|
|
25
27
|
const { bounceDetect, applyDeliveryReport } = require('../bounce-detect');
|
|
@@ -51,7 +53,6 @@ const {
|
|
|
51
53
|
emitChangeEvent,
|
|
52
54
|
filterEmptyObjectValues,
|
|
53
55
|
getDateBuckets,
|
|
54
|
-
resolveCredentials,
|
|
55
56
|
useAuthServerForOAuth2,
|
|
56
57
|
collectCidReferences,
|
|
57
58
|
cidReferenceRegex
|
|
@@ -60,6 +61,7 @@ const {
|
|
|
60
61
|
// Import application constants
|
|
61
62
|
const {
|
|
62
63
|
AUTH_ERROR_NOTIFY,
|
|
64
|
+
AUTH_SUCCESS_NOTIFY,
|
|
63
65
|
ACCOUNT_INITIALIZED_NOTIFY,
|
|
64
66
|
REDIS_PREFIX,
|
|
65
67
|
MESSAGE_NEW_NOTIFY,
|
|
@@ -71,10 +73,10 @@ const {
|
|
|
71
73
|
MAX_INLINE_ATTACHMENT_SIZE,
|
|
72
74
|
DEFAULT_MAX_IMAP_AUTH_FAILURE_TIME,
|
|
73
75
|
AUTH_FAILURE_DISABLED_FIELD,
|
|
76
|
+
LAST_ERROR_EVENT_FIELD,
|
|
74
77
|
AUTH_FAILURE_DISABLED_DESCRIPTION,
|
|
75
78
|
EMAIL_DELIVERY_ERROR_NOTIFY,
|
|
76
|
-
EMAIL_SENT_NOTIFY
|
|
77
|
-
TRANSIENT_NETWORK_CODES
|
|
79
|
+
EMAIL_SENT_NOTIFY
|
|
78
80
|
} = require('../consts');
|
|
79
81
|
const { buildRetentionPolicy } = require('../queue-retention');
|
|
80
82
|
const { readImapData } = require('../account/imap-data');
|
|
@@ -210,19 +212,28 @@ async function renewRejectedAccessToken(context, err, tokenData, tokenRenewed) {
|
|
|
210
212
|
return true;
|
|
211
213
|
}
|
|
212
214
|
|
|
215
|
+
// Everything an error run stores. One list, because clearing a subset leaves an account that has
|
|
216
|
+
// recovered still carrying the counters the auth-failure safety net reads, and the list has already
|
|
217
|
+
// grown once - LAST_ERROR_EVENT_FIELD was added after the other three
|
|
218
|
+
const ERROR_STATE_FIELDS = Object.freeze(['lastErrorState', LAST_ERROR_EVENT_FIELD, 'lastError:errorCount', 'lastError:first']);
|
|
219
|
+
|
|
213
220
|
/**
|
|
214
|
-
*
|
|
215
|
-
*
|
|
216
|
-
*
|
|
217
|
-
*
|
|
218
|
-
*
|
|
219
|
-
* failure as a generic TypeError ("fetch failed") with the real DNS/socket error attached as
|
|
220
|
-
* err.cause, so the code is looked up there as well
|
|
221
|
-
* @param {Error} err - The error to check
|
|
222
|
-
* @returns {boolean} True if the error is a transient network failure
|
|
221
|
+
* Reads a stored `lastErrorState`. `isSet` says whether it describes an error that actually
|
|
222
|
+
* happened: an empty object is what a cleared-but-rewritten state looks like, and a value that
|
|
223
|
+
* will not parse still counts as a run that happened even though nothing can be read off it
|
|
224
|
+
* @param {String} storedState - Raw JSON read from the account hash
|
|
225
|
+
* @returns {Object} { parsed, isSet }
|
|
223
226
|
*/
|
|
224
|
-
function
|
|
225
|
-
|
|
227
|
+
function parseErrorState(storedState) {
|
|
228
|
+
if (!storedState) {
|
|
229
|
+
return { parsed: null, isSet: false };
|
|
230
|
+
}
|
|
231
|
+
try {
|
|
232
|
+
const parsed = JSON.parse(storedState);
|
|
233
|
+
return { parsed, isSet: !!parsed && (typeof parsed !== 'object' || !!Object.keys(parsed).length) };
|
|
234
|
+
} catch (err) {
|
|
235
|
+
return { parsed: null, isSet: true };
|
|
236
|
+
}
|
|
226
237
|
}
|
|
227
238
|
|
|
228
239
|
/**
|
|
@@ -336,6 +347,12 @@ class BaseClient {
|
|
|
336
347
|
// scheduleInitRetry(). IMAPClient reconnects with its own backoff instead
|
|
337
348
|
this.retriesInit = false;
|
|
338
349
|
|
|
350
|
+
// Read by notifyAuthenticationSuccess(). Deliberately not persisted: a worker restart
|
|
351
|
+
// re-arming it costs at most one extra event for an account that never manages to connect,
|
|
352
|
+
// while a new account hash field would have to guess what every existing account had
|
|
353
|
+
// already been told
|
|
354
|
+
this.authSuccessNotified = false;
|
|
355
|
+
|
|
339
356
|
// Initialize notification handler for webhook and event delivery
|
|
340
357
|
this.notificationHandler = new NotificationHandler({
|
|
341
358
|
account: this.account,
|
|
@@ -574,6 +591,21 @@ class BaseClient {
|
|
|
574
591
|
}
|
|
575
592
|
}
|
|
576
593
|
|
|
594
|
+
/**
|
|
595
|
+
* The answer every client gives for a text or attachment identifier it can not decode, built in
|
|
596
|
+
* one place so the three agree on it
|
|
597
|
+
* @returns {Error} Coded 400
|
|
598
|
+
*/
|
|
599
|
+
invalidIdError() {
|
|
600
|
+
let error = new Error('Invalid identifier');
|
|
601
|
+
error.info = {
|
|
602
|
+
response: 'The provided identifier can not be decoded'
|
|
603
|
+
};
|
|
604
|
+
error.code = 'InvalidId';
|
|
605
|
+
error.statusCode = 400;
|
|
606
|
+
return error;
|
|
607
|
+
}
|
|
608
|
+
|
|
577
609
|
/**
|
|
578
610
|
* Decodes a base64url msgpack identifier the API clients hand out for text and
|
|
579
611
|
* attachment references. A truncated or foreign value used to surface as a RangeError,
|
|
@@ -591,13 +623,7 @@ class BaseClient {
|
|
|
591
623
|
}
|
|
592
624
|
|
|
593
625
|
if (!Array.isArray(parts) || !isValid(parts)) {
|
|
594
|
-
|
|
595
|
-
error.info = {
|
|
596
|
-
response: 'The provided identifier can not be decoded'
|
|
597
|
-
};
|
|
598
|
-
error.code = 'InvalidId';
|
|
599
|
-
error.statusCode = 400;
|
|
600
|
-
throw error;
|
|
626
|
+
throw this.invalidIdError();
|
|
601
627
|
}
|
|
602
628
|
|
|
603
629
|
return parts;
|
|
@@ -705,6 +731,156 @@ class BaseClient {
|
|
|
705
731
|
}
|
|
706
732
|
}
|
|
707
733
|
|
|
734
|
+
/**
|
|
735
|
+
* Drops everything an error run stored. Used by every recovery route: a completed login, and
|
|
736
|
+
* the Graph client's change subscription starting to work again. One implementation, so the set
|
|
737
|
+
* of fields cannot grow a second idea of itself.
|
|
738
|
+
*
|
|
739
|
+
* The delete is conditional, and `expected` is required for it: only the caller knows which
|
|
740
|
+
* failure it judged, and between reading that failure and getting here it can have been
|
|
741
|
+
* replaced by an unrelated one (see lib/lua/h-del-if-equals.lua).
|
|
742
|
+
*
|
|
743
|
+
* @param {String|null} expected - The raw `lastErrorState` the caller read, null when there
|
|
744
|
+
* was none. The delete is skipped when the field no longer holds it
|
|
745
|
+
* @returns {Promise<boolean>} Whether the fields were dropped
|
|
746
|
+
*/
|
|
747
|
+
async clearStoredErrorState(expected) {
|
|
748
|
+
return !!(await this.redis.hDelIfEquals(this.getAccountKey(), 'lastErrorState', expected || '', ...ERROR_STATE_FIELDS));
|
|
749
|
+
}
|
|
750
|
+
|
|
751
|
+
/**
|
|
752
|
+
* Whether a stored error run is one only the code that reported it may lift. A login clears
|
|
753
|
+
* every failure that stood between the account and a session, which is every failure a client
|
|
754
|
+
* stores by default - so this says no. A reporter whose failure a login says nothing about
|
|
755
|
+
* overrides it and keeps its own report standing (the Graph client's change subscription is
|
|
756
|
+
* one: a tenant that disabled the Exchange Online service principal keeps refreshing tokens
|
|
757
|
+
* and logging in perfectly while no subscription can be created).
|
|
758
|
+
* @param {Object} parsedState - The stored `lastErrorState`, parsed; null when there is none
|
|
759
|
+
* @returns {boolean} True when only the code that reported it may clear it
|
|
760
|
+
*/
|
|
761
|
+
isSelfClearedErrorState(parsedState) {
|
|
762
|
+
return false;
|
|
763
|
+
}
|
|
764
|
+
|
|
765
|
+
/**
|
|
766
|
+
* Reports a completed login: decides whether it is worth an `authenticationSuccess` webhook,
|
|
767
|
+
* clears the error state the previous attempt left behind, and sends the notification.
|
|
768
|
+
*
|
|
769
|
+
* Reading and clearing the error state is one step on purpose. The IMAP client used to read it
|
|
770
|
+
* on login and clear it only once a full folder sync had completed, so an account that
|
|
771
|
+
* authenticates but never manages to sync re-read the same stale error on every reconnect and
|
|
772
|
+
* announced itself again each time.
|
|
773
|
+
*
|
|
774
|
+
* Call this BEFORE the account state is flipped to `connected`. The first-login test reads the
|
|
775
|
+
* connected-session counter that setStateVal() raises, and the Graph client used to read it
|
|
776
|
+
* afterwards - so an Outlook account never announced its first login at all.
|
|
777
|
+
*
|
|
778
|
+
* @param {String} user - Username the login used, for the webhook payload
|
|
779
|
+
* @returns {Promise<boolean>} Whether the notification was sent
|
|
780
|
+
*/
|
|
781
|
+
async notifyAuthenticationSuccess(user) {
|
|
782
|
+
const accountKey = this.getAccountKey();
|
|
783
|
+
|
|
784
|
+
let storedState;
|
|
785
|
+
let storedEvent;
|
|
786
|
+
let prevConnectedCount;
|
|
787
|
+
let parsedState;
|
|
788
|
+
|
|
789
|
+
try {
|
|
790
|
+
// Read what the previous attempt left behind, then drop the run it describes. A run
|
|
791
|
+
// this login did not get past stays where it is, for the code that reported it to
|
|
792
|
+
// lift. The delete is otherwise conditional on the value just read, so a failure
|
|
793
|
+
// written since is left for whoever wrote it rather than taken along
|
|
794
|
+
[storedState, storedEvent, prevConnectedCount] = await this.redis.hmget(
|
|
795
|
+
accountKey,
|
|
796
|
+
'lastErrorState',
|
|
797
|
+
LAST_ERROR_EVENT_FIELD,
|
|
798
|
+
'state:count:connected'
|
|
799
|
+
);
|
|
800
|
+
|
|
801
|
+
parsedState = parseErrorState(storedState);
|
|
802
|
+
|
|
803
|
+
if (!this.isSelfClearedErrorState(parsedState.parsed)) {
|
|
804
|
+
await this.clearStoredErrorState(storedState);
|
|
805
|
+
}
|
|
806
|
+
} catch (err) {
|
|
807
|
+
// Saying nothing is the quiet answer: a webhook that is not sent can be read off the
|
|
808
|
+
// account state, one that is sent twice cannot be taken back
|
|
809
|
+
this.logger.error({ msg: 'Failed to consume the stored error state', account: this.account, err });
|
|
810
|
+
return false;
|
|
811
|
+
}
|
|
812
|
+
|
|
813
|
+
// What had been failing, or null when the account was not in an error state. An error state
|
|
814
|
+
// written before the event field existed carries no marker; read it as an authentication
|
|
815
|
+
// failure, which is how every recovery used to be reported
|
|
816
|
+
const errorEvent = parsedState.isSet ? storedEvent || AUTH_ERROR_NOTIFY : null;
|
|
817
|
+
|
|
818
|
+
// A string zero means the account has been initialized but not yet connected. The counter
|
|
819
|
+
// is only raised once the account reaches `connected`, which for an IMAP account means a
|
|
820
|
+
// completed folder sync - so it stays at zero for an account that logs in but cannot sync,
|
|
821
|
+
// and the instance flag is what keeps that from announcing a first login every time round
|
|
822
|
+
const isInitial = prevConnectedCount === '0' && !this.authSuccessNotified;
|
|
823
|
+
|
|
824
|
+
// Announce a recovery only when authentication was what had been failing. `connectError`
|
|
825
|
+
// stores the same error state, and reporting a name-resolution blip as
|
|
826
|
+
// `authenticationSuccess` is both wrong and, on an account that keeps flapping, one more
|
|
827
|
+
// webhook per cycle
|
|
828
|
+
if (!isInitial && errorEvent !== AUTH_ERROR_NOTIFY) {
|
|
829
|
+
this.logger.info({ msg: 'Successful login with a previous active session', account: this.account, prevActive: true, errorEvent });
|
|
830
|
+
return false;
|
|
831
|
+
}
|
|
832
|
+
|
|
833
|
+
this.authSuccessNotified = true;
|
|
834
|
+
this.logger.info({ msg: 'Successful login without a previous active session', account: this.account, isInitial, prevActive: false });
|
|
835
|
+
await this.notify(false, AUTH_SUCCESS_NOTIFY, { user });
|
|
836
|
+
return true;
|
|
837
|
+
}
|
|
838
|
+
|
|
839
|
+
/**
|
|
840
|
+
* Fetches this account's credentials from the operator's external authentication server. See
|
|
841
|
+
* resolveAuthServerCredentials() in ./credential-errors for what it reports and why
|
|
842
|
+
* @param {String} target - Protocol the credentials are for ('imap', 'smtp' or 'api')
|
|
843
|
+
* @param {Object} ctx - What to report the failure on (a subconnection reports on itself)
|
|
844
|
+
* @returns {Promise<Object>} Resolved credentials
|
|
845
|
+
*/
|
|
846
|
+
async resolveAuthServerCredentials(target, ctx) {
|
|
847
|
+
return await resolveAuthServerCredentials(this.account, target, ctx || this);
|
|
848
|
+
}
|
|
849
|
+
|
|
850
|
+
/**
|
|
851
|
+
* Reports a failed OAuth2 token refresh for an API-backed account. Both API clients call this
|
|
852
|
+
* from getTokenData(); the IMAP path reports its own through loadOAuth2LoginCredentials().
|
|
853
|
+
*
|
|
854
|
+
* @param {Error} err - The ETokenRefresh failure
|
|
855
|
+
* @param {String} provider - Provider name for the metrics label
|
|
856
|
+
* @returns {Promise<void>}
|
|
857
|
+
*/
|
|
858
|
+
async reportTokenRefreshFailure(err, provider) {
|
|
859
|
+
const statusCode = String(err.statusCode || 0);
|
|
860
|
+
postMetrics({ account: this.account }, this.logger, 'oauth2TokenRefresh', 'inc', { status: 'failure', provider, statusCode });
|
|
861
|
+
|
|
862
|
+
if (isTransientCredentialError(err)) {
|
|
863
|
+
// The endpoint is unavailable, it has not refused the refresh token. Left unflagged and
|
|
864
|
+
// unannounced so the caller retries instead of parking the account and webhooking an
|
|
865
|
+
// authentication failure that the next attempt contradicts
|
|
866
|
+
this.logger.warn({ msg: 'Token endpoint is unavailable', account: this.account, statusCode, err });
|
|
867
|
+
return;
|
|
868
|
+
}
|
|
869
|
+
|
|
870
|
+
this.state = ACCOUNT_STATES.AUTHENTICATION_ERROR;
|
|
871
|
+
await this.setStateVal();
|
|
872
|
+
|
|
873
|
+
err.authenticationFailed = true;
|
|
874
|
+
|
|
875
|
+
if (!err.errorNotified) {
|
|
876
|
+
err.errorNotified = true;
|
|
877
|
+
await this.notify(false, AUTH_ERROR_NOTIFY, {
|
|
878
|
+
response: err.oauthRequest?.response?.error?.message || err.response,
|
|
879
|
+
serverResponseCode: 'TokenGenerationError'
|
|
880
|
+
});
|
|
881
|
+
}
|
|
882
|
+
}
|
|
883
|
+
|
|
708
884
|
/**
|
|
709
885
|
* Sets error state and manages error tracking/notifications
|
|
710
886
|
* Implements logic to disable IMAP after repeated authentication failures
|
|
@@ -733,8 +909,18 @@ class BaseClient {
|
|
|
733
909
|
|
|
734
910
|
let shouldNotify = true;
|
|
735
911
|
|
|
736
|
-
// Store current error state
|
|
737
|
-
|
|
912
|
+
// Store current error state. The event is recorded beside it rather than inside it: `data`
|
|
913
|
+
// is the webhook payload and a published response shape, and notifyAuthenticationSuccess()
|
|
914
|
+
// needs to know whether the run that is ending was an authentication failure or a
|
|
915
|
+
// connection one
|
|
916
|
+
const stateTxn = createTransaction(this.redis, { logger: this.logger });
|
|
917
|
+
stateTxn.add('hSetExists', this.getAccountKey(), 'lastErrorState', JSON.stringify(data));
|
|
918
|
+
stateTxn.add('hSetExists', this.getAccountKey(), LAST_ERROR_EVENT_FIELD, event);
|
|
919
|
+
// Throws rather than reporting the failure in a return value nobody reads: an error that
|
|
920
|
+
// was not stored is one the next login announces a recovery from, one the repeat check
|
|
921
|
+
// below cannot suppress, and one the auth-failure safety net never counts towards a park
|
|
922
|
+
await stateTxn.execOrThrow();
|
|
923
|
+
|
|
738
924
|
await emitChangeEvent(this.logger, this.account, 'state', event, { error: data });
|
|
739
925
|
|
|
740
926
|
// Check if this is a repeat of the same error
|
|
@@ -760,7 +946,12 @@ class BaseClient {
|
|
|
760
946
|
const txn = createTransaction(this.redis, { logger: this.logger });
|
|
761
947
|
txn.add('hSetExists', this.getAccountKey(), 'lastError:errorCount', 1);
|
|
762
948
|
txn.add('hSetExists', this.getAccountKey(), 'lastError:first', new Date().toISOString());
|
|
763
|
-
await txn.exec();
|
|
949
|
+
const { error } = await txn.exec();
|
|
950
|
+
if (error) {
|
|
951
|
+
// Not fatal - the caller still reports the error - but the timestamp is what the
|
|
952
|
+
// auth-failure park measures its three days from, so a lost write is worth saying
|
|
953
|
+
this.logger.error({ msg: 'Redis error while resetting error state counters', error });
|
|
954
|
+
}
|
|
764
955
|
} else {
|
|
765
956
|
let errorCount;
|
|
766
957
|
let firstError;
|
|
@@ -1006,44 +1197,17 @@ class BaseClient {
|
|
|
1006
1197
|
// one instead of renewing from a stored refresh token (it has none). The app is still
|
|
1007
1198
|
// resolved above, because the caller needs it for the provider's host and port.
|
|
1008
1199
|
if (await useAuthServerForOAuth2(accountData.oauth2, ctx.logger, { account: accountObject.account, target })) {
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
// rejected credential. Reporting it as an authentication error would webhook every
|
|
1021
|
-
// account on the instance and park them in an error state over a brief blip.
|
|
1022
|
-
if (isTransientNetworkError(err)) {
|
|
1023
|
-
ctx.logger.warn({
|
|
1024
|
-
msg: 'Network error while resolving credentials from the authentication server',
|
|
1025
|
-
account: accountObject.account,
|
|
1026
|
-
target,
|
|
1027
|
-
code: err.code,
|
|
1028
|
-
err
|
|
1029
|
-
});
|
|
1030
|
-
throw err;
|
|
1031
|
-
}
|
|
1032
|
-
|
|
1033
|
-
err.authenticationFailed = true;
|
|
1034
|
-
await ctx.notify(false, AUTH_ERROR_NOTIFY, {
|
|
1035
|
-
response: err.message,
|
|
1036
|
-
serverResponseCode: 'HTTPRequestError'
|
|
1037
|
-
});
|
|
1038
|
-
ctx.logger.error({
|
|
1039
|
-
msg: 'Failed to resolve OAuth2 credentials from the authentication server',
|
|
1040
|
-
account: accountObject.account,
|
|
1041
|
-
target,
|
|
1042
|
-
err
|
|
1043
|
-
});
|
|
1044
|
-
ctx.state = AUTH_ERROR_NOTIFY;
|
|
1045
|
-
throw err;
|
|
1046
|
-
}
|
|
1200
|
+
// Bound to accountObject rather than to this client: a shared mailbox opened through a
|
|
1201
|
+
// delegated account draws its token from the delegating account's record
|
|
1202
|
+
let authData = await resolveAuthServerCredentials(accountObject.account, target, ctx);
|
|
1203
|
+
|
|
1204
|
+
// The auth server owns the credentials, but a shared mailbox is still addressed by
|
|
1205
|
+
// the configured delegatedUser - same precedence as the stored-token path above.
|
|
1206
|
+
return {
|
|
1207
|
+
oauth2User: accountData.oauth2.auth.delegatedUser || authData.user,
|
|
1208
|
+
accessToken: authData.accessToken,
|
|
1209
|
+
oauth2App
|
|
1210
|
+
};
|
|
1047
1211
|
}
|
|
1048
1212
|
|
|
1049
1213
|
// Check if token needs refresh (with 30 second buffer)
|
|
@@ -1056,12 +1220,17 @@ class BaseClient {
|
|
|
1056
1220
|
});
|
|
1057
1221
|
accessToken = accountData.oauth2.accessToken;
|
|
1058
1222
|
} catch (err) {
|
|
1059
|
-
//
|
|
1060
|
-
|
|
1223
|
+
// A token endpoint that could not be reached, or that answered 429 or a 5xx, has not
|
|
1224
|
+
// refused the refresh token. Microsoft and Google both throttle and fail this
|
|
1225
|
+
// endpoint often enough that treating it as an authentication failure produced a
|
|
1226
|
+
// steady stream of authenticationError / authenticationSuccess pairs and parked
|
|
1227
|
+
// otherwise healthy accounts
|
|
1228
|
+
if (isTransientCredentialError(err)) {
|
|
1061
1229
|
ctx.logger.warn({
|
|
1062
1230
|
msg: 'Network error during OAuth2 token refresh',
|
|
1063
1231
|
account: accountObject.account,
|
|
1064
1232
|
code: err.code,
|
|
1233
|
+
status: credentialErrorStatus(err) || undefined,
|
|
1065
1234
|
err
|
|
1066
1235
|
});
|
|
1067
1236
|
// Do not mark as authenticationFailed, let the caller handle as a connection error
|
|
@@ -1082,7 +1251,7 @@ class BaseClient {
|
|
|
1082
1251
|
account: accountObject.account,
|
|
1083
1252
|
err
|
|
1084
1253
|
});
|
|
1085
|
-
ctx.state =
|
|
1254
|
+
ctx.state = ACCOUNT_STATES.AUTHENTICATION_ERROR;
|
|
1086
1255
|
throw err;
|
|
1087
1256
|
}
|
|
1088
1257
|
} else {
|
|
@@ -3743,7 +3912,6 @@ module.exports = {
|
|
|
3743
3912
|
BaseClient,
|
|
3744
3913
|
metricsMeta: postMetrics,
|
|
3745
3914
|
applyReferenceRecipients,
|
|
3746
|
-
isTransientNetworkError,
|
|
3747
3915
|
markRejectedAccessToken,
|
|
3748
3916
|
renewRejectedAccessToken
|
|
3749
3917
|
};
|