Add @snowluma/websocket TS package and integrate
Introduce an in-tree TypeScript WebSocket package (@snowluma/websocket): move JS websocket implementation into packages/websocket/src (client, server, websocket, extensions, native, index) and add package.json + tsconfig. Replace direct 'ws' dependency in core with the workspace package and update runtime manifest/description. Implement a native addon loader for platform-specific binaries, add typings/refinements across client/server/websocket (more strict types, handshake parsing, permessage-deflate plumbing, buffer/raw data handling), and wire WebSocketClient as the package default export while exposing internal types. Update vite config to bundle the new package and copy only platform-target native binaries into dist/native. Remove legacy JS entrypoints and native loader, and adjust imports/usages in core (ws-transport) to accept broader raw data types.
This commit is contained in:
1 parent
5fb969da7c
commit
252a65b833
15 files changed
+645
-436
No files matched your search
@@ -14,13 +14,12 @@
|
||||
"typecheck": "tsc --noEmit"
|
||||
},
|
||||
"dependencies": {
|
||||
"ws": "^8.20.0"
|
||||
"@snowluma/websocket": "workspace:*"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@hono/node-server": "^1.19.14",
|
||||
"@rollup/plugin-node-resolve": "^16.0.3",
|
||||
"@types/node": "^24.12.2",
|
||||
"@types/ws": "^8.18.1",
|
||||
"cross-env": "^10.1.0",
|
||||
"hono": "^4.12.14",
|
||||
"tsx": "^4.21.0",
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import WebSocket, { WebSocketServer } from 'ws';
|
||||
import type { IncomingHttpHeaders, IncomingMessage } from 'http';
|
||||
import { WebSocket, WebSocketServer } from '@snowluma/websocket';
|
||||
import type { IncomingMessage } from 'http';
|
||||
import type { ApiHandler } from './api-handler';
|
||||
import type { JsonObject, OneBotConfig, WsClientEndpoint, WsRole, WsServerEndpoint } from './types';
|
||||
import { createLogger } from '../utils/logger';
|
||||
@@ -157,7 +157,7 @@ export class WsTransport {
|
||||
const conn: ForwardConnection = { socket, role };
|
||||
this.forwardConnections.set(socket, conn);
|
||||
|
||||
socket.on('message', (raw) => {
|
||||
socket.on('message', (raw: Buffer) => {
|
||||
void this.handleApiMessage(socket, role, raw);
|
||||
});
|
||||
|
||||
@@ -165,14 +165,14 @@ export class WsTransport {
|
||||
this.forwardConnections.delete(socket);
|
||||
});
|
||||
|
||||
socket.on('error', (error) => {
|
||||
socket.on('error', (error: Error) => {
|
||||
log.warn('forward socket error: %s', error instanceof Error ? error.message : String(error));
|
||||
});
|
||||
|
||||
this.sendBootstrapMetaEvents(socket, role);
|
||||
});
|
||||
|
||||
wss.on('error', (error) => {
|
||||
wss.on('error', (error: Error) => {
|
||||
log.warn('server error: %s', error instanceof Error ? error.message : String(error));
|
||||
});
|
||||
|
||||
@@ -212,7 +212,7 @@ export class WsTransport {
|
||||
this.sendBootstrapMetaEvents(socket, role);
|
||||
});
|
||||
|
||||
socket.on('message', (raw) => {
|
||||
socket.on('message', (raw: Buffer) => {
|
||||
void this.handleApiMessage(socket, role, raw);
|
||||
});
|
||||
|
||||
@@ -228,12 +228,12 @@ export class WsTransport {
|
||||
this.reconnectTimers.add(timer);
|
||||
});
|
||||
|
||||
socket.on('error', (error) => {
|
||||
socket.on('error', (error: Error) => {
|
||||
log.warn('reverse error %s: %s', endpointUrl, error instanceof Error ? error.message : String(error));
|
||||
});
|
||||
}
|
||||
|
||||
private async handleApiMessage(socket: WebSocket, role: WsRole, raw: WebSocket.RawData): Promise<void> {
|
||||
private async handleApiMessage(socket: WebSocket, role: WsRole, raw: Buffer | string): Promise<void> {
|
||||
if (role !== 'api' && role !== 'universal') return;
|
||||
|
||||
const text = rawDataToString(raw);
|
||||
@@ -309,9 +309,9 @@ function isAuthorized(request: IncomingMessage, token: string): boolean {
|
||||
return false;
|
||||
}
|
||||
|
||||
function rawDataToString(raw: WebSocket.RawData): string {
|
||||
function rawDataToString(raw: Buffer | string | ArrayBuffer | ArrayBufferView | Buffer[]): string {
|
||||
if (typeof raw === 'string') return raw;
|
||||
if (raw instanceof Buffer) return raw.toString('utf8');
|
||||
if (Buffer.isBuffer(raw)) return raw.toString('utf8');
|
||||
if (Array.isArray(raw)) return Buffer.concat(raw).toString('utf8');
|
||||
if (raw instanceof ArrayBuffer) return Buffer.from(new Uint8Array(raw)).toString('utf8');
|
||||
if (ArrayBuffer.isView(raw)) {
|
||||
@@ -322,7 +322,7 @@ function rawDataToString(raw: WebSocket.RawData): string {
|
||||
|
||||
function safeSend(socket: WebSocket, payload: string): void {
|
||||
if (socket.readyState !== WebSocket.OPEN) return;
|
||||
socket.send(payload, (error) => {
|
||||
socket.send(payload, (error?: Error | null) => {
|
||||
if (error) {
|
||||
log.warn('send error: %s', error instanceof Error ? error.message : String(error));
|
||||
}
|
||||
|
||||
@@ -13,9 +13,9 @@ const nativeDir = path.resolve(runtimeDir, 'native');
|
||||
// vite-plugin-cp consumes globs through globby; on Windows we must use POSIX-style separators.
|
||||
const toPosix = (p: string) => p.replace(/\\/g, '/');
|
||||
|
||||
const external = [
|
||||
'ws'
|
||||
];
|
||||
// `@snowluma/websocket` is bundled (it's an in-tree TS workspace package), so
|
||||
// it must NOT be marked external. Only Node builtins stay external.
|
||||
const external: string[] = [];
|
||||
|
||||
const nodeModules = [...builtinModules, ...builtinModules.map((m) => `node:${m}`), 'node:sqlite'].flat();
|
||||
|
||||
@@ -26,6 +26,15 @@ const nativeSrc = toPosix(nativeDir);
|
||||
// (.gitignore and other dev artifacts must NOT be shipped.)
|
||||
const runtimeDistFiles = ['launcher.bat', 'package.json'];
|
||||
|
||||
// Only ship native binaries matching the current build host's platform/arch.
|
||||
// Override via SNOWLUMA_TARGET=<platform>-<arch> for cross-target packaging.
|
||||
const targetTriple = process.env.SNOWLUMA_TARGET ?? `${process.platform}-${process.arch}`;
|
||||
const nativeGlobs = [
|
||||
`snowluma-${targetTriple}.dll`,
|
||||
`snowluma-${targetTriple}.node`,
|
||||
`websocket-${targetTriple}.node`,
|
||||
];
|
||||
|
||||
const BaseConfigPlugin: PluginOption[] = [
|
||||
cp({
|
||||
targets: [
|
||||
@@ -34,7 +43,11 @@ const BaseConfigPlugin: PluginOption[] = [
|
||||
dest: distDir,
|
||||
flatten: true,
|
||||
})),
|
||||
{ src: `${nativeSrc}/*`, dest: path.join(distDir, 'native'), flatten: true },
|
||||
...nativeGlobs.map((g) => ({
|
||||
src: `${nativeSrc}/${g}`,
|
||||
dest: path.join(distDir, 'native'),
|
||||
flatten: true,
|
||||
})),
|
||||
]
|
||||
})
|
||||
];
|
||||
|
||||
@@ -4,8 +4,5 @@
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "index.mjs",
|
||||
"description": "SnowLuma runtime distribution manifest: ships into dist/ (launcher.bat, package.json, native/*.dll, native/*.node)",
|
||||
"dependencies": {
|
||||
"ws": "^8.20.0"
|
||||
}
|
||||
"description": "SnowLuma runtime distribution manifest: ships into dist/ (launcher.bat, package.json, native/*.dll, native/*.node). Native libraries are loaded via process.dlopen()."
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
import { WebSocket as InternalWebSocket } from './websocket.js';
|
||||
import { WebSocketServer } from './server.js';
|
||||
import { WebSocketClient } from './client.js';
|
||||
import native from './native.js';
|
||||
|
||||
WebSocketClient.Server = WebSocketServer;
|
||||
|
||||
const WebSocket = WebSocketClient;
|
||||
const Server = WebSocketServer;
|
||||
const _internal = { WebSocket: InternalWebSocket, native };
|
||||
|
||||
export {
|
||||
WebSocket,
|
||||
WebSocketServer,
|
||||
Server,
|
||||
_internal,
|
||||
};
|
||||
|
||||
export default {
|
||||
WebSocket,
|
||||
WebSocketServer,
|
||||
Server,
|
||||
_internal,
|
||||
};
|
||||
@@ -1,33 +0,0 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { createRequire } from 'node:module';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
|
||||
const candidates = [
|
||||
path.join(__dirname, '..', 'build', 'Release', 'snowluma_ws.node'),
|
||||
path.join(__dirname, '..', 'build', 'Debug', 'snowluma_ws.node'),
|
||||
];
|
||||
|
||||
let addon = null;
|
||||
let lastErr = null;
|
||||
for (const p of candidates) {
|
||||
if (fs.existsSync(p)) {
|
||||
try {
|
||||
addon = require(p);
|
||||
break;
|
||||
} catch (e) {
|
||||
lastErr = e;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!addon) {
|
||||
throw new Error(
|
||||
'Failed to load native snowluma_ws addon. Run `npm run build` first. ' +
|
||||
(lastErr ? `Last error: ${lastErr.message}` : ''),
|
||||
);
|
||||
}
|
||||
|
||||
export default addon;
|
||||
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"name": "@snowluma/websocket",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./src/index.ts",
|
||||
"types": "./src/index.ts",
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./src/index.ts",
|
||||
"default": "./src/index.ts"
|
||||
}
|
||||
},
|
||||
"description": "SnowLuma in-tree WebSocket implementation. Loads packages/runtime/native/websocket-<platform>-<arch>.node via process.dlopen().",
|
||||
"devDependencies": {
|
||||
"@types/node": "^24.12.2",
|
||||
"typescript": "catalog:"
|
||||
}
|
||||
}
|
||||
@@ -3,19 +3,28 @@ import net from 'node:net';
|
||||
import tls from 'node:tls';
|
||||
import crypto from 'node:crypto';
|
||||
import { URL } from 'node:url';
|
||||
import native from './native.js';
|
||||
import type { Socket } from 'node:net';
|
||||
import native from './native';
|
||||
import {
|
||||
type AcceptedPerMessageDeflate,
|
||||
type PerMessageDeflateConfig,
|
||||
offerPerMessageDeflate,
|
||||
parseAcceptedPerMessageDeflate,
|
||||
} from './extensions.js';
|
||||
import { WebSocket, CONNECTING, OPEN, isValidCloseCode } from './websocket.js';
|
||||
} from './extensions';
|
||||
import { WebSocket as InternalWebSocket, CONNECTING, OPEN, CLOSED, isValidCloseCode, type SendCallback, type SendOptions } from './websocket';
|
||||
|
||||
function parseHeaders(headerBlock) {
|
||||
interface ParsedHandshakeResponse {
|
||||
statusCode: number;
|
||||
statusMessage: string;
|
||||
headers: Record<string, string>;
|
||||
}
|
||||
|
||||
function parseHeaders(headerBlock: string): ParsedHandshakeResponse {
|
||||
const lines = headerBlock.split('\r\n');
|
||||
const status = lines.shift();
|
||||
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 = Object.create(null);
|
||||
const headers: Record<string, string> = Object.create(null);
|
||||
for (const line of lines) {
|
||||
if (!line) continue;
|
||||
const idx = line.indexOf(':');
|
||||
@@ -24,14 +33,49 @@ function parseHeaders(headerBlock) {
|
||||
const v = line.slice(idx + 1).trim();
|
||||
headers[k] = v;
|
||||
}
|
||||
return { statusCode: Number(m[1]), statusMessage: m[2], headers };
|
||||
return { statusCode: Number(m[1]), statusMessage: m[2] ?? '', headers };
|
||||
}
|
||||
|
||||
class WebSocketClient extends EventEmitter {
|
||||
constructor(address, protocols, options) {
|
||||
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;
|
||||
}
|
||||
|
||||
export class WebSocketClient extends EventEmitter {
|
||||
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 _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;
|
||||
options = protocols as WebSocketClientOptions;
|
||||
protocols = undefined;
|
||||
}
|
||||
options = options || {};
|
||||
@@ -42,12 +86,8 @@ class WebSocketClient extends EventEmitter {
|
||||
this._secure = this._url.protocol === 'wss:';
|
||||
this._readyState = CONNECTING;
|
||||
this._maxPayload = options.maxPayload;
|
||||
this._ws = null;
|
||||
this._pendingQueue = [];
|
||||
this._perMessageDeflate = options.perMessageDeflate;
|
||||
this._protocols = Array.isArray(protocols) ? protocols.map(String) : undefined;
|
||||
this.protocol = '';
|
||||
this.extensions = '';
|
||||
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);
|
||||
@@ -57,11 +97,11 @@ class WebSocketClient extends EventEmitter {
|
||||
this._wsKey = keyBytes.toString('base64');
|
||||
this._expectedAccept = native.computeAcceptKey(this._wsKey);
|
||||
|
||||
const connectOpts = {
|
||||
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 || '');
|
||||
@@ -76,15 +116,15 @@ class WebSocketClient extends EventEmitter {
|
||||
`Sec-WebSocket-Key: ${this._wsKey}`,
|
||||
'Sec-WebSocket-Version: 13',
|
||||
];
|
||||
if (Array.isArray(protocols) && protocols.length > 0) {
|
||||
reqLines.push(`Sec-WebSocket-Protocol: ${protocols.join(', ')}`);
|
||||
if (this._protocols && this._protocols.length > 0) {
|
||||
reqLines.push(`Sec-WebSocket-Protocol: ${this._protocols.join(', ')}`);
|
||||
}
|
||||
const extensionOffer = offerPerMessageDeflate(options.perMessageDeflate);
|
||||
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)) {
|
||||
if (options!.headers) {
|
||||
for (const [k, v] of Object.entries(options!.headers)) {
|
||||
reqLines.push(`${k}: ${v}`);
|
||||
}
|
||||
}
|
||||
@@ -92,26 +132,25 @@ class WebSocketClient extends EventEmitter {
|
||||
this._socket.write(reqLines.join('\r\n'));
|
||||
};
|
||||
|
||||
if (this._secure && connectOpts.servername === undefined && net.isIP(host) === 0) {
|
||||
connectOpts.servername = host;
|
||||
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, onConnect)
|
||||
: net.connect(connectOpts, onConnect);
|
||||
? tls.connect(connectOpts as tls.ConnectionOptions, onConnect)
|
||||
: net.connect(connectOpts as net.NetConnectOpts, onConnect);
|
||||
|
||||
this._socket.setNoDelay && this._socket.setNoDelay(true);
|
||||
this._handshakeBuf = Buffer.alloc(0);
|
||||
this._socket.on('data', (chunk) => this._onHandshakeData(chunk));
|
||||
this._socket.on('error', (err) => this._onEarlyError(err));
|
||||
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() {
|
||||
get readyState(): number {
|
||||
return this._ws ? this._ws.readyState : this._readyState;
|
||||
}
|
||||
|
||||
_onHandshakeData(chunk) {
|
||||
private _onHandshakeData(chunk: Buffer): void {
|
||||
this._handshakeBuf = Buffer.concat([this._handshakeBuf, chunk]);
|
||||
const idx = this._handshakeBuf.indexOf('\r\n\r\n');
|
||||
if (idx < 0) {
|
||||
@@ -122,11 +161,11 @@ class WebSocketClient extends EventEmitter {
|
||||
}
|
||||
const headBlock = this._handshakeBuf.slice(0, idx).toString('latin1');
|
||||
const rest = this._handshakeBuf.slice(idx + 4);
|
||||
let parsed;
|
||||
let parsed: ParsedHandshakeResponse;
|
||||
try {
|
||||
parsed = parseHeaders(headBlock);
|
||||
} catch (e) {
|
||||
return this._abort(e.message);
|
||||
return this._abort((e as Error).message);
|
||||
}
|
||||
|
||||
if (parsed.statusCode !== 101) {
|
||||
@@ -141,30 +180,29 @@ class WebSocketClient extends EventEmitter {
|
||||
if (parsed.headers['sec-websocket-accept'] !== this._expectedAccept) {
|
||||
return this._abort('Invalid Sec-WebSocket-Accept');
|
||||
}
|
||||
let acceptedExtensions;
|
||||
let acceptedExtensions: AcceptedPerMessageDeflate | null;
|
||||
try {
|
||||
acceptedExtensions = parseAcceptedPerMessageDeflate(
|
||||
parsed.headers['sec-websocket-extensions'],
|
||||
this._perMessageDeflate,
|
||||
);
|
||||
} catch (e) {
|
||||
return this._abort(e.message);
|
||||
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 && (!Array.isArray(this._protocols) || !this._protocols.includes(protocol))) {
|
||||
if (protocol && (!this._protocols || !this._protocols.includes(protocol))) {
|
||||
return this._abort('Unexpected Sec-WebSocket-Protocol');
|
||||
}
|
||||
|
||||
// Detach handshake listeners; hand the socket off to the WebSocket.
|
||||
this._socket.removeAllListeners('data');
|
||||
this._socket.removeAllListeners('error');
|
||||
this._socket.removeAllListeners('close');
|
||||
|
||||
this._readyState = OPEN;
|
||||
this._ws = new WebSocket(this._socket, {
|
||||
this._ws = new InternalWebSocket(this._socket, {
|
||||
isServer: false,
|
||||
maxPayload: this._maxPayload,
|
||||
extensions: acceptedExtensions ? { perMessageDeflate: acceptedExtensions } : undefined,
|
||||
@@ -173,68 +211,63 @@ class WebSocketClient extends EventEmitter {
|
||||
});
|
||||
this.protocol = protocol;
|
||||
this.extensions = acceptedExtensions ? 'permessage-deflate' : '';
|
||||
// Forward events to the client wrapper.
|
||||
this._ws.on('message', (d, isBinary) => this.emit('message', d, isBinary));
|
||||
this._ws.on('ping', (d) => this.emit('ping', d));
|
||||
this._ws.on('pong', (d) => this.emit('pong', d));
|
||||
this._ws.on('close', (c, r) => this.emit('close', c, r));
|
||||
this._ws.on('error', (e) => this.emit('error', e));
|
||||
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');
|
||||
|
||||
// Feed leftover bytes (if any) into the frame parser.
|
||||
if (rest.length > 0) this._ws._onData(rest);
|
||||
|
||||
// Flush any queued sends that happened before open.
|
||||
for (const entry of this._pendingQueue) this._ws.send(entry.data, entry.options, entry.cb);
|
||||
this._pendingQueue = [];
|
||||
}
|
||||
|
||||
_onEarlyError(err) {
|
||||
private _onEarlyError(err: Error): void {
|
||||
this.emit('error', err);
|
||||
}
|
||||
|
||||
_onEarlyClose() {
|
||||
private _onEarlyClose(): void {
|
||||
if (!this._ws) {
|
||||
this._readyState = 3;
|
||||
this._readyState = CLOSED;
|
||||
this.emit('close', 1006, '');
|
||||
}
|
||||
}
|
||||
|
||||
_abort(msg) {
|
||||
private _abort(msg: string): void {
|
||||
const err = new Error('WebSocket handshake failed: ' + msg);
|
||||
try { this._socket.destroy(); } catch {}
|
||||
try { this._socket.destroy(); } catch { /* noop */ }
|
||||
this.emit('error', err);
|
||||
this._readyState = 3;
|
||||
this._readyState = CLOSED;
|
||||
this.emit('close', 1006, '');
|
||||
}
|
||||
|
||||
send(data, options, cb) {
|
||||
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, mask, cb) { if (this._ws) this._ws.ping(data, mask, cb); }
|
||||
pong(data, mask, cb) { if (this._ws) this._ws.pong(data, mask, 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, reason) {
|
||||
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 {}
|
||||
try { this._socket.destroy(); } catch { /* noop */ }
|
||||
}
|
||||
|
||||
terminate() {
|
||||
terminate(): void {
|
||||
if (this._ws) return this._ws.terminate();
|
||||
try { this._socket.destroy(); } catch {}
|
||||
try { this._socket.destroy(); } catch { /* noop */ }
|
||||
}
|
||||
}
|
||||
|
||||
WebSocketClient.CONNECTING = 0;
|
||||
WebSocketClient.OPEN = 1;
|
||||
WebSocketClient.CLOSING = 2;
|
||||
WebSocketClient.CLOSED = 3;
|
||||
|
||||
export { WebSocketClient };
|
||||
@@ -2,14 +2,32 @@ import zlib from 'node:zlib';
|
||||
|
||||
const TRAILER = Buffer.from([0x00, 0x00, 0xff, 0xff]);
|
||||
|
||||
function parseHeader(header) {
|
||||
const offers = [];
|
||||
export interface PerMessageDeflateConfig {
|
||||
clientNoContextTakeover?: boolean;
|
||||
serverNoContextTakeover?: boolean;
|
||||
threshold?: number;
|
||||
}
|
||||
|
||||
export interface AcceptedPerMessageDeflate {
|
||||
enabled: true;
|
||||
requestNoContextTakeover: boolean;
|
||||
responseNoContextTakeover: boolean;
|
||||
threshold: number;
|
||||
}
|
||||
|
||||
interface ParsedOffer {
|
||||
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);
|
||||
const parts = rawOffer.split(';').map(p => p.trim()).filter(Boolean);
|
||||
if (parts.length === 0) continue;
|
||||
const name = parts.shift().toLowerCase();
|
||||
const params = Object.create(null);
|
||||
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) {
|
||||
@@ -17,8 +35,10 @@ function parseHeader(header) {
|
||||
} 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("'"))) {
|
||||
if (
|
||||
(value.startsWith('"') && value.endsWith('"')) ||
|
||||
(value.startsWith("'") && value.endsWith("'"))
|
||||
) {
|
||||
value = value.slice(1, -1);
|
||||
}
|
||||
params[key] = value;
|
||||
@@ -29,7 +49,9 @@ function parseHeader(header) {
|
||||
return offers;
|
||||
}
|
||||
|
||||
function normalizePerMessageDeflateOptions(value) {
|
||||
function normalizePerMessageDeflateOptions(
|
||||
value: unknown,
|
||||
): PerMessageDeflateConfig | null {
|
||||
if (value === undefined || value === false || value === null) return null;
|
||||
if (value === true) {
|
||||
return { clientNoContextTakeover: true, serverNoContextTakeover: true };
|
||||
@@ -38,18 +60,21 @@ function normalizePerMessageDeflateOptions(value) {
|
||||
return {
|
||||
clientNoContextTakeover: true,
|
||||
serverNoContextTakeover: true,
|
||||
...value,
|
||||
...(value as PerMessageDeflateConfig),
|
||||
};
|
||||
}
|
||||
return { clientNoContextTakeover: true, serverNoContextTakeover: true };
|
||||
}
|
||||
|
||||
function acceptPerMessageDeflate(requestHeader, options) {
|
||||
export function acceptPerMessageDeflate(
|
||||
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');
|
||||
const offer = parseHeader(requestHeader).find(item => item.name === 'permessage-deflate');
|
||||
if (!offer) return null;
|
||||
const responseParams = [];
|
||||
const responseParams: string[] = [];
|
||||
|
||||
if (config.serverNoContextTakeover !== false || offer.params.server_no_context_takeover) {
|
||||
responseParams.push('server_no_context_takeover');
|
||||
@@ -58,7 +83,7 @@ function acceptPerMessageDeflate(requestHeader, options) {
|
||||
responseParams.push('client_no_context_takeover');
|
||||
}
|
||||
|
||||
const accepted = {
|
||||
const accepted: AcceptedPerMessageDeflate = {
|
||||
enabled: true,
|
||||
requestNoContextTakeover: responseParams.includes('client_no_context_takeover'),
|
||||
responseNoContextTakeover: responseParams.includes('server_no_context_takeover'),
|
||||
@@ -71,7 +96,7 @@ function acceptPerMessageDeflate(requestHeader, options) {
|
||||
};
|
||||
}
|
||||
|
||||
function offerPerMessageDeflate(options) {
|
||||
export function offerPerMessageDeflate(options: unknown): string | null {
|
||||
const config = normalizePerMessageDeflateOptions(options);
|
||||
if (!config) return null;
|
||||
const params = ['permessage-deflate'];
|
||||
@@ -80,10 +105,13 @@ function offerPerMessageDeflate(options) {
|
||||
return params.join('; ');
|
||||
}
|
||||
|
||||
function parseAcceptedPerMessageDeflate(responseHeader, requestedOptions) {
|
||||
export function parseAcceptedPerMessageDeflate(
|
||||
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');
|
||||
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') {
|
||||
@@ -98,7 +126,7 @@ function parseAcceptedPerMessageDeflate(responseHeader, requestedOptions) {
|
||||
};
|
||||
}
|
||||
|
||||
function compressRaw(data) {
|
||||
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);
|
||||
@@ -106,27 +134,38 @@ function compressRaw(data) {
|
||||
return compressed;
|
||||
}
|
||||
|
||||
function decompressRaw(data, maxPayload) {
|
||||
export function decompressRaw(data: Buffer, maxPayload?: number): Buffer {
|
||||
const inflated = zlib.inflateRawSync(Buffer.concat([data, TRAILER]), {
|
||||
finishFlush: zlib.constants.Z_SYNC_FLUSH,
|
||||
});
|
||||
if (maxPayload !== undefined && inflated.length > maxPayload) {
|
||||
const err = new Error('Message too large after inflate');
|
||||
const err = new Error('Message too large after inflate') as Error & { code?: number };
|
||||
err.code = 1009;
|
||||
throw err;
|
||||
}
|
||||
return inflated;
|
||||
}
|
||||
|
||||
function normalizeProtocolList(protocols) {
|
||||
export function normalizeProtocolList(
|
||||
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);
|
||||
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 [];
|
||||
}
|
||||
|
||||
function chooseSubprotocol(requestHeader, protocols) {
|
||||
export function chooseSubprotocol(
|
||||
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);
|
||||
@@ -139,14 +178,3 @@ function chooseSubprotocol(requestHeader, protocols) {
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export {
|
||||
acceptPerMessageDeflate,
|
||||
chooseSubprotocol,
|
||||
compressRaw,
|
||||
decompressRaw,
|
||||
offerPerMessageDeflate,
|
||||
normalizeProtocolList,
|
||||
parseAcceptedPerMessageDeflate,
|
||||
parseHeader,
|
||||
};
|
||||
@@ -0,0 +1,54 @@
|
||||
import type { EventEmitter } from 'node:events';
|
||||
import { WebSocket as InternalWebSocket } from './websocket';
|
||||
import { WebSocketServer } from './server';
|
||||
import { WebSocketClient } from './client';
|
||||
import native from './native';
|
||||
import type { SendOptions, SendCallback } from './websocket';
|
||||
|
||||
WebSocketClient.Server = WebSocketServer;
|
||||
|
||||
// `WebSocket` mirrors the `ws` package's default export shape. We use
|
||||
// declaration merging (const + interface) so the name resolves to the client
|
||||
// constructor in value space AND a structural interface in type space. The
|
||||
// interface is intentionally narrow enough to cover both `WebSocketClient`
|
||||
// (constructed by the user) and the internal `WebSocket` (emitted by the
|
||||
// server's `connection` event). It also shadows Node 22+'s global DOM-style
|
||||
// `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;
|
||||
}
|
||||
|
||||
const Server = WebSocketServer;
|
||||
const _internal = { WebSocket: InternalWebSocket, native };
|
||||
|
||||
export {
|
||||
WebSocketClient,
|
||||
WebSocketServer,
|
||||
Server,
|
||||
InternalWebSocket,
|
||||
_internal,
|
||||
};
|
||||
|
||||
export type { SendOptions, SendCallback, WebSocketRawData } from './websocket';
|
||||
export type { WebSocketClientOptions } from './client';
|
||||
export type { WebSocketServerOptions, SubprotocolSelector } from './server';
|
||||
|
||||
export default WebSocketClient;
|
||||
@@ -0,0 +1,88 @@
|
||||
import { existsSync } from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
|
||||
export interface ParserOptions {
|
||||
isServer: boolean;
|
||||
maxPayload: number;
|
||||
allowedRsv: number;
|
||||
}
|
||||
|
||||
export interface ParsedFrame {
|
||||
fin: boolean;
|
||||
opcode: number;
|
||||
payload: Buffer;
|
||||
rsv?: number;
|
||||
}
|
||||
|
||||
export interface ParseResult {
|
||||
frames: ParsedFrame[];
|
||||
error?: boolean;
|
||||
code?: number;
|
||||
message?: string;
|
||||
}
|
||||
|
||||
export interface ParserInstance {
|
||||
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;
|
||||
}
|
||||
|
||||
function platformBinaryName(): string {
|
||||
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'),
|
||||
];
|
||||
}
|
||||
|
||||
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(', ')}`,
|
||||
);
|
||||
}
|
||||
|
||||
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 addon: NativeAddon = loadAddon();
|
||||
export default addon;
|
||||
@@ -1,21 +1,22 @@
|
||||
import { EventEmitter } from 'node:events';
|
||||
import http from 'node:http';
|
||||
import https from 'node:https';
|
||||
import native from './native.js';
|
||||
import type { IncomingMessage, Server as HttpServer, ServerResponse } from 'node:http';
|
||||
import type { Server as HttpsServer } from 'node:https';
|
||||
import type { Duplex } from 'node:stream';
|
||||
import native from './native';
|
||||
import {
|
||||
type PerMessageDeflateConfig,
|
||||
acceptPerMessageDeflate,
|
||||
chooseSubprotocol,
|
||||
} from './extensions.js';
|
||||
import { WebSocket, OPEN } from './websocket.js';
|
||||
} from './extensions';
|
||||
import { WebSocket, OPEN } from './websocket';
|
||||
|
||||
const WS_GUID = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11';
|
||||
|
||||
function computeAccept(key) {
|
||||
function computeAccept(key: string): string {
|
||||
return native.computeAcceptKey(key);
|
||||
}
|
||||
|
||||
// Abort the upgrade with a canned HTTP error response.
|
||||
function abortUpgrade(socket, status, message) {
|
||||
function abortUpgrade(socket: Duplex, status: number, message?: string): void {
|
||||
try {
|
||||
const body = message ? message : http.STATUS_CODES[status] || '';
|
||||
const head =
|
||||
@@ -23,41 +24,44 @@ function abortUpgrade(socket, status, message) {
|
||||
'Connection: close\r\n' +
|
||||
`Content-Length: ${Buffer.byteLength(body)}\r\n` +
|
||||
'Content-Type: text/plain\r\n\r\n';
|
||||
socket.write(head + body);
|
||||
socket.write(head + body);
|
||||
} catch { /* noop */ }
|
||||
try { socket.destroy(); } catch { /* noop */ }
|
||||
}
|
||||
|
||||
function getTlsOptions(options) {
|
||||
const 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',
|
||||
];
|
||||
const tlsOptions = {};
|
||||
for (const key of keys) {
|
||||
if (options[key] !== undefined) tlsOptions[key] = options[key];
|
||||
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',
|
||||
] 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);
|
||||
@@ -65,8 +69,32 @@ function getTlsOptions(options) {
|
||||
return tlsOptions;
|
||||
}
|
||||
|
||||
class WebSocketServer extends EventEmitter {
|
||||
constructor(options) {
|
||||
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;
|
||||
}
|
||||
|
||||
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;
|
||||
|
||||
constructor(options?: WebSocketServerOptions) {
|
||||
super();
|
||||
options = options || {};
|
||||
this.options = {
|
||||
@@ -82,15 +110,10 @@ class WebSocketServer extends EventEmitter {
|
||||
backlog: options.backlog,
|
||||
tls: options.tls,
|
||||
};
|
||||
const tlsOptions = getTlsOptions(options);
|
||||
const tlsOptions = getTlsOptions(options as WebSocketServerOptions & TlsOptions);
|
||||
this.options.tls = Object.keys(tlsOptions).length > 0 ? tlsOptions : undefined;
|
||||
this.clients = new Set();
|
||||
this._server = null; // internal http.Server (if we own it)
|
||||
this._externalServer = null;
|
||||
this._upgradeHandler = null;
|
||||
|
||||
if (this.options.noServer) {
|
||||
// Just provide handleUpgrade; user is responsible for routing.
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -98,9 +121,8 @@ class WebSocketServer extends EventEmitter {
|
||||
this._externalServer = this.options.server;
|
||||
this._attachToServer(this._externalServer);
|
||||
} else if (this.options.port !== undefined) {
|
||||
const requestHandler = (req, res) => {
|
||||
// Non-WebSocket HTTP hits on the standalone port get a 426.
|
||||
const body = http.STATUS_CODES[426];
|
||||
const requestHandler = (_req: IncomingMessage, res: ServerResponse) => {
|
||||
const body = http.STATUS_CODES[426] ?? '';
|
||||
res.writeHead(426, {
|
||||
'Content-Length': Buffer.byteLength(body),
|
||||
'Content-Type': 'text/plain',
|
||||
@@ -117,25 +139,23 @@ class WebSocketServer extends EventEmitter {
|
||||
this.options.backlog,
|
||||
() => this.emit('listening'),
|
||||
);
|
||||
this._server.on('error', (err) => this.emit('error', err));
|
||||
this._server.on('error', (err: Error) => this.emit('error', err));
|
||||
} else {
|
||||
throw new Error('WebSocketServer requires { port } or { server } or { noServer: true }');
|
||||
}
|
||||
}
|
||||
|
||||
address() {
|
||||
address(): ReturnType<HttpServer['address']> | null {
|
||||
if (this._server) return this._server.address();
|
||||
if (this._externalServer && this._externalServer.address) return this._externalServer.address();
|
||||
return null;
|
||||
}
|
||||
|
||||
_attachToServer(server) {
|
||||
const handler = (req, socket, head) => {
|
||||
// If a path is configured, filter on it.
|
||||
private _attachToServer(server: HttpServer | HttpsServer): void {
|
||||
const handler: UpgradeHandler = (req, socket, head) => {
|
||||
if (this.options.path) {
|
||||
const urlPath = req.url.split('?')[0];
|
||||
const urlPath = (req.url ?? '/').split('?')[0];
|
||||
if (urlPath !== this.options.path) {
|
||||
// Let other upgrade listeners handle it; if none, abort.
|
||||
if (server.listenerCount('upgrade') === 1) {
|
||||
abortUpgrade(socket, 400, 'Bad path for WebSocket');
|
||||
}
|
||||
@@ -150,11 +170,14 @@ class WebSocketServer extends EventEmitter {
|
||||
server.on('upgrade', handler);
|
||||
}
|
||||
|
||||
// Perform the RFC 6455 handshake on an already-produced upgrade request.
|
||||
// Accepts the same argument shape as `ws` for drop-in compatibility.
|
||||
handleUpgrade(request, socket, head, cb) {
|
||||
const upgrade = (request.headers['upgrade'] || '').toLowerCase();
|
||||
const connection = (request.headers['connection'] || '').toLowerCase();
|
||||
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'];
|
||||
|
||||
@@ -167,22 +190,22 @@ class WebSocketServer extends EventEmitter {
|
||||
'HTTP/1.1 426 Upgrade Required\r\n' +
|
||||
'Sec-WebSocket-Version: 13\r\n' +
|
||||
'Connection: close\r\n\r\n');
|
||||
} catch {}
|
||||
try { socket.destroy(); } catch {}
|
||||
} catch { /* noop */ }
|
||||
try { socket.destroy(); } catch { /* noop */ }
|
||||
return;
|
||||
}
|
||||
if (!key || !/^[+/0-9A-Za-z]{22}==$/.test(key)) {
|
||||
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'],
|
||||
request.headers['sec-websocket-extensions'] as string | undefined,
|
||||
this.options.perMessageDeflate,
|
||||
);
|
||||
const protocol = chooseSubprotocol(
|
||||
request.headers['sec-websocket-protocol'],
|
||||
request.headers['sec-websocket-protocol'] as string | undefined,
|
||||
this.options.protocols,
|
||||
);
|
||||
const responseHeaders = [
|
||||
@@ -195,42 +218,48 @@ class WebSocketServer extends EventEmitter {
|
||||
if (protocol) responseHeaders.push(`Sec-WebSocket-Protocol: ${protocol}`);
|
||||
try {
|
||||
socket.write(responseHeaders.join('\r\n') + '\r\n\r\n');
|
||||
} catch (err) {
|
||||
try { socket.destroy(); } catch {}
|
||||
} catch {
|
||||
try { socket.destroy(); } catch { /* noop */ }
|
||||
return;
|
||||
}
|
||||
|
||||
// Disable Nagle for lower latency (typical WS guidance).
|
||||
if (socket.setTimeout) socket.setTimeout(0);
|
||||
if (socket.setNoDelay) socket.setNoDelay(true);
|
||||
const ns = socket as Duplex & { setTimeout?: (ms: number) => void; setNoDelay?: (b: boolean) => void };
|
||||
ns.setTimeout?.(0);
|
||||
ns.setNoDelay?.(true);
|
||||
|
||||
const ws = new WebSocket(socket, {
|
||||
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: protocol ?? '',
|
||||
readyState: OPEN,
|
||||
});
|
||||
this.clients.add(ws);
|
||||
ws.on('close', () => this.clients.delete(ws));
|
||||
|
||||
// If `head` contained bytes past the HTTP request (unusual for most
|
||||
// clients but possible), feed them into the parser now.
|
||||
if (head && head.length > 0) ws._onData(head);
|
||||
|
||||
cb(ws, request);
|
||||
};
|
||||
|
||||
if (typeof this.options.verifyClient === 'function') {
|
||||
const info = { origin: request.headers['origin'], secure: !!(socket.encrypted), req: request };
|
||||
if (this.options.verifyClient.length >= 2) {
|
||||
// Async style: (info, cb)
|
||||
this.options.verifyClient(info, (allow, code, message, headers) => {
|
||||
if (!allow) return abortUpgrade(socket, code || 401, message);
|
||||
doAccept();
|
||||
});
|
||||
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 = this.options.verifyClient(info);
|
||||
const allow = (verify as (i: VerifyInfo) => boolean)(info);
|
||||
if (!allow) return abortUpgrade(socket, 401, 'Unauthorized');
|
||||
doAccept();
|
||||
}
|
||||
@@ -239,22 +268,18 @@ class WebSocketServer extends EventEmitter {
|
||||
}
|
||||
}
|
||||
|
||||
close(cb) {
|
||||
// Stop accepting new upgrades and close our owned server (if any).
|
||||
close(cb?: (err?: Error) => void): void {
|
||||
if (this._externalServer && this._upgradeHandler) {
|
||||
this._externalServer.removeListener('upgrade', this._upgradeHandler);
|
||||
this._upgradeHandler = null;
|
||||
}
|
||||
// Initiate a graceful close on all live clients.
|
||||
for (const ws of this.clients) {
|
||||
try { ws.close(1001, 'Server shutting down'); } catch {}
|
||||
try { ws.close(1001, 'Server shutting down'); } catch { /* noop */ }
|
||||
}
|
||||
if (this._server) {
|
||||
this._server.close((err) => cb && cb(err));
|
||||
this._server.close((err?: Error) => cb && cb(err));
|
||||
} else if (cb) {
|
||||
setImmediate(cb);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export { WebSocketServer };
|
||||
@@ -1,37 +1,43 @@
|
||||
import { EventEmitter } from 'node:events';
|
||||
import crypto from 'node:crypto';
|
||||
import native from './native.js';
|
||||
import { compressRaw, decompressRaw } from './extensions.js';
|
||||
import type { Socket } from 'node:net';
|
||||
import native, { type ParsedFrame, type ParserInstance } from './native';
|
||||
import {
|
||||
type AcceptedPerMessageDeflate,
|
||||
compressRaw,
|
||||
decompressRaw,
|
||||
} from './extensions';
|
||||
|
||||
// RFC 6455 opcodes.
|
||||
const OP_CONT = 0x0;
|
||||
const OP_TEXT = 0x1;
|
||||
const OP_BIN = 0x2;
|
||||
const OP_CLOSE = 0x8;
|
||||
const OP_PING = 0x9;
|
||||
const OP_PONG = 0xA;
|
||||
const RSV1 = 0x40;
|
||||
export const OP_CONT = 0x0;
|
||||
export const OP_TEXT = 0x1;
|
||||
export const OP_BIN = 0x2;
|
||||
export const OP_CLOSE = 0x8;
|
||||
export const OP_PING = 0x9;
|
||||
export const OP_PONG = 0xA;
|
||||
export const RSV1 = 0x40;
|
||||
|
||||
// Ready states (mirror the standard WebSocket API numbers).
|
||||
const CONNECTING = 0;
|
||||
const OPEN = 1;
|
||||
const CLOSING = 2;
|
||||
const CLOSED = 3;
|
||||
export const CONNECTING = 0;
|
||||
export const OPEN = 1;
|
||||
export const CLOSING = 2;
|
||||
export const CLOSED = 3;
|
||||
|
||||
// Default cap per-message and per-frame.
|
||||
const DEFAULT_MAX_PAYLOAD = 100 * 1024 * 1024;
|
||||
|
||||
function isValidCloseCode(code) {
|
||||
if (code === 1000 || code === 1001 || code === 1002 || code === 1003 ||
|
||||
code === 1007 || code === 1008 || code === 1009 || code === 1010 ||
|
||||
code === 1011) {
|
||||
export function isValidCloseCode(code: number): boolean {
|
||||
if (
|
||||
code === 1000 || code === 1001 || code === 1002 || code === 1003 ||
|
||||
code === 1007 || code === 1008 || code === 1009 || code === 1010 ||
|
||||
code === 1011
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
if (code >= 3000 && code <= 4999) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
function encodeClosePayload(code, reason) {
|
||||
export function encodeClosePayload(code: number | undefined | null, reason?: string): Buffer {
|
||||
const reasonBuf = reason ? Buffer.from(String(reason), 'utf8') : Buffer.alloc(0);
|
||||
if (code === undefined || code === null) {
|
||||
if (reasonBuf.length > 0) {
|
||||
@@ -46,22 +52,19 @@ function encodeClosePayload(code, reason) {
|
||||
}
|
||||
|
||||
// Streaming UTF-8 validator used while a text message is being received in
|
||||
// fragments. Returns { ok, done } after appending a chunk; `done` means the
|
||||
// message ended on a code-point boundary.
|
||||
// fragments. Returns false if invalid; `done()` checks code-point boundary.
|
||||
class Utf8Validator {
|
||||
constructor() {
|
||||
this.state = 0; // bytes still expected in current code point
|
||||
this.codepoint = 0;
|
||||
this.minNext = 0; // for overlong / surrogate range validation
|
||||
}
|
||||
private state = 0;
|
||||
private codepoint = 0;
|
||||
private minNext = 0;
|
||||
|
||||
push(buf) {
|
||||
push(buf: Buffer): boolean {
|
||||
for (let i = 0; i < buf.length; i++) {
|
||||
const b = buf[i];
|
||||
const b = buf[i]!;
|
||||
if (this.state === 0) {
|
||||
if ((b & 0x80) === 0) continue;
|
||||
if ((b & 0xE0) === 0xC0) {
|
||||
if (b < 0xC2) return false; // overlong
|
||||
if (b < 0xC2) return false;
|
||||
this.codepoint = b & 0x1F;
|
||||
this.state = 1;
|
||||
this.minNext = 0x80;
|
||||
@@ -79,11 +82,7 @@ class Utf8Validator {
|
||||
}
|
||||
} else {
|
||||
if (b < this.minNext || b > 0xBF) return false;
|
||||
// Reject UTF-16 surrogates encoded as 3-byte sequences (ED A0..BF ..).
|
||||
if (this.state === 2 && this.codepoint === 0xD && (b & 0x20)) {
|
||||
// Actually this branch is unreachable because minNext would be 0x80
|
||||
// and for codepoint starting 0xED (codepoint==0xD) minNext above is
|
||||
// 0x80 already so any A0..BF passes. We explicitly reject here.
|
||||
return false;
|
||||
}
|
||||
if (this.codepoint === 0xD && this.state === 2 && b >= 0xA0) {
|
||||
@@ -97,67 +96,107 @@ class Utf8Validator {
|
||||
return true;
|
||||
}
|
||||
|
||||
done() {
|
||||
done(): boolean {
|
||||
return this.state === 0;
|
||||
}
|
||||
}
|
||||
|
||||
function randomMaskKey() {
|
||||
export function randomMaskKey(): Buffer {
|
||||
const b = Buffer.allocUnsafe(4);
|
||||
// crypto.randomFillSync is slightly faster than randomBytes for small sizes.
|
||||
crypto.randomFillSync(b);
|
||||
return b;
|
||||
}
|
||||
|
||||
// Shared WebSocket connection handling logic. Used by both server- and
|
||||
// client-side after a successful handshake.
|
||||
class WebSocket extends EventEmitter {
|
||||
constructor(socket, options) {
|
||||
export interface SendOptions {
|
||||
binary?: boolean;
|
||||
compress?: boolean;
|
||||
}
|
||||
|
||||
export type SendCallback = (err?: Error | null) => void;
|
||||
|
||||
export type WebSocketRawData = Buffer;
|
||||
|
||||
export interface WebSocketEvents {
|
||||
message: (data: Buffer, isBinary: boolean) => void;
|
||||
ping: (data: Buffer) => void;
|
||||
pong: (data: Buffer) => void;
|
||||
close: (code: number, reason: string) => void;
|
||||
error: (err: Error) => void;
|
||||
}
|
||||
|
||||
export interface WebSocketOptions {
|
||||
isServer?: boolean;
|
||||
maxPayload?: number;
|
||||
readyState?: number;
|
||||
extensions?: { perMessageDeflate?: AcceptedPerMessageDeflate };
|
||||
protocol?: string;
|
||||
}
|
||||
|
||||
// Shared WebSocket connection handling logic (post-handshake).
|
||||
export class WebSocket extends EventEmitter {
|
||||
protected readonly _socket: Socket;
|
||||
protected readonly _isServer: boolean;
|
||||
protected readonly _maxPayload: number;
|
||||
protected _readyState: number;
|
||||
protected readonly _perMessageDeflate?: AcceptedPerMessageDeflate;
|
||||
public protocol: string;
|
||||
public extensions: string;
|
||||
|
||||
protected readonly _parser: ParserInstance;
|
||||
|
||||
// Fragmented message assembly state.
|
||||
protected _msgOpcode = 0;
|
||||
protected _msgChunks: Buffer[] = [];
|
||||
protected _msgSize = 0;
|
||||
protected _msgValidator: Utf8Validator | null = null;
|
||||
protected _msgCompressed = false;
|
||||
|
||||
// Close state.
|
||||
protected _closeCodeSent: number | null = null;
|
||||
protected _closeCodeReceived: number | null = null;
|
||||
protected _closeReasonReceived = '';
|
||||
protected _closeFrameSent = false;
|
||||
protected _closeTimer: NodeJS.Timeout | null = null;
|
||||
|
||||
// Ready state constants exposed as instance fields (for ws compatibility).
|
||||
static readonly CONNECTING = CONNECTING;
|
||||
static readonly OPEN = OPEN;
|
||||
static readonly CLOSING = CLOSING;
|
||||
static readonly CLOSED = CLOSED;
|
||||
|
||||
constructor(socket: Socket, options?: WebSocketOptions) {
|
||||
super();
|
||||
options = options || {};
|
||||
this._socket = socket;
|
||||
this._isServer = !!options.isServer;
|
||||
this._maxPayload = options.maxPayload ?? DEFAULT_MAX_PAYLOAD;
|
||||
this._readyState = options.readyState ?? OPEN;
|
||||
this._perMessageDeflate = options.extensions && options.extensions.perMessageDeflate;
|
||||
this._perMessageDeflate = options.extensions?.perMessageDeflate;
|
||||
this.protocol = options.protocol || '';
|
||||
this.extensions = this._perMessageDeflate ? 'permessage-deflate' : '';
|
||||
|
||||
this._parser = new native.Parser({
|
||||
isServer: this._isServer, // server expects masked frames from clients
|
||||
isServer: this._isServer,
|
||||
maxPayload: this._maxPayload,
|
||||
allowedRsv: this._perMessageDeflate ? RSV1 : 0,
|
||||
});
|
||||
|
||||
// Fragmented message assembly state.
|
||||
this._msgOpcode = 0;
|
||||
this._msgChunks = [];
|
||||
this._msgSize = 0;
|
||||
this._msgValidator = null;
|
||||
this._msgCompressed = false;
|
||||
|
||||
// Close state.
|
||||
this._closeCodeSent = null;
|
||||
this._closeCodeReceived = null;
|
||||
this._closeReasonReceived = '';
|
||||
this._closeFrameSent = false;
|
||||
this._closeTimer = null;
|
||||
|
||||
this._bindSocket();
|
||||
}
|
||||
|
||||
get readyState() { return this._readyState; }
|
||||
get isServer() { return this._isServer; }
|
||||
get readyState(): number { return this._readyState; }
|
||||
get isServer(): boolean { return this._isServer; }
|
||||
|
||||
_bindSocket() {
|
||||
protected _bindSocket(): void {
|
||||
const sock = this._socket;
|
||||
sock.on('data', (chunk) => this._onData(chunk));
|
||||
sock.on('data', (chunk: Buffer) => this._onData(chunk));
|
||||
sock.on('end', () => this._onEnd());
|
||||
sock.on('close', () => this._onSocketClose());
|
||||
sock.on('error', (err) => this._onError(err));
|
||||
sock.on('error', (err: Error) => this._onError(err));
|
||||
}
|
||||
|
||||
_onData(chunk) {
|
||||
/** @internal */
|
||||
_onData(chunk: Buffer): void {
|
||||
if (this._readyState === CLOSED) return;
|
||||
const res = this._parser.push(chunk);
|
||||
if (res.error) {
|
||||
@@ -170,10 +209,8 @@ class WebSocket extends EventEmitter {
|
||||
}
|
||||
}
|
||||
|
||||
_onEnd() {
|
||||
// Peer gracefully half-closed without a Close frame.
|
||||
protected _onEnd(): void {
|
||||
if (this._readyState !== CLOSED) {
|
||||
// If we never received a Close, treat as abnormal.
|
||||
if (this._closeCodeReceived === null) {
|
||||
this._closeCodeReceived = 1006;
|
||||
this._closeReasonReceived = '';
|
||||
@@ -182,7 +219,7 @@ class WebSocket extends EventEmitter {
|
||||
}
|
||||
}
|
||||
|
||||
_onSocketClose() {
|
||||
protected _onSocketClose(): void {
|
||||
if (this._readyState === CLOSED) return;
|
||||
if (this._closeCodeReceived === null) {
|
||||
this._closeCodeReceived = 1006;
|
||||
@@ -192,12 +229,13 @@ class WebSocket extends EventEmitter {
|
||||
this.emit('close', this._closeCodeReceived, this._closeReasonReceived);
|
||||
}
|
||||
|
||||
_onError(err) {
|
||||
protected _onError(err: Error): void {
|
||||
this.emit('error', err);
|
||||
}
|
||||
|
||||
_handleFrame(f) {
|
||||
const { fin, opcode, payload, rsv = 0 } = f;
|
||||
protected _handleFrame(f: ParsedFrame): void {
|
||||
const { fin, opcode, payload } = f;
|
||||
const rsv = f.rsv ?? 0;
|
||||
if (opcode === OP_PING) {
|
||||
this.emit('ping', payload);
|
||||
if (this._readyState === OPEN) this._sendControl(OP_PONG, payload);
|
||||
@@ -212,7 +250,6 @@ class WebSocket extends EventEmitter {
|
||||
return;
|
||||
}
|
||||
|
||||
// Data frames (TEXT / BIN / CONT).
|
||||
if (opcode === OP_TEXT || opcode === OP_BIN) {
|
||||
if (this._msgOpcode !== 0) {
|
||||
this._failConnection(1002, 'New data frame started before previous fragmented message finished');
|
||||
@@ -226,8 +263,7 @@ class WebSocket extends EventEmitter {
|
||||
this._msgChunks = [];
|
||||
this._msgSize = 0;
|
||||
this._msgCompressed = (rsv & RSV1) !== 0;
|
||||
if (opcode === OP_TEXT) this._msgValidator = new Utf8Validator();
|
||||
else this._msgValidator = null;
|
||||
this._msgValidator = (opcode === OP_TEXT) ? new Utf8Validator() : null;
|
||||
} else if (opcode === OP_CONT) {
|
||||
if (this._msgOpcode === 0) {
|
||||
this._failConnection(1002, 'Continuation frame without active message');
|
||||
@@ -248,13 +284,14 @@ class WebSocket extends EventEmitter {
|
||||
|
||||
if (fin) {
|
||||
let data = this._msgChunks.length === 1
|
||||
? this._msgChunks[0]
|
||||
? this._msgChunks[0]!
|
||||
: Buffer.concat(this._msgChunks, this._msgSize);
|
||||
if (this._msgCompressed) {
|
||||
try {
|
||||
data = decompressRaw(data, this._maxPayload);
|
||||
} catch (err) {
|
||||
this._failConnection(err.code || 1007, err.message || 'Invalid compressed payload');
|
||||
const e = err as Error & { code?: number };
|
||||
this._failConnection(e.code || 1007, e.message || 'Invalid compressed payload');
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -274,22 +311,25 @@ class WebSocket extends EventEmitter {
|
||||
}
|
||||
}
|
||||
|
||||
_handleCloseFrame(payload) {
|
||||
protected _handleCloseFrame(payload: Buffer): void {
|
||||
let code = 1005;
|
||||
let reason = '';
|
||||
if (payload.length === 1) {
|
||||
return this._failConnection(1002, 'Close payload length 1');
|
||||
this._failConnection(1002, 'Close payload length 1');
|
||||
return;
|
||||
}
|
||||
if (payload.length >= 2) {
|
||||
code = payload.readUInt16BE(0);
|
||||
if (!isValidCloseCode(code)) {
|
||||
return this._failConnection(1002, 'Invalid close code');
|
||||
this._failConnection(1002, 'Invalid close code');
|
||||
return;
|
||||
}
|
||||
if (payload.length > 2) {
|
||||
try {
|
||||
reason = new TextDecoder('utf-8', { fatal: true }).decode(payload.subarray(2));
|
||||
} catch {
|
||||
return this._failConnection(1007, 'Invalid UTF-8 in close reason');
|
||||
this._failConnection(1007, 'Invalid UTF-8 in close reason');
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -297,92 +337,86 @@ class WebSocket extends EventEmitter {
|
||||
this._closeReasonReceived = reason;
|
||||
|
||||
if (this._readyState === OPEN) {
|
||||
// Echo a close frame back with same code (per RFC 6455 §5.5.1).
|
||||
this._readyState = CLOSING;
|
||||
const echo = encodeClosePayload(code === 1005 ? undefined : code, '');
|
||||
this._sendControl(OP_CLOSE, echo);
|
||||
this._closeFrameSent = true;
|
||||
this._endSocketSoon();
|
||||
} else if (this._readyState === CLOSING) {
|
||||
// We already sent our close frame; the handshake is complete.
|
||||
this._endSocketSoon();
|
||||
}
|
||||
}
|
||||
|
||||
_endSocketSoon() {
|
||||
// Flush pending writes then half-close. Give the peer a moment to close.
|
||||
protected _endSocketSoon(): void {
|
||||
try { this._socket.end(); } catch { /* noop */ }
|
||||
if (this._closeTimer) clearTimeout(this._closeTimer);
|
||||
this._closeTimer = setTimeout(() => this._destroySocket(), 30000);
|
||||
this._closeTimer.unref && this._closeTimer.unref();
|
||||
this._closeTimer.unref?.();
|
||||
}
|
||||
|
||||
_destroySocket() {
|
||||
protected _destroySocket(): void {
|
||||
try { this._socket.destroy(); } catch { /* noop */ }
|
||||
}
|
||||
|
||||
_failConnection(code, reason) {
|
||||
protected _failConnection(code: number, reason: string): void {
|
||||
if (this._readyState === CLOSED) return;
|
||||
const payload = encodeClosePayload(code, reason);
|
||||
let frame = null;
|
||||
let frame: Buffer | null = null;
|
||||
try {
|
||||
frame = native.buildFrame(OP_CLOSE, true, payload,
|
||||
this._isServer ? null : randomMaskKey(), 0);
|
||||
} catch { /* noop */ }
|
||||
this._closeCodeSent = code;
|
||||
this._readyState = CLOSING;
|
||||
const err = new Error(`WebSocket protocol error: ${reason}`);
|
||||
const err = new Error(`WebSocket protocol error: ${reason}`) as Error & { code?: number };
|
||||
err.code = code;
|
||||
this.emit('error', err);
|
||||
// Use `end(frame)` so the close frame flushes and a FIN is sent. This
|
||||
// yields a clean TCP half-close peers can observe via the 'end' event.
|
||||
try {
|
||||
if (frame) this._socket.end(frame);
|
||||
else this._socket.end();
|
||||
} catch { /* noop */ }
|
||||
// Failsafe: destroy if the peer never FIN's back.
|
||||
if (this._closeTimer) clearTimeout(this._closeTimer);
|
||||
this._closeTimer = setTimeout(() => this._destroySocket(), 2000);
|
||||
this._closeTimer.unref && this._closeTimer.unref();
|
||||
this._closeTimer.unref?.();
|
||||
}
|
||||
|
||||
_sendControl(opcode, payload) {
|
||||
if (!payload) payload = Buffer.alloc(0);
|
||||
const frame = native.buildFrame(opcode, true, payload, this._isServer ? null : randomMaskKey(), 0);
|
||||
protected _sendControl(opcode: number, payload?: Buffer): void {
|
||||
const data = payload ?? Buffer.alloc(0);
|
||||
const frame = native.buildFrame(opcode, true, data, this._isServer ? null : randomMaskKey(), 0);
|
||||
this._socket.write(frame);
|
||||
}
|
||||
|
||||
// Public API -------------------------------------------------------------
|
||||
|
||||
send(data, options, cb) {
|
||||
send(data: string | Buffer | Uint8Array | ArrayBuffer, options?: SendOptions | SendCallback, cb?: SendCallback): void {
|
||||
if (typeof options === 'function') { cb = options; options = undefined; }
|
||||
options = options || {};
|
||||
const opts: SendOptions = options || {};
|
||||
if (this._readyState !== OPEN) {
|
||||
const err = new Error('WebSocket is not open');
|
||||
if (cb) return cb(err);
|
||||
if (cb) { cb(err); return; }
|
||||
throw err;
|
||||
}
|
||||
let payload;
|
||||
let opcode;
|
||||
let payload: Buffer;
|
||||
let opcode: number;
|
||||
if (typeof data === 'string') {
|
||||
payload = Buffer.from(data, 'utf8');
|
||||
opcode = options.binary ? OP_BIN : OP_TEXT;
|
||||
opcode = opts.binary ? OP_BIN : OP_TEXT;
|
||||
} else if (Buffer.isBuffer(data)) {
|
||||
payload = data;
|
||||
opcode = options.binary === false ? OP_TEXT : OP_BIN;
|
||||
opcode = opts.binary === false ? OP_TEXT : OP_BIN;
|
||||
} else if (data instanceof Uint8Array) {
|
||||
payload = Buffer.from(data.buffer, data.byteOffset, data.byteLength);
|
||||
opcode = options.binary === false ? OP_TEXT : OP_BIN;
|
||||
opcode = opts.binary === false ? OP_TEXT : OP_BIN;
|
||||
} else if (data instanceof ArrayBuffer) {
|
||||
payload = Buffer.from(data);
|
||||
opcode = options.binary === false ? OP_TEXT : OP_BIN;
|
||||
opcode = opts.binary === false ? OP_TEXT : OP_BIN;
|
||||
} else {
|
||||
const err = new TypeError('Unsupported data type for send()');
|
||||
if (cb) return cb(err);
|
||||
if (cb) { cb(err); return; }
|
||||
throw err;
|
||||
}
|
||||
let rsv = 0;
|
||||
if (this._perMessageDeflate && options.compress !== false &&
|
||||
if (this._perMessageDeflate && opts.compress !== false &&
|
||||
payload.length >= (this._perMessageDeflate.threshold ?? 1024)) {
|
||||
payload = compressRaw(payload);
|
||||
rsv = RSV1;
|
||||
@@ -392,14 +426,15 @@ class WebSocket extends EventEmitter {
|
||||
this._socket.write(frame, cb);
|
||||
}
|
||||
|
||||
ping(data, mask, cb) {
|
||||
if (typeof data === 'function') { cb = data; data = undefined; mask = undefined; }
|
||||
if (typeof mask === 'function') { cb = mask; mask = undefined; }
|
||||
const payload = data ? (Buffer.isBuffer(data) ? data : Buffer.from(String(data), 'utf8')) : Buffer.alloc(0);
|
||||
ping(data?: Buffer | string | SendCallback, _mask?: unknown, cb?: SendCallback): void {
|
||||
if (typeof data === 'function') { cb = data; data = undefined; }
|
||||
const payload = data
|
||||
? (Buffer.isBuffer(data) ? data : Buffer.from(String(data), 'utf8'))
|
||||
: Buffer.alloc(0);
|
||||
if (payload.length > 125) throw new Error('Ping payload must be <=125 bytes');
|
||||
if (this._readyState !== OPEN) {
|
||||
const err = new Error('WebSocket is not open');
|
||||
if (cb) return cb(err);
|
||||
if (cb) { cb(err); return; }
|
||||
throw err;
|
||||
}
|
||||
const maskKey = this._isServer ? null : randomMaskKey();
|
||||
@@ -407,14 +442,15 @@ class WebSocket extends EventEmitter {
|
||||
this._socket.write(frame, cb);
|
||||
}
|
||||
|
||||
pong(data, mask, cb) {
|
||||
if (typeof data === 'function') { cb = data; data = undefined; mask = undefined; }
|
||||
if (typeof mask === 'function') { cb = mask; mask = undefined; }
|
||||
const payload = data ? (Buffer.isBuffer(data) ? data : Buffer.from(String(data), 'utf8')) : Buffer.alloc(0);
|
||||
pong(data?: Buffer | string | SendCallback, _mask?: unknown, cb?: SendCallback): void {
|
||||
if (typeof data === 'function') { cb = data; data = undefined; }
|
||||
const payload = data
|
||||
? (Buffer.isBuffer(data) ? data : Buffer.from(String(data), 'utf8'))
|
||||
: Buffer.alloc(0);
|
||||
if (payload.length > 125) throw new Error('Pong payload must be <=125 bytes');
|
||||
if (this._readyState !== OPEN) {
|
||||
const err = new Error('WebSocket is not open');
|
||||
if (cb) return cb(err);
|
||||
if (cb) { cb(err); return; }
|
||||
throw err;
|
||||
}
|
||||
const maskKey = this._isServer ? null : randomMaskKey();
|
||||
@@ -422,7 +458,7 @@ class WebSocket extends EventEmitter {
|
||||
this._socket.write(frame, cb);
|
||||
}
|
||||
|
||||
close(code, reason) {
|
||||
close(code?: number, reason?: string): void {
|
||||
if (this._readyState === CLOSED || this._readyState === CLOSING) return;
|
||||
if (code !== undefined && !isValidCloseCode(code)) {
|
||||
throw new RangeError(`Invalid close code: ${code}`);
|
||||
@@ -439,23 +475,8 @@ class WebSocket extends EventEmitter {
|
||||
this._endSocketSoon();
|
||||
}
|
||||
|
||||
terminate() {
|
||||
terminate(): void {
|
||||
this._readyState = CLOSING;
|
||||
this._destroySocket();
|
||||
}
|
||||
}
|
||||
|
||||
WebSocket.CONNECTING = CONNECTING;
|
||||
WebSocket.OPEN = OPEN;
|
||||
WebSocket.CLOSING = CLOSING;
|
||||
WebSocket.CLOSED = CLOSED;
|
||||
|
||||
export {
|
||||
WebSocket,
|
||||
CONNECTING, OPEN, CLOSING, CLOSED,
|
||||
OP_CONT, OP_TEXT, OP_BIN, OP_CLOSE, OP_PING, OP_PONG,
|
||||
RSV1,
|
||||
isValidCloseCode,
|
||||
encodeClosePayload,
|
||||
randomMaskKey,
|
||||
};
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"types": ["node"]
|
||||
},
|
||||
"include": ["src/**/*"],
|
||||
"exclude": ["node_modules"]
|
||||
}
|
||||
Generated
+13
-32
@@ -26,9 +26,9 @@ importers:
|
||||
|
||||
packages/core:
|
||||
dependencies:
|
||||
ws:
|
||||
specifier: ^8.20.0
|
||||
version: 8.20.0
|
||||
'@snowluma/websocket':
|
||||
specifier: workspace:*
|
||||
version: link:../websocket
|
||||
devDependencies:
|
||||
'@hono/node-server':
|
||||
specifier: ^1.19.14
|
||||
@@ -39,9 +39,6 @@ importers:
|
||||
'@types/node':
|
||||
specifier: ^24.12.2
|
||||
version: 24.12.2
|
||||
'@types/ws':
|
||||
specifier: ^8.18.1
|
||||
version: 8.18.1
|
||||
cross-env:
|
||||
specifier: ^10.1.0
|
||||
version: 10.1.0
|
||||
@@ -64,11 +61,16 @@ importers:
|
||||
specifier: ^4.1.4
|
||||
version: 4.1.4(@types/[email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))
|
||||
|
||||
packages/runtime:
|
||||
dependencies:
|
||||
ws:
|
||||
specifier: ^8.20.0
|
||||
version: 8.20.0
|
||||
packages/runtime: {}
|
||||
|
||||
packages/websocket:
|
||||
devDependencies:
|
||||
'@types/node':
|
||||
specifier: ^24.12.2
|
||||
version: 24.12.2
|
||||
typescript:
|
||||
specifier: 'catalog:'
|
||||
version: 6.0.2
|
||||
|
||||
packages/webui:
|
||||
dependencies:
|
||||
@@ -1258,9 +1260,6 @@ packages:
|
||||
'@types/[email protected]':
|
||||
resolution: {integrity: sha512-60BCwRFOZCQhDncwQdxxeOEEkbc5dIMccYLwbxsS4TUNeVECQ/pBJ0j09mrHOl/JJvpRPGwO9SvE4nR2Nb/a4Q==}
|
||||
|
||||
'@types/[email protected]':
|
||||
resolution: {integrity: sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==}
|
||||
|
||||
'@typescript-eslint/[email protected]':
|
||||
resolution: {integrity: sha512-aC2qc5thQahutKjP+cl8cgN9DWe3ZUqVko30CMSZHnFEHyhOYoZSzkGtAI2mcwZ38xeImDucI4dnqsHiOYuuCw==}
|
||||
engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
|
||||
@@ -2219,18 +2218,6 @@ packages:
|
||||
resolution: {integrity: sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==}
|
||||
engines: {node: '>=0.10.0'}
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-sAt8BhgNbzCtgGbt2OxmpuryO63ZoDk/sqaB/znQm94T4fCEsy/yV+7CdC1kJhOU9lboAEU7R3kquuycDoibVA==}
|
||||
engines: {node: '>=10.0.0'}
|
||||
peerDependencies:
|
||||
bufferutil: ^4.0.1
|
||||
utf-8-validate: '>=5.0.2'
|
||||
peerDependenciesMeta:
|
||||
bufferutil:
|
||||
optional: true
|
||||
utf-8-validate:
|
||||
optional: true
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==}
|
||||
|
||||
@@ -3327,10 +3314,6 @@ snapshots:
|
||||
|
||||
'@types/[email protected]': {}
|
||||
|
||||
'@types/[email protected]':
|
||||
dependencies:
|
||||
'@types/node': 25.6.0
|
||||
|
||||
'@typescript-eslint/[email protected](@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])':
|
||||
dependencies:
|
||||
'@eslint-community/regexpp': 4.12.2
|
||||
@@ -4306,8 +4289,6 @@ snapshots:
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
Reference in new issue
Block a user