aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--names/forget.js83
-rw-r--r--names/forget.test.js86
-rw-r--r--names/server.js32
-rw-r--r--nwcpush/server.js22
-rw-r--r--package.json2
5 files changed, 224 insertions, 1 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();
diff --git a/nwcpush/server.js b/nwcpush/server.js
index bdf30aa..7873a4e 100644
--- a/nwcpush/server.js
+++ b/nwcpush/server.js
@@ -694,6 +694,28 @@ const server = Bun.serve({
return json({ ok: true, devices: n });
}
+ // Server-to-server: an account was deleted at the registrar. Its devices'
+ // registrations go (found by the keys they asked to be told about, then
+ // the same devices' NWC wakes), and its scheduled posts.
+ if (url.pathname === '/forget' && req.method === 'POST') {
+ const body = await req.json().catch(() => null);
+ if (!CFG.notifyToken || body?.token !== CFG.notifyToken) return json({ error: 'forbidden' }, 403);
+ const pks = new Set((Array.isArray(body.pubkeys) ? body.pubkeys : []).filter((k) => /^[0-9a-f]{64}$/.test(k || '')));
+ if (!pks.size) return json({ error: 'pubkeys required' }, 400);
+ const ids = new Set();
+ for (const [id, r] of Object.entries(notifyRegs)) if ((r.ptags || []).some((k) => pks.has(k))) { ids.add(id); delete notifyRegs[id]; }
+ for (const pk of Object.keys(regs)) {
+ regs[pk] = regs[pk].filter((r) => !ids.has(r.id));
+ if (!regs[pk].length) delete regs[pk];
+ }
+ let posts = 0;
+ for (const [id, s2] of Object.entries(scheduled)) if (pks.has(s2.ev?.pubkey)) { delete scheduled[id]; posts++; }
+ if (ids.size) { persist(); resubscribe(); }
+ if (posts) persistScheduled();
+ log(`forgot ${ids.size} device(s), ${posts} scheduled post(s)`);
+ return json({ ok: true, devices: ids.size, scheduled: posts });
+ }
+
// Claim a pay request before spending on it. The first claimant (or the
// same one again) gets ok:true; anyone else ok:false and stands down.
if (url.pathname === '/claim' && req.method === 'POST') {
diff --git a/package.json b/package.json
index 85fc10f..357f54f 100644
--- a/package.json
+++ b/package.json
@@ -5,7 +5,7 @@
"description": "Server-side services for coinos v3: the payment-name registrar, NWC push, Blossom sync storage, the public feed and media proxy",
"license": "MIT",
"scripts": {
- "test": "bun test names/store.test.js",
+ "test": "bun test names/store.test.js names/forget.test.js",
"names": "bun names/server.js",
"nwcpush": "bun nwcpush/server.js",
"blossom": "bun blossom/server.js",