CodeSampleX

Пример

socks 2.8.10: SocksClient.createConnectionChain

Проверенный пример — npm socks 2.8.10: SocksClient.createConnectionChain. Контракт выполнен на node 22 · linux debian/x64 · docker и пройден.

sha256:b7979b46943dc467c956b84d1e400825ff044f480e920b4f29d121704c893f5b

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. MIT-0

Свидетельства выполнения

Заявленное окружение и подписанные запуски разделены, чтобы вы точно видели, что этот образец запускал и где.

Основа свидетельства
Подписанный контракт пройден
Квитанции проверки
1
Ключи подписи, собравшие его
1
Заявленная среда node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

Среды запусков проверки

Окружение Контракт Этапы Запуск
node 22 · linux debian/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1node:22@sha256:8a34c4ab3ea2…
2026-09-07

Кейс

HOW
Цель
verify socks.SocksClient.createConnectionChain in pkg:npm/socks@2.8.10
Пакеты
Символы
  • socks.SocksClient.createConnectionChain
Окружение
node 22.23.2
Создан
2026-09-07T01:12:56Z

Контракт

  1. SocksClient exports static createConnectionChain method
  2. createConnectionChain validates command and rejects invalid commands
  3. createConnectionChain requires at least two proxies in the chain
  4. createConnectionChain validates destination and proxy host parameters
  5. createConnectionChain supports callback error propagation
  6. createConnectionChain establishes multi-proxy tunnel over SOCKS5 chain using promises
  7. createConnectionChain establishes multi-proxy tunnel over SOCKS5 chain using callbacks

Файлы

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

Скачать артефакт с исходным кодом (tar.gz)

