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.

960 B
Raw Blame
import { validDomainRegex } from "@dub/utils";
import { DubApiError } from "./errors";

const MAX_HOSTNAMES_ALLOWED = 10;

export const validateAllowedHostnames = (
  allowedHostnames: string[] | undefined,
) => {
  if (!allowedHostnames) {
    return [];
  }

  allowedHostnames = [...new Set(allowedHostnames)];

  const results = allowedHostnames.map(
    (hostname) =>
      validDomainRegex.test(hostname) ||
      hostname === "localhost" ||
      hostname.startsWith("*."),
  );

  const invalidHostnames = results.filter((result) => !result);

  if (invalidHostnames.length > 0) {
    throw new DubApiError({
      code: "unprocessable_entity",
      message: "Invalid hostnames.",
    });
  }

  if (allowedHostnames && allowedHostnames.length > MAX_HOSTNAMES_ALLOWED) {
    throw new DubApiError({
      code: "unprocessable_entity",
      message: `Maximum of ${MAX_HOSTNAMES_ALLOWED} hostnames allowed.`,
    });
  }

  return allowedHostnames;
};