@oxyhq/core 10.1.5 → 10.2.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.
@@ -1,3 +1,5 @@
1
+ import { createHmac } from 'node:crypto';
2
+ import { isIPv4, isIPv6 } from 'node:net';
1
3
  import rateLimit from 'express-rate-limit';
2
4
  /**
3
5
  * Built-in exemptions. A media app's cover-art/avatar fan-out and HLS
@@ -15,9 +17,98 @@ function isBuiltInExempt(req) {
15
17
  path === '/health' ||
16
18
  path.endsWith('/health'));
17
19
  }
18
- /** IPv6-safe IP key generator (replaces colons to avoid Redis namespace issues). */
19
- function ipKeyGenerator(ip) {
20
- return ip.replace(/:/g, '_');
20
+ /**
21
+ * Anonymous rate-limit keys must be PRIVACY-PRESERVING: the raw client IP must
22
+ * never reach a store at rest (in-memory or Redis). We therefore HMAC-hash the
23
+ * IP into a short, transient-only bucket key. Two IPv6-specific concerns shape
24
+ * the pre-hash normalization:
25
+ *
26
+ * - IPv6 hosts are typically handed an entire /64 (often a /56), so a single
27
+ * host can rotate through an enormous address space and evade a per-address
28
+ * limit. We bucket IPv6 to its /56 prefix BEFORE hashing.
29
+ * - express-rate-limit only exposes an `ipKeyGenerator` /56 helper from v8
30
+ * onwards; `@oxyhq/core` pins v7 (peer `^7.0.0`), so the masking is
31
+ * implemented here rather than pulling a major-version bump of a
32
+ * security-critical dependency (and its rate-limit-redis compatibility) into
33
+ * an unrelated privacy change. This mirrors `packages/api/src/utils/ipKey.ts`.
34
+ */
35
+ const IPV6_SUBNET_BITS = 56;
36
+ /** Expand an IPv6 literal (handling `::` and embedded IPv4) to 8 numeric hextets, or null if unparseable. */
37
+ function ipv6Hextets(ip) {
38
+ let addr = ip;
39
+ const zone = addr.indexOf('%');
40
+ if (zone !== -1) {
41
+ addr = addr.slice(0, zone);
42
+ }
43
+ // Embedded IPv4 tail (e.g. `::ffff:203.0.113.7`) → fold the dotted quad into two hextets.
44
+ const lastColon = addr.lastIndexOf(':');
45
+ if (lastColon !== -1 && addr.slice(lastColon + 1).includes('.')) {
46
+ const v4 = addr.slice(lastColon + 1);
47
+ if (!isIPv4(v4)) {
48
+ return null;
49
+ }
50
+ const octets = v4.split('.').map((part) => Number.parseInt(part, 10));
51
+ const high = ((octets[0] << 8) | octets[1]).toString(16);
52
+ const low = ((octets[2] << 8) | octets[3]).toString(16);
53
+ addr = `${addr.slice(0, lastColon + 1)}${high}:${low}`;
54
+ }
55
+ const halves = addr.split('::');
56
+ if (halves.length > 2) {
57
+ return null;
58
+ }
59
+ const head = halves[0] ? halves[0].split(':') : [];
60
+ const tail = halves.length === 2 && halves[1] ? halves[1].split(':') : [];
61
+ let groups;
62
+ if (halves.length === 1) {
63
+ groups = head;
64
+ }
65
+ else {
66
+ const missing = 8 - (head.length + tail.length);
67
+ if (missing < 0) {
68
+ return null;
69
+ }
70
+ groups = [...head, ...new Array(missing).fill('0'), ...tail];
71
+ }
72
+ if (groups.length !== 8) {
73
+ return null;
74
+ }
75
+ const hextets = groups.map((group) => Number.parseInt(group || '0', 16));
76
+ if (hextets.some((value) => Number.isNaN(value) || value < 0 || value > 0xffff)) {
77
+ return null;
78
+ }
79
+ return hextets;
80
+ }
81
+ /** Mask an IPv6 address to its /{bits} prefix, returned as a canonical hex string. */
82
+ function maskIPv6(ip, bits) {
83
+ const hextets = ipv6Hextets(ip);
84
+ if (!hextets) {
85
+ return ip;
86
+ }
87
+ const masked = hextets.map((hextet, index) => {
88
+ const groupStart = index * 16;
89
+ if (groupStart >= bits) {
90
+ return 0;
91
+ }
92
+ const keepBits = Math.min(16, bits - groupStart);
93
+ const mask = keepBits >= 16 ? 0xffff : (0xffff << (16 - keepBits)) & 0xffff;
94
+ return hextet & mask;
95
+ });
96
+ return `${masked.map((hextet) => hextet.toString(16)).join(':')}/${bits}`;
97
+ }
98
+ /**
99
+ * Hash a client IP into a privacy-preserving bucket key. IPv6 is bucketed to its
100
+ * /56 prefix first (so a single v6 host can't rotate through its allocation to
101
+ * mint fresh keys), then HMAC'd with the server-side salt. The salt is resolved
102
+ * at CALL time (`IP_HASH_SALT`, else `DEVICE_ID_SALT`, else empty) — an empty
103
+ * salt still hashes, which beats storing a raw IP; backends SHOULD set one of
104
+ * those envs. The `rl|` namespace ensures a rate-limit key can never collide
105
+ * with, or be correlated against, a deviceId derivation that reuses the same
106
+ * salt. The result is a short hex digest with no colons, so it is Redis-safe.
107
+ */
108
+ function hashAnonymousIp(ip) {
109
+ const normalized = isIPv6(ip) && !ip.startsWith('::ffff:') ? maskIPv6(ip, IPV6_SUBNET_BITS) : ip;
110
+ const salt = process.env.IP_HASH_SALT || process.env.DEVICE_ID_SALT || '';
111
+ return createHmac('sha256', salt).update(`rl|${normalized}`).digest('hex').slice(0, 24);
21
112
  }
22
113
  /**
23
114
  * Resolve the trusted authenticated rate-limit key.
@@ -43,14 +134,17 @@ function resolveTrustedAuthenticatedKey(req) {
43
134
  }
44
135
  return null;
45
136
  }
46
- /** Resolve the rate-limit key: per trusted authenticated identity, else per (IPv6-safe) IP. */
137
+ /** Resolve the rate-limit key: per trusted authenticated identity, else per hashed (IPv6-bucketed) IP. */
47
138
  function resolveKey(req) {
48
139
  const authenticatedKey = resolveTrustedAuthenticatedKey(req);
49
140
  if (authenticatedKey) {
50
141
  return authenticatedKey;
51
142
  }
52
- const ip = req.ip || req.socket.remoteAddress || 'unknown';
53
- return ipKeyGenerator(ip);
143
+ const ip = req.ip || req.socket.remoteAddress;
144
+ if (!ip) {
145
+ return 'unknown';
146
+ }
147
+ return hashAnonymousIp(ip);
54
148
  }
55
149
  /**
56
150
  * Build the composed Oxy rate-limit middleware. See module docs for rationale.