From 4b5f14cecb97c12805117832be55bcaa0ecfc8dc Mon Sep 17 00:00:00 2001 From: xzeldon Date: Mon, 12 Dec 2022 02:05:49 +0300 Subject: [PATCH] Initial commit --- server.js | 1826 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 1826 insertions(+) create mode 100644 server.js diff --git a/server.js b/server.js new file mode 100644 index 0000000..c343b5c --- /dev/null +++ b/server.js @@ -0,0 +1,1826 @@ +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __esm = (fn, res) => function __init() { + return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res; +}; +var __commonJS = (cb, mod) => function __require() { + return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; +}; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// node_modules/tslib/tslib.es6.js +var tslib_es6_exports = {}; +__export(tslib_es6_exports, { + __assign: () => __assign, + __asyncDelegator: () => __asyncDelegator, + __asyncGenerator: () => __asyncGenerator, + __asyncValues: () => __asyncValues, + __await: () => __await, + __awaiter: () => __awaiter, + __classPrivateFieldGet: () => __classPrivateFieldGet, + __classPrivateFieldIn: () => __classPrivateFieldIn, + __classPrivateFieldSet: () => __classPrivateFieldSet, + __createBinding: () => __createBinding, + __decorate: () => __decorate, + __exportStar: () => __exportStar, + __extends: () => __extends, + __generator: () => __generator, + __importDefault: () => __importDefault, + __importStar: () => __importStar, + __makeTemplateObject: () => __makeTemplateObject, + __metadata: () => __metadata, + __param: () => __param, + __read: () => __read, + __rest: () => __rest, + __spread: () => __spread, + __spreadArray: () => __spreadArray, + __spreadArrays: () => __spreadArrays, + __values: () => __values +}); +function __extends(d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +} +function __rest(s, e) { + var t = {}; + for (var p in s) + if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) + t[p[i]] = s[p[i]]; + } + return t; +} +function __decorate(decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") + r = Reflect.decorate(decorators, target, key, desc); + else + for (var i = decorators.length - 1; i >= 0; i--) + if (d = decorators[i]) + r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; +} +function __param(paramIndex, decorator) { + return function(target, key) { + decorator(target, key, paramIndex); + }; +} +function __metadata(metadataKey, metadataValue) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") + return Reflect.metadata(metadataKey, metadataValue); +} +function __awaiter(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function(resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +} +function __generator(thisArg, body) { + var _ = { label: 0, sent: function() { + if (t[0] & 1) + throw t[1]; + return t[1]; + }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { + return this; + }), g; + function verb(n) { + return function(v) { + return step([n, v]); + }; + } + function step(op) { + if (f) + throw new TypeError("Generator is already executing."); + while (g && (g = 0, op[0] && (_ = 0)), _) + try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) + return t; + if (y = 0, t) + op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: + case 1: + t = op; + break; + case 4: + _.label++; + return { value: op[1], done: false }; + case 5: + _.label++; + y = op[1]; + op = [0]; + continue; + case 7: + op = _.ops.pop(); + _.trys.pop(); + continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { + _ = 0; + continue; + } + if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) { + _.label = op[1]; + break; + } + if (op[0] === 6 && _.label < t[1]) { + _.label = t[1]; + t = op; + break; + } + if (t && _.label < t[2]) { + _.label = t[2]; + _.ops.push(op); + break; + } + if (t[2]) + _.ops.pop(); + _.trys.pop(); + continue; + } + op = body.call(thisArg, _); + } catch (e) { + op = [6, e]; + y = 0; + } finally { + f = t = 0; + } + if (op[0] & 5) + throw op[1]; + return { value: op[0] ? op[1] : void 0, done: true }; + } +} +function __exportStar(m, o) { + for (var p in m) + if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) + __createBinding(o, m, p); +} +function __values(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) + return m.call(o); + if (o && typeof o.length === "number") + return { + next: function() { + if (o && i >= o.length) + o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); +} +function __read(o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) + return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) + ar.push(r.value); + } catch (error) { + e = { error }; + } finally { + try { + if (r && !r.done && (m = i["return"])) + m.call(i); + } finally { + if (e) + throw e.error; + } + } + return ar; +} +function __spread() { + for (var ar = [], i = 0; i < arguments.length; i++) + ar = ar.concat(__read(arguments[i])); + return ar; +} +function __spreadArrays() { + for (var s = 0, i = 0, il = arguments.length; i < il; i++) + s += arguments[i].length; + for (var r = Array(s), k = 0, i = 0; i < il; i++) + for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) + r[k] = a[j]; + return r; +} +function __spreadArray(to, from, pack) { + if (pack || arguments.length === 2) + for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) + ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; + } + } + return to.concat(ar || Array.prototype.slice.call(from)); +} +function __await(v) { + return this instanceof __await ? (this.v = v, this) : new __await(v); +} +function __asyncGenerator(thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) + throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() { + return this; + }, i; + function verb(n) { + if (g[n]) + i[n] = function(v) { + return new Promise(function(a, b) { + q.push([n, v, a, b]) > 1 || resume(n, v); + }); + }; + } + function resume(n, v) { + try { + step(g[n](v)); + } catch (e) { + settle(q[0][3], e); + } + } + function step(r) { + r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); + } + function fulfill(value) { + resume("next", value); + } + function reject(value) { + resume("throw", value); + } + function settle(f, v) { + if (f(v), q.shift(), q.length) + resume(q[0][0], q[0][1]); + } +} +function __asyncDelegator(o) { + var i, p; + return i = {}, verb("next"), verb("throw", function(e) { + throw e; + }), verb("return"), i[Symbol.iterator] = function() { + return this; + }, i; + function verb(n, f) { + i[n] = o[n] ? function(v) { + return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; + } : f; + } +} +function __asyncValues(o) { + if (!Symbol.asyncIterator) + throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() { + return this; + }, i); + function verb(n) { + i[n] = o[n] && function(v) { + return new Promise(function(resolve, reject) { + v = o[n](v), settle(resolve, reject, v.done, v.value); + }); + }; + } + function settle(resolve, reject, d, v) { + Promise.resolve(v).then(function(v2) { + resolve({ value: v2, done: d }); + }, reject); + } +} +function __makeTemplateObject(cooked, raw) { + if (Object.defineProperty) { + Object.defineProperty(cooked, "raw", { value: raw }); + } else { + cooked.raw = raw; + } + return cooked; +} +function __importStar(mod) { + if (mod && mod.__esModule) + return mod; + var result = {}; + if (mod != null) { + for (var k in mod) + if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) + __createBinding(result, mod, k); + } + __setModuleDefault(result, mod); + return result; +} +function __importDefault(mod) { + return mod && mod.__esModule ? mod : { default: mod }; +} +function __classPrivateFieldGet(receiver, state, kind, f) { + if (kind === "a" && !f) + throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) + throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +} +function __classPrivateFieldSet(receiver, state, value, kind, f) { + if (kind === "m") + throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) + throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) + throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value; +} +function __classPrivateFieldIn(state, receiver) { + if (receiver === null || typeof receiver !== "object" && typeof receiver !== "function") + throw new TypeError("Cannot use 'in' operator on non-object"); + return typeof state === "function" ? receiver === state : state.has(receiver); +} +var extendStatics, __assign, __createBinding, __setModuleDefault; +var init_tslib_es6 = __esm({ + "node_modules/tslib/tslib.es6.js"() { + extendStatics = function(d, b) { + extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) { + d2.__proto__ = b2; + } || function(d2, b2) { + for (var p in b2) + if (Object.prototype.hasOwnProperty.call(b2, p)) + d2[p] = b2[p]; + }; + return extendStatics(d, b); + }; + __assign = function() { + __assign = Object.assign || function __assign2(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) + if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); + }; + __createBinding = Object.create ? function(o, m, k, k2) { + if (k2 === void 0) + k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; + } + Object.defineProperty(o, k2, desc); + } : function(o, m, k, k2) { + if (k2 === void 0) + k2 = k; + o[k2] = m[k]; + }; + __setModuleDefault = Object.create ? function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + } : function(o, v) { + o["default"] = v; + }; + } +}); + +// node_modules/proxy-chain/dist/request_error.js +var require_request_error = __commonJS({ + "node_modules/proxy-chain/dist/request_error.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.RequestError = void 0; + var RequestError = class extends Error { + constructor(message, statusCode, headers) { + super(message); + Object.defineProperty(this, "statusCode", { + enumerable: true, + configurable: true, + writable: true, + value: statusCode + }); + Object.defineProperty(this, "headers", { + enumerable: true, + configurable: true, + writable: true, + value: headers + }); + this.name = RequestError.name; + Error.captureStackTrace(this, RequestError); + } + }; + exports.RequestError = RequestError; + } +}); + +// node_modules/proxy-chain/dist/utils/parse_authorization_header.js +var require_parse_authorization_header = __commonJS({ + "node_modules/proxy-chain/dist/utils/parse_authorization_header.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.parseAuthorizationHeader = void 0; + var buffer_1 = require("buffer"); + var splitAt = (string, index) => { + return [ + index === -1 ? "" : string.substring(0, index), + index === -1 ? "" : string.substring(index + 1) + ]; + }; + var parseAuthorizationHeader = (header) => { + if (header) { + header = header.trim(); + } + if (!header) { + return null; + } + const [type, data] = splitAt(header, header.indexOf(" ")); + if (type.toLowerCase() !== "basic") { + return { type, data }; + } + const auth = buffer_1.Buffer.from(data, "base64").toString(); + const [username, password] = auth.includes(":") ? splitAt(auth, auth.indexOf(":")) : [auth, ""]; + return { + type, + data, + username, + password + }; + }; + exports.parseAuthorizationHeader = parseAuthorizationHeader; + } +}); + +// node_modules/proxy-chain/dist/utils/redact_url.js +var require_redact_url = __commonJS({ + "node_modules/proxy-chain/dist/utils/redact_url.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.redactUrl = void 0; + var url_1 = require("url"); + var redactUrl = (url, passwordReplacement = "") => { + if (typeof url !== "object") { + url = new url_1.URL(url); + } + if (url.password) { + return url.href.replace(`:${url.password}`, `:${passwordReplacement}`); + } + return url.href; + }; + exports.redactUrl = redactUrl; + } +}); + +// node_modules/proxy-chain/dist/utils/nodeify.js +var require_nodeify = __commonJS({ + "node_modules/proxy-chain/dist/utils/nodeify.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.nodeify = void 0; + var nodeify = (promise, callback) => { + if (typeof callback !== "function") + return promise; + promise.then((result) => callback(null, result), callback).catch((error) => { + process.nextTick(() => { + throw error; + }); + }); + return promise; + }; + exports.nodeify = nodeify; + } +}); + +// node_modules/proxy-chain/dist/utils/count_target_bytes.js +var require_count_target_bytes = __commonJS({ + "node_modules/proxy-chain/dist/utils/count_target_bytes.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getTargetStats = exports.countTargetBytes = void 0; + var targetBytesWritten = Symbol("targetBytesWritten"); + var targetBytesRead = Symbol("targetBytesRead"); + var targets = Symbol("targets"); + var calculateTargetStats = Symbol("calculateTargetStats"); + function typeSocket(source) { + } + var countTargetBytes = (source, target) => { + typeSocket(source); + source[targetBytesWritten] = source[targetBytesWritten] || 0; + source[targetBytesRead] = source[targetBytesRead] || 0; + source[targets] = source[targets] || /* @__PURE__ */ new Set(); + source[targets].add(target); + target.once("close", () => { + source[targetBytesWritten] += target.bytesWritten; + source[targetBytesRead] += target.bytesRead; + source[targets].delete(target); + }); + if (!source[calculateTargetStats]) { + source[calculateTargetStats] = () => { + let bytesWritten = source[targetBytesWritten]; + let bytesRead = source[targetBytesRead]; + for (const socket of source[targets]) { + bytesWritten += socket.bytesWritten; + bytesRead += socket.bytesRead; + } + return { + bytesWritten, + bytesRead + }; + }; + } + }; + exports.countTargetBytes = countTargetBytes; + var getTargetStats = (socket) => { + typeSocket(socket); + if (socket[calculateTargetStats]) { + return socket[calculateTargetStats](); + } + return { + bytesWritten: null, + bytesRead: null + }; + }; + exports.getTargetStats = getTargetStats; + } +}); + +// node_modules/proxy-chain/dist/utils/decode_uri_component_safe.js +var require_decode_uri_component_safe = __commonJS({ + "node_modules/proxy-chain/dist/utils/decode_uri_component_safe.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.decodeURIComponentSafe = void 0; + var decodeURIComponentSafe = (encodedURIComponent) => { + try { + return decodeURIComponent(encodedURIComponent); + } catch (e) { + return encodedURIComponent; + } + }; + exports.decodeURIComponentSafe = decodeURIComponentSafe; + } +}); + +// node_modules/proxy-chain/dist/utils/get_basic.js +var require_get_basic = __commonJS({ + "node_modules/proxy-chain/dist/utils/get_basic.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getBasicAuthorizationHeader = void 0; + var decode_uri_component_safe_1 = require_decode_uri_component_safe(); + var getBasicAuthorizationHeader = (url) => { + const username = (0, decode_uri_component_safe_1.decodeURIComponentSafe)(url.username); + const password = (0, decode_uri_component_safe_1.decodeURIComponentSafe)(url.password); + const auth = `${username}:${password}`; + if (username.includes(":")) { + throw new Error("Username contains an invalid colon"); + } + return `Basic ${Buffer.from(auth).toString("base64")}`; + }; + exports.getBasicAuthorizationHeader = getBasicAuthorizationHeader; + } +}); + +// node_modules/proxy-chain/dist/statuses.js +var require_statuses = __commonJS({ + "node_modules/proxy-chain/dist/statuses.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.errorCodeToStatusCode = exports.badGatewayStatusCodes = void 0; + var http_1 = require("http"); + exports.badGatewayStatusCodes = { + TIMEOUT: 504, + NON_200: 590, + STATUS_CODE_OUT_OF_RANGE: 592, + NOT_FOUND: 593, + CONNECTION_REFUSED: 594, + CONNECTION_RESET: 595, + BROKEN_PIPE: 596, + AUTH_FAILED: 597, + GENERIC_ERROR: 599 + }; + http_1.STATUS_CODES["590"] = "Non Successful"; + http_1.STATUS_CODES["592"] = "Status Code Out Of Range"; + http_1.STATUS_CODES["593"] = "Not Found"; + http_1.STATUS_CODES["594"] = "Connection Refused"; + http_1.STATUS_CODES["595"] = "Connection Reset"; + http_1.STATUS_CODES["596"] = "Broken Pipe"; + http_1.STATUS_CODES["597"] = "Auth Failed"; + http_1.STATUS_CODES["599"] = "Upstream Error"; + exports.errorCodeToStatusCode = { + ENOTFOUND: exports.badGatewayStatusCodes.NOT_FOUND, + ECONNREFUSED: exports.badGatewayStatusCodes.CONNECTION_REFUSED, + ECONNRESET: exports.badGatewayStatusCodes.CONNECTION_RESET, + EPIPE: exports.badGatewayStatusCodes.BROKEN_PIPE, + ETIMEDOUT: exports.badGatewayStatusCodes.TIMEOUT + }; + } +}); + +// node_modules/proxy-chain/dist/chain.js +var require_chain = __commonJS({ + "node_modules/proxy-chain/dist/chain.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.chain = void 0; + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + var http_1 = tslib_1.__importDefault(require("http")); + var buffer_1 = require("buffer"); + var count_target_bytes_1 = require_count_target_bytes(); + var get_basic_1 = require_get_basic(); + var statuses_1 = require_statuses(); + var createHttpResponse = (statusCode, statusMessage, message = "") => { + return [ + `HTTP/1.1 ${statusCode} ${statusMessage || http_1.default.STATUS_CODES[statusCode] || "Unknown Status Code"}`, + "Connection: close", + `Date: ${new Date().toUTCString()}`, + `Content-Length: ${buffer_1.Buffer.byteLength(message)}`, + ``, + message + ].join("\r\n"); + }; + var chain = ({ request, sourceSocket, head, handlerOpts, server: server2, isPlain }) => { + if (head && head.length > 0) { + sourceSocket.unshift(head); + } + const { proxyChainId } = sourceSocket; + const { upstreamProxyUrlParsed: proxy } = handlerOpts; + const options = { + method: "CONNECT", + path: request.url, + headers: [ + "host", + request.url + ], + localAddress: handlerOpts.localAddress, + family: handlerOpts.ipFamily, + lookup: handlerOpts.dnsLookup + }; + if (proxy.username || proxy.password) { + options.headers.push("proxy-authorization", (0, get_basic_1.getBasicAuthorizationHeader)(proxy)); + } + const client = http_1.default.request(proxy.origin, options); + client.on("connect", (response, targetSocket, clientHead) => { + (0, count_target_bytes_1.countTargetBytes)(sourceSocket, targetSocket); + if (sourceSocket.readyState !== "open") { + targetSocket.destroy(); + return; + } + targetSocket.on("error", (error) => { + server2.log(proxyChainId, `Chain Destination Socket Error: ${error.stack}`); + sourceSocket.destroy(); + }); + sourceSocket.on("error", (error) => { + server2.log(proxyChainId, `Chain Source Socket Error: ${error.stack}`); + targetSocket.destroy(); + }); + if (response.statusCode !== 200) { + server2.log(proxyChainId, `Failed to authenticate upstream proxy: ${response.statusCode}`); + if (isPlain) { + sourceSocket.end(); + } else { + const { statusCode } = response; + const status = statusCode === 401 || statusCode === 407 ? statuses_1.badGatewayStatusCodes.AUTH_FAILED : statuses_1.badGatewayStatusCodes.NON_200; + sourceSocket.end(createHttpResponse(status, `UPSTREAM${response.statusCode}`)); + } + return; + } + if (clientHead.length > 0) { + targetSocket.unshift(clientHead); + } + server2.emit("tunnelConnectResponded", { + proxyChainId, + response, + socket: targetSocket, + head: clientHead + }); + sourceSocket.write(isPlain ? "" : `HTTP/1.1 200 Connection Established\r +\r +`); + sourceSocket.pipe(targetSocket); + targetSocket.pipe(sourceSocket); + targetSocket.on("close", () => { + sourceSocket.resume(); + if (sourceSocket.writable) { + sourceSocket.end(); + } + }); + sourceSocket.on("close", () => { + targetSocket.resume(); + if (targetSocket.writable) { + targetSocket.end(); + } + }); + }); + client.on("error", (error) => { + var _a, _b; + server2.log(proxyChainId, `Failed to connect to upstream proxy: ${error.stack}`); + if (sourceSocket.readyState === "open") { + if (isPlain) { + sourceSocket.end(); + } else { + const statusCode = (_a = statuses_1.errorCodeToStatusCode[error.code]) !== null && _a !== void 0 ? _a : statuses_1.badGatewayStatusCodes.GENERIC_ERROR; + const response = createHttpResponse(statusCode, (_b = error.code) !== null && _b !== void 0 ? _b : "Upstream Closed Early"); + sourceSocket.end(response); + } + } + }); + sourceSocket.on("error", () => { + client.destroy(); + }); + sourceSocket.on("close", () => { + client.destroy(); + }); + client.end(); + }; + exports.chain = chain; + } +}); + +// node_modules/proxy-chain/dist/utils/is_hop_by_hop_header.js +var require_is_hop_by_hop_header = __commonJS({ + "node_modules/proxy-chain/dist/utils/is_hop_by_hop_header.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.isHopByHopHeader = void 0; + var hopByHopHeaders = [ + "connection", + "keep-alive", + "proxy-authenticate", + "proxy-authorization", + "te", + "trailer", + "transfer-encoding", + "upgrade" + ]; + var isHopByHopHeader = (header) => hopByHopHeaders.includes(header.toLowerCase()); + exports.isHopByHopHeader = isHopByHopHeader; + } +}); + +// node_modules/proxy-chain/dist/utils/valid_headers_only.js +var require_valid_headers_only = __commonJS({ + "node_modules/proxy-chain/dist/utils/valid_headers_only.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validHeadersOnly = void 0; + var http_1 = require("http"); + var is_hop_by_hop_header_1 = require_is_hop_by_hop_header(); + var validHeadersOnly = (rawHeaders) => { + const result = []; + let containsHost = false; + for (let i = 0; i < rawHeaders.length; i += 2) { + const name = rawHeaders[i]; + const value = rawHeaders[i + 1]; + try { + (0, http_1.validateHeaderName)(name); + (0, http_1.validateHeaderValue)(name, value); + } catch (error) { + continue; + } + if ((0, is_hop_by_hop_header_1.isHopByHopHeader)(name)) { + continue; + } + if (name.toLowerCase() === "host") { + if (containsHost) { + continue; + } + containsHost = true; + } + result.push(name, value); + } + return result; + }; + exports.validHeadersOnly = validHeadersOnly; + } +}); + +// node_modules/proxy-chain/dist/forward.js +var require_forward = __commonJS({ + "node_modules/proxy-chain/dist/forward.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.forward = void 0; + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + var http_1 = tslib_1.__importDefault(require("http")); + var https_1 = tslib_1.__importDefault(require("https")); + var stream_1 = tslib_1.__importDefault(require("stream")); + var util_1 = tslib_1.__importDefault(require("util")); + var valid_headers_only_1 = require_valid_headers_only(); + var get_basic_1 = require_get_basic(); + var count_target_bytes_1 = require_count_target_bytes(); + var statuses_1 = require_statuses(); + var pipeline = util_1.default.promisify(stream_1.default.pipeline); + var forward = async (request, response, handlerOpts) => new Promise(async (resolve, reject) => { + const proxy = handlerOpts.upstreamProxyUrlParsed; + const origin = proxy ? proxy.origin : request.url; + const options = { + method: request.method, + headers: (0, valid_headers_only_1.validHeadersOnly)(request.rawHeaders), + insecureHTTPParser: true, + localAddress: handlerOpts.localAddress, + family: handlerOpts.ipFamily, + lookup: handlerOpts.dnsLookup + }; + if (proxy) { + options.path = request.url; + try { + if (proxy.username || proxy.password) { + options.headers.push("proxy-authorization", (0, get_basic_1.getBasicAuthorizationHeader)(proxy)); + } + } catch (error) { + reject(error); + return; + } + } + const fn = origin.startsWith("https:") ? https_1.default.request : http_1.default.request; + const client = fn(origin, options, async (clientResponse) => { + try { + let statusCode = clientResponse.statusCode; + if (statusCode < 100 || statusCode > 999) { + statusCode = statuses_1.badGatewayStatusCodes.STATUS_CODE_OUT_OF_RANGE; + } + if (clientResponse.statusCode === 407) { + reject(new Error("407 Proxy Authentication Required")); + return; + } + response.writeHead(statusCode, clientResponse.statusMessage, (0, valid_headers_only_1.validHeadersOnly)(clientResponse.rawHeaders)); + await pipeline(clientResponse, response); + resolve(); + } catch { + resolve(); + } + }); + client.once("socket", (socket) => { + (0, count_target_bytes_1.countTargetBytes)(request.socket, socket); + }); + request.pipe(client); + client.on("error", (error) => { + var _a; + if (response.headersSent) { + return; + } + const statusCode = (_a = statuses_1.errorCodeToStatusCode[error.code]) !== null && _a !== void 0 ? _a : statuses_1.badGatewayStatusCodes.GENERIC_ERROR; + response.statusCode = !proxy && error.code === "ENOTFOUND" ? 404 : statusCode; + response.setHeader("content-type", "text/plain; charset=utf-8"); + response.end(http_1.default.STATUS_CODES[response.statusCode]); + resolve(); + }); + }); + exports.forward = forward; + } +}); + +// node_modules/proxy-chain/dist/direct.js +var require_direct = __commonJS({ + "node_modules/proxy-chain/dist/direct.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.direct = void 0; + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + var net_1 = tslib_1.__importDefault(require("net")); + var url_1 = require("url"); + var count_target_bytes_1 = require_count_target_bytes(); + var direct = ({ request, sourceSocket, head, server: server2, handlerOpts }) => { + const url = new url_1.URL(`connect://${request.url}`); + if (!url.hostname) { + throw new Error("Missing CONNECT hostname"); + } + if (!url.port) { + throw new Error("Missing CONNECT port"); + } + if (head.length > 0) { + sourceSocket.unshift(head); + } + const options = { + port: Number(url.port), + host: url.hostname, + localAddress: handlerOpts.localAddress, + family: handlerOpts.ipFamily, + lookup: handlerOpts.dnsLookup + }; + if (options.host[0] === "[") { + options.host = options.host.slice(1, -1); + } + const targetSocket = net_1.default.createConnection(options, () => { + try { + sourceSocket.write(`HTTP/1.1 200 Connection Established\r +\r +`); + } catch (error) { + sourceSocket.destroy(error); + } + }); + (0, count_target_bytes_1.countTargetBytes)(sourceSocket, targetSocket); + sourceSocket.pipe(targetSocket); + targetSocket.pipe(sourceSocket); + targetSocket.on("close", () => { + sourceSocket.resume(); + if (sourceSocket.writable) { + sourceSocket.end(); + } + }); + sourceSocket.on("close", () => { + targetSocket.resume(); + if (targetSocket.writable) { + targetSocket.end(); + } + }); + const { proxyChainId } = sourceSocket; + targetSocket.on("error", (error) => { + server2.log(proxyChainId, `Direct Destination Socket Error: ${error.stack}`); + sourceSocket.destroy(); + }); + sourceSocket.on("error", (error) => { + server2.log(proxyChainId, `Direct Source Socket Error: ${error.stack}`); + targetSocket.destroy(); + }); + }; + exports.direct = direct; + } +}); + +// node_modules/proxy-chain/dist/custom_response.js +var require_custom_response = __commonJS({ + "node_modules/proxy-chain/dist/custom_response.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.handleCustomResponse = void 0; + var handleCustomResponse = async (_request, response, handlerOpts) => { + const { customResponseFunction } = handlerOpts; + if (!customResponseFunction) { + throw new Error('The "customResponseFunction" option is required'); + } + const customResponse = await customResponseFunction(); + if (typeof customResponse !== "object" || customResponse === null) { + throw new Error('The user-provided "customResponseFunction" must return an object.'); + } + response.statusCode = customResponse.statusCode || 200; + if (customResponse.headers) { + for (const [key, value] of Object.entries(customResponse.headers)) { + response.setHeader(key, value); + } + } + response.end(customResponse.body, customResponse.encoding); + }; + exports.handleCustomResponse = handleCustomResponse; + } +}); + +// node_modules/proxy-chain/dist/utils/normalize_url_port.js +var require_normalize_url_port = __commonJS({ + "node_modules/proxy-chain/dist/utils/normalize_url_port.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.normalizeUrlPort = void 0; + var mapping = { + "ftp:": 21, + "http:": 80, + "https:": 443, + "ws:": 80, + "wss:": 443 + }; + var normalizeUrlPort = (url) => { + if (url.port) { + return Number(url.port); + } + if (mapping.hasOwnProperty(url.protocol)) { + return mapping[url.protocol]; + } + throw new Error(`Unexpected protocol: ${url.protocol}`); + }; + exports.normalizeUrlPort = normalizeUrlPort; + } +}); + +// node_modules/proxy-chain/dist/custom_connect.js +var require_custom_connect = __commonJS({ + "node_modules/proxy-chain/dist/custom_connect.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.customConnect = void 0; + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + var net_1 = tslib_1.__importDefault(require("net")); + var util_1 = require("util"); + var asyncWrite = (0, util_1.promisify)(net_1.default.Socket.prototype.write); + var customConnect = async (socket, server2) => { + await asyncWrite.call(socket, "HTTP/1.1 200 Connection Established\r\n\r\n"); + server2.emit("connection", socket); + return new Promise((resolve) => { + if (socket.destroyed) { + resolve(); + return; + } + socket.once("close", () => { + resolve(); + }); + }); + }; + exports.customConnect = customConnect; + } +}); + +// node_modules/proxy-chain/dist/server.js +var require_server = __commonJS({ + "node_modules/proxy-chain/dist/server.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Server = void 0; + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + var http_1 = tslib_1.__importDefault(require("http")); + var util_1 = tslib_1.__importDefault(require("util")); + var url_1 = require("url"); + var events_1 = require("events"); + var buffer_1 = require("buffer"); + var parse_authorization_header_1 = require_parse_authorization_header(); + var redact_url_1 = require_redact_url(); + var nodeify_1 = require_nodeify(); + var count_target_bytes_1 = require_count_target_bytes(); + var request_error_1 = require_request_error(); + var chain_1 = require_chain(); + var forward_1 = require_forward(); + var direct_1 = require_direct(); + var custom_response_1 = require_custom_response(); + var normalize_url_port_1 = require_normalize_url_port(); + var statuses_1 = require_statuses(); + var custom_connect_1 = require_custom_connect(); + var DEFAULT_AUTH_REALM = "ProxyChain"; + var DEFAULT_PROXY_SERVER_PORT = 8e3; + var Server = class extends events_1.EventEmitter { + constructor(options = {}) { + super(); + Object.defineProperty(this, "port", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "prepareRequestFunction", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "authRealm", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "verbose", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "server", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "lastHandlerId", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "stats", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "connections", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + if (options.port === void 0 || options.port === null) { + this.port = DEFAULT_PROXY_SERVER_PORT; + } else { + this.port = options.port; + } + this.prepareRequestFunction = options.prepareRequestFunction; + this.authRealm = options.authRealm || DEFAULT_AUTH_REALM; + this.verbose = !!options.verbose; + this.server = http_1.default.createServer(); + this.server.on("clientError", this.onClientError.bind(this)); + this.server.on("request", this.onRequest.bind(this)); + this.server.on("connect", this.onConnect.bind(this)); + this.server.on("connection", this.onConnection.bind(this)); + this.lastHandlerId = 0; + this.stats = { + httpRequestCount: 0, + connectRequestCount: 0 + }; + this.connections = /* @__PURE__ */ new Map(); + } + log(connectionId, str) { + if (this.verbose) { + const logPrefix = connectionId ? `${String(connectionId)} | ` : ""; + console.log(`ProxyServer[${this.port}]: ${logPrefix}${str}`); + } + } + onClientError(err, socket) { + this.log(socket.proxyChainId, `onClientError: ${err}`); + if (err.code === "ECONNRESET" || !socket.writable) { + return; + } + this.sendSocketResponse(socket, 400, {}, "Invalid request"); + } + registerConnection(socket) { + const unique = this.lastHandlerId++; + socket.proxyChainId = unique; + this.connections.set(unique, socket); + socket.on("close", () => { + this.emit("connectionClosed", { + connectionId: unique, + stats: this.getConnectionStats(unique) + }); + this.connections.delete(unique); + }); + } + onConnection(socket) { + if (!socket.remoteAddress) { + socket.destroy(); + return; + } + this.registerConnection(socket); + socket.on("error", (err) => { + if (this.listenerCount("error") === 1) { + this.log(socket.proxyChainId, `Source socket emitted error: ${err.stack || err}`); + } + }); + } + normalizeHandlerError(error) { + if (error.message === "Username contains an invalid colon") { + return new request_error_1.RequestError("Invalid colon in username in upstream proxy credentials", statuses_1.badGatewayStatusCodes.AUTH_FAILED); + } + if (error.message === "407 Proxy Authentication Required") { + return new request_error_1.RequestError("Invalid upstream proxy credentials", statuses_1.badGatewayStatusCodes.AUTH_FAILED); + } + return error; + } + async onRequest(request, response) { + try { + const handlerOpts = await this.prepareRequestHandling(request); + handlerOpts.srcResponse = response; + const { proxyChainId } = request.socket; + if (handlerOpts.customResponseFunction) { + this.log(proxyChainId, "Using HandlerCustomResponse"); + return await (0, custom_response_1.handleCustomResponse)(request, response, handlerOpts); + } + this.log(proxyChainId, "Using forward"); + return await (0, forward_1.forward)(request, response, handlerOpts); + } catch (error) { + this.failRequest(request, this.normalizeHandlerError(error)); + } + } + async onConnect(request, socket, head) { + try { + const handlerOpts = await this.prepareRequestHandling(request); + handlerOpts.srcHead = head; + const data = { request, sourceSocket: socket, head, handlerOpts, server: this, isPlain: false }; + if (handlerOpts.customConnectServer) { + socket.unshift(head); + return await (0, custom_connect_1.customConnect)(socket, handlerOpts.customConnectServer); + } + if (handlerOpts.upstreamProxyUrlParsed) { + this.log(socket.proxyChainId, `Using HandlerTunnelChain => ${request.url}`); + return await (0, chain_1.chain)(data); + } + this.log(socket.proxyChainId, `Using HandlerTunnelDirect => ${request.url}`); + return await (0, direct_1.direct)(data); + } catch (error) { + this.failRequest(request, this.normalizeHandlerError(error)); + } + } + getHandlerOpts(request) { + const handlerOpts = { + server: this, + id: request.socket.proxyChainId, + srcRequest: request, + srcHead: null, + trgParsed: null, + upstreamProxyUrlParsed: null, + isHttp: false, + srcResponse: null, + customResponseFunction: null, + customConnectServer: null + }; + this.log(request.socket.proxyChainId, `!!! Handling ${request.method} ${request.url} HTTP/${request.httpVersion}`); + if (request.method === "CONNECT") { + try { + handlerOpts.trgParsed = new url_1.URL(`connect://${request.url}`); + } catch { + throw new request_error_1.RequestError(`Target "${request.url}" could not be parsed`, 400); + } + if (!handlerOpts.trgParsed.hostname || !handlerOpts.trgParsed.port) { + throw new request_error_1.RequestError(`Target "${request.url}" could not be parsed`, 400); + } + this.stats.connectRequestCount++; + } else { + let parsed; + try { + parsed = new url_1.URL(request.url); + } catch (error) { + throw new request_error_1.RequestError(`Target "${request.url}" could not be parsed`, 400); + } + if (parsed.protocol !== "http:") { + throw new request_error_1.RequestError(`Only HTTP protocol is supported (was ${parsed.protocol})`, 400); + } + handlerOpts.trgParsed = parsed; + handlerOpts.isHttp = true; + this.stats.httpRequestCount++; + } + return handlerOpts; + } + async callPrepareRequestFunction(request, handlerOpts) { + if (this.prepareRequestFunction) { + const funcOpts = { + connectionId: request.socket.proxyChainId, + request, + username: "", + password: "", + hostname: handlerOpts.trgParsed.hostname, + port: (0, normalize_url_port_1.normalizeUrlPort)(handlerOpts.trgParsed), + isHttp: handlerOpts.isHttp + }; + const proxyAuth = request.headers["proxy-authorization"]; + if (proxyAuth) { + const auth = (0, parse_authorization_header_1.parseAuthorizationHeader)(proxyAuth); + if (!auth) { + throw new request_error_1.RequestError('Invalid "Proxy-Authorization" header', 400); + } + if (auth.type.toLowerCase() !== "basic") { + throw new request_error_1.RequestError('The "Proxy-Authorization" header must have the "Basic" type.', 400); + } + funcOpts.username = auth.username; + funcOpts.password = auth.password; + } + const result = await this.prepareRequestFunction(funcOpts); + return result !== null && result !== void 0 ? result : {}; + } + return {}; + } + async prepareRequestHandling(request) { + const handlerOpts = this.getHandlerOpts(request); + const funcResult = await this.callPrepareRequestFunction(request, handlerOpts); + handlerOpts.localAddress = funcResult.localAddress; + handlerOpts.ipFamily = funcResult.ipFamily; + handlerOpts.dnsLookup = funcResult.dnsLookup; + handlerOpts.customConnectServer = funcResult.customConnectServer; + if (funcResult.requestAuthentication) { + throw new request_error_1.RequestError(funcResult.failMsg || "Proxy credentials required.", 407); + } + if (funcResult.upstreamProxyUrl) { + try { + handlerOpts.upstreamProxyUrlParsed = new url_1.URL(funcResult.upstreamProxyUrl); + } catch (error) { + throw new Error(`Invalid "upstreamProxyUrl" provided: ${error} (was "${funcResult.upstreamProxyUrl}"`); + } + if (handlerOpts.upstreamProxyUrlParsed.protocol !== "http:") { + throw new Error(`Invalid "upstreamProxyUrl" provided: URL must have the "http" protocol (was "${funcResult.upstreamProxyUrl}")`); + } + } + const { proxyChainId } = request.socket; + if (funcResult.customResponseFunction) { + this.log(proxyChainId, "Using custom response function"); + handlerOpts.customResponseFunction = funcResult.customResponseFunction; + if (!handlerOpts.isHttp) { + throw new Error('The "customResponseFunction" option can only be used for HTTP requests.'); + } + if (typeof handlerOpts.customResponseFunction !== "function") { + throw new Error('The "customResponseFunction" option must be a function.'); + } + } + if (handlerOpts.upstreamProxyUrlParsed) { + this.log(proxyChainId, `Using upstream proxy ${(0, redact_url_1.redactUrl)(handlerOpts.upstreamProxyUrlParsed)}`); + } + return handlerOpts; + } + failRequest(request, error) { + const { proxyChainId } = request.socket; + if (error.name === "RequestError") { + const typedError = error; + this.log(proxyChainId, `Request failed (status ${typedError.statusCode}): ${error.message}`); + this.sendSocketResponse(request.socket, typedError.statusCode, typedError.headers, error.message); + } else { + this.log(proxyChainId, `Request failed with error: ${error.stack || error}`); + this.sendSocketResponse(request.socket, 500, {}, "Internal error in proxy server"); + this.emit("requestFailed", { error, request }); + } + this.log(proxyChainId, "Closing because request failed with error"); + } + sendSocketResponse(socket, statusCode = 500, caseSensitiveHeaders = {}, message = "") { + try { + const headers = Object.fromEntries(Object.entries(caseSensitiveHeaders).map(([name, value]) => [name.toLowerCase(), value])); + headers.connection = "close"; + headers.date = new Date().toUTCString(); + headers["content-length"] = String(buffer_1.Buffer.byteLength(message)); + headers.server = headers.server || this.authRealm; + headers["content-type"] = headers["content-type"] || "text/plain; charset=utf-8"; + if (statusCode === 407 && !headers["proxy-authenticate"]) { + headers["proxy-authenticate"] = `Basic realm="${this.authRealm}"`; + } + let msg = `HTTP/1.1 ${statusCode} ${http_1.default.STATUS_CODES[statusCode] || "Unknown Status Code"}\r +`; + for (const [key, value] of Object.entries(headers)) { + msg += `${key}: ${value}\r +`; + } + msg += `\r +${message}`; + socket.setTimeout(1e3, () => { + socket.destroy(); + }); + socket.end(msg); + } catch (err) { + this.log(socket.proxyChainId, `Unhandled error in sendResponse(), will be ignored: ${err.stack || err}`); + } + } + listen(callback) { + const promise = new Promise((resolve, reject) => { + const onError = (error) => { + this.log(null, `Listen failed: ${error}`); + removeListeners(); + reject(error); + }; + const onListening = () => { + this.port = this.server.address().port; + this.log(null, "Listening..."); + removeListeners(); + resolve(); + }; + const removeListeners = () => { + this.server.removeListener("error", onError); + this.server.removeListener("listening", onListening); + }; + this.server.on("error", onError); + this.server.on("listening", onListening); + this.server.listen(this.port); + }); + return (0, nodeify_1.nodeify)(promise, callback); + } + getConnectionIds() { + return [...this.connections.keys()]; + } + getConnectionStats(connectionId) { + const socket = this.connections.get(connectionId); + if (!socket) + return void 0; + const targetStats = (0, count_target_bytes_1.getTargetStats)(socket); + const result = { + srcTxBytes: socket.bytesWritten, + srcRxBytes: socket.bytesRead, + trgTxBytes: targetStats.bytesWritten, + trgRxBytes: targetStats.bytesRead + }; + return result; + } + closeConnection(connectionId) { + this.log(null, "Closing pending socket"); + const socket = this.connections.get(connectionId); + if (!socket) + return; + socket.destroy(); + this.log(null, `Destroyed pending socket`); + } + closeConnections() { + this.log(null, "Closing pending sockets"); + for (const socket of this.connections.values()) { + socket.destroy(); + } + this.connections.clear(); + this.log(null, `Destroyed ${this.connections.size} pending sockets`); + } + close(closeConnections, callback) { + if (typeof closeConnections === "function") { + callback = closeConnections; + closeConnections = false; + } + if (closeConnections) { + this.closeConnections(); + } + if (this.server) { + const { server: server2 } = this; + this.server = null; + const promise = util_1.default.promisify(server2.close).bind(server2)(); + return (0, nodeify_1.nodeify)(promise, callback); + } + return (0, nodeify_1.nodeify)(Promise.resolve(), callback); + } + }; + exports.Server = Server; + } +}); + +// node_modules/proxy-chain/dist/anonymize_proxy.js +var require_anonymize_proxy = __commonJS({ + "node_modules/proxy-chain/dist/anonymize_proxy.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.listenConnectAnonymizedProxy = exports.closeAnonymizedProxy = exports.anonymizeProxy = void 0; + var url_1 = require("url"); + var server_1 = require_server(); + var nodeify_1 = require_nodeify(); + var anonymizedProxyUrlToServer = {}; + var anonymizeProxy = (options, callback) => { + let proxyUrl; + let port = 0; + if (typeof options === "string") { + proxyUrl = options; + } else { + proxyUrl = options.url; + port = options.port; + if (port < 0 || port > 65535) { + throw new Error('Invalid "port" option: only values equals or between 0-65535 are valid'); + } + } + const parsedProxyUrl = new url_1.URL(proxyUrl); + if (parsedProxyUrl.protocol !== "http:") { + throw new Error('Invalid "proxyUrl" option: only HTTP proxies are currently supported.'); + } + if (!parsedProxyUrl.username && !parsedProxyUrl.password) { + return (0, nodeify_1.nodeify)(Promise.resolve(proxyUrl), callback); + } + let server2; + const startServer = () => { + return Promise.resolve().then(() => { + server2 = new server_1.Server({ + port, + prepareRequestFunction: () => { + return { + requestAuthentication: false, + upstreamProxyUrl: proxyUrl + }; + } + }); + return server2.listen(); + }); + }; + const promise = startServer().then(() => { + const url = `http://127.0.0.1:${server2.port}`; + anonymizedProxyUrlToServer[url] = server2; + return url; + }); + return (0, nodeify_1.nodeify)(promise, callback); + }; + exports.anonymizeProxy = anonymizeProxy; + var closeAnonymizedProxy = (anonymizedProxyUrl, closeConnections, callback) => { + if (typeof anonymizedProxyUrl !== "string") { + throw new Error('The "anonymizedProxyUrl" parameter must be a string'); + } + const server2 = anonymizedProxyUrlToServer[anonymizedProxyUrl]; + if (!server2) { + return (0, nodeify_1.nodeify)(Promise.resolve(false), callback); + } + delete anonymizedProxyUrlToServer[anonymizedProxyUrl]; + const promise = server2.close(closeConnections).then(() => { + return true; + }); + return (0, nodeify_1.nodeify)(promise, callback); + }; + exports.closeAnonymizedProxy = closeAnonymizedProxy; + var listenConnectAnonymizedProxy = (anonymizedProxyUrl, tunnelConnectRespondedCallback) => { + const server2 = anonymizedProxyUrlToServer[anonymizedProxyUrl]; + if (!server2) { + return false; + } + server2.on("tunnelConnectResponded", ({ response, socket, head }) => { + tunnelConnectRespondedCallback({ response, socket, head }); + }); + return true; + }; + exports.listenConnectAnonymizedProxy = listenConnectAnonymizedProxy; + } +}); + +// node_modules/proxy-chain/dist/tcp_tunnel_tools.js +var require_tcp_tunnel_tools = __commonJS({ + "node_modules/proxy-chain/dist/tcp_tunnel_tools.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.closeTunnel = exports.createTunnel = void 0; + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + var url_1 = require("url"); + var net_1 = tslib_1.__importDefault(require("net")); + var chain_1 = require_chain(); + var nodeify_1 = require_nodeify(); + var runningServers = {}; + var getAddress = (server2) => { + const { address: host, port, family } = server2.address(); + if (family === "IPv6") { + return `[${host}]:${port}`; + } + return `${host}:${port}`; + }; + function createTunnel(proxyUrl, targetHost, options, callback) { + const parsedProxyUrl = new url_1.URL(proxyUrl); + if (parsedProxyUrl.protocol !== "http:") { + throw new Error(`The proxy URL must have the "http" protocol (was "${proxyUrl}")`); + } + const url = new url_1.URL(`connect://${targetHost || ""}`); + if (!url.hostname) { + throw new Error("Missing target hostname"); + } + if (!url.port) { + throw new Error("Missing target port"); + } + const verbose = options && options.verbose; + const server2 = net_1.default.createServer(); + const log = (...args) => { + if (verbose) + console.log(...args); + }; + server2.log = log; + server2.on("connection", (sourceSocket) => { + const remoteAddress = `${sourceSocket.remoteAddress}:${sourceSocket.remotePort}`; + const { connections } = runningServers[getAddress(server2)]; + log(`new client connection from ${remoteAddress}`); + sourceSocket.on("close", (hadError) => { + connections.delete(sourceSocket); + log(`connection from ${remoteAddress} closed, hadError=${hadError}`); + }); + connections.add(sourceSocket); + (0, chain_1.chain)({ + request: { url: targetHost }, + sourceSocket, + handlerOpts: { upstreamProxyUrlParsed: parsedProxyUrl }, + server: server2, + isPlain: true + }); + }); + const promise = new Promise((resolve, reject) => { + server2.once("error", reject); + server2.listen(0, () => { + const address = getAddress(server2); + server2.off("error", reject); + runningServers[address] = { server: server2, connections: /* @__PURE__ */ new Set() }; + log("server listening to ", address); + resolve(address); + }); + }); + return (0, nodeify_1.nodeify)(promise, callback); + } + exports.createTunnel = createTunnel; + function closeTunnel(serverPath, closeConnections, callback) { + const { hostname, port } = new url_1.URL(`tcp://${serverPath}`); + if (!hostname) + throw new Error("serverPath must contain hostname"); + if (!port) + throw new Error("serverPath must contain port"); + const promise = new Promise((resolve) => { + if (!runningServers[serverPath]) + return resolve(false); + if (!closeConnections) + return resolve(true); + for (const connection of runningServers[serverPath].connections) { + connection.destroy(); + } + resolve(true); + }).then((serverExists) => new Promise((resolve) => { + if (!serverExists) + return resolve(false); + runningServers[serverPath].server.close(() => { + delete runningServers[serverPath]; + resolve(true); + }); + })); + return (0, nodeify_1.nodeify)(promise, callback); + } + exports.closeTunnel = closeTunnel; + } +}); + +// node_modules/proxy-chain/dist/index.js +var require_dist = __commonJS({ + "node_modules/proxy-chain/dist/index.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); + tslib_1.__exportStar(require_request_error(), exports); + tslib_1.__exportStar(require_server(), exports); + tslib_1.__exportStar(require_redact_url(), exports); + tslib_1.__exportStar(require_anonymize_proxy(), exports); + tslib_1.__exportStar(require_tcp_tunnel_tools(), exports); + } +}); + +// node_modules/dotenv/package.json +var require_package = __commonJS({ + "node_modules/dotenv/package.json"(exports, module2) { + module2.exports = { + name: "dotenv", + version: "16.0.3", + description: "Loads environment variables from .env file", + main: "lib/main.js", + types: "lib/main.d.ts", + exports: { + ".": { + require: "./lib/main.js", + types: "./lib/main.d.ts", + default: "./lib/main.js" + }, + "./config": "./config.js", + "./config.js": "./config.js", + "./lib/env-options": "./lib/env-options.js", + "./lib/env-options.js": "./lib/env-options.js", + "./lib/cli-options": "./lib/cli-options.js", + "./lib/cli-options.js": "./lib/cli-options.js", + "./package.json": "./package.json" + }, + scripts: { + "dts-check": "tsc --project tests/types/tsconfig.json", + lint: "standard", + "lint-readme": "standard-markdown", + pretest: "npm run lint && npm run dts-check", + test: "tap tests/*.js --100 -Rspec", + prerelease: "npm test", + release: "standard-version" + }, + repository: { + type: "git", + url: "git://github.com/motdotla/dotenv.git" + }, + keywords: [ + "dotenv", + "env", + ".env", + "environment", + "variables", + "config", + "settings" + ], + readmeFilename: "README.md", + license: "BSD-2-Clause", + devDependencies: { + "@types/node": "^17.0.9", + decache: "^4.6.1", + dtslint: "^3.7.0", + sinon: "^12.0.1", + standard: "^16.0.4", + "standard-markdown": "^7.1.0", + "standard-version": "^9.3.2", + tap: "^15.1.6", + tar: "^6.1.11", + typescript: "^4.5.4" + }, + engines: { + node: ">=12" + } + }; + } +}); + +// node_modules/dotenv/lib/main.js +var require_main = __commonJS({ + "node_modules/dotenv/lib/main.js"(exports, module2) { + var fs = require("fs"); + var path = require("path"); + var os = require("os"); + var packageJson = require_package(); + var version = packageJson.version; + var LINE = /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg; + function parse(src) { + const obj = {}; + let lines = src.toString(); + lines = lines.replace(/\r\n?/mg, "\n"); + let match; + while ((match = LINE.exec(lines)) != null) { + const key = match[1]; + let value = match[2] || ""; + value = value.trim(); + const maybeQuote = value[0]; + value = value.replace(/^(['"`])([\s\S]*)\1$/mg, "$2"); + if (maybeQuote === '"') { + value = value.replace(/\\n/g, "\n"); + value = value.replace(/\\r/g, "\r"); + } + obj[key] = value; + } + return obj; + } + function _log(message) { + console.log(`[dotenv@${version}][DEBUG] ${message}`); + } + function _resolveHome(envPath) { + return envPath[0] === "~" ? path.join(os.homedir(), envPath.slice(1)) : envPath; + } + function config2(options) { + let dotenvPath = path.resolve(process.cwd(), ".env"); + let encoding = "utf8"; + const debug = Boolean(options && options.debug); + const override = Boolean(options && options.override); + if (options) { + if (options.path != null) { + dotenvPath = _resolveHome(options.path); + } + if (options.encoding != null) { + encoding = options.encoding; + } + } + try { + const parsed = DotenvModule.parse(fs.readFileSync(dotenvPath, { encoding })); + Object.keys(parsed).forEach(function(key) { + if (!Object.prototype.hasOwnProperty.call(process.env, key)) { + process.env[key] = parsed[key]; + } else { + if (override === true) { + process.env[key] = parsed[key]; + } + if (debug) { + if (override === true) { + _log(`"${key}" is already defined in \`process.env\` and WAS overwritten`); + } else { + _log(`"${key}" is already defined in \`process.env\` and was NOT overwritten`); + } + } + } + }); + return { parsed }; + } catch (e) { + if (debug) { + _log(`Failed to load ${dotenvPath} ${e.message}`); + } + return { error: e }; + } + } + var DotenvModule = { + config: config2, + parse + }; + module2.exports.config = DotenvModule.config; + module2.exports.parse = DotenvModule.parse; + module2.exports = DotenvModule; + } +}); + +// server.js +var ProxyChain = require_dist(); +require_main().config(); +var config = { + port: process.env.PORT || 1488, + login: process.env.LOGIN || "username", + password: process.env.PASSWORD || "password" +}; +var server = new ProxyChain.Server({ + port: config.port, + verbose: true, + prepareRequestFunction: ({ request, username, password, hostname, port, isHttp, connectionId }) => { + return { + requestAuthentication: username !== config.login || password !== config.password, + failMsg: "Bad username or password, please try again." + }; + } +}); +server.listen(() => { + console.log(`Proxy server is listening on port ${server.port}`); +}); +server.on("connectionClosed", ({ connectionId, stats }) => { + console.log(`Connection ${connectionId} closed`); + console.dir(stats); +}); +server.on("requestFailed", ({ request, error }) => { + console.log(`Request ${request.url} failed`); + console.error(error); +});