diff options
| author | Adam Soltys <[email protected]> | 2026-11-10 15:09:20 -0700 |
|---|---|---|
| committer | Adam Soltys <[email protected]> | 2026-11-10 15:09:20 -0700 |
| commit | f8c9efa8d1fab36ded9fa525c0ed56cd16ae5345 (patch) | |
| tree | 05aef10cbbbccc8bb4d71e536a9860d3d114d402 /names | |
| parent | 3c5e9c347a4b1a48d19d1a20ab4ace6f19852770 (diff) | |
| download | coinosv3-server-f8c9efa8d1fab36ded9fa525c0ed56cd16ae5345.tar.gz coinosv3-server-f8c9efa8d1fab36ded9fa525c0ed56cd16ae5345.zip | |
names: delete my account. "someone's asking for a way to delete their v3 account. we allowed that in v2. i guess we'd want to free up the name once the deletion is done and remove any records we have on them on the server" (Adam, 2026-11-10). POST /account/delete, NIP-98 signed: the signer's account is its key, the names it owns or manages, and those names' other key (a login identity's name is kept by its wallet's key). Everything filed under them goes: the names (DNS record, node offer), custom offers, POS tokens and sales, hats and hat invoices, the welcome mark, Lightning receipts, migration grants (which would otherwise keep the name reserved for the key that left), queued webhooks, closed and never-funded withdraw links. Then the notifier is told (POST /forget with the shared notify token): the devices registered to be told about those keys lose their registrations, NWC wakes included, and the keys' scheduled posts are dropped. Money is never deleted: while sats are queued, parked or in flight to them, or an open withdraw link of theirs still holds some, the answer is 409 "funds" with the amounts; { check: true } asks without doing. Kept: what stops a payment being made twice (delivered, withdrawPaid, inflight) and the unpaid-invoice map, which ages out in a week. names/forget.js + forget.test.js; run against both real services on throwaway state
Co-Authored-By: Claude Fable 5.2 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VMan6V74NSFWZtNtgCfokN
Diffstat (limited to 'names')
| -rw-r--r-- | names/forget.js | 83 | ||||
| -rw-r--r-- | names/forget.test.js | 86 | ||||
| -rw-r--r-- | names/server.js | 32 |
3 files changed, 201 insertions, 0 deletions
diff --git a/names/forget.js b/names/forget.js new file mode 100644 index 0000000..b02fe8c --- /dev/null +++ b/names/forget.js @@ -0,0 +1,83 @@ +// "Delete my account" (a v3 user via Adam, 2026-11-10: "we allowed that in +// v2 … free up the name once the deletion is done and remove any records we +// have on them on the server"). +// +// An account here is a key and what hangs off it: the names it owns or +// manages (a login identity's name is kept up to date by its wallet's key, +// the record's `manager`), and everything filed under those names or keys. +// Money is never deleted: while a payment is still on its way to them, or a +// withdraw link of theirs still holds sats, the account stays (blockers). +// What is kept afterwards is only what stops a payment being made twice +// (delivered, withdrawPaid, inflight) and the unpaid-invoice map, which ages +// out in a week and has to outlive a payer who is slow. + +const HEX = /^[0-9a-f]{64}$/; + +// The keys and names one signer answers for. +export function accountOf(state, signer) { + const keys = new Set([signer]); + const names = []; + for (const [key, rec] of Object.entries(state.names || {})) { + if (rec.pubkey !== signer && rec.manager !== signer) continue; + names.push(key); + for (const k of [rec.pubkey, rec.manager]) if (HEX.test(k || '')) keys.add(k); + } + return { keys, names }; +} + +// Sats still owed to this account, or held for it. Non-zero means "not yet". +export function accountBlockers(state, { keys, names }) { + const mine = (p) => keys.has(p.pubkey) || names.includes(p.name); + let pendingSat = 0, withdrawSat = 0, paying = 0; + for (const p of [...(state.pending || []), ...(state.parked || [])]) if (mine(p)) pendingSat += Number(p.sat) || 0; + for (const v of Object.values(state.inflight || {})) if (names.includes(v.name)) pendingSat += Number(v.sat) || 0; + for (const w of Object.values(state.withdraws || {})) { + if (!keys.has(w.pubkey)) continue; + if ((w.claims || []).some((c) => c.status === 'paying')) paying++; + if (w.status === 'open') withdrawSat += Math.max(0, (w.totalSat || 0) - (w.spentSat || 0)); + } + return { pendingSat, withdrawSat, paying, any: pendingSat > 0 || withdrawSat > 0 || paying > 0 }; +} + +// Take the account out of `state`. Returns what the caller still has to undo +// outside it: DNS records to delete and node offers to disable. +export function forgetAccount(state, { keys, names }) { + const dns = [], offers = [], removed = {}; + const count = (what, n = 1) => { if (n) removed[what] = (removed[what] || 0) + n; }; + const named = new Set(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.offerId) offers.push(rec.offerId); + delete state.names[key]; + count('names'); + } + for (const [id, o] of Object.entries(state.offers || {})) { + if (!named.has(o.key) && !keys.has(o.pubkey)) continue; + offers.push(id); delete state.offers[id]; count('offers'); + } + const byKey = (coll, field = 'key') => { + for (const [id, v] of Object.entries(state[coll] || {})) if (named.has(v?.[field])) { delete state[coll][id]; count(coll); } + }; + byKey('posTokens'); byKey('posInvoices'); + for (const coll of ['hats', 'hatsMut', 'welcomed']) + for (const k of keys) if (state[coll] && k in state[coll]) { delete state[coll][k]; count(coll); } + for (const [id, v] of Object.entries(state.hatInvoices || {})) if (keys.has(v?.pubkey)) { delete state.hatInvoices[id]; count('hatInvoices'); } + for (const key of names) if (state.lnReceipts && key in state.lnReceipts) { delete state.lnReceipts[key]; count('lnReceipts'); } + // a grant left behind would keep the name reserved for the key that just left + for (const [key, g] of Object.entries(state.migrations || {})) + if (named.has(key) || keys.has(g?.pubkey) || keys.has(g?.manager)) { delete state.migrations[key]; count('migrations'); } + if (Array.isArray(state.webhookQueue)) { + const before = state.webhookQueue.length; + state.webhookQueue = state.webhookQueue.filter((q) => !named.has(q.key)); + count('webhookQueue', before - state.webhookQueue.length); + } + // withdraw links: only closed and never-funded ones are left (blockers) + for (const [id, w] of Object.entries(state.withdraws || {})) { + if (!keys.has(w.pubkey)) continue; + if (w.status === 'unfunded' && w.fundHash && state.withdrawFunding) delete state.withdrawFunding[w.fundHash]; + delete state.withdraws[id]; count('withdraws'); + } + return { dns, offers: [...new Set(offers)], removed }; +} diff --git a/names/forget.test.js b/names/forget.test.js new file mode 100644 index 0000000..ec1c22a --- /dev/null +++ b/names/forget.test.js @@ -0,0 +1,86 @@ +// bun test names/forget.test.js +import { test, expect } from 'bun:test'; +import { accountOf, accountBlockers, forgetAccount } from './forget.js'; + +const hex = (i) => i.toString(16).padStart(64, '0'); +const WALLET = hex(1), LOGIN = hex(2), OTHER = hex(3); +const fixture = () => ({ + names: { + '[email protected]': { pubkey: LOGIN, manager: WALLET, recordId: 'r1', domain: 'coinos.io', offerId: 'o-name' }, + '[email protected]': { pubkey: OTHER, recordId: 'r2', domain: 'coinos.io' }, + }, + offers: { 'o-custom': { key: '[email protected]', pubkey: LOGIN }, 'o-orphan': { key: '[email protected]', pubkey: WALLET }, 'o-bob': { key: '[email protected]', pubkey: OTHER } }, + posTokens: { t1: { key: '[email protected]' }, t2: { key: '[email protected]' } }, + posInvoices: { h1: { key: '[email protected]', sat: 5 }, h2: { key: '[email protected]', sat: 5 } }, + invoices: { h9: { key: '[email protected]' } }, + hats: { [LOGIN]: { owned: ['cap'] }, [OTHER]: { owned: ['crown'] } }, + hatInvoices: { hh: { pubkey: WALLET }, hb: { pubkey: OTHER } }, + welcomed: { [LOGIN]: 1, [WALLET]: 1, [OTHER]: 1 }, + lnReceipts: { '[email protected]': [{ sat: 1 }], '[email protected]': [{ sat: 2 }] }, + migrations: { '[email protected]': { pubkey: LOGIN, manager: WALLET }, '[email protected]': { pubkey: OTHER } }, + webhookQueue: [{ key: '[email protected]' }, { key: '[email protected]' }], + withdraws: { + w1: { id: 'w1', pubkey: WALLET, status: 'closed', totalSat: 100, spentSat: 100, claims: [] }, + w2: { id: 'w2', pubkey: WALLET, status: 'unfunded', totalSat: 50, spentSat: 0, fundHash: 'fh', claims: [] }, + w3: { id: 'w3', pubkey: OTHER, status: 'open', totalSat: 50, spentSat: 0, claims: [] }, + }, + withdrawFunding: { fh: 'w2' }, + withdrawPaid: { ph: 'w1' }, + delivered: { d1: 1 }, + pending: [], parked: [], inflight: {}, +}); + +test('the wallet key answers for the login identity\'s name it manages', () => { + const a = accountOf(fixture(), WALLET); + expect(a.names).toEqual(['[email protected]']); + expect([...a.keys].sort()).toEqual([WALLET, LOGIN].sort()); + expect(accountOf(fixture(), LOGIN).names).toEqual(['[email protected]']); + expect(accountOf(fixture(), hex(77)).names).toEqual([]); +}); + +test('everything of theirs goes, nobody else\'s does', () => { + const s = fixture(); + 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.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']); + expect(Object.keys(s.posTokens)).toEqual(['t2']); + expect(Object.keys(s.posInvoices)).toEqual(['h2']); + expect(Object.keys(s.hats)).toEqual([OTHER]); + expect(Object.keys(s.hatInvoices)).toEqual(['hb']); + expect(Object.keys(s.welcomed)).toEqual([OTHER]); + expect(Object.keys(s.lnReceipts)).toEqual(['[email protected]']); + expect(Object.keys(s.migrations)).toEqual(['[email protected]']); + expect(s.webhookQueue).toEqual([{ key: '[email protected]' }]); + expect(Object.keys(s.withdraws)).toEqual(['w3']); + expect(s.withdrawFunding).toEqual({}); + // what guards against paying twice, and the unpaid-invoice map, stay + expect(s.withdrawPaid).toEqual({ ph: 'w1' }); + expect(s.delivered).toEqual({ d1: 1 }); + expect(Object.keys(s.invoices)).toEqual(['h9']); + // a second run finds nothing + expect(forgetAccount(s, accountOf(s, WALLET)).removed).toEqual({}); +}); + +test('money on its way, or held in a withdraw link, blocks', () => { + let s = fixture(); + s.pending.push({ name: '[email protected]', sat: 21, hash: 'x' }); + expect(accountBlockers(s, accountOf(s, WALLET))).toMatchObject({ pendingSat: 21, any: true }); + s = fixture(); + s.parked.push({ name: '[email protected]', pubkey: LOGIN, sat: 7 }); + expect(accountBlockers(s, accountOf(s, WALLET))).toMatchObject({ pendingSat: 7, any: true }); + s = fixture(); + s.inflight.z = { name: '[email protected]', sat: 9 }; + expect(accountBlockers(s, accountOf(s, WALLET)).pendingSat).toBe(9); + s = fixture(); + s.withdraws.w1 = { id: 'w1', pubkey: WALLET, status: 'open', totalSat: 100, spentSat: 40, claims: [] }; + expect(accountBlockers(s, accountOf(s, WALLET))).toMatchObject({ withdrawSat: 60, any: true }); + s = fixture(); + s.withdraws.w1.claims.push({ status: 'paying' }); + expect(accountBlockers(s, accountOf(s, WALLET)).any).toBe(true); + // someone else's open link is not ours to wait on + expect(accountBlockers(fixture(), accountOf(fixture(), WALLET)).any).toBe(false); +}); diff --git a/names/server.js b/names/server.js index 6336e2b..4d497c5 100644 --- a/names/server.js +++ b/names/server.js @@ -36,6 +36,7 @@ import { decodeOffer } from '../coinosv3/src/bolt12.js'; import { registrationIdentity } from './ownership.js'; import { openStore } from './store.js'; import { withdrawService } from './withdraw.js'; +import { accountOf, accountBlockers, forgetAccount } from './forget.js'; const CFG = JSON.parse(readFileSync(process.env.NAMES_CONFIG || join(import.meta.dir, 'config.json'), 'utf8')); @@ -2240,6 +2241,37 @@ Bun.serve({ return json({ ok: true, webhook: { url: rawUrl, secret: secret || null } }); } + // Delete my account: the signer's names are freed and every record filed + // under them or their keys goes (names/forget.js). Refused while sats are + // still on their way to them or held in a withdraw link of theirs. + // { check: true } only reports what would happen. + if (url.pathname === '/account/delete' && req.method === 'POST') { + if (!rateOk(ip)) return json({ error: 'rate limited' }, 429); + const bodyText = await req.text(); + const a = await checkNip98(req, url, bodyText); + if (a.error) return json({ error: a.error }, 401); + let body = {}; + if (bodyText) { try { body = JSON.parse(bodyText); } catch { return json({ error: 'bad body' }, 400); } } + const acct = accountOf(state, a.pubkey); + const hold = accountBlockers(state, acct); + if (body.check) return json({ names: acct.names, pendingSat: hold.pendingSat, withdrawSat: hold.withdrawSat, paying: hold.paying, blocked: hold.any }); + 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}`)); + 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) { + await fetch(`${CFG.push.url}/forget`, { + method: 'POST', headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ token: CFG.push.token, pubkeys: [...acct.keys] }), + signal: AbortSignal.timeout(5000), + }).catch((e) => log(`account delete: notifier not told: ${e.message}`)); + } + log(`account deleted: ${acct.names.join(', ') || '(no name)'} ${JSON.stringify(out.removed)}`); + return json({ ok: true, names: acct.names }); + } + if (url.pathname === '/register' && req.method === 'DELETE') { if (!rateOk(ip)) return json({ error: 'rate limited' }, 429); const bodyText = await req.text(); |
