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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "walter-ws",
3
- "version": "1.0.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",
@@ -24,6 +24,7 @@
24
24
  ],
25
25
  "scripts": {
26
26
  "start": "node examples/server.js",
27
+ "live": "node examples/live-crypto.js",
27
28
  "test": "node --test test/walter-ws.test.js",
28
29
  "bench": "node benchmark/vs.js"
29
30
  },
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
  /**
@@ -34,20 +26,53 @@ class WalterClient extends EventEmitter {
34
26
  * @param {string|string[]} [options.protocols] - Optional subprotocol(s)
35
27
  * @param {number} [options.maxPayload=1048576] - Max allowed incoming frame/message payload size in bytes
36
28
  * @param {number} [options.handshakeTimeout=10000] - Handshake timeout in ms
29
+ * @param {boolean} [options.autoReconnect=false] - Automatically reconnect on unexpected disconnect
30
+ * @param {number} [options.reconnectInterval=1000] - Initial reconnect delay in ms
31
+ * @param {number} [options.maxReconnectInterval=30000] - Maximum backoff delay in ms
32
+ * @param {number} [options.maxReconnectAttempts=Infinity] - Max reconnect attempts
33
+ * @param {boolean} [options.offlineQueue=false] - Queue outgoing messages while connecting/reconnecting
37
34
  */
38
35
  constructor(url, options = {}) {
39
36
  super();
40
37
 
41
- this.url = typeof url === 'string' ? new URL(url) : url;
42
- if (this.url.protocol !== 'ws:' && this.url.protocol !== 'wss:') {
43
- 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;
44
64
  }
45
65
 
46
66
  this.options = {
47
- headers: options.headers || {},
67
+ headers: options.headers || null,
48
68
  protocols: options.protocols || null,
49
69
  maxPayload: options.maxPayload ?? 1024 * 1024,
50
70
  handshakeTimeout: options.handshakeTimeout ?? 10000,
71
+ autoReconnect: options.autoReconnect ?? false,
72
+ reconnectInterval: options.reconnectInterval ?? 1000,
73
+ maxReconnectInterval: options.maxReconnectInterval ?? 30000,
74
+ maxReconnectAttempts: options.maxReconnectAttempts ?? Infinity,
75
+ offlineQueue: options.offlineQueue ?? false,
51
76
  };
52
77
 
53
78
  this.readyState = READY_STATES.CONNECTING;
@@ -55,90 +80,179 @@ class WalterClient extends EventEmitter {
55
80
  this._connection = null;
56
81
  this._req = null;
57
82
 
83
+ this._explicitClose = false;
84
+ this._reconnectAttempts = 0;
85
+ this._reconnectTimer = null;
86
+ /** @type {Array<{ data: any, options: any, callback: any }>} */
87
+ this._sendQueue = [];
88
+
89
+ // W3C callback properties
90
+ this.onopen = null;
91
+ this.onmessage = null;
92
+ this.onclose = null;
93
+ this.onerror = null;
94
+
58
95
  this._connect();
59
96
  }
60
97
 
61
98
  /**
62
- * 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.
63
101
  */
64
102
  _connect() {
65
- const isSecure = this.url.protocol === 'wss:';
66
- const transport = isSecure ? https : http;
67
- const key = generateSecWebSocketKey();
68
- const expectedAccept = computeAcceptKey(key);
69
-
70
- const headers = {
71
- ...this.options.headers,
72
- Upgrade: 'websocket',
73
- Connection: 'Upgrade',
74
- 'Sec-WebSocket-Key': key,
75
- 'Sec-WebSocket-Version': '13',
76
- };
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`;
77
118
 
78
119
  if (this.options.protocols) {
79
120
  const protoList = Array.isArray(this.options.protocols)
80
121
  ? this.options.protocols.join(', ')
81
122
  : String(this.options.protocols);
82
- headers['Sec-WebSocket-Protocol'] = protoList;
123
+ reqLines += `Sec-WebSocket-Protocol: ${protoList}\r\n`;
83
124
  }
84
125
 
85
- const reqOptions = {
86
- protocol: isSecure ? 'https:' : 'http:',
87
- hostname: this.url.hostname,
88
- port: this.url.port || (isSecure ? 443 : 80),
89
- path: `${this.url.pathname}${this.url.search}`,
90
- method: 'GET',
91
- headers,
92
- agent: false,
93
- timeout: this.options.handshakeTimeout,
126
+ if (this.options.headers) {
127
+ for (const [k, v] of Object.entries(this.options.headers)) {
128
+ reqLines += `${k}: ${v}\r\n`;
129
+ }
130
+ }
131
+
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
+ }
158
+
159
+ const onHandshakeError = (err) => {
160
+ if (handshakeDone) return;
161
+ handshakeDone = true;
162
+ if (this.readyState !== READY_STATES.CLOSED) {
163
+ this.readyState = READY_STATES.CLOSED;
164
+ if (this.listenerCount('error') > 0) {
165
+ this.emit('error', err);
166
+ }
167
+ if (typeof this.onerror === 'function') {
168
+ this.onerror({ error: err, message: err.message, target: this });
169
+ }
170
+ this._handleDisconnect(CLOSE_CODES.ABNORMAL_CLOSURE, err.message);
171
+ }
94
172
  };
95
173
 
96
- const req = transport.request(reqOptions);
97
- this._req = req;
174
+ socket.once('error', onHandshakeError);
98
175
 
99
- req.on('timeout', () => {
100
- req.destroy(new Error('WebSocket opening handshake timed out'));
101
- });
176
+ // Queue handshake HTTP request immediately; Node buffers and flushes on connect
177
+ socket.write(reqLines);
102
178
 
103
- req.on('error', (err) => {
104
- if (this.readyState !== READY_STATES.CLOSED) {
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}`);
105
199
  this.readyState = READY_STATES.CLOSED;
106
- this.emit('error', err);
107
- this.emit('close', CLOSE_CODES.ABNORMAL_CLOSURE, err.message);
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;
208
+ }
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
+ }
108
224
  }
