Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

10.6 KB
Raw Blame
"use client";

import { clientAccessCheck } from "@/lib/client-access-check";
import { isAllowedSyncUXOrigin } from "@/lib/domain-connect/allowed-origins";
import {
  DUB_CUSTOM_DOMAIN_A_RECORD,
  DUB_CUSTOM_DOMAIN_CNAME,
} from "@/lib/domain-connect/constants";
import type { DomainConnectDiscovery } from "@/lib/domain-connect/types";
import useWorkspace from "@/lib/swr/use-workspace";
import { DomainVerificationStatusProps } from "@/lib/types";
import { useForwardDnsInstructionsModal } from "@/ui/modals/forward-dns-instructions-modal";
import {
  Button,
  CircleInfo,
  Cloudflare,
  CopyButton,
  TabSelect,
  Vercel,
} from "@dub/ui";
import { EnvelopeArrowRight } from "@dub/ui/icons";
import { cn, getSubdomain } from "@dub/utils";
import { usePathname } from "next/navigation";
import { Fragment, useState } from "react";
import { toast } from "sonner";

export default function DomainConfiguration({
  data,
  domainConnect,
  domain,
  workspaceId,
  workspaceSlug,
}: {
  data: { status: DomainVerificationStatusProps; response: any };
  domainConnect?: DomainConnectDiscovery | null;
  domain?: string;
  workspaceId?: string;
  workspaceSlug?: string;
}) {
  const pathname = usePathname();
  const { role } = useWorkspace();
  const { domainJson, configJson } = data.response;
  const subdomain = getSubdomain(domainJson.name, domainJson.apexName);
  const [recordType, setRecordType] = useState<"A" | "CNAME">(
    !!subdomain ? "CNAME" : "A",
  );
  const [autoLoading, setAutoLoading] = useState(false);

  const { error: permissionsError } = clientAccessCheck({
    action: "domains.write",
    role,
  });

  const { ForwardDnsInstructionsModal, setShowForwardDnsModal } =
    useForwardDnsInstructionsModal({
      domain: domain ?? "",
      recordType,
      workspaceId: workspaceId ?? "",
      endpoint:
        domain && workspaceId
          ? `/api/domains/${encodeURIComponent(domain)}/forward-instructions?workspaceId=${workspaceId}`
          : "",
    });

  const handleAutoConfigure = async () => {
    if (!domain || !workspaceId) return;
    setAutoLoading(true);
    try {
      const res = await fetch(
        `/api/domains/${encodeURIComponent(domain)}/domain-connect/apply?workspaceId=${workspaceId}`,
        {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            returnTo: pathname ?? `/${workspaceSlug}/settings/domains`,
          }),
        },
      );
      const json = await res.json().catch(() => ({}));
      if (!res.ok) {
        toast.error(json?.error?.message ?? "Could not start auto configure.");
        return;
      }
      if (json?.applyUrl) {
        if (!isAllowedSyncUXOrigin(json.applyUrl as string)) {
          toast.error("Invalid redirect URL from server.");
          return;
        }
        window.location.assign(json.applyUrl as string);
        return;
      }
      toast.error("Could not start auto configure.");
    } catch {
      toast.error("Could not start auto configure.");
    } finally {
      setAutoLoading(false);
    }
  };

  if (data.status === "Conflicting DNS Records") {
    return (
      <div className="pt-5">
        <div className="flex justify-start space-x-4">
          <div className="ease border-b-2 border-black pb-1 text-sm text-black transition-all duration-150">
            {configJson?.conflicts.some((x: { type: string }) => x.type === "A")
              ? "A Record (recommended)"
              : "CNAME Record (recommended)"}
          </div>
        </div>
        <DnsRecord
          instructions="Please remove the following conflicting DNS records from your DNS provider:"
          records={configJson?.conflicts.map(
            ({
              name,
              type,
              value,
            }: {
              name: string;
              type: string;
              value: string;
            }) => ({
              name,
              type,
              value,
            }),
          )}
        />
        <DnsRecord
          instructions="Afterwards, set the following record on your DNS provider:"
          records={[
            {
              type: recordType,
              name: recordType === "A" ? "@" : subdomain ?? "www",
              value:
                recordType === "A"
                  ? DUB_CUSTOM_DOMAIN_A_RECORD
                  : DUB_CUSTOM_DOMAIN_CNAME,
              ttl: "86400",
            },
          ]}
        />
      </div>
    );
  }

  if (data.status === "Unknown Error") {
    return (
      <div className="pt-5">
        <p className="mb-5 text-sm">{data.response.domainJson.error.message}</p>
      </div>
    );
  }

  const txtVerification =
    data.status === "Pending Verification"
      ? domainJson.verification.find((x: any) => x.type === "TXT")
      : undefined;

  const providerLabel =
    domainConnect?.providerKind === "cloudflare" ? "Cloudflare" : "Vercel";
  const ProviderIcon =
    domainConnect?.providerKind === "cloudflare" ? Cloudflare : Vercel;

  return (
    <div className="pt-2">
      <div className="-ml-1.5 border-b border-neutral-200">
        <TabSelect
          options={[
            { id: "A", label: `A Record${!subdomain ? " (recommended)" : ""}` },
            {
              id: "CNAME",
              label: `CNAME Record${subdomain ? " (recommended)" : ""}`,
            },
          ]}
          selected={recordType}
          onSelect={setRecordType}
        />
      </div>

      <DnsRecord
        instructions={`To configure your ${
          recordType === "A" ? "apex domain" : "subdomain"
        } <code>${
          recordType === "A" ? domainJson.apexName : domainJson.name
        }</code>, set the following ${txtVerification ? "records" : `${recordType} record`} on your DNS provider:`}
        records={[
          {
            type: recordType,
            name: recordType === "A" ? "@" : subdomain ?? "www",
            value:
              recordType === "A"
                ? DUB_CUSTOM_DOMAIN_A_RECORD
                : DUB_CUSTOM_DOMAIN_CNAME,
            ttl: "86400",
          },
          ...(txtVerification
            ? [
                {
                  type: txtVerification.type,
                  name: txtVerification.domain.slice(
                    0,
                    txtVerification.domain.length -
                      domainJson.apexName.length -
                      1,
                  ),
                  value: txtVerification.value,
                },
              ]
            : []),
        ]}
        warning={
          txtVerification
            ? "Warning: if you are using this domain for another site, setting this TXT record will transfer domain ownership away from that site and break it. Please exercise caution when setting this record; make sure that the domain that is shown in the TXT verification value is actually the <b><i>domain you want to use on Dub</i></b> – <b><i>not your production site</i></b>."
            : undefined
        }
      />

      {(domainConnect || (domain && workspaceId)) && (
        <div className="mt-4 flex flex-wrap gap-2">
          {domainConnect && domain && workspaceId && (
            <Button
              type="button"
              variant="secondary"
              text={`Auto configure with ${providerLabel}`}
              icon={
                <ProviderIcon
                  className={cn(
                    "size-4 shrink-0",
                    domainConnect.providerKind === "cloudflare"
                      ? "text-[#F6821F]"
                      : "text-black",
                  )}
                />
              }
              className="w-fit"
              onClick={handleAutoConfigure}
              loading={autoLoading}
            />
          )}
          {domain && workspaceId && (
            <Button
              type="button"
              variant="secondary"
              text="Forward instructions"
              icon={<EnvelopeArrowRight className="size-4 shrink-0" />}
              className="w-fit"
              onClick={() => setShowForwardDnsModal(true)}
              disabledTooltip={permissionsError || undefined}
            />
          )}
        </div>
      )}
      <ForwardDnsInstructionsModal />
    </div>
  );
}

