From f1c37280cabaf5fbaf8e4b633ed85da41a90b8f7 Mon Sep 17 00:00:00 2001 From: Emmanuel Isenah <86387828+Armadillidiid@users.noreply.github.com> Date: Tue, 9 Apr 2024 08:54:27 +0100 Subject: [PATCH] fix: update subdomain computation in getDomainAndSubdomain function The getDomainAndSubdomain function previously incorrectly computed the subdomain for domain names with multiple subdomains. This commit fixes the computation by properly iterating over the domain parts to extract the subdomain. Additionally, it adds a trailing dot to the parent domain for canonicalization. --- aws-ts-static-website/index.ts | 45 +++++++++++++++++++++------------- 1 file changed, 28 insertions(+), 17 deletions(-) diff --git a/aws-ts-static-website/index.ts b/aws-ts-static-website/index.ts index 394956641..4fbb6d759 100644 --- a/aws-ts-static-website/index.ts +++ b/aws-ts-static-website/index.ts @@ -233,24 +233,35 @@ const distributionArgs: aws.cloudfront.DistributionArgs = { const cdn = new aws.cloudfront.Distribution("cdn", distributionArgs); // Split a domain name into its subdomain and parent domain names. +// e.g "example.com" => "", "example.com". // e.g. "www.example.com" => "www", "example.com". -function getDomainAndSubdomain(domain: string): { subdomain: string, parentDomain: string } { - const parts = domain.split("."); - if (parts.length < 2) { - throw new Error(`No TLD found on ${domain}`); - } - // No subdomain, e.g. awesome-website.com. - if (parts.length === 2) { - return { subdomain: "", parentDomain: domain }; - } - - const subdomain = parts[0]; - parts.shift(); // Drop first element. - return { - subdomain, - // Trailing "." to canonicalize domain. - parentDomain: parts.join(".") + ".", - }; +// e.g. "subdomain.subdomain.example.com" => "subdomain.subdomain", "example.com". +function getDomainAndSubdomain(domain: string): { + subdomain: string; + parentDomain: string; +} { + const parts = domain.split("."); + if (parts.length < 2) { + throw new Error(`No TLD found on ${domain}`); + } + // No subdomain, e.g. example.com. + if (parts.length === 2) { + return { subdomain: "", parentDomain: domain }; + } + + let subdomain = ""; + for (let i = 0; i < parts.length - 2; i++) { + subdomain += parts[i] + "."; + } + subdomain = subdomain.slice(0, -1); // Remove trailing dot + + const parentDomain = parts.slice(-2).join("."); + + return { + subdomain, + // Add trailing "." to canonicalize domain. + parentDomain: parentDomain + ".", + }; } // Creates a new Route53 DNS record pointing the domain to the CloudFront distribution.