UNPKG

@sap-cloud-sdk/connectivity

Version:

SAP Cloud SDK for JavaScript connectivity

47 lines 1.86 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.getIssuerSubdomain = getIssuerSubdomain; exports.replaceSubdomain = replaceSubdomain; const url_1 = require("url"); const util_1 = require("@sap-cloud-sdk/util"); /** * @internal */ function getIssuerSubdomain(decodedJwt, isIasToken = false) { // For IAS tokens, prefer ias_iss claim over standard iss claim const issuer = isIasToken && decodedJwt?.ias_iss ? decodedJwt.ias_iss : decodedJwt?.iss; if (issuer) { if (!(0, util_1.isValidUrl)(issuer)) { throw new Error(`Issuer URL in JWT is not a valid URL: "${issuer}".`); } return getHost(new url_1.URL(issuer)).split('.')[0]; } } function getHost(url) { const { host } = url; if (!host || host.indexOf('.') === -1) { throw new Error(`Failed to determine hostname: invalid host in "${url}".`); } return host; } /** * @internal * Replaces the first part of the hostname (subdomain) in a URL. * @param baseUrl - The URL whose subdomain should be replaced. * @param newSubdomain - The new subdomain to use or a falsy value to remove the subdomain. * @returns The URL with replaced subdomain, with trailing slash removed if present. */ function replaceSubdomain(baseUrl, newSubdomain) { if (!(0, util_1.isValidUrl)(baseUrl)) { throw new Error(`Base URL is not a valid URL: "${baseUrl}".`); } const url = new url_1.URL(baseUrl); const hostParts = getHost(url).split('.'); const subdomainReplacment = newSubdomain ? [newSubdomain] : []; url.hostname = [...subdomainReplacment, ...hostParts.slice(1)].join('.'); let result = url.toString(); // Remove trailing slash for consistency result = (0, util_1.removeTrailingSlashes)(result); return result; } //# sourceMappingURL=subdomain-replacer.js.map