@arcblock/ws 1.30.24 → 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.
- package/esm/server/index.d.mts +26 -12
- package/esm/server/index.mjs +281 -16
- package/lib/server/index.cjs +281 -16
- package/lib/server/index.d.cts +26 -12
- package/package.json +3 -3
package/esm/server/index.d.mts
CHANGED
|
@@ -11,6 +11,8 @@ interface WsSocket extends WebSocket {
|
|
|
11
11
|
authInfo?: unknown;
|
|
12
12
|
}>;
|
|
13
13
|
heartbeatAt: number;
|
|
14
|
+
isAlive?: boolean;
|
|
15
|
+
clientIp?: string;
|
|
14
16
|
authInfo?: unknown;
|
|
15
17
|
}
|
|
16
18
|
interface HookParams {
|
|
@@ -40,19 +42,16 @@ interface WsServerOptions {
|
|
|
40
42
|
skipLogOnHookError?: boolean;
|
|
41
43
|
broadcastEventName?: string;
|
|
42
44
|
heartbeatTimeout?: number;
|
|
43
|
-
|
|
44
|
-
* Maximum size of a single inbound WebSocket frame in bytes. The `ws`
|
|
45
|
-
* library rejects oversized frames with close code 1009. Defaults to 64 KiB
|
|
46
|
-
* which is far above any legitimate Phoenix-protocol client message.
|
|
47
|
-
*/
|
|
45
|
+
heartbeatInterval?: number;
|
|
48
46
|
maxPayload?: number;
|
|
49
|
-
/**
|
|
50
|
-
* Maximum distinct `phx_join` topics a single socket can hold. Each join
|
|
51
|
-
* inserts a Set into `this.topics`, so an unbounded value lets a hostile
|
|
52
|
-
* client force unbounded server-side memory growth via random topic strings.
|
|
53
|
-
* Defaults to 64. Set to 0 to disable the cap.
|
|
54
|
-
*/
|
|
55
47
|
maxTopicsPerSocket?: number;
|
|
48
|
+
maxConnections?: number;
|
|
49
|
+
maxConnectionsPerIp?: number;
|
|
50
|
+
trustProxy?: boolean | number;
|
|
51
|
+
trustProxyHops?: number;
|
|
52
|
+
trustedProxies?: string[];
|
|
53
|
+
trustedIpHeader?: string;
|
|
54
|
+
sanitizeErrors?: boolean;
|
|
56
55
|
}
|
|
57
56
|
interface BroadcastOptions {
|
|
58
57
|
enableLog?: boolean;
|
|
@@ -94,9 +93,22 @@ declare class WsServer extends EventEmitter {
|
|
|
94
93
|
logger: Logger;
|
|
95
94
|
skipLogOnHookError: boolean;
|
|
96
95
|
heartbeatTimeout: number;
|
|
96
|
+
heartbeatInterval: number;
|
|
97
|
+
heartbeatTimer?: ReturnType<typeof setInterval>;
|
|
97
98
|
maxTopicsPerSocket: number;
|
|
99
|
+
maxConnections: number;
|
|
100
|
+
maxConnectionsPerIp: number;
|
|
101
|
+
trustProxy: boolean;
|
|
102
|
+
trustProxyHops: number;
|
|
103
|
+
trustedProxies: string[];
|
|
104
|
+
trustedIpHeader?: string;
|
|
105
|
+
sanitizeErrors: boolean;
|
|
98
106
|
wss: WebSocketServer;
|
|
99
107
|
topics: Record<string, Set<WsSocket>>;
|
|
108
|
+
connections: Set<WsSocket>;
|
|
109
|
+
ipConnectionCounts: Map<string, number>;
|
|
110
|
+
pendingConnections: number;
|
|
111
|
+
pendingIpConnections: Map<string, number>;
|
|
100
112
|
broadcastEventName: string;
|
|
101
113
|
constructor(opts?: WsServerOptions);
|
|
102
114
|
attach(server: http.Server): this;
|
|
@@ -129,7 +141,9 @@ declare class WsServer extends EventEmitter {
|
|
|
129
141
|
/**
|
|
130
142
|
* private
|
|
131
143
|
*/
|
|
132
|
-
onWssConnection(socket: WebSocket): Promise<void>;
|
|
144
|
+
onWssConnection(socket: WebSocket, request?: http.IncomingMessage): Promise<void>;
|
|
145
|
+
_cleanupSocket(wsSocket: WsSocket): void;
|
|
146
|
+
_sweepConnections(): void;
|
|
133
147
|
/**
|
|
134
148
|
* private
|
|
135
149
|
*/
|
package/esm/server/index.mjs
CHANGED
|
@@ -7,7 +7,17 @@ import get from "lodash/get.js";
|
|
|
7
7
|
|
|
8
8
|
//#region src/server/index.ts
|
|
9
9
|
const eventHub = cluster.isMaster ? __require("@arcblock/event-hub/single").default : __require("@arcblock/event-hub").default;
|
|
10
|
-
const nanoid = (
|
|
10
|
+
const nanoid = () => globalThis.crypto.randomUUID();
|
|
11
|
+
const INTERNAL_ERROR_RE = /\b(?:EACCES|EADDRINUSE|ECONNREFUSED|ENOENT|EPERM|ETIMEDOUT|SQLITE_\w+|ER_[A-Z_]+|TypeError|ReferenceError|SyntaxError|RangeError)\b/;
|
|
12
|
+
const FILE_PATH_RE = /(?:\/[\w.-]+){2,}|[A-Za-z]:\\[\w.\\-]+/;
|
|
13
|
+
const sanitizeErrorMessage = (err, fallback = "Internal server error", sanitizeAll = false) => {
|
|
14
|
+
if (sanitizeAll) return fallback;
|
|
15
|
+
if (err instanceof TypeError || err instanceof ReferenceError || err instanceof SyntaxError || err instanceof RangeError) return fallback;
|
|
16
|
+
if (err && typeof err === "object" && ("syscall" in err || "path" in err || "sql" in err)) return fallback;
|
|
17
|
+
const msg = err?.message || String(err ?? "");
|
|
18
|
+
if (!msg || msg.includes("\n") || INTERNAL_ERROR_RE.test(msg) || FILE_PATH_RE.test(msg)) return fallback;
|
|
19
|
+
return msg;
|
|
20
|
+
};
|
|
11
21
|
const sleep = (timeout) => new Promise((resolve) => {
|
|
12
22
|
setTimeout(resolve, timeout);
|
|
13
23
|
});
|
|
@@ -41,8 +51,144 @@ const refreshHeartbeat = (socket) => {
|
|
|
41
51
|
socket.heartbeatAt = Date.now();
|
|
42
52
|
};
|
|
43
53
|
const HEARTBEAT_TIMEOUT = 300 * 1e3;
|
|
54
|
+
const DEFAULT_HEARTBEAT_INTERVAL = 30 * 1e3;
|
|
44
55
|
const MAX_PAYLOAD = 64 * 1024;
|
|
45
56
|
const MAX_TOPICS_PER_SOCKET = 64;
|
|
57
|
+
const FORBIDDEN_TOPICS = new Set([
|
|
58
|
+
"__proto__",
|
|
59
|
+
"constructor",
|
|
60
|
+
"prototype"
|
|
61
|
+
]);
|
|
62
|
+
const MAX_CONNECTIONS = 1024;
|
|
63
|
+
const MAX_CONNECTIONS_PER_IP = 64;
|
|
64
|
+
const parseEnvNonNegativeInt = (raw, fallback) => {
|
|
65
|
+
if (raw === void 0 || raw.trim() === "") return fallback;
|
|
66
|
+
const parsed = Number(raw);
|
|
67
|
+
return Number.isInteger(parsed) && parsed >= 0 ? parsed : fallback;
|
|
68
|
+
};
|
|
69
|
+
const parseEnvBoolean = (raw) => {
|
|
70
|
+
if (raw === void 0 || raw.trim() === "") return void 0;
|
|
71
|
+
const normalized = raw.trim().toLowerCase();
|
|
72
|
+
if (normalized === "1" || normalized === "true") return true;
|
|
73
|
+
if (normalized === "0" || normalized === "false") return false;
|
|
74
|
+
const numeric = Number(normalized);
|
|
75
|
+
if (Number.isInteger(numeric) && numeric > 0) return true;
|
|
76
|
+
};
|
|
77
|
+
const parseEnvPositiveInt = (raw, fallback) => {
|
|
78
|
+
if (raw === void 0 || raw.trim() === "") return fallback;
|
|
79
|
+
const parsed = Number(raw);
|
|
80
|
+
return Number.isInteger(parsed) && parsed >= 1 ? parsed : fallback;
|
|
81
|
+
};
|
|
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
|
+
}
|
|
177
|
+
const rawXff = headers["x-forwarded-for"];
|
|
178
|
+
const xffStr = Array.isArray(rawXff) ? rawXff.join(",") : rawXff;
|
|
179
|
+
if (typeof xffStr === "string" && xffStr.trim()) {
|
|
180
|
+
const hops = xffStr.split(",").map((part) => normalizeIpAddress(part)).filter(Boolean);
|
|
181
|
+
if (hops.length > 0) return hops[Math.max(0, hops.length - Math.max(1, trustProxyHops))];
|
|
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
|
+
}
|
|
191
|
+
};
|
|
46
192
|
/**
|
|
47
193
|
* Create a websocket server
|
|
48
194
|
*
|
|
@@ -65,7 +211,16 @@ var WsServer = class extends EventEmitter {
|
|
|
65
211
|
this.logger = opts.logger || logger_default("server", opts.silent);
|
|
66
212
|
this.skipLogOnHookError = opts.skipLogOnHookError || false;
|
|
67
213
|
this.heartbeatTimeout = opts.heartbeatTimeout || HEARTBEAT_TIMEOUT;
|
|
214
|
+
this.heartbeatInterval = opts.heartbeatInterval ?? DEFAULT_HEARTBEAT_INTERVAL;
|
|
68
215
|
this.maxTopicsPerSocket = opts.maxTopicsPerSocket ?? MAX_TOPICS_PER_SOCKET;
|
|
216
|
+
this.maxConnections = opts.maxConnections ?? parseEnvNonNegativeInt(process.env.WS_MAX_CONNECTIONS, MAX_CONNECTIONS);
|
|
217
|
+
this.maxConnectionsPerIp = opts.maxConnectionsPerIp ?? parseEnvNonNegativeInt(process.env.WS_MAX_CONNECTIONS_PER_IP, MAX_CONNECTIONS_PER_IP);
|
|
218
|
+
this.trustProxy = typeof opts.trustProxy === "number" ? opts.trustProxy > 0 : opts.trustProxy ?? parseEnvBoolean(process.env.WS_TRUST_PROXY) ?? parseEnvBoolean(process.env.TRUST_PROXY) ?? false;
|
|
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);
|
|
223
|
+
this.sanitizeErrors = opts.sanitizeErrors ?? false;
|
|
69
224
|
this.wss = new WebSocketServer({
|
|
70
225
|
noServer: true,
|
|
71
226
|
clientTracking: false,
|
|
@@ -74,12 +229,29 @@ var WsServer = class extends EventEmitter {
|
|
|
74
229
|
this.wss.on("connection", this.onWssConnection.bind(this));
|
|
75
230
|
this.wss.on("close", this.onWssClose.bind(this));
|
|
76
231
|
this.wss.on("error", this.onWssError.bind(this));
|
|
77
|
-
this.topics =
|
|
232
|
+
this.topics = Object.create(null);
|
|
233
|
+
this.connections = /* @__PURE__ */ new Set();
|
|
234
|
+
this.ipConnectionCounts = /* @__PURE__ */ new Map();
|
|
235
|
+
this.pendingConnections = 0;
|
|
236
|
+
this.pendingIpConnections = /* @__PURE__ */ new Map();
|
|
237
|
+
if (this.heartbeatInterval > 0) {
|
|
238
|
+
this.heartbeatTimer = setInterval(() => this._sweepConnections(), this.heartbeatInterval);
|
|
239
|
+
this.heartbeatTimer.unref?.();
|
|
240
|
+
}
|
|
78
241
|
this.broadcastEventName = opts.broadcastEventName || "@arcblock/ws:broadcast";
|
|
79
242
|
eventHub.on(this.broadcastEventName, (data) => this._doBroadCast(data));
|
|
80
243
|
}
|
|
81
244
|
attach(server) {
|
|
82
245
|
server.on("upgrade", this.onConnect.bind(this));
|
|
246
|
+
const origClose = server.close.bind(server);
|
|
247
|
+
server.close = ((cb) => {
|
|
248
|
+
if (this.heartbeatTimer) {
|
|
249
|
+
clearInterval(this.heartbeatTimer);
|
|
250
|
+
this.heartbeatTimer = void 0;
|
|
251
|
+
}
|
|
252
|
+
server.closeAllConnections?.();
|
|
253
|
+
return origClose(cb);
|
|
254
|
+
});
|
|
83
255
|
return this;
|
|
84
256
|
}
|
|
85
257
|
onConnect(request, socket, head) {
|
|
@@ -90,20 +262,56 @@ var WsServer = class extends EventEmitter {
|
|
|
90
262
|
socket.destroy();
|
|
91
263
|
return;
|
|
92
264
|
}
|
|
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;
|
|
267
|
+
if (this.maxConnections > 0 && this.connections.size + this.pendingConnections >= this.maxConnections) {
|
|
268
|
+
this.logger.warn?.("max connections reached", { maxConnections: this.maxConnections });
|
|
269
|
+
socket.write("HTTP/1.1 503 Service Unavailable\r\n\r\n");
|
|
270
|
+
socket.destroy();
|
|
271
|
+
return;
|
|
272
|
+
}
|
|
273
|
+
const currentIpCount = (this.ipConnectionCounts.get(clientIp) || 0) + (this.pendingIpConnections.get(clientIp) || 0);
|
|
274
|
+
if (this.maxConnectionsPerIp > 0 && currentIpCount >= this.maxConnectionsPerIp) {
|
|
275
|
+
this.logger.warn?.("per-IP connection limit reached", {
|
|
276
|
+
clientIp,
|
|
277
|
+
maxConnectionsPerIp: this.maxConnectionsPerIp
|
|
278
|
+
});
|
|
279
|
+
socket.write("HTTP/1.1 429 Too Many Requests\r\n\r\n");
|
|
280
|
+
socket.destroy();
|
|
281
|
+
return;
|
|
282
|
+
}
|
|
283
|
+
this.pendingConnections += 1;
|
|
284
|
+
this.pendingIpConnections.set(clientIp, (this.pendingIpConnections.get(clientIp) || 0) + 1);
|
|
285
|
+
let pendingReleased = false;
|
|
286
|
+
const releasePending = () => {
|
|
287
|
+
if (pendingReleased) return;
|
|
288
|
+
pendingReleased = true;
|
|
289
|
+
this.pendingConnections = Math.max(0, this.pendingConnections - 1);
|
|
290
|
+
const nextPending = (this.pendingIpConnections.get(clientIp) || 1) - 1;
|
|
291
|
+
if (nextPending <= 0) this.pendingIpConnections.delete(clientIp);
|
|
292
|
+
else this.pendingIpConnections.set(clientIp, nextPending);
|
|
293
|
+
};
|
|
294
|
+
socket.once("close", releasePending);
|
|
295
|
+
socket.once("error", releasePending);
|
|
93
296
|
if (!this.authenticate) {
|
|
94
297
|
this.wss.handleUpgrade(request, socket, head, (ws) => {
|
|
298
|
+
ws.clientIp = clientIp;
|
|
299
|
+
releasePending();
|
|
95
300
|
this.wss.emit("connection", ws, request);
|
|
96
301
|
});
|
|
97
302
|
return;
|
|
98
303
|
}
|
|
99
304
|
this.authenticate(request, (err, authInfo) => {
|
|
100
305
|
if (err) {
|
|
306
|
+
releasePending();
|
|
101
307
|
socket.write("HTTP/1.1 401 Unauthorized\r\n\r\n");
|
|
102
308
|
socket.destroy();
|
|
103
309
|
return;
|
|
104
310
|
}
|
|
105
311
|
this.wss.handleUpgrade(request, socket, head, (ws) => {
|
|
106
312
|
ws.authInfo = authInfo;
|
|
313
|
+
ws.clientIp = clientIp;
|
|
314
|
+
releasePending();
|
|
107
315
|
this.wss.emit("connection", ws, request);
|
|
108
316
|
});
|
|
109
317
|
});
|
|
@@ -262,12 +470,19 @@ var WsServer = class extends EventEmitter {
|
|
|
262
470
|
/**
|
|
263
471
|
* private
|
|
264
472
|
*/
|
|
265
|
-
async onWssConnection(socket) {
|
|
473
|
+
async onWssConnection(socket, request) {
|
|
266
474
|
const wsSocket = socket;
|
|
267
475
|
wsSocket.id = nanoid();
|
|
268
|
-
wsSocket.channel =
|
|
476
|
+
wsSocket.channel = Object.create(null);
|
|
477
|
+
wsSocket.isAlive = true;
|
|
478
|
+
wsSocket.clientIp = wsSocket.clientIp || request?.socket?.remoteAddress || "unknown";
|
|
479
|
+
this.connections.add(wsSocket);
|
|
480
|
+
this.ipConnectionCounts.set(wsSocket.clientIp, (this.ipConnectionCounts.get(wsSocket.clientIp) || 0) + 1);
|
|
269
481
|
refreshHeartbeat(wsSocket);
|
|
270
482
|
this.logger.debug("socket connected", { id: wsSocket.id });
|
|
483
|
+
wsSocket.on("pong", () => {
|
|
484
|
+
wsSocket.isAlive = true;
|
|
485
|
+
});
|
|
271
486
|
wsSocket.on("message", async (msg) => {
|
|
272
487
|
this.logger.debug("socket onmessage", msg.toString());
|
|
273
488
|
let joinRef;
|
|
@@ -276,7 +491,12 @@ var WsServer = class extends EventEmitter {
|
|
|
276
491
|
let event;
|
|
277
492
|
let payload;
|
|
278
493
|
try {
|
|
279
|
-
|
|
494
|
+
const parsed = JSON.parse(msg.toString());
|
|
495
|
+
if (!Array.isArray(parsed)) {
|
|
496
|
+
this.logger.warn?.("Invalid message format, expected array");
|
|
497
|
+
return;
|
|
498
|
+
}
|
|
499
|
+
[joinRef, ref, topic, event, payload] = parsed;
|
|
280
500
|
} catch (err) {
|
|
281
501
|
this.logger.error("parse socket message error", {
|
|
282
502
|
id: wsSocket.id,
|
|
@@ -284,10 +504,26 @@ var WsServer = class extends EventEmitter {
|
|
|
284
504
|
});
|
|
285
505
|
return;
|
|
286
506
|
}
|
|
287
|
-
if (!topic || !event) {
|
|
507
|
+
if (typeof topic !== "string" || typeof event !== "string" || !topic || !event) {
|
|
288
508
|
this.logger.warn?.("Invalid message format, topic/event fields are required");
|
|
289
509
|
return;
|
|
290
510
|
}
|
|
511
|
+
if (FORBIDDEN_TOPICS.has(topic)) {
|
|
512
|
+
this.logger.warn?.("Invalid topic name", {
|
|
513
|
+
id: wsSocket.id,
|
|
514
|
+
topic
|
|
515
|
+
});
|
|
516
|
+
reply({
|
|
517
|
+
socket: wsSocket,
|
|
518
|
+
topic,
|
|
519
|
+
event: `chan_reply_${ref}`,
|
|
520
|
+
data: { message: "invalid topic" },
|
|
521
|
+
status: "error",
|
|
522
|
+
ref: typeof ref === "string" ? ref : "",
|
|
523
|
+
joinRef: typeof joinRef === "string" ? joinRef : ""
|
|
524
|
+
});
|
|
525
|
+
return;
|
|
526
|
+
}
|
|
291
527
|
if (topic === "phoenix" && event === "heartbeat") {
|
|
292
528
|
reply({
|
|
293
529
|
socket: wsSocket,
|
|
@@ -299,7 +535,7 @@ var WsServer = class extends EventEmitter {
|
|
|
299
535
|
return;
|
|
300
536
|
}
|
|
301
537
|
if (event === "phx_join") {
|
|
302
|
-
if (this.maxTopicsPerSocket > 0 && !(
|
|
538
|
+
if (this.maxTopicsPerSocket > 0 && !Object.hasOwn(wsSocket.channel, topic) && Object.keys(wsSocket.channel).length >= this.maxTopicsPerSocket) {
|
|
303
539
|
reply({
|
|
304
540
|
socket: wsSocket,
|
|
305
541
|
topic,
|
|
@@ -329,21 +565,21 @@ var WsServer = class extends EventEmitter {
|
|
|
329
565
|
payload
|
|
330
566
|
});
|
|
331
567
|
wsSocket.channel[topic] = { authInfo };
|
|
568
|
+
if (!(this.topics[topic] instanceof Set)) this.topics[topic] = /* @__PURE__ */ new Set();
|
|
569
|
+
this.topics[topic].add(wsSocket);
|
|
332
570
|
} catch (error) {
|
|
333
571
|
if (!this.skipLogOnHookError) this.logger.error("preJoinChannel error", { error });
|
|
334
572
|
reply({
|
|
335
573
|
socket: wsSocket,
|
|
336
574
|
topic,
|
|
337
575
|
event: `chan_reply_${ref}`,
|
|
338
|
-
data: { message: error.
|
|
576
|
+
data: { message: sanitizeErrorMessage(error, "Internal server error", this.sanitizeErrors) },
|
|
339
577
|
status: "error",
|
|
340
578
|
ref,
|
|
341
579
|
joinRef
|
|
342
580
|
});
|
|
343
581
|
return;
|
|
344
582
|
}
|
|
345
|
-
if (!this.topics[topic]) this.topics[topic] = /* @__PURE__ */ new Set();
|
|
346
|
-
this.topics[topic].add(wsSocket);
|
|
347
583
|
reply({
|
|
348
584
|
socket: wsSocket,
|
|
349
585
|
topic,
|
|
@@ -387,7 +623,7 @@ var WsServer = class extends EventEmitter {
|
|
|
387
623
|
socket: wsSocket,
|
|
388
624
|
topic,
|
|
389
625
|
event: `chan_reply_${ref}`,
|
|
390
|
-
data: { message: error.
|
|
626
|
+
data: { message: sanitizeErrorMessage(error, "Internal server error", this.sanitizeErrors) },
|
|
391
627
|
status: "error",
|
|
392
628
|
ref,
|
|
393
629
|
joinRef
|
|
@@ -431,7 +667,7 @@ var WsServer = class extends EventEmitter {
|
|
|
431
667
|
socket: wsSocket,
|
|
432
668
|
topic,
|
|
433
669
|
event: `chan_reply_${ref}`,
|
|
434
|
-
data: { message: error.
|
|
670
|
+
data: { message: sanitizeErrorMessage(error, "Internal server error", this.sanitizeErrors) },
|
|
435
671
|
status: "error",
|
|
436
672
|
ref,
|
|
437
673
|
joinRef
|
|
@@ -448,20 +684,48 @@ var WsServer = class extends EventEmitter {
|
|
|
448
684
|
});
|
|
449
685
|
wsSocket.on("close", () => {
|
|
450
686
|
this.logger.debug("socket onclose", { id: wsSocket.id });
|
|
451
|
-
|
|
687
|
+
this._cleanupSocket(wsSocket);
|
|
452
688
|
});
|
|
453
689
|
wsSocket.on("error", (err) => {
|
|
454
690
|
this.logger.error("socket onerror", {
|
|
455
691
|
id: wsSocket.id,
|
|
456
692
|
error: err
|
|
457
693
|
});
|
|
458
|
-
|
|
694
|
+
this._cleanupSocket(wsSocket);
|
|
459
695
|
});
|
|
460
696
|
}
|
|
697
|
+
_cleanupSocket(wsSocket) {
|
|
698
|
+
if (this.connections.delete(wsSocket) && wsSocket.clientIp) {
|
|
699
|
+
const nextCount = (this.ipConnectionCounts.get(wsSocket.clientIp) || 1) - 1;
|
|
700
|
+
if (nextCount <= 0) this.ipConnectionCounts.delete(wsSocket.clientIp);
|
|
701
|
+
else this.ipConnectionCounts.set(wsSocket.clientIp, nextCount);
|
|
702
|
+
}
|
|
703
|
+
Object.keys(this.topics).forEach((topic) => this._leaveChannel(wsSocket, topic));
|
|
704
|
+
}
|
|
705
|
+
_sweepConnections() {
|
|
706
|
+
const now = Date.now();
|
|
707
|
+
for (const socket of Array.from(this.connections)) {
|
|
708
|
+
const noHeartbeatTime = now - socket.heartbeatAt;
|
|
709
|
+
if (noHeartbeatTime > this.heartbeatTimeout || socket.isAlive === false) {
|
|
710
|
+
this.logger.error(`Socket has no heartbeat within ${Math.floor(noHeartbeatTime / 1e3)} seconds`, { id: socket.id });
|
|
711
|
+
this._cleanupSocket(socket);
|
|
712
|
+
socket.terminate?.();
|
|
713
|
+
continue;
|
|
714
|
+
}
|
|
715
|
+
if (socket.readyState === WebSocket.OPEN) {
|
|
716
|
+
socket.isAlive = false;
|
|
717
|
+
socket.ping?.();
|
|
718
|
+
}
|
|
719
|
+
}
|
|
720
|
+
}
|
|
461
721
|
/**
|
|
462
722
|
* private
|
|
463
723
|
*/
|
|
464
724
|
onWssClose() {
|
|
725
|
+
if (this.heartbeatTimer) {
|
|
726
|
+
clearInterval(this.heartbeatTimer);
|
|
727
|
+
this.heartbeatTimer = void 0;
|
|
728
|
+
}
|
|
465
729
|
this.logger.debug("ws server onclose");
|
|
466
730
|
this.emit("close");
|
|
467
731
|
}
|
|
@@ -473,12 +737,13 @@ var WsServer = class extends EventEmitter {
|
|
|
473
737
|
this.emit("error", error);
|
|
474
738
|
}
|
|
475
739
|
_leaveChannel(socket, topic) {
|
|
476
|
-
if (
|
|
740
|
+
if (socket?.channel && Object.hasOwn(socket.channel, topic)) delete socket.channel[topic];
|
|
741
|
+
if (this.topics[topic] instanceof Set) this.topics[topic].delete(socket);
|
|
477
742
|
this.emit("channel.leave", {
|
|
478
743
|
socket,
|
|
479
744
|
topic
|
|
480
745
|
});
|
|
481
|
-
if (!this.topics[topic] || !this.topics[topic].size) this.emit("channel.destroy", {
|
|
746
|
+
if (!(this.topics[topic] instanceof Set) || !this.topics[topic].size) this.emit("channel.destroy", {
|
|
482
747
|
socket,
|
|
483
748
|
topic
|
|
484
749
|
});
|
package/lib/server/index.cjs
CHANGED
|
@@ -12,7 +12,17 @@ lodash_get = require_rolldown_runtime.__toESM(lodash_get);
|
|
|
12
12
|
|
|
13
13
|
//#region src/server/index.ts
|
|
14
14
|
const eventHub = node_cluster.default.isMaster ? require("@arcblock/event-hub/single").default : require("@arcblock/event-hub").default;
|
|
15
|
-
const nanoid = (
|
|
15
|
+
const nanoid = () => globalThis.crypto.randomUUID();
|
|
16
|
+
const INTERNAL_ERROR_RE = /\b(?:EACCES|EADDRINUSE|ECONNREFUSED|ENOENT|EPERM|ETIMEDOUT|SQLITE_\w+|ER_[A-Z_]+|TypeError|ReferenceError|SyntaxError|RangeError)\b/;
|
|
17
|
+
const FILE_PATH_RE = /(?:\/[\w.-]+){2,}|[A-Za-z]:\\[\w.\\-]+/;
|
|
18
|
+
const sanitizeErrorMessage = (err, fallback = "Internal server error", sanitizeAll = false) => {
|
|
19
|
+
if (sanitizeAll) return fallback;
|
|
20
|
+
if (err instanceof TypeError || err instanceof ReferenceError || err instanceof SyntaxError || err instanceof RangeError) return fallback;
|
|
21
|
+
if (err && typeof err === "object" && ("syscall" in err || "path" in err || "sql" in err)) return fallback;
|
|
22
|
+
const msg = err?.message || String(err ?? "");
|
|
23
|
+
if (!msg || msg.includes("\n") || INTERNAL_ERROR_RE.test(msg) || FILE_PATH_RE.test(msg)) return fallback;
|
|
24
|
+
return msg;
|
|
25
|
+
};
|
|
16
26
|
const sleep = (timeout) => new Promise((resolve) => {
|
|
17
27
|
setTimeout(resolve, timeout);
|
|
18
28
|
});
|
|
@@ -46,8 +56,144 @@ const refreshHeartbeat = (socket) => {
|
|
|
46
56
|
socket.heartbeatAt = Date.now();
|
|
47
57
|
};
|
|
48
58
|
const HEARTBEAT_TIMEOUT = 300 * 1e3;
|
|
59
|
+
const DEFAULT_HEARTBEAT_INTERVAL = 30 * 1e3;
|
|
49
60
|
const MAX_PAYLOAD = 64 * 1024;
|
|
50
61
|
const MAX_TOPICS_PER_SOCKET = 64;
|
|
62
|
+
const FORBIDDEN_TOPICS = new Set([
|
|
63
|
+
"__proto__",
|
|
64
|
+
"constructor",
|
|
65
|
+
"prototype"
|
|
66
|
+
]);
|
|
67
|
+
const MAX_CONNECTIONS = 1024;
|
|
68
|
+
const MAX_CONNECTIONS_PER_IP = 64;
|
|
69
|
+
const parseEnvNonNegativeInt = (raw, fallback) => {
|
|
70
|
+
if (raw === void 0 || raw.trim() === "") return fallback;
|
|
71
|
+
const parsed = Number(raw);
|
|
72
|
+
return Number.isInteger(parsed) && parsed >= 0 ? parsed : fallback;
|
|
73
|
+
};
|
|
74
|
+
const parseEnvBoolean = (raw) => {
|
|
75
|
+
if (raw === void 0 || raw.trim() === "") return void 0;
|
|
76
|
+
const normalized = raw.trim().toLowerCase();
|
|
77
|
+
if (normalized === "1" || normalized === "true") return true;
|
|
78
|
+
if (normalized === "0" || normalized === "false") return false;
|
|
79
|
+
const numeric = Number(normalized);
|
|
80
|
+
if (Number.isInteger(numeric) && numeric > 0) return true;
|
|
81
|
+
};
|
|
82
|
+
const parseEnvPositiveInt = (raw, fallback) => {
|
|
83
|
+
if (raw === void 0 || raw.trim() === "") return fallback;
|
|
84
|
+
const parsed = Number(raw);
|
|
85
|
+
return Number.isInteger(parsed) && parsed >= 1 ? parsed : fallback;
|
|
86
|
+
};
|
|
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
|
+
}
|
|
182
|
+
const rawXff = headers["x-forwarded-for"];
|
|
183
|
+
const xffStr = Array.isArray(rawXff) ? rawXff.join(",") : rawXff;
|
|
184
|
+
if (typeof xffStr === "string" && xffStr.trim()) {
|
|
185
|
+
const hops = xffStr.split(",").map((part) => normalizeIpAddress(part)).filter(Boolean);
|
|
186
|
+
if (hops.length > 0) return hops[Math.max(0, hops.length - Math.max(1, trustProxyHops))];
|
|
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
|
+
}
|
|
196
|
+
};
|
|
51
197
|
/**
|
|
52
198
|
* Create a websocket server
|
|
53
199
|
*
|
|
@@ -70,7 +216,16 @@ var WsServer = class extends node_events.default {
|
|
|
70
216
|
this.logger = opts.logger || require_logger.default("server", opts.silent);
|
|
71
217
|
this.skipLogOnHookError = opts.skipLogOnHookError || false;
|
|
72
218
|
this.heartbeatTimeout = opts.heartbeatTimeout || HEARTBEAT_TIMEOUT;
|
|
219
|
+
this.heartbeatInterval = opts.heartbeatInterval ?? DEFAULT_HEARTBEAT_INTERVAL;
|
|
73
220
|
this.maxTopicsPerSocket = opts.maxTopicsPerSocket ?? MAX_TOPICS_PER_SOCKET;
|
|
221
|
+
this.maxConnections = opts.maxConnections ?? parseEnvNonNegativeInt(process.env.WS_MAX_CONNECTIONS, MAX_CONNECTIONS);
|
|
222
|
+
this.maxConnectionsPerIp = opts.maxConnectionsPerIp ?? parseEnvNonNegativeInt(process.env.WS_MAX_CONNECTIONS_PER_IP, MAX_CONNECTIONS_PER_IP);
|
|
223
|
+
this.trustProxy = typeof opts.trustProxy === "number" ? opts.trustProxy > 0 : opts.trustProxy ?? parseEnvBoolean(process.env.WS_TRUST_PROXY) ?? parseEnvBoolean(process.env.TRUST_PROXY) ?? false;
|
|
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);
|
|
228
|
+
this.sanitizeErrors = opts.sanitizeErrors ?? false;
|
|
74
229
|
this.wss = new ws.WebSocketServer({
|
|
75
230
|
noServer: true,
|
|
76
231
|
clientTracking: false,
|
|
@@ -79,12 +234,29 @@ var WsServer = class extends node_events.default {
|
|
|
79
234
|
this.wss.on("connection", this.onWssConnection.bind(this));
|
|
80
235
|
this.wss.on("close", this.onWssClose.bind(this));
|
|
81
236
|
this.wss.on("error", this.onWssError.bind(this));
|
|
82
|
-
this.topics =
|
|
237
|
+
this.topics = Object.create(null);
|
|
238
|
+
this.connections = /* @__PURE__ */ new Set();
|
|
239
|
+
this.ipConnectionCounts = /* @__PURE__ */ new Map();
|
|
240
|
+
this.pendingConnections = 0;
|
|
241
|
+
this.pendingIpConnections = /* @__PURE__ */ new Map();
|
|
242
|
+
if (this.heartbeatInterval > 0) {
|
|
243
|
+
this.heartbeatTimer = setInterval(() => this._sweepConnections(), this.heartbeatInterval);
|
|
244
|
+
this.heartbeatTimer.unref?.();
|
|
245
|
+
}
|
|
83
246
|
this.broadcastEventName = opts.broadcastEventName || "@arcblock/ws:broadcast";
|
|
84
247
|
eventHub.on(this.broadcastEventName, (data) => this._doBroadCast(data));
|
|
85
248
|
}
|
|
86
249
|
attach(server) {
|
|
87
250
|
server.on("upgrade", this.onConnect.bind(this));
|
|
251
|
+
const origClose = server.close.bind(server);
|
|
252
|
+
server.close = ((cb) => {
|
|
253
|
+
if (this.heartbeatTimer) {
|
|
254
|
+
clearInterval(this.heartbeatTimer);
|
|
255
|
+
this.heartbeatTimer = void 0;
|
|
256
|
+
}
|
|
257
|
+
server.closeAllConnections?.();
|
|
258
|
+
return origClose(cb);
|
|
259
|
+
});
|
|
88
260
|
return this;
|
|
89
261
|
}
|
|
90
262
|
onConnect(request, socket, head) {
|
|
@@ -95,20 +267,56 @@ var WsServer = class extends node_events.default {
|
|
|
95
267
|
socket.destroy();
|
|
96
268
|
return;
|
|
97
269
|
}
|
|
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;
|
|
272
|
+
if (this.maxConnections > 0 && this.connections.size + this.pendingConnections >= this.maxConnections) {
|
|
273
|
+
this.logger.warn?.("max connections reached", { maxConnections: this.maxConnections });
|
|
274
|
+
socket.write("HTTP/1.1 503 Service Unavailable\r\n\r\n");
|
|
275
|
+
socket.destroy();
|
|
276
|
+
return;
|
|
277
|
+
}
|
|
278
|
+
const currentIpCount = (this.ipConnectionCounts.get(clientIp) || 0) + (this.pendingIpConnections.get(clientIp) || 0);
|
|
279
|
+
if (this.maxConnectionsPerIp > 0 && currentIpCount >= this.maxConnectionsPerIp) {
|
|
280
|
+
this.logger.warn?.("per-IP connection limit reached", {
|
|
281
|
+
clientIp,
|
|
282
|
+
maxConnectionsPerIp: this.maxConnectionsPerIp
|
|
283
|
+
});
|
|
284
|
+
socket.write("HTTP/1.1 429 Too Many Requests\r\n\r\n");
|
|
285
|
+
socket.destroy();
|
|
286
|
+
return;
|
|
287
|
+
}
|
|
288
|
+
this.pendingConnections += 1;
|
|
289
|
+
this.pendingIpConnections.set(clientIp, (this.pendingIpConnections.get(clientIp) || 0) + 1);
|
|
290
|
+
let pendingReleased = false;
|
|
291
|
+
const releasePending = () => {
|
|
292
|
+
if (pendingReleased) return;
|
|
293
|
+
pendingReleased = true;
|
|
294
|
+
this.pendingConnections = Math.max(0, this.pendingConnections - 1);
|
|
295
|
+
const nextPending = (this.pendingIpConnections.get(clientIp) || 1) - 1;
|
|
296
|
+
if (nextPending <= 0) this.pendingIpConnections.delete(clientIp);
|
|
297
|
+
else this.pendingIpConnections.set(clientIp, nextPending);
|
|
298
|
+
};
|
|
299
|
+
socket.once("close", releasePending);
|
|
300
|
+
socket.once("error", releasePending);
|
|
98
301
|
if (!this.authenticate) {
|
|
99
302
|
this.wss.handleUpgrade(request, socket, head, (ws$1) => {
|
|
303
|
+
ws$1.clientIp = clientIp;
|
|
304
|
+
releasePending();
|
|
100
305
|
this.wss.emit("connection", ws$1, request);
|
|
101
306
|
});
|
|
102
307
|
return;
|
|
103
308
|
}
|
|
104
309
|
this.authenticate(request, (err, authInfo) => {
|
|
105
310
|
if (err) {
|
|
311
|
+
releasePending();
|
|
106
312
|
socket.write("HTTP/1.1 401 Unauthorized\r\n\r\n");
|
|
107
313
|
socket.destroy();
|
|
108
314
|
return;
|
|
109
315
|
}
|
|
110
316
|
this.wss.handleUpgrade(request, socket, head, (ws$1) => {
|
|
111
317
|
ws$1.authInfo = authInfo;
|
|
318
|
+
ws$1.clientIp = clientIp;
|
|
319
|
+
releasePending();
|
|
112
320
|
this.wss.emit("connection", ws$1, request);
|
|
113
321
|
});
|
|
114
322
|
});
|
|
@@ -267,12 +475,19 @@ var WsServer = class extends node_events.default {
|
|
|
267
475
|
/**
|
|
268
476
|
* private
|
|
269
477
|
*/
|
|
270
|
-
async onWssConnection(socket) {
|
|
478
|
+
async onWssConnection(socket, request) {
|
|
271
479
|
const wsSocket = socket;
|
|
272
480
|
wsSocket.id = nanoid();
|
|
273
|
-
wsSocket.channel =
|
|
481
|
+
wsSocket.channel = Object.create(null);
|
|
482
|
+
wsSocket.isAlive = true;
|
|
483
|
+
wsSocket.clientIp = wsSocket.clientIp || request?.socket?.remoteAddress || "unknown";
|
|
484
|
+
this.connections.add(wsSocket);
|
|
485
|
+
this.ipConnectionCounts.set(wsSocket.clientIp, (this.ipConnectionCounts.get(wsSocket.clientIp) || 0) + 1);
|
|
274
486
|
refreshHeartbeat(wsSocket);
|
|
275
487
|
this.logger.debug("socket connected", { id: wsSocket.id });
|
|
488
|
+
wsSocket.on("pong", () => {
|
|
489
|
+
wsSocket.isAlive = true;
|
|
490
|
+
});
|
|
276
491
|
wsSocket.on("message", async (msg) => {
|
|
277
492
|
this.logger.debug("socket onmessage", msg.toString());
|
|
278
493
|
let joinRef;
|
|
@@ -281,7 +496,12 @@ var WsServer = class extends node_events.default {
|
|
|
281
496
|
let event;
|
|
282
497
|
let payload;
|
|
283
498
|
try {
|
|
284
|
-
|
|
499
|
+
const parsed = JSON.parse(msg.toString());
|
|
500
|
+
if (!Array.isArray(parsed)) {
|
|
501
|
+
this.logger.warn?.("Invalid message format, expected array");
|
|
502
|
+
return;
|
|
503
|
+
}
|
|
504
|
+
[joinRef, ref, topic, event, payload] = parsed;
|
|
285
505
|
} catch (err) {
|
|
286
506
|
this.logger.error("parse socket message error", {
|
|
287
507
|
id: wsSocket.id,
|
|
@@ -289,10 +509,26 @@ var WsServer = class extends node_events.default {
|
|
|
289
509
|
});
|
|
290
510
|
return;
|
|
291
511
|
}
|
|
292
|
-
if (!topic || !event) {
|
|
512
|
+
if (typeof topic !== "string" || typeof event !== "string" || !topic || !event) {
|
|
293
513
|
this.logger.warn?.("Invalid message format, topic/event fields are required");
|
|
294
514
|
return;
|
|
295
515
|
}
|
|
516
|
+
if (FORBIDDEN_TOPICS.has(topic)) {
|
|
517
|
+
this.logger.warn?.("Invalid topic name", {
|
|
518
|
+
id: wsSocket.id,
|
|
519
|
+
topic
|
|
520
|
+
});
|
|
521
|
+
reply({
|
|
522
|
+
socket: wsSocket,
|
|
523
|
+
topic,
|
|
524
|
+
event: `chan_reply_${ref}`,
|
|
525
|
+
data: { message: "invalid topic" },
|
|
526
|
+
status: "error",
|
|
527
|
+
ref: typeof ref === "string" ? ref : "",
|
|
528
|
+
joinRef: typeof joinRef === "string" ? joinRef : ""
|
|
529
|
+
});
|
|
530
|
+
return;
|
|
531
|
+
}
|
|
296
532
|
if (topic === "phoenix" && event === "heartbeat") {
|
|
297
533
|
reply({
|
|
298
534
|
socket: wsSocket,
|
|
@@ -304,7 +540,7 @@ var WsServer = class extends node_events.default {
|
|
|
304
540
|
return;
|
|
305
541
|
}
|
|
306
542
|
if (event === "phx_join") {
|
|
307
|
-
if (this.maxTopicsPerSocket > 0 && !(
|
|
543
|
+
if (this.maxTopicsPerSocket > 0 && !Object.hasOwn(wsSocket.channel, topic) && Object.keys(wsSocket.channel).length >= this.maxTopicsPerSocket) {
|
|
308
544
|
reply({
|
|
309
545
|
socket: wsSocket,
|
|
310
546
|
topic,
|
|
@@ -334,21 +570,21 @@ var WsServer = class extends node_events.default {
|
|
|
334
570
|
payload
|
|
335
571
|
});
|
|
336
572
|
wsSocket.channel[topic] = { authInfo };
|
|
573
|
+
if (!(this.topics[topic] instanceof Set)) this.topics[topic] = /* @__PURE__ */ new Set();
|
|
574
|
+
this.topics[topic].add(wsSocket);
|
|
337
575
|
} catch (error) {
|
|
338
576
|
if (!this.skipLogOnHookError) this.logger.error("preJoinChannel error", { error });
|
|
339
577
|
reply({
|
|
340
578
|
socket: wsSocket,
|
|
341
579
|
topic,
|
|
342
580
|
event: `chan_reply_${ref}`,
|
|
343
|
-
data: { message: error.
|
|
581
|
+
data: { message: sanitizeErrorMessage(error, "Internal server error", this.sanitizeErrors) },
|
|
344
582
|
status: "error",
|
|
345
583
|
ref,
|
|
346
584
|
joinRef
|
|
347
585
|
});
|
|
348
586
|
return;
|
|
349
587
|
}
|
|
350
|
-
if (!this.topics[topic]) this.topics[topic] = /* @__PURE__ */ new Set();
|
|
351
|
-
this.topics[topic].add(wsSocket);
|
|
352
588
|
reply({
|
|
353
589
|
socket: wsSocket,
|
|
354
590
|
topic,
|
|
@@ -392,7 +628,7 @@ var WsServer = class extends node_events.default {
|
|
|
392
628
|
socket: wsSocket,
|
|
393
629
|
topic,
|
|
394
630
|
event: `chan_reply_${ref}`,
|
|
395
|
-
data: { message: error.
|
|
631
|
+
data: { message: sanitizeErrorMessage(error, "Internal server error", this.sanitizeErrors) },
|
|
396
632
|
status: "error",
|
|
397
633
|
ref,
|
|
398
634
|
joinRef
|
|
@@ -436,7 +672,7 @@ var WsServer = class extends node_events.default {
|
|
|
436
672
|
socket: wsSocket,
|
|
437
673
|
topic,
|
|
438
674
|
event: `chan_reply_${ref}`,
|
|
439
|
-
data: { message: error.
|
|
675
|
+
data: { message: sanitizeErrorMessage(error, "Internal server error", this.sanitizeErrors) },
|
|
440
676
|
status: "error",
|
|
441
677
|
ref,
|
|
442
678
|
joinRef
|
|
@@ -453,20 +689,48 @@ var WsServer = class extends node_events.default {
|
|
|
453
689
|
});
|
|
454
690
|
wsSocket.on("close", () => {
|
|
455
691
|
this.logger.debug("socket onclose", { id: wsSocket.id });
|
|
456
|
-
|
|
692
|
+
this._cleanupSocket(wsSocket);
|
|
457
693
|
});
|
|
458
694
|
wsSocket.on("error", (err) => {
|
|
459
695
|
this.logger.error("socket onerror", {
|
|
460
696
|
id: wsSocket.id,
|
|
461
697
|
error: err
|
|
462
698
|
});
|
|
463
|
-
|
|
699
|
+
this._cleanupSocket(wsSocket);
|
|
464
700
|
});
|
|
465
701
|
}
|
|
702
|
+
_cleanupSocket(wsSocket) {
|
|
703
|
+
if (this.connections.delete(wsSocket) && wsSocket.clientIp) {
|
|
704
|
+
const nextCount = (this.ipConnectionCounts.get(wsSocket.clientIp) || 1) - 1;
|
|
705
|
+
if (nextCount <= 0) this.ipConnectionCounts.delete(wsSocket.clientIp);
|
|
706
|
+
else this.ipConnectionCounts.set(wsSocket.clientIp, nextCount);
|
|
707
|
+
}
|
|
708
|
+
Object.keys(this.topics).forEach((topic) => this._leaveChannel(wsSocket, topic));
|
|
709
|
+
}
|
|
710
|
+
_sweepConnections() {
|
|
711
|
+
const now = Date.now();
|
|
712
|
+
for (const socket of Array.from(this.connections)) {
|
|
713
|
+
const noHeartbeatTime = now - socket.heartbeatAt;
|
|
714
|
+
if (noHeartbeatTime > this.heartbeatTimeout || socket.isAlive === false) {
|
|
715
|
+
this.logger.error(`Socket has no heartbeat within ${Math.floor(noHeartbeatTime / 1e3)} seconds`, { id: socket.id });
|
|
716
|
+
this._cleanupSocket(socket);
|
|
717
|
+
socket.terminate?.();
|
|
718
|
+
continue;
|
|
719
|
+
}
|
|
720
|
+
if (socket.readyState === ws.default.OPEN) {
|
|
721
|
+
socket.isAlive = false;
|
|
722
|
+
socket.ping?.();
|
|
723
|
+
}
|
|
724
|
+
}
|
|
725
|
+
}
|
|
466
726
|
/**
|
|
467
727
|
* private
|
|
468
728
|
*/
|
|
469
729
|
onWssClose() {
|
|
730
|
+
if (this.heartbeatTimer) {
|
|
731
|
+
clearInterval(this.heartbeatTimer);
|
|
732
|
+
this.heartbeatTimer = void 0;
|
|
733
|
+
}
|
|
470
734
|
this.logger.debug("ws server onclose");
|
|
471
735
|
this.emit("close");
|
|
472
736
|
}
|
|
@@ -478,12 +742,13 @@ var WsServer = class extends node_events.default {
|
|
|
478
742
|
this.emit("error", error);
|
|
479
743
|
}
|
|
480
744
|
_leaveChannel(socket, topic) {
|
|
481
|
-
if (
|
|
745
|
+
if (socket?.channel && Object.hasOwn(socket.channel, topic)) delete socket.channel[topic];
|
|
746
|
+
if (this.topics[topic] instanceof Set) this.topics[topic].delete(socket);
|
|
482
747
|
this.emit("channel.leave", {
|
|
483
748
|
socket,
|
|
484
749
|
topic
|
|
485
750
|
});
|
|
486
|
-
if (!this.topics[topic] || !this.topics[topic].size) this.emit("channel.destroy", {
|
|
751
|
+
if (!(this.topics[topic] instanceof Set) || !this.topics[topic].size) this.emit("channel.destroy", {
|
|
487
752
|
socket,
|
|
488
753
|
topic
|
|
489
754
|
});
|
package/lib/server/index.d.cts
CHANGED
|
@@ -11,6 +11,8 @@ interface WsSocket extends WebSocket {
|
|
|
11
11
|
authInfo?: unknown;
|
|
12
12
|
}>;
|
|
13
13
|
heartbeatAt: number;
|
|
14
|
+
isAlive?: boolean;
|
|
15
|
+
clientIp?: string;
|
|
14
16
|
authInfo?: unknown;
|
|
15
17
|
}
|
|
16
18
|
interface HookParams {
|
|
@@ -40,19 +42,16 @@ interface WsServerOptions {
|
|
|
40
42
|
skipLogOnHookError?: boolean;
|
|
41
43
|
broadcastEventName?: string;
|
|
42
44
|
heartbeatTimeout?: number;
|
|
43
|
-
|
|
44
|
-
* Maximum size of a single inbound WebSocket frame in bytes. The `ws`
|
|
45
|
-
* library rejects oversized frames with close code 1009. Defaults to 64 KiB
|
|
46
|
-
* which is far above any legitimate Phoenix-protocol client message.
|
|
47
|
-
*/
|
|
45
|
+
heartbeatInterval?: number;
|
|
48
46
|
maxPayload?: number;
|
|
49
|
-
/**
|
|
50
|
-
* Maximum distinct `phx_join` topics a single socket can hold. Each join
|
|
51
|
-
* inserts a Set into `this.topics`, so an unbounded value lets a hostile
|
|
52
|
-
* client force unbounded server-side memory growth via random topic strings.
|
|
53
|
-
* Defaults to 64. Set to 0 to disable the cap.
|
|
54
|
-
*/
|
|
55
47
|
maxTopicsPerSocket?: number;
|
|
48
|
+
maxConnections?: number;
|
|
49
|
+
maxConnectionsPerIp?: number;
|
|
50
|
+
trustProxy?: boolean | number;
|
|
51
|
+
trustProxyHops?: number;
|
|
52
|
+
trustedProxies?: string[];
|
|
53
|
+
trustedIpHeader?: string;
|
|
54
|
+
sanitizeErrors?: boolean;
|
|
56
55
|
}
|
|
57
56
|
interface BroadcastOptions {
|
|
58
57
|
enableLog?: boolean;
|
|
@@ -94,9 +93,22 @@ declare class WsServer extends EventEmitter {
|
|
|
94
93
|
logger: Logger;
|
|
95
94
|
skipLogOnHookError: boolean;
|
|
96
95
|
heartbeatTimeout: number;
|
|
96
|
+
heartbeatInterval: number;
|
|
97
|
+
heartbeatTimer?: ReturnType<typeof setInterval>;
|
|
97
98
|
maxTopicsPerSocket: number;
|
|
99
|
+
maxConnections: number;
|
|
100
|
+
maxConnectionsPerIp: number;
|
|
101
|
+
trustProxy: boolean;
|
|
102
|
+
trustProxyHops: number;
|
|
103
|
+
trustedProxies: string[];
|
|
104
|
+
trustedIpHeader?: string;
|
|
105
|
+
sanitizeErrors: boolean;
|
|
98
106
|
wss: WebSocketServer;
|
|
99
107
|
topics: Record<string, Set<WsSocket>>;
|
|
108
|
+
connections: Set<WsSocket>;
|
|
109
|
+
ipConnectionCounts: Map<string, number>;
|
|
110
|
+
pendingConnections: number;
|
|
111
|
+
pendingIpConnections: Map<string, number>;
|
|
100
112
|
broadcastEventName: string;
|
|
101
113
|
constructor(opts?: WsServerOptions);
|
|
102
114
|
attach(server: http.Server): this;
|
|
@@ -129,7 +141,9 @@ declare class WsServer extends EventEmitter {
|
|
|
129
141
|
/**
|
|
130
142
|
* private
|
|
131
143
|
*/
|
|
132
|
-
onWssConnection(socket: WebSocket): Promise<void>;
|
|
144
|
+
onWssConnection(socket: WebSocket, request?: http.IncomingMessage): Promise<void>;
|
|
145
|
+
_cleanupSocket(wsSocket: WsSocket): void;
|
|
146
|
+
_sweepConnections(): void;
|
|
133
147
|
/**
|
|
134
148
|
* private
|
|
135
149
|
*/
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@arcblock/ws",
|
|
3
|
-
"version": "1.30.
|
|
3
|
+
"version": "1.30.26",
|
|
4
4
|
"description": "OCAP Chain websocket server and client",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"websocket"
|
|
@@ -75,11 +75,11 @@
|
|
|
75
75
|
"url": "https://github.com/ArcBlock/blockchain/issues"
|
|
76
76
|
},
|
|
77
77
|
"dependencies": {
|
|
78
|
-
"@arcblock/event-hub": "1.30.
|
|
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",
|
|
82
|
-
"phoenix": "1.7.
|
|
82
|
+
"phoenix": "1.7.24",
|
|
83
83
|
"ws": "^8.18.0"
|
|
84
84
|
},
|
|
85
85
|
"devDependencies": {
|