Skip to content

Black Friday

Annual Pro is $90 for the first year, normally $120. Or start monthly at $6 for two months, then $12.

Ends Dec 4, 11:59 PM PT.

Create an account
← Public packages

@kentcdodds/cloudflare

Cloudflare helpers: API v4, static site publishing to Pages, analytics, WAF rules, logs, and docs.

FollowFork

Files

custom-domain-core.ts

942 lines · 39.3 KB · TypeScript
/**
 * Shared, dependency-injected logic for pointing a custom hostname at a Kody
 * package app (`./custom-domain`) and removing that setup
 * (`./custom-domain-remove`). The export files wire in the live `kody` runtime
 * and `./api-v4`; tests wire in mocks.
 */
import type { CloudflareApiV4Result } from './api-v4.ts'
import type { CloudflareAccount } from './auth.ts'

/** Kody's own domains. The Kody runtime refuses custom hostnames under them. */
export const KODY_RESERVED_DOMAINS = ['kody.codes', 'kody.run'] as const

/** CNAME target Kody hands out for package-app custom hostnames. */
export const DEFAULT_KODY_CNAME_TARGET = 'domains.kody.run'

/** Prefix written into the Cloudflare record comment so later runs can tell our records apart. */
export const RECORD_COMMENT_MARKER = 'kody-custom-domain'

export const DEFAULT_WAIT_MINUTES = 1
export const MAX_WAIT_MINUTES = 15

/** Seconds between sync attempts. The last value repeats. */
export const SYNC_BACKOFF_SECONDS = [5, 10, 15, 20, 30] as const

export type KodyHostnameRecord = { type: string; name: string; value: string }

export type KodyHostnameRow = {
	id: string
	hostname: string
	binding_kind: 'app' | 'org'
	package_id: string | null
	hostname_status: string
	ssl_status: string
	verification?: {
		ownership_verification: KodyHostnameRecord | null
		ssl_validation_records: KodyHostnameRecord[]
	}
	/** Kody's summary: pending (it re-checks on its own), active, or needs_attention. */
	status?: { state: string; reason: string | null } | null
}

export type KodyHostnameResult = {
	hostname: KodyHostnameRow
	dns?: { type: 'CNAME'; name: string; target: string | null }
	verification?: {
		ownership_verification: KodyHostnameRecord | null
		ssl_validation_records: KodyHostnameRecord[]
	}
}

export type KodyPackageSummary = {
	package_id: string
	kody_id: string
	slug?: string
	name: string
	has_app: boolean
	internet_visible?: boolean
}

/** The slice of the `kody` runtime object these helpers use. */
export type KodyCustomDomainClient = {
	packageList(input: Record<string, never>): Promise<{ packages: KodyPackageSummary[] }>
	packageAppCustomHostnameList(input: Record<string, never>): Promise<{ hostnames: KodyHostnameRow[] }>
	packageAppCustomHostnameAdd(input: {
		hostname: string
		binding_kind: 'app'
		package_id: string
	}): Promise<KodyHostnameResult>
	packageAppCustomHostnameSync(input: { hostname: string }): Promise<KodyHostnameResult>
	packageAppCustomHostnameDelete?(input: { hostname: string }): Promise<{ ok: boolean; id: string; hostname: string }>
}

export type CloudflareRequest = {
	method?: 'GET' | 'POST' | 'PATCH' | 'DELETE'
	path: string
	query?: Record<string, string | number | boolean | null | undefined>
	body?: unknown
}

export type CloudflareCaller = (request: CloudflareRequest) => Promise<CloudflareApiV4Result>

export type CustomDomainDeps = {
	kody: KodyCustomDomainClient
	cloudflare: CloudflareCaller
	sleep?: (ms: number) => Promise<void>
	now?: () => number
}

export type DnsRecord = {
	id: string
	type: string
	name: string
	content: string
	proxied?: boolean
	comment?: string | null
}

export type PlannedAction = {
	kind: 'kody.add' | 'kody.sync' | 'kody.delete' | 'dns.create' | 'dns.update' | 'dns.delete'
	description: string
	record?: { type: string; name: string; content?: string; proxied?: boolean; id?: string }
	done: boolean
}

export type CustomDomainSetupInput = {
	hostname: string
	package: string
	dryRun?: boolean
	waitMinutes?: number
	account?: CloudflareAccount
	apiTokenSecret?: string
}

/**
 * How a validation record Kody reports is satisfied. Cloudflare for SaaS can
 * ask for TXT, CNAME, HTTP (ACME HTTP-01, served through the routing CNAME), or
 * email validation; anything else is `unknown`.
 */
export type ValidationKind = 'txt' | 'cname' | 'http' | 'email' | 'unknown'

export type RecordPurpose = 'routing' | 'ownership' | 'certificate'

/**
 * One DNS record (or validation step) and what this run did about it.
 * - `created` / `updated`: this run wrote it (only ever records carrying the helper's comment)
 * - `reused`: already in place with the right value; left untouched
 * - `planned`: a dry run would write it
 * - `not_needed`: no DNS record required (for example HTTP validation, or the hostname is already active)
 * - `manual`: needs a person; see `note` and `nextSteps`
 */
export type RecordOutcome = {
	purpose: RecordPurpose
	kind: ValidationKind
	/** Record type as written to DNS (`CNAME`, `TXT`) or as Kody reported it (`http`, `email`, ...). */
	type: string
	name: string
	value: string
	outcome: 'created' | 'updated' | 'reused' | 'planned' | 'not_needed' | 'manual'
	id?: string
	note?: string
}

