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
+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