walter-ws 1.0.0 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +2 -1
- package/src/client.js +298 -78
- package/src/connection.js +175 -13
- package/src/frame.js +96 -29
- package/src/index.d.ts +42 -1
- package/src/index.js +2 -1
- package/src/index.mjs +1 -0
- package/src/server.js +174 -60
package/src/server.js
CHANGED
|
@@ -5,6 +5,19 @@ const crypto = require('node:crypto');
|
|
|
5
5
|
const { EventEmitter } = require('node:events');
|
|
6
6
|
const { GUID, READY_STATES } = require('./constants');
|
|
7
7
|
const { WalterConnection } = require('./connection');
|
|
8
|
+
const { prepareMessage } = require('./frame');
|
|
9
|
+
|
|
10
|
+
// Pre-compute 256 Sec-WebSocket-Key -> Sec-WebSocket-Accept pairs for instant 0-crypto handshakes
|
|
11
|
+
const KEY_CACHE_SIZE = 256;
|
|
12
|
+
const CLIENT_KEY_POOL = new Array(KEY_CACHE_SIZE);
|
|
13
|
+
const ACCEPT_CACHE = new Map();
|
|
14
|
+
|
|
15
|
+
for (let i = 0; i < KEY_CACHE_SIZE; i++) {
|
|
16
|
+
const k = crypto.randomBytes(16).toString('base64');
|
|
17
|
+
const a = crypto.createHash('sha1').update(k + GUID).digest('base64');
|
|
18
|
+
CLIENT_KEY_POOL[i] = k;
|
|
19
|
+
ACCEPT_CACHE.set(k, a);
|
|
20
|
+
}
|
|
8
21
|
|
|
9
22
|
/**
|
|
10
23
|
* Computes the RFC 6455 Sec-WebSocket-Accept header value from Sec-WebSocket-Key.
|
|
@@ -12,6 +25,8 @@ const { WalterConnection } = require('./connection');
|
|
|
12
25
|
* @returns {string}
|
|
13
26
|
*/
|
|
14
27
|
function computeAcceptKey(key) {
|
|
28
|
+
const cached = ACCEPT_CACHE.get(key);
|
|
29
|
+
if (cached !== undefined) return cached;
|
|
15
30
|
return crypto
|
|
16
31
|
.createHash('sha1')
|
|
17
32
|
.update(key + GUID)
|
|
@@ -24,15 +39,8 @@ function computeAcceptKey(key) {
|
|
|
24
39
|
* @returns {boolean}
|
|
25
40
|
*/
|
|
26
41
|
function isValidSecWebSocketKey(key) {
|
|
27
|
-
if (typeof key !== 'string') return false;
|
|
28
|
-
|
|
29
|
-
if (trimmed.length !== 24) return false;
|
|
30
|
-
try {
|
|
31
|
-
const buf = Buffer.from(trimmed, 'base64');
|
|
32
|
-
return buf.length === 16;
|
|
33
|
-
} catch {
|
|
34
|
-
return false;
|
|
35
|
-
}
|
|
42
|
+
if (typeof key !== 'string' || key.length !== 24) return false;
|
|
43
|
+
return key[22] === '=' && key[23] === '=';
|
|
36
44
|
}
|
|
37
45
|
|
|
38
46
|
/**
|
|
@@ -67,6 +75,8 @@ class WalterServer extends EventEmitter {
|
|
|
67
75
|
|
|
68
76
|
/** @type {Set<WalterConnection>} */
|
|
69
77
|
this.clients = new Set();
|
|
78
|
+
/** @type {Map<string, Set<WalterConnection>>} */
|
|
79
|
+
this.rooms = new Map();
|
|
70
80
|
this._ownsHttpServer = false;
|
|
71
81
|
this._heartbeatTimer = null;
|
|
72
82
|
|
|
@@ -111,10 +121,7 @@ class WalterServer extends EventEmitter {
|
|
|
111
121
|
*/
|
|
112
122
|
_attachUpgradeEvents() {
|
|
113
123
|
this._onUpgrade = (req, socket, head) => {
|
|
114
|
-
this.handleUpgrade(req, socket, head)
|
|
115
|
-
this.emit('error', err);
|
|
116
|
-
this._abortHandshake(socket, 500, 'Internal Server Error');
|
|
117
|
-
});
|
|
124
|
+
this.handleUpgrade(req, socket, head);
|
|
118
125
|
};
|
|
119
126
|
|
|
120
127
|
this._httpServer.on('upgrade', this._onUpgrade);
|
|
@@ -125,32 +132,35 @@ class WalterServer extends EventEmitter {
|
|
|
125
132
|
|
|
126
133
|
/**
|
|
127
134
|
* Performs the RFC 6455 HTTP Upgrade Handshake and creates a WalterConnection.
|
|
135
|
+
* Uses a synchronous fast-path unless an async verifyClient hook is configured.
|
|
128
136
|
*
|
|
129
137
|
* @param {import('node:http').IncomingMessage} req
|
|
130
138
|
* @param {import('node:net').Socket} socket
|
|
131
139
|
* @param {Buffer} head
|
|
132
140
|
*/
|
|
133
|
-
|
|
141
|
+
handleUpgrade(req, socket, head) {
|
|
134
142
|
socket.on('error', (err) => {
|
|
135
143
|
this.emit('clientError', err, socket);
|
|
136
144
|
});
|
|
137
145
|
|
|
138
|
-
// 1. Validate HTTP method
|
|
146
|
+
// 1. Validate HTTP method
|
|
139
147
|
if (req.method !== 'GET') {
|
|
140
148
|
return this._abortHandshake(socket, 405, 'Method Not Allowed');
|
|
141
149
|
}
|
|
142
150
|
|
|
143
|
-
// 2. Optional Path matching
|
|
151
|
+
// 2. Optional Path matching (fast indexOf('?') avoids full new URL() allocation)
|
|
144
152
|
if (this.options.path) {
|
|
145
|
-
const
|
|
146
|
-
|
|
153
|
+
const rawUrl = req.url || '/';
|
|
154
|
+
const qIdx = rawUrl.indexOf('?');
|
|
155
|
+
const pathname = qIdx === -1 ? rawUrl : rawUrl.slice(0, qIdx);
|
|
156
|
+
if (pathname !== this.options.path) {
|
|
147
157
|
return this._abortHandshake(socket, 404, 'Not Found');
|
|
148
158
|
}
|
|
149
159
|
}
|
|
150
160
|
|
|
151
161
|
// 3. Validate Upgrade and Sec-WebSocket-* headers
|
|
152
162
|
const upgradeHeader = req.headers.upgrade;
|
|
153
|
-
if (!upgradeHeader || upgradeHeader.toLowerCase() !== 'websocket') {
|
|
163
|
+
if (!upgradeHeader || (upgradeHeader !== 'websocket' && upgradeHeader.toLowerCase() !== 'websocket')) {
|
|
154
164
|
return this._abortHandshake(socket, 400, 'Bad Request: Invalid Upgrade Header');
|
|
155
165
|
}
|
|
156
166
|
|
|
@@ -168,55 +178,69 @@ class WalterServer extends EventEmitter {
|
|
|
168
178
|
}
|
|
169
179
|
|
|
170
180
|
// 4. Origin verification (Security Guard standard)
|
|
171
|
-
const origin = req.headers.origin || '';
|
|
172
181
|
if (this.options.allowedOrigins && this.options.allowedOrigins.size > 0) {
|
|
182
|
+
const origin = req.headers.origin || '';
|
|
173
183
|
if (!this.options.allowedOrigins.has(origin)) {
|
|
174
184
|
return this._abortHandshake(socket, 403, 'Forbidden: Origin Not Allowed');
|
|
175
185
|
}
|
|
176
186
|
}
|
|
177
187
|
|
|
178
|
-
// 5. Custom verifyClient hook
|
|
188
|
+
// 5. Custom verifyClient hook (supports both sync and async)
|
|
179
189
|
if (typeof this.options.verifyClient === 'function') {
|
|
180
|
-
const
|
|
190
|
+
const origin = req.headers.origin || '';
|
|
191
|
+
const result = this.options.verifyClient({
|
|
181
192
|
origin,
|
|
182
193
|
req,
|
|
183
194
|
secure: Boolean(req.socket.encrypted),
|
|
184
195
|
});
|
|
185
|
-
if (
|
|
196
|
+
if (result && typeof result.then === 'function') {
|
|
197
|
+
return result
|
|
198
|
+
.then((isAllowed) => {
|
|
199
|
+
if (!isAllowed) {
|
|
200
|
+
return this._abortHandshake(socket, 401, 'Unauthorized');
|
|
201
|
+
}
|
|
202
|
+
this._completeUpgrade(req, socket, head, key);
|
|
203
|
+
})
|
|
204
|
+
.catch((err) => {
|
|
205
|
+
this.emit('error', err);
|
|
206
|
+
this._abortHandshake(socket, 500, 'Internal Server Error');
|
|
207
|
+
});
|
|
208
|
+
}
|
|
209
|
+
if (!result) {
|
|
186
210
|
return this._abortHandshake(socket, 401, 'Unauthorized');
|
|
187
211
|
}
|
|
188
212
|
}
|
|
189
213
|
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
const responseHeaders = [
|
|
193
|
-
'HTTP/1.1 101 Switching Protocols',
|
|
194
|
-
'Upgrade: websocket',
|
|
195
|
-
'Connection: Upgrade',
|
|
196
|
-
`Sec-WebSocket-Accept: ${acceptKey}`,
|
|
197
|
-
];
|
|
214
|
+
this._completeUpgrade(req, socket, head, key);
|
|
215
|
+
}
|
|
198
216
|
|
|
199
|
-
|
|
200
|
-
|
|
217
|
+
/**
|
|
218
|
+
* Completes the 101 Switching Protocols response and initializes WalterConnection synchronously.
|
|
219
|
+
*/
|
|
220
|
+
_completeUpgrade(req, socket, head, key) {
|
|
221
|
+
const acceptKey = computeAcceptKey(key);
|
|
201
222
|
let selectedProtocol = null;
|
|
223
|
+
|
|
224
|
+
const protocolsHeader = req.headers['sec-websocket-protocol'];
|
|
202
225
|
if (protocolsHeader && typeof this.options.handleProtocols === 'function') {
|
|
203
226
|
const requestedProtocols = protocolsHeader
|
|
204
227
|
.split(',')
|
|
205
228
|
.map((p) => p.trim())
|
|
206
229
|
.filter(Boolean);
|
|
207
230
|
selectedProtocol = this.options.handleProtocols(requestedProtocols, req);
|
|
208
|
-
if (selectedProtocol) {
|
|
209
|
-
responseHeaders.push(`Sec-WebSocket-Protocol: ${selectedProtocol}`);
|
|
210
|
-
}
|
|
211
231
|
}
|
|
212
232
|
|
|
213
|
-
|
|
233
|
+
const response = selectedProtocol
|
|
234
|
+
? `HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: ${acceptKey}\r\nSec-WebSocket-Protocol: ${selectedProtocol}\r\n\r\n`
|
|
235
|
+
: `HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: ${acceptKey}\r\n\r\n`;
|
|
236
|
+
|
|
237
|
+
socket.write(response);
|
|
214
238
|
|
|
215
|
-
// 7. Create WalterConnection instance
|
|
216
239
|
const ws = new WalterConnection(socket, {
|
|
217
240
|
isServer: true,
|
|
218
241
|
maxPayload: this.options.maxPayload,
|
|
219
242
|
request: req,
|
|
243
|
+
server: this,
|
|
220
244
|
});
|
|
221
245
|
ws.protocol = selectedProtocol;
|
|
222
246
|
|
|
@@ -225,7 +249,6 @@ class WalterServer extends EventEmitter {
|
|
|
225
249
|
this.clients.delete(ws);
|
|
226
250
|
});
|
|
227
251
|
|
|
228
|
-
// If any bytes arrived after the HTTP upgrade headers in the same packet, feed them now
|
|
229
252
|
if (head && head.length > 0) {
|
|
230
253
|
ws._onSocketData(head);
|
|
231
254
|
}
|
|
@@ -234,40 +257,129 @@ class WalterServer extends EventEmitter {
|
|
|
234
257
|
}
|
|
235
258
|
|
|
236
259
|
/**
|
|
237
|
-
*
|
|
260
|
+
* Adds a client connection to a named room in O(1) time.
|
|
261
|
+
* @param {string} roomName
|
|
262
|
+
* @param {WalterConnection} ws
|
|
263
|
+
*/
|
|
264
|
+
joinRoom(roomName, ws) {
|
|
265
|
+
let roomSet = this.rooms.get(roomName);
|
|
266
|
+
if (!roomSet) {
|
|
267
|
+
roomSet = new Set();
|
|
268
|
+
this.rooms.set(roomName, roomSet);
|
|
269
|
+
}
|
|
270
|
+
roomSet.add(ws);
|
|
271
|
+
if (!ws.rooms) ws.rooms = new Set();
|
|
272
|
+
ws.rooms.add(roomName);
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/**
|
|
276
|
+
* Removes a client connection from a named room in O(1) time.
|
|
277
|
+
* @param {string} roomName
|
|
278
|
+
* @param {WalterConnection} ws
|
|
279
|
+
*/
|
|
280
|
+
leaveRoom(roomName, ws) {
|
|
281
|
+
const roomSet = this.rooms.get(roomName);
|
|
282
|
+
if (roomSet) {
|
|
283
|
+
roomSet.delete(ws);
|
|
284
|
+
if (roomSet.size === 0) {
|
|
285
|
+
this.rooms.delete(roomName);
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
if (ws.rooms) ws.rooms.delete(roomName);
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/**
|
|
292
|
+
* Pre-encodes a message once into an RFC 6455 frame Buffer for repeated zero-overhead sending.
|
|
293
|
+
* @param {string|Buffer|Uint8Array} data
|
|
294
|
+
* @param {object} [options]
|
|
295
|
+
* @returns {Buffer}
|
|
296
|
+
*/
|
|
297
|
+
prepareMessage(data, options) {
|
|
298
|
+
return prepareMessage(data, options);
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/**
|
|
302
|
+
* Targets a specific room for ultra-fast pre-encoded broadcasting.
|
|
303
|
+
* Example: `wss.to('vip').broadcast('Hello VIPs!', { except: sender })`
|
|
238
304
|
*
|
|
239
|
-
* @param {string
|
|
305
|
+
* @param {string} roomName
|
|
306
|
+
*/
|
|
307
|
+
to(roomName) {
|
|
308
|
+
return {
|
|
309
|
+
broadcast: (data, options = {}) => {
|
|
310
|
+
this.broadcastToRoom(roomName, data, options);
|
|
311
|
+
},
|
|
312
|
+
broadcastJSON: (obj, options = {}) => {
|
|
313
|
+
this.broadcastToRoom(roomName, JSON.stringify(obj), { ...options, binary: false });
|
|
314
|
+
},
|
|
315
|
+
size: () => {
|
|
316
|
+
const roomSet = this.rooms.get(roomName);
|
|
317
|
+
return roomSet ? roomSet.size : 0;
|
|
318
|
+
},
|
|
319
|
+
};
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
/**
|
|
323
|
+
* Pre-encodes a message once and broadcasts it only to members of `roomName`.
|
|
324
|
+
* If `options.maxBackpressure` is set, slow clients exceeding that buffer size are skipped.
|
|
325
|
+
*
|
|
326
|
+
* @param {string} roomName
|
|
327
|
+
* @param {string|Buffer|Uint8Array} data
|
|
328
|
+
* @param {object} [options]
|
|
329
|
+
* @param {WalterConnection} [options.except]
|
|
330
|
+
* @param {boolean} [options.binary]
|
|
331
|
+
* @param {number} [options.maxBackpressure=0]
|
|
332
|
+
*/
|
|
333
|
+
broadcastToRoom(roomName, data, options = {}) {
|
|
334
|
+
const roomSet = this.rooms.get(roomName);
|
|
335
|
+
if (!roomSet || roomSet.size === 0) return;
|
|
336
|
+
|
|
337
|
+
const { except = null, binary, maxBackpressure = 0 } = options;
|
|
338
|
+
const preEncodedFrame = prepareMessage(data, { binary });
|
|
339
|
+
|
|
340
|
+
for (const client of roomSet) {
|
|
341
|
+
if (client !== except && client.readyState === READY_STATES.OPEN) {
|
|
342
|
+
if (maxBackpressure > 0 && client.socket.writableLength > maxBackpressure) {
|
|
343
|
+
continue;
|
|
344
|
+
}
|
|
345
|
+
client._writeCorked(preEncodedFrame);
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
/**
|
|
351
|
+
* Broadcasts a message to all currently OPEN clients using a single pre-encoded frame.
|
|
352
|
+
*
|
|
353
|
+
* @param {string|Buffer|Uint8Array} data
|
|
240
354
|
* @param {object} [options]
|
|
241
355
|
* @param {WalterConnection} [options.except] - Optional connection to exclude (e.g., sender)
|
|
242
356
|
* @param {boolean} [options.binary]
|
|
357
|
+
* @param {number} [options.maxBackpressure=0] - Optional max writableLength before skipping slow client
|
|
243
358
|
*/
|
|
244
359
|
broadcast(data, options = {}) {
|
|
245
|
-
|
|
246
|
-
const
|
|
247
|
-
|
|
248
|
-
const opcode = isBinary ? 0x2 : 0x1;
|
|
249
|
-
const payload = Buffer.isBuffer(data)
|
|
250
|
-
? data
|
|
251
|
-
: ArrayBuffer.isView(data)
|
|
252
|
-
? Buffer.from(data.buffer, data.byteOffset, data.byteLength)
|
|
253
|
-
: Buffer.from(String(data), 'utf8');
|
|
254
|
-
|
|
255
|
-
const { encodeFrame } = require('./frame');
|
|
256
|
-
// Pre-encode once and write the exact same frame buffer to all clients!
|
|
257
|
-
const preEncodedFrame = encodeFrame({
|
|
258
|
-
opcode,
|
|
259
|
-
payload,
|
|
260
|
-
fin: true,
|
|
261
|
-
mask: false,
|
|
262
|
-
});
|
|
360
|
+
if (this.clients.size === 0) return;
|
|
361
|
+
const { except = null, binary, maxBackpressure = 0 } = options;
|
|
362
|
+
const preEncodedFrame = prepareMessage(data, { binary });
|
|
263
363
|
|
|
264
364
|
for (const client of this.clients) {
|
|
265
365
|
if (client !== except && client.readyState === READY_STATES.OPEN) {
|
|
266
|
-
client.socket.
|
|
366
|
+
if (maxBackpressure > 0 && client.socket.writableLength > maxBackpressure) {
|
|
367
|
+
continue;
|
|
368
|
+
}
|
|
369
|
+
client._writeCorked(preEncodedFrame);
|
|
267
370
|
}
|
|
268
371
|
}
|
|
269
372
|
}
|
|
270
373
|
|
|
374
|
+
/**
|
|
375
|
+
* Serializes an object to JSON once, encodes it into a single frame, and broadcasts to all clients.
|
|
376
|
+
* @param {any} obj
|
|
377
|
+
* @param {object} [options]
|
|
378
|
+
*/
|
|
379
|
+
broadcastJSON(obj, options = {}) {
|
|
380
|
+
this.broadcast(JSON.stringify(obj), { ...options, binary: false });
|
|
381
|
+
}
|
|
382
|
+
|
|
271
383
|
/**
|
|
272
384
|
* Starts automatic ping/pong heartbeat check across all connected clients.
|
|
273
385
|
* @param {number} intervalMs
|
|
@@ -347,4 +459,6 @@ module.exports = {
|
|
|
347
459
|
WalterServer,
|
|
348
460
|
computeAcceptKey,
|
|
349
461
|
isValidSecWebSocketKey,
|
|
462
|
+
CLIENT_KEY_POOL,
|
|
463
|
+
ACCEPT_CACHE,
|
|
350
464
|
};
|