CodeSampleX

샘플

socks 2.8.10: SocksClient.createConnectionChain

검증된 샘플 — npm socks 2.8.10: SocksClient.createConnectionChain. node 22 · linux debian/x64 · docker에서 contract를 실행해 통과했습니다: SocksClient.createConnectionChain…

sha256:5adcdfc45bd06d6c7afaf944734be550b1791aa4d57a08ca7c1036aa18065ccb

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. MIT-0

실행 증거

선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.

증거 기준
서명된 컨트랙트 통과
검증 영수증
1
빌드한 서명 키
1
선언된 환경 linux 24 · ubuntu · glibc 2.39 x64 npm

검증 실행 환경

환경 컨트랙트 단계 실행일
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 SocksClient.createConnectionChain in pkg:npm/socks@2.8.10
패키지
심벌
  • SocksClient.createConnectionChain
생성일
2026-09-07T01:01:03Z

컨트랙트

  1. SocksClient.createConnectionChain establishes a connection through chained SOCKS5 proxies
  2. SocksClient.createConnectionChain supports callback interface
  3. SocksClient.createConnectionChain rejects configuration with fewer than two proxies

파일

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

소스 아티팩트 내려받기 (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 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:
  - 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:b579b569f6a11f93ac2389c66eb8ab2e529db67f865c54ff86f9ab5d79bc9cc5","contract":["SocksClient.createConnectionChain establishes a connection through chained SOCKS5 proxies","SocksClient.createConnectionChain supports callback interface","SocksClient.createConnectionChain rejects configuration with fewer than two proxies"],"goal":"verify SocksClient.createConnectionChain in pkg:npm/socks@2.8.10","kind":"HOW","packages":["pkg:npm/socks@2.8.10"],"schemaVersion":1,"symbols":["SocksClient.createConnectionChain"]},"contractCommand":["node","test/contract.cjs"],"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/socks@2.8.10"],"schemaVersion":1,"subject":"pkg:npm/socks@2.8.10","symbols":["SocksClient.createConnectionChain"],"verifierAdapter":"node-typescript@1"}
index.js
'use strict';

const { SocksClient, SocksClientError } = require('socks');

/**
 * Creates a chained SOCKS connection through multiple proxies.
 * @param {import('socks').SocksClientChainOptions} options
 * @param {Function} [callback]
 * @returns {Promise<import('socks').SocksClientEstablishedEvent>}
 */
function createProxyChainConnection(options, callback) {
  return SocksClient.createConnectionChain(options, callback);
}

module.exports = {
  SocksClient,
  SocksClientError,
  createProxyChainConnection
};
package-lock.json
{
  "name": "sample-socks-chain",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-socks-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-chain",
  "version": "1.0.0",
  "private": true,
  "description": "verify SocksClient.createConnectionChain in pkg:npm/socks@2.8.10",
  "main": "index.js",
  "scripts": {
    "test": "node test/contract.cjs"
  },
  "dependencies": {
    "socks": "2.8.10"
  },
  "license": "MIT-0"
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify SocksClient.createConnectionChain in pkg:npm/socks@2.8.10",
  "kind": "HOW",
  "packages": [
    "pkg:npm/socks@2.8.10"
  ],
  "symbols": [
    "SocksClient.createConnectionChain"
  ]
}
test/contract.cjs
'use strict';

const assert = require('assert');
const net = require('net');
const {
  SocksClient,
  SocksClientError,
  createProxyChainConnection
} = require('../index.js');

function createMockSocksServer(name) {
  const server = net.createServer((clientSocket) => {
    let state = 'AUTH';
    let forwardSocket = null;

    clientSocket.on('data', (chunk) => {
      if (forwardSocket) {
        forwardSocket.write(chunk);
        return;
      }

      if (state === 'AUTH') {
        assert.strictEqual(chunk[0], 0x05, `${name}: SOCKS version 5 expected`);
        clientSocket.write(Buffer.from([0x05, 0x00]));
        state = 'REQUEST';
      } else if (state === 'REQUEST') {
        assert.strictEqual(chunk[0], 0x05, `${name}: SOCKS version 5 expected`);
        assert.strictEqual(chunk[1], 0x01, `${name}: CONNECT command expected`);

        const atyp = chunk[3];
        let targetHost;
        let targetPort;
        let offset = 4;

        if (atyp === 0x01) {
          targetHost = `${chunk[offset]}.${chunk[offset + 1]}.${chunk[offset + 2]}.${chunk[offset + 3]}`;
          offset += 4;
          targetPort = chunk.readUInt16BE(offset);
          offset += 2;
        } else if (atyp === 0x03) {
          const len = chunk[offset++];
          targetHost = chunk.slice(offset, offset + len).toString('utf8');
          offset += len;
          targetPort = chunk.readUInt16BE(offset);
          offset += 2;
        } else {
          throw new Error('Unsupported ATYP: ' + atyp);
        }

        forwardSocket = net.connect(targetPort, targetHost, () => {
          clientSocket.write(Buffer.from([0x05, 0x00, 0x00, 0x01, 127, 0, 0, 1, 0x00, 0x00]));
        });

        forwardSocket.on('data', (data) => {
          clientSocket.write(data);
        });
        forwardSocket.on('error', () => {
          clientSocket.destroy();
        });
        clientSocket.on('close', () => {
          if (forwardSocket) forwardSocket.destroy();
        });
        forwardSocket.on('close', () => {
          clientSocket.destroy();
        });

        if (offset < chunk.length) {
          forwardSocket.write(chunk.slice(offset));
        }
      }
    });
  });

  return server;
}

async function run() {
  const targetServer = net.createServer((socket) => {
    socket.on('data', (data) => {
      socket.write(Buffer.concat([Buffer.from('ECHO:'), data]));
    });
  });
  await new Promise((resolve) => targetServer.listen(0, '127.0.0.1', resolve));
  const targetPort = targetServer.address().port;

  const proxy2 = createMockSocksServer('proxy2');
  await new Promise((resolve) => proxy2.listen(0, '127.0.0.1', resolve));
  const proxy2Port = proxy2.address().port;

  const proxy1 = createMockSocksServer('proxy1');
  await new Promise((resolve) => proxy1.listen(0, '127.0.0.1', resolve));
  const proxy1Port = proxy1.address().port;

  try {
    const chainOptions = {
      command: 'connect',
      proxies: [
        { host: '127.0.0.1', port: proxy1Port, type: 5 },
        { host: '127.0.0.1', port: proxy2Port, type: 5 }
      ],
      destination: {
        host: '127.0.0.1',
        port: targetPort
      }
    };

    // 1. SocksClient.createConnectionChain establishes a connection through chained SOCKS5 proxies
    const info = await createProxyChainConnection(chainOptions);
    assert(info && info.socket, 'createConnectionChain must return established socket');
    assert(info.socket instanceof net.Socket, 'info.socket must be a net.Socket');

    const echoResponse = await new Promise((resolve, reject) => {
      info.socket.once('data', (d) => resolve(d.toString('utf8')));
      info.socket.once('error', reject);
      info.socket.write('chain-payload');
    });
    assert.strictEqual(echoResponse, 'ECHO:chain-payload', 'Destination should echo back sent data');
    info.socket.destroy();

    // 2. SocksClient.createConnectionChain supports callback interface
    const callbackInfo = await new Promise((resolve, reject) => {
      createProxyChainConnection(chainOptions, (err, res) => {
        if (err) return reject(err);
        resolve(res);
      });
    });
    assert(callbackInfo && callbackInfo.socket, 'Callback interface must return established socket');
    callbackInfo.socket.destroy();

    // 3. SocksClient.createConnectionChain rejects configuration with fewer than two proxies
    let caught = null;
    try {
      await createProxyChainConnection({
        command: 'connect',
        proxies: [
          { host: '127.0.0.1', port: proxy1Port, type: 5 }
        ],
        destination: {
          host: '127.0.0.1',
          port: targetPort
        }
      });
    } catch (err) {
      caught = err;
    }
    assert(caught instanceof SocksClientError, 'Must throw SocksClientError for invalid proxy count');
    assert.strictEqual(caught.message, 'At least two socks proxies must be provided for chaining.');

    console.log('Contract assertions passed.');
    process.exit(0);
  } finally {
    targetServer.close();
    proxy1.close();
    proxy2.close();
  }
}

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

오리진 시더

익명