The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
import dns from "node:dns/promises";
import { isAllowedSyncUXOrigin } from "./allowed-origins";
import { DOMAIN_CONNECT_PROVIDER_ID } from "./constants";
import type {
DomainConnectDiscovery,
DomainConnectProviderKind,
} from "./types";
type DomainConnectSettings = {
providerId?: string;
urlSyncUX?: string;
urlAPI?: string;
};
function providerKindFromId(
id: string | undefined,
): DomainConnectProviderKind | null {
if (!id) return null;
const lower = id.toLowerCase();
if (lower === "vercel.com") return "vercel";
if (lower === "cloudflare.com" || lower.includes("cloudflare"))
return "cloudflare";
return null;
}
const ALLOWED_SETTINGS_HOST_SUFFIXES = [
"domainconnect.org",
".vercel.com",
".cloudflare.com",
];
function isAllowedSettingsHost(host: string): boolean {
return ALLOWED_SETTINGS_HOST_SUFFIXES.some((suffix) => {
const hostnameSuffix = suffix.replace(/^\./, "");
return host === hostnameSuffix || host.endsWith(`.${hostnameSuffix}`);
});
}
function settingsBaseFromTxtRecords(records: string[][]): string | null {
const candidates = records
.map((chunks) =>
chunks
.join("")
.replace(/^"(.*)"$/, "$1")
.trim(),
)
.map((s) =>
s
.replace(/^https?:\/\//i, "")
.replace(/\/$/, "")
.toLowerCase(),
)
.filter((s) => {
if (!s.includes(".")) return false;
const [host, ...pathParts] = s.split("/");
if (
!host ||
!/^[a-z0-9.-]+$/.test(host) ||
/^\d+\.\d+\.\d+\.\d+$/.test(host)
) {
return false;
}
// Allow only simple path segments (no query/fragment)
if (
pathParts.some(
(p) => !p || !/^[a-z0-9._-]+$/i.test(p) || p === "." || p === "..",
)
) {
return false;
}
return isAllowedSettingsHost(host);
});
return candidates[0] ?? null;
}
/**
* Discover Domain Connect provider for the given apex domain.
* Returns null when the provider is not Vercel or Cloudflare, or on any error.
*/
export async function discoverDomainConnect(
apexDomain: string,
): Promise<DomainConnectDiscovery | null> {
let txtRecords: string[][];
try {
txtRecords = await dns.resolveTxt(
`_domainconnect.${apexDomain.toLowerCase()}`,
);
} catch {
return null;
}
const settingsBase = settingsBaseFromTxtRecords(txtRecords);
if (!settingsBase) return null;
const settingsUrl = `https://${settingsBase}/v2/${encodeURIComponent(apexDomain.toLowerCase())}/settings`;
let res: Response;
try {
res = await fetch(settingsUrl, {
headers: { accept: "application/json" },
redirect: "manual",
signal: AbortSignal.timeout(3000),
});
} catch {
return null;
}
if (!res.ok) return null;
let json: DomainConnectSettings;
try {
json = (await res.json()) as DomainConnectSettings;
} catch {
return null;
}
const urlSyncUX = json.urlSyncUX?.trim().replace(/\/$/, "");
const dnsProviderId = json.providerId ?? "";
if (!urlSyncUX || !dnsProviderId) return null;
let parsedSyncUX: URL;
try {
parsedSyncUX = new URL(urlSyncUX);
} catch {
return null;
}
if (parsedSyncUX.protocol !== "https:") return null;
if (!isAllowedSyncUXOrigin(urlSyncUX)) return null;
const providerKind = providerKindFromId(dnsProviderId);
if (!providerKind) return null;
let urlAPI: string | undefined;
try {
const parsedAPI = new URL(json.urlAPI ?? "");
if (
parsedAPI.protocol === "https:" &&
isAllowedSettingsHost(parsedAPI.hostname)
) {
urlAPI = `${parsedAPI.origin}${parsedAPI.pathname}`.replace(/\/$/, "");
}
} catch {}
return { providerKind, dnsProviderId, urlSyncUX, urlAPI };
}
/** Template version from the provider, or undefined when the lookup is inconclusive. */
export async function fetchDomainConnectTemplateVersion(
urlAPI: string,
serviceId: string,
): Promise<number | undefined> {
try {
const res = await fetch(
`${urlAPI}/v2/domainTemplates/providers/${DOMAIN_CONNECT_PROVIDER_ID}/services/${serviceId}`,
{
headers: { accept: "application/json" },
redirect: "manual",
signal: AbortSignal.timeout(3000),
},
);
if (!res.ok) return;
const { version } = (await res.json()) as { version?: unknown };
return typeof version === "number" ? version : undefined;
} catch {
return;
}
}
/**
* Only discover when the feature is enabled and the status warrants it.
*/
export async function discoverDomainConnectIfEligible(
apexDomain: string,
status: string,
): Promise<DomainConnectDiscovery | null> {
if (!process.env.DOMAIN_CONNECT_PRIVATE_KEY?.trim()) return null;
if (status !== "Pending Verification" && status !== "Invalid Configuration")
return null;
return discoverDomainConnect(apexDomain);
}