proxy-agent.js 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  1. 'use strict'
  2. const { kProxy, kClose, kDestroy, kInterceptors } = require('../core/symbols')
  3. const { URL } = require('node:url')
  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 kAgent = Symbol('proxy agent')
  10. const kClient = Symbol('proxy client')
  11. const kProxyHeaders = Symbol('proxy headers')
  12. const kRequestTls = Symbol('request tls settings')
  13. const kProxyTls = Symbol('proxy tls settings')
  14. const kConnectEndpoint = Symbol('connect endpoint function')
  15. function defaultProtocolPort (protocol) {
  16. return protocol === 'https:' ? 443 : 80
  17. }
  18. function defaultFactory (origin, opts) {
  19. return new Pool(origin, opts)
  20. }
  21. const noop = () => {}
  22. class ProxyAgent extends DispatcherBase {
  23. constructor (opts) {
  24. super()
  25. if (!opts || (typeof opts === 'object' && !(opts instanceof URL) && !opts.uri)) {
  26. throw new InvalidArgumentError('Proxy uri is mandatory')
  27. }
  28. const { clientFactory = defaultFactory } = opts
  29. if (typeof clientFactory !== 'function') {
  30. throw new InvalidArgumentError('Proxy opts.clientFactory must be a function.')
  31. }
  32. const url = this.#getUrl(opts)
  33. const { href, origin, port, protocol, username, password, hostname: proxyHostname } = url
  34. this[kProxy] = { uri: href, protocol }
  35. this[kInterceptors] = opts.interceptors?.ProxyAgent && Array.isArray(opts.interceptors.ProxyAgent)
  36. ? opts.interceptors.ProxyAgent
  37. : []
  38. this[kRequestTls] = opts.requestTls
  39. this[kProxyTls] = opts.proxyTls
  40. this[kProxyHeaders] = opts.headers || {}
  41. if (opts.auth && opts.token) {
  42. throw new InvalidArgumentError('opts.auth cannot be used in combination with opts.token')
  43. } else if (opts.auth) {
  44. /* @deprecated in favour of opts.token */
  45. this[kProxyHeaders]['proxy-authorization'] = `Basic ${opts.auth}`
  46. } else if (opts.token) {
  47. this[kProxyHeaders]['proxy-authorization'] = opts.token
  48. } else if (username && password) {
  49. this[kProxyHeaders]['proxy-authorization'] = `Basic ${Buffer.from(`${decodeURIComponent(username)}:${decodeURIComponent(password)}`).toString('base64')}`
  50. }
  51. const connect = buildConnector({ ...opts.proxyTls })
  52. this[kConnectEndpoint] = buildConnector({ ...opts.requestTls })
  53. this[kClient] = clientFactory(url, { connect })
  54. this[kAgent] = new Agent({
  55. ...opts,
  56. connect: async (opts, callback) => {
  57. let requestedPath = opts.host
  58. if (!opts.port) {
  59. requestedPath += `:${defaultProtocolPort(opts.protocol)}`
  60. }
  61. try {
  62. const { socket, statusCode } = await this[kClient].connect({
  63. origin,
  64. port,
  65. path: requestedPath,
  66. signal: opts.signal,
  67. headers: {
  68. ...this[kProxyHeaders],
  69. host: opts.host
  70. },
  71. servername: this[kProxyTls]?.servername || proxyHostname
  72. })
  73. if (statusCode !== 200) {
  74. socket.on('error', noop).destroy()
  75. callback(new RequestAbortedError(`Proxy response (${statusCode}) !== 200 when HTTP Tunneling`))
  76. }
  77. if (opts.protocol !== 'https:') {
  78. callback(null, socket)
  79. return
  80. }
  81. let servername
  82. if (this[kRequestTls]) {
  83. servername = this[kRequestTls].servername
  84. } else {
  85. servername = opts.servername
  86. }
  87. this[kConnectEndpoint]({ ...opts, servername, httpSocket: socket }, callback)
  88. } catch (err) {
  89. if (err.code === 'ERR_TLS_CERT_ALTNAME_INVALID') {
  90. // Throw a custom error to avoid loop in client.js#connect
  91. callback(new SecureProxyConnectionError(err))
  92. } else {
  93. callback(err)
  94. }
  95. }
  96. }
  97. })
  98. }
  99. dispatch (opts, handler) {
  100. const headers = buildHeaders(opts.headers)
  101. throwIfProxyAuthIsSent(headers)
  102. if (headers && !('host' in headers) && !('Host' in headers)) {
  103. const { host } = new URL(opts.origin)
  104. headers.host = host
  105. }
  106. return this[kAgent].dispatch(
  107. {
  108. ...opts,
  109. headers
  110. },
  111. handler
  112. )
  113. }
  114. /**
  115. * @param {import('../types/proxy-agent').ProxyAgent.Options | string | URL} opts
  116. * @returns {URL}
  117. */
  118. #getUrl (opts) {
  119. if (typeof opts === 'string') {
  120. return new URL(opts)
  121. } else if (opts instanceof URL) {
  122. return opts
  123. } else {
  124. return new URL(opts.uri)
  125. }
  126. }
  127. async [kClose] () {
  128. await this[kAgent].close()
  129. await this[kClient].close()
  130. }
  131. async [kDestroy] () {
  132. await this[kAgent].destroy()
  133. await this[kClient].destroy()
  134. }
  135. }
  136. /**
  137. * @param {string[] | Record<string, string>} headers
  138. * @returns {Record<string, string>}
  139. */
  140. function buildHeaders (headers) {
  141. // When using undici.fetch, the headers list is stored
  142. // as an array.
  143. if (Array.isArray(headers)) {
  144. /** @type {Record<string, string>} */
  145. const headersPair = {}
  146. for (let i = 0; i < headers.length; i += 2) {
  147. headersPair[headers[i]] = headers[i + 1]
  148. }
  149. return headersPair
  150. }
  151. return headers
  152. }
  153. /**
  154. * @param {Record<string, string>} headers
  155. *
  156. * Previous versions of ProxyAgent suggests the Proxy-Authorization in request headers
  157. * Nevertheless, it was changed and to avoid a security vulnerability by end users
  158. * this check was created.
  159. * It should be removed in the next major version for performance reasons
  160. */
  161. function throwIfProxyAuthIsSent (headers) {
  162. const existProxyAuth = headers && Object.keys(headers)
  163. .find((key) => key.toLowerCase() === 'proxy-authorization')
  164. if (existProxyAuth) {
  165. throw new InvalidArgumentError('Proxy-Authorization should be sent in ProxyAgent constructor')
  166. }
  167. }
  168. module.exports = ProxyAgent