walter-ws 0.0.0-stage → 1.0.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.
@@ -0,0 +1,470 @@
1
+ 'use strict';
2
+
3
+ const { EventEmitter } = require('node:events');
4
+ const bufferModule = require('node:buffer');
5
+ const { TextDecoder } = require('node:util');
6
+ const {
7
+ READY_STATES,
8
+ OPCODES,
9
+ CLOSE_CODES,
10
+ isValidCloseCode,
11
+ } = require('./constants');
12
+ const {
13
+ WebSocketProtocolError,
14
+ encodeFrame,
15
+ FrameParser,
16
+ } = require('./frame');
17
+
18
+ let nextConnectionId = 1;
19
+
20
+ const utf8Decoder = new TextDecoder('utf-8', { fatal: true });
21
+ const isUtf8 = bufferModule.isUtf8;
22
+
23
+ /**
24
+ * Validates that a Buffer contains valid UTF-8 encoded text and returns the decoded string.
25
+ * Throws WebSocketProtocolError with CLOSE_CODES.INVALID_FRAME_PAYLOAD_DATA (1007) if invalid.
26
+ *
27
+ * @param {Buffer} buffer
28
+ * @returns {string}
29
+ */
30
+ function decodeUTF8Strict(buffer) {
31
+ if (typeof isUtf8 === 'function') {
32
+ if (!isUtf8(buffer)) {
33
+ throw new WebSocketProtocolError(
34
+ 'Invalid UTF-8 sequence in text frame',
35
+ CLOSE_CODES.INVALID_FRAME_PAYLOAD_DATA
36
+ );
37
+ }
38
+ return buffer.toString('utf8');
39
+ }
40
+ try {
41
+ return utf8Decoder.decode(buffer);
42
+ } catch {
43
+ throw new WebSocketProtocolError(
44
+ 'Invalid UTF-8 sequence in text frame',
45
+ CLOSE_CODES.INVALID_FRAME_PAYLOAD_DATA
46
+ );
47
+ }
48
+ }
49
+
50
+ /**
51
+ * Represents a single RFC 6455 WebSocket connection wrapping a raw net.Socket / tls.TLSSocket.
52
+ */
53
+ class WalterConnection extends EventEmitter {
54
+ /**
55
+ * @param {import('node:net').Socket} socket
56
+ * @param {object} [options]
57
+ * @param {boolean} [options.isServer=true] - True if server-side connection, false if client-side
58
+ * @param {number} [options.maxPayload=1048576] - Maximum allowed payload size in bytes (1MB default)
59
+ * @param {import('node:http').IncomingMessage} [options.request] - Initial HTTP upgrade request
60
+ */
61
+ constructor(socket, options = {}) {
62
+ super();
63
+
64
+ this.id = nextConnectionId++;
65
+ this.socket = socket;
66
+ this.isServer = options.isServer ?? true;
67
+ this.maxPayload = options.maxPayload ?? 1024 * 1024;
68
+ this.request = options.request || null;
69
+ this.readyState = READY_STATES.OPEN;
70
+ this.isAlive = true;
71
+
72
+ this._closeCode = CLOSE_CODES.NO_STATUS_RECEIVED;
73
+ this._closeReason = '';
74
+ this._closeFrameSent = false;
75
+ this._closeFrameReceived = false;
76
+
77
+ // Fragmentation state
78
+ this._fragments = [];
79
+ this._fragmentsLength = 0;
80
+ this._fragmentOpcode = null;
81
+
82
+ this._parser = new FrameParser({
83
+ maxPayload: this.maxPayload,
84
+ requireMask: this.isServer, // Server requires client frames to be masked; Client requires unmasked frames
85
+ });
86
+
87
+ this._bindSocketEvents();
88
+ }
89
+
90
+ /**
91
+ * Attaches data, error, and close listeners to the underlying TCP socket.
92
+ */
93
+ _bindSocketEvents() {
94
+ this.socket.setNoDelay(true);
95
+
96
+ this.socket.on('data', (chunk) => {
97
+ this._onSocketData(chunk);
98
+ });
99
+
100
+ this.socket.on('error', (err) => {
101
+ if (this.listenerCount('error') > 0) {
102
+ this.emit('error', err);
103
+ }
104
+ });
105
+
106
+ this.socket.on('end', () => {
107
+ if (this.readyState !== READY_STATES.CLOSED) {
108
+ this.socket.end();
109
+ }
110
+ });
111
+
112
+ this.socket.on('close', () => {
113
+ this._fragments = [];
114
+ this._fragmentsLength = 0;
115
+ this._fragmentOpcode = null;
116
+
117
+ if (this.readyState !== READY_STATES.CLOSED) {
118
+ this.readyState = READY_STATES.CLOSED;
119
+ const code = this._closeFrameReceived
120
+ ? this._closeCode
121
+ : CLOSE_CODES.ABNORMAL_CLOSURE;
122
+ this.emit('close', code, this._closeReason);
123
+ }
124
+ });
125
+ }
126
+
127
+ /**
128
+ * Feeds incoming TCP chunks into FrameParser and processes decoded frames.
129
+ * @param {Buffer} chunk
130
+ */
131
+ _onSocketData(chunk) {
132
+ if (this.readyState === READY_STATES.CLOSED) return;
133
+
134
+ let frames;
135
+ try {
136
+ frames = this._parser.feed(chunk);
137
+ } catch (err) {
138
+ this._handleProtocolError(err);
139
+ return;
140
+ }
141
+
142
+ for (const frame of frames) {
143
+ try {
144
+ this._processFrame(frame);
145
+ } catch (err) {
146
+ this._handleProtocolError(err);
147
+ return;
148
+ }
149
+ }
150
+ }
151
+
152
+ /**
153
+ * Processes a single parsed RFC 6455 frame.
154
+ * @param {{ fin: boolean, opcode: number, masked: boolean, payload: Buffer }} frame
155
+ */
156
+ _processFrame(frame) {
157
+ const { fin, opcode, payload } = frame;
158
+
159
+ // Handle Control Frames (may be interjected in the middle of a fragmented message)
160
+ if ((opcode & 0x08) !== 0) {
161
+ if (opcode === OPCODES.PING) {
162
+ this.emit('ping', payload);
163
+ if (this.readyState === READY_STATES.OPEN) {
164
+ // Copy payload if it's a subarray of the parser's shared receive buffer
165
+ const pongPayload = this.isServer ? payload : Buffer.from(payload);
166
+ this.pong(pongPayload);
167
+ }
168
+ return;
169
+ }
170
+
171
+ if (opcode === OPCODES.PONG) {
172
+ this.isAlive = true;
173
+ this.emit('pong', payload);
174
+ return;
175
+ }
176
+
177
+ if (opcode === OPCODES.CLOSE) {
178
+ this._handleCloseFrame(payload);
179
+ return;
180
+ }
181
+ }
182
+
183
+ // Handle Data Frames & Fragmentation
184
+ if (opcode === OPCODES.CONTINUATION) {
185
+ if (this._fragmentOpcode === null) {
186
+ throw new WebSocketProtocolError(
187
+ 'Received CONTINUATION frame without an active fragmented message',
188
+ CLOSE_CODES.PROTOCOL_ERROR
189
+ );
190
+ }
191
+
192
+ this._fragmentsLength += payload.length;
193
+ if (this.maxPayload > 0 && this._fragmentsLength > this.maxPayload) {
194
+ throw new WebSocketProtocolError(
195
+ `Fragmented message exceeds maxPayload (${this.maxPayload} bytes)`,
196
+ CLOSE_CODES.MESSAGE_TOO_BIG
197
+ );
198
+ }
199
+
200
+ this._fragments.push(payload);
201
+
202
+ if (fin) {
203
+ const fullPayload = Buffer.concat(this._fragments, this._fragmentsLength);
204
+ const completedOpcode = this._fragmentOpcode;
205
+ this._fragments = [];
206
+ this._fragmentsLength = 0;
207
+ this._fragmentOpcode = null;
208
+ this._deliverDataMessage(completedOpcode, fullPayload);
209
+ }
210
+ return;
211
+ }
212
+
213
+ if (opcode === OPCODES.TEXT || opcode === OPCODES.BINARY) {
214
+ if (this._fragmentOpcode !== null) {
215
+ throw new WebSocketProtocolError(
216
+ 'Received new data frame before previous fragmented message finished',
217
+ CLOSE_CODES.PROTOCOL_ERROR
218
+ );
219
+ }
220
+
221
+ if (!fin) {
222
+ this._fragmentOpcode = opcode;
223
+ this._fragments = [payload];
224
+ this._fragmentsLength = payload.length;
225
+ } else {
226
+ this._deliverDataMessage(opcode, payload);
227
+ }
228
+ }
229
+ }
230
+
231
+ /**
232
+ * Emits a complete data message (Text or Binary) to listeners.
233
+ * @param {number} opcode
234
+ * @param {Buffer} payload
235
+ */
236
+ _deliverDataMessage(opcode, payload) {
237
+ if (opcode === OPCODES.TEXT) {
238
+ const text = decodeUTF8Strict(payload);
239
+ this.emit('message', text, false);
240
+ } else if (opcode === OPCODES.BINARY) {
241
+ this.emit('message', payload, true);
242
+ }
243
+ }
244
+
245
+ /**
246
+ * Handles incoming CLOSE (0x8) control frame.
247
+ * @param {Buffer} payload
248
+ */
249
+ _handleCloseFrame(payload) {
250
+ if (payload.length === 1) {
251
+ throw new WebSocketProtocolError(
252
+ 'Close frame payload cannot be 1 byte',
253
+ CLOSE_CODES.PROTOCOL_ERROR
254
+ );
255
+ }
256
+
257
+ let code = CLOSE_CODES.NO_STATUS_RECEIVED;
258
+ let reason = '';
259
+
260
+ if (payload.length >= 2) {
261
+ code = payload.readUInt16BE(0);
262
+ if (!isValidCloseCode(code)) {
263
+ throw new WebSocketProtocolError(
264
+ `Invalid close status code: ${code}`,
265
+ CLOSE_CODES.PROTOCOL_ERROR
266
+ );
267
+ }
268
+ const reasonBuf = payload.subarray(2);
269
+ reason = decodeUTF8Strict(reasonBuf);
270
+ }
271
+
272
+ this._closeFrameReceived = true;
273
+ this._closeCode = code;
274
+ this._closeReason = reason;
275
+
276
+ if (this.readyState === READY_STATES.OPEN) {
277
+ this.readyState = READY_STATES.CLOSING;
278
+ // Echo back close frame per RFC 6455 Section 5.5.1
279
+ const echoCode = isValidCloseCode(code) ? code : CLOSE_CODES.NORMAL_CLOSURE;
280
+ this._sendCloseFrame(echoCode, reason, () => {
281
+ this.socket.end();
282
+ });
283
+ } else if (this.readyState === READY_STATES.CLOSING) {
284
+ // Both sides have exchanged Close frames; close underlying TCP socket
285
+ this.socket.end();
286
+ }
287
+ }
288
+
289
+ /**
290
+ * Handles protocol violations by sending an appropriate close frame and terminating the connection.
291
+ * @param {Error} err
292
+ */
293
+ _handleProtocolError(err) {
294
+ const closeCode =
295
+ err instanceof WebSocketProtocolError
296
+ ? err.closeCode
297
+ : CLOSE_CODES.PROTOCOL_ERROR;
298
+
299
+ if (this.listenerCount('error') > 0) {
300
+ this.emit('error', err);
301
+ }
302
+
303
+ if (this.readyState === READY_STATES.OPEN) {
304
+ this.readyState = READY_STATES.CLOSING;
305
+ this._sendCloseFrame(closeCode, err.message.slice(0, 100), () => {
306
+ this.socket.end();
307
+ });
308
+ } else {
309
+ this.socket.destroy();
310
+ }
311
+ }
312
+
313
+ /**
314
+ * Sends a text or binary message over the WebSocket connection.
315
+ *
316
+ * @param {string|Buffer|Uint8Array} data
317
+ * @param {object} [options]
318
+ * @param {boolean} [options.binary] - Force binary frame
319
+ * @param {Function} [callback]
320
+ */
321
+ send(data, options = {}, callback) {
322
+ if (typeof options === 'function') {
323
+ callback = options;
324
+ options = {};
325
+ }
326
+
327
+ if (this.readyState !== READY_STATES.OPEN) {
328
+ const err = new Error(`WebSocket is not open: readyState ${this.readyState}`);
329
+ if (callback) return callback(err);
330
+ throw err;
331
+ }
332
+
333
+ const isBinary =
334
+ options.binary ?? (Buffer.isBuffer(data) || ArrayBuffer.isView(data));
335
+ const opcode = isBinary ? OPCODES.BINARY : OPCODES.TEXT;
336
+ const payload = Buffer.isBuffer(data)
337
+ ? data
338
+ : ArrayBuffer.isView(data)
339
+ ? Buffer.from(data.buffer, data.byteOffset, data.byteLength)
340
+ : Buffer.from(String(data), 'utf8');
341
+
342
+ const frame = encodeFrame({
343
+ opcode,
344
+ payload,
345
+ fin: true,
346
+ mask: !this.isServer, // Clients must mask; Servers must not mask
347
+ returnParts: true,
348
+ });
349
+
350
+ if (Array.isArray(frame)) {
351
+ this.socket.cork();
352
+ this.socket.write(frame[0]);
353
+ this.socket.write(frame[1], callback);
354
+ this.socket.uncork();
355
+ } else {
356
+ this.socket.write(frame, callback);
357
+ }
358
+ }
359
+
360
+ /**
361
+ * Helper to serialize and send an object as JSON text.
362
+ * @param {any} obj
363
+ * @param {Function} [callback]
364
+ */
365
+ sendJSON(obj, callback) {
366
+ this.send(JSON.stringify(obj), { binary: false }, callback);
367
+ }
368
+
369
+ /**
370
+ * Sends a Ping control frame.
371
+ * @param {Buffer|string} [data]
372
+ * @param {Function} [callback]
373
+ */
374
+ ping(data = Buffer.alloc(0), callback) {
375
+ if (this.readyState !== READY_STATES.OPEN) return;
376
+ const frame = encodeFrame({
377
+ opcode: OPCODES.PING,
378
+ payload: data,
379
+ fin: true,
380
+ mask: !this.isServer,
381
+ });
382
+ this.socket.write(frame, callback);
383
+ }
384
+
385
+ /**
386
+ * Sends a Pong control frame.
387
+ * @param {Buffer|string} [data]
388
+ * @param {Function} [callback]
389
+ */
390
+ pong(data = Buffer.alloc(0), callback) {
391
+ if (this.readyState !== READY_STATES.OPEN) return;
392
+ const frame = encodeFrame({
393
+ opcode: OPCODES.PONG,
394
+ payload: data,
395
+ fin: true,
396
+ mask: !this.isServer,
397
+ });
398
+ this.socket.write(frame, callback);
399
+ }
400
+
401
+ /**
402
+ * Initiates a clean closing handshake.
403
+ * @param {number} [code=1000]
404
+ * @param {string} [reason='']
405
+ */
406
+ close(code = CLOSE_CODES.NORMAL_CLOSURE, reason = '') {
407
+ if (this.readyState === READY_STATES.CLOSED || this.readyState === READY_STATES.CLOSING) {
408
+ return;
409
+ }
410
+
411
+ if (!isValidCloseCode(code)) {
412
+ throw new Error(`Invalid WebSocket close code: ${code}`);
413
+ }
414
+
415
+ this.readyState = READY_STATES.CLOSING;
416
+ this._closeCode = code;
417
+ this._closeReason = reason;
418
+
419
+ this._sendCloseFrame(code, reason, () => {
420
+ // Force close TCP socket if peer doesn't reply within 3 seconds
421
+ const timer = setTimeout(() => {
422
+ if (this.readyState !== READY_STATES.CLOSED) {
423
+ this.socket.destroy();
424
+ }
425
+ }, 3000);
426
+ timer.unref?.();
427
+ });
428
+ }
429
+
430
+ /**
431
+ * Internal helper to build and send the Close frame.
432
+ * @param {number} code
433
+ * @param {string} reason
434
+ * @param {Function} [callback]
435
+ */
436
+ _sendCloseFrame(code, reason = '', callback) {
437
+ if (this._closeFrameSent) {
438
+ if (callback) callback();
439
+ return;
440
+ }
441
+ this._closeFrameSent = true;
442
+
443
+ const reasonBuf = Buffer.from(String(reason), 'utf8').subarray(0, 123);
444
+ const payload = Buffer.allocUnsafe(2 + reasonBuf.length);
445
+ payload.writeUInt16BE(code, 0);
446
+ reasonBuf.copy(payload, 2);
447
+
448
+ const frame = encodeFrame({
449
+ opcode: OPCODES.CLOSE,
450
+ payload,
451
+ fin: true,
452
+ mask: !this.isServer,
453
+ });
454
+
455
+ this.socket.write(frame, callback);
456
+ }
457
+
458
+ /**
459
+ * Immediately destroys the underlying TCP connection without a closing handshake.
460
+ */
461
+ terminate() {
462
+ this.readyState = READY_STATES.CLOSED;
463
+ this.socket.destroy();
464
+ }
465
+ }
466
+
467
+ module.exports = {
468
+ WalterConnection,
469
+ decodeUTF8Strict,
470
+ };
@@ -0,0 +1,67 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * RFC 6455 Magic GUID used for Sec-WebSocket-Accept calculation
5
+ */
6
+ const GUID = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11';
7
+
8
+ /**
9
+ * WebSocket Connection Ready States
10
+ */
11
+ const READY_STATES = Object.freeze({
12
+ CONNECTING: 0,
13
+ OPEN: 1,
14
+ CLOSING: 2,
15
+ CLOSED: 3,
16
+ });
17
+
18
+ /**
19
+ * RFC 6455 Frame Opcodes
20
+ */
21
+ const OPCODES = Object.freeze({
22
+ CONTINUATION: 0x0,
23
+ TEXT: 0x1,
24
+ BINARY: 0x2,
25
+ CLOSE: 0x8,
26
+ PING: 0x9,
27
+ PONG: 0xa,
28
+ });
29
+
30
+ /**
31
+ * RFC 6455 Standard Close Status Codes
32
+ */
33
+ const CLOSE_CODES = Object.freeze({
34
+ NORMAL_CLOSURE: 1000,
35
+ GOING_AWAY: 1001,
36
+ PROTOCOL_ERROR: 1002,
37
+ UNSUPPORTED_DATA: 1003,
38
+ NO_STATUS_RECEIVED: 1005,
39
+ ABNORMAL_CLOSURE: 1006,
40
+ INVALID_FRAME_PAYLOAD_DATA: 1007,
41
+ POLICY_VIOLATION: 1008,
42
+ MESSAGE_TOO_BIG: 1009,
43
+ MANDATORY_EXTENSION: 1010,
44
+ INTERNAL_ERROR: 1011,
45
+ });
46
+
47
+ /**
48
+ * Validate if a status code is allowed to be sent in a Close frame per RFC 6455 Section 7.4
49
+ * @param {number} code
50
+ * @returns {boolean}
51
+ */
52
+ function isValidCloseCode(code) {
53
+ if (typeof code !== 'number' || !Number.isInteger(code)) return false;
54
+ if (code >= 1000 && code <= 1014) {
55
+ // 1004 (Reserved), 1005 (No Status), 1006 (Abnormal) MUST NOT be set in a Close control frame
56
+ return code !== 1004 && code !== 1005 && code !== 1006;
57
+ }
58
+ return code >= 3000 && code <= 4999;
59
+ }
60
+
61
+ module.exports = {
62
+ GUID,
63
+ READY_STATES,
64
+ OPCODES,
65
+ CLOSE_CODES,
66
+ isValidCloseCode,
67
+ };