export type CustomDomainSetupResult = {
	ok: boolean
	status: 'already_configured' | 'planned' | 'active' | 'pending'
	dryRun: boolean
	hostname: string
	package: { id: string; name: string }
	zone: { id: string; name: string }
	kodyHostname: { id: string; hostnameStatus: string; sslStatus: string } | null
	actions: PlannedAction[]
	syncAttempts: number
	warnings: string[]
	nextStep: string | null
	/** Cloudflare hostname status as Kody last reported it (`active`, `pending`, ...), or null before registration. */
	hostnameStatus: string | null
	/** Cloudflare certificate status as Kody last reported it (`active`, `pending_validation`, ...), or null before registration. */
	sslStatus: string | null
	/** Kody's own summary state and reason (`pending`, `active`, `needs_attention`), when it reports one. */
	kodyStatus: { state: string; reason: string | null } | null
	/** Every routing and validation record, and whether it was created, reused, planned, not needed, or needs a person. */
	records: RecordOutcome[]
	/** True when at least one step needs a person (see `nextSteps`). Everything else was still finished. */
	needsManualAction: boolean
	/** Ordered, actionable next steps. Empty when the hostname is active and nothing is left to do. */
	nextSteps: string[]
}

export type CustomDomainRemoveInput = {
	hostname: string
	confirm?: boolean
	account?: CloudflareAccount
	apiTokenSecret?: string
}

export type CustomDomainRemoveResult = {
	ok: boolean
	status: 'planned' | 'removed' | 'nothing_to_remove'
	dryRun: boolean
	hostname: string
	zone: { id: string; name: string }
	actions: PlannedAction[]
	skipped: Array<{ type: string; name: string; content: string; reason: string }>
	nextStep: string | null
}

const SETUP_KEYS = new Set(['hostname', 'package', 'dryRun', 'waitMinutes', 'account', 'apiTokenSecret'])
const REMOVE_KEYS = new Set(['hostname', 'confirm', 'account', 'apiTokenSecret'])
const ACCOUNTS = new Set(['default', 'kody', 'pages'])
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
const LABEL = /^(?!-)[a-z0-9-]{1,63}(?<!-)$/

function rejectUnknownKeys(raw: Record<string, unknown>, allowed: Set<string>, what: string) {
	const unknown = Object.keys(raw).filter((key) => !allowed.has(key))
	if (unknown.length) {
		throw new Error(
			`Unknown ${what} input key(s): ${unknown.join(', ')}. Accepted keys: ${[...allowed].join(', ')}.`,
		)
	}
}

function parseAuth(raw: Record<string, unknown>) {
	const out: { account?: CloudflareAccount; apiTokenSecret?: string } = {}
	if (raw.account !== undefined) {
		if (typeof raw.account !== 'string' || !ACCOUNTS.has(raw.account)) {
			throw new Error('account must be one of: default, kody, pages.')
		}
		out.account = raw.account as CloudflareAccount
	}
	if (raw.apiTokenSecret !== undefined) {
		if (typeof raw.apiTokenSecret !== 'string' || !raw.apiTokenSecret.trim()) {
			throw new Error('apiTokenSecret must be a Kody secret name.')
		}
		out.apiTokenSecret = raw.apiTokenSecret.trim()
	}
	if (out.account && out.apiTokenSecret) {
		throw new Error('Pass either account or apiTokenSecret, not both.')
	}
	return out
}

/**
 * Normalize and validate a hostname. Rejects schemes, paths, ports, wildcards,
 * IP addresses, and anything under Kody's own domains.
 */
export function normalizeHostname(value: unknown): string {
	if (typeof value !== 'string' || !value.trim()) {
		throw new Error('hostname is required, for example "app.example.com".')
	}
	const hostname = value.trim().toLowerCase().replace(/\.$/, '')
	if (/[/:@?#\s]/.test(hostname)) {
		throw new Error(
			`hostname must be a bare hostname like "app.example.com" (no scheme, path, or port). Got "${value}".`,
		)
	}
	if (hostname.includes('*')) {
		throw new Error('Wildcard hostnames are not supported.')
	}
	if (hostname.length > 253) throw new Error('hostname is longer than 253 characters.')
	const labels = hostname.split('.')
	if (labels.length < 2 || labels.some((label) => !LABEL.test(label))) {
		throw new Error(`"${hostname}" is not a valid hostname.`)
	}
	if (/^\d+$/.test(labels[labels.length - 1])) {
		throw new Error('IP addresses are not supported; pass a DNS hostname.')
	}
	for (const reserved of KODY_RESERVED_DOMAINS) {
		if (hostname === reserved || hostname.endsWith('.' + reserved)) {
			throw new Error(
				`"${hostname}" is under ${reserved}. Kody refuses custom hostnames on its own domains (kody.codes, kody.run) on purpose, so package app code stays cross-site from Kody's cookies. Use a hostname in a zone you own.`,
			)
		}
	}
	return hostname
}

function parseWaitMinutes(value: unknown): number {
	if (value === undefined) return DEFAULT_WAIT_MINUTES
	if (typeof value !== 'number' || !Number.isFinite(value) || value < 0 || value > MAX_WAIT_MINUTES) {
		throw new Error(`waitMinutes must be a number from 0 to ${MAX_WAIT_MINUTES}.`)
	}
	return value
}

export function parseSetupInput(raw: unknown): Required<Pick<CustomDomainSetupInput, 'hostname' | 'package' | 'dryRun' | 'waitMinutes'>> &
	Pick<CustomDomainSetupInput, 'account' | 'apiTokenSecret'> {
	if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
		throw new Error('Pass an object: { hostname, package, dryRun?, waitMinutes? }.')
	}
	const record = raw as Record<string, unknown>
	rejectUnknownKeys(record, SETUP_KEYS, 'custom-domain')
	if (typeof record.package !== 'string' || !record.package.trim()) {
		throw new Error('package is required: a package id (UUID) or name like "@scope/leaf".')
	}
	if (record.dryRun !== undefined && typeof record.dryRun !== 'boolean') {
		throw new Error('dryRun must be a boolean.')
	}
	return {
		hostname: normalizeHostname(record.hostname),
		package: record.package.trim(),
		dryRun: record.dryRun === true,
		waitMinutes: parseWaitMinutes(record.waitMinutes),
		...parseAuth(record),
	}
}

