// Inbound registry rows from LinkSpin (2026-10-15, the reverse of lssync.js). Marty: 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 another sponsor or the company. LinkSpin's iapsync.js now posts its rows here // (POST /api/partner/registry, HMAC LS_SYNC_SECRET over ts + newline + raw body; see server.js). // // Per row {email, username, wallet, sponsorEmail, joinedAt, profile}: // - FIRST-PLATFORM RULE: an email that already has an InstantAdPay account keeps its sponsor. Only EMPTY fields are // filled: username (if free and allowed here), wallet (if no other account or linked position holds it), profile. // A conflict is skipped and logged, never forced. // - A new email becomes a waiting (shell) account, joinedVia 'linkspin', under its LinkSpin sponsor's InstantAdPay // account. A sponsor not on InstantAdPay yet gets a shell too, from rows received in this or an earlier batch, // climbing at most 25 levels (as LinkSpin's carry.js does). A sponsor whose row has not arrived is remembered // (pending) and bound when it does, as long as the shell is still unclaimed and still has no sponsor. // - Nothing here sends mail or notices, touches the chain or runs the sign-up anti-fraud checks (there is no request: // no IP, no device). The checks run when the owner claims the shell at their first sign-in (server.js), and until // then accounts.listAll leaves unclaimed shells out of every sweep that mails, counts or adopts members. // - Loop guard: each email is muted in lssync while its row is applied, then lssync records the result as already // pushed when it equals what LinkSpin sent, so it is not bounced back (see lssync.release). No-op rows change nothing. // - SPONSOR FOLLOW (2026-10-22, sponsorfollow.js): a row that carries a DELIBERATE change made on LinkSpin (sponsorSetBy // adopt / rescue / release / expire / admin) is the one exception to the first-platform rule: it is applied, a clear // back to the tank included, when the member is not bound on InstantAdPay's contract (no memberId, not on chain), the // change is newer than our own deliberate change, and the two sides agreed before it (or we have no sponsor). Bound, // diverged and race cases change nothing here and are logged for Admin > Members > Sponsor check. Applied quietly. // - NETWORK TANK: a row's `tank` (LinkSpin's own adoptions of the person) is kept as remote state, so our waiting list // hides someone adopted on LinkSpin and the two-adoptions limit counts both sites. 'use strict'; const SF = require('./sponsorfollow'); const fs = require('fs'); const path = require('path'); let R = null, st = null, chain_ = Promise.resolve(); const MAX_UP = 25; const FILE = () => path.join(R.dataDir, 'lsinbound.json'); const norm = v => String(v || '').trim().toLowerCase(); const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/; 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.rows = st.rows || {}; st.pending = st.pending || {}; st.log = st.log || []; st.stats = Object.assign({ batches: 0, received: 0, noop: 0, created: 0, filled: 0, sponsored: 0, conflicts: 0, errors: 0 }, st.stats || {}); return st; } function save() { try { const tmp = FILE() + '.tmp'; fs.writeFileSync(tmp, JSON.stringify(load())); fs.renameSync(tmp, FILE()); } catch (e) { console.error('lsinbound save', e.message); } } function note(ev) { const s = load(); s.log.push(Object.assign({ ts: Date.now() }, ev)); if (s.log.length > 300) s.log = s.log.slice(-300); } function init(deps) { R = deps; load(); } // { dataDir, accounts, lssync, follow (sponsorfollow glue), store (sponsorfollow store) } function clean(x) { if (!x || typeof x !== 'object') return null; const email = norm(x.email); if (!EMAIL_RE.test(email) || email.length > 190) return null; const username = norm(x.username).replace(/^@/, '') || null; const wallet = /^0x[0-9a-f]{40}$/.test(norm(x.wallet)) ? norm(x.wallet) : null; let sponsorEmail = norm(x.sponsorEmail); if (!EMAIL_RE.test(sponsorEmail) || sponsorEmail === email) sponsorEmail = null; const profile = x.profile && typeof x.profile === 'object' ? x.profile : null; const out = { email, username, wallet, sponsorEmail, joinedAt: Number(x.joinedAt) || null, profile }; if (SF.isDeliberate(x.sponsorSetBy) && Number(x.sponsorSetAt) > 0) { // a deliberate change on LinkSpin (sponsorfollow.js) out.sponsorSetAt = Number(x.sponsorSetAt); out.sponsorSetBy = String(x.sponsorSetBy); const pv = norm(x.sponsorPrevEmail); out.sponsorPrevEmail = EMAIL_RE.test(pv) ? pv : null; out.sponsorSetOrigin = norm(x.sponsorSetOrigin).replace(/[^a-z]/g, '').slice(0, 20) || 'linkspin'; } if (Object.prototype.hasOwnProperty.call(x, 'tank')) out.tank = SF.cleanTank(x.tank); // null = LinkSpin has no adoption of them now return out; } const tokenOf = a => a.username || a.code; // released / rescued / expired back to the tank on purpose here: an ordinary row must not refill the sponsor (sponsorfollow.js) const emptiedOnPurpose = email => { const pv = R.store && R.store.get(email); return !!(pv && SF.isDeliberate(pv.by) && !pv.sponsorEmail); }; function conflict(sum, email, kind, detail) { sum.conflicts++; note({ type: 'conflict', email, kind, detail: String(detail || '').slice(0, 120) }); } // would binding `email` under `sp` close a loop (sp already sits below email)? async function wouldCycle(email, sp) { let cur = sp; const seen = new Set(); for (let i = 0; cur && i < 60; i++) { if (cur.email === email) return true; if (seen.has(cur.email)) return true; seen.add(cur.email); cur = await R.accounts.sponsorOf(cur.email); } return false; } // the sponsor's InstantAdPay account, building their shell (and theirs, upward) from known rows when needed async function sponsorAccount(spEmail, depth, ctx) { const sp = await R.accounts.byEmail(spEmail); if (sp) return sp; if (depth >= MAX_UP || !load().rows[spEmail] || ctx.done.has(spEmail)) return null; return place(spEmail, depth + 1, ctx); } // fill only what is empty; returns true when something was written async function fill(a, r, sum) { let wrote = false; const A = R.accounts; if (r.username && !a.username) { const other = await A.byUsername(r.username); if (other && other.email !== a.email) conflict(sum, a.email, 'username-taken', r.username); else { const x = await A.setUsername(a.email, r.username); if (x && x.error) conflict(sum, a.email, 'username', r.username + ': ' + x.error); else { sum.filled++; wrote = true; } } } if (r.wallet) { if (!a.address) { const other = await A.byAddress(r.wallet); if (other && other.email !== a.email) conflict(sum, a.email, 'wallet-taken', r.wallet); else { const x = await A.linkWallet(a.email, r.wallet); if (x && x.error) conflict(sum, a.email, 'wallet', r.wallet + ': ' + x.error); else { sum.filled++; wrote = true; } } } else if (norm(a.address) !== r.wallet) conflict(sum, a.email, 'wallet-differs', r.wallet); // InstantAdPay's wallet stands } if (r.profile && A.setProfile) { // same rules as LinkSpin's side: https only, known socials, fills only what is empty 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; if (pf.socials && typeof pf.socials === 'object') { const c = {}; for (const k of ['facebook', 'twitter', 'youtube', 'instagram', 'tiktok', 'telegram', 'linkedin', 'website', 'video']) { const v = String(pf.socials[k] || '').trim(); if (ok(v)) c[k] = v; } if (Object.keys(c).length) soc = JSON.stringify(c); } const upd = [!a.avatarUrl && ok(av) ? av : undefined, !a.bio && bio ? bio : undefined, !a.socials && soc ? soc : undefined]; if (upd.some(v => v !== undefined)) { const x = await A.setProfile(a.email, upd[0], upd[1], upd[2]); if (!(x && x.error)) { sum.filled++; wrote = true; } } } return wrote; } async function place(email, depth, ctx) { const s = load(); const r = s.rows[email]; const A = R.accounts; if (ctx.done.has(email)) return A.byEmail(email); ctx.done.add(email); R.lssync.mute(email); let a = await A.byEmail(email); let wrote = false; if (!r) return a; const inc = SF.incomingOf(r); if (a && inc && R.follow) { // a deliberate sponsor change made on LinkSpin: the follow rule decides (never on a member bound here) const d = await R.follow.applyIncoming(email, r, { sponsorAccount: em => sponsorAccount(em, depth, ctx) }); if (d.apply) { ctx.sum.followed++; wrote = true; delete s.pending[email]; note({ type: 'follow', email, by: r.sponsorSetBy, sponsor: r.sponsorEmail || null, action: d.action }); } else if (d.action !== 'same' && d.action !== 'ordinary') { ctx.sum.followKept++; note({ type: 'follow-kept', email, by: r.sponsorSetBy, action: d.action, detail: String(d.reason || '').slice(0, 120) }); } a = await A.byEmail(email); } else if (!a) { let tok = ''; if (r.sponsorEmail) { const sp = await sponsorAccount(r.sponsorEmail, depth, ctx); if (sp) tok = tokenOf(sp); else { s.pending[email] = r.sponsorEmail; ctx.sum.pendingSponsor++; } } const x = await A.ensure(email, tok, 'linkspin', 'linkspin'); if (!x || x.error) { conflict(ctx.sum, email, 'create', x && x.error); return null; } a = x.account; if (x.created) { ctx.sum.created++; wrote = true; note({ type: 'shell', email, sponsor: tok || null, pending: tok ? null : (r.sponsorEmail || null) }); } // a new waiting account built from a deliberate change carries the same record, so its row does not echo back if (x.created && inc && R.store && (!r.sponsorEmail || tok)) R.store.record(email, { at: inc.at, by: inc.by, sponsorEmail: inc.sponsorEmail, prevEmail: inc.prevEmail, origin: inc.origin || 'linkspin' }); } else if (A.isUnclaimedShell(a) && !a.sponsorRef && r.sponsorEmail && !emptiedOnPurpose(email)) { // our own waiting account, still without a sponsor: this row (or a later one) names one const sp = await sponsorAccount(r.sponsorEmail, depth, ctx); if (sp && sp.email !== email && !(await wouldCycle(email, sp))) { await A.setSponsorRef(email, tokenOf(sp)); delete s.pending[email]; ctx.sum.sponsored++; wrote = true; } else if (!sp) s.pending[email] = r.sponsorEmail; } if (await fill(a, r, ctx.sum)) wrote = true; if (!wrote) ctx.sum.noop++; return A.byEmail(email); } // shells waiting for a sponsor whose row has now arrived (or whose account now exists) async function resolvePending(ctx) { const s = load(); const A = R.accounts; for (const [email, spEmail] of Object.entries(s.pending)) { const a = await A.byEmail(email); if (!a || !A.isUnclaimedShell(a) || a.sponsorRef || emptiedOnPurpose(email)) { delete s.pending[email]; continue; } // claimed, bound or emptied on purpose meanwhile: leave it const sp = await sponsorAccount(spEmail, 0, ctx); if (!sp) continue; if (sp.email === email || await wouldCycle(email, sp)) { delete s.pending[email]; conflict(ctx.sum, email, 'sponsor-cycle', spEmail); continue; } R.lssync.mute(email); ctx.done.add(email); await A.setSponsorRef(email, tokenOf(sp)); delete s.pending[email]; ctx.sum.sponsored++; note({ type: 'sponsored', email, sponsor: tokenOf(sp) }); } } async function handle(rows) { const s = load(); s.stats.batches++; const sum = { rows: 0, noop: 0, created: 0, filled: 0, sponsored: 0, conflicts: 0, pendingSponsor: 0, errors: 0, followed: 0, followKept: 0, tank: 0 }; const ctx = { sum, done: new Set() }; const batch = []; for (const x of rows || []) { const r = clean(x); if (!r) continue; sum.rows++; s.rows[r.email] = r; batch.push(r); } if (R.store) for (const r of batch) if (Object.prototype.hasOwnProperty.call(r, 'tank')) { R.store.setRemote(r.email, r.tank); sum.tank++; } // network tank try { for (const r of batch) { try { await place(r.email, 0, ctx); } catch (e) { sum.errors++; s.stats.lastError = { at: Date.now(), email: r.email, error: String(e.message).slice(0, 160) }; console.error('lsinbound', r.email, e.message); } } try { await resolvePending(ctx); } catch (e) { sum.errors++; s.stats.lastError = { at: Date.now(), error: 'pending: ' + String(e.message).slice(0, 160) }; } } finally { for (const email of ctx.done) await R.lssync.release(email, s.rows[email]); // loop guard: equal results are not echoed } s.stats.received += sum.rows; for (const k of ['noop', 'created', 'filled', 'sponsored', 'conflicts', 'errors', 'followed', 'followKept']) s.stats[k] = (s.stats[k] || 0) + sum[k]; s.last = Object.assign({ at: Date.now() }, sum); save(); return Object.assign({ proto: SF.PROTO }, sum); // proto 2: this side understands sponsor follow + network tank facts } // batches are applied one at a time (two overlapping posts must not both create the same sponsor shell) function receive(rows) { const run = chain_.then(() => handle(rows)); chain_ = run.catch(() => {}); return run; } function adminView() { const s = load(); return Object.assign({}, s.stats, { knownRows: Object.keys(s.rows).length, pendingSponsors: Object.keys(s.pending).length, last: s.last || null, lastError: s.stats.lastError || null, recent: s.log.slice(-25).reverse() }); } module.exports = { init, receive, adminView };