109
- });
110
-
111
- req.on('response', (res) => {
112
- const err = new Error(`Unexpected server response: ${res.statusCode}`);
113
- this.readyState = READY_STATES.CLOSED;
114
- res.resume();
115
- this.emit('error', err);
116
- this.emit('close', CLOSE_CODES.ABNORMAL_CLOSURE, err.message);
117
- });
118
-
119
- req.on('upgrade', (res, socket, head) => {
120
- const acceptHeader = res.headers['sec-websocket-accept'];
225
+
121
226
  if (acceptHeader !== expectedAccept) {
122
227
  socket.destroy();
123
228
  const err = new Error(
124
229
  `Invalid Sec-WebSocket-Accept header: expected ${expectedAccept}, got ${acceptHeader}`
125
230
  );
126
231
  this.readyState = READY_STATES.CLOSED;
127
- this.emit('error', err);
128
- this.emit('close', CLOSE_CODES.PROTOCOL_ERROR, err.message);
232
+ if (this.listenerCount('error') > 0) {
233
+ this.emit('error', err);
234
+ }
235
+ if (typeof this.onerror === 'function') {
236
+ this.onerror({ error: err, message: err.message, target: this });
237
+ }
238
+ this._handleDisconnect(CLOSE_CODES.PROTOCOL_ERROR, err.message);
129
239
  return;
130
240
  }
131
241
 
132
242
  this._connection = new WalterConnection(socket, {
133
- isServer: false, // Client masks outgoing frames and expects unmasked server frames
243
+ isServer: false,
134
244
  maxPayload: this.options.maxPayload,
135
245
  });
136
246
 
137
247
  this.readyState = READY_STATES.OPEN;
138
- this.protocol = res.headers['sec-websocket-protocol'] || null;
248
+ this._reconnectAttempts = 0;
249
+ this.protocol = protocolHeader;
139
250
 
140
251
  this._connection.on('message', (data, isBinary) => {
141
252
  this.emit('message', data, isBinary);
253
+ if (typeof this.onmessage === 'function') {
254
+ this.onmessage({ data, isBinary, target: this });
255
+ }
142
256
  });
143
257
 
144
258
  this._connection.on('ping', (data) => {
@@ -150,32 +264,92 @@ class WalterClient extends EventEmitter {
150
264
  });
151
265
 
152
266
  this._connection.on('error', (err) => {
153
- this.emit('error', err);
267
+ if (this.listenerCount('error') > 0) {
268
+ this.emit('error', err);
269
+ }
270
+ if (typeof this.onerror === 'function') {
271
+ this.onerror({ error: err, message: err.message, target: this });
272
+ }
154
273
  });
155
274
 
156
275
  this._connection.on('close', (code, reason) => {
157
276
  this.readyState = READY_STATES.CLOSED;
158
- this.emit('close', code, reason);
277
+ this._handleDisconnect(code, reason);
159
278
  });
160
279
 
161
280
  this.emit('open');
281
+ if (typeof this.onopen === 'function') {
282
+ this.onopen({ target: this });
283
+ }
162
284
 
163
- if (head && head.length > 0) {
285
+ this._flushOfflineQueue();
286
+
287
+ if (head.length > 0) {
164
288
  this._connection._onSocketData(head);
165
289
  }
166
- });
290
+ };
167
291
 
168
- req.end();
292
+ socket.on('data', onHandshakeData);
293
+ }
294
+
295
+ /**
296
+ * Handles disconnection and schedules automatic reconnect if enabled.
297
+ * @param {number} code
298
+ * @param {string} reason
299
+ */
300
+ _handleDisconnect(code, reason) {
301
+ this.emit('close', code, reason);
302
+ if (typeof this.onclose === 'function') {
303
+ this.onclose({ code, reason, target: this });
304
+ }
305
+
306
+ if (
307
+ this.options.autoReconnect &&
308
+ !this._explicitClose &&
309
+ this._reconnectAttempts < this.options.maxReconnectAttempts
310
+ ) {
311
+ const attempt = this._reconnectAttempts++;
312
+ const delay = Math.min(
313
+ this.options.reconnectInterval * Math.pow(1.5, attempt),
314
+ this.options.maxReconnectInterval
315
+ );
316
+ this.emit('reconnecting', attempt + 1, delay);
317
+ this._reconnectTimer = setTimeout(() => {
318
+ this.readyState = READY_STATES.CONNECTING;
319
+ this._connect();
320
+ }, delay);
321
+ this._reconnectTimer.unref?.();
322
+ }
323
+ }
324
+
325
+ /**
326
+ * Flushes any messages queued while the client was connecting/reconnecting.
327
+ */
328
+ _flushOfflineQueue() {
329
+ if (this._sendQueue.length === 0) return;
330
+ const queue = this._sendQueue;
331
+ this._sendQueue = [];
332
+ for (const item of queue) {
333
+ if (this.readyState === READY_STATES.OPEN && this._connection) {
334
+ this._connection.send(item.data, item.options, item.callback);
335
+ }
336
+ }
169
337
  }