export function parseRemoveInput(raw: unknown): { hostname: string; confirm: boolean; account?: CloudflareAccount; apiTokenSecret?: string } {
	if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
		throw new Error('Pass an object: { hostname, confirm? }.')
	}
	const record = raw as Record<string, unknown>
	rejectUnknownKeys(record, REMOVE_KEYS, 'custom-domain-remove')
	if (record.confirm !== undefined && typeof record.confirm !== 'boolean') {
		throw new Error('confirm must be a boolean.')
	}
	return { hostname: normalizeHostname(record.hostname), confirm: record.confirm === true, ...parseAuth(record) }
}

/** Candidate zone names for a hostname, most specific first (never a bare TLD). */
export function zoneCandidates(hostname: string): string[] {
	const labels = hostname.split('.')
	const out: string[] = []
	for (let i = 0; i <= labels.length - 2; i++) out.push(labels.slice(i).join('.'))
	return out
}

function stripTxtQuotes(value: string): string {
	const trimmed = String(value ?? '').trim()
	if (trimmed.length >= 2 && trimmed.startsWith('"') && trimmed.endsWith('"')) {
		return trimmed.slice(1, -1).replace(/"\s+"/g, '')
	}
	return trimmed
}

function sameHost(a: string, b: string): boolean {
	return a.toLowerCase().replace(/\.$/, '') === b.toLowerCase().replace(/\.$/, '')
}

function isOurs(record: DnsRecord): boolean {
	return typeof record.comment === 'string' && record.comment.startsWith(RECORD_COMMENT_MARKER)
}

function recordComment(role: string, packageName: string): string {
	return `${RECORD_COMMENT_MARKER} ${role} for ${packageName}`.slice(0, 100)
}

function describeRecord(record: DnsRecord): string {
	return `${record.type} ${record.name} -> ${record.content}${record.proxied ? ' (proxied)' : ''}${record.comment ? ` [comment: ${record.comment}]` : ''}`
}

async function cfOk(cloudflare: CloudflareCaller, request: CloudflareRequest, what: string) {
	const response = await cloudflare(request)
	if (!response.success) {
		const errors = JSON.stringify(response.errors ?? []).slice(0, 500)
		throw new Error(`Cloudflare ${what} failed (HTTP ${response.httpStatus}): ${errors}`)
	}
	return response
}

/**
 * Find the Cloudflare zone that owns `hostname` among zones the token can see:
 * the longest suffix of the hostname that is a zone wins (so a delegated
 * subdomain zone beats its parent).
 */
export async function findZone(cloudflare: CloudflareCaller, hostname: string): Promise<{ id: string; name: string; status?: string }> {
	const candidates = zoneCandidates(hostname)
	for (const name of candidates) {
		const response = await cfOk(cloudflare, { path: '/client/v4/zones', query: { name } }, `zone lookup for ${name}`)
		const zones = Array.isArray(response.result) ? (response.result as Array<{ id: string; name: string; status?: string }>) : []
		const matching = zones.filter((candidate) => sameHost(candidate.name, name))
		const zone = matching.find((candidate) => candidate.status === 'active') ?? matching[0]
		if (zone) return { id: zone.id, name: zone.name, status: zone.status }
	}
	throw new Error(
		`No Cloudflare zone for "${hostname}" in the connected account (tried: ${candidates.join(', ')}). Add the zone to Cloudflare, or pass account / apiTokenSecret for a token that can see it.`,
	)
}

async function listRecords(cloudflare: CloudflareCaller, zoneId: string, name: string): Promise<DnsRecord[]> {
	const response = await cfOk(
		cloudflare,
		{ path: `/client/v4/zones/${zoneId}/dns_records`, query: { name, per_page: 100 } },
		`DNS record lookup for ${name}`,
	)
	const items = Array.isArray(response.result) ? (response.result as DnsRecord[]) : []
	return items.filter((record) => sameHost(record.name, name))
}

