proxy-agent.js 7.8 KB

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