CodeSampleX

示例

socks 2.8.10: SocksClient.createConnectionChain

已验证示例 — npm socks 2.8.10: SocksClient.createConnectionChain. contract 在 node 22 · linux debian/x64 · docker 上运行并通过: SocksClient exports static…

sha256:b7979b46943dc467c956b84d1e400825ff044f480e920b4f29d121704c893f5b

本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。 提交了通过的契约回执的不同签名密钥数量。为 1 表示只有作者;大于 1 表示还有其他人构建过。密钥是自行生成的,背后没有注册身份,因此计的是密钥而非人。 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);
});

原始种子者

匿名