/** Resolve a package id (UUID), scoped name (`@scope/leaf`), or name leaf to one saved package. */
export async function resolvePackage(kody: KodyCustomDomainClient, ref: string): Promise<KodyPackageSummary> {
	const { packages } = await kody.packageList({})
	const lower = ref.toLowerCase()
	let matches: KodyPackageSummary[]
	if (UUID.test(ref)) matches = packages.filter((pkg) => pkg.package_id.toLowerCase() === lower)
	else if (ref.startsWith('@')) matches = packages.filter((pkg) => pkg.name.toLowerCase() === lower)
	else matches = packages.filter((pkg) => pkg.kody_id.toLowerCase() === lower || (pkg.slug ?? '').toLowerCase() === lower)
	if (matches.length === 0) {
		throw new Error(`No saved package matches "${ref}". Pass the package id or its scoped name like "@scope/leaf".`)
	}
	if (matches.length > 1) {
		throw new Error(`"${ref}" matches ${matches.length} packages (${matches.map((pkg) => pkg.name).join(', ')}). Pass the package id.`)
	}
	return matches[0]
}

function verificationOf(result: KodyHostnameResult | KodyHostnameRow | null | undefined) {
	if (!result) return { ownership: null as KodyHostnameRecord | null, ssl: [] as KodyHostnameRecord[] }
	const verification = 'verification' in result && result.verification ? result.verification : undefined
	const rowVerification = 'hostname' in result && typeof result.hostname === 'object' ? result.hostname.verification : undefined
	const source = verification ?? rowVerification
	return {
		ownership: source?.ownership_verification ?? null,
		ssl: source?.ssl_validation_records ?? [],
	}
}

function isActive(row: KodyHostnameRow | null | undefined): boolean {
	return !!row && row.hostname_status === 'active' && row.ssl_status === 'active'
}

type TxtPlan =
	| { state: 'present'; record: DnsRecord }
	| { state: 'create'; foreign: DnsRecord[] }
	| { state: 'update'; record: DnsRecord }
	| { state: 'conflict'; reason: string }

/**
 * Decide what to do for one verification TXT record (ownership or certificate).
 * A name can hold several TXT values, so TXT records this helper did not create
 * are never changed: ours is added beside them. `keep` lists other values Kody
 * currently expects at the same name, so a second expected value is added
 * instead of overwriting the first. Only a CNAME at the name blocks a TXT.
 */
export function planTxt(existing: DnsRecord[], name: string, value: string | null, keep: string[] = []): TxtPlan {
	const cnames = existing.filter((record) => record.type === 'CNAME')
	if (cnames.length) {
		return { state: 'conflict', reason: `${name} has a CNAME, so no TXT record can be added there: ${cnames.map(describeRecord).join('; ')}` }
	}
	const txt = existing.filter((record) => record.type === 'TXT')
	if (value !== null) {
		const match = txt.find((record) => stripTxtQuotes(record.content) === value)
		if (match) return { state: 'present', record: match }
		const expected = new Set([value, ...keep])
		const stale = txt.find((record) => isOurs(record) && !expected.has(stripTxtQuotes(record.content)))
		if (stale) return { state: 'update', record: stale }
	}
	return { state: 'create', foreign: txt.filter((record) => !isOurs(record)) }
}

/** Decide what to do for a CNAME (the routing record, or a CNAME validation record). */
export function planCname(existing: DnsRecord[], hostname: string, target: string): { state: 'present'; record: DnsRecord } | { state: 'create' } | { state: 'conflict'; reason: string } {
	if (existing.length === 0) return { state: 'create' }
	if (existing.length === 1) {
		const [record] = existing
		if (record.type === 'CNAME' && sameHost(record.content, target)) {
			if (record.proxied) {
				return {
					state: 'conflict',
					reason: `${hostname} has a proxied CNAME to ${target}. It must be DNS-only (grey cloud). This helper will not change it; switch it to DNS-only yourself, then re-run.`,
				}
			}
			return { state: 'present', record }
		}
	}
	return {
		state: 'conflict',
		reason: `${hostname} already has record(s): ${existing.map(describeRecord).join('; ')}. Remove them (or pick another hostname), then re-run.`,
	}
}

/** Map the validation type Kody reports (from Cloudflare for SaaS) to how it is satisfied. */
export function validationKind(type: unknown): ValidationKind {
	const normalized = String(type ?? '').trim().toLowerCase().replace(/[^a-z0-9]/g, '')
	if (normalized === 'txt' || normalized === 'dnstxt') return 'txt'
	if (normalized === 'cname' || normalized === 'dnscname') return 'cname'
	if (normalized === 'http' || normalized === 'http01' || normalized === 'httpurl') return 'http'
	if (normalized === 'email') return 'email'
	return 'unknown'
}

function conflictError(hostname: string, reasons: string[]): Error {
	return new Error(`Refusing to configure ${hostname}; nothing was changed. Conflicts:\n- ${reasons.join('\n- ')}`)
}

function inZone(name: string, zoneName: string): boolean {
	const host = name.toLowerCase().replace(/\.$/, '')
	const zone = zoneName.toLowerCase().replace(/\.$/, '')
	return host === zone || host.endsWith('.' + zone)
}

function errorMessage(error: unknown): string {
	return error instanceof Error ? error.message : String(error)
}

type VerificationEntry = { purpose: 'ownership' | 'certificate'; record: KodyHostnameRecord }

function verificationEntries(source: KodyHostnameResult | KodyHostnameRow | null | undefined): VerificationEntry[] {
	const { ownership, ssl } = verificationOf(source)
	const out: VerificationEntry[] = []
	if (ownership && (ownership.name || ownership.value)) out.push({ purpose: 'ownership', record: ownership })
	for (const record of ssl) {
		if (record && (record.name || record.value)) out.push({ purpose: 'certificate', record })
	}
	return out
}

