Files
instantadpay/erase.js
T
martbost ccfaacc935 Holding tank batches (Marty 2026-11-15), master switch tankBatches OFF
Active members with their own paid package ($20+ InstantAdPay, $25+ LinkSpin via the
refuel record) receive tank people in batches: Paid 10, Fueled 20 (counted refuel streak
or a $50+ package), Twin Engine 25 (both engines this cycle or the top package, the live
catalog's highest, $500 today), +5 per further consecutive refuel month up to 50. Every
2 days per sponsor, topped up to their size, dealt by rotation highest tier first from
tank.adoptable() (grace, rule 3, LinkSpin adoptions respected), never self, own upline,
adopted twice, flagged, spam, mistyped, erased or unsubscribed. Same tank.adopt path
(sponsor change, chat, "X is now your sponsor" email, switch-on reminders); one notice
per batch to the sponsor. Uncontacted after 7 days -> back to the tank as 'unreached'
(not counted). Tank feed: payments-topic card + live toast, sponsor/count/level only.
Member panel "How to get fed leads" (tankfeed.js). Every number is a site setting.

5xYourTeam draft gets its own cap (fiveXDraftCap, default 10): open draft picks only;
plain adoptions, the 24-hour safety net and batches each count their own people.
Admin: GET /api/admin/tank/batches/preview (read-only) + /api/admin/tank/batches.
Chatbot: coming soon only. qa/tank-batch.test.mjs (60 checks) in run.sh member.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 14:59:20 -06:00

200 lines
15 KiB
JavaScript

// 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('tank_batch_picks', 'adoptee=? OR sponsor=?', [E, E]); // holding tank batches (2026-11-15)
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 words = ex.filter(x => x.length >= 5); // a long username inside text too
const where = '`' + c + '` LIKE ?' + ex.map(() => ' OR `' + c + '` = ?').join('') + words.map(() => ' OR `' + c + '` REGEXP ?').join('');
const wordRe = w => '(^|[^a-z0-9_])' + w.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '([^a-z0-9_]|$)'; // the whole word, not a longer name
try { const [x] = await db.q('SELECT COUNT(*) n FROM `' + t + '` WHERE ' + where, [like(E)].concat(ex, words.map(wordRe))); 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);
// names: usernames of an account already erased (a second pass after the code learned something new), e.g. ['oldname']
const names = (Array.isArray(o.names) ? o.names : []).map(norm).filter(x => /^[a-z0-9_.-]{5,30}$/.test(x));
const exact = (acct ? [acct.username, acct.code].filter(Boolean).map(norm) : []).concat(names);
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;
// their username inside messages that stay (another member's chat to them, a notice to their sponsor about them): the name
// goes, the message stays. Whole words only, usernames of 5+ characters (a short one could be an ordinary word).
let rd = 0;
for (const u of exact.filter(x => x.length >= 5 && ((acct && norm(acct.username) === x) || names.includes(x)))) {
const re = new RegExp('(^|[^a-z0-9_])@?' + u.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '(?![a-z0-9_])', 'gi');
for (const m of await db.q('SELECT id, subject, body FROM sponsor_messages WHERE subject LIKE ? OR body LIKE ?', [like(u), like(u)])) {
const sub = String(m.subject || '').replace(re, '$1[erased member]'), body = m.body == null ? null : String(m.body).replace(re, '$1[erased member]');
if (sub === m.subject && body === m.body) continue;
rd++; if (!o.dryRun) await db.q('UPDATE sponsor_messages SET subject=?, body=? WHERE id=?', [sub, body, m.id]);
}
}
if (rd) res.sql['sponsor_messages (others, name removed)'] = rd;
} 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; } };