const MarkdownText = ({ text }: { text: string }) => {
  return (
    <p
      className="prose-sm prose-code:rounded-md prose-code:bg-neutral-100 prose-code:p-1 prose-code:text-[.8125rem] prose-code:font-medium prose-code:font-mono prose-code:text-neutral-900 max-w-none"
      dangerouslySetInnerHTML={{ __html: text }}
    />
  );
};

const DnsRecord = ({
  instructions,
  records,
  warning,
}: {
  instructions: string;
  records: { type: string; name: string; value: string; ttl?: string }[];
  warning?: string;
}) => {
  const hasTtl = records.some((x) => x.ttl);

  return (
    <div className="mt-3 text-left text-neutral-600">
      <div className="my-5">
        <MarkdownText text={instructions} />
      </div>
      <div
        className={cn(
          "scrollbar-hide grid items-end gap-x-10 gap-y-1 overflow-x-auto rounded-lg bg-neutral-100/80 p-4 text-sm",
          hasTtl
            ? "grid-cols-[repeat(4,max-content)]"
            : "grid-cols-[repeat(3,max-content)]",
        )}
      >
        {["Type", "Name", "Value"].concat(hasTtl ? "TTL" : []).map((s) => (
          <p key={s} className="font-medium text-neutral-950">
            {s}
          </p>
        ))}

        {records.map((record, idx) => (
          <Fragment key={idx}>
            <p key={record.type} className="font-mono">
              {record.type}
            </p>
            <p key={record.name} className="font-mono">
              {record.name}
            </p>
            <p key={record.value} className="flex items-end gap-1 font-mono">
              {record.value}{" "}
              <CopyButton
                variant="neutral"
                className="-mb-0.5"
                value={record.value}
              />
            </p>
            {hasTtl && (
              <p key={record.ttl} className="font-mono">
                {record.ttl}
              </p>
            )}
          </Fragment>
        ))}
      </div>
      {(warning || hasTtl) && (
        <div
          className={cn(
            "mt-4 flex items-center gap-2 rounded-lg p-3",
            warning
              ? "bg-orange-50 text-orange-600"
              : "bg-indigo-50 text-indigo-600",
          )}
        >
          <CircleInfo className="h-5 w-5 shrink-0" />
          <MarkdownText
            text={
              warning ||
              "If a TTL value of 86400 is not available, choose the highest available value. Domain propagation may take up to 12 hours."
            }
          />
        </div>
      )}
    </div>
  );
};