CodeSampleX

Sample

ws 8.21.1: WebSocketServer.handleUpgrade

Verified sample for npm ws 8.21.1: WebSocketServer.handleUpgrade. The contract ran on node 22 · linux alpine/x64 · docker and passed.

sha256:7555d3a4217171289f8d31492334c2dc52ff00e60e4f40ad759b3c8b19902db5

This network offers one thing: a sample that builds. It ran the sample in a sandbox and kept the signed receipt. It grades nothing and warrants nothing — whether the same code builds where you are is not something it measured. How many distinct signing keys filed a passing contract receipt. One is the author alone; more than one means somebody else built it too. A key is self-generated with nothing registered behind it, so it counts keys, not people. MIT-0

Execution evidence

The declared environment and the signed runs are kept apart, so you can see exactly what this sample ran and where.

Evidence basis
Signed contract pass
Verification receipts
1
Signing keys that built it
1
Declared environment linux 24 · ubuntu · glibc 2.39 x64 npm

Verification-run environments

Environment Contract Stages Run
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-08-30

Case

HOW
Goal
verify WebSocketServer.handleUpgrade in pkg:npm/ws@8.21.1
Packages
Symbols
  • WebSocketServer.handleUpgrade
Created
2026-08-30T22:30:46Z

Contract

  1. WebSocketServer initialized with noServer: true throws when calling address()
  2. WebSocketServer.handleUpgrade completes HTTP upgrade handshake over duplex socket
  3. WebSocket client successfully sends and receives messages after handleUpgrade connection
  4. handleUpgrade callback receives the upgraded WebSocket instance and request object

Files

  • PROMPT.md
  • csx.json
  • index.mjs
  • package-lock.json
  • package.json
  • spec.json
  • test/contract.mjs

Download the source artifact (tar.gz)

Source

PROMPT.md
Clean-room public code sample — generation instructions

Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.

A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.

Goal: verify WebSocketServer.handleUpgrade in pkg:npm/ws@8.21.1
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/ws@8.21.1
Demonstrate these symbols/APIs:
  - WebSocketServer.handleUpgrade

Rules:
  - One focused purpose; the smallest project that proves the goal.
  - Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
  - Pin every dependency with a lockfile so resolution is reproducible.
  - No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
  - No personal names, emails, company names, or project identifiers of any kind.
  - No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
  - Keep it under 200 files and 256KB packed.
