@orkestrel/websocket 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +55 -0
- package/dist/src/server/index.cjs +608 -0
- package/dist/src/server/index.cjs.map +1 -0
- package/dist/src/server/index.d.cts +399 -0
- package/dist/src/server/index.d.ts +399 -0
- package/dist/src/server/index.js +580 -0
- package/dist/src/server/index.js.map +1 -0
- package/package.json +83 -0
|
@@ -0,0 +1,580 @@
|
|
|
1
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
2
|
+
import { Emitter } from "@orkestrel/emitter";
|
|
3
|
+
//#region src/server/constants.ts
|
|
4
|
+
/**
|
|
5
|
+
* The RFC 6455 GUID concatenated to a client's `Sec-WebSocket-Key` before the SHA-1
|
|
6
|
+
* hash that yields the `Sec-WebSocket-Accept` response value.
|
|
7
|
+
*
|
|
8
|
+
* @remarks
|
|
9
|
+
* A fixed, spec-mandated constant (RFC 6455 §4.2.2) — read only by
|
|
10
|
+
* {@link computeWebSocketAccept}.
|
|
11
|
+
*/
|
|
12
|
+
var WEBSOCKET_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
|
|
13
|
+
/** The WebSocket protocol version this wrapper speaks (`Sec-WebSocket-Version: 13`). */
|
|
14
|
+
var WEBSOCKET_VERSION = "13";
|
|
15
|
+
/** Text frame opcode — a UTF-8 payload (RFC 6455 §5.6). */
|
|
16
|
+
var WEBSOCKET_OPCODE_TEXT = 1;
|
|
17
|
+
/** Binary frame opcode — a raw byte payload (RFC 6455 §5.6). */
|
|
18
|
+
var WEBSOCKET_OPCODE_BINARY = 2;
|
|
19
|
+
/** Close frame opcode — a control frame ending the connection (RFC 6455 §5.5.1). */
|
|
20
|
+
var WEBSOCKET_OPCODE_CLOSE = 8;
|
|
21
|
+
/** Ping frame opcode — a control frame the peer must answer with a pong (RFC 6455 §5.5.2). */
|
|
22
|
+
var WEBSOCKET_OPCODE_PING = 9;
|
|
23
|
+
/** Pong frame opcode — a control frame answering a ping (RFC 6455 §5.5.3). */
|
|
24
|
+
var WEBSOCKET_OPCODE_PONG = 10;
|
|
25
|
+
/** Ready state for a connecting WebSocket (before the handshake completes). */
|
|
26
|
+
var WEBSOCKET_READY_CONNECTING = 0;
|
|
27
|
+
/** Ready state for an open WebSocket (the handshake completed; frames flow). */
|
|
28
|
+
var WEBSOCKET_READY_OPEN = 1;
|
|
29
|
+
/** Ready state for a closing WebSocket (a close frame was sent or received). */
|
|
30
|
+
var WEBSOCKET_READY_CLOSING = 2;
|
|
31
|
+
/** Ready state for a closed WebSocket (the socket ended). */
|
|
32
|
+
var WEBSOCKET_READY_CLOSED = 3;
|
|
33
|
+
/** Normal-closure status code (RFC 6455 §7.4.1) — the default `close` code. */
|
|
34
|
+
var WEBSOCKET_CLOSE_NORMAL = 1e3;
|
|
35
|
+
/** Protocol-error status code (RFC 6455 §7.4.1) — a framing/state rule was violated. */
|
|
36
|
+
var WEBSOCKET_CLOSE_PROTOCOL = 1002;
|
|
37
|
+
/** 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). */
|
|
38
|
+
var WEBSOCKET_CLOSE_UNSUPPORTED = 1003;
|
|
39
|
+
/** Invalid-frame-payload-data status code (RFC 6455 §7.4.1) — e.g. non-UTF-8 text or an unparseable close reason. */
|
|
40
|
+
var WEBSOCKET_CLOSE_INVALID = 1007;
|
|
41
|
+
/** Message-too-big status code (RFC 6455 §7.4.1) — a reassembled message exceeded the payload cap. */
|
|
42
|
+
var WEBSOCKET_CLOSE_TOOBIG = 1009;
|
|
43
|
+
/** The default maximum inbound single-frame length AND reassembled-message total byte count (100 MiB — the `ws` package default). */
|
|
44
|
+
var WEBSOCKET_MAX_PAYLOAD = 104857600;
|
|
45
|
+
/** The default close-handshake timeout in milliseconds — how long `close()` waits for the peer's echo before tearing the socket down. */
|
|
46
|
+
var WEBSOCKET_CLOSE_TIMEOUT_MS = 3e4;
|
|
47
|
+
/** 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). */
|
|
48
|
+
var WEBSOCKET_FAIL_TIMEOUT_MS = 1e3;
|
|
49
|
+
/** The maximum control-frame payload length in bytes (RFC 6455 §5.5). */
|
|
50
|
+
var WEBSOCKET_CONTROL_MAXLEN = 125;
|
|
51
|
+
//#endregion
|
|
52
|
+
//#region src/server/helpers.ts
|
|
53
|
+
/**
|
|
54
|
+
* Compute the `Sec-WebSocket-Accept` response value for an RFC 6455 upgrade.
|
|
55
|
+
*
|
|
56
|
+
* @remarks
|
|
57
|
+
* The base64-encoded SHA-1 of the client's `Sec-WebSocket-Key` concatenated with the
|
|
58
|
+
* fixed {@link WEBSOCKET_GUID} (RFC 6455 §4.2.2) — the proof the server understood the
|
|
59
|
+
* handshake. Pure and deterministic.
|
|
60
|
+
*
|
|
61
|
+
* @param key - The client's `Sec-WebSocket-Key` header value
|
|
62
|
+
* @returns The base64 accept token to send back as `Sec-WebSocket-Accept`
|
|
63
|
+
*/
|
|
64
|
+
function computeWebSocketAccept(key) {
|
|
65
|
+
return createHash("sha1").update(key + WEBSOCKET_GUID).digest("base64");
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Decode a single RFC 6455 frame from the front of a buffer.
|
|
69
|
+
*
|
|
70
|
+
* @remarks
|
|
71
|
+
* Reads the FIN bit and opcode (byte 0), the mask bit and 7-bit payload length (byte
|
|
72
|
+
* 1) — extended to a 16-bit length when the 7-bit field is `126`, or a 64-bit length
|
|
73
|
+
* when it is `127` — the optional 4-byte mask key, then the payload, XOR-unmasking it
|
|
74
|
+
* against the key when the mask bit is set (client→server frames MUST be masked, RFC
|
|
75
|
+
* 6455 §5.3; an unmasked frame still decodes, leaving the payload as-is, so the caller
|
|
76
|
+
* can enforce policy). Returns `undefined` the moment the buffer is too short for the
|
|
77
|
+
* part it is up to (the length prefix, the mask, or the full payload) — the signal to
|
|
78
|
+
* the caller to read more bytes and retry, exactly like {@link SSEParser} on a partial
|
|
79
|
+
* line. `consumed` is the total bytes the frame occupied, so the caller slices the
|
|
80
|
+
* remainder. Pure; never throws on a short buffer.
|
|
81
|
+
*
|
|
82
|
+
* @param buffer - The accumulation buffer to decode the next frame from
|
|
83
|
+
* @returns The parsed {@link WebSocketFrame}, or `undefined` when the buffer is incomplete
|
|
84
|
+
*/
|
|
85
|
+
function parseWebSocketFrame(buffer) {
|
|
86
|
+
if (buffer.length < 2) return void 0;
|
|
87
|
+
const firstByte = buffer[0] ?? 0;
|
|
88
|
+
const secondByte = buffer[1] ?? 0;
|
|
89
|
+
const fin = (firstByte & 128) !== 0;
|
|
90
|
+
const rsv = (firstByte & 112) >> 4;
|
|
91
|
+
const opcode = firstByte & 15;
|
|
92
|
+
const masked = (secondByte & 128) !== 0;
|
|
93
|
+
let length = secondByte & 127;
|
|
94
|
+
let offset = 2;
|
|
95
|
+
if (length === 126) {
|
|
96
|
+
if (buffer.length < offset + 2) return void 0;
|
|
97
|
+
length = buffer.readUInt16BE(offset);
|
|
98
|
+
offset += 2;
|
|
99
|
+
} else if (length === 127) {
|
|
100
|
+
if (buffer.length < offset + 8) return void 0;
|
|
101
|
+
const high = buffer.readUInt32BE(offset);
|
|
102
|
+
const low = buffer.readUInt32BE(offset + 4);
|
|
103
|
+
length = high * 4294967296 + low;
|
|
104
|
+
offset += 8;
|
|
105
|
+
}
|
|
106
|
+
let mask;
|
|
107
|
+
if (masked) {
|
|
108
|
+
if (buffer.length < offset + 4) return void 0;
|
|
109
|
+
mask = buffer.subarray(offset, offset + 4);
|
|
110
|
+
offset += 4;
|
|
111
|
+
}
|
|
112
|
+
if (buffer.length < offset + length) return void 0;
|
|
113
|
+
const payload = Buffer.alloc(length);
|
|
114
|
+
buffer.copy(payload, 0, offset, offset + length);
|
|
115
|
+
if (mask !== void 0) for (let index = 0; index < length; index += 1) payload[index] = (payload[index] ?? 0) ^ (mask[index % 4] ?? 0);
|
|
116
|
+
return {
|
|
117
|
+
fin,
|
|
118
|
+
opcode,
|
|
119
|
+
payload,
|
|
120
|
+
consumed: offset + length,
|
|
121
|
+
masked,
|
|
122
|
+
rsv
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* Read the declared payload length off the front of a buffer, without buffering or
|
|
127
|
+
* reading the payload itself.
|
|
128
|
+
*
|
|
129
|
+
* @remarks
|
|
130
|
+
* Decodes only byte 1's 7-bit length field, extended by the 16-bit (`126`) or 64-bit
|
|
131
|
+
* (`127`) form exactly like {@link parseWebSocketFrame} — but stops there, so a caller
|
|
132
|
+
* can reject an over-cap frame the moment its length is known, before the payload
|
|
133
|
+
* bytes have even arrived. Returns `undefined` until the length field itself is fully
|
|
134
|
+
* buffered (mirrors the parser's incomplete-buffer contract). Pure; never throws.
|
|
135
|
+
*
|
|
136
|
+
* @param buffer - The accumulation buffer to read the next frame's length from
|
|
137
|
+
* @returns The declared payload length, or `undefined` when the buffer is too short to know it yet
|
|
138
|
+
*
|
|
139
|
+
* @example
|
|
140
|
+
* ```ts
|
|
141
|
+
* const declared = measureWebSocketFrame(buffer)
|
|
142
|
+
* if (declared !== undefined && declared > limit) fail(WEBSOCKET_CLOSE_TOOBIG)
|
|
143
|
+
* ```
|
|
144
|
+
*/
|
|
145
|
+
function measureWebSocketFrame(buffer) {
|
|
146
|
+
if (buffer.length < 2) return void 0;
|
|
147
|
+
let length = (buffer[1] ?? 0) & 127;
|
|
148
|
+
const offset = 2;
|
|
149
|
+
if (length === 126) {
|
|
150
|
+
if (buffer.length < 4) return void 0;
|
|
151
|
+
length = buffer.readUInt16BE(offset);
|
|
152
|
+
} else if (length === 127) {
|
|
153
|
+
if (buffer.length < 10) return void 0;
|
|
154
|
+
const high = buffer.readUInt32BE(offset);
|
|
155
|
+
const low = buffer.readUInt32BE(6);
|
|
156
|
+
length = high * 4294967296 + low;
|
|
157
|
+
}
|
|
158
|
+
return length;
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* Decode a byte sequence as strict UTF-8, or signal it is malformed.
|
|
162
|
+
*
|
|
163
|
+
* @remarks
|
|
164
|
+
* Wraps `TextDecoder('utf-8', { fatal: true })` in a try/catch so a malformed sequence
|
|
165
|
+
* returns `undefined` instead of throwing (AGENTS §14 — a guard-adjacent coercer never
|
|
166
|
+
* throws on bad input). Pure.
|
|
167
|
+
*
|
|
168
|
+
* @param bytes - The raw bytes to decode
|
|
169
|
+
* @returns The decoded string, or `undefined` when `bytes` is not valid UTF-8
|
|
170
|
+
*
|
|
171
|
+
* @example
|
|
172
|
+
* ```ts
|
|
173
|
+
* const text = parseUTF8(payload)
|
|
174
|
+
* if (text === undefined) fail(WEBSOCKET_CLOSE_INVALID)
|
|
175
|
+
* ```
|
|
176
|
+
*/
|
|
177
|
+
function parseUTF8(bytes) {
|
|
178
|
+
try {
|
|
179
|
+
return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
|
|
180
|
+
} catch {
|
|
181
|
+
return;
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
/**
|
|
185
|
+
* Whether a numeric value is a valid RFC 6455 close status code to RECEIVE (§7.4.1).
|
|
186
|
+
*
|
|
187
|
+
* @remarks
|
|
188
|
+
* True for `1000`–`1003`, `1007`–`1014`, and the application range `3000`–`4999`; false
|
|
189
|
+
* for anything below `1000`, the reserved-for-local-use-only codes `1004`–`1006` and
|
|
190
|
+
* `1015`, and the unassigned `1016`–`2999` range. The `1012`–`1014` extension of the
|
|
191
|
+
* strict RFC 6455 receivable set is a deliberate IANA-interop choice: those three codes
|
|
192
|
+
* (Service Restart, Try Again Later, Bad Gateway) are IANA-registered in the WebSocket
|
|
193
|
+
* Close Code Number Registry and accepted by the `ws` ecosystem and modern conformance
|
|
194
|
+
* suites, so a peer sending one is not treated as a protocol violation. Pure predicate,
|
|
195
|
+
* never throws.
|
|
196
|
+
*
|
|
197
|
+
* @param code - The close status code to validate
|
|
198
|
+
* @returns `true` when `code` is a valid RFC 6455 close code
|
|
199
|
+
*
|
|
200
|
+
* @example
|
|
201
|
+
* ```ts
|
|
202
|
+
* if (!isCloseCode(code)) fail(WEBSOCKET_CLOSE_PROTOCOL)
|
|
203
|
+
* ```
|
|
204
|
+
*/
|
|
205
|
+
function isCloseCode(code) {
|
|
206
|
+
if (code >= 1e3 && code <= 1003) return true;
|
|
207
|
+
if (code >= 1007 && code <= 1014) return true;
|
|
208
|
+
if (code >= 3e3 && code <= 4999) return true;
|
|
209
|
+
return false;
|
|
210
|
+
}
|
|
211
|
+
/**
|
|
212
|
+
* Encode a single RFC 6455 frame to its wire bytes — the inverse of
|
|
213
|
+
* {@link parseWebSocketFrame}.
|
|
214
|
+
*
|
|
215
|
+
* @remarks
|
|
216
|
+
* Builds a final (FIN-set) frame: byte 0 is `0x80 | opcode`; the payload length uses
|
|
217
|
+
* the 7-bit form below 126, the `126` + 16-bit form below 65 536, or the `127` +
|
|
218
|
+
* 64-bit form beyond; when `masked` is set the mask bit is set, a 4-byte key (supplied
|
|
219
|
+
* via `options.mask`, else random) is written, and the payload is XOR-masked. Server→
|
|
220
|
+
* client frames are unmasked (the default); pass `masked: true` to encode a CLIENT
|
|
221
|
+
* frame (e.g. to feed the parser in a test). A `string` payload is encoded as UTF-8.
|
|
222
|
+
* Returns one contiguous `Buffer` (header + payload), so the wrapper writes it with a
|
|
223
|
+
* single `socket.write`. Pure.
|
|
224
|
+
*
|
|
225
|
+
* @param opcode - The frame opcode (a `WEBSOCKET_OPCODE_*` value)
|
|
226
|
+
* @param payload - The payload, a `Buffer` or a UTF-8 `string`
|
|
227
|
+
* @param options - Masking control ({@link WebSocketEncodeOptions}); defaults to unmasked
|
|
228
|
+
* @returns The complete frame as wire bytes
|
|
229
|
+
*/
|
|
230
|
+
function encodeWebSocketFrame(opcode, payload, options) {
|
|
231
|
+
const body = typeof payload === "string" ? Buffer.from(payload, "utf-8") : payload;
|
|
232
|
+
const length = body.length;
|
|
233
|
+
const masked = options?.masked === true;
|
|
234
|
+
const mask = masked ? options?.mask ?? randomBytes(4) : void 0;
|
|
235
|
+
const maskBit = masked ? 128 : 0;
|
|
236
|
+
const extended = length < 126 ? 0 : length < 65536 ? 2 : 8;
|
|
237
|
+
const header = Buffer.alloc(2 + extended + (mask !== void 0 ? 4 : 0));
|
|
238
|
+
header[0] = 128 | opcode;
|
|
239
|
+
if (length < 126) header[1] = maskBit | length;
|
|
240
|
+
else if (length < 65536) {
|
|
241
|
+
header[1] = maskBit | 126;
|
|
242
|
+
header.writeUInt16BE(length, 2);
|
|
243
|
+
} else {
|
|
244
|
+
header[1] = maskBit | 127;
|
|
245
|
+
header.writeUInt32BE(Math.floor(length / 4294967296), 2);
|
|
246
|
+
header.writeUInt32BE(length % 4294967296, 6);
|
|
247
|
+
}
|
|
248
|
+
if (mask === void 0) return Buffer.concat([header, body]);
|
|
249
|
+
mask.copy(header, header.length - 4);
|
|
250
|
+
const maskedBody = Buffer.alloc(length);
|
|
251
|
+
for (let index = 0; index < length; index += 1) maskedBody[index] = (body[index] ?? 0) ^ (mask[index % 4] ?? 0);
|
|
252
|
+
return Buffer.concat([header, maskedBody]);
|
|
253
|
+
}
|
|
254
|
+
//#endregion
|
|
255
|
+
//#region src/server/NodeWebSocket.ts
|
|
256
|
+
/**
|
|
257
|
+
* A server-native WebSocket over a raw upgraded `node:stream` Duplex — the lean
|
|
258
|
+
* wrapper around the RFC 6455 wire protocol.
|
|
259
|
+
*
|
|
260
|
+
* @remarks
|
|
261
|
+
* Created by `createNodeWebSocket`. When given a client `key` it runs in SERVER mode —
|
|
262
|
+
* it writes the `101 Switching Protocols` handshake (`computeWebSocketAccept(key)`) and
|
|
263
|
+
* emits `open`; given no key it runs in CLIENT mode (no handshake, frames masked). It
|
|
264
|
+
* then listens on the socket's `data`, accumulating bytes in `#buffer` and decoding
|
|
265
|
+
* every complete frame with {@link parseWebSocketFrame} (slicing `consumed` and
|
|
266
|
+
* re-parsing the remainder): a TEXT frame — reassembling continuation fragments across
|
|
267
|
+
* `fin: false` frames — decodes to UTF-8 and emits `message`; a PING is auto-answered
|
|
268
|
+
* with a PONG and emits `ping`; a PONG emits `pong`; a CLOSE is echoed and ends the
|
|
269
|
+
* socket, emitting `close`. `send` writes a text frame, `ping` a ping, `close` a close
|
|
270
|
+
* frame; `destroy` tears down immediately. It owns a typed `#emitter` (AGENTS §13) that
|
|
271
|
+
* isolates a throwing listener and routes the error to its own `error` handler (the `error`
|
|
272
|
+
* option) — the socket never crashes. The untyped socket `data` is narrowed to a `Buffer`
|
|
273
|
+
* with a guard, never an assertion (AGENTS §14).
|
|
274
|
+
*/
|
|
275
|
+
var NodeWebSocket = class {
|
|
276
|
+
#emitter;
|
|
277
|
+
#socket;
|
|
278
|
+
#protocol;
|
|
279
|
+
#masked;
|
|
280
|
+
#payload;
|
|
281
|
+
#timeout;
|
|
282
|
+
#requireMask;
|
|
283
|
+
#signal;
|
|
284
|
+
#buffer = Buffer.alloc(0);
|
|
285
|
+
#readyState = 0;
|
|
286
|
+
#code = void 0;
|
|
287
|
+
#reason = void 0;
|
|
288
|
+
#fragments = [];
|
|
289
|
+
#messageOpcode = void 0;
|
|
290
|
+
#fragmentBytes = 0;
|
|
291
|
+
#closeTimer = void 0;
|
|
292
|
+
#destroyed = false;
|
|
293
|
+
#onData = (chunk) => {
|
|
294
|
+
if (this.#readyState === 3) return;
|
|
295
|
+
const bytes = this.#bytes(chunk);
|
|
296
|
+
if (bytes === void 0) return;
|
|
297
|
+
this.#ingest(bytes);
|
|
298
|
+
};
|
|
299
|
+
#onClose = () => {
|
|
300
|
+
this.#finish();
|
|
301
|
+
};
|
|
302
|
+
#onError = (error) => {
|
|
303
|
+
this.#emitter.emit("error", error);
|
|
304
|
+
};
|
|
305
|
+
#onAbort = () => {
|
|
306
|
+
this.destroy();
|
|
307
|
+
};
|
|
308
|
+
constructor(options) {
|
|
309
|
+
this.#emitter = new Emitter({
|
|
310
|
+
on: options.on,
|
|
311
|
+
error: options.error
|
|
312
|
+
});
|
|
313
|
+
this.#socket = options.socket;
|
|
314
|
+
this.#protocol = options.protocol;
|
|
315
|
+
this.#masked = options.key === void 0;
|
|
316
|
+
this.#payload = options.payload ?? 104857600;
|
|
317
|
+
this.#timeout = options.timeout ?? 3e4;
|
|
318
|
+
this.#requireMask = !this.#masked;
|
|
319
|
+
this.#signal = options.signal;
|
|
320
|
+
if (options.key !== void 0) {
|
|
321
|
+
const protocol = this.#protocol === void 0 ? "" : `Sec-WebSocket-Protocol: ${this.#protocol}\r\n`;
|
|
322
|
+
this.#socket.write(`HTTP/1.1 101 Switching Protocols\r
|
|
323
|
+
Upgrade: websocket\r
|
|
324
|
+
Connection: Upgrade\r
|
|
325
|
+
Sec-WebSocket-Accept: ${computeWebSocketAccept(options.key)}\r\n` + protocol + "\r\n");
|
|
326
|
+
}
|
|
327
|
+
this.#readyState = 1;
|
|
328
|
+
this.#socket.on("data", this.#onData);
|
|
329
|
+
this.#socket.on("close", this.#onClose);
|
|
330
|
+
this.#socket.on("error", this.#onError);
|
|
331
|
+
this.#emitter.emit("open");
|
|
332
|
+
const head = options.head;
|
|
333
|
+
if (head !== void 0 && head.length > 0) this.#ingest(head);
|
|
334
|
+
if (this.#readyState !== 3) if (this.#signal?.aborted === true) this.destroy();
|
|
335
|
+
else this.#signal?.addEventListener("abort", this.#onAbort, { once: true });
|
|
336
|
+
}
|
|
337
|
+
get emitter() {
|
|
338
|
+
return this.#emitter;
|
|
339
|
+
}
|
|
340
|
+
get readyState() {
|
|
341
|
+
return this.#readyState;
|
|
342
|
+
}
|
|
343
|
+
send(data) {
|
|
344
|
+
if (this.#readyState !== 1) return;
|
|
345
|
+
this.#write(1, Buffer.from(data, "utf-8"));
|
|
346
|
+
}
|
|
347
|
+
ping(data) {
|
|
348
|
+
if (this.#readyState !== 1) return;
|
|
349
|
+
if (data !== void 0 && Buffer.byteLength(data, "utf-8") > 125) throw new RangeError("ping payload exceeds 125 bytes");
|
|
350
|
+
this.#write(9, data === void 0 ? Buffer.alloc(0) : Buffer.from(data, "utf-8"));
|
|
351
|
+
}
|
|
352
|
+
close(code, reason) {
|
|
353
|
+
if (this.#readyState === 2 || this.#readyState === 3) return;
|
|
354
|
+
if (code !== void 0 && !isCloseCode(code)) throw new RangeError("invalid close code");
|
|
355
|
+
if (reason !== void 0 && Buffer.byteLength(reason, "utf-8") > 123) throw new RangeError("close reason exceeds 123 bytes");
|
|
356
|
+
this.#readyState = 2;
|
|
357
|
+
this.#code = code ?? 1e3;
|
|
358
|
+
this.#reason = reason === void 0 || reason.length === 0 ? void 0 : reason;
|
|
359
|
+
this.#write(8, this.#encodeClose(this.#code, this.#reason));
|
|
360
|
+
this.#socket.end();
|
|
361
|
+
this.#closeTimer = setTimeout(() => this.destroy(), this.#timeout);
|
|
362
|
+
this.#closeTimer.unref();
|
|
363
|
+
}
|
|
364
|
+
destroy() {
|
|
365
|
+
if (this.#destroyed) return;
|
|
366
|
+
this.#destroyed = true;
|
|
367
|
+
this.#socket.off("data", this.#onData);
|
|
368
|
+
this.#socket.off("close", this.#onClose);
|
|
369
|
+
this.#socket.off("error", this.#onError);
|
|
370
|
+
this.#signal?.removeEventListener("abort", this.#onAbort);
|
|
371
|
+
clearTimeout(this.#closeTimer);
|
|
372
|
+
this.#closeTimer = void 0;
|
|
373
|
+
if (!this.#socket.destroyed) this.#socket.destroy();
|
|
374
|
+
this.#finish();
|
|
375
|
+
this.#emitter.destroy();
|
|
376
|
+
}
|
|
377
|
+
#drain() {
|
|
378
|
+
for (;;) {
|
|
379
|
+
const frame = parseWebSocketFrame(this.#buffer);
|
|
380
|
+
if (frame === void 0) return;
|
|
381
|
+
this.#buffer = this.#buffer.subarray(frame.consumed);
|
|
382
|
+
this.#dispatch(frame.fin, frame.opcode, frame.payload, frame.masked, frame.rsv);
|
|
383
|
+
if (this.#readyState === 3) return;
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
#dispatch(fin, opcode, payload, masked, rsv) {
|
|
387
|
+
if (rsv !== 0) {
|
|
388
|
+
this.#fail(WEBSOCKET_CLOSE_PROTOCOL);
|
|
389
|
+
return;
|
|
390
|
+
}
|
|
391
|
+
if (masked !== this.#requireMask) {
|
|
392
|
+
this.#fail(WEBSOCKET_CLOSE_PROTOCOL);
|
|
393
|
+
return;
|
|
394
|
+
}
|
|
395
|
+
if (opcode === 8 || opcode === 9 || opcode === 10) {
|
|
396
|
+
if (!fin || payload.length > 125) {
|
|
397
|
+
this.#fail(WEBSOCKET_CLOSE_PROTOCOL);
|
|
398
|
+
return;
|
|
399
|
+
}
|
|
400
|
+
if (opcode === 9) {
|
|
401
|
+
this.#write(10, payload);
|
|
402
|
+
this.#emitter.emit("ping");
|
|
403
|
+
return;
|
|
404
|
+
}
|
|
405
|
+
if (opcode === 10) {
|
|
406
|
+
this.#emitter.emit("pong");
|
|
407
|
+
return;
|
|
408
|
+
}
|
|
409
|
+
this.#close(payload);
|
|
410
|
+
return;
|
|
411
|
+
}
|
|
412
|
+
if (opcode === 1 || opcode === 2) {
|
|
413
|
+
if (this.#messageOpcode !== void 0) {
|
|
414
|
+
this.#fail(WEBSOCKET_CLOSE_PROTOCOL);
|
|
415
|
+
return;
|
|
416
|
+
}
|
|
417
|
+
this.#messageOpcode = opcode;
|
|
418
|
+
} else if (opcode === 0) {
|
|
419
|
+
if (this.#messageOpcode === void 0) {
|
|
420
|
+
this.#fail(WEBSOCKET_CLOSE_PROTOCOL);
|
|
421
|
+
return;
|
|
422
|
+
}
|
|
423
|
+
} else {
|
|
424
|
+
this.#fail(WEBSOCKET_CLOSE_PROTOCOL);
|
|
425
|
+
return;
|
|
426
|
+
}
|
|
427
|
+
this.#fragments.push(payload);
|
|
428
|
+
this.#fragmentBytes += payload.length;
|
|
429
|
+
if (this.#fragmentBytes > this.#payload) {
|
|
430
|
+
this.#fail(WEBSOCKET_CLOSE_TOOBIG);
|
|
431
|
+
return;
|
|
432
|
+
}
|
|
433
|
+
if (!fin) return;
|
|
434
|
+
if (this.#messageOpcode === 2) {
|
|
435
|
+
this.#fail(WEBSOCKET_CLOSE_UNSUPPORTED);
|
|
436
|
+
return;
|
|
437
|
+
}
|
|
438
|
+
const text = parseUTF8(Buffer.concat(this.#fragments));
|
|
439
|
+
if (text === void 0) {
|
|
440
|
+
this.#fail(WEBSOCKET_CLOSE_INVALID);
|
|
441
|
+
return;
|
|
442
|
+
}
|
|
443
|
+
this.#emitter.emit("message", text);
|
|
444
|
+
this.#messageOpcode = void 0;
|
|
445
|
+
this.#fragments = [];
|
|
446
|
+
this.#fragmentBytes = 0;
|
|
447
|
+
}
|
|
448
|
+
#close(payload) {
|
|
449
|
+
if (!this.#decodeClose(payload)) return;
|
|
450
|
+
if (this.#readyState === 1) {
|
|
451
|
+
this.#readyState = 2;
|
|
452
|
+
this.#write(8, payload);
|
|
453
|
+
}
|
|
454
|
+
this.#socket.end();
|
|
455
|
+
this.#socket.off("data", this.#onData);
|
|
456
|
+
this.#socket.off("close", this.#onClose);
|
|
457
|
+
this.#socket.off("error", this.#onError);
|
|
458
|
+
this.#finish();
|
|
459
|
+
}
|
|
460
|
+
#fail(code, reason) {
|
|
461
|
+
if (this.#readyState === 2 || this.#readyState === 3) return;
|
|
462
|
+
this.#code = code;
|
|
463
|
+
this.#reason = reason;
|
|
464
|
+
this.#readyState = 2;
|
|
465
|
+
this.#socket.off("data", this.#onData);
|
|
466
|
+
this.#socket.off("close", this.#onClose);
|
|
467
|
+
this.#socket.off("error", this.#onError);
|
|
468
|
+
this.#write(8, this.#encodeClose(code, reason));
|
|
469
|
+
this.#socket.end(() => {
|
|
470
|
+
if (!this.#socket.destroyed) this.#socket.destroy();
|
|
471
|
+
clearTimeout(this.#closeTimer);
|
|
472
|
+
this.#closeTimer = void 0;
|
|
473
|
+
});
|
|
474
|
+
this.#messageOpcode = void 0;
|
|
475
|
+
this.#fragments = [];
|
|
476
|
+
this.#fragmentBytes = 0;
|
|
477
|
+
this.#finish();
|
|
478
|
+
this.#closeTimer = setTimeout(() => {
|
|
479
|
+
if (!this.#socket.destroyed) this.#socket.destroy();
|
|
480
|
+
}, WEBSOCKET_FAIL_TIMEOUT_MS);
|
|
481
|
+
this.#closeTimer.unref();
|
|
482
|
+
}
|
|
483
|
+
#write(opcode, payload) {
|
|
484
|
+
if (this.#socket.destroyed) return;
|
|
485
|
+
this.#socket.write(encodeWebSocketFrame(opcode, payload, { masked: this.#masked }));
|
|
486
|
+
}
|
|
487
|
+
#encodeClose(code, reason) {
|
|
488
|
+
if (code === void 0) return Buffer.alloc(0);
|
|
489
|
+
const text = reason === void 0 ? Buffer.alloc(0) : Buffer.from(reason, "utf-8");
|
|
490
|
+
const payload = Buffer.alloc(2 + text.length);
|
|
491
|
+
payload.writeUInt16BE(code, 0);
|
|
492
|
+
text.copy(payload, 2);
|
|
493
|
+
return payload;
|
|
494
|
+
}
|
|
495
|
+
#decodeClose(payload) {
|
|
496
|
+
if (payload.length === 0) {
|
|
497
|
+
this.#code = void 0;
|
|
498
|
+
this.#reason = void 0;
|
|
499
|
+
return true;
|
|
500
|
+
}
|
|
501
|
+
if (payload.length === 1) {
|
|
502
|
+
this.#fail(WEBSOCKET_CLOSE_PROTOCOL);
|
|
503
|
+
return false;
|
|
504
|
+
}
|
|
505
|
+
const code = payload.readUInt16BE(0);
|
|
506
|
+
if (!isCloseCode(code)) {
|
|
507
|
+
this.#fail(WEBSOCKET_CLOSE_PROTOCOL);
|
|
508
|
+
return false;
|
|
509
|
+
}
|
|
510
|
+
const reason = payload.length > 2 ? parseUTF8(payload.subarray(2)) : "";
|
|
511
|
+
if (reason === void 0) {
|
|
512
|
+
this.#fail(WEBSOCKET_CLOSE_INVALID);
|
|
513
|
+
return false;
|
|
514
|
+
}
|
|
515
|
+
this.#code = code;
|
|
516
|
+
this.#reason = reason.length === 0 ? void 0 : reason;
|
|
517
|
+
return true;
|
|
518
|
+
}
|
|
519
|
+
#finish() {
|
|
520
|
+
if (this.#readyState === 3) return;
|
|
521
|
+
clearTimeout(this.#closeTimer);
|
|
522
|
+
this.#closeTimer = void 0;
|
|
523
|
+
this.#signal?.removeEventListener("abort", this.#onAbort);
|
|
524
|
+
this.#readyState = 3;
|
|
525
|
+
this.#emitter.emit("close", this.#code, this.#reason);
|
|
526
|
+
}
|
|
527
|
+
#ingest(bytes) {
|
|
528
|
+
this.#buffer = Buffer.concat([this.#buffer, bytes]);
|
|
529
|
+
const declared = measureWebSocketFrame(this.#buffer);
|
|
530
|
+
if (declared !== void 0 && declared > this.#payload) {
|
|
531
|
+
this.#fail(WEBSOCKET_CLOSE_TOOBIG);
|
|
532
|
+
return;
|
|
533
|
+
}
|
|
534
|
+
this.#drain();
|
|
535
|
+
}
|
|
536
|
+
#bytes(chunk) {
|
|
537
|
+
if (Buffer.isBuffer(chunk)) return chunk;
|
|
538
|
+
if (typeof chunk === "string") return Buffer.from(chunk, "utf-8");
|
|
539
|
+
}
|
|
540
|
+
};
|
|
541
|
+
//#endregion
|
|
542
|
+
//#region src/server/factories.ts
|
|
543
|
+
/**
|
|
544
|
+
* Create a server-native WebSocket over a raw upgraded `node:stream` Duplex socket.
|
|
545
|
+
*
|
|
546
|
+
* @remarks
|
|
547
|
+
* The construction entry point for the {@link NodeWebSocketInterface} (AGENTS §8). Pass
|
|
548
|
+
* the upgraded `socket` plus the client's `Sec-WebSocket-Key` as `key` to run in SERVER
|
|
549
|
+
* mode — the wrapper writes the `101 Switching Protocols` handshake and sends unmasked
|
|
550
|
+
* frames; omit `key` for CLIENT mode (no handshake, masked frames). This is the
|
|
551
|
+
* lean-native handle; it speaks only the WebSocket wire protocol — an MCP transport (the
|
|
552
|
+
* later chunk) is built ON it. It is the WebSocket counterpart to
|
|
553
|
+
* `createSQLiteDatabase` / `createIndexedDBDatabase`.
|
|
554
|
+
*
|
|
555
|
+
* @param options - The {@link NodeWebSocketOptions} (`socket`, optional `key` / `head` /
|
|
556
|
+
* `protocol` / `on`)
|
|
557
|
+
* @returns A typed {@link NodeWebSocketInterface}
|
|
558
|
+
*
|
|
559
|
+
* @example
|
|
560
|
+
* ```ts
|
|
561
|
+
* import { createNodeWebSocket } from '@src/server'
|
|
562
|
+
*
|
|
563
|
+
* // In a node:http 'upgrade' handler — server mode, identified by the client key:
|
|
564
|
+
* server.on('upgrade', (request, socket, head) => {
|
|
565
|
+
* const ws = createNodeWebSocket({
|
|
566
|
+
* socket,
|
|
567
|
+
* key: request.headers['sec-websocket-key'],
|
|
568
|
+
* head,
|
|
569
|
+
* on: { message: (text) => ws.send(`echo: ${text}`) },
|
|
570
|
+
* })
|
|
571
|
+
* })
|
|
572
|
+
* ```
|
|
573
|
+
*/
|
|
574
|
+
function createNodeWebSocket(options) {
|
|
575
|
+
return new NodeWebSocket(options);
|
|
576
|
+
}
|
|
577
|
+
//#endregion
|
|
578
|
+
export { NodeWebSocket, WEBSOCKET_CLOSE_INVALID, WEBSOCKET_CLOSE_NORMAL, WEBSOCKET_CLOSE_PROTOCOL, WEBSOCKET_CLOSE_TIMEOUT_MS, WEBSOCKET_CLOSE_TOOBIG, WEBSOCKET_CLOSE_UNSUPPORTED, WEBSOCKET_CONTROL_MAXLEN, WEBSOCKET_FAIL_TIMEOUT_MS, WEBSOCKET_GUID, WEBSOCKET_MAX_PAYLOAD, WEBSOCKET_OPCODE_BINARY, WEBSOCKET_OPCODE_CLOSE, WEBSOCKET_OPCODE_PING, WEBSOCKET_OPCODE_PONG, WEBSOCKET_OPCODE_TEXT, WEBSOCKET_READY_CLOSED, WEBSOCKET_READY_CLOSING, WEBSOCKET_READY_CONNECTING, WEBSOCKET_READY_OPEN, WEBSOCKET_VERSION, computeWebSocketAccept, createNodeWebSocket, encodeWebSocketFrame, isCloseCode, measureWebSocketFrame, parseUTF8, parseWebSocketFrame };
|
|
579
|
+
|
|
580
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":["#emitter","#socket","#protocol","#masked","#payload","#timeout","#requireMask","#signal","#onData","#readyState","#bytes","#ingest","#onClose","#finish","#onError","#onAbort","#write","#code","#reason","#encodeClose","#closeTimer","#destroyed","#buffer","#dispatch","#fail","#close","#messageOpcode","#fragments","#fragmentBytes","#decodeClose","#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\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// 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\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.#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\tthis.#socket.end()\n\t\t// Detach the socket listeners here, mirroring `#fail` — the echo write above has\n\t\t// already gone out, so this cannot drop it, but it prevents a socket `error` fired\n\t\t// during the post-close `end()` flush from surfacing AFTER the terminal `close`\n\t\t// (the same asymmetry `#fail` guards against).\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.#finish()\n\t}\n\n\t// The single funnel for every RFC 6455 validation breach: close with `code`, DETACH\n\t// the socket 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.#socket.off('data', this.#onData)\n\t\tthis.#socket.off('close', this.#onClose)\n\t\tthis.#socket.off('error', this.#onError)\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// 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\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 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,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;;AAGtC,IAAa,wBAAwB;;AAGrC,IAAa,6BAA6B;;AAG1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