walter-ws 1.1.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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "walter-ws",
3
- "version": "1.1.0",
3
+ "version": "1.2.0",
4
4
  "description": "Ultra-fast zero-dependency RFC 6455 WebSocket Server & Client implementation in pure Node.js",
5
5
  "main": "./src/index.js",
6
6
  "module": "./src/index.mjs",
package/src/client.js CHANGED
@@ -1,26 +1,18 @@
1
1
  'use strict';
2
2
 
3
- const http = require('node:http');
4
- const https = require('node:https');
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 { computeAcceptKey } = require('./server');
8
+ const { CLIENT_KEY_POOL, ACCEPT_CACHE } = require('./server');
10
9
 
11
- const KEY_POOL_SIZE = 4096;
12
- const keyPool = Buffer.allocUnsafe(KEY_POOL_SIZE);
13
- crypto.randomFillSync(keyPool);
14
- let keyPoolOffset = 0;
10
+ let keyPoolIdx = 0;
15
11
 
16
- function generateSecWebSocketKey() {
17
- if (keyPoolOffset + 16 > KEY_POOL_SIZE) {
18
- crypto.randomFillSync(keyPool);
19
- keyPoolOffset = 0;
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,13 +35,36 @@ class WalterClient extends EventEmitter {
43
35
  constructor(url, options = {}) {
44
36
  super();
45
37
 
46
- this.url = typeof url === 'string' ? new URL(url) : url;
47
- if (this.url.protocol !== 'ws:' && this.url.protocol !== 'wss:') {
48
- throw new Error(`Invalid WebSocket URL protocol: ${this.url.protocol}`);
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
69
  maxPayload: options.maxPayload ?? 1024 * 1024,
55
70
  handshakeTimeout: options.handshakeTimeout ?? 10000,
@@ -81,48 +96,69 @@ class WalterClient extends EventEmitter {
81
96
  }
82
97
 
83
98
  /**
84
- * Initiates the HTTP Upgrade handshake with the remote server.
99
+ * Initiates the HTTP Upgrade handshake directly over a raw net.Socket / tls.TLSSocket
100
+ * to bypass Node's heavy http.ClientRequest wrapper.
85
101
  */
86
102
  _connect() {
87
- const isSecure = this.url.protocol === 'wss:';
88
- const transport = isSecure ? https : http;
89
- const key = generateSecWebSocketKey();
90
- const expectedAccept = computeAcceptKey(key);
91
-
92
- const headers = {
93
- ...this.options.headers,
94
- Upgrade: 'websocket',
95
- Connection: 'Upgrade',
96
- 'Sec-WebSocket-Key': key,
97
- 'Sec-WebSocket-Version': '13',
98
- };
103
+ const isSecure = this._isSecure;
104
+ const { key, expectedAccept } = nextClientHandshakePair();
105
+
106
+ const hostHeader =
107
+ (isSecure && this._port === 443) || (!isSecure && this._port === 80)
108
+ ? this._hostname
109
+ : `${this._hostname}:${this._port}`;
110
+
111
+ let reqLines =
112
+ `GET ${this._path} HTTP/1.1\r\n` +
113
+ `Host: ${hostHeader}\r\n` +
114
+ `Upgrade: websocket\r\n` +
115
+ `Connection: Upgrade\r\n` +
116
+ `Sec-WebSocket-Key: ${key}\r\n` +
117
+ `Sec-WebSocket-Version: 13\r\n`;
99
118
 
100
119
  if (this.options.protocols) {
101
120
  const protoList = Array.isArray(this.options.protocols)
102
121
  ? this.options.protocols.join(', ')
103
122
  : String(this.options.protocols);
104
- headers['Sec-WebSocket-Protocol'] = protoList;
123
+ reqLines += `Sec-WebSocket-Protocol: ${protoList}\r\n`;
105
124
  }
106
125
 
107
- const reqOptions = {
108
- protocol: isSecure ? 'https:' : 'http:',
109
- hostname: this.url.hostname,
110
- port: this.url.port || (isSecure ? 443 : 80),
111
- path: `${this.url.pathname}${this.url.search}`,
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;
126
+ if (this.options.headers) {
127
+ for (const [k, v] of Object.entries(this.options.headers)) {
128
+ reqLines += `${k}: ${v}\r\n`;
129
+ }
130
+ }
120
131
 
121
- req.on('timeout', () => {
122
- req.destroy(new Error('WebSocket opening handshake timed out'));
123
- });
132
+ reqLines += '\r\n';
133
+
134
+ const socket = isSecure
135
+ ? tls.connect({
136
+ host: this._hostname,
137
+ port: this._port,
138
+ servername: this._hostname,
139
+ })
140
+ : net.connect({
141
+ host: this._hostname,
142
+ port: this._port,
143
+ });
144
+
145
+ socket.setNoDelay(true);
146
+ this._req = socket;
147
+
148
+ let handshakeDone = false;
149
+ let headerBuf = Buffer.alloc(0);
150
+
151
+ if (this.options.handshakeTimeout > 0) {
152
+ socket.setTimeout(this.options.handshakeTimeout, () => {
153
+ if (!handshakeDone) {
154
+ socket.destroy(new Error('WebSocket opening handshake timed out'));
155
+ }
156
+ });
157
+ }
124
158
 
125
- req.on('error', (err) => {
159
+ const onHandshakeError = (err) => {
160
+ if (handshakeDone) return;
161
+ handshakeDone = true;
126
162
  if (this.readyState !== READY_STATES.CLOSED) {
127
163
  this.readyState = READY_STATES.CLOSED;
128
164
  if (this.listenerCount('error') > 0) {
@@ -133,23 +169,60 @@ class WalterClient extends EventEmitter {
133
169
  }
134
170
  this._handleDisconnect(CLOSE_CODES.ABNORMAL_CLOSURE, err.message);
135
171
  }
136
- });
137
-
138
- req.on('response', (res) => {
139
- const err = new Error(`Unexpected server response: ${res.statusCode}`);
140
- this.readyState = READY_STATES.CLOSED;
141
- res.resume();
142
- if (this.listenerCount('error') > 0) {
143
- this.emit('error', err);
172
+ };
173
+
174
+ socket.once('error', onHandshakeError);
175
+
176
+ // Queue handshake HTTP request immediately; Node buffers and flushes on connect
177
+ socket.write(reqLines);
178
+
179
+ const onHandshakeData = (chunk) => {
180
+ headerBuf = headerBuf.length === 0 ? chunk : Buffer.concat([headerBuf, chunk]);
181
+ const headerEnd = headerBuf.indexOf('\r\n\r\n');
182
+ if (headerEnd === -1) return;
183
+
184
+ socket.removeListener('data', onHandshakeData);
185
+ socket.removeListener('error', onHandshakeError);
186
+ socket.setTimeout(0);
187
+ handshakeDone = true;
188
+
189
+ const rawHeaderStr = headerBuf.subarray(0, headerEnd).toString('latin1');
190
+ const head = headerBuf.subarray(headerEnd + 4);
191
+ const lines = rawHeaderStr.split('\r\n');
192
+ const statusLine = lines[0] || '';
193
+
194
+ if (!statusLine.startsWith('HTTP/1.1 101')) {
195
+ const match = statusLine.match(/HTTP\/1\.\d\s+(\d+)/);
196
+ const statusCode = match ? match[1] : statusLine;
197
+ socket.destroy();
198
+ const err = new Error(`Unexpected server response: ${statusCode}`);
199
+ this.readyState = READY_STATES.CLOSED;
200
+ if (this.listenerCount('error') > 0) {
201
+ this.emit('error', err);
202
+ }
203
+ if (typeof this.onerror === 'function') {
204
+ this.onerror({ error: err, message: err.message, target: this });
205
+ }
206
+ this._handleDisconnect(CLOSE_CODES.ABNORMAL_CLOSURE, err.message);
207
+ return;
144
208
  }
145
- if (typeof this.onerror === 'function') {
146
- this.onerror({ error: err, message: err.message, target: this });
209
+
210
+ let acceptHeader = '';
211
+ let protocolHeader = null;
212
+
213
+ for (let i = 1; i < lines.length; i++) {
214
+ const line = lines[i];
215
+ const colon = line.indexOf(':');
216
+ if (colon === -1) continue;
217
+ const hName = line.slice(0, colon).trim().toLowerCase();
218
+ const hVal = line.slice(colon + 1).trim();
219
+ if (hName === 'sec-websocket-accept') {
220
+ acceptHeader = hVal;
221
+ } else if (hName === 'sec-websocket-protocol') {
222
+ protocolHeader = hVal;
223
+ }
147
224
  }
148
- this._handleDisconnect(CLOSE_CODES.ABNORMAL_CLOSURE, err.message);
149
- });
150
225
 
151
- req.on('upgrade', (res, socket, head) => {
152
- const acceptHeader = res.headers['sec-websocket-accept'];
153
226
  if (acceptHeader !== expectedAccept) {
154
227
  socket.destroy();
155
228
  const err = new Error(
@@ -167,13 +240,13 @@ class WalterClient extends EventEmitter {
167
240
  }
168
241
 
169
242
  this._connection = new WalterConnection(socket, {
170
- isServer: false, // Client masks outgoing frames and expects unmasked server frames
243
+ isServer: false,
171
244
  maxPayload: this.options.maxPayload,
172
245
  });
173
246
 
174
247
  this.readyState = READY_STATES.OPEN;
175
248
  this._reconnectAttempts = 0;
176
- this.protocol = res.headers['sec-websocket-protocol'] || null;
249
+ this.protocol = protocolHeader;
177
250
 
178
251
  this._connection.on('message', (data, isBinary) => {
179
252
  this.emit('message', data, isBinary);
@@ -211,12 +284,12 @@ class WalterClient extends EventEmitter {
211
284
 
212
285
  this._flushOfflineQueue();
213
286
 
214
- if (head && head.length > 0) {
287
+ if (head.length > 0) {
215
288
  this._connection._onSocketData(head);
216
289
  }
217
- });
290
+ };
218
291
 
219
- req.end();
292
+ socket.on('data', onHandshakeData);
220
293
  }
221
294
 
222
295
  /**
package/src/connection.js CHANGED
@@ -79,8 +79,8 @@ class WalterConnection extends EventEmitter {
79
79
  this._fragmentsLength = 0;
80
80
  this._fragmentOpcode = null;
81
81
 
82
- // Room membership (O(1) Set) and fast corked batch queue
83
- this.rooms = new Set();
82
+ // Room membership (lazy Set) and fast corked batch queue
83
+ this.rooms = null;
84
84
  this._server = options.server || null;
85
85
  this._corkScheduled = false;
86
86
 
@@ -98,6 +98,7 @@ class WalterConnection extends EventEmitter {
98
98
  * @returns {this}
99
99
  */
100
100
  join(roomName) {
101
+ if (!this.rooms) this.rooms = new Set();
101
102
  if (this._server) {
102
103
  this._server.joinRoom(roomName, this);
103
104
  } else {
@@ -112,6 +113,7 @@ class WalterConnection extends EventEmitter {
112
113
  * @returns {this}
113
114
  */
114
115
  leave(roomName) {
116
+ if (!this.rooms) return this;
115
117
  if (this._server) {
116
118
  this._server.leaveRoom(roomName, this);
117
119
  } else {
@@ -124,6 +126,7 @@ class WalterConnection extends EventEmitter {
124
126
  * Leaves all joined rooms.
125
127
  */
126
128
  leaveAllRooms() {
129
+ if (!this.rooms || this.rooms.size === 0) return;
127
130
  if (this._server) {
128
131
  for (const room of this.rooms) {
129
132
  this._server.leaveRoom(room, this);
@@ -172,6 +175,10 @@ class WalterConnection extends EventEmitter {
172
175
  _bindSocketEvents() {
173
176
  this.socket.setNoDelay(true);
174
177
 
178
+ if (this.socket.listenerCount('data') > 0) {
179
+ // Do not disturb existing listeners if any
180
+ }
181
+
175
182
  this.socket.on('data', (chunk) => {
176
183
  this._onSocketData(chunk);
177
184
  });
@@ -219,9 +226,23 @@ class WalterConnection extends EventEmitter {
219
226
  return;
220
227
  }
221
228
 
222
- for (const frame of frames) {
229
+ const len = frames.length;
230
+ if (len === 0) return;
231
+
232
+ if (len > 1 && !this._corkScheduled && this.readyState === READY_STATES.OPEN) {
233
+ this._corkScheduled = true;
234
+ this.socket.cork();
235
+ queueMicrotask(() => {
236
+ this._corkScheduled = false;
237
+ if (!this.socket.destroyed) {
238
+ this.socket.uncork();
239
+ }
240
+ });
241
+ }
242
+
243
+ for (let i = 0; i < len; i++) {
223
244
  try {
224
- this._processFrame(frame);
245
+ this._processFrame(frames[i]);
225
246
  } catch (err) {
226
247
  this._handleProtocolError(err);
227
248
  return;
@@ -413,11 +434,12 @@ class WalterConnection extends EventEmitter {
413
434
  const isBinary =
414
435
  options.binary ?? (Buffer.isBuffer(data) || ArrayBuffer.isView(data));
415
436
  const opcode = isBinary ? OPCODES.BINARY : OPCODES.TEXT;
416
- const payload = Buffer.isBuffer(data)
417
- ? data
418
- : ArrayBuffer.isView(data)
419
- ? Buffer.from(data.buffer, data.byteOffset, data.byteLength)
420
- : Buffer.from(String(data), 'utf8');
437
+ const payload =
438
+ typeof data === 'string' || Buffer.isBuffer(data)
439
+ ? data
440
+ : ArrayBuffer.isView(data)
441
+ ? Buffer.from(data.buffer, data.byteOffset, data.byteLength)
442
+ : String(data);
421
443
 
422
444
  const frame = encodeFrame({
423
445
  opcode,
@@ -428,10 +450,15 @@ class WalterConnection extends EventEmitter {
428
450
  });
429
451
 
430
452
  if (Array.isArray(frame)) {
431
- this.socket.cork();
432
- this.socket.write(frame[0]);
433
- this.socket.write(frame[1], callback);
434
- this.socket.uncork();
453
+ if (this._corkScheduled) {
454
+ this.socket.write(frame[0]);
455
+ this.socket.write(frame[1], callback);
456
+ } else {
457
+ this.socket.cork();
458
+ this.socket.write(frame[0]);
459
+ this.socket.write(frame[1], callback);
460
+ this.socket.uncork();
461
+ }
435
462
  } else if (options.batch) {
436
463
  this._writeCorked(frame, callback);
437
464
  } else {
@@ -447,12 +474,10 @@ class WalterConnection extends EventEmitter {
447
474
  sendFrame(preEncodedFrame, callback) {
448
475
  if (this.readyState !== READY_STATES.OPEN) return;
449
476
  if (Array.isArray(preEncodedFrame)) {
450
- this.socket.cork();
451
- this.socket.write(preEncodedFrame[0]);
452
- this.socket.write(preEncodedFrame[1], callback);
453
- this.socket.uncork();
477
+ this._writeCorked(preEncodedFrame[0]);
478
+ this._writeCorked(preEncodedFrame[1], callback);
454
479
  } else {
455
- this.socket.write(preEncodedFrame, callback);
480
+ this._writeCorked(preEncodedFrame, callback);
456
481
  }
457
482
  }
458
483
 
@@ -478,7 +503,7 @@ class WalterConnection extends EventEmitter {
478
503
  fin: true,
479
504
  mask: !this.isServer,
480
505
  });
481
- this.socket.write(frame, callback);
506
+ this._writeCorked(frame, callback);
482
507
  }
483
508
 
484
509
  /**
@@ -494,7 +519,7 @@ class WalterConnection extends EventEmitter {
494
519
  fin: true,
495
520
  mask: !this.isServer,
496
521
  });
497
- this.socket.write(frame, callback);
522
+ this._writeCorked(frame, callback);
498
523
  }
499
524
 
500
525
  /**
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
- // Use 32-bit typed array operations when buffers are 4-byte aligned for maximum throughput
61
- const srcByteOffset = src.byteOffset;
62
- const destByteOffset = dest.byteOffset + destOffset;
63
- if (len >= 32 && (srcByteOffset & 3) === 0 && (destByteOffset & 3) === 0) {
64
- const u32Count = len >>> 2;
65
- const src32 = new Uint32Array(src.buffer, srcByteOffset, u32Count);
66
- const dest32 = new Uint32Array(dest.buffer, destByteOffset, u32Count);
67
- // Little-endian 32-bit mask representation
68
- const mask32 = (k0 | (k1 << 8) | (k2 << 16) | (k3 << 24)) >>> 0;
69
- for (let j = 0; j < u32Count; j++) {
70
- dest32[j] = src32[j] ^ mask32;
71
- }
72
- i = u32Count << 2;
73
- } else {
74
- const end4 = len & ~3;
75
- while (i < end4) {
76
- dest[destOffset + i] = src[i] ^ k0;
77
- dest[destOffset + i + 1] = src[i + 1] ^ k1;
78
- dest[destOffset + i + 2] = src[i + 2] ^ k2;
79
- dest[destOffset + i + 3] = src[i + 3] ^ k3;
80
- i += 4;
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
- const payloadBuf = Buffer.isBuffer(payload) ? payload : Buffer.from(String(payload), 'utf8');
111
- const payloadLength = payloadBuf.length;
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 large payloads (>= 1024 bytes): allocate only the small header
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 (>= 4096 bytes): allocate 8/14-byte header + masked copy
151
- if (mask && payloadLength >= 4096 && returnParts) {
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.allocUnsafe(payloadLength);
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 frame = Buffer.allocUnsafe(headerLength + maskKeyLength + payloadLength);
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 = Buffer.isBuffer(data)
408
- ? data
409
- : ArrayBuffer.isView(data)
410
- ? Buffer.from(data.buffer, data.byteOffset, data.byteLength)
411
- : Buffer.from(String(data), 'utf8');
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
- const trimmed = key.trim();
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).catch((err) => {
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
- async handleUpgrade(req, socket, head) {
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 and version
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 reqUrl = new URL(req.url || '/', `http://${req.headers.host || 'localhost'}`);
149
- if (reqUrl.pathname !== this.options.path) {
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 isAllowed = await this.options.verifyClient({
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 (!isAllowed) {
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
- // 6. Send 101 Switching Protocols response
194
- const acceptKey = computeAcceptKey(key.trim());
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
- // Subprotocol negotiation if requested
203
- const protocolsHeader = req.headers['sec-websocket-protocol'];
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
- socket.write(responseHeaders.join('\r\n') + '\r\n\r\n');
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.socket.write(preEncodedFrame);
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.socket.write(preEncodedFrame);
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
  };