All files / lib/cloudflare dns.ts

100% Statements 76/76
100% Branches 40/40
100% Functions 6/6
100% Lines 71/71

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244                  19x 19x                       19x             23x   18x 18x             16x 1x     1x     15x       15x 1x 1x     14x 14x 14x   2x     2x                             23x   23x 23x 23x     19x             17x 16x     16x   16x 4x 4x       12x 12x 2x     2x                               2x 1x 1x     1x 1x     1x         11x 11x                                 11x 9x 9x     2x 2x   2x 1x 1x     1x 1x   2x     2x                           23x 23x             20x 3x     17x         17x 2x           15x 5x       10x 10x 2x       8x 8x   8x 6x     2x           3x            
/**
 * Cloudflare DNS Utilities
 *
 * Zone ID lookup, CNAME record management, and external DNS verification
 * via the Cloudflare REST API and DNS-over-HTTPS.
 */
 
import { BASE_DOMAIN } from "../domain-utils";
 
export const CF_API_BASE = "https://api.cloudflare.com/client/v4";
const DOH_API = "https://cloudflare-dns.com/dns-query";
 
export interface CloudflareApiResponse<T = unknown> {
	success: boolean;
	result: T;
	errors: Array<{ code: number; message: string }>;
}
 
// Cache zone ID for the lifetime of this Worker isolate.
// In Cloudflare Workers, module-level state persists across requests within
// the same isolate. This is intentional — the zone ID for our base domain
// never changes, so caching it avoids redundant API calls on every publish.
let cachedZoneId: string | null = null;
 
/**
 * Look up the Cloudflare zone ID for the base domain.
 * Caches the result for the lifetime of the module.
 */
async function getZoneId(apiToken: string): Promise<string | null> {
	if (cachedZoneId) return cachedZoneId;
 
	try {
		const response = await fetch(
			`${CF_API_BASE}/zones?name=${BASE_DOMAIN}&status=active`,
			{
				headers: { Authorization: `Bearer ${apiToken}` },
			},
		);
 
		if (!response.ok) {
			console.error(
				`[DNS] Failed to look up zone for ${BASE_DOMAIN}: ${response.status}`,
			);
			return null;
		}
 
		const data = (await response.json()) as CloudflareApiResponse<
			Array<{ id: string; name: string }>
		>;
 
		if (!data.result?.length) {
			console.error(`[DNS] Zone not found for ${BASE_DOMAIN}`);
			return null;
		}
 
		cachedZoneId = data.result[0].id;
		console.log(`[DNS] Zone ID for ${BASE_DOMAIN}: ${cachedZoneId}`);
		return cachedZoneId;
	} catch (error) {
		console.error(
			`[DNS] Error looking up zone: ${error instanceof Error ? error.message : error}`,
		);
		return null;
	}
}
 
/**
 * Ensure a CNAME DNS record exists pointing the custom domain
 * to the Pages project's *.pages.dev hostname.
 *
 * @returns true if the record exists (or was created), false on error
 */
