CodeSampleX

Exemplo

http-proxy-agent 5.0.0

Amostra verificada para npm http-proxy-agent 5.0.0. O contrato rodou em node 22 · linux alpine/x64 · docker e passou: createHttpProxyAgent is exported as the…

sha256:a7f3c9a5984833def91459efcaa01cdf18f7d04efac3e85a7cb81739db57a545

Esta rede oferece uma coisa: uma amostra que compila. Ela a executou em um sandbox e guardou o recibo assinado. Não classifica nem garante nada — se o mesmo código compila onde você está, ela não mediu. Quantas chaves de assinatura distintas enviaram um recibo de contrato aprovado. Uma é só o autor; mais de uma significa que outra pessoa também o compilou. Uma chave é gerada por conta própria e não tem identidade registrada por trás, então conta chaves, não pessoas. MIT-0

Evidência de execução

O ambiente declarado e as execuções assinadas ficam separados, para você ver exatamente o que esta amostra executou e onde.

Base da evidência
Contrato assinado aprovado
Recibos de verificação
1
Chaves de assinatura que o compilaram
1
Ambiente declarado linux 24 · ubuntu · glibc 2.39 x64 npm

Ambientes das execuções de verificação

Ambiente Contrato Etapas Execução
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-23

Caso

HOW
Objetivo
verify pkg:npm/http-proxy-agent@5.0.0
Pacotes
Criado
2026-08-23T14:08:37Z

Contrato

  1. createHttpProxyAgent is exported as the default function and provides HttpProxyAgent constructor property
  2. createHttpProxyAgent parses proxy URL string and configures proxy host, port, protocol, and secureProxy flag
  3. HttpProxyAgent constructor accepts proxy options object with host, port, and protocol
  4. HttpProxyAgent defaults proxy port to 80 for HTTP protocol and 443 for HTTPS protocol
  5. HttpProxyAgent removes path and pathname from proxy options to avoid Unix domain socket conflicts
  6. getAgentConfig normalizes agent proxy options and secureProxy flag
  7. callback transforms request path into absolute URL format and injects Basic Proxy-Authorization header
  8. HttpProxyAgent establishes network socket connection and tunnels HTTP requests through the proxy server

Arquivos

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

Baixar o artefato de código-fonte (tar.gz)

