0
# SOCKS Proxy Agent
1
2
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.
3
4
## Package Information
5
6
- **Package Name**: socks-proxy-agent
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install socks-proxy-agent`
10
11
## Core Imports
12
13
```typescript
14
import { SocksProxyAgent } from "socks-proxy-agent";
15
```
16
17
For CommonJS:
18
19
```javascript
20
const { SocksProxyAgent } = require("socks-proxy-agent");
21
```
22
23
With TypeScript types:
24
25
```typescript
26
import { SocksProxyAgent, type SocksProxyAgentOptions } from "socks-proxy-agent";
27
```
28
29
You can also import just the types:
30
31
```typescript
32
import type { SocksProxyAgentOptions } from "socks-proxy-agent";
33
```
34
35
## Basic Usage
36
37
```typescript
38
import https from 'https';
39
import { SocksProxyAgent } from 'socks-proxy-agent';
40
41
// Create SOCKS proxy agent
42
const agent = new SocksProxyAgent('socks://your-name%40gmail.com:password@proxy.server.com:1080');
43
44
// Use with https requests
45
https.get('https://ipinfo.io', { agent }, (res) => {
46
console.log(res.headers);
47
res.pipe(process.stdout);
48
});
49
```
50
51
WebSocket usage example:
52
53
```typescript
54
import WebSocket from 'ws';
55
import { SocksProxyAgent } from 'socks-proxy-agent';
56
57
const agent = new SocksProxyAgent('socks://proxy.server.com:1080');
58
const socket = new WebSocket('ws://echo.websocket.events', { agent });
59
60
socket.on('open', () => {
61
console.log('Connection opened');
62
socket.send('hello world');
63
});
64
```
65
66
## Architecture
67
68
SOCKS Proxy Agent extends the `Agent` class from the `agent-base` package and implements the SOCKS protocol handshake. Key components include:
69
70
- **Protocol Support**: SOCKS4, SOCKS4a, SOCKS5, and SOCKS5h with automatic protocol detection
71
- **Authentication**: Username/password authentication via URL encoding
72
- **DNS Resolution**: Client-side or proxy-side hostname resolution depending on protocol
73
- **TLS Integration**: Automatic TLS socket upgrade for HTTPS endpoints
74
- **Error Handling**: Comprehensive error handling for connection failures and timeouts
75
76
## Capabilities
77
78
### SocksProxyAgent Class
79
80
Main proxy agent class that handles SOCKS connections and integrates with Node.js HTTP stack.
81
82
```typescript { .api }
83
/**
84
* SOCKS proxy agent for HTTP and HTTPS requests
85
*/
86
class SocksProxyAgent extends Agent {
87
/**
88
* Create a new SOCKS proxy agent
89
* @param uri - SOCKS proxy URL (string or URL object)
90
* @param opts - Optional configuration options
91
*/
92
constructor(uri: string | URL, opts?: SocksProxyAgentOptions);
93
94
/** Supported SOCKS protocols */
95
static readonly protocols: readonly ["socks", "socks4", "socks4a", "socks5", "socks5h"];
96
97
/** Whether DNS lookup should be performed locally */
98
readonly shouldLookup: boolean;
99
100
/** SOCKS proxy configuration */
101
readonly proxy: SocksProxy;
102
103
/** Connection timeout in milliseconds */
104
timeout: number | null;
105
106
/** TCP socket options for proxy connection */
107
socketOptions: SocksSocketOptions | null;
108
109
/**
110
* Initiates a SOCKS connection to the proxy server and target host
111
* @param req - HTTP client request object
112
* @param opts - Connection options including host, port, and TLS settings
113
* @returns Promise resolving to connected Socket or TLS Socket
114
* @throws Error if no host is defined
115
*/
116
connect(req: http.ClientRequest, opts: AgentConnectOpts): Promise<net.Socket>;
117
}
118
```
119
120
### Configuration Options
121
122
Configuration interface for customizing SOCKS proxy agent behavior.
123
124
```typescript { .api }
125
/**
126
* Configuration options for SocksProxyAgent constructor
127
* Combines http.AgentOptions with socketOptions, excluding proxy-specific fields
128
* that are derived from the proxy URL
129
*/
130
type SocksProxyAgentOptions = Omit<
131
SocksProxy,
132
'ipaddress' | 'host' | 'port' | 'type' | 'userId' | 'password'
133
> & {
134
/** TCP socket options for the proxy connection */
135
socketOptions?: SocksSocketOptions;
136
} & http.AgentOptions;
137
138
/**
139
* TCP socket options excluding port and host (handled by proxy configuration)
140
*/
141
type SocksSocketOptions = Omit<net.TcpNetConnectOpts, 'port' | 'host'>;
142
```
143
144
### SOCKS Proxy Configuration
145
146
Proxy configuration object containing connection details and credentials.
147
148
```typescript { .api }
149
/**
150
* SOCKS proxy server configuration (from 'socks' package)
151
*/
152
interface SocksProxy {
153
/** Proxy server hostname or IP address */
154
host: string;
155
/** Proxy server port number */
156
port: number;
157
/** SOCKS protocol version (4 or 5) */
158
type: 4 | 5;
159
/** Username for authentication (non-enumerable property) */
160
userId?: string;
161
/** Password for authentication (non-enumerable property) */
162
password?: string;
163
}
164
```
165
166
### Agent Connection Options
167
168
Connection options passed to the agent's connect method.
169
170
```typescript { .api }
171
/**
172
* Connection options for agent connect method (from 'agent-base' package)
173
* This is the union type AgentConnectOpts from agent-base
174
*/
175
type AgentConnectOpts = HttpConnectOpts | HttpsConnectOpts;
176
177
interface HttpConnectOpts extends net.TcpNetConnectOpts {
178
/** Target hostname */
179
host: string;
180
/** Target port number */
181
port: number;
182
/** This is an HTTP (non-secure) connection */
183
secureEndpoint: false;
184
/** Protocol identifier */
185
protocol?: string;
186
}
187
188
interface HttpsConnectOpts extends tls.ConnectionOptions {
189
/** Target hostname */
190
host: string;
191
/** Target port number */
192
port: number;
193
/** This is an HTTPS (secure) connection */
194
secureEndpoint: true;
195
/** Protocol identifier */
196
protocol?: string;
197
}
198
```
199
200
## URL Schemes and Protocol Support
201
202
### Supported URL Formats
203
204
The agent accepts SOCKS proxy URLs in the following formats:
205
206
- `socks://host:port` - SOCKS5 with hostname resolution on proxy (default)
207
- `socks4://host:port` - SOCKS4 with local DNS lookup
208
- `socks4a://host:port` - SOCKS4a with hostname resolution on proxy
209
- `socks5://host:port` - SOCKS5 with local DNS lookup
210
- `socks5h://host:port` - SOCKS5 with hostname resolution on proxy
211
212
### Authentication
213
214
Include credentials in the URL userinfo section:
215
216
```typescript
217
// Username and password authentication
218
const agent = new SocksProxyAgent('socks://username:password@proxy.server.com:1080');
219
220
// URL-encoded special characters
221
const agent = new SocksProxyAgent('socks://user%40domain.com:pass%21word@proxy.server.com:1080');
222
```
223
224
### Default Port
225
226
If no port is specified, the agent uses the standard SOCKS port 1080 as defined in RFC 1928.
227
228
## Error Handling
229
230
The agent provides comprehensive error handling for various failure scenarios:
231
232
- **Protocol Errors**: `TypeError` for unsupported proxy protocols
233
- **Configuration Errors**: `Error` when required connection parameters are missing
234
- **Timeout Errors**: Automatic cleanup when connection timeouts occur
235
- **TLS Errors**: Proper error handling and socket cleanup for HTTPS connections
236
237
Example error handling:
238
239
```typescript
240
import { SocksProxyAgent } from 'socks-proxy-agent';
241
242
try {
243
const agent = new SocksProxyAgent('invalid://proxy.server.com:1080');
244
} catch (error) {
245
if (error instanceof TypeError) {
246
console.error('Unsupported proxy protocol:', error.message);
247
}
248
}
249
```
250
251
## Common Use Cases
252
253
### HTTP Client Integration
254
255
```typescript
256
import http from 'http';
257
import https from 'https';
258
import { SocksProxyAgent } from 'socks-proxy-agent';
259
260
const agent = new SocksProxyAgent('socks5://proxy.server.com:1080');
261
262
// HTTP requests
263
http.get('http://example.com', { agent }, handleResponse);
264
265
// HTTPS requests
266
https.get('https://secure.example.com', { agent }, handleResponse);
267
```
268
269
### WebSocket Connections
270
271
```typescript
272
import WebSocket from 'ws';
273
import { SocksProxyAgent } from 'socks-proxy-agent';
274
275
const agent = new SocksProxyAgent('socks://proxy.server.com:1080');
276
const ws = new WebSocket('ws://websocket.server.com', { agent });
277
```
278
279
### Custom Timeout Configuration
280
281
```typescript
282
import { SocksProxyAgent } from 'socks-proxy-agent';
283
284
const agent = new SocksProxyAgent(
285
'socks://proxy.server.com:1080',
286
{
287
timeout: 30000, // 30 second timeout
288
socketOptions: {
289
keepAlive: true,
290
keepAliveInitialDelay: 10000
291
}
292
}
293
);
294
```
295
296
### IPv6 Support
297
298
```typescript
299
import { SocksProxyAgent } from 'socks-proxy-agent';
300
301
// IPv6 proxy server
302
const agent = new SocksProxyAgent('socks://[2001:db8::1]:1080');
303
```