Files
instantadpay/lssync.js
T
martbost 84d566e784 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>
2026-11-15 12:29:31 -06:00

124 lines
10 KiB
JavaScript

// LinkSpin registry sync (Marty 2026-10-08: "members in InstantAdPay synchronized with those waiting inside LinkSpin").
// Two paths, same signed POST to LinkSpin /api/partner/registry (HMAC-SHA256 of ts + newline + raw body, LS_SYNC_SECRET):
// touch(email) right after an account changes (created, named, wallet linked, sponsor bound): that row goes within ~3 s
// tick() every 2 minutes: every account is hashed (username, wallet, sponsor, joined) against the last pushed
// hash in DATA_DIR/lssync.json and only changed rows go, 100 per request. Catches anything touch() missed.
// LinkSpin upserts the rows and creates shell accounts with their sponsor line, so a new InstantAdPay member is already
// "waiting" on LinkSpin before they ever sign in there. Nothing here moves money; the registry is identity + line only.
//
// Sponsor follow (2026-10-22, sponsorfollow.js): a row also carries sponsorSetAt / sponsorSetBy / sponsorPrevEmail /
// sponsorSetOrigin while the account's sponsor is the result of a deliberate change (tank adoption, rescue, release,
// window expiry, admin edit), and `tank` (this site's own adoptions of the person: count + the open one, or null).
// Rows without those facts hash exactly as before, so nothing is resent on deploy. Until LinkSpin answers proto 2 the
// hash of a row carrying the new facts is not recorded, so it is sent again once LinkSpin runs the new code.
'use strict';
const crypto = require('crypto');
const SF = require('./sponsorfollow');
const prohibited = require('./prohibited'); // 2026-10-30: a profile that fails the policy never leaves this site
const fs = require('fs');
const path = require('path');
let R = null, state = null, pending = new Map(), timer = null, ticking = false;
const muted = new Set(); // emails lsinbound.js is writing right now: their rows came FROM LinkSpin, hold them until it decides
const URL_ = () => String(process.env.LS_URL || 'https://linkspin.app').replace(/\/+$/, '');
const SECRET = () => String(process.env.LS_SYNC_SECRET || '').trim();
const on = () => SECRET().length >= 32;
const FILE = () => path.join(R.dataDir, 'lssync.json');
function load() { if (state) return state; try { state = JSON.parse(fs.readFileSync(FILE(), 'utf8')); } catch (e) { state = { hashes: {}, pushed: 0, last: null, errors: 0 }; } return state; }
function save() { try { fs.writeFileSync(FILE(), JSON.stringify(load())); } catch (e) {} }
function init(deps) { R = deps; load(); }
async function rowFor(acct, byRef, tankMap) {
const ref = String(acct.sponsorRef || '').toLowerCase(); let sponsorEmail = null;
if (ref) { const sp = byRef ? byRef.get(ref) : (await R.accounts.byUsername(ref) || await R.accounts.byCode(ref)); if (sp && sp.email !== acct.email) sponsorEmail = sp.email; }
const row = { email: acct.email, username: acct.username || null, wallet: acct.address || null, sponsorEmail, joinedAt: Number(acct.created) || null, memberId: acct.memberId || null, profile: profileOf(acct) };
if (acct.joinedVia === 'btc4hits') row.origin = 'btc4hits'; // BTC4Hits import (2026-11-11): LinkSpin words its holding-tank mail for them
if (R.follow) Object.assign(row, SF.rowFields(R.follow.get(acct.email), sponsorEmail) || {});
const T = R.tank && R.tank();
if (T) { try { row.tank = (tankMap ? tankMap.get(String(acct.email).toLowerCase()) : await T.summaryFor(acct.email)) || null; } catch (e) {} }
return row;
}
const carriesNew = r => !!(r.sponsorSetBy || r.tank);
// the member's profile travels too (Marty 2026-10-11: no re-typing on LinkSpin; they can change it there later). Avatar as an
// absolute https URL so the other property can show it; socials as the parsed {platform: url} object.
const PUBLIC = () => String(process.env.PUBLIC_URL || 'https://instantadpay.com').replace(/\/+$/, '');
function profileOf(a) {
if (a.profileQuarantined) return null; // quarantined (link planted on a brand-new free account): stays here, unseen, until Marty decides
const cp = prohibited.cleanProfile({ avatarUrl: a.avatarUrl, bio: a.bio, socials: a.socials }, 'InstantAdPay'); // policy applied on the way out too
const socials = cp.socials;
const av = String(a.avatarUrl || '').trim();
const avatarUrl = !av ? null : /^https:\/\//i.test(av) ? av : av.startsWith('/') ? PUBLIC() + av : null;
const bio = cp.bio;
// the BixPay partner link travels too (2026-10-29): LinkSpin shows it read-only ("Edit on InstantAdPay") and resolves the
// same way; only set when there is one, so rows without it keep the hash they had
const bixPartnerLink = String(a.bixPartnerLink || '').trim() || null;
if (!avatarUrl && !bio && !bixPartnerLink && !(socials && Object.keys(socials).length)) return null;
const out = { avatarUrl, bio, socials: socials && Object.keys(socials).length ? socials : null };
if (bixPartnerLink) out.bixPartnerLink = bixPartnerLink;
return out;
}
const hashOf = r => crypto.createHash('sha1').update([r.username || '', r.wallet || '', r.sponsorEmail || '', r.joinedAt || '', r.memberId || '', r.profile ? JSON.stringify(r.profile) : ''].join('|') + SF.hashExtra(r)).digest('hex').slice(0, 16);
async function post(rows) {
const raw = JSON.stringify({ rows }); const ts = String(Date.now());
const sig = crypto.createHmac('sha256', SECRET()).update(ts + '\n' + raw).digest('hex');
const r = await fetch(URL_() + '/api/partner/registry', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-LS-Ts': ts, 'X-LS-Sig': sig }, body: raw, signal: AbortSignal.timeout(20000) });
if (!r.ok) throw new Error('linkspin ' + r.status + ' ' + (await r.text()).slice(0, 120));
return r.json();
}
async function push(rows) {
const st = load(); let sent = 0;
for (let i = 0; i < rows.length; i += 100) {
const chunk = rows.slice(i, i + 100); const res = await post(chunk); sent += chunk.length;
const peerNew = Number(res && res.proto) >= SF.PROTO; if (R.follow) R.follow.setPeer(peerNew ? SF.PROTO : 1);
for (const r of chunk) { if (peerNew || !carriesNew(r)) st.hashes[r.email] = hashOf(r); } // an old LinkSpin ignored the new facts: send again later
}
st.pushed += sent; st.last = { at: Date.now(), rows: sent }; save(); return sent;
}
// QUIET (Marty 2026-11-14, "join one = join all"): a waiting account the network hub made here (joinedVia 'hub', never signed
// in) is never pushed to LinkSpin. The hub tells LinkSpin itself, quietly; pushed from here, LinkSpin's registry route would
// link the wallet and its engine would switch payouts on and email them. Once they sign in here they sync like anyone.
const hubShell = a => !!a && a.joinedVia === 'hub' && R.accounts.isUnclaimedShell && R.accounts.isUnclaimedShell(a);
// an account just changed: send its row shortly (debounced so a join + username + wallet in a row go as one)
function touch(email) {
if (!on() || !email) return; pending.set(String(email).toLowerCase(), Date.now());
if (!timer) timer = setTimeout(async () => { timer = null; const st = load(); const emails = [...pending.keys()].filter(e => !muted.has(e)); for (const e of emails) pending.delete(e); try { const rows = []; for (const e of emails) { const a = await R.accounts.byEmail(e); if (a && !hubShell(a)) { const r = await rowFor(a); if (st.hashes[r.email] !== hashOf(r)) rows.push(r); } } if (rows.length) await push(rows); } catch (e) { load().errors++; save(); console.error('lssync touch', e.message); } }, 3000);
}
// the reconcile pass: only rows whose hash changed since the last push
async function tick(force) {
if (!on() || ticking) return { skipped: true };
ticking = true;
try {
const all = await R.accounts.listAll(50000, { shells: true }); const st = load();
const byRef = new Map(); for (const a of all) { if (a.username) byRef.set(String(a.username).toLowerCase(), a); if (a.code) byRef.set(String(a.code).toLowerCase(), a); }
const T = R.tank && R.tank(); let tankMap = null; if (T) { try { tankMap = await T.summaryMap(); } catch (e) { tankMap = null; } }
const rows = []; for (const a of all) { if (!a.email || muted.has(a.email) || hubShell(a)) continue; const r = await rowFor(a, byRef, tankMap || (T ? new Map() : null)); if (force || st.hashes[r.email] !== hashOf(r)) rows.push(r); }
const sent = rows.length ? await push(rows) : 0;
return { accounts: all.length, changed: rows.length, sent };
} catch (e) { load().errors++; save(); console.error('lssync tick', e.message); return { error: e.message }; }
finally { ticking = false; }
}
// Reverse-sync loop guard (2026-10-15, see lsinbound.js): while a LinkSpin row is being applied its email is muted; afterwards,
// if the account now says exactly what LinkSpin sent (username, wallet, sponsor), its hash is recorded as already pushed, so
// it is never sent back. When InstantAdPay's facts differ (its sponsor binding stood, a wallet was skipped) the row goes
// back once; LinkSpin only fills empty fields, so that changes nothing there and its own hash stops a resend.
function mute(email) { muted.add(String(email || '').toLowerCase()); }
async function release(email, sent) {
const e = String(email || '').toLowerCase(); muted.delete(e); let same = false;
try {
const a = await R.accounts.byEmail(e);
if (a && sent) {
const r = await rowFor(a); const n = v => String(v || '').toLowerCase();
// a deliberate change from LinkSpin counts as the same only when we now carry that same record (applied, not refused)
const sameFollow = !sent.sponsorSetBy || (Number(r.sponsorSetAt) === Number(sent.sponsorSetAt) && String(r.sponsorSetBy) === String(sent.sponsorSetBy));
if (n(r.username) === n(sent.username) && n(r.wallet) === n(sent.wallet) && n(r.sponsorEmail) === n(sent.sponsorEmail) && sameFollow) { load().hashes[e] = hashOf(r); save(); same = true; }
}
} catch (err) {}
if (pending.has(e) && !timer) { pending.delete(e); touch(e); } // a touch that queued while muted goes now (the hash check drops it when same)
return same;
}
// 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 = { _state: load, _save: save, _forget: e => { pending.delete(String(e || '').toLowerCase()); muted.delete(String(e || '').toLowerCase()); }, init, touch, tick, adminView, on, mute, release, knows };