index.js 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  1. import { _nullishCoalesce, _optionalChain } from '@sentry/utils';
  2. import assert from 'assert';
  3. import * as net from 'net';
  4. import * as tls from 'tls';
  5. import { URL } from 'url';
  6. import { logger } from '@sentry/utils';
  7. import { Agent } from './base.js';
  8. import { parseProxyResponse } from './parse-proxy-response.js';
  9. /**
  10. * This code was originally forked from https://github.com/TooTallNate/proxy-agents/tree/b133295fd16f6475578b6b15bd9b4e33ecb0d0b7
  11. * With the following licence:
  12. *
  13. * (The MIT License)
  14. *
  15. * Copyright (c) 2013 Nathan Rajlich <nathan@tootallnate.net>*
  16. *
  17. * Permission is hereby granted, free of charge, to any person obtaining
  18. * a copy of this software and associated documentation files (the
  19. * 'Software'), to deal in the Software without restriction, including
  20. * without limitation the rights to use, copy, modify, merge, publish,
  21. * distribute, sublicense, and/or sell copies of the Software, and to
  22. * permit persons to whom the Software is furnished to do so, subject to
  23. * the following conditions:*
  24. *
  25. * The above copyright notice and this permission notice shall be
  26. * included in all copies or substantial portions of the Software.*
  27. *
  28. * THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
  29. * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  30. * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  31. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
  32. * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
  33. * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
  34. * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  35. */
  36. function debug(...args) {
  37. logger.log('[https-proxy-agent]', ...args);
  38. }
  39. /**
  40. * The `HttpsProxyAgent` implements an HTTP Agent subclass that connects to
  41. * the specified "HTTP(s) proxy server" in order to proxy HTTPS requests.
  42. *
  43. * Outgoing HTTP requests are first tunneled through the proxy server using the
  44. * `CONNECT` HTTP request method to establish a connection to the proxy server,
  45. * and then the proxy server connects to the destination target and issues the
  46. * HTTP request from the proxy server.
  47. *
  48. * `https:` requests have their socket connection upgraded to TLS once
  49. * the connection to the proxy server has been established.
  50. */
  51. class HttpsProxyAgent extends Agent {
  52. static __initStatic() {this.protocols = ['http', 'https']; }
  53. constructor(proxy, opts) {
  54. super(opts);
  55. this.options = {};
  56. this.proxy = typeof proxy === 'string' ? new URL(proxy) : proxy;
  57. this.proxyHeaders = _nullishCoalesce(_optionalChain([opts, 'optionalAccess', _2 => _2.headers]), () => ( {}));
  58. debug('Creating new HttpsProxyAgent instance: %o', this.proxy.href);
  59. // Trim off the brackets from IPv6 addresses
  60. const host = (this.proxy.hostname || this.proxy.host).replace(/^\[|\]$/g, '');
  61. const port = this.proxy.port ? parseInt(this.proxy.port, 10) : this.proxy.protocol === 'https:' ? 443 : 80;
  62. this.connectOpts = {
  63. // Attempt to negotiate http/1.1 for proxy servers that support http/2
  64. ALPNProtocols: ['http/1.1'],
  65. ...(opts ? omit(opts, 'headers') : null),
  66. host,
  67. port,
  68. };
  69. }
  70. /**
  71. * Called when the node-core HTTP client library is creating a
  72. * new HTTP request.
  73. */
  74. async connect(req, opts) {
  75. const { proxy } = this;
  76. if (!opts.host) {
  77. throw new TypeError('No "host" provided');
  78. }
  79. // Create a socket connection to the proxy server.
  80. let socket;
  81. if (proxy.protocol === 'https:') {
  82. debug('Creating `tls.Socket`: %o', this.connectOpts);
  83. const servername = this.connectOpts.servername || this.connectOpts.host;
  84. socket = tls.connect({
  85. ...this.connectOpts,
  86. servername: servername && net.isIP(servername) ? undefined : servername,
  87. });
  88. } else {
  89. debug('Creating `net.Socket`: %o', this.connectOpts);
  90. socket = net.connect(this.connectOpts);
  91. }
  92. const headers =
  93. typeof this.proxyHeaders === 'function' ? this.proxyHeaders() : { ...this.proxyHeaders };
  94. const host = net.isIPv6(opts.host) ? `[${opts.host}]` : opts.host;
  95. let payload = `CONNECT ${host}:${opts.port} HTTP/1.1\r\n`;
  96. // Inject the `Proxy-Authorization` header if necessary.
  97. if (proxy.username || proxy.password) {
  98. const auth = `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`;
  99. headers['Proxy-Authorization'] = `Basic ${Buffer.from(auth).toString('base64')}`;
  100. }
  101. headers.Host = `${host}:${opts.port}`;
  102. if (!headers['Proxy-Connection']) {
  103. headers['Proxy-Connection'] = this.keepAlive ? 'Keep-Alive' : 'close';
  104. }
  105. for (const name of Object.keys(headers)) {
  106. payload += `${name}: ${headers[name]}\r\n`;
  107. }
  108. const proxyResponsePromise = parseProxyResponse(socket);
  109. socket.write(`${payload}\r\n`);
  110. const { connect, buffered } = await proxyResponsePromise;
  111. req.emit('proxyConnect', connect);
  112. // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  113. // @ts-ignore Not EventEmitter in Node types
  114. this.emit('proxyConnect', connect, req);
  115. if (connect.statusCode === 200) {
  116. req.once('socket', resume);
  117. if (opts.secureEndpoint) {
  118. // The proxy is connecting to a TLS server, so upgrade
  119. // this socket connection to a TLS connection.
  120. debug('Upgrading socket connection to TLS');
  121. const servername = opts.servername || opts.host;
  122. return tls.connect({
  123. ...omit(opts, 'host', 'path', 'port'),
  124. socket,
  125. servername: net.isIP(servername) ? undefined : servername,
  126. });
  127. }
  128. return socket;
  129. }
  130. // Some other status code that's not 200... need to re-play the HTTP
  131. // header "data" events onto the socket once the HTTP machinery is
  132. // attached so that the node core `http` can parse and handle the
  133. // error status code.
  134. // Close the original socket, and a new "fake" socket is returned
  135. // instead, so that the proxy doesn't get the HTTP request
  136. // written to it (which may contain `Authorization` headers or other
  137. // sensitive data).
  138. //
  139. // See: https://hackerone.com/reports/541502
  140. socket.destroy();
  141. const fakeSocket = new net.Socket({ writable: false });
  142. fakeSocket.readable = true;
  143. // Need to wait for the "socket" event to re-play the "data" events.
  144. req.once('socket', (s) => {
  145. debug('Replaying proxy buffer for failed request');
  146. assert(s.listenerCount('data') > 0);
  147. // Replay the "buffered" Buffer onto the fake `socket`, since at
  148. // this point the HTTP module machinery has been hooked up for
  149. // the user.
  150. s.push(buffered);
  151. s.push(null);
  152. });
  153. return fakeSocket;
  154. }
  155. }HttpsProxyAgent.__initStatic();
  156. function resume(socket) {
  157. socket.resume();
  158. }
  159. function omit(
  160. obj,
  161. ...keys
  162. )
  163. {
  164. const ret = {}
  165. ;
  166. let key;
  167. for (key in obj) {
  168. if (!keys.includes(key)) {
  169. ret[key] = obj[key];
  170. }
  171. }
  172. return ret;
  173. }
  174. export { HttpsProxyAgent };
  175. //# sourceMappingURL=index.js.map