샘플
ws 8.18.0: Prove that WebSocketServer in noServer mode requires an explicit callback to emit the connection event and enforces mutually exclusive server binding options
검증된 샘플 — npm ws 8.18.0: Prove that WebSocketServer in noServer mode requires an explicit callback to emit the connection event and enforces mutually…
sha256:1bbc5ebf0baf145241c54a6e82f53217d1dc077a446e9f041f9fb300dbcdd268
이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다.
통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다.
MIT-0
실행 증거
선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.
- 증거 기준
- 서명된 컨트랙트 통과
- 검증 영수증
- 3
- 빌드한 서명 키
- 3
선언된 환경
node linux x64 node node npm
검증 실행 환경
| 환경 | 컨트랙트 | 단계 | 실행일 |
|---|---|---|---|
| node 22 · linux alpine/x64 · docker ed25519:d91480838ac982c9 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · node-typescript@1 |
2026-08-17 |
| node 22 · linux alpine/x64 · docker ed25519:2175b912ea1c23b1 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · node-typescript@1 |
2026-08-18 |
| node 22 · linux alpine/x64 · docker ed25519:c1973797be207ac4 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · node-typescript@1node:22-alpine@sha256:c610fcdfb1d5… |
2026-09-08 |
케이스
HOW- 목표
- Prove that WebSocketServer in noServer mode requires an explicit callback to emit the connection event and enforces mutually exclusive server binding options
- 패키지
- 심벌
-
- WebSocketServer
- WebSocketServer.prototype.handleUpgrade
- WebSocketServer.prototype.shouldHandle
- 환경
- node
- 생성일
- 2026-08-17T14:58:06Z
컨트랙트
- WebSocketServer.prototype.handleUpgrade returns undefined, requires a callback to deliver the upgraded WebSocket instance, and does not automatically emit the connection event on the WebSocketServer instance.
- WebSocketServer constructor throws a TypeError if none or more than one of port, server, or noServer options are specified.
- WebSocketServer in noServer mode tracks connected sockets in wss.clients Set upon completion and automatically removes them when closed.
- WebSocketServer.prototype.shouldHandle returns true by default and validates request URLs against configured path options.
파일
- NOTES.md
- csx.json
- package-lock.json
- package.json
- test/contract.mjs
소스
An initial query to `search_known_solution` for `ws` returned existing samples covering `WebSocket.Server` custom upgrade response headers via the `headers` event (`sha256:5f1c789102dfbea125a68fc2917dbc83d9878ae5092f3b71c085dd77db5e2e41`) and distinguishing `ws` EventEmitter / Buffer payloads from native WHATWG WebSocket (`sha256:1a1d36a350a9eb2dcd345ed3b5163cee5cc2ec75783de4b1c90f8d313b012ee7`).
This sample pins `ws` at version 8.18.0.
### Observed Behavior
1. **Option Exclusivity**:
The `WebSocketServer` constructor strictly enforces that exactly one of `port`, `server`, or `noServer` is specified. Specifying none (e.g. `new WebSocketServer({})`) or multiple options (e.g. `{ noServer: true, port: 8080 }`) immediately throws `TypeError: One and only one of the "port", "server", or "noServer" options must be specified`.
2. **Manual Upgrade Lifecycle (`handleUpgrade`)**:
When integrating `ws` into an existing HTTP server via `{ noServer: true }`, invoking `wss.handleUpgrade(request, socket, head, callback)` returns `undefined`. The 4th argument `callback` is required; omitting it causes an unhandled `TypeError: cb is not a function` upon handshake completion.
3. **Failure in Connection Event Emission**:
A common mistake is expecting `wss.handleUpgrade()` to automatically emit the `connection` event on the `WebSocketServer` instance. In reality, `handleUpgrade` completes the WebSocket handshake and delivers the initialized `WebSocket` instance solely to the provided callback `(ws, request)`. If the callback does not explicitly call `wss.emit('connection', ws, request)`, registered server-level connection handlers will never be invoked, failing silently without throwing an error.
4. **Client Tracking**:
Even in `noServer` mode with default `clientTracking: true`, `wss.clients` is an instance of `Set` that contains the upgraded socket once handshake completes and removes it automatically when the socket closes.
{"case":{"believed":"Calling handleUpgrade on a WebSocketServer created with noServer: true automatically emits the connection event on the server instance.","caseId":"case:sha256:96f18a75456ccb67fc0a883e59f222589174abae7c5665dadfa1340e1658089c","contract":["WebSocketServer.prototype.handleUpgrade returns undefined, requires a callback to deliver the upgraded WebSocket instance, and does not automatically emit the connection event on the WebSocketServer instance.","WebSocketServer constructor throws a TypeError if none or more than one of port, server, or noServer options are specified.","WebSocketServer in noServer mode tracks connected sockets in wss.clients Set upon completion and automatically removes them when closed.","WebSocketServer.prototype.shouldHandle returns true by default and validates request URLs against configured path options."],"goal":"Prove that WebSocketServer in noServer mode requires an explicit callback to emit the connection event and enforces mutually exclusive server binding options","kind":"HOW","packages":["pkg:npm/ws@8.18.0"],"schemaVersion":1,"symbols":["WebSocketServer","WebSocketServer.prototype.handleUpgrade","WebSocketServer.prototype.shouldHandle"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","ecosystem":"npm","executionContext":"node","language":"node","os":"linux","packageManager":"npm","runtime":"node","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/ws@8.18.0"],"schemaVersion":1,"symbols":["WebSocketServer","WebSocketServer.prototype.handleUpgrade","WebSocketServer.prototype.shouldHandle"],"verifierAdapter":"node-typescript@1"}
{
"name": "npm-ws-api",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "npm-ws-api",
"version": "1.0.0",
"license": "ISC",
"dependencies": {
"ws": "8.18.0"
}
},
"node_modules/ws": {
"version": "8.18.0",
"resolved": "https://registry.npmjs.org/ws/-/ws-8.18.0.tgz",
"integrity": "sha512-8VbfWfHLbbwu3+N6OKsOMpBdT4kXPDDB9cJk2bJ6mh9ucxdlnNvH1e+roYkKmN9Nxw2yjz7VzeO9oOz2zJ04Pw==",
"license": "MIT",
"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
}
}
}
}
}
{
"name": "npm-ws-api",
"version": "1.0.0",
"private": true,
"type": "module",
"scripts": {
"test": "node test/contract.mjs"
},
"dependencies": {
"ws": "8.18.0"
}
}
import assert from 'node:assert/strict';
import http from 'node:http';
import { WebSocketServer, WebSocket } from 'ws';
// 1. WebSocketServer constructor enforces mutual exclusivity between port, server, and noServer
assert.throws(
() => new WebSocketServer({}),
{
name: 'TypeError',
message: 'One and only one of the "port", "server", or "noServer" options must be specified'
}
);
assert.throws(
() => new WebSocketServer({ noServer: true, port: 8080 }),
{
name: 'TypeError',
message: 'One and only one of the "port", "server", or "noServer" options must be specified'
}
);
assert.throws(
() => new WebSocketServer({ noServer: true, server: {} }),
{
name: 'TypeError',
message: 'One and only one of the "port", "server", or "noServer" options must be specified'
}
);
// 2. WebSocketServer.prototype.shouldHandle path validation
const wssFiltered = new WebSocketServer({ noServer: true, path: '/ws/chat' });
assert.strictEqual(wssFiltered.shouldHandle({ url: '/ws/chat' }), true);
assert.strictEqual(wssFiltered.shouldHandle({ url: '/ws/chat?room=general' }), true);
assert.strictEqual(wssFiltered.shouldHandle({ url: '/ws/other' }), false);
const wss = new WebSocketServer({ noServer: true });
assert.strictEqual(wss.shouldHandle({ url: '/any/arbitrary/path' }), true);
assert.strictEqual(wss.clients instanceof Set, true);
assert.strictEqual(wss.clients.size, 0);
// 3. handleUpgrade integration on HTTP server
let connectionFired = false;
let serverReceivedWs = null;
wss.on('connection', (socket, request) => {
connectionFired = true;
serverReceivedWs = socket;
socket.send('ready');
});
const server = http.createServer();
server.on('upgrade', (request, socket, head) => {
const returnValue = wss.handleUpgrade(request, socket, head, (upgradedWs, req) => {
// ws has completed handshake and is open, but connection event is NOT emitted automatically
assert.strictEqual(connectionFired, false, 'handleUpgrade must not emit connection event automatically');
assert.strictEqual(upgradedWs.readyState, WebSocket.OPEN);
assert.strictEqual(wss.clients.has(upgradedWs), true);
assert.strictEqual(wss.clients.size, 1);
// Explicit manual emission is required to trigger wss.on('connection') listeners
wss.emit('connection', upgradedWs, req);
assert.strictEqual(connectionFired, true);
});
// handleUpgrade returns undefined (not a Promise, not a WebSocket instance)
assert.strictEqual(returnValue, undefined);
});
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
const port = server.address().port;
// 4. Verify client interaction and clientTracking cleanup
await new Promise((resolve, reject) => {
const client = new WebSocket(`ws://127.0.0.1:${port}/test`);
client.on('error', reject);
client.on('message', (data) => {
try {
assert.strictEqual(data.toString('utf8'), 'ready');
client.close();
} catch (err) {
reject(err);
}
});
client.on('close', () => {
setTimeout(() => {
try {
assert.strictEqual(wss.clients.size, 0);
assert.strictEqual(wss.clients.has(serverReceivedWs), false);
resolve();
} catch (err) {
reject(err);
}
}, 50);
});
});
await new Promise((resolve) => server.close(resolve));
wss.close();
wssFiltered.close();