Files
instantadpay/lssync.js
martbost 4e51470cf5 Sponsor follow + one network holding tank + Sponsor check (Marty, 2026-10-22, approved 1-3)
Deliberate sponsor changes (tank adoption, dormant-lead rescue, release, adoption window ending, admin edit) are now
recorded (sponsorfollow.json: when, how, the sponsor before, origin) and travel on the LinkSpin sync rows as
sponsorSetAt/By/PrevEmail/Origin. A deliberate change from LinkSpin is applied here (a clear back to the tank included)
only when the member is not bound on the InstantAdPay contract (memberId or wallet on chain), it is newer than our own
deliberate change, and both sides agreed before it (or we have no sponsor). Bound, diverged and race cases change
nothing and are logged. Race within 15 min: the earlier change wins on both. Ordinary bindings keep the first-platform
rule. Accounts with no record behave as before; rows without the new facts hash exactly as before (no resend on deploy).

Network tank: rows carry this site's own adoptions of a person; the waiting list hides someone adopted on LinkSpin, the
two-adoptions limit counts both sites, the 3-day hold applies to a LinkSpin adoption too, follows close local open
adoptions quietly (no chat, mail or feed post).

Admin > Members > Sponsor check: shared members whose sponsor differs or is one-sided, each side's when/how, chain
binding, and Use InstantAdPay's / Use LinkSpin's sponsor (applied on the other site, refused when bound there).
Partner endpoints /api/partner/sponsor-facts and /api/partner/sponsor-apply (same HMAC as the registry rows).

Tests: qa/sponsorfollow.test.cjs 27/27, qa/sponsorfollow-e2e.mjs 20/20 (local IAP + local LinkSpin, throwaway data),
QA member walk 0 bugs. No sponsor was changed on production.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 09:05:07 -05:00

109 lines
8.8 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 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 (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) {
let socials = null; try { socials = a.socials ? (typeof a.socials === 'string' ? JSON.parse(a.socials) : a.socials) : null; } catch (e) { socials = null; }
const av = String(a.avatarUrl || '').trim();
const avatarUrl = !av ? null : /^https:\/\//i.test(av) ? av : av.startsWith('/') ? PUBLIC() + av : null;
const bio = String(a.bio || '').trim().slice(0, 600) || null;
if (!avatarUrl && !bio && !(socials && Object.keys(socials).length)) return null;
return { avatarUrl, bio, socials: socials && Object.keys(socials).length ? socials : null };
}
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;
}
// 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) { 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)) 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;
}
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 };