function outcomeKey(outcome: Pick<RecordOutcome, 'purpose' | 'kind' | 'name' | 'value'>): string {
	return `${outcome.purpose}|${outcome.kind}|${outcome.name.toLowerCase().replace(/\.$/, '')}|${outcome.value}`
}

/**
 * Point `hostname` at a Kody package app. See `./custom-domain` for the
 * public contract; this takes injected deps so it can be unit tested.
 *
 * Only the routing CNAME is checked before any write (a conflict there throws
 * with "nothing was changed"). Everything after registration is best effort:
 * a validation record it cannot publish (unknown type, email validation, a
 * blocked name, a Cloudflare error) becomes a `manual` record plus a next
 * step, and the rest still runs.
 */
export async function setupCustomDomain(rawInput: unknown, deps: CustomDomainDeps): Promise<CustomDomainSetupResult> {
	const input = parseSetupInput(rawInput)
	const { kody, cloudflare } = deps
	const sleep = deps.sleep ?? ((ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)))
	const now = deps.now ?? (() => Date.now())
	const { hostname, dryRun } = input
	const warnings: string[] = []
	const actions: PlannedAction[] = []

	const pkg = await resolvePackage(kody, input.package)
	if (!pkg.has_app) {
		throw new Error(`${pkg.name} has no package app, so there is nothing to serve on ${hostname}.`)
	}
	if (pkg.internet_visible === false) {
		warnings.push(
			`${pkg.name} is not internet-visible. App-level custom hostnames serve one internet-visible public app; Kody may refuse the binding or serve nothing until the app is internet-visible.`,
		)
	}

	const zone = await findZone(cloudflare, hostname)
	if (sameHost(zone.name, hostname)) {
		throw new Error(`${hostname} is the zone apex. Use a subdomain such as "app.${zone.name}" (an apex CNAME would collide with the zone's other records).`)
	}
	if (zone.status && zone.status !== 'active') {
		warnings.push(`Cloudflare zone ${zone.name} status is "${zone.status}", not "active".`)
	}

	const { hostnames } = await kody.packageAppCustomHostnameList({})
	let row = hostnames.find((candidate) => sameHost(candidate.hostname, hostname)) ?? null
	if (row && (row.binding_kind !== 'app' || row.package_id !== pkg.package_id)) {
		throw new Error(
			`${hostname} is already registered in Kody as a ${row.binding_kind} hostname${row.package_id ? ` for package ${row.package_id}` : ''}, not for ${pkg.name}. Remove that registration first if you mean to move it.`,
		)
	}

	const ownershipName = `_cf-custom-hostname.${hostname}`
	let target = DEFAULT_KODY_CNAME_TARGET
	const cname = planCname(await listRecords(cloudflare, zone.id, hostname), hostname, target)
	if (cname.state === 'conflict') throw conflictError(hostname, [cname.reason])

	const routing: RecordOutcome = {
		purpose: 'routing',
		kind: 'cname',
		type: 'CNAME',
		name: hostname,
		value: target,
		outcome: cname.state === 'present' ? 'reused' : 'planned',
		...(cname.state === 'present' ? { id: cname.record.id } : {}),
	}
	const warned = new Set<string>()
	const warnOnce = (message: string) => {
		if (warned.has(message)) return
		warned.add(message)
		warnings.push(message)
	}
	const summary = (r: KodyHostnameRow | null) => (r ? { id: r.id, hostnameStatus: r.hostname_status, sslStatus: r.ssl_status } : null)
	const base = {
		dryRun,
		hostname,
		package: { id: pkg.package_id, name: pkg.name },
		zone: { id: zone.id, name: zone.name },
	}
	const statusFields = (r: KodyHostnameRow | null) => ({
		kodyHostname: summary(r),
		hostnameStatus: r?.hostname_status ?? null,
		sslStatus: r?.ssl_status ?? null,
		kodyStatus: r?.status && typeof r.status === 'object' ? { state: String(r.status.state), reason: r.status.reason ?? null } : null,
	})

	if (cname.state === 'present' && isActive(row)) {
		const records: RecordOutcome[] = [
			routing,
			...verificationEntries(row).map(({ purpose, record }) => ({
				purpose,
				kind: validationKind(record.type),
				type: record.type,
				name: record.name,
				value: record.value,
				outcome: 'not_needed' as const,
				note: 'The hostname and certificate are already active.',
			})),
		]
		return {
			ok: true,
			status: 'already_configured',
			...base,
			...statusFields(row),
			actions: [],
			syncAttempts: 0,
			warnings,
			nextStep: null,
			records,
			needsManualAction: false,
			nextSteps: [],
		}
	}

	const label = (purpose: VerificationEntry['purpose']) => (purpose === 'ownership' ? 'hostname ownership' : 'certificate')
	const permissionHint = `Check that the Cloudflare token can edit DNS on ${zone.name} (Zone: Read and DNS: Edit), then re-run.`
	const written = new Map<string, RecordOutcome>()

	const createRecord = async (record: { type: string; name: string; content: string; proxied?: boolean }, role: string, what: string): Promise<{ id?: string; error?: string }> => {
		try {
			const body = { ...record, ttl: 1, comment: recordComment(role, pkg.name) }
			const created = await cfOk(cloudflare, { method: 'POST', path: `/client/v4/zones/${zone.id}/dns_records`, body }, what)
			return { id: (created.result as { id?: string } | null)?.id }
		} catch (error) {
			return { error: errorMessage(error) }
		}
	}

	/** Publish (or, with `apply` false, plan) one validation record Kody reported. Never throws. */
	const reconcileOne = async (entry: VerificationEntry, siblings: string[], apply: boolean): Promise<RecordOutcome> => {
		const { purpose, record } = entry
		const kind = validationKind(record.type)
		const name = String(record.name ?? '').trim().toLowerCase().replace(/\.$/, '')
		const value = String(record.value ?? '').trim()
		const out = { purpose, kind, type: String(record.type), name: String(record.name ?? ''), value: String(record.value ?? '') }
		if (kind === 'http') {
			return {
				...out,
				outcome: 'not_needed',
				note: `HTTP validation: Cloudflare fetches ${out.name || 'a token over HTTP'} and Kody answers it once ${hostname} is a DNS-only CNAME to ${target}. No DNS record is needed.`,
			}
		}
		if (kind === 'email') {
			return {
				...out,
				outcome: 'manual',
				note: `Cloudflare is validating the ${label(purpose)} by email${value ? ` (${value})` : ''}. Approve the validation email Cloudflare sends to the domain's administrative contacts, or remove the hostname and add it again with TXT or HTTP validation.`,
			}
		}
		if (kind === 'unknown') {
			return {
				...out,
				outcome: 'manual',
				note: `Kody reported a ${label(purpose)} validation record of type "${out.type}" that this helper does not publish automatically (name "${out.name}", value "${out.value}"). Publish it by hand at your DNS provider (DNS only, not proxied), then re-run.`,
			}
		}
		const type = kind === 'txt' ? 'TXT' : 'CNAME'
		const typed = { ...out, type }
		if (!name || !value) {
			return { ...typed, outcome: 'manual', note: `Kody reported an incomplete ${label(purpose)} ${type} record (name "${out.name}", value "${out.value}"). Re-run in a minute; if it persists, sync the hostname in Kody and check its setup records.` }
		}
		if (!inZone(name, zone.name)) {
			return { ...typed, outcome: 'manual', note: `${name} is outside the Cloudflare zone ${zone.name}. Add ${type} ${name} -> ${value} (DNS only) at the DNS provider for that name, then re-run.` }
		}
		const existing = await listRecords(cloudflare, zone.id, name)
		if (kind === 'cname') {
			if (sameHost(name, hostname)) {
				return sameHost(value, routing.value)
					? { ...typed, outcome: 'not_needed', note: 'Same record as the routing CNAME.' }
					: { ...typed, outcome: 'manual', note: `Kody asked for ${hostname} to CNAME to ${value}, but the routing CNAME points at ${routing.value}. Check the hostname's setup records in Kody.` }
			}
			const plan = planCname(existing, name, value)
			if (plan.state === 'present') return { ...typed, outcome: 'reused', id: plan.record.id }
			if (plan.state === 'conflict') return { ...typed, outcome: 'manual', note: `${plan.reason} This helper never changes records it did not create.` }
			if (!apply) return { ...typed, outcome: 'planned' }
			const created = await createRecord({ type: 'CNAME', name, content: value, proxied: false }, purpose === 'ownership' ? 'ownership-cname' : 'ssl-validation-cname', `create CNAME ${name}`)
			if (created.error) return { ...typed, outcome: 'manual', note: `Could not create CNAME ${name} -> ${value}: ${created.error}. ${permissionHint}` }
			return { ...typed, outcome: 'created', id: created.id }
		}
		const plan = planTxt(existing, name, value, siblings)
		if (plan.state === 'present') return { ...typed, outcome: 'reused', id: plan.record.id }
		if (plan.state === 'conflict') {
			return { ...typed, outcome: 'manual', note: `${plan.reason}. This helper never changes records it did not create; remove that CNAME or publish TXT ${name} = "${value}" elsewhere, then re-run.` }
		}
		if (plan.state === 'create' && plan.foreign.length) {
			warnOnce(`${name} has TXT record(s) this helper did not create; they were left untouched and the helper's value was added beside them: ${plan.foreign.map(describeRecord).join('; ')}`)
		}
		if (!apply) return { ...typed, outcome: 'planned', ...(plan.state === 'update' ? { id: plan.record.id, note: 'Replaces a stale value this helper wrote earlier.' } : {}) }
		if (plan.state === 'update') {
			try {
				await cfOk(cloudflare, { method: 'PATCH', path: `/client/v4/zones/${zone.id}/dns_records/${plan.record.id}`, body: { content: value } }, `update TXT ${name}`)
				return { ...typed, outcome: 'updated', id: plan.record.id }
			} catch (error) {
				return { ...typed, outcome: 'manual', note: `Could not update TXT ${name}: ${errorMessage(error)}. ${permissionHint}` }
			}
		}
		const created = await createRecord({ type: 'TXT', name, content: value }, purpose === 'ownership' ? 'ownership' : 'ssl-validation', `create TXT ${name}`)
		if (created.error) return { ...typed, outcome: 'manual', note: `Could not create TXT ${name}: ${created.error}. ${permissionHint}` }
		return { ...typed, outcome: 'created', id: created.id }
	}

	let verification: RecordOutcome[] = []
	const reconcileAll = async (source: KodyHostnameResult | KodyHostnameRow | null, apply: boolean) => {
		const entries = verificationEntries(source)
		const next: RecordOutcome[] = []
		for (const entry of entries) {
			const siblings = entries
				.filter((other) => other !== entry && validationKind(other.record.type) === 'txt' && sameHost(String(other.record.name ?? ''), String(entry.record.name ?? '')))
				.map((other) => String(other.record.value ?? '').trim())
			const outcome = await reconcileOne(entry, siblings, apply)
			const key = outcomeKey(outcome)
			if (outcome.outcome === 'created' || outcome.outcome === 'updated') written.set(key, outcome)
			next.push(outcome.outcome === 'reused' && written.has(key) ? written.get(key)! : outcome)
		}
		// Keep records from earlier passes that Kody stopped reporting (it drops them once validated),
		// so the result still lists everything this call created or relied on.
		const nextKeys = new Set(next.map(outcomeKey))
		for (const earlier of verification) {
			if (nextKeys.has(outcomeKey(earlier))) continue
			next.push(
				earlier.outcome === 'manual' || earlier.outcome === 'planned'
					? { ...earlier, outcome: 'not_needed', note: 'Kody no longer asks for this record.' }
					: earlier,
			)
		}
		verification = next
	}

	if (!row) {
		actions.push({ kind: 'kody.add', description: `Register ${hostname} in Kody as an app hostname for ${pkg.name}.`, done: false })
	}
	if (cname.state === 'create') {
		actions.push({
			kind: 'dns.create',
			description: `Create DNS-only CNAME ${hostname} -> ${target}.`,
			record: { type: 'CNAME', name: hostname, content: target, proxied: false },
			done: false,
		})
	}
	actions.push({
		kind: 'dns.create',
		description: row
			? `Publish the ownership and certificate validation records Kody reports (TXT or CNAME; HTTP validation needs no record).`
			: `Publish the ownership TXT ${ownershipName} (value comes from Kody after registration) and any certificate validation records Kody reports (HTTP validation needs no record).`,
		done: false,
	})
	actions.push({
		kind: 'kody.sync',
		description: `Sync with Kody (backoff ${SYNC_BACKOFF_SECONDS.join('s, ')}s) until hostname and SSL are active or ${input.waitMinutes} minute(s) pass.`,
		done: false,
	})

	const manualSteps = (records: RecordOutcome[]) => records.filter((record) => record.outcome === 'manual' && record.note).map((record) => record.note as string)

	if (dryRun) {
		if (row) {
			await reconcileAll(row, false)
		} else {
			verification = [
				{
					purpose: 'ownership',
					kind: 'txt',
					type: 'TXT',
					name: ownershipName,
					value: '',
					outcome: 'planned',
					note: 'Kody issues the value at registration. Certificate validation records (if any) are reported then too.',
				},
			]
		}
		const records = [routing, ...verification]
		const manual = manualSteps(records)
		const nextSteps = ['Re-run without dryRun to apply these actions.', ...manual]
		return {
			ok: true,
			status: 'planned',
			...base,
			...statusFields(row),
			actions,
			syncAttempts: 0,
			warnings,
			nextStep: nextSteps.join(' '),
			records,
			needsManualAction: manual.length > 0,
			nextSteps,
		}
	}

	const applied: PlannedAction[] = []
	let latest: KodyHostnameResult | null = null
	if (!row) {
		latest = await kody.packageAppCustomHostnameAdd({ hostname, binding_kind: 'app', package_id: pkg.package_id })
		row = latest.hostname
		applied.push({ kind: 'kody.add', description: `Registered ${hostname} in Kody for ${pkg.name}.`, done: true })
	}
	if (cname.state === 'create') {
		target = (latest?.dns?.target && latest.dns.target.trim()) || target
		routing.value = target
	}

	const reported = new Set<string>()
	const recordActions = () => {
		for (const [key, outcome] of written) {
			if (reported.has(key)) continue
			reported.add(key)
			applied.push({
				kind: outcome.outcome === 'updated' ? 'dns.update' : 'dns.create',
				description: `${outcome.outcome === 'updated' ? 'Updated' : 'Created'} ${outcome.purpose} ${outcome.type} ${outcome.name}.`,
				record: { type: outcome.type, name: outcome.name, content: outcome.value, id: outcome.id },
				done: true,
			})
		}
	}

	await reconcileAll(latest ?? row, true)
	recordActions()
	if (cname.state === 'create') {
		const created = await createRecord({ type: 'CNAME', name: hostname, content: target, proxied: false }, 'cname', `create CNAME ${hostname}`)
		if (created.error) {
			routing.outcome = 'manual'
			routing.note = `Could not create the DNS-only CNAME ${hostname} -> ${target}: ${created.error}. ${permissionHint}`
		} else {
			routing.outcome = 'created'
			if (created.id) routing.id = created.id
			applied.push({
				kind: 'dns.create',
				description: `Created DNS-only CNAME ${hostname} -> ${target}.`,
				record: { type: 'CNAME', name: hostname, content: target, proxied: false, id: created.id },
				done: true,
			})
		}
	}

	const deadline = now() + input.waitMinutes * 60_000
	let attempts = 0
	let syncError: string | null = null
	for (;;) {
		try {
			latest = await kody.packageAppCustomHostnameSync({ hostname })
		} catch (error) {
			syncError = errorMessage(error)
			break
		}
		attempts += 1
		row = latest.hostname
		await reconcileAll(latest, true)
		recordActions()
		if (isActive(row)) break
		const delay = SYNC_BACKOFF_SECONDS[Math.min(attempts - 1, SYNC_BACKOFF_SECONDS.length - 1)] * 1000
		const remaining = deadline - now()
		if (remaining <= 0) break
		await sleep(Math.min(delay, remaining))
	}
	if (attempts) applied.push({ kind: 'kody.sync', description: `Synced ${attempts} time(s).`, done: true })

	const active = isActive(row)
	if (active) {
		verification = verification.map((record) =>
			record.outcome === 'manual' ? { ...record, outcome: 'not_needed', note: 'The hostname and certificate went active, so this step is no longer needed.' } : record,
		)
	}
	const records = [routing, ...verification]
	const manual = manualSteps(records)
	const nextSteps: string[] = [...manual]
	if (syncError) {
		nextSteps.push(`Syncing with Kody failed (${syncError}). Everything above was still applied; re-run the same call to sync again.`)
	}
	const fields = statusFields(row)
	if (!active) {
		if (fields.kodyStatus?.state === 'needs_attention') {
			nextSteps.push(`Kody marked ${hostname} as needing attention${fields.kodyStatus.reason ? `: ${fields.kodyStatus.reason}` : ''}. Fix that, then re-run (the call syncs again).`)
		}
		if (verification.some((record) => record.kind === 'http' && record.purpose === 'certificate')) {
			nextSteps.push('The certificate uses HTTP validation, which completes through the CNAME with no extra record; it usually goes active within a few minutes.')
		}
		nextSteps.push(
			`Re-run the same call (it is idempotent) in a minute or two to check again; still ${row?.hostname_status}/${row?.ssl_status}. Kody also re-checks pending hostnames on its own every few minutes.`,
		)
	}
	return {
		ok: true,
		status: active ? 'active' : 'pending',
		...base,
		...fields,
		actions: applied,
		syncAttempts: attempts,
		warnings,
		nextStep: nextSteps.length ? nextSteps.join(' ') : null,
		records,
		needsManualAction: manual.length > 0,
		nextSteps,
	}
}

