diff --git a/reverse_engineering/helpers/escapeV6IpForURL.js b/reverse_engineering/helpers/escapeV6IpForURL.js index f5c2ac9..ecb5ae3 100644 --- a/reverse_engineering/helpers/escapeV6IpForURL.js +++ b/reverse_engineering/helpers/escapeV6IpForURL.js @@ -16,13 +16,13 @@ const ip = require('ip'); */ function escapeV6IpForURL({ host }) { /** - * If the host is already URL compatible then the ip lib will return false > ip.isV6Format('[::1]') false If the host - * is a proper ipv6 ip then the `new URL(host)` will fail with Uncaught TypeError: Invalid URL code: - * 'ERR_INVALID_URL', !ip.isV4Format(host) check required because isV6Format returns true for ipv4 address because of - * backward compatibility + * If the host is already URL compatible then the ip lib will return false > ip.isV6Format('[::1]') false If the + * host is a proper ipv6 ip then the `new URL(host)` will fail with Uncaught TypeError: Invalid URL code: + * 'ERR_INVALID_URL', !ip.isV4Format(host) check required because isV6Format returns true for ipv4 address because + * of backward compatibility */ if (ip.isV6Format(host) && !ip.isV4Format(host)) { - return `[${host}]`; + return escapeHost(host); } const isUrlValid = isValidURL(host); @@ -42,7 +42,20 @@ function escapeV6IpForURL({ host }) { const port = separatedIpPortionsAndPort.at(-1); const escapedIpWithPort = `[${ipPortions.join(':')}]:${port}`; - return host.replace(unescapedIpWithPort, escapedIpWithPort); + const hostWithEscapedAllPortionsButTheLastOne = host.replace(unescapedIpWithPort, escapedIpWithPort); + if (isValidURL(hostWithEscapedAllPortionsButTheLastOne)) { + return hostWithEscapedAllPortionsButTheLastOne; + } + + return host.replace(unescapedIpWithPort, escapeHost(unescapedIpWithPort)); +} + +/** + * @param {string} host + * @returns {string} + */ +function escapeHost(host) { + return `[${host}]`; } /**