"use strict";
// shamelessly stolem from https://github.com/y-mehta/ssrf-req-filter
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ssrfFilter = void 0;
const https_1 = __importDefault(require("https"));
const http_1 = __importDefault(require("http"));
const ipaddr_js_1 = __importDefault(require("ipaddr.js"));
function checkIp(ip) {
    if (!ipaddr_js_1.default.isValid(ip)) {
        return true;
    }
    try {
        const addr = ipaddr_js_1.default.parse(ip);
        const range = addr.range();
        if (range !== "unicast") {
            return false; // Private IP Range
        }
    }
    catch (err) {
        return false;
    }
    return true;
}
function ssrfFilter(url) {
    const agent = url.protocol === "https:" ? new https_1.default.Agent() : new http_1.default.Agent();
    const oldCreateConnection = agent.createConnection;
    agent.createConnection = function (options, func) {
        const { host: address } = options;
        if (!checkIp(address)) {
            throw new Error(`Call to ${address} is blocked.`);
        }
        const socket = oldCreateConnection.call(this, options, func);
        socket.on("lookup", (error, address) => {
            if (error || checkIp(address)) {
                return false;
            }
            return socket.destroy(new Error(`Call to ${address} is blocked.`));
        });
        return socket;
    };
    return agent;
}
exports.ssrfFilter = ssrfFilter;
//# sourceMappingURL=ssrf-filter.js.map