Código-fonte

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 pkg:npm/http-proxy-agent@5.0.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/http-proxy-agent@5.0.0

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:c08a5e5b6cf7fcb54bbbd1c5501bee750d4df519355342946d4364e9dfa252df","contract":["createHttpProxyAgent is exported as the default function and provides HttpProxyAgent constructor property","createHttpProxyAgent parses proxy URL string and configures proxy host, port, protocol, and secureProxy flag","HttpProxyAgent constructor accepts proxy options object with host, port, and protocol","HttpProxyAgent defaults proxy port to 80 for HTTP protocol and 443 for HTTPS protocol","HttpProxyAgent removes path and pathname from proxy options to avoid Unix domain socket conflicts","getAgentConfig normalizes agent proxy options and secureProxy flag","callback transforms request path into absolute URL format and injects Basic Proxy-Authorization header","HttpProxyAgent establishes network socket connection and tunnels HTTP requests through the proxy server"],"goal":"verify pkg:npm/http-proxy-agent@5.0.0","kind":"HOW","packages":["pkg:npm/http-proxy-agent@5.0.0"],"schemaVersion":1,"symbols":["HttpProxyAgent","createHttpProxyAgent"]},"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/http-proxy-agent@5.0.0"],"schemaVersion":1,"subject":"pkg:npm/http-proxy-agent@5.0.0","verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-http-proxy-agent",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-http-proxy-agent",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "http-proxy-agent": "5.0.0"
      }
    },
    "node_modules/@tootallnate/once": {
      "version": "2.0.1",
      "resolved": "https://registry.npmjs.org/@tootallnate/once/-/once-2.0.1.tgz",
      "integrity": "sha512-HqmEUIGRJ5fSXchkVgR5F7qn48bDBzv0kWj/Kfu5e6uci4UlEeng4331LnBkWffb++Ei3FOVLxo8JJWMFBDMeQ==",
      "license": "MIT",
      "engines": {
        "node": ">= 10"
      }
    },
    "node_modules/agent-base": {
      "version": "6.0.2",
      "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz",
      "integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==",
      "license": "MIT",
      "dependencies": {
        "debug": "4"
      },
      "engines": {
        "node": ">= 6.0.0"
      }
    },
    "node_modules/debug": {
      "version": "4.4.3",
      "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
      "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
      "license": "MIT",
      "dependencies": {
        "ms": "^2.1.3"
      },
      "engines": {
        "node": ">=6.0"
      },
      "peerDependenciesMeta": {
        "supports-color": {
          "optional": true
        }
      }
    },
    "node_modules/http-proxy-agent": {
      "version": "5.0.0",
      "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-5.0.0.tgz",
      "integrity": "sha512-n2hY8YdoRE1i7r6M0w9DIw5GgZN0G25P8zLCRQ8rjXtTU3vsNFBI/vWK/UIeE6g5MUUz6avwAPXmL6Fy9D/90w==",
      "license": "MIT",
      "dependencies": {
        "@tootallnate/once": "2",
        "agent-base": "6",
        "debug": "4"
      },
      "engines": {
        "node": ">= 6"
      }
    },
    "node_modules/ms": {
      "version": "2.1.3",
      "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
      "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
      "license": "MIT"
    }
  }
}
package.json
{
  "name": "sample-http-proxy-agent",
  "version": "1.0.0",
  "private": true,
  "description": "Clean-room verification of http-proxy-agent",
  "main": "src/index.js",
  "license": "MIT-0",
  "dependencies": {
    "http-proxy-agent": "5.0.0"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/http-proxy-agent@5.0.0",
  "kind": "HOW",
  "packages": [
    "pkg:npm/http-proxy-agent@5.0.0"
  ]
}
src/index.js
const http = require('node:http');
const createHttpProxyAgent = require('http-proxy-agent');

const { HttpProxyAgent } = createHttpProxyAgent;

/**
 * Creates an HttpProxyAgent instance from a URL string or an options object.
 *
 * @param {string | object} proxy - Proxy URL string or options object
 * @param {object} [options] - Additional agent options
 * @returns {HttpProxyAgent} Configured HttpProxyAgent instance
 */
function createProxyAgent(proxy, options) {
  if (options && typeof proxy === 'string') {
    const url = new URL(proxy);
    return createHttpProxyAgent({
      protocol: url.protocol,
      host: url.hostname,
      port: url.port ? parseInt(url.port, 10) : (url.protocol === 'https:' ? 443 : 80),
      auth: url.username ? `${url.username}:${url.password}` : undefined,
      ...options
    });
  }
  return createHttpProxyAgent(proxy);
}

/**
 * Extracts normalized proxy configuration details from an HttpProxyAgent instance.
 *
 * @param {HttpProxyAgent} agent - The HttpProxyAgent instance
 * @returns {object} Normalized proxy configuration
 */
function getAgentConfig(agent) {
  if (!agent || !agent.proxy) {
    throw new TypeError('Expected an HttpProxyAgent instance with a valid proxy property');
  }

  const { protocol, host, hostname, port, auth } = agent.proxy;

  return {
    protocol: protocol || (agent.secureProxy ? 'https:' : 'http:'),
    host: hostname || host,
    port: port ? parseInt(port, 10) : (agent.secureProxy ? 443 : 80),
    auth: auth || null,
    secureProxy: Boolean(agent.secureProxy)
  };
}

module.exports = {
  createProxyAgent,
  getAgentConfig,
  HttpProxyAgent,
  createHttpProxyAgent
};
test/contract.mjs
import assert from 'node:assert';
import http from 'node:http';
import { createRequire } from 'node:module';

const require = createRequire(import.meta.url);
const {
  createProxyAgent,
  getAgentConfig,
  HttpProxyAgent,
  createHttpProxyAgent
} = require('../src/index.js');

async function runContractTests() {
  // 1. Export verification
  assert.strictEqual(typeof createHttpProxyAgent, 'function', 'createHttpProxyAgent should be exported as a function');
  assert.strictEqual(typeof HttpProxyAgent, 'function', 'HttpProxyAgent constructor should be accessible');
  assert.strictEqual(typeof createProxyAgent, 'function', 'createProxyAgent helper should be a function');
  assert.strictEqual(typeof getAgentConfig, 'function', 'getAgentConfig helper should be a function');

  // 2. createHttpProxyAgent parses proxy URL string and configures proxy host, port, protocol, and secureProxy flag
  const httpAgent = createProxyAgent('http://127.0.0.1:8080');
  assert(httpAgent instanceof HttpProxyAgent, 'httpAgent should be an instance of HttpProxyAgent');
  assert.strictEqual(httpAgent.secureProxy, false);
  assert.strictEqual(httpAgent.proxy.host, '127.0.0.1');
  assert.strictEqual(httpAgent.proxy.port, 8080);
  assert.strictEqual(httpAgent.proxy.protocol, 'http:');

  const httpsAgent = createProxyAgent('https://127.0.0.1:8443');
  assert(httpsAgent instanceof HttpProxyAgent, 'httpsAgent should be an instance of HttpProxyAgent');
  assert.strictEqual(httpsAgent.secureProxy, true);
  assert.strictEqual(httpsAgent.proxy.host, '127.0.0.1');
  assert.strictEqual(httpsAgent.proxy.port, 8443);

  // 3. HttpProxyAgent constructor accepts proxy options object with host, port, and protocol
  const optsAgent = new HttpProxyAgent({
    host: '127.0.0.1',
    port: 3128,
    protocol: 'http:'
  });
  assert(optsAgent instanceof HttpProxyAgent, 'optsAgent should be an instance of HttpProxyAgent');
  assert.strictEqual(optsAgent.proxy.host, '127.0.0.1');
  assert.strictEqual(optsAgent.proxy.port, 3128);
  assert.strictEqual(optsAgent.secureProxy, false);

  // 4. HttpProxyAgent defaults proxy port to 80 for HTTP protocol and 443 for HTTPS protocol
  const defaultHttp = createProxyAgent('http://127.0.0.1');
  assert.strictEqual(defaultHttp.proxy.port, 80, 'HTTP proxy should default to port 80');

  const defaultHttps = createProxyAgent('https://127.0.0.1');
  assert.strictEqual(defaultHttps.proxy.port, 443, 'HTTPS proxy should default to port 443');

  // 5. HttpProxyAgent removes path and pathname from proxy options to avoid Unix domain socket conflicts
  const pathAgent = createProxyAgent('http://127.0.0.1:8080/some-proxy-path');
  assert.strictEqual(pathAgent.proxy.path, undefined, 'proxy.path should be deleted');
  assert.strictEqual(pathAgent.proxy.pathname, undefined, 'proxy.pathname should be deleted');

  // 6. Helper getAgentConfig normalizes agent proxy options
  const config = getAgentConfig(httpAgent);
  assert.deepStrictEqual(config, {
    protocol: 'http:',
    host: '127.0.0.1',
    port: 8080,
    auth: null,
    secureProxy: false
  });

  // 7. callback transforms request path into absolute URL and injects Basic Proxy-Authorization header
  await new Promise((resolve, reject) => {
    let capturedAuthHeader = null;
    let capturedUrl = null;

    const mockProxy = http.createServer((req, res) => {
      capturedAuthHeader = req.headers['proxy-authorization'];
      capturedUrl = req.url;
      res.writeHead(200, { 'Content-Type': 'text/plain' });
      res.end('proxy-response-ok');
    });

    mockProxy.listen(0, '127.0.0.1', () => {
      const proxyPort = mockProxy.address().port;
      const authAgent = new HttpProxyAgent({
        host: '127.0.0.1',
        port: proxyPort,
        auth: 'user:pass'
      });

      const clientReq = http.get({
        hostname: '127.0.0.1',
        port: 9999,
        path: '/test-endpoint',
        agent: authAgent
      }, (res) => {
        let body = '';
        res.on('data', chunk => { body += chunk; });
        res.on('end', () => {
          try {
            assert.strictEqual(res.statusCode, 200);
            assert.strictEqual(body, 'proxy-response-ok');
            assert.strictEqual(capturedUrl, 'http://127.0.0.1:9999/test-endpoint');
            const expectedAuth = 'Basic ' + Buffer.from('user:pass').toString('base64');
            assert.strictEqual(capturedAuthHeader, expectedAuth);
            mockProxy.close(resolve);
          } catch (err) {
            mockProxy.close(() => reject(err));
          }
        });
      });

      clientReq.on('error', (err) => {
        mockProxy.close(() => reject(err));
      });
    });
  });

  // 8. HttpProxyAgent establishes network socket connection and tunnels HTTP requests end-to-end
  await new Promise((resolve, reject) => {
    const targetServer = http.createServer((req, res) => {
      res.writeHead(200, { 'Content-Type': 'text/plain' });
      res.end('target-echo:' + req.url);
    });

    targetServer.listen(0, '127.0.0.1', () => {
      const targetPort = targetServer.address().port;

      const proxyServer = http.createServer((req, res) => {
        const parsedUrl = new URL(req.url);
        const forwardReq = http.request({
          hostname: parsedUrl.hostname,
          port: parsedUrl.port,
          path: parsedUrl.pathname + parsedUrl.search,
          method: req.method,
          headers: req.headers
        }, (forwardRes) => {
          res.writeHead(forwardRes.statusCode, forwardRes.headers);
          forwardRes.pipe(res);
        });

        forwardReq.on('error', (err) => {
          res.writeHead(502);
          res.end(err.message);
        });

        req.pipe(forwardReq);
      });

      proxyServer.listen(0, '127.0.0.1', () => {
        const proxyPort = proxyServer.address().port;
        const agent = createProxyAgent(`http://127.0.0.1:${proxyPort}`);

        const request = http.get({
          hostname: '127.0.0.1',
          port: targetPort,
          path: '/resource/data?query=1',
          agent: agent
        }, (res) => {
          let data = '';
          res.on('data', chunk => { data += chunk; });
          res.on('end', () => {
            try {
              assert.strictEqual(res.statusCode, 200);
              assert.strictEqual(data, 'target-echo:/resource/data?query=1');
              proxyServer.close(() => {
                targetServer.close(resolve);
              });
            } catch (err) {
              proxyServer.close(() => {
                targetServer.close(() => reject(err));
              });
            }
          });
        });

        request.on('error', (err) => {
          proxyServer.close(() => {
            targetServer.close(() => reject(err));
          });
        });
      });
    });
  });

  console.log('Contract tests passed successfully.');
}

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

Seeder de origem

anônimo