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 rows stay consistent. Refused unless
force: a main wallet, an on-chain member number, positions, a team here, ads still running or queued. SQL: the account,
sessions, signals, credits (unspent ad credits go away), credit log, views, visits, drips, nudges, digests, adoptions,
marks, promo redemptions, prospects, pipeline notes, their ads and every row hanging off them; messages they sent and
notices to them; a chat another member sent them stays for that member with a tombstone recipient; help-desk tickets
stay as history with the requester tombstoned and their own messages blanked; other members' mute lists. Documents:
every doc that mentions them is scrubbed by scrub.js (new, same file in LinkSpin) through the owning module's live copy
(lsinbound, lssync, sponsorfollow, refill, tank-ready, hubsync) or through docstore (legacy reloaded). A residue sweep
over every text column reports anything left. A 30-day email-hash tombstone (erase.json) stops lsinbound and the hub
path from bringing them back; the log keeps hashes and counts only. hubsync handles member.erased {emailHash}.
qa/erase.test.cjs 6 pass (JSON mode); qa/erase.mysql.test.cjs passes against a disposable mysql:8 on core.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
martbost
2026-11-15 12:29:31 -06:00
parent b925661eac
commit 84d566e784
13 changed files with 461 additions and 10 deletions
+2 -1
View File
@@ -188,4 +188,5 @@ 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)
module.exports = { install, init, drain, flush, view, nameOf, rows, rowPut, rowDel, isOn, claim, names };
+184
View File
@@ -0,0 +1,184 @@
// 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 InstantAdPay from INSIDE the running app, so the documents the modules keep in memory and the MySQL
// 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 (stop it first: skill iap-kill-ad). What goes:
// - the account, sessions, signals, credits (unspent ad credits simply go away), credit log, views, visits, drips, nudges,
// digests, adoptions (as adoptee or adopter), marks, promo redemptions, prospects and pipeline notes, their ads with every
// row that hangs off them (hours, countries, clicks, inbox deliveries, visits, reports);
// - messages: everything they sent; notices and broadcasts to them; a CHAT message another member sent them stays for that
// member, its recipient replaced by a tombstone address;
// - help desk tickets stay as closed history: requester replaced by the tombstone, their own messages blanked;
// - every data document (docs table) that mentions them: their keys, list items and records (scrub.js), through the owning
// module's live state when a module keeps one in memory, else read and written through docstore.
// A tombstone (SHA-256 of the email, kept 30 days in erase.json) stops the LinkSpin and hub syncs 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 db = require('./db');
const { scrubDeep, scrubText, mentions } = require('./scrub');
let R = null; // { dataDir, accounts, docstore, owners: {doc: {state, save}}, reload: {doc: fn}, forget: [fn(email)] }
const TOMB_MS = 30 * 86400000;
const REMOVED = '[removed: this member asked for their data to be erased]';
const norm = v => String(v || '').trim().toLowerCase();
const hashOf = email => crypto.createHash('sha256').update(norm(email)).digest('hex');
const tombAddr = hash => 'erased-' + hash.slice(0, 12) + '@erased.invalid';
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;
}
const like = t => '%' + String(t).replace(/[\\%_]/g, m => '\\' + m) + '%';
async function tables() { return new Set((await db.q('SELECT table_name t FROM information_schema.tables WHERE table_schema = DATABASE()')).map(r => r.t || r.TABLE_NAME)); }
// the SQL work, in order: deletes and the two updates that keep other members' side of a conversation / the desk history
function steps(E, h, campIds, ticketIds, memberMsgIds) {
const S = []; const tomb = tombAddr(h);
const del = (t, where, args) => S.push({ t, where, args, op: 'delete' });
const upd = (t, set, setArgs, where, args) => S.push({ t, where, args, op: 'update', set, setArgs });
del('accounts', 'email=?', [E]); del('sessions', 'email=?', [E]); // first: nothing can sign in or be synced as them while the rest runs
if (campIds.length) for (const t of ['camp_hours', 'camp_geo', 'click_sources', 'solo_inbox', 'visit_seen', 'visit_repeat', 'video_seen', 'ad_reports', 'ad_clicks']) del(t, 'campaign_id IN (?)', [campIds]);
del('campaigns', 'owner_email=?', [E]); del('ad_clicks', 'owner_email=?', [E]);
for (const t of ['account_signals', 'daily_views', 'digests', 'drips', 'earned_credits', 'nudges', 'solo_inbox', 'visit_seen', 'visit_repeat', 'video_seen', 'credit_log', 'promo_redemptions', 'positions']) del(t, 'email=?', [E]);
del('prospects', 'owner_email=?', [E]); del('pipeline_notes', 'owner_email=? OR person=?', [E, E]); del('lead_marks', '`lead`=? OR sponsor=?', [E, E]);
upd('ad_reports', "reporter=''", [], 'reporter=?', [E]); upd('promo_codes', 'funder=NULL', [], 'funder=?', [E]);
del('adoptions', 'adoptee=? OR adopter=?', [E, E]);
del('event_marks', 'k LIKE ?', [like(E)]); del('doc_claims', 'k LIKE ?', [like(E)]);
del('sponsor_messages', 'from_email=?', [E]);
upd('sponsor_messages', 'to_email=?', [tomb], "to_email=? AND kind='chat'", [E]); // the other member's own words stay theirs
del('sponsor_messages', "to_email=? AND kind<>'chat'", [E]); // notices, alerts, broadcasts: copies made for them alone
if (memberMsgIds.length) del('ticket_translations', 'message_id IN (?)', [memberMsgIds]);
if (ticketIds.length) upd('ticket_messages', 'body=?, attachments=NULL, email_message_id=NULL', [REMOVED], "ticket_id IN (?) AND author='member'", [ticketIds]);
upd('tickets', 'email=?, name=NULL, username=NULL', [tomb], 'email=?', [E]);
return S;
}
// what still mentions them anywhere in the database (every text column of every table but docs); [] = clean
async function residue(E, exact) {
if (!db.enabled()) return [];
const cols = await db.q("SELECT table_name t, column_name c FROM information_schema.columns WHERE table_schema = DATABASE() AND data_type IN ('char','varchar','text','mediumtext','longtext','json') AND table_name NOT IN ('docs','docs_writer')");
const out = [];
for (const r of cols) {
const t = r.t || r.TABLE_NAME, c = r.c || r.COLUMN_NAME; const ex = exact.filter(Boolean);
const where = '`' + c + '` LIKE ?' + ex.map(() => ' OR `' + c + '` = ?').join('');
try { const [x] = await db.q('SELECT COUNT(*) n FROM `' + t + '` WHERE ' + where, [like(E)].concat(ex)); if (Number(x.n)) out.push({ table: t, column: c, n: Number(x.n) }); } catch (e) {}
}
return out;
}
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); }
if (db.enabled()) { const [r] = await db.q("SELECT COUNT(*) n FROM campaigns WHERE owner_email=? AND status IN ('active','queued','paused')", [E]); if (Number(r.n)) out.push('ads still running or queued: ' + r.n + ' (stop them first, skill iap-kill-ad)'); }
return out;
}
// email -> {ok, dryRun, emailHash, found, blockers, sql: {table: rows}, docs: {doc: removed}, residue, 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, sql: {}, docs: {} };
if (blockers.length && !o.force && !o.dryRun) return Object.assign(res, { error: 'Not erased: ' + blockers.join('; ') + '. Send force: true to erase anyway.' });
let campIds = [], ticketIds = [], memberMsgIds = [], have = new Set();
if (db.enabled()) {
have = await tables();
campIds = (await db.q('SELECT id FROM campaigns WHERE owner_email=?', [E])).map(r => r.id);
ticketIds = have.has('tickets') ? (await db.q('SELECT id FROM tickets WHERE email=?', [E])).map(r => r.id) : [];
memberMsgIds = ticketIds.length ? (await db.q("SELECT id FROM ticket_messages WHERE ticket_id IN (?) AND author='member'", [ticketIds])).map(r => r.id) : [];
}
if (!o.dryRun) { load().tomb[h] = Date.now(); save(); } // before anything goes: the syncs refuse them from here on
if (db.enabled()) {
for (const s of steps(E, h, campIds, ticketIds, memberMsgIds)) {
if (!have.has(s.t)) continue;
const key = s.t + (s.op === 'update' ? ' (kept, scrubbed)' : '');
if (o.dryRun) { const [r] = await db.q('SELECT COUNT(*) n FROM `' + s.t + '` WHERE ' + s.where, s.args); res.sql[key] = (res.sql[key] || 0) + Number(r.n); continue; }
const r = s.op === 'delete' ? await db.q('DELETE FROM `' + s.t + '` WHERE ' + s.where, s.args) : await db.q('UPDATE `' + s.t + '` SET ' + s.set + ' WHERE ' + s.where, s.setArgs.concat(s.args));
res.sql[key] = (res.sql[key] || 0) + Number(r.affectedRows || 0);
}
// other members' chat mute lists that name them
const mutes = await db.q('SELECT email, chat_mutes FROM accounts WHERE chat_mutes LIKE ?', [like(E)]);
let mu = 0; for (const m of mutes) { let list = []; try { list = JSON.parse(m.chat_mutes || '[]'); } catch (e) {} const keep = list.filter(x => norm(x) !== E); if (keep.length !== list.length) { mu++; if (!o.dryRun) await db.q('UPDATE accounts SET chat_mutes=? WHERE email=?', [JSON.stringify(keep), m.email]); } }
if (mu) res.sql['accounts.chat_mutes (others, scrubbed)'] = mu;
} else if (acct && !o.dryRun) { const r = await R.accounts.removeAccount(E); res.sql.accounts = r && r.ok ? 1 : 0; }
else if (acct) res.sql.accounts = 1;
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.sql)) if (!res.sql[k]) delete res.sql[k];
for (const k of Object.keys(res.docs)) if (!res.docs[k]) delete res.docs[k];
if (o.sweep) { res.residue = await residue(E, exact); 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,
sql: Object.values(res.sql).reduce((a, b) => a + b, 0), docs: Object.keys(res.docs).length, residue: (res.residue || []).length });
if (s.log.length > 500) s.log = s.log.slice(-500); save();
console.log('member erase', h.slice(0, 16), 'by', o.by, 'sql rows', JSON.stringify(res.sql), '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 (accounts, then the help desk)
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.identities()) if (hashOf(a.email) === h) { email = norm(a.email); break; }
if (!email && db.enabled()) { try { for (const r of await db.q('SELECT DISTINCT email FROM tickets')) if (hashOf(r.email) === h) { email = norm(r.email); break; } } catch (e) {} }
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, sql: r.sql, 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; } };
+13 -1
View File
@@ -16,6 +16,8 @@
// Rule 2 (2026-11-14): the sponsor written for an arrival is person.locks.iap's sponsor when that lock exists, never the
// plain network sponsor. QUIET: nothing on this path sends mail, a notice or a post, and lssync.js never
// pushes a hub waiting account to LinkSpin (qa/hubsync.test.cjs, mail audit).
// member.erased (2026-11-15) the hub erased someone: erase.js finds them by the SHA-256 of the email and takes them out
// here too; refused (wallet, member number, team) = a log note, never retried.
// anything else ignored.
// Each seq is applied once (done map). A failing event answers 503 so the hub retries it; after 5 tries it is set aside
// in the log so one bad row cannot hold every later event back.
@@ -130,9 +132,19 @@ async function walletConnected(ev) {
if (sum && sum.errors) throw new Error('lsinbound errors ' + sum.errors);
return 'applied';
}
// member.erased (2026-11-15): the hub erased someone; erase.js takes them out here too, found by the SHA-256 of the email
// (the event carries nothing else). Refused here (a wallet, a member number, a team) = noted for Marty, never retried.
async function memberErased(ev) {
if (!R.erase) return 'ignored';
const r = await R.erase.byHash(ev.data && ev.data.emailHash, 'hub');
if (r.result === 'refused') note({ type: 'erase-refused', hash: String(ev.data.emailHash).slice(0, 16), error: String(r.error || '').slice(0, 200) });
else note({ type: 'erased', hash: String((ev.data && ev.data.emailHash) || '').slice(0, 16), result: r.result });
return r.result === 'erased' ? 'applied' : 'ignored';
}
async function apply(ev) {
if (ev.type === 'member.joined') return memberJoined(ev);
if (ev.type === 'wallet.connected') return walletConnected(ev);
if (ev.type === 'member.erased') return memberErased(ev);
// sponsor.changed is IGNORED here on purpose (checked 2026-11-14 for the switch-on): it would need the deliberate-change
// record (at / by / previous sponsor) to go through sponsorfollow's rule, and a member locked on the InstantAdPay contract
// must never move anyway (the contract pays whoever it holds). qa/hubsync.test.cjs proves a locked member stays put.
@@ -359,4 +371,4 @@ function adminView() {
return Object.assign({ enabled: enabled(), on: on(), site: SITE(), url: URL_(), since: s.since, outbox: s.outbox.length, retrying: Object.keys(s.tries).length,
disagree: Object.keys(s.disagree).length, tankCache: held.size, tankHubDownUntil: heldDownUntil || null }, s.stats, { disagreements: Object.entries(s.disagree).slice(-25).map(([email, d]) => Object.assign({ email }, d)), recent: s.log.slice(-25).reverse() });
}
module.exports = { _hubBy: hubBy, init, enabled, on, receive, touch, wallet, onChain, flush, reconcile, start, adminView, heldAmong, lockedAnywhere, hubSponsor, hubInfo, resolvePerson: q => resolve(q), _sign: sign, _heldReset: () => { held.clear(); heldDownUntil = 0; }, _heldAge: ms => { for (const c of held.values()) c.at -= ms; } };
module.exports = { _state: load, _save: save, _forgetHeld: email => held.delete(norm(email)), _hubBy: hubBy, init, enabled, on, receive, touch, wallet, onChain, flush, reconcile, start, adminView, heldAmong, lockedAnywhere, hubSponsor, hubInfo, resolvePerson: q => resolve(q), _sign: sign, _heldReset: () => { held.clear(); heldDownUntil = 0; }, _heldAge: ms => { for (const c of held.values()) c.at -= ms; } };
+2 -2
View File
@@ -160,7 +160,7 @@ async function handle(rows, opts) {
const s = load(); s.stats.batches++;
const sum = { rows: 0, noop: 0, created: 0, filled: 0, sponsored: 0, conflicts: 0, pendingSponsor: 0, errors: 0, followed: 0, followKept: 0, tank: 0 };
const ctx = { sum, done: new Set(), via: opts && opts.via, refOf: opts && opts.refOf }; const batch = [];
for (const x of rows || []) { const r = clean(x); if (!r) continue; sum.rows++; s.rows[r.email] = r; batch.push(r); }
for (const x of rows || []) { const r = clean(x); if (!r) continue; if (R.erased && R.erased(r.email)) { sum.erased = (sum.erased || 0) + 1; continue; } sum.rows++; s.rows[r.email] = r; batch.push(r); } // erased here (erase.js): never brought back by a sync
if (R.store) for (const r of batch) if (Object.prototype.hasOwnProperty.call(r, 'tank')) { R.store.setRemote(r.email, r.tank); sum.tank++; } // network tank
try {
for (const r of batch) {
@@ -192,4 +192,4 @@ function networkSponsor(email, address) {
if (/^0x[0-9a-f]{40}$/.test(w)) for (const x of Object.values(s.rows)) if (x.wallet === w && x.sponsorEmail && x.sponsorEmail !== e && x.email !== e) return { sponsorEmail: x.sponsorEmail, via: 'same wallet' };
return null;
}
module.exports = { init, receive, adminView, networkSponsor };
module.exports = { init, receive, adminView, networkSponsor, _state: load, _save: save }; // _state/_save: the member erase (erase.js)
+1 -1
View File
@@ -120,4 +120,4 @@ async function release(email, sent) {
// does LinkSpin know this email? (its row was pushed and recorded) - used by the link-farm admin list, never for a cascade
function knows(email) { const st = load(); return Object.prototype.hasOwnProperty.call(st.hashes || {}, String(email || '').toLowerCase()); }
function adminView() { const st = load(); return { on: on(), url: URL_(), tracked: Object.keys(st.hashes).length, pushed: st.pushed, last: st.last, errors: st.errors, pendingTouches: pending.size }; }
module.exports = { init, touch, tick, adminView, on, mute, release, knows };
module.exports = { _state: load, _save: save, _forget: e => { pending.delete(String(e || '').toLowerCase()); muted.delete(String(e || '').toLowerCase()); }, init, touch, tick, adminView, on, mute, release, knows };
+70
View File
@@ -0,0 +1,70 @@
// Member erase (erase.js) against a REAL, disposable MySQL: the SQL half (deletes, the chat message another member keeps,
// the help-desk ticket kept as scrubbed history, other members' mute lists, the residue sweep). Skipped without
// TEST_DATABASE_URL. Synthetic members only; NEVER point it at a live database (it creates and fills tables).
// TEST_DATABASE_URL=mysql://root:pw@127.0.0.1:3306/scratch node qa/erase.mysql.test.cjs
'use strict';
const fs = require('fs'); const os = require('os'); const path = require('path'); const assert = require('assert');
const ROOT = path.join(__dirname, '..');
const URL_ = process.env.TEST_DATABASE_URL;
if (!URL_) { console.log('erase mysql: TEST_DATABASE_URL not set, skipped'); process.exit(0); }
process.env.DATABASE_URL = URL_; delete process.env.DOCSTORE_URL;
const db = require(path.join(ROOT, 'db.js')); const accounts = require(path.join(ROOT, 'accounts.js')); const erase = require(path.join(ROOT, 'erase.js'));
const E = 'gone9@example.test', O = 'other9@example.test';
(async () => {
const DIR = fs.mkdtempSync(path.join(os.tmpdir(), 'erase-sql-'));
{ // db.js alters promo_codes and visit_seen before it creates them (fine on the live database, not on an empty one)
const c0 = await require('mysql2/promise').createConnection(URL_);
await c0.query(`CREATE TABLE IF NOT EXISTS promo_codes (code VARCHAR(24) NOT NULL PRIMARY KEY, credits INT NOT NULL, partner VARCHAR(80) NULL, note VARCHAR(200) NULL,
max_uses INT NOT NULL DEFAULT 0, expires BIGINT NOT NULL DEFAULT 0, active TINYINT NOT NULL DEFAULT 1, created BIGINT NOT NULL)`);
await c0.query('CREATE TABLE IF NOT EXISTS visit_seen (campaign_id INT NOT NULL, email VARCHAR(190) NOT NULL, day CHAR(10) NOT NULL, ts BIGINT NOT NULL, UNIQUE KEY uq_visit (campaign_id, email), INDEX (email, day))');
await c0.end();
}
await db.init({ dataDir: DIR }); accounts.init({ dataDir: DIR });
const q = db.q;
await q('CREATE TABLE IF NOT EXISTS account_signals (email VARCHAR(190) PRIMARY KEY, signup_ip VARCHAR(45) NULL)');
await q('CREATE TABLE IF NOT EXISTS ad_clicks (id VARCHAR(16) PRIMARY KEY, campaign_id INT NOT NULL, owner_email VARCHAR(190) NOT NULL, ts BIGINT NOT NULL)');
await q('CREATE TABLE IF NOT EXISTS event_marks (k VARCHAR(160) PRIMARY KEY, ts BIGINT NOT NULL)');
const now = Date.now();
await q("INSERT INTO accounts (email, sponsor_ref, code, created, username) VALUES (?, 'akuwhite', 'gonec01', ?, 'goneuser9'), (?, '', 'othc01', ?, 'other9')", [E, now, O, now]);
await q('UPDATE accounts SET chat_mutes=? WHERE email=?', [JSON.stringify([E, 'x@example.test']), O]);
await q("INSERT INTO sessions (token, email, member_id, expires) VALUES ('t1', ?, 0, ?)", [E, now + 1e6]);
const c = await q("INSERT INTO campaigns (owner_email, member_id, type, name, target_url, budget, status, created) VALUES (?, 0, 'visits', 'x', 'https://x.test', 60, 'out', ?)", [E, now]);
const cid = c.insertId;
await q("INSERT INTO camp_hours (campaign_id, day, hour, n) VALUES (?, '2026-11-01', 1, 3)", [cid]);
await q("INSERT INTO visit_seen (campaign_id, email, day, ts) VALUES (?, ?, '2026-11-01', 1)", [cid, O]); // another member's visit to THEIR ad
await q("INSERT INTO visit_seen (campaign_id, email, day, ts) VALUES (999, ?, '2026-11-01', 1)", [E]);
await q("INSERT INTO ad_clicks (id, campaign_id, owner_email, ts) VALUES ('c1', ?, ?, 1)", [cid, E]);
await q('INSERT INTO earned_credits (email, balance, updated) VALUES (?, 551, 1), (?, 10, 1)', [E, O]);
await q("INSERT INTO credit_log (email, ts, day, delta, kind, note) VALUES (?, 1, '2026-11-01', 5, 'x', 'n')", [E]);
await q("INSERT INTO account_signals (email, signup_ip) VALUES (?, '1.2.3.4')", [E]);
await q("INSERT INTO adoptions (adoptee, adopter, ts, expires) VALUES (?, ?, 1, 2)", [E, O]);
await q("INSERT INTO event_marks (k, ts) VALUES (?, 1), ('keep:other', 1)", ['tankpay1:' + E + ':17']);
await q("INSERT INTO sponsor_messages (from_member, from_email, to_email, subject, body, sent, kind) VALUES (0, ?, ?, '', 'their words', 1, 'chat'), (0, ?, ?, '', 'my words', 2, 'chat'), (1, 'admin@example.test', ?, 'Your ad', 'n', 3, 'notice')", [E, O, O, E, E]);
const tk = await q("INSERT INTO tickets (ref, platform, email, name, username, subject, category, created, updated) VALUES ('LS-9001', 'linkspin', ?, 'Gone Person', 'goneuser9', 'delete me', 'account', 1, 1)", [E]);
await q("INSERT INTO ticket_messages (ticket_id, author, body, created) VALUES (?, 'member', 'please delete gone9@example.test', 1), (?, 'admin', 'Done.', 2)", [tk.insertId, tk.insertId]);
let fails = 0;
const t = async (name, fn) => { try { await fn(); console.log('ok', name); } catch (e) { fails++; console.log('FAIL', name, '::', e.stack.split('\n').slice(0, 3).join(' | ')); } };
erase.init({ dataDir: DIR, accounts, docstore: null, owners: {}, reload: {}, forget: [] });
await t('dry run counts every table and changes nothing', async () => {
const r = await erase.erase(E);
assert.strictEqual(r.sql.accounts, 1); assert.strictEqual(r.sql.campaigns, 1); assert.strictEqual(r.sql.camp_hours, 1); assert.strictEqual(r.sql.visit_seen, 2);
assert.strictEqual(r.sql.sponsor_messages, 2, 'sent by them + the notice to them'); assert.strictEqual(r.sql['sponsor_messages (kept, scrubbed)'], 1);
assert.strictEqual(r.sql['tickets (kept, scrubbed)'], 1); assert.strictEqual(r.sql['ticket_messages (kept, scrubbed)'], 1);
assert.strictEqual(r.sql['accounts.chat_mutes (others, scrubbed)'], 1);
assert.ok(r.residue.length > 0); assert.strictEqual((await q('SELECT COUNT(*) n FROM accounts WHERE email=?', [E]))[0].n, 1);
});
await t('erase: rows gone, the other member keeps their message (recipient tombstoned), the ticket stays scrubbed, residue empty', async () => {
const r = await erase.erase(E, { dryRun: false });
assert.strictEqual(r.ok, true); assert.deepStrictEqual(r.residue, [], JSON.stringify(r.residue));
const one = async (sql, a) => Number((await q(sql, a))[0].n);
assert.strictEqual(await one('SELECT COUNT(*) n FROM accounts WHERE email=?', [E]), 0); assert.strictEqual(await one('SELECT COUNT(*) n FROM accounts WHERE email=?', [O]), 1);
assert.strictEqual(await one('SELECT COUNT(*) n FROM campaigns WHERE id=?', [cid]), 0); assert.strictEqual(await one('SELECT COUNT(*) n FROM visit_seen WHERE campaign_id=?', [cid]), 0);
assert.strictEqual(await one('SELECT COUNT(*) n FROM earned_credits WHERE email=?', [O]), 1); assert.strictEqual(await one("SELECT COUNT(*) n FROM event_marks WHERE k='keep:other'"), 1);
const msgs = await q('SELECT from_email, to_email, body FROM sponsor_messages ORDER BY sent');
assert.deepStrictEqual(msgs.map(m => [m.from_email, m.body]), [[O, 'my words']]); assert.ok(/^erased-[0-9a-f]{12}@erased\.invalid$/.test(msgs[0].to_email));
const [tkt] = await q("SELECT email, name, username FROM tickets WHERE ref='LS-9001'"); assert.ok(/@erased\.invalid$/.test(tkt.email)); assert.strictEqual(tkt.name, null);
const tm = await q('SELECT author, body FROM ticket_messages ORDER BY id'); assert.ok(/removed/.test(tm[0].body)); assert.strictEqual(tm[1].body, 'Done.');
assert.deepStrictEqual(JSON.parse((await q('SELECT chat_mutes FROM accounts WHERE email=?', [O]))[0].chat_mutes), ['x@example.test']);
});
console.log(fails ? fails + ' FAILED' : 'erase mysql: all passed'); process.exit(fails ? 1 : 0);
})().catch(e => { console.error(e); process.exit(1); });
+105
View File
@@ -0,0 +1,105 @@
// 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, a reload hook, the tombstone, blockers + force, the hub's member.erased event through
// hubsync.receive, and scrub.js being the same file in the sibling LinkSpin / 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 }; } };
const erase = require(path.join(ROOT, 'erase.js'));
let forgot = [];
erase.init({ dataDir: DIR, accounts, 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);
});
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(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, lsinbound: { receive: async () => ({}) }, erase });
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' : 'erase: all ' + n + ' passed');
process.exit(fails ? 1 : 0);
})();
+2
View File
@@ -76,6 +76,7 @@ elif [ "$MODE" = "member" ]; then
node qa/bixpay.test.cjs || status=1
node qa/profile-policy.test.cjs || status=1
node qa/sov-heroes-store.cjs || status=1
node qa/erase.test.cjs || status=1 # member erase (erase.js + scrub.js, 2026-11-15); qa/erase.mysql.test.cjs needs TEST_DATABASE_URL
elif [ "$MODE" = "draft" ]; then
node qa/draft-partner.test.mjs || status=1
elif [ "$MODE" = "theme" ]; then
@@ -105,6 +106,7 @@ elif [ "$MODE" = "gamepass" ]; then
elif [ "$MODE" = "sov-passes" ]; then
node qa/sov-passes-store.cjs || status=1
node qa/sov-heroes-store.cjs || status=1
node qa/erase.test.cjs || status=1 # member erase (erase.js + scrub.js, 2026-11-15); qa/erase.mysql.test.cjs needs TEST_DATABASE_URL
node qa/sov-passes-local.mjs || status=1
elif [ "$MODE" = "nas" ]; then
node qa/nas-served.mjs || status=1
+1 -1
View File
@@ -305,4 +305,4 @@ function resetConversions(kinds) {
return { cleared: n };
}
module.exports = { init, tick, stats, resetConversions, PACKS, compose };
module.exports = { init, tick, stats, resetConversions, PACKS, compose, _state: () => S, _save: save }; // _state/_save: the member erase (erase.js)
+61
View File
@@ -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 };
+18 -2
View File
@@ -56,6 +56,7 @@ const lsconv = require('./lsconv'); // conversion tracking: ad click ids pushed
const lsreport = require('./lsreport'); // conversion linkage: the LinkSpin click on the account, sign-up / wallet / purchase reported, reporting only (2026-11-07)
const lsinbound = require('./lsinbound'); // reverse registry sync: LinkSpin-first members arrive as waiting accounts (2026-10-15)
const draftpartner = require('./draftpartner'); // 5xYourTeam The Draft: signed pool / adopt / release / status on the network tank (2026-11-15, needs DRAFT_PARTNER_SECRET)
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: members from other doors arrive as waiting accounts, ours are reported (2026-11-12, only with HUB_ENABLED)
const SF = require('./sponsorfollow'); // deliberate sponsor changes follow to LinkSpin until chain-bound + one network tank (2026-10-22)
const bixpay = require('./bixpay'); // BixPay Visa card: partner-link field, sponsor-follows resolver, tracked clicks (2026-10-29, gated by site config bixpayLive)
@@ -746,9 +747,17 @@ async function boot() {
notify: async (email, subject, text) => { const html = '<p>' + String(text).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/(https:\/\/[^\s)]+)/g, '<a href="$1" target="_blank" rel="noopener">$1</a>').split('\n\n').join('</p><p>').replace(/\n/g, '<br>') + '</p>'; await messages.deliver(1, ADMIN_EMAIL || 'house@instantadpay.com', [email], subject, html, 'notice'); } } });
// LinkSpin registry sync (2026-10-08): every account change is pushed to LinkSpin within seconds; a 2-minute reconcile catches the rest
lssync.init({ dataDir: DATA_DIR, accounts, follow: followStore, tank: () => tank }); accounts.onChange(email => lssync.touch(email));
lsinbound.init({ dataDir: DATA_DIR, accounts, lssync, follow, store: followStore });
lsinbound.init({ dataDir: DATA_DIR, accounts, lssync, follow, store: followStore, erased: email => erase.isErased(email) });
// member erase (erase.js): the modules that keep a document in memory are scrubbed through their live copy, the rest through docstore
erase.init({ dataDir: DATA_DIR, accounts, docstore,
owners: { 'lsinbound.json': { state: lsinbound._state, save: lsinbound._save }, 'lssync.json': { state: lssync._state, save: lssync._save },
'sponsorfollow.json': { state: followStore._state, save: followStore._save }, 'refill.json': { state: refill._state, save: refill._save },
'tank-ready.json': tank._ready, ...(db.enabled() ? {} : { 'tank.json': tank._json }),
...(hubsync.enabled() ? { 'hubsync.json': { state: hubsync._state, save: hubsync._save } } : {}) },
reload: { 'legacy.json': () => legacy.reload(), 'legacy-grants.json': () => legacy.reload() },
forget: [email => lssync._forget(email), email => { if (hubsync.enabled()) hubsync._forgetHeld(email); }] });
// network hub (hubsync.js): nothing at all happens here unless HUB_ENABLED is on; the LinkSpin sync above runs either way
if (hubsync.enabled()) { hubsync.init({ dataDir: DATA_DIR, accounts, lsinbound, follow: followStore, chain }); accounts.onChange(email => { lssync.touch(email); hubsync.touch(email); }); hubsync.start(); }
if (hubsync.enabled()) { hubsync.init({ dataDir: DATA_DIR, accounts, lsinbound, follow: followStore, chain, erase }); accounts.onChange(email => { lssync.touch(email); hubsync.touch(email); }); hubsync.start(); }
// 5xYourTeam draft picks (draftpartner.js, 2026-11-15): the routes answer 503 until DRAFT_PARTNER_SECRET is set; the pool stays empty
// and nobody can be drafted while the hub is off (DRAFT_ALLOW_NO_HUB=1 is for local tests only, refused in production)
await draftpartner.init({ dataDir: DATA_DIR, accounts, chain, tank, ads, requireHub: !(process.env.DRAFT_ALLOW_NO_HUB === '1' && process.env.NODE_ENV !== 'production'),
@@ -3348,6 +3357,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);
+1 -1
View File
@@ -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;
}
+1 -1
View File
@@ -718,5 +718,5 @@ async function adminView() {
return { waiting: await waiting(), adoptions: recent.map(ad => Object.assign({}, ad, { adopteeName: names[ad.adoptee], adopterName: names[ad.adopter] })), cap: capOpen(), ttlDays: TTL_MS / 86400000, holdHours: READY_MS / 3600000, aligned: alignedRecent(30), payReminders: payView() };
}
module.exports = { partnerEligibility, openOf, closeAdoption, countAll, remoteCount: email => remoteCount(String(email || '').toLowerCase()), lockedWhy, inTank, setSponsorDeliberate: (email, token, by, note) => setSponsor(email, token, by, note), HOLD_MS, NOT_COUNTED,
module.exports = { _ready: { state: () => RS.load(), save: () => RS.save() }, _json: { state: () => J.db, save: () => J.save() } /* member erase (erase.js) */, partnerEligibility, openOf, closeAdoption, countAll, remoteCount: email => remoteCount(String(email || '').toLowerCase()), lockedWhy, inTank, setSponsorDeliberate: (email, token, by, note) => setSponsor(email, token, by, note), HOLD_MS, NOT_COUNTED,
init, view, adopt, holdFor, markReady, readyRec, readyTick, autoAssign, payTick, payView, activateLink, PAY_R1_MS, PAY_R2_MS, alignToNetwork, alignedRecent, setClock, eligibility, READY_MS, release, sweep, rescueSweep, rescueInfo, markContacted, adminView, waiting, adoptable, adoptableOf, openedSince, leftText, inviteAsk, dismissInvite, nameSponsor, GRACE_MS, hasOwnBuy, recordGift, onFollow, summaryMap, summaryFor, historyMap, capOpen, TTL_MS, WARN_DAYS, RESCUE_DAYS, MAX_ADOPTIONS };