// Member erase (Marty 2026-11-15, ticket LS-1021: "I want delete my account data from all your sites"). One named admin action // that takes a person out of LinkSpin from INSIDE the running app, so the documents the modules keep in memory and the MySQL // `docs` rows stay consistent (an edit straight in the database would be written back over by the next save). // POST /api/admin/erase {email, dryRun (default true), force} (admin) and the hub's member.erased event (hubsync.js) // Refused unless force: a linked main wallet, an on-chain member number, linked positions, anyone sponsored under them here, // an ad still running or queued. What goes: // - the account (accounts.removeAccount), their spin links with every click row (rot_hits) and conversion (rotator.eraseOwner); // - every data document that mentions them (scrub.js: their keys, list items and records; another member's record only loses // the pointer), through the owning module's live copy when it keeps one in memory, else read and written through docstore: // accounts, audiences, coach, convtrack, earned (their unspent credits simply go away), hubsync, iapsync, mail-intro, // postbacks, registry, rotator, sponsorfollow, updates-log, and any other document that names them. // Their help-desk tickets live in the shared InstantAdPay desk (InstantAdPay's erase scrubs those). A tombstone (SHA-256 of the // email, kept 30 days in erase.json) stops the InstantAdPay registry sync and hub events from bringing them back while the other // sites catch up. The log keeps hashes and counts, never the email. Dry run = the same counts, nothing changed. 'use strict'; const crypto = require('crypto'); const fs = require('fs'); const path = require('path'); const { scrubDeep, scrubText, mentions } = require('./scrub'); let R = null; // { dataDir, accounts, ads, rotator, docstore, owners: {doc: {state, save}}, reload: {doc: fn}, forget: [fn(email)] } const TOMB_MS = 30 * 86400000; const norm = v => String(v || '').trim().toLowerCase(); const hashOf = email => crypto.createHash('sha256').update(norm(email)).digest('hex'); const FILE = () => path.join(R.dataDir, 'erase.json'); let st = null; function load() { if (st) return st; try { st = JSON.parse(fs.readFileSync(FILE(), 'utf8')); } catch (e) { st = null; } if (!st || typeof st !== 'object') st = {}; st.v = 1; st.tomb = st.tomb || {}; st.log = st.log || []; return st; } function save() { try { const f = FILE(); fs.writeFileSync(f + '.tmp', JSON.stringify(load())); fs.renameSync(f + '.tmp', f); } catch (e) { console.error('erase save', e.message); } } function init(deps) { R = deps; st = null; load(); } function isErased(email) { const s = load(); const h = hashOf(email); const t = s.tomb[h]; if (!t) return false; if (Date.now() - t > TOMB_MS) { delete s.tomb[h]; save(); return false; } return true; } function docNames() { if (R.docstore && R.docstore.isOn && R.docstore.isOn()) return R.docstore.names(); const out = []; const walk = (d, pre) => { let ents = []; try { ents = fs.readdirSync(d, { withFileTypes: true }); } catch (e) {} for (const x of ents) { const p = path.join(d, x.name); if (x.isDirectory()) walk(p, pre + x.name + '/'); else if (/\.jsonl?$/i.test(x.name)) out.push(pre + x.name); } }; walk(R.dataDir, ''); return out; } // every data document that mentions them: counted (dry run) or scrubbed, through the module that holds it in memory if any function docs(needles, dryRun) { const out = {}; for (const name of docNames()) { if (name === 'erase.json') continue; // hashes only const file = path.join(R.dataDir, name); let body; try { body = fs.readFileSync(file, 'utf8'); } catch (e) { continue; } if (!mentions(body, needles)) continue; const own = R.owners[name]; try { if (own) { const live = own.state(); const n = scrubDeep(dryRun ? JSON.parse(JSON.stringify(live)) : live, needles); if (!dryRun && n) own.save(); out[name] = n; } else { const r = scrubText(body, needles, /\.jsonl$/i.test(name)); if (!dryRun && r.removed) { fs.writeFileSync(file, r.body); if (R.reload && R.reload[name]) R.reload[name](); } out[name] = r.removed; } } catch (e) { out[name] = 'error: ' + String(e.message).slice(0, 80); } } return out; } function docResidue(needles) { return docNames().filter(n => n !== 'erase.json').filter(n => { try { return mentions(fs.readFileSync(path.join(R.dataDir, n), 'utf8'), needles); } catch (e) { return false; } }); } async function blockersOf(acct, E) { const out = []; if (acct.address) out.push('main wallet linked'); if (Number(acct.memberId) > 0) out.push('on-chain member #' + acct.memberId); try { const pos = await R.accounts.positions(E); if (pos && pos.length) out.push('linked positions: ' + pos.length); } catch (e) {} const refs = [acct.username, acct.code].filter(Boolean).map(norm); if (refs.length) { const team = (await R.accounts.listByReferrer(refs)).filter(a => norm(a.email) !== E); if (team.length) out.push('sponsored under them here: ' + team.length); } try { const live = ((R.ads && await R.ads.listCampaigns(E)) || []).filter(c => ['active', 'queued', 'paused'].includes(c.status)); if (live.length) out.push('ads still running or queued: ' + live.length); } catch (e) {} return out; } // email -> {ok, dryRun, emailHash, found, blockers, account, spinLinks, docs: {doc: removed}, docResidue} async function erase(email, opts) { const o = Object.assign({ dryRun: true, force: false, by: 'admin', sweep: true }, opts || {}); const E = norm(email); if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(E)) return { error: 'A valid email is required.' }; const h = hashOf(E); const acct = await R.accounts.byEmail(E); const exact = acct ? [acct.username, acct.code].filter(Boolean).map(norm) : []; const needles = { emails: [E], exact }; const blockers = acct ? await blockersOf(acct, E) : []; const res = { dryRun: !!o.dryRun, emailHash: h, found: !!acct, blockers, forced: !!o.force && blockers.length > 0, account: 0, spinLinks: null, docs: {} }; if (blockers.length && !o.force && !o.dryRun) return Object.assign(res, { error: 'Not erased: ' + blockers.join('; ') + '. Send force: true to erase anyway.' }); if (!o.dryRun) { load().tomb[h] = Date.now(); save(); } // before anything goes: the syncs refuse them from here on if (acct) { if (o.dryRun) res.account = 1; else { const r = await R.accounts.removeAccount(E); res.account = r && r.ok ? 1 : 0; } } if (R.rotator && R.rotator.eraseOwner) res.spinLinks = await R.rotator.eraseOwner(E, o.dryRun); res.docs = docs(needles, o.dryRun); if (!o.dryRun) for (const f of R.forget || []) { try { f(E); } catch (e) {} } // caches that are not documents (hub lookups, pending pushes) for (const k of Object.keys(res.docs)) if (!res.docs[k]) delete res.docs[k]; if (o.sweep) res.docResidue = o.dryRun ? [] : docResidue(needles); if (!o.dryRun) { const s = load(); s.log.push({ at: Date.now(), by: String(o.by).slice(0, 20), hash: h.slice(0, 16), forced: res.forced, found: res.found, spinLinks: res.spinLinks ? res.spinLinks.rotations : 0, docs: Object.keys(res.docs).length, residue: (res.docResidue || []).length }); if (s.log.length > 500) s.log = s.log.slice(-500); save(); console.log('member erase', h.slice(0, 16), 'by', o.by, 'account', res.account, 'spin links', JSON.stringify(res.spinLinks), 'docs', JSON.stringify(res.docs)); } res.ok = true; return res; } // the hub's member.erased event carries only the SHA-256 of the email: find who here has it async function byHash(hash, by) { const h = norm(hash); if (!/^[0-9a-f]{64}$/.test(h)) return { result: 'bad-hash' }; let email = null; for (const a of await R.accounts.listAll(1e7, { shells: true })) if (hashOf(a.email) === h) { email = norm(a.email); break; } if (!email) { const s = load(); s.tomb[h] = Date.now(); save(); return { result: 'not-here' }; } const r = await erase(email, { dryRun: false, by: by || 'hub', sweep: false }); return { result: r.error ? 'refused' : 'erased', error: r.error || null, docs: r.docs }; } function view() { const s = load(); return { tombstones: Object.keys(s.tomb).length, recent: s.log.slice(-20).reverse() }; } module.exports = { init, erase, byHash, isErased, hashOf, view, _reset: () => { st = null; } };