Debian Codegraph @

lib/dispatcher/proxy-agent.js

raw
1 'use strict'
2
3 const { kProxy, kClose, kDestroy, kDispatch } = require('../core/symbols')
4 const Agent = require('./agent')
5 const Pool = require('./pool')
6 const DispatcherBase = require('./dispatcher-base')
7 const { InvalidArgumentError, RequestAbortedError, SecureProxyConnectionError } = require('../core/errors')
8 const buildConnector = require('../core/connect')
9 const Client = require('./client')
10 const { channels } = require('../core/diagnostics')
11 const Socks5ProxyAgent = require('./socks5-proxy-agent')
12
13 const kAgent = Symbol('proxy agent')
14 const kClient = Symbol('proxy client')
15 const kProxyHeaders = Symbol('proxy headers')
16 const kRequestTls = Symbol('request tls settings')
17 const kProxyTls = Symbol('proxy tls settings')
18 const kConnectEndpoint = Symbol('connect endpoint function')
19 const kConnectEndpointHTTP1 = Symbol('connect endpoint function (http/1.1 only)')
20 const kTunnelProxy = Symbol('tunnel proxy')
21 const proxyAuthorization = 'proxy-authorization'
22
23 function defaultProtocolPort (protocol) {
24 return protocol === 'https:' ? 443 : 80
25 }
26
27 function defaultFactory (origin, opts) {
28 return new Pool(origin, opts)
29 }
30
31 const noop = () => {}
32
33 function defaultAgentFactory (origin, opts) {
34 if (opts.connections === 1) {
35 return new Client(origin, opts)
36 }
37 return new Pool(origin, opts)
38 }
39
40 class Http1ProxyWrapper extends DispatcherBase {
41 #client
42
43 constructor (proxyUrl, { headers = {}, connect, factory }) {
44 if (!proxyUrl) {
45 throw new InvalidArgumentError('Proxy URL is mandatory')
46 }
47
48 super()
49
50 this[kProxyHeaders] = headers
51 if (factory) {
52 this.#client = factory(proxyUrl, { connect })
53 } else {
54 this.#client = new Client(proxyUrl, { connect })
55 }
56 }
57
58 [kDispatch] (opts, handler) {
59 const onResponseStart = handler.onResponseStart
60 handler.onResponseStart = function (controller, statusCode, data, statusMessage) {
61 if (statusCode === 407) {
62 if (typeof handler.onResponseError === 'function') {
63 handler.onResponseError(controller, new InvalidArgumentError('Proxy Authentication Required (407)'))
64 }
65 return
66 }
67 if (onResponseStart) onResponseStart.call(this, controller, statusCode, data, statusMessage)
68 }
69
70 // Rewrite request as an HTTP1 Proxy request, without tunneling.
71 const {
72 origin,
73 path = '/',
74 headers = {}
75 } = opts
76
77 opts.path = origin + path
78
79 if (!('host' in headers) && !('Host' in headers)) {
80 const { host } = new URL(origin)
81 headers.host = host
82 }
83 opts.headers = { ...this[kProxyHeaders], ...headers }
84
85 return this.#client[kDispatch](opts, handler)
86 }
87
88 [kClose] () {
89 return this.#client.close()
90 }
91
92 [kDestroy] (err) {
93 return this.#client.destroy(err)
94 }
95 }
96
97 class ProxyAgent extends DispatcherBase {
98 constructor (opts) {
99 if (!opts || (typeof opts === 'object' && !(opts instanceof URL) && !opts.uri)) {
100 throw new InvalidArgumentError('Proxy uri is mandatory')
101 }
102
103 const { clientFactory = defaultFactory } = opts
104 if (typeof clientFactory !== 'function') {
105 throw new InvalidArgumentError('Proxy opts.clientFactory must be a function.')
106 }
107
108 const { proxyTunnel = true, connectTimeout } = opts
109
110 super()
111
112 const url = this.#getUrl(opts)
113 const { href, origin, port, protocol, username, password, hostname: proxyHostname } = url
114
115 this[kProxy] = { uri: href, protocol }
116 this[kRequestTls] = opts.requestTls
117 this[kProxyTls] = opts.proxyTls
118 this[kProxyHeaders] = opts.headers || {}
119 this[kTunnelProxy] = proxyTunnel
120
121 if (opts.auth && opts.token) {
122 throw new InvalidArgumentError('opts.auth cannot be used in combination with opts.token')
123 } else if (opts.auth) {
124 /* @deprecated in favour of opts.token */
125 this[kProxyHeaders]['proxy-authorization'] = `Basic ${opts.auth}`
126 } else if (opts.token) {
127 this[kProxyHeaders]['proxy-authorization'] = opts.token
128 } else if (username && password) {
129 this[kProxyHeaders]['proxy-authorization'] = `Basic ${Buffer.from(`${decodeURIComponent(username)}:${decodeURIComponent(password)}`).toString('base64')}`
130 } else if (username) {
131 this[kProxyHeaders]['proxy-authorization'] = `Basic ${Buffer.from(`${decodeURIComponent(username)}:`).toString('base64')}`
132 }
133
134 const connect = buildConnector({ timeout: connectTimeout, ...opts.proxyTls })
135 this[kConnectEndpoint] = buildConnector({ timeout: connectTimeout, ...opts.requestTls })
136 this[kConnectEndpointHTTP1] = buildConnector({ timeout: connectTimeout, ...opts.requestTls, allowH2: false })
137
138 const agentFactory = opts.factory || defaultAgentFactory
139 const factory = (origin, options) => {
140 const { protocol } = new URL(origin)
141
142 // Handle SOCKS5 proxy
143 if (this[kProxy].protocol === 'socks5:' || this[kProxy].protocol === 'socks:') {
144 return new Socks5ProxyAgent(this[kProxy].uri, {
145 headers: this[kProxyHeaders],
146 connect,
147 factory: agentFactory,
148 username: opts.username || username,
149 password: opts.password || password,
150 proxyTls: opts.proxyTls,
151 requestTls: opts.requestTls
152 })
153 }
154
155 if (!this[kTunnelProxy] && protocol === 'http:' && this[kProxy].protocol === 'http:') {
156 return new Http1ProxyWrapper(this[kProxy].uri, {
157 headers: this[kProxyHeaders],
158 connect,
159 factory: agentFactory
160 })
161 }
162 return agentFactory(origin, options)
163 }
164
165 // For SOCKS5 proxies, we don't need a client to the proxy itself
166 // The SOCKS5 connection is handled within Socks5ProxyAgent
167 if (protocol === 'socks5:' || protocol === 'socks:') {
168 this[kClient] = null
169 } else {
170 this[kClient] = clientFactory(url, { connect })
171 }
172
173 this[kAgent] = new Agent({
174 ...opts,
175 factory,
176 connect: async (opts, callback) => {
177 // SOCKS5 proxies handle their own connections via Socks5ProxyAgent,
178 // so this connect function should never be called for them.
179 if (!this[kClient]) {
180 callback(new InvalidArgumentError('Cannot establish tunnel connection without a proxy client'))
181 return
182 }
183
184 let requestedPath = opts.host
185 if (!opts.port) {
186 requestedPath += `:${defaultProtocolPort(opts.protocol)}`
187 }
188 try {
189 const connectParams = {
190 origin,
191 port,
192 path: requestedPath,
193 signal: opts.signal,
194 headers: {
195 ...this[kProxyHeaders],
196 host: opts.host,
197 ...(opts.connections == null || opts.connections > 0 ? { 'proxy-connection': 'keep-alive' } : {})
198 },
199 servername: this[kProxyTls]?.servername || proxyHostname
200 }
201 const { socket, statusCode } = await this[kClient].connect(connectParams)
202 if (statusCode !== 200) {
203 socket.on('error', noop).destroy()
204 callback(new RequestAbortedError(`Proxy response (${statusCode}) !== 200 when HTTP Tunneling`))
205 return
206 }
207
208 if (channels.proxyConnected.hasSubscribers) {
209 channels.proxyConnected.publish({
210 socket,
211 connectParams
212 })
213 }
214
215 if (opts.protocol !== 'https:') {
216 callback(null, socket)
217 return
218 }
219 let servername
220 if (this[kRequestTls]) {
221 servername = this[kRequestTls].servername
222 } else {
223 servername = opts.servername
224 }
225 const connectEndpoint = opts.allowH2 === false
226 ? this[kConnectEndpointHTTP1]
227 : this[kConnectEndpoint]
228
229 connectEndpoint({ ...opts, servername, httpSocket: socket }, callback)
230 } catch (err) {
231 if (err.code === 'ERR_TLS_CERT_ALTNAME_INVALID') {
232 // Throw a custom error to avoid loop in client.js#connect
233 callback(new SecureProxyConnectionError(err))
234 } else {
235 callback(err)
236 }
237 }
238 }
239 })
240 }
241
242 dispatch (opts, handler) {
243 const headers = buildHeaders(opts.headers)
244 throwIfProxyAuthIsSent(headers)
245
246 if (headers && !('host' in headers) && !('Host' in headers)) {
247 const { host } = new URL(opts.origin)
248 headers.host = host
249 }
250
251 return this[kAgent].dispatch(
252 {
253 ...opts,
254 headers
255 },
256 handler
257 )
258 }
259
260 /**
261 * @param {import('../../types/proxy-agent').ProxyAgent.Options | string | URL} opts
262 * @returns {URL}
263 */
264 #getUrl (opts) {
265 if (typeof opts === 'string') {
266 return new URL(opts)
267 } else if (opts instanceof URL) {
268 return opts
269 } else {
270 return new URL(opts.uri)
271 }
272 }
273
274 [kClose] () {
275 const promises = [this[kAgent].close()]
276 if (this[kClient]) {
277 promises.push(this[kClient].close())
278 }
279 return Promise.all(promises)
280 }
281
282 [kDestroy] () {
283 const promises = [this[kAgent].destroy()]
284 if (this[kClient]) {
285 promises.push(this[kClient].destroy())
286 }
287 return Promise.all(promises)
288 }
289 }
290
291 /**
292 * @param {string[] | Record<string, string>} headers
293 * @returns {Record<string, string>}
294 */
295 function buildHeaders (headers) {
296 // When using undici.fetch, the headers list is stored
297 // as an array.
298 if (Array.isArray(headers)) {
299 /** @type {Record<string, string>} */
300 const headersPair = {}
301
302 for (let i = 0; i < headers.length; i += 2) {
303 if (isProxyAuthorizationHeader(headers[i])) {
304 throwProxyAuthError()
305 }
306
307 headersPair[headers[i]] = headers[i + 1]
308 }
309
310 return headersPair
311 }
312
313 return headers
314 }
315
316 /**
317 * @param {Record<string, string>} headers
318 *
319 * Previous versions of ProxyAgent suggests the Proxy-Authorization in request headers
320 * Nevertheless, it was changed and to avoid a security vulnerability by end users
321 * this check was created.
322 * It should be removed in the next major version for performance reasons
323 */
324 function throwIfProxyAuthIsSent (headers) {
325 for (const key in headers) {
326 if (isProxyAuthorizationHeader(key)) {
327 throwProxyAuthError()
328 }
329 }
330 }
331
332 /**
333 * @param {string} key
334 * @returns {boolean}
335 */
336 function isProxyAuthorizationHeader (key) {
337 return key.length === proxyAuthorization.length && key.toLowerCase() === proxyAuthorization
338 }
339
340 function throwProxyAuthError () {
341 throw new InvalidArgumentError('Proxy-Authorization should be sent in ProxyAgent constructor')
342 }
343
344 module.exports = ProxyAgent