emailengine-app 2.74.2 → 2.75.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/CHANGELOG.md +25 -0
- package/data/google-crawlers.json +1 -1
- package/lib/account.js +94 -18
- package/lib/api-routes/message-routes.js +3 -1
- package/lib/consts.js +6 -0
- package/lib/db.js +4 -1
- package/lib/egress-filter.js +220 -0
- package/lib/email-client/base-client.js +5 -8
- package/lib/email-client/gmail-client.js +2 -5
- package/lib/email-client/imap/mailbox.js +3 -9
- package/lib/email-client/notification-handler.js +11 -12
- package/lib/email-client/outlook-client.js +2 -5
- package/lib/imapproxy/imap-core/README.md +69 -0
- package/lib/oauth/external-account-config.js +41 -1
- package/lib/oauth/external-account-signer.js +7 -2
- package/lib/oauth/verify-app.js +18 -3
- package/lib/queue-retention.js +56 -0
- package/lib/respawn-backoff.js +95 -0
- package/lib/schemas.js +9 -2
- package/lib/settings.js +4 -1
- package/lib/tools.js +20 -0
- package/lib/ui-routes/admin-config-routes.js +22 -18
- package/lib/utils/network.js +122 -3
- package/lib/web-safe-html.js +401 -0
- package/lib/webhook-request.js +40 -2
- package/lib/webhooks.js +2 -3
- package/package.json +10 -8
- package/sbom.json +1 -1
- package/server.js +33 -8
- package/static/js/ee-client.js +55 -6
- package/static/js/ui.js +13 -0
- package/static/licenses.html +325 -285
- package/translations/messages.pot +26 -26
- package/views/config/webhooks.hbs +2 -2
- package/views/partials/webhooks_editor_functions.hbs +1 -1
- package/workers/api.js +32 -17
- package/workers/documents.js +6 -0
- package/workers/export.js +8 -1
- package/workers/imap.js +17 -19
- package/workers/submit.js +10 -0
- package/workers/webhooks.js +23 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,30 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## [2.75.0](https://github.com/postalsys/emailengine/compare/v2.74.2...v2.75.0) (2026-07-28)
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
### Features
|
|
7
|
+
|
|
8
|
+
* **web-safe-html:** fold quoted thread history into a collapse marker ([25d45bf](https://github.com/postalsys/emailengine/commit/25d45bf5b8dcc64443272f4b85178ee2c497d79c))
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
### Bug Fixes
|
|
12
|
+
|
|
13
|
+
* **account:** serialize account updates so a refreshed token is not lost ([e577825](https://github.com/postalsys/emailengine/commit/e5778255710b1be912e6b259073ec963c2da03a2))
|
|
14
|
+
* **api:** match IPv4-mapped peer addresses against the address allowlists ([5acff06](https://github.com/postalsys/emailengine/commit/5acff061b31af6db49ffe9d856a5017bdfcaf4e7))
|
|
15
|
+
* **api:** trust X-Forwarded-For only from declared proxies ([6e93ea7](https://github.com/postalsys/emailengine/commit/6e93ea714cd75aa876f713345d675a5416b36aeb))
|
|
16
|
+
* **api:** warn about a spoofable admin allowlist when the proxy list is empty ([4309abe](https://github.com/postalsys/emailengine/commit/4309abe2d45652699f76b4adc31ff37e79802a53))
|
|
17
|
+
* **deps:** bump imapflow to 1.6.1 to restore IMAP account verification ([c2a5437](https://github.com/postalsys/emailengine/commit/c2a543779b29c369d35bfbbc175810fc1d96f02c))
|
|
18
|
+
* **deps:** update @postalsys/email-ai-tools to 1.13.15 ([89ec145](https://github.com/postalsys/emailengine/commit/89ec145a8f43a29405cf154825601dd8ba10fae6))
|
|
19
|
+
* **deps:** update dependencies ([@bull-board](https://github.com/bull-board) 8.3.2) ([a5644f3](https://github.com/postalsys/emailengine/commit/a5644f34e56128451c642d2034ddf7db0d1cc7a8))
|
|
20
|
+
* **logging:** stop logging decrypted setting values and lower Redis reconnect noise ([5c62ac4](https://github.com/postalsys/emailengine/commit/5c62ac486112688e8a964c66a43eb609abe7c8da))
|
|
21
|
+
* **oauth:** pin external account token_url to Google STS ([27ade81](https://github.com/postalsys/emailengine/commit/27ade8183cd31b503077ebefd5724f2f0620947d))
|
|
22
|
+
* **queue:** retain failed queue entries instead of deleting them on arrival ([e83af35](https://github.com/postalsys/emailengine/commit/e83af359aafc49d584cd0c234e089e9dceb83f3b))
|
|
23
|
+
* **server:** drain workers on shutdown and back off crash-looping respawns ([29b3b5d](https://github.com/postalsys/emailengine/commit/29b3b5d0d7b76793ea2852c9a37a8c622217a6ea))
|
|
24
|
+
* **webhooks:** filter webhook egress and stop following redirects ([e44bed5](https://github.com/postalsys/emailengine/commit/e44bed549848d8eb2b04bb991aa2c6cee0bb47c2))
|
|
25
|
+
* **webhooks:** report the refused redirect status and probe through the delivery path ([9f7c666](https://github.com/postalsys/emailengine/commit/9f7c666f5e2a0bfae069a0c43c33a75d04922747))
|
|
26
|
+
* **webhooks:** stop retrying an endpoint that answers with a redirect ([bbb6055](https://github.com/postalsys/emailengine/commit/bbb605560d31bb494495b46a57cd233a78024d99))
|
|
27
|
+
|
|
3
28
|
## [2.74.2](https://github.com/postalsys/emailengine/compare/v2.74.1...v2.74.2) (2026-07-26)
|
|
4
29
|
|
|
5
30
|
|
package/lib/account.js
CHANGED
|
@@ -21,6 +21,7 @@ const { deepStrictEqual, strictEqual } = require('assert');
|
|
|
21
21
|
const { encrypt, decrypt } = require('./encrypt');
|
|
22
22
|
const { oauth2Apps, LEGACY_KEYS, isApiBasedApp } = require('./oauth2-apps');
|
|
23
23
|
const settings = require('./settings');
|
|
24
|
+
const { buildRetentionPolicy } = require('./queue-retention');
|
|
24
25
|
const { isDocumentStoreEnabled, documentStoreFeatureEnabled } = require('./document-store');
|
|
25
26
|
const redisScanDelete = require('./redis-scan-delete');
|
|
26
27
|
const { customAlphabet } = require('nanoid');
|
|
@@ -28,7 +29,7 @@ const Lock = require('ioredfour');
|
|
|
28
29
|
const { redis } = require('./db');
|
|
29
30
|
const nanoid = customAlphabet('0123456789abcdefghijklmnopqrstuvwxyz', 16);
|
|
30
31
|
const { REDIS_PREFIX, ACCOUNT_DELETED_NOTIFY } = require('./consts');
|
|
31
|
-
const {
|
|
32
|
+
const { messageWebSafeHtml } = require('./web-safe-html');
|
|
32
33
|
const { checkAccountScopes: checkScopes } = require('./oauth/scope-checker');
|
|
33
34
|
const { ACCOUNT_STATES, ERROR_STATES, calculateEffectiveState, validateAccountState, getDisplayState, formatLastError } = require('./account/account-state');
|
|
34
35
|
const { decodeStoredMailboxEntry } = require('./email-client/imap/listing-diff');
|
|
@@ -40,6 +41,11 @@ const defaultLock = new Lock({
|
|
|
40
41
|
namespace: 'ee'
|
|
41
42
|
});
|
|
42
43
|
|
|
44
|
+
// Serialization window for Account.update(). The critical section is a few Redis round trips, so
|
|
45
|
+
// the TTL only has to cover a stalled writer, and the wait only has to outlast a normal one.
|
|
46
|
+
const ACCOUNT_UPDATE_LOCK_TTL = 10 * 1000;
|
|
47
|
+
const ACCOUNT_UPDATE_LOCK_WAIT = 5 * 1000;
|
|
48
|
+
|
|
43
49
|
class Account {
|
|
44
50
|
constructor(options) {
|
|
45
51
|
this.redis = options.redis;
|
|
@@ -725,11 +731,74 @@ class Account {
|
|
|
725
731
|
return accountData;
|
|
726
732
|
}
|
|
727
733
|
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
734
|
+
/**
|
|
735
|
+
* Applies an account update, serialized per account.
|
|
736
|
+
*
|
|
737
|
+
* persistUpdate() is a read-modify-write: it loads the stored account, merges partial
|
|
738
|
+
* `imap`/`smtp`/`oauth2` objects into what it read, and writes the result back. Two writers
|
|
739
|
+
* interleaving there silently lose one of the merges - the case that matters is an unattended
|
|
740
|
+
* OAuth2 token refresh landing between an admin update's read and its write, which puts the
|
|
741
|
+
* stale refreshToken back and leaves the account unable to authenticate until someone
|
|
742
|
+
* reauthorizes it by hand. The same check-then-set applies to the OAuth2 user uniqueness
|
|
743
|
+
* check inside. The lock covers that half only; see dispatchPostUpdateCommands().
|
|
744
|
+
*
|
|
745
|
+
* Lock acquisition failing is not treated as an error. The critical section is a handful of
|
|
746
|
+
* Redis round trips, so a timeout here means Redis is already in trouble; refusing the write
|
|
747
|
+
* would take out token refreshes for every account rather than losing a rare merge.
|
|
748
|
+
*
|
|
749
|
+
* @param {Object} accountData - Account fields to write
|
|
750
|
+
* @param {Object} [opts]
|
|
751
|
+
* @param {boolean} [opts.reauthorized] - Marks an update carrying credentials supplied by an
|
|
752
|
+
* external caller, i.e. possible operator re-authorization. Only the public account-update
|
|
753
|
+
* API route sets it; every unattended writer (token renewal, client initialize(),
|
|
754
|
+
* invalidateAccessToken) leaves it false and can therefore never trigger the reconnect gate.
|
|
755
|
+
* @returns {Promise<Object>} `{ account }`
|
|
756
|
+
*/
|
|
732
757
|
async update(accountData, { reauthorized = false } = {}) {
|
|
758
|
+
const lock = this.getLock();
|
|
759
|
+
const lockKey = `account:update:${accountData.account}`;
|
|
760
|
+
let updateLock;
|
|
761
|
+
|
|
762
|
+
let lockErr;
|
|
763
|
+
try {
|
|
764
|
+
updateLock = await lock.waitAcquireLock(lockKey, ACCOUNT_UPDATE_LOCK_TTL, ACCOUNT_UPDATE_LOCK_WAIT);
|
|
765
|
+
} catch (err) {
|
|
766
|
+
lockErr = err;
|
|
767
|
+
}
|
|
768
|
+
|
|
769
|
+
if (!updateLock?.success) {
|
|
770
|
+
this.logger.warn({ msg: 'Failed to get account update lock, proceeding unserialized', account: accountData.account, lockKey, err: lockErr });
|
|
771
|
+
}
|
|
772
|
+
|
|
773
|
+
let oldAccountData;
|
|
774
|
+
try {
|
|
775
|
+
oldAccountData = await this.persistUpdate(accountData);
|
|
776
|
+
} finally {
|
|
777
|
+
if (updateLock?.success) {
|
|
778
|
+
try {
|
|
779
|
+
await lock.releaseLock(updateLock);
|
|
780
|
+
} catch (err) {
|
|
781
|
+
// The lock expires on its own, so a failed release must not mask the result
|
|
782
|
+
this.logger.error({ msg: 'Failed to release account update lock', account: accountData.account, lockKey, err });
|
|
783
|
+
}
|
|
784
|
+
}
|
|
785
|
+
}
|
|
786
|
+
|
|
787
|
+
await this.dispatchPostUpdateCommands(accountData, oldAccountData, reauthorized);
|
|
788
|
+
|
|
789
|
+
return {
|
|
790
|
+
account: this.account
|
|
791
|
+
};
|
|
792
|
+
}
|
|
793
|
+
|
|
794
|
+
/**
|
|
795
|
+
* The read-modify-write half of update(): loads the stored account, merges partial credential
|
|
796
|
+
* objects into it and writes the result back. Runs under the update lock.
|
|
797
|
+
*
|
|
798
|
+
* @param {Object} accountData - Account fields to write
|
|
799
|
+
* @returns {Promise<Object>} The account as it was before the write
|
|
800
|
+
*/
|
|
801
|
+
async persistUpdate(accountData) {
|
|
733
802
|
let oldAccountData = await this.loadAccountData(accountData.account);
|
|
734
803
|
|
|
735
804
|
if (accountData.oauth2?.provider) {
|
|
@@ -822,6 +891,23 @@ class Account {
|
|
|
822
891
|
throw error;
|
|
823
892
|
}
|
|
824
893
|
|
|
894
|
+
return oldAccountData;
|
|
895
|
+
}
|
|
896
|
+
|
|
897
|
+
/**
|
|
898
|
+
* Dispatches the reconnect/update commands a persisted change implies.
|
|
899
|
+
*
|
|
900
|
+
* Deliberately runs outside the update lock. These are RPCs into the IMAP worker, and the
|
|
901
|
+
* connection setup they trigger can itself persist an account change (a token renewal during
|
|
902
|
+
* connect), so holding the lock across them would make a writer wait on its own dispatch.
|
|
903
|
+
* Nothing here writes account data; it only compares what was read against what was written.
|
|
904
|
+
*
|
|
905
|
+
* @param {Object} accountData - The fields that were just written
|
|
906
|
+
* @param {Object} oldAccountData - The account as it was before the write
|
|
907
|
+
* @param {boolean} reauthorized - Whether the caller supplied fresh operator credentials
|
|
908
|
+
* @returns {Promise<void>} Resolves once the dispatch has been attempted
|
|
909
|
+
*/
|
|
910
|
+
async dispatchPostUpdateCommands(accountData, oldAccountData, reauthorized) {
|
|
825
911
|
let reconnectRequested = false;
|
|
826
912
|
|
|
827
913
|
if ('imap' in accountData && !reconnectRequested) {
|
|
@@ -915,10 +1001,6 @@ class Account {
|
|
|
915
1001
|
});
|
|
916
1002
|
}
|
|
917
1003
|
}
|
|
918
|
-
|
|
919
|
-
return {
|
|
920
|
-
account: this.account
|
|
921
|
-
};
|
|
922
1004
|
}
|
|
923
1005
|
|
|
924
1006
|
async genId() {
|
|
@@ -1153,7 +1235,7 @@ class Account {
|
|
|
1153
1235
|
// consumed and would pile up in Redis.
|
|
1154
1236
|
if (documentStoreFeatureEnabled) {
|
|
1155
1237
|
try {
|
|
1156
|
-
let queueKeep = (await settings.get('queueKeep'))
|
|
1238
|
+
let queueKeep = (await settings.get('queueKeep')) ?? true;
|
|
1157
1239
|
let serviceUrl = (await settings.get('serviceUrl')) || null;
|
|
1158
1240
|
|
|
1159
1241
|
let payload = {
|
|
@@ -1164,8 +1246,7 @@ class Account {
|
|
|
1164
1246
|
};
|
|
1165
1247
|
|
|
1166
1248
|
await this.documentsQueue.add(ACCOUNT_DELETED_NOTIFY, payload, {
|
|
1167
|
-
|
|
1168
|
-
removeOnFail: queueKeep,
|
|
1249
|
+
...buildRetentionPolicy(queueKeep),
|
|
1169
1250
|
attempts: 10,
|
|
1170
1251
|
backoff: {
|
|
1171
1252
|
type: 'exponential',
|
|
@@ -1691,12 +1772,7 @@ class Account {
|
|
|
1691
1772
|
|
|
1692
1773
|
if (options.preProcessHtml && messageData.text && (messageData.text.html || messageData.text.plain)) {
|
|
1693
1774
|
// If available, use the cached version
|
|
1694
|
-
messageData.text.html =
|
|
1695
|
-
messageData.text._generatedHtml ||
|
|
1696
|
-
mimeHtml({
|
|
1697
|
-
html: messageData.text.html,
|
|
1698
|
-
text: messageData.text.plain
|
|
1699
|
-
});
|
|
1775
|
+
messageData.text.html = messageData.text._generatedHtml || (await messageWebSafeHtml(messageData));
|
|
1700
1776
|
messageData.text.webSafe = true;
|
|
1701
1777
|
messageData.text._cachedWebSafe = !!messageData.text._generatedHtml;
|
|
1702
1778
|
}
|
|
@@ -6,6 +6,7 @@ const getSecret = require('../get-secret');
|
|
|
6
6
|
const settings = require('../settings');
|
|
7
7
|
const Joi = require('joi');
|
|
8
8
|
const { failAction } = require('../tools');
|
|
9
|
+
const { COLLAPSE_CLASS } = require('../consts');
|
|
9
10
|
const { handleError } = require('./route-helpers');
|
|
10
11
|
|
|
11
12
|
const {
|
|
@@ -168,7 +169,8 @@ async function init(args) {
|
|
|
168
169
|
.falsy('N', 'false', 0)
|
|
169
170
|
.default(false)
|
|
170
171
|
.description(
|
|
171
|
-
'Shorthand option to fetch and preprocess HTML and inline images. Overrides `textType`, `preProcessHtml`, and `embedAttachedImages` options.'
|
|
172
|
+
'Shorthand option to fetch and preprocess HTML and inline images. Overrides `textType`, `preProcessHtml`, and `embedAttachedImages` options. ' +
|
|
173
|
+
`Quoted thread history is folded into a single collapsed <details class="${COLLAPSE_CLASS}"> element.`
|
|
172
174
|
)
|
|
173
175
|
.label('WebSafeHtml'),
|
|
174
176
|
|
package/lib/consts.js
CHANGED
|
@@ -200,6 +200,12 @@ module.exports = {
|
|
|
200
200
|
|
|
201
201
|
NONCE_BYTES: 16,
|
|
202
202
|
|
|
203
|
+
// Class names on the collapse marker web-safe HTML wraps quoted thread history in. Part of the
|
|
204
|
+
// output contract - consumers select on them to style or hide the block - so they are defined
|
|
205
|
+
// once here and referenced by both the generator (lib/web-safe-html.js) and the API docs.
|
|
206
|
+
COLLAPSE_CLASS: 'ee-collapsed-thread',
|
|
207
|
+
COLLAPSE_TOGGLE_CLASS: 'ee-collapsed-thread-toggle',
|
|
208
|
+
|
|
203
209
|
// We are using a legacy hash function in caching operations
|
|
204
210
|
// This is not insecure but it pops out in security scanners, so we need to mask the name of the hash
|
|
205
211
|
MAILBOX_HASH: Buffer.from('c2hhMQ', 'base64url').toString(),
|
package/lib/db.js
CHANGED
|
@@ -54,7 +54,10 @@ const REDIS_CONF = Object.assign(
|
|
|
54
54
|
return delay;
|
|
55
55
|
},
|
|
56
56
|
reconnectOnError(err) {
|
|
57
|
-
|
|
57
|
+
// Not fatal: this fires on every transient connection error and we always reconnect,
|
|
58
|
+
// so logging it at fatal turned an ordinary Redis failover into a burst of top
|
|
59
|
+
// severity alerts. The retryStrategy above reports the actual retry cadence.
|
|
60
|
+
logger.warn({ msg: 'Redis connection error', isMainThread, threadId, err });
|
|
58
61
|
// always try to reconnect
|
|
59
62
|
return true;
|
|
60
63
|
},
|
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const net = require('net');
|
|
4
|
+
const dns = require('dns').promises;
|
|
5
|
+
const ipaddr = require('ipaddr.js');
|
|
6
|
+
|
|
7
|
+
// Egress policies for operator-supplied outbound URLs (webhook targets), least to most
|
|
8
|
+
// restrictive. EmailEngine is usually self-hosted alongside the services it notifies, so
|
|
9
|
+
// blocking private ranges outright would break ordinary deployments - the default therefore only
|
|
10
|
+
// blocks the link-local range, which is where every cloud provider parks its instance metadata
|
|
11
|
+
// service and which no real webhook receiver lives on.
|
|
12
|
+
const POLICY_OFF = 'off';
|
|
13
|
+
const POLICY_LINK_LOCAL = 'link-local';
|
|
14
|
+
const POLICY_PRIVATE = 'private';
|
|
15
|
+
|
|
16
|
+
const VALID_POLICIES = new Set([POLICY_OFF, POLICY_LINK_LOCAL, POLICY_PRIVATE]);
|
|
17
|
+
|
|
18
|
+
// Range names come from ipaddr.js `range()`
|
|
19
|
+
const LINK_LOCAL_BLOCKED_RANGES = new Set(['linkLocal']);
|
|
20
|
+
|
|
21
|
+
const PRIVATE_BLOCKED_RANGES = new Set([
|
|
22
|
+
'linkLocal',
|
|
23
|
+
'loopback',
|
|
24
|
+
'private',
|
|
25
|
+
'uniqueLocal',
|
|
26
|
+
'carrierGradeNat',
|
|
27
|
+
'reserved',
|
|
28
|
+
'unspecified',
|
|
29
|
+
'broadcast',
|
|
30
|
+
'multicast'
|
|
31
|
+
]);
|
|
32
|
+
|
|
33
|
+
// Metadata endpoints that range classification alone does not catch under the default policy:
|
|
34
|
+
// AWS serves IMDS over IPv6 from a unique-local address, and Alibaba Cloud parks its IMDS in the
|
|
35
|
+
// carrier-grade NAT range. Normalized forms, compared against a normalized subject.
|
|
36
|
+
const ALWAYS_BLOCKED_ADDRESSES = new Set(['fd00:ec2:0:0:0:0:0:254', '100.100.100.200']);
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Resolves the configured egress policy, falling back to the default for unknown values.
|
|
40
|
+
* @param {string} [value] - Raw configured value
|
|
41
|
+
* @returns {string} One of the POLICY_* constants
|
|
42
|
+
*/
|
|
43
|
+
function normalizePolicy(value) {
|
|
44
|
+
let policy = (value || '').toString().trim().toLowerCase();
|
|
45
|
+
return VALID_POLICIES.has(policy) ? policy : POLICY_LINK_LOCAL;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Checks a single IP address against an egress policy.
|
|
50
|
+
*
|
|
51
|
+
* IPv4-mapped IPv6 addresses are unwrapped first, otherwise `::ffff:169.254.169.254` would be
|
|
52
|
+
* classified as a plain IPv6 unicast address and sail through.
|
|
53
|
+
*
|
|
54
|
+
* @param {string} ip - IP address to classify
|
|
55
|
+
* @param {string} policy - One of the POLICY_* constants
|
|
56
|
+
* @returns {boolean} True when the address must not be contacted
|
|
57
|
+
*/
|
|
58
|
+
function isBlockedAddress(ip, policy) {
|
|
59
|
+
if (policy === POLICY_OFF) {
|
|
60
|
+
return false;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
let parsed;
|
|
64
|
+
try {
|
|
65
|
+
parsed = ipaddr.parse(ip);
|
|
66
|
+
} catch (err) {
|
|
67
|
+
// Fail closed: an address we can not classify is not one we should connect to
|
|
68
|
+
return true;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
if (parsed.kind() === 'ipv6' && parsed.isIPv4MappedAddress()) {
|
|
72
|
+
parsed = parsed.toIPv4Address();
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
if (ALWAYS_BLOCKED_ADDRESSES.has(parsed.toNormalizedString())) {
|
|
76
|
+
return true;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const blockedRanges = policy === POLICY_PRIVATE ? PRIVATE_BLOCKED_RANGES : LINK_LOCAL_BLOCKED_RANGES;
|
|
80
|
+
|
|
81
|
+
return blockedRanges.has(parsed.range());
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Builds the error thrown for a blocked destination. Carries `code` so callers can recognize a
|
|
86
|
+
* policy rejection and stop retrying: a blocked target is a configuration problem, and burning
|
|
87
|
+
* ten attempts on it only delays the operator seeing the real reason.
|
|
88
|
+
* @param {string} reason - Human readable explanation
|
|
89
|
+
* @returns {Error} Error tagged with code EEGRESSBLOCKED
|
|
90
|
+
*/
|
|
91
|
+
function blockedError(reason) {
|
|
92
|
+
let err = new Error(reason);
|
|
93
|
+
err.code = 'EEGRESSBLOCKED';
|
|
94
|
+
return err;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
// An operator who does not know this policy exists otherwise has nothing to search for: the
|
|
98
|
+
// message would describe a refusal without naming what is refusing. It also reaches operators who
|
|
99
|
+
// only ever see the log line, which no amount of UI help would.
|
|
100
|
+
const POLICY_HINT = 'See EENGINE_WEBHOOK_EGRESS_POLICY if this destination is intended.';
|
|
101
|
+
|
|
102
|
+
// A destination the policy refuses, as opposed to one we could not parse - the hint belongs on the
|
|
103
|
+
// former only, since the setting cannot help with a malformed URL
|
|
104
|
+
const policyBlockedError = reason => blockedError(`${reason}. ${POLICY_HINT}`);
|
|
105
|
+
|
|
106
|
+
// Verdict cache for resolved hostnames. Node's dns.lookup has no cache of its own and glibc has
|
|
107
|
+
// none either without nscd, so without this every webhook delivery pays a resolver round trip -
|
|
108
|
+
// and the notify worker runs at concurrency 1 by default, so that cost is fully serialized ahead
|
|
109
|
+
// of each POST. Caching the verdict rather than the addresses keeps entries tiny.
|
|
110
|
+
//
|
|
111
|
+
// This gives up nothing: undici resolves the name again independently when it connects, so the
|
|
112
|
+
// check is inherently time-of-check/time-of-use racy and a short TTL introduces no hole that was
|
|
113
|
+
// not already there. Distinct webhook targets are few, so the hit rate is effectively total.
|
|
114
|
+
const VERDICT_TTL = 60 * 1000;
|
|
115
|
+
const VERDICT_CACHE_LIMIT = 1000;
|
|
116
|
+
const verdictCache = new Map();
|
|
117
|
+
|
|
118
|
+
function readCachedVerdict(key) {
|
|
119
|
+
const hit = verdictCache.get(key);
|
|
120
|
+
if (!hit) {
|
|
121
|
+
return null;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
if (hit.expires <= Date.now()) {
|
|
125
|
+
verdictCache.delete(key);
|
|
126
|
+
return null;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
return hit;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
function cacheVerdict(key, blockedBy) {
|
|
133
|
+
// Bounded: drop the oldest entry once full. Map preserves insertion order.
|
|
134
|
+
if (verdictCache.size >= VERDICT_CACHE_LIMIT) {
|
|
135
|
+
verdictCache.delete(verdictCache.keys().next().value);
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
verdictCache.set(key, { blockedBy, expires: Date.now() + VERDICT_TTL });
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* Verifies that a URL may be contacted under the given egress policy.
|
|
143
|
+
*
|
|
144
|
+
* Hostnames are resolved and every returned address is checked, so a name that points at a
|
|
145
|
+
* blocked address is rejected just like a literal would be.
|
|
146
|
+
*
|
|
147
|
+
* @param {string} url - Destination URL
|
|
148
|
+
* @param {Object} [opts]
|
|
149
|
+
* @param {string} [opts.policy] - One of the POLICY_* constants, defaults to the link-local policy
|
|
150
|
+
* @param {Function} [opts.resolve] - Injectable resolver returning [{address}], defaults to dns.lookup
|
|
151
|
+
* @returns {Promise<void>} Resolves when the destination is allowed
|
|
152
|
+
* @throws {Error} Tagged with code EEGRESSBLOCKED when the destination is not allowed
|
|
153
|
+
*/
|
|
154
|
+
async function assertAllowedUrl(url, opts) {
|
|
155
|
+
const { policy = POLICY_LINK_LOCAL, resolve } = opts || {};
|
|
156
|
+
|
|
157
|
+
if (policy === POLICY_OFF) {
|
|
158
|
+
return;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
let hostname;
|
|
162
|
+
try {
|
|
163
|
+
hostname = new URL(url).hostname;
|
|
164
|
+
} catch (err) {
|
|
165
|
+
throw blockedError(`Invalid webhook URL: ${url}`);
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
// URL keeps IPv6 literals in brackets, ipaddr.js does not want them
|
|
169
|
+
if (hostname.startsWith('[') && hostname.endsWith(']')) {
|
|
170
|
+
hostname = hostname.slice(1, -1);
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
// A literal needs no resolution, so it is both the cheapest path and never cached
|
|
174
|
+
if (net.isIP(hostname)) {
|
|
175
|
+
if (isBlockedAddress(hostname, policy)) {
|
|
176
|
+
throw policyBlockedError(`Refusing to deliver to a blocked address (${hostname})`);
|
|
177
|
+
}
|
|
178
|
+
return;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
const cacheKey = `${policy}:${hostname}`;
|
|
182
|
+
const cached = readCachedVerdict(cacheKey);
|
|
183
|
+
if (cached) {
|
|
184
|
+
if (cached.blockedBy) {
|
|
185
|
+
throw policyBlockedError(`Refusing to deliver to ${hostname}, it resolves to a blocked address (${cached.blockedBy})`);
|
|
186
|
+
}
|
|
187
|
+
return;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
let addresses;
|
|
191
|
+
try {
|
|
192
|
+
addresses = resolve ? await resolve(hostname) : await dns.lookup(hostname, { all: true });
|
|
193
|
+
} catch (err) {
|
|
194
|
+
// A name that does not resolve is a delivery problem, not a policy one. Let the request
|
|
195
|
+
// proceed and fail with the transport's own error so it retries like any other DNS blip.
|
|
196
|
+
// Deliberately not cached, so a resolver blip cannot pin a verdict for a whole minute.
|
|
197
|
+
return;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
for (let { address } of addresses) {
|
|
201
|
+
if (isBlockedAddress(address, policy)) {
|
|
202
|
+
cacheVerdict(cacheKey, address);
|
|
203
|
+
throw policyBlockedError(`Refusing to deliver to ${hostname}, it resolves to a blocked address (${address})`);
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
cacheVerdict(cacheKey, null);
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
module.exports = {
|
|
211
|
+
assertAllowedUrl,
|
|
212
|
+
isBlockedAddress,
|
|
213
|
+
normalizePolicy,
|
|
214
|
+
// Exported so tests can start from a known state; nothing in production clears the cache,
|
|
215
|
+
// entries simply expire.
|
|
216
|
+
clearVerdictCache: () => verdictCache.clear(),
|
|
217
|
+
POLICY_OFF,
|
|
218
|
+
POLICY_LINK_LOCAL,
|
|
219
|
+
POLICY_PRIVATE
|
|
220
|
+
};
|
|
@@ -10,7 +10,8 @@ const { templates } = require('../templates');
|
|
|
10
10
|
const { Gateway } = require('../gateway');
|
|
11
11
|
const os = require('os');
|
|
12
12
|
const punycode = require('punycode.js');
|
|
13
|
-
const { inlineHtml, inlineText, htmlToText, textToHtml
|
|
13
|
+
const { inlineHtml, inlineText, htmlToText, textToHtml } = require('@postalsys/email-text-tools');
|
|
14
|
+
const { messageWebSafeHtml } = require('../web-safe-html');
|
|
14
15
|
const { randomUUID: uuid } = require('crypto');
|
|
15
16
|
const { addTrackers } = require('../add-trackers');
|
|
16
17
|
const { getRawEmail } = require('../get-raw-email');
|
|
@@ -67,6 +68,7 @@ const {
|
|
|
67
68
|
EMAIL_DELIVERY_ERROR_NOTIFY,
|
|
68
69
|
EMAIL_SENT_NOTIFY
|
|
69
70
|
} = require('../consts');
|
|
71
|
+
const { buildRetentionPolicy } = require('../queue-retention');
|
|
70
72
|
|
|
71
73
|
// Configure download chunk size from environment or use default
|
|
72
74
|
const DOWNLOAD_CHUNK_SIZE = getByteSize(readEnvValue('EENGINE_CHUNK_SIZE')) || DEFAULT_DOWNLOAD_CHUNK_SIZE;
|
|
@@ -2060,11 +2062,9 @@ class BaseClient {
|
|
|
2060
2062
|
|
|
2061
2063
|
// Configure queue job options
|
|
2062
2064
|
let queueName = 'queued';
|
|
2063
|
-
let retention = typeof queueKeep === 'number' ? { age: 24 * 3600, count: queueKeep } : queueKeep;
|
|
2064
2065
|
let jobOpts = {
|
|
2065
2066
|
jobId: queueId,
|
|
2066
|
-
|
|
2067
|
-
removeOnFail: retention,
|
|
2067
|
+
...buildRetentionPolicy(queueKeep),
|
|
2068
2068
|
attempts: typeof deliveryAttempts === 'number' ? deliveryAttempts : defaultDeliveryAttempts,
|
|
2069
2069
|
backoff: {
|
|
2070
2070
|
type: 'exponential',
|
|
@@ -2736,10 +2736,7 @@ class BaseClient {
|
|
|
2736
2736
|
let notifyWebSafeHtml = await settings.get('notifyWebSafeHtml');
|
|
2737
2737
|
if (notifyWebSafeHtml && messageData.text && (messageData.text.html || messageData.text.plain)) {
|
|
2738
2738
|
// convert to web safe
|
|
2739
|
-
messageData.text._generatedHtml =
|
|
2740
|
-
html: messageData.text.html,
|
|
2741
|
-
text: messageData.text.plain
|
|
2742
|
-
});
|
|
2739
|
+
messageData.text._generatedHtml = await messageWebSafeHtml(messageData);
|
|
2743
2740
|
|
|
2744
2741
|
// embed inline images as data URIs
|
|
2745
2742
|
if (messageData.text.html && messageData.attachments) {
|
|
@@ -9,7 +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 {
|
|
12
|
+
const { messageWebSafeHtml } = require('../web-safe-html');
|
|
13
13
|
const { emitChangeEvent } = require('../tools');
|
|
14
14
|
const { Gateway } = require('../gateway');
|
|
15
15
|
|
|
@@ -1300,10 +1300,7 @@ class GmailClient extends BaseClient {
|
|
|
1300
1300
|
|
|
1301
1301
|
// Generate web-safe HTML if requested
|
|
1302
1302
|
if (options.preProcessHtml && formattedMessage.text && (formattedMessage.text.html || formattedMessage.text.plain)) {
|
|
1303
|
-
formattedMessage.text.html =
|
|
1304
|
-
html: formattedMessage.text.html,
|
|
1305
|
-
text: formattedMessage.text.plain
|
|
1306
|
-
});
|
|
1303
|
+
formattedMessage.text.html = await messageWebSafeHtml(formattedMessage);
|
|
1307
1304
|
formattedMessage.text.webSafe = true;
|
|
1308
1305
|
}
|
|
1309
1306
|
|
|
@@ -18,7 +18,7 @@ const settings = require('../../settings');
|
|
|
18
18
|
const { bounceDetect } = require('../../bounce-detect');
|
|
19
19
|
const { arfDetect } = require('../../arf-detect');
|
|
20
20
|
const appendList = require('../../append-list');
|
|
21
|
-
const {
|
|
21
|
+
const { messageWebSafeHtml } = require('../../web-safe-html');
|
|
22
22
|
const simpleParser = require('mailparser').simpleParser;
|
|
23
23
|
const ical = require('ical.js');
|
|
24
24
|
const addressparser = require('nodemailer/lib/addressparser');
|
|
@@ -1646,10 +1646,7 @@ class Mailbox {
|
|
|
1646
1646
|
let notifyWebSafeHtml = await settings.get('notifyWebSafeHtml');
|
|
1647
1647
|
if (notifyWebSafeHtml && messageInfo.text && (messageInfo.text.html || messageInfo.text.plain)) {
|
|
1648
1648
|
// convert to web safe
|
|
1649
|
-
messageInfo.text._generatedHtml =
|
|
1650
|
-
html: messageInfo.text.html,
|
|
1651
|
-
text: messageInfo.text.plain
|
|
1652
|
-
});
|
|
1649
|
+
messageInfo.text._generatedHtml = await messageWebSafeHtml(messageInfo);
|
|
1653
1650
|
messageInfo.text.webSafe = true;
|
|
1654
1651
|
|
|
1655
1652
|
// Embed images referenced by Content-ID
|
|
@@ -2680,10 +2677,7 @@ class Mailbox {
|
|
|
2680
2677
|
|
|
2681
2678
|
// Convert to web-safe HTML if requested
|
|
2682
2679
|
if (options.preProcessHtml && messageInfo.text && (messageInfo.text.html || messageInfo.text.plain)) {
|
|
2683
|
-
messageInfo.text.html =
|
|
2684
|
-
html: messageInfo.text.html,
|
|
2685
|
-
text: messageInfo.text.plain
|
|
2686
|
-
});
|
|
2680
|
+
messageInfo.text.html = await messageWebSafeHtml(messageInfo);
|
|
2687
2681
|
messageInfo.text.webSafe = true;
|
|
2688
2682
|
}
|
|
2689
2683
|
|
|
@@ -6,6 +6,7 @@ const { webhooks: Webhooks } = require('../webhooks');
|
|
|
6
6
|
const { getESClient, isDocumentStoreEnabled } = require('../document-store');
|
|
7
7
|
const { getThread } = require('../threads');
|
|
8
8
|
const settings = require('../settings');
|
|
9
|
+
const { buildRetentionPolicy } = require('../queue-retention');
|
|
9
10
|
|
|
10
11
|
// Import notification-related constants
|
|
11
12
|
const { MESSAGE_NEW_NOTIFY, MESSAGE_DELETED_NOTIFY, MESSAGE_UPDATED_NOTIFY, EMAIL_BOUNCE_NOTIFY, MAILBOX_DELETED_NOTIFY } = require('../consts');
|
|
@@ -227,9 +228,13 @@ class NotificationHandler {
|
|
|
227
228
|
* Processes notification with document store sync only (no webhook)
|
|
228
229
|
* @param {string} event - Event type
|
|
229
230
|
* @param {Object} payload - Notification payload
|
|
231
|
+
* @param {boolean|number} queueKeep - Whether/how many jobs to keep
|
|
230
232
|
*/
|
|
231
|
-
async processDocumentOnly(event, payload) {
|
|
232
|
-
|
|
233
|
+
async processDocumentOnly(event, payload, queueKeep) {
|
|
234
|
+
// Goes through buildJobOptions like every other enqueue. Passing DOCUMENT_JOB_OPTIONS
|
|
235
|
+
// straight through left this path on the hardcoded baseline: it ignored the queueKeep
|
|
236
|
+
// setting and, more importantly, never picked up the failed-entry floor.
|
|
237
|
+
await this.documentsQueue.add(event, payload, this.buildJobOptions(queueKeep).documents);
|
|
233
238
|
}
|
|
234
239
|
|
|
235
240
|
/**
|
|
@@ -238,17 +243,11 @@ class NotificationHandler {
|
|
|
238
243
|
* @returns {Object} Job options for notify and documents queues
|
|
239
244
|
*/
|
|
240
245
|
buildJobOptions(queueKeep) {
|
|
241
|
-
const retention =
|
|
246
|
+
const retention = buildRetentionPolicy(queueKeep);
|
|
242
247
|
|
|
243
|
-
const notifyOptions = Object.assign({}, DEFAULT_JOB_OPTIONS,
|
|
244
|
-
removeOnComplete: retention,
|
|
245
|
-
removeOnFail: retention
|
|
246
|
-
});
|
|
248
|
+
const notifyOptions = Object.assign({}, DEFAULT_JOB_OPTIONS, retention);
|
|
247
249
|
|
|
248
|
-
const documentOptions = Object.assign({}, DOCUMENT_JOB_OPTIONS,
|
|
249
|
-
removeOnComplete: retention,
|
|
250
|
-
removeOnFail: retention
|
|
251
|
-
});
|
|
250
|
+
const documentOptions = Object.assign({}, DOCUMENT_JOB_OPTIONS, retention);
|
|
252
251
|
|
|
253
252
|
return {
|
|
254
253
|
notify: notifyOptions,
|
|
@@ -300,7 +299,7 @@ class NotificationHandler {
|
|
|
300
299
|
await this.processWebhookOnly(event, payload);
|
|
301
300
|
} else if (addDocumentQueueJob) {
|
|
302
301
|
// Document store only
|
|
303
|
-
await this.processDocumentOnly(event, payload);
|
|
302
|
+
await this.processDocumentOnly(event, payload, queueKeep);
|
|
304
303
|
}
|
|
305
304
|
}
|
|
306
305
|
}
|
|
@@ -9,7 +9,7 @@ const getSecret = require('../get-secret');
|
|
|
9
9
|
const msgpack = require('msgpack5')();
|
|
10
10
|
const he = require('he');
|
|
11
11
|
const { emitChangeEvent, prepareUrl } = require('../tools');
|
|
12
|
-
const {
|
|
12
|
+
const { messageWebSafeHtml } = require('../web-safe-html');
|
|
13
13
|
const crypto = require('crypto');
|
|
14
14
|
const { Gateway } = require('../gateway');
|
|
15
15
|
const { detectMimeType, detectExtension } = require('nodemailer/lib/mime-funcs/mime-types');
|
|
@@ -1760,10 +1760,7 @@ class OutlookClient extends BaseClient {
|
|
|
1760
1760
|
|
|
1761
1761
|
// Generate web-safe HTML if requested
|
|
1762
1762
|
if (options.preProcessHtml && formattedMessage.text && (formattedMessage.text.html || formattedMessage.text.plain)) {
|
|
1763
|
-
formattedMessage.text.html =
|
|
1764
|
-
html: formattedMessage.text.html,
|
|
1765
|
-
text: formattedMessage.text.plain
|
|
1766
|
-
});
|
|
1763
|
+
formattedMessage.text.html = await messageWebSafeHtml(formattedMessage);
|
|
1767
1764
|
|
|
1768
1765
|
formattedMessage.text.webSafe = true;
|
|
1769
1766
|
}
|