or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-socks-proxy-agent

A SOCKS proxy http.Agent implementation for HTTP and HTTPS requests

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/socks-proxy-agent@8.0.x

To install, run

npx @tessl/cli install tessl/npm-socks-proxy-agent@8.0.0

index.mddocs/

SOCKS Proxy Agent

SOCKS Proxy Agent provides an HTTP Agent implementation that connects through SOCKS proxy servers for HTTP and HTTPS requests. It supports SOCKS4, SOCKS4a, SOCKS5, and SOCKS5h protocols, integrating seamlessly with Node.js built-in http and https modules and WebSocket libraries.

Package Information

  • Package Name: socks-proxy-agent
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install socks-proxy-agent

Core Imports

import { SocksProxyAgent } from "socks-proxy-agent";

For CommonJS:

const { SocksProxyAgent } = require("socks-proxy-agent");

With TypeScript types:

import { SocksProxyAgent, type SocksProxyAgentOptions } from "socks-proxy-agent";

You can also import just the types:

import type { SocksProxyAgentOptions } from "socks-proxy-agent";

Basic Usage

import https from 'https';
import { SocksProxyAgent } from 'socks-proxy-agent';

// Create SOCKS proxy agent
const agent = new SocksProxyAgent('socks://your-name%40gmail.com:password@proxy.server.com:1080');

// Use with https requests
https.get('https://ipinfo.io', { agent }, (res) => {
  console.log(res.headers);
  res.pipe(process.stdout);
});

WebSocket usage example:

import WebSocket from 'ws';
import { SocksProxyAgent } from 'socks-proxy-agent';

const agent = new SocksProxyAgent('socks://proxy.server.com:1080');
const socket = new WebSocket('ws://echo.websocket.events', { agent });

socket.on('open', () => {
  console.log('Connection opened');
  socket.send('hello world');
});

Architecture

SOCKS Proxy Agent extends the Agent class from the agent-base package and implements the SOCKS protocol handshake. Key components include:

  • Protocol Support: SOCKS4, SOCKS4a, SOCKS5, and SOCKS5h with automatic protocol detection
  • Authentication: Username/password authentication via URL encoding
  • DNS Resolution: Client-side or proxy-side hostname resolution depending on protocol
  • TLS Integration: Automatic TLS socket upgrade for HTTPS endpoints
  • Error Handling: Comprehensive error handling for connection failures and timeouts

Capabilities

SocksProxyAgent Class

Main proxy agent class that handles SOCKS connections and integrates with Node.js HTTP stack.

/**
 * SOCKS proxy agent for HTTP and HTTPS requests
 */
class SocksProxyAgent extends Agent {
  /**
   * Create a new SOCKS proxy agent
   * @param uri - SOCKS proxy URL (string or URL object)
   * @param opts - Optional configuration options
   */
  constructor(uri: string | URL, opts?: SocksProxyAgentOptions);

  /** Supported SOCKS protocols */
  static readonly protocols: readonly ["socks", "socks4", "socks4a", "socks5", "socks5h"];

  /** Whether DNS lookup should be performed locally */
  readonly shouldLookup: boolean;

  /** SOCKS proxy configuration */
  readonly proxy: SocksProxy;

  /** Connection timeout in milliseconds */
  timeout: number | null;

  /** TCP socket options for proxy connection */
  socketOptions: SocksSocketOptions | null;

  /**
   * Initiates a SOCKS connection to the proxy server and target host
   * @param req - HTTP client request object
   * @param opts - Connection options including host, port, and TLS settings
   * @returns Promise resolving to connected Socket or TLS Socket
   * @throws Error if no host is defined
   */
  connect(req: http.ClientRequest, opts: AgentConnectOpts): Promise<net.Socket>;
}

Configuration Options

Configuration interface for customizing SOCKS proxy agent behavior.

/**
 * Configuration options for SocksProxyAgent constructor
 * Combines http.AgentOptions with socketOptions, excluding proxy-specific fields
 * that are derived from the proxy URL
 */
type SocksProxyAgentOptions = Omit<
  SocksProxy,
  'ipaddress' | 'host' | 'port' | 'type' | 'userId' | 'password'  
> & {
  /** TCP socket options for the proxy connection */
  socketOptions?: SocksSocketOptions;
} & http.AgentOptions;

