@orkestrel/websocket 0.0.4 → 0.0.6
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/dist/src/server/index.cjs +159 -58
- package/dist/src/server/index.cjs.map +1 -1
- package/dist/src/server/index.d.cts +72 -9
- package/dist/src/server/index.d.ts +72 -9
- package/dist/src/server/index.js +155 -59
- package/dist/src/server/index.js.map +1 -1
- package/package.json +15 -14
|
@@ -17,6 +17,8 @@ var WEBSOCKET_VERSION = "13";
|
|
|
17
17
|
var WEBSOCKET_OPCODE_TEXT = 1;
|
|
18
18
|
/** Binary frame opcode — a raw byte payload (RFC 6455 §5.6). */
|
|
19
19
|
var WEBSOCKET_OPCODE_BINARY = 2;
|
|
20
|
+
/** Continuation frame opcode — the next fragment of an open data message (RFC 6455 §5.4). */
|
|
21
|
+
var WEBSOCKET_OPCODE_CONTINUATION = 0;
|
|
20
22
|
/** Close frame opcode — a control frame ending the connection (RFC 6455 §5.5.1). */
|
|
21
23
|
var WEBSOCKET_OPCODE_CLOSE = 8;
|
|
22
24
|
/** Ping frame opcode — a control frame the peer must answer with a pong (RFC 6455 §5.5.2). */
|
|
@@ -49,6 +51,8 @@ var WEBSOCKET_CLOSE_TIMEOUT_MS = 3e4;
|
|
|
49
51
|
var WEBSOCKET_FAIL_TIMEOUT_MS = 1e3;
|
|
50
52
|
/** The maximum control-frame payload length in bytes (RFC 6455 §5.5). */
|
|
51
53
|
var WEBSOCKET_CONTROL_MAXLEN = 125;
|
|
54
|
+
/** The maximum UTF-8 close-reason length after the two-byte status code. */
|
|
55
|
+
var WEBSOCKET_CLOSE_REASON_MAXLEN = 123;
|
|
52
56
|
//#endregion
|
|
53
57
|
//#region src/server/helpers.ts
|
|
54
58
|
/**
|
|
@@ -66,6 +70,46 @@ function computeWebSocketAccept(key) {
|
|
|
66
70
|
return (0, node_crypto.createHash)("sha1").update(key + WEBSOCKET_GUID).digest("base64");
|
|
67
71
|
}
|
|
68
72
|
/**
|
|
73
|
+
* Whether a value is a canonical RFC 6455 `Sec-WebSocket-Key`.
|
|
74
|
+
*
|
|
75
|
+
* @remarks
|
|
76
|
+
* A valid key is exactly 16 random bytes encoded as 24 characters of base64, ending
|
|
77
|
+
* in `==` (RFC 6455 §4.1). This predicate is suitable at an HTTP upgrade boundary:
|
|
78
|
+
* malformed or non-canonical encodings return `false`; nothing is thrown.
|
|
79
|
+
*
|
|
80
|
+
* @param key - The proposed `Sec-WebSocket-Key` header value
|
|
81
|
+
* @returns `true` when `key` is the canonical base64 encoding of 16 bytes
|
|
82
|
+
*
|
|
83
|
+
* @example
|
|
84
|
+
* ```ts
|
|
85
|
+
* const key = request.headers['sec-websocket-key']
|
|
86
|
+
* if (typeof key !== 'string' || !isWebSocketKey(key)) socket.destroy()
|
|
87
|
+
* ```
|
|
88
|
+
*/
|
|
89
|
+
function isWebSocketKey(key) {
|
|
90
|
+
if (!/^[A-Za-z0-9+/]{22}==$/.test(key)) return false;
|
|
91
|
+
return Buffer.from(key, "base64").length === 16;
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* Whether a value is one valid WebSocket subprotocol token.
|
|
95
|
+
*
|
|
96
|
+
* @remarks
|
|
97
|
+
* Subprotocols use the HTTP `token` grammar. Whitespace, separators, commas, and
|
|
98
|
+
* control characters are rejected, preventing an untrusted value from injecting a
|
|
99
|
+
* second handshake header.
|
|
100
|
+
*
|
|
101
|
+
* @param protocol - The negotiated subprotocol to validate
|
|
102
|
+
* @returns `true` when `protocol` is one non-empty HTTP token
|
|
103
|
+
*
|
|
104
|
+
* @example
|
|
105
|
+
* ```ts
|
|
106
|
+
* if (!isWebSocketProtocol(protocol)) throw new RangeError('invalid protocol')
|
|
107
|
+
* ```
|
|
108
|
+
*/
|
|
109
|
+
function isWebSocketProtocol(protocol) {
|
|
110
|
+
return /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/.test(protocol);
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
69
113
|
* Decode a single RFC 6455 frame from the front of a buffer.
|
|
70
114
|
*
|
|
71
115
|
* @remarks
|
|
@@ -85,8 +129,8 @@ function computeWebSocketAccept(key) {
|
|
|
85
129
|
*/
|
|
86
130
|
function parseWebSocketFrame(buffer) {
|
|
87
131
|
if (buffer.length < 2) return void 0;
|
|
88
|
-
const firstByte = buffer
|
|
89
|
-
const secondByte = buffer
|
|
132
|
+
const firstByte = buffer.readUInt8(0);
|
|
133
|
+
const secondByte = buffer.readUInt8(1);
|
|
90
134
|
const fin = (firstByte & 128) !== 0;
|
|
91
135
|
const rsv = (firstByte & 112) >> 4;
|
|
92
136
|
const opcode = firstByte & 15;
|
|
@@ -113,7 +157,7 @@ function parseWebSocketFrame(buffer) {
|
|
|
113
157
|
if (buffer.length < offset + length) return void 0;
|
|
114
158
|
const payload = Buffer.alloc(length);
|
|
115
159
|
buffer.copy(payload, 0, offset, offset + length);
|
|
116
|
-
if (mask !== void 0) for (let index = 0; index < length; index += 1) payload[index] = (
|
|
160
|
+
if (mask !== void 0) for (let index = 0; index < length; index += 1) payload[index] = payload.readUInt8(index) ^ mask.readUInt8(index % 4);
|
|
117
161
|
return {
|
|
118
162
|
fin,
|
|
119
163
|
opcode,
|
|
@@ -145,7 +189,7 @@ function parseWebSocketFrame(buffer) {
|
|
|
145
189
|
*/
|
|
146
190
|
function measureWebSocketFrame(buffer) {
|
|
147
191
|
if (buffer.length < 2) return void 0;
|
|
148
|
-
let length = (
|
|
192
|
+
let length = buffer.readUInt8(1) & 127;
|
|
149
193
|
const offset = 2;
|
|
150
194
|
if (length === 126) {
|
|
151
195
|
if (buffer.length < 4) return void 0;
|
|
@@ -159,6 +203,36 @@ function measureWebSocketFrame(buffer) {
|
|
|
159
203
|
return length;
|
|
160
204
|
}
|
|
161
205
|
/**
|
|
206
|
+
* Whether the next frame uses the shortest valid RFC 6455 payload-length encoding.
|
|
207
|
+
*
|
|
208
|
+
* @remarks
|
|
209
|
+
* Returns `undefined` until the complete length prefix is buffered. The 16-bit form
|
|
210
|
+
* is canonical only for lengths at least 126; the 64-bit form only for lengths at
|
|
211
|
+
* least 65,536 and with its most-significant bit clear (RFC 6455 §5.2).
|
|
212
|
+
*
|
|
213
|
+
* @param buffer - The accumulation buffer containing the next frame header
|
|
214
|
+
* @returns Its canonicality, or `undefined` while the length prefix is incomplete
|
|
215
|
+
*
|
|
216
|
+
* @example
|
|
217
|
+
* ```ts
|
|
218
|
+
* if (isWebSocketFrameCanonical(buffer) === false) fail(WEBSOCKET_CLOSE_PROTOCOL)
|
|
219
|
+
* ```
|
|
220
|
+
*/
|
|
221
|
+
function isWebSocketFrameCanonical(buffer) {
|
|
222
|
+
if (buffer.length < 2) return void 0;
|
|
223
|
+
const lengthCode = buffer.readUInt8(1) & 127;
|
|
224
|
+
if (lengthCode < 126) return true;
|
|
225
|
+
if (lengthCode === 126) {
|
|
226
|
+
if (buffer.length < 4) return void 0;
|
|
227
|
+
return buffer.readUInt16BE(2) >= 126;
|
|
228
|
+
}
|
|
229
|
+
if (buffer.length < 10) return void 0;
|
|
230
|
+
const high = buffer.readUInt32BE(2);
|
|
231
|
+
const low = buffer.readUInt32BE(6);
|
|
232
|
+
if ((high & 2147483648) !== 0) return false;
|
|
233
|
+
return high > 0 || low >= 65536;
|
|
234
|
+
}
|
|
235
|
+
/**
|
|
162
236
|
* Decode a byte sequence as strict UTF-8, or signal it is malformed.
|
|
163
237
|
*
|
|
164
238
|
* @remarks
|
|
@@ -204,6 +278,7 @@ function parseUTF8(bytes) {
|
|
|
204
278
|
* ```
|
|
205
279
|
*/
|
|
206
280
|
function isCloseCode(code) {
|
|
281
|
+
if (!Number.isInteger(code)) return false;
|
|
207
282
|
if (code >= 1e3 && code <= 1003) return true;
|
|
208
283
|
if (code >= 1007 && code <= 1014) return true;
|
|
209
284
|
if (code >= 3e3 && code <= 4999) return true;
|
|
@@ -229,6 +304,9 @@ function isCloseCode(code) {
|
|
|
229
304
|
* @returns The complete frame as wire bytes
|
|
230
305
|
*/
|
|
231
306
|
function encodeWebSocketFrame(opcode, payload, options) {
|
|
307
|
+
if (!Number.isInteger(opcode) || opcode < 0 || opcode > 15) throw new RangeError("opcode must be an integer between 0 and 15");
|
|
308
|
+
if (options?.mask !== void 0 && options.mask.length !== 4) throw new RangeError("mask must contain exactly 4 bytes");
|
|
309
|
+
if (options?.mask !== void 0 && options.masked !== true) throw new RangeError("mask requires masked: true");
|
|
232
310
|
const body = typeof payload === "string" ? Buffer.from(payload, "utf-8") : payload;
|
|
233
311
|
const length = body.length;
|
|
234
312
|
const masked = options?.masked === true;
|
|
@@ -249,7 +327,7 @@ function encodeWebSocketFrame(opcode, payload, options) {
|
|
|
249
327
|
if (mask === void 0) return Buffer.concat([header, body]);
|
|
250
328
|
mask.copy(header, header.length - 4);
|
|
251
329
|
const maskedBody = Buffer.alloc(length);
|
|
252
|
-
for (let index = 0; index < length; index += 1) maskedBody[index] = (
|
|
330
|
+
for (let index = 0; index < length; index += 1) maskedBody[index] = body.readUInt8(index) ^ mask.readUInt8(index % 4);
|
|
253
331
|
return Buffer.concat([header, maskedBody]);
|
|
254
332
|
}
|
|
255
333
|
//#endregion
|
|
@@ -270,72 +348,71 @@ function encodeWebSocketFrame(opcode, payload, options) {
|
|
|
270
348
|
* socket, emitting `close`. `send` writes a text frame, `ping` a ping, `close` a close
|
|
271
349
|
* frame; `destroy` tears down immediately. It owns a typed `#emitter` (AGENTS §13) that
|
|
272
350
|
* isolates a throwing listener and routes the error to its own `error` handler (the `error`
|
|
273
|
-
* option) — the socket never crashes.
|
|
274
|
-
*
|
|
351
|
+
* option) — the socket never crashes. An underlying socket error emits the domain
|
|
352
|
+
* `error` event and terminates the wrapper. The untyped socket `data` is narrowed to a
|
|
353
|
+
* `Buffer` with a guard, never an assertion (AGENTS §14).
|
|
275
354
|
*/
|
|
276
355
|
var NodeWebSocket = class {
|
|
277
356
|
#emitter;
|
|
278
357
|
#socket;
|
|
279
|
-
#protocol;
|
|
280
358
|
#masked;
|
|
281
359
|
#payload;
|
|
282
360
|
#timeout;
|
|
283
|
-
#requireMask;
|
|
284
361
|
#signal;
|
|
362
|
+
#dataListener;
|
|
363
|
+
#closeListener;
|
|
364
|
+
#errorListener;
|
|
365
|
+
#abortListener;
|
|
285
366
|
#buffer = Buffer.alloc(0);
|
|
286
367
|
#readyState = 0;
|
|
287
|
-
#code
|
|
288
|
-
#reason
|
|
368
|
+
#code;
|
|
369
|
+
#reason;
|
|
289
370
|
#fragments = [];
|
|
290
|
-
#messageOpcode
|
|
371
|
+
#messageOpcode;
|
|
291
372
|
#fragmentBytes = 0;
|
|
292
|
-
#closeTimer
|
|
373
|
+
#closeTimer;
|
|
293
374
|
#destroyed = false;
|
|
294
375
|
#detached = false;
|
|
295
|
-
#onData = (chunk) => {
|
|
296
|
-
if (this.#readyState === 3) return;
|
|
297
|
-
const bytes = this.#bytes(chunk);
|
|
298
|
-
if (bytes === void 0) return;
|
|
299
|
-
this.#ingest(bytes);
|
|
300
|
-
};
|
|
301
|
-
#onClose = () => {
|
|
302
|
-
this.#finish();
|
|
303
|
-
};
|
|
304
|
-
#onError = (error) => {
|
|
305
|
-
this.#emitter.emit("error", error);
|
|
306
|
-
};
|
|
307
|
-
#onDetachedError = () => void 0;
|
|
308
|
-
#onAbort = () => {
|
|
309
|
-
this.destroy();
|
|
310
|
-
};
|
|
311
376
|
constructor(options) {
|
|
377
|
+
const payload = options.payload ?? 104857600;
|
|
378
|
+
if (!Number.isSafeInteger(payload) || payload < 0) throw new RangeError("payload must be a non-negative safe integer");
|
|
379
|
+
const timeout = options.timeout ?? 3e4;
|
|
380
|
+
if (!Number.isSafeInteger(timeout) || timeout < 0) throw new RangeError("timeout must be a non-negative safe integer");
|
|
381
|
+
if (options.key !== void 0 && !isWebSocketKey(options.key)) throw new RangeError("key must be the canonical base64 encoding of 16 bytes");
|
|
382
|
+
if (options.protocol !== void 0 && !isWebSocketProtocol(options.protocol)) throw new RangeError("protocol must be a valid WebSocket subprotocol token");
|
|
383
|
+
if (options.protocol !== void 0 && options.key === void 0) throw new RangeError("protocol requires a server key");
|
|
312
384
|
this.#emitter = new _orkestrel_emitter.Emitter({
|
|
313
|
-
on: options.on,
|
|
314
|
-
error: options.error
|
|
385
|
+
...options.on === void 0 ? {} : { on: options.on },
|
|
386
|
+
...options.error === void 0 ? {} : { error: options.error }
|
|
315
387
|
});
|
|
316
388
|
this.#socket = options.socket;
|
|
317
|
-
this.#protocol = options.protocol;
|
|
318
389
|
this.#masked = options.key === void 0;
|
|
319
|
-
this.#payload =
|
|
320
|
-
this.#timeout =
|
|
321
|
-
this.#requireMask = !this.#masked;
|
|
390
|
+
this.#payload = payload;
|
|
391
|
+
this.#timeout = timeout;
|
|
322
392
|
this.#signal = options.signal;
|
|
393
|
+
this.#dataListener = this.#handleData.bind(this);
|
|
394
|
+
this.#closeListener = this.#finish.bind(this);
|
|
395
|
+
this.#errorListener = this.#handleError.bind(this);
|
|
396
|
+
this.#abortListener = this.destroy.bind(this);
|
|
323
397
|
if (options.key !== void 0) {
|
|
324
|
-
const
|
|
325
|
-
|
|
326
|
-
Upgrade: websocket
|
|
327
|
-
Connection: Upgrade
|
|
328
|
-
Sec-WebSocket-Accept: ${computeWebSocketAccept(options.key)}
|
|
398
|
+
const headers = [
|
|
399
|
+
"HTTP/1.1 101 Switching Protocols",
|
|
400
|
+
"Upgrade: websocket",
|
|
401
|
+
"Connection: Upgrade",
|
|
402
|
+
`Sec-WebSocket-Accept: ${computeWebSocketAccept(options.key)}`
|
|
403
|
+
];
|
|
404
|
+
if (options.protocol !== void 0) headers.push(`Sec-WebSocket-Protocol: ${options.protocol}`);
|
|
405
|
+
this.#socket.write(`${headers.join("\r\n")}\r\n\r\n`);
|
|
329
406
|
}
|
|
330
407
|
this.#readyState = 1;
|
|
331
|
-
this.#socket.on("data", this.#
|
|
332
|
-
this.#socket.on("close", this.#
|
|
333
|
-
this.#socket.on("error", this.#
|
|
408
|
+
this.#socket.on("data", this.#dataListener);
|
|
409
|
+
this.#socket.on("close", this.#closeListener);
|
|
410
|
+
this.#socket.on("error", this.#errorListener);
|
|
334
411
|
this.#emitter.emit("open");
|
|
335
412
|
const head = options.head;
|
|
336
413
|
if (head !== void 0 && head.length > 0) this.#ingest(head);
|
|
337
414
|
if (this.#readyState !== 3) if (this.#signal?.aborted === true) this.destroy();
|
|
338
|
-
else this.#signal?.addEventListener("abort", this.#
|
|
415
|
+
else this.#signal?.addEventListener("abort", this.#abortListener, { once: true });
|
|
339
416
|
}
|
|
340
417
|
get emitter() {
|
|
341
418
|
return this.#emitter;
|
|
@@ -355,7 +432,7 @@ Sec-WebSocket-Accept: ${computeWebSocketAccept(options.key)}\r\n` + protocol + "
|
|
|
355
432
|
close(code, reason) {
|
|
356
433
|
if (this.#readyState === 2 || this.#readyState === 3) return;
|
|
357
434
|
if (code !== void 0 && !isCloseCode(code)) throw new RangeError("invalid close code");
|
|
358
|
-
if (reason !== void 0 && Buffer.byteLength(reason, "utf-8") > 123) throw new RangeError(
|
|
435
|
+
if (reason !== void 0 && Buffer.byteLength(reason, "utf-8") > 123) throw new RangeError(`close reason exceeds 123 bytes`);
|
|
359
436
|
this.#readyState = 2;
|
|
360
437
|
this.#code = code ?? 1e3;
|
|
361
438
|
this.#reason = reason === void 0 || reason.length === 0 ? void 0 : reason;
|
|
@@ -368,7 +445,7 @@ Sec-WebSocket-Accept: ${computeWebSocketAccept(options.key)}\r\n` + protocol + "
|
|
|
368
445
|
if (this.#destroyed) return;
|
|
369
446
|
this.#destroyed = true;
|
|
370
447
|
this.#detach();
|
|
371
|
-
this.#signal?.removeEventListener("abort", this.#
|
|
448
|
+
this.#signal?.removeEventListener("abort", this.#abortListener);
|
|
372
449
|
clearTimeout(this.#closeTimer);
|
|
373
450
|
this.#closeTimer = void 0;
|
|
374
451
|
if (!this.#socket.destroyed) this.#socket.destroy();
|
|
@@ -377,6 +454,15 @@ Sec-WebSocket-Accept: ${computeWebSocketAccept(options.key)}\r\n` + protocol + "
|
|
|
377
454
|
}
|
|
378
455
|
#drain() {
|
|
379
456
|
for (;;) {
|
|
457
|
+
if (isWebSocketFrameCanonical(this.#buffer) === false) {
|
|
458
|
+
this.#fail(WEBSOCKET_CLOSE_PROTOCOL);
|
|
459
|
+
return;
|
|
460
|
+
}
|
|
461
|
+
const declared = measureWebSocketFrame(this.#buffer);
|
|
462
|
+
if (declared !== void 0 && declared > this.#payload) {
|
|
463
|
+
this.#fail(WEBSOCKET_CLOSE_TOOBIG);
|
|
464
|
+
return;
|
|
465
|
+
}
|
|
380
466
|
const frame = parseWebSocketFrame(this.#buffer);
|
|
381
467
|
if (frame === void 0) return;
|
|
382
468
|
this.#buffer = this.#buffer.subarray(frame.consumed);
|
|
@@ -389,7 +475,7 @@ Sec-WebSocket-Accept: ${computeWebSocketAccept(options.key)}\r\n` + protocol + "
|
|
|
389
475
|
this.#fail(WEBSOCKET_CLOSE_PROTOCOL);
|
|
390
476
|
return;
|
|
391
477
|
}
|
|
392
|
-
if (masked
|
|
478
|
+
if (masked === this.#masked) {
|
|
393
479
|
this.#fail(WEBSOCKET_CLOSE_PROTOCOL);
|
|
394
480
|
return;
|
|
395
481
|
}
|
|
@@ -480,10 +566,10 @@ Sec-WebSocket-Accept: ${computeWebSocketAccept(options.key)}\r\n` + protocol + "
|
|
|
480
566
|
#detach() {
|
|
481
567
|
if (this.#detached) return;
|
|
482
568
|
this.#detached = true;
|
|
483
|
-
this.#socket.off("data", this.#
|
|
484
|
-
this.#socket.off("close", this.#
|
|
485
|
-
this.#socket.off("error", this.#
|
|
486
|
-
this.#socket.on("error",
|
|
569
|
+
this.#socket.off("data", this.#dataListener);
|
|
570
|
+
this.#socket.off("close", this.#closeListener);
|
|
571
|
+
this.#socket.off("error", this.#errorListener);
|
|
572
|
+
this.#socket.on("error", () => void 0);
|
|
487
573
|
}
|
|
488
574
|
#write(opcode, payload) {
|
|
489
575
|
if (this.#socket.destroyed) return;
|
|
@@ -512,7 +598,12 @@ Sec-WebSocket-Accept: ${computeWebSocketAccept(options.key)}\r\n` + protocol + "
|
|
|
512
598
|
this.#fail(WEBSOCKET_CLOSE_PROTOCOL);
|
|
513
599
|
return false;
|
|
514
600
|
}
|
|
515
|
-
|
|
601
|
+
if (payload.length === 2) {
|
|
602
|
+
this.#code = code;
|
|
603
|
+
this.#reason = void 0;
|
|
604
|
+
return true;
|
|
605
|
+
}
|
|
606
|
+
const reason = parseUTF8(payload.subarray(2));
|
|
516
607
|
if (reason === void 0) {
|
|
517
608
|
this.#fail(WEBSOCKET_CLOSE_INVALID);
|
|
518
609
|
return false;
|
|
@@ -526,19 +617,24 @@ Sec-WebSocket-Accept: ${computeWebSocketAccept(options.key)}\r\n` + protocol + "
|
|
|
526
617
|
this.#detach();
|
|
527
618
|
clearTimeout(this.#closeTimer);
|
|
528
619
|
this.#closeTimer = void 0;
|
|
529
|
-
this.#signal?.removeEventListener("abort", this.#
|
|
620
|
+
this.#signal?.removeEventListener("abort", this.#abortListener);
|
|
530
621
|
this.#readyState = 3;
|
|
531
622
|
this.#emitter.emit("close", this.#code, this.#reason);
|
|
532
623
|
}
|
|
533
624
|
#ingest(bytes) {
|
|
534
625
|
this.#buffer = Buffer.concat([this.#buffer, bytes]);
|
|
535
|
-
const declared = measureWebSocketFrame(this.#buffer);
|
|
536
|
-
if (declared !== void 0 && declared > this.#payload) {
|
|
537
|
-
this.#fail(WEBSOCKET_CLOSE_TOOBIG);
|
|
538
|
-
return;
|
|
539
|
-
}
|
|
540
626
|
this.#drain();
|
|
541
627
|
}
|
|
628
|
+
#handleData(chunk) {
|
|
629
|
+
if (this.#readyState === 3) return;
|
|
630
|
+
const bytes = this.#bytes(chunk);
|
|
631
|
+
if (bytes === void 0) return;
|
|
632
|
+
this.#ingest(bytes);
|
|
633
|
+
}
|
|
634
|
+
#handleError(error) {
|
|
635
|
+
this.#emitter.emit("error", error);
|
|
636
|
+
this.destroy();
|
|
637
|
+
}
|
|
542
638
|
#bytes(chunk) {
|
|
543
639
|
if (Buffer.isBuffer(chunk)) return chunk;
|
|
544
640
|
if (typeof chunk === "string") return Buffer.from(chunk, "utf-8");
|
|
@@ -585,6 +681,7 @@ exports.NodeWebSocket = NodeWebSocket;
|
|
|
585
681
|
exports.WEBSOCKET_CLOSE_INVALID = WEBSOCKET_CLOSE_INVALID;
|
|
586
682
|
exports.WEBSOCKET_CLOSE_NORMAL = WEBSOCKET_CLOSE_NORMAL;
|
|
587
683
|
exports.WEBSOCKET_CLOSE_PROTOCOL = WEBSOCKET_CLOSE_PROTOCOL;
|
|
684
|
+
exports.WEBSOCKET_CLOSE_REASON_MAXLEN = WEBSOCKET_CLOSE_REASON_MAXLEN;
|
|
588
685
|
exports.WEBSOCKET_CLOSE_TIMEOUT_MS = WEBSOCKET_CLOSE_TIMEOUT_MS;
|
|
589
686
|
exports.WEBSOCKET_CLOSE_TOOBIG = WEBSOCKET_CLOSE_TOOBIG;
|
|
590
687
|
exports.WEBSOCKET_CLOSE_UNSUPPORTED = WEBSOCKET_CLOSE_UNSUPPORTED;
|
|
@@ -594,6 +691,7 @@ exports.WEBSOCKET_GUID = WEBSOCKET_GUID;
|
|
|
594
691
|
exports.WEBSOCKET_MAX_PAYLOAD = WEBSOCKET_MAX_PAYLOAD;
|
|
595
692
|
exports.WEBSOCKET_OPCODE_BINARY = WEBSOCKET_OPCODE_BINARY;
|
|
596
693
|
exports.WEBSOCKET_OPCODE_CLOSE = WEBSOCKET_OPCODE_CLOSE;
|
|
694
|
+
exports.WEBSOCKET_OPCODE_CONTINUATION = WEBSOCKET_OPCODE_CONTINUATION;
|
|
597
695
|
exports.WEBSOCKET_OPCODE_PING = WEBSOCKET_OPCODE_PING;
|
|
598
696
|
exports.WEBSOCKET_OPCODE_PONG = WEBSOCKET_OPCODE_PONG;
|
|
599
697
|
exports.WEBSOCKET_OPCODE_TEXT = WEBSOCKET_OPCODE_TEXT;
|
|
@@ -606,6 +704,9 @@ exports.computeWebSocketAccept = computeWebSocketAccept;
|
|
|
606
704
|
exports.createNodeWebSocket = createNodeWebSocket;
|
|
607
705
|
exports.encodeWebSocketFrame = encodeWebSocketFrame;
|
|
608
706
|
exports.isCloseCode = isCloseCode;
|
|
707
|
+
exports.isWebSocketFrameCanonical = isWebSocketFrameCanonical;
|
|
708
|
+
exports.isWebSocketKey = isWebSocketKey;
|
|
709
|
+
exports.isWebSocketProtocol = isWebSocketProtocol;
|
|
609
710
|
exports.measureWebSocketFrame = measureWebSocketFrame;
|
|
610
711
|
exports.parseUTF8 = parseUTF8;
|
|
611
712
|
exports.parseWebSocketFrame = parseWebSocketFrame;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["#emitter","#socket","#protocol","#masked","#payload","#timeout","#requireMask","#signal","#onData","#readyState","#bytes","#ingest","#onClose","#finish","#onError","#onDetachedError","#onAbort","#write","#code","#reason","#encodeClose","#closeTimer","#destroyed","#detach","#buffer","#dispatch","#fail","#close","#messageOpcode","#fragments","#fragmentBytes","#decodeClose","#detached","#drain"],"sources":["../../../src/server/constants.ts","../../../src/server/helpers.ts","../../../src/server/NodeWebSocket.ts","../../../src/server/factories.ts"],"sourcesContent":["import type { WebSocketReadyState } from './types.js'\n\n// The WebSocket wrapper's wire constants (AGENTS §5 constants file) — the RFC 6455\n// magic values the codec and the handshake are built on: the accept GUID, the\n// supported protocol version, the frame opcodes, the four ready states, and the\n// normal-closure status code. Every member is exported; the codec helpers and the\n// `NodeWebSocket` wrapper read them by name rather than re-spelling the bit values.\n\n/**\n * The RFC 6455 GUID concatenated to a client's `Sec-WebSocket-Key` before the SHA-1\n * hash that yields the `Sec-WebSocket-Accept` response value.\n *\n * @remarks\n * A fixed, spec-mandated constant (RFC 6455 §4.2.2) — read only by\n * {@link computeWebSocketAccept}.\n */\nexport const WEBSOCKET_GUID = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'\n\n/** The WebSocket protocol version this wrapper speaks (`Sec-WebSocket-Version: 13`). */\nexport const WEBSOCKET_VERSION = '13'\n\n/** Text frame opcode — a UTF-8 payload (RFC 6455 §5.6). */\nexport const WEBSOCKET_OPCODE_TEXT = 0x01\n\n/** Binary frame opcode — a raw byte payload (RFC 6455 §5.6). */\nexport const WEBSOCKET_OPCODE_BINARY = 0x02\n\n/** Close frame opcode — a control frame ending the connection (RFC 6455 §5.5.1). */\nexport const WEBSOCKET_OPCODE_CLOSE = 0x08\n\n/** Ping frame opcode — a control frame the peer must answer with a pong (RFC 6455 §5.5.2). */\nexport const WEBSOCKET_OPCODE_PING = 0x09\n\n/** Pong frame opcode — a control frame answering a ping (RFC 6455 §5.5.3). */\nexport const WEBSOCKET_OPCODE_PONG = 0x0a\n\n/** Ready state for a connecting WebSocket (before the handshake completes). */\nexport const WEBSOCKET_READY_CONNECTING: WebSocketReadyState = 0\n\n/** Ready state for an open WebSocket (the handshake completed; frames flow). */\nexport const WEBSOCKET_READY_OPEN: WebSocketReadyState = 1\n\n/** Ready state for a closing WebSocket (a close frame was sent or received). */\nexport const WEBSOCKET_READY_CLOSING: WebSocketReadyState = 2\n\n/** Ready state for a closed WebSocket (the socket ended). */\nexport const WEBSOCKET_READY_CLOSED: WebSocketReadyState = 3\n\n/** Normal-closure status code (RFC 6455 §7.4.1) — the default `close` code. */\nexport const WEBSOCKET_CLOSE_NORMAL = 1000\n\n/** Protocol-error status code (RFC 6455 §7.4.1) — a framing/state rule was violated. */\nexport const WEBSOCKET_CLOSE_PROTOCOL = 1002\n\n/** Unsupported-data status code (RFC 6455 §7.4.1) — the endpoint received a data type it cannot accept (e.g. binary on a text-only endpoint). */\nexport const WEBSOCKET_CLOSE_UNSUPPORTED = 1003\n\n/** Invalid-frame-payload-data status code (RFC 6455 §7.4.1) — e.g. non-UTF-8 text or an unparseable close reason. */\nexport const WEBSOCKET_CLOSE_INVALID = 1007\n\n/** Message-too-big status code (RFC 6455 §7.4.1) — a reassembled message exceeded the payload cap. */\nexport const WEBSOCKET_CLOSE_TOOBIG = 1009\n\n/** The default maximum inbound single-frame length AND reassembled-message total byte count (100 MiB — the `ws` package default). */\nexport const WEBSOCKET_MAX_PAYLOAD = 104_857_600\n\n/** The default close-handshake timeout in milliseconds — how long `close()` waits for the peer's echo before tearing the socket down. */\nexport const WEBSOCKET_CLOSE_TIMEOUT_MS = 30_000\n\n/** The post-`#fail` flush grace in milliseconds — how long a validation-breach close frame is given to flush through the socket's write buffer before the hard `destroy()` fallback fires (the normal path destroys sooner, on the `end()` flush callback). */\nexport const WEBSOCKET_FAIL_TIMEOUT_MS = 1_000\n\n/** The maximum control-frame payload length in bytes (RFC 6455 §5.5). */\nexport const WEBSOCKET_CONTROL_MAXLEN = 125\n","import type { WebSocketEncodeOptions, WebSocketFrame } from './types.js'\nimport { createHash, randomBytes } from 'node:crypto'\nimport { WEBSOCKET_GUID } from './constants.js'\n\n// The RFC 6455 codec — three pure, exported, exhaustively unit-tested functions that\n// are the entire bit-level surface of the WebSocket wrapper (AGENTS §5: the codec\n// branches are exported helpers, not hidden privates). `computeWebSocketAccept`\n// derives the handshake token; `parseWebSocketFrame` decodes ONE frame off a buffer,\n// returning `undefined` when the buffer holds an incomplete frame so the caller\n// accumulates across `data` chunks (the same streaming-decoder contract as the core\n// `SSEParser`); `encodeWebSocketFrame` is the inverse — it builds the wire bytes for a\n// frame. `parse` and `encode` are exact inverses, proven by the round-trip tests.\n//\n// Numeric byte reads are narrowed with `?? 0` rather than `!` (AGENTS §14): a read\n// past the buffer is impossible once the length guards pass, and `?? 0` keeps the\n// arithmetic total without an assertion.\n\n/**\n * Compute the `Sec-WebSocket-Accept` response value for an RFC 6455 upgrade.\n *\n * @remarks\n * The base64-encoded SHA-1 of the client's `Sec-WebSocket-Key` concatenated with the\n * fixed {@link WEBSOCKET_GUID} (RFC 6455 §4.2.2) — the proof the server understood the\n * handshake. Pure and deterministic.\n *\n * @param key - The client's `Sec-WebSocket-Key` header value\n * @returns The base64 accept token to send back as `Sec-WebSocket-Accept`\n */\nexport function computeWebSocketAccept(key: string): string {\n\treturn createHash('sha1')\n\t\t.update(key + WEBSOCKET_GUID)\n\t\t.digest('base64')\n}\n\n/**\n * Decode a single RFC 6455 frame from the front of a buffer.\n *\n * @remarks\n * Reads the FIN bit and opcode (byte 0), the mask bit and 7-bit payload length (byte\n * 1) — extended to a 16-bit length when the 7-bit field is `126`, or a 64-bit length\n * when it is `127` — the optional 4-byte mask key, then the payload, XOR-unmasking it\n * against the key when the mask bit is set (client→server frames MUST be masked, RFC\n * 6455 §5.3; an unmasked frame still decodes, leaving the payload as-is, so the caller\n * can enforce policy). Returns `undefined` the moment the buffer is too short for the\n * part it is up to (the length prefix, the mask, or the full payload) — the signal to\n * the caller to read more bytes and retry, exactly like {@link SSEParser} on a partial\n * line. `consumed` is the total bytes the frame occupied, so the caller slices the\n * remainder. Pure; never throws on a short buffer.\n *\n * @param buffer - The accumulation buffer to decode the next frame from\n * @returns The parsed {@link WebSocketFrame}, or `undefined` when the buffer is incomplete\n */\nexport function parseWebSocketFrame(buffer: Buffer): WebSocketFrame | undefined {\n\tif (buffer.length < 2) return undefined\n\n\tconst firstByte = buffer[0] ?? 0\n\tconst secondByte = buffer[1] ?? 0\n\n\tconst fin = (firstByte & 0x80) !== 0\n\tconst rsv = (firstByte & 0x70) >> 4\n\tconst opcode = firstByte & 0x0f\n\tconst masked = (secondByte & 0x80) !== 0\n\tlet length = secondByte & 0x7f\n\tlet offset = 2\n\n\tif (length === 126) {\n\t\tif (buffer.length < offset + 2) return undefined\n\t\tlength = buffer.readUInt16BE(offset)\n\t\toffset += 2\n\t} else if (length === 127) {\n\t\tif (buffer.length < offset + 8) return undefined\n\t\t// Split into two 32-bit reads — a payload past 2^53 is beyond any real frame,\n\t\t// and this keeps the arithmetic in safe-integer range.\n\t\tconst high = buffer.readUInt32BE(offset)\n\t\tconst low = buffer.readUInt32BE(offset + 4)\n\t\tlength = high * 0x1_0000_0000 + low\n\t\toffset += 8\n\t}\n\n\tlet mask: Buffer | undefined\n\tif (masked) {\n\t\tif (buffer.length < offset + 4) return undefined\n\t\tmask = buffer.subarray(offset, offset + 4)\n\t\toffset += 4\n\t}\n\n\tif (buffer.length < offset + length) return undefined\n\n\tconst payload = Buffer.alloc(length)\n\tbuffer.copy(payload, 0, offset, offset + length)\n\n\tif (mask !== undefined) {\n\t\tfor (let index = 0; index < length; index += 1) {\n\t\t\tpayload[index] = (payload[index] ?? 0) ^ (mask[index % 4] ?? 0)\n\t\t}\n\t}\n\n\treturn { fin, opcode, payload, consumed: offset + length, masked, rsv }\n}\n\n/**\n * Read the declared payload length off the front of a buffer, without buffering or\n * reading the payload itself.\n *\n * @remarks\n * Decodes only byte 1's 7-bit length field, extended by the 16-bit (`126`) or 64-bit\n * (`127`) form exactly like {@link parseWebSocketFrame} — but stops there, so a caller\n * can reject an over-cap frame the moment its length is known, before the payload\n * bytes have even arrived. Returns `undefined` until the length field itself is fully\n * buffered (mirrors the parser's incomplete-buffer contract). Pure; never throws.\n *\n * @param buffer - The accumulation buffer to read the next frame's length from\n * @returns The declared payload length, or `undefined` when the buffer is too short to know it yet\n *\n * @example\n * ```ts\n * const declared = measureWebSocketFrame(buffer)\n * if (declared !== undefined && declared > limit) fail(WEBSOCKET_CLOSE_TOOBIG)\n * ```\n */\nexport function measureWebSocketFrame(buffer: Buffer): number | undefined {\n\tif (buffer.length < 2) return undefined\n\n\tconst secondByte = buffer[1] ?? 0\n\tlet length = secondByte & 0x7f\n\tconst offset = 2\n\n\tif (length === 126) {\n\t\tif (buffer.length < offset + 2) return undefined\n\t\tlength = buffer.readUInt16BE(offset)\n\t} else if (length === 127) {\n\t\tif (buffer.length < offset + 8) return undefined\n\t\tconst high = buffer.readUInt32BE(offset)\n\t\tconst low = buffer.readUInt32BE(offset + 4)\n\t\tlength = high * 0x1_0000_0000 + low\n\t}\n\n\treturn length\n}\n\n/**\n * Decode a byte sequence as strict UTF-8, or signal it is malformed.\n *\n * @remarks\n * Wraps `TextDecoder('utf-8', { fatal: true })` in a try/catch so a malformed sequence\n * returns `undefined` instead of throwing (AGENTS §14 — a guard-adjacent coercer never\n * throws on bad input). Pure.\n *\n * @param bytes - The raw bytes to decode\n * @returns The decoded string, or `undefined` when `bytes` is not valid UTF-8\n *\n * @example\n * ```ts\n * const text = parseUTF8(payload)\n * if (text === undefined) fail(WEBSOCKET_CLOSE_INVALID)\n * ```\n */\nexport function parseUTF8(bytes: Buffer): string | undefined {\n\ttry {\n\t\treturn new TextDecoder('utf-8', { fatal: true }).decode(bytes)\n\t} catch {\n\t\treturn undefined\n\t}\n}\n\n/**\n * Whether a numeric value is a valid RFC 6455 close status code to RECEIVE (§7.4.1).\n *\n * @remarks\n * True for `1000`–`1003`, `1007`–`1014`, and the application range `3000`–`4999`; false\n * for anything below `1000`, the reserved-for-local-use-only codes `1004`–`1006` and\n * `1015`, and the unassigned `1016`–`2999` range. The `1012`–`1014` extension of the\n * strict RFC 6455 receivable set is a deliberate IANA-interop choice: those three codes\n * (Service Restart, Try Again Later, Bad Gateway) are IANA-registered in the WebSocket\n * Close Code Number Registry and accepted by the `ws` ecosystem and modern conformance\n * suites, so a peer sending one is not treated as a protocol violation. Pure predicate,\n * never throws.\n *\n * @param code - The close status code to validate\n * @returns `true` when `code` is a valid RFC 6455 close code\n *\n * @example\n * ```ts\n * if (!isCloseCode(code)) fail(WEBSOCKET_CLOSE_PROTOCOL)\n * ```\n */\nexport function isCloseCode(code: number): boolean {\n\tif (code >= 1000 && code <= 1003) return true\n\tif (code >= 1007 && code <= 1014) return true\n\tif (code >= 3000 && code <= 4999) return true\n\treturn false\n}\n\n/**\n * Encode a single RFC 6455 frame to its wire bytes — the inverse of\n * {@link parseWebSocketFrame}.\n *\n * @remarks\n * Builds a final (FIN-set) frame: byte 0 is `0x80 | opcode`; the payload length uses\n * the 7-bit form below 126, the `126` + 16-bit form below 65 536, or the `127` +\n * 64-bit form beyond; when `masked` is set the mask bit is set, a 4-byte key (supplied\n * via `options.mask`, else random) is written, and the payload is XOR-masked. Server→\n * client frames are unmasked (the default); pass `masked: true` to encode a CLIENT\n * frame (e.g. to feed the parser in a test). A `string` payload is encoded as UTF-8.\n * Returns one contiguous `Buffer` (header + payload), so the wrapper writes it with a\n * single `socket.write`. Pure.\n *\n * @param opcode - The frame opcode (a `WEBSOCKET_OPCODE_*` value)\n * @param payload - The payload, a `Buffer` or a UTF-8 `string`\n * @param options - Masking control ({@link WebSocketEncodeOptions}); defaults to unmasked\n * @returns The complete frame as wire bytes\n */\nexport function encodeWebSocketFrame(\n\topcode: number,\n\tpayload: Buffer | string,\n\toptions?: WebSocketEncodeOptions,\n): Buffer {\n\tconst body = typeof payload === 'string' ? Buffer.from(payload, 'utf-8') : payload\n\tconst length = body.length\n\tconst masked = options?.masked === true\n\tconst mask = masked ? (options?.mask ?? randomBytes(4)) : undefined\n\tconst maskBit = masked ? 0x80 : 0\n\n\t// The header size: 2 base bytes + the extended-length bytes (0 / 2 / 8) + the mask\n\t// key (0 / 4). The length prefix and the mask key write into this header.\n\tconst extended = length < 126 ? 0 : length < 65_536 ? 2 : 8\n\tconst header = Buffer.alloc(2 + extended + (mask !== undefined ? 4 : 0))\n\theader[0] = 0x80 | opcode\n\n\tif (length < 126) {\n\t\theader[1] = maskBit | length\n\t} else if (length < 65_536) {\n\t\theader[1] = maskBit | 126\n\t\theader.writeUInt16BE(length, 2)\n\t} else {\n\t\theader[1] = maskBit | 127\n\t\theader.writeUInt32BE(Math.floor(length / 0x1_0000_0000), 2)\n\t\theader.writeUInt32BE(length % 0x1_0000_0000, 6)\n\t}\n\n\tif (mask === undefined) return Buffer.concat([header, body])\n\n\tmask.copy(header, header.length - 4)\n\tconst maskedBody = Buffer.alloc(length)\n\tfor (let index = 0; index < length; index += 1) {\n\t\tmaskedBody[index] = (body[index] ?? 0) ^ (mask[index % 4] ?? 0)\n\t}\n\treturn Buffer.concat([header, maskedBody])\n}\n","import type { Duplex } from 'node:stream'\nimport type {\n\tNodeWebSocketEventMap,\n\tNodeWebSocketInterface,\n\tNodeWebSocketOptions,\n\tWebSocketReadyState,\n} from './types.js'\nimport type { EmitterInterface } from '@orkestrel/emitter'\nimport { Emitter } from '@orkestrel/emitter'\nimport {\n\tcomputeWebSocketAccept,\n\tencodeWebSocketFrame,\n\tisCloseCode,\n\tmeasureWebSocketFrame,\n\tparseUTF8,\n\tparseWebSocketFrame,\n} from './helpers.js'\nimport {\n\tWEBSOCKET_CLOSE_INVALID,\n\tWEBSOCKET_CLOSE_NORMAL,\n\tWEBSOCKET_CLOSE_PROTOCOL,\n\tWEBSOCKET_CLOSE_TIMEOUT_MS,\n\tWEBSOCKET_CLOSE_TOOBIG,\n\tWEBSOCKET_CLOSE_UNSUPPORTED,\n\tWEBSOCKET_CONTROL_MAXLEN,\n\tWEBSOCKET_FAIL_TIMEOUT_MS,\n\tWEBSOCKET_MAX_PAYLOAD,\n\tWEBSOCKET_OPCODE_BINARY,\n\tWEBSOCKET_OPCODE_CLOSE,\n\tWEBSOCKET_OPCODE_PING,\n\tWEBSOCKET_OPCODE_PONG,\n\tWEBSOCKET_OPCODE_TEXT,\n\tWEBSOCKET_READY_CLOSED,\n\tWEBSOCKET_READY_CLOSING,\n\tWEBSOCKET_READY_CONNECTING,\n\tWEBSOCKET_READY_OPEN,\n} from './constants.js'\n\n/**\n * A server-native WebSocket over a raw upgraded `node:stream` Duplex — the lean\n * wrapper around the RFC 6455 wire protocol.\n *\n * @remarks\n * Created by `createNodeWebSocket`. When given a client `key` it runs in SERVER mode —\n * it writes the `101 Switching Protocols` handshake (`computeWebSocketAccept(key)`) and\n * emits `open`; given no key it runs in CLIENT mode (no handshake, frames masked). It\n * then listens on the socket's `data`, accumulating bytes in `#buffer` and decoding\n * every complete frame with {@link parseWebSocketFrame} (slicing `consumed` and\n * re-parsing the remainder): a TEXT frame — reassembling continuation fragments across\n * `fin: false` frames — decodes to UTF-8 and emits `message`; a PING is auto-answered\n * with a PONG and emits `ping`; a PONG emits `pong`; a CLOSE is echoed and ends the\n * socket, emitting `close`. `send` writes a text frame, `ping` a ping, `close` a close\n * frame; `destroy` tears down immediately. It owns a typed `#emitter` (AGENTS §13) that\n * isolates a throwing listener and routes the error to its own `error` handler (the `error`\n * option) — the socket never crashes. The untyped socket `data` is narrowed to a `Buffer`\n * with a guard, never an assertion (AGENTS §14).\n */\nexport class NodeWebSocket implements NodeWebSocketInterface {\n\treadonly #emitter: Emitter<NodeWebSocketEventMap>\n\treadonly #socket: Duplex\n\treadonly #protocol: string | undefined\n\treadonly #masked: boolean\n\treadonly #payload: number\n\treadonly #timeout: number\n\treadonly #requireMask: boolean\n\treadonly #signal: AbortSignal | undefined\n\t#buffer: Buffer = Buffer.alloc(0)\n\t#readyState: WebSocketReadyState = WEBSOCKET_READY_CONNECTING\n\t#code: number | undefined = undefined\n\t#reason: string | undefined = undefined\n\t#fragments: Buffer[] = []\n\t#messageOpcode: number | undefined = undefined\n\t#fragmentBytes = 0\n\t#closeTimer: ReturnType<typeof setTimeout> | undefined = undefined\n\t#destroyed = false\n\t#detached = false\n\n\t// The socket listeners are bound fields so `destroy` can detach exactly these.\n\treadonly #onData = (chunk: unknown): void => {\n\t\tif (this.#readyState === WEBSOCKET_READY_CLOSED) return\n\t\tconst bytes = this.#bytes(chunk)\n\t\tif (bytes === undefined) return\n\t\tthis.#ingest(bytes)\n\t}\n\n\treadonly #onClose = (): void => {\n\t\tthis.#finish()\n\t}\n\n\treadonly #onError = (error: unknown): void => {\n\t\tthis.#emitter.emit('error', error)\n\t}\n\n\t// Keep a terminal socket safe from late peer errors after the domain listener is gone.\n\treadonly #onDetachedError = (): void => undefined\n\n\t// Bound so `#finish` / `destroy` can detach exactly this listener from `#signal`.\n\treadonly #onAbort = (): void => {\n\t\tthis.destroy()\n\t}\n\n\tconstructor(options: NodeWebSocketOptions) {\n\t\tthis.#emitter = new Emitter({ on: options.on, error: options.error })\n\t\tthis.#socket = options.socket\n\t\tthis.#protocol = options.protocol\n\t\t// Server mode is identified by a client key (it writes the handshake + sends\n\t\t// unmasked frames); without one this is a client (no handshake, masked frames).\n\t\tthis.#masked = options.key === undefined\n\t\tthis.#payload = options.payload ?? WEBSOCKET_MAX_PAYLOAD\n\t\tthis.#timeout = options.timeout ?? WEBSOCKET_CLOSE_TIMEOUT_MS\n\t\t// A server (masked === false, i.e. this instance is unmasked outbound) requires\n\t\t// masked inbound frames from the client (RFC 6455 §5.1); a client instance accepts\n\t\t// unmasked frames from the server.\n\t\tthis.#requireMask = !this.#masked\n\t\tthis.#signal = options.signal\n\n\t\tif (options.key !== undefined) {\n\t\t\tconst protocol =\n\t\t\t\tthis.#protocol === undefined ? '' : `Sec-WebSocket-Protocol: ${this.#protocol}\\r\\n`\n\t\t\tthis.#socket.write(\n\t\t\t\t'HTTP/1.1 101 Switching Protocols\\r\\n' +\n\t\t\t\t\t'Upgrade: websocket\\r\\n' +\n\t\t\t\t\t'Connection: Upgrade\\r\\n' +\n\t\t\t\t\t`Sec-WebSocket-Accept: ${computeWebSocketAccept(options.key)}\\r\\n` +\n\t\t\t\t\tprotocol +\n\t\t\t\t\t'\\r\\n',\n\t\t\t)\n\t\t}\n\n\t\tthis.#readyState = WEBSOCKET_READY_OPEN\n\t\tthis.#socket.on('data', this.#onData)\n\t\tthis.#socket.on('close', this.#onClose)\n\t\tthis.#socket.on('error', this.#onError)\n\t\tthis.#emitter.emit('open')\n\n\t\t// Replay any bytes buffered after the upgrade headers through the same ingest path\n\t\t// as `#onData`, so the pre-buffer cap check applies uniformly (AGENTS §5 dedup).\n\t\tconst head = options.head\n\t\tif (head !== undefined && head.length > 0) {\n\t\t\tthis.#ingest(head)\n\t\t}\n\n\t\t// The external cancellation seam (composes with `@orkestrel/abort` /\n\t\t// `@orkestrel/timeout`'s native AbortSignals) — wired last so an already-aborted\n\t\t// signal tears the socket down only after the rest of construction has run. The\n\t\t// head-replay above can itself synchronously terminate the socket (a complete\n\t\t// CLOSE frame or an RFC violation routes through `#fail`/`#close` -> `#finish`),\n\t\t// which flushes the close frame GRACEFULLY via `#socket.end()`. In that case skip\n\t\t// the seam entirely: forcing `destroy()` would discard that flushing frame (the\n\t\t// loss `#fail` is engineered to avoid), and there is no live socket to attach to.\n\t\tif (this.#readyState !== WEBSOCKET_READY_CLOSED) {\n\t\t\tif (this.#signal?.aborted === true) {\n\t\t\t\tthis.destroy()\n\t\t\t} else {\n\t\t\t\tthis.#signal?.addEventListener('abort', this.#onAbort, { once: true })\n\t\t\t}\n\t\t}\n\t}\n\n\tget emitter(): EmitterInterface<NodeWebSocketEventMap> {\n\t\treturn this.#emitter\n\t}\n\n\tget readyState(): WebSocketReadyState {\n\t\treturn this.#readyState\n\t}\n\n\tsend(data: string): void {\n\t\tif (this.#readyState !== WEBSOCKET_READY_OPEN) return\n\t\tthis.#write(WEBSOCKET_OPCODE_TEXT, Buffer.from(data, 'utf-8'))\n\t}\n\n\tping(data?: string): void {\n\t\tif (this.#readyState !== WEBSOCKET_READY_OPEN) return\n\t\tif (data !== undefined && Buffer.byteLength(data, 'utf-8') > WEBSOCKET_CONTROL_MAXLEN) {\n\t\t\tthrow new RangeError('ping payload exceeds 125 bytes')\n\t\t}\n\t\tthis.#write(\n\t\t\tWEBSOCKET_OPCODE_PING,\n\t\t\tdata === undefined ? Buffer.alloc(0) : Buffer.from(data, 'utf-8'),\n\t\t)\n\t}\n\n\tclose(code?: number, reason?: string): void {\n\t\tif (\n\t\t\tthis.#readyState === WEBSOCKET_READY_CLOSING ||\n\t\t\tthis.#readyState === WEBSOCKET_READY_CLOSED\n\t\t) {\n\t\t\treturn\n\t\t}\n\t\tif (code !== undefined && !isCloseCode(code)) throw new RangeError('invalid close code')\n\t\tif (reason !== undefined && Buffer.byteLength(reason, 'utf-8') > 123) {\n\t\t\tthrow new RangeError('close reason exceeds 123 bytes')\n\t\t}\n\t\tthis.#readyState = WEBSOCKET_READY_CLOSING\n\t\tthis.#code = code ?? WEBSOCKET_CLOSE_NORMAL\n\t\tthis.#reason = reason === undefined || reason.length === 0 ? undefined : reason\n\t\tthis.#write(WEBSOCKET_OPCODE_CLOSE, this.#encodeClose(this.#code, this.#reason))\n\t\t// End the writable side after the close frame; the peer's echo (or the socket\n\t\t// `close`) drives the final state transition through `#finish`.\n\t\tthis.#socket.end()\n\t\tthis.#closeTimer = setTimeout(() => this.destroy(), this.#timeout)\n\t\tthis.#closeTimer.unref()\n\t}\n\n\tdestroy(): void {\n\t\tif (this.#destroyed) return\n\t\tthis.#destroyed = true\n\t\t// Detach before destroy so a destroy-time error reaches the terminal sink.\n\t\tthis.#detach()\n\t\tthis.#signal?.removeEventListener('abort', this.#onAbort)\n\t\t// `#finish` no-ops once already CLOSED (e.g. after `#fail` armed the hard-teardown\n\t\t// fallback), so the timer is cleared here unconditionally rather than relying on it.\n\t\tclearTimeout(this.#closeTimer)\n\t\tthis.#closeTimer = undefined\n\t\tif (!this.#socket.destroyed) this.#socket.destroy()\n\t\tthis.#finish()\n\t\tthis.#emitter.destroy()\n\t}\n\n\t// Decode every complete frame currently in the buffer, dispatching each and slicing\n\t// it off; stops when a partial frame remains (parse returns `undefined`).\n\t#drain(): void {\n\t\tfor (;;) {\n\t\t\tconst frame = parseWebSocketFrame(this.#buffer)\n\t\t\tif (frame === undefined) return\n\t\t\tthis.#buffer = this.#buffer.subarray(frame.consumed)\n\t\t\tthis.#dispatch(frame.fin, frame.opcode, frame.payload, frame.masked, frame.rsv)\n\t\t\tif (this.#readyState === WEBSOCKET_READY_CLOSED) return\n\t\t}\n\t}\n\n\t// Route one decoded frame through the RFC 6455 validation gauntlet, then the\n\t// fragmentation state machine. Any validity breach funnels through `#fail`, which\n\t// closes with the specified code and tears the socket down.\n\t#dispatch(fin: boolean, opcode: number, payload: Buffer, masked: boolean, rsv: number): void {\n\t\tif (rsv !== 0) {\n\t\t\tthis.#fail(WEBSOCKET_CLOSE_PROTOCOL)\n\t\t\treturn\n\t\t}\n\t\tif (masked !== this.#requireMask) {\n\t\t\tthis.#fail(WEBSOCKET_CLOSE_PROTOCOL)\n\t\t\treturn\n\t\t}\n\n\t\tif (\n\t\t\topcode === WEBSOCKET_OPCODE_CLOSE ||\n\t\t\topcode === WEBSOCKET_OPCODE_PING ||\n\t\t\topcode === WEBSOCKET_OPCODE_PONG\n\t\t) {\n\t\t\tif (!fin || payload.length > WEBSOCKET_CONTROL_MAXLEN) {\n\t\t\t\tthis.#fail(WEBSOCKET_CLOSE_PROTOCOL)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif (opcode === WEBSOCKET_OPCODE_PING) {\n\t\t\t\tthis.#write(WEBSOCKET_OPCODE_PONG, payload)\n\t\t\t\tthis.#emitter.emit('ping')\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif (opcode === WEBSOCKET_OPCODE_PONG) {\n\t\t\t\tthis.#emitter.emit('pong')\n\t\t\t\treturn\n\t\t\t}\n\t\t\tthis.#close(payload)\n\t\t\treturn\n\t\t}\n\n\t\tif (opcode === WEBSOCKET_OPCODE_TEXT || opcode === WEBSOCKET_OPCODE_BINARY) {\n\t\t\tif (this.#messageOpcode !== undefined) {\n\t\t\t\tthis.#fail(WEBSOCKET_CLOSE_PROTOCOL)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tthis.#messageOpcode = opcode\n\t\t} else if (opcode === 0x00) {\n\t\t\tif (this.#messageOpcode === undefined) {\n\t\t\t\tthis.#fail(WEBSOCKET_CLOSE_PROTOCOL)\n\t\t\t\treturn\n\t\t\t}\n\t\t} else {\n\t\t\t// Reserved data (0x3–0x7) or reserved control (0xB–0xF) opcodes.\n\t\t\tthis.#fail(WEBSOCKET_CLOSE_PROTOCOL)\n\t\t\treturn\n\t\t}\n\n\t\tthis.#fragments.push(payload)\n\t\tthis.#fragmentBytes += payload.length\n\t\tif (this.#fragmentBytes > this.#payload) {\n\t\t\tthis.#fail(WEBSOCKET_CLOSE_TOOBIG)\n\t\t\treturn\n\t\t}\n\t\tif (!fin) return\n\n\t\tif (this.#messageOpcode === WEBSOCKET_OPCODE_BINARY) {\n\t\t\tthis.#fail(WEBSOCKET_CLOSE_UNSUPPORTED)\n\t\t\treturn\n\t\t}\n\t\tconst text = parseUTF8(Buffer.concat(this.#fragments))\n\t\tif (text === undefined) {\n\t\t\tthis.#fail(WEBSOCKET_CLOSE_INVALID)\n\t\t\treturn\n\t\t}\n\t\tthis.#emitter.emit('message', text)\n\t\tthis.#messageOpcode = undefined\n\t\tthis.#fragments = []\n\t\tthis.#fragmentBytes = 0\n\t}\n\n\t// Handle a validated CLOSE frame: decode it (which itself may `#fail` on an invalid\n\t// code/reason), then — if still OPEN — echo the peer's payload verbatim and end.\n\t#close(payload: Buffer): void {\n\t\tconst valid = this.#decodeClose(payload)\n\t\tif (!valid) return\n\t\tif (this.#readyState === WEBSOCKET_READY_OPEN) {\n\t\t\t// Echo the peer's close frame before ending, per RFC 6455 §5.5.1.\n\t\t\tthis.#readyState = WEBSOCKET_READY_CLOSING\n\t\t\tthis.#write(WEBSOCKET_OPCODE_CLOSE, payload)\n\t\t}\n\t\t// The echo is queued; detach before `end()` can surface a socket error.\n\t\tthis.#detach()\n\t\tthis.#socket.end()\n\t\tthis.#finish()\n\t}\n\n\t// The single funnel for every RFC 6455 validation breach: close with `code`, `#detach`\n\t// the domain listeners (the connection is protocol-dead — RFC 6455 permits discarding\n\t// further input after sending close, and this also stops a post-fail socket `error`\n\t// emitting AFTER the terminal `close` event), write the close frame, then flush + half\n\t// -close via `end()` (never a synchronous `destroy()`, which can discard the buffered\n\t// close frame and leave the peer seeing 1006 instead of the intended code) before\n\t// finishing. The hard-teardown fallback is armed AFTER `#finish` so `#finish`'s\n\t// `clearTimeout` cannot kill it; the normal path destroys the moment the write buffer\n\t// flushes (the `end()` callback), the unref'd timer is only the malicious-peer backstop.\n\t#fail(code: number, reason?: string): void {\n\t\tif (\n\t\t\tthis.#readyState === WEBSOCKET_READY_CLOSING ||\n\t\t\tthis.#readyState === WEBSOCKET_READY_CLOSED\n\t\t) {\n\t\t\treturn\n\t\t}\n\t\tthis.#code = code\n\t\tthis.#reason = reason\n\t\tthis.#readyState = WEBSOCKET_READY_CLOSING\n\t\tthis.#detach()\n\t\tthis.#write(WEBSOCKET_OPCODE_CLOSE, this.#encodeClose(code, reason))\n\t\tthis.#socket.end(() => {\n\t\t\tif (!this.#socket.destroyed) this.#socket.destroy()\n\t\t\t// The normal flush path destroyed the socket already — clear the unref'd\n\t\t\t// fallback timer below so it doesn't linger `WEBSOCKET_FAIL_TIMEOUT_MS` holding\n\t\t\t// its closure alive for no reason.\n\t\t\tclearTimeout(this.#closeTimer)\n\t\t\tthis.#closeTimer = undefined\n\t\t})\n\t\tthis.#messageOpcode = undefined\n\t\tthis.#fragments = []\n\t\tthis.#fragmentBytes = 0\n\t\tthis.#finish()\n\t\tthis.#closeTimer = setTimeout(() => {\n\t\t\tif (!this.#socket.destroyed) this.#socket.destroy()\n\t\t}, WEBSOCKET_FAIL_TIMEOUT_MS)\n\t\tthis.#closeTimer.unref()\n\t}\n\n\t// Drop only this wrapper's domain listeners and arm one durable terminal error sink.\n\t#detach(): void {\n\t\tif (this.#detached) return\n\t\tthis.#detached = true\n\t\tthis.#socket.off('data', this.#onData)\n\t\tthis.#socket.off('close', this.#onClose)\n\t\tthis.#socket.off('error', this.#onError)\n\t\tthis.#socket.on('error', this.#onDetachedError)\n\t}\n\n\t// Write one frame to the socket — masked in client mode, unmasked in server mode.\n\t// A destroyed socket silently drops the write (the lifecycle is already ending).\n\t#write(opcode: number, payload: Buffer): void {\n\t\tif (this.#socket.destroyed) return\n\t\tthis.#socket.write(encodeWebSocketFrame(opcode, payload, { masked: this.#masked }))\n\t}\n\n\t// Build a close-frame payload: the 2-byte big-endian code, then the optional UTF-8\n\t// reason. An undefined code yields an empty payload (a bare close).\n\t#encodeClose(code: number | undefined, reason: string | undefined): Buffer {\n\t\tif (code === undefined) return Buffer.alloc(0)\n\t\tconst text = reason === undefined ? Buffer.alloc(0) : Buffer.from(reason, 'utf-8')\n\t\tconst payload = Buffer.alloc(2 + text.length)\n\t\tpayload.writeUInt16BE(code, 0)\n\t\ttext.copy(payload, 2)\n\t\treturn payload\n\t}\n\n\t// Validate and read a peer close-frame payload into `#code` / `#reason` (RFC 6455\n\t// §7.4.1). A bare close (0 bytes) is valid with no code/reason. A single stray byte\n\t// is a protocol error. 2+ bytes carry a code (must be a receivable close code) and\n\t// an optional UTF-8 reason. Returns `false` when a breach routed through `#fail`\n\t// (the caller must not also echo).\n\t#decodeClose(payload: Buffer): boolean {\n\t\tif (payload.length === 0) {\n\t\t\tthis.#code = undefined\n\t\t\tthis.#reason = undefined\n\t\t\treturn true\n\t\t}\n\t\tif (payload.length === 1) {\n\t\t\tthis.#fail(WEBSOCKET_CLOSE_PROTOCOL)\n\t\t\treturn false\n\t\t}\n\t\tconst code = payload.readUInt16BE(0)\n\t\tif (!isCloseCode(code)) {\n\t\t\tthis.#fail(WEBSOCKET_CLOSE_PROTOCOL)\n\t\t\treturn false\n\t\t}\n\t\tconst reason = payload.length > 2 ? parseUTF8(payload.subarray(2)) : ''\n\t\tif (reason === undefined) {\n\t\t\tthis.#fail(WEBSOCKET_CLOSE_INVALID)\n\t\t\treturn false\n\t\t}\n\t\tthis.#code = code\n\t\tthis.#reason = reason.length === 0 ? undefined : reason\n\t\treturn true\n\t}\n\n\t// Transition to CLOSED once (idempotent), clear the close-handshake timer, and emit\n\t// the final `close` with the last known code/reason.\n\t#finish(): void {\n\t\tif (this.#readyState === WEBSOCKET_READY_CLOSED) return\n\t\tthis.#detach()\n\t\tclearTimeout(this.#closeTimer)\n\t\tthis.#closeTimer = undefined\n\t\tthis.#signal?.removeEventListener('abort', this.#onAbort)\n\t\tthis.#readyState = WEBSOCKET_READY_CLOSED\n\t\tthis.#emitter.emit('close', this.#code, this.#reason)\n\t}\n\n\t// Append `bytes` to the accumulation buffer, then reject an over-cap frame the moment\n\t// its declared length is known — before its payload is even buffered — else drain\n\t// every complete frame. Shared by `#onData` AND the constructor's head-replay so the\n\t// pre-buffer cap check applies uniformly on both ingest paths (AGENTS §5 dedup).\n\t#ingest(bytes: Buffer): void {\n\t\tthis.#buffer = Buffer.concat([this.#buffer, bytes])\n\t\tconst declared = measureWebSocketFrame(this.#buffer)\n\t\tif (declared !== undefined && declared > this.#payload) {\n\t\t\tthis.#fail(WEBSOCKET_CLOSE_TOOBIG)\n\t\t\treturn\n\t\t}\n\t\tthis.#drain()\n\t}\n\n\t// Narrow an untyped socket `data` chunk to a `Buffer` (AGENTS §14) — a `node:net`\n\t// socket without an explicit encoding yields Buffers, but the listener parameter is\n\t// `unknown`, so it crosses through this guard, never an assertion. A non-Buffer\n\t// chunk (a string from a mis-encoded socket) is normalized; anything else is dropped.\n\t#bytes(chunk: unknown): Buffer | undefined {\n\t\tif (Buffer.isBuffer(chunk)) return chunk\n\t\tif (typeof chunk === 'string') return Buffer.from(chunk, 'utf-8')\n\t\treturn undefined\n\t}\n}\n","import type { NodeWebSocketInterface, NodeWebSocketOptions } from './types.js'\nimport { NodeWebSocket } from './NodeWebSocket.js'\n\n/**\n * Create a server-native WebSocket over a raw upgraded `node:stream` Duplex socket.\n *\n * @remarks\n * The construction entry point for the {@link NodeWebSocketInterface} (AGENTS §8). Pass\n * the upgraded `socket` plus the client's `Sec-WebSocket-Key` as `key` to run in SERVER\n * mode — the wrapper writes the `101 Switching Protocols` handshake and sends unmasked\n * frames; omit `key` for CLIENT mode (no handshake, masked frames). This is the\n * lean-native handle; it speaks only the WebSocket wire protocol — an MCP transport (the\n * later chunk) is built ON it. It is the WebSocket counterpart to\n * `createSQLiteDatabase` / `createIndexedDBDatabase`.\n *\n * @param options - The {@link NodeWebSocketOptions} (`socket`, optional `key` / `head` /\n * `protocol` / `on`)\n * @returns A typed {@link NodeWebSocketInterface}\n *\n * @example\n * ```ts\n * import { createNodeWebSocket } from '@src/server'\n *\n * // In a node:http 'upgrade' handler — server mode, identified by the client key:\n * server.on('upgrade', (request, socket, head) => {\n * \tconst ws = createNodeWebSocket({\n * \t\tsocket,\n * \t\tkey: request.headers['sec-websocket-key'],\n * \t\thead,\n * \t\ton: { message: (text) => ws.send(`echo: ${text}`) },\n * \t})\n * })\n * ```\n */\nexport function createNodeWebSoc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Q,aAAa,CAAC;EACnC,IAAI,CAAC,YAAY,IAAI,GAAG;GACvB,KAAKA,MAAM,wBAAwB;GACnC,OAAO;EACR;EACA,MAAM,SAAS,QAAQ,SAAS,IAAI,UAAU,QAAQ,SAAS,CAAC,CAAC,IAAI;EACrE,IAAI,WAAW,KAAA,GAAW;GACzB,KAAKA,MAAM,uBAAuB;GAClC,OAAO;EACR;EACA,KAAKR,QAAQ;EACb,KAAKC,UAAU,OAAO,WAAW,IAAI,KAAA,IAAY;EACjD,OAAO;CACR;CAIA,UAAgB;EACf,IAAI,KAAKV,gBAAAA,GAAwC;EACjD,KAAKc,QAAQ;EACb,aAAa,KAAKF,WAAW;EAC7B,KAAKA,cAAc,KAAA;EACnB,KAAKd,SAAS,oBAAoB,SAAS,KAAKS,QAAQ;EACxD,KAAKP,cAAAA;EACL,KAAKT,SAAS,KAAK,SAAS,KAAKkB,OAAO,KAAKC,OAAO;CACrD;CAMA,QAAQ,OAAqB;EAC5B,KAAKK,UAAU,OAAO,OAAO,CAAC,KAAKA,SAAS,KAAK,CAAC;EAClD,MAAM,WAAW,sBAAsB,KAAKA,OAAO;EACnD,IAAI,aAAa,KAAA,KAAa,WAAW,KAAKpB,UAAU;GACvD,KAAKsB,MAAM,sBAAsB;GACjC;EACD;EACA,KAAKO,OAAO;CACb;CAMA,OAAO,OAAoC;EAC1C,IAAI,OAAO,SAAS,KAAK,GAAG,OAAO;EACnC,IAAI,OAAO,UAAU,UAAU,OAAO,OAAO,KAAK,OAAO,OAAO;CAEjE;AACD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACraA,SAAgB,oBAAoB,SAAuD;CAC1F,OAAO,IAAI,cAAc,OAAO;AACjC"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["#emitter","#socket","#masked","#payload","#timeout","#signal","#dataListener","#closeListener","#errorListener","#abortListener","#handleData","#finish","#handleError","#readyState","#ingest","#write","#code","#reason","#encodeClose","#closeTimer","#destroyed","#detach","#buffer","#fail","#dispatch","#close","#messageOpcode","#fragments","#fragmentBytes","#decodeClose","#detached","#drain","#bytes"],"sources":["../../../src/server/constants.ts","../../../src/server/helpers.ts","../../../src/server/NodeWebSocket.ts","../../../src/server/factories.ts"],"sourcesContent":["import type { WebSocketReadyState } from './types.js'\n\n// The WebSocket wrapper's wire constants (AGENTS §5 constants file) — the RFC 6455\n// magic values the codec and the handshake are built on: the accept GUID, the\n// supported protocol version, the frame opcodes, the four ready states, and the\n// normal-closure status code. Every member is exported; the codec helpers and the\n// `NodeWebSocket` wrapper read them by name rather than re-spelling the bit values.\n\n/**\n * The RFC 6455 GUID concatenated to a client's `Sec-WebSocket-Key` before the SHA-1\n * hash that yields the `Sec-WebSocket-Accept` response value.\n *\n * @remarks\n * A fixed, spec-mandated constant (RFC 6455 §4.2.2) — read only by\n * {@link computeWebSocketAccept}.\n */\nexport const WEBSOCKET_GUID = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'\n\n/** The WebSocket protocol version this wrapper speaks (`Sec-WebSocket-Version: 13`). */\nexport const WEBSOCKET_VERSION = '13'\n\n/** Text frame opcode — a UTF-8 payload (RFC 6455 §5.6). */\nexport const WEBSOCKET_OPCODE_TEXT = 0x01\n\n/** Binary frame opcode — a raw byte payload (RFC 6455 §5.6). */\nexport const WEBSOCKET_OPCODE_BINARY = 0x02\n\n/** Continuation frame opcode — the next fragment of an open data message (RFC 6455 §5.4). */\nexport const WEBSOCKET_OPCODE_CONTINUATION = 0x00\n\n/** Close frame opcode — a control frame ending the connection (RFC 6455 §5.5.1). */\nexport const WEBSOCKET_OPCODE_CLOSE = 0x08\n\n/** Ping frame opcode — a control frame the peer must answer with a pong (RFC 6455 §5.5.2). */\nexport const WEBSOCKET_OPCODE_PING = 0x09\n\n/** Pong frame opcode — a control frame answering a ping (RFC 6455 §5.5.3). */\nexport const WEBSOCKET_OPCODE_PONG = 0x0a\n\n/** Ready state for a connecting WebSocket (before the handshake completes). */\nexport const WEBSOCKET_READY_CONNECTING: WebSocketReadyState = 0\n\n/** Ready state for an open WebSocket (the handshake completed; frames flow). */\nexport const WEBSOCKET_READY_OPEN: WebSocketReadyState = 1\n\n/** Ready state for a closing WebSocket (a close frame was sent or received). */\nexport const WEBSOCKET_READY_CLOSING: WebSocketReadyState = 2\n\n/** Ready state for a closed WebSocket (the socket ended). */\nexport const WEBSOCKET_READY_CLOSED: WebSocketReadyState = 3\n\n/** Normal-closure status code (RFC 6455 §7.4.1) — the default `close` code. */\nexport const WEBSOCKET_CLOSE_NORMAL = 1000\n\n/** Protocol-error status code (RFC 6455 §7.4.1) — a framing/state rule was violated. */\nexport const WEBSOCKET_CLOSE_PROTOCOL = 1002\n\n/** Unsupported-data status code (RFC 6455 §7.4.1) — the endpoint received a data type it cannot accept (e.g. binary on a text-only endpoint). */\nexport const WEBSOCKET_CLOSE_UNSUPPORTED = 1003\n\n/** Invalid-frame-payload-data status code (RFC 6455 §7.4.1) — e.g. non-UTF-8 text or an unparseable close reason. */\nexport const WEBSOCKET_CLOSE_INVALID = 1007\n\n/** Message-too-big status code (RFC 6455 §7.4.1) — a reassembled message exceeded the payload cap. */\nexport const WEBSOCKET_CLOSE_TOOBIG = 1009\n\n/** The default maximum inbound single-frame length AND reassembled-message total byte count (100 MiB — the `ws` package default). */\nexport const WEBSOCKET_MAX_PAYLOAD = 104_857_600\n\n/** The default close-handshake timeout in milliseconds — how long `close()` waits for the peer's echo before tearing the socket down. */\nexport const WEBSOCKET_CLOSE_TIMEOUT_MS = 30_000\n\n/** The post-`#fail` flush grace in milliseconds — how long a validation-breach close frame is given to flush through the socket's write buffer before the hard `destroy()` fallback fires (the normal path destroys sooner, on the `end()` flush callback). */\nexport const WEBSOCKET_FAIL_TIMEOUT_MS = 1_000\n\n/** The maximum control-frame payload length in bytes (RFC 6455 §5.5). */\nexport const WEBSOCKET_CONTROL_MAXLEN = 125\n\n/** The maximum UTF-8 close-reason length after the two-byte status code. */\nexport const WEBSOCKET_CLOSE_REASON_MAXLEN = WEBSOCKET_CONTROL_MAXLEN - 2\n","import type { WebSocketEncodeOptions, WebSocketFrame } from './types.js'\nimport { createHash, randomBytes } from 'node:crypto'\nimport { WEBSOCKET_GUID } from './constants.js'\n\n// The RFC 6455 codec and boundary guards — pure, exported, and exhaustively tested.\n// `computeWebSocketAccept` derives the handshake token; the `isWebSocket*` guards\n// validate upgrade/header invariants; `measureWebSocketFrame` and\n// `parseWebSocketFrame` decode the next frame incrementally; `encodeWebSocketFrame`\n// builds the inverse wire representation.\n//\n/**\n * Compute the `Sec-WebSocket-Accept` response value for an RFC 6455 upgrade.\n *\n * @remarks\n * The base64-encoded SHA-1 of the client's `Sec-WebSocket-Key` concatenated with the\n * fixed {@link WEBSOCKET_GUID} (RFC 6455 §4.2.2) — the proof the server understood the\n * handshake. Pure and deterministic.\n *\n * @param key - The client's `Sec-WebSocket-Key` header value\n * @returns The base64 accept token to send back as `Sec-WebSocket-Accept`\n */\nexport function computeWebSocketAccept(key: string): string {\n\treturn createHash('sha1')\n\t\t.update(key + WEBSOCKET_GUID)\n\t\t.digest('base64')\n}\n\n/**\n * Whether a value is a canonical RFC 6455 `Sec-WebSocket-Key`.\n *\n * @remarks\n * A valid key is exactly 16 random bytes encoded as 24 characters of base64, ending\n * in `==` (RFC 6455 §4.1). This predicate is suitable at an HTTP upgrade boundary:\n * malformed or non-canonical encodings return `false`; nothing is thrown.\n *\n * @param key - The proposed `Sec-WebSocket-Key` header value\n * @returns `true` when `key` is the canonical base64 encoding of 16 bytes\n *\n * @example\n * ```ts\n * const key = request.headers['sec-websocket-key']\n * if (typeof key !== 'string' || !isWebSocketKey(key)) socket.destroy()\n * ```\n */\nexport function isWebSocketKey(key: string): boolean {\n\tif (!/^[A-Za-z0-9+/]{22}==$/.test(key)) return false\n\treturn Buffer.from(key, 'base64').length === 16\n}\n\n/**\n * Whether a value is one valid WebSocket subprotocol token.\n *\n * @remarks\n * Subprotocols use the HTTP `token` grammar. Whitespace, separators, commas, and\n * control characters are rejected, preventing an untrusted value from injecting a\n * second handshake header.\n *\n * @param protocol - The negotiated subprotocol to validate\n * @returns `true` when `protocol` is one non-empty HTTP token\n *\n * @example\n * ```ts\n * if (!isWebSocketProtocol(protocol)) throw new RangeError('invalid protocol')\n * ```\n */\nexport function isWebSocketProtocol(protocol: string): boolean {\n\treturn /^[!#$%&'*+\\-.^_`|~0-9A-Za-z]+$/.test(protocol)\n}\n\n/**\n * Decode a single RFC 6455 frame from the front of a buffer.\n *\n * @remarks\n * Reads the FIN bit and opcode (byte 0), the mask bit and 7-bit payload length (byte\n * 1) — extended to a 16-bit length when the 7-bit field is `126`, or a 64-bit length\n * when it is `127` — the optional 4-byte mask key, then the payload, XOR-unmasking it\n * against the key when the mask bit is set (client→server frames MUST be masked, RFC\n * 6455 §5.3; an unmasked frame still decodes, leaving the payload as-is, so the caller\n * can enforce policy). Returns `undefined` the moment the buffer is too short for the\n * part it is up to (the length prefix, the mask, or the full payload) — the signal to\n * the caller to read more bytes and retry, exactly like {@link SSEParser} on a partial\n * line. `consumed` is the total bytes the frame occupied, so the caller slices the\n * remainder. Pure; never throws on a short buffer.\n *\n * @param buffer - The accumulation buffer to decode the next frame from\n * @returns The parsed {@link WebSocketFrame}, or `undefined` when the buffer is incomplete\n */\nexport function parseWebSocketFrame(buffer: Buffer): WebSocketFrame | undefined {\n\tif (buffer.length < 2) return undefined\n\n\tconst firstByte = buffer.readUInt8(0)\n\tconst secondByte = buffer.readUInt8(1)\n\n\tconst fin = (firstByte & 0x80) !== 0\n\tconst rsv = (firstByte & 0x70) >> 4\n\tconst opcode = firstByte & 0x0f\n\tconst masked = (secondByte & 0x80) !== 0\n\tlet length = secondByte & 0x7f\n\tlet offset = 2\n\n\tif (length === 126) {\n\t\tif (buffer.length < offset + 2) return undefined\n\t\tlength = buffer.readUInt16BE(offset)\n\t\toffset += 2\n\t} else if (length === 127) {\n\t\tif (buffer.length < offset + 8) return undefined\n\t\t// Split into two 32-bit reads — a payload past 2^53 is beyond any real frame,\n\t\t// and this keeps the arithmetic in safe-integer range.\n\t\tconst high = buffer.readUInt32BE(offset)\n\t\tconst low = buffer.readUInt32BE(offset + 4)\n\t\tlength = high * 0x1_0000_0000 + low\n\t\toffset += 8\n\t}\n\n\tlet mask: Buffer | undefined\n\tif (masked) {\n\t\tif (buffer.length < offset + 4) return undefined\n\t\tmask = buffer.subarray(offset, offset + 4)\n\t\toffset += 4\n\t}\n\n\tif (buffer.length < offset + length) return undefined\n\n\tconst payload = Buffer.alloc(length)\n\tbuffer.copy(payload, 0, offset, offset + length)\n\n\tif (mask !== undefined) {\n\t\tfor (let index = 0; index < length; index += 1) {\n\t\t\tpayload[index] = payload.readUInt8(index) ^ mask.readUInt8(index % 4)\n\t\t}\n\t}\n\n\treturn { fin, opcode, payload, consumed: offset + length, masked, rsv }\n}\n\n/**\n * Read the declared payload length off the front of a buffer, without buffering or\n * reading the payload itself.\n *\n * @remarks\n * Decodes only byte 1's 7-bit length field, extended by the 16-bit (`126`) or 64-bit\n * (`127`) form exactly like {@link parseWebSocketFrame} — but stops there, so a caller\n * can reject an over-cap frame the moment its length is known, before the payload\n * bytes have even arrived. Returns `undefined` until the length field itself is fully\n * buffered (mirrors the parser's incomplete-buffer contract). Pure; never throws.\n *\n * @param buffer - The accumulation buffer to read the next frame's length from\n * @returns The declared payload length, or `undefined` when the buffer is too short to know it yet\n *\n * @example\n * ```ts\n * const declared = measureWebSocketFrame(buffer)\n * if (declared !== undefined && declared > limit) fail(WEBSOCKET_CLOSE_TOOBIG)\n * ```\n */\nexport function measureWebSocketFrame(buffer: Buffer): number | undefined {\n\tif (buffer.length < 2) return undefined\n\n\tconst secondByte = buffer.readUInt8(1)\n\tlet length = secondByte & 0x7f\n\tconst offset = 2\n\n\tif (length === 126) {\n\t\tif (buffer.length < offset + 2) return undefined\n\t\tlength = buffer.readUInt16BE(offset)\n\t} else if (length === 127) {\n\t\tif (buffer.length < offset + 8) return undefined\n\t\tconst high = buffer.readUInt32BE(offset)\n\t\tconst low = buffer.readUInt32BE(offset + 4)\n\t\tlength = high * 0x1_0000_0000 + low\n\t}\n\n\treturn length\n}\n\n/**\n * Whether the next frame uses the shortest valid RFC 6455 payload-length encoding.\n *\n * @remarks\n * Returns `undefined` until the complete length prefix is buffered. The 16-bit form\n * is canonical only for lengths at least 126; the 64-bit form only for lengths at\n * least 65,536 and with its most-significant bit clear (RFC 6455 §5.2).\n *\n * @param buffer - The accumulation buffer containing the next frame header\n * @returns Its canonicality, or `undefined` while the length prefix is incomplete\n *\n * @example\n * ```ts\n * if (isWebSocketFrameCanonical(buffer) === false) fail(WEBSOCKET_CLOSE_PROTOCOL)\n * ```\n */\nexport function isWebSocketFrameCanonical(buffer: Buffer): boolean | undefined {\n\tif (buffer.length < 2) return undefined\n\n\tconst lengthCode = buffer.readUInt8(1) & 0x7f\n\tif (lengthCode < 126) return true\n\tif (lengthCode === 126) {\n\t\tif (buffer.length < 4) return undefined\n\t\treturn buffer.readUInt16BE(2) >= 126\n\t}\n\tif (buffer.length < 10) return undefined\n\tconst high = buffer.readUInt32BE(2)\n\tconst low = buffer.readUInt32BE(6)\n\tif ((high & 0x8000_0000) !== 0) return false\n\treturn high > 0 || low >= 65_536\n}\n\n/**\n * Decode a byte sequence as strict UTF-8, or signal it is malformed.\n *\n * @remarks\n * Wraps `TextDecoder('utf-8', { fatal: true })` in a try/catch so a malformed sequence\n * returns `undefined` instead of throwing (AGENTS §14 — a guard-adjacent coercer never\n * throws on bad input). Pure.\n *\n * @param bytes - The raw bytes to decode\n * @returns The decoded string, or `undefined` when `bytes` is not valid UTF-8\n *\n * @example\n * ```ts\n * const text = parseUTF8(payload)\n * if (text === undefined) fail(WEBSOCKET_CLOSE_INVALID)\n * ```\n */\nexport function parseUTF8(bytes: Buffer): string | undefined {\n\ttry {\n\t\treturn new TextDecoder('utf-8', { fatal: true }).decode(bytes)\n\t} catch {\n\t\treturn undefined\n\t}\n}\n\n/**\n * Whether a numeric value is a valid RFC 6455 close status code to RECEIVE (§7.4.1).\n *\n * @remarks\n * True for `1000`–`1003`, `1007`–`1014`, and the application range `3000`–`4999`; false\n * for anything below `1000`, the reserved-for-local-use-only codes `1004`–`1006` and\n * `1015`, and the unassigned `1016`–`2999` range. The `1012`–`1014` extension of the\n * strict RFC 6455 receivable set is a deliberate IANA-interop choice: those three codes\n * (Service Restart, Try Again Later, Bad Gateway) are IANA-registered in the WebSocket\n * Close Code Number Registry and accepted by the `ws` ecosystem and modern conformance\n * suites, so a peer sending one is not treated as a protocol violation. Pure predicate,\n * never throws.\n *\n * @param code - The close status code to validate\n * @returns `true` when `code` is a valid RFC 6455 close code\n *\n * @example\n * ```ts\n * if (!isCloseCode(code)) fail(WEBSOCKET_CLOSE_PROTOCOL)\n * ```\n */\nexport function isCloseCode(code: number): boolean {\n\tif (!Number.isInteger(code)) return false\n\tif (code >= 1000 && code <= 1003) return true\n\tif (code >= 1007 && code <= 1014) return true\n\tif (code >= 3000 && code <= 4999) return true\n\treturn false\n}\n\n/**\n * Encode a single RFC 6455 frame to its wire bytes — the inverse of\n * {@link parseWebSocketFrame}.\n *\n * @remarks\n * Builds a final (FIN-set) frame: byte 0 is `0x80 | opcode`; the payload length uses\n * the 7-bit form below 126, the `126` + 16-bit form below 65 536, or the `127` +\n * 64-bit form beyond; when `masked` is set the mask bit is set, a 4-byte key (supplied\n * via `options.mask`, else random) is written, and the payload is XOR-masked. Server→\n * client frames are unmasked (the default); pass `masked: true` to encode a CLIENT\n * frame (e.g. to feed the parser in a test). A `string` payload is encoded as UTF-8.\n * Returns one contiguous `Buffer` (header + payload), so the wrapper writes it with a\n * single `socket.write`. Pure.\n *\n * @param opcode - The frame opcode (a `WEBSOCKET_OPCODE_*` value)\n * @param payload - The payload, a `Buffer` or a UTF-8 `string`\n * @param options - Masking control ({@link WebSocketEncodeOptions}); defaults to unmasked\n * @returns The complete frame as wire bytes\n */\nexport function encodeWebSocketFrame(\n\topcode: number,\n\tpayload: Buffer | string,\n\toptions?: WebSocketEncodeOptions,\n): Buffer {\n\tif (!Number.isInteger(opcode) || opcode < 0 || opcode > 0x0f) {\n\t\tthrow new RangeError('opcode must be an integer between 0 and 15')\n\t}\n\tif (options?.mask !== undefined && options.mask.length !== 4) {\n\t\tthrow new RangeError('mask must contain exactly 4 bytes')\n\t}\n\tif (options?.mask !== undefined && options.masked !== true) {\n\t\tthrow new RangeError('mask requires masked: true')\n\t}\n\tconst body = typeof payload === 'string' ? Buffer.from(payload, 'utf-8') : payload\n\tconst length = body.length\n\tconst masked = options?.masked === true\n\tconst mask = masked ? (options?.mask ?? randomBytes(4)) : undefined\n\tconst maskBit = masked ? 0x80 : 0\n\n\t// The header size: 2 base bytes + the extended-length bytes (0 / 2 / 8) + the mask\n\t// key (0 / 4). The length prefix and the mask key write into this header.\n\tconst extended = length < 126 ? 0 : length < 65_536 ? 2 : 8\n\tconst header = Buffer.alloc(2 + extended + (mask !== undefined ? 4 : 0))\n\theader[0] = 0x80 | opcode\n\n\tif (length < 126) {\n\t\theader[1] = maskBit | length\n\t} else if (length < 65_536) {\n\t\theader[1] = maskBit | 126\n\t\theader.writeUInt16BE(length, 2)\n\t} else {\n\t\theader[1] = maskBit | 127\n\t\theader.writeUInt32BE(Math.floor(length / 0x1_0000_0000), 2)\n\t\theader.writeUInt32BE(length % 0x1_0000_0000, 6)\n\t}\n\n\tif (mask === undefined) return Buffer.concat([header, body])\n\n\tmask.copy(header, header.length - 4)\n\tconst maskedBody = Buffer.alloc(length)\n\tfor (let index = 0; index < length; index += 1) {\n\t\tmaskedBody[index] = body.readUInt8(index) ^ mask.readUInt8(index % 4)\n\t}\n\treturn Buffer.concat([header, maskedBody])\n}\n","import type { Duplex } from 'node:stream'\nimport type {\n\tNodeWebSocketEventMap,\n\tNodeWebSocketInterface,\n\tNodeWebSocketOptions,\n\tWebSocketReadyState,\n} from './types.js'\nimport type { EmitterInterface } from '@orkestrel/emitter'\nimport { Emitter } from '@orkestrel/emitter'\nimport {\n\tcomputeWebSocketAccept,\n\tencodeWebSocketFrame,\n\tisCloseCode,\n\tisWebSocketFrameCanonical,\n\tisWebSocketKey,\n\tisWebSocketProtocol,\n\tmeasureWebSocketFrame,\n\tparseUTF8,\n\tparseWebSocketFrame,\n} from './helpers.js'\nimport {\n\tWEBSOCKET_CLOSE_INVALID,\n\tWEBSOCKET_CLOSE_NORMAL,\n\tWEBSOCKET_CLOSE_PROTOCOL,\n\tWEBSOCKET_CLOSE_REASON_MAXLEN,\n\tWEBSOCKET_CLOSE_TIMEOUT_MS,\n\tWEBSOCKET_CLOSE_TOOBIG,\n\tWEBSOCKET_CLOSE_UNSUPPORTED,\n\tWEBSOCKET_CONTROL_MAXLEN,\n\tWEBSOCKET_FAIL_TIMEOUT_MS,\n\tWEBSOCKET_MAX_PAYLOAD,\n\tWEBSOCKET_OPCODE_BINARY,\n\tWEBSOCKET_OPCODE_CLOSE,\n\tWEBSOCKET_OPCODE_CONTINUATION,\n\tWEBSOCKET_OPCODE_PING,\n\tWEBSOCKET_OPCODE_PONG,\n\tWEBSOCKET_OPCODE_TEXT,\n\tWEBSOCKET_READY_CLOSED,\n\tWEBSOCKET_READY_CLOSING,\n\tWEBSOCKET_READY_CONNECTING,\n\tWEBSOCKET_READY_OPEN,\n} from './constants.js'\n\n/**\n * A server-native WebSocket over a raw upgraded `node:stream` Duplex — the lean\n * wrapper around the RFC 6455 wire protocol.\n *\n * @remarks\n * Created by `createNodeWebSocket`. When given a client `key` it runs in SERVER mode —\n * it writes the `101 Switching Protocols` handshake (`computeWebSocketAccept(key)`) and\n * emits `open`; given no key it runs in CLIENT mode (no handshake, frames masked). It\n * then listens on the socket's `data`, accumulating bytes in `#buffer` and decoding\n * every complete frame with {@link parseWebSocketFrame} (slicing `consumed` and\n * re-parsing the remainder): a TEXT frame — reassembling continuation fragments across\n * `fin: false` frames — decodes to UTF-8 and emits `message`; a PING is auto-answered\n * with a PONG and emits `ping`; a PONG emits `pong`; a CLOSE is echoed and ends the\n * socket, emitting `close`. `send` writes a text frame, `ping` a ping, `close` a close\n * frame; `destroy` tears down immediately. It owns a typed `#emitter` (AGENTS §13) that\n * isolates a throwing listener and routes the error to its own `error` handler (the `error`\n * option) — the socket never crashes. An underlying socket error emits the domain\n * `error` event and terminates the wrapper. The untyped socket `data` is narrowed to a\n * `Buffer` with a guard, never an assertion (AGENTS §14).\n */\nexport class NodeWebSocket implements NodeWebSocketInterface {\n\treadonly #emitter: Emitter<NodeWebSocketEventMap>\n\treadonly #socket: Duplex\n\treadonly #masked: boolean\n\treadonly #payload: number\n\treadonly #timeout: number\n\treadonly #signal: AbortSignal | undefined\n\treadonly #dataListener: (chunk: unknown) => void\n\treadonly #closeListener: () => void\n\treadonly #errorListener: (error: unknown) => void\n\treadonly #abortListener: () => void\n\t#buffer: Buffer = Buffer.alloc(0)\n\t#readyState: WebSocketReadyState = WEBSOCKET_READY_CONNECTING\n\t#code: number | undefined\n\t#reason: string | undefined\n\t#fragments: Buffer[] = []\n\t#messageOpcode: number | undefined\n\t#fragmentBytes = 0\n\t#closeTimer: ReturnType<typeof setTimeout> | undefined\n\t#destroyed = false\n\t#detached = false\n\n\tconstructor(options: NodeWebSocketOptions) {\n\t\tconst payload = options.payload ?? WEBSOCKET_MAX_PAYLOAD\n\t\tif (!Number.isSafeInteger(payload) || payload < 0) {\n\t\t\tthrow new RangeError('payload must be a non-negative safe integer')\n\t\t}\n\t\tconst timeout = options.timeout ?? WEBSOCKET_CLOSE_TIMEOUT_MS\n\t\tif (!Number.isSafeInteger(timeout) || timeout < 0) {\n\t\t\tthrow new RangeError('timeout must be a non-negative safe integer')\n\t\t}\n\t\tif (options.key !== undefined && !isWebSocketKey(options.key)) {\n\t\t\tthrow new RangeError('key must be the canonical base64 encoding of 16 bytes')\n\t\t}\n\t\tif (options.protocol !== undefined && !isWebSocketProtocol(options.protocol)) {\n\t\t\tthrow new RangeError('protocol must be a valid WebSocket subprotocol token')\n\t\t}\n\t\tif (options.protocol !== undefined && options.key === undefined) {\n\t\t\tthrow new RangeError('protocol requires a server key')\n\t\t}\n\n\t\tthis.#emitter = new Emitter({\n\t\t\t...(options.on === undefined ? {} : { on: options.on }),\n\t\t\t...(options.error === undefined ? {} : { error: options.error }),\n\t\t})\n\t\tthis.#socket = options.socket\n\t\t// Server mode is identified by a client key (it writes the handshake + sends\n\t\t// unmasked frames); without one this is a client (no handshake, masked frames).\n\t\tthis.#masked = options.key === undefined\n\t\tthis.#payload = payload\n\t\tthis.#timeout = timeout\n\t\tthis.#signal = options.signal\n\t\t// Retain each bound listener so terminal paths detach only this wrapper's callbacks.\n\t\tthis.#dataListener = this.#handleData.bind(this)\n\t\tthis.#closeListener = this.#finish.bind(this)\n\t\tthis.#errorListener = this.#handleError.bind(this)\n\t\tthis.#abortListener = this.destroy.bind(this)\n\n\t\tif (options.key !== undefined) {\n\t\t\tconst headers = [\n\t\t\t\t'HTTP/1.1 101 Switching Protocols',\n\t\t\t\t'Upgrade: websocket',\n\t\t\t\t'Connection: Upgrade',\n\t\t\t\t`Sec-WebSocket-Accept: ${computeWebSocketAccept(options.key)}`,\n\t\t\t]\n\t\t\tif (options.protocol !== undefined) {\n\t\t\t\theaders.push(`Sec-WebSocket-Protocol: ${options.protocol}`)\n\t\t\t}\n\t\t\tthis.#socket.write(`${headers.join('\\r\\n')}\\r\\n\\r\\n`)\n\t\t}\n\n\t\tthis.#readyState = WEBSOCKET_READY_OPEN\n\t\tthis.#socket.on('data', this.#dataListener)\n\t\tthis.#socket.on('close', this.#closeListener)\n\t\tthis.#socket.on('error', this.#errorListener)\n\t\tthis.#emitter.emit('open')\n\n\t\t// Replay any bytes buffered after the upgrade headers through the same ingest path\n\t\t// as `#handleData`, so the pre-buffer cap check applies uniformly (AGENTS §5 dedup).\n\t\tconst head = options.head\n\t\tif (head !== undefined && head.length > 0) {\n\t\t\tthis.#ingest(head)\n\t\t}\n\n\t\t// The external cancellation seam (composes with `@orkestrel/abort` /\n\t\t// `@orkestrel/timeout`'s native AbortSignals) — wired last so an already-aborted\n\t\t// signal tears the socket down only after the rest of construction has run. The\n\t\t// head-replay above can itself synchronously terminate the socket (a complete\n\t\t// CLOSE frame or an RFC violation routes through `#fail`/`#close` -> `#finish`),\n\t\t// which flushes the close frame GRACEFULLY via `#socket.end()`. In that case skip\n\t\t// the seam entirely: forcing `destroy()` would discard that flushing frame (the\n\t\t// loss `#fail` is engineered to avoid), and there is no live socket to attach to.\n\t\tif (this.#readyState !== WEBSOCKET_READY_CLOSED) {\n\t\t\tif (this.#signal?.aborted === true) {\n\t\t\t\tthis.destroy()\n\t\t\t} else {\n\t\t\t\tthis.#signal?.addEventListener('abort', this.#abortListener, { once: true })\n\t\t\t}\n\t\t}\n\t}\n\n\tget emitter(): EmitterInterface<NodeWebSocketEventMap> {\n\t\treturn this.#emitter\n\t}\n\n\tget readyState(): WebSocketReadyState {\n\t\treturn this.#readyState\n\t}\n\n\tsend(data: string): void {\n\t\tif (this.#readyState !== WEBSOCKET_READY_OPEN) return\n\t\tthis.#write(WEBSOCKET_OPCODE_TEXT, Buffer.from(data, 'utf-8'))\n\t}\n\n\tping(data?: string): void {\n\t\tif (this.#readyState !== WEBSOCKET_READY_OPEN) return\n\t\tif (data !== undefined && Buffer.byteLength(data, 'utf-8') > WEBSOCKET_CONTROL_MAXLEN) {\n\t\t\tthrow new RangeError('ping payload exceeds 125 bytes')\n\t\t}\n\t\tthis.#write(\n\t\t\tWEBSOCKET_OPCODE_PING,\n\t\t\tdata === undefined ? Buffer.alloc(0) : Buffer.from(data, 'utf-8'),\n\t\t)\n\t}\n\n\tclose(code?: number, reason?: string): void {\n\t\tif (\n\t\t\tthis.#readyState === WEBSOCKET_READY_CLOSING ||\n\t\t\tthis.#readyState === WEBSOCKET_READY_CLOSED\n\t\t) {\n\t\t\treturn\n\t\t}\n\t\tif (code !== undefined && !isCloseCode(code)) throw new RangeError('invalid close code')\n\t\tif (\n\t\t\treason !== undefined &&\n\t\t\tBuffer.byteLength(reason, 'utf-8') > WEBSOCKET_CLOSE_REASON_MAXLEN\n\t\t) {\n\t\t\tthrow new RangeError(`close reason exceeds ${WEBSOCKET_CLOSE_REASON_MAXLEN} bytes`)\n\t\t}\n\t\tthis.#readyState = WEBSOCKET_READY_CLOSING\n\t\tthis.#code = code ?? WEBSOCKET_CLOSE_NORMAL\n\t\tthis.#reason = reason === undefined || reason.length === 0 ? undefined : reason\n\t\tthis.#write(WEBSOCKET_OPCODE_CLOSE, this.#encodeClose(this.#code, this.#reason))\n\t\t// End the writable side after the close frame; the peer's echo (or the socket\n\t\t// `close`) drives the final state transition through `#finish`.\n\t\tthis.#socket.end()\n\t\tthis.#closeTimer = setTimeout(() => this.destroy(), this.#timeout)\n\t\tthis.#closeTimer.unref()\n\t}\n\n\tdestroy(): void {\n\t\tif (this.#destroyed) return\n\t\tthis.#destroyed = true\n\t\t// Detach before destroy so a destroy-time error reaches the terminal sink.\n\t\tthis.#detach()\n\t\tthis.#signal?.removeEventListener('abort', this.#abortListener)\n\t\t// `#finish` no-ops once already CLOSED (e.g. after `#fail` armed the hard-teardown\n\t\t// fallback), so the timer is cleared here unconditionally rather than relying on it.\n\t\tclearTimeout(this.#closeTimer)\n\t\tthis.#closeTimer = undefined\n\t\tif (!this.#socket.destroyed) this.#socket.destroy()\n\t\tthis.#finish()\n\t\tthis.#emitter.destroy()\n\t}\n\n\t// Decode every complete frame currently in the buffer, dispatching each and slicing\n\t// it off; stops when a partial frame remains (parse returns `undefined`).\n\t#drain(): void {\n\t\tfor (;;) {\n\t\t\tconst canonical = isWebSocketFrameCanonical(this.#buffer)\n\t\t\tif (canonical === false) {\n\t\t\t\tthis.#fail(WEBSOCKET_CLOSE_PROTOCOL)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tconst declared = measureWebSocketFrame(this.#buffer)\n\t\t\tif (declared !== undefined && declared > this.#payload) {\n\t\t\t\tthis.#fail(WEBSOCKET_CLOSE_TOOBIG)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tconst frame = parseWebSocketFrame(this.#buffer)\n\t\t\tif (frame === undefined) return\n\t\t\tthis.#buffer = this.#buffer.subarray(frame.consumed)\n\t\t\tthis.#dispatch(frame.fin, frame.opcode, frame.payload, frame.masked, frame.rsv)\n\t\t\tif (this.#readyState === WEBSOCKET_READY_CLOSED) return\n\t\t}\n\t}\n\n\t// Route one decoded frame through the RFC 6455 validation gauntlet, then the\n\t// fragmentation state machine. Any validity breach funnels through `#fail`, which\n\t// closes with the specified code and tears the socket down.\n\t#dispatch(fin: boolean, opcode: number, payload: Buffer, masked: boolean, rsv: number): void {\n\t\tif (rsv !== 0) {\n\t\t\tthis.#fail(WEBSOCKET_CLOSE_PROTOCOL)\n\t\t\treturn\n\t\t}\n\t\t// Server mode sends unmasked and requires masked input; client mode is the inverse.\n\t\tif (masked === this.#masked) {\n\t\t\tthis.#fail(WEBSOCKET_CLOSE_PROTOCOL)\n\t\t\treturn\n\t\t}\n\n\t\tif (\n\t\t\topcode === WEBSOCKET_OPCODE_CLOSE ||\n\t\t\topcode === WEBSOCKET_OPCODE_PING ||\n\t\t\topcode === WEBSOCKET_OPCODE_PONG\n\t\t) {\n\t\t\tif (!fin || payload.length > WEBSOCKET_CONTROL_MAXLEN) {\n\t\t\t\tthis.#fail(WEBSOCKET_CLOSE_PROTOCOL)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif (opcode === WEBSOCKET_OPCODE_PING) {\n\t\t\t\tthis.#write(WEBSOCKET_OPCODE_PONG, payload)\n\t\t\t\tthis.#emitter.emit('ping')\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif (opcode === WEBSOCKET_OPCODE_PONG) {\n\t\t\t\tthis.#emitter.emit('pong')\n\t\t\t\treturn\n\t\t\t}\n\t\t\tthis.#close(payload)\n\t\t\treturn\n\t\t}\n\n\t\tif (opcode === WEBSOCKET_OPCODE_TEXT || opcode === WEBSOCKET_OPCODE_BINARY) {\n\t\t\tif (this.#messageOpcode !== undefined) {\n\t\t\t\tthis.#fail(WEBSOCKET_CLOSE_PROTOCOL)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tthis.#messageOpcode = opcode\n\t\t} else if (opcode === WEBSOCKET_OPCODE_CONTINUATION) {\n\t\t\tif (this.#messageOpcode === undefined) {\n\t\t\t\tthis.#fail(WEBSOCKET_CLOSE_PROTOCOL)\n\t\t\t\treturn\n\t\t\t}\n\t\t} else {\n\t\t\t// Reserved data (0x3–0x7) or reserved control (0xB–0xF) opcodes.\n\t\t\tthis.#fail(WEBSOCKET_CLOSE_PROTOCOL)\n\t\t\treturn\n\t\t}\n\n\t\tthis.#fragments.push(payload)\n\t\tthis.#fragmentBytes += payload.length\n\t\tif (this.#fragmentBytes > this.#payload) {\n\t\t\tthis.#fail(WEBSOCKET_CLOSE_TOOBIG)\n\t\t\treturn\n\t\t}\n\t\tif (!fin) return\n\n\t\tif (this.#messageOpcode === WEBSOCKET_OPCODE_BINARY) {\n\t\t\tthis.#fail(WEBSOCKET_CLOSE_UNSUPPORTED)\n\t\t\treturn\n\t\t}\n\t\tconst text = parseUTF8(Buffer.concat(this.#fragments))\n\t\tif (text === undefined) {\n\t\t\tthis.#fail(WEBSOCKET_CLOSE_INVALID)\n\t\t\treturn\n\t\t}\n\t\tthis.#emitter.emit('message', text)\n\t\tthis.#messageOpcode = undefined\n\t\tthis.#fragments = []\n\t\tthis.#fragmentBytes = 0\n\t}\n\n\t// Handle a validated CLOSE frame: decode it (which itself may `#fail` on an invalid\n\t// code/reason), then — if still OPEN — echo the peer's payload verbatim and end.\n\t#close(payload: Buffer): void {\n\t\tconst valid = this.#decodeClose(payload)\n\t\tif (!valid) return\n\t\tif (this.#readyState === WEBSOCKET_READY_OPEN) {\n\t\t\t// Echo the peer's close frame before ending, per RFC 6455 §5.5.1.\n\t\t\tthis.#readyState = WEBSOCKET_READY_CLOSING\n\t\t\tthis.#write(WEBSOCKET_OPCODE_CLOSE, payload)\n\t\t}\n\t\t// The echo is queued; detach before `end()` can surface a socket error.\n\t\tthis.#detach()\n\t\tthis.#socket.end()\n\t\tthis.#finish()\n\t}\n\n\t// The single funnel for every RFC 6455 validation breach: close with `code`, `#detach`\n\t// the domain listeners (the connection is protocol-dead — RFC 6455 permits discarding\n\t// further input after sending close, and this also stops a post-fail socket `error`\n\t// emitting AFTER the terminal `close` event), write the close frame, then flush + half\n\t// -close via `end()` (never a synchronous `destroy()`, which can discard the buffered\n\t// close frame and leave the peer seeing 1006 instead of the intended code) before\n\t// finishing. The hard-teardown fallback is armed AFTER `#finish` so `#finish`'s\n\t// `clearTimeout` cannot kill it; the normal path destroys the moment the write buffer\n\t// flushes (the `end()` callback), the unref'd timer is only the malicious-peer backstop.\n\t#fail(code: number, reason?: string): void {\n\t\tif (\n\t\t\tthis.#readyState === WEBSOCKET_READY_CLOSING ||\n\t\t\tthis.#readyState === WEBSOCKET_READY_CLOSED\n\t\t) {\n\t\t\treturn\n\t\t}\n\t\tthis.#code = code\n\t\tthis.#reason = reason\n\t\tthis.#readyState = WEBSOCKET_READY_CLOSING\n\t\tthis.#detach()\n\t\tthis.#write(WEBSOCKET_OPCODE_CLOSE, this.#encodeClose(code, reason))\n\t\tthis.#socket.end(() => {\n\t\t\tif (!this.#socket.destroyed) this.#socket.destroy()\n\t\t\t// The normal flush path destroyed the socket already — clear the unref'd\n\t\t\t// fallback timer below so it doesn't linger `WEBSOCKET_FAIL_TIMEOUT_MS` holding\n\t\t\t// its closure alive for no reason.\n\t\t\tclearTimeout(this.#closeTimer)\n\t\t\tthis.#closeTimer = undefined\n\t\t})\n\t\tthis.#messageOpcode = undefined\n\t\tthis.#fragments = []\n\t\tthis.#fragmentBytes = 0\n\t\tthis.#finish()\n\t\tthis.#closeTimer = setTimeout(() => {\n\t\t\tif (!this.#socket.destroyed) this.#socket.destroy()\n\t\t}, WEBSOCKET_FAIL_TIMEOUT_MS)\n\t\tthis.#closeTimer.unref()\n\t}\n\n\t// Drop only this wrapper's domain listeners and arm one durable terminal error sink.\n\t#detach(): void {\n\t\tif (this.#detached) return\n\t\tthis.#detached = true\n\t\tthis.#socket.off('data', this.#dataListener)\n\t\tthis.#socket.off('close', this.#closeListener)\n\t\tthis.#socket.off('error', this.#errorListener)\n\t\t// Keep a terminal socket safe from late peer errors after the domain listener is gone.\n\t\tthis.#socket.on('error', () => undefined)\n\t}\n\n\t// Write one frame to the socket — masked in client mode, unmasked in server mode.\n\t// A destroyed socket silently drops the write (the lifecycle is already ending).\n\t#write(opcode: number, payload: Buffer): void {\n\t\tif (this.#socket.destroyed) return\n\t\tthis.#socket.write(encodeWebSocketFrame(opcode, payload, { masked: this.#masked }))\n\t}\n\n\t// Build a close-frame payload: the 2-byte big-endian code, then the optional UTF-8\n\t// reason. An undefined code yields an empty payload (a bare close).\n\t#encodeClose(code: number | undefined, reason: string | undefined): Buffer {\n\t\tif (code === undefined) return Buffer.alloc(0)\n\t\tconst text = reason === undefined ? Buffer.alloc(0) : Buffer.from(reason, 'utf-8')\n\t\tconst payload = Buffer.alloc(2 + text.length)\n\t\tpayload.writeUInt16BE(code, 0)\n\t\ttext.copy(payload, 2)\n\t\treturn payload\n\t}\n\n\t// Validate and read a peer close-frame payload into `#code` / `#reason` (RFC 6455\n\t// §7.4.1). A bare close (0 bytes) is valid with no code/reason. A single stray byte\n\t// is a protocol error. 2+ bytes carry a code (must be a receivable close code) and\n\t// an optional UTF-8 reason. Returns `false` when a breach routed through `#fail`\n\t// (the caller must not also echo).\n\t#decodeClose(payload: Buffer): boolean {\n\t\tif (payload.length === 0) {\n\t\t\tthis.#code = undefined\n\t\t\tthis.#reason = undefined\n\t\t\treturn true\n\t\t}\n\t\tif (payload.length === 1) {\n\t\t\tthis.#fail(WEBSOCKET_CLOSE_PROTOCOL)\n\t\t\treturn false\n\t\t}\n\t\tconst code = payload.readUInt16BE(0)\n\t\tif (!isCloseCode(code)) {\n\t\t\tthis.#fail(WEBSOCKET_CLOSE_PROTOCOL)\n\t\t\treturn false\n\t\t}\n\t\tif (payload.length === 2) {\n\t\t\tthis.#code = code\n\t\t\tthis.#reason = undefined\n\t\t\treturn true\n\t\t}\n\t\tconst reason = parseUTF8(payload.subarray(2))\n\t\tif (reason === undefined) {\n\t\t\tthis.#fail(WEBSOCKET_CLOSE_INVALID)\n\t\t\treturn false\n\t\t}\n\t\tthis.#code = code\n\t\tthis.#reason = reason.length === 0 ? undefined : reason\n\t\treturn true\n\t}\n\n\t// Transition to CLOSED once (idempotent), clear the close-handshake timer, and emit\n\t// the final `close` with the last known code/reason.\n\t#finish(): void {\n\t\tif (this.#readyState === WEBSOCKET_READY_CLOSED) return\n\t\tthis.#detach()\n\t\tclearTimeout(this.#closeTimer)\n\t\tthis.#closeTimer = undefined\n\t\tthis.#signal?.removeEventListener('abort', this.#abortListener)\n\t\tthis.#readyState = WEBSOCKET_READY_CLOSED\n\t\tthis.#emitter.emit('close', this.#code, this.#reason)\n\t}\n\n\t// Append `bytes` to the accumulation buffer, then drain every complete frame. `#drain`\n\t// preflights canonical encoding and the declared payload cap on EACH iteration, so\n\t// every coalesced frame receives the same validation. Shared by `#handleData` and head replay.\n\t#ingest(bytes: Buffer): void {\n\t\tthis.#buffer = Buffer.concat([this.#buffer, bytes])\n\t\tthis.#drain()\n\t}\n\n\t#handleData(chunk: unknown): void {\n\t\tif (this.#readyState === WEBSOCKET_READY_CLOSED) return\n\t\tconst bytes = this.#bytes(chunk)\n\t\tif (bytes === undefined) return\n\t\tthis.#ingest(bytes)\n\t}\n\n\t#handleError(error: unknown): void {\n\t\tthis.#emitter.emit('error', error)\n\t\tthis.destroy()\n\t}\n\n\t// Narrow an untyped socket `data` chunk to a `Buffer` (AGENTS §14) — a `node:net`\n\t// socket without an explicit encoding yields Buffers, but the listener parameter is\n\t// `unknown`, so it crosses through this guard, never an assertion. A non-Buffer\n\t// chunk (a string from a mis-encoded socket) is normalized; anything else is dropped.\n\t#bytes(chunk: unknown): Buffer | undefined {\n\t\tif (Buffer.isBuffer(chunk)) return chunk\n\t\tif (typeof chunk === 'string') return Buffer.from(chunk, 'utf-8')\n\t\treturn undefined\n\t}\n}\n","import type { NodeWebSocketInterface, NodeWebSocketOptions } from './types.js'\nimport { NodeWebSocket } from './NodeWebSocket.js'\n\n/**\n * Create a server-native WebSocket over a raw upgraded `node:stream` Duplex socket.\n *\n * @remarks\n * The construction entry point for the {@link NodeWebSocketInterface} (AGENTS §8). Pass\n * the upgraded `socket` plus the client's `Sec-WebSocket-Key` as `key` to run in SERVER\n * mode — the wrapper writes the `101 Switching Protocols` handshake and sends unmasked\n * frames; omit `key` for CLIENT mode (no handshake, masked frames). This is the\n * lean-native handle; it speaks only the WebSocket wire protocol — an MCP transport (the\n * later chunk) is built ON it. It is the WebSocket counterpart to\n * `createSQLiteDatabase` / `createIndexedDBDatabase`.\n *\n * @param options - The {@link NodeWebSocketOptions} (`socket`, optional `key` / `head` /\n * `protocol` / `on`)\n * @returns A typed {@link NodeWebSocketInterface}\n *\n * @example\n * ```ts\n * import { createNodeWebSocket } from '@src/server'\n *\n * // In a node:http 'upgrade' handler — server mode, identified by the client key:\n * server.on('upgrade', (request, socket, head) => {\n * \tconst ws = createNodeWebSocket({\n * \t\tsocket,\n * \t\tkey: request.headers['sec-websocket-key'],\n * \t\thead,\n * \t\ton: { message: (text) => ws.send(`echo: ${text}`) },\n * \t})\n * })\n * ```\n */\nexport function createNodeWebSocket(options: NodeWebSocketOptions): NodeWebSocketInterface {\n\treturn new NodeWebSocket(options)\n}\n"],"mappings":";;;;;;;;;;;;AAgBA,IAAa,iBAAiB;;AAG9B,IAAa,oBAAoB;;AAGjC,IAAa,wBAAwB;;AAGrC,IAAa,0BAA0B;;AAGvC,IAAa,gCAAgC;;AAG7C,IAAa,yBAAyB;;AAGtC,IAAa,wBAAwB;;AAGrC,IAAa,wBAAwB;;AAGrC,IAAa,6BAAkD;;AAG/D,IAAa,uBAA4C;;AAGzD,IAAa,0BAA+C;;AAG5D,IAAa,yBAA8C;;AAG3D,IAAa,yBAAyB;;AAGtC,IAAa,2BAA2B;;AAGxC,IAAa,8BAA8B;;AAG3C,IAAa,0BAA0B;;AAGvC,IAAa,yBAAyB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