"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.DevConsoleLocalhostMiddleware = void 0;
exports.isLocalhostHttpRequest = isLocalhostHttpRequest;
exports.isLocalhostIncomingMessage = isLocalhostIncomingMessage;
const tslib_1 = require("tslib");
const _a = tslib_1.__importStar(require("@zyno-io/ts-server-foundation/type-metadata-runtime"));
const http_1 = require("../http");
const __tsf_metadata_type = _a.createCompactMetadataRegistryV1("[1,[{\"kind\":3}]]", []);
const LOCAL_ADDRESSES = new Set(['127.0.0.1', '::1', '::ffff:127.0.0.1', 'localhost']);
const FORWARDED_HEADERS = ['forwarded', 'x-forwarded-for', 'x-forwarded-host', 'x-forwarded-proto', 'x-real-ip'];
let _DevConsoleLocalhostMiddlewareMetadata_1;
class DevConsoleLocalhostMiddleware {
    handle(request, _response) {
        if (!isLocalhostHttpRequest(request))
            throw new http_1.HttpUnauthorizedError('DevConsole is only available from direct localhost requests');
    }
    static __tsfType = _DevConsoleLocalhostMiddlewareMetadata_1 = _a.decodeCompactMetadataV1("[1,{\"kind\":16,\"name\":\"DevConsoleLocalhostMiddleware\",\"typeName\":\"DevConsoleLocalhostMiddleware\",\"classType\":{\"$tsf\":0},\"properties\":[],\"methods\":[{\"name\":\"handle\",\"parameters\":[{\"name\":\"request\",\"type\":{\"kind\":16,\"typeName\":\"HttpRequest\",\"classType\":{\"$tsfImport\":[1,\"../http/index\",\"HttpRequest\"]}},\"optional\":false,\"default\":false},{\"name\":\"_response\",\"type\":{\"kind\":16,\"typeName\":\"HttpResponse\",\"classType\":{\"$tsfImport\":[1,\"../http/index\",\"HttpResponse\"]}},\"optional\":false,\"default\":false}],\"returnType\":{\"$tsfType\":0}}],\"hasConstructor\":false,\"constructorParameters\":[]}]", [() => DevConsoleLocalhostMiddleware, require], __tsf_metadata_type);
}
exports.DevConsoleLocalhostMiddleware = DevConsoleLocalhostMiddleware;
_DevConsoleLocalhostMiddlewareMetadata_1.classType = DevConsoleLocalhostMiddleware;
DevConsoleLocalhostMiddleware.__tsfType = _DevConsoleLocalhostMiddlewareMetadata_1;
function isLocalhostHttpRequest(request) {
    if (FORWARDED_HEADERS.some(header => request.headers[header] !== undefined))
        return false;
    return isLocalAddress(request.remoteAddress);
}
function isLocalhostIncomingMessage(request) {
    if (FORWARDED_HEADERS.some(header => request.headers[header] !== undefined))
        return false;
    return isLocalAddress(request.socket.remoteAddress ?? '');
}
function isLocalAddress(address) {
    return LOCAL_ADDRESSES.has(address) || address.endsWith(':127.0.0.1');
}
//# sourceMappingURL=security.js.map