diff options
| author | Adam Soltys <[email protected]> | 2026-11-15 21:30:02 -0700 |
|---|---|---|
| committer | Adam Soltys <[email protected]> | 2026-11-15 21:30:02 -0700 |
| commit | 4b222a2043ff2abc0edffe553700d5f1fe9519f7 (patch) | |
| tree | 89ca531b3ce85480f2b09d065b3f319aeba6c9e9 /names | |
| parent | 4aa5606408f7188a7edda5c010793f9d7d1dc076 (diff) | |
| download | coinosv3-server-4b222a2043ff2abc0edffe553700d5f1fe9519f7.tar.gz coinosv3-server-4b222a2043ff2abc0edffe553700d5f1fe9519f7.zip | |
BIP-353 records move to our own DNS: Knot on cs, served from ovh2. "just learned cloudflare may have a quota on how many names we can register on dns so is that going to foil our plans to give everyone a bip353 payment address?" … "yeah build it on cs don't worry about the fallback just get it working with our knot dns" (Adam, 2026-11-16). coinos.io's Cloudflare zone (Pro) was at 3,038 of its 3,500 records with one TXT per name and about 35 names claimed a day. user._bitcoin-payment.coinos.io and user._bitcoin-payment.staging.coinos.io get delegated (NS + DS in Cloudflare) to Knot DNS, so there's no record quota. The `dns` compose service on cs is the hidden primary: it signs both zones (ECDSA P-256, NSEC3 without iterations, the KSK fixed because its DS sits in Cloudflare) and listens on cs's Tailscale address only, because the house router forwards nothing to cs. ovh2 runs the public secondary (dns/secondary.conf, dns1.coinos.io), notified and transferred over Tailscale with a TSIG key, so names keep resolving while cs is down. The registrar sends RFC 2136 UPDATEs signed with TSIG hmac-sha256 over TCP (names/dns-update.js) for domains with `knot` in its config. It replaces a name's TXT RRset whole, removes it on release and on account deletion (forgetAccount now hands back the name), and deletes a name's leftover Cloudflare record as it rewrites it. names/dns-migrate.js does the one-shot moves: backfill, check, cf-cleanup. dns/README.md is the runbook. Tested against Knot 3.4.11: updates land signed, a 700-byte URI spans several TXT strings, a wrong key gets NOTAUTH and an out-of-zone name gets NOTZONE. bun test names/ passes (21, with the new dns-update tests)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VMan6SwkivduFDDkMmnXjZ
Diffstat (limited to 'names')
| -rw-r--r-- | names/dns-migrate.js | 89 | ||||
| -rw-r--r-- | names/dns-update.js | 90 | ||||
| -rw-r--r-- | names/dns-update.test.js | 21 | ||||
| -rw-r--r-- | names/forget.js | 2 | ||||
| -rw-r--r-- | names/forget.test.js | 2 | ||||
| -rw-r--r-- | names/server.js | 28 |
6 files changed, 227 insertions, 5 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; } diff --git a/names/dns-update.js b/names/dns-update.js new file mode 100644 index 0000000..021caf5 --- /dev/null +++ b/names/dns-update.js @@ -0,0 +1,90 @@ +// BIP-353 records on our own DNS server (Knot, dns/), not Cloudflare. +// Cloudflare caps a zone at 3,500 records (Pro) and coinos.io reached 3,038 +// with one TXT per name (2026-11-16), so `user._bitcoin-payment.<domain>` is +// delegated to Knot, which signs it (DNSSEC) and takes changes as RFC 2136 +// UPDATE messages authenticated with TSIG (RFC 8945, hmac-sha256), over TCP +// (an ark + lno URI doesn't fit a 512-byte UDP message). +import { createHmac, randomInt } from 'node:crypto'; +import { connect } from 'node:net'; + +const TYPE = { TXT: 16, SOA: 6, ANY: 255, TSIG: 250 }; +const CLASS = { IN: 1, NONE: 254, ANY: 255 }; + +function nameWire(name) { + const parts = String(name).replace(/\.$/, '').split('.').filter(Boolean); + const out = []; + for (const p of parts) { + const b = Buffer.from(p.toLowerCase(), 'ascii'); + if (!b.length || b.length > 63) throw new Error(`bad DNS label in ${name}`); + out.push(Buffer.from([b.length]), b); + } + out.push(Buffer.from([0])); + return Buffer.concat(out); +} +const u16 = (n) => { const b = Buffer.alloc(2); b.writeUInt16BE(n); return b; }; +const u32 = (n) => { const b = Buffer.alloc(4); b.writeUInt32BE(n >>> 0); return b; }; +const u48 = (n) => { const b = Buffer.alloc(6); b.writeUIntBE(n, 0, 6); return b; }; + +// TXT rdata: the value as ≤255-byte character-strings, in order (BIP-353 +// readers concatenate them) +export function txtRdata(value) { + const bytes = Buffer.from(String(value), 'utf8'); + const out = []; + for (let i = 0; i < bytes.length || i === 0; i += 255) { + const c = bytes.subarray(i, i + 255); + out.push(Buffer.from([c.length]), c); + if (!bytes.length) break; + } + return Buffer.concat(out); +} +const rr = (name, type, cls, ttl, rdata = Buffer.alloc(0)) => + Buffer.concat([nameWire(name), u16(type), u16(cls), u32(ttl), u16(rdata.length), rdata]); + +// ops: [{ name, value? }] — every op replaces the name's TXT records with +// `value`, or removes them when value is null +export function buildUpdate(zone, ops, ttl, key, { id = randomInt(0, 65536), now = Math.floor(Date.now() / 1000) } = {}) { + const updates = []; + for (const op of ops) { + updates.push(rr(op.name, TYPE.TXT, CLASS.ANY, 0)); // delete the RRset + if (op.value != null) updates.push(rr(op.name, TYPE.TXT, CLASS.IN, ttl, txtRdata(op.value))); + } + const header = (arcount) => Buffer.concat([u16(id), u16(5 << 11), u16(1), u16(0), u16(updates.length), u16(arcount)]); + const zoneSec = Buffer.concat([nameWire(zone), u16(TYPE.SOA), u16(CLASS.IN)]); + const body = Buffer.concat([zoneSec, ...updates]); + const unsigned = Buffer.concat([header(0), body]); + // TSIG: MAC over the message, then the TSIG variables (RFC 8945 §4.3.3) + const keyName = nameWire(key.name), alg = nameWire('hmac-sha256'); + const fudge = 300; + const vars = Buffer.concat([keyName, u16(CLASS.ANY), u32(0), alg, u48(now), u16(fudge), u16(0), u16(0)]); + const mac = createHmac('sha256', Buffer.from(key.secret, 'base64')).update(unsigned).update(vars).digest(); + const tsigRdata = Buffer.concat([alg, u48(now), u16(fudge), u16(mac.length), mac, u16(id), u16(0), u16(0)]); + const tsig = Buffer.concat([keyName, u16(TYPE.TSIG), u16(CLASS.ANY), u32(0), u16(tsigRdata.length), tsigRdata]); + return { id, msg: Buffer.concat([header(1), body, tsig]) }; +} + +const RCODES = ['NOERROR', 'FORMERR', 'SERVFAIL', 'NXDOMAIN', 'NOTIMP', 'REFUSED', 'YXDOMAIN', 'YXRRSET', 'NXRRSET', 'NOTAUTH', 'NOTZONE']; + +function exchange(host, port, msg, timeoutMs) { + return new Promise((resolve, reject) => { + const sock = connect({ host, port }); + let buf = Buffer.alloc(0); + const done = (err, v) => { clearTimeout(timer); sock.destroy(); err ? reject(err) : resolve(v); }; + const timer = setTimeout(() => done(new Error(`dns update to ${host}:${port} timed out`)), timeoutMs); + sock.on('connect', () => sock.write(Buffer.concat([u16(msg.length), msg]))); + sock.on('data', (d) => { + buf = Buffer.concat([buf, d]); + if (buf.length >= 2 && buf.length >= 2 + buf.readUInt16BE(0)) done(null, buf.subarray(2, 2 + buf.readUInt16BE(0))); + }); + sock.on('error', (e) => done(e)); + }); +} + +// Send one UPDATE; throws unless the server answers NOERROR. +export async function dnsUpdate(cfg, ops, ttl) { + if (!ops.length) return; + const { id, msg } = buildUpdate(cfg.zone, ops, ttl, cfg.key); + const res = await exchange(cfg.server || 'dns', cfg.port || 53, msg, cfg.timeoutMs || 10000); + if (res.length < 12 || res.readUInt16BE(0) !== id) throw new Error('dns update: bad reply'); + const rcode = res.readUInt16BE(2) & 0xf; + if (rcode) throw new Error(`dns update refused: ${RCODES[rcode] || rcode}`); +} diff --git a/names/dns-update.test.js b/names/dns-update.test.js new file mode 100644 index 0000000..536d037 --- /dev/null +++ b/names/dns-update.test.js @@ -0,0 +1,21 @@ +import { expect, test } from 'bun:test'; +import { txtRdata, buildUpdate } from './dns-update.js'; + +test('TXT values split into 255-byte strings, in order', () => { + const v = 'x'.repeat(600); + const r = txtRdata(v); + expect([r[0], r[256], r[512]]).toEqual([255, 255, 90]); + expect(r.length).toBe(600 + 3); +}); + +test('an UPDATE is opcode 5 for the zone, with a TSIG record last', () => { + const key = { name: 'names-update', secret: Buffer.alloc(32, 1).toString('base64') }; + const { msg, id } = buildUpdate('user._bitcoin-payment.coinos.io', [{ name: 'a.user._bitcoin-payment.coinos.io', value: 'bitcoin:?ark=x' }, { name: 'b.user._bitcoin-payment.coinos.io', value: null }], 300, key, { id: 7, now: 1 }); + expect(id).toBe(7); + expect(msg.readUInt16BE(2) >> 11).toBe(5); + expect([msg.readUInt16BE(4), msg.readUInt16BE(8), msg.readUInt16BE(10)]).toEqual([1, 3, 1]); // zone, 2 deletes + 1 add, TSIG + expect(msg.includes(Buffer.from('hmac-sha256'))).toBe(true); + // same inputs, same signature + expect(buildUpdate('user._bitcoin-payment.coinos.io', [{ name: 'a.user._bitcoin-payment.coinos.io', value: 'v' }], 300, key, { id: 7, now: 1 }).msg) + .toEqual(buildUpdate('user._bitcoin-payment.coinos.io', [{ name: 'a.user._bitcoin-payment.coinos.io', value: 'v' }], 300, key, { id: 7, now: 1 }).msg); +}); diff --git a/names/forget.js b/names/forget.js index b02fe8c..afb2ac9 100644 --- a/names/forget.js +++ b/names/forget.js @@ -48,7 +48,7 @@ export function forgetAccount(state, { keys, names }) { for (const key of names) { const rec = state.names[key]; if (!rec) continue; - if (rec.recordId) dns.push({ domain: rec.domain || key.split('@')[1], recordId: rec.recordId }); + if (rec.recordId) dns.push({ domain: rec.domain || key.split('@')[1], recordId: rec.recordId, name: key.split('@')[0] }); if (rec.offerId) offers.push(rec.offerId); delete state.names[key]; count('names'); diff --git a/names/forget.test.js b/names/forget.test.js index ec1c22a..243b2d2 100644 --- a/names/forget.test.js +++ b/names/forget.test.js @@ -43,7 +43,7 @@ test('everything of theirs goes, nobody else\'s does', () => { const acct = accountOf(s, WALLET); expect(accountBlockers(s, acct).any).toBe(false); const out = forgetAccount(s, acct); - expect(out.dns).toEqual([{ domain: 'coinos.io', recordId: 'r1' }]); + expect(out.dns).toEqual([{ domain: 'coinos.io', recordId: 'r1', name: 'andy' }]); expect(out.offers.sort()).toEqual(['o-custom', 'o-name', 'o-orphan']); expect(Object.keys(s.names)).toEqual(['[email protected]']); expect(Object.keys(s.offers)).toEqual(['o-bob']); diff --git a/names/server.js b/names/server.js index 92e6fd8..34aae77 100644 --- a/names/server.js +++ b/names/server.js @@ -28,6 +28,7 @@ import { mnemonicToSeedSync } from '@scure/bip39'; import { lnBackend } from '../bridge/ln.js'; import { ArkManager } from '../coinosv3/src/ark/manager.js'; import { fetchPreview } from './preview.js'; +import { dnsUpdate } from './dns-update.js'; import { translate, translateDeepl, languages } from './translate.js'; import { decodeAddress, arkIdFromServerPubkey } from '../coinosv3/src/ark/proto.js'; import { decodeNoffer } from '../coinosv3/src/noffer.js'; @@ -87,7 +88,20 @@ const cfHeaders = { }; const recordName = (name, domain) => `${name}.user._bitcoin-payment.${domain}`; +// A domain with `knot` in its config keeps its BIP-353 records on our own +// DNS server (dns/: Knot on cs, signed, served from ovh2), the subtree +// user._bitcoin-payment.<domain> delegated there — Cloudflare's per-zone +// record quota (3,500 on Pro) can't hold one record per name. Records are +// replaced whole (recordId 'knot'); a Cloudflare record a name still has +// from before is removed as it's rewritten. +const KNOT_ID = 'knot'; +async function knotWrite(name, domain, uri, existingId) { + await dnsUpdate(DOMAINS[domain].knot, [{ name: recordName(name, domain), value: uri }], TTL); + if (existingId && existingId !== KNOT_ID) await cfDeleteRecord(domain, existingId).catch((e) => log(`old cloudflare record ${existingId} stayed: ${e.message}`)); + return KNOT_ID; +} async function cfWrite(name, domain, uri, existingId) { + if (DOMAINS[domain]?.knot) return knotWrite(name, domain, uri, existingId); // A domain whose config says dns: false gets no BIP-353 records: its names // are LNURL and NIP-05 only. paff.club: every browser's tipping wallet // claims a name there, the zone hit Cloudflare's record quota ("Record quota @@ -113,8 +127,16 @@ async function cfWrite(name, domain, uri, existingId) { if (!j.success) throw new Error('dns write failed: ' + JSON.stringify(j.errors).slice(0, 200)); return j.result.id; } -async function cfDelete(domain, recordId) { +async function cfDelete(domain, recordId, name) { if (!recordId) return; // a name on a domain without records (dns: false) + if (DOMAINS[domain]?.knot) { + if (name) await dnsUpdate(DOMAINS[domain].knot, [{ name: recordName(name, domain), value: null }], TTL); + if (recordId !== KNOT_ID) await cfDeleteRecord(domain, recordId).catch(() => {}); + return; + } + return cfDeleteRecord(domain, recordId); +} +async function cfDeleteRecord(domain, recordId) { const zoneId = DOMAINS[domain]?.zoneId; if (!zoneId) throw new Error('unknown domain'); const r = await fetch(`${CF}/zones/${zoneId}/dns_records/${recordId}`, { @@ -2288,7 +2310,7 @@ Bun.serve({ if (hold.any) return json({ error: 'funds', pendingSat: hold.pendingSat, withdrawSat: hold.withdrawSat, paying: hold.paying }, 409); const out = forgetAccount(state, acct); persist(); - for (const d of out.dns) await cfDelete(d.domain, d.recordId).catch((e) => log(`account delete: dns record ${d.recordId} stayed: ${e.message}`)); + for (const d of out.dns) await cfDelete(d.domain, d.recordId, d.name).catch((e) => log(`account delete: dns record ${d.recordId} stayed: ${e.message}`)); if (ln) for (const id of out.offers) await ln.call('disableoffer', { offer_id: id }).catch(() => {}); // their devices' push registrations and scheduled posts, at the notifier if (CFG.push && CFG.push.url) { @@ -2316,7 +2338,7 @@ Bun.serve({ const existing = state.names[key]; if (!existing) return json({ error: 'unknown name' }, 404); if (existing.pubkey !== auth.pubkey && existing.manager !== auth.pubkey) return json({ error: 'not your name' }, 403); - await cfDelete(domain, existing.recordId).catch(() => {}); + await cfDelete(domain, existing.recordId, name).catch(() => {}); if (existing.offerId && ln) await ln.call('disableoffer', { offer_id: existing.offerId }).catch(() => {}); delete state.names[key]; persist(); |
