walter-ws 1.1.0 → 1.2.1
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 +1 -1
- package/src/client.js +150 -71
- package/src/connection.js +54 -21
- package/src/frame.js +72 -34
- package/src/server.js +64 -42
package/package.json
CHANGED
package/src/client.js
CHANGED
|
@@ -1,26 +1,18 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
const
|
|
4
|
-
const
|
|
5
|
-
const crypto = require('node:crypto');
|
|
3
|
+
const net = require('node:net');
|
|
4
|
+
const tls = require('node:tls');
|
|
6
5
|
const { EventEmitter } = require('node:events');
|
|
7
6
|
const { READY_STATES, CLOSE_CODES } = require('./constants');
|
|
8
7
|
const { WalterConnection } = require('./connection');
|
|
9
|
-
const {
|
|
8
|
+
const { CLIENT_KEY_POOL, ACCEPT_CACHE } = require('./server');
|
|
10
9
|
|
|
11
|
-
|
|
12
|
-
const keyPool = Buffer.allocUnsafe(KEY_POOL_SIZE);
|
|
13
|
-
crypto.randomFillSync(keyPool);
|
|
14
|
-
let keyPoolOffset = 0;
|
|
10
|
+
let keyPoolIdx = 0;
|
|
15
11
|
|
|
16
|
-
function
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
}
|
|
21
|
-
const key = keyPool.subarray(keyPoolOffset, keyPoolOffset + 16).toString('base64');
|
|
22
|
-
keyPoolOffset += 16;
|
|
23
|
-
return key;
|
|
12
|
+
function nextClientHandshakePair() {
|
|
13
|
+
const key = CLIENT_KEY_POOL[keyPoolIdx];
|
|
14
|
+
keyPoolIdx = (keyPoolIdx + 1) & 255;
|
|
15
|
+
return { key, expectedAccept: ACCEPT_CACHE.get(key) };
|
|
24
16
|
}
|
|
25
17
|
|
|
26
18
|
/**
|
|
@@ -43,16 +35,41 @@ class WalterClient extends EventEmitter {
|
|
|
43
35
|
constructor(url, options = {}) {
|
|
44
36
|
super();
|
|
45
37
|
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
38
|
+
if (typeof url === 'string') {
|
|
39
|
+
const isSecure = url.startsWith('wss://');
|
|
40
|
+
const isWs = isSecure || url.startsWith('ws://');
|
|
41
|
+
if (!isWs) {
|
|
42
|
+
this.url = new URL(url);
|
|
43
|
+
throw new Error(`Invalid WebSocket URL protocol: ${this.url.protocol}`);
|
|
44
|
+
}
|
|
45
|
+
const rest = url.slice(isSecure ? 6 : 5);
|
|
46
|
+
const slashIdx = rest.indexOf('/');
|
|
47
|
+
const hostPart = slashIdx === -1 ? rest : rest.slice(0, slashIdx);
|
|
48
|
+
const pathPart = slashIdx === -1 ? '/' : rest.slice(slashIdx);
|
|
49
|
+
const colonIdx = hostPart.indexOf(':');
|
|
50
|
+
this._isSecure = isSecure;
|
|
51
|
+
this._hostname = colonIdx === -1 ? hostPart : hostPart.slice(0, colonIdx);
|
|
52
|
+
this._port = colonIdx === -1 ? (isSecure ? 443 : 80) : Number(hostPart.slice(colonIdx + 1));
|
|
53
|
+
this._path = pathPart;
|
|
54
|
+
this.url = url;
|
|
55
|
+
} else {
|
|
56
|
+
if (url.protocol !== 'ws:' && url.protocol !== 'wss:') {
|
|
57
|
+
throw new Error(`Invalid WebSocket URL protocol: ${url.protocol}`);
|
|
58
|
+
}
|
|
59
|
+
this._isSecure = url.protocol === 'wss:';
|
|
60
|
+
this._hostname = url.hostname;
|
|
61
|
+
this._port = url.port || (this._isSecure ? 443 : 80);
|
|
62
|
+
this._path = `${url.pathname}${url.search}`;
|
|
63
|
+
this.url = url;
|
|
49
64
|
}
|
|
50
65
|
|
|
51
66
|
this.options = {
|
|
52
|
-
headers: options.headers ||
|
|
67
|
+
headers: options.headers || null,
|
|
53
68
|
protocols: options.protocols || null,
|
|
54
|
-
maxPayload: options.maxPayload ?? 1024 * 1024,
|
|
69
|
+
maxPayload: options.maxPayload ?? 16 * 1024 * 1024,
|
|
55
70
|
handshakeTimeout: options.handshakeTimeout ?? 10000,
|
|
71
|
+
skipUTF8Validation: options.skipUTF8Validation ?? false,
|
|
72
|
+
rawBuffer: options.rawBuffer ?? false,
|
|
56
73
|
autoReconnect: options.autoReconnect ?? false,
|
|
57
74
|
reconnectInterval: options.reconnectInterval ?? 1000,
|
|
58
75
|
maxReconnectInterval: options.maxReconnectInterval ?? 30000,
|
|
@@ -81,48 +98,69 @@ class WalterClient extends EventEmitter {
|
|
|
81
98
|
}
|
|
82
99
|
|
|
83
100
|
/**
|
|
84
|
-
* Initiates the HTTP Upgrade handshake
|
|
101
|
+
* Initiates the HTTP Upgrade handshake directly over a raw net.Socket / tls.TLSSocket
|
|
102
|
+
* to bypass Node's heavy http.ClientRequest wrapper.
|
|
85
103
|
*/
|
|
86
104
|
_connect() {
|
|
87
|
-
const isSecure = this.
|
|
88
|
-
const
|
|
89
|
-
|
|
90
|
-
const
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
105
|
+
const isSecure = this._isSecure;
|
|
106
|
+
const { key, expectedAccept } = nextClientHandshakePair();
|
|
107
|
+
|
|
108
|
+
const hostHeader =
|
|
109
|
+
(isSecure && this._port === 443) || (!isSecure && this._port === 80)
|
|
110
|
+
? this._hostname
|
|
111
|
+
: `${this._hostname}:${this._port}`;
|
|
112
|
+
|
|
113
|
+
let reqLines =
|
|
114
|
+
`GET ${this._path} HTTP/1.1\r\n` +
|
|
115
|
+
`Host: ${hostHeader}\r\n` +
|
|
116
|
+
`Upgrade: websocket\r\n` +
|
|
117
|
+
`Connection: Upgrade\r\n` +
|
|
118
|
+
`Sec-WebSocket-Key: ${key}\r\n` +
|
|
119
|
+
`Sec-WebSocket-Version: 13\r\n`;
|
|
99
120
|
|
|
100
121
|
if (this.options.protocols) {
|
|
101
122
|
const protoList = Array.isArray(this.options.protocols)
|
|
102
123
|
? this.options.protocols.join(', ')
|
|
103
124
|
: String(this.options.protocols);
|
|
104
|
-
|
|
125
|
+
reqLines += `Sec-WebSocket-Protocol: ${protoList}\r\n`;
|
|
105
126
|
}
|
|
106
127
|
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
method: 'GET',
|
|
113
|
-
headers,
|
|
114
|
-
agent: false,
|
|
115
|
-
timeout: this.options.handshakeTimeout,
|
|
116
|
-
};
|
|
117
|
-
|
|
118
|
-
const req = transport.request(reqOptions);
|
|
119
|
-
this._req = req;
|
|
128
|
+
if (this.options.headers) {
|
|
129
|
+
for (const [k, v] of Object.entries(this.options.headers)) {
|
|
130
|
+
reqLines += `${k}: ${v}\r\n`;
|
|
131
|
+
}
|
|
132
|
+
}
|
|
120
133
|
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
134
|
+
reqLines += '\r\n';
|
|
135
|
+
|
|
136
|
+
const socket = isSecure
|
|
137
|
+
? tls.connect({
|
|
138
|
+
host: this._hostname,
|
|
139
|
+
port: this._port,
|
|
140
|
+
servername: this._hostname,
|
|
141
|
+
})
|
|
142
|
+
: net.connect({
|
|
143
|
+
host: this._hostname,
|
|
144
|
+
port: this._port,
|
|
145
|
+
});
|
|
146
|
+
|
|
147
|
+
socket.setNoDelay(true);
|
|
148
|
+
this._req = socket;
|
|
149
|
+
|
|
150
|
+
let handshakeDone = false;
|
|
151
|
+
let headerBuf = Buffer.alloc(0);
|
|
152
|
+
|
|
153
|
+
if (this.options.handshakeTimeout > 0) {
|
|
154
|
+
socket.setTimeout(this.options.handshakeTimeout, () => {
|
|
155
|
+
if (!handshakeDone) {
|
|
156
|
+
socket.destroy(new Error('WebSocket opening handshake timed out'));
|
|
157
|
+
}
|
|
158
|
+
});
|
|
159
|
+
}
|
|
124
160
|
|
|
125
|
-
|
|
161
|
+
const onHandshakeError = (err) => {
|
|
162
|
+
if (handshakeDone) return;
|
|
163
|
+
handshakeDone = true;
|
|
126
164
|
if (this.readyState !== READY_STATES.CLOSED) {
|
|
127
165
|
this.readyState = READY_STATES.CLOSED;
|
|
128
166
|
if (this.listenerCount('error') > 0) {
|
|
@@ -133,23 +171,60 @@ class WalterClient extends EventEmitter {
|
|
|
133
171
|
}
|
|
134
172
|
this._handleDisconnect(CLOSE_CODES.ABNORMAL_CLOSURE, err.message);
|
|
135
173
|
}
|
|
136
|
-
}
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
174
|
+
};
|
|
175
|
+
|
|
176
|
+
socket.once('error', onHandshakeError);
|
|
177
|
+
|
|
178
|
+
// Queue handshake HTTP request immediately; Node buffers and flushes on connect
|
|
179
|
+
socket.write(reqLines);
|
|
180
|
+
|
|
181
|
+
const onHandshakeData = (chunk) => {
|
|
182
|
+
headerBuf = headerBuf.length === 0 ? chunk : Buffer.concat([headerBuf, chunk]);
|
|
183
|
+
const headerEnd = headerBuf.indexOf('\r\n\r\n');
|
|
184
|
+
if (headerEnd === -1) return;
|
|
185
|
+
|
|
186
|
+
socket.removeListener('data', onHandshakeData);
|
|
187
|
+
socket.removeListener('error', onHandshakeError);
|
|
188
|
+
socket.setTimeout(0);
|
|
189
|
+
handshakeDone = true;
|
|
190
|
+
|
|
191
|
+
const rawHeaderStr = headerBuf.subarray(0, headerEnd).toString('latin1');
|
|
192
|
+
const head = headerBuf.subarray(headerEnd + 4);
|
|
193
|
+
const lines = rawHeaderStr.split('\r\n');
|
|
194
|
+
const statusLine = lines[0] || '';
|
|
195
|
+
|
|
196
|
+
if (!statusLine.startsWith('HTTP/1.1 101')) {
|
|
197
|
+
const match = statusLine.match(/HTTP\/1\.\d\s+(\d+)/);
|
|
198
|
+
const statusCode = match ? match[1] : statusLine;
|
|
199
|
+
socket.destroy();
|
|
200
|
+
const err = new Error(`Unexpected server response: ${statusCode}`);
|
|
201
|
+
this.readyState = READY_STATES.CLOSED;
|
|
202
|
+
if (this.listenerCount('error') > 0) {
|
|
203
|
+
this.emit('error', err);
|
|
204
|
+
}
|
|
205
|
+
if (typeof this.onerror === 'function') {
|
|
206
|
+
this.onerror({ error: err, message: err.message, target: this });
|
|
207
|
+
}
|
|
208
|
+
this._handleDisconnect(CLOSE_CODES.ABNORMAL_CLOSURE, err.message);
|
|
209
|
+
return;
|
|
144
210
|
}
|
|
145
|
-
|
|
146
|
-
|
|
211
|
+
|
|
212
|
+
let acceptHeader = '';
|
|
213
|
+
let protocolHeader = null;
|
|
214
|
+
|
|
215
|
+
for (let i = 1; i < lines.length; i++) {
|
|
216
|
+
const line = lines[i];
|
|
217
|
+
const colon = line.indexOf(':');
|
|
218
|
+
if (colon === -1) continue;
|
|
219
|
+
const hName = line.slice(0, colon).trim().toLowerCase();
|
|
220
|
+
const hVal = line.slice(colon + 1).trim();
|
|
221
|
+
if (hName === 'sec-websocket-accept') {
|
|
222
|
+
acceptHeader = hVal;
|
|
223
|
+
} else if (hName === 'sec-websocket-protocol') {
|
|
224
|
+
protocolHeader = hVal;
|
|
225
|
+
}
|
|
147
226
|
}
|
|
148
|
-
this._handleDisconnect(CLOSE_CODES.ABNORMAL_CLOSURE, err.message);
|
|
149
|
-
});
|
|
150
227
|
|
|
151
|
-
req.on('upgrade', (res, socket, head) => {
|
|
152
|
-
const acceptHeader = res.headers['sec-websocket-accept'];
|
|
153
228
|
if (acceptHeader !== expectedAccept) {
|
|
154
229
|
socket.destroy();
|
|
155
230
|
const err = new Error(
|
|
@@ -167,13 +242,17 @@ class WalterClient extends EventEmitter {
|
|
|
167
242
|
}
|
|
168
243
|
|
|
169
244
|
this._connection = new WalterConnection(socket, {
|
|
170
|
-
isServer: false,
|
|
245
|
+
isServer: false,
|
|
171
246
|
maxPayload: this.options.maxPayload,
|
|
247
|
+
skipUTF8Validation: this.options.skipUTF8Validation,
|
|
248
|
+
rawBuffer: this.options.rawBuffer,
|
|
172
249
|
});
|
|
250
|
+
this._socket = socket;
|
|
251
|
+
this.socket = socket;
|
|
173
252
|
|
|
174
253
|
this.readyState = READY_STATES.OPEN;
|
|
175
254
|
this._reconnectAttempts = 0;
|
|
176
|
-
this.protocol =
|
|
255
|
+
this.protocol = protocolHeader;
|
|
177
256
|
|
|
178
257
|
this._connection.on('message', (data, isBinary) => {
|
|
179
258
|
this.emit('message', data, isBinary);
|
|
@@ -211,12 +290,12 @@ class WalterClient extends EventEmitter {
|
|
|
211
290
|
|
|
212
291
|
this._flushOfflineQueue();
|
|
213
292
|
|
|
214
|
-
if (head
|
|
293
|
+
if (head.length > 0) {
|
|
215
294
|
this._connection._onSocketData(head);
|
|
216
295
|
}
|
|
217
|
-
}
|
|
296
|
+
};
|
|
218
297
|
|
|
219
|
-
|
|
298
|
+
socket.on('data', onHandshakeData);
|
|
220
299
|
}
|
|
221
300
|
|
|
222
301
|
/**
|
package/src/connection.js
CHANGED
|
@@ -65,6 +65,8 @@ class WalterConnection extends EventEmitter {
|
|
|
65
65
|
this.socket = socket;
|
|
66
66
|
this.isServer = options.isServer ?? true;
|
|
67
67
|
this.maxPayload = options.maxPayload ?? 1024 * 1024;
|
|
68
|
+
this.skipUTF8Validation = options.skipUTF8Validation ?? false;
|
|
69
|
+
this.rawBuffer = options.rawBuffer ?? false;
|
|
68
70
|
this.request = options.request || null;
|
|
69
71
|
this.readyState = READY_STATES.OPEN;
|
|
70
72
|
this.isAlive = true;
|
|
@@ -79,8 +81,8 @@ class WalterConnection extends EventEmitter {
|
|
|
79
81
|
this._fragmentsLength = 0;
|
|
80
82
|
this._fragmentOpcode = null;
|
|
81
83
|
|
|
82
|
-
// Room membership (
|
|
83
|
-
this.rooms =
|
|
84
|
+
// Room membership (lazy Set) and fast corked batch queue
|
|
85
|
+
this.rooms = null;
|
|
84
86
|
this._server = options.server || null;
|
|
85
87
|
this._corkScheduled = false;
|
|
86
88
|
|
|
@@ -98,6 +100,7 @@ class WalterConnection extends EventEmitter {
|
|
|
98
100
|
* @returns {this}
|
|
99
101
|
*/
|
|
100
102
|
join(roomName) {
|
|
103
|
+
if (!this.rooms) this.rooms = new Set();
|
|
101
104
|
if (this._server) {
|
|
102
105
|
this._server.joinRoom(roomName, this);
|
|
103
106
|
} else {
|
|
@@ -112,6 +115,7 @@ class WalterConnection extends EventEmitter {
|
|
|
112
115
|
* @returns {this}
|
|
113
116
|
*/
|
|
114
117
|
leave(roomName) {
|
|
118
|
+
if (!this.rooms) return this;
|
|
115
119
|
if (this._server) {
|
|
116
120
|
this._server.leaveRoom(roomName, this);
|
|
117
121
|
} else {
|
|
@@ -124,6 +128,7 @@ class WalterConnection extends EventEmitter {
|
|
|
124
128
|
* Leaves all joined rooms.
|
|
125
129
|
*/
|
|
126
130
|
leaveAllRooms() {
|
|
131
|
+
if (!this.rooms || this.rooms.size === 0) return;
|
|
127
132
|
if (this._server) {
|
|
128
133
|
for (const room of this.rooms) {
|
|
129
134
|
this._server.leaveRoom(room, this);
|
|
@@ -172,6 +177,10 @@ class WalterConnection extends EventEmitter {
|
|
|
172
177
|
_bindSocketEvents() {
|
|
173
178
|
this.socket.setNoDelay(true);
|
|
174
179
|
|
|
180
|
+
if (this.socket.listenerCount('data') > 0) {
|
|
181
|
+
// Do not disturb existing listeners if any
|
|
182
|
+
}
|
|
183
|
+
|
|
175
184
|
this.socket.on('data', (chunk) => {
|
|
176
185
|
this._onSocketData(chunk);
|
|
177
186
|
});
|
|
@@ -219,9 +228,23 @@ class WalterConnection extends EventEmitter {
|
|
|
219
228
|
return;
|
|
220
229
|
}
|
|
221
230
|
|
|
222
|
-
|
|
231
|
+
const len = frames.length;
|
|
232
|
+
if (len === 0) return;
|
|
233
|
+
|
|
234
|
+
if (len > 1 && !this._corkScheduled && this.readyState === READY_STATES.OPEN) {
|
|
235
|
+
this._corkScheduled = true;
|
|
236
|
+
this.socket.cork();
|
|
237
|
+
queueMicrotask(() => {
|
|
238
|
+
this._corkScheduled = false;
|
|
239
|
+
if (!this.socket.destroyed) {
|
|
240
|
+
this.socket.uncork();
|
|
241
|
+
}
|
|
242
|
+
});
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
for (let i = 0; i < len; i++) {
|
|
223
246
|
try {
|
|
224
|
-
this._processFrame(
|
|
247
|
+
this._processFrame(frames[i]);
|
|
225
248
|
} catch (err) {
|
|
226
249
|
this._handleProtocolError(err);
|
|
227
250
|
return;
|
|
@@ -315,7 +338,13 @@ class WalterConnection extends EventEmitter {
|
|
|
315
338
|
*/
|
|
316
339
|
_deliverDataMessage(opcode, payload) {
|
|
317
340
|
if (opcode === OPCODES.TEXT) {
|
|
318
|
-
|
|
341
|
+
if (this.rawBuffer) {
|
|
342
|
+
this.emit('message', payload, false);
|
|
343
|
+
return;
|
|
344
|
+
}
|
|
345
|
+
const text = this.skipUTF8Validation
|
|
346
|
+
? payload.toString('utf8')
|
|
347
|
+
: decodeUTF8Strict(payload);
|
|
319
348
|
this.emit('message', text, false);
|
|
320
349
|
} else if (opcode === OPCODES.BINARY) {
|
|
321
350
|
this.emit('message', payload, true);
|
|
@@ -413,11 +442,12 @@ class WalterConnection extends EventEmitter {
|
|
|
413
442
|
const isBinary =
|
|
414
443
|
options.binary ?? (Buffer.isBuffer(data) || ArrayBuffer.isView(data));
|
|
415
444
|
const opcode = isBinary ? OPCODES.BINARY : OPCODES.TEXT;
|
|
416
|
-
const payload =
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
445
|
+
const payload =
|
|
446
|
+
typeof data === 'string' || Buffer.isBuffer(data)
|
|
447
|
+
? data
|
|
448
|
+
: ArrayBuffer.isView(data)
|
|
449
|
+
? Buffer.from(data.buffer, data.byteOffset, data.byteLength)
|
|
450
|
+
: String(data);
|
|
421
451
|
|
|
422
452
|
const frame = encodeFrame({
|
|
423
453
|
opcode,
|
|
@@ -428,10 +458,15 @@ class WalterConnection extends EventEmitter {
|
|
|
428
458
|
});
|
|
429
459
|
|
|
430
460
|
if (Array.isArray(frame)) {
|
|
431
|
-
this.
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
461
|
+
if (this._corkScheduled) {
|
|
462
|
+
this.socket.write(frame[0]);
|
|
463
|
+
this.socket.write(frame[1], callback);
|
|
464
|
+
} else {
|
|
465
|
+
this.socket.cork();
|
|
466
|
+
this.socket.write(frame[0]);
|
|
467
|
+
this.socket.write(frame[1], callback);
|
|
468
|
+
this.socket.uncork();
|
|
469
|
+
}
|
|
435
470
|
} else if (options.batch) {
|
|
436
471
|
this._writeCorked(frame, callback);
|
|
437
472
|
} else {
|
|
@@ -447,12 +482,10 @@ class WalterConnection extends EventEmitter {
|
|
|
447
482
|
sendFrame(preEncodedFrame, callback) {
|
|
448
483
|
if (this.readyState !== READY_STATES.OPEN) return;
|
|
449
484
|
if (Array.isArray(preEncodedFrame)) {
|
|
450
|
-
this.
|
|
451
|
-
this.
|
|
452
|
-
this.socket.write(preEncodedFrame[1], callback);
|
|
453
|
-
this.socket.uncork();
|
|
485
|
+
this._writeCorked(preEncodedFrame[0]);
|
|
486
|
+
this._writeCorked(preEncodedFrame[1], callback);
|
|
454
487
|
} else {
|
|
455
|
-
this.
|
|
488
|
+
this._writeCorked(preEncodedFrame, callback);
|
|
456
489
|
}
|
|
457
490
|
}
|
|
458
491
|
|
|
@@ -478,7 +511,7 @@ class WalterConnection extends EventEmitter {
|
|
|
478
511
|
fin: true,
|
|
479
512
|
mask: !this.isServer,
|
|
480
513
|
});
|
|
481
|
-
this.
|
|
514
|
+
this._writeCorked(frame, callback);
|
|
482
515
|
}
|
|
483
516
|
|
|
484
517
|
/**
|
|
@@ -494,7 +527,7 @@ class WalterConnection extends EventEmitter {
|
|
|
494
527
|
fin: true,
|
|
495
528
|
mask: !this.isServer,
|
|
496
529
|
});
|
|
497
|
-
this.
|
|
530
|
+
this._writeCorked(frame, callback);
|
|
498
531
|
}
|
|
499
532
|
|
|
500
533
|
/**
|
package/src/frame.js
CHANGED
|
@@ -57,30 +57,58 @@ function applyMask(src, maskKey, dest = Buffer.allocUnsafe(src.length), destOffs
|
|
|
57
57
|
|
|
58
58
|
let i = 0;
|
|
59
59
|
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
const
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
60
|
+
if (len >= 32) {
|
|
61
|
+
const srcByteOffset = src.byteOffset;
|
|
62
|
+
const destByteOffset = dest.byteOffset + destOffset;
|
|
63
|
+
const srcMod = srcByteOffset & 3;
|
|
64
|
+
const destMod = destByteOffset & 3;
|
|
65
|
+
|
|
66
|
+
if (srcMod === destMod) {
|
|
67
|
+
let alignPad = 0;
|
|
68
|
+
if (srcMod !== 0) {
|
|
69
|
+
alignPad = 4 - srcMod;
|
|
70
|
+
dest[destOffset] = src[0] ^ k0;
|
|
71
|
+
if (alignPad >= 2) dest[destOffset + 1] = src[1] ^ k1;
|
|
72
|
+
if (alignPad === 3) dest[destOffset + 2] = src[2] ^ k2;
|
|
73
|
+
i = alignPad;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const u32Count = (len - alignPad) >>> 2;
|
|
77
|
+
if (u32Count > 0) {
|
|
78
|
+
const src32 = new Uint32Array(src.buffer, srcByteOffset + alignPad, u32Count);
|
|
79
|
+
const dest32 = new Uint32Array(dest.buffer, destByteOffset + alignPad, u32Count);
|
|
80
|
+
let mask32;
|
|
81
|
+
if (alignPad === 0) {
|
|
82
|
+
mask32 = (k0 | (k1 << 8) | (k2 << 16) | (k3 << 24)) >>> 0;
|
|
83
|
+
} else if (alignPad === 1) {
|
|
84
|
+
mask32 = (k1 | (k2 << 8) | (k3 << 16) | (k0 << 24)) >>> 0;
|
|
85
|
+
} else if (alignPad === 2) {
|
|
86
|
+
mask32 = (k2 | (k3 << 8) | (k0 << 16) | (k1 << 24)) >>> 0;
|
|
87
|
+
} else {
|
|
88
|
+
mask32 = (k3 | (k0 << 8) | (k1 << 16) | (k2 << 24)) >>> 0;
|
|
89
|
+
}
|
|
90
|
+
for (let j = 0; j < u32Count; j++) {
|
|
91
|
+
dest32[j] = src32[j] ^ mask32;
|
|
92
|
+
}
|
|
93
|
+
i += u32Count << 2;
|
|
94
|
+
}
|
|
95
|
+
const remKeys = [k0, k1, k2, k3];
|
|
96
|
+
for (; i < len; i++) {
|
|
97
|
+
dest[destOffset + i] = src[i] ^ remKeys[i & 3];
|
|
98
|
+
}
|
|
99
|
+
return dest;
|
|
81
100
|
}
|
|
82
101
|
}
|
|
83
102
|
|
|
103
|
+
const end4 = len & ~3;
|
|
104
|
+
while (i < end4) {
|
|
105
|
+
dest[destOffset + i] = src[i] ^ k0;
|
|
106
|
+
dest[destOffset + i + 1] = src[i + 1] ^ k1;
|
|
107
|
+
dest[destOffset + i + 2] = src[i + 2] ^ k2;
|
|
108
|
+
dest[destOffset + i + 3] = src[i + 3] ^ k3;
|
|
109
|
+
i += 4;
|
|
110
|
+
}
|
|
111
|
+
|
|
84
112
|
const remKeys = [k0, k1, k2, k3];
|
|
85
113
|
for (; i < len; i++) {
|
|
86
114
|
dest[destOffset + i] = src[i] ^ remKeys[i & 3];
|
|
@@ -107,8 +135,17 @@ function encodeFrame(options) {
|
|
|
107
135
|
mask = false,
|
|
108
136
|
returnParts = false,
|
|
109
137
|
} = options;
|
|
110
|
-
|
|
111
|
-
|
|
138
|
+
|
|
139
|
+
let payloadBuf;
|
|
140
|
+
let payloadLength;
|
|
141
|
+
|
|
142
|
+
if (Buffer.isBuffer(payload)) {
|
|
143
|
+
payloadBuf = payload;
|
|
144
|
+
payloadLength = payload.length;
|
|
145
|
+
} else {
|
|
146
|
+
payloadBuf = Buffer.from(String(payload), 'utf8');
|
|
147
|
+
payloadLength = payloadBuf.length;
|
|
148
|
+
}
|
|
112
149
|
|
|
113
150
|
// Control frames (Close, Ping, Pong) cannot exceed 125 bytes or be fragmented
|
|
114
151
|
if ((opcode & 0x08) !== 0) {
|
|
@@ -133,7 +170,7 @@ function encodeFrame(options) {
|
|
|
133
170
|
headerLength = 10;
|
|
134
171
|
}
|
|
135
172
|
|
|
136
|
-
// Unmasked frames with
|
|
173
|
+
// Unmasked frames with payloads >= 1024 bytes: allocate only the 2/4/10-byte header and zero-copy write with cork()
|
|
137
174
|
if (!mask && payloadLength >= 1024 && returnParts) {
|
|
138
175
|
const header = Buffer.allocUnsafe(headerLength);
|
|
139
176
|
header[0] = (fin ? 0x80 : 0x00) | (opcode & 0x0f);
|
|
@@ -147,8 +184,8 @@ function encodeFrame(options) {
|
|
|
147
184
|
return [header, payloadBuf];
|
|
148
185
|
}
|
|
149
186
|
|
|
150
|
-
// Masked frames with large payloads (>=
|
|
151
|
-
if (mask && payloadLength >=
|
|
187
|
+
// Masked frames with large payloads (>= 16384 bytes): allocate 4-byte-aligned payload buffer + small header
|
|
188
|
+
if (mask && payloadLength >= 16384 && returnParts) {
|
|
152
189
|
const header = Buffer.allocUnsafe(headerLength + 4);
|
|
153
190
|
header[0] = (fin ? 0x80 : 0x00) | (opcode & 0x0f);
|
|
154
191
|
header[1] = secondByte;
|
|
@@ -160,13 +197,14 @@ function encodeFrame(options) {
|
|
|
160
197
|
}
|
|
161
198
|
fillRandomMask(header, headerLength);
|
|
162
199
|
const maskKey = header.subarray(headerLength, headerLength + 4);
|
|
163
|
-
const maskedPayload = Buffer.
|
|
200
|
+
const maskedPayload = Buffer.allocUnsafeSlow(payloadLength);
|
|
164
201
|
applyMask(payloadBuf, maskKey, maskedPayload, 0);
|
|
165
202
|
return [header, maskedPayload];
|
|
166
203
|
}
|
|
167
204
|
|
|
168
205
|
const maskKeyLength = mask ? 4 : 0;
|
|
169
|
-
const
|
|
206
|
+
const totalLen = headerLength + maskKeyLength + payloadLength;
|
|
207
|
+
const frame = Buffer.allocUnsafe(totalLen);
|
|
170
208
|
|
|
171
209
|
// Byte 0: FIN (bit 7), RSV1-3 (bits 6-4 = 0), Opcode (bits 3-0)
|
|
172
210
|
frame[0] = (fin ? 0x80 : 0x00) | (opcode & 0x0f);
|
|
@@ -364,7 +402,6 @@ class FrameParser {
|
|
|
364
402
|
let payload;
|
|
365
403
|
if (masked) {
|
|
366
404
|
const maskKey = chunk.subarray(offset + headerSize, payloadStart);
|
|
367
|
-
// Copy the 4 mask bytes into local primitives before in-place unmasking
|
|
368
405
|
payload = applyMask(rawPayload, maskKey, rawPayload, 0);
|
|
369
406
|
} else {
|
|
370
407
|
payload = rawPayload;
|
|
@@ -404,11 +441,12 @@ function prepareMessage(data, options = {}) {
|
|
|
404
441
|
const isBinary =
|
|
405
442
|
options.binary ?? (Buffer.isBuffer(data) || ArrayBuffer.isView(data));
|
|
406
443
|
const opcode = isBinary ? OPCODES.BINARY : OPCODES.TEXT;
|
|
407
|
-
const payload =
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
444
|
+
const payload =
|
|
445
|
+
typeof data === 'string' || Buffer.isBuffer(data)
|
|
446
|
+
? data
|
|
447
|
+
: ArrayBuffer.isView(data)
|
|
448
|
+
? Buffer.from(data.buffer, data.byteOffset, data.byteLength)
|
|
449
|
+
: String(data);
|
|
412
450
|
|
|
413
451
|
return encodeFrame({
|
|
414
452
|
opcode,
|
package/src/server.js
CHANGED
|
@@ -7,12 +7,26 @@ const { GUID, READY_STATES } = require('./constants');
|
|
|
7
7
|
const { WalterConnection } = require('./connection');
|
|
8
8
|
const { prepareMessage } = require('./frame');
|
|
9
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
|
+
}
|
|
21
|
+
|
|
10
22
|
/**
|
|
11
23
|
* Computes the RFC 6455 Sec-WebSocket-Accept header value from Sec-WebSocket-Key.
|
|
12
24
|
* @param {string} key
|
|
13
25
|
* @returns {string}
|
|
14
26
|
*/
|
|
15
27
|
function computeAcceptKey(key) {
|
|
28
|
+
const cached = ACCEPT_CACHE.get(key);
|
|
29
|
+
if (cached !== undefined) return cached;
|
|
16
30
|
return crypto
|
|
17
31
|
.createHash('sha1')
|
|
18
32
|
.update(key + GUID)
|
|
@@ -25,15 +39,8 @@ function computeAcceptKey(key) {
|
|
|
25
39
|
* @returns {boolean}
|
|
26
40
|
*/
|
|
27
41
|
function isValidSecWebSocketKey(key) {
|
|
28
|
-
if (typeof key !== 'string') return false;
|
|
29
|
-
|
|
30
|
-
if (trimmed.length !== 24) return false;
|
|
31
|
-
try {
|
|
32
|
-
const buf = Buffer.from(trimmed, 'base64');
|
|
33
|
-
return buf.length === 16;
|
|
34
|
-
} catch {
|
|
35
|
-
return false;
|
|
36
|
-
}
|
|
42
|
+
if (typeof key !== 'string' || key.length !== 24) return false;
|
|
43
|
+
return key[22] === '=' && key[23] === '=';
|
|
37
44
|
}
|
|
38
45
|
|
|
39
46
|
/**
|
|
@@ -114,10 +121,7 @@ class WalterServer extends EventEmitter {
|
|
|
114
121
|
*/
|
|
115
122
|
_attachUpgradeEvents() {
|
|
116
123
|
this._onUpgrade = (req, socket, head) => {
|
|
117
|
-
this.handleUpgrade(req, socket, head)
|
|
118
|
-
this.emit('error', err);
|
|
119
|
-
this._abortHandshake(socket, 500, 'Internal Server Error');
|
|
120
|
-
});
|
|
124
|
+
this.handleUpgrade(req, socket, head);
|
|
121
125
|
};
|
|
122
126
|
|
|
123
127
|
this._httpServer.on('upgrade', this._onUpgrade);
|
|
@@ -128,32 +132,35 @@ class WalterServer extends EventEmitter {
|
|
|
128
132
|
|
|
129
133
|
/**
|
|
130
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.
|
|
131
136
|
*
|
|
132
137
|
* @param {import('node:http').IncomingMessage} req
|
|
133
138
|
* @param {import('node:net').Socket} socket
|
|
134
139
|
* @param {Buffer} head
|
|
135
140
|
*/
|
|
136
|
-
|
|
141
|
+
handleUpgrade(req, socket, head) {
|
|
137
142
|
socket.on('error', (err) => {
|
|
138
143
|
this.emit('clientError', err, socket);
|
|
139
144
|
});
|
|
140
145
|
|
|
141
|
-
// 1. Validate HTTP method
|
|
146
|
+
// 1. Validate HTTP method
|
|
142
147
|
if (req.method !== 'GET') {
|
|
143
148
|
return this._abortHandshake(socket, 405, 'Method Not Allowed');
|
|
144
149
|
}
|
|
145
150
|
|
|
146
|
-
// 2. Optional Path matching
|
|
151
|
+
// 2. Optional Path matching (fast indexOf('?') avoids full new URL() allocation)
|
|
147
152
|
if (this.options.path) {
|
|
148
|
-
const
|
|
149
|
-
|
|
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) {
|
|
150
157
|
return this._abortHandshake(socket, 404, 'Not Found');
|
|
151
158
|
}
|
|
152
159
|
}
|
|
153
160
|
|
|
154
161
|
// 3. Validate Upgrade and Sec-WebSocket-* headers
|
|
155
162
|
const upgradeHeader = req.headers.upgrade;
|
|
156
|
-
if (!upgradeHeader || upgradeHeader.toLowerCase() !== 'websocket') {
|
|
163
|
+
if (!upgradeHeader || (upgradeHeader !== 'websocket' && upgradeHeader.toLowerCase() !== 'websocket')) {
|
|
157
164
|
return this._abortHandshake(socket, 400, 'Bad Request: Invalid Upgrade Header');
|
|
158
165
|
}
|
|
159
166
|
|
|
@@ -171,51 +178,64 @@ class WalterServer extends EventEmitter {
|
|
|
171
178
|
}
|
|
172
179
|
|
|
173
180
|
// 4. Origin verification (Security Guard standard)
|
|
174
|
-
const origin = req.headers.origin || '';
|
|
175
181
|
if (this.options.allowedOrigins && this.options.allowedOrigins.size > 0) {
|
|
182
|
+
const origin = req.headers.origin || '';
|
|
176
183
|
if (!this.options.allowedOrigins.has(origin)) {
|
|
177
184
|
return this._abortHandshake(socket, 403, 'Forbidden: Origin Not Allowed');
|
|
178
185
|
}
|
|
179
186
|
}
|
|
180
187
|
|
|
181
|
-
// 5. Custom verifyClient hook
|
|
188
|
+
// 5. Custom verifyClient hook (supports both sync and async)
|
|
182
189
|
if (typeof this.options.verifyClient === 'function') {
|
|
183
|
-
const
|
|
190
|
+
const origin = req.headers.origin || '';
|
|
191
|
+
const result = this.options.verifyClient({
|
|
184
192
|
origin,
|
|
185
193
|
req,
|
|
186
194
|
secure: Boolean(req.socket.encrypted),
|
|
187
195
|
});
|
|
188
|
-
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) {
|
|
189
210
|
return this._abortHandshake(socket, 401, 'Unauthorized');
|
|
190
211
|
}
|
|
191
212
|
}
|
|
192
213
|
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
const responseHeaders = [
|
|
196
|
-
'HTTP/1.1 101 Switching Protocols',
|
|
197
|
-
'Upgrade: websocket',
|
|
198
|
-
'Connection: Upgrade',
|
|
199
|
-
`Sec-WebSocket-Accept: ${acceptKey}`,
|
|
200
|
-
];
|
|
214
|
+
this._completeUpgrade(req, socket, head, key);
|
|
215
|
+
}
|
|
201
216
|
|
|
202
|
-
|
|
203
|
-
|
|
217
|
+
/**
|
|
218
|
+
* Completes the 101 Switching Protocols response and initializes WalterConnection synchronously.
|
|
219
|
+
*/
|
|
220
|
+
_completeUpgrade(req, socket, head, key) {
|
|
221
|
+
const acceptKey = computeAcceptKey(key);
|
|
204
222
|
let selectedProtocol = null;
|
|
223
|
+
|
|
224
|
+
const protocolsHeader = req.headers['sec-websocket-protocol'];
|
|
205
225
|
if (protocolsHeader && typeof this.options.handleProtocols === 'function') {
|
|
206
226
|
const requestedProtocols = protocolsHeader
|
|
207
227
|
.split(',')
|
|
208
228
|
.map((p) => p.trim())
|
|
209
229
|
.filter(Boolean);
|
|
210
230
|
selectedProtocol = this.options.handleProtocols(requestedProtocols, req);
|
|
211
|
-
if (selectedProtocol) {
|
|
212
|
-
responseHeaders.push(`Sec-WebSocket-Protocol: ${selectedProtocol}`);
|
|
213
|
-
}
|
|
214
231
|
}
|
|
215
232
|
|
|
216
|
-
|
|
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);
|
|
217
238
|
|
|
218
|
-
// 7. Create WalterConnection instance
|
|
219
239
|
const ws = new WalterConnection(socket, {
|
|
220
240
|
isServer: true,
|
|
221
241
|
maxPayload: this.options.maxPayload,
|
|
@@ -229,7 +249,6 @@ class WalterServer extends EventEmitter {
|
|
|
229
249
|
this.clients.delete(ws);
|
|
230
250
|
});
|
|
231
251
|
|
|
232
|
-
// If any bytes arrived after the HTTP upgrade headers in the same packet, feed them now
|
|
233
252
|
if (head && head.length > 0) {
|
|
234
253
|
ws._onSocketData(head);
|
|
235
254
|
}
|
|
@@ -249,6 +268,7 @@ class WalterServer extends EventEmitter {
|
|
|
249
268
|
this.rooms.set(roomName, roomSet);
|
|
250
269
|
}
|
|
251
270
|
roomSet.add(ws);
|
|
271
|
+
if (!ws.rooms) ws.rooms = new Set();
|
|
252
272
|
ws.rooms.add(roomName);
|
|
253
273
|
}
|
|
254
274
|
|
|
@@ -265,7 +285,7 @@ class WalterServer extends EventEmitter {
|
|
|
265
285
|
this.rooms.delete(roomName);
|
|
266
286
|
}
|
|
267
287
|
}
|
|
268
|
-
ws.rooms.delete(roomName);
|
|
288
|
+
if (ws.rooms) ws.rooms.delete(roomName);
|
|
269
289
|
}
|
|
270
290
|
|
|
271
291
|
/**
|
|
@@ -322,7 +342,7 @@ class WalterServer extends EventEmitter {
|
|
|
322
342
|
if (maxBackpressure > 0 && client.socket.writableLength > maxBackpressure) {
|
|
323
343
|
continue;
|
|
324
344
|
}
|
|
325
|
-
client.
|
|
345
|
+
client._writeCorked(preEncodedFrame);
|
|
326
346
|
}
|
|
327
347
|
}
|
|
328
348
|
}
|
|
@@ -346,7 +366,7 @@ class WalterServer extends EventEmitter {
|
|
|
346
366
|
if (maxBackpressure > 0 && client.socket.writableLength > maxBackpressure) {
|
|
347
367
|
continue;
|
|
348
368
|
}
|
|
349
|
-
client.
|
|
369
|
+
client._writeCorked(preEncodedFrame);
|
|
350
370
|
}
|
|
351
371
|
}
|
|
352
372
|
}
|
|
@@ -439,4 +459,6 @@ module.exports = {
|
|
|
439
459
|
WalterServer,
|
|
440
460
|
computeAcceptKey,
|
|
441
461
|
isValidSecWebSocketKey,
|
|
462
|
+
CLIENT_KEY_POOL,
|
|
463
|
+
ACCEPT_CACHE,
|
|
442
464
|
};
|