Reverse registry sync: push LinkSpin-first members to InstantAdPay (iapsync.js)
Mirror of InstantAdPay's lssync: touch() on account create / username / wallet (incl. admin set) / sponsor / profile via a new accounts.onChange hook, plus a 2-minute hashed tick, 100 rows per signed POST to IAP_URL/api/partner/registry with the same LS_SYNC_SECRET. Inert while the secret is missing or short. Loop guard (documented in the module header): only rows changed since our last push, and never rows the registry already holds (= what InstantAdPay told us), so the accounts built from the InstantAdPay import are recorded and not sent. A pushed LinkSpin-first email gets a registry row with firstProperty 'linkspin', and registry.upsert no longer overwrites an existing firstProperty, so InstantAdPay's echo cannot relabel it. Also: the inbound InstantAdPay handler binds sponsors in a second pass, so a row that precedes its sponsor's row in the same batch (newest-first order) is no longer left without a sponsor. Admin: GET /api/admin/iapsync, POST .../run. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+11
-7
@@ -391,10 +391,14 @@ async function signup(email, password, sponsorRef) {
|
||||
return impl().signup(e, String(password), String(sponsorRef || ''));
|
||||
}
|
||||
async function login(email, password) { return impl().login(normEmail(email), String(password || '')); }
|
||||
// change listener (2026-10-15): the reverse registry sync (iapsync.js) hears about created / named / wallet-linked /
|
||||
// re-sponsored / profile-edited accounts so InstantAdPay learns about LinkSpin-first members within seconds
|
||||
let changeFn = null; function onChange(fn) { changeFn = fn; } const changed = e => { try { if (changeFn) changeFn(e); } catch (err) {} };
|
||||
const tap = e => r => { if (r && !r.error) changed(e); return r; };
|
||||
async function ensure(email, sponsorRef, via, joinedRef) {
|
||||
const e = normEmail(email);
|
||||
if (!EMAIL_RE.test(e)) return { error: 'That email address does not look right.' };
|
||||
return impl().ensure(e, String(sponsorRef || ''), String(via || '').toLowerCase().slice(0, 20) || null, String(joinedRef || '').toLowerCase().slice(0, 80) || null);
|
||||
return impl().ensure(e, String(sponsorRef || ''), String(via || '').toLowerCase().slice(0, 20) || null, String(joinedRef || '').toLowerCase().slice(0, 80) || null).then(r => { if (r && r.created) changed(e); return r; }); // sign-ins of existing accounts are not changes
|
||||
}
|
||||
async function byEmail(email) { return impl().byEmail(normEmail(email)); }
|
||||
async function byAddress(address) { return impl().byAddress(normAddr(address)); }
|
||||
@@ -407,7 +411,7 @@ async function setUsername(email, username) {
|
||||
const n = normUser(username);
|
||||
if (!USER_RE.test(n)) return { error: 'Usernames are 3 to 20 letters, numbers, or underscores.' };
|
||||
if (/^\d+$/.test(n)) return { error: 'Usernames need at least one letter.' }; // keep /join/<number> unambiguous
|
||||
return impl().setUsername(normEmail(email), n);
|
||||
return impl().setUsername(normEmail(email), n).then(tap(normEmail(email)));
|
||||
}
|
||||
async function setMemberId(email, id) { return impl().setMemberId(normEmail(email), Number(id) || 0); }
|
||||
async function namesForMembers(ids) { return impl().namesForMembers([...new Set(ids)].filter(n => n > 0)); }
|
||||
@@ -439,13 +443,13 @@ async function downline(email, depth = 3) {
|
||||
async function linkWallet(email, address) {
|
||||
const a = normAddr(address);
|
||||
if (!/^0x[0-9a-f]{40}$/.test(a)) return { error: 'Bad wallet address.' };
|
||||
return impl().linkWallet(normEmail(email), a);
|
||||
return impl().linkWallet(normEmail(email), a).then(tap(normEmail(email)));
|
||||
}
|
||||
async function count() { return impl().count(); }
|
||||
// admin: newest-first account list, and re-pointing a member's sponsor (a
|
||||
// username, share code, or numeric member id: the same tokens join links use)
|
||||
async function listAll(limit = 500) { return impl().listAll(limit); }
|
||||
async function setSponsorRef(email, ref) { return impl().setSponsorRef(normEmail(email), String(ref || '').trim().toLowerCase().slice(0, 40)); }
|
||||
async function setSponsorRef(email, ref) { return impl().setSponsorRef(normEmail(email), String(ref || '').trim().toLowerCase().slice(0, 40)).then(tap(normEmail(email))); }
|
||||
|
||||
// resolve a member's DIRECT sponsor account (the token they joined under)
|
||||
async function sponsorOf(email) {
|
||||
@@ -469,13 +473,13 @@ async function getChatSettings(email) {
|
||||
return { available: a ? a.chatAvailable !== false : true, mutes: await impl().getMutes(String(email || '').toLowerCase()) };
|
||||
}
|
||||
|
||||
module.exports = { init, signup, login, ensure, byEmail, byAddress, byCode, byUsername, byMemberId: id => impl().byMemberId(Number(id) || 0), listAll, setSponsorRef,
|
||||
module.exports = { init, signup, login, ensure, onChange, byEmail, byAddress, byCode, byUsername, byMemberId: id => impl().byMemberId(Number(id) || 0), listAll, setSponsorRef,
|
||||
setUsername, setMemberId, namesForMembers, listByReferrer, downline, linkWallet, count,
|
||||
setLineBanner: (e, b, t) => impl().setLineBanner(String(e || '').toLowerCase(), b, t),
|
||||
setWallOffers: (e, j) => impl().setWallOffers(String(e || '').toLowerCase(), j),
|
||||
setProfile: (e, a, bio, socials) => impl().setProfile(String(e || '').toLowerCase(), a, bio, socials),
|
||||
setProfile: (e, a, bio, socials) => impl().setProfile(String(e || '').toLowerCase(), a, bio, socials).then(tap(String(e || '').toLowerCase())),
|
||||
touchSeen: e => impl().touchSeen(String(e || '').toLowerCase()),
|
||||
adminSetAddress: (e, a) => impl().adminSetAddress(String(e || '').toLowerCase(), a ? normAddr(a) : null),
|
||||
adminSetAddress: (e, a) => impl().adminSetAddress(String(e || '').toLowerCase(), a ? normAddr(a) : null).then(tap(String(e || '').toLowerCase())),
|
||||
positionByAddress: a => impl().positionByAddress(normAddr(a)),
|
||||
removeAccount: e => impl().removeAccount(String(e || '').toLowerCase()),
|
||||
setChatAvailable: (e, v) => impl().setChatAvailable(String(e || '').toLowerCase(), v),
|
||||
|
||||
+126
@@ -0,0 +1,126 @@
|
||||
// Reverse registry sync, LinkSpin -> InstantAdPay (Marty 2026-10-15: someone whose FIRST contact is a LinkSpin member's
|
||||
// link is placed right on LinkSpin, but InstantAdPay never heard of them, so a later InstantAdPay join without that link
|
||||
// landed under someone else or the company). Mirror of InstantAdPay's lssync.js, same wire format and signing:
|
||||
// POST <IAP_URL>/api/partner/registry body {rows:[{email, username, wallet, sponsorEmail, joinedAt, profile}]}
|
||||
// headers X-LS-Ts (ms) + X-LS-Sig = hex HMAC-SHA256(ts + "\n" + rawBody) with LS_SYNC_SECRET (ONE secret, both ways)
|
||||
// touch(email) right after an account changes (created, named, wallet linked, sponsor bound, profile): ~3 s debounce
|
||||
// tick() every 2 minutes: every account hashed against the last pushed hash (DATA_DIR/iapsync.json); only
|
||||
// changed rows go, 100 per request. Inert (no network at all) while the secret is missing or short.
|
||||
// InstantAdPay creates waiting (shell) accounts for people new to it with their LinkSpin line, and only FILLS EMPTY fields
|
||||
// on accounts it already has (its own sponsor binding always stands). memberId is not sent: it is LinkSpin's contract id.
|
||||
//
|
||||
// LOOP GUARD (why rows do not ping-pong between the two sites):
|
||||
// 1. A row is a candidate only when its hash differs from the last hash this module pushed for that email.
|
||||
// 2. A candidate is DROPPED (and its hash recorded as if pushed) when the registry already holds the same facts: the
|
||||
// registry is what InstantAdPay told us (lssync rows are upserted into it before any LinkSpin account is written),
|
||||
// so a row equal to it is an InstantAdPay row coming back. Compared: username, wallet, sponsorEmail and profile,
|
||||
// each only when LinkSpin has a value (a field LinkSpin lacks tells InstantAdPay nothing).
|
||||
// => the ~1,100 accounts LinkSpin built from the InstantAdPay import are recorded on the first tick and send 0 rows;
|
||||
// only LinkSpin-first members (no registry row, firstProperty 'linkspin') and fields changed on LinkSpin go.
|
||||
// 3. After a push, a LinkSpin-first email gets its own registry row (firstProperty 'linkspin'); registry.upsert never
|
||||
// overwrites an existing firstProperty, so InstantAdPay's echo cannot relabel it.
|
||||
// 4. InstantAdPay ignores no-op rows, records its own lssync hash for rows whose result equals what we sent (so it does
|
||||
// not echo them), and at most echoes ONCE where its facts differ (kept sponsor, skipped wallet). LinkSpin's inbound
|
||||
// handler only fills empty fields, so that echo changes no LinkSpin account, and rule 1 stops a resend.
|
||||
'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 URL_ = () => String(process.env.IAP_URL || 'https://instantadpay.com').replace(/\/+$/, '');
|
||||
const SECRET = () => String(process.env.LS_SYNC_SECRET || '').trim();
|
||||
const on = () => SECRET().length >= 32;
|
||||
const FILE = () => path.join(R.dataDir, 'iapsync.json');
|
||||
const norm = v => String(v || '').trim().toLowerCase();
|
||||
function load() {
|
||||
if (state) return state;
|
||||
try { state = JSON.parse(fs.readFileSync(FILE(), 'utf8')); } catch (e) { state = null; }
|
||||
if (!state || typeof state !== 'object') state = {};
|
||||
state.hashes = state.hashes || {}; state.pushed = state.pushed || 0; state.known = state.known || 0; state.errors = state.errors || 0; state.last = state.last || null;
|
||||
return state;
|
||||
}
|
||||
function save() { try { fs.writeFileSync(FILE(), JSON.stringify(load())); } catch (e) {} }
|
||||
|
||||
function init(deps) { R = deps; load(); } // { dataDir, accounts, registry, host }
|
||||
const PUBLIC = () => String(process.env.PUBLIC_URL || ('https://' + (R.host || 'linkspin.app'))).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 };
|
||||
}
|
||||
async function rowFor(acct, byRef) {
|
||||
const ref = norm(acct.sponsorRef); 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: norm(acct.email), username: acct.username || null, wallet: acct.address ? norm(acct.address) : null, sponsorEmail, joinedAt: Number(acct.created) || null, profile: profileOf(acct) };
|
||||
}
|
||||
const canon = o => { if (!o || typeof o !== 'object') return JSON.stringify(o == null ? null : o); return '{' + Object.keys(o).sort().filter(k => o[k] != null).map(k => JSON.stringify(k) + ':' + canon(o[k])).join(',') + '}'; };
|
||||
const hashOf = r => crypto.createHash('sha1').update([r.username || '', r.wallet || '', r.sponsorEmail || '', r.joinedAt || '', r.profile ? canon(r.profile) : ''].join('|')).digest('hex').slice(0, 16);
|
||||
// does the registry (= what InstantAdPay told us) already say everything this row says?
|
||||
function sameAsRegistry(r, reg) {
|
||||
if (!reg) return false;
|
||||
if (r.username && norm(r.username) !== norm(reg.username)) return false;
|
||||
if (r.wallet && norm(r.wallet) !== norm(reg.wallet)) return false;
|
||||
if (r.sponsorEmail && norm(r.sponsorEmail) !== norm(reg.sponsorEmail)) return false;
|
||||
if (r.profile && canon(r.profile) !== canon(reg.profile)) return false;
|
||||
return true;
|
||||
}
|
||||
// rows worth sending: changed since our last push and not just InstantAdPay's own facts coming back
|
||||
async function select(rows) {
|
||||
const st = load(); const out = []; let known = 0;
|
||||
for (const r of rows) {
|
||||
const h = hashOf(r); if (st.hashes[r.email] === h) continue;
|
||||
if (sameAsRegistry(r, await R.registry.get(r.email))) { st.hashes[r.email] = h; known++; continue; }
|
||||
out.push(r);
|
||||
}
|
||||
if (known) { st.known += known; save(); }
|
||||
return out;
|
||||
}
|
||||
|
||||
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(30000) });
|
||||
if (!r.ok) throw new Error('instantadpay ' + r.status + ' ' + (await r.text()).slice(0, 120));
|
||||
return r.json();
|
||||
}
|
||||
async function push(rows) {
|
||||
const st = load(); let sent = 0; let result = null;
|
||||
for (let i = 0; i < rows.length; i += 100) {
|
||||
const chunk = rows.slice(i, i + 100); result = await post(chunk); sent += chunk.length;
|
||||
for (const r of chunk) {
|
||||
st.hashes[r.email] = hashOf(r);
|
||||
// a LinkSpin-first member becomes part of the network registry, labelled as such (rule 3 above)
|
||||
if (!(await R.registry.get(r.email))) { try { await R.registry.upsert({ email: r.email, username: r.username, wallet: r.wallet, sponsorEmail: r.sponsorEmail, joinedAt: r.joinedAt, profile: r.profile, firstProperty: 'linkspin' }); } catch (e) {} }
|
||||
}
|
||||
save();
|
||||
}
|
||||
st.pushed += sent; st.last = { at: Date.now(), rows: sent, result }; save(); return sent;
|
||||
}
|
||||
function touch(email) {
|
||||
if (!on() || !email) return; pending.set(norm(email), Date.now());
|
||||
if (!timer) timer = setTimeout(async () => {
|
||||
timer = null; const emails = [...pending.keys()]; pending.clear();
|
||||
try { const rows = []; for (const e of emails) { const a = await R.accounts.byEmail(e); if (a) rows.push(await rowFor(a)); } const go = await select(rows); if (go.length) await push(go); }
|
||||
catch (e) { load().errors++; load().lastError = { at: Date.now(), error: String(e.message).slice(0, 160) }; save(); console.error('iapsync touch', e.message); }
|
||||
}, 3000);
|
||||
}
|
||||
async function tick(force) {
|
||||
if (!on() || ticking) return { skipped: true };
|
||||
ticking = true;
|
||||
try {
|
||||
const all = await R.accounts.listAll(50000); const st = load();
|
||||
const byRef = new Map(); for (const a of all) { if (a.username) byRef.set(norm(a.username), a); if (a.code) byRef.set(norm(a.code), a); }
|
||||
const rows = []; for (const a of all) { if (!a.email) continue; rows.push(await rowFor(a, byRef)); }
|
||||
if (force) for (const r of rows) delete st.hashes[r.email];
|
||||
const go = await select(rows);
|
||||
const sent = go.length ? await push(go) : 0;
|
||||
return { accounts: all.length, changed: go.length, sent };
|
||||
} catch (e) { load().errors++; load().lastError = { at: Date.now(), error: String(e.message).slice(0, 160) }; save(); console.error('iapsync tick', e.message); return { error: e.message }; }
|
||||
finally { ticking = false; }
|
||||
}
|
||||
function adminView() { const st = load(); return { on: on(), url: URL_(), tracked: Object.keys(st.hashes).length, pushed: st.pushed, knownSkipped: st.known, last: st.last, errors: st.errors, lastError: st.lastError || null, pendingTouches: pending.size }; }
|
||||
module.exports = { init, touch, tick, adminView, on };
|
||||
+5
-1
@@ -23,7 +23,11 @@ const J = {
|
||||
if (!this.db) this.load();
|
||||
const e = norm(rec.email); if (!e) return null;
|
||||
const cur = this.db.byEmail[e] || { email: e, created: Date.now() };
|
||||
for (const k of ['username', 'wallet', 'sponsorEmail', 'firstProperty', 'joinedAt', 'profile']) if (rec[k] != null && rec[k] !== '') cur[k] = k === 'wallet' || k === 'sponsorEmail' ? norm(rec[k]) : rec[k];
|
||||
for (const k of ['username', 'wallet', 'sponsorEmail', 'firstProperty', 'joinedAt', 'profile']) {
|
||||
if (rec[k] == null || rec[k] === '') continue;
|
||||
if (k === 'firstProperty' && cur.firstProperty) continue; // first contact is history: an InstantAdPay echo of a LinkSpin-first row must not relabel it (2026-10-15)
|
||||
cur[k] = k === 'wallet' || k === 'sponsorEmail' ? norm(rec[k]) : rec[k];
|
||||
}
|
||||
cur.updated = Date.now(); this.db.byEmail[e] = cur; this.save(); return cur;
|
||||
},
|
||||
async all() { if (!this.db) this.load(); return Object.values(this.db.byEmail); },
|
||||
|
||||
@@ -37,6 +37,7 @@ const audit = require('./audit'); // counter audit: views vs delivery logs,
|
||||
const leaderboard = require('./leaderboard');
|
||||
const toolkit = require('./toolkit');
|
||||
const registry = require('./registry'); // network registry: who is who across properties (LinkSpin, 2026-09-15)
|
||||
const iapsync = require('./iapsync'); // reverse registry sync: LinkSpin-first members reach InstantAdPay (2026-10-15)
|
||||
const carry = require('./carry'); // sponsor carry-over: engine activation, claim window, notices
|
||||
const rotator = require('./rotator');
|
||||
const health = require('./health'); // destination health checks + auto-pause (2026-10-10)
|
||||
@@ -416,6 +417,10 @@ async function boot() {
|
||||
pipeline.init({ dataDir: DATA_DIR, accounts, coach, chain });
|
||||
registry.init({ dataDir: DATA_DIR });
|
||||
carry.init({ dataDir: DATA_DIR, accounts, registry, chain, mailer, messages, siteConfig, adminEmail: ADMIN_EMAIL, host: SITE_HOST });
|
||||
// reverse registry sync (2026-10-15): account changes reach InstantAdPay within seconds; a 2-minute reconcile catches the rest
|
||||
iapsync.init({ dataDir: DATA_DIR, accounts, registry, host: SITE_HOST }); accounts.onChange(email => iapsync.touch(email));
|
||||
setTimeout(() => iapsync.tick().catch(e => console.error('iapsync', e.message)), 2 * 60 * 1000);
|
||||
setInterval(() => iapsync.tick().catch(e => console.error('iapsync', e.message)), 2 * 60 * 1000);
|
||||
const ownHosts = () => [SITE_HOST].concat(String(siteConfig().linkDomains || '').split(',').map(x => x.trim().toLowerCase()).filter(Boolean), pagesHost() ? [pagesHost()] : []);
|
||||
rotator.init({ dataDir: DATA_DIR, geo, ownHosts, sources });
|
||||
// destination health: every 30 min, first pass 2 min after boot; a pause lands in the owner's on-site inbox (same path as the payment notices)
|
||||
@@ -2149,7 +2154,6 @@ const server = http.createServer(async (req, res) => {
|
||||
if (!a) continue;
|
||||
if (r.username && !a.username) { try { await accounts.setUsername(e, r.username); updated++; } catch (err) {} }
|
||||
if (r.wallet && !a.address) { try { await accounts.linkWallet(e, r.wallet); updated++; } catch (err) {} }
|
||||
if (r.sponsorEmail && !a.sponsorRef) { const sp = await accounts.byEmail(r.sponsorEmail); if (sp && (sp.username || sp.code)) { try { await accounts.setSponsorRef(e, sp.username || sp.code); updated++; } catch (err) {} } }
|
||||
if (r.profile && typeof r.profile === 'object') { // the InstantAdPay profile fills only what is still empty here; the member can change it on this side any time (Marty 2026-10-11)
|
||||
const pf = r.profile, ok = v => /^https:[/][/][^ ]+$/i.test(v) && v.length <= 300;
|
||||
const av = String(pf.avatarUrl || '').trim(); const bio = String(pf.bio || '').trim().slice(0, 600); let soc = null;
|
||||
@@ -2158,8 +2162,17 @@ const server = http.createServer(async (req, res) => {
|
||||
if (upd.some(x => x !== undefined)) { try { await accounts.setProfile(e, upd[0], upd[1], upd[2]); updated++; } catch (err) {} }
|
||||
}
|
||||
}
|
||||
// sponsors in a second pass: a batch is newest-first, so a member's row usually comes BEFORE their sponsor's, whose
|
||||
// shell did not exist yet in the first pass (the sponsor line was left empty until the next change, 2026-10-15)
|
||||
for (const r of rows) {
|
||||
const e = String(r.email || '').trim().toLowerCase(); if (!e || !r.sponsorEmail) continue;
|
||||
const a = await accounts.byEmail(e); if (!a || a.sponsorRef) continue;
|
||||
const sp = await accounts.byEmail(r.sponsorEmail); if (sp && sp.email !== a.email && (sp.username || sp.code)) { try { await accounts.setSponsorRef(e, sp.username || sp.code); updated++; } catch (err) {} }
|
||||
}
|
||||
return json(res, 200, { ok: true, rows: rows.length, imported: n, shells, updated, registry: await registry.count() });
|
||||
}
|
||||
if (p === '/api/admin/iapsync' && req.method === 'GET') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); return json(res, 200, iapsync.adminView()); }
|
||||
if (p === '/api/admin/iapsync/run' && req.method === 'POST') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); const b = await readBody(req); return json(res, 200, await iapsync.tick(!!(b && b.force))); }
|
||||
if (p === '/api/admin/registry/import' && req.method === 'POST') {
|
||||
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
||||
const b = await readBody(req); const n = await registry.importRows(b.rows || [], b.property || 'instantadpay');
|
||||
|
||||
Reference in New Issue
Block a user