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
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
# imap-core (vendored fork)
|
|
2
|
+
|
|
3
|
+
This directory is a **vendored fork**, not a dependency. It is not listed in `package.json`, so
|
|
4
|
+
`npm update` never touches it and `npm audit` never sees it.
|
|
5
|
+
|
|
6
|
+
## Provenance
|
|
7
|
+
|
|
8
|
+
Upstream: the `imap-core` module of [WildDuck](https://github.com/nodemailer/wildduck)
|
|
9
|
+
(`lib/imap-core` in that repository).
|
|
10
|
+
|
|
11
|
+
Imported into EmailEngine in `dd0d6e34` ("Added IMAP proxy server", 2022-08-23) and patched in
|
|
12
|
+
place since. It provides the IMAP protocol server that `lib/imapproxy/imap-server.js` builds on:
|
|
13
|
+
the command parser/compiler, the connection and command state machines, and the message indexer.
|
|
14
|
+
|
|
15
|
+
The WildDuck-specific parts of upstream (MongoDB-backed mailbox storage, the `test/prepare.sh`
|
|
16
|
+
fixture loader that talks to a WildDuck REST API) came along with the import and are not used
|
|
17
|
+
here.
|
|
18
|
+
|
|
19
|
+
## Local patches
|
|
20
|
+
|
|
21
|
+
Everything below is EmailEngine-only and has no upstream equivalent. Re-syncing with upstream
|
|
22
|
+
means re-applying these.
|
|
23
|
+
|
|
24
|
+
| Commit | Date | Change |
|
|
25
|
+
| --- | --- | --- |
|
|
26
|
+
| `4453330a` | 2026-06-01 | Prevent IMAP proxy worker crashes and connection leaks (#596) |
|
|
27
|
+
| `3661dddb` | 2026-06-05 | Harden STARTTLS against command injection: reject pipelined data buffered before the TLS upgrade |
|
|
28
|
+
| `9fb8a5e3` | 2026-06-05 | Bound inbound line length in the parser, so an unterminated line cannot grow without limit |
|
|
29
|
+
| `627c6d47` | 2026-06-05 | Re-arm a generous idle timeout for proxied connections |
|
|
30
|
+
| `e97950e7` | 2026-06-05 | Close leaks and a worker crash found in the connection hardening review |
|
|
31
|
+
| `d51e92d2` | 2026-06-06 | Prevent post-BYE command dispatch during teardown |
|
|
32
|
+
| `31f6a590` | 2026-07-26 | Fix the dead teardown guard in the notification listener |
|
|
33
|
+
|
|
34
|
+
Earlier local changes (`09085d12`, `0a389560`, `7e2e94f3`, `04c2aa90`, `1d6df05e`, `612d9f96`,
|
|
35
|
+
`13edec58`, `2e0bf1ce`, `b9a3e06c`, `b58a827e`, `1813f089`) are maintenance: dependency swaps
|
|
36
|
+
(`punycode` to `punycode.js`, `wild-config` to `@zone-eu/wild-config`), the `fast` IMAP indexing
|
|
37
|
+
option, OAuth `useAuthServer` support, formatting and lint-glob fixes.
|
|
38
|
+
|
|
39
|
+
`git log -- lib/imapproxy/imap-core/` is the authoritative list; this table is a summary.
|
|
40
|
+
|
|
41
|
+
## Tests
|
|
42
|
+
|
|
43
|
+
The `test/` directory is upstream's mocha suite. It is written for mocha, which is not a
|
|
44
|
+
dependency here, and had never been executed after the import.
|
|
45
|
+
|
|
46
|
+
The hermetic specs now run as part of the normal unit tier through
|
|
47
|
+
`test/imap-core-vendored-test.js`, which installs the mocha globals the specs expect and requires
|
|
48
|
+
them. **Do not edit the files under `test/` to make them run** - keeping them byte-identical to
|
|
49
|
+
upstream is what makes the patch list above reviewable. Adapt them from the EmailEngine side
|
|
50
|
+
instead.
|
|
51
|
+
|
|
52
|
+
Wired up and running:
|
|
53
|
+
|
|
54
|
+
- `imap-parser-test.js`
|
|
55
|
+
- `imap-compiler-test.js`
|
|
56
|
+
- `imap-compile-stream-test.js`
|
|
57
|
+
- `imap-indexer-test.js` (upstream has its `#rebuild` block commented out)
|
|
58
|
+
- `tools-test.js`
|
|
59
|
+
|
|
60
|
+
Not wired up, because they drive a live server via `test-server.js` and need MongoDB plus a
|
|
61
|
+
WildDuck REST API that does not exist in this repository:
|
|
62
|
+
|
|
63
|
+
- `protocol-test.js`
|
|
64
|
+
- `search-test.js`
|
|
65
|
+
|
|
66
|
+
That is a real coverage gap: `protocol-test.js` is the suite that exercises the connection and
|
|
67
|
+
command state machines, which is where most of the local patches above landed. The connection
|
|
68
|
+
handling that EmailEngine actually ships is covered instead by `test/dovecot/` (live IMAP against
|
|
69
|
+
Dovecot) and the IMAP proxy's own integration tests.
|
|
@@ -9,6 +9,42 @@
|
|
|
9
9
|
const ACCEPTED_SUBJECT_TOKEN_TYPES = new Set(['urn:ietf:params:oauth:token-type:jwt', 'urn:ietf:params:oauth:token-type:id_token']);
|
|
10
10
|
const IMPERSONATION_URL_RE = /\/v1\/projects\/-\/serviceAccounts\/([^/]+):generateAccessToken$/;
|
|
11
11
|
|
|
12
|
+
// Google STS is the only endpoint allowed to receive the subject token.
|
|
13
|
+
//
|
|
14
|
+
// The subject token is read from this host - a projected OIDC token file, or a metadata endpoint -
|
|
15
|
+
// and POSTed verbatim as the `subject_token` form field. A caller-chosen token_url therefore turns
|
|
16
|
+
// the credential source into an exfiltration channel: point it at your own server and whatever the
|
|
17
|
+
// configured file contains is delivered to you, and the response comes back in-band because
|
|
18
|
+
// /v1/oauth2/{app}/verify reports the endpoint's error_description. Pinning the host closes that
|
|
19
|
+
// channel, so the credential source can only ever be delivered to Google.
|
|
20
|
+
const STS_HOST = 'sts.googleapis.com';
|
|
21
|
+
|
|
22
|
+
// Regional STS endpoints, e.g. sts.europe-west1.rep.googleapis.com
|
|
23
|
+
const REGIONAL_STS_HOST_RE = /^sts\.[a-z0-9-]+\.rep\.googleapis\.com$/;
|
|
24
|
+
|
|
25
|
+
// Validates token_url against the Google STS endpoints. `allowedTokenHosts` is an injection point
|
|
26
|
+
// for tests that stand up a local STS double; production callers never pass it, which is the same
|
|
27
|
+
// arrangement as the signer's iamCredentialsBaseUrl option.
|
|
28
|
+
function assertTokenUrl(rawUrl, allowedTokenHosts) {
|
|
29
|
+
let url;
|
|
30
|
+
try {
|
|
31
|
+
url = new URL(rawUrl);
|
|
32
|
+
} catch (err) {
|
|
33
|
+
throw makeError('External account token_url is not a valid URL', 'EExternalAccountConfig');
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
if (allowedTokenHosts && allowedTokenHosts.includes(url.hostname)) {
|
|
37
|
+
return;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
if (url.protocol !== 'https:' || !(url.hostname === STS_HOST || REGIONAL_STS_HOST_RE.test(url.hostname))) {
|
|
41
|
+
throw makeError(
|
|
42
|
+
`External account token_url must be a Google STS endpoint (https://${STS_HOST}/v1/token), got ${JSON.stringify(url.protocol + '//' + url.hostname)}`,
|
|
43
|
+
'EExternalAccountConfig'
|
|
44
|
+
);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
12
48
|
function makeError(message, code, statusCode, extra) {
|
|
13
49
|
let err = new Error(message);
|
|
14
50
|
err.code = code;
|
|
@@ -25,7 +61,9 @@ function makeError(message, code, statusCode, extra) {
|
|
|
25
61
|
// returns the derived target service account email. Throws an error tagged with
|
|
26
62
|
// code 'EExternalAccountConfig' on any problem so callers can surface a clean
|
|
27
63
|
// validation message instead of a late runtime failure.
|
|
28
|
-
function validateConfig(config) {
|
|
64
|
+
function validateConfig(config, opts) {
|
|
65
|
+
const { allowedTokenHosts } = opts || {};
|
|
66
|
+
|
|
29
67
|
if (!config || typeof config !== 'object') {
|
|
30
68
|
throw makeError('External account configuration must be a JSON object', 'EExternalAccountConfig');
|
|
31
69
|
}
|
|
@@ -41,6 +79,8 @@ function validateConfig(config) {
|
|
|
41
79
|
}
|
|
42
80
|
}
|
|
43
81
|
|
|
82
|
+
assertTokenUrl(config.token_url, allowedTokenHosts);
|
|
83
|
+
|
|
44
84
|
if (!ACCEPTED_SUBJECT_TOKEN_TYPES.has(config.subject_token_type)) {
|
|
45
85
|
throw makeError(
|
|
46
86
|
`External account subject_token_type ${JSON.stringify(config.subject_token_type)} is not supported. ` +
|
|
@@ -19,7 +19,7 @@ class ExternalAccountSigner {
|
|
|
19
19
|
constructor(opts) {
|
|
20
20
|
opts = opts || {};
|
|
21
21
|
|
|
22
|
-
let { targetServiceAccountEmail } = validateConfig(opts.config);
|
|
22
|
+
let { targetServiceAccountEmail } = validateConfig(opts.config, { allowedTokenHosts: opts.allowedTokenHosts });
|
|
23
23
|
|
|
24
24
|
this.config = opts.config;
|
|
25
25
|
// The service account whose Google-managed key signs the JWT. Exposed so
|
|
@@ -59,7 +59,12 @@ class ExternalAccountSigner {
|
|
|
59
59
|
try {
|
|
60
60
|
rawText = await this._readFile(source.file, 'utf8');
|
|
61
61
|
} catch (err) {
|
|
62
|
-
|
|
62
|
+
// Report the errno rather than the raw message: the path came from the operator so
|
|
63
|
+
// echoing it back is useful, but the full fs message adds nothing and this string
|
|
64
|
+
// is surfaced in the verify report.
|
|
65
|
+
throw makeError(`Failed to read subject token file ${source.file}${err.code ? ` (${err.code})` : ''}`, 'ESubjectTokenRead', null, {
|
|
66
|
+
cause: err
|
|
67
|
+
});
|
|
63
68
|
}
|
|
64
69
|
return extractFromFormat(rawText, format);
|
|
65
70
|
}
|
package/lib/oauth/verify-app.js
CHANGED
|
@@ -29,17 +29,29 @@ const withTimeout = (promise, ms, label) =>
|
|
|
29
29
|
new Promise((resolve, reject) => setTimeout(() => reject(new Error(`${label} timed out after ${Math.round(ms / 1000)}s`)), ms).unref())
|
|
30
30
|
]);
|
|
31
31
|
|
|
32
|
+
// Upper bound on remote error text echoed into the verify report. These strings come from the
|
|
33
|
+
// remote endpoint, so they are reflected content: bound them rather than passing an
|
|
34
|
+
// arbitrarily long body through into the API response.
|
|
35
|
+
const MAX_REMOTE_DETAIL_LENGTH = 512;
|
|
36
|
+
|
|
37
|
+
function truncateDetail(value) {
|
|
38
|
+
if (typeof value !== 'string') {
|
|
39
|
+
return null;
|
|
40
|
+
}
|
|
41
|
+
return value.length > MAX_REMOTE_DETAIL_LENGTH ? `${value.slice(0, MAX_REMOTE_DETAIL_LENGTH)}...` : value;
|
|
42
|
+
}
|
|
43
|
+
|
|
32
44
|
function describeResponse(err) {
|
|
33
45
|
let resp = err && (err.response || (err.tokenRequest && err.tokenRequest.response));
|
|
34
46
|
if (resp && typeof resp === 'object') {
|
|
35
47
|
// Google API errors nest the detail under error.message; OAuth/STS errors
|
|
36
48
|
// use top-level string error/error_description fields.
|
|
37
49
|
if (resp.error && typeof resp.error === 'object' && resp.error.message) {
|
|
38
|
-
return resp.error.message;
|
|
50
|
+
return truncateDetail(resp.error.message);
|
|
39
51
|
}
|
|
40
|
-
let parts = [resp.error, resp.error_description].filter(
|
|
52
|
+
let parts = [resp.error, resp.error_description].filter(part => typeof part === 'string' && part);
|
|
41
53
|
if (parts.length) {
|
|
42
|
-
return parts.join(': ');
|
|
54
|
+
return truncateDetail(parts.join(': '));
|
|
43
55
|
}
|
|
44
56
|
}
|
|
45
57
|
return null;
|
|
@@ -395,3 +407,6 @@ async function verifyOAuth2App(appId, opts) {
|
|
|
395
407
|
}
|
|
396
408
|
|
|
397
409
|
module.exports = { verifyOAuth2App };
|
|
410
|
+
|
|
411
|
+
// Exported for tests only; describeResponse reflects remote content into the verify report.
|
|
412
|
+
module.exports.__test__ = { describeResponse, MAX_REMOTE_DETAIL_LENGTH };
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// Retention policies for BullMQ job entries.
|
|
4
|
+
//
|
|
5
|
+
// This module is deliberately dependency-free (no Redis, no settings) so it can be unit tested
|
|
6
|
+
// directly. Four call sites used to build these policies inline from the `queueKeep` setting and
|
|
7
|
+
// had already drifted apart: three read the setting with `?? true` and one with `|| true`, which
|
|
8
|
+
// silently turned an explicit `queueKeep = 0` into "keep everything".
|
|
9
|
+
|
|
10
|
+
// How long a completed entry is kept when the operator asked for a bounded count. Completed jobs
|
|
11
|
+
// are purely for debugging, so a day is plenty.
|
|
12
|
+
const COMPLETED_JOB_RETENTION_AGE = 24 * 3600;
|
|
13
|
+
|
|
14
|
+
// Failed entries are the only record that a delivery was given up on, so they outlive completed
|
|
15
|
+
// ones. Bounded on both axes because webhook payloads can carry up to `notifyTextSize` (2MB by
|
|
16
|
+
// default) of message text and an endpoint that is down fails every event it is sent.
|
|
17
|
+
// Both are overridable because the right bound depends on payload size: a `messageNew` webhook
|
|
18
|
+
// carries up to `notifyTextSize` (2MB by default) of message text, and a receiver that is down
|
|
19
|
+
// turns every event into a retained entry.
|
|
20
|
+
const FAILED_JOB_RETENTION_AGE = Number(process.env.EENGINE_QUEUE_KEEP_FAILED_AGE) || 7 * 24 * 3600;
|
|
21
|
+
const FAILED_JOB_RETENTION_COUNT = Number(process.env.EENGINE_QUEUE_KEEP_FAILED) || 500;
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Builds the `removeOnComplete` / `removeOnFail` pair for a queue job.
|
|
25
|
+
*
|
|
26
|
+
* A job reaches the failed set only after every retry is exhausted, which for a webhook means the
|
|
27
|
+
* event is gone. `queueKeep` defaults to 0, so applying it to failures too (the previous behavior)
|
|
28
|
+
* deleted that record the moment it was written and left nothing but a log line behind. Failures
|
|
29
|
+
* therefore get their own floor: at least `FAILED_JOB_RETENTION_COUNT` entries for
|
|
30
|
+
* `FAILED_JOB_RETENTION_AGE` seconds, regardless of how few completed entries are wanted.
|
|
31
|
+
*
|
|
32
|
+
* BullMQ reads these values as "when to remove", not "how much to keep": `true` removes the entry
|
|
33
|
+
* immediately, `false` keeps it forever, a number keeps the last N, and `{age, count}` keeps
|
|
34
|
+
* entries younger than `age` up to `count` of them.
|
|
35
|
+
*
|
|
36
|
+
* @param {boolean|number} queueKeep - The `queueKeep` setting: entries to retain, or a boolean
|
|
37
|
+
* @returns {{removeOnComplete: boolean|Object, removeOnFail: boolean|Object}} BullMQ job options
|
|
38
|
+
*/
|
|
39
|
+
function buildRetentionPolicy(queueKeep) {
|
|
40
|
+
const removeOnComplete = typeof queueKeep === 'number' ? { age: COMPLETED_JOB_RETENTION_AGE, count: queueKeep } : queueKeep;
|
|
41
|
+
|
|
42
|
+
// Always bounded, and widened when the operator asked to keep more entries than the floor
|
|
43
|
+
const removeOnFail = {
|
|
44
|
+
age: FAILED_JOB_RETENTION_AGE,
|
|
45
|
+
count: typeof queueKeep === 'number' ? Math.max(queueKeep, FAILED_JOB_RETENTION_COUNT) : FAILED_JOB_RETENTION_COUNT
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
return { removeOnComplete, removeOnFail };
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
module.exports = {
|
|
52
|
+
buildRetentionPolicy,
|
|
53
|
+
COMPLETED_JOB_RETENTION_AGE,
|
|
54
|
+
FAILED_JOB_RETENTION_AGE,
|
|
55
|
+
FAILED_JOB_RETENTION_COUNT
|
|
56
|
+
};
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// Respawn pacing for supervised worker threads.
|
|
4
|
+
//
|
|
5
|
+
// A worker that dies deterministically (bad config, an unsatisfiable dependency, a crash on
|
|
6
|
+
// startup) used to be respawned on a flat 1s timer forever: roughly one thread start per second,
|
|
7
|
+
// indefinitely, pinning a core and burying every other log line under the same repeating stack.
|
|
8
|
+
//
|
|
9
|
+
// This is pacing, not a circuit breaker. Respawning never stops and is never blocked by another
|
|
10
|
+
// worker's failures - the delay only grows while a given worker type keeps dying quickly, and a
|
|
11
|
+
// worker that stays up resets its own type immediately.
|
|
12
|
+
|
|
13
|
+
const DEFAULT_BASE_DELAY = 1000;
|
|
14
|
+
const DEFAULT_MAX_DELAY = 60 * 1000;
|
|
15
|
+
|
|
16
|
+
// How long a worker must survive before its start counts as successful. Longer than any plausible
|
|
17
|
+
// startup crash, shorter than any real workload, so a genuine crash loop cannot look healthy.
|
|
18
|
+
const DEFAULT_STABLE_UPTIME = 60 * 1000;
|
|
19
|
+
|
|
20
|
+
const DEFAULT_JITTER = 0.2;
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Tracks per-type crash streaks and derives how long to wait before the next respawn.
|
|
24
|
+
*/
|
|
25
|
+
class RespawnTracker {
|
|
26
|
+
constructor(opts) {
|
|
27
|
+
const {
|
|
28
|
+
baseDelay = DEFAULT_BASE_DELAY,
|
|
29
|
+
maxDelay = DEFAULT_MAX_DELAY,
|
|
30
|
+
stableUptime = DEFAULT_STABLE_UPTIME,
|
|
31
|
+
jitter = DEFAULT_JITTER,
|
|
32
|
+
random = Math.random
|
|
33
|
+
} = opts || {};
|
|
34
|
+
|
|
35
|
+
this.baseDelay = baseDelay;
|
|
36
|
+
this.maxDelay = maxDelay;
|
|
37
|
+
this.stableUptime = stableUptime;
|
|
38
|
+
this.jitter = jitter;
|
|
39
|
+
this.random = random;
|
|
40
|
+
|
|
41
|
+
// worker type -> count of consecutive short-lived exits
|
|
42
|
+
this.failures = new Map();
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Records that a worker of the given type exited and returns the delay before respawning it.
|
|
47
|
+
*
|
|
48
|
+
* @param {string} type - Worker type (imap, api, webhooks, ...)
|
|
49
|
+
* @param {number} uptimeMs - How long the worker had been running
|
|
50
|
+
* @returns {number} Milliseconds to wait before respawning
|
|
51
|
+
*/
|
|
52
|
+
recordExit(type, uptimeMs) {
|
|
53
|
+
if (uptimeMs >= this.stableUptime) {
|
|
54
|
+
// The worker did real work before dying, so this is not a crash loop. Start over so a
|
|
55
|
+
// long-lived worker that finally crashes restarts as promptly as a fresh one.
|
|
56
|
+
this.failures.delete(type);
|
|
57
|
+
return this.delayFor(1);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
const failures = (this.failures.get(type) || 0) + 1;
|
|
61
|
+
this.failures.set(type, failures);
|
|
62
|
+
|
|
63
|
+
return this.delayFor(failures);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Delay for the nth consecutive failure. The first failure keeps the historical 1s delay.
|
|
68
|
+
* @param {number} failures - Consecutive short-lived exits, 1 based
|
|
69
|
+
* @returns {number} Milliseconds to wait
|
|
70
|
+
*/
|
|
71
|
+
delayFor(failures) {
|
|
72
|
+
const delay = Math.min(this.baseDelay * Math.pow(2, failures - 1), this.maxDelay);
|
|
73
|
+
|
|
74
|
+
// Spread respawns so a fleet-wide crash (Redis went away) does not come back in lockstep
|
|
75
|
+
const spread = 1 - this.jitter + this.jitter * 2 * this.random();
|
|
76
|
+
|
|
77
|
+
return Math.round(delay * spread);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Consecutive short-lived exits recorded for a type, for logging.
|
|
82
|
+
* @param {string} type - Worker type
|
|
83
|
+
* @returns {number} Current streak
|
|
84
|
+
*/
|
|
85
|
+
streakFor(type) {
|
|
86
|
+
return this.failures.get(type) || 0;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
module.exports = {
|
|
91
|
+
RespawnTracker,
|
|
92
|
+
DEFAULT_BASE_DELAY,
|
|
93
|
+
DEFAULT_MAX_DELAY,
|
|
94
|
+
DEFAULT_STABLE_UPTIME
|
|
95
|
+
};
|
package/lib/schemas.js
CHANGED
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
const Joi = require('joi');
|
|
4
4
|
const config = require('@zone-eu/wild-config');
|
|
5
5
|
const { getByteSize } = require('./tools');
|
|
6
|
+
const { COLLAPSE_CLASS } = require('./consts');
|
|
6
7
|
const { locales } = require('./translations');
|
|
7
8
|
const { LEGACY_KEYS, OAUTH_PROVIDERS } = require('./oauth2-apps');
|
|
8
9
|
const { ACCOUNT_STATES } = require('./account/account-state');
|
|
@@ -282,7 +283,9 @@ const settingsSchema = {
|
|
|
282
283
|
notifyWebSafeHtml: Joi.boolean()
|
|
283
284
|
.truthy('Y', 'true', '1', 'on')
|
|
284
285
|
.falsy('N', 'false', 0, '')
|
|
285
|
-
.description(
|
|
286
|
+
.description(
|
|
287
|
+
'Sanitize HTML content to remove potentially dangerous elements before including in webhooks, and fold quoted thread history into a collapsed block'
|
|
288
|
+
),
|
|
286
289
|
notifyTextSize: Joi.number().integer().min(0).description('Maximum size (in bytes) of text content to include in webhook payloads'),
|
|
287
290
|
notifyAttachments: Joi.boolean().truthy('Y', 'true', '1', 'on').falsy('N', 'false', 0, '').description('Include attachment data in webhook payloads'),
|
|
288
291
|
notifyAttachmentSize: Joi.number().integer().min(0).description('Maximum size (in bytes) per attachment to include in webhook payloads'),
|
|
@@ -1142,7 +1145,11 @@ const messageDetailsSchema = Joi.object({
|
|
|
1142
1145
|
.description('Whether the message content was truncated (true if more content is available via separate API call)'),
|
|
1143
1146
|
webSafe: Joi.boolean()
|
|
1144
1147
|
.example(true)
|
|
1145
|
-
.description(
|
|
1148
|
+
.description(
|
|
1149
|
+
'Whether the HTML content has been processed into a web-safe version (set when webSafeHtml was requested). ' +
|
|
1150
|
+
`Web-safe HTML for a reply also carries the quoted thread in a single collapsed <details class="${COLLAPSE_CLASS}"> ` +
|
|
1151
|
+
'element, so renderers can hide it behind one control. Its <summary> is deliberately empty - supply your own label.'
|
|
1152
|
+
)
|
|
1146
1153
|
}).label('TextInfoDetails'),
|
|
1147
1154
|
|
|
1148
1155
|
bounces: bounceListSchema,
|
package/lib/settings.js
CHANGED
|
@@ -56,7 +56,10 @@ module.exports = {
|
|
|
56
56
|
|
|
57
57
|
value = JSON.parse(value);
|
|
58
58
|
} catch (err) {
|
|
59
|
-
|
|
59
|
+
// NB! never log `value` here. By this point a value for an encrypted key has
|
|
60
|
+
// already been decrypted, so on a parse failure this would write the plaintext
|
|
61
|
+
// secret (OAuth2 client secrets, the SMTP/IMAP proxy passwords) into the log.
|
|
62
|
+
logger.debug({ msg: 'Failed to parse stored setting', key, encrypted: ENCRYPTED_KEYS.includes(key), err });
|
|
60
63
|
return null;
|
|
61
64
|
}
|
|
62
65
|
}
|
package/lib/tools.js
CHANGED
|
@@ -2040,6 +2040,26 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
|
|
|
2040
2040
|
return key in process.env || `${key}_FILE` in process.env;
|
|
2041
2041
|
},
|
|
2042
2042
|
|
|
2043
|
+
/**
|
|
2044
|
+
* Reads a comma-separated environment value as a trimmed, blank-free array.
|
|
2045
|
+
*
|
|
2046
|
+
* Returns `null` when the variable is not set at all, which callers rely on to distinguish
|
|
2047
|
+
* "no allowlist configured" (feature off) from "an allowlist that happens to be empty".
|
|
2048
|
+
*
|
|
2049
|
+
* @param {string} key - Environment variable name
|
|
2050
|
+
* @returns {string[]|null} Parsed entries, or null when unset
|
|
2051
|
+
*/
|
|
2052
|
+
readEnvList(key) {
|
|
2053
|
+
if (!module.exports.hasEnvValue(key)) {
|
|
2054
|
+
return null;
|
|
2055
|
+
}
|
|
2056
|
+
|
|
2057
|
+
return (module.exports.readEnvValue(key) || '')
|
|
2058
|
+
.split(',')
|
|
2059
|
+
.map(v => v.trim())
|
|
2060
|
+
.filter(v => v);
|
|
2061
|
+
},
|
|
2062
|
+
|
|
2043
2063
|
readEnvValue(key) {
|
|
2044
2064
|
if (key in process.env) {
|
|
2045
2065
|
return process.env[key];
|
|
@@ -21,7 +21,9 @@ const consts = require('../consts');
|
|
|
21
21
|
const getSecret = require('../get-secret');
|
|
22
22
|
const timezonesList = require('timezones-list').default;
|
|
23
23
|
const { redis, submitQueue, notifyQueue, documentsQueue } = require('../db');
|
|
24
|
-
const { getByteSize, formatByteSize, getDuration, failAction,
|
|
24
|
+
const { getByteSize, formatByteSize, getDuration, failAction, readEnvValue, readEnvList, httpAgent } = require('../tools');
|
|
25
|
+
const { assertAllowedUrl, normalizePolicy, POLICY_OFF } = require('../egress-filter');
|
|
26
|
+
const { sendWebhookRequest } = require('../webhook-request');
|
|
25
27
|
const { llmPreProcess } = require('../llm-pre-process');
|
|
26
28
|
const { documentStoreFeatureEnabled } = require('../document-store');
|
|
27
29
|
const { locales } = require('../translations');
|
|
@@ -51,12 +53,12 @@ config.api = config.api || {
|
|
|
51
53
|
const MAX_BODY_SIZE = getByteSize(readEnvValue('EENGINE_MAX_BODY_SIZE') || config.api.maxBodySize) || DEFAULT_MAX_BODY_SIZE;
|
|
52
54
|
const MAX_PAYLOAD_TIMEOUT = getDuration(readEnvValue('EENGINE_MAX_PAYLOAD_TIMEOUT') || config.api.maxPayloadTimeout) || DEFAULT_MAX_PAYLOAD_TIMEOUT;
|
|
53
55
|
|
|
54
|
-
const ADMIN_ACCESS_ADDRESSES =
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
56
|
+
const ADMIN_ACCESS_ADDRESSES = readEnvList('EENGINE_ADMIN_ACCESS_ADDRESSES');
|
|
57
|
+
|
|
58
|
+
// Must match the policy the webhooks worker enforces on real deliveries, including the null that
|
|
59
|
+
// tells sendWebhookRequest to keep following redirects when the policy is off
|
|
60
|
+
const WEBHOOK_EGRESS_POLICY = normalizePolicy(readEnvValue('EENGINE_WEBHOOK_EGRESS_POLICY'));
|
|
61
|
+
const validateWebhookTarget = WEBHOOK_EGRESS_POLICY === POLICY_OFF ? null : target => assertAllowedUrl(target, { policy: WEBHOOK_EGRESS_POLICY });
|
|
60
62
|
|
|
61
63
|
const IMAP_INDEXERS = [
|
|
62
64
|
{
|
|
@@ -1065,12 +1067,14 @@ return true;`
|
|
|
1065
1067
|
let start = Date.now();
|
|
1066
1068
|
let duration;
|
|
1067
1069
|
try {
|
|
1068
|
-
let res;
|
|
1069
|
-
|
|
1070
1070
|
let serviceUrl = await settings.get('serviceUrl');
|
|
1071
1071
|
|
|
1072
|
+
// The same call the notify worker makes, rather than a lookalike: a probe that
|
|
1073
|
+
// reimplements delivery can only prove that the reimplementation works. It also
|
|
1074
|
+
// inherits the delivery timeout and the response drain, both of which this route
|
|
1075
|
+
// used to do without while running on the same keep-alive retry dispatcher.
|
|
1072
1076
|
try {
|
|
1073
|
-
|
|
1077
|
+
await sendWebhookRequest(fetchCmd, parsed.toString(), {
|
|
1074
1078
|
method: 'post',
|
|
1075
1079
|
body:
|
|
1076
1080
|
request.payload.payload ||
|
|
@@ -1084,20 +1088,17 @@ return true;`
|
|
|
1084
1088
|
}
|
|
1085
1089
|
}),
|
|
1086
1090
|
headers,
|
|
1087
|
-
dispatcher: httpAgent.retry
|
|
1091
|
+
dispatcher: httpAgent.retry,
|
|
1092
|
+
validateTarget: validateWebhookTarget
|
|
1088
1093
|
});
|
|
1089
1094
|
duration = Date.now() - start;
|
|
1090
1095
|
} catch (err) {
|
|
1091
1096
|
duration = Date.now() - start;
|
|
1097
|
+
// undici wraps a connection failure in a generic "fetch failed"; the cause is
|
|
1098
|
+
// the part worth reporting back to the operator
|
|
1092
1099
|
throw err.cause || err;
|
|
1093
1100
|
}
|
|
1094
1101
|
|
|
1095
|
-
if (!res.ok) {
|
|
1096
|
-
let err = new Error(res.statusText || `Invalid response: ${res.status} ${res.statusText}`);
|
|
1097
|
-
err.statusCode = res.status;
|
|
1098
|
-
throw err;
|
|
1099
|
-
}
|
|
1100
|
-
|
|
1101
1102
|
return {
|
|
1102
1103
|
success: true,
|
|
1103
1104
|
target: webhooks,
|
|
@@ -1110,7 +1111,10 @@ return true;`
|
|
|
1110
1111
|
target: webhooks,
|
|
1111
1112
|
duration,
|
|
1112
1113
|
error: err.message,
|
|
1113
|
-
code: err.code
|
|
1114
|
+
code: err.code,
|
|
1115
|
+
// Same field the stored webhookErrorFlag carries, so the probe and the error
|
|
1116
|
+
// block on this page describe a failed delivery the same way
|
|
1117
|
+
statusCode: err.statusCode
|
|
1114
1118
|
};
|
|
1115
1119
|
}
|
|
1116
1120
|
},
|
package/lib/utils/network.js
CHANGED
|
@@ -24,6 +24,46 @@ for (let prefixEntry of googleCrawlerRanges.prefixes) {
|
|
|
24
24
|
}
|
|
25
25
|
}
|
|
26
26
|
|
|
27
|
+
/**
|
|
28
|
+
* Parses an address, unwrapping the IPv4-mapped IPv6 form to the plain IPv4 it carries.
|
|
29
|
+
*
|
|
30
|
+
* A dual-stack listener reports an IPv4 peer as `::ffff:10.0.0.5`, while operators write the
|
|
31
|
+
* allowlist as `10.0.0.5`. Without this the two never compare equal, so a proxy declared in
|
|
32
|
+
* `EENGINE_API_PROXY_ADDRESSES` is not recognized and its X-Forwarded-For is discarded - which
|
|
33
|
+
* then denies the admin allowlist the very address it is configured to match.
|
|
34
|
+
*
|
|
35
|
+
* @param {string} address - IP address in any textual form
|
|
36
|
+
* @returns {Object} ipaddr.js address object, IPv4 whenever the input describes an IPv4 address
|
|
37
|
+
*/
|
|
38
|
+
function parseComparableIp(address) {
|
|
39
|
+
let parsed = ipaddr.parse(address);
|
|
40
|
+
|
|
41
|
+
if (parsed.kind() === 'ipv6' && parsed.isIPv4MappedAddress()) {
|
|
42
|
+
return parsed.toIPv4Address();
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
return parsed;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Parses a CIDR range the same way, so an IPv4-mapped range matches plain IPv4 subjects.
|
|
50
|
+
*
|
|
51
|
+
* The mapped prefix occupies the first 96 bits, so the remaining bits are the IPv4 prefix length:
|
|
52
|
+
* `::ffff:10.0.0.0/104` describes exactly `10.0.0.0/8`.
|
|
53
|
+
*
|
|
54
|
+
* @param {string} range - CIDR range
|
|
55
|
+
* @returns {Array} `[address, bits]` as ipaddr.js reports it, unwrapped where applicable
|
|
56
|
+
*/
|
|
57
|
+
function parseComparableCidr(range) {
|
|
58
|
+
let [parsed, bits] = ipaddr.parseCIDR(range);
|
|
59
|
+
|
|
60
|
+
if (parsed.kind() === 'ipv6' && parsed.isIPv4MappedAddress()) {
|
|
61
|
+
return [parsed.toIPv4Address(), Math.max(bits - 96, 0)];
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
return [parsed, bits];
|
|
65
|
+
}
|
|
66
|
+
|
|
27
67
|
/**
|
|
28
68
|
* Matches an IP address against a list of addresses or CIDR ranges
|
|
29
69
|
* @param {string} ip - IP address to check
|
|
@@ -31,14 +71,32 @@ for (let prefixEntry of googleCrawlerRanges.prefixes) {
|
|
|
31
71
|
* @returns {boolean} True if IP matches any address in the list
|
|
32
72
|
*/
|
|
33
73
|
function matchIp(ip, addresses) {
|
|
34
|
-
let parsed
|
|
74
|
+
let parsed;
|
|
75
|
+
try {
|
|
76
|
+
parsed = parseComparableIp(ip);
|
|
77
|
+
} catch (err) {
|
|
78
|
+
// Every caller uses this for an allowlist decision, so an address we can not parse must
|
|
79
|
+
// match nothing. Throwing here used to surface as a 500 for any request that carried a
|
|
80
|
+
// non-IP value in a trusted X-Forwarded-For header.
|
|
81
|
+
//
|
|
82
|
+
// Logged at debug, not error: the subject address is client-supplied (it can come from an
|
|
83
|
+
// X-Forwarded-For chain entry), so junk here is expected input rather than a fault. Bad
|
|
84
|
+
// entries in the allowlist itself are a config problem and still log at error below.
|
|
85
|
+
logger.debug({ msg: 'Failed to parse IP address', ip, err });
|
|
86
|
+
return false;
|
|
87
|
+
}
|
|
88
|
+
|
|
35
89
|
for (let addr of addresses) {
|
|
36
90
|
try {
|
|
37
91
|
let match;
|
|
38
92
|
if (/\/\d+$/.test(addr)) {
|
|
39
|
-
|
|
93
|
+
let [range, bits] = parseComparableCidr(addr);
|
|
94
|
+
// ipaddr.js throws when the families differ, and a list that mixes IPv4 and IPv6
|
|
95
|
+
// entries is ordinary rather than a misconfiguration, so a mismatch is simply not
|
|
96
|
+
// a match instead of an error log on every request
|
|
97
|
+
match = range.kind() === parsed.kind() && parsed.match(range, bits);
|
|
40
98
|
} else {
|
|
41
|
-
match = parsed.toNormalizedString() ===
|
|
99
|
+
match = parsed.toNormalizedString() === parseComparableIp(addr).toNormalizedString();
|
|
42
100
|
}
|
|
43
101
|
if (match) {
|
|
44
102
|
return true;
|
|
@@ -51,6 +109,66 @@ function matchIp(ip, addresses) {
|
|
|
51
109
|
return false;
|
|
52
110
|
}
|
|
53
111
|
|
|
112
|
+
/**
|
|
113
|
+
* Resolves the effective client IP address for an incoming HTTP request.
|
|
114
|
+
*
|
|
115
|
+
* `X-Forwarded-For` is a list that each proxy APPENDS to, so the left-most entry is whatever the
|
|
116
|
+
* original caller sent and is never trustworthy on its own - nginx's canonical
|
|
117
|
+
* `$proxy_add_x_forwarded_for`, Apache's mod_proxy and HAProxy's `option forwardfor` all preserve
|
|
118
|
+
* a client-supplied value and add the peer after it. Two security controls key off the resolved
|
|
119
|
+
* address (the `EENGINE_ADMIN_ACCESS_ADDRESSES` admin allowlist and per-token
|
|
120
|
+
* `restrictions.addresses`), so taking the left-most entry lets any caller present the address the
|
|
121
|
+
* allowlist expects and walk through both.
|
|
122
|
+
*
|
|
123
|
+
* With `trustedProxies` (`EENGINE_API_PROXY_ADDRESSES`) configured the chain is therefore walked
|
|
124
|
+
* from the right, discarding entries contributed by declared proxies; the first entry that is not
|
|
125
|
+
* one of our proxies is the closest address they actually observed. Both the peer and the chain
|
|
126
|
+
* are checked, so a caller that is not behind a declared proxy gets no say at all.
|
|
127
|
+
*
|
|
128
|
+
* With no `trustedProxies` there is no way to know how many hops to believe, so the historical
|
|
129
|
+
* left-most behavior is kept for compatibility. That mode is fine for logging but must not be
|
|
130
|
+
* relied on for allowlists - which is what the startup warning in the API worker is about.
|
|
131
|
+
*
|
|
132
|
+
* @param {Object} opts
|
|
133
|
+
* @param {string} opts.remoteAddress - Peer address of the socket the request arrived on
|
|
134
|
+
* @param {string} [opts.forwardedFor] - Raw `X-Forwarded-For` header value, if any
|
|
135
|
+
* @param {boolean} [opts.enableApiProxy] - Whether the deployment is configured to sit behind a proxy
|
|
136
|
+
* @param {string[]} [opts.trustedProxies] - Addresses or CIDR ranges of our own proxies
|
|
137
|
+
* @returns {string} Address to treat as the client for logging and allowlist checks
|
|
138
|
+
*/
|
|
139
|
+
function resolveClientIp({ remoteAddress, forwardedFor, enableApiProxy, trustedProxies }) {
|
|
140
|
+
if (!enableApiProxy || !forwardedFor) {
|
|
141
|
+
return remoteAddress;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
// Anything that is not a bare IP (a port suffix, an obfuscated identifier, junk) can not be
|
|
145
|
+
// matched against an allowlist, so it is treated as no claim at all
|
|
146
|
+
const asClientAddress = value => (net.isIP(value) ? value : remoteAddress);
|
|
147
|
+
|
|
148
|
+
if (!trustedProxies || !trustedProxies.length) {
|
|
149
|
+
return asClientAddress(forwardedFor.split(',')[0].trim());
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
if (!matchIp(remoteAddress, trustedProxies)) {
|
|
153
|
+
// Request did not come from a declared proxy, so its forwarding header means nothing
|
|
154
|
+
return remoteAddress;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
const chain = forwardedFor
|
|
158
|
+
.split(',')
|
|
159
|
+
.map(entry => entry.trim())
|
|
160
|
+
.filter(entry => entry);
|
|
161
|
+
|
|
162
|
+
for (let i = chain.length - 1; i >= 0; i--) {
|
|
163
|
+
if (!matchIp(chain[i], trustedProxies)) {
|
|
164
|
+
return asClientAddress(chain[i]);
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
// Every hop was one of ours, so nothing in the chain describes an external caller
|
|
169
|
+
return remoteAddress;
|
|
170
|
+
}
|
|
171
|
+
|
|
54
172
|
/**
|
|
55
173
|
* Detects if a request is from an automated scanner (Google, Barracuda, etc.)
|
|
56
174
|
* @param {string} ip - IP address to check
|
|
@@ -232,6 +350,7 @@ module.exports = {
|
|
|
232
350
|
updatePublicInterfaces,
|
|
233
351
|
getLocalAddress,
|
|
234
352
|
matchIp,
|
|
353
|
+
resolveClientIp,
|
|
235
354
|
detectAutomatedRequest,
|
|
236
355
|
googleCrawlerMap
|
|
237
356
|
};
|