/**
 * Remove a custom hostname set up by `setupCustomDomain`: DNS records whose
 * comment carries the helper marker, then the Kody hostname row. Records the
 * helper did not create are reported and left alone.
 */
export async function removeCustomDomain(rawInput: unknown, deps: CustomDomainDeps): Promise<CustomDomainRemoveResult> {
	const input = parseRemoveInput(rawInput)
	const { kody, cloudflare } = deps
	const { hostname } = input
	const zone = await findZone(cloudflare, hostname)
	const { hostnames } = await kody.packageAppCustomHostnameList({})
	const row = hostnames.find((candidate) => sameHost(candidate.hostname, hostname)) ?? null

	const names = new Set([hostname, `_cf-custom-hostname.${hostname}`, `_acme-challenge.${hostname}`])
	// Only DNS-backed validation records have a name to look under (HTTP and email validation have none).
	for (const { record } of verificationEntries(row)) {
		const kind = validationKind(record.type)
		const name = String(record.name ?? '').toLowerCase().replace(/\.$/, '')
		if ((kind === 'txt' || kind === 'cname') && name && inZone(name, zone.name)) names.add(name)
	}
	const actions: PlannedAction[] = []
	const skipped: CustomDomainRemoveResult['skipped'] = []
	for (const name of names) {
		for (const record of await listRecords(cloudflare, zone.id, name)) {
			if (isOurs(record)) {
				actions.push({
					kind: 'dns.delete',
					description: `Delete ${record.type} ${record.name}.`,
					record: { type: record.type, name: record.name, content: record.content, id: record.id },
					done: false,
				})
			} else {
				skipped.push({ type: record.type, name: record.name, content: record.content, reason: 'not created by this helper (no kody-custom-domain comment)' })
			}
		}
	}
	if (row) {
		actions.push({ kind: 'kody.delete', description: `Delete the Kody hostname registration ${hostname} (${row.id}).`, done: false })
	}
	const base = { hostname, zone: { id: zone.id, name: zone.name }, skipped }
	if (actions.length === 0) {
		return { ok: true, status: 'nothing_to_remove', dryRun: !input.confirm, ...base, actions, nextStep: null }
	}
	if (!input.confirm) {
		return { ok: true, status: 'planned', dryRun: true, ...base, actions, nextStep: 'Re-run with confirm: true to apply these deletions.' }
	}
	for (const action of actions) {
		if (action.kind === 'dns.delete' && action.record?.id) {
			await cfOk(cloudflare, { method: 'DELETE', path: `/client/v4/zones/${zone.id}/dns_records/${action.record.id}` }, `delete ${action.record.type} ${action.record.name}`)
			action.done = true
		} else if (action.kind === 'kody.delete') {
			if (!kody.packageAppCustomHostnameDelete) throw new Error('packageAppCustomHostnameDelete is not available on this kody client.')
			await kody.packageAppCustomHostnameDelete({ hostname })
			action.done = true
		}
	}
	return {
		ok: true,
		status: 'removed',
		dryRun: false,
		...base,
		actions,
		nextStep: skipped.length ? 'Some records were left in place because this helper did not create them; delete them by hand if they are no longer needed.' : null,
	}
}