"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) 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 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.RequestFilteringHttpAgent = void 0;
exports.isForbiddenHost = isForbiddenHost;
exports.isForbiddenHeader = isForbiddenHeader;
exports.isPrivateAddress = isPrivateAddress;
const rangeCheck = __importStar(require("range_check"));
const RequestSecurityError_1 = require("./RequestSecurityError");
const MablHttpAgent_1 = require("./MablHttpAgent");
const FORBIDDEN_HOSTS = new Set(['metadata.google.internal']);
const FORBIDDEN_IP_RANGES = ['169.254.169.254/32'];
const FORBIDDEN_HEADERS = {
    'metadata-flavor': 'google',
    'x-google-metadata-request': undefined,
};
const FORBIDDEN_HEADER_NAMES = Object.keys(FORBIDDEN_HEADERS);
const RFC_1918_RANGES = ['10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16'];
const LOCAL_ADDRESSES = new Set(['127.0.0.1', '::1']);
const LOCAL_HOSTS = new Set(['localhost']);
class RequestFilteringHttpAgent extends MablHttpAgent_1.MablHttpAgent {
    constructor(httpAgent, httpsAgent) {
        super(httpAgent, httpsAgent);
    }
    static async createNewInstance(config) {
        const constructorParameters = await MablHttpAgent_1.MablHttpAgent.getConstructorParameters(undefined, undefined, config?.cookieJar);
        return new RequestFilteringHttpAgent(constructorParameters.httpAgent, constructorParameters.httpsAgent);
    }
    callback(req, opts) {
        if (isForbiddenHost(opts.host)) {
            return Promise.reject(new RequestSecurityError_1.RequestSecurityError('Request contains forbidden host'));
        }
        else if (containsForbiddenHeader(opts.headers)) {
            return Promise.reject(new RequestSecurityError_1.RequestSecurityError('Request contains forbidden header'));
        }
        else if (isPrivateAddress(opts.host)) {
            return Promise.reject(new RequestSecurityError_1.RequestSecurityError('Request contains private address'));
        }
        return super.callback(req, opts);
    }
}
exports.RequestFilteringHttpAgent = RequestFilteringHttpAgent;
function isForbiddenHost(host) {
    if (!host) {
        return false;
    }
    if (rangeCheck.isIP(host)) {
        return rangeCheck.inRange(host, FORBIDDEN_IP_RANGES);
    }
    const normalizedHost = host.toLowerCase();
    return FORBIDDEN_HOSTS.has(normalizedHost);
}
function containsForbiddenHeader(headers) {
    if (!headers) {
        return false;
    }
    return Object.keys(headers).some((header) => isForbiddenHeader(header, headers[header]));
}
function isForbiddenHeader(headerName, headerValue) {
    const normalizedHeaderName = headerName.toLowerCase().trim();
    if (!FORBIDDEN_HEADER_NAMES.includes(normalizedHeaderName)) {
        return false;
    }
    const forbiddenHeaderValue = FORBIDDEN_HEADERS[normalizedHeaderName];
    if (!forbiddenHeaderValue) {
        return true;
    }
    if (!headerValue) {
        return false;
    }
    const headerValueType = typeof headerValue;
    if (headerValueType === 'string') {
        const normalizedHeaderValue = headerValue.toLowerCase().trim();
        return normalizedHeaderValue == forbiddenHeaderValue;
    }
    else if (headerValueType === 'number') {
        return headerValue == forbiddenHeaderValue;
    }
    else if (Array.isArray(headerValue)) {
        return headerValue.some((value) => isForbiddenHeader(headerName, value));
    }
    return false;
}
function isPrivateAddress(host) {
    if (!host) {
        return false;
    }
    if (rangeCheck.isIP(host)) {
        if (rangeCheck.inRange(host, RFC_1918_RANGES)) {
            return true;
        }
        const normalizedIP = rangeCheck.searchIP(host);
        return LOCAL_ADDRESSES.has(normalizedIP);
    }
    const normalizedHostname = host.toLowerCase();
    return LOCAL_HOSTS.has(normalizedHostname);
}
