@arcblock/ws 1.30.23 → 1.30.25
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 +22 -12
- package/esm/server/index.mjs +178 -16
- package/lib/server/index.cjs +178 -16
- package/lib/server/index.d.cts +22 -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,14 @@ 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
|
+
sanitizeErrors?: boolean;
|
|
56
53
|
}
|
|
57
54
|
interface BroadcastOptions {
|
|
58
55
|
enableLog?: boolean;
|
|
@@ -94,9 +91,20 @@ declare class WsServer extends EventEmitter {
|
|
|
94
91
|
logger: Logger;
|
|
95
92
|
skipLogOnHookError: boolean;
|
|
96
93
|
heartbeatTimeout: number;
|
|
94
|
+
heartbeatInterval: number;
|
|
95
|
+
heartbeatTimer?: ReturnType<typeof setInterval>;
|
|
97
96
|
maxTopicsPerSocket: number;
|
|
97
|
+
maxConnections: number;
|
|
98
|
+
maxConnectionsPerIp: number;
|
|
99
|
+
trustProxy: boolean;
|
|
100
|
+
trustProxyHops: number;
|
|
101
|
+
sanitizeErrors: boolean;
|
|
98
102
|
wss: WebSocketServer;
|
|
99
103
|
topics: Record<string, Set<WsSocket>>;
|
|
104
|
+
connections: Set<WsSocket>;
|
|
105
|
+
ipConnectionCounts: Map<string, number>;
|
|
106
|
+
pendingConnections: number;
|
|
107
|
+
pendingIpConnections: Map<string, number>;
|
|
100
108
|
broadcastEventName: string;
|
|
101
109
|
constructor(opts?: WsServerOptions);
|
|
102
110
|
attach(server: http.Server): this;
|
|
@@ -129,7 +137,9 @@ declare class WsServer extends EventEmitter {
|
|
|
129
137
|
/**
|
|
130
138
|
* private
|
|
131
139
|
*/
|
|
132
|
-
onWssConnection(socket: WebSocket): Promise<void>;
|
|
140
|
+
onWssConnection(socket: WebSocket, request?: http.IncomingMessage): Promise<void>;
|
|
141
|
+
_cleanupSocket(wsSocket: WsSocket): void;
|
|
142
|
+
_sweepConnections(): void;
|
|
133
143
|
/**
|
|
134
144
|
* private
|
|
135
145
|
*/
|
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,45 @@ 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 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;
|
|
86
|
+
const rawXff = headers["x-forwarded-for"];
|
|
87
|
+
const xffStr = Array.isArray(rawXff) ? rawXff.join(",") : rawXff;
|
|
88
|
+
if (typeof xffStr === "string" && xffStr.trim()) {
|
|
89
|
+
const hops = xffStr.split(",").map((part) => part.trim()).filter(Boolean);
|
|
90
|
+
if (hops.length > 0) return hops[Math.max(0, hops.length - Math.max(1, trustProxyHops))];
|
|
91
|
+
}
|
|
92
|
+
};
|
|
46
93
|
/**
|
|
47
94
|
* Create a websocket server
|
|
48
95
|
*
|
|
@@ -65,7 +112,13 @@ var WsServer = class extends EventEmitter {
|
|
|
65
112
|
this.logger = opts.logger || logger_default("server", opts.silent);
|
|
66
113
|
this.skipLogOnHookError = opts.skipLogOnHookError || false;
|
|
67
114
|
this.heartbeatTimeout = opts.heartbeatTimeout || HEARTBEAT_TIMEOUT;
|
|
115
|
+
this.heartbeatInterval = opts.heartbeatInterval ?? DEFAULT_HEARTBEAT_INTERVAL;
|
|
68
116
|
this.maxTopicsPerSocket = opts.maxTopicsPerSocket ?? MAX_TOPICS_PER_SOCKET;
|
|
117
|
+
this.maxConnections = opts.maxConnections ?? parseEnvNonNegativeInt(process.env.WS_MAX_CONNECTIONS, MAX_CONNECTIONS);
|
|
118
|
+
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);
|
|
120
|
+
this.trustProxyHops = opts.trustProxyHops ?? (typeof opts.trustProxy === "number" && opts.trustProxy > 0 ? Math.floor(opts.trustProxy) : parseEnvPositiveInt(process.env.WS_TRUST_PROXY_HOPS, 1));
|
|
121
|
+
this.sanitizeErrors = opts.sanitizeErrors ?? false;
|
|
69
122
|
this.wss = new WebSocketServer({
|
|
70
123
|
noServer: true,
|
|
71
124
|
clientTracking: false,
|
|
@@ -74,12 +127,29 @@ var WsServer = class extends EventEmitter {
|
|
|
74
127
|
this.wss.on("connection", this.onWssConnection.bind(this));
|
|
75
128
|
this.wss.on("close", this.onWssClose.bind(this));
|
|
76
129
|
this.wss.on("error", this.onWssError.bind(this));
|
|
77
|
-
this.topics =
|
|
130
|
+
this.topics = Object.create(null);
|
|
131
|
+
this.connections = /* @__PURE__ */ new Set();
|
|
132
|
+
this.ipConnectionCounts = /* @__PURE__ */ new Map();
|
|
133
|
+
this.pendingConnections = 0;
|
|
134
|
+
this.pendingIpConnections = /* @__PURE__ */ new Map();
|
|
135
|
+
if (this.heartbeatInterval > 0) {
|
|
136
|
+
this.heartbeatTimer = setInterval(() => this._sweepConnections(), this.heartbeatInterval);
|
|
137
|
+
this.heartbeatTimer.unref?.();
|
|
138
|
+
}
|
|
78
139
|
this.broadcastEventName = opts.broadcastEventName || "@arcblock/ws:broadcast";
|
|
79
140
|
eventHub.on(this.broadcastEventName, (data) => this._doBroadCast(data));
|
|
80
141
|
}
|
|
81
142
|
attach(server) {
|
|
82
143
|
server.on("upgrade", this.onConnect.bind(this));
|
|
144
|
+
const origClose = server.close.bind(server);
|
|
145
|
+
server.close = ((cb) => {
|
|
146
|
+
if (this.heartbeatTimer) {
|
|
147
|
+
clearInterval(this.heartbeatTimer);
|
|
148
|
+
this.heartbeatTimer = void 0;
|
|
149
|
+
}
|
|
150
|
+
server.closeAllConnections?.();
|
|
151
|
+
return origClose(cb);
|
|
152
|
+
});
|
|
83
153
|
return this;
|
|
84
154
|
}
|
|
85
155
|
onConnect(request, socket, head) {
|
|
@@ -90,20 +160,55 @@ var WsServer = class extends EventEmitter {
|
|
|
90
160
|
socket.destroy();
|
|
91
161
|
return;
|
|
92
162
|
}
|
|
163
|
+
const clientIp = (this.trustProxy ? resolveClientIpFromHeaders(request.headers, this.trustProxyHops) : void 0) || request.socket?.remoteAddress || "unknown";
|
|
164
|
+
if (this.maxConnections > 0 && this.connections.size + this.pendingConnections >= this.maxConnections) {
|
|
165
|
+
this.logger.warn?.("max connections reached", { maxConnections: this.maxConnections });
|
|
166
|
+
socket.write("HTTP/1.1 503 Service Unavailable\r\n\r\n");
|
|
167
|
+
socket.destroy();
|
|
168
|
+
return;
|
|
169
|
+
}
|
|
170
|
+
const currentIpCount = (this.ipConnectionCounts.get(clientIp) || 0) + (this.pendingIpConnections.get(clientIp) || 0);
|
|
171
|
+
if (this.maxConnectionsPerIp > 0 && currentIpCount >= this.maxConnectionsPerIp) {
|
|
172
|
+
this.logger.warn?.("per-IP connection limit reached", {
|
|
173
|
+
clientIp,
|
|
174
|
+
maxConnectionsPerIp: this.maxConnectionsPerIp
|
|
175
|
+
});
|
|
176
|
+
socket.write("HTTP/1.1 429 Too Many Requests\r\n\r\n");
|
|
177
|
+
socket.destroy();
|
|
178
|
+
return;
|
|
179
|
+
}
|
|
180
|
+
this.pendingConnections += 1;
|
|
181
|
+
this.pendingIpConnections.set(clientIp, (this.pendingIpConnections.get(clientIp) || 0) + 1);
|
|
182
|
+
let pendingReleased = false;
|
|
183
|
+
const releasePending = () => {
|
|
184
|
+
if (pendingReleased) return;
|
|
185
|
+
pendingReleased = true;
|
|
186
|
+
this.pendingConnections = Math.max(0, this.pendingConnections - 1);
|
|
187
|
+
const nextPending = (this.pendingIpConnections.get(clientIp) || 1) - 1;
|
|
188
|
+
if (nextPending <= 0) this.pendingIpConnections.delete(clientIp);
|
|
189
|
+
else this.pendingIpConnections.set(clientIp, nextPending);
|
|
190
|
+
};
|
|
191
|
+
socket.once("close", releasePending);
|
|
192
|
+
socket.once("error", releasePending);
|
|
93
193
|
if (!this.authenticate) {
|
|
94
194
|
this.wss.handleUpgrade(request, socket, head, (ws) => {
|
|
195
|
+
ws.clientIp = clientIp;
|
|
196
|
+
releasePending();
|
|
95
197
|
this.wss.emit("connection", ws, request);
|
|
96
198
|
});
|
|
97
199
|
return;
|
|
98
200
|
}
|
|
99
201
|
this.authenticate(request, (err, authInfo) => {
|
|
100
202
|
if (err) {
|
|
203
|
+
releasePending();
|
|
101
204
|
socket.write("HTTP/1.1 401 Unauthorized\r\n\r\n");
|
|
102
205
|
socket.destroy();
|
|
103
206
|
return;
|
|
104
207
|
}
|
|
105
208
|
this.wss.handleUpgrade(request, socket, head, (ws) => {
|
|
106
209
|
ws.authInfo = authInfo;
|
|
210
|
+
ws.clientIp = clientIp;
|
|
211
|
+
releasePending();
|
|
107
212
|
this.wss.emit("connection", ws, request);
|
|
108
213
|
});
|
|
109
214
|
});
|
|
@@ -262,12 +367,19 @@ var WsServer = class extends EventEmitter {
|
|
|
262
367
|
/**
|
|
263
368
|
* private
|
|
264
369
|
*/
|
|
265
|
-
async onWssConnection(socket) {
|
|
370
|
+
async onWssConnection(socket, request) {
|
|
266
371
|
const wsSocket = socket;
|
|
267
372
|
wsSocket.id = nanoid();
|
|
268
|
-
wsSocket.channel =
|
|
373
|
+
wsSocket.channel = Object.create(null);
|
|
374
|
+
wsSocket.isAlive = true;
|
|
375
|
+
wsSocket.clientIp = wsSocket.clientIp || request?.socket?.remoteAddress || "unknown";
|
|
376
|
+
this.connections.add(wsSocket);
|
|
377
|
+
this.ipConnectionCounts.set(wsSocket.clientIp, (this.ipConnectionCounts.get(wsSocket.clientIp) || 0) + 1);
|
|
269
378
|
refreshHeartbeat(wsSocket);
|
|
270
379
|
this.logger.debug("socket connected", { id: wsSocket.id });
|
|
380
|
+
wsSocket.on("pong", () => {
|
|
381
|
+
wsSocket.isAlive = true;
|
|
382
|
+
});
|
|
271
383
|
wsSocket.on("message", async (msg) => {
|
|
272
384
|
this.logger.debug("socket onmessage", msg.toString());
|
|
273
385
|
let joinRef;
|
|
@@ -276,7 +388,12 @@ var WsServer = class extends EventEmitter {
|
|
|
276
388
|
let event;
|
|
277
389
|
let payload;
|
|
278
390
|
try {
|
|
279
|
-
|
|
391
|
+
const parsed = JSON.parse(msg.toString());
|
|
392
|
+
if (!Array.isArray(parsed)) {
|
|
393
|
+
this.logger.warn?.("Invalid message format, expected array");
|
|
394
|
+
return;
|
|
395
|
+
}
|
|
396
|
+
[joinRef, ref, topic, event, payload] = parsed;
|
|
280
397
|
} catch (err) {
|
|
281
398
|
this.logger.error("parse socket message error", {
|
|
282
399
|
id: wsSocket.id,
|
|
@@ -284,10 +401,26 @@ var WsServer = class extends EventEmitter {
|
|
|
284
401
|
});
|
|
285
402
|
return;
|
|
286
403
|
}
|
|
287
|
-
if (!topic || !event) {
|
|
404
|
+
if (typeof topic !== "string" || typeof event !== "string" || !topic || !event) {
|
|
288
405
|
this.logger.warn?.("Invalid message format, topic/event fields are required");
|
|
289
406
|
return;
|
|
290
407
|
}
|
|
408
|
+
if (FORBIDDEN_TOPICS.has(topic)) {
|
|
409
|
+
this.logger.warn?.("Invalid topic name", {
|
|
410
|
+
id: wsSocket.id,
|
|
411
|
+
topic
|
|
412
|
+
});
|
|
413
|
+
reply({
|
|
414
|
+
socket: wsSocket,
|
|
415
|
+
topic,
|
|
416
|
+
event: `chan_reply_${ref}`,
|
|
417
|
+
data: { message: "invalid topic" },
|
|
418
|
+
status: "error",
|
|
419
|
+
ref: typeof ref === "string" ? ref : "",
|
|
420
|
+
joinRef: typeof joinRef === "string" ? joinRef : ""
|
|
421
|
+
});
|
|
422
|
+
return;
|
|
423
|
+
}
|
|
291
424
|
if (topic === "phoenix" && event === "heartbeat") {
|
|
292
425
|
reply({
|
|
293
426
|
socket: wsSocket,
|
|
@@ -299,7 +432,7 @@ var WsServer = class extends EventEmitter {
|
|
|
299
432
|
return;
|
|
300
433
|
}
|
|
301
434
|
if (event === "phx_join") {
|
|
302
|
-
if (this.maxTopicsPerSocket > 0 && !(
|
|
435
|
+
if (this.maxTopicsPerSocket > 0 && !Object.hasOwn(wsSocket.channel, topic) && Object.keys(wsSocket.channel).length >= this.maxTopicsPerSocket) {
|
|
303
436
|
reply({
|
|
304
437
|
socket: wsSocket,
|
|
305
438
|
topic,
|
|
@@ -329,21 +462,21 @@ var WsServer = class extends EventEmitter {
|
|
|
329
462
|
payload
|
|
330
463
|
});
|
|
331
464
|
wsSocket.channel[topic] = { authInfo };
|
|
465
|
+
if (!(this.topics[topic] instanceof Set)) this.topics[topic] = /* @__PURE__ */ new Set();
|
|
466
|
+
this.topics[topic].add(wsSocket);
|
|
332
467
|
} catch (error) {
|
|
333
468
|
if (!this.skipLogOnHookError) this.logger.error("preJoinChannel error", { error });
|
|
334
469
|
reply({
|
|
335
470
|
socket: wsSocket,
|
|
336
471
|
topic,
|
|
337
472
|
event: `chan_reply_${ref}`,
|
|
338
|
-
data: { message: error.
|
|
473
|
+
data: { message: sanitizeErrorMessage(error, "Internal server error", this.sanitizeErrors) },
|
|
339
474
|
status: "error",
|
|
340
475
|
ref,
|
|
341
476
|
joinRef
|
|
342
477
|
});
|
|
343
478
|
return;
|
|
344
479
|
}
|
|
345
|
-
if (!this.topics[topic]) this.topics[topic] = /* @__PURE__ */ new Set();
|
|
346
|
-
this.topics[topic].add(wsSocket);
|
|
347
480
|
reply({
|
|
348
481
|
socket: wsSocket,
|
|
349
482
|
topic,
|
|
@@ -387,7 +520,7 @@ var WsServer = class extends EventEmitter {
|
|
|
387
520
|
socket: wsSocket,
|
|
388
521
|
topic,
|
|
389
522
|
event: `chan_reply_${ref}`,
|
|
390
|
-
data: { message: error.
|
|
523
|
+
data: { message: sanitizeErrorMessage(error, "Internal server error", this.sanitizeErrors) },
|
|
391
524
|
status: "error",
|
|
392
525
|
ref,
|
|
393
526
|
joinRef
|
|
@@ -431,7 +564,7 @@ var WsServer = class extends EventEmitter {
|
|
|
431
564
|
socket: wsSocket,
|
|
432
565
|
topic,
|
|
433
566
|
event: `chan_reply_${ref}`,
|
|
434
|
-
data: { message: error.
|
|
567
|
+
data: { message: sanitizeErrorMessage(error, "Internal server error", this.sanitizeErrors) },
|
|
435
568
|
status: "error",
|
|
436
569
|
ref,
|
|
437
570
|
joinRef
|
|
@@ -448,20 +581,48 @@ var WsServer = class extends EventEmitter {
|
|
|
448
581
|
});
|
|
449
582
|
wsSocket.on("close", () => {
|
|
450
583
|
this.logger.debug("socket onclose", { id: wsSocket.id });
|
|
451
|
-
|
|
584
|
+
this._cleanupSocket(wsSocket);
|
|
452
585
|
});
|
|
453
586
|
wsSocket.on("error", (err) => {
|
|
454
587
|
this.logger.error("socket onerror", {
|
|
455
588
|
id: wsSocket.id,
|
|
456
589
|
error: err
|
|
457
590
|
});
|
|
458
|
-
|
|
591
|
+
this._cleanupSocket(wsSocket);
|
|
459
592
|
});
|
|
460
593
|
}
|
|
594
|
+
_cleanupSocket(wsSocket) {
|
|
595
|
+
if (this.connections.delete(wsSocket) && wsSocket.clientIp) {
|
|
596
|
+
const nextCount = (this.ipConnectionCounts.get(wsSocket.clientIp) || 1) - 1;
|
|
597
|
+
if (nextCount <= 0) this.ipConnectionCounts.delete(wsSocket.clientIp);
|
|
598
|
+
else this.ipConnectionCounts.set(wsSocket.clientIp, nextCount);
|
|
599
|
+
}
|
|
600
|
+
Object.keys(this.topics).forEach((topic) => this._leaveChannel(wsSocket, topic));
|
|
601
|
+
}
|
|
602
|
+
_sweepConnections() {
|
|
603
|
+
const now = Date.now();
|
|
604
|
+
for (const socket of Array.from(this.connections)) {
|
|
605
|
+
const noHeartbeatTime = now - socket.heartbeatAt;
|
|
606
|
+
if (noHeartbeatTime > this.heartbeatTimeout || socket.isAlive === false) {
|
|
607
|
+
this.logger.error(`Socket has no heartbeat within ${Math.floor(noHeartbeatTime / 1e3)} seconds`, { id: socket.id });
|
|
608
|
+
this._cleanupSocket(socket);
|
|
609
|
+
socket.terminate?.();
|
|
610
|
+
continue;
|
|
611
|
+
}
|
|
612
|
+
if (socket.readyState === WebSocket.OPEN) {
|
|
613
|
+
socket.isAlive = false;
|
|
614
|
+
socket.ping?.();
|
|
615
|
+
}
|
|
616
|
+
}
|
|
617
|
+
}
|
|
461
618
|
/**
|
|
462
619
|
* private
|
|
463
620
|
*/
|
|
464
621
|
onWssClose() {
|
|
622
|
+
if (this.heartbeatTimer) {
|
|
623
|
+
clearInterval(this.heartbeatTimer);
|
|
624
|
+
this.heartbeatTimer = void 0;
|
|
625
|
+
}
|
|
465
626
|
this.logger.debug("ws server onclose");
|
|
466
627
|
this.emit("close");
|
|
467
628
|
}
|
|
@@ -473,12 +634,13 @@ var WsServer = class extends EventEmitter {
|
|
|
473
634
|
this.emit("error", error);
|
|
474
635
|
}
|
|
475
636
|
_leaveChannel(socket, topic) {
|
|
476
|
-
if (
|
|
637
|
+
if (socket?.channel && Object.hasOwn(socket.channel, topic)) delete socket.channel[topic];
|
|
638
|
+
if (this.topics[topic] instanceof Set) this.topics[topic].delete(socket);
|
|
477
639
|
this.emit("channel.leave", {
|
|
478
640
|
socket,
|
|
479
641
|
topic
|
|
480
642
|
});
|
|
481
|
-
if (!this.topics[topic] || !this.topics[topic].size) this.emit("channel.destroy", {
|
|
643
|
+
if (!(this.topics[topic] instanceof Set) || !this.topics[topic].size) this.emit("channel.destroy", {
|
|
482
644
|
socket,
|
|
483
645
|
topic
|
|
484
646
|
});
|
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,45 @@ 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 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;
|
|
91
|
+
const rawXff = headers["x-forwarded-for"];
|
|
92
|
+
const xffStr = Array.isArray(rawXff) ? rawXff.join(",") : rawXff;
|
|
93
|
+
if (typeof xffStr === "string" && xffStr.trim()) {
|
|
94
|
+
const hops = xffStr.split(",").map((part) => part.trim()).filter(Boolean);
|
|
95
|
+
if (hops.length > 0) return hops[Math.max(0, hops.length - Math.max(1, trustProxyHops))];
|
|
96
|
+
}
|
|
97
|
+
};
|
|
51
98
|
/**
|
|
52
99
|
* Create a websocket server
|
|
53
100
|
*
|
|
@@ -70,7 +117,13 @@ var WsServer = class extends node_events.default {
|
|
|
70
117
|
this.logger = opts.logger || require_logger.default("server", opts.silent);
|
|
71
118
|
this.skipLogOnHookError = opts.skipLogOnHookError || false;
|
|
72
119
|
this.heartbeatTimeout = opts.heartbeatTimeout || HEARTBEAT_TIMEOUT;
|
|
120
|
+
this.heartbeatInterval = opts.heartbeatInterval ?? DEFAULT_HEARTBEAT_INTERVAL;
|
|
73
121
|
this.maxTopicsPerSocket = opts.maxTopicsPerSocket ?? MAX_TOPICS_PER_SOCKET;
|
|
122
|
+
this.maxConnections = opts.maxConnections ?? parseEnvNonNegativeInt(process.env.WS_MAX_CONNECTIONS, MAX_CONNECTIONS);
|
|
123
|
+
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);
|
|
125
|
+
this.trustProxyHops = opts.trustProxyHops ?? (typeof opts.trustProxy === "number" && opts.trustProxy > 0 ? Math.floor(opts.trustProxy) : parseEnvPositiveInt(process.env.WS_TRUST_PROXY_HOPS, 1));
|
|
126
|
+
this.sanitizeErrors = opts.sanitizeErrors ?? false;
|
|
74
127
|
this.wss = new ws.WebSocketServer({
|
|
75
128
|
noServer: true,
|
|
76
129
|
clientTracking: false,
|
|
@@ -79,12 +132,29 @@ var WsServer = class extends node_events.default {
|
|
|
79
132
|
this.wss.on("connection", this.onWssConnection.bind(this));
|
|
80
133
|
this.wss.on("close", this.onWssClose.bind(this));
|
|
81
134
|
this.wss.on("error", this.onWssError.bind(this));
|
|
82
|
-
this.topics =
|
|
135
|
+
this.topics = Object.create(null);
|
|
136
|
+
this.connections = /* @__PURE__ */ new Set();
|
|
137
|
+
this.ipConnectionCounts = /* @__PURE__ */ new Map();
|
|
138
|
+
this.pendingConnections = 0;
|
|
139
|
+
this.pendingIpConnections = /* @__PURE__ */ new Map();
|
|
140
|
+
if (this.heartbeatInterval > 0) {
|
|
141
|
+
this.heartbeatTimer = setInterval(() => this._sweepConnections(), this.heartbeatInterval);
|
|
142
|
+
this.heartbeatTimer.unref?.();
|
|
143
|
+
}
|
|
83
144
|
this.broadcastEventName = opts.broadcastEventName || "@arcblock/ws:broadcast";
|
|
84
145
|
eventHub.on(this.broadcastEventName, (data) => this._doBroadCast(data));
|
|
85
146
|
}
|
|
86
147
|
attach(server) {
|
|
87
148
|
server.on("upgrade", this.onConnect.bind(this));
|
|
149
|
+
const origClose = server.close.bind(server);
|
|
150
|
+
server.close = ((cb) => {
|
|
151
|
+
if (this.heartbeatTimer) {
|
|
152
|
+
clearInterval(this.heartbeatTimer);
|
|
153
|
+
this.heartbeatTimer = void 0;
|
|
154
|
+
}
|
|
155
|
+
server.closeAllConnections?.();
|
|
156
|
+
return origClose(cb);
|
|
157
|
+
});
|
|
88
158
|
return this;
|
|
89
159
|
}
|
|
90
160
|
onConnect(request, socket, head) {
|
|
@@ -95,20 +165,55 @@ var WsServer = class extends node_events.default {
|
|
|
95
165
|
socket.destroy();
|
|
96
166
|
return;
|
|
97
167
|
}
|
|
168
|
+
const clientIp = (this.trustProxy ? resolveClientIpFromHeaders(request.headers, this.trustProxyHops) : void 0) || request.socket?.remoteAddress || "unknown";
|
|
169
|
+
if (this.maxConnections > 0 && this.connections.size + this.pendingConnections >= this.maxConnections) {
|
|
170
|
+
this.logger.warn?.("max connections reached", { maxConnections: this.maxConnections });
|
|
171
|
+
socket.write("HTTP/1.1 503 Service Unavailable\r\n\r\n");
|
|
172
|
+
socket.destroy();
|
|
173
|
+
return;
|
|
174
|
+
}
|
|
175
|
+
const currentIpCount = (this.ipConnectionCounts.get(clientIp) || 0) + (this.pendingIpConnections.get(clientIp) || 0);
|
|
176
|
+
if (this.maxConnectionsPerIp > 0 && currentIpCount >= this.maxConnectionsPerIp) {
|
|
177
|
+
this.logger.warn?.("per-IP connection limit reached", {
|
|
178
|
+
clientIp,
|
|
179
|
+
maxConnectionsPerIp: this.maxConnectionsPerIp
|
|
180
|
+
});
|
|
181
|
+
socket.write("HTTP/1.1 429 Too Many Requests\r\n\r\n");
|
|
182
|
+
socket.destroy();
|
|
183
|
+
return;
|
|
184
|
+
}
|
|
185
|
+
this.pendingConnections += 1;
|
|
186
|
+
this.pendingIpConnections.set(clientIp, (this.pendingIpConnections.get(clientIp) || 0) + 1);
|
|
187
|
+
let pendingReleased = false;
|
|
188
|
+
const releasePending = () => {
|
|
189
|
+
if (pendingReleased) return;
|
|
190
|
+
pendingReleased = true;
|
|
191
|
+
this.pendingConnections = Math.max(0, this.pendingConnections - 1);
|
|
192
|
+
const nextPending = (this.pendingIpConnections.get(clientIp) || 1) - 1;
|
|
193
|
+
if (nextPending <= 0) this.pendingIpConnections.delete(clientIp);
|
|
194
|
+
else this.pendingIpConnections.set(clientIp, nextPending);
|
|
195
|
+
};
|
|
196
|
+
socket.once("close", releasePending);
|
|
197
|
+
socket.once("error", releasePending);
|
|
98
198
|
if (!this.authenticate) {
|
|
99
199
|
this.wss.handleUpgrade(request, socket, head, (ws$1) => {
|
|
200
|
+
ws$1.clientIp = clientIp;
|
|
201
|
+
releasePending();
|
|
100
202
|
this.wss.emit("connection", ws$1, request);
|
|
101
203
|
});
|
|
102
204
|
return;
|
|
103
205
|
}
|
|
104
206
|
this.authenticate(request, (err, authInfo) => {
|
|
105
207
|
if (err) {
|
|
208
|
+
releasePending();
|
|
106
209
|
socket.write("HTTP/1.1 401 Unauthorized\r\n\r\n");
|
|
107
210
|
socket.destroy();
|
|
108
211
|
return;
|
|
109
212
|
}
|
|
110
213
|
this.wss.handleUpgrade(request, socket, head, (ws$1) => {
|
|
111
214
|
ws$1.authInfo = authInfo;
|
|
215
|
+
ws$1.clientIp = clientIp;
|
|
216
|
+
releasePending();
|
|
112
217
|
this.wss.emit("connection", ws$1, request);
|
|
113
218
|
});
|
|
114
219
|
});
|
|
@@ -267,12 +372,19 @@ var WsServer = class extends node_events.default {
|
|
|
267
372
|
/**
|
|
268
373
|
* private
|
|
269
374
|
*/
|
|
270
|
-
async onWssConnection(socket) {
|
|
375
|
+
async onWssConnection(socket, request) {
|
|
271
376
|
const wsSocket = socket;
|
|
272
377
|
wsSocket.id = nanoid();
|
|
273
|
-
wsSocket.channel =
|
|
378
|
+
wsSocket.channel = Object.create(null);
|
|
379
|
+
wsSocket.isAlive = true;
|
|
380
|
+
wsSocket.clientIp = wsSocket.clientIp || request?.socket?.remoteAddress || "unknown";
|
|
381
|
+
this.connections.add(wsSocket);
|
|
382
|
+
this.ipConnectionCounts.set(wsSocket.clientIp, (this.ipConnectionCounts.get(wsSocket.clientIp) || 0) + 1);
|
|
274
383
|
refreshHeartbeat(wsSocket);
|
|
275
384
|
this.logger.debug("socket connected", { id: wsSocket.id });
|
|
385
|
+
wsSocket.on("pong", () => {
|
|
386
|
+
wsSocket.isAlive = true;
|
|
387
|
+
});
|
|
276
388
|
wsSocket.on("message", async (msg) => {
|
|
277
389
|
this.logger.debug("socket onmessage", msg.toString());
|
|
278
390
|
let joinRef;
|
|
@@ -281,7 +393,12 @@ var WsServer = class extends node_events.default {
|
|
|
281
393
|
let event;
|
|
282
394
|
let payload;
|
|
283
395
|
try {
|
|
284
|
-
|
|
396
|
+
const parsed = JSON.parse(msg.toString());
|
|
397
|
+
if (!Array.isArray(parsed)) {
|
|
398
|
+
this.logger.warn?.("Invalid message format, expected array");
|
|
399
|
+
return;
|
|
400
|
+
}
|
|
401
|
+
[joinRef, ref, topic, event, payload] = parsed;
|
|
285
402
|
} catch (err) {
|
|
286
403
|
this.logger.error("parse socket message error", {
|
|
287
404
|
id: wsSocket.id,
|
|
@@ -289,10 +406,26 @@ var WsServer = class extends node_events.default {
|
|
|
289
406
|
});
|
|
290
407
|
return;
|
|
291
408
|
}
|
|
292
|
-
if (!topic || !event) {
|
|
409
|
+
if (typeof topic !== "string" || typeof event !== "string" || !topic || !event) {
|
|
293
410
|
this.logger.warn?.("Invalid message format, topic/event fields are required");
|
|
294
411
|
return;
|
|
295
412
|
}
|
|
413
|
+
if (FORBIDDEN_TOPICS.has(topic)) {
|
|
414
|
+
this.logger.warn?.("Invalid topic name", {
|
|
415
|
+
id: wsSocket.id,
|
|
416
|
+
topic
|
|
417
|
+
});
|
|
418
|
+
reply({
|
|
419
|
+
socket: wsSocket,
|
|
420
|
+
topic,
|
|
421
|
+
event: `chan_reply_${ref}`,
|
|
422
|
+
data: { message: "invalid topic" },
|
|
423
|
+
status: "error",
|
|
424
|
+
ref: typeof ref === "string" ? ref : "",
|
|
425
|
+
joinRef: typeof joinRef === "string" ? joinRef : ""
|
|
426
|
+
});
|
|
427
|
+
return;
|
|
428
|
+
}
|
|
296
429
|
if (topic === "phoenix" && event === "heartbeat") {
|
|
297
430
|
reply({
|
|
298
431
|
socket: wsSocket,
|
|
@@ -304,7 +437,7 @@ var WsServer = class extends node_events.default {
|
|
|
304
437
|
return;
|
|
305
438
|
}
|
|
306
439
|
if (event === "phx_join") {
|
|
307
|
-
if (this.maxTopicsPerSocket > 0 && !(
|
|
440
|
+
if (this.maxTopicsPerSocket > 0 && !Object.hasOwn(wsSocket.channel, topic) && Object.keys(wsSocket.channel).length >= this.maxTopicsPerSocket) {
|
|
308
441
|
reply({
|
|
309
442
|
socket: wsSocket,
|
|
310
443
|
topic,
|
|
@@ -334,21 +467,21 @@ var WsServer = class extends node_events.default {
|
|
|
334
467
|
payload
|
|
335
468
|
});
|
|
336
469
|
wsSocket.channel[topic] = { authInfo };
|
|
470
|
+
if (!(this.topics[topic] instanceof Set)) this.topics[topic] = /* @__PURE__ */ new Set();
|
|
471
|
+
this.topics[topic].add(wsSocket);
|
|
337
472
|
} catch (error) {
|
|
338
473
|
if (!this.skipLogOnHookError) this.logger.error("preJoinChannel error", { error });
|
|
339
474
|
reply({
|
|
340
475
|
socket: wsSocket,
|
|
341
476
|
topic,
|
|
342
477
|
event: `chan_reply_${ref}`,
|
|
343
|
-
data: { message: error.
|
|
478
|
+
data: { message: sanitizeErrorMessage(error, "Internal server error", this.sanitizeErrors) },
|
|
344
479
|
status: "error",
|
|
345
480
|
ref,
|
|
346
481
|
joinRef
|
|
347
482
|
});
|
|
348
483
|
return;
|
|
349
484
|
}
|
|
350
|
-
if (!this.topics[topic]) this.topics[topic] = /* @__PURE__ */ new Set();
|
|
351
|
-
this.topics[topic].add(wsSocket);
|
|
352
485
|
reply({
|
|
353
486
|
socket: wsSocket,
|
|
354
487
|
topic,
|
|
@@ -392,7 +525,7 @@ var WsServer = class extends node_events.default {
|
|
|
392
525
|
socket: wsSocket,
|
|
393
526
|
topic,
|
|
394
527
|
event: `chan_reply_${ref}`,
|
|
395
|
-
data: { message: error.
|
|
528
|
+
data: { message: sanitizeErrorMessage(error, "Internal server error", this.sanitizeErrors) },
|
|
396
529
|
status: "error",
|
|
397
530
|
ref,
|
|
398
531
|
joinRef
|
|
@@ -436,7 +569,7 @@ var WsServer = class extends node_events.default {
|
|
|
436
569
|
socket: wsSocket,
|
|
437
570
|
topic,
|
|
438
571
|
event: `chan_reply_${ref}`,
|
|
439
|
-
data: { message: error.
|
|
572
|
+
data: { message: sanitizeErrorMessage(error, "Internal server error", this.sanitizeErrors) },
|
|
440
573
|
status: "error",
|
|
441
574
|
ref,
|
|
442
575
|
joinRef
|
|
@@ -453,20 +586,48 @@ var WsServer = class extends node_events.default {
|
|
|
453
586
|
});
|
|
454
587
|
wsSocket.on("close", () => {
|
|
455
588
|
this.logger.debug("socket onclose", { id: wsSocket.id });
|
|
456
|
-
|
|
589
|
+
this._cleanupSocket(wsSocket);
|
|
457
590
|
});
|
|
458
591
|
wsSocket.on("error", (err) => {
|
|
459
592
|
this.logger.error("socket onerror", {
|
|
460
593
|
id: wsSocket.id,
|
|
461
594
|
error: err
|
|
462
595
|
});
|
|
463
|
-
|
|
596
|
+
this._cleanupSocket(wsSocket);
|
|
464
597
|
});
|
|
465
598
|
}
|
|
599
|
+
_cleanupSocket(wsSocket) {
|
|
600
|
+
if (this.connections.delete(wsSocket) && wsSocket.clientIp) {
|
|
601
|
+
const nextCount = (this.ipConnectionCounts.get(wsSocket.clientIp) || 1) - 1;
|
|
602
|
+
if (nextCount <= 0) this.ipConnectionCounts.delete(wsSocket.clientIp);
|
|
603
|
+
else this.ipConnectionCounts.set(wsSocket.clientIp, nextCount);
|
|
604
|
+
}
|
|
605
|
+
Object.keys(this.topics).forEach((topic) => this._leaveChannel(wsSocket, topic));
|
|
606
|
+
}
|
|
607
|
+
_sweepConnections() {
|
|
608
|
+
const now = Date.now();
|
|
609
|
+
for (const socket of Array.from(this.connections)) {
|
|
610
|
+
const noHeartbeatTime = now - socket.heartbeatAt;
|
|
611
|
+
if (noHeartbeatTime > this.heartbeatTimeout || socket.isAlive === false) {
|
|
612
|
+
this.logger.error(`Socket has no heartbeat within ${Math.floor(noHeartbeatTime / 1e3)} seconds`, { id: socket.id });
|
|
613
|
+
this._cleanupSocket(socket);
|
|
614
|
+
socket.terminate?.();
|
|
615
|
+
continue;
|
|
616
|
+
}
|
|
617
|
+
if (socket.readyState === ws.default.OPEN) {
|
|
618
|
+
socket.isAlive = false;
|
|
619
|
+
socket.ping?.();
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
}
|
|
466
623
|
/**
|
|
467
624
|
* private
|
|
468
625
|
*/
|
|
469
626
|
onWssClose() {
|
|
627
|
+
if (this.heartbeatTimer) {
|
|
628
|
+
clearInterval(this.heartbeatTimer);
|
|
629
|
+
this.heartbeatTimer = void 0;
|
|
630
|
+
}
|
|
470
631
|
this.logger.debug("ws server onclose");
|
|
471
632
|
this.emit("close");
|
|
472
633
|
}
|
|
@@ -478,12 +639,13 @@ var WsServer = class extends node_events.default {
|
|
|
478
639
|
this.emit("error", error);
|
|
479
640
|
}
|
|
480
641
|
_leaveChannel(socket, topic) {
|
|
481
|
-
if (
|
|
642
|
+
if (socket?.channel && Object.hasOwn(socket.channel, topic)) delete socket.channel[topic];
|
|
643
|
+
if (this.topics[topic] instanceof Set) this.topics[topic].delete(socket);
|
|
482
644
|
this.emit("channel.leave", {
|
|
483
645
|
socket,
|
|
484
646
|
topic
|
|
485
647
|
});
|
|
486
|
-
if (!this.topics[topic] || !this.topics[topic].size) this.emit("channel.destroy", {
|
|
648
|
+
if (!(this.topics[topic] instanceof Set) || !this.topics[topic].size) this.emit("channel.destroy", {
|
|
487
649
|
socket,
|
|
488
650
|
topic
|
|
489
651
|
});
|
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,14 @@ 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
|
+
sanitizeErrors?: boolean;
|
|
56
53
|
}
|
|
57
54
|
interface BroadcastOptions {
|
|
58
55
|
enableLog?: boolean;
|
|
@@ -94,9 +91,20 @@ declare class WsServer extends EventEmitter {
|
|
|
94
91
|
logger: Logger;
|
|
95
92
|
skipLogOnHookError: boolean;
|
|
96
93
|
heartbeatTimeout: number;
|
|
94
|
+
heartbeatInterval: number;
|
|
95
|
+
heartbeatTimer?: ReturnType<typeof setInterval>;
|
|
97
96
|
maxTopicsPerSocket: number;
|
|
97
|
+
maxConnections: number;
|
|
98
|
+
maxConnectionsPerIp: number;
|
|
99
|
+
trustProxy: boolean;
|
|
100
|
+
trustProxyHops: number;
|
|
101
|
+
sanitizeErrors: boolean;
|
|
98
102
|
wss: WebSocketServer;
|
|
99
103
|
topics: Record<string, Set<WsSocket>>;
|
|
104
|
+
connections: Set<WsSocket>;
|
|
105
|
+
ipConnectionCounts: Map<string, number>;
|
|
106
|
+
pendingConnections: number;
|
|
107
|
+
pendingIpConnections: Map<string, number>;
|
|
100
108
|
broadcastEventName: string;
|
|
101
109
|
constructor(opts?: WsServerOptions);
|
|
102
110
|
attach(server: http.Server): this;
|
|
@@ -129,7 +137,9 @@ declare class WsServer extends EventEmitter {
|
|
|
129
137
|
/**
|
|
130
138
|
* private
|
|
131
139
|
*/
|
|
132
|
-
onWssConnection(socket: WebSocket): Promise<void>;
|
|
140
|
+
onWssConnection(socket: WebSocket, request?: http.IncomingMessage): Promise<void>;
|
|
141
|
+
_cleanupSocket(wsSocket: WsSocket): void;
|
|
142
|
+
_sweepConnections(): void;
|
|
133
143
|
/**
|
|
134
144
|
* private
|
|
135
145
|
*/
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@arcblock/ws",
|
|
3
|
-
"version": "1.30.
|
|
3
|
+
"version": "1.30.25",
|
|
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.25",
|
|
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": {
|