d86f2fbcf8
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>
155 lines
10 KiB
JavaScript
155 lines
10 KiB
JavaScript
// 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.
|
|
'use strict';
|
|
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 }
|
|
|
|
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;
|
|
return { email, username, wallet, sponsorEmail, joinedAt: Number(x.joinedAt) || null, profile };
|
|
}
|
|
const tokenOf = a => a.username || a.code;
|
|
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;
|
|
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) }); }
|
|
} else if (A.isUnclaimedShell(a) && !a.sponsorRef && r.sponsorEmail) {
|
|
// 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) { delete s.pending[email]; continue; } // claimed or bound 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 };
|
|
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); }
|
|
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']) s.stats[k] += sum[k];
|
|
s.last = Object.assign({ at: Date.now() }, sum); save();
|
|
return sum;
|
|
}
|
|
// 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 };
|