Debian Codegraph @

lib/dispatcher/socks5-proxy-agent.js

raw
1 'use strict'
2
3 const { URL } = require('node:url')
4
5 let tls // include tls conditionally since it is not always available
6 const DispatcherBase = require('./dispatcher-base')
7 const { InvalidArgumentError } = require('../core/errors')
8 const { Socks5Client, STATES } = require('../core/socks5-client')
9 const { kDispatch, kClose, kDestroy } = require('../core/symbols')
10 const Pool = require('./pool')
11 const buildConnector = require('../core/connect')
12 const { debuglog } = require('node:util')
13
14 const debug = debuglog('undici:socks5-proxy')
15
16 const kProxyUrl = Symbol('proxy url')
17 const kProxyHeaders = Symbol('proxy headers')
18 const kProxyAuth = Symbol('proxy auth')
19 const kProxyProtocol = Symbol('proxy protocol')
20 const kPools = Symbol('pools')
21 const kConnector = Symbol('connector')
22 const kRequestTls = Symbol('request tls settings')
23
24 // Static flag to ensure warning is only emitted once per process
25 let experimentalWarningEmitted = false
26
27 /**
28 * SOCKS5 proxy agent for dispatching requests through a SOCKS5 proxy
29 */
30 class Socks5ProxyAgent extends DispatcherBase {
31 constructor (proxyUrl, options = {}) {
32 super()
33
34 // Emit experimental warning only once
35 if (!experimentalWarningEmitted) {
36 process.emitWarning(
37 'SOCKS5 proxy support is experimental and subject to change',
38 'ExperimentalWarning'
39 )
40 experimentalWarningEmitted = true
41 }
42
43 if (!proxyUrl) {
44 throw new InvalidArgumentError('Proxy URL is mandatory')
45 }
46
47 // Parse proxy URL
48 const url = typeof proxyUrl === 'string' ? new URL(proxyUrl) : proxyUrl
49
50 if (url.protocol !== 'socks5:' && url.protocol !== 'socks:') {
51 throw new InvalidArgumentError('Proxy URL must use socks5:// or socks:// protocol')
52 }
53
54 this[kProxyUrl] = url
55 this[kProxyHeaders] = options.headers || {}
56 this[kProxyProtocol] = options.proxyTls ? 'https:' : 'http:'
57 this[kRequestTls] = options.requestTls
58
59 // Extract auth from URL or options
60 this[kProxyAuth] = {
61 username: options.username || (url.username ? decodeURIComponent(url.username) : null),
62 password: options.password || (url.password ? decodeURIComponent(url.password) : null)
63 }
64
65 // Create connector for proxy connection
66 this[kConnector] = options.connect || buildConnector({
67 ...options.proxyTls,
68 servername: options.proxyTls?.servername || url.hostname
69 })
70
71 // Pools for the actual HTTP connections (with SOCKS5 tunnel connect function), keyed by origin
72 this[kPools] = new Map()
73 }
74
75 /**
76 * Create a SOCKS5 connection to the proxy
77 */
78 async createSocks5Connection (targetHost, targetPort) {
79 const proxyHost = this[kProxyUrl].hostname
80 const proxyPort = parseInt(this[kProxyUrl].port) || 1080
81
82 debug('creating SOCKS5 connection to', proxyHost, proxyPort)
83
84 // Connect to the SOCKS5 proxy
85 const socketReady = Promise.withResolvers()
86
87 this[kConnector]({
88 hostname: proxyHost,
89 host: proxyHost,
90 port: proxyPort,
91 protocol: this[kProxyProtocol]
92 }, (err, socket) => {
93 if (err) {
94 socketReady.reject(err)
95 } else {
96 socketReady.resolve(socket)
97 }
98 })
99
100 const socket = await socketReady.promise
101
102 // Create SOCKS5 client
103 const socks5Client = new Socks5Client(socket, this[kProxyAuth])
104
105 // Handle SOCKS5 errors
106 socks5Client.on('error', (err) => {
107 debug('SOCKS5 error:', err)
108 socket.destroy()
109 })
110
111 // Perform SOCKS5 handshake
112 await socks5Client.handshake()
113
114 // Wait for authentication (if required)
115 const authenticationReady = Promise.withResolvers()
116
117 const authenticationTimeout = setTimeout(() => {
118 authenticationReady.reject(new Error('SOCKS5 authentication timeout'))
119 }, 5000)
120
121 const onAuthenticated = () => {
122 clearTimeout(authenticationTimeout)
123 socks5Client.removeListener('error', onAuthenticationError)
124 authenticationReady.resolve()
125 }
126
127 const onAuthenticationError = (err) => {
128 clearTimeout(authenticationTimeout)
129 socks5Client.removeListener('authenticated', onAuthenticated)
130 authenticationReady.reject(err)
131 }
132
133 // Check if already authenticated (for NO_AUTH method)
134 if (socks5Client.state === STATES.AUTHENTICATED) {
135 clearTimeout(authenticationTimeout)
136 authenticationReady.resolve()
137 } else {
138 socks5Client.once('authenticated', onAuthenticated)
139 socks5Client.once('error', onAuthenticationError)
140 }
141
142 await authenticationReady.promise
143
144 // Send CONNECT command
145 await socks5Client.connect(targetHost, targetPort)
146
147 // Wait for connection
148 const connectionReady = Promise.withResolvers()
149
150 const connectionTimeout = setTimeout(() => {
151 connectionReady.reject(new Error('SOCKS5 connection timeout'))
152 }, 5000)
153
154 const onConnected = (info) => {
155 debug('SOCKS5 tunnel established to', targetHost, targetPort, 'via', info)
156 clearTimeout(connectionTimeout)
157 socks5Client.removeListener('error', onConnectionError)
158 connectionReady.resolve()
159 }
160
161 const onConnectionError = (err) => {
162 clearTimeout(connectionTimeout)
163 socks5Client.removeListener('connected', onConnected)
164 connectionReady.reject(err)
165 }
166
167 socks5Client.once('connected', onConnected)
168 socks5Client.once('error', onConnectionError)
169
170 await connectionReady.promise
171
172 return socket
173 }
174
175 /**
176 * Dispatch a request through the SOCKS5 proxy
177 */
178 [kDispatch] (opts, handler) {
179 const { origin } = opts
180
181 debug('dispatching request to', origin, 'via SOCKS5')
182
183 try {
184 const originKey = String(origin)
185 let pool = this[kPools].get(originKey)
186 // Create a Pool per origin so requests are not routed to the wrong host
187 if (!pool || pool.destroyed || pool.closed) {
188 pool = new Pool(origin, {
189 pipelining: opts.pipelining,
190 connections: opts.connections,
191 connect: async (connectOpts, callback) => {
192 try {
193 const url = new URL(origin)
194 const targetHost = url.hostname
195 const targetPort = parseInt(url.port) || (url.protocol === 'https:' ? 443 : 80)
196
197 debug('establishing SOCKS5 connection to', targetHost, targetPort)
198
199 // Create SOCKS5 tunnel
200 const socket = await this.createSocks5Connection(targetHost, targetPort)
201
202 // Handle TLS if needed
203 let finalSocket = socket
204 if (url.protocol === 'https:') {
205 if (!tls) {
206 tls = require('node:tls')
207 }
208 debug('upgrading to TLS')
209 finalSocket = tls.connect({
210 ...this[kRequestTls],
211 socket,
212 servername: this[kRequestTls]?.servername || targetHost
213 })
214
215 const tlsReady = Promise.withResolvers()
216 finalSocket.once('secureConnect', tlsReady.resolve)
217 finalSocket.once('error', tlsReady.reject)
218 await tlsReady.promise
219 }
220
221 callback(null, finalSocket)
222 } catch (err) {
223 debug('SOCKS5 connection error:', err)
224 callback(err)
225 }
226 }
227 })
228 this[kPools].set(originKey, pool)
229 }
230
231 // Dispatch the request through the per-origin pool
232 return pool[kDispatch](opts, handler)
233 } catch (err) {
234 debug('dispatch error:', err)
235 if (typeof handler.onResponseError === 'function') {
236 handler.onResponseError(null, err)
237 return false
238 } else if (typeof handler.onError === 'function') {
239 handler.onError(err)
240 return false
241 } else {
242 throw err
243 }
244 }
245 }
246
247 async [kClose] () {
248 const closePromises = []
249 for (const pool of this[kPools].values()) {
250 closePromises.push(pool.close())
251 }
252 this[kPools].clear()
253 await Promise.all(closePromises)
254 }
255
256 async [kDestroy] (err) {
257 const destroyPromises = []
258 for (const pool of this[kPools].values()) {
259 destroyPromises.push(pool.destroy(err))
260 }
261 this[kPools].clear()
262 await Promise.all(destroyPromises)
263 }
264 }
265
266 module.exports = Socks5ProxyAgent