emailengine-app 2.84.1 → 2.85.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/.dockerignore +6 -0
- package/.ncurc.js +5 -3
- package/.prettierignore +5 -1
- package/.prettierrc.js +2 -0
- package/.release-please-manifest.json +1 -1
- package/CHANGELOG.md +61 -0
- package/Dockerfile +8 -2
- package/README.md +1 -1
- package/bin/emailengine.js +444 -403
- package/copy-static-files.sh +39 -14
- package/data/google-crawlers.json +1 -1
- package/data/public_suffix_list.dat +16562 -0
- package/docker-compose.yml +1 -1
- package/eslint.config.js +81 -99
- package/lib/account/own-account-key.js +42 -0
- package/lib/account-assignment.js +1 -33
- package/lib/account.js +68 -24
- package/lib/add-trackers.js +11 -4
- package/lib/api-reference/format.js +4 -3
- package/lib/api-routes/account-routes.js +244 -26
- package/lib/api-routes/blocklist-routes.js +23 -2
- package/lib/api-routes/delivery-test-routes.js +26 -3
- package/lib/api-routes/export-routes.js +28 -2
- package/lib/api-routes/gateway-routes.js +37 -5
- package/lib/api-routes/mailbox-routes.js +41 -2
- package/lib/api-routes/message-routes.js +104 -4
- package/lib/api-routes/mint-bounds.js +11 -0
- package/lib/api-routes/oauth2-app-routes.js +48 -15
- package/lib/api-routes/outbox-routes.js +45 -11
- package/lib/api-routes/permission-map.js +12 -1
- package/lib/api-routes/route-helpers.js +125 -3
- package/lib/api-routes/settings-routes.js +23 -2
- package/lib/api-routes/submit-routes.js +338 -309
- package/lib/api-routes/template-routes.js +38 -2
- package/lib/api-routes/token-routes.js +142 -96
- package/lib/api-routes/webhook-route-routes.js +13 -2
- package/lib/auth-token.js +23 -10
- package/lib/bounce-detect.js +414 -210
- package/lib/consts.js +39 -4
- package/lib/create-imap-client.js +41 -2
- package/lib/email-client/base-client.js +30 -41
- package/lib/email-client/gmail-client.js +30 -18
- package/lib/email-client/imap/mailbox.js +13 -23
- package/lib/email-client/imap/response-metrics.js +75 -0
- package/lib/email-client/imap/subconnection.js +1 -1
- package/lib/email-client/imap-client.js +6 -3
- package/lib/email-client/message-builder.js +7 -2
- package/lib/email-client/notification-handler.js +1 -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/gateway.js +2 -3
- package/lib/get-raw-email.js +4 -2
- package/lib/hapi-request-logger.js +107 -0
- package/lib/imap-proxy-auth.js +14 -1
- package/lib/imapproxy/imap-core/README.md +6 -5
- 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/mcp/tools.js +37 -8
- package/lib/notify-attachments.js +17 -0
- 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-mailbox.js +35 -0
- package/lib/oauth/outlook.js +26 -44
- package/lib/oauth/state.js +24 -0
- package/lib/oauth2-apps.js +1 -1
- package/lib/pbkdf2-phc.js +19 -2
- package/lib/privileged-settings.js +6 -3
- package/lib/redis-scan-delete.js +15 -1
- package/lib/schemas.js +79 -33
- package/lib/settings.js +13 -1
- package/lib/smtp-auth.js +23 -0
- package/lib/sso.js +1 -1
- package/lib/swagger-options.js +1 -1
- package/lib/thread-diagnostics.js +46 -0
- package/lib/timezones.js +109 -0
- package/lib/token-permission-view.js +3 -3
- package/lib/tools.js +285 -66
- package/lib/totp.js +2 -5
- package/lib/translations.js +1 -2
- package/lib/ui-routes/account-routes.js +491 -491
- package/lib/ui-routes/account-setup.js +99 -0
- package/lib/ui-routes/admin-config-routes.js +98 -48
- package/lib/ui-routes/admin-entities-routes.js +113 -31
- package/lib/ui-routes/auth-routes.js +137 -62
- package/lib/ui-routes/connection-security-form.js +74 -0
- package/lib/ui-routes/form-lists.js +46 -0
- package/lib/ui-routes/internals-routes.js +5 -0
- package/lib/ui-routes/mcp-consent-routes.js +5 -1
- package/lib/ui-routes/oauth-config-routes.js +133 -100
- package/lib/ui-routes/route-helpers.js +19 -3
- package/lib/ui-routes/sign-in-helpers.js +59 -0
- package/lib/ui-routes/tls-config-routes.js +58 -15
- package/lib/ui-routes/unsubscribe-routes.js +6 -3
- package/lib/utils/back-off.js +82 -0
- package/lib/utils/map-concurrent.js +36 -0
- package/lib/utils/murmurhash3.js +66 -0
- package/lib/utils/network.js +28 -0
- package/lib/utils/provider-id.js +27 -0
- package/lib/utils/public-suffix.js +122 -0
- package/lib/utils/random-id.js +26 -0
- package/lib/utils/require-tls.js +33 -0
- package/lib/utils/version.js +74 -0
- package/lib/web-safe-html.js +5 -6
- package/lib/webhook-penalty.js +75 -0
- package/lib/webhook-routing.js +49 -2
- package/lib/webhooks.js +41 -6
- package/package.json +37 -39
- package/sbom.json +7980 -1
- package/server.js +659 -455
- 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 +191 -1016
- package/translations/messages.pot +70 -71
- package/views/account/security.hbs +10 -0
- package/views/accounts/account.hbs +11 -11
- package/views/accounts/edit.hbs +6 -2
- package/views/config/ai.hbs +1 -1
- package/views/config/security.hbs +2 -2
- package/views/config/service.hbs +3 -0
- package/views/internals/index.hbs +8 -0
- package/views/partials/gateway_form.hbs +3 -1
- package/views/partials/webhook_form.hbs +1 -1
- package/views/suppression-lists/index.hbs +1 -1
- package/workers/api.js +780 -585
- package/workers/export.js +1 -1
- package/workers/submit.js +1 -1
- package/workers/webhooks.js +54 -34
- 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
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// Retries an async operation with capped exponential delays. Replaces the exponential-backoff
|
|
4
|
+
// package and keeps its semantics for the options EmailEngine uses:
|
|
5
|
+
//
|
|
6
|
+
// - the delay before attempt n (0-based) is startingDelay * timeMultiple^(n - 1), capped at
|
|
7
|
+
// maxDelay, and the first attempt runs immediately. With delayFirstAttempt the exponent is n
|
|
8
|
+
// instead, so the first attempt waits startingDelay as well.
|
|
9
|
+
// - after each failure retry(err, failures) is awaited; a falsy answer rethrows that error.
|
|
10
|
+
// - numOfAttempts bounds the total number of attempts (Infinity keeps going); the last error is
|
|
11
|
+
// rethrown once it is reached.
|
|
12
|
+
//
|
|
13
|
+
// The wait is node:timers/promises setTimeout, looked up at call time, so a suite can drive the
|
|
14
|
+
// loop with test/helpers/instant-timers.js like the other retry loops.
|
|
15
|
+
|
|
16
|
+
const timers = require('node:timers/promises');
|
|
17
|
+
|
|
18
|
+
// setTimeout() fires after 1 ms for any delay above this, which would turn an uncapped backoff
|
|
19
|
+
// into a busy loop
|
|
20
|
+
const MAX_TIMER_DELAY = 2 ** 31 - 1;
|
|
21
|
+
|
|
22
|
+
const DEFAULTS = {
|
|
23
|
+
delayFirstAttempt: false,
|
|
24
|
+
maxDelay: Infinity,
|
|
25
|
+
numOfAttempts: 10,
|
|
26
|
+
retry: () => true,
|
|
27
|
+
startingDelay: 100,
|
|
28
|
+
timeMultiple: 2
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
function getDelay(options, attempt) {
|
|
32
|
+
const exponent = options.delayFirstAttempt ? attempt : attempt - 1;
|
|
33
|
+
if (exponent < 0) {
|
|
34
|
+
return 0;
|
|
35
|
+
}
|
|
36
|
+
const delay = Math.min(options.startingDelay * Math.pow(options.timeMultiple, exponent), options.maxDelay);
|
|
37
|
+
return Math.min(delay, MAX_TIMER_DELAY);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* @template T
|
|
42
|
+
* @param {() => Promise<T>} request The operation to run
|
|
43
|
+
* @param {Object} [options]
|
|
44
|
+
* @param {boolean} [options.delayFirstAttempt=false] Wait startingDelay before the first attempt too
|
|
45
|
+
* @param {number} [options.startingDelay=100] First delay in ms
|
|
46
|
+
* @param {number} [options.timeMultiple=2] Growth factor between delays
|
|
47
|
+
* @param {number} [options.maxDelay=Infinity] Upper bound for a single delay in ms
|
|
48
|
+
* @param {number} [options.numOfAttempts=10] Maximum number of attempts, at least 1
|
|
49
|
+
* @param {(err: Error, failures: number) => boolean|Promise<boolean>} [options.retry] Whether to try again after a failure
|
|
50
|
+
* @returns {Promise<T>}
|
|
51
|
+
*/
|
|
52
|
+
async function backOff(request, options) {
|
|
53
|
+
// an option passed as undefined keeps its default instead of turning the delay into NaN
|
|
54
|
+
const settings = Object.assign({}, DEFAULTS);
|
|
55
|
+
for (const [key, value] of Object.entries(options || {})) {
|
|
56
|
+
if (value !== undefined) {
|
|
57
|
+
settings[key] = value;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
options = settings;
|
|
61
|
+
|
|
62
|
+
const maxAttempts = Math.max(options.numOfAttempts, 1);
|
|
63
|
+
|
|
64
|
+
for (let attempt = 0; ; attempt++) {
|
|
65
|
+
const delay = getDelay(options, attempt);
|
|
66
|
+
if (delay > 0) {
|
|
67
|
+
await timers.setTimeout(delay);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
try {
|
|
71
|
+
return await request();
|
|
72
|
+
} catch (err) {
|
|
73
|
+
const failures = attempt + 1;
|
|
74
|
+
const shouldRetry = await options.retry(err, failures);
|
|
75
|
+
if (!shouldRetry || failures >= maxAttempts) {
|
|
76
|
+
throw err;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
module.exports = { backOff, getDelay };
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Runs `fn` over `items` with at most `limit` calls in flight and resolves with the results in
|
|
5
|
+
* item order once every call has settled. Rejects with the first failure, like Promise.all, but
|
|
6
|
+
* only after the calls already in flight have settled, so a caller never has calls outstanding
|
|
7
|
+
* it does not know about. A caller that wants every item attempted regardless settles each
|
|
8
|
+
* outcome inside `fn`.
|
|
9
|
+
*
|
|
10
|
+
* @param {Array} items
|
|
11
|
+
* @param {number} limit - Calls in flight at once
|
|
12
|
+
* @param {Function} fn - async (item, index) -> result
|
|
13
|
+
* @returns {Promise<Array>}
|
|
14
|
+
*/
|
|
15
|
+
async function mapConcurrent(items, limit, fn) {
|
|
16
|
+
const results = new Array(items.length);
|
|
17
|
+
let next = 0;
|
|
18
|
+
let failure = null;
|
|
19
|
+
const runner = async () => {
|
|
20
|
+
while (next < items.length && !failure) {
|
|
21
|
+
const index = next++;
|
|
22
|
+
try {
|
|
23
|
+
results[index] = await fn(items[index], index);
|
|
24
|
+
} catch (err) {
|
|
25
|
+
failure = failure || err;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
};
|
|
29
|
+
await Promise.all(Array.from({ length: Math.max(1, Math.min(limit, items.length)) }, runner));
|
|
30
|
+
if (failure) {
|
|
31
|
+
throw failure;
|
|
32
|
+
}
|
|
33
|
+
return results;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
module.exports = { mapConcurrent };
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// MurmurHash3, the x86 32-bit variant, over the UTF-8 bytes of a string.
|
|
4
|
+
//
|
|
5
|
+
// The output is load-bearing: tools.getRendezvousScore() ranks IMAP workers and local addresses
|
|
6
|
+
// with it, so the hash decides which worker owns an account and which source address it connects
|
|
7
|
+
// from. A different hash would move every account to another worker and another source IP on
|
|
8
|
+
// upgrade. The result must stay bit-identical to the `murmurhash` package's v3() this replaced,
|
|
9
|
+
// which test/murmurhash3-test.js pins with vectors recorded from that package.
|
|
10
|
+
|
|
11
|
+
const C1 = 0xcc9e2d51;
|
|
12
|
+
const C2 = 0x1b873593;
|
|
13
|
+
|
|
14
|
+
function rotl32(x, r) {
|
|
15
|
+
return (x << r) | (x >>> (32 - r));
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function mixK1(k1) {
|
|
19
|
+
k1 = Math.imul(k1, C1);
|
|
20
|
+
k1 = rotl32(k1, 15);
|
|
21
|
+
return Math.imul(k1, C2);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* @param {string|Uint8Array} key Input, strings are hashed as UTF-8
|
|
26
|
+
* @param {number} [seed=0] 32-bit seed
|
|
27
|
+
* @returns {number} Unsigned 32-bit hash
|
|
28
|
+
*/
|
|
29
|
+
function murmurhash3(key, seed) {
|
|
30
|
+
const bytes = typeof key === 'string' ? Buffer.from(key, 'utf-8') : key;
|
|
31
|
+
const length = bytes.length;
|
|
32
|
+
const tail = length & ~3;
|
|
33
|
+
|
|
34
|
+
let h1 = seed >>> 0;
|
|
35
|
+
|
|
36
|
+
for (let i = 0; i < tail; i += 4) {
|
|
37
|
+
const k1 = bytes[i] | (bytes[i + 1] << 8) | (bytes[i + 2] << 16) | (bytes[i + 3] << 24);
|
|
38
|
+
h1 ^= mixK1(k1);
|
|
39
|
+
h1 = rotl32(h1, 13);
|
|
40
|
+
h1 = (Math.imul(h1, 5) + 0xe6546b64) | 0;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
let k1 = 0;
|
|
44
|
+
switch (length & 3) {
|
|
45
|
+
case 3:
|
|
46
|
+
k1 ^= bytes[tail + 2] << 16;
|
|
47
|
+
// falls through
|
|
48
|
+
case 2:
|
|
49
|
+
k1 ^= bytes[tail + 1] << 8;
|
|
50
|
+
// falls through
|
|
51
|
+
case 1:
|
|
52
|
+
k1 ^= bytes[tail];
|
|
53
|
+
h1 ^= mixK1(k1);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
h1 ^= length;
|
|
57
|
+
h1 ^= h1 >>> 16;
|
|
58
|
+
h1 = Math.imul(h1, 0x85ebca6b);
|
|
59
|
+
h1 ^= h1 >>> 13;
|
|
60
|
+
h1 = Math.imul(h1, 0xc2b2ae35);
|
|
61
|
+
h1 ^= h1 >>> 16;
|
|
62
|
+
|
|
63
|
+
return h1 >>> 0;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
module.exports = { murmurhash3 };
|
package/lib/utils/network.js
CHANGED
|
@@ -54,6 +54,33 @@ function parseComparableIp(address) {
|
|
|
54
54
|
* @param {string} range - CIDR range
|
|
55
55
|
* @returns {Array} `[address, bits]` as ipaddr.js reports it, unwrapped where applicable
|
|
56
56
|
*/
|
|
57
|
+
/**
|
|
58
|
+
* The address a per-client budget (a failed-login count, a rate limit) is kept for. An IPv6
|
|
59
|
+
* client has at least a /64 to pick addresses from, so a budget keyed on the full address was a
|
|
60
|
+
* fresh budget per guess; the /64 is the unit a client controls. IPv4 and IPv4-mapped addresses
|
|
61
|
+
* are kept whole, and a value that is not an address is used as it is
|
|
62
|
+
*
|
|
63
|
+
* @param {String} remoteAddress
|
|
64
|
+
* @returns {String}
|
|
65
|
+
*/
|
|
66
|
+
function budgetAddress(remoteAddress) {
|
|
67
|
+
if (!remoteAddress) {
|
|
68
|
+
return 'unknown';
|
|
69
|
+
}
|
|
70
|
+
try {
|
|
71
|
+
let addr = parseComparableIp(remoteAddress);
|
|
72
|
+
if (addr.kind() === 'ipv6') {
|
|
73
|
+
return `${addr.parts
|
|
74
|
+
.slice(0, 4)
|
|
75
|
+
.map(part => part.toString(16))
|
|
76
|
+
.join(':')}::/64`;
|
|
77
|
+
}
|
|
78
|
+
return addr.toString();
|
|
79
|
+
} catch (err) {
|
|
80
|
+
return String(remoteAddress);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
57
84
|
function parseComparableCidr(range) {
|
|
58
85
|
let [parsed, bits] = ipaddr.parseCIDR(range);
|
|
59
86
|
|
|
@@ -380,6 +407,7 @@ module.exports = {
|
|
|
380
407
|
getAccountHttpRoute,
|
|
381
408
|
parseComparableIp,
|
|
382
409
|
parseComparableCidr,
|
|
410
|
+
budgetAddress,
|
|
383
411
|
matchIp,
|
|
384
412
|
resolveClientIp,
|
|
385
413
|
detectAutomatedRequest,
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// Whether a provider id can become one path segment of a provider API URL.
|
|
4
|
+
//
|
|
5
|
+
// Provider ids are opaque strings the provider handed out, but the ones a request carries (a
|
|
6
|
+
// search by emailId or threadId, a reference threadId) and the ones inside a compound id
|
|
7
|
+
// (attachment and text ids are msgpack inside base64url) arrive from the API caller, and nothing
|
|
8
|
+
// above the client has looked at them. A segment of `..` walks the URL up to a sibling resource on
|
|
9
|
+
// the same token (another mailbox, on an application-credentials app), a `/` ends the segment
|
|
10
|
+
// early, and `?`, `#` and `%` change what the rest of the URL means. The joi schemas of the request
|
|
11
|
+
// ids and the clients' check of a decoded part are this one rule.
|
|
12
|
+
|
|
13
|
+
// eslint-disable-next-line no-control-regex
|
|
14
|
+
const PROVIDER_ID_SEGMENT = /^(?!\.{1,2}$)[^\s/\\?#%\u0000-\u001f\u007f]+$/;
|
|
15
|
+
|
|
16
|
+
// longer than any id a provider hands out; the regex has no cap of its own
|
|
17
|
+
const MAX_PROVIDER_ID_LENGTH = 1024;
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* @param {*} value - the decoded part
|
|
21
|
+
* @returns {Boolean}
|
|
22
|
+
*/
|
|
23
|
+
function isSafePathSegment(value) {
|
|
24
|
+
return typeof value === 'string' && value.length <= MAX_PROVIDER_ID_LENGTH && PROVIDER_ID_SEGMENT.test(value);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
module.exports = { PROVIDER_ID_SEGMENT, isSafePathSegment };
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// Registrable-domain lookup against the Public Suffix List (https://publicsuffix.org/list/), in
|
|
4
|
+
// place of the psl package, whose bundled copy of the list had not been refreshed since its last
|
|
5
|
+
// release. The list itself lives in data/public_suffix_list.dat and is refreshed by
|
|
6
|
+
// copy-static-files.sh on every `npm run update`.
|
|
7
|
+
//
|
|
8
|
+
// The matching follows the list's own algorithm (https://github.com/publicsuffix/list/wiki/Format):
|
|
9
|
+
// an exception rule wins outright, otherwise the matching rule with the most labels does, and a
|
|
10
|
+
// name no rule covers falls back to the implicit "*" rule (its last label is the suffix). Both the
|
|
11
|
+
// ICANN and the private section are used, as psl did.
|
|
12
|
+
|
|
13
|
+
const fs = require('fs');
|
|
14
|
+
const pathlib = require('path');
|
|
15
|
+
const net = require('net');
|
|
16
|
+
const { domainToASCII } = require('url');
|
|
17
|
+
|
|
18
|
+
const LIST_PATH = pathlib.join(__dirname, '..', '..', 'data', 'public_suffix_list.dat');
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* @param {string} text The list in its published format
|
|
22
|
+
* @returns {{ exact: Set<string>, wildcard: Set<string>, exception: Set<string> }} Rules in ASCII
|
|
23
|
+
* (punycode) form; `wildcard` holds the parent of each "*." rule, which `exact` holds as well
|
|
24
|
+
*/
|
|
25
|
+
function parseList(text) {
|
|
26
|
+
const rules = { exact: new Set(), wildcard: new Set(), exception: new Set() };
|
|
27
|
+
|
|
28
|
+
for (let line of text.split('\n')) {
|
|
29
|
+
// a rule is the first whitespace-delimited token of a line that is not a comment
|
|
30
|
+
line = line.trim().split(/\s/)[0];
|
|
31
|
+
if (!line || line.startsWith('//')) {
|
|
32
|
+
continue;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
let set = rules.exact;
|
|
36
|
+
if (line.startsWith('!')) {
|
|
37
|
+
set = rules.exception;
|
|
38
|
+
line = line.slice(1);
|
|
39
|
+
} else if (line.startsWith('*.')) {
|
|
40
|
+
set = rules.wildcard;
|
|
41
|
+
line = line.slice(2);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const rule = domainToASCII(line) || line.toLowerCase();
|
|
45
|
+
set.add(rule);
|
|
46
|
+
|
|
47
|
+
// The parent of a wildcard rule counts as a public suffix of its own, as it does in psl and
|
|
48
|
+
// libpsl: "*.kawasaki.jp" makes "kawasaki.jp" no more registrable than "foo.kawasaki.jp"
|
|
49
|
+
if (set === rules.wildcard) {
|
|
50
|
+
rules.exact.add(rule);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
return rules;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
let defaultRules = null;
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Returns the registrable domain of a host name: the public suffix plus one label, e.g.
|
|
61
|
+
* "example.co.uk" for "imap.mail.example.co.uk".
|
|
62
|
+
*
|
|
63
|
+
* @param {string} host
|
|
64
|
+
* @param {Object} [rules] Parsed rules, the bundled list when omitted
|
|
65
|
+
* @returns {string|null} The registrable domain in the spelling of the input (lower-cased), or null
|
|
66
|
+
* for an IP address, an invalid name, or a name that is itself a public suffix
|
|
67
|
+
*/
|
|
68
|
+
function getRegistrableDomain(host, rules) {
|
|
69
|
+
if (typeof host !== 'string') {
|
|
70
|
+
return null;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
host = host.trim().toLowerCase().replace(/\.$/, '');
|
|
74
|
+
if (!host || net.isIP(host.replace(/^\[|\]$/g, ''))) {
|
|
75
|
+
return null;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
const ascii = domainToASCII(host);
|
|
79
|
+
if (!ascii) {
|
|
80
|
+
return null;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
const labels = ascii.split('.');
|
|
84
|
+
if (labels.some(label => !label)) {
|
|
85
|
+
return null;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
if (!rules) {
|
|
89
|
+
defaultRules = defaultRules || parseList(fs.readFileSync(LIST_PATH, 'utf-8'));
|
|
90
|
+
rules = defaultRules;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// number of labels in the public suffix
|
|
94
|
+
let suffixLength = 0;
|
|
95
|
+
|
|
96
|
+
for (let i = 0; i < labels.length && !suffixLength; i++) {
|
|
97
|
+
// an exception marks its own name as registrable: the suffix is one label shorter
|
|
98
|
+
if (rules.exception.has(labels.slice(i).join('.'))) {
|
|
99
|
+
suffixLength = labels.length - i - 1;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
for (let i = 0; i < labels.length && !suffixLength; i++) {
|
|
104
|
+
if (rules.exact.has(labels.slice(i).join('.')) || (i + 1 < labels.length && rules.wildcard.has(labels.slice(i + 1).join('.')))) {
|
|
105
|
+
suffixLength = labels.length - i;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
suffixLength = suffixLength || 1;
|
|
110
|
+
|
|
111
|
+
if (labels.length <= suffixLength) {
|
|
112
|
+
return null;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
// Answer in the caller's spelling (an IDN stays in Unicode) when the label counts line up, which
|
|
116
|
+
// they do unless the input used an ideographic full stop that domainToASCII folded into a dot
|
|
117
|
+
const original = host.split('.');
|
|
118
|
+
const source = original.length === labels.length ? original : labels;
|
|
119
|
+
return source.slice(-(suffixLength + 1)).join('.');
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
module.exports = { getRegistrableDomain, parseList, LIST_PATH };
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const { randomInt } = require('crypto');
|
|
4
|
+
|
|
5
|
+
// The alphabet and length of generated account and gateway ids. Kept identical to the nanoid
|
|
6
|
+
// customAlphabet() call this replaced, so new ids look like the ones already stored.
|
|
7
|
+
const ID_ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyz';
|
|
8
|
+
const ID_LENGTH = 16;
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Generates a random string from a CSPRNG. Every character is drawn uniformly from the alphabet
|
|
12
|
+
* (crypto.randomInt rejects out-of-range values instead of taking a biased modulo).
|
|
13
|
+
*
|
|
14
|
+
* @param {string} [alphabet] Characters to draw from
|
|
15
|
+
* @param {number} [size] Length of the result
|
|
16
|
+
* @returns {string}
|
|
17
|
+
*/
|
|
18
|
+
function randomId(alphabet = ID_ALPHABET, size = ID_LENGTH) {
|
|
19
|
+
let id = '';
|
|
20
|
+
for (let i = 0; i < size; i++) {
|
|
21
|
+
id += alphabet[randomInt(alphabet.length)];
|
|
22
|
+
}
|
|
23
|
+
return id;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
module.exports = { randomId, ID_ALPHABET, ID_LENGTH };
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// Whether a cleartext SMTP connection must upgrade with STARTTLS.
|
|
4
|
+
//
|
|
5
|
+
// Nodemailer's default is opportunistic: with `secure: false` it upgrades when the server
|
|
6
|
+
// advertises STARTTLS and otherwise carries on in cleartext, AUTH included, which is what an
|
|
7
|
+
// attacker on the path who strips the advertisement gets. Every SMTP transport EmailEngine builds
|
|
8
|
+
// (an account's own server, a gateway, the verification probe) therefore asks for `requireTLS`
|
|
9
|
+
// unless the stored configuration says `requireTLS: false`, the opt-out for a relay on a trusted
|
|
10
|
+
// network that has no TLS at all. A connection that is `secure: true` from the start needs no
|
|
11
|
+
// upgrade and is left alone. lib/create-imap-client.js applies the same rule to IMAP.
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Settles `requireTLS` on an SMTP transport configuration, in place.
|
|
15
|
+
*
|
|
16
|
+
* @param {Object} smtpSettings - Nodemailer transport options, carrying EmailEngine's `requireTLS`
|
|
17
|
+
* @returns {Object} the same object
|
|
18
|
+
*/
|
|
19
|
+
function applyRequireTls(smtpSettings) {
|
|
20
|
+
if (!smtpSettings || typeof smtpSettings !== 'object') {
|
|
21
|
+
return smtpSettings;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
if (smtpSettings.secure) {
|
|
25
|
+
delete smtpSettings.requireTLS;
|
|
26
|
+
return smtpSettings;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
smtpSettings.requireTLS = smtpSettings.requireTLS !== false;
|
|
30
|
+
return smtpSettings;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
module.exports = { applyRequireTls };
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// Semantic version parsing and precedence (semver 2.0.0, section 11) for the two places EmailEngine
|
|
4
|
+
// compares versions: the update check against the latest GitHub release tag, and the license
|
|
5
|
+
// check's record of which version last validated. Both only ever see MAJOR.MINOR.PATCH with an
|
|
6
|
+
// optional pre-release, so ranges, wildcards and partial versions are deliberately not accepted.
|
|
7
|
+
|
|
8
|
+
const VERSION_RE = /^v?(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* @param {string} version A version such as `2.84.2`, `v2.84.2` or `3.0.0-beta.1`
|
|
12
|
+
* @returns {{ core: number[], prerelease: string[] } | null} The parsed version, or null if it is not one
|
|
13
|
+
*/
|
|
14
|
+
function parseVersion(version) {
|
|
15
|
+
const match = typeof version === 'string' ? version.match(VERSION_RE) : null;
|
|
16
|
+
if (!match) {
|
|
17
|
+
return null;
|
|
18
|
+
}
|
|
19
|
+
return {
|
|
20
|
+
core: [Number(match[1]), Number(match[2]), Number(match[3])],
|
|
21
|
+
prerelease: match[4] ? match[4].split('.') : []
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function compareIdentifiers(a, b) {
|
|
26
|
+
const aNumeric = /^\d+$/.test(a);
|
|
27
|
+
const bNumeric = /^\d+$/.test(b);
|
|
28
|
+
if (aNumeric && bNumeric) {
|
|
29
|
+
return Math.sign(Number(a) - Number(b));
|
|
30
|
+
}
|
|
31
|
+
if (aNumeric !== bNumeric) {
|
|
32
|
+
// numeric identifiers have lower precedence than alphanumeric ones
|
|
33
|
+
return aNumeric ? -1 : 1;
|
|
34
|
+
}
|
|
35
|
+
return a < b ? -1 : a > b ? 1 : 0;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Compares two versions by semver precedence. Build metadata is ignored.
|
|
40
|
+
*
|
|
41
|
+
* @param {string} a
|
|
42
|
+
* @param {string} b
|
|
43
|
+
* @returns {number} -1 when a is lower than b, 0 when equal, 1 when higher
|
|
44
|
+
* @throws {TypeError} when either argument is not a version
|
|
45
|
+
*/
|
|
46
|
+
function compareVersions(a, b) {
|
|
47
|
+
const va = parseVersion(a);
|
|
48
|
+
const vb = parseVersion(b);
|
|
49
|
+
if (!va || !vb) {
|
|
50
|
+
throw new TypeError(`Invalid version: ${JSON.stringify(va ? b : a)}`);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
for (let i = 0; i < 3; i++) {
|
|
54
|
+
if (va.core[i] !== vb.core[i]) {
|
|
55
|
+
return va.core[i] < vb.core[i] ? -1 : 1;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
// a version without a pre-release ranks above any pre-release of the same core version
|
|
60
|
+
if (!va.prerelease.length || !vb.prerelease.length) {
|
|
61
|
+
return Math.sign(vb.prerelease.length - va.prerelease.length);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const length = Math.min(va.prerelease.length, vb.prerelease.length);
|
|
65
|
+
for (let i = 0; i < length; i++) {
|
|
66
|
+
const result = compareIdentifiers(va.prerelease[i], vb.prerelease[i]);
|
|
67
|
+
if (result) {
|
|
68
|
+
return result;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
return Math.sign(va.prerelease.length - vb.prerelease.length);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
module.exports = { parseVersion, compareVersions };
|
package/lib/web-safe-html.js
CHANGED
|
@@ -5,7 +5,7 @@ const { analyze } = require('@postalsys/email-content');
|
|
|
5
5
|
// lazy getter, and touching it loads jsdom (tens of MB of heap) into every process that merely
|
|
6
6
|
// requires this module, the main process included.
|
|
7
7
|
const textTools = require('@postalsys/email-text-tools');
|
|
8
|
-
const { getBoolean, readEnvValue } = require('./tools');
|
|
8
|
+
const { getBoolean, readEnvValue, attributeValueRegex } = require('./tools');
|
|
9
9
|
const { COLLAPSE_CLASS, COLLAPSE_TOGGLE_CLASS } = require('./consts');
|
|
10
10
|
const logger = require('./logger');
|
|
11
11
|
const he = require('he');
|
|
@@ -385,9 +385,8 @@ async function collapseThreadHistory(messageData) {
|
|
|
385
385
|
// prefix). A renderer folds whatever carries them, so they must only ever come from us.
|
|
386
386
|
const RESERVED_CLASS_NAME = /^ee-collapsed-thread/i;
|
|
387
387
|
|
|
388
|
-
// A class attribute with its value in any of the three HTML syntaxes
|
|
389
|
-
|
|
390
|
-
const CLASS_ATTRIBUTE = /([\s/]class\s*=\s*)(?:"([^"]*)"|'([^']*)'|([^\s"'>]+))/gi;
|
|
388
|
+
// A class attribute with its value in any of the three HTML syntaxes
|
|
389
|
+
const CLASS_ATTRIBUTE = attributeValueRegex(['class']);
|
|
391
390
|
|
|
392
391
|
/**
|
|
393
392
|
* Removes the collapse marker's class names from sender HTML.
|
|
@@ -405,8 +404,8 @@ function stripReservedClasses(html) {
|
|
|
405
404
|
return html;
|
|
406
405
|
}
|
|
407
406
|
|
|
408
|
-
return html.replace(CLASS_ATTRIBUTE, (match, prefix,
|
|
409
|
-
let raw =
|
|
407
|
+
return html.replace(CLASS_ATTRIBUTE, (match, prefix, value) => {
|
|
408
|
+
let raw = /^["']/.test(value) ? value.slice(1, -1) : value;
|
|
410
409
|
let tokens = he.decode(raw, { isAttributeValue: true }).split(/\s+/);
|
|
411
410
|
let kept = tokens.filter(token => token && !RESERVED_CLASS_NAME.test(token));
|
|
412
411
|
if (kept.length === tokens.filter(token => token).length) {
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// A delivery penalty per webhook target.
|
|
4
|
+
//
|
|
5
|
+
// The webhook queue is one queue with a small concurrency, and every attempt against a target
|
|
6
|
+
// that accepts the connection and never answers costs the whole attempt timeout (30 seconds by
|
|
7
|
+
// default). One account pointing its own webhook URL at such a target, and generating a dozen
|
|
8
|
+
// events a minute, kept the queue busy with timeouts and delayed every other account's
|
|
9
|
+
// deliveries behind them, indefinitely. So a target whose attempt just ran into the timeout is
|
|
10
|
+
// penalised: for a short while, deliveries to the same origin are moved back to the delayed set
|
|
11
|
+
// instead of being attempted, and the queue spends its time on targets that answer. The
|
|
12
|
+
// penalised delivery is not lost, it is tried again once the penalty is over, with its attempt
|
|
13
|
+
// count unchanged.
|
|
14
|
+
//
|
|
15
|
+
// Only the slow failures count. A refused or reset connection and a name that does not resolve
|
|
16
|
+
// fail in milliseconds, so they never hold the queue, and penalising them would defer every
|
|
17
|
+
// delivery to a receiver for a minute because it was restarting when one attempt arrived. A
|
|
18
|
+
// target answering with an HTTP status, any status, is not penalised either: it answered
|
|
19
|
+
// quickly, and the retry schedule already spaces those out. Nor is an egress or redirect
|
|
20
|
+
// refusal, which fails the job for good anyway.
|
|
21
|
+
|
|
22
|
+
const { createHash } = require('crypto');
|
|
23
|
+
const { REDIS_PREFIX } = require('./consts');
|
|
24
|
+
|
|
25
|
+
// At most this long per penalty, whatever the attempt timeout is set to
|
|
26
|
+
const MAX_PENALTY_MS = 5 * 60 * 1000;
|
|
27
|
+
|
|
28
|
+
// The failures that cost the attempt its whole timeout: lib/webhook-request.js reports its
|
|
29
|
+
// own deadline as ETIMEDOUT, undici's dispatcher deadlines carry their own codes
|
|
30
|
+
const SLOW_FAILURE_CODES = new Set(['ETIMEDOUT', 'UND_ERR_CONNECT_TIMEOUT', 'UND_ERR_HEADERS_TIMEOUT', 'UND_ERR_BODY_TIMEOUT']);
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Redis key of the penalty for a target, by its origin: a receiver is one host, whatever paths
|
|
34
|
+
* its URLs have, and the credentials in the URL are not part of what identifies it.
|
|
35
|
+
*
|
|
36
|
+
* @param {String} url - the delivery URL
|
|
37
|
+
* @returns {String|null} the key, or null for a URL that does not parse
|
|
38
|
+
*/
|
|
39
|
+
function penaltyKey(url) {
|
|
40
|
+
let origin;
|
|
41
|
+
try {
|
|
42
|
+
origin = new URL(url).origin;
|
|
43
|
+
} catch (err) {
|
|
44
|
+
return null;
|
|
45
|
+
}
|
|
46
|
+
if (!origin || origin === 'null') {
|
|
47
|
+
return null;
|
|
48
|
+
}
|
|
49
|
+
return `${REDIS_PREFIX}webhook:penalty:${createHash('sha256').update(origin).digest('base64url').slice(0, 32)}`;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* How long a target is penalised after a failed attempt, in milliseconds; 0 when the failure is
|
|
54
|
+
* not the kind that holds the queue.
|
|
55
|
+
*
|
|
56
|
+
* @param {Error} err - the failure
|
|
57
|
+
* @param {Number} attemptTimeout - the per-attempt wall clock cap, in milliseconds
|
|
58
|
+
* @returns {Number}
|
|
59
|
+
*/
|
|
60
|
+
function penaltyFor(err, attemptTimeout) {
|
|
61
|
+
if (!err || typeof err !== 'object') {
|
|
62
|
+
return 0;
|
|
63
|
+
}
|
|
64
|
+
let code = err.code || (err.cause && err.cause.code);
|
|
65
|
+
if (!code || !SLOW_FAILURE_CODES.has(code)) {
|
|
66
|
+
return 0;
|
|
67
|
+
}
|
|
68
|
+
// twice the attempt cap: long enough that a dozen events a minute to a dead target no
|
|
69
|
+
// longer each cost a full timeout, short enough that a target that comes back is not
|
|
70
|
+
// kept waiting for long
|
|
71
|
+
let penalty = 2 * (Number(attemptTimeout) || 0);
|
|
72
|
+
return Math.min(Math.max(penalty, 1000), MAX_PENALTY_MS);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
module.exports = { penaltyKey, penaltyFor, MAX_PENALTY_MS };
|