170
338
 
171
339
  /**
172
340
  * Sends a text or binary message to the server.
341
+ * If `offlineQueue` is true and the connection is not yet OPEN, queues the message automatically.
342
+ *
173
343
  * @param {string|Buffer|Uint8Array} data
174
344
  * @param {object} [options]
175
345
  * @param {Function} [callback]
176
346
  */
177
347
  send(data, options, callback) {
178
348
  if (!this._connection || this.readyState !== READY_STATES.OPEN) {
349
+ if (this.options.offlineQueue && !this._explicitClose) {
350
+ this._sendQueue.push({ data, options, callback });
351
+ return;
352
+ }
179
353
  throw new Error(`WebSocket is not open: readyState ${this.readyState}`);
180
354
  }
181
355
  this._connection.send(data, options, callback);
@@ -187,10 +361,7 @@ class WalterClient extends EventEmitter {
187
361
  * @param {Function} [callback]
188
362
  */
189
363
  sendJSON(obj, callback) {
190
- if (!this._connection || this.readyState !== READY_STATES.OPEN) {
191
- throw new Error(`WebSocket is not open: readyState ${this.readyState}`);
192
- }
193
- this._connection.sendJSON(obj, callback);
364
+ this.send(JSON.stringify(obj), { binary: false }, callback);
194
365
  }
195
366
 
196
367
  /**
@@ -214,11 +385,17 @@ class WalterClient extends EventEmitter {
214
385
  }
215
386
 
216
387
  /**
217
- * Initiates a clean closing handshake.
388
+ * Initiates a clean closing handshake and stops any auto-reconnect timer.
218
389
  * @param {number} [code=1000]
219
390
  * @param {string} [reason='']
220
391
  */
221
392
  close(code = CLOSE_CODES.NORMAL_CLOSURE, reason = '') {
393
+ this._explicitClose = true;
394
+ if (this._reconnectTimer) {
395
+ clearTimeout(this._reconnectTimer);
396
+ this._reconnectTimer = null;
397
+ }
398
+
222
399
  if (this.readyState === READY_STATES.CLOSED || this.readyState === READY_STATES.CLOSING) {
223
400
  return;
224
401
  }
@@ -230,10 +407,53 @@ class WalterClient extends EventEmitter {
230
407
  }
231
408
  }
232
409
 
410
+ /**
411
+ * W3C EventTarget compatibility: addEventListener
412
+ * @param {string} type
413
+ * @param {Function} listener
414
+ * @param {object|boolean} [options]
415
+ */
416
+ addEventListener(type, listener, options) {
417
+ if (typeof listener !== 'function') return;
418
+ const once = typeof options === 'object' && options !== null && options.once;
419
+ const wrapped = (arg1, arg2) => {
420
+ if (type === 'message') {
421
+ listener({ data: arg1, isBinary: arg2, target: this });
422
+ } else if (type === 'close') {
423
+ listener({ code: arg1, reason: arg2, target: this });
424
+ } else if (type === 'error') {
425
+ listener({ error: arg1, message: arg1?.message, target: this });
426
+ } else {
427
+ listener({ target: this });
428
+ }
429
+ };
430
+ listener._walterWrapped = wrapped;
431
+ if (once) {
432
+ this.once(type, wrapped);
433
+ } else {
434
+ this.on(type, wrapped);
435
+ }
436
+ }
437
+
438
+ /**
439
+ * W3C EventTarget compatibility: removeEventListener
440
+ * @param {string} type
441
+ * @param {Function} listener
442
+ */
443
+ removeEventListener(type, listener) {
444
+ if (!listener) return;
445
+ this.removeListener(type, listener._walterWrapped || listener);
446
+ }
447
+
233
448
  /**
234
449
  * Immediately terminates the underlying socket connection.
235
450
  */
236
451
  terminate() {
452
+ this._explicitClose = true;
453
+ if (this._reconnectTimer) {
454
+ clearTimeout(this._reconnectTimer);
455
+ this._reconnectTimer = null;
456
+ }
237
457
  this.readyState = READY_STATES.CLOSED;
238
458
  if (this._connection) {
239
459
  this._connection.terminate();