emailengine-app 2.87.2 → 2.89.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.ncurc.js +24 -44
- package/.release-please-manifest.json +1 -1
- package/CHANGELOG.md +37 -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 +155 -16
- 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/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 +244 -0
- package/lib/node-version.js +99 -12
- package/lib/oauth/gmail.js +18 -0
- package/lib/oauth/outlook-identity.js +54 -12
- package/lib/prepared-password.js +38 -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/schemas.js +18 -2
- package/lib/settings.js +50 -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 +90 -18
- package/lib/ui-routes/admin-config-routes.js +3 -276
- package/lib/ui-routes/auth-routes.js +13 -64
- package/lib/ui-routes/dashboard-routes.js +4 -0
- package/lib/ui-routes/license-routes.js +326 -0
- package/lib/web-safe-html.js +74 -1
- package/lib/webhook-delivery.js +21 -20
- package/lib/webhook-penalty.js +18 -17
- package/lib/webhooks.js +18 -0
- package/list-generate.js +56 -19
- package/package.json +28 -31
- package/sbom.json +373 -964
- package/scan.js +2 -0
- package/server.js +273 -100
- package/static/css/flyonui.css +2 -2
- package/static/js/ui.js +11 -4
- package/static/licenses.html +1108 -504
- package/translations/messages.pot +18 -18
- package/views/config/license.hbs +43 -16
- package/views/dashboard.hbs +9 -0
- package/views/partials/side_menu.hbs +1 -1
- package/views/upgrade.hbs +25 -0
- package/workers/api.js +108 -107
- package/workers/imap.js +4 -6
- package/lib/net-tos-guard.js +0 -42
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// The admin password checks the admin UI's sign-in and step-down routes share. Split out of
|
|
4
|
+
// lib/ui-routes/auth-routes.js.
|
|
5
|
+
|
|
6
|
+
const pbkdf2 = require('./pbkdf2-phc');
|
|
7
|
+
|
|
8
|
+
// Single place that knows how a failed password check is interpreted: an absent password and a
|
|
9
|
+
// verify() that throws (which happens only on a malformed stored hash, never on a wrong password)
|
|
10
|
+
// are both failures, never a pass. Sign-in, the password change and both passkey registration
|
|
11
|
+
// steps all come through here, so a change to how the account password is checked - a KDF swap,
|
|
12
|
+
// a dummy verify to flatten timing - lands in one place.
|
|
13
|
+
async function verifyAdminPassword(hash, password, logger) {
|
|
14
|
+
if (!password) {
|
|
15
|
+
return false;
|
|
16
|
+
}
|
|
17
|
+
try {
|
|
18
|
+
return await pbkdf2.verify(hash, password);
|
|
19
|
+
} catch (err) {
|
|
20
|
+
logger.error({ msg: 'Failed to verify password hash', err });
|
|
21
|
+
return false;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
// The current-password check behind the security page's step-down actions (the password change
|
|
26
|
+
// and switching the second factor off). A live session alone is not supposed to reveal the
|
|
27
|
+
// password, and unthrottled the field let a hijacked session guess it at full speed, so the
|
|
28
|
+
// check is rate limited the way the login form is: keyed on the account rather than the address
|
|
29
|
+
// because the caller is already authenticated as it, and with the login form's per-username
|
|
30
|
+
// budget. Owns the limiter and the warn logs; the caller decides how to report the failure.
|
|
31
|
+
//
|
|
32
|
+
// @returns {Promise<{ ok: true } | { ok: false, reason: 'rateLimited' | 'invalid', message: String, statusCode: Number }>}
|
|
33
|
+
async function verifyCurrentPassword(request, h, authData, password) {
|
|
34
|
+
let rateLimit = await h.checkRateLimit(`password:verify:${authData.user || 'admin'}`, 1, 10, 60);
|
|
35
|
+
if (!rateLimit.success) {
|
|
36
|
+
request.logger.warn({ msg: 'Rate limited', rateLimit, remoteAddress: request.app.ip });
|
|
37
|
+
return { ok: false, reason: 'rateLimited', message: 'Rate limited, please wait and try again', statusCode: 429 };
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
if (!(await verifyAdminPassword(authData.password, password, request.logger))) {
|
|
41
|
+
request.logger.warn({ msg: 'Invalid current password', remoteAddress: request.app.ip });
|
|
42
|
+
return { ok: false, reason: 'invalid', message: 'Invalid password', statusCode: 403 };
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
return { ok: true };
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Replaces the admin password: stores the hash, ends every session and message-browser token by
|
|
50
|
+
* bumping passwordVersion, and removes every passkey of the user. Registering a passkey takes the
|
|
51
|
+
* password, so a passkey that outlived a password change could belong to whoever had the old one,
|
|
52
|
+
* and a passkey signs in without the second factor. The one place a password is replaced (the
|
|
53
|
+
* security page, the `emailengine password` command, EENGINE_PREPARED_PASSWORD), so a new way of
|
|
54
|
+
* replacing it can not forget the passkeys again.
|
|
55
|
+
*
|
|
56
|
+
* @param {string} passwordHash - PBKDF2 hash of the new password
|
|
57
|
+
* @param {Object} deps
|
|
58
|
+
* @param {Object} deps.settings - settings store (`get()`, `set()`)
|
|
59
|
+
* @param {Object} deps.passkeys - passkey store (`deleteAllCredentials()`)
|
|
60
|
+
* @param {Object} deps.logger
|
|
61
|
+
* @param {Object} [authData] - The stored authData, when the caller already read it
|
|
62
|
+
* @returns {Promise<{ authData: Object, clearedPasskeys: number }>}
|
|
63
|
+
*/
|
|
64
|
+
async function setAdminPassword(passwordHash, { settings, passkeys, logger }, authData) {
|
|
65
|
+
// read only when the caller did not: a caller that read nothing passes null, not undefined
|
|
66
|
+
authData = (authData === undefined ? await settings.get('authData') : authData) || {};
|
|
67
|
+
authData.user = authData.user || 'admin';
|
|
68
|
+
authData.password = passwordHash;
|
|
69
|
+
authData.passwordVersion = Date.now();
|
|
70
|
+
|
|
71
|
+
await settings.set('authData', authData);
|
|
72
|
+
|
|
73
|
+
let clearedPasskeys = 0;
|
|
74
|
+
try {
|
|
75
|
+
clearedPasskeys = await passkeys.deleteAllCredentials(authData.user);
|
|
76
|
+
logger.info({ msg: 'All passkeys cleared after password change', user: authData.user, cleared: clearedPasskeys });
|
|
77
|
+
} catch (err) {
|
|
78
|
+
// The password is replaced either way; say loudly that the passkeys are not gone
|
|
79
|
+
logger.error({ msg: 'Failed to clear passkeys after password change', err });
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
return { authData, clearedPasskeys };
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
module.exports = { verifyAdminPassword, verifyCurrentPassword, setAdminPassword };
|
|
@@ -32,6 +32,9 @@ async function init(args) {
|
|
|
32
32
|
tags: ['api', 'License'],
|
|
33
33
|
|
|
34
34
|
plugins: {
|
|
35
|
+
// open while the license is missing or suspended (workers/api.js preResponse), so an
|
|
36
|
+
// instance can still report its state and register a key
|
|
37
|
+
licensePrecheck: false,
|
|
35
38
|
mcp: {
|
|
36
39
|
name: 'get_license',
|
|
37
40
|
title: 'Get license',
|
|
@@ -78,6 +81,9 @@ async function init(args) {
|
|
|
78
81
|
tags: ['api', 'License'],
|
|
79
82
|
|
|
80
83
|
plugins: {
|
|
84
|
+
// open while the license is missing or suspended (workers/api.js preResponse), so an
|
|
85
|
+
// instance can still report its state and register a key
|
|
86
|
+
licensePrecheck: false,
|
|
81
87
|
openapi: {
|
|
82
88
|
'x-ee-impact': IMPACT.DESTRUCTIVE,
|
|
83
89
|
responses: apiResponses('Returns an empty license object. EmailEngine drops to limited mode.', 401, 403, 429, 500)
|
|
@@ -124,6 +130,9 @@ async function init(args) {
|
|
|
124
130
|
tags: ['api', 'License'],
|
|
125
131
|
|
|
126
132
|
plugins: {
|
|
133
|
+
// open while the license is missing or suspended (workers/api.js preResponse), so an
|
|
134
|
+
// instance can still report its state and register a key
|
|
135
|
+
licensePrecheck: false,
|
|
127
136
|
mcp: {
|
|
128
137
|
name: 'set_license',
|
|
129
138
|
title: 'Apply license',
|
package/lib/api-token-auth.js
CHANGED
|
@@ -30,11 +30,22 @@ const { mcpOptions } = require('./api-routes/route-metadata');
|
|
|
30
30
|
* @param {Object} deps.redis - Redis client, for the template ownership lookup
|
|
31
31
|
* @param {Function} deps.checkRateLimit - async (key, count, allowed, windowSize) => { success, allowed, count, ttl }
|
|
32
32
|
* @param {Function} deps.sessionPasswordVersion - async () => the password version sessions are stamped with
|
|
33
|
+
* @param {Function} deps.sessionAdmitted - (session) => whether the session's SSO provider still admits its user
|
|
33
34
|
* @param {String[]} [deps.adminAccessAddresses] - EENGINE_ADMIN_ACCESS_ADDRESSES, the admin perimeter
|
|
34
35
|
* @param {Object} deps.logger
|
|
35
36
|
* @returns {Function} async (request, token) => { isValid, credentials, artifacts }
|
|
36
37
|
*/
|
|
37
|
-
function createApiTokenValidator({
|
|
38
|
+
function createApiTokenValidator({
|
|
39
|
+
settings,
|
|
40
|
+
tokens,
|
|
41
|
+
tokenAuditLog,
|
|
42
|
+
redis,
|
|
43
|
+
checkRateLimit,
|
|
44
|
+
sessionPasswordVersion,
|
|
45
|
+
sessionAdmitted,
|
|
46
|
+
adminAccessAddresses,
|
|
47
|
+
logger
|
|
48
|
+
}) {
|
|
38
49
|
return async function validateApiToken(request, token) {
|
|
39
50
|
let disableTokens = await settings.get('disableTokens');
|
|
40
51
|
if (disableTokens && (!token || token === 'preauth')) {
|
|
@@ -75,7 +86,8 @@ function createApiTokenValidator({ settings, tokens, tokenAuditLog, redis, check
|
|
|
75
86
|
// that was supposed to end every session. Same predicate as the session strategy,
|
|
76
87
|
// including its "only when a local password exists" condition, so a session stamped
|
|
77
88
|
// before this shipped is not force-expired.
|
|
78
|
-
|
|
89
|
+
// The same goes for an SSO user the identity provider's allow-list no longer admits
|
|
90
|
+
if (isEndedSession(await sessionPasswordVersion(), session) || !sessionAdmitted(session)) {
|
|
79
91
|
logger.warn({
|
|
80
92
|
msg: 'Session token presented for an ended session',
|
|
81
93
|
account: request.params.account,
|
|
@@ -139,7 +151,7 @@ function createApiTokenValidator({ settings, tokens, tokenAuditLog, redis, check
|
|
|
139
151
|
// The last-use record is skipped on MCP-dispatched injects: the outer /mcp
|
|
140
152
|
// request just wrote the same credential's entry, and the second write would
|
|
141
153
|
// only repeat it
|
|
142
|
-
tokenData = await tokens.get(token, false, { log: !request.app.mcpInternal, remoteAddress: request.app.ip });
|
|
154
|
+
tokenData = await tokens.get(token, false, { log: !request.app.mcpInternal && !request.app.authRecheck, remoteAddress: request.app.ip });
|
|
143
155
|
} catch (err) {
|
|
144
156
|
// A thrown Boom reaches the client the way the scope and permission refusals
|
|
145
157
|
// below do (the api-token scheme does not catch it), so the reason travels as a
|
|
@@ -353,7 +365,8 @@ function createApiTokenValidator({ settings, tokens, tokenAuditLog, redis, check
|
|
|
353
365
|
// /mcp request already spent one unit of this token's budget at the door, and
|
|
354
366
|
// counting the inner request too silently halved every restricted token's
|
|
355
367
|
// effective limit over MCP.
|
|
356
|
-
|
|
368
|
+
// A re-check of an open stream (request.app.authRecheck) is not a request either.
|
|
369
|
+
if (tokenData.restrictions.rateLimit && !request.app.mcpInternal && !request.app.authRecheck) {
|
|
357
370
|
let rateLimit = await checkRateLimit(
|
|
358
371
|
`api:${tokenData.id}`,
|
|
359
372
|
1,
|
|
@@ -395,7 +408,10 @@ function createApiTokenValidator({ settings, tokens, tokenAuditLog, redis, check
|
|
|
395
408
|
// check above was deferred): every tool call writes its own row as the injected API
|
|
396
409
|
// request it becomes, and a second content-free row per call would halve the capped
|
|
397
410
|
// audit retention for MCP traffic. Denials at the door are still recorded above.
|
|
398
|
-
|
|
411
|
+
//
|
|
412
|
+
// Nor for the periodic re-check of an open change stream, which asks whether the token still
|
|
413
|
+
// admits a request it already accepted.
|
|
414
|
+
if (!mcpEndpoint && !request.app.authRecheck) {
|
|
399
415
|
tokenAuditLog.allowed(auditEntry);
|
|
400
416
|
}
|
|
401
417
|
|
package/lib/calendar-event.js
CHANGED
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
// VCALENDAR (ical.js 2.x; 1.x read such a value as floating, in the server's own zone), so the
|
|
9
9
|
// ISO timestamps are the instant the invite means wherever EmailEngine happens to run.
|
|
10
10
|
|
|
11
|
+
const { withinNotifyAttachmentSize } = require('./notify-attachments');
|
|
11
12
|
const ical = require('ical.js');
|
|
12
13
|
const { filterEmptyObjectValues } = require('./utils/filter-empty');
|
|
13
14
|
|
|
@@ -76,6 +77,10 @@ function parseCalendarEvent(content) {
|
|
|
76
77
|
};
|
|
77
78
|
}
|
|
78
79
|
|
|
80
|
+
// The largest calendar file read for the webhook. Any sender can attach one, and it was loaded,
|
|
81
|
+
// parsed and copied into the payload whole: a real invite is a few kilobytes.
|
|
82
|
+
const MAX_CALENDAR_SIZE = 1024 * 1024;
|
|
83
|
+
|
|
79
84
|
/**
|
|
80
85
|
* The calendar events of a new message, for the messageNew webhook (`notifyCalendarEvents`).
|
|
81
86
|
* Shared by the IMAP mailbox and the Gmail API and Graph clients, which differ only in how an
|
|
@@ -90,13 +95,14 @@ async function collectCalendarEvents(attachments, load, logger) {
|
|
|
90
95
|
const events = new Map();
|
|
91
96
|
|
|
92
97
|
for (const attachment of [...(attachments || [])].sort(sortCalendarAttachments)) {
|
|
93
|
-
if (!CALENDAR_CONTENT_TYPES.includes(attachment.contentType)) {
|
|
98
|
+
if (!CALENDAR_CONTENT_TYPES.includes(attachment.contentType) || !withinNotifyAttachmentSize(attachment, MAX_CALENDAR_SIZE)) {
|
|
94
99
|
continue;
|
|
95
100
|
}
|
|
96
101
|
if (!attachment.content) {
|
|
97
102
|
await load(attachment);
|
|
98
103
|
}
|
|
99
|
-
|
|
104
|
+
// a part without a reported size is measured once loaded
|
|
105
|
+
if (!attachment.content || !withinNotifyAttachmentSize(attachment, MAX_CALENDAR_SIZE)) {
|
|
100
106
|
continue;
|
|
101
107
|
}
|
|
102
108
|
|
|
@@ -155,4 +161,10 @@ async function collectCalendarEvents(attachments, load, logger) {
|
|
|
155
161
|
});
|
|
156
162
|
}
|
|
157
163
|
|
|
158
|
-
module.exports = {
|
|
164
|
+
module.exports = {
|
|
165
|
+
MAX_CALENDAR_SIZE,
|
|
166
|
+
CALENDAR_CONTENT_TYPES,
|
|
167
|
+
sortCalendarAttachments,
|
|
168
|
+
parseCalendarEvent,
|
|
169
|
+
collectCalendarEvents
|
|
170
|
+
};
|
package/lib/consts.js
CHANGED
|
@@ -269,6 +269,11 @@ module.exports = {
|
|
|
269
269
|
// drops the connection would otherwise cause an unthrottled login loop
|
|
270
270
|
STABLE_CONNECTION_TIME: 5 * 60 * 1000, // 5 min
|
|
271
271
|
|
|
272
|
+
// How much lifetime a stored OAuth2 access token must have left to be used as is rather than
|
|
273
|
+
// renewed first. An IMAP login on a provider that ends the session with its token asks for more,
|
|
274
|
+
// see lib/email-client/imap/session-expiry.js
|
|
275
|
+
OAUTH_TOKEN_MIN_VALIDITY: 30 * 1000,
|
|
276
|
+
|
|
272
277
|
MAX_INLINE_ATTACHMENT_SIZE: 2 * 1024 * 1024,
|
|
273
278
|
|
|
274
279
|
// How many times processing of the same Gmail history entry may start
|
package/lib/db.js
CHANGED
|
@@ -49,6 +49,7 @@ const REDIS_CONF = Object.assign(
|
|
|
49
49
|
},
|
|
50
50
|
typeof redisConf === 'string' ? redisUrl(redisConf) : redisConf || {}
|
|
51
51
|
);
|
|
52
|
+
redisUrl.applyRedisTlsSwitch(REDIS_CONF);
|
|
52
53
|
|
|
53
54
|
const getRedisURL = (masked = true) => {
|
|
54
55
|
let redisUrlParts = [`redis${REDIS_CONF.tls ? 's' : ''}://`];
|
|
@@ -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 };
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// Exchange Online ties an IMAP session to the lifetime of the OAuth2 access token it logged in
|
|
4
|
+
// with. Once that token expires, the next command on the session (typically the DONE that ends
|
|
5
|
+
// IDLE so an API request can run) is answered with `* BYE Session invalidated -
|
|
6
|
+
// AccessTokenExpired`, and whatever request was in flight fails with it. Renewing the stored token
|
|
7
|
+
// does nothing for a session that is already open: IMAP has no way to authenticate again inside an
|
|
8
|
+
// authenticated session, so the session has to be replaced before its token runs out.
|
|
9
|
+
//
|
|
10
|
+
// ImapFlow does the replacing (its `sessionExpires` option, from 2.11.0): from `sessionExpiryLead`
|
|
11
|
+
// before the expiry it closes the connection the first time nothing runs on it, and shortly before
|
|
12
|
+
// the expiry it closes it regardless. The close handlers reconnect a primary connection or a
|
|
13
|
+
// subconnection, and a command connection is opened again for the next request. What stays here is
|
|
14
|
+
// deciding which sessions that applies to and making sure each login starts with a token that has
|
|
15
|
+
// enough life left, only for the providers listed below (a Gmail session outlives its token, and
|
|
16
|
+
// reconnecting those every hour would only cost a resync).
|
|
17
|
+
|
|
18
|
+
const { OAUTH_TOKEN_MIN_VALIDITY } = require('../../consts');
|
|
19
|
+
|
|
20
|
+
// Providers whose IMAP sessions end when the access token used to log in expires
|
|
21
|
+
const TOKEN_BOUND_SESSION_PROVIDERS = new Set(['outlook']);
|
|
22
|
+
|
|
23
|
+
// How long before the token expires the connection starts looking for a moment to close
|
|
24
|
+
const REAUTH_LEAD = 5 * 60 * 1000;
|
|
25
|
+
|
|
26
|
+
// Up to this much is added to the lead at random. Accounts that logged in together (a worker
|
|
27
|
+
// restart) renew together and would otherwise all reconnect in the same few seconds one token
|
|
28
|
+
// lifetime later, and every lifetime after that
|
|
29
|
+
const REAUTH_JITTER = 2 * 60 * 1000;
|
|
30
|
+
|
|
31
|
+
// A session that would have to be replaced sooner than this after logging in gets no deadline. Only
|
|
32
|
+
// a provider handing out short tokens gets there, and replacing such a session on every login would
|
|
33
|
+
// turn into a reconnect loop; it ends the way it did before, with the server's BYE. Longer than
|
|
34
|
+
// STABLE_CONNECTION_TIME, so the close handler reconnects the replaced primary at once instead of
|
|
35
|
+
// throttling it as a connection that died young
|
|
36
|
+
const REAUTH_MIN_DELAY = 6 * 60 * 1000;
|
|
37
|
+
|
|
38
|
+
// How much lifetime a token must have left to be used for a login on such a provider. Above the
|
|
39
|
+
// longest lead plus REAUTH_MIN_DELAY with a minute to spare, so a session that logs in with a token
|
|
40
|
+
// it got this way always gets a deadline. Kept close to that sum, because command connections and
|
|
41
|
+
// subconnections log in too, and every renewal they cause moves the next replacement of the primary
|
|
42
|
+
// connection earlier
|
|
43
|
+
const LOGIN_MIN_VALIDITY = 15 * 60 * 1000;
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* How much lifetime a stored access token needs to be used as is
|
|
47
|
+
* @param {string} provider - OAuth2 app provider (`outlook`, `gmail`, ...)
|
|
48
|
+
* @param {string} target - What the token is for (`imap`, `smtp`, `api`)
|
|
49
|
+
* @returns {number} Milliseconds
|
|
50
|
+
*/
|
|
51
|
+
function minTokenValidity(provider, target) {
|
|
52
|
+
return target === 'imap' && TOKEN_BOUND_SESSION_PROVIDERS.has(provider) ? LOGIN_MIN_VALIDITY : OAUTH_TOKEN_MIN_VALIDITY;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* The ImapFlow options that close a session before the token it logs in with expires, or null when
|
|
57
|
+
* the session does not end with its token (or the token is too short-lived to bother)
|
|
58
|
+
* @param {string} provider - OAuth2 app provider
|
|
59
|
+
* @param {Date|string|number} expires - Expiry of the token the session logs in with
|
|
60
|
+
* @param {number} now - Current epoch milliseconds
|
|
61
|
+
* @param {Function} [random=Math.random] - Source of the jitter, for tests
|
|
62
|
+
* @returns {{sessionExpires: number, sessionExpiryLead: number}|null}
|
|
63
|
+
*/
|
|
64
|
+
function sessionExpiryOptions(provider, expires, now, random = Math.random) {
|
|
65
|
+
if (!TOKEN_BOUND_SESSION_PROVIDERS.has(provider) || !expires) {
|
|
66
|
+
return null;
|
|
67
|
+
}
|
|
68
|
+
const sessionExpires = new Date(expires).getTime();
|
|
69
|
+
const sessionExpiryLead = REAUTH_LEAD + Math.round(random() * REAUTH_JITTER);
|
|
70
|
+
if (!Number.isFinite(sessionExpires) || sessionExpires - sessionExpiryLead - now < REAUTH_MIN_DELAY) {
|
|
71
|
+
return null;
|
|
72
|
+
}
|
|
73
|
+
return { sessionExpires, sessionExpiryLead };
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
module.exports = {
|
|
77
|
+
LOGIN_MIN_VALIDITY,
|
|
78
|
+
REAUTH_LEAD,
|
|
79
|
+
REAUTH_JITTER,
|
|
80
|
+
REAUTH_MIN_DELAY,
|
|
81
|
+
minTokenValidity,
|
|
82
|
+
sessionExpiryOptions
|
|
83
|
+
};
|
|
@@ -29,6 +29,7 @@ const { ReconnectBackoff } = require('./reconnect-backoff');
|
|
|
29
29
|
const { isRefusedImapLogin, imapResponseText } = require('./imap/login-failure');
|
|
30
30
|
const { knownUidNext, planStaleViewProbe, evaluateStaleViewProbe } = require('./imap/stale-view');
|
|
31
31
|
const { applyIdleSettings, commandSocketTimeout } = require('./imap/idle-settings');
|
|
32
|
+
const { sessionExpiryOptions } = require('./imap/session-expiry');
|
|
32
33
|
const { learnedInterval, recordClose } = require('./imap/adaptive-idle-store');
|
|
33
34
|
|
|
34
35
|
// How long a learned IDLE interval read for one connection is reused for the account's others
|
|
@@ -1689,11 +1690,14 @@ class IMAPClient extends BaseClient {
|
|
|
1689
1690
|
// the same method is also called by subconnections, so do not mark the primary connection as failing if something happens
|
|
1690
1691
|
ctx = ctx || this;
|
|
1691
1692
|
let imapConnectionConfig;
|
|
1693
|
+
// ImapFlow's sessionExpires/sessionExpiryLead, for a session that ends with its token
|
|
1694
|
+
let sessionOptions = null;
|
|
1692
1695
|
|
|
1693
1696
|
if (accountData.oauth2 && accountData.oauth2.auth) {
|
|
1694
1697
|
// OAuth2 authentication configuration
|
|
1695
|
-
const { oauth2User, accessToken, oauth2App } = await this.loadOAuth2AccountCredentials(accountData, ctx, 'imap');
|
|
1698
|
+
const { oauth2User, accessToken, oauth2App, expires } = await this.loadOAuth2AccountCredentials(accountData, ctx, 'imap');
|
|
1696
1699
|
const providerData = oauth2ProviderData(oauth2App.provider, oauth2App.cloud);
|
|
1700
|
+
sessionOptions = sessionExpiryOptions(oauth2App.provider, expires, Date.now());
|
|
1697
1701
|
|
|
1698
1702
|
imapConnectionConfig = Object.assign(
|
|
1699
1703
|
{
|
|
@@ -1714,6 +1718,8 @@ class IMAPClient extends BaseClient {
|
|
|
1714
1718
|
// If authentication server is set then it overrides authentication data
|
|
1715
1719
|
if (await useAuthServerForConnection(imapConnectionConfig, ctx.logger, { account: this.account, target: 'imap' })) {
|
|
1716
1720
|
imapConnectionConfig.auth = await this.resolveAuthServerCredentials('imap', ctx);
|
|
1721
|
+
// the expiry of the stored token says nothing about the one the session logs in with
|
|
1722
|
+
sessionOptions = null;
|
|
1717
1723
|
}
|
|
1718
1724
|
|
|
1719
1725
|
// Configure TLS settings
|
|
@@ -1760,7 +1766,11 @@ class IMAPClient extends BaseClient {
|
|
|
1760
1766
|
vendor: (await settings.get('imapClientVendor')) || this.imapConfig.clientInfo.vendor,
|
|
1761
1767
|
'support-url': (await settings.get('imapClientSupportUrl')) || this.imapConfig.clientInfo['support-url']
|
|
1762
1768
|
}
|
|
1763
|
-
}
|
|
1769
|
+
},
|
|
1770
|
+
// Exchange Online ends the session when its token expires; ImapFlow closes the connection
|
|
1771
|
+
// before that while nothing runs on it, and the close handlers open a new one (see
|
|
1772
|
+
// session-expiry.js). Applies to every connection built from this configuration
|
|
1773
|
+
sessionOptions
|
|
1764
1774
|
);
|
|
1765
1775
|
|
|
1766
1776
|
this.resyncDelay = imapConfig.resyncDelay * 1000;
|