proxy-agent.js 5.2 KB

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