// Sponsor follow + one network holding tank (Marty, 2026-10-22). The SAME file ships in InstantAdPay and LinkSpin. // // Background: the registry sync between the two sites (IAP lssync.js / lsinbound.js, LinkSpin iapsync.js + its // /api/partner/registry) never overwrites a sponsor (first-platform rule). That is right for ordinary bindings (join link, // cookie, last touch, carry-over), but a DELIBERATE change on one side (tank adoption, dormant-lead rescue, release to the // tank, an adoption falling back at the end of its window, an admin edit) stayed on that side only. // // The follow rule (decide() below, unit-tested in qa/sponsorfollow.test.cjs / tests/sponsorfollow.test.cjs): // - A deliberate change is recorded here with when, how and the sponsor before it (record()). Sync rows carry it as // sponsorSetAt / sponsorSetBy / sponsorPrevEmail / sponsorSetOrigin, and only while it still describes the current // sponsor (rowFields()), so a later ordinary change never travels as if it were deliberate. // - The receiver applies the incoming sponsor (a clear back to the tank included) only when ALL hold: // the change is deliberate; the member is NOT bound (or binding) on the receiver's contract; it is newer than the // receiver's own deliberate change; and the receiver either agreed with the sender before the change // (receiver's sponsor == sponsorPrevEmail), has no sponsor, or has an older deliberate change of its own. // Otherwise nothing moves: 'bound' and 'diverged' are logged for the admin mismatch report (conservative: when the // two sides already disagreed before the change, a person decides). // - Race: both sides changed independently within WINDOW_MS -> the EARLIER change wins on both sides and the case is // logged as a conflict (the later one is undone on the side that made it, and reported, never silently kept). // - Ping-pong: the receiver stores the incoming record unchanged (same at/by/origin), so its own row carries the same // facts back and the sender sees 'same' (plus the hash / registry loop guards of the sync modules). // - Accounts with no record (everything before this shipped) are "old, non-deliberate": nothing is rewritten on deploy. // // Network tank: each platform keeps its own adoptions; rows carry a small tank summary (own adoption count and the open // adoption, if any) which the other side stores as remote state: its waiting list hides a member with an open adoption // elsewhere, and the two-adoptions-per-person lifetime limit counts both platforms. The adoption itself reaches the other // side as an ordinary deliberate follow (by 'adopt'), applied quietly (no chat, mail or feed post there). 'use strict'; const fs = require('fs'); const path = require('path'); const crypto = require('crypto'); const DELIBERATE = ['adopt', 'rescue', 'release', 'expire', 'admin', 'invited']; // invited = the member named who invited them (tank.js nameSponsor, 2026-11-07) const WINDOW_MS = 15 * 60 * 1000; const PROTO = 2; // wire version: 2 = rows may carry sponsorSet* + tank, peers answer { proto: 2 } const n = v => String(v == null ? '' : v).trim().toLowerCase(); const isDeliberate = by => DELIBERATE.includes(String(by || '')); // ---- the rule (pure) ---- // local { sponsorEmail, prov: {at, by, sponsorEmail, prevEmail, origin} | null, bound: bool } // incoming { sponsorEmail, at, by, prevEmail, origin } // -> { action, apply: bool, conflict: bool, reason } // actions: ordinary (caller keeps today's fill-empty rule) | same | bound | stale | conflict-keep | conflict-apply | // diverged | apply function decide(local, incoming, opts) { const win = (opts && opts.windowMs) || WINDOW_MS; const inc = incoming || {}; const loc = local || {}; if (!isDeliberate(inc.by) || !(Number(inc.at) > 0)) return { action: 'ordinary', apply: false, reason: 'not a deliberate change' }; if (n(inc.sponsorEmail) === n(loc.sponsorEmail)) return { action: 'same', apply: false, reason: 'already the same sponsor' }; if (loc.bound) return { action: 'bound', apply: false, conflict: true, reason: 'member is bound on this contract; the sponsor here cannot move' }; const lp = loc.prov && isDeliberate(loc.prov.by) && Number(loc.prov.at) > 0 && n(loc.prov.sponsorEmail) === n(loc.sponsorEmail) ? loc.prov : null; const at = Number(inc.at); if (lp) { const lat = Number(lp.at); // sequential, not a race: the earlier record came from the same platform, or the sender built on our current sponsor const sequential = (lp.origin && inc.origin && n(lp.origin) === n(inc.origin)) || n(inc.prevEmail) === n(loc.sponsorEmail); if (at === lat && !sequential) return { action: 'conflict-keep', apply: false, conflict: true, reason: 'two different changes with the same time; nothing moved' }; if (!sequential && Math.abs(at - lat) <= win) { if (at < lat) return { action: 'conflict-apply', apply: true, conflict: true, reason: 'both sides changed within ' + Math.round(win / 60000) + ' min; the earlier change (incoming) wins on both' }; return { action: 'conflict-keep', apply: false, conflict: true, reason: 'both sides changed within ' + Math.round(win / 60000) + ' min; the earlier change (this side) wins on both' }; } if (at <= lat) return { action: 'stale', apply: false, reason: 'this side has a newer deliberate change' }; return { action: 'apply', apply: true, reason: 'newer deliberate change' }; } if (!n(loc.sponsorEmail)) return { action: 'apply', apply: true, reason: 'no sponsor here' }; if (n(inc.prevEmail) === n(loc.sponsorEmail)) return { action: 'apply', apply: true, reason: 'both sides had the same sponsor before the change' }; return { action: 'diverged', apply: false, conflict: true, reason: 'the two sides already had different sponsors before this change; left for the admin' }; } // the follow fields a sync row carries for an account (only while the record still describes the current sponsor) function rowFields(prov, currentSponsorEmail) { if (!prov || !isDeliberate(prov.by) || !(Number(prov.at) > 0)) return null; if (n(prov.sponsorEmail) !== n(currentSponsorEmail)) return null; return { sponsorSetAt: Number(prov.at), sponsorSetBy: prov.by, sponsorPrevEmail: prov.prevEmail ? n(prov.prevEmail) : null, sponsorSetOrigin: prov.origin || null }; } // what a received row says about a deliberate change (null when it says nothing) function incomingOf(row) { if (!row || !isDeliberate(row.sponsorSetBy) || !(Number(row.sponsorSetAt) > 0)) return null; return { sponsorEmail: row.sponsorEmail ? n(row.sponsorEmail) : null, at: Number(row.sponsorSetAt), by: String(row.sponsorSetBy), prevEmail: row.sponsorPrevEmail ? n(row.sponsorPrevEmail) : null, origin: row.sponsorSetOrigin ? n(row.sponsorSetOrigin) : null }; } // hash suffix: empty when the row has none of the new fields, so every existing row hashes exactly as before (no resend) function hashExtra(r) { const parts = []; if (r && r.sponsorSetBy) parts.push('f:' + [r.sponsorSetAt, r.sponsorSetBy, r.sponsorPrevEmail || '', r.sponsorSetOrigin || ''].join(',')); if (r && r.tank) parts.push('t:' + [r.tank.count || 0, r.tank.open ? 1 : 0, r.tank.adopterEmail || '', r.tank.ts || '', r.tank.expires || ''].join(',')); return parts.length ? '|' + parts.join('|') : ''; } function cleanTank(t) { if (!t || typeof t !== 'object') return null; const count = Math.max(0, Math.min(99, Number(t.count) || 0)); const open = !!t.open; if (!count && !open) return null; return { count, open, adopterEmail: open && t.adopterEmail ? n(t.adopterEmail) : null, ts: open ? Number(t.ts) || null : null, expires: open ? Number(t.expires) || null : null }; } // ---- store: records, remote tank state, pending follows, the conflict log ---- function create(opts) { const platform = n(opts.platform); const dataDir = opts.dataDir; const FILE = () => path.join(dataDir, 'sponsorfollow.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.prov = st.prov || {}; st.remote = st.remote || {}; st.pending = st.pending || {}; st.log = st.log || []; st.peer = st.peer || {}; return st; } function save() { try { const f = FILE(); fs.writeFileSync(f + '.tmp', JSON.stringify(load())); fs.renameSync(f + '.tmp', f); } catch (e) { console.error('sponsorfollow save', e.message); } } const api = { platform, PROTO, WINDOW_MS, DELIBERATE, decide, rowFields, incomingOf, hashExtra, cleanTank, isDeliberate, get(email) { return load().prov[n(email)] || null; }, // a deliberate change made on this platform (origin = this platform), or one received and applied (origin kept) record(email, rec) { const e = n(email); if (!e || !isDeliberate(rec.by)) return null; const r = { at: Number(rec.at) || Date.now(), by: rec.by, sponsorEmail: rec.sponsorEmail ? n(rec.sponsorEmail) : null, prevEmail: rec.prevEmail ? n(rec.prevEmail) : null, origin: n(rec.origin || platform) }; if (rec.note) r.note = String(rec.note).slice(0, 160); load().prov[e] = r; save(); return r; }, remote(email) { return load().remote[n(email)] || null; }, setRemote(email, tank) { const e = n(email); const t = cleanTank(tank); const s = load(); const cur = s.remote[e] ? JSON.stringify(s.remote[e]) : null; if (!t) { if (cur) { delete s.remote[e]; save(); } return; } if (cur !== JSON.stringify(t)) { s.remote[e] = t; save(); } }, remoteOpen(email, now) { const t = api.remote(email); return !!(t && t.open && (!t.expires || t.expires > (now || Date.now()))); }, remoteCount(email) { const t = api.remote(email); return t ? Number(t.count) || 0 : 0; }, pending() { return Object.assign({}, load().pending); }, pendingFor(email) { return load().pending[n(email)] || null; }, setPending(email, incoming, why) { const s = load(); s.pending[n(email)] = Object.assign({}, incoming, { why: String(why || '').slice(0, 120), since: (s.pending[n(email)] && s.pending[n(email)].since) || Date.now() }); save(); }, clearPending(email) { const s = load(); if (s.pending[n(email)]) { delete s.pending[n(email)]; save(); } }, note(ev) { const s = load(); s.log.push(Object.assign({ ts: Date.now() }, ev)); if (s.log.length > 500) s.log = s.log.slice(-500); save(); }, recent(k) { return load().log.slice(-(k || 100)).reverse(); }, conflictsFor(email) { const e = n(email); return load().log.filter(x => x.email === e && x.conflict); }, 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; } }; return api; } // ---- signed partner calls (the same HMAC the registry sync uses: hex HMAC-SHA256(ts + "\n" + raw), LS_SYNC_SECRET) ---- const SECRET = () => String(process.env.LS_SYNC_SECRET || '').trim(); function verify(raw, headers) { const secret = SECRET(); if (secret.length < 32) return { status: 503, error: 'sync not configured' }; const ts = String(headers['x-ls-ts'] || ''), sig = String(headers['x-ls-sig'] || ''); if (!/^\d{13}$/.test(ts) || Math.abs(Date.now() - Number(ts)) > 10 * 60000) return { status: 401, error: 'stale' }; const want = crypto.createHmac('sha256', secret).update(ts + '\n' + raw).digest('hex'); if (want.length !== sig.length || !crypto.timingSafeEqual(Buffer.from(want), Buffer.from(sig))) return { status: 401, error: 'bad signature' }; return null; } async function peerPost(baseUrl, pth, body, timeoutMs) { const secret = SECRET(); if (secret.length < 32) throw new Error('sync not configured (LS_SYNC_SECRET)'); const raw = JSON.stringify(body || {}); const ts = String(Date.now()); const sig = crypto.createHmac('sha256', secret).update(ts + '\n' + raw).digest('hex'); const r = await fetch(String(baseUrl).replace(/\/+$/, '') + pth, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-LS-Ts': ts, 'X-LS-Sig': sig }, body: raw, signal: AbortSignal.timeout(timeoutMs || 30000) }); const txt = await r.text(); let j = null; try { j = JSON.parse(txt); } catch (e) {} if (!r.ok) throw new Error((j && j.error) || ('peer ' + r.status + ' ' + txt.slice(0, 120))); return j || {}; } // ---- the admin mismatch report (pure): both sides' facts -> rows that differ ---- // facts row: { email, username, sponsorEmail, sponsorRef, prov, bound, boundWhy, memberId, created, joinedVia, adoptions, activation } function mismatches(iapRows, lsRows) { const L = new Map((lsRows || []).map(r => [n(r.email), r])); const out = []; let shared = 0, same = 0; for (const a of iapRows || []) { const b = L.get(n(a.email)); if (!b) continue; shared++; const sa = n(a.sponsorEmail), sb = n(b.sponsorEmail); if (sa === sb) { same++; continue; } out.push({ email: n(a.email), username: a.username || b.username || null, kind: sa && sb ? 'differ' : sa ? 'iap-only' : 'ls-only', iap: a, ls: b }); } out.sort((x, y) => (x.kind === 'differ' ? 0 : 1) - (y.kind === 'differ' ? 0 : 1) || x.email.localeCompare(y.email)); return { shared, same, rows: out }; } // ---- the platform glue: one implementation, per-platform hooks ---- // deps: { store, accounts, tank: () => tankModule|null, peer: 'linkspin'|'instantadpay', // isBound: async acct => { bound, why, retry }, // retry = cannot tell right now (chain read failed, activation in flight) // sponsorAccount: async email => acct|null, // the sponsor's account here (may build a waiting shell) // wouldCycle: async (email, spAcct) => bool, // optional // activationOf: acct => { id, sponsorId, block, tx } | null, // afterResolve: async email => {} } // optional, after a pending follow is settled function glue(deps) { const S = deps.store, A = deps.accounts; const tokenOf = a => a.username || a.code || (a.memberId ? String(a.memberId) : ''); async function accountOfRef(ref) { const t = n(ref); if (!t) return null; return (await A.byUsername(t).catch(() => null)) || (await A.byCode(t).catch(() => null)) || (/^\d+$/.test(t) && A.byMemberId ? await A.byMemberId(Number(t)).catch(() => null) : null) || null; } async function emailOfRef(ref) { const a = await accountOfRef(ref); return a ? n(a.email) : null; } // a deliberate change made on THIS platform: record first (so the ~3 s sync touch already carries it), then write async function setDeliberate(email, token, by, note) { const e = n(email); const a = await A.byEmail(e); if (!a) return { error: 'No such account.' }; const prev = await emailOfRef(a.sponsorRef); const tok = n(token); const next = tok ? await emailOfRef(tok) : null; if (isDeliberate(by)) S.record(e, { by, sponsorEmail: next, prevEmail: prev, note }); return A.setSponsorRef(e, tok); } async function closeLocalAdoptions(email, inc, d) { const T = deps.tank && deps.tank(); if (!T || !T.onFollow) return; try { await T.onFollow(email, inc, d); } catch (e) { console.error('tank onFollow', e.message); } } // a row from the other platform that carries a deliberate change async function applyIncoming(email, row, opts) { const inc = incomingOf(row); if (!inc) return { action: 'ordinary' }; const e = n(email); const a = await A.byEmail(e); if (!a) return { action: 'no-account' }; const cur = await emailOfRef(a.sponsorRef); if (n(cur) === n(inc.sponsorEmail)) { S.clearPending(e); return { action: 'same', apply: false }; } // nothing to move (no chain read needed) const b = (await deps.isBound(a).catch(err => ({ retry: true, why: 'bound check failed: ' + err.message }))) || {}; if (b.retry && !b.bound) { S.setPending(e, inc, b.why); S.note({ email: e, action: 'pending', by: inc.by, from: cur, to: inc.sponsorEmail, reason: b.why }); return { action: 'pending', reason: b.why }; } const d = decide({ sponsorEmail: cur, prov: S.get(e), bound: !!b.bound }, inc, opts); if (!d.apply) { S.clearPending(e); if (d.action !== 'same') S.note({ email: e, action: d.action, by: inc.by, at: inc.at, origin: inc.origin, from: cur, to: inc.sponsorEmail, prev: inc.prevEmail, reason: d.reason + (b.bound && b.why ? ' (' + b.why + ')' : ''), conflict: !!d.conflict }); return d; } let tok = ''; if (inc.sponsorEmail) { const sp = await ((opts && opts.sponsorAccount) || deps.sponsorAccount)(inc.sponsorEmail); if (!sp) { S.setPending(e, inc, 'the new sponsor has no account here yet'); S.note({ email: e, action: 'pending', by: inc.by, from: cur, to: inc.sponsorEmail, reason: 'sponsor account missing' }); return { action: 'pending', reason: 'sponsor account missing' }; } if (n(sp.email) === e || (deps.wouldCycle && await deps.wouldCycle(e, sp))) { S.clearPending(e); S.note({ email: e, action: 'refused', by: inc.by, from: cur, to: inc.sponsorEmail, reason: 'would sponsor themselves or close a loop', conflict: true }); return { action: 'refused', reason: 'loop' }; } tok = tokenOf(sp); if (!tok) { S.setPending(e, inc, 'the new sponsor has no username or code here yet'); return { action: 'pending', reason: 'sponsor token missing' }; } } S.record(e, { at: inc.at, by: inc.by, sponsorEmail: inc.sponsorEmail, prevEmail: inc.prevEmail, origin: inc.origin || deps.peer }); const r = await A.setSponsorRef(e, tok); if (r && r.error) { S.note({ email: e, action: 'error', reason: r.error, conflict: true }); return { action: 'error', reason: r.error }; } await closeLocalAdoptions(e, inc, d); S.clearPending(e); S.note({ email: e, action: d.action, by: inc.by, at: inc.at, origin: inc.origin, from: cur, to: inc.sponsorEmail, reason: d.reason, conflict: !!d.conflict }); return d; } // follows that could not be settled yet (chain unreadable, activation in flight, sponsor not here yet): retried on the sync tick async function retryPending(maxAgeMs) { const out = { tried: 0, settled: 0, dropped: 0 }; const now = Date.now(); for (const [e, p] of Object.entries(S.pending())) { if (now - (p.since || now) > (maxAgeMs || 7 * 86400000)) { S.clearPending(e); S.note({ email: e, action: 'gave-up', by: p.by, to: p.sponsorEmail, reason: 'pending for 7 days: ' + (p.why || ''), conflict: true }); out.dropped++; continue; } out.tried++; const r = await applyIncoming(e, { sponsorEmail: p.sponsorEmail, sponsorSetAt: p.at, sponsorSetBy: p.by, sponsorPrevEmail: p.prevEmail, sponsorSetOrigin: p.origin }).catch(err => ({ action: 'error', reason: err.message })); if (r.action !== 'pending') { out.settled++; if (deps.afterResolve) { try { await deps.afterResolve(e); } catch (err) {} } } } return out; } // the admin's pick in the mismatch report: apply `sponsorEmail` (null = back to the tank) here unless bound here async function adminApply(email, sponsorEmail, opts) { const e = n(email); const a = await A.byEmail(e); if (!a) return { error: 'No account for ' + e + ' here.' }; const b = (await deps.isBound(a).catch(err => ({ retry: true, why: err.message }))) || {}; if (b.bound) return { error: 'Refused: ' + e + ' is already bound on this platform\'s contract (' + (b.why || 'on chain') + '). Its sponsor here cannot change.' }; if (b.retry) return { error: 'Could not confirm that ' + e + ' is not on the contract yet (' + (b.why || 'chain read failed') + '). Nothing changed. Try again in a minute.' }; let tok = ''; if (sponsorEmail) { const sp = await deps.sponsorAccount(n(sponsorEmail)); if (!sp) return { error: 'The sponsor ' + n(sponsorEmail) + ' has no account here. Nothing changed.' }; if (n(sp.email) === e || (deps.wouldCycle && await deps.wouldCycle(e, sp))) return { error: 'That would make the member their own upline. Nothing changed.' }; tok = tokenOf(sp); if (!tok) return { error: 'The sponsor has no username or code here yet. Nothing changed.' }; } const prev = await emailOfRef(a.sponsorRef); S.record(e, { by: 'admin', sponsorEmail: sponsorEmail ? n(sponsorEmail) : null, prevEmail: prev, origin: (opts && opts.origin) || S.platform, note: (opts && opts.note) || 'mismatch report' }); const r = await A.setSponsorRef(e, tok); if (r && r.error) return r; await closeLocalAdoptions(e, { by: 'admin', sponsorEmail: sponsorEmail ? n(sponsorEmail) : null }, { action: 'admin' }); S.clearPending(e); S.note({ email: e, action: 'admin-fix', by: 'admin', from: prev, to: sponsorEmail ? n(sponsorEmail) : null, reason: (opts && opts.note) || 'mismatch report' }); return { ok: true, email: e, from: prev, to: sponsorEmail ? n(sponsorEmail) : null }; } // this platform's facts for the mismatch report (no chain reads: memberId + the indexed activation event) async function facts(onlyEmails) { const all = await A.listAll(50000, { shells: true }); const only = onlyEmails && onlyEmails.length ? new Set(onlyEmails.map(n)) : null; const byTok = new Map(); for (const a of all) { if (a.username) byTok.set(n(a.username), a); if (a.code) byTok.set(n(a.code), a); if (a.memberId) byTok.set(String(a.memberId), a); } const T = deps.tank && deps.tank(); const hist = T && T.historyMap ? await T.historyMap().catch(() => new Map()) : new Map(); const logBy = new Map(); for (const x of S.recent(500)) { if (!x.email) continue; if (!logBy.has(x.email)) logBy.set(x.email, []); if (logBy.get(x.email).length < 6) logBy.get(x.email).push(x); } return all.filter(a => a.email && (!only || only.has(n(a.email)))).map(a => { const e = n(a.email); const sp = a.sponsorRef ? byTok.get(n(a.sponsorRef)) : null; const act = deps.activationOf ? deps.activationOf(a) : null; return { email: e, username: a.username || null, sponsorRef: a.sponsorRef || '', sponsorEmail: sp && n(sp.email) !== e ? n(sp.email) : null, sponsorName: sp ? (sp.username ? '@' + sp.username : n(sp.email)) : null, deadLink: !!(a.sponsorRef && !sp), prov: S.get(e), memberId: Number(a.memberId) || 0, bound: Number(a.memberId) > 0 || !!act, activation: act || null, created: Number(a.created) || null, joinedVia: a.joinedVia || null, joinedRef: a.joinedRef || null, lastSeen: Number(a.lastSeen) || 0, wallet: !!a.address, adoptions: hist.get(e) || [], remoteTank: S.remote(e), pending: S.pendingFor(e), log: logBy.get(e) || [] }; }); } return { setDeliberate, applyIncoming, retryPending, adminApply, facts, emailOfRef, accountOfRef, tokenOf }; } module.exports = { create, glue, decide, rowFields, incomingOf, hashExtra, cleanTank, isDeliberate, verify, peerPost, mismatches, DELIBERATE, WINDOW_MS, PROTO };