diff options
| -rw-r--r-- | compose.yml | 20 | ||||
| -rwxr-xr-x | deploy/post-receive | 2 | ||||
| -rw-r--r-- | dns/README.md | 57 | ||||
| -rw-r--r-- | dns/bootstrap/user._bitcoin-payment.coinos.io.zone | 6 | ||||
| -rw-r--r-- | dns/bootstrap/user._bitcoin-payment.staging.coinos.io.zone | 6 | ||||
| -rw-r--r-- | dns/primary.conf | 58 | ||||
| -rw-r--r-- | dns/secondary.conf | 37 | ||||
| -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 |
13 files changed, 412 insertions, 6 deletions
diff --git a/compose.yml b/compose.yml index 7626977..cf1d7bc 100644 --- a/compose.yml +++ b/compose.yml @@ -7,6 +7,7 @@ # $STATE/blossom/data/ # $STATE/live/config.json $STATE/live/data/ (TURN key; streams and their recordings) # $STATE/messages/bin/magnitude-relay $STATE/messages/data/ (see messages/README.md) +# $STATE/dns/keys.conf $STATE/dns/storage/ (TSIG keys; zones, journal, DNSSEC keys — see dns/README.md) services: names: image: ghcr.io/coinos/bun:1.4.3 @@ -26,6 +27,25 @@ services: networks: [net] restart: unless-stopped + # BIP-353 records: Knot DNS, the hidden primary (dns/primary.conf). The + # registrar updates it over `net`; ovh2's public secondary transfers from + # it over Tailscale, on cs's Tailscale address only. The bootstrap zones + # are copied in once (cp -n); after that the zones live in Knot's storage. + dns: + image: cznic/knot:3.4 + container_name: dns + command: sh -c 'cp -n /bootstrap/*.zone /storage/ && exec knotd -c /config/knot.conf' + volumes: + - ./dns/primary.conf:/config/knot.conf:ro + - ./dns/bootstrap:/bootstrap:ro + - ${STATE}/dns/keys.conf:/keys/keys.conf:ro + - ${STATE}/dns/storage:/storage + ports: + - ${DNS_XFR_ADDR:-100.119.250.121}:53:53/tcp + - ${DNS_XFR_ADDR:-100.119.250.121}:53:53/udp + networks: [net] + restart: unless-stopped + nwcpush: image: ghcr.io/coinos/bun:1.4.3 container_name: nwcpush diff --git a/deploy/post-receive b/deploy/post-receive index a0ec2b7..ad238d1 100755 --- a/deploy/post-receive +++ b/deploy/post-receive @@ -11,7 +11,7 @@ LOG=/home/adam/coinosv3-server-deploy.log MIRROR=/home/adam/git/coinosv3-server.git [email protected]:npub1w27mc4aa6m0ufe3xs5z3m6qyr52gc0rglept7vqlwx4xeaf72tasnqz70r/coinosv3-server.git BARE=$(pwd) -SERVICES="names nwcpush blossom live messages" +SERVICES="names nwcpush blossom live messages dns" while read -r oldrev newrev ref; do [ "$ref" = refs/heads/prod ] || continue diff --git a/dns/README.md b/dns/README.md new file mode 100644 index 0000000..f730ff8 --- /dev/null +++ b/dns/README.md @@ -0,0 +1,57 @@ +# BIP-353 DNS (Knot) + +`₿[email protected]` resolves through a DNSSEC-signed TXT record at +`name.user._bitcoin-payment.coinos.io`. Cloudflare caps a zone at 3,500 records +(Pro), and one record per name had coinos.io at 3,038 on 2026-11-16, so the +per-name records live on our own Knot DNS instead: + +``` +Cloudflare (coinos.io zone, DNSSEC) + dns1.coinos.io A 51.79.52.200 (DNS only) + user._bitcoin-payment.coinos.io NS dns1.coinos.io + DS (the zone's KSK) + user._bitcoin-payment.staging.coinos.io NS dns1.coinos.io + DS + │ +ovh2 knot-bip353 public secondary, answers the internet (secondary.conf) + │ NOTIFY / AXFR+IXFR over Tailscale, TSIG key `xfr` +cs dns hidden primary, signs the zones (primary.conf, compose `dns`) + │ RFC 2136 UPDATE over the compose network, TSIG key `names-update` +cs names the registrar (names/dns-update.js), domains with `knot` in its config +``` + +## cs (primary) + +- State: `$STATE/dns/keys.conf` (both TSIG keys, `key:` list) and + `$STATE/dns/storage/` (zone files, journal, DNSSEC keys — back it up; losing + the KSK means a new DS in Cloudflare). +- The compose service publishes port 53 on cs's Tailscale address only. +- `docker exec dns knotc zone-status`, `docker exec dns kdig @127.0.0.1 TXT adam.user._bitcoin-payment.coinos.io`. +- DS for Cloudflare: `docker exec dns keymgr user._bitcoin-payment.coinos.io ds` (the SHA-256 line). +- The KSK never rolls by itself (`ksk-lifetime: 0`); ZSKs roll every 90 days + without anyone's help. + +## names config + +```json +"coinos.io": { "zoneId": "…", "knot": { "zone": "user._bitcoin-payment.coinos.io", "server": "dns", "port": 53, + "key": { "name": "names-update", "secret": "<base64 from keys.conf>" } } } +``` + +One-shot moves (`names/dns-migrate.js`, inside the names container): +`backfill` (every name → Knot), `check` (Knot matches the database), +`cf-cleanup` (delete the per-name TXT records from Cloudflare). + +## ovh2 (public secondary) + +Installed by hand (ovh2 has no deploy hook): + +``` +/etc/knot-bip353/knot.conf = dns/secondary.conf +/etc/knot-bip353/keys.conf = the `xfr` key only +/var/lib/knot-bip353/ storage +docker run -d --name knot-bip353 --network host --restart unless-stopped \ + -v /etc/knot-bip353/knot.conf:/config/knot.conf:ro -v /etc/knot-bip353/keys.conf:/keys/keys.conf:ro \ + -v /var/lib/knot-bip353:/storage cznic/knot:3.4 knotd -c /config/knot.conf +ufw allow 53/udp; ufw allow 53/tcp +``` + +A config change there: copy the file over, `docker restart knot-bip353`. diff --git a/dns/bootstrap/user._bitcoin-payment.coinos.io.zone b/dns/bootstrap/user._bitcoin-payment.coinos.io.zone new file mode 100644 index 0000000..02be942 --- /dev/null +++ b/dns/bootstrap/user._bitcoin-payment.coinos.io.zone @@ -0,0 +1,6 @@ +; first contents only: the zone lives in Knot's journal after this, and the +; names registrar fills it (names/dns-update.js) +$ORIGIN user._bitcoin-payment.coinos.io. +$TTL 300 +@ SOA dns1.coinos.io. hostmaster.coinos.io. 1 3600 600 1209600 300 +@ NS dns1.coinos.io. diff --git a/dns/bootstrap/user._bitcoin-payment.staging.coinos.io.zone b/dns/bootstrap/user._bitcoin-payment.staging.coinos.io.zone new file mode 100644 index 0000000..1d52fba --- /dev/null +++ b/dns/bootstrap/user._bitcoin-payment.staging.coinos.io.zone @@ -0,0 +1,6 @@ +; first contents only: the zone lives in Knot's journal after this, and the +; names registrar fills it (names/dns-update.js) +$ORIGIN user._bitcoin-payment.staging.coinos.io. +$TTL 300 +@ SOA dns1.coinos.io. hostmaster.coinos.io. 1 3600 600 1209600 300 +@ NS dns1.coinos.io. diff --git a/dns/primary.conf b/dns/primary.conf new file mode 100644 index 0000000..6aa1efb --- /dev/null +++ b/dns/primary.conf @@ -0,0 +1,58 @@ +# Knot DNS, hidden primary on cs, for the BIP-353 records (names/dns-update.js). +# Cloudflare's coinos.io zone delegates user._bitcoin-payment.coinos.io (and +# the staging one) here with NS + DS records; Knot signs the zones (DNSSEC) +# and the registrar changes them with TSIG-signed UPDATEs over the compose +# network. Nothing on the internet reaches this server: ovh2 runs the public +# secondary (dns/secondary.conf), notified and transferred over Tailscale. +# Keys (TSIG names-update and xfr) live in the state dir, never in git. +server: + listen: 0.0.0.0@53 + rundir: /rundir + +include: /keys/keys.conf + +remote: + - id: ovh2 + address: 100.120.75.121@53 + key: xfr + +acl: + - id: names_update + key: names-update + action: update + update-type: TXT + - id: xfr_ovh2 + key: xfr + action: transfer + +# The KSK never rolls on its own: its DS sits in Cloudflare by hand. +policy: + - id: ecdsa + algorithm: ecdsap256sha256 + ksk-lifetime: 0 + zsk-lifetime: 90d + nsec3: on + nsec3-iterations: 0 + nsec3-salt-length: 0 + +template: + - id: default + storage: /storage + file: "%s.zone" + dnssec-signing: on + dnssec-policy: ecdsa + serial-policy: unixtime + journal-content: all + zonefile-load: difference-no-serial + zonefile-sync: 60 + semantic-checks: on + notify: ovh2 + acl: [names_update, xfr_ovh2] + +log: + - target: stdout + any: info + +zone: + - domain: user._bitcoin-payment.coinos.io + - domain: user._bitcoin-payment.staging.coinos.io diff --git a/dns/secondary.conf b/dns/secondary.conf new file mode 100644 index 0000000..a6f6c90 --- /dev/null +++ b/dns/secondary.conf @@ -0,0 +1,37 @@ +# Knot DNS, public secondary on ovh2 (51.79.52.200, dns1.coinos.io) for the +# BIP-353 zones signed by the primary on cs (dns/primary.conf). It answers +# the internet and keeps answering while cs or its uplink is down. +# Installed by hand on ovh2: /etc/knot-bip353/{knot.conf,keys.conf}, docker +# container `knot-bip353` (host network). See dns/README.md. +server: + listen: [ 51.79.52.200@53, 100.120.75.121@53 ] + rundir: /rundir + +include: /keys/keys.conf + +remote: + - id: cs + address: 100.119.250.121@53 + key: xfr + +acl: + - id: notify_cs + address: 100.119.250.121 + key: xfr + action: notify + +template: + - id: default + storage: /storage + file: "%s.zone" + master: cs + acl: notify_cs + zonefile-sync: 60 + +log: + - target: stdout + any: info + +zone: + - domain: user._bitcoin-payment.coinos.io + - domain: user._bitcoin-payment.staging.coinos.io 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(); |
