emailengine-app 2.74.2 → 2.76.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.
Files changed (51) hide show
  1. package/.github/workflows/test.yml +0 -10
  2. package/CHANGELOG.md +40 -0
  3. package/config/e2e.toml +1 -1
  4. package/data/google-crawlers.json +1 -1
  5. package/lib/account.js +94 -18
  6. package/lib/api-routes/message-routes.js +3 -1
  7. package/lib/api-routes/route-helpers.js +3 -0
  8. package/lib/api-routes/submit-routes.js +159 -52
  9. package/lib/consts.js +6 -0
  10. package/lib/db.js +4 -1
  11. package/lib/egress-filter.js +220 -0
  12. package/lib/email-client/base-client.js +169 -27
  13. package/lib/email-client/gmail/send-request.js +16 -1
  14. package/lib/email-client/gmail-client.js +91 -10
  15. package/lib/email-client/imap/mailbox.js +3 -9
  16. package/lib/email-client/imap-client.js +103 -1
  17. package/lib/email-client/message-builder.js +24 -7
  18. package/lib/email-client/notification-handler.js +11 -12
  19. package/lib/email-client/outlook/send-request.js +18 -1
  20. package/lib/email-client/outlook-client.js +81 -9
  21. package/lib/imapproxy/imap-core/README.md +69 -0
  22. package/lib/oauth/external-account-config.js +41 -1
  23. package/lib/oauth/external-account-signer.js +7 -2
  24. package/lib/oauth/verify-app.js +18 -3
  25. package/lib/queue-retention.js +56 -0
  26. package/lib/respawn-backoff.js +95 -0
  27. package/lib/schemas.js +9 -2
  28. package/lib/settings.js +4 -1
  29. package/lib/tools.js +20 -0
  30. package/lib/ui-routes/admin-config-routes.js +22 -18
  31. package/lib/utils/network.js +122 -3
  32. package/lib/web-safe-html.js +401 -0
  33. package/lib/webhook-request.js +40 -2
  34. package/lib/webhooks.js +2 -3
  35. package/package.json +17 -20
  36. package/playwright.config.js +1 -1
  37. package/sbom.json +1 -1
  38. package/server.js +45 -8
  39. package/static/js/ee-client.js +55 -6
  40. package/static/js/ui.js +13 -0
  41. package/static/licenses.html +332 -292
  42. package/translations/messages.pot +52 -52
  43. package/views/config/webhooks.hbs +2 -2
  44. package/views/partials/webhooks_editor_functions.hbs +1 -1
  45. package/workers/api.js +32 -17
  46. package/workers/documents.js +6 -0
  47. package/workers/export.js +8 -1
  48. package/workers/imap.js +17 -19
  49. package/workers/submit.js +10 -0
  50. package/workers/webhooks.js +23 -2
  51. package/Gruntfile.js +0 -58
@@ -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('Sanitize HTML content to remove potentially dangerous elements before including in webhooks'),
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('Whether the HTML content has been processed into a web-safe version (set when webSafeHtml was requested)')
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
- logger.debug({ key, value, err });
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, hasEnvValue, readEnvValue, httpAgent } = require('../tools');
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 = hasEnvValue('EENGINE_ADMIN_ACCESS_ADDRESSES')
55
- ? readEnvValue('EENGINE_ADMIN_ACCESS_ADDRESSES')
56
- .split(',')
57
- .map(v => v.trim())
58
- .filter(v => v)
59
- : null;
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
- res = await fetchCmd(parsed.toString(), {
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
  },
@@ -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 = ipaddr.parse(ip);
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
- match = parsed.match(ipaddr.parseCIDR(addr));
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() === ipaddr.parse(addr).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
  };