import assert from 'node:assert/strict' import { describe, it } from 'node:test' import { normalizeHostname, parseSetupInput, planCname, planTxt, removeCustomDomain, setupCustomDomain, zoneCandidates, type CloudflareRequest, type DnsRecord, type KodyCustomDomainClient, type KodyHostnameResult, type KodyHostnameRow, validationKind, } from '../src/custom-domain-core.ts' import type { CloudflareApiV4Result } from '../src/api-v4.ts' const PKG = { package_id: '1fdc2a34-676e-4f4b-ae49-394f8dd45d1a', kody_id: 'web-app', slug: 'web-app', name: '@acme/web-app', has_app: true, internet_visible: true, } const OTHER = { ...PKG, package_id: '8012b9ea-ae66-4bff-b986-763062754b71', kody_id: 'other-app', slug: 'other-app', name: '@acme/other-app' } const ZONE = { id: 'zone1', name: 'example.com', status: 'active' } const HOST = 'app.example.com' function ok(result: unknown): CloudflareApiV4Result { return { status: 200, httpStatus: 200, body: { success: true, result }, success: true, result, resultInfo: null, errors: [], messages: [] } } function row(overrides: Partial = {}): KodyHostnameRow { return { id: 'row1', hostname: HOST, binding_kind: 'app', package_id: PKG.package_id, hostname_status: 'pending', ssl_status: 'pending_validation', verification: { ownership_verification: { type: 'txt', name: `_cf-custom-hostname.${HOST}`, value: 'owner-token' }, ssl_validation_records: [], }, ...overrides, } } function result(r: KodyHostnameRow): KodyHostnameResult { return { hostname: r, dns: { type: 'CNAME', name: r.hostname, target: 'domains.kody.run' }, verification: r.verification } } /** In-memory Cloudflare zone + Kody hostname table. Records every write. */ function harness(opts: { records?: DnsRecord[] rows?: KodyHostnameRow[] zones?: Array syncSequence?: KodyHostnameRow[] packages?: Array /** Verification Kody returns from add (defaults to an ownership TXT and no SSL records). */ addVerification?: KodyHostnameRow['verification'] /** Make Cloudflare DNS writes fail with this HTTP status. */ failWrites?: number } = {}) { const records: DnsRecord[] = [...(opts.records ?? [])] const rows: KodyHostnameRow[] = [...(opts.rows ?? [])] const zones = opts.zones ?? [ZONE] const syncSequence = [...(opts.syncSequence ?? [])] const writes: string[] = [] let nextId = 1 const cloudflare = async (req: CloudflareRequest) => { const method = req.method ?? 'GET' if (method === 'GET' && req.path === '/client/v4/zones') { return ok(zones.filter((zone) => zone.name === req.query?.name)) } const match = req.path.match(/^\/client\/v4\/zones\/([^/]+)\/dns_records(?:\/([^/]+))?$/) assert.ok(match, `unexpected path ${req.path}`) if (method === 'GET') return ok(records.filter((record) => record.name === req.query?.name)) writes.push(`${method} ${req.path}`) if (opts.failWrites) { return { status: opts.failWrites, httpStatus: opts.failWrites, body: null, success: false, result: null, resultInfo: null, errors: [{ code: 10000, message: 'Authentication error' }], messages: [] } } if (method === 'POST') { const body = req.body as DnsRecord const created = { ...body, id: `rec${nextId++}` } records.push(created) return ok(created) } const index = records.findIndex((record) => record.id === match[2]) if (method === 'PATCH') { Object.assign(records[index], req.body as object) return ok(records[index]) } records.splice(index, 1) return ok({ id: match[2] }) } const kody: KodyCustomDomainClient = { packageList: async () => ({ packages: opts.packages ?? [PKG, OTHER] }), packageAppCustomHostnameList: async () => ({ hostnames: rows }), packageAppCustomHostnameAdd: async (input) => { writes.push(`kody.add ${input.hostname}`) const added = row({ hostname: input.hostname, package_id: input.package_id, ...(opts.addVerification ? { verification: opts.addVerification } : {}) }) rows.push(added) return result(added) }, packageAppCustomHostnameSync: async (input) => { writes.push(`kody.sync ${input.hostname}`) const next = syncSequence.length > 1 ? syncSequence.shift()! : syncSequence[0] ?? rows[0] rows[0] = next return result(next) }, packageAppCustomHostnameDelete: async (input) => { writes.push(`kody.delete ${input.hostname}`) rows.splice(0, rows.length) return { ok: true, id: 'row1', hostname: input.hostname } }, } let clock = 0 const sleeps: number[] = [] const deps = { kody, cloudflare, now: () => clock, sleep: async (ms: number) => { sleeps.push(ms) clock += ms }, } return { deps, records, rows, writes, sleeps } } const activeRow = row({ hostname_status: 'active', ssl_status: 'active', verification: { ownership_verification: null, ssl_validation_records: [] } }) const goodCname: DnsRecord = { id: 'c1', type: 'CNAME', name: HOST, content: 'domains.kody.run', proxied: false, comment: 'hand made' } describe('hostname validation', () => { it('normalizes case and trailing dot', () => { assert.equal(normalizeHostname(' App.Example.COM. '), HOST) }) it("rejects Kody's own domains", () => { for (const host of ['kody.codes', 'x.kody.codes', 'kody.run', 'a.b.kody.run']) { assert.throws(() => normalizeHostname(host), /Kody refuses custom hostnames/) } assert.equal(normalizeHostname('notkody.run'), 'notkody.run') }) it('rejects schemes, paths, ports, wildcards, and junk', () => { for (const bad of ['https://a.example.com', 'a.example.com/x', 'a.example.com:443', '*.example.com', 'example', '-a.example.com', '1.2.3.4', '']) { assert.throws(() => normalizeHostname(bad)) } }) it('rejects unknown keys and bad waitMinutes', () => { assert.throws(() => parseSetupInput({ hostname: HOST, package: 'x', dryrun: true }), /Unknown custom-domain input key\(s\): dryrun/) assert.throws(() => parseSetupInput({ hostname: HOST, package: 'x', waitMinutes: 99 }), /waitMinutes/) assert.throws(() => parseSetupInput({ hostname: HOST }), /package is required/) assert.equal(parseSetupInput({ hostname: HOST, package: 'x' }).waitMinutes, 1) }) it('lists zone candidates most specific first', () => { assert.deepEqual(zoneCandidates('a.b.example.com'), ['a.b.example.com', 'b.example.com', 'example.com']) }) }) describe('record planning', () => { it('accepts a matching DNS-only CNAME and flags proxied or foreign records', () => { assert.equal(planCname([], HOST, 'domains.kody.run').state, 'create') assert.equal(planCname([goodCname], HOST, 'domains.kody.run').state, 'present') assert.equal(planCname([{ ...goodCname, proxied: true }], HOST, 'domains.kody.run').state, 'conflict') assert.equal(planCname([{ ...goodCname, content: 'elsewhere.com' }], HOST, 'domains.kody.run').state, 'conflict') assert.equal(planCname([{ id: 'a', type: 'A', name: HOST, content: '1.2.3.4' }], HOST, 'domains.kody.run').state, 'conflict') }) it('matches quoted TXT values, only updates records it owns, and adds beside foreign TXT', () => { const name = `_cf-custom-hostname.${HOST}` const mine = { id: 't', type: 'TXT', name, content: 'old', comment: 'kody-custom-domain ownership for x' } assert.equal(planTxt([{ id: 't', type: 'TXT', name, content: '"v1"' }], name, 'v1').state, 'present') const beside = planTxt([{ id: 't', type: 'TXT', name, content: 'old' }], name, 'v1') assert.equal(beside.state, 'create') assert.equal(beside.state === 'create' && beside.foreign.length, 1) assert.equal(planTxt([mine], name, 'v1').state, 'update') // A second value Kody expects at the same name is added, not written over the first. assert.equal(planTxt([{ ...mine, content: 'v1' }], name, 'v2', ['v1']).state, 'create') assert.equal(planTxt([{ id: 'c', type: 'CNAME', name, content: 'x.example.net' }], name, 'v1').state, 'conflict') assert.equal(planTxt([], name, 'v1').state, 'create') }) it('maps every validation type Kody can report', () => { assert.equal(validationKind('txt'), 'txt') assert.equal(validationKind('TXT'), 'txt') assert.equal(validationKind('cname'), 'cname') assert.equal(validationKind('http'), 'http') assert.equal(validationKind('HTTP-01'), 'http') assert.equal(validationKind('email'), 'email') assert.equal(validationKind('carrier-pigeon'), 'unknown') assert.equal(validationKind(undefined), 'unknown') }) }) describe('setupCustomDomain', () => { it('reports already_configured with no writes for an active, correctly pointed hostname', async () => { const h = harness({ records: [goodCname], rows: [activeRow] }) const out = await setupCustomDomain({ hostname: HOST, package: '@acme/web-app', dryRun: true }, h.deps) assert.equal(out.status, 'already_configured') assert.deepEqual(out.actions, []) assert.equal(h.writes.length, 0) const real = await setupCustomDomain({ hostname: HOST, package: PKG.package_id }, h.deps) assert.equal(real.status, 'already_configured') assert.equal(h.writes.length, 0) }) it('dryRun on a fresh hostname plans add, CNAME, TXT, and sync without writing', async () => { const h = harness() const out = await setupCustomDomain({ hostname: HOST, package: 'web-app', dryRun: true }, h.deps) assert.equal(out.status, 'planned') assert.deepEqual(out.actions.map((a) => a.kind), ['kody.add', 'dns.create', 'dns.create', 'kody.sync']) assert.ok(out.actions.every((a) => !a.done)) assert.equal(h.writes.length, 0) }) it('creates everything, syncs with backoff, and adds SSL records Kody reports', async () => { const sslRow = row({ verification: { ownership_verification: { type: 'txt', name: `_cf-custom-hostname.${HOST}`, value: 'owner-token' }, ssl_validation_records: [{ type: 'txt', name: `_acme-challenge.${HOST}`, value: 'ssl-token' }], }, }) const h = harness({ syncSequence: [sslRow, sslRow, activeRow] }) const out = await setupCustomDomain({ hostname: HOST, package: '@acme/web-app', waitMinutes: 2 }, h.deps) assert.equal(out.status, 'active') assert.equal(out.syncAttempts, 3) assert.deepEqual(h.sleeps, [5000, 10000]) const byName = Object.fromEntries(h.records.map((r) => [r.name + ' ' + r.type, r])) assert.equal(byName[`${HOST} CNAME`].content, 'domains.kody.run') assert.equal(byName[`${HOST} CNAME`].proxied, false) assert.equal(byName[`_cf-custom-hostname.${HOST} TXT`].content, 'owner-token') assert.equal(byName[`_acme-challenge.${HOST} TXT`].content, 'ssl-token') assert.ok(h.records.every((r) => r.comment?.startsWith('kody-custom-domain'))) assert.equal(h.writes.filter((w) => w.startsWith('kody.add')).length, 1) }) it('returns pending when waitMinutes runs out, and a re-run finishes without duplicating', async () => { const h = harness({ syncSequence: [row()] }) const first = await setupCustomDomain({ hostname: HOST, package: '@acme/web-app', waitMinutes: 0 }, h.deps) assert.equal(first.status, 'pending') assert.match(first.nextStep ?? '', /Re-run/) const recordCount = h.records.length h.rows[0] = row() const h2writes = h.writes.length // Kody flips to active on the next sync. h.deps.kody.packageAppCustomHostnameSync = async () => result(activeRow) const second = await setupCustomDomain({ hostname: HOST, package: '@acme/web-app' }, h.deps) assert.equal(second.status, 'active') assert.equal(h.records.length, recordCount) assert.ok(!h.writes.slice(h2writes).some((w) => w.startsWith('kody.add') || w.startsWith('POST'))) }) it('refuses conflicting records without changing anything', async () => { const h = harness({ records: [{ id: 'a', type: 'A', name: HOST, content: '1.2.3.4' }] }) await assert.rejects(setupCustomDomain({ hostname: HOST, package: '@acme/web-app' }, h.deps), /nothing was changed[\s\S]*A app\.example\.com/) assert.equal(h.writes.length, 0) }) it('adds the ownership TXT beside a foreign TXT and never touches the foreign one', async () => { const foreign: DnsRecord = { id: 'f', type: 'TXT', name: `_cf-custom-hostname.${HOST}`, content: 'someone-else' } const h = harness({ records: [{ ...foreign }], syncSequence: [activeRow] }) const out = await setupCustomDomain({ hostname: HOST, package: '@acme/web-app' }, h.deps) assert.equal(out.status, 'active') assert.deepEqual(h.records.find((r) => r.id === 'f'), foreign) assert.ok(!h.writes.some((w) => w.includes('/dns_records/f'))) assert.ok(h.records.some((r) => r.name === foreign.name && r.content === 'owner-token' && r.comment?.startsWith('kody-custom-domain'))) assert.ok(out.warnings.some((w) => /left untouched/.test(w))) }) it('refuses a hostname registered to a different package', async () => { const h = harness({ rows: [row({ package_id: OTHER.package_id })] }) await assert.rejects(setupCustomDomain({ hostname: HOST, package: '@acme/web-app', dryRun: true }, h.deps), /not for @acme\/web-app/) }) it('fails clearly when no zone matches, at the apex, or the package has no app', async () => { await assert.rejects(setupCustomDomain({ hostname: 'a.nope.dev', package: 'web-app', dryRun: true }, harness().deps), /No Cloudflare zone for "a\.nope\.dev"/) await assert.rejects(setupCustomDomain({ hostname: 'example.com', package: 'web-app', dryRun: true }, harness().deps), /zone apex/) const noApp = harness({ packages: [{ ...PKG, has_app: false }] }) await assert.rejects(setupCustomDomain({ hostname: HOST, package: 'web-app', dryRun: true }, noApp.deps), /has no package app/) await assert.rejects(setupCustomDomain({ hostname: HOST, package: '@x/missing', dryRun: true }, harness().deps), /No saved package/) }) }) describe('setupCustomDomain validation types', () => { const ownershipTxt = { type: 'txt', name: `_cf-custom-hostname.${HOST}`, value: 'owner-token' } const pendingWith = (ssl: KodyHostnameRow['verification'] extends infer V ? V extends { ssl_validation_records: infer S } ? S : never : never, ownership: { type: string; name: string; value: string } | null = ownershipTxt) => row({ verification: { ownership_verification: ownership, ssl_validation_records: ssl } }) const posts = (h: ReturnType) => h.writes.filter((w) => w.startsWith('POST') || w.startsWith('PATCH')) it('http: needs no DNS record, keeps waiting, and finishes when the certificate goes active', async () => { const httpRecord = { type: 'http', name: `http://${HOST}/.well-known/acme-challenge/abc`, value: 'abc.def' } const pending = pendingWith([httpRecord]) const h = harness({ addVerification: pending.verification, syncSequence: [pending, pending, activeRow] }) const out = await setupCustomDomain({ hostname: HOST, package: '@acme/web-app', waitMinutes: 2 }, h.deps) assert.equal(out.status, 'active') assert.equal(out.syncAttempts, 3) assert.equal(out.hostnameStatus, 'active') assert.equal(out.sslStatus, 'active') assert.equal(out.needsManualAction, false) assert.deepEqual(out.nextSteps, []) // Only the routing CNAME and the ownership TXT were written; nothing for HTTP validation. assert.deepEqual(h.records.map((r) => `${r.type} ${r.name}`).sort(), [`CNAME ${HOST}`, `TXT _cf-custom-hostname.${HOST}`]) assert.equal(out.records.find((r) => r.purpose === 'routing')?.outcome, 'created') assert.equal(out.records.find((r) => r.purpose === 'ownership')?.outcome, 'created') }) it('http: returns pending (not an error) when waitMinutes runs out, with a note that the CNAME satisfies it', async () => { const pending = pendingWith([{ type: 'http', name: `http://${HOST}/.well-known/acme-challenge/abc`, value: 'abc.def' }]) const h = harness({ addVerification: pending.verification, syncSequence: [pending] }) const out = await setupCustomDomain({ hostname: HOST, package: '@acme/web-app', waitMinutes: 0 }, h.deps) assert.equal(out.status, 'pending') const http = out.records.find((r) => r.kind === 'http') assert.equal(http?.outcome, 'not_needed') assert.match(http?.note ?? '', /No DNS record is needed/) assert.ok(out.nextSteps.some((step) => /HTTP validation/.test(step))) assert.ok(out.nextSteps.some((step) => /Re-run/.test(step))) }) it('cname: creates a DNS-only CNAME validation record, and a re-run reuses it', async () => { const cnameRecord = { type: 'cname', name: `_acme-challenge.${HOST}`, value: `${HOST}.dcv.example.net` } const pending = pendingWith([cnameRecord]) const h = harness({ addVerification: pending.verification, syncSequence: [pending] }) const first = await setupCustomDomain({ hostname: HOST, package: '@acme/web-app', waitMinutes: 0 }, h.deps) assert.equal(first.status, 'pending') const created = h.records.find((r) => r.name === cnameRecord.name) assert.equal(created?.type, 'CNAME') assert.equal(created?.content, cnameRecord.value) assert.equal(created?.proxied, false) assert.equal(first.records.find((r) => r.name === cnameRecord.name)?.outcome, 'created') const before = posts(h).length const second = await setupCustomDomain({ hostname: HOST, package: '@acme/web-app', waitMinutes: 0 }, h.deps) assert.equal(posts(h).length, before) assert.equal(second.records.find((r) => r.name === cnameRecord.name)?.outcome, 'reused') assert.equal(second.records.find((r) => r.purpose === 'routing')?.outcome, 'reused') }) it('txt: two certificate TXT values at the same name are both published', async () => { const pending = pendingWith([ { type: 'txt', name: `_acme-challenge.${HOST}`, value: 'one' }, { type: 'txt', name: `_acme-challenge.${HOST}`, value: 'two' }, ]) const h = harness({ addVerification: pending.verification, syncSequence: [pending] }) await setupCustomDomain({ hostname: HOST, package: '@acme/web-app', waitMinutes: 0 }, h.deps) assert.deepEqual(h.records.filter((r) => r.name === `_acme-challenge.${HOST}`).map((r) => r.content).sort(), ['one', 'two']) assert.ok(!h.writes.some((w) => w.startsWith('PATCH'))) }) it('email and unknown types: finish everything else, then return clear manual next steps', async () => { const pending = pendingWith([ { type: 'email', name: HOST, value: 'admin@example.com' }, { type: 'carrier-pigeon', name: 'coop', value: 'coo' }, ]) const h = harness({ addVerification: pending.verification, syncSequence: [pending] }) const out = await setupCustomDomain({ hostname: HOST, package: '@acme/web-app', waitMinutes: 0 }, h.deps) assert.equal(out.ok, true) assert.equal(out.status, 'pending') assert.equal(out.needsManualAction, true) // The routing CNAME and ownership TXT were still created. assert.ok(h.records.some((r) => r.type === 'CNAME' && r.name === HOST)) assert.ok(h.records.some((r) => r.type === 'TXT' && r.name === `_cf-custom-hostname.${HOST}`)) assert.equal(out.records.find((r) => r.kind === 'email')?.outcome, 'manual') assert.equal(out.records.find((r) => r.kind === 'unknown')?.outcome, 'manual') assert.ok(out.nextSteps.some((step) => /by email/.test(step))) assert.ok(out.nextSteps.some((step) => /"carrier-pigeon"/.test(step) && /by hand/.test(step))) assert.ok(out.nextStep?.includes('carrier-pigeon')) }) it('ownership by http needs no TXT record', async () => { const pending = pendingWith([], { type: 'http', name: `http://${HOST}/.well-known/cf-custom-hostname-challenge/x`, value: 'y' }) const h = harness({ addVerification: pending.verification, syncSequence: [pending, activeRow] }) const out = await setupCustomDomain({ hostname: HOST, package: '@acme/web-app', waitMinutes: 1 }, h.deps) assert.equal(out.status, 'active') assert.deepEqual(h.records.map((r) => `${r.type} ${r.name}`), [`CNAME ${HOST}`]) assert.equal(out.records.find((r) => r.purpose === 'ownership')?.outcome, 'not_needed') }) it('a validation name blocked by a foreign CNAME becomes a manual step, not a mid-run throw', async () => { const blocker: DnsRecord = { id: 'b', type: 'CNAME', name: `_acme-challenge.${HOST}`, content: 'delegated.example.net' } const pending = pendingWith([{ type: 'txt', name: `_acme-challenge.${HOST}`, value: 'ssl-token' }]) const h = harness({ records: [{ ...blocker }], addVerification: pending.verification, syncSequence: [pending] }) const out = await setupCustomDomain({ hostname: HOST, package: '@acme/web-app', waitMinutes: 0 }, h.deps) assert.equal(out.status, 'pending') assert.equal(out.needsManualAction, true) assert.deepEqual(h.records.find((r) => r.id === 'b'), blocker) assert.ok(h.records.some((r) => r.type === 'CNAME' && r.name === HOST)) }) it('Cloudflare write errors are reported with a permission hint instead of throwing', async () => { const h = harness({ failWrites: 403, syncSequence: [row()] }) const out = await setupCustomDomain({ hostname: HOST, package: '@acme/web-app', waitMinutes: 0 }, h.deps) assert.equal(out.status, 'pending') assert.equal(out.records.find((r) => r.purpose === 'routing')?.outcome, 'manual') assert.ok(out.nextSteps.some((step) => /DNS: Edit/.test(step))) }) it('a failing Kody sync returns pending with a next step', async () => { const h = harness() h.deps.kody.packageAppCustomHostnameSync = async () => { throw new Error('rate limited') } const out = await setupCustomDomain({ hostname: HOST, package: '@acme/web-app' }, h.deps) assert.equal(out.status, 'pending') assert.equal(out.syncAttempts, 0) assert.ok(out.nextSteps.some((step) => /rate limited/.test(step))) }) it('surfaces needs_attention from Kody', async () => { const stuck = row({ status: { state: 'needs_attention', reason: 'CAA records block issuance' } }) const h = harness({ syncSequence: [stuck] }) const out = await setupCustomDomain({ hostname: HOST, package: '@acme/web-app', waitMinutes: 0 }, h.deps) assert.deepEqual(out.kodyStatus, { state: 'needs_attention', reason: 'CAA records block issuance' }) assert.ok(out.nextSteps.some((step) => /CAA records/.test(step))) }) }) describe('setupCustomDomain reruns', () => { it('dryRun on a set-up but pending hostname reports what is in place and writes nothing', async () => { const pending = row({ verification: { ownership_verification: { type: 'txt', name: `_cf-custom-hostname.${HOST}`, value: 'owner-token' }, ssl_validation_records: [{ type: 'http', name: `http://${HOST}/.well-known/acme-challenge/a`, value: 'b' }], }, }) const ownTxt: DnsRecord = { id: 'o', type: 'TXT', name: `_cf-custom-hostname.${HOST}`, content: '"owner-token"' } const h = harness({ records: [goodCname, ownTxt], rows: [pending] }) const out = await setupCustomDomain({ hostname: HOST, package: '@acme/web-app', dryRun: true }, h.deps) assert.equal(out.status, 'planned') assert.equal(h.writes.length, 0) assert.deepEqual( out.records.map((r) => `${r.purpose}:${r.outcome}`), ['routing:reused', 'ownership:reused', 'certificate:not_needed'], ) assert.ok(!out.actions.some((a) => a.kind === 'kody.add')) }) it('already_configured lists the reused routing record and nothing else to do', async () => { const h = harness({ records: [goodCname], rows: [activeRow] }) const out = await setupCustomDomain({ hostname: HOST, package: '@acme/web-app', dryRun: true }, h.deps) assert.equal(out.status, 'already_configured') assert.deepEqual(out.records, [{ purpose: 'routing', kind: 'cname', type: 'CNAME', name: HOST, value: 'domains.kody.run', outcome: 'reused', id: 'c1' }]) assert.equal(out.hostnameStatus, 'active') assert.equal(out.sslStatus, 'active') assert.equal(out.needsManualAction, false) assert.deepEqual(out.nextSteps, []) }) it('never touches other hostnames or their records', async () => { const otherRow = row({ id: 'row2', hostname: 'other.example.com', package_id: OTHER.package_id }) const otherRecord: DnsRecord = { id: 'x', type: 'CNAME', name: 'other.example.com', content: 'domains.kody.run', comment: 'kody-custom-domain cname for y' } const h = harness({ records: [{ ...otherRecord }], rows: [otherRow], syncSequence: [activeRow] }) await setupCustomDomain({ hostname: HOST, package: '@acme/web-app' }, h.deps) assert.deepEqual(h.records.find((r) => r.id === 'x'), otherRecord) assert.ok(h.writes.every((w) => !w.includes('other.example.com') && !w.endsWith('/x'))) }) it('picks the longest matching zone (a delegated subdomain zone beats its parent)', async () => { const sub = { id: 'zone2', name: 'apps.example.com', status: 'active' } const h = harness({ zones: [ZONE, sub] }) const out = await setupCustomDomain({ hostname: 'web.apps.example.com', package: 'web-app', dryRun: true }, h.deps) assert.deepEqual(out.zone, { id: 'zone2', name: 'apps.example.com' }) }) }) describe('removeCustomDomain', () => { it('plans without confirm, then deletes only marked records and the Kody row', async () => { const marked = (id: string, type: string, name: string, content: string): DnsRecord => ({ id, type, name, content, comment: 'kody-custom-domain x for y' }) const h = harness({ records: [ marked('c', 'CNAME', HOST, 'domains.kody.run'), marked('t', 'TXT', `_cf-custom-hostname.${HOST}`, 'owner-token'), { id: 'keep', type: 'TXT', name: `_acme-challenge.${HOST}`, content: 'manual' }, ], rows: [activeRow], }) const plan = await removeCustomDomain({ hostname: HOST }, h.deps) assert.equal(plan.status, 'planned') assert.equal(h.writes.length, 0) assert.equal(plan.skipped.length, 1) const done = await removeCustomDomain({ hostname: HOST, confirm: true }, h.deps) assert.equal(done.status, 'removed') assert.deepEqual(h.records.map((r) => r.id), ['keep']) assert.ok(h.writes.includes(`kody.delete ${HOST}`)) }) it('reports nothing_to_remove when there is nothing it owns', async () => { const h = harness({ records: [goodCname] }) const out = await removeCustomDomain({ hostname: HOST, confirm: true }, h.deps) assert.equal(out.status, 'nothing_to_remove') assert.equal(h.writes.length, 0) }) it('ignores HTTP validation records when looking for records to remove', async () => { const httpRow = row({ hostname_status: 'active', ssl_status: 'active', verification: { ownership_verification: null, ssl_validation_records: [{ type: 'http', name: `http://${HOST}/.well-known/acme-challenge/a`, value: 'b' }] }, }) const h = harness({ records: [goodCname], rows: [httpRow] }) const out = await removeCustomDomain({ hostname: HOST }, h.deps) assert.equal(out.status, 'planned') assert.deepEqual(out.actions.map((a) => a.kind), ['kody.delete']) }) })