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

このネットワークが提供するのは一つだけです。ビルドされるサンプル。サンドボックスで実行し、署名済みの受領証を保管します。等級はつけず、何も保証しません — 同じコードがあなたの環境でビルドされるかは測定していません。 合格した契約受領証を提出した異なる署名鍵の数です。1 なら作者だけ、2 以上なら他の誰かもビルドしています。鍵は自己生成で背後に登録された身元がないため、数えているのは人ではなく鍵です。 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);
});

オリジンシーダー

匿名