Исходный код

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 socks.SocksClient.createConnectionChain in pkg:npm/socks@2.8.10
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/socks@2.8.10
Demonstrate these symbols/APIs:
  - socks.SocksClient.createConnectionChain

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:8645fbac3a12ad0ab7ba0770efa566950c9d313a483207363ea5c1e640535635","contract":["SocksClient exports static createConnectionChain method","createConnectionChain validates command and rejects invalid commands","createConnectionChain requires at least two proxies in the chain","createConnectionChain validates destination and proxy host parameters","createConnectionChain supports callback error propagation","createConnectionChain establishes multi-proxy tunnel over SOCKS5 chain using promises","createConnectionChain establishes multi-proxy tunnel over SOCKS5 chain using callbacks"],"goal":"verify socks.SocksClient.createConnectionChain in pkg:npm/socks@2.8.10","kind":"HOW","packages":["pkg:npm/socks@2.8.10"],"schemaVersion":1,"symbols":["socks.SocksClient.createConnectionChain"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","executionContext":"node","language":"javascript","libc":"glibc","libcVersion":"2.39","moduleSystem":"cjs","os":"linux","osVersionBucket":"24","packageManager":"npm","packageManagerVersion":"10.9.8","runtime":"node","runtimeVersion":"22.23.2","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/socks@2.8.10"],"schemaVersion":1,"subject":"pkg:npm/socks@2.8.10","symbols":["socks.SocksClient.createConnectionChain"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-socks-create-connection-chain",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-socks-create-connection-chain",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "socks": "2.8.10"
      }
    },
    "node_modules/ip-address": {
      "version": "10.7.0",
      "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.7.0.tgz",
      "integrity": "sha512-BGFsyJd5mpXp3rK6jIdADLNgpJUK1jnjzvYF8lK+VyDab9JAmqN0YOKDdP17HlgKb2+ehPgDc8EtnRLbGCAMhA==",
      "license": "MIT",
      "engines": {
        "node": ">= 12"
      }
    },
    "node_modules/smart-buffer": {
      "version": "4.2.0",
      "resolved": "https://registry.npmjs.org/smart-buffer/-/smart-buffer-4.2.0.tgz",
      "integrity": "sha512-94hK0Hh8rPqQl2xXc3HsaBoOXKV20MToPkcXvwbISWLEs+64sBq5kFgn2kJDHb1Pry9yrP0dxrCI9RRci7RXKg==",
      "license": "MIT",
      "engines": {
        "node": ">= 6.0.0",
        "npm": ">= 3.0.0"
      }
    },
    "node_modules/socks": {
      "version": "2.8.10",
      "resolved": "https://registry.npmjs.org/socks/-/socks-2.8.10.tgz",
      "integrity": "sha512-e0VyvkVTwVYViNovRkZ9aodhxVlyoMn7eJhVUPxZ+eK9P/7CBkxvvsBOHqFPEH416726W8tLXXXjKwqgTErrCQ==",
      "license": "MIT",
      "dependencies": {
        "ip-address": "^10.1.1",
        "smart-buffer": "^4.2.0"
      },
      "engines": {
        "node": ">= 10.0.0",
        "npm": ">= 3.0.0"
      }
    }
  }
}
package.json
{
  "name": "sample-socks-create-connection-chain",
  "version": "1.0.0",
  "private": true,
  "description": "Clean-room code sample for socks.SocksClient.createConnectionChain",
  "main": "src/index.js",
  "license": "MIT-0",
  "dependencies": {
    "socks": "2.8.10"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify socks.SocksClient.createConnectionChain in pkg:npm/socks@2.8.10",
  "kind": "HOW",
  "packages": [
    "pkg:npm/socks@2.8.10"
  ],
  "symbols": [
    "socks.SocksClient.createConnectionChain"
  ]
}
src/index.js
const { SocksClient } = require('socks');

/**
 * Creates a SOCKS connection chain to a destination host through multiple SOCKS proxies.
 *
 * @param {import('socks').SocksClientChainOptions} options - Options describing proxy chain and destination
 * @param {(err: Error | null, info?: import('socks').SocksClientEstablishedEvent) => void} [callback] - Optional callback
 * @returns {Promise<import('socks').SocksClientEstablishedEvent>}
 */
function createConnectionChain(options, callback) {
  return SocksClient.createConnectionChain(options, callback);
}

/**
 * Helper to build options for creating a SOCKS connection chain.
 *
 * @param {Array<{ host: string, port: number, type: 4 | 5 }>} proxies - Ordered array of proxies
 * @param {{ host: string, port: number }} destination - Final destination host and port
 * @param {object} [extraOptions] - Additional options like timeout or randomizeChain
 * @returns {import('socks').SocksClientChainOptions}
 */
function buildChainOptions(proxies, destination, extraOptions = {}) {
  return {
    command: 'connect',
    proxies,
    destination,
    ...extraOptions
  };
}

module.exports = {
  SocksClient,
  createConnectionChain,
  buildChainOptions
};
test/contract.mjs
import assert from 'node:assert/strict';
import net from 'node:net';
import { createRequire } from 'node:module';

const require = createRequire(import.meta.url);
const {
  SocksClient,
  createConnectionChain,
  buildChainOptions
} = require('../src/index.js');

function startEchoServer() {
  return new Promise((resolve, reject) => {
    const sockets = new Set();
    const server = net.createServer((socket) => {
      sockets.add(socket);
      socket.on('data', (data) => {
        socket.write(`echo:${data.toString()}`);
      });
      socket.on('close', () => sockets.delete(socket));
      socket.on('error', () => {});
    });

    server.listen(0, '127.0.0.1', () => {
      const port = server.address().port;
      resolve({
        port,
        close: () => new Promise((res) => {
          for (const s of sockets) s.destroy();
          server.close(res);
        })
      });
    });
    server.on('error', reject);
  });
}

function startMockSocks5Server() {
  return new Promise((resolve, reject) => {
    const sockets = new Set();
    const server = net.createServer((clientSocket) => {
      sockets.add(clientSocket);
      let state = 0; // 0: auth handshake, 1: connect request, 2: tunnel
      let buffer = Buffer.alloc(0);

      clientSocket.on('data', (chunk) => {
        if (state === 2) return;
        buffer = Buffer.concat([buffer, chunk]);

        if (state === 0 && buffer.length >= 2) {
          const nmethods = buffer[1];
          if (buffer.length >= 2 + nmethods) {
            buffer = buffer.subarray(2 + nmethods);
            state = 1;
            clientSocket.write(Buffer.from([0x05, 0x00]));
          }
        }

        if (state === 1 && buffer.length >= 4) {
          const atyp = buffer[3];
          let targetHost;
          let targetPort;
          let reqLen = 0;

          if (atyp === 0x01 && buffer.length >= 10) {
            targetHost = `${buffer[4]}.${buffer[5]}.${buffer[6]}.${buffer[7]}`;
            targetPort = buffer.readUInt16BE(8);
            reqLen = 10;
          } else if (atyp === 0x03) {
            const hostLen = buffer[4];
            if (buffer.length >= 5 + hostLen + 2) {
              targetHost = buffer.subarray(5, 5 + hostLen).toString();
              targetPort = buffer.readUInt16BE(5 + hostLen);
              reqLen = 5 + hostLen + 2;
            }
          }

          if (reqLen > 0) {
            buffer = buffer.subarray(reqLen);
            state = 2;
            const upstream = net.connect(targetPort, targetHost, () => {
              clientSocket.write(Buffer.from([0x05, 0x00, 0x00, 0x01, 0x7f, 0x00, 0x00, 0x01, 0x00, 0x00]));
              if (buffer.length > 0) {
                upstream.write(buffer);
                buffer = Buffer.alloc(0);
              }
              clientSocket.pipe(upstream);
              upstream.pipe(clientSocket);
            });
            sockets.add(upstream);
            upstream.on('close', () => sockets.delete(upstream));
            upstream.on('error', () => clientSocket.destroy());
          }
        }
      });

      clientSocket.on('close', () => sockets.delete(clientSocket));
      clientSocket.on('error', () => {});
    });

    server.listen(0, '127.0.0.1', () => {
      const port = server.address().port;
      resolve({
        port,
        close: () => new Promise((res) => {
          for (const s of sockets) s.destroy();
          server.close(res);
        })
      });
    });
    server.on('error', reject);
  });
}

async function testContract() {
  // 1. SocksClient exports static createConnectionChain method
  assert.equal(typeof SocksClient.createConnectionChain, 'function', 'SocksClient.createConnectionChain should be a function');
  assert.equal(typeof createConnectionChain, 'function', 'createConnectionChain helper should be a function');
  assert.equal(typeof buildChainOptions, 'function', 'buildChainOptions helper should be a function');

  // 2. createConnectionChain validates command and rejects invalid commands
  await assert.rejects(
    async () => {
      await SocksClient.createConnectionChain({
        command: 'bind',
        destination: { host: '127.0.0.1', port: 8080 },
        proxies: [
          { host: '127.0.0.1', port: 1080, type: 5 },
          { host: '127.0.0.1', port: 1081, type: 5 }
        ]
      });
    },
    {
      message: /Chaining currently only supports the connect command/
    },
    'should reject non-connect command'
  );

  // 3. createConnectionChain requires at least two proxies in the chain
  await assert.rejects(
    async () => {
      await SocksClient.createConnectionChain({
        command: 'connect',
        destination: { host: '127.0.0.1', port: 8080 },
        proxies: [
          { host: '127.0.0.1', port: 1080, type: 5 }
        ]
      });
    },
    {
      message: /At least two socks proxies must be provided/
    },
    'should reject when fewer than 2 proxies are supplied'
  );

  // 4. createConnectionChain validates destination and proxy host parameters
  await assert.rejects(
    async () => {
      await SocksClient.createConnectionChain({
        command: 'connect',
        destination: { host: '', port: -1 },
        proxies: [
          { host: '127.0.0.1', port: 1080, type: 5 },
          { host: '127.0.0.1', port: 1081, type: 5 }
        ]
      });
    },
    {
      message: /An invalid destination host was provided/
    },
    'should reject invalid destination'
  );

  await assert.rejects(
    async () => {
      await SocksClient.createConnectionChain({
        command: 'connect',
        destination: { host: '127.0.0.1', port: 8080 },
        proxies: [
          { host: '127.0.0.1', port: 1080, type: 5 },
          { host: '127.0.0.1', port: 999999, type: 5 }
        ]
      });
    },
    {
      message: /Invalid SOCKS proxy details were provided/
    },
    'should reject invalid proxy port'
  );

  // 5. createConnectionChain supports callback error propagation
  await new Promise((resolve, reject) => {
    SocksClient.createConnectionChain(
      {
        command: 'invalid',
        destination: { host: '127.0.0.1', port: 8080 },
        proxies: [
          { host: '127.0.0.1', port: 1080, type: 5 },
          { host: '127.0.0.1', port: 1081, type: 5 }
        ]
      },
      (err) => {
        try {
          assert.ok(err, 'callback should receive validation error');
          assert.match(err.message, /Chaining currently only supports the connect command/);
          resolve();
        } catch (assertionErr) {
          reject(assertionErr);
        }
      }
    );
  });

  // Start offline mock servers: Echo target + 2 SOCKS5 proxies
  const echoServer = await startEchoServer();
  const proxy2 = await startMockSocks5Server();
  const proxy1 = await startMockSocks5Server();

  try {
    // 6. createConnectionChain establishes multi-proxy tunnel over SOCKS5 chain using promises
    const chainOptions = buildChainOptions(
      [
        { host: '127.0.0.1', port: proxy1.port, type: 5 },
        { host: '127.0.0.1', port: proxy2.port, type: 5 }
      ],
      { host: '127.0.0.1', port: echoServer.port }
    );

    const established = await createConnectionChain(chainOptions);
    assert.ok(established, 'established event object should be returned');
    assert.ok(established.socket instanceof net.Socket, 'established.socket should be an instance of net.Socket');

    // Verify end-to-end communication through the proxy chain
    const echoResponse = await new Promise((resolve, reject) => {
      established.socket.once('data', (data) => resolve(data.toString()));
      established.socket.once('error', reject);
      established.socket.write('ping-promise');
    });
    assert.equal(echoResponse, 'echo:ping-promise', 'response from echo server over 2-hop proxy chain must match');
    established.socket.destroy();

    // 7. createConnectionChain establishes multi-proxy tunnel over SOCKS5 chain using callbacks
    const callbackResult = await new Promise((resolve, reject) => {
      createConnectionChain(chainOptions, (err, info) => {
        if (err) return reject(err);
        resolve(info);
      });
    });

    assert.ok(callbackResult, 'callback should receive info object');
    assert.ok(callbackResult.socket instanceof net.Socket, 'callback socket should be net.Socket instance');

    const callbackEcho = await new Promise((resolve, reject) => {
      callbackResult.socket.once('data', (data) => resolve(data.toString()));
      callbackResult.socket.once('error', reject);
      callbackResult.socket.write('ping-callback');
    });
    assert.equal(callbackEcho, 'echo:ping-callback', 'callback-established connection should communicate through chain');
    callbackResult.socket.destroy();

  } finally {
    await proxy1.close();
    await proxy2.close();
    await echoServer.close();
  }

  console.log('All socks.SocksClient.createConnectionChain contract assertions passed successfully.');
}

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

Исходный сидер

аноним