Extracts domain from URL

by neonDog

JavaScript

const getRegDomain = (h) => {
    if (!h) return '';
    const parts = h.split('.');
    if (parts.length <= 2) return h;
    return parts.slice(-2).join('.');
};

/**
 * Build site-specific headers (Origin, Referer, sec-fetch-site and small defaults)
 * - url: destination URL
 * - originUrl: optional origin URL (used to compute sec-fetch-site and set Origin for non-GET/HEAD)
 * - options: the options object passed to fetchWithProxy (used to check caller headers)
 *
 * Returns an object of headers to merge into options.headers (caller headers take precedence).
 */
function makeSecFetchSiteHeader(url, originUrl) {
    let out = 'none';

    try {
        const parsedUrl = new URL(url);
        const hostname = parsedUrl.hostname;

        if (originUrl) {
            try {
                const o = new URL(originUrl);
                const originHost = o.hostname;
                const originOrigin = o.origin;
                if (originOrigin === parsedUrl.origin) {
                    out = 'same-origin';
                } else if (getRegDomain(originHost) === getRegDomain(hostname)) {
                    out = 'same-site';
                } else {
                    out = 'cross-site';
                }

            } catch (e) {
                // ignore
            }
        }

    } catch (e) {
        // ignore
    }

    return out;
}

function makeSecUserAgentHeader(userAgent) {
    // Simplistic parsing of User-Agent to build a sec-ch-ua header
    // Example input:
    // Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36
    const match = userAgent.match(/(Chromium|Not=A?Brand|Google Chrome)\/(\d+\.\d+\.\d+\.\d+)/);
    if (match) {
        return `"${match[1]}";v="${match[2]}"`;
    }
    return false;
}

let r = makeSecUserAgentHeader('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0...