proxy-agent.js 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. 'use strict'
  2. const { kProxy, kClose, kDestroy, kDispatch } = require('../core/symbols')
  3. const Agent = require('./agent')
  4. const Pool = require('./pool')
  5. const DispatcherBase = require('./dispatcher-base')
  6. const { InvalidArgumentError, RequestAbortedError, SecureProxyConnectionError } = require('../core/errors')
  7. const buildConnector = require('../core/connect')
  8. const Client = require('./client')
  9. const { channels } = require('../core/diagnostics')
  10. const kAgent = Symbol('proxy agent')
  11. const kClient = Symbol('proxy client')
  12. const kProxyHeaders = Symbol('proxy headers')
  13. const kRequestTls = Symbol('request tls settings')
  14. const kProxyTls = Symbol('proxy tls settings')
  15. const kConnectEndpoint = Symbol('connect endpoint function')
  16. const kTunnelProxy = Symbol('tunnel proxy')
  17. function defaultProtocolPort (protocol) {
  18. return protocol === 'https:' ? 443 : 80
  19. }
  20. function defaultFactory (origin, opts) {
  21. return new Pool(origin, opts)
  22. }
  23. const noop = () => {}
  24. function defaultAgentFactory (origin, opts) {
  25. if (opts.connections === 1) {
  26. return new Client(origin, opts)
  27. }
  28. return new Pool(origin, opts)
  29. }
  30. class Http1ProxyWrapper extends DispatcherBase {
  31. #client
  32. constructor (proxyUrl, { headers = {}, connect, factory }) {
  33. if (!proxyUrl) {
  34. throw new InvalidArgumentError('Proxy URL is mandatory')
  35. }
  36. super()
  37. this[kProxyHeaders] = headers
  38. if (factory) {
  39. this.#client = factory(proxyUrl, { connect })
  40. } else {
  41. this.#client = new Client(proxyUrl, { connect })
  42. }
  43. }
  44. [kDispatch] (opts, handler) {
  45. const onHeaders = handler.onHeaders
  46. handler.onHeaders = function (statusCode, data, resume) {
  47. if (statusCode === 407) {
  48. if (typeof handler.onError === 'function') {
  49. handler.onError(new InvalidArgumentError('Proxy Authentication Required (407)'))
  50. }
  51. return
  52. }
  53. if (onHeaders) onHeaders.call(this, statusCode, data, resume)
  54. }
  55. // Rewrite request as an HTTP1 Proxy request, without tunneling.
  56. const {
  57. origin,
  58. path = '/',
  59. headers = {}
  60. } = opts
  61. opts.path = origin + path
  62. if (!('host' in headers) && !('Host' in headers)) {
  63. const { host } = new URL(origin)
  64. headers.host = host
  65. }
  66. opts.headers = { ...this[kProxyHeaders], ...headers }
  67. return this.#client[kDispatch](opts, handler)
  68. }
  69. [kClose] () {
  70. return this.#client.close()
  71. }
  72. [kDestroy] (err) {
  73. return this.#client.destroy(err)
  74. }
  75. }
  76. class ProxyAgent extends DispatcherBase {
  77. constructor (opts) {
  78. if (!opts || (typeof opts === 'object' && !(opts instanceof URL) && !opts.uri)) {
  79. throw new InvalidArgumentError('Proxy uri is mandatory')
  80. }
  81. const { clientFactory = defaultFactory } = opts
  82. if (typeof clientFactory !== 'function') {
  83. throw new InvalidArgumentError('Proxy opts.clientFactory must be a function.')
  84. }
  85. const { proxyTunnel = true } = opts
  86. super()
  87. const url = this.#getUrl(opts)
  88. const { href, origin, port, protocol, username, password, hostname: proxyHostname } = url
  89. this[kProxy] = { uri: href, protocol }
  90. this[kRequestTls] = opts.requestTls
  91. this[kProxyTls] = opts.proxyTls
  92. this[kProxyHeaders] = opts.headers || {}
  93. this[kTunnelProxy] = proxyTunnel
  94. if (opts.auth && opts.token) {
  95. throw new InvalidArgumentError('opts.auth cannot be used in combination with opts.token')
  96. } else if (opts.auth) {
  97. /* @deprecated in favour of opts.token */
  98. this[kProxyHeaders]['proxy-authorization'] = `Basic ${opts.auth}`
  99. } else if (opts.token) {
  100. this[kProxyHeaders]['proxy-authorization'] = opts.token
  101. } else if (username && password) {
  102. this[kProxyHeaders]['proxy-authorization'] = `Basic ${Buffer.from(`${decodeURIComponent(username)}:${decodeURIComponent(password)}`).toString('base64')}`
  103. }
  104. const connect = buildConnector({ ...opts.proxyTls })
  105. this[kConnectEndpoint] = buildConnector({ ...opts.requestTls })
  106. const agentFactory = opts.factory || defaultAgentFactory
  107. const factory = (origin, options) => {
  108. const { protocol } = new URL(origin)
  109. if (!this[kTunnelProxy] && protocol === 'http:' && this[kProxy].protocol === 'http:') {
  110. return new Http1ProxyWrapper(this[kProxy].uri, {
  111. headers: this[kProxyHeaders],
  112. connect,
  113. factory: agentFactory
  114. })
  115. }
  116. return agentFactory(origin, options)
  117. }
  118. this[kClient] = clientFactory(url, { connect })
  119. this[kAgent] = new Agent({
  120. ...opts,
  121. factory,
  122. connect: async (opts, callback) => {
  123. let requestedPath = opts.host
  124. if (!opts.port) {
  125. requestedPath += `:${defaultProtocolPort(opts.protocol)}`
  126. }
  127. try {
  128. const connectParams = {
  129. origin,
  130. port,
  131. path: requestedPath,
  132. signal: opts.signal,
  133. headers: {
  134. ...this[kProxyHeaders],
  135. host: opts.host,
  136. ...(opts.connections == null || opts.connections > 0 ? { 'proxy-connection': 'keep-alive' } : {})
  137. },
  138. servername: this[kProxyTls]?.servername || proxyHostname
  139. }
  140. const { socket, statusCode } = await this[kClient].connect(connectParams)
  141. if (statusCode !== 200) {
  142. socket.on('error', noop).destroy()
  143. callback(new RequestAbortedError(`Proxy response (${statusCode}) !== 200 when HTTP Tunneling`))
  144. return
  145. }
  146. if (channels.proxyConnected.hasSubscribers) {
  147. channels.proxyConnected.publish({
  148. socket,
  149. connectParams
  150. })
  151. }
  152. if (opts.protocol !== 'https:') {
  153. callback(null, socket)
  154. return
  155. }
  156. let servername
  157. if (this[kRequestTls]) {
  158. servername = this[kRequestTls].servername
  159. } else {
  160. servername = opts.servername
  161. }
  162. this[kConnectEndpoint]({ ...opts, servername, httpSocket: socket }, callback)
  163. } catch (err) {
  164. if (err.code === 'ERR_TLS_CERT_ALTNAME_INVALID') {
  165. // Throw a custom error to avoid loop in client.js#connect
  166. callback(new SecureProxyConnectionError(err))
  167. } else {
  168. callback(err)
  169. }
  170. }
  171. }
  172. })
  173. }
  174. dispatch (opts, handler) {
  175. const headers = buildHeaders(opts.headers)
  176. throwIfProxyAuthIsSent(headers)
  177. if (headers && !('host' in headers) && !('Host' in headers)) {
  178. const { host } = new URL(opts.origin)
  179. headers.host = host
  180. }
  181. return this[kAgent].dispatch(
  182. {
  183. ...opts,
  184. headers
  185. },
  186. handler
  187. )
  188. }
  189. /**
  190. * @param {import('../../types/proxy-agent').ProxyAgent.Options | string | URL} opts
  191. * @returns {URL}
  192. */
  193. #getUrl (opts) {
  194. if (typeof opts === 'string') {
  195. return new URL(opts)
  196. } else if (opts instanceof URL) {
  197. return opts
  198. } else {
  199. return new URL(opts.uri)
  200. }
  201. }
  202. [kClose] () {
  203. return Promise.all([
  204. this[kAgent].close(),
  205. this[kClient].close()
  206. ])
  207. }
  208. [kDestroy] () {
  209. return Promise.all([
  210. this[kAgent].destroy(),
  211. this[kClient].destroy()
  212. ])
  213. }
  214. }
  215. /**
  216. * @param {string[] | Record<string, string>} headers
  217. * @returns {Record<string, string>}
  218. */
  219. function buildHeaders (headers) {
  220. // When using undici.fetch, the headers list is stored
  221. // as an array.
  222. if (Array.isArray(headers)) {
  223. /** @type {Record<string, string>} */
  224. const headersPair = {}
  225. for (let i = 0; i < headers.length; i += 2) {
  226. headersPair[headers[i]] = headers[i + 1]
  227. }
  228. return headersPair
  229. }
  230. return headers
  231. }
  232. /**
  233. * @param {Record<string, string>} headers
  234. *
  235. * Previous versions of ProxyAgent suggests the Proxy-Authorization in request headers
  236. * Nevertheless, it was changed and to avoid a security vulnerability by end users
  237. * this check was created.
  238. * It should be removed in the next major version for performance reasons
  239. */
  240. function throwIfProxyAuthIsSent (headers) {
  241. const existProxyAuth = headers && Object.keys(headers)
  242. .find((key) => key.toLowerCase() === 'proxy-authorization')
  243. if (existProxyAuth) {
  244. throw new InvalidArgumentError('Proxy-Authorization should be sent in ProxyAgent constructor')
  245. }
  246. }
  247. module.exports = ProxyAgent