@arcblock/ws 1.30.25 → 1.30.26

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.
@@ -49,6 +49,8 @@ interface WsServerOptions {
49
49
  maxConnectionsPerIp?: number;
50
50
  trustProxy?: boolean | number;
51
51
  trustProxyHops?: number;
52
+ trustedProxies?: string[];
53
+ trustedIpHeader?: string;
52
54
  sanitizeErrors?: boolean;
53
55
  }
54
56
  interface BroadcastOptions {
@@ -98,6 +100,8 @@ declare class WsServer extends EventEmitter {
98
100
  maxConnectionsPerIp: number;
99
101
  trustProxy: boolean;
100
102
  trustProxyHops: number;
103
+ trustedProxies: string[];
104
+ trustedIpHeader?: string;
101
105
  sanitizeErrors: boolean;
102
106
  wss: WebSocketServer;
103
107
  topics: Record<string, Set<WsSocket>>;
@@ -79,16 +79,115 @@ const parseEnvPositiveInt = (raw, fallback) => {
79
79
  const parsed = Number(raw);
80
80
  return Number.isInteger(parsed) && parsed >= 1 ? parsed : fallback;
81
81
  };
82
- const resolveClientIpFromHeaders = (headers, trustProxyHops) => {
83
- const rawRealIp = headers["x-real-ip"];
84
- const realIp = (Array.isArray(rawRealIp) ? rawRealIp[0] : rawRealIp)?.trim();
85
- if (realIp) return realIp;
82
+ const DEFAULT_TRUSTED_PROXIES = [
83
+ "127.0.0.0/8",
84
+ "::1/128",
85
+ "10.0.0.0/8",
86
+ "172.16.0.0/12",
87
+ "192.168.0.0/16",
88
+ "fc00::/7",
89
+ "fe80::/10"
90
+ ];
91
+ const parseIpv4ToUint32 = (ip) => {
92
+ const parts = ip.split(".");
93
+ if (parts.length !== 4) return null;
94
+ let result = 0;
95
+ for (const part of parts) {
96
+ if (!/^\d{1,3}$/.test(part)) return null;
97
+ const n = Number(part);
98
+ if (n < 0 || n > 255) return null;
99
+ result = (result << 8 | n) >>> 0;
100
+ }
101
+ return result;
102
+ };
103
+ const parseIpv6ToBigInt = (raw) => {
104
+ const ip = raw.toLowerCase();
105
+ if (ip.includes(".")) {
106
+ const lastColon = ip.lastIndexOf(":");
107
+ if (lastColon === -1) return null;
108
+ const v4 = parseIpv4ToUint32(ip.slice(lastColon + 1));
109
+ if (v4 === null) return null;
110
+ const highHex = (v4 >>> 16 & 65535).toString(16);
111
+ const lowHex = (v4 & 65535).toString(16);
112
+ return parseIpv6ToBigInt(`${ip.slice(0, lastColon)}:${highHex}:${lowHex}`);
113
+ }
114
+ const doubleColonParts = ip.split("::");
115
+ if (doubleColonParts.length > 2) return null;
116
+ const head = doubleColonParts[0] ? doubleColonParts[0].split(":") : [];
117
+ const tail = doubleColonParts.length === 2 && doubleColonParts[1] ? doubleColonParts[1].split(":") : [];
118
+ if (doubleColonParts.length === 1 && head.length !== 8) return null;
119
+ if (doubleColonParts.length === 2 && head.length + tail.length > 7) return null;
120
+ const missing = doubleColonParts.length === 2 ? 8 - (head.length + tail.length) : 0;
121
+ const groups = [
122
+ ...head,
123
+ ...Array(missing).fill("0"),
124
+ ...tail
125
+ ];
126
+ if (groups.length !== 8) return null;
127
+ let value = 0n;
128
+ for (const group of groups) {
129
+ if (!/^[0-9a-f]{1,4}$/i.test(group)) return null;
130
+ value = value << 16n | BigInt(Number.parseInt(group, 16));
131
+ }
132
+ return value;
133
+ };
134
+ const normalizeIpAddress = (raw) => {
135
+ if (!raw) return "";
136
+ const trimmed = raw.trim().replace(/^\[|\]$/g, "");
137
+ if (/^::ffff:\d{1,3}(?:\.\d{1,3}){3}$/i.test(trimmed)) return trimmed.slice(7);
138
+ return trimmed;
139
+ };
140
+ const isIpInCidr = (rawIp, rawRule) => {
141
+ const rule = rawRule.trim();
142
+ if (!rule) return false;
143
+ if (rule === "*") return true;
144
+ const ip = normalizeIpAddress(rawIp);
145
+ if (!ip) return false;
146
+ const [rawNet, rawPrefix] = rule.split("/");
147
+ const net = normalizeIpAddress(rawNet);
148
+ const ipV4 = parseIpv4ToUint32(ip);
149
+ const netV4 = parseIpv4ToUint32(net);
150
+ if (ipV4 !== null && netV4 !== null) {
151
+ const prefix = rawPrefix !== void 0 ? Number(rawPrefix) : 32;
152
+ if (!Number.isInteger(prefix) || prefix < 0 || prefix > 32) return false;
153
+ const mask = prefix === 0 ? 0 : 4294967295 << 32 - prefix >>> 0;
154
+ return (ipV4 & mask) >>> 0 === (netV4 & mask) >>> 0;
155
+ }
156
+ const ipV6 = parseIpv6ToBigInt(ip);
157
+ const netV6 = parseIpv6ToBigInt(net);
158
+ if (ipV6 !== null && netV6 !== null) {
159
+ const prefix = rawPrefix !== void 0 ? Number(rawPrefix) : 128;
160
+ if (!Number.isInteger(prefix) || prefix < 0 || prefix > 128) return false;
161
+ if (prefix === 0) return true;
162
+ const shift = BigInt(128 - prefix);
163
+ return ipV6 >> shift === netV6 >> shift;
164
+ }
165
+ return false;
166
+ };
167
+ const isTrustedProxySocket = (remoteAddress, trustedProxies) => {
168
+ if (!remoteAddress) return false;
169
+ return trustedProxies.some((rule) => isIpInCidr(remoteAddress, rule));
170
+ };
171
+ const resolveClientIpFromHeaders = (headers, trustProxyHops, trustedIpHeader) => {
172
+ if (trustedIpHeader) {
173
+ const rawCustom = headers[trustedIpHeader.toLowerCase()];
174
+ const customIp = normalizeIpAddress(Array.isArray(rawCustom) ? rawCustom[0] : rawCustom);
175
+ if (customIp) return customIp;
176
+ }
86
177
  const rawXff = headers["x-forwarded-for"];
87
178
  const xffStr = Array.isArray(rawXff) ? rawXff.join(",") : rawXff;
88
179
  if (typeof xffStr === "string" && xffStr.trim()) {
89
- const hops = xffStr.split(",").map((part) => part.trim()).filter(Boolean);
180
+ const hops = xffStr.split(",").map((part) => normalizeIpAddress(part)).filter(Boolean);
90
181
  if (hops.length > 0) return hops[Math.max(0, hops.length - Math.max(1, trustProxyHops))];
91
182
  }
183
+ if (trustProxyHops <= 1) {
184
+ const rawCfIp = headers["cf-connecting-ip"];
185
+ const cfIp = normalizeIpAddress(Array.isArray(rawCfIp) ? rawCfIp[0] : rawCfIp);
186
+ if (cfIp) return cfIp;
187
+ const rawRealIp = headers["x-real-ip"];
188
+ const realIp = normalizeIpAddress(Array.isArray(rawRealIp) ? rawRealIp[0] : rawRealIp);
189
+ if (realIp) return realIp;
190
+ }
92
191
  };
93
192
  /**
94
193
  * Create a websocket server
@@ -116,8 +215,11 @@ var WsServer = class extends EventEmitter {
116
215
  this.maxTopicsPerSocket = opts.maxTopicsPerSocket ?? MAX_TOPICS_PER_SOCKET;
117
216
  this.maxConnections = opts.maxConnections ?? parseEnvNonNegativeInt(process.env.WS_MAX_CONNECTIONS, MAX_CONNECTIONS);
118
217
  this.maxConnectionsPerIp = opts.maxConnectionsPerIp ?? parseEnvNonNegativeInt(process.env.WS_MAX_CONNECTIONS_PER_IP, MAX_CONNECTIONS_PER_IP);
119
- this.trustProxy = typeof opts.trustProxy === "number" ? opts.trustProxy > 0 : opts.trustProxy ?? parseEnvBoolean(process.env.WS_TRUST_PROXY) ?? parseEnvBoolean(process.env.TRUST_PROXY) ?? Boolean(process.env.BLOCKLET_PORT);
218
+ this.trustProxy = typeof opts.trustProxy === "number" ? opts.trustProxy > 0 : opts.trustProxy ?? parseEnvBoolean(process.env.WS_TRUST_PROXY) ?? parseEnvBoolean(process.env.TRUST_PROXY) ?? false;
120
219
  this.trustProxyHops = opts.trustProxyHops ?? (typeof opts.trustProxy === "number" && opts.trustProxy > 0 ? Math.floor(opts.trustProxy) : parseEnvPositiveInt(process.env.WS_TRUST_PROXY_HOPS, 1));
220
+ const envTrustedProxies = process.env.WS_TRUSTED_PROXIES?.split(",").map((s) => s.trim()).filter(Boolean);
221
+ this.trustedProxies = opts.trustedProxies ?? (envTrustedProxies && envTrustedProxies.length > 0 ? envTrustedProxies : DEFAULT_TRUSTED_PROXIES);
222
+ this.trustedIpHeader = opts.trustedIpHeader ?? (process.env.WS_TRUSTED_IP_HEADER?.trim() || void 0);
121
223
  this.sanitizeErrors = opts.sanitizeErrors ?? false;
122
224
  this.wss = new WebSocketServer({
123
225
  noServer: true,
@@ -160,7 +262,8 @@ var WsServer = class extends EventEmitter {
160
262
  socket.destroy();
161
263
  return;
162
264
  }
163
- const clientIp = (this.trustProxy ? resolveClientIpFromHeaders(request.headers, this.trustProxyHops) : void 0) || request.socket?.remoteAddress || "unknown";
265
+ const socketIp = normalizeIpAddress(request.socket?.remoteAddress) || "unknown";
266
+ const clientIp = (this.trustProxy && isTrustedProxySocket(socketIp, this.trustedProxies) ? resolveClientIpFromHeaders(request.headers, this.trustProxyHops, this.trustedIpHeader) : void 0) || socketIp;
164
267
  if (this.maxConnections > 0 && this.connections.size + this.pendingConnections >= this.maxConnections) {
165
268
  this.logger.warn?.("max connections reached", { maxConnections: this.maxConnections });
166
269
  socket.write("HTTP/1.1 503 Service Unavailable\r\n\r\n");
@@ -84,16 +84,115 @@ const parseEnvPositiveInt = (raw, fallback) => {
84
84
  const parsed = Number(raw);
85
85
  return Number.isInteger(parsed) && parsed >= 1 ? parsed : fallback;
86
86
  };
87
- const resolveClientIpFromHeaders = (headers, trustProxyHops) => {
88
- const rawRealIp = headers["x-real-ip"];
89
- const realIp = (Array.isArray(rawRealIp) ? rawRealIp[0] : rawRealIp)?.trim();
90
- if (realIp) return realIp;
87
+ const DEFAULT_TRUSTED_PROXIES = [
88
+ "127.0.0.0/8",
89
+ "::1/128",
90
+ "10.0.0.0/8",
91
+ "172.16.0.0/12",
92
+ "192.168.0.0/16",
93
+ "fc00::/7",
94
+ "fe80::/10"
95
+ ];
96
+ const parseIpv4ToUint32 = (ip) => {
97
+ const parts = ip.split(".");
98
+ if (parts.length !== 4) return null;
99
+ let result = 0;
100
+ for (const part of parts) {
101
+ if (!/^\d{1,3}$/.test(part)) return null;
102
+ const n = Number(part);
103
+ if (n < 0 || n > 255) return null;
104
+ result = (result << 8 | n) >>> 0;
105
+ }
106
+ return result;
107
+ };
108
+ const parseIpv6ToBigInt = (raw) => {
109
+ const ip = raw.toLowerCase();
110
+ if (ip.includes(".")) {
111
+ const lastColon = ip.lastIndexOf(":");
112
+ if (lastColon === -1) return null;
113
+ const v4 = parseIpv4ToUint32(ip.slice(lastColon + 1));
114
+ if (v4 === null) return null;
115
+ const highHex = (v4 >>> 16 & 65535).toString(16);
116
+ const lowHex = (v4 & 65535).toString(16);
117
+ return parseIpv6ToBigInt(`${ip.slice(0, lastColon)}:${highHex}:${lowHex}`);
118
+ }
119
+ const doubleColonParts = ip.split("::");
120
+ if (doubleColonParts.length > 2) return null;
121
+ const head = doubleColonParts[0] ? doubleColonParts[0].split(":") : [];
122
+ const tail = doubleColonParts.length === 2 && doubleColonParts[1] ? doubleColonParts[1].split(":") : [];
123
+ if (doubleColonParts.length === 1 && head.length !== 8) return null;
124
+ if (doubleColonParts.length === 2 && head.length + tail.length > 7) return null;
125
+ const missing = doubleColonParts.length === 2 ? 8 - (head.length + tail.length) : 0;
126
+ const groups = [
127
+ ...head,
128
+ ...Array(missing).fill("0"),
129
+ ...tail
130
+ ];
131
+ if (groups.length !== 8) return null;
132
+ let value = 0n;
133
+ for (const group of groups) {
134
+ if (!/^[0-9a-f]{1,4}$/i.test(group)) return null;
135
+ value = value << 16n | BigInt(Number.parseInt(group, 16));
136
+ }
137
+ return value;
138
+ };
139
+ const normalizeIpAddress = (raw) => {
140
+ if (!raw) return "";
141
+ const trimmed = raw.trim().replace(/^\[|\]$/g, "");
142
+ if (/^::ffff:\d{1,3}(?:\.\d{1,3}){3}$/i.test(trimmed)) return trimmed.slice(7);
143
+ return trimmed;
144
+ };
145
+ const isIpInCidr = (rawIp, rawRule) => {
146
+ const rule = rawRule.trim();
147
+ if (!rule) return false;
148
+ if (rule === "*") return true;
149
+ const ip = normalizeIpAddress(rawIp);
150
+ if (!ip) return false;
151
+ const [rawNet, rawPrefix] = rule.split("/");
152
+ const net = normalizeIpAddress(rawNet);
153
+ const ipV4 = parseIpv4ToUint32(ip);
154
+ const netV4 = parseIpv4ToUint32(net);
155
+ if (ipV4 !== null && netV4 !== null) {
156
+ const prefix = rawPrefix !== void 0 ? Number(rawPrefix) : 32;
157
+ if (!Number.isInteger(prefix) || prefix < 0 || prefix > 32) return false;
158
+ const mask = prefix === 0 ? 0 : 4294967295 << 32 - prefix >>> 0;
159
+ return (ipV4 & mask) >>> 0 === (netV4 & mask) >>> 0;
160
+ }
161
+ const ipV6 = parseIpv6ToBigInt(ip);
162
+ const netV6 = parseIpv6ToBigInt(net);
163
+ if (ipV6 !== null && netV6 !== null) {
164
+ const prefix = rawPrefix !== void 0 ? Number(rawPrefix) : 128;
165
+ if (!Number.isInteger(prefix) || prefix < 0 || prefix > 128) return false;
166
+ if (prefix === 0) return true;
167
+ const shift = BigInt(128 - prefix);
168
+ return ipV6 >> shift === netV6 >> shift;
169
+ }
170
+ return false;
171
+ };
172
+ const isTrustedProxySocket = (remoteAddress, trustedProxies) => {
173
+ if (!remoteAddress) return false;
174
+ return trustedProxies.some((rule) => isIpInCidr(remoteAddress, rule));
175
+ };
176
+ const resolveClientIpFromHeaders = (headers, trustProxyHops, trustedIpHeader) => {
177
+ if (trustedIpHeader) {
178
+ const rawCustom = headers[trustedIpHeader.toLowerCase()];
179
+ const customIp = normalizeIpAddress(Array.isArray(rawCustom) ? rawCustom[0] : rawCustom);
180
+ if (customIp) return customIp;
181
+ }
91
182
  const rawXff = headers["x-forwarded-for"];
92
183
  const xffStr = Array.isArray(rawXff) ? rawXff.join(",") : rawXff;
93
184
  if (typeof xffStr === "string" && xffStr.trim()) {
94
- const hops = xffStr.split(",").map((part) => part.trim()).filter(Boolean);
185
+ const hops = xffStr.split(",").map((part) => normalizeIpAddress(part)).filter(Boolean);
95
186
  if (hops.length > 0) return hops[Math.max(0, hops.length - Math.max(1, trustProxyHops))];
96
187
  }
188
+ if (trustProxyHops <= 1) {
189
+ const rawCfIp = headers["cf-connecting-ip"];
190
+ const cfIp = normalizeIpAddress(Array.isArray(rawCfIp) ? rawCfIp[0] : rawCfIp);
191
+ if (cfIp) return cfIp;
192
+ const rawRealIp = headers["x-real-ip"];
193
+ const realIp = normalizeIpAddress(Array.isArray(rawRealIp) ? rawRealIp[0] : rawRealIp);
194
+ if (realIp) return realIp;
195
+ }
97
196
  };
98
197
  /**
99
198
  * Create a websocket server
@@ -121,8 +220,11 @@ var WsServer = class extends node_events.default {
121
220
  this.maxTopicsPerSocket = opts.maxTopicsPerSocket ?? MAX_TOPICS_PER_SOCKET;
122
221
  this.maxConnections = opts.maxConnections ?? parseEnvNonNegativeInt(process.env.WS_MAX_CONNECTIONS, MAX_CONNECTIONS);
123
222
  this.maxConnectionsPerIp = opts.maxConnectionsPerIp ?? parseEnvNonNegativeInt(process.env.WS_MAX_CONNECTIONS_PER_IP, MAX_CONNECTIONS_PER_IP);
124
- this.trustProxy = typeof opts.trustProxy === "number" ? opts.trustProxy > 0 : opts.trustProxy ?? parseEnvBoolean(process.env.WS_TRUST_PROXY) ?? parseEnvBoolean(process.env.TRUST_PROXY) ?? Boolean(process.env.BLOCKLET_PORT);
223
+ this.trustProxy = typeof opts.trustProxy === "number" ? opts.trustProxy > 0 : opts.trustProxy ?? parseEnvBoolean(process.env.WS_TRUST_PROXY) ?? parseEnvBoolean(process.env.TRUST_PROXY) ?? false;
125
224
  this.trustProxyHops = opts.trustProxyHops ?? (typeof opts.trustProxy === "number" && opts.trustProxy > 0 ? Math.floor(opts.trustProxy) : parseEnvPositiveInt(process.env.WS_TRUST_PROXY_HOPS, 1));
225
+ const envTrustedProxies = process.env.WS_TRUSTED_PROXIES?.split(",").map((s) => s.trim()).filter(Boolean);
226
+ this.trustedProxies = opts.trustedProxies ?? (envTrustedProxies && envTrustedProxies.length > 0 ? envTrustedProxies : DEFAULT_TRUSTED_PROXIES);
227
+ this.trustedIpHeader = opts.trustedIpHeader ?? (process.env.WS_TRUSTED_IP_HEADER?.trim() || void 0);
126
228
  this.sanitizeErrors = opts.sanitizeErrors ?? false;
127
229
  this.wss = new ws.WebSocketServer({
128
230
  noServer: true,
@@ -165,7 +267,8 @@ var WsServer = class extends node_events.default {
165
267
  socket.destroy();
166
268
  return;
167
269
  }
168
- const clientIp = (this.trustProxy ? resolveClientIpFromHeaders(request.headers, this.trustProxyHops) : void 0) || request.socket?.remoteAddress || "unknown";
270
+ const socketIp = normalizeIpAddress(request.socket?.remoteAddress) || "unknown";
271
+ const clientIp = (this.trustProxy && isTrustedProxySocket(socketIp, this.trustedProxies) ? resolveClientIpFromHeaders(request.headers, this.trustProxyHops, this.trustedIpHeader) : void 0) || socketIp;
169
272
  if (this.maxConnections > 0 && this.connections.size + this.pendingConnections >= this.maxConnections) {
170
273
  this.logger.warn?.("max connections reached", { maxConnections: this.maxConnections });
171
274
  socket.write("HTTP/1.1 503 Service Unavailable\r\n\r\n");
@@ -49,6 +49,8 @@ interface WsServerOptions {
49
49
  maxConnectionsPerIp?: number;
50
50
  trustProxy?: boolean | number;
51
51
  trustProxyHops?: number;
52
+ trustedProxies?: string[];
53
+ trustedIpHeader?: string;
52
54
  sanitizeErrors?: boolean;
53
55
  }
54
56
  interface BroadcastOptions {
@@ -98,6 +100,8 @@ declare class WsServer extends EventEmitter {
98
100
  maxConnectionsPerIp: number;
99
101
  trustProxy: boolean;
100
102
  trustProxyHops: number;
103
+ trustedProxies: string[];
104
+ trustedIpHeader?: string;
101
105
  sanitizeErrors: boolean;
102
106
  wss: WebSocketServer;
103
107
  topics: Record<string, Set<WsSocket>>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@arcblock/ws",
3
- "version": "1.30.25",
3
+ "version": "1.30.26",
4
4
  "description": "OCAP Chain websocket server and client",
5
5
  "keywords": [
6
6
  "websocket"
@@ -75,7 +75,7 @@
75
75
  "url": "https://github.com/ArcBlock/blockchain/issues"
76
76
  },
77
77
  "dependencies": {
78
- "@arcblock/event-hub": "1.30.25",
78
+ "@arcblock/event-hub": "1.30.26",
79
79
  "debug": "^4.4.3",
80
80
  "eventemitter3": "^4.0.7",
81
81
  "lodash": "^4.17.23",