From f4789156b838de863b7e50bafde11676c30c3cd0 Mon Sep 17 00:00:00 2001 From: martbost Date: Sun, 15 Nov 2026 12:29:33 -0600 Subject: [PATCH] Member erase (Marty 2026-11-15, ticket LS-1021): POST /api/admin/erase {email, dryRun (default true), force} + the hub's member.erased event erase.js runs inside the app so the documents modules keep in memory and the MySQL docs rows stay consistent. Refused unless force: a main wallet, an on-chain member number, positions, a team here, ads running or queued. Removes the account, their spin links with every click row in rot_hits and conversions (rotator.eraseOwner, docstore.rowsWhere), and scrubs every document that mentions them with scrub.js (same file as InstantAdPay) through the owning module's live copy: accounts, audiences, coach, convtrack, earned (unspent credits go away), hubsync, iapsync, mail-intro, postbacks, registry, rotator, sponsorfollow; others (updates-log, ...) through docstore. A 30-day email-hash tombstone (erase.json) stops the InstantAdPay registry sync and hub events from bringing them back; the log keeps hashes and counts only. hubsync handles member.erased {emailHash}. qa/erase.test.cjs 6 pass. Co-Authored-By: Claude Opus 5.5 --- accounts.js | 2 +- ads.js | Bin 133431 -> 133579 bytes audiences.js | 2 +- coach.js | 2 +- convtrack.js | 2 +- docstore.js | 15 +++++- erase.js | 120 ++++++++++++++++++++++++++++++++++++++++++++++ hubsync.js | 8 +++- iapsync.js | 2 +- mailer.js | 2 +- postbacks.js | 2 +- qa/erase.test.cjs | 107 +++++++++++++++++++++++++++++++++++++++++ qa/run.sh | 1 + registry.js | 2 +- rotator.js | 14 +++++- scrub.js | 61 +++++++++++++++++++++++ server.js | 19 +++++++- sponsorfollow.js | 2 +- 18 files changed, 349 insertions(+), 14 deletions(-) create mode 100644 erase.js create mode 100644 qa/erase.test.cjs create mode 100644 scrub.js diff --git a/accounts.js b/accounts.js index afa635e..66bf5eb 100644 --- a/accounts.js +++ b/accounts.js @@ -499,7 +499,7 @@ async function getChatSettings(email) { return { available: a ? a.chatAvailable !== false : true, mutes: await impl().getMutes(String(email || '').toLowerCase()) }; } -module.exports = { init, signup, login, ensure, onChange, byEmail, byAddress, byCode, byUsername, byMemberId: id => impl().byMemberId(Number(id) || 0), listAll, setSponsorRef, +module.exports = { /* member erase (erase.js, 2026-11-15): the live copy */ _json: { state: () => J.db, save: () => J.save() }, init, signup, login, ensure, onChange, byEmail, byAddress, byCode, byUsername, byMemberId: id => impl().byMemberId(Number(id) || 0), listAll, setSponsorRef, setUsername, setMemberId, namesForMembers, listByReferrer, downline, linkWallet, onWalletLinked, count, setLineBanner: (e, b, t) => impl().setLineBanner(String(e || '').toLowerCase(), b, t), setWallOffers: (e, j) => impl().setWallOffers(String(e || '').toLowerCase(), j), diff --git a/ads.js b/ads.js index c7332c911632c6b29d4627b378e4391945c1e9bf..8ea3097a0b84b4d7dc8a7971f456428a82de69e1 100644 GIT binary patch delta 144 zcmdl!iR1KSj)oS-Eld+w0`#>Ma#M4YQi~K)ixP`d6*Rz zl|o5IszOd?S*k*EenF*zmcBxKYGP4dYKoOYwL)=8Vo9o%f`+Dot=;r<%uG^~&n{tC ia`n-nPdATj)oS-Eld+wwyUr*EoT7$O-lxp diff --git a/audiences.js b/audiences.js index 1f49fcb..6655ff5 100644 --- a/audiences.js +++ b/audiences.js @@ -105,4 +105,4 @@ function matcher(req) { const vid = cookieVid(req), soft = softKey(req); return // admin Member content (2026-10-18): the audiences members made by hand (every member has an automatic one, not listed) function adminAll() { return Object.values(load().audiences).filter(a => !a.auto).map(a => Object.assign({}, a, sizes(a.id))); } -module.exports = { init, adminAll, list, create, rename, remove, owns, get, nameOf, defaultFor, hit, has, prune, flush, isId, cleanEvent, cookieVid, newVid, cookieHeader, softKey, matcher }; +module.exports = { /* member erase (erase.js, 2026-11-15): the live copy */ _state: () => load(), _save: () => { save(); flush(); }, init, adminAll, list, create, rename, remove, owns, get, nameOf, defaultFor, hit, has, prune, flush, isId, cleanEvent, cookieVid, newVid, cookieHeader, softKey, matcher }; diff --git a/coach.js b/coach.js index c2975e1..bba6168 100644 --- a/coach.js +++ b/coach.js @@ -299,4 +299,4 @@ function init(opts) { X = arguments[0] || {}; J.load(); } async function viewsSince(since) { return impl().viewsSince(since); } -module.exports = { init, RUNGS, rungFor, describe, coachView, prospects, saveProspect, removeProspect, STATUSES, recordView, linkStats, nudgeTick, recordClick, clickSources, clicksSince, refHost, viewsSince }; +module.exports = { /* member erase (erase.js, 2026-11-15): the live copy */ _json: { state: () => J.db, save: () => J.save() }, init, RUNGS, rungFor, describe, coachView, prospects, saveProspect, removeProspect, STATUSES, recordView, linkStats, nudgeTick, recordClick, clickSources, clicksSince, refHost, viewsSince }; diff --git a/convtrack.js b/convtrack.js index 820e15d..1552cf1 100644 --- a/convtrack.js +++ b/convtrack.js @@ -315,4 +315,4 @@ function withClickId(target, id) { const sep = base.includes('?') ? (/[?&]$/.test(base) ? '' : '&') : '?'; return base + sep + 'lsclk=' + encodeURIComponent(id) + hash; } -module.exports = { goalRows, goalRowsOf, selfFor, noteOwner, noteSession, importOwners, isOwnerSk, markSelfClick, withClickId, countSince, init, flush, prune, softKey, isPx, isClickId, isAdId, cleanName, cleanValue, goalsOf, goal, createGoal, updateGoal, recordAdClick, importClicks, lookup, record, postbackCtx, landing, report, partnerSummary, csv, adminCounts, testGoal, LIMITS, WINDOW_MS, SOFT_MS }; +module.exports = { /* member erase (erase.js, 2026-11-15): the live copy */ _state: () => load(), _save: () => { save(); flush(); }, goalRows, goalRowsOf, selfFor, noteOwner, noteSession, importOwners, isOwnerSk, markSelfClick, withClickId, countSince, init, flush, prune, softKey, isPx, isClickId, isAdId, cleanName, cleanValue, goalsOf, goal, createGoal, updateGoal, recordAdClick, importClicks, lookup, record, postbackCtx, landing, report, partnerSummary, csv, adminCounts, testGoal, LIMITS, WINDOW_MS, SOFT_MS }; diff --git a/docstore.js b/docstore.js index c3cdbda..93a07f5 100644 --- a/docstore.js +++ b/docstore.js @@ -194,4 +194,17 @@ async function claim(key) { // SIGTERM during a deploy: write what is pending, then exit async function drain(ms) { const end = Date.now() + (ms || 8000); while ((pending.size || flushing || rowQ.length || rowBusy) && Date.now() < end) { await flush().catch(() => {}); await new Promise(r => setTimeout(r, 100)); } } function view() { return Object.assign({ ready, writer, documents: cache.size, pending: pending.size, rowQueue: rowQ.length, rowTables: Object.fromEntries([...ROWS].map(([k, v]) => [k, v.length])), bytes: [...cache.values()].reduce((t, d) => t + d.body.length, 0) }, stats); } -module.exports = { install, init, drain, flush, view, nameOf, rows, rowPut, rowDel, isOn, claim }; +const names = () => [...cache.keys()]; // every document name (the member erase walks them all, 2026-11-15) +// member erase (2026-11-15): count or delete the rows of a row table whose JSON body has `field` (e.g. '$.r') in `values`. Waits +// for queued row writes first, so a click queued before the erase cannot land after it. +async function rowsWhere(table, field, values, del) { + if (!pool || !values.length) return 0; + for (let i = 0; i < 100 && (rowQ.length || rowBusy); i++) await new Promise(r => setTimeout(r, 100)); + const vals = values.map(String); const where = 'CAST(JSON_UNQUOTE(JSON_EXTRACT(body, ?)) AS CHAR) IN (?)'; + if (!del) { const [[r]] = await pool.query('SELECT COUNT(*) n FROM `' + table + '` WHERE ' + where, [field, vals]); return Number(r.n); } + if (!writer) return 0; + const [r] = await pool.query('DELETE FROM `' + table + '` WHERE ' + where, [field, vals]); + const mem = ROWS.get(table); if (mem) { const k = field.replace(/^\$\./, ''); ROWS.set(table, mem.filter(x => !vals.includes(String(x[k])))); } + return Number(r.affectedRows || 0); +} +module.exports = { install, init, drain, flush, view, nameOf, rows, rowPut, rowDel, isOn, claim, names, rowsWhere }; diff --git a/erase.js b/erase.js new file mode 100644 index 0000000..24ab9e2 --- /dev/null +++ b/erase.js @@ -0,0 +1,120 @@ +// 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; } }; diff --git a/hubsync.js b/hubsync.js index b1a4612..12ad54d 100644 --- a/hubsync.js +++ b/hubsync.js @@ -3,6 +3,7 @@ // IN POST /api/hub/events body {events:[{seq, at, type, personId, data}]}, headers X-Hub-Ts (ms) + X-Hub-Sig = hex // HMAC-SHA256(ts + "\n" + rawBody) with HUB_SECRET (network-hub lib/signing.js). Older than 5 minutes = refused. The hub // only moves its cursor on a 2xx, so events can arrive twice: each seq is applied once (DATA_DIR/hubsync.json lastSeq). +// member.erased (2026-11-15): the hub erased someone; erase.js finds them by the SHA-256 of the email and takes them out. // member.joined from another door: /v1/resolve {id} for the person, then the SAME waiting (shell) account the InstantAdPay // registry sync makes (/api/partner/registry in server.js): accounts.ensure(email, '', 'carried', 'network'), then only // EMPTY fields are filled (username, sponsor, wallet last, while carry.hold keeps activation off). The sponsor is placed @@ -81,6 +82,7 @@ const quiet = new Set(); const isQuiet = email => quiet.has(norm(email)); // QUIET (Marty 2026-11-14, "join one = join all"): nothing here sends mail, a notice or a post; qa/hubsync.test.cjs checks it. async function place(p, depth, seen) { const e = norm(p.email); if (!e || p.blocked || seen.has(e)) return null; seen.add(e); + if (R.erased && R.erased(e)) return null; // erased here (erase.js, 2026-11-15): a hub event never brings them back const ps = sponsorFor(p); let sp = ps && ps.email ? await R.accounts.byEmail(ps.email) : null; if (!sp && ps && ps.id && depth < MAX_UP) { // the sponsor is new here too: their line first @@ -117,6 +119,10 @@ async function apply(ev) { if (norm(ev.data && ev.data.site) === SITE()) return; // our own join coming back const p = await resolveId(ev.personId); if (p && p.email) await place(p, 0, new Set()); + } else if (type === 'member.erased') { // the hub erased someone (2026-11-15): erase.js finds them by the SHA-256 of the email + if (!R.erase) return; + const r = await R.erase.byHash(ev.data && ev.data.emailHash, 'hub'); + if (r.result === 'refused') console.error('hubsync member.erased refused here:', String(r.error || '').slice(0, 200)); } else if (type === 'wallet.connected') { // fill an empty wallet only, same rule as the InstantAdPay registry sync const p = await resolveId(ev.personId); if (!p || !p.email || !p.wallet || p.blocked) return; const a = await R.accounts.byEmail(p.email); @@ -329,4 +335,4 @@ function adminView() { made: Object.keys(st.made || {}).length, tankCache: held.size, tankHubDownUntil: heldDownUntil || null, disagree: Object.entries(st.disagree).slice(-50).map(([e, d]) => ({ member: mask(e), hub: mask(d.hub), here: mask(d.here), how: d.how, at: d.at })), disagreeTotal: Object.keys(st.disagree).length }; } -module.exports = { init, on, receive, touch, onChain, flush, tick, adminView, isQuiet, heldAmong, lockedAnywhere, hubSponsor, _heldReset: () => { held.clear(); heldDownUntil = 0; }, _heldAge: ms => { for (const c of held.values()) c.at -= ms; } }; +module.exports = { /* member erase (erase.js, 2026-11-15): the live copy */ _state: load, _save: save, _forgetHeld: e => held.delete(norm(e)), init, on, receive, touch, onChain, flush, tick, adminView, isQuiet, heldAmong, lockedAnywhere, hubSponsor, _heldReset: () => { held.clear(); heldDownUntil = 0; }, _heldAge: ms => { for (const c of held.values()) c.at -= ms; } }; diff --git a/iapsync.js b/iapsync.js index 22b029d..e997ae9 100644 --- a/iapsync.js +++ b/iapsync.js @@ -143,4 +143,4 @@ async function tick(force) { finally { ticking = false; } } function adminView() { const st = load(); return { on: on(), url: URL_(), tracked: Object.keys(st.hashes).length, pushed: st.pushed, knownSkipped: st.known, last: st.last, errors: st.errors, lastError: st.lastError || null, pendingTouches: pending.size }; } -module.exports = { init, touch, tick, adminView, on }; +module.exports = { init, touch, tick, adminView, on, /* member erase (erase.js, 2026-11-15): the live copy */ _state: load, _save: save, _forget: e => pending.delete(norm(e)) }; diff --git a/mailer.js b/mailer.js index 4a332e3..125d04e 100644 --- a/mailer.js +++ b/mailer.js @@ -77,4 +77,4 @@ function sendCode(to, code) { + 'LinkSpin\nAdvertise and earn instantly. Locked in code, not promises.\n' + SITE_URL, { code: true }); } -module.exports = { init, hasKey, send, sendCode }; +module.exports = { init, hasKey, send, sendCode, /* member erase (erase.js, 2026-11-15): the live copy */ _intro: { state: () => introLoad(), save: () => { try { fs.writeFileSync(introFile() + '.tmp', JSON.stringify(introLoad())); fs.renameSync(introFile() + '.tmp', introFile()); } catch (e) {} } } }; diff --git a/postbacks.js b/postbacks.js index 236e9db..9cf4ff3 100644 --- a/postbacks.js +++ b/postbacks.js @@ -153,4 +153,4 @@ async function inbound(key, body) { } // admin Member content (2026-10-18): every postback of every owner function adminAll() { return J.db.items.map(p => Object.assign(pubItem(p), { owner: p.owner })); } -module.exports = { init, adminAll, EVENTS, validateUrl, fill, deliver, list, create, update, logFor, logForSource, partnerKey, rotateKey, bindClick, clickOf, fire, test, convertFor, inbound }; +module.exports = { /* member erase (erase.js, 2026-11-15): the live copy */ _json: { state: () => { if (!J.db) J.load(); return J.db; }, save: () => J.save() }, init, adminAll, EVENTS, validateUrl, fill, deliver, list, create, update, logFor, logForSource, partnerKey, rotateKey, bindClick, clickOf, fire, test, convertFor, inbound }; diff --git a/qa/erase.test.cjs b/qa/erase.test.cjs new file mode 100644 index 0000000..c341785 --- /dev/null +++ b/qa/erase.test.cjs @@ -0,0 +1,107 @@ +// LinkSpin member erase (erase.js + scrub.js, 2026-11-15, ticket LS-1021) in JSON mode on a throwaway DATA_DIR, synthetic members only: +// scrub rules, dry run changes nothing, a module's live copy is scrubbed and saved (not overwritten later), plain documents +// and JSON Lines through the fs layer, their spin links (rotator.eraseOwner), the tombstone, blockers + force, the hub's +// member.erased event through hubsync.receive, and scrub.js being the same file in the sibling InstantAdPay checkout. +// node qa/erase.test.cjs +'use strict'; +const fs = require('fs'); const os = require('os'); const path = require('path'); const crypto = require('crypto'); const assert = require('assert'); +const ROOT = path.join(__dirname, '..'); +let fails = 0, n = 0; +async function t(name, fn) { n++; try { await fn(); console.log('ok', name); } catch (e) { fails++; console.log('FAIL', name, '::', e && e.stack ? e.stack.split('\n').slice(0, 3).join(' | ') : e); } } +delete process.env.DATABASE_URL; delete process.env.DOCSTORE_URL; +const { scrubDeep, scrubText, mentions } = require(path.join(ROOT, 'scrub.js')); +const E = 'gone.person9@example.test', OTHER = 'stay@example.test'; +const needles = { emails: [E], exact: ['goneuser', 'abc1234'] }; + +(async () => { + await t('scrub: keys, list items, records and map values go; other people and look-alikes stay', () => { + const doc = { byEmail: { [E]: { u: 'goneuser' }, [OTHER]: { u: 'stay', sponsorEmail: 'x@example.test' } }, byCode: { abc1234: E, zzz9999: OTHER }, + sends: [{ subject: 'Hi', recipients: [OTHER, E, 'xgone.person9@example.test'], delivered: [E] }], + log: [{ ts: 1, email: E, action: 'adopt' }, { ts: 2, email: OTHER }, { ts: 3, note: 'tankpay1:' + E + ':17' }], + clicks: { a1: { owner: E, n: 3 }, a2: { owner: OTHER, n: 1 } }, own: { 's:1': { [E]: 5, [OTHER]: 6 } }, nums: [1, 2, 3], + names: ['goneuserx', 'goneuser'], text: 'goneuser is a word here, kept', + prov: { [OTHER]: { sponsorEmail: E, at: 1 } }, team: [{ email: OTHER, sponsorEmail: E, ts: 4 }] }; + const removed = scrubDeep(doc, needles); + assert.ok(removed >= 9, 'removed ' + removed); + assert.deepStrictEqual(Object.keys(doc.byEmail), [OTHER]); assert.deepStrictEqual(doc.byCode, { zzz9999: OTHER }); + assert.deepStrictEqual(doc.sends[0].recipients, [OTHER, 'xgone.person9@example.test'], 'a longer address that contains it is someone else'); + assert.deepStrictEqual(doc.sends[0].delivered, []); assert.deepStrictEqual(doc.log.map(x => x.ts), [2]); + assert.deepStrictEqual(Object.keys(doc.clicks), ['a2']); assert.deepStrictEqual(doc.own, { 's:1': { [OTHER]: 6 } }); + assert.deepStrictEqual(doc.names, ['goneuserx'], 'a username only matches a whole string'); assert.strictEqual(doc.text, 'goneuser is a word here, kept'); + assert.deepStrictEqual(doc.nums, [1, 2, 3]); + assert.deepStrictEqual(doc.prov, { [OTHER]: { sponsorEmail: null, at: 1 } }, "another member's record only loses the pointer"); + assert.deepStrictEqual(doc.team, [{ email: OTHER, sponsorEmail: null, ts: 4 }]); + const lines = [JSON.stringify({ e: OTHER }), JSON.stringify({ e: E }), JSON.stringify({ u: 'goneuser' })].join('\n'); + const r = scrubText(lines, needles, true); assert.strictEqual(r.removed, 2); assert.strictEqual(r.body, JSON.stringify({ e: OTHER })); + assert.strictEqual(mentions('{"a":"' + OTHER + '"}', needles), false); + }); + + // ---- erase.js on a throwaway data dir ---- + const DIR = fs.mkdtempSync(path.join(os.tmpdir(), 'erase-iap-')); + const W = (f, o) => fs.writeFileSync(path.join(DIR, f), typeof o === 'string' ? o : JSON.stringify(o)); + const Rd = f => JSON.parse(fs.readFileSync(path.join(DIR, f), 'utf8')); + W('updates-log.json', { sends: [{ subject: 'S', recipients: [OTHER, E], delivered: [E] }] }); + W('legacy.json', { [E]: { b: 'faucetwave', s: 'e' }, [OTHER]: { b: 'tier1ads', s: 'a' } }); + W('events.jsonl', JSON.stringify({ e: E }) + '\n' + JSON.stringify({ e: OTHER })); + W('unrelated.json', { a: OTHER }); + // a module that keeps its document in memory and writes it back later (the reason erase works through the live copy) + let live = { rows: { [E]: { email: E, username: 'goneuser' }, [OTHER]: { email: OTHER } }, log: [{ email: E }] }; let saves = 0; + W('lsinbound.json', live); + const owner = { state: () => live, save: () => { saves++; W('lsinbound.json', live); } }; + let reloads = 0; + const accts = { [E]: { email: E, username: 'goneuser', code: 'abc1234', address: null, memberId: 0 }, [OTHER]: { email: OTHER, username: 'stay', code: 'zzz9999', sponsorRef: '' }, + 'walleted@example.test': { email: 'walleted@example.test', username: 'wal', code: 'w1', address: '0x' + '1'.repeat(40), memberId: 0 } }; + const accounts = { byEmail: async e => accts[e] || null, positions: async () => [], identities: async () => Object.values(accts), + listByReferrer: async refs => Object.values(accts).filter(a => refs.includes(a.sponsorRef)), removeAccount: async e => { if (!accts[e]) return { error: 'none' }; delete accts[e]; return { ok: true }; } }; + accounts.listAll = async () => Object.values(accts); + let rot = [{ id: 7, owner: E }, { id: 8, owner: OTHER }]; const rotator = { eraseOwner: async (e, dry) => { const mine = rot.filter(r => r.owner === e); if (!dry) rot = rot.filter(r => r.owner !== e); return { rotations: mine.length, hits: 0, conv: 0 }; } }; + const erase = require(path.join(ROOT, 'erase.js')); + let forgot = []; + erase.init({ dataDir: DIR, accounts, ads: { listCampaigns: async () => [] }, rotator, docstore: null, owners: { 'lsinbound.json': owner }, reload: { 'legacy.json': () => reloads++ }, forget: [e => forgot.push(e)] }); + const before = fs.readFileSync(path.join(DIR, 'updates-log.json'), 'utf8'); + + await t('dry run (the default) counts and changes nothing', async () => { + const r = await erase.erase(E); + assert.strictEqual(r.dryRun, true); assert.strictEqual(r.found, true); assert.deepStrictEqual(r.blockers, []); + assert.deepStrictEqual(Object.keys(r.docs).sort(), ['events.jsonl', 'legacy.json', 'lsinbound.json', 'updates-log.json']); + assert.strictEqual(fs.readFileSync(path.join(DIR, 'updates-log.json'), 'utf8'), before); assert.ok(live.rows[E], 'live copy untouched'); + assert.ok(accts[E]); assert.strictEqual(erase.isErased(E), false); assert.strictEqual(saves, 0); assert.strictEqual(r.spinLinks.rotations, 1); assert.strictEqual(rot.length, 2); + }); + await t('a linked wallet blocks it, force overrides', async () => { + const r = await erase.erase('walleted@example.test', { dryRun: false }); assert.ok(/main wallet/.test(r.error)); assert.ok(accts['walleted@example.test']); + const f = await erase.erase('walleted@example.test', { dryRun: false, force: true }); assert.strictEqual(f.forced, true); assert.ok(!accts['walleted@example.test']); + }); + await t('erase: the account, the live copy (saved), plain docs, JSON Lines; reload hook; caches; tombstone; others intact', async () => { + const r = await erase.erase(E, { dryRun: false }); + assert.strictEqual(r.ok, true); assert.ok(!accts[E]); assert.ok(accts[OTHER]); assert.deepStrictEqual(rot, [{ id: 8, owner: OTHER }], 'their spin link went, not the other one'); + assert.deepStrictEqual(Object.keys(live.rows), [OTHER]); assert.deepStrictEqual(live.log, []); assert.strictEqual(saves, 1); + assert.deepStrictEqual(Rd('lsinbound.json').rows[E], undefined); + assert.deepStrictEqual(Rd('updates-log.json').sends[0], { subject: 'S', recipients: [OTHER], delivered: [] }); + assert.deepStrictEqual(Object.keys(Rd('legacy.json')), [OTHER]); assert.strictEqual(reloads, 1); + assert.strictEqual(fs.readFileSync(path.join(DIR, 'events.jsonl'), 'utf8'), JSON.stringify({ e: OTHER })); + assert.deepStrictEqual(r.docResidue, []); assert.deepStrictEqual(forgot.slice(-1), [E]); + assert.strictEqual(erase.isErased(E), true); assert.strictEqual(erase.isErased(OTHER), false); + const log = fs.readFileSync(path.join(DIR, 'erase.json'), 'utf8'); assert.ok(!log.includes(E), 'the erase log keeps no email'); assert.ok(log.includes(erase.hashOf(E).slice(0, 16))); + const again = await erase.erase(E, { dryRun: false }); assert.strictEqual(again.found, false); assert.deepStrictEqual(again.docs, {}, 'a second run finds nothing'); + }); + await t('hub member.erased: found by the email hash through hubsync.receive, answered 200', async () => { + accts['hubgone@example.test'] = { email: 'hubgone@example.test', username: 'hg', code: 'hg12345', address: null, memberId: 0 }; + process.env.HUB_ENABLED = '1'; process.env.HUB_URL = 'http://127.0.0.1:9'; process.env.HUB_SECRET = 's'.repeat(40); + const hubsync = require(path.join(ROOT, 'hubsync.js')); + hubsync.init({ dataDir: DIR, accounts, registry: {}, carry: { hold() {}, unhold() {} }, follow: null, chain: null, erase, erased: e => erase.isErased(e) }); + const raw = JSON.stringify({ events: [{ seq: 9001, at: Date.now(), type: 'member.erased', personId: 'h_' + '0'.repeat(16), data: { emailHash: erase.hashOf('HubGone@example.test') } }] }); + const ts = String(Date.now()); const sig = crypto.createHmac('sha256', 's'.repeat(40)).update(ts + '\n' + raw).digest('hex'); + const r = await hubsync.receive({ 'x-hub-ts': ts, 'x-hub-sig': sig }, raw); + assert.strictEqual(r.status, 200); assert.ok(!accts['hubgone@example.test'], 'erased'); assert.strictEqual(erase.isErased('hubgone@example.test'), true); + const r2 = await hubsync.receive({ 'x-hub-ts': ts, 'x-hub-sig': sig }, raw); assert.strictEqual(r2.status, 200, 'delivered twice is fine'); + }); + await t('scrub.js is the same file in the sibling checkout (InstantAdPay <-> LinkSpin)', () => { + const sib = [path.join(ROOT, '..', '..', 'linkspin', 'site'), path.join(ROOT, '..', '..', 'onchain-ad-membership', 'site'), path.join(ROOT, '..', 'ls-erase'), path.join(ROOT, '..', 'iap-erase')] + .map(d => path.join(d, 'scrub.js')).find(f => fs.existsSync(f) && path.resolve(f) !== path.resolve(path.join(ROOT, 'scrub.js'))); + if (!sib) { console.log(' (sibling scrub.js not found, skipped)'); return; } + const h = f => crypto.createHash('sha1').update(fs.readFileSync(f, 'utf8').replace(/\r\n/g, '\n')).digest('hex'); + assert.strictEqual(h(path.join(ROOT, 'scrub.js')), h(sib), 'scrub.js differs from ' + sib); + }); + console.log(fails ? fails + ' of ' + n + ' FAILED' : 'linkspin erase: all ' + n + ' passed'); + process.exit(fails ? 1 : 0); +})(); diff --git a/qa/run.sh b/qa/run.sh index 572100c..61211a8 100644 --- a/qa/run.sh +++ b/qa/run.sh @@ -78,6 +78,7 @@ elif [ "$MODE" = "member" ]; then node qa/netconv.test.mjs || status=1 node qa/topup-positions.test.cjs || status=1 # a top-up the ad's position cannot cover offers the position that can, then moves the ad there (Michael Camire 2026-11-14) node qa/bannerspin-attrib.test.cjs || status=1 # Banner Spin: impression -> click -> the banner shown gets the click (same browser, same connection, script ?x=), rows add up (Michael Camire 2026-11-14) + node qa/erase.test.cjs || status=1 # member erase (erase.js + scrub.js, 2026-11-15, LS-1021) elif [ "$MODE" = "policy" ]; then node qa/profile-policy.test.cjs || status=1 elif [ "$MODE" = "sponsorfollow" ]; then diff --git a/registry.js b/registry.js index 73b9261..9c6b7ab 100644 --- a/registry.js +++ b/registry.js @@ -63,4 +63,4 @@ async function importRows(rows, property) { let n = 0; for (const r of rows || []) { if (await upsert(Object.assign({ firstProperty: property || 'instantadpay' }, r))) n++; } return n; } -module.exports = { init, get, byWallet, byUsername, upsert, all, count, chainUp, importRows }; +module.exports = { /* member erase (erase.js, 2026-11-15): the live copy */ _json: { state: () => { if (!J.db) J.load(); return J.db; }, save: () => J.save() }, init, get, byWallet, byUsername, upsert, all, count, chainUp, importRows }; diff --git a/rotator.js b/rotator.js index 5fcce2c..0980b0b 100644 --- a/rotator.js +++ b/rotator.js @@ -362,6 +362,18 @@ async function claim(demoOwner, newOwner) { for (const r of mine) { r.owner = o; delete r.demo; delete r.expires; r.name = r.name === 'My first spin' ? 'My first spin' : r.name; } if (mine.length) J.save(); return { ok: true, claimed: mine.length }; } +// member erase (erase.js, 2026-11-15): every spin link the person owns goes, with its clicks (memory and every rot_hits row) and +// conversions. dryRun counts only. -> { rotations, hits, conv } +async function eraseOwner(email, dryRun) { + const e = norm(email); const ids = new Set(J.db.rotations.filter(r => norm(r.owner) === e).map(r => r.id)); + if (!ids.size) return { rotations: 0, hits: 0, conv: 0 }; + const list = [...ids]; const memHits = J.db.hits.filter(h => ids.has(h.r)).length; const conv = J.db.conv.filter(c => ids.has(c.r)).length; + if (dryRun) { const rows = docstore.isOn() ? await docstore.rowsWhere('rot_hits', '$.r', list, false) : 0; return { rotations: ids.size, hits: Math.max(memHits, rows), conv }; } + J.db.rotations = J.db.rotations.filter(r => !ids.has(r.id)); // first: no new click can be counted for them + J.db.hits = J.db.hits.filter(h => !ids.has(h.r)); J.db.conv = J.db.conv.filter(c => !ids.has(c.r)); HIT_IX = null; J.save(); + const rows = docstore.isOn() ? await docstore.rowsWhere('rot_hits', '$.r', list, true) : 0; + return { rotations: ids.size, hits: Math.max(memHits, rows), conv }; +} function sweepDemos() { const now = Date.now(); const gone = new Set(); J.db.rotations = J.db.rotations.filter(r => { if (r.demo && r.expires && r.expires < now) { gone.add(r.id); return false; } return true; }); @@ -395,5 +407,5 @@ function adminAll() { destinations: (r.destinations || []).map(d => ({ id: d.id, url: d.url, label: d.label || '', weight: d.weight, active: !!d.active, autoPaused: d.autoPaused || 0, health: d.health ? { state: d.health.state, note: d.health.note || '', checkedAt: d.health.checkedAt || 0 } : null })), hits: o.hits, hits7: o.hits7, bots: o.bots, conversions: cv[r.id] || 0 }; }); } -module.exports = { init, convRows, adminAll, hitById, list, get, create, update, remove, addDest, updateDest, resolve, stats, totals, convert, summary, createDemo, claim, sweepDemos, servedToday, window24, +module.exports = { eraseOwner, _json: { state: () => J.db, save: () => J.save() }, init, convRows, adminAll, hitById, list, get, create, update, remove, addDest, updateDest, resolve, stats, totals, convert, summary, createDemo, claim, sweepDemos, servedToday, window24, pub, rawRotations, save, findMine, setExternalConvert, PRESETS, cleanHours, cleanTz, cellAt, zoneFor, isOn, COUNTRY_TZ, sourceCounts, detachSource, ensureFixed, ensurePartner, partnerStats }; diff --git a/scrub.js b/scrub.js new file mode 100644 index 0000000..3888f51 --- /dev/null +++ b/scrub.js @@ -0,0 +1,61 @@ +// Member erase helper (Marty 2026-11-15, ticket LS-1021): take one person out of a data document without touching anyone +// else's entries. The SAME file ships in InstantAdPay and LinkSpin (qa/erase.test.cjs checks the copies match). +// +// needles = { emails: [...], exact: [...] }: an email matches anywhere inside a string at word edges ("x|a@b.com|y", +// "tankpay1:a@b.com:17"); an exact needle (username, referral code, hub id) only matches a whole string or key, so a short +// username never eats unrelated text. Rules, applied from the top of the document down: +// - a key that matches is deleted with everything under it (byEmail[a@b.com], hashes[a@b.com], own[..][a@b.com]) +// - an array item that is a matching string, or an object with a matching field (other than a pointer, below), is removed +// - in a map, a record that is THEIRS (its email / owner / adoptee / username ... field matches) is removed whole +// (clicks {owner}, refill records {owner}, rows {email}) +// - in another member's record, a field that only POINTS at them (sponsorEmail, prevEmail, adopter, ...) is set to null +// - any other matching string value in a map is deleted with its key (byCode[code] = email) +// - anything else is walked into. Numbers, booleans and other people's records stay as they were. +// Returns how many keys / items / records / fields were removed or blanked (0 = nothing about them in it). +'use strict'; + +const esc = s => String(s).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +function matcher(needles) { + const emails = [...new Set(((needles && needles.emails) || []).map(e => String(e || '').trim().toLowerCase()).filter(e => e.includes('@')))]; + const exact = new Set(((needles && needles.exact) || []).map(x => String(x || '').trim().toLowerCase()).filter(x => x.length >= 3)); + const re = emails.length ? new RegExp('(^|[^a-z0-9._%+-])(' + emails.map(esc).join('|') + ')(?![a-z0-9-]|\\.[a-z0-9])', 'i') : null; + const hit = s => { if (typeof s !== 'string' || !s) return false; const l = s.trim().toLowerCase(); return exact.has(l) || (re ? re.test(s) : false); }; + const inText = s => { if (!s) return false; if (re && re.test(s)) return true; for (const x of exact) if (s.toLowerCase().includes('"' + x + '"')) return true; return false; }; + return { hit, inText, empty: !emails.length && !exact.size }; +} +const isObj = v => v && typeof v === 'object' && !Array.isArray(v); +const OWN = new Set(['email', 'owner', 'owneremail', 'adoptee', 'member', 'memberemail', 'user', 'username', 'account', 'lead', 'person', 'recipient', 'e', 'u']); +const REF = new Set(['sponsoremail', 'prevemail', 'previousemail', 'adopter', 'adopteremail', 'sponsor', 'from', 'to', 'by', 'inviter', 'referrer', 'mentor', 'coach']); +const otherHit = (v, m) => isObj(v) && Object.entries(v).some(([k, x]) => typeof x === 'string' && !REF.has(k.toLowerCase()) && m.hit(x)); // not just a pointer +const ownHit = (v, m) => isObj(v) && Object.entries(v).some(([k, x]) => typeof x === 'string' && OWN.has(k.toLowerCase()) && m.hit(x)); + +function scrubDeep(node, needles, m0) { + const m = m0 || matcher(needles); if (m.empty) return 0; + let n = 0; + if (Array.isArray(node)) { + for (let i = node.length - 1; i >= 0; i--) { + const v = node[i]; + if ((typeof v === 'string' && m.hit(v)) || otherHit(v, m)) { node.splice(i, 1); n++; } // their item / a log line about them + else if (v && typeof v === 'object') n += scrubDeep(v, null, m); + } + } else if (isObj(node)) { + for (const k of Object.keys(node)) { + const v = node[k]; + if (m.hit(k) || ownHit(v, m)) { delete node[k]; n++; continue; } + if (typeof v === 'string' && m.hit(v)) { if (REF.has(k.toLowerCase())) node[k] = null; else delete node[k]; n++; continue; } + if (v && typeof v === 'object') n += scrubDeep(v, null, m); + } + } + return n; +} +// a whole document as text: JSON is parsed, scrubbed and written back; JSON Lines lose every line that mentions them. +// Returns { body, removed } (body unchanged and removed 0 when nothing matched). +function scrubText(body, needles, isLines) { + const m = matcher(needles); if (m.empty || !m.inText(body)) return { body, removed: 0 }; + if (isLines) { const lines = String(body).split('\n'); const keep = lines.filter(l => !m.inText(l)); return { body: keep.join('\n'), removed: lines.length - keep.length }; } + const obj = JSON.parse(body); const removed = scrubDeep(obj, null, m); + return { body: removed ? JSON.stringify(obj) : body, removed }; +} +const mentions = (body, needles) => matcher(needles).inText(String(body || '')); + +module.exports = { scrubDeep, scrubText, mentions, matcher }; diff --git a/server.js b/server.js index 5dc3aa2..82b50fc 100644 --- a/server.js +++ b/server.js @@ -46,6 +46,7 @@ const leaderboard = require('./leaderboard'); const toolkit = require('./toolkit'); const registry = require('./registry'); // network registry: who is who across properties (LinkSpin, 2026-09-15) const iapsync = require('./iapsync'); // reverse registry sync: LinkSpin-first members reach InstantAdPay (2026-10-15) +const erase = require('./erase'); // member erase (2026-11-15, LS-1021): POST /api/admin/erase + the hub's member.erased event const hubsync = require('./hubsync'); // network hub link, inert unless HUB_ENABLED=1 (2026-11-12) const SF = require('./sponsorfollow'); // deliberate sponsor changes follow to InstantAdPay until chain-bound + one network tank (2026-10-22) let follow = null, followStore = null; @@ -741,7 +742,7 @@ async function boot() { setTimeout(() => carry.backfillMemberIds().then(r => console.log('memberId backfill', JSON.stringify(r))).catch(e => console.error('memberId backfill', e.message)), 60000); // reverse registry sync (2026-10-15): account changes reach InstantAdPay within seconds; a 2-minute reconcile catches the rest iapsync.init({ dataDir: DATA_DIR, accounts, registry, host: SITE_HOST, follow: followStore, tank: () => tank }); accounts.onChange(email => { iapsync.touch(email); hubsync.touch(email); }); - hubsync.init({ dataDir: DATA_DIR, accounts, registry, carry, follow: followStore, chain }); setInterval(() => hubsync.tick().catch(e => console.error('hubsync', e.message)), 30 * 1000); // touch/tick do nothing while HUB_ENABLED is off + hubsync.init({ dataDir: DATA_DIR, accounts, registry, carry, follow: followStore, chain, erase, erased: email => erase.isErased(email) }); setInterval(() => hubsync.tick().catch(e => console.error('hubsync', e.message)), 30 * 1000); // touch/tick do nothing while HUB_ENABLED is off setTimeout(() => iapsync.tick().catch(e => console.error('iapsync', e.message)), 2 * 60 * 1000); setInterval(() => iapsync.tick().catch(e => console.error('iapsync', e.message)), 2 * 60 * 1000); const ownHosts = () => [SITE_HOST].concat(String(siteConfig().linkDomains || '').split(',').map(x => x.trim().toLowerCase()).filter(Boolean), pagesHost() ? [pagesHost()] : []); @@ -763,6 +764,13 @@ async function boot() { zones.init({ dataDir: DATA_DIR, ads, siteHost: SITE_HOST }); pages.init({ dataDir: DATA_DIR, ownHosts, imageBase: () => (IS_PROD ? 'https' : 'http') + '://' + SITE_HOST, openrouterKey: () => { if (process.env.OPENROUTER_API_KEY) return process.env.OPENROUTER_API_KEY.trim(); try { return fs.readFileSync(path.join(DATA_DIR, 'openrouter.key'), 'utf8').trim(); } catch (e) { return ''; } } }); audiences.init({ dataDir: DATA_DIR }); + // member erase (erase.js, 2026-11-15): the modules that keep a document in memory are scrubbed through their live copy, the rest through docstore + erase.init({ dataDir: DATA_DIR, accounts, ads, rotator, docstore, + owners: { 'accounts.json': accounts._json, 'audiences.json': { state: audiences._state, save: audiences._save }, 'coach.json': coach._json, + 'convtrack.json': { state: convtrack._state, save: convtrack._save }, 'earned.json': ads._earned, 'hubsync.json': { state: hubsync._state, save: hubsync._save }, + 'iapsync.json': { state: iapsync._state, save: iapsync._save }, 'mail-intro.json': mailer._intro, 'postbacks.json': postbacks._json, 'registry.json': registry._json, + 'rotator.json': rotator._json, 'sponsorfollow.json': { state: followStore._state, save: followStore._save } }, + reload: {}, forget: [email => iapsync._forget(email), email => hubsync._forgetHeld(email)] }); // link-domain pool: channels live in site.json (linkDomainChannels), check state in domains.json; a burn alerts the admin once domains.init({ dataDir: DATA_DIR, siteConfig, saveSite: patch => fs.writeFileSync(SITE_FILE, JSON.stringify(Object.assign(siteConfig(), patch), null, 2)), notify: async text => { const sc = siteConfig(); if (sc.telegramBotToken && sc.telegramAdminChatId) await telegramSend(sc.telegramAdminChatId, text); else if (ADMIN_EMAIL && mailer.hasKey()) await mailer.send(ADMIN_EMAIL, 'LinkSpin: link domain burned', text.replace(/<[^>]+>/g, '')); } }); @@ -2376,6 +2384,13 @@ const server = http.createServer(async (req, res) => { spamscan.setAllow(e, !b.remove); console.log('spamscan allowlist', b.remove ? 'removed' : 'added', e); return json(res, 200, spamscan.view()); } + // member erase (2026-11-15, ticket LS-1021): {email, dryRun (default true; only dryRun: false erases), force}. erase.js + if (p === '/api/admin/erase' && req.method === 'POST') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + const b = await readBody(req); const r = await erase.erase(String(b.email || ''), { dryRun: b.dryRun !== false, force: b.force === true, by: 'admin' }); + return json(res, r.error ? 400 : 200, r); + } + if (p === '/api/admin/erase' && req.method === 'GET') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); return json(res, 200, erase.view()); } if (p === '/api/admin/member' && req.method === 'DELETE') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); const e = String(u.searchParams.get('email') || '').trim().toLowerCase(); const acct = e && await accounts.byEmail(e); @@ -3054,7 +3069,7 @@ const server = http.createServer(async (req, res) => { const want = crypto.createHmac('sha256', secret).update(ts + '\n' + raw).digest('hex'); if (want.length !== sig.length || !crypto.timingSafeEqual(Buffer.from(want), Buffer.from(sig))) return json(res, 401, { error: 'bad signature' }); let b; try { b = JSON.parse(raw || '{}'); } catch (e) { return json(res, 400, { error: 'bad json' }); } - const rows = Array.isArray(b.rows) ? b.rows.slice(0, 500) : []; + const rows = (Array.isArray(b.rows) ? b.rows.slice(0, 500) : []).filter(r => !(r && erase.isErased(r.email))); // erased here (erase.js): a sync never brings them back // sponsor follow (2026-10-22): no engine activation may start for these people until the batch has settled their // sponsor (carry.hold); wallets are linked LAST, after every sponsor decision, for the same reason const held = rows.map(r => String(r.email || '').trim().toLowerCase()).filter(Boolean); carry.hold(held); diff --git a/sponsorfollow.js b/sponsorfollow.js index c330946..8862b52 100644 --- a/sponsorfollow.js +++ b/sponsorfollow.js @@ -134,7 +134,7 @@ function create(opts) { setPeer(proto) { const s = load(); if (s.peer.proto !== proto) { s.peer.proto = proto; s.peer.at = Date.now(); save(); } }, peerProto() { return Number(load().peer.proto) || 1; }, view() { const s = load(); return { records: Object.keys(s.prov).length, remoteTank: Object.keys(s.remote).length, pending: Object.keys(s.pending).length, peerProto: Number(s.peer.proto) || 1, recent: s.log.slice(-40).reverse() }; }, - _state: load, _reset() { st = null; } + _state: load, _save: save, _reset() { st = null; } // _state/_save: the member erase (erase.js) scrubs the live copy }; return api; }