Files
instantadpay/lssync.js
T
martbost d86f2fbcf8 Reverse registry sync: LinkSpin-first members arrive on InstantAdPay as waiting accounts
POST /api/partner/registry (same HMAC LS_SYNC_SECRET scheme LinkSpin accepts from us, 10-minute window) feeds
lsinbound.js: an email already on InstantAdPay keeps its sponsor and only gets empty fields filled (username if free
and allowed, wallet if no other account or linked position holds it, profile); a new email becomes a waiting shell
(joinedVia linkspin) under its LinkSpin sponsor, building the sponsor's shell upward from known rows (25 levels),
remembering a sponsor whose row has not arrived and binding it later, refusing sponsor loops. No mail, notices or chain.

Unclaimed shells are left out of accounts.listAll by default (tank, coach nudges, Friday/Wednesday broadcasts, member
update audiences, leaderboard, 1,000-member milestone count); the admin members table and lssync ask for them. The first
sign-in claims the shell: the sign-up anti-fraud checks run then, a sponsorless shell takes the link used, lastSeen set.

Loop guard: lssync mutes an email while its LinkSpin row is applied, then records the result as already pushed when it
equals what LinkSpin sent; touch() now skips rows whose hash is unchanged. Status: GET /api/admin/lsinbound (also under
/api/admin/lssync as inbound).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 10:44:53 -05:00

93 lines
7.2 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.
'use strict';
const crypto = require('crypto');
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) {
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; }
return { email: acct.email, username: acct.username || null, wallet: acct.address || null, sponsorEmail, joinedAt: Number(acct.created) || null, memberId: acct.memberId || null, profile: profileOf(acct) };
}
// 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('|')).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); await post(chunk); sent += chunk.length;
for (const r of chunk) st.hashes[r.email] = hashOf(r);
}
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 rows = []; for (const a of all) { if (!a.email || muted.has(a.email)) continue; const r = await rowFor(a, byRef); 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();
if (n(r.username) === n(sent.username) && n(r.wallet) === n(sent.wallet) && n(r.sponsorEmail) === n(sent.sponsorEmail)) { 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 };