csx.json
{"case":{"caseId":"case:sha256:4904ae573f9c73db5e7ede6d0b704c1c0b3dcd1f23e52d55e4ccd3e1153f8dce","contract":["WebSocketServer initialized with noServer: true throws when calling address()","WebSocketServer.handleUpgrade completes HTTP upgrade handshake over duplex socket","WebSocket client successfully sends and receives messages after handleUpgrade connection","handleUpgrade callback receives the upgraded WebSocket instance and request object"],"goal":"verify WebSocketServer.handleUpgrade in pkg:npm/ws@8.21.1","kind":"HOW","packages":["pkg:npm/ws@8.21.1"],"schemaVersion":1,"symbols":["WebSocketServer.handleUpgrade"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"npm","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/ws@8.21.1"],"schemaVersion":1,"subject":"pkg:npm/ws@8.21.1","symbols":["WebSocketServer.handleUpgrade"],"verifierAdapter":"node-typescript@1"}
index.mjs
import http from 'node:http';
import { WebSocketServer, WebSocket } from 'ws';

/**
 * Creates an HTTP server and pairs it with a WebSocketServer using handleUpgrade.
 * @param {Object} [options]
 * @param {string} [options.wsPath='/ws'] - Path for WebSocket upgrade requests
 * @returns {{ server: http.Server, wss: WebSocketServer, close: () => Promise<void> }}
 */
export function createUpgradableServer(options = {}) {
  const wsPath = options.wsPath || '/ws';
  const wss = new WebSocketServer({ noServer: true });

  const server = http.createServer((req, res) => {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('OK');
  });

  server.on('upgrade', (request, socket, head) => {
    const url = new URL(request.url, 'http://localhost');
    if (url.pathname === wsPath) {
      wss.handleUpgrade(request, socket, head, (ws) => {
        wss.emit('connection', ws, request);
      });
    } else {
      socket.destroy();
    }
  });

  const close = () => {
    return new Promise((resolve) => {
      wss.close(() => {
        server.close(() => {
          resolve();
        });
      });
    });
  };

  return { server, wss, close };
}

export { WebSocketServer, WebSocket };
package-lock.json
{
  "name": "sample-ws-handle-upgrade",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-ws-handle-upgrade",
      "version": "1.0.0",
      "dependencies": {
        "ws": "8.21.1"
      }
    },
    "node_modules/ws": {
      "version": "8.21.1",
      "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.1.tgz",
      "integrity": "sha512-+0NTnW77fFN/DjQi6k/Sq/Yvk4Sgajw7urW8V+asjXnRgDs9gyGkdb7EzgfhA4goXsRIZKE28fzIXBHEzhuiWw==",
      "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
        }
      }
    }
  }
}
package.json
{
  "name": "sample-ws-handle-upgrade",
  "version": "1.0.0",
  "type": "module",
  "private": true,
  "dependencies": {
    "ws": "8.21.1"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify WebSocketServer.handleUpgrade in pkg:npm/ws@8.21.1",
  "kind": "HOW",
  "packages": [
    "pkg:npm/ws@8.21.1"
  ],
  "symbols": [
    "WebSocketServer.handleUpgrade"
  ]
}
test/contract.mjs
import assert from 'node:assert/strict';
import { createUpgradableServer, WebSocketServer, WebSocket } from '../index.mjs';

async function runContractTests() {
  // Test 1: WebSocketServer initialized with noServer: true throws when address() is called
  const standaloneWss = new WebSocketServer({ noServer: true });
  assert.equal(standaloneWss.options.noServer, true, 'noServer option should be true');
  assert.throws(
    () => standaloneWss.address(),
    /The server is operating in "noServer" mode/,
    'address() should throw in noServer mode'
  );
  standaloneWss.close();

  // Test 2: Set up upgradable server and verify handleUpgrade completes upgrade handshake
  const { server, wss, close } = createUpgradableServer({ wsPath: '/custom-ws' });

  await new Promise((resolve, reject) => {
    server.listen(0, '127.0.0.1', () => resolve());
    server.on('error', reject);
  });

  const address = server.address();
  const port = address.port;

  let connectionHandled = false;
  let receivedServerRequest = null;
  let serverWsInstance = null;

  wss.on('connection', (ws, req) => {
    connectionHandled = true;
    serverWsInstance = ws;
    receivedServerRequest = req;

    ws.on('message', (data) => {
      const msg = data.toString();
      if (msg === 'ping') {
        ws.send('pong');
      }
    });
  });

  // Test 3: Client connects and sends/receives messages
  const clientWs = new WebSocket(`ws://127.0.0.1:${port}/custom-ws`);

  await new Promise((resolve, reject) => {
    clientWs.on('open', resolve);
    clientWs.on('error', reject);
  });

  assert.equal(connectionHandled, true, 'wss should have emitted connection event via handleUpgrade');
  assert.ok(serverWsInstance instanceof WebSocket, 'server WebSocket should be an instance of WebSocket');
  assert.ok(receivedServerRequest, 'server should receive the upgraded HTTP request object');
  assert.equal(receivedServerRequest.url, '/custom-ws', 'request URL should match upgrade path');

  const responsePromise = new Promise((resolve) => {
    clientWs.on('message', (data) => {
      resolve(data.toString());
    });
  });

  clientWs.send('ping');
  const response = await responsePromise;
  assert.equal(response, 'pong', 'Client should receive pong message from server');

  clientWs.close();
  await new Promise((resolve) => clientWs.on('close', resolve));

  // Test 4: Verify non-matching path is rejected / destroyed
  const invalidClient = new WebSocket(`ws://127.0.0.1:${port}/other-path`);
  const rejected = await new Promise((resolve) => {
    invalidClient.on('error', () => resolve(true));
    invalidClient.on('close', () => resolve(true));
    invalidClient.on('open', () => resolve(false));
  });
  assert.equal(rejected, true, 'Connection to non-matching route should be closed');

  await close();
  console.log('All contract assertions passed.');
}

runContractTests().catch((err) => {
  console.error('Contract test failed:', err);
  process.exit(1);
});

Origin Seeder

anonymous