emailengine-app 2.84.0 → 2.84.2
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/.dockerignore +6 -0
- package/.release-please-manifest.json +1 -1
- package/CHANGELOG.md +35 -0
- package/Dockerfile +2 -2
- package/bin/emailengine.js +15 -0
- package/data/google-crawlers.json +1 -1
- package/docker-compose.yml +1 -1
- package/lib/account/own-account-key.js +42 -0
- package/lib/account-assignment.js +1 -33
- package/lib/account.js +32 -19
- package/lib/add-trackers.js +11 -4
- package/lib/api-routes/account-routes.js +67 -14
- package/lib/api-routes/gateway-routes.js +9 -3
- package/lib/api-routes/message-routes.js +7 -1
- package/lib/api-routes/mint-bounds.js +11 -0
- package/lib/api-routes/route-helpers.js +125 -3
- package/lib/api-routes/submit-routes.js +4 -2
- package/lib/auth-token.js +23 -10
- package/lib/bounce-detect.js +17 -5
- package/lib/consts.js +34 -0
- package/lib/create-imap-client.js +41 -2
- package/lib/email-client/base-client.js +20 -10
- package/lib/email-client/gmail-client.js +21 -7
- package/lib/email-client/imap/mailbox.js +10 -4
- package/lib/email-client/imap/response-metrics.js +75 -0
- package/lib/email-client/imap-client.js +5 -2
- package/lib/email-client/message-builder.js +7 -2
- package/lib/email-client/outlook/graph-api.js +17 -2
- package/lib/email-client/outlook-client.js +6 -3
- package/lib/email-client/smtp-pool-manager.js +6 -0
- package/lib/encrypt.js +9 -0
- package/lib/export.js +3 -1
- package/lib/get-raw-email.js +4 -2
- package/lib/imap-proxy-auth.js +14 -1
- package/lib/imapproxy/imap-core/lib/commands/authenticate-plain.js +1 -0
- package/lib/imapproxy/imap-core/lib/commands/login.js +1 -0
- package/lib/imapproxy/imap-core/lib/imap-command.js +86 -43
- package/lib/imapproxy/imap-core/lib/imap-stream.js +58 -13
- package/lib/imapproxy/imap-core/lib/indexer/indexer.js +3 -1
- package/lib/mcp/listen.js +10 -1
- package/lib/oauth/external-account-config.js +3 -1
- package/lib/oauth/gmail.js +21 -48
- package/lib/oauth/mail-ru.js +5 -38
- package/lib/oauth/outlook.js +26 -44
- package/lib/pbkdf2-phc.js +18 -1
- package/lib/privileged-settings.js +6 -3
- package/lib/redis-scan-delete.js +15 -1
- package/lib/schemas.js +78 -32
- package/lib/settings.js +13 -1
- package/lib/smtp-auth.js +23 -0
- package/lib/tools.js +245 -56
- package/lib/ui-routes/account-routes.js +16 -37
- package/lib/ui-routes/admin-config-routes.js +10 -38
- package/lib/ui-routes/admin-entities-routes.js +22 -24
- package/lib/ui-routes/auth-routes.js +47 -24
- package/lib/ui-routes/connection-security-form.js +74 -0
- package/lib/ui-routes/form-lists.js +46 -0
- package/lib/ui-routes/mcp-consent-routes.js +5 -1
- package/lib/ui-routes/oauth-config-routes.js +9 -18
- package/lib/ui-routes/sign-in-helpers.js +59 -0
- package/lib/ui-routes/unsubscribe-routes.js +6 -3
- package/lib/utils/map-concurrent.js +36 -0
- package/lib/utils/network.js +28 -0
- package/lib/utils/provider-id.js +27 -0
- package/lib/utils/require-tls.js +33 -0
- package/lib/web-safe-html.js +5 -6
- package/lib/webhook-penalty.js +75 -0
- package/lib/webhook-routing.js +22 -2
- package/package.json +21 -21
- package/sbom.json +1 -1
- package/server.js +74 -38
- package/static/js/ace/ace.js +1 -1
- package/static/js/ace/mode-handlebars.js +1 -1
- package/static/js/ace/mode-html.js +1 -1
- package/static/js/ace/mode-javascript.js +1 -1
- package/static/js/ace/mode-markdown.js +1 -1
- package/static/js/ace/worker-html.js +1 -1
- package/static/js/ace/worker-javascript.js +1 -1
- package/static/js/ace/worker-json.js +1 -1
- package/static/js/ee-client.js +5 -0
- package/static/licenses.html +23 -23
- package/translations/messages.pot +66 -66
- package/views/account/security.hbs +10 -0
- package/views/accounts/account.hbs +11 -11
- package/views/accounts/edit.hbs +6 -2
- package/views/partials/gateway_form.hbs +3 -1
- package/workers/api.js +43 -3
- package/workers/webhooks.js +39 -3
- package/config/test.toml +0 -46
- package/install.sh +0 -428
- package/setup-production.sh +0 -215
- package/systemd/emailengine.service +0 -97
- package/systemd/nginx-proxy.conf +0 -77
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
const Boom = require('@hapi/boom');
|
|
4
4
|
const { isDeepStrictEqual } = require('node:util');
|
|
5
5
|
const tokenPermissions = require('../token-permissions');
|
|
6
|
+
const { sessionTokenAdmits } = require('./permission-map');
|
|
6
7
|
const settings = require('../settings');
|
|
7
8
|
|
|
8
9
|
// Shared helpers for the extracted API route modules under lib/api-routes/.
|
|
@@ -375,7 +376,109 @@ function isRestrictedCredential(request) {
|
|
|
375
376
|
if (request.app && request.app.sessionToken) {
|
|
376
377
|
return true;
|
|
377
378
|
}
|
|
378
|
-
|
|
379
|
+
const tokenData = request.auth && request.auth.artifacts;
|
|
380
|
+
if (isSurfaceBoundToken(tokenData)) {
|
|
381
|
+
return true;
|
|
382
|
+
}
|
|
383
|
+
return tokenPermissions.inspect(tokenData).narrowed;
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
/**
|
|
387
|
+
* Whether a token reaches the API only through an MCP surface scope.
|
|
388
|
+
*
|
|
389
|
+
* `mcp` and `mcp-manage` admit the operations their surface table covers, on requests the MCP
|
|
390
|
+
* endpoint dispatched itself. A token holding one of them and neither `api` nor `*` is therefore
|
|
391
|
+
* bounded below the full API whether or not it carries a permissions record: the ones minted before
|
|
392
|
+
* every MCP token got an explicit grant list have no record, and read as unnarrowed to inspect().
|
|
393
|
+
*
|
|
394
|
+
* @param {Object} tokenData - the token record (request.auth.artifacts)
|
|
395
|
+
* @returns {Boolean}
|
|
396
|
+
*/
|
|
397
|
+
function isSurfaceBoundToken(tokenData) {
|
|
398
|
+
const scopes = tokenData && Array.isArray(tokenData.scopes) ? tokenData.scopes : null;
|
|
399
|
+
if (!scopes || scopes.includes('*') || scopes.includes('api')) {
|
|
400
|
+
return false;
|
|
401
|
+
}
|
|
402
|
+
return scopes.includes('mcp') || scopes.includes('mcp-manage');
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
/**
|
|
406
|
+
* Whether the credential behind a request is bound to one account.
|
|
407
|
+
*
|
|
408
|
+
* A bound token is admitted to its own account's routes only (the api-token strategy checks the
|
|
409
|
+
* binding against the path), but it is not narrowed in the permission-record sense and so reads as
|
|
410
|
+
* unrestricted to isRestrictedCredential(). The payload rules that decide whether an account may
|
|
411
|
+
* borrow another account's identity need both answers.
|
|
412
|
+
*
|
|
413
|
+
* @param {Object} request - the Hapi request
|
|
414
|
+
* @returns {Boolean}
|
|
415
|
+
*/
|
|
416
|
+
function isBoundCredential(request) {
|
|
417
|
+
const tokenData = request.auth && request.auth.artifacts;
|
|
418
|
+
return !!(tokenData && tokenData.account);
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
/**
|
|
422
|
+
* Refuses an account payload that would make the account authenticate as a different one, when the
|
|
423
|
+
* credential sending it is bound to an account or otherwise restricted.
|
|
424
|
+
*
|
|
425
|
+
* `oauth2.auth.delegatedAccount` makes the account connect with the named account's stored OAuth2
|
|
426
|
+
* token, and nothing else checks that the two belong together: an account-bound token could name
|
|
427
|
+
* any other account on the instance and read its mailbox through its own routes, which is exactly
|
|
428
|
+
* what the binding promises cannot happen. `delegatedUser` alone retargets a Microsoft 365 shared
|
|
429
|
+
* mailbox. And on an application-credentials app (`gmailService`, `outlookService`) there is no
|
|
430
|
+
* per-user credential at all, so changing `auth.user` points the account at any mailbox in the
|
|
431
|
+
* tenant. The admin interface and an unrestricted, unbound token keep every one of these.
|
|
432
|
+
*
|
|
433
|
+
* `isServiceApp` is asked only when the payload names a user and the credential is one this guard
|
|
434
|
+
* applies to, so the lookup it performs is not paid on the common path.
|
|
435
|
+
*
|
|
436
|
+
* @param {Object} request - the Hapi request
|
|
437
|
+
* @param {Object} [opts]
|
|
438
|
+
* @param {Function} [opts.isServiceApp] - async, resolves true when the account's OAuth2 app uses application credentials
|
|
439
|
+
*/
|
|
440
|
+
async function assertNoIdentityRetarget(request, opts) {
|
|
441
|
+
opts = opts || {};
|
|
442
|
+
const auth = request.payload && request.payload.oauth2 && request.payload.oauth2.auth;
|
|
443
|
+
if (!auth || typeof auth !== 'object') {
|
|
444
|
+
return;
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
if (!isBoundCredential(request) && !isRestrictedCredential(request)) {
|
|
448
|
+
return;
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
if (auth.delegatedAccount || auth.delegatedUser) {
|
|
452
|
+
throw Boom.forbidden("A token with restricted permissions can not delegate an account to another account's credentials or to a shared mailbox");
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
if (auth.user && typeof opts.isServiceApp === 'function' && (await opts.isServiceApp())) {
|
|
456
|
+
throw Boom.forbidden('A token with restricted permissions can not change the mailbox of an account that authenticates with application credentials');
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
/**
|
|
461
|
+
* Refuses a request whose credential does not hold an operation the handler is about to perform in
|
|
462
|
+
* addition to the one its route resolves to.
|
|
463
|
+
*
|
|
464
|
+
* The permission check runs once per route, against routeGrant(). A route that writes when asked
|
|
465
|
+
* to (`GET .../message/{message}?markAsSeen=true` sets the `\Seen` flag) therefore has to ask for
|
|
466
|
+
* the second grant itself. A session token is held to SESSION_TOKEN_GRANTS, a narrowed token to its
|
|
467
|
+
* record, through the same two predicates the strategy uses; every other credential holds
|
|
468
|
+
* everything and passes.
|
|
469
|
+
*
|
|
470
|
+
* @param {Object} request - the Hapi request
|
|
471
|
+
* @param {{action: String, group: String}} operation - the (action, group) pair the handler needs
|
|
472
|
+
* @param {String} what - the thing being refused, for the message
|
|
473
|
+
*/
|
|
474
|
+
function assertCredentialAllows(request, operation, what) {
|
|
475
|
+
const allowed =
|
|
476
|
+
request.app && request.app.sessionToken
|
|
477
|
+
? sessionTokenAdmits(operation, { account: request.params && request.params.account })
|
|
478
|
+
: tokenPermissions.check({ tokenData: request.auth && request.auth.artifacts, operation }).allowed;
|
|
479
|
+
if (!allowed) {
|
|
480
|
+
throw Boom.forbidden(`A token with restricted permissions can not ${what}`);
|
|
481
|
+
}
|
|
379
482
|
}
|
|
380
483
|
|
|
381
484
|
/**
|
|
@@ -408,6 +511,13 @@ function assertNoPrivilegedSettings(request, keys, verb = 'change') {
|
|
|
408
511
|
throw Boom.forbidden(`A token with restricted permissions can not ${verb} ${privileged.join(', ')}`);
|
|
409
512
|
}
|
|
410
513
|
|
|
514
|
+
// The service-account authentication methods that act with something the instance holds rather than
|
|
515
|
+
// with a credential the caller supplied, and what a refusal calls each
|
|
516
|
+
const ATTACHED_IDENTITY_METHODS = new Map([
|
|
517
|
+
['metadataServer', 'the attached service account (metadataServer)'],
|
|
518
|
+
['externalAccount', 'a credential source read from this host (externalAccount)']
|
|
519
|
+
]);
|
|
520
|
+
|
|
411
521
|
/**
|
|
412
522
|
* Refuses an OAuth2 application that would authenticate as the instance's own cloud identity, when
|
|
413
523
|
* the credential creating it is narrowed.
|
|
@@ -427,23 +537,35 @@ function assertNoPrivilegedSettings(request, keys, verb = 'change') {
|
|
|
427
537
|
* unrestricted token remain. A saved app's method is pinned (isAuthMethodLocked() in
|
|
428
538
|
* lib/oauth2-apps.js), so the stored one is what an update checks.
|
|
429
539
|
*
|
|
540
|
+
* `authMethod: 'externalAccount'` is refused on the same grounds. Its credential source is a file
|
|
541
|
+
* path the instance reads, or a URL the instance fetches with caller-chosen headers from the host
|
|
542
|
+
* it runs on, outside the HTTP proxy and the egress policy because the endpoint it is meant for is
|
|
543
|
+
* the local identity server. Either one reads the deployment's own environment, and the verify
|
|
544
|
+
* report says how the read went, so a narrowed `oauth2` token could use it to read files and probe
|
|
545
|
+
* the instance's network. Same remedy: the admin interface or an unrestricted token.
|
|
546
|
+
*
|
|
430
547
|
* @param {Object} request - the Hapi request
|
|
431
548
|
* @param {string} [authMethod] - the method of the app being created (the payload's) or modified (the stored one's)
|
|
432
549
|
* @param {string} verb - 'create' or 'modify', for the refusal message
|
|
433
550
|
*/
|
|
434
551
|
function assertNoAttachedIdentity(request, authMethod, verb) {
|
|
435
|
-
|
|
552
|
+
const what = ATTACHED_IDENTITY_METHODS.get(authMethod);
|
|
553
|
+
if (!what || !isRestrictedCredential(request)) {
|
|
436
554
|
return;
|
|
437
555
|
}
|
|
438
556
|
|
|
439
557
|
throw Boom.forbidden(
|
|
440
|
-
`A token with restricted permissions can not ${verb} an application that uses
|
|
558
|
+
`A token with restricted permissions can not ${verb} an application that uses ${what}. Use the admin interface or an unrestricted token`
|
|
441
559
|
);
|
|
442
560
|
}
|
|
443
561
|
|
|
444
562
|
module.exports = {
|
|
445
563
|
handleError,
|
|
446
564
|
assertNoAttachedIdentity,
|
|
565
|
+
assertNoIdentityRetarget,
|
|
566
|
+
assertCredentialAllows,
|
|
567
|
+
isRestrictedCredential,
|
|
568
|
+
isBoundCredential,
|
|
447
569
|
logApiError,
|
|
448
570
|
throwNotFound,
|
|
449
571
|
assertNoPrivilegedSettings,
|
|
@@ -9,6 +9,7 @@ const { handleError, assertNoNetworkOverride } = require('./route-helpers');
|
|
|
9
9
|
const BEHAVIOR = require('./behavior-notes');
|
|
10
10
|
const { IMPACT } = require('./operation-impact');
|
|
11
11
|
const { FIELD_USAGE } = require('../field-usage');
|
|
12
|
+
const { MAX_MAIL_MERGE_ENTRIES, MAX_DELIVERY_ATTEMPTS } = require('../consts');
|
|
12
13
|
const {
|
|
13
14
|
messageReferenceSchema,
|
|
14
15
|
documentStoreSchema,
|
|
@@ -44,7 +45,7 @@ const sendAtSchema = Joi.date().iso().example('2021-07-08T07:06:34.336Z').descri
|
|
|
44
45
|
const deliveryAttemptsSchema = Joi.number()
|
|
45
46
|
.integer()
|
|
46
47
|
.min(0)
|
|
47
|
-
.max(
|
|
48
|
+
.max(MAX_DELIVERY_ATTEMPTS)
|
|
48
49
|
.example(10)
|
|
49
50
|
.description('How many delivery attempts to make until message is considered as failed');
|
|
50
51
|
|
|
@@ -332,7 +333,8 @@ async function init(args) {
|
|
|
332
333
|
}).label('MailMergeListEntry')
|
|
333
334
|
)
|
|
334
335
|
.min(1)
|
|
335
|
-
.
|
|
336
|
+
.max(MAX_MAIL_MERGE_ENTRIES)
|
|
337
|
+
.description(`Mail merge options. A separate email is generated for each recipient, up to ${MAX_MAIL_MERGE_ENTRIES} per request`)
|
|
336
338
|
.meta({ usage: FIELD_USAGE.mailMerge })
|
|
337
339
|
.label('MailMergeList'),
|
|
338
340
|
|
package/lib/auth-token.js
CHANGED
|
@@ -11,7 +11,8 @@ const tokens = require('./tokens');
|
|
|
11
11
|
const tokenPermissions = require('./token-permissions');
|
|
12
12
|
const tokenAuditLog = require('./token-audit-log');
|
|
13
13
|
const { SURFACE_GRANTS } = require('./api-routes/permission-map');
|
|
14
|
-
const {
|
|
14
|
+
const { createHash } = require('crypto');
|
|
15
|
+
const { matchIp, budgetAddress } = require('./utils/network');
|
|
15
16
|
const { windowBudget, reserveAttempts, releaseAttempts } = require('./rate-limit');
|
|
16
17
|
|
|
17
18
|
// Reason-specific denial messages, shared verbatim by both auth handlers. The
|
|
@@ -50,8 +51,16 @@ const AUTH_FAILURE_ADDRESS_LIMIT = 100;
|
|
|
50
51
|
|
|
51
52
|
const TOKEN_SHAPE = /^[0-9a-f]{64}$/i;
|
|
52
53
|
|
|
53
|
-
|
|
54
|
-
const
|
|
54
|
+
// what a recheck writes to the per-token trail
|
|
55
|
+
const NO_AUDIT = { allowed() {}, denied() {} };
|
|
56
|
+
|
|
57
|
+
// The username is the client's to choose and may be as long as a command line (about 1 MB), and
|
|
58
|
+
// a reserved attempt is a Redis key that lives for the window, so the key carries a digest of it
|
|
59
|
+
// rather than the name itself. Fixed length, and nothing a client writes ends up in Redis as it was
|
|
60
|
+
const budgetAccount = account => (account ? createHash('sha256').update(String(account)).digest('base64url').slice(0, 22) : '');
|
|
61
|
+
|
|
62
|
+
const authFailureKey = (remoteAddress, account) => `auth:fail:${budgetAddress(remoteAddress)}:${budgetAccount(account)}`;
|
|
63
|
+
const authFailureAddressKey = remoteAddress => `auth:fail-addr:${budgetAddress(remoteAddress)}`;
|
|
55
64
|
|
|
56
65
|
/**
|
|
57
66
|
* Runs a credential check under the client's failed-login budget.
|
|
@@ -117,16 +126,20 @@ async function withAuthFailureBudget({ remoteAddress, account, password }, attem
|
|
|
117
126
|
* @param {String} opts.account - username the client authenticated as
|
|
118
127
|
* @param {String} opts.requiredScope - scope the token must hold ('smtp' | 'imap-proxy')
|
|
119
128
|
* @param {String} opts.remoteAddress - client IP, checked against token restrictions
|
|
129
|
+
* @param {Boolean} [opts.recheck] - the token already opened this session and is being asked
|
|
130
|
+
* whether it still admits it: neither a use of the token nor an audit entry is recorded
|
|
120
131
|
* @returns {Promise<{authenticated: Boolean, reason: (null|'username'|'scope'|'permissions'|'ip')}>}
|
|
121
132
|
*/
|
|
122
|
-
async function validateAuthToken({ password, account, requiredScope, remoteAddress }) {
|
|
133
|
+
async function validateAuthToken({ password, account, requiredScope, remoteAddress, recheck }) {
|
|
123
134
|
if (!/^[0-9a-f]{64}$/i.test(password)) {
|
|
124
135
|
return { authenticated: false, reason: null };
|
|
125
136
|
}
|
|
126
137
|
|
|
138
|
+
const audit = recheck ? NO_AUDIT : tokenAuditLog;
|
|
139
|
+
|
|
127
140
|
let tokenData;
|
|
128
141
|
try {
|
|
129
|
-
tokenData = await tokens.get(password, false, { log:
|
|
142
|
+
tokenData = await tokens.get(password, false, { log: !recheck, remoteAddress });
|
|
130
143
|
} catch (err) {
|
|
131
144
|
logger.error({ msg: 'Failed to fetch token', err });
|
|
132
145
|
}
|
|
@@ -156,7 +169,7 @@ async function validateAuthToken({ password, account, requiredScope, remoteAddre
|
|
|
156
169
|
account,
|
|
157
170
|
requestedScope: requiredScope
|
|
158
171
|
});
|
|
159
|
-
|
|
172
|
+
audit.denied(auditEntry, 'username');
|
|
160
173
|
return { authenticated: false, reason: 'username' };
|
|
161
174
|
}
|
|
162
175
|
|
|
@@ -169,7 +182,7 @@ async function validateAuthToken({ password, account, requiredScope, remoteAddre
|
|
|
169
182
|
requestedScope: requiredScope,
|
|
170
183
|
scopes: tokenData.scopes
|
|
171
184
|
});
|
|
172
|
-
|
|
185
|
+
audit.denied(auditEntry, 'scope');
|
|
173
186
|
return { authenticated: false, reason: 'scope' };
|
|
174
187
|
}
|
|
175
188
|
|
|
@@ -212,7 +225,7 @@ async function validateAuthToken({ password, account, requiredScope, remoteAddre
|
|
|
212
225
|
reason: permissionCheck.reason,
|
|
213
226
|
required: permissionCheck.required
|
|
214
227
|
});
|
|
215
|
-
|
|
228
|
+
audit.denied(auditEntry, permissionCheck.reason);
|
|
216
229
|
return { authenticated: false, reason: 'permissions' };
|
|
217
230
|
}
|
|
218
231
|
|
|
@@ -225,11 +238,11 @@ async function validateAuthToken({ password, account, requiredScope, remoteAddre
|
|
|
225
238
|
remoteAddress,
|
|
226
239
|
addressAllowlist: tokenData.restrictions.addresses
|
|
227
240
|
});
|
|
228
|
-
|
|
241
|
+
audit.denied(auditEntry, 'ip');
|
|
229
242
|
return { authenticated: false, reason: 'ip' };
|
|
230
243
|
}
|
|
231
244
|
|
|
232
|
-
|
|
245
|
+
audit.allowed(auditEntry);
|
|
233
246
|
|
|
234
247
|
return { authenticated: true, reason: null };
|
|
235
248
|
}
|
package/lib/bounce-detect.js
CHANGED
|
@@ -38,6 +38,12 @@ const DELAY_NOTICE_RE =
|
|
|
38
38
|
// "I'm not going to try again"), so a 4.x.x status on its own does not make a notice a delay
|
|
39
39
|
const GAVE_UP_RE = /permanent error|given up|not going to try again|retry timeout exceeded|will not be retried|could not be delivered/i;
|
|
40
40
|
|
|
41
|
+
// The first run of non-whitespace after a marker line, where a bounce names the recipient. A
|
|
42
|
+
// newline is whitespace, so one `\s*` is the whole skip; the `\s*\n*\s*` it replaces was three
|
|
43
|
+
// overlapping quantifiers whose combinations grew with the fourth power of a newline run. Anchored,
|
|
44
|
+
// so a text that ends in whitespace fails once rather than once per start position.
|
|
45
|
+
const NEXT_TOKEN = /^\s*(\S+)/;
|
|
46
|
+
|
|
41
47
|
/**
|
|
42
48
|
* Tells whether a notice the text heuristics matched reports a delay rather than a failure
|
|
43
49
|
*
|
|
@@ -549,8 +555,12 @@ async function bounceDetect(sourceStream) {
|
|
|
549
555
|
* 550 5.1.1 No such user (in reply to RCPT TO command)
|
|
550
556
|
*/
|
|
551
557
|
// The address classes exclude '<' and whitespace and are bounded, so a run of '<' or of
|
|
552
|
-
// unterminated addresses can not make every start position scan to the end of the text
|
|
553
|
-
|
|
558
|
+
// unterminated addresses can not make every start position scan to the end of the text.
|
|
559
|
+
// The whitespace between the host and `said:` is matched by one quantifier: Postfix writes
|
|
560
|
+
// the address right after the name (`host mx.example.com[203.0.113.4] said:`), and the
|
|
561
|
+
// `\s*(?:\[...\])?\s+` that allowed a space there had two adjacent whitespace runs that
|
|
562
|
+
// split a long run of spaces every possible way (50 KB of spaces took about a second)
|
|
563
|
+
let m = text.match(/<([^<>@\s]{1,256}@[^<>\s]{1,256})>:\s*host\s+([a-z0-9._-]+)(?:\[([^\]\s]{1,256})\])?\s+said:/im);
|
|
554
564
|
if (m) {
|
|
555
565
|
// Find the end of the error message (double newline or end of string)
|
|
556
566
|
let end = text.substr(m.index + m[0].length).match(/\r?\n\r?\n|$/);
|
|
@@ -591,8 +601,10 @@ async function bounceDetect(sourceStream) {
|
|
|
591
601
|
// Use bounded quantifier to prevent ReDoS with nested [\s\w]* patterns
|
|
592
602
|
let m = text.match(/Delivery[^:]{0,100}failed[^:]{0,50}:/im);
|
|
593
603
|
if (m) {
|
|
594
|
-
// Look for email address on the next line
|
|
595
|
-
|
|
604
|
+
// Look for email address on the next line. One whitespace quantifier: `\s*\n*\s*` was
|
|
605
|
+
// three overlapping ones (a newline is whitespace), and a few hundred newlines after
|
|
606
|
+
// the marker took seconds of backtracking
|
|
607
|
+
let addrMatch = text.substring(m.index + m[0].length).match(NEXT_TOKEN);
|
|
596
608
|
if (addrMatch && addrMatch[1].indexOf('@') >= 0) {
|
|
597
609
|
result.recipient = addrMatch[1].trim();
|
|
598
610
|
}
|
|
@@ -607,7 +619,7 @@ async function bounceDetect(sourceStream) {
|
|
|
607
619
|
*/
|
|
608
620
|
let m = text.match(/The following recipients were affected:/im);
|
|
609
621
|
if (m) {
|
|
610
|
-
let addrMatch = text.substr(m.index + m[0].length).match(
|
|
622
|
+
let addrMatch = text.substr(m.index + m[0].length).match(NEXT_TOKEN);
|
|
611
623
|
if (addrMatch && addrMatch[1].indexOf('@') >= 0) {
|
|
612
624
|
result.recipient = addrMatch[1].trim();
|
|
613
625
|
}
|
package/lib/consts.js
CHANGED
|
@@ -117,6 +117,12 @@ module.exports = {
|
|
|
117
117
|
|
|
118
118
|
LOGIN_PERIOD_TTL: 30 * 24 * 3600 * 1000,
|
|
119
119
|
|
|
120
|
+
// How long an admin session cookie is honoured after it was issued, whatever the browser
|
|
121
|
+
// does with it. The sealed cookie carries no expiry of its own, so without this a cookie
|
|
122
|
+
// captured once stayed valid until the next password change. Same length as the "remember
|
|
123
|
+
// me" cookie lifetime, so that option keeps meaning what it says
|
|
124
|
+
ADMIN_SESSION_MAX_AGE: 30 * 24 * 3600 * 1000,
|
|
125
|
+
|
|
120
126
|
DEFAULT_PAGE_SIZE: 20,
|
|
121
127
|
|
|
122
128
|
// Max POST payload size for message upload requests. NB! Does not apply for all routes
|
|
@@ -277,10 +283,35 @@ module.exports = {
|
|
|
277
283
|
|
|
278
284
|
// How many times to retry an email sending before it is considered as failing
|
|
279
285
|
DEFAULT_DELIVERY_ATTEMPTS: 10,
|
|
286
|
+
// The most a caller may ask for, through the API or the X-EE-Delivery-Attempts header of a
|
|
287
|
+
// stored draft or SMTP submission
|
|
288
|
+
MAX_DELIVERY_ATTEMPTS: 100,
|
|
289
|
+
|
|
290
|
+
// A mail merge turns one submit call into one queued message per entry, each a copy of the
|
|
291
|
+
// message with its attachments; the list is bounded and the copies are queued a few at a time
|
|
292
|
+
MAX_MAIL_MERGE_ENTRIES: 1000,
|
|
293
|
+
MAIL_MERGE_CONCURRENCY: 10,
|
|
280
294
|
|
|
281
295
|
// fixed boundary to prevent downloading attachments that are too large
|
|
282
296
|
MAX_ALLOWED_DOWNLOAD_SIZE: 250 * 1024 * 1024, // 250 MB
|
|
283
297
|
|
|
298
|
+
// How much of a suspected bounce or delivery report is fetched for parsing. The report and
|
|
299
|
+
// its delivery-status part come first and are small; what follows is the returned original,
|
|
300
|
+
// which the parse does not need and which a sender can make as large as the server allows
|
|
301
|
+
MAX_BOUNCE_DOWNLOAD_SIZE: 20 * 1024 * 1024, // 20 MB
|
|
302
|
+
|
|
303
|
+
// Bounds on what one IMAP server response may make a worker buffer, passed to every ImapFlow
|
|
304
|
+
// client (lib/create-imap-client.js). ImapFlow's own defaults are sized for one client talking
|
|
305
|
+
// to one trusted server (1 GB per line and literal, 2 GB per response); a worker here serves
|
|
306
|
+
// many accounts, and one hostile or broken server must not take them all down with it. The
|
|
307
|
+
// literal cap sits above MAX_ALLOWED_DOWNLOAD_SIZE, since a whole-message download is one
|
|
308
|
+
// literal, and the response cap leaves room for a multi-part FETCH and its framing. The line
|
|
309
|
+
// cap covers responses without a literal, where the largest legitimate one is a SEARCH
|
|
310
|
+
// result (a million UIDs is about 8 MB).
|
|
311
|
+
IMAP_MAX_LINE_LENGTH: 32 * 1024 * 1024, // 32 MB
|
|
312
|
+
IMAP_MAX_LITERAL_SIZE: 256 * 1024 * 1024, // 256 MB
|
|
313
|
+
IMAP_MAX_RESPONSE_SIZE: 512 * 1024 * 1024, // 512 MB
|
|
314
|
+
|
|
284
315
|
// while we do require a valid cert, the passing requirements are extremely low
|
|
285
316
|
TLS_DEFAULTS: {
|
|
286
317
|
minVersion: (process.env.EENGINE_TLS_MIN_VERSION || '').toString().trim() || 'TLSv1',
|
|
@@ -417,6 +448,9 @@ module.exports = {
|
|
|
417
448
|
'ETIMEDOUT',
|
|
418
449
|
'ECONNRESET',
|
|
419
450
|
'ECONNREFUSED',
|
|
451
|
+
// no route to the host, such as an IPv6 address on a host without IPv6 connectivity
|
|
452
|
+
'ENETUNREACH',
|
|
453
|
+
'EHOSTUNREACH',
|
|
420
454
|
'UND_ERR_SOCKET',
|
|
421
455
|
'UND_ERR_CONNECT_TIMEOUT',
|
|
422
456
|
'UND_ERR_HEADERS_TIMEOUT',
|
|
@@ -10,15 +10,54 @@
|
|
|
10
10
|
// every FETCH would fail on such a host. EmailEngine never reads that id (new messages are
|
|
11
11
|
// deduplicated on emailId or Message-ID, and the value only appears in a log line), so the
|
|
12
12
|
// algorithm is free to differ from ImapFlow's default on every installation.
|
|
13
|
+
//
|
|
14
|
+
// maxLineLength, maxLiteralSize, maxResponseSize: what one server response may make the worker
|
|
15
|
+
// buffer. ImapFlow's defaults (1 GB, 1 GB, 2 GB) assume one trusted server; a worker here serves
|
|
16
|
+
// many accounts, so a hostile or broken server answering one of them must not exhaust the memory
|
|
17
|
+
// of all of them. The values are in lib/consts.js with the reasoning.
|
|
18
|
+
//
|
|
19
|
+
// doSTARTTLS: a cleartext connection (`secure: false`) upgrades with STARTTLS and must succeed at
|
|
20
|
+
// it. Left unset, ImapFlow upgrades only when the server advertises STARTTLS and otherwise logs a
|
|
21
|
+
// warning and continues in cleartext, LOGIN included, which is what an on-path attacker who strips
|
|
22
|
+
// the capability gets. The account-level `requireTLS: false` is the opt-out for a server on a
|
|
23
|
+
// trusted network that has no TLS at all, and it leaves doSTARTTLS unset rather than false: the
|
|
24
|
+
// connection still upgrades when the server offers STARTTLS, the same as an SMTP transport with
|
|
25
|
+
// requireTLS off (lib/utils/require-tls.js). `requireTLS` is EmailEngine's field, not ImapFlow's,
|
|
26
|
+
// so it is consumed here. A connection that is `secure: true` from the start is not affected.
|
|
13
27
|
|
|
14
28
|
const { ImapFlow } = require('imapflow');
|
|
29
|
+
const { IMAP_MAX_LINE_LENGTH, IMAP_MAX_LITERAL_SIZE, IMAP_MAX_RESPONSE_SIZE } = require('./consts');
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Turns EmailEngine's connection configuration into ImapFlow options.
|
|
33
|
+
*
|
|
34
|
+
* @param {Object} config - Connection options, applied over the defaults
|
|
35
|
+
* @returns {Object} the options ImapFlow is constructed with
|
|
36
|
+
*/
|
|
37
|
+
function imapClientOptions(config) {
|
|
38
|
+
let { requireTLS, ...options } = config || {};
|
|
39
|
+
|
|
40
|
+
options = {
|
|
41
|
+
idHashAlgorithm: 'sha256',
|
|
42
|
+
maxLineLength: IMAP_MAX_LINE_LENGTH,
|
|
43
|
+
maxLiteralSize: IMAP_MAX_LITERAL_SIZE,
|
|
44
|
+
maxResponseSize: IMAP_MAX_RESPONSE_SIZE,
|
|
45
|
+
...options
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
if (!options.secure && options.doSTARTTLS === undefined && requireTLS !== false) {
|
|
49
|
+
options.doSTARTTLS = true;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
return options;
|
|
53
|
+
}
|
|
15
54
|
|
|
16
55
|
/**
|
|
17
56
|
* @param {Object} config - Connection options, applied over the defaults
|
|
18
57
|
* @returns {ImapFlow}
|
|
19
58
|
*/
|
|
20
59
|
function createImapClient(config) {
|
|
21
|
-
return new ImapFlow(
|
|
60
|
+
return new ImapFlow(imapClientOptions(config));
|
|
22
61
|
}
|
|
23
62
|
|
|
24
|
-
module.exports = { createImapClient };
|
|
63
|
+
module.exports = { createImapClient, imapClientOptions };
|
|
@@ -26,6 +26,7 @@ const { bounceDetect, applyDeliveryReport, PARSER_OPTIONS: DSN_PARSER_OPTIONS }
|
|
|
26
26
|
const { parseCalendarEvent, sortCalendarAttachments, CALENDAR_CONTENT_TYPES } = require('../calendar-event');
|
|
27
27
|
const { llmPreProcess, summaryFetchHeaders, summaryProvider } = require('../llm-pre-process');
|
|
28
28
|
const { notificationHeaderFields, narrowHeaders } = require('../utils/header-map');
|
|
29
|
+
const { mapConcurrent } = require('../utils/map-concurrent');
|
|
29
30
|
const { oauth2Apps } = require('../oauth2-apps');
|
|
30
31
|
const { Account } = require('../account');
|
|
31
32
|
const { removeBcc } = require('../get-raw-email');
|
|
@@ -71,6 +72,7 @@ const {
|
|
|
71
72
|
DEFAULT_DOWNLOAD_CHUNK_SIZE,
|
|
72
73
|
EMAIL_COMPLAINT_NOTIFY,
|
|
73
74
|
MAX_INLINE_ATTACHMENT_SIZE,
|
|
75
|
+
MAIL_MERGE_CONCURRENCY,
|
|
74
76
|
DEFAULT_MAX_IMAP_AUTH_FAILURE_TIME,
|
|
75
77
|
AUTH_FAILURE_DISABLED_FIELD,
|
|
76
78
|
LAST_ERROR_EVENT_FIELD,
|
|
@@ -1553,7 +1555,9 @@ class BaseClient {
|
|
|
1553
1555
|
return null;
|
|
1554
1556
|
}
|
|
1555
1557
|
|
|
1556
|
-
|
|
1558
|
+
// The account id is percent-encoded so the separator cannot occur in it: `a/b` + `c` and
|
|
1559
|
+
// `a` + `b/c` used to be the same key, and the cached dry-run preview of one leaked to the other
|
|
1560
|
+
const idempotencyKeyName = objName ? `${encodeURIComponent(objName)}/${idempotencyKey}` : idempotencyKey;
|
|
1557
1561
|
|
|
1558
1562
|
// check last 24-48 hours, so probably will return 2 keys, at rare cases 1
|
|
1559
1563
|
const { bucketKeys } = getDateBuckets(1 * 24 * 3600);
|
|
@@ -1781,10 +1785,10 @@ class BaseClient {
|
|
|
1781
1785
|
delete data.messageId;
|
|
1782
1786
|
delete data.to;
|
|
1783
1787
|
|
|
1784
|
-
|
|
1785
|
-
|
|
1786
|
-
//
|
|
1787
|
-
|
|
1788
|
+
// Queued a few at a time rather than all at once: every entry is a copy of the message,
|
|
1789
|
+
// attachments included, and a long list queued in parallel held every copy in memory and
|
|
1790
|
+
// every Redis write in flight together
|
|
1791
|
+
let queueEntry = async mailMergeEntry => {
|
|
1788
1792
|
let messageCopy = structuredClone(data);
|
|
1789
1793
|
if (messageCopy.sendAt) {
|
|
1790
1794
|
// date values do not survive JSON based copying
|
|
@@ -1806,15 +1810,21 @@ class BaseClient {
|
|
|
1806
1810
|
messageCopy.render.params = mailMergeEntry.params;
|
|
1807
1811
|
}
|
|
1808
1812
|
|
|
1809
|
-
|
|
1810
|
-
}
|
|
1813
|
+
return await this.queueMessageEntry(messageCopy, meta, licenseInfo, connectionOptions);
|
|
1814
|
+
};
|
|
1815
|
+
|
|
1816
|
+
// every entry is attempted and reports its own outcome, so the pool never stops early
|
|
1817
|
+
let results = await mapConcurrent(mailMergeList, MAIL_MERGE_CONCURRENCY, async mailMergeEntry => {
|
|
1818
|
+
try {
|
|
1819
|
+
return { status: 'fulfilled', value: await queueEntry(mailMergeEntry) };
|
|
1820
|
+
} catch (reason) {
|
|
1821
|
+
return { status: 'rejected', reason };
|
|
1822
|
+
}
|
|
1823
|
+
});
|
|
1811
1824
|
|
|
1812
1825
|
let response = {
|
|
1813
1826
|
mailMerge: []
|
|
1814
1827
|
};
|
|
1815
|
-
|
|
1816
|
-
// Process all messages in parallel
|
|
1817
|
-
let results = await Promise.allSettled(messageProcessors);
|
|
1818
1828
|
for (let i = 0; i < mailMergeList.length; i++) {
|
|
1819
1829
|
let mailMergeEntry = mailMergeList[i];
|
|
1820
1830
|
let resultEntry = results[i];
|
|
@@ -9,6 +9,7 @@ const addressparser = require('nodemailer/lib/addressparser');
|
|
|
9
9
|
const libmime = require('libmime');
|
|
10
10
|
const he = require('he');
|
|
11
11
|
const { BaseClient, metricsMeta } = require('./base-client');
|
|
12
|
+
const { isSafePathSegment } = require('../utils/provider-id');
|
|
12
13
|
const { isTransientCredentialError } = require('./credential-errors');
|
|
13
14
|
const { messageWebSafeHtml, applyWebSafeHtmlOptions } = require('../web-safe-html');
|
|
14
15
|
const { emitChangeEvent, toCamelCase, collectCidReferences, embedCidImages, truncateTextContents, readEnvValue } = require('../tools');
|
|
@@ -773,7 +774,7 @@ class GmailClient extends BaseClient {
|
|
|
773
774
|
if (query.search.emailId) {
|
|
774
775
|
// Return only a single matching email
|
|
775
776
|
|
|
776
|
-
let messageEntry = await this.request(`${GMAIL_API_BASE}/gmail/v1/users/me/messages/${query.search.emailId}`, 'get', {
|
|
777
|
+
let messageEntry = await this.request(`${GMAIL_API_BASE}/gmail/v1/users/me/messages/${encodeURIComponent(query.search.emailId)}`, 'get', {
|
|
777
778
|
format: 'full'
|
|
778
779
|
});
|
|
779
780
|
|
|
@@ -796,9 +797,13 @@ class GmailClient extends BaseClient {
|
|
|
796
797
|
|
|
797
798
|
if (query.search.threadId) {
|
|
798
799
|
// Threading is a special case - fetch entire thread
|
|
799
|
-
let threadListingResult = await this.request(
|
|
800
|
-
|
|
801
|
-
|
|
800
|
+
let threadListingResult = await this.request(
|
|
801
|
+
`${GMAIL_API_BASE}/gmail/v1/users/me/threads/${encodeURIComponent(query.search.threadId)}`,
|
|
802
|
+
'get',
|
|
803
|
+
{
|
|
804
|
+
format: 'full'
|
|
805
|
+
}
|
|
806
|
+
);
|
|
802
807
|
|
|
803
808
|
let messageCount = threadListingResult?.messages?.length || 0;
|
|
804
809
|
let currentPage = pageCursor.currentPage();
|
|
@@ -1447,7 +1452,7 @@ class GmailClient extends BaseClient {
|
|
|
1447
1452
|
// Decode text part references
|
|
1448
1453
|
const [emailId, textParts] = this.unpackApiId(
|
|
1449
1454
|
textId,
|
|
1450
|
-
parts => parts.length >= 2 && Array.isArray(parts[1]) && Array.isArray(parts[1][0]) && Array.isArray(parts[1][1])
|
|
1455
|
+
parts => parts.length >= 2 && isSafePathSegment(parts[0]) && Array.isArray(parts[1]) && Array.isArray(parts[1][0]) && Array.isArray(parts[1][1])
|
|
1451
1456
|
);
|
|
1452
1457
|
|
|
1453
1458
|
const bodyParts = new Map();
|
|
@@ -2710,12 +2715,21 @@ class GmailClient extends BaseClient {
|
|
|
2710
2715
|
*/
|
|
2711
2716
|
async getAttachmentContent(attachmentId, options) {
|
|
2712
2717
|
options = options || {};
|
|
2713
|
-
|
|
2718
|
+
// The message and attachment parts become path segments of the API URL, so a part that
|
|
2719
|
+
// would leave its segment is an invalid id rather than a request for a different resource
|
|
2720
|
+
const [emailId, contentType, disposition, filename, id] = this.unpackApiId(
|
|
2721
|
+
attachmentId,
|
|
2722
|
+
parts => parts.length >= 5 && isSafePathSegment(parts[0]) && isSafePathSegment(parts[4])
|
|
2723
|
+
);
|
|
2714
2724
|
|
|
2715
2725
|
await this.prepare();
|
|
2716
2726
|
|
|
2717
2727
|
const requestQuery = {};
|
|
2718
|
-
const result = await this.request(
|
|
2728
|
+
const result = await this.request(
|
|
2729
|
+
`${GMAIL_API_BASE}/gmail/v1/users/me/messages/${encodeURIComponent(emailId)}/attachments/${encodeURIComponent(id)}`,
|
|
2730
|
+
'get',
|
|
2731
|
+
requestQuery
|
|
2732
|
+
);
|
|
2719
2733
|
|
|
2720
2734
|
const content = result?.data ? Buffer.from(result?.data, 'base64url') : null;
|
|
2721
2735
|
|
|
@@ -45,6 +45,7 @@ const {
|
|
|
45
45
|
REDIS_PREFIX,
|
|
46
46
|
MAX_INLINE_ATTACHMENT_SIZE,
|
|
47
47
|
MAX_ALLOWED_DOWNLOAD_SIZE,
|
|
48
|
+
MAX_BOUNCE_DOWNLOAD_SIZE,
|
|
48
49
|
TRANSIENT_NETWORK_CODES,
|
|
49
50
|
CONNECTION_CLOSING_CODES,
|
|
50
51
|
PHANTOM_SELECT_FAIL_THRESHOLD,
|
|
@@ -1340,10 +1341,13 @@ class Mailbox {
|
|
|
1340
1341
|
if (this.connection.mightBeDSNResponse(messageInfo)) {
|
|
1341
1342
|
let sourceStream;
|
|
1342
1343
|
try {
|
|
1344
|
+
// A delivery report is small and its status part comes first, so the download is
|
|
1345
|
+
// cut well below the general cap: the rest is the returned original, which the
|
|
1346
|
+
// parse does not need and which a sender can make as large as the server allows
|
|
1343
1347
|
({ content: sourceStream } = await this.requireImapClient().download(messageInfo.uid, false, {
|
|
1344
1348
|
uid: true,
|
|
1345
1349
|
chunkSize: options.chunkSize,
|
|
1346
|
-
maxBytes:
|
|
1350
|
+
maxBytes: MAX_BOUNCE_DOWNLOAD_SIZE
|
|
1347
1351
|
}));
|
|
1348
1352
|
|
|
1349
1353
|
// No content means the message was expunged after it was detected (a server-side
|
|
@@ -1382,7 +1386,7 @@ class Mailbox {
|
|
|
1382
1386
|
let result = await this.requireImapClient().download(messageInfo.uid, false, {
|
|
1383
1387
|
uid: true,
|
|
1384
1388
|
chunkSize: options.chunkSize,
|
|
1385
|
-
maxBytes:
|
|
1389
|
+
maxBytes: MAX_BOUNCE_DOWNLOAD_SIZE
|
|
1386
1390
|
});
|
|
1387
1391
|
content = result.content;
|
|
1388
1392
|
}
|
|
@@ -1679,7 +1683,8 @@ class Mailbox {
|
|
|
1679
1683
|
// Download missing attachments in batch
|
|
1680
1684
|
try {
|
|
1681
1685
|
let contentParts = await this.requireImapClient().downloadMany(messageInfo.uid, partList, {
|
|
1682
|
-
uid: true
|
|
1686
|
+
uid: true,
|
|
1687
|
+
maxBytes: MAX_ALLOWED_DOWNLOAD_SIZE
|
|
1683
1688
|
});
|
|
1684
1689
|
|
|
1685
1690
|
if (contentParts) {
|
|
@@ -2653,7 +2658,8 @@ class Mailbox {
|
|
|
2653
2658
|
|
|
2654
2659
|
// Download all referenced images in batch
|
|
2655
2660
|
let contentParts = await connectionClient.downloadMany(messageInfo.uid, partList, {
|
|
2656
|
-
uid: true
|
|
2661
|
+
uid: true,
|
|
2662
|
+
maxBytes: MAX_ALLOWED_DOWNLOAD_SIZE
|
|
2657
2663
|
});
|
|
2658
2664
|
|
|
2659
2665
|
if (contentParts) {
|