index.js 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. "use strict";
  2. var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
  3. if (k2 === undefined) k2 = k;
  4. var desc = Object.getOwnPropertyDescriptor(m, k);
  5. if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
  6. desc = { enumerable: true, get: function() { return m[k]; } };
  7. }
  8. Object.defineProperty(o, k2, desc);
  9. }) : (function(o, m, k, k2) {
  10. if (k2 === undefined) k2 = k;
  11. o[k2] = m[k];
  12. }));
  13. var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
  14. Object.defineProperty(o, "default", { enumerable: true, value: v });
  15. }) : function(o, v) {
  16. o["default"] = v;
  17. });
  18. var __importStar = (this && this.__importStar) || function (mod) {
  19. if (mod && mod.__esModule) return mod;
  20. var result = {};
  21. if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
  22. __setModuleDefault(result, mod);
  23. return result;
  24. };
  25. var __importDefault = (this && this.__importDefault) || function (mod) {
  26. return (mod && mod.__esModule) ? mod : { "default": mod };
  27. };
  28. Object.defineProperty(exports, "__esModule", { value: true });
  29. exports.SocksProxyAgent = void 0;
  30. const socks_1 = require("socks");
  31. const agent_base_1 = require("agent-base");
  32. const debug_1 = __importDefault(require("debug"));
  33. const dns = __importStar(require("dns"));
  34. const net = __importStar(require("net"));
  35. const tls = __importStar(require("tls"));
  36. const url_1 = require("url");
  37. const debug = (0, debug_1.default)('socks-proxy-agent');
  38. function parseSocksURL(url) {
  39. let lookup = false;
  40. let type = 5;
  41. const host = url.hostname;
  42. // From RFC 1928, Section 3: https://tools.ietf.org/html/rfc1928#section-3
  43. // "The SOCKS service is conventionally located on TCP port 1080"
  44. const port = parseInt(url.port, 10) || 1080;
  45. // figure out if we want socks v4 or v5, based on the "protocol" used.
  46. // Defaults to 5.
  47. switch (url.protocol.replace(':', '')) {
  48. case 'socks4':
  49. lookup = true;
  50. type = 4;
  51. break;
  52. // pass through
  53. case 'socks4a':
  54. type = 4;
  55. break;
  56. case 'socks5':
  57. lookup = true;
  58. type = 5;
  59. break;
  60. // pass through
  61. case 'socks': // no version specified, default to 5h
  62. type = 5;
  63. break;
  64. case 'socks5h':
  65. type = 5;
  66. break;
  67. default:
  68. throw new TypeError(`A "socks" protocol must be specified! Got: ${String(url.protocol)}`);
  69. }
  70. const proxy = {
  71. host,
  72. port,
  73. type,
  74. };
  75. if (url.username) {
  76. Object.defineProperty(proxy, 'userId', {
  77. value: decodeURIComponent(url.username),
  78. enumerable: false,
  79. });
  80. }
  81. if (url.password != null) {
  82. Object.defineProperty(proxy, 'password', {
  83. value: decodeURIComponent(url.password),
  84. enumerable: false,
  85. });
  86. }
  87. return { lookup, proxy };
  88. }
  89. class SocksProxyAgent extends agent_base_1.Agent {
  90. constructor(uri, opts) {
  91. super(opts);
  92. const url = typeof uri === 'string' ? new url_1.URL(uri) : uri;
  93. const { proxy, lookup } = parseSocksURL(url);
  94. this.shouldLookup = lookup;
  95. this.proxy = proxy;
  96. this.timeout = opts?.timeout ?? null;
  97. this.socketOptions = opts?.socketOptions ?? null;
  98. }
  99. /**
  100. * Initiates a SOCKS connection to the specified SOCKS proxy server,
  101. * which in turn connects to the specified remote host and port.
  102. */
  103. async connect(req, opts) {
  104. const { shouldLookup, proxy, timeout } = this;
  105. if (!opts.host) {
  106. throw new Error('No `host` defined!');
  107. }
  108. let { host } = opts;
  109. const { port, lookup: lookupFn = dns.lookup } = opts;
  110. if (shouldLookup) {
  111. // Client-side DNS resolution for "4" and "5" socks proxy versions.
  112. host = await new Promise((resolve, reject) => {
  113. // Use the request's custom lookup, if one was configured:
  114. lookupFn(host, {}, (err, res) => {
  115. if (err) {
  116. reject(err);
  117. }
  118. else {
  119. resolve(res);
  120. }
  121. });
  122. });
  123. }
  124. const socksOpts = {
  125. proxy,
  126. destination: {
  127. host,
  128. port: typeof port === 'number' ? port : parseInt(port, 10),
  129. },
  130. command: 'connect',
  131. timeout: timeout ?? undefined,
  132. // @ts-expect-error the type supplied by socks for socket_options is wider
  133. // than necessary since socks will always override the host and port
  134. socket_options: this.socketOptions ?? undefined,
  135. };
  136. const cleanup = (tlsSocket) => {
  137. req.destroy();
  138. socket.destroy();
  139. if (tlsSocket)
  140. tlsSocket.destroy();
  141. };
  142. debug('Creating socks proxy connection: %o', socksOpts);
  143. const { socket } = await socks_1.SocksClient.createConnection(socksOpts);
  144. debug('Successfully created socks proxy connection');
  145. if (timeout !== null) {
  146. socket.setTimeout(timeout);
  147. socket.on('timeout', () => cleanup());
  148. }
  149. if (opts.secureEndpoint) {
  150. // The proxy is connecting to a TLS server, so upgrade
  151. // this socket connection to a TLS connection.
  152. debug('Upgrading socket connection to TLS');
  153. const servername = opts.servername || opts.host;
  154. const tlsSocket = tls.connect({
  155. ...omit(opts, 'host', 'path', 'port'),
  156. socket,
  157. servername: net.isIP(servername) ? undefined : servername,
  158. });
  159. tlsSocket.once('error', (error) => {
  160. debug('Socket TLS error', error.message);
  161. cleanup(tlsSocket);
  162. });
  163. return tlsSocket;
  164. }
  165. return socket;
  166. }
  167. }
  168. SocksProxyAgent.protocols = [
  169. 'socks',
  170. 'socks4',
  171. 'socks4a',
  172. 'socks5',
  173. 'socks5h',
  174. ];
  175. exports.SocksProxyAgent = SocksProxyAgent;
  176. function omit(obj, ...keys) {
  177. const ret = {};
  178. let key;
  179. for (key in obj) {
  180. if (!keys.includes(key)) {
  181. ret[key] = obj[key];
  182. }
  183. }
  184. return ret;
  185. }
  186. //# sourceMappingURL=index.js.map