export async function ensureDnsCname(
	domain: string,
	projectName: string,
	apiToken: string,
): Promise<boolean> {
	const target = `${projectName}.pages.dev`;
 
	try {
		const zoneId = await getZoneId(apiToken);
		if (!zoneId) return false;
 
		// Check if CNAME already exists
		const listResponse = await fetch(
			`${CF_API_BASE}/zones/${zoneId}/dns_records?type=CNAME&name=${domain}`,
			{
				headers: { Authorization: `Bearer ${apiToken}` },
			},
		);
 
		if (listResponse.ok) {
			const listData = (await listResponse.json()) as CloudflareApiResponse<
				Array<{ id: string; name: string; content: string }>
			>;
			const existing = listData.result || [];
 
			if (existing.some((r) => r.name === domain && r.content === target)) {
				console.log(`[DNS] CNAME already exists: ${domain} → ${target}`);
				return true;
			}
 
			// If a CNAME exists but points elsewhere, update it
			const staleRecord = existing.find((r) => r.name === domain);
			if (staleRecord) {
				console.log(
					`[DNS] Updating CNAME ${domain}: ${staleRecord.content} → ${target}`,
				);
				const updateResponse = await fetch(
					`${CF_API_BASE}/zones/${zoneId}/dns_records/${staleRecord.id}`,
					{
						method: "PATCH",
						headers: {
							Authorization: `Bearer ${apiToken}`,
							"Content-Type": "application/json",
						},
						body: JSON.stringify({
							type: "CNAME",
							name: domain,
							content: target,
							proxied: true,
						}),
					},
				);
				if (updateResponse.ok) {
					console.log(`[DNS] Updated CNAME: ${domain} → ${target}`);
					return true;
				}
				const errData =
					(await updateResponse.json()) as CloudflareApiResponse;
				console.error(
					`[DNS] Failed to update CNAME: ${JSON.stringify(errData.errors)}`,
				);
				return false;
			}
		}
 
		// Create new CNAME record
		console.log(`[DNS] Creating CNAME: ${domain} → ${target}`);
		const createResponse = await fetch(
			`${CF_API_BASE}/zones/${zoneId}/dns_records`,
			{
				method: "POST",
				headers: {
					Authorization: `Bearer ${apiToken}`,
					"Content-Type": "application/json",
				},
				body: JSON.stringify({
					type: "CNAME",
					name: domain,
					content: target,
					proxied: true,
				}),
			},
		);
 
		if (createResponse.ok) {
			console.log(`[DNS] Created CNAME: ${domain} → ${target}`);
			return true;
		}
 
		const errorData = (await createResponse.json()) as CloudflareApiResponse;
		const errorStr = JSON.stringify(errorData.errors);
 
		if (errorStr.includes("already exists")) {
			console.log(`[DNS] CNAME already exists (race): ${domain}`);
			return true;
		}
 
		console.error(`[DNS] Failed to create CNAME for ${domain}: ${errorStr}`);
		return false;
	} catch (error) {
		console.error(
			`[DNS] Error ensuring CNAME for ${domain}: ${error instanceof Error ? error.message : error}`,
		);
		return false;
	}
}
 
/**
 * Verify that an external domain's CNAME record points to the expected
 * *.pages.dev target using Cloudflare's DNS-over-HTTPS API.
 *
 * Works from Workers (no Node `dns` module needed).
 */
export async function verifyExternalDnsCname(
	domain: string,
	expectedTarget: string,
): Promise<{ verified: boolean; resolvedTarget?: string; error?: string }> {
	try {
		const response = await fetch(
			`${DOH_API}?name=${encodeURIComponent(domain)}&type=CNAME`,
			{
				headers: { Accept: "application/dns-json" },
			},
		);
 
		if (!response.ok) {
			return { verified: false, error: `DNS query failed: ${response.status}` };
		}
 
		const data = (await response.json()) as {
			Status: number;
			Answer?: Array<{ type: number; data: string }>;
		};
 
		if (data.Status !== 0) {
			return {
				verified: false,
				error: `DNS query returned status ${data.Status}`,
			};
		}
 
		if (!data.Answer?.length) {
			return { verified: false, error: "No CNAME record found" };
		}
 
		// Type 5 = CNAME record
		const cnameRecord = data.Answer.find((a) => a.type === 5);
		if (!cnameRecord) {
			return { verified: false, error: "No CNAME record found" };
		}
 
		// Normalize: strip trailing dot and compare case-insensitively
		const resolved = cnameRecord.data.replace(/\.$/, "").toLowerCase();
		const expected = expectedTarget.replace(/\.$/, "").toLowerCase();
 
		if (resolved === expected) {
			return { verified: true, resolvedTarget: resolved };
		}
 
		return {
			verified: false,
			resolvedTarget: resolved,
			error: `CNAME points to ${resolved}, expected ${expected}`,
		};
	} catch (error) {
		return {
			verified: false,
			error: `DNS verification failed: ${error instanceof Error ? error.message : error}`,
		};
	}
}