emailengine-app 2.79.9 → 2.80.1
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 +73 -0
- package/README.md +6 -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 +101 -1
- package/lib/api-routes/blocklist-routes.js +24 -0
- package/lib/api-routes/delivery-test-routes.js +6 -0
- package/lib/api-routes/gateway-routes.js +30 -0
- package/lib/api-routes/index.js +1 -1
- package/lib/api-routes/license-routes.js +10 -0
- package/lib/api-routes/mcp-oauth-routes.js +3 -3
- package/lib/api-routes/mcp-routes.js +39 -21
- package/lib/api-routes/oauth2-app-routes.js +38 -1
- package/lib/api-routes/outbox-routes.js +6 -0
- package/lib/api-routes/permission-map.js +208 -43
- package/lib/api-routes/pubsub-routes.js +8 -0
- package/lib/api-routes/route-helpers.js +58 -11
- package/lib/api-routes/settings-routes.js +67 -6
- package/lib/api-routes/stats-routes.js +6 -0
- package/lib/api-routes/template-routes.js +21 -0
- package/lib/api-routes/token-routes.js +34 -2
- package/lib/api-routes/webhook-route-routes.js +13 -0
- 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 +238 -67
- package/lib/email-client/credential-errors.js +122 -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/login-failure.js +52 -0
- package/lib/email-client/imap/mailbox.js +457 -379
- package/lib/email-client/imap/subconnection.js +17 -12
- package/lib/email-client/imap/sync-operations.js +46 -59
- package/lib/email-client/imap-client.js +139 -101
- 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/enum-descriptions.js +12 -2
- 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/mcp/oauth.js +46 -8
- package/lib/mcp/protocol.js +78 -35
- package/lib/mcp/tools.js +53 -17
- package/lib/privileged-settings.js +147 -0
- package/lib/routes-ui.js +4 -34
- package/lib/schemas.js +92 -16
- package/lib/security-headers.js +15 -0
- package/lib/settings.js +13 -0
- package/lib/tls/catalog.js +428 -0
- package/lib/tls/context.js +302 -0
- package/lib/tls/der.js +223 -0
- package/lib/tls/listeners.js +62 -0
- package/lib/tls/provision.js +555 -0
- package/lib/tls/self-signed.js +282 -0
- package/lib/tls/status.js +480 -0
- package/lib/tls/store.js +667 -0
- package/lib/token-permission-view.js +252 -102
- package/lib/token-permissions.js +176 -26
- package/lib/tokens.js +7 -6
- package/lib/tools.js +73 -27
- package/lib/ui-routes/account-routes.js +43 -30
- package/lib/ui-routes/admin-config-routes.js +63 -22
- package/lib/ui-routes/admin-entities-routes.js +23 -13
- package/lib/ui-routes/auth-routes.js +16 -1
- package/lib/ui-routes/internals-routes.js +3 -5
- package/lib/ui-routes/mcp-consent-routes.js +72 -31
- package/lib/ui-routes/network-config-routes.js +54 -45
- package/lib/ui-routes/tls-config-routes.js +628 -0
- package/lib/utils/mailbox-path.js +51 -0
- package/lib/utils/severity.js +31 -0
- package/package.json +12 -12
- package/sbom.json +1 -1
- package/server.js +23 -1
- 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 +97 -61
- package/static/licenses.html +341 -1252
- package/translations/messages.pot +62 -56
- package/views/account/login-redirect.hbs +22 -0
- package/views/account/passkeys.hbs +2 -2
- package/views/accounts/account.hbs +2 -2
- package/views/accounts/browse.hbs +1 -1
- package/views/accounts/edit.hbs +1 -1
- package/views/accounts/register/imap-server.hbs +1 -1
- package/views/config/ai.hbs +1 -1
- package/views/config/branding.hbs +2 -2
- package/views/config/document-store/chat.hbs +1 -1
- package/views/config/document-store/index.hbs +1 -1
- package/views/config/imap-proxy.hbs +1 -4
- package/views/config/license.hbs +1 -1
- package/views/config/mcp.hbs +88 -52
- package/views/config/network.hbs +1 -1
- package/views/config/oauth/app.hbs +2 -2
- package/views/config/service.hbs +1 -1
- package/views/config/smtp.hbs +1 -4
- package/views/config/tls-upload.hbs +81 -0
- package/views/config/tls.hbs +593 -0
- package/views/config/webhooks.hbs +2 -2
- package/views/internals/index.hbs +1 -1
- package/views/layout/app.hbs +6 -6
- package/views/layout/login.hbs +5 -5
- package/views/layout/main.hbs +2 -2
- package/views/layout/prompt.hbs +3 -3
- package/views/layout/public.hbs +1 -1
- package/views/mcp/authorize.hbs +47 -45
- package/views/partials/ace_assets.hbs +1 -1
- package/views/partials/add_account_modal.hbs +1 -1
- package/views/partials/filter_editor_js.hbs +2 -2
- package/views/partials/gateway_js.hbs +1 -1
- package/views/partials/mcp_access_levels.hbs +16 -9
- package/views/partials/mcp_tool_count.hbs +15 -14
- package/views/partials/oauth_form.hbs +1 -1
- package/views/partials/public_theme_init.hbs +1 -1
- package/views/partials/side_menu.hbs +1 -0
- package/views/partials/template_form.hbs +1 -1
- package/views/partials/theme_init.hbs +1 -1
- 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/views/partials/webhooks_editor_functions.hbs +1 -1
- package/views/reference/index.hbs +1 -1
- package/views/reference/redirect.hbs +1 -1
- package/views/reference/tag.hbs +1 -1
- package/views/reference/token.hbs +1 -1
- package/views/templates/template.hbs +1 -1
- package/views/tokens/new.hbs +175 -74
- package/views/unsubscribe.hbs +1 -1
- package/views/webhooks/webhook.hbs +1 -1
- package/workers/api.js +102 -142
- 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
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// Where EmailEngine decides whether a failed attempt to obtain a credential means "the credential
|
|
4
|
+
// was refused" or "the service that holds it is having a bad minute". Getting that wrong is
|
|
5
|
+
// expensive: a refusal webhooks `authenticationError`, parks the account in an error state and
|
|
6
|
+
// stops the API clients retrying, and then the next attempt contradicts it with
|
|
7
|
+
// `authenticationSuccess`. Microsoft and Google throttle and 5xx their token endpoints often
|
|
8
|
+
// enough, and one authentication server is shared by every account on an instance, for that to be
|
|
9
|
+
// a steady stream of events and parked accounts on a busy deployment.
|
|
10
|
+
//
|
|
11
|
+
// Its own module rather than a corner of base-client.js because both sides of the fence need it:
|
|
12
|
+
// base-client owns the IMAP and API credential paths, message-builder owns the SMTP one, and
|
|
13
|
+
// base-client already imports message-builder - so there is no direction in which one could
|
|
14
|
+
// require the other.
|
|
15
|
+
//
|
|
16
|
+
// The IMAP server's own verdict on a login (a NO to AUTHENTICATE that is the server's problem
|
|
17
|
+
// rather than the credential's) is decided in ./imap/login-failure.js, kept dependency-free so the
|
|
18
|
+
// pure subconnection tests do not inherit the Redis connections this module's imports open.
|
|
19
|
+
|
|
20
|
+
const { resolveCredentials } = require('../tools');
|
|
21
|
+
const { AUTH_ERROR_NOTIFY, TRANSIENT_NETWORK_CODES } = require('../consts');
|
|
22
|
+
const { ACCOUNT_STATES } = require('../account/account-state');
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Failing to reach a remote endpoint is a connection problem, not a rejected credential. Both
|
|
26
|
+
* OAuth2 credential sources (EmailEngine's own token refresh and an external authentication
|
|
27
|
+
* server) use this to avoid reporting an unreachable host as an authentication error, and the API
|
|
28
|
+
* transports use it to decide which failed requests to repeat. undici reports a connection failure
|
|
29
|
+
* as a generic TypeError ("fetch failed") with the real DNS/socket error attached as err.cause, so
|
|
30
|
+
* the code is looked up there as well
|
|
31
|
+
* @param {Error} err - The error to check
|
|
32
|
+
* @returns {boolean} True if the error is a transient network failure
|
|
33
|
+
*/
|
|
34
|
+
function isTransientNetworkError(err) {
|
|
35
|
+
return !!err && (TRANSIENT_NETWORK_CODES.has(err.code) || (!!err.cause && TRANSIENT_NETWORK_CODES.has(err.cause.code)));
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Reads the HTTP status a failed credential request came back with. The OAuth2 clients put it on
|
|
40
|
+
* the error itself and repeat it in the request record they attach; the Graph and Gmail transports
|
|
41
|
+
* only carry the request record, and so does the external authentication server (`authRequest`,
|
|
42
|
+
* attached by resolveCredentials() in lib/tools.js - it must not put an operator's status on
|
|
43
|
+
* err.statusCode, which is read as the status of the API request being served). Boom wrappers are
|
|
44
|
+
* deliberately not consulted: Account.getActiveAccessTokenData() boomifies every renewal failure
|
|
45
|
+
* as 403, which would mask the status the token endpoint actually sent
|
|
46
|
+
* @param {Error} err - The error to read
|
|
47
|
+
* @returns {number} The status, or 0 when the failure never reached a response
|
|
48
|
+
*/
|
|
49
|
+
function credentialErrorStatus(err) {
|
|
50
|
+
return Number(err?.statusCode || err?.tokenRequest?.status || err?.oauthRequest?.status || err?.authRequest?.status || 0);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Whether a failed attempt to obtain a credential means the credential service is unavailable
|
|
55
|
+
* rather than the credential being refused. 408, 429 and every 5xx are the service failing; only a
|
|
56
|
+
* 4xx is the credential itself being rejected (an expired refresh token comes back as 400
|
|
57
|
+
* invalid_grant, a revoked one as 401), which is the case a human has to resolve by
|
|
58
|
+
* re-authorizing the account
|
|
59
|
+
* @param {Error} err - The error to check
|
|
60
|
+
* @returns {boolean} True when the failure is the service's, not the credential's
|
|
61
|
+
*/
|
|
62
|
+
function isTransientCredentialError(err) {
|
|
63
|
+
if (isTransientNetworkError(err)) {
|
|
64
|
+
return true;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const status = credentialErrorStatus(err);
|
|
68
|
+
return status === 408 || status === 429 || (status >= 500 && status < 600);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Fetches an account's credentials from the operator's external authentication server and reports
|
|
73
|
+
* a refusal as an authentication error. Shared by every connection path - IMAP, SMTP and the API
|
|
74
|
+
* clients - because they all have to draw the same line: one authentication server serves every
|
|
75
|
+
* account on the instance, so announcing an outage as an authentication failure webhooks and parks
|
|
76
|
+
* the whole fleet at once. A transient failure is rethrown unflagged, and the caller reports it as
|
|
77
|
+
* a connection error and retries.
|
|
78
|
+
*
|
|
79
|
+
* @param {String} account - Account id
|
|
80
|
+
* @param {String} target - Protocol the credentials are for ('imap', 'smtp' or 'api')
|
|
81
|
+
* @param {Object} ctx - What to report the failure on; needs `logger`, `notify` and `state` (an
|
|
82
|
+
* IMAP subconnection passes itself, and its notify() is a no-op, so its failures stay its own)
|
|
83
|
+
* @returns {Promise<Object>} Resolved credentials
|
|
84
|
+
*/
|
|
85
|
+
async function resolveAuthServerCredentials(account, target, ctx) {
|
|
86
|
+
try {
|
|
87
|
+
return await resolveCredentials(account, target);
|
|
88
|
+
} catch (err) {
|
|
89
|
+
if (isTransientCredentialError(err)) {
|
|
90
|
+
ctx.logger.warn({
|
|
91
|
+
msg: 'Network error while resolving credentials from the authentication server',
|
|
92
|
+
account,
|
|
93
|
+
target,
|
|
94
|
+
code: err.code,
|
|
95
|
+
status: credentialErrorStatus(err) || undefined,
|
|
96
|
+
err
|
|
97
|
+
});
|
|
98
|
+
throw err;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
err.authenticationFailed = true;
|
|
102
|
+
await ctx.notify(false, AUTH_ERROR_NOTIFY, {
|
|
103
|
+
response: err.message,
|
|
104
|
+
serverResponseCode: 'HTTPRequestError'
|
|
105
|
+
});
|
|
106
|
+
ctx.logger.error({
|
|
107
|
+
msg: 'Failed to resolve credentials from the authentication server',
|
|
108
|
+
account,
|
|
109
|
+
target,
|
|
110
|
+
err
|
|
111
|
+
});
|
|
112
|
+
ctx.state = ACCOUNT_STATES.AUTHENTICATION_ERROR;
|
|
113
|
+
throw err;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
module.exports = {
|
|
118
|
+
isTransientNetworkError,
|
|
119
|
+
credentialErrorStatus,
|
|
120
|
+
isTransientCredentialError,
|
|
121
|
+
resolveAuthServerCredentials
|
|
122
|
+
};
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
const { metricsMeta, markRejectedAccessToken, renewRejectedAccessToken
|
|
3
|
+
const { metricsMeta, markRejectedAccessToken, renewRejectedAccessToken } = require('../base-client');
|
|
4
|
+
const { isTransientNetworkError } = require('../credential-errors');
|
|
4
5
|
|
|
5
6
|
// Gmail API configuration
|
|
6
7
|
const GMAIL_API_BASE = 'https://gmail.googleapis.com';
|
|
@@ -8,7 +8,8 @@ const msgpack = require('../msgpack');
|
|
|
8
8
|
const addressparser = require('nodemailer/lib/addressparser');
|
|
9
9
|
const libmime = require('libmime');
|
|
10
10
|
const he = require('he');
|
|
11
|
-
const { BaseClient, metricsMeta
|
|
11
|
+
const { BaseClient, metricsMeta } = require('./base-client');
|
|
12
|
+
const { isTransientCredentialError } = require('./credential-errors');
|
|
12
13
|
const { messageWebSafeHtml, applyWebSafeHtmlOptions } = require('../web-safe-html');
|
|
13
14
|
const { emitChangeEvent, toCamelCase, collectCidReferences, cidReferenceRegex, truncateTextContents } = require('../tools');
|
|
14
15
|
const { Gateway } = require('../gateway');
|
|
@@ -20,7 +21,6 @@ const {
|
|
|
20
21
|
EMAIL_SENT_NOTIFY,
|
|
21
22
|
REDIS_PREFIX,
|
|
22
23
|
AUTH_ERROR_NOTIFY,
|
|
23
|
-
AUTH_SUCCESS_NOTIFY,
|
|
24
24
|
DEFAULT_GMAIL_EXPORT_BATCH_SIZE,
|
|
25
25
|
GMAIL_MAX_HISTORY_ENTRY_ATTEMPTS
|
|
26
26
|
} = require('../consts');
|
|
@@ -384,10 +384,9 @@ class GmailClient extends BaseClient {
|
|
|
384
384
|
profileRes = await this.request(`${GMAIL_API_BASE}/gmail/v1/users/me/profile`);
|
|
385
385
|
}
|
|
386
386
|
} catch (err) {
|
|
387
|
-
if (
|
|
388
|
-
//
|
|
389
|
-
//
|
|
390
|
-
// an authentication error that only re-authorization could clear
|
|
387
|
+
if (isTransientCredentialError(err)) {
|
|
388
|
+
// Not a refused credential - left unflagged so the worker retries init() instead of
|
|
389
|
+
// reporting an authentication error only re-authorization could clear
|
|
391
390
|
throw err;
|
|
392
391
|
}
|
|
393
392
|
|
|
@@ -498,44 +497,12 @@ class GmailClient extends BaseClient {
|
|
|
498
497
|
this.backgroundTimersArmed = true;
|
|
499
498
|
}
|
|
500
499
|
|
|
501
|
-
//
|
|
502
|
-
|
|
503
|
-
let isFirstSuccessfulConnection = prevConnectedCount === '0'; // string zero means the account has been initialized but not yet connected
|
|
500
|
+
// Before the state flip below - see notifyAuthenticationSuccess()
|
|
501
|
+
await this.notifyAuthenticationSuccess(accountData.oauth2?.auth?.user);
|
|
504
502
|
|
|
505
503
|
this.state = 'connected';
|
|
506
504
|
await this.setStateVal();
|
|
507
505
|
|
|
508
|
-
let isInitial = !!isFirstSuccessfulConnection;
|
|
509
|
-
|
|
510
|
-
if (!isFirstSuccessfulConnection) {
|
|
511
|
-
// check if the connection was previously in an errored state
|
|
512
|
-
let prevLastErrorState = await this.redis.hget(this.getAccountKey(), 'lastErrorState');
|
|
513
|
-
if (prevLastErrorState) {
|
|
514
|
-
try {
|
|
515
|
-
prevLastErrorState = JSON.parse(prevLastErrorState);
|
|
516
|
-
} catch (err) {
|
|
517
|
-
// ignore
|
|
518
|
-
}
|
|
519
|
-
}
|
|
520
|
-
|
|
521
|
-
if (prevLastErrorState && typeof prevLastErrorState === 'object' && Object.keys(prevLastErrorState).length) {
|
|
522
|
-
// was previously errored
|
|
523
|
-
isFirstSuccessfulConnection = true;
|
|
524
|
-
}
|
|
525
|
-
}
|
|
526
|
-
|
|
527
|
-
// Send appropriate authentication success notification
|
|
528
|
-
if (isFirstSuccessfulConnection) {
|
|
529
|
-
this.logger.info({ msg: 'Successful login without a previous active session', account: this.account, isInitial, prevActive: false });
|
|
530
|
-
await this.notify(false, AUTH_SUCCESS_NOTIFY, {
|
|
531
|
-
user: accountData.oauth2?.auth?.user
|
|
532
|
-
});
|
|
533
|
-
} else {
|
|
534
|
-
this.logger.info({ msg: 'Successful login with a previous active session', account: this.account, isInitial, prevActive: true });
|
|
535
|
-
}
|
|
536
|
-
|
|
537
|
-
// Clear any previous error state
|
|
538
|
-
await this.redis.hdel(this.getAccountKey(), 'lastErrorState', 'lastError:errorCount', 'lastError:first');
|
|
539
506
|
await emitChangeEvent(this.logger, this.account, 'state', this.state);
|
|
540
507
|
}
|
|
541
508
|
|
|
@@ -2030,9 +1997,15 @@ class GmailClient extends BaseClient {
|
|
|
2030
1997
|
let tokenData;
|
|
2031
1998
|
try {
|
|
2032
1999
|
tokenData = await this.accountObject.getActiveAccessTokenData();
|
|
2033
|
-
if (
|
|
2034
|
-
//
|
|
2035
|
-
//
|
|
2000
|
+
if (this.state === 'authenticationError') {
|
|
2001
|
+
// A valid token means the credential recovered, so announce it here as well as in
|
|
2002
|
+
// init() - this is also what clears the stored error state, which would otherwise
|
|
2003
|
+
// outlive the error it describes. Deliberately only the authentication error, the
|
|
2004
|
+
// same rule the Graph client follows: a token says nothing about `unset` (an
|
|
2005
|
+
// account the safety net parked) or `disconnected` (one that was closed), and
|
|
2006
|
+
// flipping either to `connected` for having fetched one was never right
|
|
2007
|
+
await this.notifyAuthenticationSuccess(tokenData.user);
|
|
2008
|
+
|
|
2036
2009
|
this.state = 'connected';
|
|
2037
2010
|
await this.setStateVal();
|
|
2038
2011
|
|
|
@@ -2052,23 +2025,7 @@ class GmailClient extends BaseClient {
|
|
|
2052
2025
|
}
|
|
2053
2026
|
} catch (E) {
|
|
2054
2027
|
if (E.code === 'ETokenRefresh') {
|
|
2055
|
-
|
|
2056
|
-
this.state = 'authenticationError';
|
|
2057
|
-
await this.setStateVal();
|
|
2058
|
-
|
|
2059
|
-
E.authenticationFailed = true;
|
|
2060
|
-
|
|
2061
|
-
// Track failed token refresh
|
|
2062
|
-
const statusCode = String(E.statusCode || 0);
|
|
2063
|
-
metricsMeta({ account: this.account }, this.logger, 'oauth2TokenRefresh', 'inc', { status: 'failure', provider: 'gmail', statusCode });
|
|
2064
|
-
|
|
2065
|
-
if (!E.errorNotified) {
|
|
2066
|
-
E.errorNotified = true;
|
|
2067
|
-
await this.notify(false, AUTH_ERROR_NOTIFY, {
|
|
2068
|
-
response: E.oauthRequest?.response?.error?.message || E.response,
|
|
2069
|
-
serverResponseCode: 'TokenGenerationError'
|
|
2070
|
-
});
|
|
2071
|
-
}
|
|
2028
|
+
await this.reportTokenRefreshFailure(E, 'gmail');
|
|
2072
2029
|
}
|
|
2073
2030
|
|
|
2074
2031
|
throw E;
|
|
@@ -2122,8 +2079,10 @@ class GmailClient extends BaseClient {
|
|
|
2122
2079
|
this.renewWatch()
|
|
2123
2080
|
.catch(err => {
|
|
2124
2081
|
this.logger.error({ msg: 'Failed to renew Gmail subscription watch', account: this.account, err });
|
|
2125
|
-
// Check if this is a permanent auth failure
|
|
2126
|
-
|
|
2082
|
+
// Check if this is a permanent auth failure. A token endpoint that answered 429
|
|
2083
|
+
// or a 5xx has not refused the credential, and stopping the timer on one would
|
|
2084
|
+
// leave the watch unrenewed until something else happens to fetch a token
|
|
2085
|
+
if ((err.code === 'ETokenRefresh' && !isTransientCredentialError(err)) || this.state === 'authenticationError') {
|
|
2127
2086
|
authError = true;
|
|
2128
2087
|
}
|
|
2129
2088
|
})
|
|
@@ -2230,11 +2189,21 @@ class GmailClient extends BaseClient {
|
|
|
2230
2189
|
watchExpiration: watchExpiration ? new Date(watchExpiration).toISOString() : null
|
|
2231
2190
|
});
|
|
2232
2191
|
} catch (err) {
|
|
2192
|
+
// NB! `lastWatch` is deliberately NOT moved here, so it now means "last
|
|
2193
|
+
// successful arm" rather than "last attempt". It gates the renewal at the top of
|
|
2194
|
+
// this method against MIN_WATCH_TTL, so writing it on a failure bought a broken
|
|
2195
|
+
// watch a full day of silence even though the renewal timer fires hourly - and a
|
|
2196
|
+
// Gmail watch lapses seven days after the last successful call, so a week of
|
|
2197
|
+
// daily failures ended push entirely. The attempt time goes on the failure
|
|
2198
|
+
// record instead, which is what reports how stale this is. A failing watch now
|
|
2199
|
+
// retries at the timer's own cadence, hourly, with no backoff and no cap: one
|
|
2200
|
+
// call per account per hour is orders of magnitude under the Gmail quota, and
|
|
2201
|
+
// the alternative is the seven-day lapse this replaces
|
|
2233
2202
|
await this.accountObject.update({
|
|
2234
|
-
lastWatch: new Date(now),
|
|
2235
2203
|
watchFailure: {
|
|
2236
2204
|
err: err.message,
|
|
2237
|
-
req: err.oauthRequest
|
|
2205
|
+
req: err.oauthRequest,
|
|
2206
|
+
time: new Date(now).toISOString()
|
|
2238
2207
|
}
|
|
2239
2208
|
});
|
|
2240
2209
|
this.logger.error({
|
|
@@ -2250,6 +2219,23 @@ class GmailClient extends BaseClient {
|
|
|
2250
2219
|
// GCP, so ensurePubsub never persisted the markers). Surface it once per connection -
|
|
2251
2220
|
// the renewal timer re-fires ~hourly and this branch never updates lastWatch, so an
|
|
2252
2221
|
// unguarded warning would otherwise repeat every cycle.
|
|
2222
|
+
// Recorded, not just logged: this is the one failure mode that armed no watch and
|
|
2223
|
+
// wrote nothing, so an operator polling the account saw what a healthy one shows.
|
|
2224
|
+
// Written every cycle, unlike the warning below - the record's whole job is to say
|
|
2225
|
+
// when the state was last observed, and a latch would freeze that at the first
|
|
2226
|
+
// sighting while the check went on running hourly. Best effort, because init()
|
|
2227
|
+
// awaits this method and a Redis hiccup must not fail the account setup
|
|
2228
|
+
try {
|
|
2229
|
+
await this.accountObject.update({
|
|
2230
|
+
watchFailure: {
|
|
2231
|
+
err: 'Pub/Sub topic and IAM markers are not recorded on the linked application',
|
|
2232
|
+
time: new Date(now).toISOString()
|
|
2233
|
+
}
|
|
2234
|
+
});
|
|
2235
|
+
} catch (err) {
|
|
2236
|
+
this.logger.error({ msg: 'Failed to record the missing watch markers', account: this.account, err });
|
|
2237
|
+
}
|
|
2238
|
+
|
|
2253
2239
|
if (!this._loggedMissingWatchMarkers) {
|
|
2254
2240
|
this._loggedMissingWatchMarkers = true;
|
|
2255
2241
|
this.logger.warn({
|
|
@@ -2261,6 +2247,26 @@ class GmailClient extends BaseClient {
|
|
|
2261
2247
|
});
|
|
2262
2248
|
}
|
|
2263
2249
|
}
|
|
2250
|
+
} else if (!accountData._app?.pubSubApp && (accountData.watchFailure || accountData.watchResponse)) {
|
|
2251
|
+
// Nothing pushes to this account any more: the Pub/Sub app was unlinked, or the account
|
|
2252
|
+
// was re-authorized onto an app that has none. The watch record is only ever cleared by
|
|
2253
|
+
// a successful arm, so an account with no push configured went on reporting the last
|
|
2254
|
+
// failure - state 'error' with a frozen lastCheck - for good. Keyed on the pubSubApp
|
|
2255
|
+
// term alone, never on the whole condition above: a still-linked account inside
|
|
2256
|
+
// MIN_WATCH_TTL takes the same else and its failure has to stay.
|
|
2257
|
+
// Best effort, because init() awaits this method and a Redis hiccup must not fail the
|
|
2258
|
+
// account setup
|
|
2259
|
+
this.watchExpiration = null;
|
|
2260
|
+
try {
|
|
2261
|
+
await this.getAccount();
|
|
2262
|
+
await this.accountObject.update({
|
|
2263
|
+
lastWatch: null,
|
|
2264
|
+
watchResponse: null,
|
|
2265
|
+
watchFailure: null
|
|
2266
|
+
});
|
|
2267
|
+
} catch (err) {
|
|
2268
|
+
this.logger.error({ msg: 'Failed to clear the stored Gmail watch record', account: this.account, err });
|
|
2269
|
+
}
|
|
2264
2270
|
}
|
|
2265
2271
|
}
|
|
2266
2272
|
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// The failures the IMAP client raises on its own behalf, rather than passing on something a server
|
|
4
|
+
// said. Each was written out by hand at every site that needed it - ten copies of the first alone,
|
|
5
|
+
// across imap-client.js, mailbox.js and sync-operations.js - which is how one of them ended up
|
|
6
|
+
// carrying a different code from the rest.
|
|
7
|
+
//
|
|
8
|
+
// The first two are in CONNECTION_CLOSING_CODES, so every existing handler already treats them as
|
|
9
|
+
// "the connection is gone, retry after the reconnect" rather than as a command failure.
|
|
10
|
+
// `IMAPUnavailable` is deliberately NOT in that set: it says the account has no usable connection
|
|
11
|
+
// to serve a request with, which is a 503 for the caller and not something a sync retries past.
|
|
12
|
+
// All of them are 503, which is what an API path reports.
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* There is no connection to run this on: the client was torn down and not replaced yet.
|
|
16
|
+
* @returns {Error} A connection-closing error
|
|
17
|
+
*/
|
|
18
|
+
function connectionNotAvailableError() {
|
|
19
|
+
const err = new Error('IMAP connection not available');
|
|
20
|
+
err.code = 'IMAPConnectionClosing';
|
|
21
|
+
err.statusCode = 503;
|
|
22
|
+
return err;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* The connection went away in the middle of a sync. The original failure is kept as `cause`,
|
|
27
|
+
* because on this path it is the only record of why the server dropped the connection
|
|
28
|
+
* (NO [OVERQUOTA], * BYE Too many connections, [SERVERBUG]).
|
|
29
|
+
* @param {Error} [cause] - What the server or socket reported
|
|
30
|
+
* @returns {Error} A connection-closing error
|
|
31
|
+
*/
|
|
32
|
+
function connectionClosedError(cause) {
|
|
33
|
+
const err = new Error('IMAP connection closed during sync', { cause });
|
|
34
|
+
err.code = 'IMAPConnectionClosing';
|
|
35
|
+
err.statusCode = 503;
|
|
36
|
+
return err;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* The account has no usable connection to serve this request with. Unlike the two above, this is
|
|
41
|
+
* the answer to a caller rather than a signal to a sync loop, so its code stays outside
|
|
42
|
+
* CONNECTION_CLOSING_CODES and nothing retries past it.
|
|
43
|
+
* @returns {Error} A 503 for the caller
|
|
44
|
+
*/
|
|
45
|
+
function connectionUnavailableError() {
|
|
46
|
+
const err = new Error('IMAP connection is currently not available for requested account');
|
|
47
|
+
err.code = 'IMAPUnavailable';
|
|
48
|
+
err.statusCode = 503;
|
|
49
|
+
return err;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
module.exports = { connectionNotAvailableError, connectionClosedError, connectionUnavailableError };
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
// Pure helpers behind IMAPClient.getCurrentListing()
|
|
3
|
+
// Pure helpers behind the mailbox listing: the diff IMAPClient.getCurrentListing() runs, and
|
|
4
|
+
// the comparisons that decide which listed folders an account watches.
|
|
4
5
|
//
|
|
5
6
|
// Every IMAP sync pass re-runs LIST and has to work out which folders are new, which changed
|
|
6
7
|
// shape, and which disappeared, then persist the result. That comparison is the part worth
|
|
@@ -10,10 +11,13 @@
|
|
|
10
11
|
// in imap-client.js.
|
|
11
12
|
//
|
|
12
13
|
// Folder paths are compared through normalizePath(), which case-folds INBOX so a server that
|
|
13
|
-
// reports "Inbox" one pass and "INBOX" the next does not look like a delete plus an add.
|
|
14
|
+
// reports "Inbox" one pass and "INBOX" the next does not look like a delete plus an add. Every
|
|
15
|
+
// comparison of a path against another path goes through samePath() (lib/utils/mailbox-path.js)
|
|
16
|
+
// for that reason, which is why the ones that match stored account configuration against a
|
|
17
|
+
// listing live here too rather than as an open-coded `===` at each call site.
|
|
14
18
|
|
|
15
19
|
const msgpack = require('../../msgpack');
|
|
16
|
-
const { normalizePath } = require('../../
|
|
20
|
+
const { normalizePath, samePath } = require('../../utils/mailbox-path');
|
|
17
21
|
const { STORED_MAILBOX_FIELDS } = require('../../consts');
|
|
18
22
|
|
|
19
23
|
// The fields diffMailboxListing() compares, i.e. everything buildStoredListingObject() persists
|
|
@@ -21,6 +25,35 @@ const { STORED_MAILBOX_FIELDS } = require('../../consts');
|
|
|
21
25
|
// stored field list so that persisting a new field can not silently leave it uncompared.
|
|
22
26
|
const COMPARED_MAILBOX_FIELDS = STORED_MAILBOX_FIELDS.filter(field => field !== 'path');
|
|
23
27
|
|
|
28
|
+
/**
|
|
29
|
+
* Does a configured selector pick out this listed folder? Account `path` entries and
|
|
30
|
+
* `subconnections` entries are stored exactly as the API received them and are either a folder
|
|
31
|
+
* path or a special-use token like "\Sent". Tokens are matched literally - they are a fixed
|
|
32
|
+
* vocabulary the server never spells differently - while paths go through samePath().
|
|
33
|
+
*
|
|
34
|
+
* @param {String} configuredPath - One entry of an account's `path` or `subconnections`
|
|
35
|
+
* @param {Object} entry - Mailbox entry from the server listing
|
|
36
|
+
* @returns {Boolean} True when the selector picks out this folder
|
|
37
|
+
*/
|
|
38
|
+
function matchesListingEntry(configuredPath, entry) {
|
|
39
|
+
// The token compare is guarded on the token existing: most folders carry no special use, and
|
|
40
|
+
// an undefined configured entry must not match an undefined specialUse
|
|
41
|
+
return samePath(configuredPath, entry.path) || (!!entry.specialUse && configuredPath === entry.specialUse);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Index of the first configured selector that picks out this folder, or -1. The position is what
|
|
46
|
+
* orders the candidates for the folder the primary connection watches, so the lowest-numbered
|
|
47
|
+
* selector wins.
|
|
48
|
+
*
|
|
49
|
+
* @param {Array} configuredPaths - An account's `path` list
|
|
50
|
+
* @param {Object} entry - Mailbox entry from the server listing
|
|
51
|
+
* @returns {Number} Index into configuredPaths, or -1 when the folder is not selected
|
|
52
|
+
*/
|
|
53
|
+
function configuredPathIndex(configuredPaths, entry) {
|
|
54
|
+
return configuredPaths.findIndex(configuredPath => matchesListingEntry(configuredPath, entry));
|
|
55
|
+
}
|
|
56
|
+
|
|
24
57
|
/**
|
|
25
58
|
* Decodes one msgpack-encoded entry of the stored mailbox listing hash, or returns false if the
|
|
26
59
|
* value is unusable. Callers drop a false entry rather than failing: a single corrupt value must
|
|
@@ -83,11 +116,15 @@ function decodeStoredListing(storedListing) {
|
|
|
83
116
|
*
|
|
84
117
|
* @param {Array} listing - Mailbox entries from the server (already filtered of \Noselect)
|
|
85
118
|
* @param {Array} storedListing - Decoded entries previously persisted for this account
|
|
86
|
-
* @returns {Object} { hasChanges, deletedEntries } - deletedEntries are
|
|
87
|
-
* server no longer lists, whose message index the caller must
|
|
119
|
+
* @returns {Object} { hasChanges, hasChangesBesidesNew, deletedEntries } - deletedEntries are
|
|
120
|
+
* stored folders the server no longer lists, whose message index the caller must
|
|
121
|
+
* clear. The second flag is for the caller that defers the folders that appeared
|
|
122
|
+
* (see IMAPClient.getCurrentListing): without it, a pass whose only change was a
|
|
123
|
+
* deferred folder still rewrites the whole listing hash with what it just read
|
|
88
124
|
*/
|
|
89
125
|
function diffMailboxListing(listing, storedListing) {
|
|
90
126
|
let hasChanges = false;
|
|
127
|
+
let hasChangesBesidesNew = false;
|
|
91
128
|
|
|
92
129
|
// Map for O(1) lookups - a linear scan per folder is quadratic on accounts with thousands
|
|
93
130
|
// of folders, which is common on shared/public namespaces.
|
|
@@ -113,6 +150,7 @@ function diffMailboxListing(listing, storedListing) {
|
|
|
113
150
|
for (let field of COMPARED_MAILBOX_FIELDS) {
|
|
114
151
|
if (existingMailbox[field] !== mailbox[field]) {
|
|
115
152
|
hasChanges = true;
|
|
153
|
+
hasChangesBesidesNew = true;
|
|
116
154
|
break;
|
|
117
155
|
}
|
|
118
156
|
}
|
|
@@ -124,9 +162,10 @@ function diffMailboxListing(listing, storedListing) {
|
|
|
124
162
|
const deletedEntries = storedListing.filter(entry => !listingPathSet.has(normalizePath(entry.path)));
|
|
125
163
|
if (deletedEntries.length) {
|
|
126
164
|
hasChanges = true;
|
|
165
|
+
hasChangesBesidesNew = true;
|
|
127
166
|
}
|
|
128
167
|
|
|
129
|
-
return { hasChanges, deletedEntries };
|
|
168
|
+
return { hasChanges, hasChangesBesidesNew, deletedEntries };
|
|
130
169
|
}
|
|
131
170
|
|
|
132
171
|
/**
|
|
@@ -158,6 +197,8 @@ function buildStoredListingObject(listing) {
|
|
|
158
197
|
}
|
|
159
198
|
|
|
160
199
|
module.exports = {
|
|
200
|
+
matchesListingEntry,
|
|
201
|
+
configuredPathIndex,
|
|
161
202
|
decodeStoredMailboxEntry,
|
|
162
203
|
decodeStoredListing,
|
|
163
204
|
diffMailboxListing,
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// What an IMAP server's answer to a login means. ImapFlow flags every failed AUTHENTICATE or LOGIN
|
|
4
|
+
// as `authenticationFailed`, which is the fact of what happened; whether the credential was refused
|
|
5
|
+
// or the server could not serve the login right now is decided here, the way
|
|
6
|
+
// lib/email-client/credential-errors.js decides it for a token endpoint. Reporting a backend outage
|
|
7
|
+
// as `authenticationError` puts the account in an error state that re-authorizing cannot clear, and
|
|
8
|
+
// the login that follows the outage then contradicts it with `authenticationSuccess`.
|
|
9
|
+
//
|
|
10
|
+
// Dependency-free on purpose: subconnection.js consults it, and the pure subconnection tests would
|
|
11
|
+
// otherwise inherit the Redis connections lib/tools.js opens at load and never exit.
|
|
12
|
+
|
|
13
|
+
// The RFC 5530 codes a server puts on a NO when the failure is its own and temporary: a subsystem
|
|
14
|
+
// the login depends on is down, the server tripped over itself, or a limit was hit.
|
|
15
|
+
// AUTHENTICATIONFAILED, AUTHORIZATIONFAILED, EXPIRED and PRIVACYREQUIRED are the verdicts on the
|
|
16
|
+
// credential
|
|
17
|
+
const TRANSIENT_RESPONSE_CODES = new Set(['UNAVAILABLE', 'SERVERBUG', 'INUSE', 'LIMIT']);
|
|
18
|
+
|
|
19
|
+
// The same meaning carried by text alone. Exchange Online sends no response code, and "User is
|
|
20
|
+
// authenticated but not connected." is its front end saying the token was accepted but the
|
|
21
|
+
// mailbox's backend could not be reached - a failover, a mailbox move, a throttled backend. It says
|
|
22
|
+
// the same thing permanently when IMAP is disabled for the mailbox, which is why a match is
|
|
23
|
+
// reported as a connection failure carrying the text rather than dropped
|
|
24
|
+
const TRANSIENT_RESPONSE_TEXT = /user is authenticated but not connected/i;
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* The readable text of a failed IMAP command. ImapFlow rewrites err.response into the response line
|
|
28
|
+
* for a login failure and leaves the parsed response object there for any other command, so the
|
|
29
|
+
* text field is the fallback - a stored error state or webhook payload built off the object would
|
|
30
|
+
* render as "[object Object]"
|
|
31
|
+
* @param {Error} err - The error ImapFlow threw
|
|
32
|
+
* @returns {string|undefined} The response line or its text, when there is one
|
|
33
|
+
*/
|
|
34
|
+
function imapResponseText(err) {
|
|
35
|
+
return (typeof err?.response === 'string' && err.response) || err?.responseText;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Whether a failed IMAP login is the server refusing the credential, as opposed to being unable to
|
|
40
|
+
* serve the login right now
|
|
41
|
+
* @param {Error} err - The error a login attempt threw
|
|
42
|
+
* @returns {boolean} True when the server rejected the credential
|
|
43
|
+
*/
|
|
44
|
+
function isRefusedImapLogin(err) {
|
|
45
|
+
if (!err || !err.authenticationFailed || TRANSIENT_RESPONSE_CODES.has(err.serverResponseCode)) {
|
|
46
|
+
return false;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
return !TRANSIENT_RESPONSE_TEXT.test(imapResponseText(err) || '');
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
module.exports = { imapResponseText, isRefusedImapLogin };
|