"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.getLocalAddressInfo = getLocalAddressInfo;
exports.checkHostResolution = checkHostResolution;
exports.wildcardProbeHost = wildcardProbeHost;
exports.checkDomainResolvesToThisMachine = checkDomainResolvesToThisMachine;
const dns_1 = require("dns");
const net = __importStar(require("net"));
const os = __importStar(require("os"));
function stripIpv6Scope(address) {
    return address.split('%')[0];
}
function normalizeIpv4Mapped(address) {
    const lower = address.toLowerCase();
    if (lower.startsWith('::ffff:')) {
        return lower.slice('::ffff:'.length);
    }
    return lower;
}
function normalizeAddress(address) {
    return normalizeIpv4Mapped(stripIpv6Scope(address).trim());
}
function getLocalAddressInfo() {
    const addresses = new Set(['127.0.0.1', '::1']);
    let hasExternalIpv6 = false;
    for (const entries of Object.values(os.networkInterfaces())) {
        for (const entry of entries ?? []) {
            const normalized = normalizeAddress(entry.address);
            if (normalized && net.isIP(normalized)) {
                addresses.add(normalized);
            }
            if (entry.family === 'IPv6' && !entry.internal) {
                hasExternalIpv6 = true;
            }
        }
    }
    return {
        addresses: [...addresses],
        hasExternalIpv6
    };
}
function checkHostResolution(host, resolved, localInfo) {
    const localAddresses = new Set(localInfo.addresses.map(normalizeAddress));
    const matched = resolved.filter((record) => localAddresses.has(normalizeAddress(record.address)));
    const ipv4Resolved = resolved.filter((record) => record.family === 4);
    const ipv6Resolved = resolved.filter((record) => record.family === 6);
    const ipv4Matched = matched.some((record) => record.family === 4);
    const ipv6Matched = matched.some((record) => record.family === 6);
    const warnings = [];
    const errors = [];
    if (resolved.length === 0) {
        errors.push(`${host} did not resolve to any A or AAAA records.`);
    }
    if (ipv6Resolved.length > 0 && !localInfo.hasExternalIpv6 && !ipv6Matched) {
        warnings.push(`${host} has IPv6 records, but this machine does not appear to have external IPv6 enabled.`);
    }
    if (matched.length === 0) {
        errors.push(`${host} does not resolve to 127.0.0.1, ::1, or any local network interface address.`);
    }
    else if (ipv4Matched && ipv6Resolved.length > 0 && !ipv6Matched) {
        warnings.push(`${host} resolves to this machine over IPv4, but its IPv6 records do not match this machine.`);
    }
    else if (ipv6Matched && ipv4Resolved.length > 0 && !ipv4Matched) {
        warnings.push(`${host} resolves to this machine over IPv6, but its IPv4 records do not match this machine.`);
    }
    const status = errors.length > 0 ? 'fail' : warnings.length > 0 ? 'warn' : 'pass';
    return {
        host,
        resolved,
        matched,
        warnings,
        errors,
        status
    };
}
function wildcardProbeHost(domain) {
    return `runestone-wildcard-check.${domain.trim()}`;
}
async function checkDomainResolvesToThisMachine(domain) {
    const normalizedDomain = domain.trim();
    const localInfo = getLocalAddressInfo();
    const probeHost = wildcardProbeHost(normalizedDomain);
    const hosts = [probeHost];
    const checkedHosts = [];
    for (const host of hosts) {
        try {
            const resolved = await dns_1.promises.lookup(host, { all: true, verbatim: true });
            checkedHosts.push(checkHostResolution(host, resolved, localInfo));
        }
        catch (error) {
            const message = error instanceof Error ? error.message : String(error);
            checkedHosts.push({
                host,
                resolved: [],
                matched: [],
                warnings: [],
                errors: [`${host} could not be resolved: ${message}`],
                status: 'fail'
            });
        }
    }
    const status = checkedHosts.some((host) => host.status === 'fail')
        ? 'fail'
        : checkedHosts.some((host) => host.status === 'warn')
            ? 'warn'
            : 'pass';
    return {
        domain: normalizedDomain,
        wildcardProbeHost: probeHost,
        checkedHosts,
        localAddresses: localInfo.addresses,
        hasExternalIpv6: localInfo.hasExternalIpv6,
        status
    };
}
//# sourceMappingURL=domain-checker.js.map