diff --git a/accounts.js b/accounts.js index 06e429c..88d429a 100644 --- a/accounts.js +++ b/accounts.js @@ -469,7 +469,11 @@ async function linkWallet(email, address) { 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); } +// A waiting account made from a LinkSpin registry row (lsinbound.js, 2026-10-15) that its owner has not signed in to yet. +// It exists so the LinkSpin line is already in place; it is not a member yet, so the sweeps that mail, count or adopt +// members (listAll by default) leave it out. It becomes an ordinary account the first time its owner signs in (lastSeen). +const isUnclaimedShell = a => !!a && a.joinedVia === 'linkspin' && !a.lastSeen && !a.memberId; +async function listAll(limit = 500, opts) { const all = await impl().listAll(limit); return opts && opts.shells ? all : all.filter(a => !isUnclaimedShell(a)); } async function identities() { return impl().identities(); } async function setSponsorRef(email, ref) { const r = await impl().setSponsorRef(normEmail(email), String(ref || '').trim().toLowerCase().slice(0, 40)); if (r && !r.error) changed(normEmail(email)); return r; } @@ -495,7 +499,7 @@ async function getChatSettings(email) { return { available: a ? a.chatAvailable !== false : true, mutes: await impl().getMutes(String(email || '').toLowerCase()) }; } -module.exports = { init, signup, login, ensure, onChange, byEmail, byAddress, byCode, byUsername, byMemberId: id => impl().byMemberId(Number(id) || 0), listAll, identities, setSponsorRef, +module.exports = { init, signup, login, ensure, onChange, isUnclaimedShell, byEmail, byAddress, byCode, byUsername, byMemberId: id => impl().byMemberId(Number(id) || 0), listAll, identities, setSponsorRef, setUsername, reservedUsername, 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), diff --git a/lsinbound.js b/lsinbound.js new file mode 100644 index 0000000..2c02ce4 --- /dev/null +++ b/lsinbound.js @@ -0,0 +1,154 @@ +// 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 }; diff --git a/lssync.js b/lssync.js index affcb9a..b722681 100644 --- a/lssync.js +++ b/lssync.js @@ -11,6 +11,7 @@ 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; @@ -55,20 +56,37 @@ async function push(rows) { // 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 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)); } if (rows.length) await push(rows); } catch (e) { load().errors++; save(); console.error('lssync touch', e.message); } }, 3000); + 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); const st = load(); + 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) continue; const r = await rowFor(a, byRef); if (force || st.hashes[r.email] !== hashOf(r)) rows.push(r); } + 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 }; +module.exports = { init, touch, tick, adminView, on, mute, release }; diff --git a/server.js b/server.js index a0e3d2c..3ead4c1 100644 --- a/server.js +++ b/server.js @@ -42,6 +42,7 @@ const videosweep = require('./videosweep'); const sbcheck = require('./sbcheck'); const reach = require('./reach'); const lssync = require('./lssync'); +const lsinbound = require('./lsinbound'); // reverse registry sync: LinkSpin-first members arrive as waiting accounts (2026-10-15) const gamestats = require('./gamestats'); const marks = require('./marks'); const feedgroup = require('./feedgroup'); // one proof-feed message per purchase: buyer, package, then the tier payouts // one-time claims shared across running instances (deploy overlap) // Google Safe Browsing screen on advertiser destinations @@ -552,6 +553,7 @@ async function boot() { tank.init({ dataDir: DATA_DIR, chain, accounts, messages, mailer, ads, site: 'https://instantadpay.com' }); // LinkSpin registry sync (2026-10-08): every account change is pushed to LinkSpin within seconds; a 2-minute reconcile catches the rest lssync.init({ dataDir: DATA_DIR, accounts }); accounts.onChange(email => lssync.touch(email)); + lsinbound.init({ dataDir: DATA_DIR, accounts, lssync }); setTimeout(() => lssync.tick().catch(e => console.error('lssync', e.message)), 2 * 60 * 1000); setInterval(() => lssync.tick().catch(e => console.error('lssync', e.message)), 2 * 60 * 1000); walletnudge.init({ dataDir: DATA_DIR, accounts, mailer, optedIn: updates.optedIn, site: 'https://instantadpay.com', @@ -725,6 +727,16 @@ function parseCookies(req) { } return out; } +// First sign-in to a waiting account made from a LinkSpin row (lsinbound.js): it becomes the person's own ordinary account. +// Its LinkSpin sponsor stands; one that arrived with no sponsor at all takes the link they signed in through, exactly as a +// brand-new account would (first InstantAdPay touch). Marked seen at once, so the sweeps count it from here on. +async function claimShell(email, shell, ref) { + try { + if (!shell.sponsorRef && ref) { const tok = String(ref).toLowerCase(); let sp = await accounts.byCode(tok); if (!sp) sp = await accounts.byUsername(tok); if (sp && sp.email !== email) await accounts.setSponsorRef(email, ref); } + await accounts.touchSeen(email); + console.log('linkspin waiting account claimed', email.replace(/^(.).*(@.*)$/, '$1***$2'), shell.sponsorRef ? 'sponsor ' + shell.sponsorRef : (ref ? 'sponsor from link ' + ref : 'no sponsor')); + } catch (e) { console.error('claimShell', e.message); } +} function isAdmin(req) { const h = req.headers.authorization || ''; if (h === 'Bearer ' + ADMIN_PASSWORD) return true; @@ -2063,8 +2075,9 @@ const server = http.createServer(async (req, res) => { if (fraud.isSuspended(e)) return json(res, 403, { error: 'This account is suspended. Contact support.' }); let fraudFlags = []; const existing = await accounts.byEmail(e); - if (!existing) { // anti-fraud checks apply to NEW accounts only (Marty, 2026-09-16: one account per person) - let spAcct = null; if (ref) { try { spAcct = await accounts.byCode(String(ref).toLowerCase()); if (!spAcct) spAcct = await accounts.byUsername(String(ref).toLowerCase()); } catch (err) {} } + const claim = accounts.isUnclaimedShell(existing); // a waiting LinkSpin account: this sign-in is its owner's real sign-up + if (!existing || claim) { // anti-fraud checks apply to NEW accounts only (Marty, 2026-09-16: one account per person) + let spAcct = null; if (claim) { try { spAcct = await accounts.sponsorOf(e); } catch (err) {} } else if (ref) { try { spAcct = await accounts.byCode(String(ref).toLowerCase()); if (!spAcct) spAcct = await accounts.byUsername(String(ref).toLowerCase()); } catch (err) {} } const fc = await fraud.checkSignup(req, spAcct, siteConfig(), e); fraudFlags = fc.flags; // an approved exception is worth a log line: it is the difference between "the guard @@ -2075,7 +2088,8 @@ const server = http.createServer(async (req, res) => { const r = await accounts.ensure(e, ref, via, joinedRef); // first touch wins; existing accounts unchanged if (r.error) return json(res, 400, r); if (r.created) pendingSponsor.del(e); - if (r.created) { fraud.recordSignup(e, req, fraudFlags).catch(() => {}); if (fraudFlags.length) fraudAlert(e, { flags: fraudFlags, ip: fraud.ipOf(req) }, null, false); } + if (claim) await claimShell(e, existing, ref); + if (r.created || claim) { fraud.recordSignup(e, req, fraudFlags).catch(() => {}); if (fraudFlags.length) fraudAlert(e, { flags: fraudFlags, ip: fraud.ipOf(req) }, null, false); } else fraud.recordSeen(e, req).catch(() => {}); // the lead is in the door: queue the getting-started sequence (opt-in box is pre-checked on both forms) if (r.created && (b.followups || b.newsletter)) drip.enqueue(e, ref, via).catch(() => {}); @@ -2155,8 +2169,9 @@ const server = http.createServer(async (req, res) => { const joinedRef = (pend && pend.joinedRef) || (g.host() + (srcTag ? '/' + srcTag : '')); // e.g. driprunner.app/adsterra let fraudFlags = []; const existing = await accounts.byEmail(e); - if (!existing) { // one account per person, exactly as on the dashboard - let spAcct = null; if (ref) { try { spAcct = await accounts.byCode(ref); if (!spAcct) spAcct = await accounts.byUsername(ref); } catch (err) {} } + const claim = accounts.isUnclaimedShell(existing); // a waiting LinkSpin account: this sign-in is its owner's real sign-up + if (!existing || claim) { // one account per person, exactly as on the dashboard + let spAcct = null; if (claim) { try { spAcct = await accounts.sponsorOf(e); } catch (err) {} } else if (ref) { try { spAcct = await accounts.byCode(ref); if (!spAcct) spAcct = await accounts.byUsername(ref); } catch (err) {} } const fc = await fraud.checkSignup(req, spAcct, siteConfig(), e); fraudFlags = fc.flags; if (fc.allowlisted) console.log('signup allowed by exception list', e.replace(/^(.).*(@.*)$/, '$1***$2'), 'via', fc.allowedBy); @@ -2164,6 +2179,7 @@ const server = http.createServer(async (req, res) => { } const r = await accounts.ensure(e, ref, via, joinedRef); // first touch wins; existing accounts unchanged if (r.error) return json(res, 400, r, cors); + if (claim) { await claimShell(e, existing, ref); fraud.recordSignup(e, req, fraudFlags).catch(() => {}); if (fraudFlags.length) fraudAlert(e, { flags: fraudFlags, ip: fraud.ipOf(req) }, null, false); } if (r.created) { pendingSponsor.del(e); fraud.recordSignup(e, req, fraudFlags).catch(() => {}); if (fraudFlags.length) fraudAlert(e, { flags: fraudFlags, ip: fraud.ipOf(req) }, null, false); @@ -2806,7 +2822,22 @@ const server = http.createServer(async (req, res) => { if (p === '/api/admin/walletnudge' && req.method === 'GET') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); return json(res, 200, walletnudge.adminView()); } if (p === '/api/admin/reach' && req.method === 'GET') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); return json(res, 200, reach.adminView()); } if (p === '/api/admin/reach/run' && req.method === 'POST') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); const b = await readBody(req); return json(res, 200, await reach.run({ dry: !!(b && b.dry) })); } - if (p === '/api/admin/lssync' && req.method === 'GET') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); return json(res, 200, lssync.adminView()); } + if (p === '/api/admin/lssync' && req.method === 'GET') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); return json(res, 200, Object.assign(lssync.adminView(), { inbound: lsinbound.adminView() })); } + if (p === '/api/admin/lsinbound' && req.method === 'GET') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); return json(res, 200, lsinbound.adminView()); } + // -- reverse registry sync from LinkSpin (2026-10-15): the same signed rows LinkSpin accepts from us (HMAC LS_SYNC_SECRET + // over ts + newline + raw body, 10-minute window). New people become waiting accounts with their LinkSpin line; existing + // accounts keep their sponsor and only get empty fields filled. No mail, no notices, no chain (lsinbound.js). + if (p === '/api/partner/registry' && req.method === 'POST') { + const secret = String(process.env.LS_SYNC_SECRET || '').trim(); if (secret.length < 32) return json(res, 503, { error: 'sync not configured' }); + const raw = await new Promise((ok, no) => { let d = ''; req.on('data', c => { d += c; if (d.length > 2e6) { req.destroy(); no(new Error('too big')); } }); req.on('end', () => ok(d)); req.on('error', no); }); + const ts = String(req.headers['x-ls-ts'] || ''), sig = String(req.headers['x-ls-sig'] || ''); + if (!/^\d{13}$/.test(ts) || Math.abs(Date.now() - Number(ts)) > 10 * 60000) return json(res, 401, { error: 'stale' }); + const want = crypto.createHmac('sha256', secret).update(ts + '\n' + raw).digest('hex'); + if (want.length !== sig.length || !crypto.timingSafeEqual(Buffer.from(want), Buffer.from(sig))) return json(res, 401, { error: 'bad signature' }); + let b; try { b = JSON.parse(raw || '{}'); } catch (e) { return json(res, 400, { error: 'bad json' }); } + const rows = Array.isArray(b.rows) ? b.rows.slice(0, 500) : []; + return json(res, 200, Object.assign({ ok: true }, await lsinbound.receive(rows))); + } if (p === '/api/admin/lssync/run' && req.method === 'POST') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); const b = await readBody(req); return json(res, 200, await lssync.tick(!!(b && b.force))); } if (p === '/api/admin/walletnudge/run' && req.method === 'POST') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); return json(res, 200, await walletnudge.tick()); } if (p === '/api/admin/tank' && req.method === 'GET') { @@ -4317,7 +4348,7 @@ const server = http.createServer(async (req, res) => { } if (p === '/api/admin/members' && req.method === 'GET') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - const members = await accounts.listAll(5000); // was 500: older members (igor147, joined 09-12) vanished from the table and its search once the site passed 500 accounts (Marty, 2026-09-29) + const members = await accounts.listAll(5000, { shells: true }); // waiting LinkSpin accounts included (2026-10-15); was 500: older members (igor147, joined 09-12) vanished from the table and its search once the site passed 500 accounts (Marty, 2026-09-29) // resolve each sponsor token (username, share code or member #) to the sponsor's name // the lookup covers EVERY account, not the page's slice: built from `members` it called every // sponsor who joined before the newest 500 a dead link (144 of them, Marty 2026-09-23)