This commit is contained in:
DrSmoothl committed 2026-10-12 15:43:34 +08:00
1 parent effeb66554
commit 7c0519f75f
977 files changed
+198426 -158324

No files matched your search

+328 -236
View File
@@ -6,268 +6,360 @@ import { URL } from 'node:url';
import type { Socket } from 'node:net';
import native from './native';
import {
type AcceptedPerMessageDeflate,
type PerMessageDeflateConfig,
offerPerMessageDeflate,
parseAcceptedPerMessageDeflate,
type AcceptedPerMessageDeflate,
type PerMessageDeflateConfig,
offerPerMessageDeflate,
parseAcceptedPerMessageDeflate,
} from './extensions';
import { WebSocket as InternalWebSocket, CONNECTING, OPEN, CLOSED, isValidCloseCode, type SendCallback, type SendOptions } from './websocket';
import {
WebSocket as InternalWebSocket,
CONNECTING,
OPEN,
CLOSED,
isValidCloseCode,
type SendCallback,
type SendOptions,
} from './websocket';
interface ParsedHandshakeResponse {
statusCode: number;
statusMessage: string;
headers: Record<string, string>;
statusCode: number;
statusMessage: string;
headers: Record<string, string>;
}
function parseHeaders(headerBlock: string): ParsedHandshakeResponse {
const lines = headerBlock.split('\r\n');
const status = lines.shift() as string;
const m = /^HTTP\/1\.1\s+(\d+)\s*(.*)$/.exec(status);
if (!m) throw new Error('Bad HTTP status line: ' + status);
const headers: Record<string, string> = Object.create(null);
for (const line of lines) {
if (!line) continue;
const idx = line.indexOf(':');
if (idx < 0) continue;
const k = line.slice(0, idx).trim().toLowerCase();
const v = line.slice(idx + 1).trim();
headers[k] = v;
}
return { statusCode: Number(m[1]), statusMessage: m[2] ?? '', headers };
const lines = headerBlock.split('\r\n');
const status = lines.shift() as string;
const m = /^HTTP\/1\.1\s+(\d+)\s*(.*)$/.exec(status);
if (!m) {
throw new Error('Bad HTTP status line: ' + status);
}
const headers: Record<string, string> = Object.create(null);
for (const line of lines) {
if (!line) {
continue;
}
const idx = line.indexOf(':');
if (idx < 0) {
continue;
}
const k = line.slice(0, idx).trim().toLowerCase();
const v = line.slice(idx + 1).trim();
headers[k] = v;
}
return { statusCode: Number(m[1]), statusMessage: m[2] ?? '', headers };
}
export interface WebSocketClientOptions {
maxPayload?: number;
perMessageDeflate?: boolean | PerMessageDeflateConfig;
headers?: Record<string, string>;
socketOptions?: net.NetConnectOpts | tls.ConnectionOptions;
// Convenience: any TLS option also accepted at top-level (mirrors the `ws` API).
[key: string]: unknown;
maxPayload?: number;
perMessageDeflate?: boolean | PerMessageDeflateConfig;
headers?: Record<string, string>;
socketOptions?: net.NetConnectOpts | tls.ConnectionOptions;
// Convenience: any TLS option also accepted at top-level (mirrors the `ws` API).
[key: string]: unknown;
}
export class WebSocketClient extends EventEmitter {
static readonly CONNECTING = 0;
static readonly OPEN = 1;
static readonly CLOSING = 2;
static readonly CLOSED = 3;
static Server: unknown;
static readonly CONNECTING = 0;
static readonly OPEN = 1;
static readonly CLOSING = 2;
static readonly CLOSED = 3;
static Server: unknown;
private readonly _url: URL;
private readonly _secure: boolean;
private _readyState: number;
private readonly _maxPayload: number | undefined;
private _ws: InternalWebSocket | null = null;
private _pendingQueue: Array<{ data: Parameters<InternalWebSocket['send']>[0]; options?: SendOptions; cb?: SendCallback }> = [];
private readonly _perMessageDeflate: boolean | PerMessageDeflateConfig | undefined;
private readonly _protocols: string[] | undefined;
public protocol = '';
public extensions = '';
private readonly _url: URL;
private readonly _secure: boolean;
private _readyState: number;
private readonly _maxPayload: number | undefined;
private _ws: InternalWebSocket | null = null;
private _pendingQueue: Array<{
data: Parameters<InternalWebSocket['send']>[0];
options?: SendOptions;
cb?: SendCallback;
}> = [];
private readonly _perMessageDeflate: boolean | PerMessageDeflateConfig | undefined;
private readonly _protocols: string[] | undefined;
public protocol = '';
public extensions = '';
private readonly _socket: Socket;
private _handshakeBuf: Buffer = Buffer.alloc(0);
private _wsKey: string;
private _expectedAccept: string;
private readonly _socket: Socket;
private _handshakeBuf: Buffer = Buffer.alloc(0);
private _wsKey: string;
private _expectedAccept: string;
constructor(
address: string,
protocols?: string | string[] | WebSocketClientOptions,
options?: WebSocketClientOptions,
) {
super();
if (typeof protocols === 'object' && !Array.isArray(protocols) && protocols !== null) {
options = protocols as WebSocketClientOptions;
protocols = undefined;
}
options = options || {};
this._url = new URL(address);
if (this._url.protocol !== 'ws:' && this._url.protocol !== 'wss:') {
throw new Error('Only ws: and wss: URLs are supported');
}
this._secure = this._url.protocol === 'wss:';
this._readyState = CONNECTING;
this._maxPayload = options.maxPayload;
this._perMessageDeflate = options.perMessageDeflate;
this._protocols = Array.isArray(protocols) ? protocols.map(String) : (typeof protocols === 'string' ? [protocols] : undefined);
constructor(
address: string,
protocols?: string | string[] | WebSocketClientOptions,
options?: WebSocketClientOptions,
) {
super();
const host = this._url.hostname;
const port = this._url.port ? Number(this._url.port) : (this._secure ? 443 : 80);
// Generate random 16-byte Sec-WebSocket-Key per RFC 6455 §4.1.
const keyBytes = crypto.randomBytes(16);
this._wsKey = keyBytes.toString('base64');
this._expectedAccept = native.computeAcceptKey(this._wsKey);
const connectOpts: net.NetConnectOpts & tls.ConnectionOptions = {
host,
port,
...(options.socketOptions || {}),
} as net.NetConnectOpts & tls.ConnectionOptions;
const onConnect = () => {
const pathAndQuery = (this._url.pathname || '/') + (this._url.search || '');
const hostHeader = (this._url.port && Number(this._url.port) !== (this._secure ? 443 : 80))
? `${host}:${this._url.port}`
: host;
const reqLines = [
`GET ${pathAndQuery} HTTP/1.1`,
`Host: ${hostHeader}`,
'Upgrade: websocket',
'Connection: Upgrade',
`Sec-WebSocket-Key: ${this._wsKey}`,
'Sec-WebSocket-Version: 13',
];
if (this._protocols && this._protocols.length > 0) {
reqLines.push(`Sec-WebSocket-Protocol: ${this._protocols.join(', ')}`);
}
const extensionOffer = offerPerMessageDeflate(this._perMessageDeflate);
if (extensionOffer) {
reqLines.push(`Sec-WebSocket-Extensions: ${extensionOffer}`);
}
if (options!.headers) {
for (const [k, v] of Object.entries(options!.headers)) {
reqLines.push(`${k}: ${v}`);
if (typeof protocols === 'object' && !Array.isArray(protocols) && protocols !== null) {
options = protocols as WebSocketClientOptions;
protocols = undefined;
}
}
reqLines.push('', '');
this._socket.write(reqLines.join('\r\n'));
};
if (this._secure && (connectOpts as tls.ConnectionOptions).servername === undefined && net.isIP(host) === 0) {
(connectOpts as tls.ConnectionOptions).servername = host;
options = options || {};
this._url = new URL(address);
if (this._url.protocol !== 'ws:' && this._url.protocol !== 'wss:') {
throw new Error('Only ws: and wss: URLs are supported');
}
this._secure = this._url.protocol === 'wss:';
this._readyState = CONNECTING;
this._maxPayload = options.maxPayload;
this._perMessageDeflate = options.perMessageDeflate;
this._protocols = Array.isArray(protocols)
? protocols.map(String)
: typeof protocols === 'string'
? [protocols]
: undefined;
const host = this._url.hostname;
const port = this._url.port ? Number(this._url.port) : this._secure ? 443 : 80;
// Generate random 16-byte Sec-WebSocket-Key per RFC 6455 §4.1.
const keyBytes = crypto.randomBytes(16);
this._wsKey = keyBytes.toString('base64');
this._expectedAccept = native.computeAcceptKey(this._wsKey);
const connectOpts: net.NetConnectOpts & tls.ConnectionOptions = {
host,
port,
...(options.socketOptions || {}),
} as net.NetConnectOpts & tls.ConnectionOptions;
const onConnect = () => {
const pathAndQuery = (this._url.pathname || '/') + (this._url.search || '');
const hostHeader =
this._url.port && Number(this._url.port) !== (this._secure ? 443 : 80)
? `${host}:${this._url.port}`
: host;
const reqLines = [
`GET ${pathAndQuery} HTTP/1.1`,
`Host: ${hostHeader}`,
'Upgrade: websocket',
'Connection: Upgrade',
`Sec-WebSocket-Key: ${this._wsKey}`,
'Sec-WebSocket-Version: 13',
];
if (this._protocols && this._protocols.length > 0) {
reqLines.push(`Sec-WebSocket-Protocol: ${this._protocols.join(', ')}`);
}
const extensionOffer = offerPerMessageDeflate(this._perMessageDeflate);
if (extensionOffer) {
reqLines.push(`Sec-WebSocket-Extensions: ${extensionOffer}`);
}
if (options!.headers) {
for (const [k, v] of Object.entries(options!.headers)) {
reqLines.push(`${k}: ${v}`);
}
}
reqLines.push('', '');
this._socket.write(reqLines.join('\r\n'));
};
if (
this._secure &&
(connectOpts as tls.ConnectionOptions).servername === undefined &&
net.isIP(host) === 0
) {
(connectOpts as tls.ConnectionOptions).servername = host;
}
this._socket = this._secure
? tls.connect(connectOpts as tls.ConnectionOptions, onConnect)
: net.connect(connectOpts as net.NetConnectOpts, onConnect);
this._socket.setNoDelay?.(true);
this._socket.on('data', (chunk: Buffer) => this._onHandshakeData(chunk));
this._socket.on('error', (err: Error) => this._onEarlyError(err));
this._socket.on('close', () => this._onEarlyClose());
}
this._socket = this._secure
? tls.connect(connectOpts as tls.ConnectionOptions, onConnect)
: net.connect(connectOpts as net.NetConnectOpts, onConnect);
this._socket.setNoDelay?.(true);
this._socket.on('data', (chunk: Buffer) => this._onHandshakeData(chunk));
this._socket.on('error', (err: Error) => this._onEarlyError(err));
this._socket.on('close', () => this._onEarlyClose());
}
get readyState(): number {
return this._ws ? this._ws.readyState : this._readyState;
}
private _onHandshakeData(chunk: Buffer): void {
this._handshakeBuf = Buffer.concat([this._handshakeBuf, chunk]);
const idx = this._handshakeBuf.indexOf('\r\n\r\n');
if (idx < 0) {
if (this._handshakeBuf.length > 16384) {
this._abort('Handshake response too large');
}
return;
}
const headBlock = this._handshakeBuf.slice(0, idx).toString('latin1');
const rest = this._handshakeBuf.slice(idx + 4);
let parsed: ParsedHandshakeResponse;
try {
parsed = parseHeaders(headBlock);
} catch (e) {
return this._abort((e as Error).message);
get readyState(): number {
return this._ws ? this._ws.readyState : this._readyState;
}
if (parsed.statusCode !== 101) {
return this._abort(`Unexpected response status ${parsed.statusCode}`);
}
if ((parsed.headers['upgrade'] || '').toLowerCase() !== 'websocket') {
return this._abort('Missing/invalid Upgrade header');
}
if (!/\bupgrade\b/i.test(parsed.headers['connection'] || '')) {
return this._abort('Missing Connection: Upgrade header');
}
if (parsed.headers['sec-websocket-accept'] !== this._expectedAccept) {
return this._abort('Invalid Sec-WebSocket-Accept');
}
let acceptedExtensions: AcceptedPerMessageDeflate | null;
try {
acceptedExtensions = parseAcceptedPerMessageDeflate(
parsed.headers['sec-websocket-extensions'],
this._perMessageDeflate,
);
} catch (e) {
return this._abort((e as Error).message);
}
if (parsed.headers['sec-websocket-extensions'] && !acceptedExtensions) {
return this._abort('Unexpected Sec-WebSocket-Extensions');
}
const protocol = parsed.headers['sec-websocket-protocol'] || '';
if (protocol && (!this._protocols || !this._protocols.includes(protocol))) {
return this._abort('Unexpected Sec-WebSocket-Protocol');
private _onHandshakeData(chunk: Buffer): void {
this._handshakeBuf = Buffer.concat([this._handshakeBuf, chunk]);
const idx = this._handshakeBuf.indexOf('\r\n\r\n');
if (idx < 0) {
if (this._handshakeBuf.length > 16384) {
this._abort('Handshake response too large');
}
return;
}
const headBlock = this._handshakeBuf.slice(0, idx).toString('latin1');
const rest = this._handshakeBuf.slice(idx + 4);
let parsed: ParsedHandshakeResponse;
try {
parsed = parseHeaders(headBlock);
} catch (e) {
return this._abort((e as Error).message);
}
if (parsed.statusCode !== 101) {
return this._abort(`Unexpected response status ${parsed.statusCode}`);
}
if ((parsed.headers['upgrade'] || '').toLowerCase() !== 'websocket') {
return this._abort('Missing/invalid Upgrade header');
}
if (!/\bupgrade\b/i.test(parsed.headers['connection'] || '')) {
return this._abort('Missing Connection: Upgrade header');
}
if (parsed.headers['sec-websocket-accept'] !== this._expectedAccept) {
return this._abort('Invalid Sec-WebSocket-Accept');
}
let acceptedExtensions: AcceptedPerMessageDeflate | null;
try {
acceptedExtensions = parseAcceptedPerMessageDeflate(
parsed.headers['sec-websocket-extensions'],
this._perMessageDeflate,
);
} catch (e) {
return this._abort((e as Error).message);
}
if (parsed.headers['sec-websocket-extensions'] && !acceptedExtensions) {
return this._abort('Unexpected Sec-WebSocket-Extensions');
}
const protocol = parsed.headers['sec-websocket-protocol'] || '';
if (protocol && (!this._protocols || !this._protocols.includes(protocol))) {
return this._abort('Unexpected Sec-WebSocket-Protocol');
}
this._socket.removeAllListeners('data');
this._socket.removeAllListeners('error');
this._socket.removeAllListeners('close');
this._readyState = OPEN;
this._ws = new InternalWebSocket(this._socket, {
isServer: false,
maxPayload: this._maxPayload,
extensions: acceptedExtensions ? { perMessageDeflate: acceptedExtensions } : undefined,
protocol,
readyState: OPEN,
});
this.protocol = protocol;
this.extensions = acceptedExtensions ? 'permessage-deflate' : '';
this._ws.on('message', (d: Buffer, isBinary: boolean) => this.emit('message', d, isBinary));
this._ws.on('ping', (d: Buffer) => this.emit('ping', d));
this._ws.on('pong', (d: Buffer) => this.emit('pong', d));
this._ws.on('close', (c: number, r: string) => this.emit('close', c, r));
this._ws.on('error', (e: Error) => this.emit('error', e));
this.emit('upgrade', parsed);
this.emit('open');
if (rest.length > 0) {
this._ws._onData(rest);
}
for (const entry of this._pendingQueue) {
this._ws.send(entry.data, entry.options, entry.cb);
}
this._pendingQueue = [];
}
this._socket.removeAllListeners('data');
this._socket.removeAllListeners('error');
this._socket.removeAllListeners('close');
this._readyState = OPEN;
this._ws = new InternalWebSocket(this._socket, {
isServer: false,
maxPayload: this._maxPayload,
extensions: acceptedExtensions ? { perMessageDeflate: acceptedExtensions } : undefined,
protocol,
readyState: OPEN,
});
this.protocol = protocol;
this.extensions = acceptedExtensions ? 'permessage-deflate' : '';
this._ws.on('message', (d: Buffer, isBinary: boolean) => this.emit('message', d, isBinary));
this._ws.on('ping', (d: Buffer) => this.emit('ping', d));
this._ws.on('pong', (d: Buffer) => this.emit('pong', d));
this._ws.on('close', (c: number, r: string) => this.emit('close', c, r));
this._ws.on('error', (e: Error) => this.emit('error', e));
this.emit('upgrade', parsed);
this.emit('open');
if (rest.length > 0) this._ws._onData(rest);
for (const entry of this._pendingQueue) this._ws.send(entry.data, entry.options, entry.cb);
this._pendingQueue = [];
}
private _onEarlyError(err: Error): void {
this.emit('error', err);
}
private _onEarlyClose(): void {
if (!this._ws) {
this._readyState = CLOSED;
this.emit('close', 1006, '');
private _onEarlyError(err: Error): void {
this.emit('error', err);
}
}
private _abort(msg: string): void {
const err = new Error('WebSocket handshake failed: ' + msg);
try { this._socket.destroy(); } catch { /* noop */ }
this.emit('error', err);
this._readyState = CLOSED;
this.emit('close', 1006, '');
}
send(data: Parameters<InternalWebSocket['send']>[0], options?: SendOptions | SendCallback, cb?: SendCallback): void {
if (this._ws) return this._ws.send(data, options, cb);
if (typeof options === 'function') { cb = options; options = undefined; }
this._pendingQueue.push({ data, options, cb });
}
ping(data?: Buffer | string | SendCallback, mask?: unknown, cb?: SendCallback): void {
this._ws?.ping(data, mask, cb);
}
pong(data?: Buffer | string | SendCallback, mask?: unknown, cb?: SendCallback): void {
this._ws?.pong(data, mask, cb);
}
close(code?: number, reason?: string): void {
if (code !== undefined && !isValidCloseCode(code)) {
throw new RangeError(`Invalid close code: ${code}`);
private _onEarlyClose(): void {
if (!this._ws) {
this._readyState = CLOSED;
this.emit('close', 1006, '');
}
}
if (this._ws) return this._ws.close(code, reason);
try { this._socket.destroy(); } catch { /* noop */ }
}
terminate(): void {
if (this._ws) return this._ws.terminate();
try { this._socket.destroy(); } catch { /* noop */ }
}
private _abort(msg: string): void {
const err = new Error('WebSocket handshake failed: ' + msg);
try {
this._socket.destroy();
} catch {
/* noop */
}
this.emit('error', err);
this._readyState = CLOSED;
this.emit('close', 1006, '');
}
send(
data: Parameters<InternalWebSocket['send']>[0],
options?: SendOptions | SendCallback,
cb?: SendCallback,
): void {
if (this._ws) {
return this._ws.send(data, options, cb);
}
if (typeof options === 'function') {
cb = options;
options = undefined;
}
this._pendingQueue.push({ data, options, cb });
}
ping(data?: Buffer | string | SendCallback, mask?: unknown, cb?: SendCallback): void {
this._ws?.ping(data, mask, cb);
}
pong(data?: Buffer | string | SendCallback, mask?: unknown, cb?: SendCallback): void {
this._ws?.pong(data, mask, cb);
}
close(code?: number, reason?: string): void {
if (code !== undefined && !isValidCloseCode(code)) {
throw new RangeError(`Invalid close code: ${code}`);
}
if (this._ws) {
return this._ws.close(code, reason);
}
try {
this._socket.destroy();
} catch {
/* noop */
}
}
terminate(): void {
if (this._ws) {
return this._ws.terminate();
}
try {
this._socket.destroy();
} catch {
/* noop */
}
}
}
+239 -155
View File
@@ -3,202 +3,286 @@ import zlib from 'node:zlib';
const TRAILER = Buffer.from([0x00, 0x00, 0xff, 0xff]);
export interface PerMessageDeflateConfig {
clientNoContextTakeover?: boolean;
serverNoContextTakeover?: boolean;
threshold?: number;
clientNoContextTakeover?: boolean;
serverNoContextTakeover?: boolean;
threshold?: number;
}
export interface AcceptedPerMessageDeflate {
enabled: true;
requestNoContextTakeover: boolean;
responseNoContextTakeover: boolean;
threshold: number;
enabled: true;
requestNoContextTakeover: boolean;
responseNoContextTakeover: boolean;
threshold: number;
}
interface ParsedOffer {
name: string;
params: Record<string, string | true>;
name: string;
params: Record<string, string | true>;
}
export function parseHeader(header: string | undefined | null): ParsedOffer[] {
const offers: ParsedOffer[] = [];
if (!header) return offers;
for (const rawOffer of String(header).split(',')) {
const parts = rawOffer.split(';').map(p => p.trim()).filter(Boolean);
if (parts.length === 0) continue;
const name = (parts.shift() as string).toLowerCase();
const params: Record<string, string | true> = Object.create(null);
for (const part of parts) {
const eq = part.indexOf('=');
if (eq === -1) {
params[part.toLowerCase()] = true;
} else {
const key = part.slice(0, eq).trim().toLowerCase();
let value = part.slice(eq + 1).trim();
if (
(value.startsWith('"') && value.endsWith('"')) ||
(value.startsWith("'") && value.endsWith("'"))
) {
value = value.slice(1, -1);
}
params[key] = value;
}
const offers: ParsedOffer[] = [];
if (!header) {
return offers;
}
offers.push({ name, params });
}
return offers;
for (const rawOffer of String(header).split(',')) {
const parts = rawOffer
.split(';')
.map((p) => p.trim())
.filter(Boolean);
if (parts.length === 0) {
continue;
}
const name = (parts.shift() as string).toLowerCase();
const params: Record<string, string | true> = Object.create(null);
for (const part of parts) {
const eq = part.indexOf('=');
if (eq === -1) {
params[part.toLowerCase()] = true;
} else {
const key = part.slice(0, eq).trim().toLowerCase();
let value = part.slice(eq + 1).trim();
if (
(value.startsWith('"') && value.endsWith('"')) ||
(value.startsWith("'") && value.endsWith("'"))
) {
value = value.slice(1, -1);
}
params[key] = value;
}
}
offers.push({ name, params });
}
return offers;
}
function normalizePerMessageDeflateOptions(
value: unknown,
): PerMessageDeflateConfig | null {
if (value === undefined || value === false || value === null) return null;
if (value === true) {
function normalizePerMessageDeflateOptions(value: unknown): PerMessageDeflateConfig | null {
if (value === undefined || value === false || value === null) {
return null;
}
if (value === true) {
return { clientNoContextTakeover: true, serverNoContextTakeover: true };
}
if (typeof value === 'object') {
return {
clientNoContextTakeover: true,
serverNoContextTakeover: true,
...(value as PerMessageDeflateConfig),
};
}
return { clientNoContextTakeover: true, serverNoContextTakeover: true };
}
if (typeof value === 'object') {
return {
clientNoContextTakeover: true,
serverNoContextTakeover: true,
...(value as PerMessageDeflateConfig),
};
}
return { clientNoContextTakeover: true, serverNoContextTakeover: true };
}
export function acceptPerMessageDeflate(
requestHeader: string | undefined,
options: unknown,
requestHeader: string | undefined,
options: unknown,
): { header: string; options: AcceptedPerMessageDeflate } | null {
const config = normalizePerMessageDeflateOptions(options);
if (!config) return null;
const offer = parseHeader(requestHeader).find(item => item.name === 'permessage-deflate');
if (!offer) return null;
const responseParams: string[] = [];
const config = normalizePerMessageDeflateOptions(options);
if (config.serverNoContextTakeover !== false || offer.params.server_no_context_takeover) {
responseParams.push('server_no_context_takeover');
}
if (config.clientNoContextTakeover !== false || offer.params.client_no_context_takeover) {
responseParams.push('client_no_context_takeover');
}
if (!config) {
return null;
}
const accepted: AcceptedPerMessageDeflate = {
enabled: true,
requestNoContextTakeover: responseParams.includes('client_no_context_takeover'),
responseNoContextTakeover: responseParams.includes('server_no_context_takeover'),
threshold: config.threshold ?? 1024,
};
const offer = parseHeader(requestHeader).find((item) => item.name === 'permessage-deflate');
return {
header: ['permessage-deflate', ...responseParams].join('; '),
options: accepted,
};
if (!offer) {
return null;
}
const responseParams: string[] = [];
if (config.serverNoContextTakeover !== false || offer.params.server_no_context_takeover) {
responseParams.push('server_no_context_takeover');
}
if (config.clientNoContextTakeover !== false || offer.params.client_no_context_takeover) {
responseParams.push('client_no_context_takeover');
}
const accepted: AcceptedPerMessageDeflate = {
enabled: true,
requestNoContextTakeover: responseParams.includes('client_no_context_takeover'),
responseNoContextTakeover: responseParams.includes('server_no_context_takeover'),
threshold: config.threshold ?? 1024,
};
return {
header: ['permessage-deflate', ...responseParams].join('; '),
options: accepted,
};
}
export function offerPerMessageDeflate(options: unknown): string | null {
const config = normalizePerMessageDeflateOptions(options);
if (!config) return null;
const params = ['permessage-deflate'];
if (config.clientNoContextTakeover !== false) params.push('client_no_context_takeover');
if (config.serverNoContextTakeover !== false) params.push('server_no_context_takeover');
return params.join('; ');
const config = normalizePerMessageDeflateOptions(options);
if (!config) {
return null;
}
const params = ['permessage-deflate'];
if (config.clientNoContextTakeover !== false) {
params.push('client_no_context_takeover');
}
if (config.serverNoContextTakeover !== false) {
params.push('server_no_context_takeover');
}
return params.join('; ');
}
export function parseAcceptedPerMessageDeflate(
responseHeader: string | undefined,
requestedOptions: unknown,
responseHeader: string | undefined,
requestedOptions: unknown,
): AcceptedPerMessageDeflate | null {
const config = normalizePerMessageDeflateOptions(requestedOptions);
if (!config) return null;
const accepted = parseHeader(responseHeader).find(item => item.name === 'permessage-deflate');
if (!accepted) return null;
for (const key of Object.keys(accepted.params)) {
if (key !== 'client_no_context_takeover' && key !== 'server_no_context_takeover') {
throw new Error(`Unsupported permessage-deflate parameter: ${key}`);
const config = normalizePerMessageDeflateOptions(requestedOptions);
if (!config) {
return null;
}
}
return {
enabled: true,
requestNoContextTakeover: !!accepted.params.server_no_context_takeover,
responseNoContextTakeover: !!accepted.params.client_no_context_takeover,
threshold: config.threshold ?? 1024,
};
const accepted = parseHeader(responseHeader).find((item) => item.name === 'permessage-deflate');
if (!accepted) {
return null;
}
for (const key of Object.keys(accepted.params)) {
if (key !== 'client_no_context_takeover' && key !== 'server_no_context_takeover') {
throw new Error(`Unsupported permessage-deflate parameter: ${key}`);
}
}
return {
enabled: true,
requestNoContextTakeover: !!accepted.params.server_no_context_takeover,
responseNoContextTakeover: !!accepted.params.client_no_context_takeover,
threshold: config.threshold ?? 1024,
};
}
export function compressRaw(data: Buffer): Buffer {
const compressed = zlib.deflateRawSync(data, { flush: zlib.constants.Z_SYNC_FLUSH });
if (compressed.length >= 4 && compressed.subarray(compressed.length - 4).equals(TRAILER)) {
return compressed.subarray(0, compressed.length - 4);
}
return compressed;
const compressed = zlib.deflateRawSync(data, { flush: zlib.constants.Z_SYNC_FLUSH });
if (compressed.length >= 4 && compressed.subarray(compressed.length - 4).equals(TRAILER)) {
return compressed.subarray(0, compressed.length - 4);
}
return compressed;
}
export function decompressRaw(data: Buffer, maxPayload?: number): Buffer {
let inflated: Buffer;
try {
inflated = zlib.inflateRawSync(Buffer.concat([data, TRAILER]), {
finishFlush: zlib.constants.Z_SYNC_FLUSH,
// A post-inflate length check is too late for a compression bomb: zlib
// has already allocated the expanded buffer by then. Node enforces this
// limit while producing output. maxOutputLength cannot be zero, so keep
// the allocation ceiling at one byte for the maxPayload=0 edge case and
// let the exact check below reject any non-empty message.
...(maxPayload === undefined
? {}
: { maxOutputLength: Math.max(1, maxPayload) }),
});
} catch (cause) {
const zlibError = cause as Error & { code?: string };
if (maxPayload !== undefined && zlibError.code === 'ERR_BUFFER_TOO_LARGE') {
const err = new Error(
`Message too large after inflate (maxPayload=${maxPayload})`,
{ cause },
) as Error & { code?: number };
err.code = 1009;
throw err;
let inflated: Buffer;
try {
inflated = zlib.inflateRawSync(Buffer.concat([data, TRAILER]), {
finishFlush: zlib.constants.Z_SYNC_FLUSH,
// A post-inflate length check is too late for a compression bomb: zlib
// has already allocated the expanded buffer by then. Node enforces this
// limit while producing output. maxOutputLength cannot be zero, so keep
// the allocation ceiling at one byte for the maxPayload=0 edge case and
// let the exact check below reject any non-empty message.
...(maxPayload === undefined ? {} : { maxOutputLength: Math.max(1, maxPayload) }),
});
} catch (cause) {
const zlibError = cause as Error & { code?: string };
if (maxPayload !== undefined && zlibError.code === 'ERR_BUFFER_TOO_LARGE') {
const err = new Error(`Message too large after inflate (maxPayload=${maxPayload})`, {
cause,
}) as Error & { code?: number };
err.code = 1009;
throw err;
}
throw cause;
}
throw cause;
}
if (maxPayload !== undefined && inflated.length > maxPayload) {
const err = new Error(
`Message too large after inflate (maxPayload=${maxPayload})`,
) as Error & { code?: number };
err.code = 1009;
throw err;
}
return inflated;
if (maxPayload !== undefined && inflated.length > maxPayload) {
const err = new Error(
`Message too large after inflate (maxPayload=${maxPayload})`,
) as Error & {
code?: number;
};
err.code = 1009;
throw err;
}
return inflated;
}
export function normalizeProtocolList(
protocols: string | string[] | Set<string> | undefined | null,
protocols: string | string[] | Set<string> | undefined | null,
): string[] {
if (!protocols) return [];
if (typeof protocols === 'string') {
return protocols.split(',').map(p => p.trim()).filter(Boolean);
}
if (Array.isArray(protocols)) {
return protocols.map(String).map(p => p.trim()).filter(Boolean);
}
if (protocols instanceof Set) {
return Array.from(protocols).map(String).map(p => p.trim()).filter(Boolean);
}
return [];
if (!protocols) {
return [];
}
if (typeof protocols === 'string') {
return protocols
.split(',')
.map((p) => p.trim())
.filter(Boolean);
}
if (Array.isArray(protocols)) {
return protocols
.map(String)
.map((p) => p.trim())
.filter(Boolean);
}
if (protocols instanceof Set) {
return Array.from(protocols)
.map(String)
.map((p) => p.trim())
.filter(Boolean);
}
return [];
}
export function chooseSubprotocol(
requestHeader: string | undefined,
protocols: string | string[] | Set<string> | ((requested: string[]) => string | null | undefined) | undefined,
requestHeader: string | undefined,
protocols:
| string
| string[]
| Set<string>
| ((requested: string[]) => string | null | undefined)
| undefined,
): string | null {
const requested = normalizeProtocolList(requestHeader);
if (typeof protocols === 'function') {
const selected = protocols(requested);
return selected && requested.includes(String(selected)) ? String(selected) : null;
}
const supported = normalizeProtocolList(protocols);
if (requested.length === 0 || supported.length === 0) return null;
for (const protocol of supported) {
if (requested.includes(protocol)) return protocol;
}
return null;
const requested = normalizeProtocolList(requestHeader);
if (typeof protocols === 'function') {
const selected = protocols(requested);
return selected && requested.includes(String(selected)) ? String(selected) : null;
}
const supported = normalizeProtocolList(protocols);
if (requested.length === 0 || supported.length === 0) {
return null;
}
for (const protocol of supported) {
if (requested.includes(protocol)) {
return protocol;
}
}
return null;
}
+19 -25
View File
@@ -16,36 +16,30 @@ WebSocketClient.Server = WebSocketServer;
// `WebSocket` type that ships with @types/node.
export const WebSocket: typeof WebSocketClient = WebSocketClient;
export interface WebSocket extends EventEmitter {
readonly readyState: number;
readonly protocol: string;
readonly extensions: string;
send(
data: string | Buffer | Uint8Array | ArrayBuffer,
options?: SendOptions | SendCallback,
cb?: SendCallback,
): void;
ping(data?: Buffer | string | SendCallback, mask?: unknown, cb?: SendCallback): void;
pong(data?: Buffer | string | SendCallback, mask?: unknown, cb?: SendCallback): void;
close(code?: number, reason?: string): void;
terminate(): void;
on(event: 'message', listener: (data: Buffer, isBinary: boolean) => void): this;
on(event: 'open', listener: () => void): this;
on(event: 'close', listener: (code: number, reason: string) => void): this;
on(event: 'error', listener: (err: Error) => void): this;
on(event: 'ping' | 'pong', listener: (data: Buffer) => void): this;
on(event: string | symbol, listener: (...args: unknown[]) => void): this;
readonly readyState: number;
readonly protocol: string;
readonly extensions: string;
send(
data: string | Buffer | Uint8Array | ArrayBuffer,
options?: SendOptions | SendCallback,
cb?: SendCallback,
): void;
ping(data?: Buffer | string | SendCallback, mask?: unknown, cb?: SendCallback): void;
pong(data?: Buffer | string | SendCallback, mask?: unknown, cb?: SendCallback): void;
close(code?: number, reason?: string): void;
terminate(): void;
on(event: 'message', listener: (data: Buffer, isBinary: boolean) => void): this;
on(event: 'open', listener: () => void): this;
on(event: 'close', listener: (code: number, reason: string) => void): this;
on(event: 'error', listener: (err: Error) => void): this;
on(event: 'ping' | 'pong', listener: (data: Buffer) => void): this;
on(event: string | symbol, listener: (...args: unknown[]) => void): this;
}
const Server = WebSocketServer;
const _internal = { WebSocket: InternalWebSocket, native };
export {
WebSocketClient,
WebSocketServer,
Server,
InternalWebSocket,
_internal,
};
export { WebSocketClient, WebSocketServer, Server, InternalWebSocket, _internal };
export type { SendOptions, SendCallback, WebSocketRawData } from './websocket';
export type { WebSocketClientOptions } from './client';
+85 -77
View File
@@ -5,83 +5,88 @@ import { fileURLToPath } from 'node:url';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
export interface ParserOptions {
isServer: boolean;
maxPayload: number;
allowedRsv: number;
isServer: boolean;
maxPayload: number;
allowedRsv: number;
}
export interface ParsedFrame {
fin: boolean;
opcode: number;
payload: Buffer;
rsv?: number;
fin: boolean;
opcode: number;
payload: Buffer;
rsv?: number;
}
export interface ParseResult {
frames: ParsedFrame[];
error?: boolean;
code?: number;
message?: string;
frames: ParsedFrame[];
error?: boolean;
code?: number;
message?: string;
}
export interface ParserInstance {
push(chunk: Buffer): ParseResult;
push(chunk: Buffer): ParseResult;
}
export interface NativeAddon {
Parser: new (options: ParserOptions) => ParserInstance;
buildFrame(
opcode: number,
fin: boolean,
payload: Buffer,
maskKey: Buffer | null,
rsv: number,
): Buffer;
computeAcceptKey(key: string): string;
Parser: new (options: ParserOptions) => ParserInstance;
buildFrame(
opcode: number,
fin: boolean,
payload: Buffer,
maskKey: Buffer | null,
rsv: number,
): Buffer;
computeAcceptKey(key: string): string;
}
function platformBinaryName(): string {
return `websocket-${process.platform}-${process.arch}.node`;
return `websocket-${process.platform}-${process.arch}.node`;
}
// The same binary ships under several layouts, depending on whether we're
// running from source (tsx), from the bundled monorepo dist/, or from a
// flattened release zip. Probe each candidate in priority order.
function searchDirs(): string[] {
return [
// Released zip (flattened): <root>/native, called from <root>/index.mjs
path.resolve(__dirname, 'native'),
// Bundled into <root>/dist/index.mjs → natives at <root>/dist/native
path.resolve(__dirname, '..', 'native'),
// Dev (tsx) — packages/websocket/src → packages/runtime/native
path.resolve(__dirname, '..', '..', 'runtime', 'native'),
// Fallback when invoked from repo root
path.resolve(process.cwd(), 'native'),
path.resolve(process.cwd(), 'dist', 'native'),
path.resolve(process.cwd(), 'packages', 'runtime', 'native'),
];
return [
// Released zip (flattened): <root>/native, called from <root>/index.mjs
path.resolve(__dirname, 'native'),
// Bundled into <root>/dist/index.mjs → natives at <root>/dist/native
path.resolve(__dirname, '..', 'native'),
// Dev (tsx) — packages/websocket/src → packages/runtime/native
path.resolve(__dirname, '..', '..', 'runtime', 'native'),
// Fallback when invoked from repo root
path.resolve(process.cwd(), 'native'),
path.resolve(process.cwd(), 'dist', 'native'),
path.resolve(process.cwd(), 'packages', 'runtime', 'native'),
];
}
function resolveAddonPath(): string {
const fileName = platformBinaryName();
for (const dir of searchDirs()) {
const full = path.join(dir, fileName);
if (existsSync(full)) return full;
}
throw new Error(
`[snowluma/websocket] native addon not found: ${fileName}. Searched: ${searchDirs().join(', ')}`,
);
const fileName = platformBinaryName();
for (const dir of searchDirs()) {
const full = path.join(dir, fileName);
if (existsSync(full)) {
return full;
}
}
throw new Error(
`[snowluma/websocket] native addon not found: ${fileName}. Searched: ${searchDirs().join(', ')}`,
);
}
function loadAddon(): NativeAddon {
const addonPath = resolveAddonPath();
const mod = { exports: {} as Record<string, unknown> };
// process.dlopen expects a NodeModule-shaped object; mod.exports is mutated in-place.
(process as unknown as { dlopen: (m: { exports: unknown }, file: string) => void }).dlopen(
mod,
addonPath,
);
return mod.exports as unknown as NativeAddon;
const addonPath = resolveAddonPath();
const mod = { exports: {} as Record<string, unknown> };
// process.dlopen expects a NodeModule-shaped object; mod.exports is mutated in-place.
(process as unknown as { dlopen: (m: { exports: unknown }, file: string) => void }).dlopen(
mod,
addonPath,
);
return mod.exports as unknown as NativeAddon;
}
// Local-only escape hatch: when SNOWLUMA_DEV_NO_NATIVE=1 is set, we return a
@@ -90,38 +95,41 @@ function loadAddon(): NativeAddon {
// actual WebSocket parsing/serialization call will throw at use-time. This
// branch never triggers for normal users because the env var is opt-in.
function createStubAddon(reason: string): NativeAddon {
const fail = (): never => {
throw new Error(
`[snowluma/websocket] native addon is stubbed (${reason}). ` +
`Set SNOWLUMA_DEV_NO_NATIVE=0 (or unset) and provide the prebuilt binary to enable WebSocket I/O.`,
);
};
class StubParser {
constructor(_options: ParserOptions) {}
push(_chunk: Buffer): ParseResult {
return fail();
const fail = (): never => {
throw new Error(
`[snowluma/websocket] native addon is stubbed (${reason}). ` +
`Set SNOWLUMA_DEV_NO_NATIVE=0 (or unset) and provide the prebuilt binary to enable WebSocket I/O.`,
);
};
class StubParser {
constructor(_options: ParserOptions) {}
push(_chunk: Buffer): ParseResult {
return fail();
}
}
}
console.warn(
`[snowluma/websocket] WARNING: using stub addon (${reason}). WebSocket features are disabled.`,
);
return {
Parser: StubParser as unknown as NativeAddon['Parser'],
buildFrame: fail as unknown as NativeAddon['buildFrame'],
computeAcceptKey: fail as unknown as NativeAddon['computeAcceptKey'],
};
console.warn(
`[snowluma/websocket] WARNING: using stub addon (${reason}). WebSocket features are disabled.`,
);
return {
Parser: StubParser as unknown as NativeAddon['Parser'],
buildFrame: fail as unknown as NativeAddon['buildFrame'],
computeAcceptKey: fail as unknown as NativeAddon['computeAcceptKey'],
};
}
function tryLoad(): NativeAddon {
const devSkip = process.env.SNOWLUMA_DEV_NO_NATIVE === '1';
try {
return loadAddon();
} catch (err) {
if (devSkip) {
return createStubAddon((err as Error).message);
const devSkip = process.env.SNOWLUMA_DEV_NO_NATIVE === '1';
try {
return loadAddon();
} catch (err) {
if (devSkip) {
return createStubAddon((err as Error).message);
}
throw err;
}
throw err;
}
}
const addon: NativeAddon = tryLoad();
+355 -250
View File
@@ -6,297 +6,402 @@ import type { Server as HttpsServer } from 'node:https';
import type { Duplex } from 'node:stream';
import native from './native';
import {
type PerMessageDeflateConfig,
acceptPerMessageDeflate,
chooseSubprotocol,
type PerMessageDeflateConfig,
acceptPerMessageDeflate,
chooseSubprotocol,
} from './extensions';
import { WebSocket, OPEN } from './websocket';
function computeAccept(key: string): string {
return native.computeAcceptKey(key);
return native.computeAcceptKey(key);
}
function abortUpgrade(socket: Duplex, status: number, message?: string): void {
try {
const body = message ? message : http.STATUS_CODES[status] || '';
const head =
`HTTP/1.1 ${status} ${http.STATUS_CODES[status] || 'Error'}\r\n` +
'Connection: close\r\n' +
`Content-Length: ${Buffer.byteLength(body)}\r\n` +
'Content-Type: text/plain\r\n\r\n';
socket.write(head + body);
} catch { /* noop */ }
try { socket.destroy(); } catch { /* noop */ }
try {
const body = message ? message : http.STATUS_CODES[status] || '';
const head =
`HTTP/1.1 ${status} ${http.STATUS_CODES[status] || 'Error'}\r\n` +
'Connection: close\r\n' +
`Content-Length: ${Buffer.byteLength(body)}\r\n` +
'Content-Type: text/plain\r\n\r\n';
socket.write(head + body);
} catch {
/* noop */
}
try {
socket.destroy();
} catch {
/* noop */
}
}
const TLS_OPTION_KEYS = [
'ALPNProtocols',
'SNICallback',
'ca',
'cert',
'ciphers',
'clientCertEngine',
'crl',
'dhparam',
'ecdhCurve',
'honorCipherOrder',
'key',
'maxVersion',
'minVersion',
'passphrase',
'pfx',
'privateKeyEngine',
'privateKeyIdentifier',
'requestCert',
'rejectUnauthorized',
'secureOptions',
'secureProtocol',
'sessionIdContext',
'sigalgs',
'ticketKeys',
'ALPNProtocols',
'SNICallback',
'ca',
'cert',
'ciphers',
'clientCertEngine',
'crl',
'dhparam',
'ecdhCurve',
'honorCipherOrder',
'key',
'maxVersion',
'minVersion',
'passphrase',
'pfx',
'privateKeyEngine',
'privateKeyIdentifier',
'requestCert',
'rejectUnauthorized',
'secureOptions',
'secureProtocol',
'sessionIdContext',
'sigalgs',
'ticketKeys',
] as const;
type TlsOptions = Record<string, unknown>;
function getTlsOptions(options: WebSocketServerOptions & TlsOptions): TlsOptions {
const tlsOptions: TlsOptions = {};
for (const key of TLS_OPTION_KEYS) {
if ((options as TlsOptions)[key] !== undefined) tlsOptions[key] = (options as TlsOptions)[key];
}
if (options.tls && typeof options.tls === 'object') {
Object.assign(tlsOptions, options.tls);
}
return tlsOptions;
const tlsOptions: TlsOptions = {};
for (const key of TLS_OPTION_KEYS) {
if ((options as TlsOptions)[key] !== undefined) {
tlsOptions[key] = (options as TlsOptions)[key];
}
}
if (options.tls && typeof options.tls === 'object') {
Object.assign(tlsOptions, options.tls);
}
return tlsOptions;
}
export type SubprotocolSelector = (requested: string[]) => string | null | undefined;
export interface WebSocketServerOptions {
port?: number;
host?: string;
server?: HttpServer | HttpsServer;
noServer?: boolean;
path?: string;
maxPayload?: number;
verifyClient?: ((info: { origin?: string; secure: boolean; req: IncomingMessage }) => boolean) | ((info: { origin?: string; secure: boolean; req: IncomingMessage }, cb: (allow: boolean, code?: number, message?: string, headers?: Record<string, string>) => void) => void);
protocols?: string | string[] | Set<string> | SubprotocolSelector;
perMessageDeflate?: boolean | PerMessageDeflateConfig;
backlog?: number;
tls?: TlsOptions;
port?: number;
host?: string;
server?: HttpServer | HttpsServer;
noServer?: boolean;
path?: string;
maxPayload?: number;
verifyClient?:
| ((info: { origin?: string; secure: boolean; req: IncomingMessage }) => boolean)
| ((
info: { origin?: string; secure: boolean; req: IncomingMessage },
cb: (
allow: boolean,
code?: number,
message?: string,
headers?: Record<string, string>,
) => void,
) => void);
protocols?: string | string[] | Set<string> | SubprotocolSelector;
perMessageDeflate?: boolean | PerMessageDeflateConfig;
backlog?: number;
tls?: TlsOptions;
}
type UpgradeHandler = (req: IncomingMessage, socket: Duplex, head: Buffer) => void;
export class WebSocketServer extends EventEmitter {
public readonly options: WebSocketServerOptions & { tls?: TlsOptions };
public readonly clients = new Set<WebSocket>();
private _server: HttpServer | HttpsServer | null = null;
private _externalServer: HttpServer | HttpsServer | null = null;
private _upgradeHandler: UpgradeHandler | null = null;
public readonly options: WebSocketServerOptions & { tls?: TlsOptions };
public readonly clients = new Set<WebSocket>();
private _server: HttpServer | HttpsServer | null = null;
private _externalServer: HttpServer | HttpsServer | null = null;
private _upgradeHandler: UpgradeHandler | null = null;
constructor(options?: WebSocketServerOptions) {
super();
options = options || {};
this.options = {
port: options.port,
host: options.host,
server: options.server,
noServer: !!options.noServer,
path: options.path,
maxPayload: options.maxPayload,
verifyClient: options.verifyClient,
protocols: options.protocols,
perMessageDeflate: options.perMessageDeflate,
backlog: options.backlog,
tls: options.tls,
};
const tlsOptions = getTlsOptions(options as WebSocketServerOptions & TlsOptions);
this.options.tls = Object.keys(tlsOptions).length > 0 ? tlsOptions : undefined;
constructor(options?: WebSocketServerOptions) {
super();
options = options || {};
this.options = {
port: options.port,
host: options.host,
server: options.server,
noServer: !!options.noServer,
path: options.path,
maxPayload: options.maxPayload,
verifyClient: options.verifyClient,
protocols: options.protocols,
perMessageDeflate: options.perMessageDeflate,
backlog: options.backlog,
tls: options.tls,
};
const tlsOptions = getTlsOptions(options as WebSocketServerOptions & TlsOptions);
this.options.tls = Object.keys(tlsOptions).length > 0 ? tlsOptions : undefined;
if (this.options.noServer) {
return;
}
if (this.options.server) {
this._externalServer = this.options.server;
this._attachToServer(this._externalServer);
} else if (this.options.port !== undefined) {
const requestHandler = (_req: IncomingMessage, res: ServerResponse) => {
const body = http.STATUS_CODES[426] ?? '';
res.writeHead(426, {
'Content-Length': Buffer.byteLength(body),
'Content-Type': 'text/plain',
});
res.end(body);
};
this._server = this.options.tls
? https.createServer(this.options.tls, requestHandler)
: http.createServer(requestHandler);
this._attachToServer(this._server);
this._server.listen(
this.options.port,
this.options.host,
this.options.backlog,
() => this.emit('listening'),
);
this._server.on('error', (err: Error) => this.emit('error', err));
} else {
throw new Error('WebSocketServer requires { port } or { server } or { noServer: true }');
}
}
address(): ReturnType<HttpServer['address']> | null {
if (this._server) return this._server.address();
if (this._externalServer && this._externalServer.address) return this._externalServer.address();
return null;
}
private _attachToServer(server: HttpServer | HttpsServer): void {
const handler: UpgradeHandler = (req, socket, head) => {
if (this.options.path) {
const urlPath = (req.url ?? '/').split('?')[0];
if (urlPath !== this.options.path) {
if (server.listenerCount('upgrade') === 1) {
abortUpgrade(socket, 400, 'Bad path for WebSocket');
}
return;
if (this.options.noServer) {
return;
}
}
this.handleUpgrade(req, socket, head, (ws) => {
this.emit('connection', ws, req);
});
};
this._upgradeHandler = handler;
server.on('upgrade', handler);
}
handleUpgrade(
request: IncomingMessage,
socket: Duplex,
head: Buffer,
cb: (ws: WebSocket, request: IncomingMessage) => void,
): void {
const upgrade = (request.headers['upgrade'] ?? '').toLowerCase();
const connection = (Array.isArray(request.headers['connection']) ? request.headers['connection'].join(',') : (request.headers['connection'] ?? '')).toLowerCase();
const version = request.headers['sec-websocket-version'];
const key = request.headers['sec-websocket-key'];
if (this.options.server) {
this._externalServer = this.options.server;
this._attachToServer(this._externalServer);
} else if (this.options.port !== undefined) {
const requestHandler = (_req: IncomingMessage, res: ServerResponse) => {
const body = http.STATUS_CODES[426] ?? '';
res.writeHead(426, {
'Content-Length': Buffer.byteLength(body),
'Content-Type': 'text/plain',
});
res.end(body);
};
if (request.method !== 'GET') return abortUpgrade(socket, 405, 'Method not allowed');
if (upgrade !== 'websocket') return abortUpgrade(socket, 400, 'Upgrade header must be websocket');
if (!/\bupgrade\b/i.test(connection)) return abortUpgrade(socket, 400, 'Connection header must contain "upgrade"');
if (version !== '13') {
try {
socket.write(
'HTTP/1.1 426 Upgrade Required\r\n' +
'Sec-WebSocket-Version: 13\r\n' +
'Connection: close\r\n\r\n');
} catch { /* noop */ }
try { socket.destroy(); } catch { /* noop */ }
return;
}
if (typeof key !== 'string' || !/^[+/0-9A-Za-z]{22}==$/.test(key)) {
return abortUpgrade(socket, 400, 'Invalid Sec-WebSocket-Key');
this._server = this.options.tls
? https.createServer(this.options.tls, requestHandler)
: http.createServer(requestHandler);
this._attachToServer(this._server);
this._server.listen(this.options.port, this.options.host, this.options.backlog, () =>
this.emit('listening'),
);
this._server.on('error', (err: Error) => this.emit('error', err));
} else {
throw new Error(
'WebSocketServer requires { port } or { server } or { noServer: true }',
);
}
}
const doAccept = () => {
const accept = computeAccept(key);
const extension = acceptPerMessageDeflate(
request.headers['sec-websocket-extensions'] as string | undefined,
this.options.perMessageDeflate,
);
const protocol = chooseSubprotocol(
request.headers['sec-websocket-protocol'] as string | undefined,
this.options.protocols,
);
const responseHeaders = [
'HTTP/1.1 101 Switching Protocols',
'Upgrade: websocket',
'Connection: Upgrade',
`Sec-WebSocket-Accept: ${accept}`,
];
if (extension) responseHeaders.push(`Sec-WebSocket-Extensions: ${extension.header}`);
if (protocol) responseHeaders.push(`Sec-WebSocket-Protocol: ${protocol}`);
try {
socket.write(responseHeaders.join('\r\n') + '\r\n\r\n');
} catch {
try { socket.destroy(); } catch { /* noop */ }
return;
}
address(): ReturnType<HttpServer['address']> | null {
if (this._server) {
return this._server.address();
}
const ns = socket as Duplex & { setTimeout?: (ms: number) => void; setNoDelay?: (b: boolean) => void };
ns.setTimeout?.(0);
ns.setNoDelay?.(true);
if (this._externalServer && this._externalServer.address) {
return this._externalServer.address();
}
const ws = new WebSocket(socket as unknown as import('node:net').Socket, {
isServer: true,
maxPayload: this.options.maxPayload,
extensions: extension ? { perMessageDeflate: extension.options } : undefined,
protocol: protocol ?? '',
readyState: OPEN,
});
this.clients.add(ws);
ws.on('close', () => this.clients.delete(ws));
return null;
}
if (head && head.length > 0) ws._onData(head);
private _attachToServer(server: HttpServer | HttpsServer): void {
const handler: UpgradeHandler = (req, socket, head) => {
if (this.options.path) {
const urlPath = (req.url ?? '/').split('?')[0];
cb(ws, request);
};
if (urlPath !== this.options.path) {
if (server.listenerCount('upgrade') === 1) {
abortUpgrade(socket, 400, 'Bad path for WebSocket');
}
const verify = this.options.verifyClient;
if (typeof verify === 'function') {
type VerifyInfo = { origin?: string; secure: boolean; req: IncomingMessage };
const info: VerifyInfo = {
origin: request.headers['origin'] as string | undefined,
secure: !!((socket as unknown as { encrypted?: boolean }).encrypted),
req: request,
};
if (verify.length >= 2) {
(verify as (i: VerifyInfo, cb: (allow: boolean, code?: number, message?: string) => void) => void)(
info,
(allow, code, message) => {
if (!allow) return abortUpgrade(socket, code || 401, message);
return;
}
}
this.handleUpgrade(req, socket, head, (ws) => {
this.emit('connection', ws, req);
});
};
this._upgradeHandler = handler;
server.on('upgrade', handler);
}
handleUpgrade(
request: IncomingMessage,
socket: Duplex,
head: Buffer,
cb: (ws: WebSocket, request: IncomingMessage) => void,
): void {
const upgrade = (request.headers['upgrade'] ?? '').toLowerCase();
const connection = (
Array.isArray(request.headers['connection'])
? request.headers['connection'].join(',')
: (request.headers['connection'] ?? '')
).toLowerCase();
const version = request.headers['sec-websocket-version'];
const key = request.headers['sec-websocket-key'];
if (request.method !== 'GET') {
return abortUpgrade(socket, 405, 'Method not allowed');
}
if (upgrade !== 'websocket') {
return abortUpgrade(socket, 400, 'Upgrade header must be websocket');
}
if (!/\bupgrade\b/i.test(connection)) {
return abortUpgrade(socket, 400, 'Connection header must contain "upgrade"');
}
if (version !== '13') {
try {
socket.write(
'HTTP/1.1 426 Upgrade Required\r\n' +
'Sec-WebSocket-Version: 13\r\n' +
'Connection: close\r\n\r\n',
);
} catch {
/* noop */
}
try {
socket.destroy();
} catch {
/* noop */
}
return;
}
if (typeof key !== 'string' || !/^[+/0-9A-Za-z]{22}==$/.test(key)) {
return abortUpgrade(socket, 400, 'Invalid Sec-WebSocket-Key');
}
const doAccept = () => {
const accept = computeAccept(key);
const extension = acceptPerMessageDeflate(
request.headers['sec-websocket-extensions'] as string | undefined,
this.options.perMessageDeflate,
);
const protocol = chooseSubprotocol(
request.headers['sec-websocket-protocol'] as string | undefined,
this.options.protocols,
);
const responseHeaders = [
'HTTP/1.1 101 Switching Protocols',
'Upgrade: websocket',
'Connection: Upgrade',
`Sec-WebSocket-Accept: ${accept}`,
];
if (extension) {
responseHeaders.push(`Sec-WebSocket-Extensions: ${extension.header}`);
}
if (protocol) {
responseHeaders.push(`Sec-WebSocket-Protocol: ${protocol}`);
}
try {
socket.write(responseHeaders.join('\r\n') + '\r\n\r\n');
} catch {
try {
socket.destroy();
} catch {
/* noop */
}
return;
}
const ns = socket as Duplex & {
setTimeout?: (ms: number) => void;
setNoDelay?: (b: boolean) => void;
};
ns.setTimeout?.(0);
ns.setNoDelay?.(true);
const ws = new WebSocket(socket as unknown as import('node:net').Socket, {
isServer: true,
maxPayload: this.options.maxPayload,
extensions: extension ? { perMessageDeflate: extension.options } : undefined,
protocol: protocol ?? '',
readyState: OPEN,
});
this.clients.add(ws);
ws.on('close', () => this.clients.delete(ws));
if (head && head.length > 0) {
ws._onData(head);
}
cb(ws, request);
};
const verify = this.options.verifyClient;
if (typeof verify === 'function') {
type VerifyInfo = { origin?: string; secure: boolean; req: IncomingMessage };
const info: VerifyInfo = {
origin: request.headers['origin'] as string | undefined,
secure: !!(socket as unknown as { encrypted?: boolean }).encrypted,
req: request,
};
if (verify.length >= 2) {
(
verify as (
i: VerifyInfo,
cb: (allow: boolean, code?: number, message?: string) => void,
) => void
)(info, (allow, code, message) => {
if (!allow) {
return abortUpgrade(socket, code || 401, message);
}
doAccept();
});
} else {
const allow = (verify as (i: VerifyInfo) => boolean)(info);
if (!allow) {
return abortUpgrade(socket, 401, 'Unauthorized');
}
doAccept();
}
} else {
doAccept();
},
);
} else {
const allow = (verify as (i: VerifyInfo) => boolean)(info);
if (!allow) return abortUpgrade(socket, 401, 'Unauthorized');
doAccept();
}
} else {
doAccept();
}
}
}
close(cb?: (err?: Error) => void): void {
if (this._externalServer && this._upgradeHandler) {
this._externalServer.removeListener('upgrade', this._upgradeHandler);
this._upgradeHandler = null;
}
for (const ws of this.clients) {
try { ws.close(1001, 'Server shutting down'); } catch { /* noop */ }
}
if (this._server) {
this._server.close((err?: Error) => cb && cb(err));
} else if (cb) {
setImmediate(cb);
}
}
close(cb?: (err?: Error) => void): void {
if (this._externalServer && this._upgradeHandler) {
this._externalServer.removeListener('upgrade', this._upgradeHandler);
this._upgradeHandler = null;
}
/** Destroy clients and, when this server owns the HTTP listener, that
* listener too. An external HTTP server is left to its owner. */
destroy(): void {
for (const ws of this.clients) {
try { ws.terminate(); } catch { /* noop */ }
for (const ws of this.clients) {
try {
ws.close(1001, 'Server shutting down');
} catch {
/* noop */
}
}
if (this._server) {
this._server.close((err?: Error) => cb && cb(err));
} else if (cb) {
setImmediate(cb);
}
}
if (this._externalServer && this._upgradeHandler) {
this._externalServer.removeListener('upgrade', this._upgradeHandler);
this._upgradeHandler = null;
/** Destroy clients and, when this server owns the HTTP listener, that
* listener too. An external HTTP server is left to its owner. */
destroy(): void {
for (const ws of this.clients) {
try {
ws.terminate();
} catch {
/* noop */
}
}
if (this._externalServer && this._upgradeHandler) {
this._externalServer.removeListener('upgrade', this._upgradeHandler);
this._upgradeHandler = null;
}
if (this._server) {
try {
this._server.closeAllConnections();
} catch {
/* noop */
}
try {
this._server.close(() => undefined);
} catch {
/* noop */
}
this._server = null;
}
}
if (this._server) {
try { this._server.closeAllConnections(); } catch { /* noop */ }
try { this._server.close(() => undefined); } catch { /* noop */ }
this._server = null;
}
}
}
File diff suppressed because it is too large. Load diff