emailengine-app 2.87.1 → 2.88.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 +31 -0
- package/ENVIRONMENT.md +26 -23
- package/LICENSE_EMAILENGINE.txt +20 -12
- package/app.json +3 -3
- package/bin/emailengine.js +7 -11
- package/data/google-crawlers.json +1 -1
- package/data/public_suffix_list.dat +48 -10
- package/lib/account.js +69 -49
- package/lib/admin-password.js +85 -0
- package/lib/api-routes/license-routes.js +9 -0
- package/lib/api-token-auth.js +21 -5
- package/lib/calendar-event.js +15 -3
- package/lib/consts.js +5 -0
- package/lib/db.js +1 -0
- package/lib/dbsc/index.js +292 -0
- package/lib/dbsc/jwt.js +157 -0
- package/lib/dbsc/protocol.js +132 -0
- package/lib/dbsc/store.js +136 -0
- package/lib/email-client/base-client.js +36 -15
- package/lib/email-client/gmail-client.js +20 -6
- package/lib/email-client/imap/connection-errors.js +30 -1
- package/lib/email-client/imap/session-expiry.js +83 -0
- package/lib/email-client/imap-client.js +12 -2
- package/lib/email-client/smtp-pool-manager.js +66 -8
- package/lib/export.js +147 -22
- package/lib/graph-notifications.js +60 -0
- package/lib/imap-proxy-auth.js +52 -18
- package/lib/imapproxy/imap-core/lib/commands/id.js +4 -2
- package/lib/imapproxy/imap-core/lib/imap-command.js +44 -4
- package/lib/imapproxy/imap-server.js +10 -1
- package/lib/imapproxy/proxy-handoff.js +100 -5
- package/lib/license-subscription.js +238 -0
- package/lib/oauth/gmail.js +18 -0
- package/lib/oauth/outlook-identity.js +54 -12
- package/lib/prepared-password.js +38 -0
- package/lib/privileged-settings.js +6 -0
- package/lib/queue-browser/index.js +6 -6
- package/lib/queue-job-actions.js +59 -4
- package/lib/read-env-value.js +46 -21
- package/lib/redis-url.js +23 -0
- package/lib/response-stream.js +69 -1
- package/lib/revocation-events.js +79 -0
- package/lib/routes-ui.js +4 -1
- package/lib/schemas.js +26 -2
- package/lib/session-default.js +13 -3
- package/lib/settings.js +47 -24
- package/lib/sso.js +23 -0
- package/lib/submit-penalty.js +24 -0
- package/lib/submit-processor.js +10 -2
- package/lib/tokens.js +6 -0
- package/lib/tools.js +86 -15
- package/lib/ui-routes/admin-config-routes.js +30 -281
- package/lib/ui-routes/auth-routes.js +17 -64
- package/lib/ui-routes/dbsc-routes.js +43 -0
- package/lib/ui-routes/license-routes.js +326 -0
- package/lib/web-safe-html.js +29 -0
- package/lib/webhook-delivery.js +21 -20
- package/lib/webhook-penalty.js +18 -17
- package/lib/webhooks.js +18 -0
- package/package.json +18 -18
- package/sbom.json +294 -294
- package/scan.js +2 -0
- package/server.js +253 -80
- package/static/css/flyonui.css +2 -2
- package/static/js/ui.js +11 -4
- package/static/licenses.html +27 -27
- package/translations/messages.pot +17 -17
- package/views/config/license.hbs +43 -16
- package/views/config/security.hbs +37 -0
- package/views/partials/side_menu.hbs +1 -1
- package/workers/api.js +128 -109
- package/workers/imap.js +4 -6
package/lib/dbsc/jwt.js
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// Verifies the proofs a browser sends for a device-bound admin session (DBSC, see lib/dbsc/): a
|
|
4
|
+
// compact JWS with `typ: dbsc+jwt`, signed by the key pair the browser created for the session.
|
|
5
|
+
// Pure, and built on Node's own crypto only (no JOSE dependency, see "Pure JavaScript only").
|
|
6
|
+
//
|
|
7
|
+
// What Chrome sends, observed against Chrome 156 on 2026-11-05 and matching the spec's normative
|
|
8
|
+
// list (§9.10, which drops the `aud` and `iat` of one of its own examples):
|
|
9
|
+
// registration: header { alg, typ: 'dbsc+jwt', jwk }, payload { jti, authorization? }
|
|
10
|
+
// refresh: header { alg, typ: 'dbsc+jwt' }, payload { jti }
|
|
11
|
+
// `jti` is the challenge the server issued. Nothing else in the payload is relied on.
|
|
12
|
+
|
|
13
|
+
const crypto = require('crypto');
|
|
14
|
+
|
|
15
|
+
// RS256 and ES256 are what the spec lists besides `none`, which binds the session to nothing and
|
|
16
|
+
// is refused outright
|
|
17
|
+
const ALGORITHMS = Object.freeze(['ES256', 'RS256']);
|
|
18
|
+
|
|
19
|
+
// A proof is a few hundred bytes; anything far larger is not one, and is refused before parsing
|
|
20
|
+
const MAX_PROOF_LENGTH = 8 * 1024;
|
|
21
|
+
|
|
22
|
+
const MIN_RSA_BITS = 2048;
|
|
23
|
+
|
|
24
|
+
const BASE64URL = /^[A-Za-z0-9_-]+$/;
|
|
25
|
+
|
|
26
|
+
function proofError(message) {
|
|
27
|
+
const err = new Error(message);
|
|
28
|
+
err.code = 'DbscInvalidProof';
|
|
29
|
+
err.statusCode = 400;
|
|
30
|
+
return err;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function decodeSegment(segment, what) {
|
|
34
|
+
try {
|
|
35
|
+
const value = BASE64URL.test(segment) && JSON.parse(Buffer.from(segment, 'base64url').toString('utf8'));
|
|
36
|
+
if (value && typeof value === 'object' && !Array.isArray(value)) {
|
|
37
|
+
return value;
|
|
38
|
+
}
|
|
39
|
+
} catch (err) {
|
|
40
|
+
// reported below like any other malformed segment
|
|
41
|
+
}
|
|
42
|
+
throw proofError(`Malformed proof ${what}`);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Splits a compact JWS and decodes its header and payload, without checking the signature
|
|
47
|
+
* @param {string} token
|
|
48
|
+
* @returns {{ header: Object, payload: Object, signingInput: Buffer, signature: Buffer }}
|
|
49
|
+
*/
|
|
50
|
+
function parseProof(token) {
|
|
51
|
+
if (typeof token !== 'string' || !token || token.length > MAX_PROOF_LENGTH) {
|
|
52
|
+
throw proofError('Missing or oversized proof');
|
|
53
|
+
}
|
|
54
|
+
const parts = token.split('.');
|
|
55
|
+
if (parts.length !== 3 || !BASE64URL.test(parts[2])) {
|
|
56
|
+
throw proofError('Malformed proof');
|
|
57
|
+
}
|
|
58
|
+
const header = decodeSegment(parts[0], 'header');
|
|
59
|
+
const payload = decodeSegment(parts[1], 'payload');
|
|
60
|
+
|
|
61
|
+
if (header.typ !== 'dbsc+jwt') {
|
|
62
|
+
throw proofError('Not a DBSC proof');
|
|
63
|
+
}
|
|
64
|
+
if (!ALGORITHMS.includes(header.alg)) {
|
|
65
|
+
throw proofError('Unsupported proof algorithm');
|
|
66
|
+
}
|
|
67
|
+
if (typeof payload.jti !== 'string' || !payload.jti) {
|
|
68
|
+
throw proofError('Proof carries no challenge');
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
return {
|
|
72
|
+
header,
|
|
73
|
+
payload,
|
|
74
|
+
signingInput: Buffer.from(`${parts[0]}.${parts[1]}`),
|
|
75
|
+
signature: Buffer.from(parts[2], 'base64url')
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Reduces a JWK to the public members of the type the algorithm needs, so a stored key can never
|
|
81
|
+
* carry a private member or an unrelated field from the browser
|
|
82
|
+
* @param {string} alg - ES256 or RS256
|
|
83
|
+
* @param {Object} jwk
|
|
84
|
+
* @returns {Object} the public JWK
|
|
85
|
+
*/
|
|
86
|
+
function publicJwkFor(alg, jwk) {
|
|
87
|
+
if (!jwk || typeof jwk !== 'object' || Array.isArray(jwk)) {
|
|
88
|
+
throw proofError('Proof carries no key');
|
|
89
|
+
}
|
|
90
|
+
if (alg === 'ES256') {
|
|
91
|
+
if (jwk.kty !== 'EC' || jwk.crv !== 'P-256' || typeof jwk.x !== 'string' || typeof jwk.y !== 'string') {
|
|
92
|
+
throw proofError('Proof key does not match its algorithm');
|
|
93
|
+
}
|
|
94
|
+
return { kty: 'EC', crv: 'P-256', x: jwk.x, y: jwk.y };
|
|
95
|
+
}
|
|
96
|
+
if (jwk.kty !== 'RSA' || typeof jwk.n !== 'string' || typeof jwk.e !== 'string') {
|
|
97
|
+
throw proofError('Proof key does not match its algorithm');
|
|
98
|
+
}
|
|
99
|
+
return { kty: 'RSA', n: jwk.n, e: jwk.e };
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function importKey(alg, jwk) {
|
|
103
|
+
let key;
|
|
104
|
+
try {
|
|
105
|
+
key = crypto.createPublicKey({ key: jwk, format: 'jwk' });
|
|
106
|
+
} catch (err) {
|
|
107
|
+
throw proofError('Proof key is not usable');
|
|
108
|
+
}
|
|
109
|
+
if (alg === 'RS256' && key.asymmetricKeyDetails.modulusLength < MIN_RSA_BITS) {
|
|
110
|
+
throw proofError('Proof key is too short');
|
|
111
|
+
}
|
|
112
|
+
return key;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function signatureValid(alg, key, signingInput, signature) {
|
|
116
|
+
if (alg === 'ES256') {
|
|
117
|
+
// JWS carries the raw r||s pair, 32 bytes each, not the DER form Node defaults to
|
|
118
|
+
return signature.length === 64 && crypto.verify('sha256', signingInput, { key, dsaEncoding: 'ieee-p1363' }, signature);
|
|
119
|
+
}
|
|
120
|
+
return crypto.verify('sha256', signingInput, { key, padding: crypto.constants.RSA_PKCS1_PADDING }, signature);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* Verifies the proof a browser sends to register a session: signed by the key its own header
|
|
125
|
+
* carries, which becomes the session's key
|
|
126
|
+
* @param {string} token
|
|
127
|
+
* @returns {{ alg: string, jwk: Object, jti: string, authorization: string|undefined }}
|
|
128
|
+
*/
|
|
129
|
+
function verifyRegistrationProof(token) {
|
|
130
|
+
const { header, payload, signingInput, signature } = parseProof(token);
|
|
131
|
+
const jwk = publicJwkFor(header.alg, header.jwk);
|
|
132
|
+
if (!signatureValid(header.alg, importKey(header.alg, jwk), signingInput, signature)) {
|
|
133
|
+
throw proofError('Proof signature does not verify');
|
|
134
|
+
}
|
|
135
|
+
return { alg: header.alg, jwk, jti: payload.jti, authorization: typeof payload.authorization === 'string' ? payload.authorization : undefined };
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* Verifies a refresh proof against the key stored when the session registered. A key in the
|
|
140
|
+
* proof's own header is ignored: the spec forbids one on refresh, and honouring it would let any
|
|
141
|
+
* key sign for the session
|
|
142
|
+
* @param {string} token
|
|
143
|
+
* @param {{ alg: string, jwk: Object }} binding - what registration stored
|
|
144
|
+
* @returns {{ jti: string }}
|
|
145
|
+
*/
|
|
146
|
+
function verifyRefreshProof(token, binding) {
|
|
147
|
+
const { header, payload, signingInput, signature } = parseProof(token);
|
|
148
|
+
if (header.alg !== binding.alg) {
|
|
149
|
+
throw proofError('Proof algorithm does not match the session');
|
|
150
|
+
}
|
|
151
|
+
if (!signatureValid(binding.alg, importKey(binding.alg, publicJwkFor(binding.alg, binding.jwk)), signingInput, signature)) {
|
|
152
|
+
throw proofError('Proof signature does not verify');
|
|
153
|
+
}
|
|
154
|
+
return { jti: payload.jti };
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
module.exports = { verifyRegistrationProof, verifyRefreshProof, ALGORITHMS, MAX_PROOF_LENGTH };
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// The wire format of device-bound admin sessions (DBSC): the headers EmailEngine sends and reads,
|
|
4
|
+
// the short-lived cookie that carries the binding, and the registration answer. Pure.
|
|
5
|
+
//
|
|
6
|
+
// Chrome sends `Secure-Session-Response` and `Sec-Secure-Session-Id` as bare values although the
|
|
7
|
+
// spec declares them structured-field strings (quoted); both spellings are read. The challenge
|
|
8
|
+
// header carries the `id` parameter the spec requires, without which the browser does not cache
|
|
9
|
+
// the challenge and signs the next proof with a stale one.
|
|
10
|
+
|
|
11
|
+
const { ALGORITHMS } = require('./jwt');
|
|
12
|
+
|
|
13
|
+
// The paths the registration header and the registration answer name
|
|
14
|
+
const REGISTRATION_PATH = '/admin/dbsc/start';
|
|
15
|
+
const REFRESH_PATH = '/admin/dbsc/refresh';
|
|
16
|
+
|
|
17
|
+
// The cookie that proves a request came from the browser holding the session key. Short-lived on
|
|
18
|
+
// purpose: a stolen copy is useless once it runs out, and only the key can mint the next one
|
|
19
|
+
const BOUND_COOKIE = 'eeb';
|
|
20
|
+
const BOUND_COOKIE_TTL = 10 * 60 * 1000;
|
|
21
|
+
|
|
22
|
+
// Challenges are base64url, which is safe inside a structured-field string without escaping
|
|
23
|
+
const SF_TOKEN = /^[A-Za-z0-9_.~+/=-]+$/;
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Reads a header the spec declares a structured-field string, accepting the bare form Chrome sends
|
|
27
|
+
* @param {string|undefined} value
|
|
28
|
+
* @returns {string|null} the string, or null when the header is absent or malformed
|
|
29
|
+
*/
|
|
30
|
+
function readSfString(value) {
|
|
31
|
+
if (typeof value !== 'string') {
|
|
32
|
+
return null;
|
|
33
|
+
}
|
|
34
|
+
let text = value.trim();
|
|
35
|
+
if (text.length >= 2 && text.startsWith('"') && text.endsWith('"')) {
|
|
36
|
+
text = text.slice(1, -1);
|
|
37
|
+
}
|
|
38
|
+
return text && SF_TOKEN.test(text) ? text : null;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* @param {string} challenge
|
|
43
|
+
* @returns {string} the Secure-Session-Registration value offering the algorithms jwt.js verifies
|
|
44
|
+
*/
|
|
45
|
+
function registrationHeader(challenge) {
|
|
46
|
+
return `(${ALGORITHMS.join(' ')});path="${REGISTRATION_PATH}";challenge="${challenge}"`;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* @param {string} challenge
|
|
51
|
+
* @param {string} sessionId - the session_identifier the browser registered under
|
|
52
|
+
* @returns {string} the Secure-Session-Challenge value
|
|
53
|
+
*/
|
|
54
|
+
function challengeHeader(challenge, sessionId) {
|
|
55
|
+
return `"${challenge}";id="${sessionId}"`;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* The bound cookie's settings, as hapi's server.state() takes them and as the attributes string the
|
|
60
|
+
* registration answer names. One source for both, because the browser compares the cookie it is
|
|
61
|
+
* sent against the attributes it registered (Domain, Path, Secure, HttpOnly, SameSite) and ignores
|
|
62
|
+
* a refresh that sets anything else
|
|
63
|
+
* @param {Object} opts
|
|
64
|
+
* @param {boolean} opts.secure - whether the admin cookies are marked Secure (an https serviceUrl)
|
|
65
|
+
* @param {string} opts.password - the iron sealing password (cookiePassword)
|
|
66
|
+
* @returns {{ state: Object, attributes: string }}
|
|
67
|
+
*/
|
|
68
|
+
function boundCookieSpec({ secure, password }) {
|
|
69
|
+
return {
|
|
70
|
+
state: {
|
|
71
|
+
ttl: BOUND_COOKIE_TTL,
|
|
72
|
+
encoding: 'iron',
|
|
73
|
+
password,
|
|
74
|
+
path: '/',
|
|
75
|
+
isSecure: !!secure,
|
|
76
|
+
isHttpOnly: true,
|
|
77
|
+
isSameSite: 'Lax',
|
|
78
|
+
clearInvalid: true,
|
|
79
|
+
ignoreErrors: true
|
|
80
|
+
},
|
|
81
|
+
attributes: ['Path=/', 'HttpOnly', 'SameSite=Lax'].concat(secure ? ['Secure'] : []).join('; ')
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* The JSON answer to a registration. The scope names no origin, so it defaults to the origin the
|
|
87
|
+
* browser registered on: an operator reaching the admin UI on a name other than the Service URL's
|
|
88
|
+
* would otherwise be told about a different site and the browser would drop the session
|
|
89
|
+
* @param {Object} opts
|
|
90
|
+
* @param {string} opts.sessionId
|
|
91
|
+
* @param {string} opts.attributes - from boundCookieSpec()
|
|
92
|
+
* @returns {Object}
|
|
93
|
+
*/
|
|
94
|
+
function registrationAnswer({ sessionId, attributes }) {
|
|
95
|
+
return {
|
|
96
|
+
session_identifier: sessionId,
|
|
97
|
+
refresh_url: REFRESH_PATH,
|
|
98
|
+
scope: {
|
|
99
|
+
include_site: false,
|
|
100
|
+
// Nothing under these carries the session, so there is nothing to refresh for
|
|
101
|
+
scope_specification: [
|
|
102
|
+
{ type: 'exclude', domain: '*', path: '/static' },
|
|
103
|
+
{ type: 'exclude', domain: '*', path: '/.well-known' }
|
|
104
|
+
]
|
|
105
|
+
},
|
|
106
|
+
credentials: [{ type: 'cookie', name: BOUND_COOKIE, attributes }]
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Whether a decoded bound cookie vouches for this session right now
|
|
112
|
+
* @param {Object|undefined} cookie - request.state.eeb
|
|
113
|
+
* @param {string} sid - the admin session's sid
|
|
114
|
+
* @param {number} [now]
|
|
115
|
+
* @returns {boolean}
|
|
116
|
+
*/
|
|
117
|
+
function boundCookieValid(cookie, sid, now = Date.now()) {
|
|
118
|
+
return !!(cookie && sid && cookie.sid === sid && Number(cookie.exp) > now);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
module.exports = {
|
|
122
|
+
REGISTRATION_PATH,
|
|
123
|
+
REFRESH_PATH,
|
|
124
|
+
BOUND_COOKIE,
|
|
125
|
+
BOUND_COOKIE_TTL,
|
|
126
|
+
readSfString,
|
|
127
|
+
registrationHeader,
|
|
128
|
+
challengeHeader,
|
|
129
|
+
boundCookieSpec,
|
|
130
|
+
registrationAnswer,
|
|
131
|
+
boundCookieValid
|
|
132
|
+
};
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// What the server remembers about device-bound admin sessions, in Redis so every API worker sees
|
|
4
|
+
// the same state:
|
|
5
|
+
//
|
|
6
|
+
// dbsc:b:{sid} the binding: the session key the browser registered (JSON), for as long as the
|
|
7
|
+
// admin session itself can live. Its existence is what makes the session bound,
|
|
8
|
+
// and it is never deleted, not on a refusal and not on logout (which marks it
|
|
9
|
+
// `ended`): a session cookie whose binding was removed would read as unbound and
|
|
10
|
+
// be accepted on its own again
|
|
11
|
+
// dbsc:c:{value} a challenge, single use and short-lived, naming the sid and step it was minted
|
|
12
|
+
// for, so a proof signed over one session's challenge cannot serve another
|
|
13
|
+
// dbsc:o:{sid} an offer throttle, so a browser that cannot bind (or will not) is asked about
|
|
14
|
+
// once a minute rather than on every page
|
|
15
|
+
// dbsc:f:{sid} failed refresh proofs, so a browser stuck on a bad key is told to stop rather
|
|
16
|
+
// than retried for ever (the spec puts no bound on its 403 loop)
|
|
17
|
+
|
|
18
|
+
const crypto = require('crypto');
|
|
19
|
+
|
|
20
|
+
const { REDIS_PREFIX } = require('../consts');
|
|
21
|
+
const { incrementCounter } = require('../rate-limit');
|
|
22
|
+
|
|
23
|
+
const CHALLENGE_TTL = 120;
|
|
24
|
+
const OFFER_INTERVAL = 60;
|
|
25
|
+
const FAILURE_WINDOW = 300;
|
|
26
|
+
const MAX_REFRESH_FAILURES = 3;
|
|
27
|
+
|
|
28
|
+
const bindingKey = sid => `${REDIS_PREFIX}dbsc:b:${sid}`;
|
|
29
|
+
const challengeKey = challenge => `${REDIS_PREFIX}dbsc:c:${challenge}`;
|
|
30
|
+
const offerKey = sid => `${REDIS_PREFIX}dbsc:o:${sid}`;
|
|
31
|
+
const failureKey = sid => `${REDIS_PREFIX}dbsc:f:${sid}`;
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* @param {Object} redis - ioredis client
|
|
35
|
+
*/
|
|
36
|
+
function createDbscStore(redis) {
|
|
37
|
+
return {
|
|
38
|
+
/**
|
|
39
|
+
* Claims the right to offer registration to a session, at most once per OFFER_INTERVAL
|
|
40
|
+
* @param {string} sid
|
|
41
|
+
* @returns {Promise<boolean>}
|
|
42
|
+
*/
|
|
43
|
+
async claimOffer(sid) {
|
|
44
|
+
return (await redis.set(offerKey(sid), '1', 'EX', OFFER_INTERVAL, 'NX')) === 'OK';
|
|
45
|
+
},
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* @param {string} sid
|
|
49
|
+
* @param {'register'|'refresh'} purpose
|
|
50
|
+
* @returns {Promise<string>} a new challenge
|
|
51
|
+
*/
|
|
52
|
+
async mintChallenge(sid, purpose) {
|
|
53
|
+
const challenge = crypto.randomBytes(24).toString('base64url');
|
|
54
|
+
await redis.set(challengeKey(challenge), JSON.stringify({ sid, purpose }), 'EX', CHALLENGE_TTL);
|
|
55
|
+
return challenge;
|
|
56
|
+
},
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Spends a challenge. Answers true only for one minted for this session and step
|
|
60
|
+
* @param {string} challenge
|
|
61
|
+
* @param {string} sid
|
|
62
|
+
* @param {'register'|'refresh'} purpose
|
|
63
|
+
* @returns {Promise<boolean>}
|
|
64
|
+
*/
|
|
65
|
+
async consumeChallenge(challenge, sid, purpose) {
|
|
66
|
+
const stored = await redis.getdel(challengeKey(challenge));
|
|
67
|
+
if (!stored) {
|
|
68
|
+
return false;
|
|
69
|
+
}
|
|
70
|
+
try {
|
|
71
|
+
const parsed = JSON.parse(stored);
|
|
72
|
+
return parsed.sid === sid && parsed.purpose === purpose;
|
|
73
|
+
} catch (err) {
|
|
74
|
+
return false;
|
|
75
|
+
}
|
|
76
|
+
},
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Stores a session's key unless the session already has one: a session is bound once, so a
|
|
80
|
+
* stolen session cookie cannot be re-bound to a key of the thief's
|
|
81
|
+
* @param {string} sid
|
|
82
|
+
* @param {Object} binding - { id, alg, jwk }
|
|
83
|
+
* @param {number} ttlSeconds - the admin session's remaining life
|
|
84
|
+
* @returns {Promise<boolean>} false when the session was already bound
|
|
85
|
+
*/
|
|
86
|
+
async bind(sid, binding, ttlSeconds) {
|
|
87
|
+
const value = JSON.stringify(Object.assign({}, binding, { created: Date.now() }));
|
|
88
|
+
return (await redis.set(bindingKey(sid), value, 'EX', Math.max(1, Math.ceil(ttlSeconds)), 'NX')) === 'OK';
|
|
89
|
+
},
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* @param {string} sid
|
|
93
|
+
* @returns {Promise<Object|null>}
|
|
94
|
+
*/
|
|
95
|
+
async getBinding(sid) {
|
|
96
|
+
const stored = await redis.get(bindingKey(sid));
|
|
97
|
+
if (!stored) {
|
|
98
|
+
return null;
|
|
99
|
+
}
|
|
100
|
+
try {
|
|
101
|
+
return JSON.parse(stored);
|
|
102
|
+
} catch (err) {
|
|
103
|
+
return null;
|
|
104
|
+
}
|
|
105
|
+
},
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Ends a binding with its session (logout) by marking it, never by deleting it: the key is
|
|
109
|
+
* what keeps a copied session cookie refused, so it stays for the session's remaining life
|
|
110
|
+
* and no key can be bound to that session again
|
|
111
|
+
* @param {string} sid
|
|
112
|
+
*/
|
|
113
|
+
async endBinding(sid) {
|
|
114
|
+
const binding = await this.getBinding(sid);
|
|
115
|
+
if (binding && !binding.ended) {
|
|
116
|
+
await redis.set(bindingKey(sid), JSON.stringify(Object.assign(binding, { ended: Date.now() })), 'XX', 'KEEPTTL');
|
|
117
|
+
}
|
|
118
|
+
await redis.del(offerKey(sid), failureKey(sid));
|
|
119
|
+
},
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Counts a failed refresh proof
|
|
123
|
+
* @param {string} sid
|
|
124
|
+
* @returns {Promise<boolean>} true while the session may still be asked again
|
|
125
|
+
*/
|
|
126
|
+
async recordRefreshFailure(sid) {
|
|
127
|
+
return (await incrementCounter(failureKey(sid), 1, FAILURE_WINDOW)) <= MAX_REFRESH_FAILURES;
|
|
128
|
+
},
|
|
129
|
+
|
|
130
|
+
async clearRefreshFailures(sid) {
|
|
131
|
+
await redis.del(failureKey(sid));
|
|
132
|
+
}
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
module.exports = { createDbscStore, MAX_REFRESH_FAILURES, bindingKey, offerKey, failureKey };
|
|
@@ -5,6 +5,7 @@ const { threadId: workerThreadId } = require('worker_threads');
|
|
|
5
5
|
const crypto = require('crypto');
|
|
6
6
|
const logger = require('../logger');
|
|
7
7
|
const settings = require('../settings');
|
|
8
|
+
const { publishRevocation } = require('../revocation-events');
|
|
8
9
|
const msgpack = require('../msgpack');
|
|
9
10
|
const { templates } = require('../templates');
|
|
10
11
|
const { Gateway } = require('../gateway');
|
|
@@ -31,6 +32,7 @@ const { createTransaction } = require('../redis-operations');
|
|
|
31
32
|
const { ACCOUNT_STATES } = require('../account/account-state');
|
|
32
33
|
const { credentialErrorStatus, isTransientCredentialError, resolveAuthServerCredentials } = require('./credential-errors');
|
|
33
34
|
const { isTransientRedisError } = require('../utils/redis-errors');
|
|
35
|
+
const { minTokenValidity } = require('./imap/session-expiry');
|
|
34
36
|
const { parseMessage } = require('../parse-message');
|
|
35
37
|
const libmime = require('libmime');
|
|
36
38
|
const { bounceDetect, applyDeliveryReport, PARSER_OPTIONS: DSN_PARSER_OPTIONS } = require('../bounce-detect');
|
|
@@ -52,7 +54,10 @@ const {
|
|
|
52
54
|
SentMailCopyDecider
|
|
53
55
|
} = require('./message-builder');
|
|
54
56
|
const { NotificationHandler, postMetrics } = require('./notification-handler');
|
|
55
|
-
const {
|
|
57
|
+
const { sendWithDeadline } = require('./smtp-pool-manager');
|
|
58
|
+
const { submitPenaltyKey, SUBMIT_PENALTY_MS } = require('../submit-penalty');
|
|
59
|
+
const { setPenalty } = require('../queue-job-actions');
|
|
60
|
+
const { isPermanentDeliveryError } = require('../delivery-error');
|
|
56
61
|
|
|
57
62
|
// Import various utility functions and constants
|
|
58
63
|
const {
|
|
@@ -1332,6 +1337,9 @@ class BaseClient {
|
|
|
1332
1337
|
return false;
|
|
1333
1338
|
}
|
|
1334
1339
|
|
|
1340
|
+
// Proxied IMAP sessions of the account end now rather than at their next periodic re-check
|
|
1341
|
+
await publishRevocation({ type: 'account', account: this.account });
|
|
1342
|
+
|
|
1335
1343
|
this.logger.warn({
|
|
1336
1344
|
msg: AUTH_FAILURE_DISABLED_DESCRIPTION,
|
|
1337
1345
|
errorEvent: event,
|
|
@@ -1389,7 +1397,8 @@ class BaseClient {
|
|
|
1389
1397
|
* @param {Object} accountData - Account configuration data
|
|
1390
1398
|
* @param {Object} ctx - Context object (usually 'this')
|
|
1391
1399
|
* @param {string} target - Target service ('imap' or 'smtp')
|
|
1392
|
-
* @returns {Object} OAuth2 credentials including access token
|
|
1400
|
+
* @returns {Object} OAuth2 credentials including the access token and its `expires` (unknown, so
|
|
1401
|
+
* absent, when an authentication server supplied the token)
|
|
1393
1402
|
*/
|
|
1394
1403
|
async loadOAuth2LoginCredentials(accountObject, accountData, ctx, target) {
|
|
1395
1404
|
const now = Date.now();
|
|
@@ -1428,14 +1437,20 @@ class BaseClient {
|
|
|
1428
1437
|
};
|
|
1429
1438
|
}
|
|
1430
1439
|
|
|
1431
|
-
// Check if token needs refresh
|
|
1432
|
-
|
|
1440
|
+
// Check if the token needs a refresh. Usually it has to be valid for 30 more seconds, but an
|
|
1441
|
+
// IMAP session on a provider that ends it when the token expires lives exactly as long as the
|
|
1442
|
+
// token it logs in with, so such a login asks for more (see session-expiry.js)
|
|
1443
|
+
const minValidity = minTokenValidity(oauth2App.provider, target);
|
|
1444
|
+
if (!accountData.oauth2.accessToken || !accountData.oauth2.expires || accountData.oauth2.expires < new Date(now + minValidity)) {
|
|
1433
1445
|
// renew access token
|
|
1434
1446
|
try {
|
|
1435
|
-
accountData = await accountObject.renewAccessToken(
|
|
1436
|
-
|
|
1437
|
-
|
|
1438
|
-
|
|
1447
|
+
accountData = await accountObject.renewAccessToken(
|
|
1448
|
+
{
|
|
1449
|
+
logger: this.logger,
|
|
1450
|
+
logRaw: this.options.logRaw
|
|
1451
|
+
},
|
|
1452
|
+
{ minValidity }
|
|
1453
|
+
);
|
|
1439
1454
|
accessToken = accountData.oauth2.accessToken;
|
|
1440
1455
|
} catch (err) {
|
|
1441
1456
|
// A token endpoint that could not be reached, or that answered 429 or a 5xx, has not
|
|
@@ -1485,7 +1500,7 @@ class BaseClient {
|
|
|
1485
1500
|
});
|
|
1486
1501
|
accessToken = accountData.oauth2.accessToken;
|
|
1487
1502
|
}
|
|
1488
|
-
return { oauth2User, accessToken, oauth2App };
|
|
1503
|
+
return { oauth2User, accessToken, oauth2App, expires: accountData.oauth2.expires };
|
|
1489
1504
|
}
|
|
1490
1505
|
|
|
1491
1506
|
/**
|
|
@@ -3451,9 +3466,6 @@ class BaseClient {
|
|
|
3451
3466
|
return false;
|
|
3452
3467
|
}
|
|
3453
3468
|
|
|
3454
|
-
// Get SMTP transport from pool
|
|
3455
|
-
const transporter = getMailTransport(smtpSettings);
|
|
3456
|
-
|
|
3457
3469
|
// Only the send itself is inside this try. Once the server has accepted the message a
|
|
3458
3470
|
// failure is a bookkeeping failure: rethrowing it made the submit worker retry (and so
|
|
3459
3471
|
// deliver) an already delivered message, and reported a messageDeliveryError for it
|
|
@@ -3466,14 +3478,18 @@ class BaseClient {
|
|
|
3466
3478
|
// ignore
|
|
3467
3479
|
}
|
|
3468
3480
|
|
|
3469
|
-
// Send the message
|
|
3470
|
-
info = await
|
|
3481
|
+
// Send the message, through the pooled transport for these settings, within the deadline
|
|
3482
|
+
info = await sendWithDeadline(smtpSettings, {
|
|
3471
3483
|
envelope,
|
|
3472
3484
|
messageId,
|
|
3473
3485
|
raw: !hasBcc ? raw : await removeBcc(raw),
|
|
3474
3486
|
dsn: data.dsn || null
|
|
3475
3487
|
});
|
|
3476
3488
|
} catch (err) {
|
|
3489
|
+
if (err.deadlineExceeded) {
|
|
3490
|
+
// The account's next messages wait instead of each holding the queue as long
|
|
3491
|
+
await setPenalty(this.redis, submitPenaltyKey(this.account), SUBMIT_PENALTY_MS);
|
|
3492
|
+
}
|
|
3477
3493
|
await this.handleSubmitError(err, {
|
|
3478
3494
|
smtpSettings,
|
|
3479
3495
|
networkRouting,
|
|
@@ -3758,7 +3774,12 @@ class BaseClient {
|
|
|
3758
3774
|
* @param {Object} context - Error handling context
|
|
3759
3775
|
*/
|
|
3760
3776
|
async recordSubmitError(err, context) {
|
|
3761
|
-
const { smtpSettings, networkRouting, gatewayData, gatewayObject, data,
|
|
3777
|
+
const { smtpSettings, networkRouting, gatewayData, gatewayObject, data, queueId, envelope } = context;
|
|
3778
|
+
|
|
3779
|
+
// A permanent failure is not retried (the submit worker discards the job), so it reports no
|
|
3780
|
+
// next attempt: the job's own nextAttempt was set before the send and still names a retry
|
|
3781
|
+
// that will not happen, which hid the failure from the feedback key and the webhook
|
|
3782
|
+
const jobData = context.jobData && isPermanentDeliveryError(err) ? Object.assign({}, context.jobData, { nextAttempt: false }) : context.jobData;
|
|
3762
3783
|
|
|
3763
3784
|
// Build SMTP status from error. Only an SMTP attempt has one to report: a provider API send
|
|
3764
3785
|
// (Gmail, Graph) reaches here with no smtpSettings, and recording a status for it would
|
|
@@ -477,12 +477,26 @@ class GmailClient extends BaseClient {
|
|
|
477
477
|
});
|
|
478
478
|
|
|
479
479
|
// Ensure Pub/Sub subscription mapping is correct
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
480
|
+
const bindingKey = `${REDIS_PREFIX}oapp:h:${accountData.oauth2.provider}`;
|
|
481
|
+
const pubsubUser = accountData.oauth2.auth?.user;
|
|
482
|
+
if (pubsubUser && (await this.redis.hget(bindingKey, pubsubUser.toLowerCase())) !== this.account) {
|
|
483
|
+
try {
|
|
484
|
+
// Another live account holding the same user keeps its routing: re-setting it here on
|
|
485
|
+
// every connect let two such accounts take the notifications from each other
|
|
486
|
+
await this.accountObject.assertOAuth2UserUnbound(accountData.oauth2.provider, pubsubUser);
|
|
487
|
+
await this.redis.hset(bindingKey, pubsubUser.toLowerCase(), this.account);
|
|
488
|
+
this.logger.info({ msg: 'Re-set missing Google Pub/Sub subscription', account: this.account, emailAddress: pubsubUser });
|
|
489
|
+
} catch (err) {
|
|
490
|
+
if (err.output?.payload?.code !== 'AccountAlreadyExists') {
|
|
491
|
+
throw err;
|
|
492
|
+
}
|
|
493
|
+
this.logger.warn({
|
|
494
|
+
msg: 'Another account holds the Google Pub/Sub routing for this user',
|
|
495
|
+
account: this.account,
|
|
496
|
+
existingAccount: err.output.payload.existingAccount,
|
|
497
|
+
emailAddress: pubsubUser
|
|
498
|
+
});
|
|
499
|
+
}
|
|
486
500
|
}
|
|
487
501
|
|
|
488
502
|
if (!isSendOnly) {
|
|
@@ -11,6 +11,9 @@
|
|
|
11
11
|
// to serve a request with, which is a 503 for the caller and not something a sync retries past.
|
|
12
12
|
// All of them are 503, which is what an API path reports.
|
|
13
13
|
|
|
14
|
+
const { ImapFlowErrorCode } = require('imapflow');
|
|
15
|
+
const { CONNECTION_CLOSING_CODES } = require('../../consts');
|
|
16
|
+
|
|
14
17
|
/**
|
|
15
18
|
* There is no connection to run this on: the client was torn down and not replaced yet.
|
|
16
19
|
* @returns {Error} A connection-closing error
|
|
@@ -62,4 +65,30 @@ function syncInterrupted(imapClient, err) {
|
|
|
62
65
|
return !imapClient.usable || err?.code === 'NoMailboxSelected';
|
|
63
66
|
}
|
|
64
67
|
|
|
65
|
-
|
|
68
|
+
/**
|
|
69
|
+
* Gives a failed command's error the HTTP status the API should answer with, when the error came
|
|
70
|
+
* from ImapFlow with a code but no status of its own. Called by the IMAP worker before the error is
|
|
71
|
+
* sent back to the caller, so every surface (REST, MCP, admin UI) answers the same.
|
|
72
|
+
*
|
|
73
|
+
* - Throttled after every retry: 429, the caller should back off, the same answer a throttled
|
|
74
|
+
* Gmail or Graph request gets.
|
|
75
|
+
* - The connection went away under the command (ImapFlow's NoConnection after a server BYE, such as
|
|
76
|
+
* Exchange Online ending a session whose access token expired): 503. The account reconnects on
|
|
77
|
+
* its own, so the request can be retried; it used to be a 500, which reads as a fault.
|
|
78
|
+
*
|
|
79
|
+
* @param {Error} err - The command failure, changed in place
|
|
80
|
+
* @returns {Error} The same error
|
|
81
|
+
*/
|
|
82
|
+
function assignRelayStatus(err) {
|
|
83
|
+
if (!err || typeof err !== 'object' || err.statusCode) {
|
|
84
|
+
return err;
|
|
85
|
+
}
|
|
86
|
+
if (err.code === ImapFlowErrorCode.ETHROTTLE) {
|
|
87
|
+
err.statusCode = 429;
|
|
88
|
+
} else if (CONNECTION_CLOSING_CODES.has(err.code)) {
|
|
89
|
+
err.statusCode = 503;
|
|
90
|
+
}
|
|
91
|
+
return err;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
module.exports = { connectionNotAvailableError, connectionClosedError, connectionUnavailableError, syncInterrupted, assignRelayStatus };
|