/**
 * TCP socket options excluding port and host (handled by proxy configuration)
 */
type SocksSocketOptions = Omit<net.TcpNetConnectOpts, 'port' | 'host'>;

SOCKS Proxy Configuration

Proxy configuration object containing connection details and credentials.

/**
 * SOCKS proxy server configuration (from 'socks' package)
 */
interface SocksProxy {
  /** Proxy server hostname or IP address */
  host: string;
  /** Proxy server port number */
  port: number;
  /** SOCKS protocol version (4 or 5) */
  type: 4 | 5;
  /** Username for authentication (non-enumerable property) */
  userId?: string;
  /** Password for authentication (non-enumerable property) */
  password?: string;
}

Agent Connection Options

Connection options passed to the agent's connect method.

/**  
 * Connection options for agent connect method (from 'agent-base' package)
 * This is the union type AgentConnectOpts from agent-base
 */
type AgentConnectOpts = HttpConnectOpts | HttpsConnectOpts;

interface HttpConnectOpts extends net.TcpNetConnectOpts {
  /** Target hostname */
  host: string;
  /** Target port number */
  port: number;
  /** This is an HTTP (non-secure) connection */
  secureEndpoint: false;
  /** Protocol identifier */
  protocol?: string;
}

interface HttpsConnectOpts extends tls.ConnectionOptions {
  /** Target hostname */
  host: string;
  /** Target port number */
  port: number;
  /** This is an HTTPS (secure) connection */
  secureEndpoint: true;
  /** Protocol identifier */
  protocol?: string;
}

URL Schemes and Protocol Support

Supported URL Formats

The agent accepts SOCKS proxy URLs in the following formats:

  • socks://host:port - SOCKS5 with hostname resolution on proxy (default)
  • socks4://host:port - SOCKS4 with local DNS lookup
  • socks4a://host:port - SOCKS4a with hostname resolution on proxy
  • socks5://host:port - SOCKS5 with local DNS lookup
  • socks5h://host:port - SOCKS5 with hostname resolution on proxy

Authentication

Include credentials in the URL userinfo section:

// Username and password authentication
const agent = new SocksProxyAgent('socks://username:password@proxy.server.com:1080');

// URL-encoded special characters
const agent = new SocksProxyAgent('socks://user%40domain.com:pass%21word@proxy.server.com:1080');

Default Port

If no port is specified, the agent uses the standard SOCKS port 1080 as defined in RFC 1928.

Error Handling

The agent provides comprehensive error handling for various failure scenarios:

  • Protocol Errors: TypeError for unsupported proxy protocols
  • Configuration Errors: Error when required connection parameters are missing
  • Timeout Errors: Automatic cleanup when connection timeouts occur
  • TLS Errors: Proper error handling and socket cleanup for HTTPS connections

Example error handling:

import { SocksProxyAgent } from 'socks-proxy-agent';

try {
  const agent = new SocksProxyAgent('invalid://proxy.server.com:1080');
} catch (error) {
  if (error instanceof TypeError) {
    console.error('Unsupported proxy protocol:', error.message);
  }
}

Common Use Cases

HTTP Client Integration

import http from 'http';
import https from 'https';
import { SocksProxyAgent } from 'socks-proxy-agent';

const agent = new SocksProxyAgent('socks5://proxy.server.com:1080');

// HTTP requests
http.get('http://example.com', { agent }, handleResponse);

// HTTPS requests
https.get('https://secure.example.com', { agent }, handleResponse);

WebSocket Connections

import WebSocket from 'ws';
import { SocksProxyAgent } from 'socks-proxy-agent';

const agent = new SocksProxyAgent('socks://proxy.server.com:1080');
const ws = new WebSocket('ws://websocket.server.com', { agent });

Custom Timeout Configuration

import { SocksProxyAgent } from 'socks-proxy-agent';

const agent = new SocksProxyAgent(
  'socks://proxy.server.com:1080',
  {
    timeout: 30000, // 30 second timeout
    socketOptions: {
      keepAlive: true,
      keepAliveInitialDelay: 10000
    }
  }
);

IPv6 Support

import { SocksProxyAgent } from 'socks-proxy-agent';

// IPv6 proxy server
const agent = new SocksProxyAgent('socks://[2001:db8::1]:1080');