diff options
Diffstat (limited to 'names/dns-migrate.js')
| -rw-r--r-- | names/dns-migrate.js | 89 |
1 files changed, 89 insertions, 0 deletions
diff --git a/names/dns-migrate.js b/names/dns-migrate.js new file mode 100644 index 0000000..30ee2b0 --- /dev/null +++ b/names/dns-migrate.js @@ -0,0 +1,89 @@ +// One-shot moves of the BIP-353 records from Cloudflare to Knot (dns/). +// Run inside the names container, where its config and database are: +// docker exec names bun names/dns-migrate.js backfill every name of a knot domain → Knot +// docker exec names bun names/dns-migrate.js check Knot holds what the database says +// docker exec names bun names/dns-migrate.js cf-cleanup delete the per-name TXT records from Cloudflare +// The database is only read: the running registrar owns it. Names it writes +// after the switch go to Knot themselves, and a stale Cloudflare record id +// left in the database is harmless (knotWrite's cleanup of it just fails). +import { Database } from 'bun:sqlite'; +import { readFileSync } from 'node:fs'; +import { dnsUpdate } from './dns-update.js'; + +const CFG = JSON.parse(readFileSync(process.env.NAMES_CONFIG, 'utf8')); +const DOMAINS = CFG.domains || {}; +const TTL = 300; +const recordName = (name, domain) => `${name}.user._bitcoin-payment.${domain}`; +const knotDomains = Object.keys(DOMAINS).filter((d) => DOMAINS[d].knot); +const log = (...a) => console.log(new Date().toISOString(), ...a); + +function names() { + const db = new Database(CFG.dbFile || '/data/names.db', { readonly: true }); + const rows = db.query("SELECT key, val FROM kv WHERE coll = 'names'").all(); + db.close(); + return rows.map((r) => ({ key: r.key, ...JSON.parse(r.val) })) + .map((r) => ({ ...r, name: r.key.split('@')[0], domain: r.domain || r.key.split('@')[1] })) + .filter((r) => knotDomains.includes(r.domain) && r.uri && r.recordId); +} + +async function backfill() { + for (const domain of knotDomains) { + const recs = names().filter((r) => r.domain === domain); + log(`${domain}: ${recs.length} names → ${DOMAINS[domain].knot.zone}`); + for (let i = 0; i < recs.length; i += 25) { + const batch = recs.slice(i, i + 25); + await dnsUpdate(DOMAINS[domain].knot, batch.map((r) => ({ name: recordName(r.name, domain), value: r.uri })), TTL); + } + log(`${domain}: done`); + } +} + +// Ask Knot directly (TCP, no recursion) for each name and compare. +async function check() { + const { Resolver } = await import('node:dns/promises'); + let bad = 0, n = 0; + for (const domain of knotDomains) { + const k = DOMAINS[domain].knot; + const res = new Resolver(); + const { address } = await import('node:dns/promises').then((d) => d.lookup(k.server || 'dns')); + res.setServers([`${address}:${k.port || 53}`]); + for (const r of names().filter((x) => x.domain === domain)) { + n++; + const got = await res.resolveTxt(recordName(r.name, domain)).then((t) => t.map((c) => c.join('')), () => []); + if (got.length !== 1 || got[0] !== r.uri) { bad++; if (bad <= 10) log(`mismatch ${r.key}: ${JSON.stringify(got).slice(0, 80)}`); } + } + } + log(`checked ${n}, ${bad} mismatched`); + if (bad) process.exitCode = 1; +} + +async function cfCleanup() { + const CF = 'https://api.cloudflare.com/client/v4'; + const headers = { 'X-Auth-Email': CFG.cfEmail, 'X-Auth-Key': CFG.cfKey, 'content-type': 'application/json' }; + for (const domain of knotDomains) { + const zoneId = DOMAINS[domain].zoneId; + const suffix = `.user._bitcoin-payment.${domain}`; + let deleted = 0; + for (;;) { + const r = await fetch(`${CF}/zones/${zoneId}/dns_records?type=TXT&name.endswith=${encodeURIComponent(suffix)}&per_page=500`, { headers }).then((x) => x.json()); + if (!r.success) throw new Error('list failed: ' + JSON.stringify(r.errors)); + // only one-label names directly under the subtree, exactly as the registrar wrote them + const recs = r.result.filter((x) => x.name.endsWith(suffix) && x.name.length > suffix.length); + if (!recs.length) break; + for (const x of recs) { + const d = await fetch(`${CF}/zones/${zoneId}/dns_records/${x.id}`, { method: 'DELETE', headers }).then((y) => y.json()); + if (!d.success) { log(`delete ${x.name} failed: ${JSON.stringify(d.errors)}`); await Bun.sleep(5000); continue; } + deleted++; + await Bun.sleep(260); // under Cloudflare's 1,200 requests / 5 minutes + } + log(`${domain}: ${deleted} deleted so far`); + } + log(`${domain}: ${deleted} Cloudflare records deleted`); + } +} + +const cmd = process.argv[2]; +if (cmd === 'backfill') await backfill(); +else if (cmd === 'check') await check(); +else if (cmd === 'cf-cleanup') await cfCleanup(); +else { console.error('usage: dns-migrate.js backfill | check | cf-cleanup'); process.exitCode = 2; } |
