diff --git a/carry.js b/carry.js index 78782b4..fb13e70 100644 --- a/carry.js +++ b/carry.js @@ -9,9 +9,8 @@ // position on this contract, the engine activates them on their behalf (activateFor, // engine-signed, gas paid by the engine), walking up until it reaches someone already // on-chain. The sponsor is told, and their first payout email follows on its own. -// - Sponsor with no wallet at all: the claim window. The member can do everything except -// buy; the sponsor has CLAIM_DAYS to link a wallet. After that the seat walks up to the -// nearest ancestor with a wallet and both sides are told. +// - Sponsor with no wallet at all: NO hold (the claim window was removed 2026-10-15). At the +// buy, the seat walks up to the nearest ancestor with a wallet and both sides are told. let ethers = null; try { ethers = require('ethers'); } catch (e) {} const fs = require('fs'); const path = require('path'); @@ -82,36 +81,38 @@ async function onJoin(acct, usedRef) { } // ---- before activation / purchase: make sure the sponsor exists on this contract ---- -// returns { sponsorId, hold, claim } — hold is set when the buy must wait (claim window) -async function resolveForChain(acct, spd) { +// A purchase is NEVER held (Marty, 2026-10-15: "We should never, ever hold up a purchase"; the 3-day claim +// window is gone). Returns { sponsorId, routed } or null when the normal resolver already has the answer. +// - Sponsor with a wallet: the engine activates them (gas on us) and they are paid, wallet off or not. +// - Sponsor with no wallet, unknown, or an activation that failed: the sale goes to the nearest ancestor +// with a wallet (activated on the spot), else sponsorId 0 = the caller's company fallback. +// Only `commit` (the buyer is about to sign) moves the member and sends the notices; a display check just answers. +async function resolveForChain(acct, spd, opts) { if (!acct || !acct.sponsorRef) return null; if (spd.id) return null; // already on-chain: nothing to do - if (spd.reason !== 'notActivated') return null; // unknown token or rpc: the normal guard handles it + if (spd.reason === 'rpc' || spd.reason === 'none') return null; // a chain hiccup is retried by the client; nothing is charged + const commit = !!(opts && opts.commit); let sp = await X.accounts.byCode(acct.sponsorRef); if (!sp) sp = await X.accounts.byUsername(acct.sponsorRef); - if (!sp) return null; - if (sp.address) { - const id = await ensureOnChain(sp, 0); - return id ? { sponsorId: id } : null; + if (sp && sp.address) { + let id = await ensureOnChain(sp, 0); + if (!id) id = await ensureOnChain(sp, 0); // one retry before passing a wallet holder over for our own failure + if (id) return { sponsorId: id }; + logEvent({ type: 'activateGaveUp', member: acct.email, sponsor: sp.email }); } - // no wallet: the claim window - const st = state(); const k = norm(acct.email); - let c = st.claims[k]; - if (!c) { - c = { member: k, sponsor: sp.email, opened: Date.now(), deadline: Date.now() + claimDays() * DAY, notified: true }; st.claims[k] = c; setState(st); - await tell(sp.email, label(acct) + ' is ready to buy on LinkSpin. Link a wallet to be their sponsor', - label(acct) + ' joined LinkSpin under you and wants to buy a package. The contract can only pay a wallet, and there is none on your LinkSpin account yet.\n\nLink one within ' + claimDays() + ' days (Wallet tab, one free signature) and their purchases pay you. If the window passes, the seat goes to the next person above you who has a wallet.\n\nhttps://' + (X.host || 'linkspin.co') + '/my#wallet'); + // walk up to the first ancestor with a wallet the engine can place on the contract + let up = sp ? await nearestWithWallet(sp.email) : null; let id = 0; let hops = 0; + while (up && hops < 25) { id = await ensureOnChain(up, 0); if (id) break; up = await nearestWithWallet(up.email); hops++; } + if (!id) up = null; + const routed = { from: sp ? label(sp) : null, to: up ? label(up) : 'the company', toEmail: up ? up.email : null }; + if (commit) { + if (up) await X.accounts.setSponsorRef(acct.email, up.username || up.code); + logEvent({ type: 'walkedUp', member: acct.email, from: sp ? sp.email : acct.sponsorRef, to: up ? up.email : 'company' }); + if (sp) await tell(sp.email, 'You missed ' + label(acct) + ' on LinkSpin: no wallet linked', + label(acct) + ' joined LinkSpin under you and bought a package, but there is no wallet on your LinkSpin account, so the contract could not pay you. The sale went to ' + routed.to + ', and ' + label(acct) + ' is now in their line.\n\nLink a wallet now (Wallet tab, one free signature) and every purchase from the people who join under you from here on pays you.\n\nhttps://' + (X.host || 'linkspin.co') + '/my#wallet'); + if (up) await tell(up.email, label(acct) + ' was placed under you on LinkSpin', + label(acct) + ' joined through ' + (sp ? label(sp) : 'a link') + ', who has no wallet on LinkSpin, so the network placed them under you. Their purchases pay you from now on.'); } - if (Date.now() < c.deadline) return { sponsorId: 0, hold: true, claim: { sponsor: label(sp), deadline: c.deadline } }; - // window passed: walk up to the nearest ancestor with a wallet, activate them, tell both sides - const up = await nearestWithWallet(sp.email); - if (!up) return { sponsorId: 0, hold: true, claim: { sponsor: label(sp), deadline: c.deadline, nobody: true } }; - const id = await ensureOnChain(up, 0); - if (!id) return null; - await X.accounts.setSponsorRef(acct.email, up.username || up.code); - delete st.claims[k]; setState(st); logEvent({ type: 'walkedUp', member: acct.email, from: sp.email, to: up.email }); - await tell(sp.email, 'The seat for ' + label(acct) + ' passed to ' + label(up), 'No wallet was linked within ' + claimDays() + ' days, so ' + label(acct) + ' was placed under ' + label(up) + ', the nearest person above you with a wallet. Link a wallet now and everyone who joins under you from here on is yours.'); - await tell(up.email, label(acct) + ' was placed under you on LinkSpin', label(acct) + ' joined through ' + label(sp) + ', who has no wallet on LinkSpin, so the network placed them under you. Their purchases pay you from now on.'); - return { sponsorId: id, movedTo: up.email }; + return { sponsorId: id, routed }; } async function nearestWithWallet(email) { diff --git a/public/assets/credits-screen.js b/public/assets/credits-screen.js index af9f07c..feb8a9c 100644 --- a/public/assets/credits-screen.js +++ b/public/assets/credits-screen.js @@ -1,148 +1,148 @@ -// LinkSpin Credits (2026-10-07): the buy screen inside the Control Room. Package picker from the catalog, the POL -// quote, connect/link a wallet, the on-chain purchase (ported from the classic /my#buy flow: sponsor hold, balance -// pre-flight, Trust Wallet heads-up), switch-on-payouts without buying, card on-ramp, purchases from the chain. -(function () { - const $ = id => document.getElementById(id); const esc = CR.esc, fmt = CR.fmt; - // wallet.js reports through IAP.status (the classic dashboard's status bar): route it to the shell's toast - if (window.IAP) IAP.status = (m, kind) => CR.toast(m, kind === 'bad'); - CR.mount({ active: 'credits', title: 'Credits', sub: 'loading' }); - const pol = wei => { try { return (Number(BigInt(String(wei || '0')) / 10000000000000000n) / 100).toFixed(2); } catch (e) { return '0.00'; } }; - const usd = c => '$' + (Number(c || 0) / 100).toLocaleString(undefined, { maximumFractionDigits: 2 }); - const NAMES = { 1000: 'Door', 2500: 'Most chosen', 5000: 'Builder', 10000: 'Growth', 25000: 'Leader', 50000: 'Network' }; - let CFG = null, ME = null, CAT = [], SEL = null, CAMP = null, DASH = null; - - function paintTiles() { - const avail = CAMP ? CAMP.availableCredits : 0, inLive = CAMP ? CAMP.inCampaigns : 0; - const addr = ME && ME.address, on = !!(ME && ME.memberId); - const bc = DASH ? (DASH.buyerCount || 0) : 0; - $('tiles').innerHTML = [ - CR.tile({ k: 'Credits available', v: fmt(avail), hi: true, note: CAMP ? 'earned ' + fmt(CAMP.earnedCredits) + ' · purchased ' + fmt(CAMP.purchasedCredits) : '' }), - CR.tile({ k: 'Working in live ads', v: fmt(inLive), note: CAMP ? (CAMP.campaigns || []).filter(c => c.status === 'live').length + ' live' : '' }), - CR.tile({ k: 'Wallet', v: addr ? addr.slice(0, 6) + '…' + addr.slice(-4) : 'not linked', note: on ? 'payouts on · member #' + ME.memberId : (addr ? 'payouts off' : 'needed to buy or be paid') }), - CR.tile({ k: 'Qualification', v: bc + ' of ' + (bc >= 5 ? 5 : bc >= 2 ? 5 : 2), note: bc >= 5 ? 'levels 2 and 3 open' : bc >= 2 ? 'level 2 open · 5 opens level 3' : 'buyers to open level 2' }) - ].join(''); - } - function paintPkgs() { - const live = CAT.filter(p => p.active !== false && p.exists !== false); - if (!live.length) { $('pkgs').innerHTML = '
No packages are on sale right now.
'; return; } - if (!SEL) SEL = (live.find(p => p.priceCents === 2500) || live[0]).id; - $('pkgs').innerHTML = live.map(p => '').join(''); - $('pkgs').querySelectorAll('.pk').forEach(b => b.addEventListener('click', () => { SEL = Number(b.dataset.id); paintPkgs(); paintQuote(); paintGoes(); })); - } - const sel = () => CAT.find(p => p.id === SEL); - function paintQuote() { - const p = sel(); if (!p) return; - if (p.costWei) { $('payPol').textContent = pol(p.costWei) + ' POL'; $('payUsd').textContent = '≈ ' + usd(p.priceCents) + ' + gas'; } - else { $('payPol').textContent = 'paused'; $('payUsd').textContent = 'price feed is catching up'; } - const rate = (p.costWei && p.priceCents) ? (p.priceCents / 100) / (Number(BigInt(p.costWei) / 1000000000000n) / 1e6) : 0; - $('rateLine').textContent = rate ? 'rate ' + rate.toFixed(4) + ' USD/POL · live from the oracle' : ''; - const addr = ME && ME.address; - $('buyBtn').disabled = !p.costWei; - $('buyBtn').textContent = addr ? 'Buy ' + usd(p.priceCents) + ' package' : 'Connect a wallet to buy'; - } - function paintGoes() { - const p = sel(); if (!p) return; - const d = p.priceCents / 100; const spName = ME && ME.sponsorName ? ('@' + String(ME.sponsorName).replace(/^@/, '')) : 'your sponsor'; - $('goesTitle').textContent = 'Where ' + usd(p.priceCents) + ' goes'; - $('goesRows').innerHTML = [ - ['Level 1 · ' + esc(spName), '$' + (d * 0.5).toFixed(2)], - ['Level 2 · upline if qualified', '$' + (d * 0.2).toFixed(2)], - ['Level 3 · upline if qualified', '$' + (d * 0.1).toFixed(2)], - ['Platform, two wallets', '$' + (d * 0.2).toFixed(2)] - ].map(([k, v]) => '
' + k + '' + v + '
').join('') - + '

A pass-up goes to the next qualified member above, else to the platform. Nothing is ever held for later.

'; - } - function paintWallet() { - const addr = ME && ME.address, on = !!(ME && ME.memberId); - $('walletMeta').textContent = addr ? (on ? 'payouts on' : 'linked · payouts off') : 'none linked'; - $('walletBox').innerHTML = addr - ? '
' + esc(addr) + '
' - + (on ? '
Payouts on. Every package your people buy pays this wallet in the same transaction.
' - : '
Linked, but payouts are off until this wallet is on the contract. Buying a package does that. So does the free activation below (gas only).
') - + '
Open on the explorer
' - : '
Link the wallet that should receive your payouts. One free signature, no transaction. SafePal is the recommended wallet; MetaMask, Phantom and any WalletConnect wallet work too.
Wallet guide
'; - const lb = $('linkBtn'); if (lb) lb.addEventListener('click', () => guard(lb, linkWallet)); - const ab = $('activateBtn'); if (ab) ab.addEventListener('click', () => guard(ab, activate)); - const rb = $('relinkBtn'); if (rb) rb.addEventListener('click', () => guard(rb, async () => { await IAPWallet.disconnect(); CR.toast('Disconnected. Reloading so you can pick another wallet.'); setTimeout(() => location.reload(), 800); })); - } - function paintBuys(E) { - const buys = E && Array.isArray(E.purchases) ? E.purchases : []; - $('buysMeta').textContent = buys.length + (buys.length === 1 ? ' purchase' : ' purchases') + ' · every row links to the transaction'; - $('buyRows').innerHTML = buys.length ? buys.slice(0, 50).map(x => { - const ts = Number(x.ts || x.time || 0); const when = ts ? new Date(ts * (ts > 1e12 ? 1 : 1000)).toLocaleString() : ''; - const pkg = x.priceCents ? usd(x.priceCents) : (x.package || x.product || ('#' + (x.productId || ''))); - const paid = x.amountWei || x.valueWei || x.paidWei ? pol(x.amountWei || x.valueWei || x.paidWei) + ' POL' : ''; - const tx = x.tx || x.hash || ''; - return '
' + esc(when) + '' + esc(String(pkg)) + '' + esc(paid) + '' + (tx ? '' + esc(tx.slice(0, 10)) + '…' + esc(tx.slice(-6)) + '' : '') + '
'; - }).join('') : '
Nothing yet. Your first package shows here with its transaction, what you paid in POL, and who in your line was paid.
'; - } - async function guard(btn, fn) { if (btn.disabled) return; btn.disabled = true; try { await fn(); } catch (e) { CR.toast((e && e.message) || 'Something went wrong.', true); } finally { btn.disabled = false; } } - - // a named sponsor that cannot be paid right now: hold the transaction and say why (never credit the company by default) - function holdText(sp) { - const who = sp.sponsorName ? ('@' + String(sp.sponsorName).replace(/^@/, '')) : 'your sponsor'; - if (sp.sponsorBlocked === 'claim' && sp.claim) return (sp.claim.nobody ? 'Nobody above you on LinkSpin has a wallet yet, so there is no one for the contract to pay. ' : who + ' has not linked a wallet on LinkSpin yet. ') + 'Your first purchase waits until ' + (sp.claim.deadline ? new Date(sp.claim.deadline).toLocaleDateString() : 'they do') + ', then it goes ahead with the nearest member above who has one. Nothing was charged.'; - if (sp.sponsorBlocked === 'notActivated') return who + ' has not switched on payouts yet, so this purchase would credit the company instead of them. Ask them to switch on payouts first (one free transaction).'; - if (sp.sponsorBlocked === 'rpc') return 'Could not confirm your sponsor on the chain just now. Try again in a minute; nothing was charged.'; - return 'Your sponsor link could not be matched to a member. Message support before buying so ' + who + ' gets credit.'; - } - async function linkWallet() { CR.toast('Check your wallet for the free link signature…'); await IAPWallet.signIn(); CR.toast('Wallet linked. Earnings pay there from now on.'); await load(); } - async function activate() { - const me = await CR.me(true); if (me.sponsorBlocked) { $('holdBox').textContent = holdText(me); $('holdBox').hidden = false; return; } - CR.toast('Confirm the free activation in your wallet…'); - const r = await IAPWallet.activate(me.sponsorId || 0); - if (!r.receipt || r.receipt.status !== '0x1') throw new Error('Transaction reverted. Check the explorer.'); - CR.toast('Payouts are on. Your invite link is live.'); await load(); - } - async function buy() { - const p = sel(); if (!p || !p.costWei) return; - $('holdBox').hidden = true; - let me = await CR.me(true); - if (!me.address) { CR.toast('Link your wallet first: one quick signature…'); await IAPWallet.signIn(); me = await CR.me(true); } - const want = String(me.address || '').toLowerCase(); if (!want) throw new Error('No wallet linked.'); - await IAPWallet.connect(); - let cur = String(await IAPWallet.activeAddress() || '').toLowerCase(); - if (cur !== want) { CR.toast('Pick ' + want.slice(0, 6) + '…' + want.slice(-4) + ' in your wallet\'s account picker…'); cur = String(await IAPWallet.pickAccount() || '').toLowerCase(); } - if (cur !== want) throw new Error('Your wallet connected as ' + cur.slice(0, 6) + '…' + cur.slice(-4) + ' but your linked wallet is ' + want.slice(0, 6) + '…' + want.slice(-4) + '. Switch accounts in the wallet app and try again.'); - const sp = await CR.get('/api/sponsor'); - if (!me.memberId && sp.sponsorBlocked) { $('holdBox').textContent = holdText(sp); $('holdBox').hidden = false; return; } - try { // pre-flight: the POL has to be there; Trust Wallet refuses transactions that spend most of a balance - const need = BigInt(p.costWei) + BigInt(p.costWei) / 50n; - const bal = await IAPWallet.balance(want); - if (bal < need) { CR.toast('That wallet holds ' + pol(bal.toString()) + ' POL, but this package needs about ' + pol(need.toString()) + ' POL plus a little for gas. Top it up and try again.', true); return; } - const pct = Number(need * 100n / bal); - if (/trust/i.test(IAPWallet.walletName() || '') && pct > 55) { - const ok = await CR.dialog({ title: 'Heads up for Trust Wallet', text: 'This purchase uses about ' + pct + '% of the POL in your wallet, and Trust Wallet refuses transactions that spend most of a balance. Add some POL first, or continue and see if it lets it through.', ok: 'Continue' }); - if (!ok) return; - } - } catch (e) { /* balance read failed: let the wallet decide */ } - CR.toast('Confirm the purchase in your wallet…'); - const r = await IAPWallet.buy(Number(p.id), sp.sponsorId || 0, p.costWei); - if (!r.receipt || r.receipt.status !== '0x1') throw new Error('Transaction reverted. Nothing was charged beyond gas.'); - CR.toast('Settled on-chain. Your credits are in Ads now.'); - await load(); - } - $('buyBtn').addEventListener('click', () => guard($('buyBtn'), buy)); - $('cardBtn').addEventListener('click', () => guard($('cardBtn'), async () => { - const p = sel(); const need = p && p.costWei ? Math.max(10, Math.ceil(Number(BigInt(p.costWei) / 1000000000000000000n)) + 3) : 30; - const q = '/api/moonpay-url?pol=' + need + (ME && ME.address ? '&address=' + encodeURIComponent(ME.address) : ''); - const r = await CR.get(q); if (!r.url) throw new Error('The card on-ramp is not available right now.'); - window.open(r.url, '_blank', 'noopener'); CR.toast('MoonPay opened in a new tab. POL lands straight in your own wallet.'); - })); - - async function load() { - try { [CFG, ME] = await Promise.all([CR.get('/api/config'), CR.me(true)]); } catch (e) { CR.sub('could not load'); return; } - let cat = null, E = null; - try { [cat, CAMP, DASH, E] = await Promise.all([CR.get('/api/catalog'), CR.get('/api/my/campaigns'), CR.get('/api/my/dashboard'), CR.get('/api/my/activity')]); } catch (e) {} - CAT = (cat && cat.products) || []; - CR.sub((CAMP ? fmt(CAMP.availableCredits) + ' free to spend · ' + fmt(CAMP.inCampaigns) + ' in live ads' : '') + (CAT[0] && CAT[0].costWei ? '' : ' · price feed catching up')); - paintTiles(); paintPkgs(); paintQuote(); paintGoes(); paintWallet(); paintBuys(E); - const spName = ME.sponsorName ? ('@' + String(ME.sponsorName).replace(/^@/, '')) : null; - $('sponsorLine').innerHTML = spName - ? 'Your sponsor ' + esc(spName) + ' is placed on the contract. The moment you confirm, half of the package lands in their wallet and the rest splits as shown. Credits appear in Ads right away.' - : 'No sponsor is recorded on your account. Your purchase still works; the sponsor share goes to the platform position. If someone invited you, open their invite link first.'; - if (ME.sponsorBlocked) { $('holdBox').textContent = holdText(ME); $('holdBox').hidden = false; } - } - CR.requireSession(load); -})(); +// LinkSpin Credits (2026-10-07): the buy screen inside the Control Room. Package picker from the catalog, the POL +// quote, connect/link a wallet, the on-chain purchase (ported from the classic /my#buy flow: sponsor hold, balance +// pre-flight, Trust Wallet heads-up), switch-on-payouts without buying, card on-ramp, purchases from the chain. +(function () { + const $ = id => document.getElementById(id); const esc = CR.esc, fmt = CR.fmt; + // wallet.js reports through IAP.status (the classic dashboard's status bar): route it to the shell's toast + if (window.IAP) IAP.status = (m, kind) => CR.toast(m, kind === 'bad'); + CR.mount({ active: 'credits', title: 'Credits', sub: 'loading' }); + const pol = wei => { try { return (Number(BigInt(String(wei || '0')) / 10000000000000000n) / 100).toFixed(2); } catch (e) { return '0.00'; } }; + const usd = c => '$' + (Number(c || 0) / 100).toLocaleString(undefined, { maximumFractionDigits: 2 }); + const NAMES = { 1000: 'Door', 2500: 'Most chosen', 5000: 'Builder', 10000: 'Growth', 25000: 'Leader', 50000: 'Network' }; + let CFG = null, ME = null, CAT = [], SEL = null, CAMP = null, DASH = null; + + function paintTiles() { + const avail = CAMP ? CAMP.availableCredits : 0, inLive = CAMP ? CAMP.inCampaigns : 0; + const addr = ME && ME.address, on = !!(ME && ME.memberId); + const bc = DASH ? (DASH.buyerCount || 0) : 0; + $('tiles').innerHTML = [ + CR.tile({ k: 'Credits available', v: fmt(avail), hi: true, note: CAMP ? 'earned ' + fmt(CAMP.earnedCredits) + ' · purchased ' + fmt(CAMP.purchasedCredits) : '' }), + CR.tile({ k: 'Working in live ads', v: fmt(inLive), note: CAMP ? (CAMP.campaigns || []).filter(c => c.status === 'live').length + ' live' : '' }), + CR.tile({ k: 'Wallet', v: addr ? addr.slice(0, 6) + '…' + addr.slice(-4) : 'not linked', note: on ? 'payouts on · member #' + ME.memberId : (addr ? 'payouts off' : 'needed to buy or be paid') }), + CR.tile({ k: 'Qualification', v: bc + ' of ' + (bc >= 5 ? 5 : bc >= 2 ? 5 : 2), note: bc >= 5 ? 'levels 2 and 3 open' : bc >= 2 ? 'level 2 open · 5 opens level 3' : 'buyers to open level 2' }) + ].join(''); + } + function paintPkgs() { + const live = CAT.filter(p => p.active !== false && p.exists !== false); + if (!live.length) { $('pkgs').innerHTML = '
No packages are on sale right now.
'; return; } + if (!SEL) SEL = (live.find(p => p.priceCents === 2500) || live[0]).id; + $('pkgs').innerHTML = live.map(p => '').join(''); + $('pkgs').querySelectorAll('.pk').forEach(b => b.addEventListener('click', () => { SEL = Number(b.dataset.id); paintPkgs(); paintQuote(); paintGoes(); })); + } + const sel = () => CAT.find(p => p.id === SEL); + function paintQuote() { + const p = sel(); if (!p) return; + if (p.costWei) { $('payPol').textContent = pol(p.costWei) + ' POL'; $('payUsd').textContent = '≈ ' + usd(p.priceCents) + ' + gas'; } + else { $('payPol').textContent = 'paused'; $('payUsd').textContent = 'price feed is catching up'; } + const rate = (p.costWei && p.priceCents) ? (p.priceCents / 100) / (Number(BigInt(p.costWei) / 1000000000000n) / 1e6) : 0; + $('rateLine').textContent = rate ? 'rate ' + rate.toFixed(4) + ' USD/POL · live from the oracle' : ''; + const addr = ME && ME.address; + $('buyBtn').disabled = !p.costWei; + $('buyBtn').textContent = addr ? 'Buy ' + usd(p.priceCents) + ' package' : 'Connect a wallet to buy'; + } + function paintGoes() { + const p = sel(); if (!p) return; + const d = p.priceCents / 100; const spName = ME && ME.sponsorName ? ('@' + String(ME.sponsorName).replace(/^@/, '')) : 'your sponsor'; + $('goesTitle').textContent = 'Where ' + usd(p.priceCents) + ' goes'; + $('goesRows').innerHTML = [ + ['Level 1 · ' + esc(spName), '$' + (d * 0.5).toFixed(2)], + ['Level 2 · upline if qualified', '$' + (d * 0.2).toFixed(2)], + ['Level 3 · upline if qualified', '$' + (d * 0.1).toFixed(2)], + ['Platform, two wallets', '$' + (d * 0.2).toFixed(2)] + ].map(([k, v]) => '
' + k + '' + v + '
').join('') + + '

A pass-up goes to the next qualified member above, else to the platform. Nothing is ever held for later.

'; + } + function paintWallet() { + const addr = ME && ME.address, on = !!(ME && ME.memberId); + $('walletMeta').textContent = addr ? (on ? 'payouts on' : 'linked · payouts off') : 'none linked'; + $('walletBox').innerHTML = addr + ? '
' + esc(addr) + '
' + + (on ? '
Payouts on. Every package your people buy pays this wallet in the same transaction.
' + : '
Linked, but payouts are off until this wallet is on the contract. Buying a package does that. So does the free activation below (gas only).
') + + '
Open on the explorer
' + : '
Link the wallet that should receive your payouts. One free signature, no transaction. SafePal is the recommended wallet; MetaMask, Phantom and any WalletConnect wallet work too.
Wallet guide
'; + const lb = $('linkBtn'); if (lb) lb.addEventListener('click', () => guard(lb, linkWallet)); + const ab = $('activateBtn'); if (ab) ab.addEventListener('click', () => guard(ab, activate)); + const rb = $('relinkBtn'); if (rb) rb.addEventListener('click', () => guard(rb, async () => { await IAPWallet.disconnect(); CR.toast('Disconnected. Reloading so you can pick another wallet.'); setTimeout(() => location.reload(), 800); })); + } + function paintBuys(E) { + const buys = E && Array.isArray(E.purchases) ? E.purchases : []; + $('buysMeta').textContent = buys.length + (buys.length === 1 ? ' purchase' : ' purchases') + ' · every row links to the transaction'; + $('buyRows').innerHTML = buys.length ? buys.slice(0, 50).map(x => { + const ts = Number(x.ts || x.time || 0); const when = ts ? new Date(ts * (ts > 1e12 ? 1 : 1000)).toLocaleString() : ''; + const pkg = x.priceCents ? usd(x.priceCents) : (x.package || x.product || ('#' + (x.productId || ''))); + const paid = x.amountWei || x.valueWei || x.paidWei ? pol(x.amountWei || x.valueWei || x.paidWei) + ' POL' : ''; + const tx = x.tx || x.hash || ''; + return '
' + esc(when) + '' + esc(String(pkg)) + '' + esc(paid) + '' + (tx ? '' + esc(tx.slice(0, 10)) + '…' + esc(tx.slice(-6)) + '' : '') + '
'; + }).join('') : '
Nothing yet. Your first package shows here with its transaction, what you paid in POL, and who in your line was paid.
'; + } + async function guard(btn, fn) { if (btn.disabled) return; btn.disabled = true; try { await fn(); } catch (e) { CR.toast((e && e.message) || 'Something went wrong.', true); } finally { btn.disabled = false; } } + + // a named sponsor that cannot be paid right now: hold the transaction and say why (never credit the company by default) + function holdText(sp) { + const who = sp.sponsorName ? ('@' + String(sp.sponsorName).replace(/^@/, '')) : 'your sponsor'; + if (sp.sponsorBlocked === 'claim' && sp.claim) return (sp.claim.nobody ? 'Nobody above you on LinkSpin has a wallet yet, so there is no one for the contract to pay. ' : who + ' has not linked a wallet on LinkSpin yet. ') + 'Your first purchase waits until ' + (sp.claim.deadline ? new Date(sp.claim.deadline).toLocaleDateString() : 'they do') + ', then it goes ahead with the nearest member above who has one. Nothing was charged.'; + if (sp.sponsorBlocked === 'notActivated') return who + ' has not switched on payouts yet, so this purchase would credit the company instead of them. Ask them to switch on payouts first (one free transaction).'; + if (sp.sponsorBlocked === 'rpc') return 'Could not confirm your sponsor on the chain just now. Try again in a minute; nothing was charged.'; + return 'Your sponsor link could not be matched to a member. Message support before buying so ' + who + ' gets credit.'; + } + async function linkWallet() { CR.toast('Check your wallet for the free link signature…'); await IAPWallet.signIn(); CR.toast('Wallet linked. Earnings pay there from now on.'); await load(); } + async function activate() { + const sp = await CR.get('/api/sponsor?intent=buy'); if (sp.sponsorBlocked) { $('holdBox').textContent = holdText(sp); $('holdBox').hidden = false; return; } + CR.toast('Confirm the free activation in your wallet…'); + const r = await IAPWallet.activate(sp.sponsorId || 0); + if (!r.receipt || r.receipt.status !== '0x1') throw new Error('Transaction reverted. Check the explorer.'); + CR.toast('Payouts are on. Your invite link is live.'); await load(); + } + async function buy() { + const p = sel(); if (!p || !p.costWei) return; + $('holdBox').hidden = true; + let me = await CR.me(true); + if (!me.address) { CR.toast('Link your wallet first: one quick signature…'); await IAPWallet.signIn(); me = await CR.me(true); } + const want = String(me.address || '').toLowerCase(); if (!want) throw new Error('No wallet linked.'); + await IAPWallet.connect(); + let cur = String(await IAPWallet.activeAddress() || '').toLowerCase(); + if (cur !== want) { CR.toast('Pick ' + want.slice(0, 6) + '…' + want.slice(-4) + ' in your wallet\'s account picker…'); cur = String(await IAPWallet.pickAccount() || '').toLowerCase(); } + if (cur !== want) throw new Error('Your wallet connected as ' + cur.slice(0, 6) + '…' + cur.slice(-4) + ' but your linked wallet is ' + want.slice(0, 6) + '…' + want.slice(-4) + '. Switch accounts in the wallet app and try again.'); + const sp = await CR.get('/api/sponsor?intent=buy'); + if (!me.memberId && sp.sponsorBlocked) { $('holdBox').textContent = holdText(sp); $('holdBox').hidden = false; return; } + try { // pre-flight: the POL has to be there; Trust Wallet refuses transactions that spend most of a balance + const need = BigInt(p.costWei) + BigInt(p.costWei) / 50n; + const bal = await IAPWallet.balance(want); + if (bal < need) { CR.toast('That wallet holds ' + pol(bal.toString()) + ' POL, but this package needs about ' + pol(need.toString()) + ' POL plus a little for gas. Top it up and try again.', true); return; } + const pct = Number(need * 100n / bal); + if (/trust/i.test(IAPWallet.walletName() || '') && pct > 55) { + const ok = await CR.dialog({ title: 'Heads up for Trust Wallet', text: 'This purchase uses about ' + pct + '% of the POL in your wallet, and Trust Wallet refuses transactions that spend most of a balance. Add some POL first, or continue and see if it lets it through.', ok: 'Continue' }); + if (!ok) return; + } + } catch (e) { /* balance read failed: let the wallet decide */ } + CR.toast('Confirm the purchase in your wallet…'); + const r = await IAPWallet.buy(Number(p.id), sp.sponsorId || 0, p.costWei); + if (!r.receipt || r.receipt.status !== '0x1') throw new Error('Transaction reverted. Nothing was charged beyond gas.'); + CR.toast('Settled on-chain. Your credits are in Ads now.'); + await load(); + } + $('buyBtn').addEventListener('click', () => guard($('buyBtn'), buy)); + $('cardBtn').addEventListener('click', () => guard($('cardBtn'), async () => { + const p = sel(); const need = p && p.costWei ? Math.max(10, Math.ceil(Number(BigInt(p.costWei) / 1000000000000000000n)) + 3) : 30; + const q = '/api/moonpay-url?pol=' + need + (ME && ME.address ? '&address=' + encodeURIComponent(ME.address) : ''); + const r = await CR.get(q); if (!r.url) throw new Error('The card on-ramp is not available right now.'); + window.open(r.url, '_blank', 'noopener'); CR.toast('MoonPay opened in a new tab. POL lands straight in your own wallet.'); + })); + + async function load() { + try { [CFG, ME] = await Promise.all([CR.get('/api/config'), CR.me(true)]); } catch (e) { CR.sub('could not load'); return; } + let cat = null, E = null; + try { [cat, CAMP, DASH, E] = await Promise.all([CR.get('/api/catalog'), CR.get('/api/my/campaigns'), CR.get('/api/my/dashboard'), CR.get('/api/my/activity')]); } catch (e) {} + CAT = (cat && cat.products) || []; + CR.sub((CAMP ? fmt(CAMP.availableCredits) + ' free to spend · ' + fmt(CAMP.inCampaigns) + ' in live ads' : '') + (CAT[0] && CAT[0].costWei ? '' : ' · price feed catching up')); + paintTiles(); paintPkgs(); paintQuote(); paintGoes(); paintWallet(); paintBuys(E); + const spName = ME.sponsorName ? ('@' + String(ME.sponsorName).replace(/^@/, '')) : null; + $('sponsorLine').innerHTML = spName + ? 'Your sponsor ' + esc(spName) + ' is placed on the contract. The moment you confirm, half of the package lands in their wallet and the rest splits as shown. Credits appear in Ads right away.' + : 'No sponsor is recorded on your account. Your purchase still works; the sponsor share goes to the platform position. If someone invited you, open their invite link first.'; + if (ME.sponsorBlocked) { $('holdBox').textContent = holdText(ME); $('holdBox').hidden = false; } + } + CR.requireSession(load); +})(); diff --git a/public/assets/my.js b/public/assets/my.js index 2bb387c..bbc7522 100644 --- a/public/assets/my.js +++ b/public/assets/my.js @@ -1,2701 +1,2701 @@ -// My account: email-first join/login, wallet link at purchase time, -// free payout activation, invite link, on-chain activity. -(async function () { - // back-office shell: no marketing nav here; rehearsal notice lives in the top bar - const $ = IAP.$; - try { - const c = await IAP.getConfig(); - if (c.rehearsal && $('boRehearsal')) { - $('boRehearsal').hidden = false; - $('boRehearsal').innerHTML = 'Testnet rehearsal · ' + c.chainName; - } - if (c.rehearsal && $('faucetCard')) $('faucetCard').hidden = false; - } catch (e) {} - // if they arrived through a sponsor's link, show who they're joining under - (async () => { - try { - const sp = await (await fetch('/api/sponsor')).json(); - if (sp && sp.invited && sp.name && $('sponsorNote')) { $('sponsorNoteName').textContent = sp.name; $('sponsorNote').hidden = false; } - } catch (e) {} - })(); - - async function api(path, body) { - const r = await (await fetch(path, { method: 'POST', - headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body || {}) })).json(); - if (r.error) throw new Error(r.error); - return r; - } - - function nextMove(d) { - if (!d.address) return 'Grab your link below and start sharing today. Then link your wallet (one free signature) so every payment can lock to you before your people start buying.'; - if (!d.memberId) return 'Your wallet is linked. Switch on payouts above (one free transaction) and every purchase in your line pays you the moment it happens.'; - if (d.buyerCount === 0) return 'Payouts are on and your link is live. Your next milestone: your first buyer of $25 or more. Every direct pays you 50 percent from their very first package.'; - if (d.buyerCount === 1) return 'One qualifying buyer down, one to go. Your next $25+ buyer unlocks level 2: 20 percent of everything your people’s people buy.'; - if (d.buyerCount < 5) return 'Level 2 is open. ' + (5 - d.buyerCount) + ' more qualifying buyer(s) unlock level 3 and the full three-level flow.'; - return 'Fully qualified. Every level pays you, and you catch the pass-ups that under-qualified positions below you let slip. Keep sharing and keep your campaigns running.'; - } - // featured rotation strip on the overview - let featItems = [], featIdx = 0, featTimer = null; - function renderOneFeatured() { - if (!featItems.length) return; - const i = featItems[featIdx % featItems.length]; - $('featStrip').innerHTML = '' + esc(i.title) + '' - + (i.by ? '' + esc(i.by) + '' : '') + ''; - } - async function loadFeatured() { - try { - const r = await (await fetch('/api/featured')).json(); - const card = $('featuredCard'); if (!card) return; - if (!r.items || !r.items.length) { card.hidden = true; return; } - card.hidden = false; - featItems = r.items; featIdx = Math.floor(Math.random() * featItems.length); - $('featSub').textContent = r.items.length + ' link' + (r.items.length === 1 ? '' : 's') + ' in rotation'; - renderOneFeatured(); // show ONE at a time (true rotation), cycle if more than one - clearInterval(featTimer); - if (featItems.length > 1) featTimer = setInterval(() => { featIdx++; renderOneFeatured(); }, 6000); - // self-sell: today's open slots + a CTA to feature your own link - try { - const st = await (await fetch('/api/featured/stats')).json(); - const today = (st.occupancy || []).find(d => d.offset === 0); - const cta = $('featCta'); - if (cta) { - cta.innerHTML = (today ? '' + today.open + ' of ' + today.cap + ' featured slots open today. ' : '') - + 'Feature your link →'; - const fb = $('featBuy'); - if (fb) fb.addEventListener('click', e => { e.preventDefault(); setPane('campaigns'); const ct = $('cType'); if (ct) { ct.value = 'featured'; ct.dispatchEvent(new Event('change')); } }); - } - } catch (e) {} - } catch (e) {} - } - - // achievement badges: the milestone ladder as unlockable medals + share-to-image - const BADGES = [ // ribbonY = vertical center of each badge's name ribbon (art differs per tier) - { key: 'payouts', label: 'Spark', sub: 'payouts on', img: '/badges/badge-spark.jpg', ribbonY: 0.728 }, - { key: 'firstBuyer', label: 'Surge', sub: 'first qualifying buyer', img: '/badges/badge-surge.jpg?v=2', ribbonY: 0.76 }, - { key: 'level2', label: 'Circuit', sub: '2 qualifying buyers', img: '/badges/badge-circuit.jpg?v=2', ribbonY: 0.72 }, - { key: 'level3', label: 'Nexus', sub: 'fully qualified', img: '/badges/badge-nexus.jpg?v=2', ribbonY: 0.73 } - ]; - let lastMilestones = []; - function renderBadges(d) { - const reached = d.milestonesReached || []; - lastMilestones = reached; - const strip = $('badgeStrip'); - if (!strip) return; - $('badgeCard').hidden = false; - strip.innerHTML = BADGES.map(b => { - const got = reached.includes(b.key); - return '
' - + '' + b.label + ' badge' - + '
' + b.label + '
' + b.sub + '
' - + (got ? ' ' : '
🔒 locked
') + '
'; - }).join(''); - strip.querySelectorAll('[data-badge]').forEach(btn => - btn.addEventListener('click', () => shareBadge(btn.dataset.badge, d))); - strip.querySelectorAll('[data-badgepost]').forEach(btn => - btn.addEventListener('click', () => postBadge(btn.dataset.badgepost, d, btn, true))); - fetch('/api/my/badge-posted').then(r => r.json()).then(r => { // the manual button is the admin's only (Marty, 2026-09-13) - if (r.canPost) strip.querySelectorAll('[data-badgepost]').forEach(b => { b.hidden = false; }); - (r.posted || []).forEach(k => { const b = strip.querySelector('[data-badgepost="' + k + '"]'); if (b) { b.textContent = 'Posted ✓'; b.disabled = true; } }); - }).catch(() => {}); - // celebrate anything newly granted this load, and post the branded badge to the team channels (Marty, 2026-09-13) - if (d.milestonesGranted && d.milestonesGranted.length) { - const total = d.milestonesGranted.reduce((s, g) => s + g.credited, 0); - const names = d.milestonesGranted.map(g => (BADGES.find(b => b.key === g.key) || {}).label).filter(Boolean).join(', '); - IAP.status('🏆 Achievement unlocked: ' + names + ' — +' + total + ' bonus credits!', 'ok'); - d.milestonesGranted.forEach((g, i) => setTimeout(() => postBadge(g.key, d, strip.querySelector('[data-badgepost="' + g.key + '"]')), 800 + i * 1500)); - } - } - // draw the badge with the member's name on the ribbon; cb(canvas) or cb(null) - function composeBadge(key, d, cb) { - const b = BADGES.find(x => x.key === key); if (!b) return cb(null); - const who = d.username ? d.username : d.memberId ? 'member #' + d.memberId : ''; - const img = new Image(); - img.onload = () => { - const c = document.createElement('canvas'); c.width = img.width; c.height = img.height; - const x = c.getContext('2d'); - x.drawImage(img, 0, 0); - if (who) { - x.textAlign = 'center'; x.textBaseline = 'middle'; - x.font = 'bold ' + Math.round(c.width * 0.055) + 'px Sora, "Segoe UI", sans-serif'; - const y = c.height * (b.ribbonY || 0.75); - x.lineJoin = 'round'; x.lineWidth = Math.max(3, Math.round(c.width * 0.008)); - x.strokeStyle = 'rgba(4,20,15,.9)'; x.strokeText(who, c.width / 2, y); - x.fillStyle = '#ffd15c'; x.fillText(who, c.width / 2, y); - } - cb(c); - }; - img.onerror = () => cb(null); - img.src = b.img; - } - async function postBadge(key, d, btn, manual) { - if (btn && btn.disabled) return; - if (btn) { btn.disabled = true; btn.textContent = 'Posting…'; } - composeBadge(key, d, c => { - if (!c) { if (btn) { btn.disabled = false; btn.textContent = 'Post to Telegram'; } return; } - c.toBlob(async bl => { - try { - const r = await (await fetch('/api/my/badge-post?key=' + encodeURIComponent(key) + (manual ? '&manual=1' : ''), { method: 'POST', headers: { 'Content-Type': 'image/jpeg' }, body: bl })).json(); - if (r.error) throw new Error(r.error); - if (btn) { btn.textContent = 'Posted ✓'; btn.disabled = true; } - if (!r.already) IAP.status('Your badge is posted in the team channels.', 'ok'); - } catch (e) { if (btn) { btn.disabled = false; btn.textContent = 'Post to Telegram'; } IAP.status(e.message || 'Could not post the badge.', 'bad'); } - }, 'image/jpeg', 0.86); - }); - } - // Share: a picker (Marty, 2026-09-13). The composed badge is stored once so a public page at - // /b// carries it as the preview image; every network gets that link. - function shareBadge(key, d) { - const b = BADGES.find(x => x.key === key); if (!b) return; - if (!d.username) { IAP.status('Pick a username first; your share page carries it.', 'bad'); return; } - IAP.status('Preparing your ' + b.label + ' badge…', 'ok'); - composeBadge(key, d, c => { - if (!c) { IAP.status('Could not load the badge art.', 'bad'); return; } - c.toBlob(async bl => { - let page = null; - try { const r = await (await fetch('/api/my/badge-image?key=' + encodeURIComponent(key), { method: 'POST', headers: { 'Content-Type': 'image/jpeg' }, body: bl })).json(); if (r.error) throw new Error(r.error); page = r.page; } - catch (e) { IAP.status(e.message || 'Could not prepare the share page.', 'bad'); return; } - openShareSheet(b, d, bl, page); - }, 'image/jpeg', 0.9); - }); - } - function openShareSheet(b, d, blob, page) { - const text = 'I just unlocked the ' + b.label + ' badge on LinkSpin (' + b.sub + '). Advertising that pays you back, on-chain, the same second a package sells.'; - const enc = encodeURIComponent; - const links = [ - ['X', 'https://x.com/intent/tweet?text=' + enc(text) + '&url=' + enc(page)], - ['Facebook', 'https://www.facebook.com/sharer/sharer.php?u=' + enc(page)], - ['Telegram', 'https://t.me/share/url?url=' + enc(page) + '&text=' + enc(text)], - ['WhatsApp', 'https://wa.me/?text=' + enc(text + ' ' + page)], - ['LinkedIn', 'https://www.linkedin.com/sharing/share-offsite/?url=' + enc(page)] - ]; - const back = document.createElement('div'); back.className = 'modal-back'; back.style.zIndex = '200'; - back.innerHTML = ''; - document.body.appendChild(back); - const close = () => back.remove(); - back.addEventListener('click', e => { if (e.target === back) close(); }); - back.querySelector('[data-sh="close"]').addEventListener('click', close); - back.querySelector('[data-sh="copy"]').addEventListener('click', async () => { try { await navigator.clipboard.writeText(page); IAP.status('Link copied.', 'ok'); } catch (e) { IAP.status('Copy this: ' + page, 'ok'); } }); - back.querySelector('[data-sh="save"]').addEventListener('click', () => { - const a = document.createElement('a'); a.href = URL.createObjectURL(blob); a.download = 'linkspin-' + b.label.toLowerCase() + '-badge.jpg'; a.click(); setTimeout(() => URL.revokeObjectURL(a.href), 5000); - IAP.status('Your ' + b.label + ' badge is saved.', 'ok'); - }); - // Massifly has no share intent: copy the post text + link, then open the feed composer (Marty, 2026-09-13) - back.querySelector('[data-sh="massifly"]').addEventListener('click', async () => { - try { await navigator.clipboard.writeText(text + ' ' + page); IAP.status('Post copied. Paste it into the Massifly composer; the badge preview appears from the link.', 'ok'); } - catch (e) { IAP.status('Copy this into Massifly: ' + text + ' ' + page, 'ok'); } - window.open('https://massifly.com/account', '_blank', 'noopener'); - }); - const nat = back.querySelector('[data-sh="native"]'); - if (nat) nat.addEventListener('click', async () => { - try { - const file = new File([blob], 'linkspin-' + b.label.toLowerCase() + '-badge.jpg', { type: 'image/jpeg' }); - if (navigator.canShare && navigator.canShare({ files: [file] })) await navigator.share({ files: [file], title: b.label + ' badge', text: text + ' ' + page }); - else await navigator.share({ title: b.label + ' badge', text, url: page }); - } catch (e) {} - }); - } - - // milestone stepper under "Your next move": lit nodes for what's done, - // amber glow on the current target — the same ladder the contract pays - function renderSteps(d) { - const el = $('ncSteps'); - if (!el) return; - const b = d.buyerCount || 0; - const steps = [ - { label: 'Joined', sub: 'free account', hit: true }, - { label: 'Spark', sub: 'payouts on', hit: !!d.memberId }, - { label: 'Surge', sub: 'first buyer · 50%', hit: b >= 1 }, - { label: 'Circuit', sub: '2 buyers · +20%', hit: b >= 2 }, - { label: 'Nexus', sub: '5 buyers · +10%', hit: b >= 5 } - ]; - const cur = steps.findIndex(s => !s.hit); - el.innerHTML = steps.map((s, i) => - '
' - + '' + (s.hit ? '✓' : i + 1) + '' - + '' + s.label + '' + s.sub + '
').join(''); - } - // ── overview v3 charts: hand-rolled SVG/CSS, real data only ── - const esc = s => String(s == null ? '' : s).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c])); - const CH = { mint: '#3b9dff', cyan: '#54ccff', violet: '#9d7dff', amber: '#ffb238', track: 'rgba(139,166,156,.18)' }; - function bars(el, xel, data) { // data: [{v,label,tip,alt}] - if (!el) return; - const max = Math.max(1, ...data.map(d => d.v)); - el.innerHTML = data.length - ? data.map(d => '
').join('') - : '
'.repeat(8); - if (xel) xel.innerHTML = data.map(d => '' + esc(d.label) + '').join(''); - } - function donut(el, segs, center) { // segs sum to the ring; r=15.9155 → circumference 100 - if (!el) return; - const total = segs.reduce((s, x) => s + x.v, 0); - let off = 25, out = ''; - if (total > 0) for (const s of segs) { - const len = s.v / total * 100; - if (len <= 0 || s.color === 'none') { off -= Math.max(0, len); continue; } - out += ''; - off -= len; - } - out += '' + esc(center.big) + '' - + '' + esc(center.small) + ''; - el.innerHTML = out; - } - function legend(el, rows) { - if (el) el.innerHTML = rows.map(r => '
' - + esc(r.label) + ' ' + esc(r.v) + '
').join(''); - } - async function loadCharts(d) { - // credit composition donut + today's viewing ring (live balances) - try { - const st = await (await fetch('/api/my/earn')).json(); - if (!st.error) { - // one rule: a balance is what is NOT committed to a live campaign. Budgets are - // set aside when a campaign starts and spend down inside Campaigns, so these - // numbers only move when a campaign is created, topped up or paused - const purchased = d.credits || 0, earned = d.earnedCredits != null ? d.earnedCredits : (st.earnedAvailable != null ? st.earnedAvailable : (st.earned || 0)), inC = d.inCampaigns || 0; - $('dbCredits').textContent = (purchased + earned).toLocaleString(); - // the Wallet tab card showed on-chain credits only, so promo/earned credits looked like 0 there (Jim, 2026-09-13) - if ($('creditLine')) $('creditLine').innerHTML = (purchased + earned).toLocaleString() + ' ' + purchased.toLocaleString() + ' purchased · ' + earned.toLocaleString() + ' earned'; - $('dbCreditsSub').textContent = purchased.toLocaleString() + ' purchased' + (d.creditedCredits ? ' (' + d.creditedCredits.toLocaleString() + ' credited to you)' : '') + ' · ' + earned.toLocaleString() + ' earned' + (inC ? ' · ' + inC.toLocaleString() + ' in campaigns' : ''); - donut($('chDonut'), - [{ v: purchased, color: CH.mint }, { v: earned, color: CH.cyan }, { v: inC, color: CH.amber }], - { big: (purchased + earned).toLocaleString(), small: 'available' }); - legend($('chDonutLegend'), [ - { color: CH.mint, label: 'Purchased, available', v: purchased.toLocaleString() }, - { color: CH.cyan, label: 'Earned, available', v: earned.toLocaleString() }, - { color: CH.amber, label: 'In live campaigns', v: inC.toLocaleString() }]); - const done = Math.min(st.views || 0, st.target || 5), left = Math.max(0, (st.target || 5) - done); - donut($('chRing'), [{ v: done, color: st.claimed ? CH.mint : CH.cyan }, { v: left, color: 'none' }], - { big: done + '/' + (st.target || 5), small: st.claimed ? 'claimed' : 'ads viewed' }); - legend($('chRingLegend'), [ - { color: st.claimed ? CH.mint : CH.cyan, label: 'Viewed today', v: done }, - { color: CH.track, label: 'To go', v: left }, - { color: CH.amber, label: 'Claim pays', v: '+' + (st.claimCredits || 0) + ' credits' }]); - } - } catch (e) {} - // recent on-chain payouts, sized to scale, oldest→newest - try { - let evs = []; - if (d.memberId) { - const a = await (await fetch('/api/my/activity')).json(); - evs = (a.earnings || []).filter(e => e.amountWei).sort((x, y) => x.block - y.block).slice(-12); - } - bars($('chEarnBars'), $('chEarnX'), evs.map(e => ({ - v: Number(BigInt(e.amountWei) / 1000000000000n) / 1e6, - label: e.type === 'AwardPaid' ? 'award' : 'L' + (e.tier || 1), - tip: IAP.fmtPol(e.amountWei) + ' POL', alt: e.type === 'AwardPaid' }))); - if (!evs.length) $('chEarnSub').textContent = d.memberId - ? 'no payouts yet — share your link' : 'activate a package to start earning'; - } catch (e) {} - // campaign delivery: impressions per campaign - try { - const r = await (await fetch('/api/my/campaigns')).json(); - const cs = (r.campaigns || []).slice(0, 8); - bars($('chCampBars'), $('chCampX'), cs.map(c => ({ - v: c.imps || 0, label: String(c.name || c.type).slice(0, 9), - tip: (c.name || c.type) + ': ' + (c.imps || 0) + ' imps · ' + (c.clicks || 0) + ' clicks', - alt: c.type === 'text' }))); - if (!cs.length) $('chCampSub').textContent = 'no campaigns yet — place your first ad'; - } catch (e) {} - } - // ── live updates: subscribe to the chain event stream so the members area - // reacts to on-chain changes (payouts, qualifications) without a refresh ── - let MYID = 0; - // synthesized sounds (no asset files; CSP-safe). cha-ching on a payment, pop on a message. - function playSound(kind) { - try { - const AC = window.AudioContext || window.webkitAudioContext; if (!AC) return; - const ctx = window.__iapAC || (window.__iapAC = new AC()); - if (ctx.state === 'suspended') ctx.resume(); - const now = ctx.currentTime; - const tone = (freq, at, dur, type, peak) => { - const o = ctx.createOscillator(), g = ctx.createGain(); - o.type = type || 'sine'; o.frequency.value = freq; - g.gain.setValueAtTime(0.0001, now + at); - g.gain.exponentialRampToValueAtTime(peak || 0.22, now + at + 0.02); - g.gain.exponentialRampToValueAtTime(0.0001, now + at + dur); - o.connect(g).connect(ctx.destination); o.start(now + at); o.stop(now + at + dur + 0.02); - }; - if (kind === 'chaching') { tone(1318, 0, 0.34, 'sine', 0.25); tone(1760, 0.09, 0.4, 'sine', 0.25); } - else { tone(680, 0, 0.16, 'triangle', 0.18); tone(1020, 0.05, 0.16, 'triangle', 0.16); } - } catch (e) {} - } - function startLiveFeed() { - if (window.__iapFeed || !window.EventSource) return; - try { - const es = new EventSource('/api/feed/live'); - window.__iapFeed = es; - es.onmessage = m => { let ev; try { ev = JSON.parse(m.data); } catch (e) { return; } handleLiveEvent(ev); }; - // browser auto-reconnects on error; nothing to do - } catch (e) {} - } - let liveRefreshT = null; - function liveRefresh() { // debounce a burst of events into one refresh - clearTimeout(liveRefreshT); - liveRefreshT = setTimeout(() => { loadDashboard(); try { loadLineage(); } catch (e) {} }, 600); - } - // community toasts (Marty, 2026-09-12: keep the dashboard feeling alive): everyone else's joins, - // purchases, payouts, qualifications, tank arrivals and adoptions, in a second, quieter toast so - // they never replace a personal one. At most one every 4 s; a burst shows the latest. - let liveT = 0, liveQ = null; - function communityToast(msg) { - const now = Date.now(); - if (now - liveT < 4000) { liveQ = msg; if (!communityToast._q) communityToast._q = setTimeout(() => { communityToast._q = null; const m = liveQ; liveQ = null; if (m) communityToast(m); }, 4200 - (now - liveT)); return; } - liveT = now; - let el = document.getElementById('liveToast'); - if (!el) { el = document.createElement('div'); el.id = 'liveToast'; el.setAttribute('role', 'status'); el.style.cssText = 'position:fixed;left:16px;bottom:16px;z-index:90;max-width:min(360px,calc(100vw - 32px));background:var(--panel-solid);border:1px solid var(--line-strong);border-left:3px solid var(--mint);border-radius:12px;padding:10px 14px;font-size:14px;box-shadow:0 10px 30px rgba(0,0,0,.4);transition:opacity .3s'; document.body.appendChild(el); } - el.textContent = msg; el.hidden = false; el.style.opacity = '1'; - clearTimeout(communityToast._t); communityToast._t = setTimeout(() => { el.style.opacity = '0'; setTimeout(() => { el.hidden = true; }, 350); }, 6000); - } - function handleLiveEvent(ev) { - if (!ev || !ev.type) return; - const nm = id => (ev.names && ev.names[id]) ? '@' + ev.names[id] : 'member #' + id; - // site-wide activity (not about me): joins, tank, adoptions, purchases, payouts, qualifications - if (ev.type === 'Joined') { communityToast('👋 ' + ev.name + ' just joined' + (ev.tank ? ' and is waiting for a sponsor in the holding tank' : '')); liveRefresh(); return; } - if (ev.type === 'Adopted') { communityToast('🤝 ' + ev.sponsor + ' picked up ' + ev.member + ' from the holding tank'); liveRefresh(); return; } - if (ev.type === 'Contest') { communityToast('🏆 ' + ev.winner + ' won the ' + (ev.kind === 'week' ? 'weekly' : 'monthly') + ' referral contest'); return; } - if (ev.type === 'Badge') { communityToast('🏆 ' + ev.member + ' unlocked ' + ev.label); return; } - if (ev.type === 'Released') { communityToast('🪣 ' + ev.sponsor + ' returned ' + ev.member + ' to the holding tank'); liveRefresh(); return; } - const mine = MYID && (ev.recipientId === MYID || ev.toId === MYID || ev.sponsorId === MYID || ev.skippedId === MYID || ev.buyerId === MYID); - if (!mine) { - if (ev.type === 'Purchase' && ev.buyerId) communityToast('🧾 ' + nm(ev.buyerId) + ' just bought a $' + Math.round((ev.priceCents || 0) / 100) + ' package'); - else if (ev.type === 'TierPaid' && ev.recipientId) communityToast('💸 ' + nm(ev.recipientId) + ' just got paid ' + IAP.fmtPol(ev.amountWei) + ' POL'); - else if (ev.type === 'BuyerCounted' && ev.sponsorId) communityToast('🎯 ' + nm(ev.sponsorId) + ' now has ' + ev.newCount + ' qualifying buyer' + (ev.newCount === 1 ? '' : 's')); - else if (ev.type === 'MemberActivated' && ev.id) communityToast('⚡ ' + nm(ev.id) + ' switched on payouts'); - return; - } - if (!MYID) return; - let toast = null, kind = 'ok'; - let sound = null; - if (ev.type === 'TierPaid' && ev.recipientId === MYID) { toast = '💸 You earned a level-' + ev.tier + ' payout of ' + IAP.fmtPol(ev.amountWei) + ' POL!'; sound = 'chaching'; } - else if (ev.type === 'AwardPaid' && ev.toId === MYID) { toast = '💸 You received ' + IAP.fmtPol(ev.amountWei) + ' POL!'; sound = 'chaching'; } - else if (ev.type === 'BuyerCounted' && ev.sponsorId === MYID) toast = '🎯 A referral just qualified — you now have ' + ev.newCount + ' qualifying buyer' + (ev.newCount === 1 ? '' : 's') + '!'; - else if (ev.type === 'PassedUp' && ev.skippedId === MYID) { toast = '⚠️ A level-' + ev.tier + ' payout passed you by. Get qualified to catch these.'; kind = 'bad'; } - else if (ev.type === 'Purchase' && ev.buyerId === MYID) toast = '✅ Purchase settled on-chain — your credits are updated.'; - else if (ev.type === 'MemberActivated' && ev.sponsorId === MYID) toast = '🤝 A new member just activated in your line!'; - if (toast) { IAP.status(toast, kind); if (sound) playSound(sound); liveRefresh(); } - } - - // training center: videos + materials (admin-curated via data/training.json) - async function loadTraining() { - try { - const r = await (await fetch('/api/training')).json(); - const el = $('trainingList'); if (!el) return; - const items = r.items || []; - if (!items.length) { el.innerHTML = '

Training materials are being added. Check back soon.

'; return; } - // section pills at the top: one per group, plus All; the active pill filters the list - const groups = [...new Set(items.map(it => it.group).filter(Boolean))]; - const pills = $('trainingPills'); - const want = loadTraining.filter || 'all'; - if (pills) { - pills.hidden = groups.length < 2; - pills.innerHTML = ['all', ...groups].map(g => '').join(''); - pills.querySelectorAll('[data-tg]').forEach(b => b.addEventListener('click', () => { loadTraining.filter = b.dataset.tg; loadTraining(); })); - } - const shown = want === 'all' ? items : items.filter(it => it.group === want); - let lastGroup = null; - el.innerHTML = shown.map(it => { - // optional section header: entries carry a `group`; a header renders when it changes - let head = ''; - if (it.group && it.group !== lastGroup) { lastGroup = it.group; head = '

' + esc(it.group) + '

'; } - const isVid = it.videoUrl && /\.(mp4|webm)(\?|$)/i.test(it.videoUrl); - // poster: the admin list can carry one; otherwise assume a .jpg next to the .mp4 (the pipeline uploads both) - const poster = it.posterUrl || (isVid ? it.videoUrl.replace(/\.(mp4|webm)(\?.*)?$/i, '.jpg$2') : ''); - const media = isVid ? '' : ''; - const links = []; - if (it.videoUrl && !isVid) links.push('Watch'); - if (it.docUrl) links.push('Open material'); - return head + '

' + esc(it.title || 'Lesson') + '

' - + (it.desc ? '

' + esc(it.desc) + '

' : '') - + (media ? '

' + media + '

' : '') - + (links.length ? '

' + links.join(' ') + '

' : '') + '
'; - }).join(''); - } catch (e) {} - } - // visual line tree on the Overview: YOU + three levels, qualified directs in gold - async function loadLineTree(buyerCount) { - try { - const r = await (await fetch('/api/my/line')).json(); - const el = $('lineTree'); if (!el) return; - const levels = r.levels || []; - const total = levels.reduce((n, L) => n + L.members.length, 0); - if ($('treeSub')) $('treeSub').textContent = total ? total + ' across 3 levels' : 'share your link to grow'; - const chip = (m, q) => '' + esc(String(m.name || 'M').replace(/^@/, '').slice(0, m.own ? 20 : 14)) + (m.buyers ? '' + m.buyers + '' : '') + ''; - const rowFor = lvl => { - const L = levels.find(x => x.level === lvl); const members = L ? L.members : []; - // gold = the contract counted this member as one of your qualifying buyers (not "the first N chips") - let html = members.map(m => chip(m, !!(m.qualified || m.bought))).join(''); // gold on every level = made their $20+ buy - if (lvl <= 2 && members.length < (lvl === 1 ? 2 : 4)) html += '+ open'; - if (!html) html = '+ open'; - return '
L' + lvl + '
' + html + '
'; - }; - el.innerHTML = '
YOU
' + rowFor(1) + rowFor(2) + rowFor(3); - } catch (e) {} - } - // "What's new" card: latest notes + what is being built; a dot marks notes newer than the member's last look (Marty, 2026-09-14) - let newsLoaded = false; - async function loadNews() { - if (newsLoaded || !$('newsCard')) return; newsLoaded = true; - try { - const r = await (await fetch('/api/releases')).json(); - if (!r.notes.length && !r.roadmap.length) return; - let seen = ''; try { seen = localStorage.getItem('iap.news.seen') || ''; } catch (e) {} - const esc = t => String(t == null ? '' : t).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c])); - const notes = r.notes.slice(0, 3).map(n => '

' + (n.date > seen ? '● ' : '') + '' + esc(n.title) + ' ' + esc(n.date) + '

').join(''); - const rm = r.roadmap.filter(x => x.status === 'building').slice(0, 2).map(x => '

Building: ' + esc(x.title) + (x.eta ? ' (' + esc(x.eta) + ')' : '') + '

').join(''); - $('newsList').innerHTML = notes + rm + '

All release notes and the roadmap →

'; - $('newsCard').hidden = false; - $('newsCard').addEventListener('click', () => { try { localStorage.setItem('iap.news.seen', r.latest || ''); } catch (e) {} $('newsList').querySelectorAll('span[style*="mint"]').forEach(s => { if (s.textContent === '●') s.remove(); }); }, { once: true }); - } catch (e) {} - } - // Leaderboard card: top 5 this week + your own rank + the prize (Marty, 2026-09-14) - async function loadLeaderboard() { - if (!$('lbCard')) return; - try { - const r = await (await fetch('/api/leaderboard?period=week')).json(); - const esc = t => String(t == null ? '' : t).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c])); - let h = r.prize ? '

Prize this week: ' + esc(r.prize) + '

' : ''; - h += r.top.length ? '' + r.top.slice(0, 5).map(x => '').join('') + '
' + x.rank + '' + esc(x.name) + '' + x.sales + ' sold · $' + x.usd + '
' - : '

No packages sold yet this week. First sale takes the top spot.

'; - h += r.me ? '

You: #' + r.me.rank + ' · ' + r.me.sales + ' sold · $' + r.me.usd + '

' : '

You: no sales yet this week. Sales are $20+ packages bought by people you sponsor.

'; - h += '

Full leaderboard: week, month, all time →

'; - $('lbList').innerHTML = h; $('lbCard').hidden = false; - } catch (e) {} - } - // Getting-started stepper: username -> wallet -> payouts -> first package. The current step gets one big - // button that opens the right tab and pulses the control (Jim: "it wasn't obvious", 2026-09-14) - function renderSteps(d) { - const card = $('gsCard'); if (!card) return; - const hasUser = !!d.username, hasWallet = !!d.address, hasPayouts = !!d.memberId, hasPackage = !!(d.memberId && (d.credits || 0) > 0); - const steps = [ - { k: 'user', t: 'Pick a username', done: hasUser }, - { k: 'wallet', t: 'Link your wallet', done: hasWallet }, - { k: 'payouts', t: 'Switch on payouts', done: hasPayouts }, - { k: 'package', t: 'Your first package', done: hasPackage } - ]; - if (steps.every(x => x.done)) { card.hidden = true; return; } - const cur = steps.find(x => !x.done); - let collapsed = false; try { collapsed = localStorage.getItem('iap.gs.collapsed') === '1'; } catch (e) {} - $('gsSub').innerHTML = steps.filter(x => x.done).length + ' of 4 done · ' + (collapsed ? 'show' : 'hide') + ''; - $('gsToggle').addEventListener('click', e => { e.preventDefault(); try { localStorage.setItem('iap.gs.collapsed', collapsed ? '0' : '1'); } catch (er) {} renderSteps(d); }); - $('gsSteps').hidden = collapsed; $('gsNow').hidden = collapsed; - $('gsSteps').innerHTML = steps.map((x, i) => '
' + (x.done ? '✓' : i + 1) + '' + x.t + '
').join(''); - const copy = { - user: ['Pick your username', 'It becomes your invite link and your public page, and it is permanent.', 'Choose a username', () => showOnboard(true)], - wallet: ['Link your wallet', 'Your payouts land in a wallet you control, so the site needs to know which one is yours. One free signature, no purchase. MetaMask recommended; Phantom users switch Polygon on first. Never held crypto? The wallet guide walks you through it.', 'Link my wallet', () => jumpTo('wallet', 'linkBtn')], - payouts: ['Switch on payouts', 'One small transaction registers your wallet with the contract so commissions can reach it. Buying any package does this automatically.', 'Activate payouts', () => jumpTo('wallet', 'activateBtn')], - package: ['Your first package', 'From $5. The $20 Activation package is the one that counts you as a qualifying buyer for your sponsor and unlocks adopting from the holding tank.', 'See packages', () => jumpTo('buy', null)] - }[cur.k]; - $('gsNow').innerHTML = '

Next: ' + copy[0] + '' + copy[1] + (cur.k === 'wallet' ? ' Wallet guide' : '') + '

'; - $('gsGo').addEventListener('click', copy[3]); - card.hidden = false; - } - function jumpTo(pane, id) { - setPane(pane); - setTimeout(() => { const el = id && $(id); if (!el) return; el.scrollIntoView({ behavior: 'smooth', block: 'center' }); el.classList.remove('pulse'); void el.offsetWidth; el.classList.add('pulse'); try { el.focus({ preventScroll: true }); } catch (e) {} }, 250); - } - async function loadDashboard() { - try { - loadNews(); loadLeaderboard(); - const d = await (await fetch('/api/my/dashboard')).json(); - if (d.error) return; - chatSync(d); - try { renderSteps(d); } catch (e) {} - MYID = d.memberId || MYID; - startLiveFeed(); - if (!window.__lbChecked) { // daily login bonus, once per session (server guards once/day) - window.__lbChecked = true; - api('/api/my/login-bonus').then(r => { - if (r && r.granted > 0) { - IAP.status('🎁 Daily login bonus: +' + r.granted + ' credits' + (r.streak > 1 ? ' · ' + r.streak + '-day streak' : '') + '!', 'ok'); - playSound('chaching'); setTimeout(loadDashboard, 900); - } - }).catch(() => {}); - } - const earnedAv = d.earnedCredits || 0, inCamp = d.inCampaigns || 0; - $('dbCredits').textContent = ((d.credits || 0) + earnedAv).toLocaleString(); - $('dbCreditsSub').textContent = (d.credits || 0).toLocaleString() + ' purchased' + (d.creditedCredits ? ' (' + d.creditedCredits.toLocaleString() + ' credited to you)' : '') + ' · ' + earnedAv.toLocaleString() + ' earned' + (inCamp ? ' · ' + inCamp.toLocaleString() + ' in campaigns' : ''); - $('dbEarned').textContent = IAP.fmtPol(d.earnedWei || '0'); - $('dbBuyers').textContent = d.buyerCount || 0; if (d.buyerCountPositions) { const sub = $('dbBuyersSub'); if (sub) sub.textContent = '+' + d.buyerCountPositions + ' on your linked positions (count toward badges; levels pay on your main position)'; } - $('dbTeam').textContent = (d.referrals || []).length; - // trend chips: only real, computable facts - const ec = $('dbEarnedChip'); - if (ec && d.earnCount) { ec.hidden = false; ec.textContent = d.earnCount + ' instant payout' + (d.earnCount > 1 ? 's' : ''); } - const bc = $('dbBuyersChip'); - if (bc && d.memberId) { - bc.hidden = false; - bc.textContent = (d.buyerCount || 0) >= 5 ? 'level 3 open' : (d.buyerCount || 0) >= 2 ? 'level 2 open' : 'level 2 at 2 buyers'; - } - const tc = $('dbTeamChip'), wk = (d.referrals || []).filter(r => Date.now() - new Date(r.joined) < 6048e5).length; - if (tc && wk) { tc.hidden = false; tc.textContent = '+' + wk + ' this week'; } - setInboxBadge(d.inboxUnread || 0); - if (d.sponsorMsg) showSponsorModal(d.sponsorMsg); - renderBadges(d); - loadFeatured(); - loadLineTree(d.buyerCount || 0); - loadCharts(d); - $('nextMove').textContent = nextMove(d); - renderSteps(d); - const wrap = $('rosterWrap'); - if ((d.referrals || []).length) { - $('rosterEmpty').hidden = true; - let t = wrap.querySelector('table'); - if (t) t.remove(); - t = document.createElement('table'); - t.className = 'roster'; - t.innerHTML = d.referrals.map(r => '' + String(r.name || r.email || '').replace(/[&<>]/g, '') + '' - + '' + new Date(r.joined).toLocaleDateString() + '' - + '' + r.status + '').join(''); - wrap.appendChild(t); - } - // overview recent-activity widget: chain events + line joins, newest first - try { - const c = await IAP.getConfig(); - const ov = $('ovFeed'); - const rows = []; - if (d.memberId) { - const a = await (await fetch('/api/my/activity')).json(); - for (const ev of [...(a.earnings || []), ...(a.purchases || [])] - .sort((x, y) => y.block - x.block).slice(0, 5)) rows.push(IAP.feedRow(ev, c)); - } - for (const r of (d.referrals || []).slice(0, 3)) { - const div = document.createElement('div'); - div.className = 'row'; - div.innerHTML = '🤝 ' + esc(r.name || r.email || 'A new member') + ' joined your line' - + new Date(r.joined).toLocaleDateString() + ''; - rows.push(div); - } - if (rows.length) { - ov.innerHTML = ''; - rows.slice(0, 6).forEach(r => ov.appendChild(r)); - } - } catch (e) {} - // ready-to-send share message + promo tools, personalized - const link = location.origin + '/join/' + (d.username || d.refCode || d.memberId || ''); - fillPromo(link, d); - // founding-week readiness: shown until every item is done (or the launch moment is a week past) - try { - const cfg = await IAP.getConfig(); const items = IAP.launchChecks(d); const done = items.filter(i => i.done).length; - const at = cfg.launchAt ? new Date(cfg.launchAt).getTime() : 0; - const show = done < items.length && !(at && Date.now() > at + 7 * 86400000); - const lm = $('launchMark'); - if (lm) { lm.hidden = !show; lm.innerHTML = show ? 'Launch ready: ' + done + ' of ' + items.length + '. ' + (at && Date.now() < at ? 'Doors open ' + new Date(at).toLocaleString([], { weekday: 'short', hour: 'numeric', minute: '2-digit' }) + '. ' : '') + 'Open the founding-week checklist' : ''; } - } catch (e) {} - // people waiting for a sponsor in the holding tank (Marty, 2026-09-12): every Overview sees it - try { - const tw = d.tankWaiting, tn = $('tankNotice'); - if (tn) { - tn.hidden = !(tw && tw.count); - if (tw && tw.count) tn.innerHTML = '' + tw.count + (tw.count === 1 ? ' person is' : ' people are') + ' waiting for a sponsor in the holding tank \u00b7 ' - + tw.names.map(esc).join(', ') + (tw.count > tw.names.length ? ' and more' : '') + '. Adopt them from My line' - + (tw.eligible ? '.' : ' (you need your own $20 package first).'); - } - } catch (e) {} - if (d.username) { // wall link rides the username - const wl = location.origin + '/wall/' + d.username; - $('wallLine').textContent = wl; - if ($('promoWallStrip')) { // the same wall link at the top of Promo tools, next to the invite link - $('promoWallStrip').hidden = false; $('promoWallLink').textContent = wl; $('promoWallOpen').href = '/wall/' + d.username; - $('promoWallCopy').onclick = async () => { try { await navigator.clipboard.writeText(wl); IAP.status('Wall link copied.', 'ok'); } catch (e) { IAP.status('Copy failed. Select the link and copy it.', 'bad'); } }; - } - $('wallCopy').hidden = false; - $('wallOpen').hidden = false; - $('wallOpen').href = '/wall/' + d.username; - $('wallCopy').onclick = async () => { - try { await navigator.clipboard.writeText(wl); IAP.status('Wall link copied.', 'ok'); } - catch (e) { IAP.status('Copy failed. Select the link text instead.', 'bad'); } - }; - } - if (d.refCode || d.memberId) { - const pitch = 'I found an advertising site that pays referrals instantly to your own wallet. ' - + 'No withdrawals, no waiting, and every payment is public on a blockchain ledger you can check yourself. ' - + 'Free to join and look around: ' + link; - $('copyPitch').hidden = false; - $('pitchPreview').hidden = false; - $('pitchPreview').textContent = '"' + pitch + '"'; - $('copyPitch').onclick = async () => { - try { await navigator.clipboard.writeText(pitch); IAP.status('Message copied. Paste it anywhere.', 'ok'); } - catch (e) { IAP.status('Copy failed. Select the preview text instead.', 'bad'); } - }; - } - } catch (e) {} - } - - // ── back-office menu: hash-routed panes ─────────────── - const PANES = ['overview', 'line', 'pipeline', 'rotator', 'buy', 'campaigns', 'earn', 'earnings', 'promo', 'training', 'wallet', 'profile']; - const TITLES = { overview: 'Start', line: 'My line', pipeline: 'Pipeline', rotator: 'Rotator', buy: 'Buy packages', campaigns: 'Campaigns', - earn: 'Earn credits', earnings: 'Earnings', promo: 'Promo tools', training: 'Training', - wallet: 'Wallet & account', profile: 'Profile' }; - const MOVED = { buy: '/credits', rotator: '/links', campaigns: '/ads', earn: '/ads', earnings: '/credits', wallet: '/wallet' }; // control-room screens (2026-10-08) - function setPane(name) { - if (MOVED[name]) { location.replace(MOVED[name]); return; } - if (!PANES.includes(name)) name = 'overview'; - for (const p of PANES) { - const el = $('pane-' + p); - if (el) el.hidden = p !== name; - } - document.querySelectorAll('.bo-menu [data-pane]').forEach(b => - b.classList.toggle('on', b.dataset.pane === name)); - if ($('boTitle')) $('boTitle').textContent = TITLES[name]; - { const h1 = document.querySelector('.topbar h1'); if (h1 && TITLES[name]) h1.textContent = TITLES[name]; } - // member ads: a fresh text ad in the strip under the title, and a banner at the foot of the pane - IAP.adSlot('text', 'adStripTop'); - if ($('adSlotPane-' + name)) IAP.adSlot('banner', 'adSlotPane-' + name); - if (name === 'earn') setEarnSub(earnSub); // refresh whichever sub-tab is active - else if (vidState.token) stopVideo(); - if (name === 'profile') loadLineBanner(); - if (name === 'line') { loadLineage(); loadUplineMessages(); loadCoach(); loadLinkStats(); loadProspects(); } - if (name === 'campaigns') ['cTarget', 'cImage', 'cVideoUrl'].forEach(id => { if ($(id)) $(id).value = ''; }); // no residual URL between visits - if (name === 'training') loadTraining(); - if (name === 'pipeline') loadPipeline(); - if (name === 'rotator') loadRotator(); - document.getElementById('memberArea').classList.remove('side-open'); // close mobile drawer - if (location.hash !== '#' + name) history.replaceState(null, '', '#' + name); - } - document.querySelectorAll('.bo-menu [data-pane]').forEach(b => - b.addEventListener('click', () => setPane(b.dataset.pane))); - document.querySelectorAll('.qa [data-goto]').forEach(b => - b.addEventListener('click', () => setPane(b.dataset.goto))); - const qaCopy = document.getElementById('qaCopyInvite'); - if (qaCopy) qaCopy.addEventListener('click', async () => { - const link = document.getElementById('inviteLine').textContent; - if (!link || !link.startsWith('http')) { setPane('line'); return; } - try { await navigator.clipboard.writeText(link); IAP.status('Invite link copied.', 'ok'); } - catch (e) { setPane('line'); } - }); - window.addEventListener('hashchange', () => setPane(location.hash.slice(1))); - if ($('boBurger')) $('boBurger').addEventListener('click', () => - document.getElementById('memberArea').classList.toggle('side-open')); - - async function render() { - // while /api/me answers, show a spinner instead of flashing the sign-in card at a signed-in member - let me = null; - try { me = await IAP.refreshNavWallet(); } catch (e) { me = null; } - if ($('bootSpin')) $('bootSpin').hidden = true; - // one way in: email. A wallet-only session (no account) is sent back to the - // email card with a finish-setup note; verifying the code links that wallet. - const walletOnly = !!(me && me.signedIn && !me.email); - const signedIn = me && me.signedIn && !walletOnly; - // signed out: the Control Room sign-in dialog (the old email card only serves the wallet-only finish-setup case) - $('authArea').hidden = !!signedIn || !walletOnly; - $('memberArea').hidden = !signedIn; - if ($('mcFinish')) $('mcFinish').hidden = !walletOnly; - if (!signedIn && !walletOnly && window.CR) { // the Control Room shell runs the sign-in dialog; render again once it reports a session - if (window.LS_SESSION_READY && (render.retries = (render.retries || 0) + 1) < 6) { setTimeout(render, 400); } - else if (!render.waiting) { render.waiting = true; window.addEventListener('ls:session', () => { render.waiting = false; render(); }, { once: true }); } - } - if (!signedIn) return; - if ($('adminLink')) $('adminLink').hidden = !me.isAdmin; // admin portal link, only for ADMIN_EMAIL - // REQUIRED first step (Marty, 2026-09-12): no username, nothing else. The modal cannot be - // skipped or dismissed; it resolves only when a username is saved, then the area renders. - if (!me.username) { - if (!render.gating) { render.gating = true; showOnboard(true).then(() => { render.gating = false; render(); }); } - return; - } - // arrived from an invite page: run the welcome tour and login ad once - if (/[?&]welcome=1/.test(location.search) && !render.welcomed) { - render.welcomed = true; - history.replaceState(null, '', '/tools' + (location.hash || '')); - (async () => { - try { if (!(await showGauntlet())) await showLoginAd(); } catch (e) {} - await render(); - })(); - } - setPane(location.hash.slice(1) || 'overview'); - $('campGate').hidden = !!me.memberId; - $('earnGate').hidden = !!me.memberId; - if (me.username && !me.address) { let shown = ''; try { shown = sessionStorage.getItem('iap.gs.walletHint'); sessionStorage.setItem('iap.gs.walletHint', '1'); } catch (e) {} if (shown !== '1') setTimeout(() => IAP.status('Next step when you are ready: link your wallet so your payouts have somewhere to land. The Getting started card at the top shows how.', 'ok'), 1200); } - loadDashboard(); - - const who = []; - if (me.email) who.push(me.email); - // members kept asking whether the wallet was really connected (Marty, 2026-09-12): say it, with a green check - if (me.address) who.push('Wallet connected ' + me.address.slice(0, 8) + '…' + me.address.slice(-6) + ''); - else who.push('No wallet connected yet (link one below)'); - if (me.memberId) who.push('on-chain member #' + me.memberId + '' - + (me.onchainSponsorId ? ', sponsored by #' + me.onchainSponsorId : '')); - else if (me.sponsorId) who.push('invited by member #' + me.sponsorId); - $('posLine').innerHTML = who.join('
'); - - $('creditLine').textContent = (me.credits || 0).toLocaleString(); - loadPositions(me); - $('linkCard').hidden = !!me.address; - $('activateCard').hidden = !(me.address && !me.memberId); - $('activityArea').hidden = !me.memberId; - $('campGate').hidden = true; // earned credits fund campaigns for everyone - $('campaignCard').hidden = false; - loadCampaigns(); - - // profile pane state - $('pfCurrent').textContent = me.username ? '@' + me.username + ' is your permanent username. Your invite link, your public page and any banners you shared carry it, so it cannot be changed.' : 'No username yet. Members see you as a number until you pick one. Choose carefully: it is permanent once saved.'; - if (!$('pfUsername').value) $('pfUsername').value = me.username || ''; - $('pfUsername').disabled = !!me.username; $('pfSaveBtn').hidden = !!me.username; - $('pfDetails').innerHTML = 'Email: ' + (me.email || 'none') + '
Wallet: ' - + (me.address ? '' + me.address.slice(0, 10) + '…' + me.address.slice(-6) + '' : 'not linked yet') - + '
On-chain member: ' + (me.memberId ? '#' + me.memberId : 'not yet'); - // the share link works from day one; usernames make it a vanity link - if (me.username || me.refCode || me.memberId) { - $('inviteLine').textContent = location.origin + '/join/' + (me.username || me.refCode || me.memberId); - $('copyInvite').hidden = false; - } else { - $('inviteLine').textContent = 'Sign in with your email to get your link.'; - $('copyInvite').hidden = true; - } - if (me.memberId) { - const bc = me.buyerCount || 0; - $('qualLine').innerHTML = '' + bc + ' qualifying buyer(s) referred
' - + (bc >= 5 ? 'Level 3 unlocked: full three-level earnings' - : bc >= 2 ? 'Level 2 unlocked · ' + (5 - bc) + ' more for level 3' - : (2 - bc) + ' more buyer(s) of $20+ unlock level 2'); - loadActivity(); - } else { - $('qualLine').innerHTML = 'Share your link now. Then switch on payouts (free, above) ' - + 'before your people start buying: the contract locks each buyer to their sponsor at ' - + 'their first purchase, and payments only route to wallets that are switched on.'; - } - } - - async function loadActivity() { - try { - const c = await IAP.getConfig(); - const a = await (await fetch('/api/my/activity')).json(); - const fill = (id, evs, empty) => { - const el = $(id); - el.innerHTML = ''; - if (!evs || !evs.length) { el.innerHTML = '
' + empty + '
'; return; } - for (const ev of evs) el.appendChild(IAP.feedRow(ev, c)); - }; - fill('earnFeed', a.earnings, 'No payouts yet. They appear here the moment one lands.'); - fill('refFeed', a.referrals, 'No referral activity yet. Share your invite link.'); - fill('buyFeed', a.purchases, 'No purchases from your wallet yet.'); - } catch (e) {} - } - - async function loadCampaigns() { - try { - const r = await (await fetch('/api/my/campaigns')).json(); - if (r.error) return; - lastRates = r.rates; - if ($('cGeoHint') && r.tiers) $('cGeoHint').textContent = 'All three ticked = everyone. Tier 1: ' + r.tiers.t1.join(', ') + '. Tier 2: ' + r.tiers.t2.join(', ') + '. Tier 3: every other country. Geo applies to delivery on this site; a narrowed banner or text ad is kept off the worldwide partner network. ' + (r.geoReady ? '' : 'Country data is still loading, so narrowed campaigns pause until it is ready. ') + 'IP geolocation by DB-IP.'; - // populate the banner-size dropdown once (ids map to NAS width/height) - if (r.bannerSizes && $('cSize') && !$('cSize').options.length) - $('cSize').innerHTML = r.bannerSizes.map(s => '').join(''); - applyType(); // the default type is banner: show its size + image rows now that the sizes exist - soloHint(); - if ($('spendBanner')) { - $('spendBanner').hidden = false; - $('spendBig').textContent = r.availableCredits.toLocaleString(); - $('spendSub').textContent = '= $' + (r.availableCredits / 100).toLocaleString(undefined, { maximumFractionDigits: 2 }) + ' of ad delivery · ' + r.purchasedCredits.toLocaleString() + ' purchased' + (r.creditedCredits ? ' (' + r.creditedCredits.toLocaleString() + ' of it credited to you, spends on anything)' : '') + ' + ' + (r.earnedCredits || 0).toLocaleString() + ' earned' + (r.positionCount > 1 ? ' · pooled across ' + r.positionCount + ' positions (largest single position ' + (r.largestPosition || 0).toLocaleString() + ')' : ''); - if ($('spendNote')) $('spendNote').textContent = r.inCampaigns - ? 'Not counting ' + r.inCampaigns.toLocaleString() + ' credits already set aside for your live campaigns. That budget spends down inside each campaign below. This number only moves when you start, top up or pause a campaign.' - : 'This is what is not committed to a campaign. When you start one, its budget moves out of here and spends down inside the campaign.'; - $('spendRates').innerHTML = [['Banner', r.rates.bannerCreditsPerBatch + ' cr / ' + r.rates.bannerBatch + ' views'], ['Text', r.rates.textCreditsPerBatch + ' cr / ' + r.rates.textBatch + ' views'], ['Login', r.rates.loginCreditsPerDay + ' cr / day'], ['Solo', r.rates.soloCostPerRecipient + ' cr / delivery'], ['Featured', (r.rates.featuredPerDay || 40) + ' cr / day'], ['Visit', (r.rates.visitCostPerVisit || 3) + ' cr / visit']].map(x => '' + x[0] + ' ' + x[1] + '').join(''); - } - $('rateLine').textContent = 'Available to spend: ' + r.availableCredits.toLocaleString() - + (r.earnedCredits ? ' (' + r.purchasedCredits.toLocaleString() + ' purchased + ' + r.earnedCredits + ' earned)' : '') - + (r.inCampaigns ? ' · ' + r.inCampaigns.toLocaleString() + ' set aside in live campaigns' : '') - + ' credits · rates: banner ' + r.rates.bannerCreditsPerBatch + 'cr/' + r.rates.bannerBatch - + ' views, text ' + r.rates.textCreditsPerBatch + 'cr/' + r.rates.textBatch - + ' views, login ' + r.rates.loginCreditsPerDay + 'cr/day, solo ' - + (r.rates.soloCostPerRecipient || 5) + 'cr/delivery'; - const el = $('campList'); - el.innerHTML = ''; - if (!r.campaigns.length) { el.innerHTML = '

No campaigns yet. Launch your first below.

'; return; } - const tbl = document.createElement('div'); - tbl.className = 'tablewrap'; - tbl.innerHTML = '' - + '' - + r.campaigns.map(c => '' - + '' - + '' - + '' - + '' - + '' - + '' - + '').join('') + '
NameTypeViews hereNetwork viewsClicksSpentBudgetStatus
' + c.name + '' + hourBars(r.hours && r.hours[c.id]) + geoLine(r.geo && r.geo[c.id]) + '' + c.type + (c.type === 'banner' && c.width ? ' ' + c.width + '×' + c.height + '' : '') + (c.dailyCap ? ' cap ' + c.dailyCap + '/day' : '') + (c.geo ? ' tier ' + esc(c.geo.replace(/,/g, '+')) + '' : '') + schedChips(c) + '' + c.imps.toLocaleString() + '' + (['banner', 'text'].includes(c.type) ? (c.impsNas || 0).toLocaleString() : 'n/a') + '' + c.clicks + (r.clickSources && r.clickSources[c.id] ? '
' + Object.entries(r.clickSources[c.id]).sort((a, b) => b[1] - a[1]).map(([k, v]) => '' + esc(k) + ' ' + v + '').join('') + (c.impsNas ? ' · network: see Network views' : '') + '
' : '') + '
' + c.spent + '' + c.budget + '' + (c.status === 'out' ? 'budget spent' : c.status === 'done' ? 'ended' : c.scheduled ? 'scheduled' : c.status) + '' + (c.status === 'active' ? '' - : c.status === 'paused' ? '' : '') - + ' ' - + '
'; - el.appendChild(tbl); - el.querySelectorAll('button[data-camp]').forEach(b => b.addEventListener('click', async () => { - try { await api('/api/my/campaigns/' + b.dataset.camp + '/' + b.dataset.act); await loadCampaigns(); } - catch (e) { IAP.status(e.message, 'bad'); } - })); - el.querySelectorAll('button[data-topup]').forEach(b => b.addEventListener('click', async () => { - const n = await IAP.ask({ title: 'Add credits', text: 'How many credits to add to this campaign? More credits buy more views.', type: 'number', placeholder: 'e.g. 100', ok: 'Add credits' }); - if (!n) return; - try { const r = await api('/api/my/campaigns/' + b.dataset.topup + '/topup', { credits: Number(n) }); - IAP.status('Added ' + r.added + ' credits' + (r.reactivated ? ' — campaign is live again.' : '.'), 'ok'); - await loadCampaigns(); loadDashboard(); - } catch (e) { IAP.status(e.message, 'bad'); } - })); - } catch (e) {} - } - let lastRates = null; - function soloHint() { - if (!lastRates || $('cType').value !== 'solo') return; - const cost = lastRates.soloCostPerRecipient || 5; - const n = Math.floor((Number($('cBudget').value) || 0) / cost); - $('cSoloHint').textContent = cost + ' credits per guaranteed inbox delivery' - + (n ? ' — this budget reaches ' + n + ' members' : '') - + '. Readers earn ' + (lastRates.soloReadCredits || 2) + ' credits for a real read, so your message gets opened.'; - } - $('cBudget').addEventListener('input', soloHint); - // rich solo editor: small toolbar over contenteditable (CSP allows no external editor); - // the server whitelist-sanitizes whatever HTML arrives, this is just authoring comfort - document.querySelectorAll('.ed-bar [data-cmd]').forEach(btn => - btn.addEventListener('click', () => { $('cSoloEd').focus(); document.execCommand(btn.dataset.cmd, false, null); })); - document.querySelectorAll('.ed-bar [data-block]').forEach(btn => - btn.addEventListener('click', () => { $('cSoloEd').focus(); document.execCommand('formatBlock', false, btn.dataset.block); })); - $('edLinkBtn').addEventListener('click', async () => { - const sel = window.getSelection(); const range = sel && sel.rangeCount ? sel.getRangeAt(0).cloneRange() : null; // the dialog steals the selection - const url = await IAP.ask({ title: 'Insert link', text: 'Link URL (https://…)', placeholder: 'https://', ok: 'Insert' }); - if (!url) return; - $('cSoloEd').focus(); if (range) { sel.removeAllRanges(); sel.addRange(range); } - document.execCommand('createLink', false, url); - }); - // inline media: upload, then drop the element at the cursor (BV-style) - let mediaMode = 'image'; - function insertHtmlAtCursor(html) { - const ed = $('cSoloEd'); - ed.focus(); - if (!document.execCommand('insertHTML', false, html)) ed.insertAdjacentHTML('beforeend', html); - } - $('edImgBtn').addEventListener('click', () => { mediaMode = 'image'; $('cSoloFile').accept = 'image/png,image/jpeg,image/webp,image/gif'; $('cSoloFile').click(); }); - $('edVidBtn').addEventListener('click', () => { mediaMode = 'video'; $('cSoloFile').accept = 'video/mp4,video/webm'; $('cSoloFile').click(); }); - $('cSoloFile').addEventListener('change', async () => { - const f = $('cSoloFile').files[0]; - if (!f) return; - $('edMediaInfo').textContent = 'Uploading ' + f.name + '…'; - try { - const r = await (await fetch('/api/my/upload', { method: 'POST', headers: { 'Content-Type': f.type }, body: f })).json(); - if (r.error) { $('edMediaInfo').textContent = r.error; $('cSoloFile').value = ''; return; } - insertHtmlAtCursor(r.type === 'video' - ? '


' - : '


'); - $('edMediaInfo').textContent = f.name + ' inserted'; - } catch (e) { $('edMediaInfo').textContent = 'Upload failed. Try again.'; } - $('cSoloFile').value = ''; - }); - // raw-text toggle: swap the WYSIWYG surface for the underlying HTML and back - $('edRawBtn').addEventListener('click', () => { - const ed = $('cSoloEd'), raw = $('cSoloRaw'); - if (raw.hidden) { raw.value = ed.innerHTML; raw.hidden = false; ed.hidden = true; $('edRawBtn').textContent = 'Visual'; } - else { ed.innerHTML = raw.value; ed.hidden = false; raw.hidden = true; $('edRawBtn').textContent = 'Raw text'; } - }); - const WHERE = { banner: 'Runs in the ad viewer, on the home page, the live ledger, every Overview, the sidebar tile, and out in the Network Ad Space rotation across the wider network.', - text: 'Runs in the ad viewer, the live ledger text slot, and out in the Network Ad Space rotation.', - login: 'Full screen for every member who signs in, ten seconds, once a day per member. Opens in a fresh tab, so any working page qualifies. Login ads spend purchased credits only.', - solo: 'Delivered into member inboxes under Earn credits. Each read is timed and rewarded, so it gets opened.', - video: 'Plays in Watch videos and the Shorts feed under Earn credits. You pay only for completed watches.', - featured: 'Your headline and link in the Featured strip on every member Overview for the days you book.', - visits: 'A distinct member opens your site in a new tab, stays eight seconds and passes a check. Nobody counts twice.' }; - const whereHint = () => { const el = $('cWhere'); if (el) el.textContent = WHERE[$('cType').value] || ''; }; - whereHint(); - // runs on every type change AND once at load, so the default type (banner) shows its size + image rows immediately - function applyType() { // hoisted: loadCampaigns may run before this line is reached - whereHint(); - const t = $('cType').value; - $('cImageRow').hidden = t !== 'banner'; // only banners carry a creative; login frames its URL - $('cSizeRow').hidden = t !== 'banner'; - $('cTitleRow').hidden = t !== 'text' && t !== 'solo'; - $('cBodyRow').hidden = t !== 'text'; - $('cSoloRow').hidden = t !== 'solo'; - $('cSoloHint').hidden = t !== 'solo'; - $('cVideoRow').hidden = t !== 'video'; - $('cFeaturedRow').hidden = t !== 'featured'; - $('cVisitsRow').hidden = t !== 'visits'; - if ($('cSchedRow')) { $('cSchedRow').hidden = t === 'featured'; $('cStartLbl').textContent = t === 'solo' ? 'Send from (optional)' : 'Start (optional)'; - $('cSchedHint').textContent = t === 'solo' ? 'Deliveries to member inboxes begin at the time you pick, so you can land when people are reading. Leave empty to start now.' : 'Leave both empty to start now and run until the budget is spent. Times are your local time. Anything left when a campaign ends goes back to Available.'; } - // fixed-cost types derive their spend (featured = day slots, visits = flat pack), - // so hide the free-form Budget field for them to avoid confusion - $('cBudgetRow').hidden = (t === 'featured' || t === 'visits'); - if ($('cCapRow')) $('cCapRow').hidden = !(t === 'banner' || t === 'text'); - // solo ads have a real floor (5cr x 10 deliveries): default to 50 so 10 isn't rejected - if (t === 'solo' && (!$('cBudget').value || Number($('cBudget').value) < 50)) $('cBudget').value = (lastRates && lastRates.soloCostPerRecipient ? lastRates.soloCostPerRecipient : 5) * 10; - if (t === 'visits') visitHint(); - $('cTitle').placeholder = t === 'solo' ? 'Subject line (max 80)' : 'Headline (max 60)'; - soloHint(); - if (t === 'video') videoHint(); - if (t === 'featured') featHint(); - } - $('cType').addEventListener('change', applyType); - let featStartDay = 0; // selected start-day offset (0 = today) - async function featHint() { - if (!lastRates || !lastRates.featuredDurations) return; - if ($('cFeatDays') && !$('cFeatDays').options.length) - $('cFeatDays').innerHTML = lastRates.featuredDurations.map(dys => - '').join(''); - let s = null; - try { s = await (await fetch('/api/featured/stats')).json(); } catch (e) {} - if (s && s.occupancy) { - const grid = $('cFeatDaysGrid'); - grid.innerHTML = s.occupancy.map(d => { - const label = d.offset === 0 ? 'Today' : d.offset === 1 ? 'Tomorrow' : new Date(d.day + 'T00:00:00Z').toLocaleDateString(undefined, { weekday: 'short', month: 'numeric', day: 'numeric' }); - const full = d.open <= 0; - return '
' - + '
' + label + '
' + d.count + '/' + d.cap + (full ? ' full' : ' left ' + d.open) + '
'; - }).join(''); - grid.querySelectorAll('.feat-day:not(.full)').forEach(el => - el.addEventListener('click', () => { featStartDay = Number(el.dataset.off); featHint(); })); - } - const dys = Number($('cFeatDays').value) || (lastRates.featuredDurations[0]); - const dayLabel = featStartDay === 0 ? 'today' : featStartDay === 1 ? 'tomorrow' : 'in ' + featStartDay + ' days'; - $('cFeatHint').textContent = 'Runs ' + dys + ' day' + (dys > 1 ? 's' : '') + ' starting ' + dayLabel - + ' for ' + (dys * lastRates.featuredPerDay) + ' credits. Max ' + (s ? s.slotsPerDay : 10) + ' links share any day.'; - } - document.addEventListener('change', e => { if (e.target && e.target.id === 'cFeatDays') featHint(); }); - function visitHint() { - if (!lastRates) return; - const n = Number($('cVisitCount').value) || 0; - const cost = n * (lastRates.visitCostPerVisit || 3); - $('cVisitHint').textContent = (lastRates.visitCostPerVisit || 3) + ' credits per verified visit' - + (n >= (lastRates.visitMinPack || 20) ? ' — ' + n + ' visits = ' + cost + ' credits' : ' (min ' + (lastRates.visitMinPack || 20) + ')') - + '. Each is a unique member, dwell + human-check verified.'; - } - $('cVisitCount').addEventListener('input', visitHint); - // video composer: tier dropdown + upload + price hint - function videoHint() { - if (!lastRates || !lastRates.videoTiers) return; - if ($('cWatchSecs') && !$('cWatchSecs').options.length) - $('cWatchSecs').innerHTML = lastRates.videoTiers.map(t => - '').join(''); - const tier = lastRates.videoTiers.find(t => t.secs === Number($('cWatchSecs').value)) || lastRates.videoTiers[0]; - const n = tier ? Math.floor((Number($('cBudget').value) || 0) / tier.cost) : 0; - $('cVideoHint').textContent = tier ? (tier.cost + ' credits per completed ' + tier.secs + 's view' - + (n ? ' — this budget buys ' + n + ' views' : '') + '. Viewers earn ' + tier.reward + ' credits each, so they watch.') : ''; - } - document.addEventListener('change', e => { if (e.target && e.target.id === 'cWatchSecs') videoHint(); }); - $('cBudget').addEventListener('input', () => { if ($('cType').value === 'video') videoHint(); }); - $('cVideoUploadBtn').addEventListener('click', () => $('cVideoFile').click()); - $('cVideoUrl').addEventListener('change', async () => { - const url = $('cVideoUrl').value.trim(); - $('cVideoInfo').textContent = url ? 'checking video…' : ''; - cVidDims = url ? await probeVideoDims(url) : null; - if (url && !cVidDims) $('cVideoInfo').textContent = 'could not read that video'; - else { $('cVideoInfo').textContent = ''; showVidOrient(); } - }); - $('cVideoFile').addEventListener('change', async () => { - const f = $('cVideoFile').files[0]; - if (!f) return; - $('cVideoInfo').textContent = 'Uploading ' + f.name + '… (large files take a moment)'; - try { - const r = await (await fetch('/api/my/upload', { method: 'POST', headers: { 'Content-Type': f.type }, body: f })).json(); - if (r.error) { $('cVideoInfo').textContent = r.error; $('cVideoFile').value = ''; return; } - $('cVideoUrl').value = r.url; - $('cVideoInfo').textContent = f.name + ' uploaded'; - $('cVideoPrev').hidden = false; - $('cVideoPrev').innerHTML = ''; - cVidDims = await probeVideoDims(r.url); showVidOrient(); - } catch (e) { $('cVideoInfo').textContent = 'Upload failed. Try again.'; } - $('cVideoFile').value = ''; - }); - $('createCampBtn').addEventListener('click', busy2($('createCampBtn'), async () => { - // in raw mode the source of truth is the textarea; sync it back first - let soloBody = $('cSoloEd').innerHTML; - if ($('cSoloRaw') && !$('cSoloRaw').hidden) soloBody = $('cSoloRaw').value; - const t = $('cType').value; - const isVideo = t === 'video', isFeat = t === 'featured'; - if (isVideo && !cVidDims && $('cVideoUrl').value) cVidDims = await probeVideoDims($('cVideoUrl').value); - await api('/api/my/campaigns', { type: t, name: $('cName').value, - targetUrl: $('cTarget').value, imageUrl: $('cImage').value, size: $('cSize').value, - title: isVideo ? $('cVideoTitle').value : isFeat ? $('cFeatTitle').value : t === 'visits' ? $('cVisitTitle').value : $('cTitle').value, - body: t === 'solo' ? soloBody : $('cBody').value, - videoUrl: $('cVideoUrl').value, watchSecs: Number($('cWatchSecs').value), - videoW: cVidDims ? cVidDims.w : null, videoH: cVidDims ? cVidDims.h : null, - days: Number($('cFeatDays').value), startDay: featStartDay, - count: Number($('cVisitCount').value), - dailyCap: ($('cDailyCap') && (t === 'banner' || t === 'text')) ? Number($('cDailyCap').value) || 0 : 0, - geo: [...document.querySelectorAll('.geoTier:checked')].map(x => x.value).join(','), - startsAt: ($('cStartAt') && $('cStartAt').value && !isFeat) ? new Date($('cStartAt').value).getTime() : 0, - endsAt: ($('cEndAt') && $('cEndAt').value && !isFeat) ? new Date($('cEndAt').value).getTime() : 0, - ctaLabel: isVideo ? $('cVideoCta').value : $('cCtaLabel').value, - budget: isFeat ? (Number($('cFeatDays').value) * (lastRates.featuredPerDay || 40)) : t === 'visits' ? (Number($('cVisitCount').value) * (lastRates.visitCostPerVisit || 3)) : Number($('cBudget').value) }); - const schedStart = ($('cStartAt') && $('cStartAt').value && !isFeat) ? new Date($('cStartAt').value) : null; - IAP.status(schedStart && schedStart.getTime() > Date.now() ? 'Campaign saved. It starts serving ' + schedStart.toLocaleString([], { dateStyle: 'medium', timeStyle: 'short' }) + '.' : 'Campaign is live. It starts serving right away.', 'ok'); - // clear EVERY field so no target/creative carries into the next campaign - ['cName', 'cBudget', 'cTarget', 'cImage', 'cTitle', 'cBody', 'cCtaLabel', - 'cVideoUrl', 'cVideoTitle', 'cVideoCta', 'cVisitTitle', 'cVisitCount', 'cFeatTitle', 'cDailyCap', 'cStartAt', 'cEndAt'] - .forEach(id => { if ($(id)) $(id).value = ''; }); - document.querySelectorAll('.geoTier').forEach(x => { x.checked = true; }); - $('cSoloEd').innerHTML = ''; if ($('cSoloRaw')) $('cSoloRaw').value = ''; - $('cVideoInfo').textContent = ''; $('cVideoPrev').hidden = true; $('cVideoPrev').innerHTML = ''; - if ($('edMediaInfo')) $('edMediaInfo').textContent = ''; - cVidDims = null; - await loadCampaigns(); - })); - // defers the busy() lookup to click time (busy is declared below) - function busy2(btn, fn) { return (...a) => busy(btn, fn)(...a); } - - // ── verified visits: open a member's site (new tab), dwell, human-check, earn ── - const visState = { token: null, id: null, dwell: 8 }; - async function loadVisitStatus() { - try { - const st = await (await fetch('/api/my/visits')).json(); - if (st.error) return; - $('vsProgress').textContent = 'today: ' + (st.status.count || 0) + ' / ' + st.status.cap + ' verified visits'; - $('vsStartBtn').hidden = st.status.count >= st.status.cap; - if (st.status.count >= st.status.cap) $('vsBox').innerHTML = 'That\'s today\'s visits. Come back tomorrow.'; - } catch (e) {} - } - async function loadVisit() { - $('vsCheck').hidden = true; $('vsVisit').hidden = true; $('vsHint').textContent = ''; - let r = null; - try { r = await (await fetch('/api/my/visits')).json(); } catch (e) {} - if (!r || !r.ad) { - $('vsBox').innerHTML = '' + (r && r.status && r.status.count >= r.status.cap - ? 'That\'s today\'s visits. Come back tomorrow.' : 'No verified-visit packs are running right now. Check back soon.') + ''; - return; - } - visState.token = r.token; visState.id = r.ad.id; visState.dwell = r.status.dwell || 8; - $('vsBox').innerHTML = '' + esc(r.ad.title || 'Member site') + '
Open the site and stay ' + visState.dwell + 's.'; - const visit = $('vsVisit'); - visit.href = r.ad.url; visit.hidden = false; - $('vsStartBtn').textContent = 'Loading…'; $('vsStartBtn').disabled = true; - // opening the site starts the dwell; then we ask the human-check - visit.onclick = () => { - let left = visState.dwell; - $('vsHint').textContent = 'Counting your visit: ' + left + 's'; - const t = setInterval(async () => { - left--; - if (left > 0) { $('vsHint').textContent = 'Counting your visit: ' + left + 's'; return; } - clearInterval(t); - $('vsHint').textContent = 'One quick check to count the visit:'; - let c = await (await fetch('/api/my/visitchallenge?token=' + visState.token)).json(); - if (c.early) { await new Promise(r2 => setTimeout(r2, (c.wait || 1) * 1000 + 300)); c = await (await fetch('/api/my/visitchallenge?token=' + visState.token)).json(); } - if (c.error) { $('vsHint').textContent = c.error; return; } - renderVisitCheck(c); - }, 1000); - }; - $('vsStartBtn').textContent = 'Next visit'; $('vsStartBtn').disabled = false; - } - function renderVisitCheck(c) { - $('vsPrompt').textContent = 'Click the ' + c.prompt + ':'; - const w = $('vsOpts'); w.innerHTML = ''; - c.options.forEach((em, i) => { - const b = document.createElement('button'); - b.className = 'btn small sec'; b.style.marginRight = '6px'; b.textContent = em; - b.addEventListener('click', () => answerVisit(i)); - w.appendChild(b); - }); - $('vsCheck').hidden = false; - } - async function answerVisit(i) { - const r = await (await fetch('/api/my/visitdone', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ token: visState.token, answer: i }) })).json(); - if (r.error) { - if (r.retry) { const c = await (await fetch('/api/my/visitchallenge?token=' + visState.token)).json(); if (!c.error) return renderVisitCheck(c); } - $('vsHint').textContent = r.error; $('vsCheck').hidden = true; return; - } - $('vsCheck').hidden = true; - $('vsHint').textContent = '+' + r.credited + ' credits — visit counted. Load the next one.'; - $('vsProgress').textContent = 'today: ' + (r.status.count || 0) + ' / ' + (r.status.cap || 0) + ' verified visits'; - IAP.status('+' + r.credited + ' credits for a verified visit.', 'ok'); - loadDashboard(); - } - $('vsStartBtn').addEventListener('click', () => loadVisit()); - - // ── watch-to-earn videos: escape-proof player, server-clock reward ── - const vidState = { token: null, secs: 0, maxSeen: 0, done: false, credited: false }; - // detected dimensions of the video being created — portrait goes to Shorts, landscape to Watch videos - let cVidDims = null; - function probeVideoDims(url) { - return new Promise(resolve => { - if (!url) return resolve(null); - const v = document.createElement('video'); v.preload = 'metadata'; v.muted = true; - let done = false; const fin = r => { if (!done) { done = true; resolve(r); } }; - v.onloadedmetadata = () => fin(v.videoWidth && v.videoHeight ? { w: v.videoWidth, h: v.videoHeight } : null); - v.onerror = () => fin(null); setTimeout(() => fin(null), 8000); v.src = url; - }); - } - function showVidOrient() { - const el = $('cVideoInfo'); if (!el) return; - if (!cVidDims) return; - const portrait = cVidDims.h > cVidDims.w; - el.textContent = (el.textContent ? el.textContent + ' · ' : '') - + (portrait ? 'portrait — shows in the Shorts reel' : 'landscape — shows in the Watch videos tab'); - } - async function loadVideoStatus() { - try { - const st = await (await fetch('/api/my/videos?orientation=landscape')).json(); - if (st.error) return; - $('vidProgress').textContent = 'today: ' + (st.status.count || 0) + ' / ' + st.status.cap + ' videos watched'; - if (st.status.left <= 0) { - $('vidBox').innerHTML = 'That is today\'s video set. Come back tomorrow.'; - $('vidStartBtn').hidden = true; - return; - } - $('vidStartBtn').hidden = false; - } catch (e) {} - } - // leaving the player (other sub-tab, other pane, page hidden) stops the clip: nothing plays or earns in the background (Marty, 2026-09-13) - function stopVideo() { - const p = $('vidPlayer'); if (!p) return; - const was = !!vidState.token && !vidState.done; - try { p.pause(); p.ontimeupdate = null; p.onseeking = null; p.removeAttribute('src'); p.load(); } catch (e) {} - vidState.token = null; vidState.done = false; vidState.credited = false; vidState.maxSeen = 0; - if ($('vidWrap')) $('vidWrap').hidden = true; - if ($('vidBox')) { $('vidBox').hidden = false; if (was) $('vidBox').innerHTML = 'Video stopped when you left the tab. Tap Load a video to start a fresh one.'; } - if ($('vidStartBtn')) { $('vidStartBtn').disabled = false; $('vidStartBtn').textContent = 'Load a video'; } - } - document.addEventListener('visibilitychange', () => { if (document.hidden && vidState.token && !vidState.done) stopVideo(); }); - async function loadVideoAd() { - let r = null; - try { r = await (await fetch('/api/my/videos?orientation=landscape')).json(); } catch (e) {} - if (!r || !r.ad) { - // same done screen as Watch ads when the day's videos are finished (Marty, 2026-09-13) - const capHit = !!(r && r.status && r.status.left <= 0), allWatched = !!(r && r.allWatched); - $('vidBox').innerHTML = (capHit || allWatched) - ? '
✓Videos done for today' + (capHit ? 'That is today’s video set (' + r.status.count + ' watched). Fresh videos tomorrow.' : 'You have watched every live video for today; each one pays once a day. New ones appear as members launch video campaigns.') + '
' - : 'No member videos are live right now. Check back when a campaign is running.'; - if ($('vidStartBtn')) $('vidStartBtn').hidden = capHit || allWatched; - $('vidBox').hidden = false; - $('vidWrap').hidden = true; - return; - } - const ad = r.ad; - vidState.token = r.token; vidState.secs = ad.watchSecs; vidState.maxSeen = 0; vidState.done = false; vidState.credited = false; - $('vidBox').hidden = true; - $('vidWrap').hidden = false; - $('vidCta').hidden = true; - $('vidHint').textContent = ad.title ? 'Now playing: ' + ad.title : ''; - const p = $('vidPlayer'); - p.src = ad.videoUrl; - p.currentTime = 0; - // escape-proof: no seeking past what's been watched; track max reached - p.onseeking = () => { if (p.currentTime > vidState.maxSeen + 0.5) p.currentTime = vidState.maxSeen; }; - p.ontimeupdate = () => { - if (p.currentTime > vidState.maxSeen) vidState.maxSeen = p.currentTime; - const left = Math.max(0, Math.ceil(vidState.secs - vidState.maxSeen)); - $('vidTimer').textContent = left > 0 ? 'Watch ' + left + 's more to earn' : 'Watch time met — finishing…'; - if (!vidState.done && vidState.maxSeen >= vidState.secs) { vidState.done = true; completeVideo(ad); } - }; - $('vidStartBtn').textContent = 'Playing…'; - $('vidStartBtn').disabled = true; - try { await p.play(); } catch (e) { $('vidStartBtn').disabled = false; $('vidStartBtn').textContent = 'Tap to play'; } - $('vidCta').href = ad.ctaUrl; - $('vidCta').textContent = ad.ctaLabel || 'Learn more'; - $('vidCta').hidden = false; - } - async function completeVideo(ad) { - if (vidState.credited) return; - vidState.credited = true; - try { - const r = await (await fetch('/api/my/videowatch', { method: 'POST', - headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ token: vidState.token }) })).json(); - if (r.error) { IAP.status(r.error, 'bad'); $('vidHint').textContent = r.error + (/no longer open|stale/.test(r.error) ? ' Loading a fresh one.' : ''); if (/no longer open|stale/.test(r.error)) setTimeout(() => loadVideoAd(), 1200); } - else if (r.credited) { IAP.status('+' + r.credited + ' credits earned for watching.', 'ok'); $('vidHint').textContent = '+' + r.credited + ' credits earned. Load the next one.'; loadDashboard(); } - else $('vidHint').textContent = 'That video just ran out of budget — load another.'; - if (r.status) $('vidProgress').textContent = 'today: ' + (r.status.count || 0) + ' / ' + r.status.cap + ' videos watched'; - } catch (e) { IAP.status('Could not confirm that watch. Try the next one.', 'bad'); } - $('vidStartBtn').disabled = false; - $('vidStartBtn').textContent = 'Next video'; - } - $('vidStartBtn').addEventListener('click', () => loadVideoAd()); - // presence enforcement: pause the watch-to-earn video when the tab/window loses focus, - // resume when it comes back — the viewer must stay on the page for the watch to complete - document.addEventListener('visibilitychange', () => { - const p = $('vidPlayer'); if (!p || !p.src) return; - if (document.hidden) p.pause(); else if (!vidState.done) p.play().catch(() => {}); - }); - window.addEventListener('blur', () => { const p = $('vidPlayer'); if (p && p.src) p.pause(); }); - window.addEventListener('focus', () => { const p = $('vidPlayer'); if (p && p.src && !vidState.done) p.play().catch(() => {}); }); - - // ── unmissable sponsor-message modal on sign-in ── - function showSponsorModal(msg) { - if (!$('msgModal')) return; - $('mmFrom').textContent = 'A message from ' + (msg.fromName || 'your sponsor'); - $('mmSubject').textContent = msg.subject || ''; - $('mmBody').innerHTML = msg.body || ''; // server-sanitized - $('msgModal').hidden = false; - $('mmAck').onclick = async () => { - $('msgModal').hidden = true; - try { await fetch('/api/my/messages/' + msg.id + '/read', { method: 'POST' }); } catch (e) {} - }; - } - - // ── coaching: every direct's rung, stalled flag, one-click nudge ── - // ── pay it forward: send POL from the sponsor's own wallet to a downline's linked address ── - async function pif(email, name, address) { - let suggest = 25; - try { const { products } = await (await fetch('/api/catalog')).json(); const p20 = (products || []).find(p => p.priceCents === 2000); if (p20 && p20.costWei) suggest = Math.ceil(Number(p20.costWei) / 1e18) + 3; } catch (e) {} - const amt = await IAP.ask({ title: 'Pay it forward', text: 'Send POL from your wallet to ' + name + ' (' + address.slice(0, 6) + '…' + address.slice(-4) + ') for their first package.\nSuggested: the $20 package plus fees. Amount in POL:', type: 'number', value: String(suggest), ok: 'Send POL' }); - if (amt === null) return; - const pol = Number(amt); if (!(pol > 0)) { IAP.status('Enter an amount in POL.', 'bad'); return; } - try { - IAP.status('Confirm the transfer in your wallet…', 'ok'); - const wei = (BigInt(Math.round(pol * 1e6)) * 10n ** 12n).toString(); - const hash = await IAPWallet.sendPol(address, wei); - await api('/api/my/gift', { email, tx: hash, pol }); - IAP.status('Sent ' + pol + ' POL to ' + name + '. They have been told, with the proof link.', 'ok'); - playSound && playSound('chaching'); - } catch (e) { IAP.status('Transfer not sent: ' + ((e && e.message) || e), 'bad'); } - } - // ── holding tank: waiting members, adopt, my open adoptions ── - const ago = ts => { if (!ts) return 'never'; const d = Math.floor((Date.now() - ts) / 86400000); return d === 0 ? 'today' : d === 1 ? 'yesterday' : d + ' days ago'; }; - async function loadTank() { - const el = $('tankList'); if (!el) return; - try { - const r = await (await fetch('/api/my/tank')).json(); - if (r.error) { el.innerHTML = ''; return; } - $('tankCap').textContent = r.cap; $('tankTtl').textContent = r.ttlDays; - $('tankSub').textContent = r.waiting.length ? r.waiting.length + ' waiting' : 'nobody waiting right now'; - const why = $('tankWhy'); why.hidden = r.eligible; why.innerHTML = r.eligible ? '' : 'not yet ' + esc(r.reason); - $('tankMine').innerHTML = r.mine.length ? '

Your open adoptions

' + r.mine.map(m => '
' + esc(m.name) + '' - + '' + (m.bought ? 'bought' : m.wallet ? 'wallet linked' : 'free, no wallet yet') + ' · last seen ' + ago(m.lastSeen) + '' - + '' + Math.max(0, Math.ceil((m.expires - Date.now()) / 86400000)) + ' days left' - + '' - + (m.address && !m.bought ? ' ' : '') + '
').join('') : ''; - $('tankMine').querySelectorAll('[data-tchat]').forEach(b => b.addEventListener('click', () => openConvo(b.dataset.tchat, b.dataset.tname))); - $('tankMine').querySelectorAll('[data-pif]').forEach(b => b.addEventListener('click', () => pif(b.dataset.pif, b.dataset.pname, b.dataset.paddr))); - if (!r.waiting.length) { el.innerHTML = '

The tank is empty. Anyone who joins from the public site without a sponsor lands here.

'; return; } - el.innerHTML = r.waiting.map(w => '
' + esc(w.name) + '' - + 'joined ' + ago(w.joined) + '' - + 'last sign-in: ' + ago(w.lastSeen) + '' - + (r.eligible ? '' : '') + '
').join(''); - el.querySelectorAll('[data-adopt]').forEach(b => b.addEventListener('click', async () => { - const note = await IAP.ask({ title: 'Adopt ' + b.dataset.aname, text: 'Your first message to ' + b.dataset.aname + ' (sent as a chat and an email):', type: 'textarea', ok: 'Adopt and send', value: 'Hi, I picked you up from the LinkSpin holding tank so you have a sponsor who will actually help. Reply here and I will walk you through the first three steps.' }); - if (note === null) return; - try { const rr = await api('/api/my/tank/adopt', { who: b.dataset.adopt, note }); IAP.status('You are now the sponsor for ' + rr.name + '. Chat and email sent.', 'ok'); loadTank(); loadCoach(); } - catch (e) { IAP.status(e.message, 'bad'); } - })); - } catch (e) {} - } - async function loadCoach() { - loadTank(); - try { - const r = await (await fetch('/api/my/coach')).json(); - const el = $('coachList'); if (!el || r.error) return; - const d = r.directs || []; - $('coachSummary').innerHTML = d.length ? '' + d.length + ' direct' + (d.length === 1 ? '' : 's') + ' · ' + r.stalled + ' quiet for 3+ days' + (r.stalled ? ' · start at the top' : '') : ''; - if (!d.length) { el.innerHTML = '

No directs yet. When someone joins through your link they show up here with their next step.

'; return; } - el.innerHTML = d.map(x => '
' + esc(x.name) + (x.stalled ? ' quiet ' + x.quietDays + 'd' : '') - + (x.rescue && x.rescue.unreached ? ' unreached · tank in ' + x.rescue.rescueInDays + 'd' : '') + (x.bound === false ? ' not bound to you on-chain' : '') + '' - + '' + esc(x.label) + ' → ' + esc(x.next) + '' - + 'rung ' + x.rung + '/6' - + '' + (x.buyerCount ? x.buyerCount + ' buyer' + (x.buyerCount === 1 ? '' : 's') : '') + '' - + '' - + (x.free && x.address ? ' ' : '') - + (x.free && x.rescue ? ' ' : '') - + (x.free ? ' ' : '') + '
').join(''); - el.querySelectorAll('[data-contacted]').forEach(b => b.addEventListener('click', async () => { - try { await api('/api/my/tank/contacted', { email: b.dataset.contacted }); IAP.status('Marked: you have contacted ' + b.dataset.cname + '.', 'ok'); loadCoach(); } - catch (e) { IAP.status(e.message, 'bad'); } - })); - el.querySelectorAll('[data-pif]').forEach(b => b.addEventListener('click', () => pif(b.dataset.pif, b.dataset.pname, b.dataset.paddr))); - el.querySelectorAll('[data-nudge]').forEach(b => b.addEventListener('click', async () => { - await openConvo(b.dataset.nudge, b.dataset.nname); - const inp = $('chatInput'); if (inp) { inp.value = b.dataset.say.replace(/\{\{name\}\}/g, b.dataset.nname.replace(/^@/, '')); inp.focus(); } - })); - el.querySelectorAll('[data-release]').forEach(b => b.addEventListener('click', async () => { - if (!(await IAP.confirmBox('Release ' + b.dataset.rname + ' to the holding tank? You stop being their sponsor and another member can adopt them.', { title: 'Release to the tank', ok: 'Release' }))) return; - try { await api('/api/my/tank/release', { email: b.dataset.release }); IAP.status(b.dataset.rname + ' is in the holding tank.', 'ok'); loadCoach(); } - catch (e) { IAP.status(e.message, 'bad'); } - })); - } catch (e) {} - } - // schedule chips on the campaign table (local time) + by-hour view bars - const fmtWhen = ms => new Date(ms).toLocaleString([], { month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' }); - function schedChips(c) { - const now = Date.now(); let s = ''; - if (c.starts && c.starts > now) s += ' starts ' + fmtWhen(c.starts) + ''; - if (c.expires && c.type !== 'featured') s += ' ' + (c.expires > now ? 'ends ' : 'ended ') + fmtWhen(c.expires) + ''; - return s; - } - function geoLine(rows) { - if (!rows || !rows.length) return ''; - return '
' + rows.map(r => esc(r.cc) + ' ' + r.n).join(' · ') + '
'; - } - function hourBars(utc) { - if (!utc || !utc.some(n => n)) return ''; - // rotate the 24 UTC buckets into the viewer's local hours - const local = new Array(24).fill(0); - for (let h = 0; h < 24; h++) local[new Date(Date.UTC(2000, 0, 1, h)).getHours()] += utc[h]; - const max = Math.max(...local); - const lab = h => (h % 12 || 12) + (h < 12 ? 'am' : 'pm'); - return '
' + local.map((n, h) => - '').join('') - + '
views by hour · last 7 days · your time
'; - } - // ── link stats: views, joins, buyers per angle ── - async function loadLinkStats() { - try { - const r = await (await fetch('/api/my/linkstats')).json(); - const t = $('linkStatsTable'); if (!t || r.error) return; - const rows = (r.angles || []).filter(a => a.views || a.joins || a.buyers); - if (!rows.length) { t.innerHTML = 'No views yet. Share your link and the numbers start here.'; return; } - t.innerHTML = 'HookViews (30d)Views (all)JoinedQualifying buyers' - + rows.map(a => '' + esc(a.angle === 'plain' ? 'plain link' : '?v=' + a.angle) + '' + a.views30 + '' + a.views + '' + a.joins + '' + a.buyers + '').join(''); - const st = $('linkSrcTable'); - if (st) { - const src = (r.sources || []).filter(x => x.views || x.joins); - st.innerHTML = src.length ? 'SourceViews (30d)Views (all)JoinedQualifying buyers' - + src.map(x => '' + esc(x.source) + '' + x.views30 + '' + x.views + '' + x.joins + '' + x.buyers + '').join('') - : 'Sources appear as visits arrive.'; - } - } catch (e) {} - } - // ── prospects: the member's own follow-up list ── - let PP_STATUSES = ['new', 'contacted', 'interested', 'joined', 'bought', 'not now']; - // ── Pipeline: the follow-up board (Marty, 2026-09-15). Stages come from the server; cards never move by hand ── - let PIPE = null, PIPE_KEY = null; - const pipeAgo = ts => { const d = Math.floor((Date.now() - ts) / 86400000); return d <= 0 ? 'today' : d === 1 ? 'yesterday' : d < 30 ? d + 'd ago' : new Date(ts).toLocaleDateString(undefined, { month: 'short', day: 'numeric' }); }; - const pipeInvite = () => { const t = ($('inviteLine') && $('inviteLine').textContent) || ''; return /^https?:\/\//.test(t) ? t : ''; }; - function pipeCardHtml(c, showStage) { - const today = new Date(); today.setHours(23, 59, 59, 999); - const due = c.followUp && c.followUp <= today.getTime(); - const chips = []; - if (c.stalled) chips.push('stalled ' + c.quietDays + 'd'); - if (due) chips.push('follow up'); - else if (c.followUp) chips.push('' + new Date(c.followUp).toLocaleDateString(undefined, { month: 'short', day: 'numeric' }) + ''); - if (c.tag) chips.push('' + esc(c.tag) + ''); - if (c.kind === 'member' && c.buyers) chips.push('' + c.buyers + ' buyer' + (c.buyers === 1 ? '' : 's') + ''); - const stage = showStage ? (PIPE.stages.find(s => s.key === c.stage) || {}).label || '' : ''; - return '
' - + '
' + esc(c.name) + '' + (c.kind === 'prospect' ? 'prospect' : (c.lastSeen ? 'seen ' + pipeAgo(c.lastSeen) : 'never signed in')) + '
' - + '
' + esc(stage ? stage + ' · ' + c.next : c.next) + '
' - + (c.note ? '
' + esc(c.note) + '
' : '') - + (chips.length ? '
' + chips.join('') + '
' : '') + '
'; - } - async function loadPipeline() { - try { - const r = await (await fetch('/api/my/pipeline')).json(); - if (r.error) { IAP.status(r.error, 'bad'); return; } - if (!r.live) { - $('pipeSoon').hidden = false; $('pipeLive').hidden = true; - $('pipeSoonEta').textContent = r.eta ? 'Opens ' + r.eta + '. It is on the roadmap so you can see what is coming and when.' : 'It is on the roadmap so you can see what is coming and when.'; - return; - } - PIPE = r; $('pipeSoon').hidden = true; $('pipeLive').hidden = false; - const badge = $('pipeBadge'); if (badge) { const n = r.counts.due + r.counts.stalled; badge.hidden = !n; badge.textContent = n > 9 ? '9+' : n; } - $('pipeDueCount').hidden = !r.due.length; $('pipeDueCount').textContent = r.due.length; - $('pipeDue').innerHTML = r.due.length ? '
' + r.due.map(c => pipeCardHtml(c, true)).join('') + '
' : '

Nothing due. Set a follow-up date on any card and it shows up here.

'; - $('pipeSummary').textContent = r.counts.total ? r.counts.total + ' people on your board' + (r.counts.stalled ? ', ' + r.counts.stalled + ' stalled' : '') + '. Cards move on their own when something happens on the ledger; open one to add a note, a follow-up date or a tag.' : 'Nobody on your board yet. Add prospects on My line, and everyone who joins through your link appears here on their own.'; - $('pipeBoard').innerHTML = r.columns.map(col => '

' + esc(col.label) + '' + col.cards.length + '

' + esc(col.hint) + '

' + col.cards.map(c => pipeCardHtml(c, false)).join('') + '
').join(''); - $('pipeLive').querySelectorAll('[data-pk]').forEach(el => { - el.addEventListener('click', () => openPipeCard(el.dataset.pk)); - el.addEventListener('keydown', e => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); openPipeCard(el.dataset.pk); } }); - }); - if (PIPE_KEY) { const c = allPipeCards().find(x => x.key === PIPE_KEY); if (c) fillPipeCard(c); else { PIPE_KEY = null; $('pipeCard').hidden = true; } } - } catch (e) { IAP.status('Could not load your pipeline.', 'bad'); } - } - function allPipeCards() { return PIPE ? PIPE.columns.flatMap(c => c.cards) : []; } - function fillPipeCard(c) { - $('pipeCardName').textContent = c.name; - const stage = (PIPE.stages.find(s => s.key === c.stage) || {}).label || ''; - $('pipeCardMeta').textContent = stage + (c.kind === 'member' ? ' · joined ' + new Date(c.since).toLocaleDateString() + (c.lastSeen ? ' · last seen ' + pipeAgo(c.lastSeen) : ' · never signed in') + (c.bought ? ' · your qualifying buyer' : '') + (c.buyersPositions ? ' · ' + c.buyers + ' buyers: ' + c.buyersMain + ' on the main wallet, ' + c.buyersPositions + ' on linked positions' : '') : ' · prospect' + (c.contact ? ' · ' + c.contact : '')); - $('pipeCardNext').innerHTML = 'Next for them: ' + esc(c.next) + (c.stalled ? ' quiet ' + c.quietDays + ' days' : ''); - const say = (c.say || '').replace('{{link}}', pipeInvite()); - $('pipeSayBlock').hidden = !say; $('pipeSay').textContent = say; - $('pipeSend').hidden = c.kind !== 'member' || !c.email; - $('pipeFollow').value = c.followUp ? new Date(c.followUp).toISOString().slice(0, 10) : ''; - const sel = $('pipeTag'); sel.innerHTML = PIPE.tags.map(t => '').join(''); - $('pipeNote').value = c.note || ''; $('pipeSaved').textContent = ''; - $('pipeCard').hidden = false; - } - function openPipeCard(key) { - const c = allPipeCards().find(x => x.key === key); if (!c) return; - PIPE_KEY = key; $('pipeLive').querySelectorAll('[data-pk]').forEach(el => el.classList.toggle('on', el.dataset.pk === key)); - fillPipeCard(c); $('pipeCard').scrollIntoView({ behavior: 'smooth', block: 'nearest' }); - } - if ($('pipeCardClose')) $('pipeCardClose').addEventListener('click', () => { PIPE_KEY = null; $('pipeCard').hidden = true; $('pipeLive').querySelectorAll('[data-pk]').forEach(el => el.classList.remove('on')); }); - if ($('pipeSave')) $('pipeSave').addEventListener('click', async () => { - if (!PIPE_KEY) return; - try { await api('/api/my/pipeline/note', { key: PIPE_KEY, note: $('pipeNote').value, followUp: $('pipeFollow').value || null, tag: $('pipeTag').value }); $('pipeSaved').textContent = 'Saved.'; loadPipeline(); } - catch (e) { IAP.status(e.message, 'bad'); } - }); - if ($('pipeCopy')) $('pipeCopy').addEventListener('click', async () => { try { await navigator.clipboard.writeText($('pipeSay').textContent); $('pipeCopy').textContent = 'Copied'; setTimeout(() => { $('pipeCopy').textContent = 'Copy message'; }, 1500); } catch (e) { IAP.status('Copy failed; select the text by hand.', 'bad'); } }); - if ($('pipeSend')) $('pipeSend').addEventListener('click', () => { - const c = allPipeCards().find(x => x.key === PIPE_KEY); if (!c || !c.email) return; - openConvo(c.email, c.name); - const ta = $('chatInput'); if (ta) { ta.value = $('pipeSay').textContent; ta.dispatchEvent(new Event('input')); ta.focus(); } - }); - // ── the rotator (LinkSpin) ── - let ROT = null, ROT_HOSTS = [], ROT_ID = null; - const rotLink = r => 'https://' + (ROT_HOSTS[0] || location.host) + '/r/' + r.code; - async function loadRotator() { - try { - const r = await (await fetch('/api/my/rotations')).json(); if (r.error) { IAP.status(r.error, 'bad'); return; } - ROT = r.rotations || []; ROT_HOSTS = r.hosts || []; - const el = $('rotList'); - el.innerHTML = ROT.length ? ROT.map(x => '
' + esc(x.name) + (x.paused ? ' paused' : '') + '' + esc(rotLink(x)) + '' + x.destinations.length + ' dest' + x.hits7 + ' hits · 7d' + x.uniques + ' uniques
').join('') : '

No rotations yet. Create one above, add two or more destinations, and share the short link.

'; - el.querySelectorAll('[data-rot]').forEach(row => row.addEventListener('click', () => openRotation(Number(row.dataset.rot)))); - if (ROT_ID) { const cur = ROT.find(x => x.id === ROT_ID); if (cur) fillRotation(cur); else { ROT_ID = null; $('rotCard').hidden = true; } } - } catch (e) { IAP.status('Could not load your rotations.', 'bad'); } - } - function fillRotation(x) { - $('rotCardName').textContent = x.name; $('rotCardLink').textContent = rotLink(x); - $('rotPause').textContent = x.paused ? 'Resume' : 'Pause'; - $('rotCardSum').textContent = x.hits + ' hits all time, ' + x.hits7 + ' in the last 7 days, ' + x.uniques + ' unique visitors, ' + x.bots + ' bot hits filtered' + (x.fallback ? '. Fallback: ' + x.fallback : '. No fallback set: with every destination paused the link shows a not-active page.'); - const t = $('rotDests'); - t.innerHTML = 'DestinationWeightShareHits7dUniques' + (x.destinations.length ? x.destinations.map(d => { const total = x.destinations.filter(q => q.active).reduce((n, q) => n + q.weight, 0) || 1; return '' + esc(d.label || 'Destination ' + d.id) + '
' + esc(d.url) + '' + (d.active ? Math.round(d.weight / total * 100) + '%' : 'paused') + '' + d.hits + '' + d.hits7 + '' + d.uniques + ' '; }).join('') : 'No destinations yet. Add at least one below.'); - t.querySelectorAll('[data-rw]').forEach(i => i.addEventListener('change', async () => { try { await api('/api/my/rotations/' + x.id + '/dest/' + i.dataset.rw, { weight: i.value }); loadRotator(); } catch (e) { IAP.status(e.message, 'bad'); } })); - t.querySelectorAll('[data-rt]').forEach(b => b.addEventListener('click', async () => { const d = x.destinations.find(q => q.id === Number(b.dataset.rt)); try { await api('/api/my/rotations/' + x.id + '/dest/' + b.dataset.rt, { active: !d.active }); loadRotator(); } catch (e) { IAP.status(e.message, 'bad'); } })); - t.querySelectorAll('[data-rx]').forEach(b => b.addEventListener('click', async () => { if (!await IAP.confirmBox('Remove this destination? Its hit history stays in the stats.')) return; try { await api('/api/my/rotations/' + x.id + '/dest/' + b.dataset.rx, { remove: true }); loadRotator(); } catch (e) { IAP.status(e.message, 'bad'); } })); - $('rotCard').hidden = false; - fetch('/api/my/rotations/' + x.id + '/stats').then(r => r.json()).then(st => { - if (!st || st.error) return; - const lst = (arr, label) => arr.length ? '
' + label + '
' + arr.map(a => esc(a.k) + ' ' + a.n).join(' · ') + '
' : ''; - $('rotStats').innerHTML = '
' + lst(st.country, 'By country') + lst(st.source, 'By source') + lst(st.device, 'By device') + '
' + (st.days.length ? '

Last days: ' + st.days.slice(-10).map(d => d.day.slice(5) + ' ' + d.n).join(' · ') + '

' : ''); - }).catch(() => {}); - } - function openRotation(id) { const x = ROT.find(r => r.id === id); if (!x) return; ROT_ID = id; fillRotation(x); $('rotCard').scrollIntoView({ behavior: 'smooth', block: 'nearest' }); } - if ($('rotNew')) $('rotNew').addEventListener('submit', async e => { e.preventDefault(); try { const r = await api('/api/my/rotations', { name: $('rotName').value, fallback: $('rotFallback').value }); $('rotName').value = ''; $('rotFallback').value = ''; ROT_ID = r.rotation.id; await loadRotator(); } catch (err) { IAP.status(err.message, 'bad'); } }); - if ($('rotAdd')) $('rotAdd').addEventListener('submit', async e => { e.preventDefault(); if (!ROT_ID) return; try { await api('/api/my/rotations/' + ROT_ID + '/dest', { url: $('rotUrl').value, label: $('rotLabel').value, weight: $('rotWeight').value }); $('rotUrl').value = ''; $('rotLabel').value = ''; $('rotWeight').value = 1; loadRotator(); } catch (err) { IAP.status(err.message, 'bad'); } }); - if ($('rotCopy')) $('rotCopy').addEventListener('click', async () => { try { await navigator.clipboard.writeText($('rotCardLink').textContent); $('rotCopy').textContent = 'Copied'; setTimeout(() => { $('rotCopy').textContent = 'Copy link'; }, 1500); } catch (e) { IAP.status('Copy failed; select the link by hand.', 'bad'); } }); - if ($('rotPause')) $('rotPause').addEventListener('click', async () => { const x = ROT.find(r => r.id === ROT_ID); if (!x) return; try { await api('/api/my/rotations/' + x.id, { paused: !x.paused }); loadRotator(); } catch (e) { IAP.status(e.message, 'bad'); } }); - if ($('rotDelete')) $('rotDelete').addEventListener('click', async () => { if (!ROT_ID || !await IAP.confirmBox('Delete this rotation? Its short link stops working immediately.')) return; try { await api('/api/my/rotations/' + ROT_ID, { remove: true }); ROT_ID = null; $('rotCard').hidden = true; loadRotator(); } catch (e) { IAP.status(e.message, 'bad'); } }); - if ($('rotClose')) $('rotClose').addEventListener('click', () => { ROT_ID = null; $('rotCard').hidden = true; }); - async function loadProspects() { - try { - const r = await (await fetch('/api/my/prospects')).json(); - if (r.error) return; - PP_STATUSES = r.statuses || PP_STATUSES; - const sel = $('ppStatus'); if (sel && !sel.options.length) sel.innerHTML = PP_STATUSES.map(s => '').join(''); - const list = r.prospects || []; const el = $('prospectList'); if (!el) return; - if (!list.length) { el.innerHTML = '

Nobody on the list yet.

'; return; } - const today = new Date(); today.setHours(0, 0, 0, 0); - el.innerHTML = list.map(p => { const due = p.nextTs && p.nextTs <= today.getTime() + 86399999; return '
' + esc(p.name) + (due ? ' follow up' : '') + '' - + '' + esc(p.contact || '') + (p.note ? ' · ' + esc(p.note) : '') + '' - + '' - + '' - + '
'; }).join(''); - const save = async (id, patch) => { const p = list.find(x => x.id === Number(id)); if (!p) return; try { await api('/api/my/prospects', Object.assign({}, p, patch)); } catch (e) { IAP.status(e.message, 'bad'); } }; - el.querySelectorAll('[data-pstatus]').forEach(s => s.addEventListener('change', () => save(s.dataset.pstatus, { status: s.value }))); - el.querySelectorAll('[data-pnext]').forEach(i => i.addEventListener('change', () => save(i.dataset.pnext, { next: i.value, nextTs: i.value ? Date.parse(i.value + 'T12:00:00') : null }))); - el.querySelectorAll('[data-pdel]').forEach(b => b.addEventListener('click', async () => { try { await api('/api/my/prospects/remove', { id: b.dataset.pdel }); loadProspects(); } catch (e) { IAP.status(e.message, 'bad'); } })); - } catch (e) {} - } - if ($('prospectForm')) $('prospectForm').addEventListener('submit', async e => { - e.preventDefault(); - try { - await api('/api/my/prospects', { name: $('ppName').value, contact: $('ppContact').value, status: $('ppStatus').value, nextTs: $('ppNext').value ? Date.parse($('ppNext').value + 'T12:00:00') : null }); - $('ppName').value = ''; $('ppContact').value = ''; $('ppNext').value = ''; loadProspects(); - } catch (err) { IAP.status(err.message, 'bad'); } - }); - // ── broadcast templates ── - const BC_TEMPLATES = [ - { label: 'Welcome', subject: 'Welcome to my line: your first three moves', html: '

Glad you are in. Three things today, in this order:

  1. Pick your username on the Profile tab (it becomes your link).
  2. Wallet tab: Connect and link wallet, then Switch on payouts. Both are free.
  3. Copy your invite link from My line and send it to one person.

Reply here if you get stuck on any of them. That is what I am here for.

' }, - { label: 'Switch on payouts', subject: 'One free step so nothing passes you by', html: '

Quick reminder: if payouts are not switched on yet, do it now on the Wallet tab. One free transaction.

The contract locks each buyer to their sponsor at their first purchase, and payouts only route to wallets that are switched on. Ready early and you never miss one.

' }, - { label: 'The $5 test', subject: 'See a payout land in real time', html: '

Want to see the whole thing work? Buy the $5 Micro package on Buy packages and watch the live ledger while you do it. You will see your credits mint and the split go out in the same transaction.

When you are ready to count as a qualifying buyer for me, the $20 Activation package is the one.

' }, - { label: 'Qualified Start', subject: 'How to open level 2 today with your own positions', html: '

You can be your own first buyers, openly. On Buy packages, the Qualified Start card lets you link a second wallet you own as a position. When it buys a $20 package, it counts as a qualifying buyer, half comes straight back to your main wallet, and the credits pool with yours.

Two positions open level 2 the same day. The three Qualified Start videos in Training show every click.

' }, - { label: 'Share your link', subject: 'One conversation a day is the whole job', html: '

Promo tools has posts, texts and emails that already carry your link. Pick one and send it to one person today.

Do not wait for the perfect moment. Nobody who waited ever built a line.

' } - ]; - (function () { - const w = $('bcTemplates'); if (!w) return; - w.innerHTML = BC_TEMPLATES.map((t, i) => '').join(''); - w.querySelectorAll('[data-bct]').forEach(b => b.addEventListener('click', () => { const t = BC_TEMPLATES[Number(b.dataset.bct)]; $('bcSubject').value = t.subject; $('bcEd').innerHTML = t.html; $('bcEd').focus(); })); - })(); - // ── Qualified Start calculator ── - (function () { - const n = $('qcN'), pk = $('qcPkg'), out = $('qcOut'); if (!n || !pk || !out) return; - const CR = { 25: 2500, 50: 5000, 100: 10000, 250: 25000, 500: 50000 }; // flat credits = cents (Marty 2026-10-07) - const calc = () => { - const k = Math.max(1, Math.min(10, Number(n.value) || 1)), usd = Number(pk.value) || 25; - const gross = k * usd, back = gross / 2, net = gross - back, credits = k * (CR[usd] || 0); - const level = k >= 5 ? 'Level 3 open (and level 2): the Nexus badge, wall position 3, full 50 / 20 / 10' : k >= 2 ? 'Level 2 open: 20% on your directs\' buyers, wall position 2' : 'Counts as one qualifying buyer. One more opens level 2.'; - out.innerHTML = '
$' + gross + ' out across ' + k + ' position' + (k === 1 ? '' : 's') + '
$' + back + ' back to your main wallet in the same transactions (the 50% direct-sponsor share)
$' + net + ' net, plus a little POL for gas in each wallet
' - + '
' + credits.toLocaleString() + ' credits pooled for your own ads
' + level + '
The 20% and 10% shares go to your upline if they are qualified, otherwise to the platform.
'; - }; - n.addEventListener('input', calc); pk.addEventListener('change', calc); calc(); - })(); - - // ── downline lineage + sponsor broadcast + upline messages ── - async function loadLineage() { - try { - const r = await (await fetch('/api/my/line')).json(); - const el = $('lineageWrap'); - if (r.error || !r.levels || !r.levels.every) return; - if (!r.levels.length || !r.levels.some(L => L.members.length)) { - el.innerHTML = '

No one in your downline yet. Share your link and it fills in here.

'; - return; - } - el.innerHTML = r.levels.map(L => !L.members.length ? '' : - '
Level ' + L.level + ' · ' + L.members.length + (L.level === 1 ? ' direct' : '') + '
' - + L.members.map(m => '
' + esc(m.name) + (m.own ? ' yours' : '') + '' - + '' + (m.email ? esc(m.email) : (m.memberId ? '#' + m.memberId + '' : '')) + (m.sponsor ? 'sponsored by ' + esc(m.sponsor) + '' : '') + (m.own ? '' : '' + (m.bought ? '$20+ buy ✓' : 'no $20+ buy yet') + (m.buyers ? ' · ' + m.buyers + ' qualifying buyer' + (m.buyers === 1 ? '' : 's') + ' of their own' : '') + '') + '' - + '' - + (m.earnedWei && m.earnedWei !== '0' ? '+' + IAP.fmtPol(m.earnedWei) + ' POL' : '0.00 POL') + '' - + '' + new Date(m.joined).toLocaleDateString() + '' - + (m.email ? '' : '') - + (m.ref && !m.own ? '' : '') - + '
' + (m.ref && !m.own ? '' : '')).join('') - + '
').join(''); - el.querySelectorAll('[data-cemail]').forEach(b => - b.addEventListener('click', () => openConvo(b.dataset.cemail, b.dataset.cname))); - el.querySelectorAll('[data-act]').forEach(b => b.addEventListener('click', () => toggleLineActivity(b))); - } catch (e) {} - } - // who is working: per-member activity drop-down under the row (any of the three levels) - const lineActCache = {}; - async function toggleLineActivity(btn) { - const box = document.querySelector('[data-actbox="' + btn.dataset.act + '"]'); if (!box) return; - const open = box.hidden; box.hidden = !open; btn.setAttribute('aria-expanded', String(open)); btn.textContent = open ? 'Activity ▴' : 'Activity ▾'; - if (!open) return; - if (!lineActCache[btn.dataset.act]) { - box.innerHTML = 'Loading…'; - try { lineActCache[btn.dataset.act] = await (await fetch('/api/my/line/activity?ref=' + encodeURIComponent(btn.dataset.act))).json(); } catch (e) { lineActCache[btn.dataset.act] = { error: 'Could not load.' }; } - } - const a = lineActCache[btn.dataset.act]; - if (a.error) { box.innerHTML = '' + esc(a.error) + ''; return; } - const ago = t => { if (!t) return 'never'; const d = Date.now() - t; if (d < 3600e3) return Math.max(1, Math.round(d / 60e3)) + ' min ago'; if (d < 86400e3) return Math.round(d / 3600e3) + 'h ago'; return Math.round(d / 86400e3) + 'd ago'; }; - const chip = (label, val, cls) => '' + esc(label) + '' + esc(val) + ''; - const working = (a.viewsToday || 0) > 0 || (a.campaignsActive || 0) > 0 || (a.linkViews30 || 0) > 0 || (a.lastSeen && Date.now() - a.lastSeen < 2 * 86400e3); - box.innerHTML = chip('Last seen', ago(a.lastSeen), a.lastSeen && Date.now() - a.lastSeen < 2 * 86400e3 ? 'on' : (a.quietDays >= 3 ? 'warn' : '')) - + chip('Joined', new Date(a.joined).toLocaleDateString()) - + chip('Stage', (a.rung || 'Joined') + (a.next ? ' · next: ' + a.next : ''), a.stalled ? 'warn' : '') - + chip('Ads today', (a.viewsToday || 0) + '/' + (a.target || 5) + (a.claimedToday ? ' claimed' : '') + (a.streakDay ? ' · streak day ' + a.streakDay : ''), (a.viewsToday || 0) > 0 ? 'on' : '') - + chip('Campaigns', (a.campaignsActive || 0) + ' active of ' + (a.campaigns || 0) + (a.imps ? ' · ' + a.imps.toLocaleString() + ' views' : ''), (a.campaignsActive || 0) > 0 ? 'on' : '') - + chip('Link', (a.linkViews30 || 0) + ' views (30d) · ' + (a.joins || 0) + ' joined', (a.linkViews30 || 0) > 0 ? 'on' : '') - + chip('Line', (a.directs || 0) + ' direct' + (a.directs === 1 ? '' : 's') + ' · ' + (a.buyerCount || 0) + ' qualifying', (a.buyerCount || 0) > 0 ? 'on' : '') - + chip('Wallet', a.wallet ? (a.badges && a.badges.includes('payouts') ? 'linked · payouts on' : 'linked') : 'not linked', a.wallet ? '' : 'warn') - + (a.badges && a.badges.length ? chip('Badges', a.badges.map(b => ({ payouts: 'Spark', firstBuyer: 'Surge', level2: 'Circuit', level3: 'Nexus' }[b] || b)).join(' · ')) : '') - + '' + (working ? 'Working' : 'Quiet') + ''; - } - async function loadUplineMessages() { - try { - const r = await (await fetch('/api/my/messages')).json(); - if (r.error) return; - const card = $('upMsgCard'), list = $('upList'); - if (!r.items || !r.items.length) { card.hidden = true; return; } - card.hidden = false; - list.innerHTML = r.items.map(i => '
' - + '
' + esc(i.subject) + '' - + '' + esc(i.fromName) + ' · ' + new Date(i.sent).toLocaleDateString() + '
' - + '
' + (i.body || '') + '
').join(''); - // opening the pane marks them read - for (const i of r.items) if (!i.read) fetch('/api/my/messages/' + i.id + '/read', { method: 'POST' }).catch(() => {}); - } catch (e) {} - } - // broadcast composer editor (its own small rich editor, server sanitizes) - document.querySelectorAll('[data-bc]').forEach(b => - b.addEventListener('click', () => { $('bcEd').focus(); document.execCommand(b.dataset.bc, false, null); })); - document.querySelectorAll('[data-bcblock]').forEach(b => - b.addEventListener('click', () => { $('bcEd').focus(); document.execCommand('formatBlock', false, b.dataset.bcblock); })); - if ($('bcLinkBtn')) $('bcLinkBtn').addEventListener('click', async () => { - const sel = window.getSelection(); const range = sel && sel.rangeCount ? sel.getRangeAt(0).cloneRange() : null; - const u = await IAP.ask({ title: 'Insert link', text: 'Link URL (https://…)', placeholder: 'https://', ok: 'Insert' }); - if (u) { $('bcEd').focus(); if (range) { sel.removeAllRanges(); sel.addRange(range); } document.execCommand('createLink', false, u); } - }); - if ($('bcSendBtn')) $('bcSendBtn').addEventListener('click', busy2($('bcSendBtn'), async () => { - const r = await api('/api/my/broadcast', { scope: $('bcScope').value, subject: $('bcSubject').value, body: $('bcEd').innerHTML }); - IAP.status('Broadcast sent to ' + r.sent + ' member' + (r.sent === 1 ? '' : 's') + '.', 'ok'); - $('bcSubject').value = ''; $('bcEd').innerHTML = ''; - $('bcHint').textContent = 'Sent. You can send your next broadcast in 24 hours.'; - })); - - // ── solo-ads inbox: list, read view, dwell-gated read reward ── - let ibTimer = null; - function setInboxBadge(n) { - for (const id of ['inboxBadge', 'inboxBadge2']) { - const b = $(id); - if (b) { b.hidden = !n; b.textContent = n; } - } - } - // Earn credits sub-tabs: Watch ads | Inbox - let earnSub = 'watch'; - function setEarnSub(which) { - earnSub = ['inbox', 'videos', 'visits'].includes(which) ? which : 'watch'; - if (earnSub !== 'videos' && vidState.token) stopVideo(); - const w = $('earn-watch'), i = $('earn-inbox'), v = $('earn-videos'), vs = $('earn-visits'); - if (w) w.hidden = earnSub !== 'watch'; - if (i) i.hidden = earnSub !== 'inbox'; - if (v) v.hidden = earnSub !== 'videos'; - if (vs) vs.hidden = earnSub !== 'visits'; - document.querySelectorAll('.subtabs [data-earn]').forEach(b => - b.classList.toggle('on', b.dataset.earn === earnSub)); - if (earnSub === 'inbox') loadInbox(); - else if (earnSub === 'videos') loadVideoStatus(); - else if (earnSub === 'visits') loadVisitStatus(); - else earnRefresh(); - } - document.querySelectorAll('.subtabs [data-earn]').forEach(b => - b.addEventListener('click', () => setEarnSub(b.dataset.earn))); - // promo toolkit: badge tiers + the AI Copy Engine (Marty, 2026-09-14) - let tkState = null; - async function loadToolkit() { - try { - const r = await (await fetch('/api/my/toolkit')).json(); if (r.error) return; tkState = r; - const esc = t => String(t == null ? '' : t).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c])); - const names = { free: 'Free', spark: 'Spark', surge: 'Surge', circuit: 'Circuit', nexus: 'Nexus' }; - $('tkTierLine').textContent = 'you are at ' + names[r.tier]; - $('tkTiers').innerHTML = r.tiers.map(t => '
' + esc(t.name) + (t.reached ? ' ✓' : '') + '
' + (t.reached ? esc(t.blurb) : 'Unlocks when you ' + esc(t.needText)) + '
    ' + t.items.map(i => '' + esc(i.t) + '').join('') + '
' + (t.reached ? '' : '
locked
') + '
').join(''); - $('tkLocked').hidden = r.unlocked; $('tkForm').hidden = !r.unlocked; - if (!r.unlocked) { $('tkLocked').textContent = 'Unlocks at Surge: your first qualifying buyer of a $20 or larger package. Then it writes posts, DMs, follow-ups, objection replies, emails and story posts in your name, with your link, inside the honesty rules. ' + (r.tier === 'free' ? 'Step one is switching on payouts.' : 'You are one buyer away.'); $('tkUsage').textContent = 'locked'; renderTkTools(r); return; } - $('tkUsage').textContent = r.freeLeft + ' free this month · then ' + r.cost + ' credits each · you have ' + r.available.toLocaleString() + ' credits'; - $('tkCostLine').textContent = r.freeLeft > 0 ? 'This one is free (' + r.freeLeft + ' left this month).' : 'This one costs ' + r.cost + ' credits from your earned pool.'; - if (!$('tkKind').options.length) { $('tkKind').innerHTML = r.kinds.map(k => '').join(''); $('tkAngle').innerHTML = r.angles.map(a => '').join(''); } - renderTkTools(r); - $('tkHistory').innerHTML = r.history.length ? '

Recent

' + r.history.map(h => '
' + esc(h.kind) + ' · ' + new Date(h.ts).toLocaleString() + (h.charged ? ' · ' + h.charged + ' credits' : ' · free') + '
' + esc(h.text).replace(/\n/g, '
') + '
').join('') : ''; - } catch (e) { console.error('toolkit', e); } - } - // the rest of the ladder: Spark templates + handout, Circuit Video Maker + split tester, Nexus Leader Ops - const tkEsc = t => String(t == null ? '' : t).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c])); - const tkRank = { free: 0, spark: 1, surge: 2, circuit: 3, nexus: 4 }; - async function tkPost(url, body) { const r = await (await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body || {}) })).json(); if (r.error) { IAP.status(r.error, 'bad'); return null; } return r; } - function renderTkTools(r) { - const at = tkRank[r.tier] || 0; - // Spark - const spark = at >= 1; $('tkSparkLocked').hidden = spark; $('tkSparkBody').hidden = !spark; - if (!spark) $('tkSparkLocked').textContent = 'Unlocks at Spark: switch on payouts in the Wallet tab. Then one tap builds a banner or text campaign aimed at your link, and you get a printable handout with your QR.'; - else { $('tkHandoutLine').hidden = !r.handoutUrl; if (r.handoutUrl) $('tkHandout').href = r.handoutUrl; } - // Circuit - const circ = at >= 3; $('tkCircuitLocked').hidden = circ; $('tkCircuitBody').hidden = !circ; - if (!circ) $('tkCircuitLocked').textContent = 'Unlocks at Circuit: two qualifying buyers in your line. Then every promo video gets your own end card and QR, and the split tester shows which join angle pulls for you.'; - else { loadTkVideos(r); loadTkSplit(); } - // Nexus - const nex = at >= 4; $('tkNexusLocked').hidden = nex; $('tkNexusBody').hidden = !nex; - if (!nex) $('tkNexusLocked').textContent = 'Unlocks at Nexus: five qualifying buyers. Then you get team triage across three levels with one-click nudges, AI-drafted team broadcasts, credit grants to your people, a co-branded join page and your own partner code.'; - else { loadTkTeam(); renderTkPartner(r); } - } - let tkVidTimer = null; - async function loadTkVideos(r) { - const box = $('tkVideos'); - if (!r.videoMaker) { box.innerHTML = '

The Video Maker is warming up on the server. Check back shortly.

'; return; } - if (!r.username) { box.innerHTML = '

Pick a username first (Profile); it goes on the end card.

'; return; } - try { - const v = await (await fetch('/api/my/toolkit/videos')).json(); if (v.error) return; - box.innerHTML = v.list.map(x => '
' + tkEsc(x.title) + '' + (x.status === 'done' ? 'Download ' : x.status === 'queued' || x.status === 'working' ? '
' + tkEsc(x.stage || 'Starting') + (x.status === 'working' ? ' · ' + (x.pct || 0) + '%' : '') + '' : '') + '
').join(''); - clearTimeout(tkVidTimer); if (v.list.some(x => x.status === 'queued' || x.status === 'working')) tkVidTimer = setTimeout(() => loadTkVideos(r), 2500); - } catch (e) {} - } - async function loadTkSplit() { - try { - const sp = await (await fetch('/api/my/toolkit/split')).json(); if (sp.error) return; - const rows = sp.rows.filter(x => x.views || x.joins); - $('tkSplit').innerHTML = !rows.length ? '

No link views yet. Share two different angle links this week and the winner shows up here.

' - : '
' + rows.map(x => '').join('') + '
AngleViewsLast 30dJoinsBuyersJoin rate
' + tkEsc(x.angle) + (x.angle === sp.best ? ' (winner so far)' : '') + '
' + tkEsc(x.link) + '
' + x.views + '' + x.views30 + '' + x.joins + '' + x.buyers + '' + x.rate + '%

Rate = joins per 100 views. A winner needs at least 10 views. Send more traffic to the winner, keep testing the rest.

'; - } catch (e) {} - } - let tkTeamData = null; - async function loadTkTeam() { - try { - const t = await (await fetch('/api/my/toolkit/team')).json(); if (t.error || !t.unlocked) return; tkTeamData = t; - $('tkTeamSub').textContent = t.total + ' in three levels (' + t.byLevel.join(' / ') + ') · ' + t.recent + ' new this week · ' + t.stalled.length + ' stalled'; - const list = t.stalled.length ? t.stalled : t.members.slice(0, 12); - $('tkTeam').innerHTML = (t.stalled.length ? '

Stalled first: quiet for a while and not yet past the next rung. One click sends them the right message from you.

' : '

Nobody stalled right now. Your newest people:

') - + list.map(m => '
' + tkEsc(m.name) + ' L' + m.level + ' · ' + tkEsc(m.label) + (m.quietDays ? ' · quiet ' + m.quietDays + 'd' : '') + '
Next: ' + tkEsc(m.next) + '
').join(''); - $('tkGrantTo').innerHTML = t.members.map(m => '').join(''); - } catch (e) {} - } - function renderTkPartner(r) { - const pk = r.partner; - $('tkPartner').innerHTML = pk - ? '

Code ' + tkEsc(pk.code) + ' gives ' + pk.credits + ' welcome credits, funded from your earned pool at each redemption. Redeemed ' + pk.uses + ' times.

Invite link with the code: ' + tkEsc(pk.link) + '

Your partner kit page (for list owners and site owners you talk to): ' + tkEsc(pk.kit) + '

' - : '

Give your recruits a welcome bonus under your own code. Each redemption moves the credits from your earned pool to theirs, so it only costs you when it works. Then hand partners the kit page, which sends their deals under you.

'; - } - document.addEventListener('click', async ev => { - const b = ev.target.closest('[data-tpl],[data-mkvid],[data-copyvid],[data-nudge],[data-copy],#tkPcGo,#tkGrantGo,#tkDraftBc,[data-sendnudge]'); if (!b) return; - if (b.dataset.tpl) { b.disabled = true; const r = await tkPost('/api/my/toolkit/template', { kind: b.dataset.tpl, budget: Number($('tkTplBudget').value) }); b.disabled = false; if (r) { IAP.status('Campaign "' + r.name + '" created with ' + r.budget + ' credits. It is under Campaigns.', 'ok'); loadDashboard(); } return; } - if (b.dataset.mkvid) { b.disabled = true; const r = await tkPost('/api/my/toolkit/video', { slug: b.dataset.mkvid }); if (r) { IAP.status(r.status === 'done' ? 'Already made.' : 'Rendering. It appears here in about a minute.', 'ok'); loadTkVideos(tkState); } else b.disabled = false; return; } - if (b.dataset.copyvid || b.dataset.copy) { try { await navigator.clipboard.writeText(b.dataset.copyvid || b.dataset.copy); IAP.status('Copied.', 'ok'); } catch (e) { IAP.status('Copy failed; select it by hand.', 'bad'); } return; } - if (b.dataset.nudge) { const row = b.closest('.tk-team'); const old = row.querySelector('.tk-nudge'); if (old) { old.remove(); return; } const box = document.createElement('div'); box.className = 'tk-nudge'; box.innerHTML = '
Lands in their inbox and their email.
'; box.querySelector('textarea').value = b.dataset.say; row.appendChild(box); return; } - if (b.dataset.sendnudge) { const box = b.closest('.tk-nudge'); b.disabled = true; const r = await tkPost('/api/my/toolkit/nudge', { email: b.dataset.sendnudge, text: box.querySelector('textarea').value }); b.disabled = false; if (r) { IAP.status('Sent.', 'ok'); box.remove(); } return; } - if (b.id === 'tkGrantGo') { b.disabled = true; const r = await tkPost('/api/my/toolkit/grant', { email: $('tkGrantTo').value, credits: Number($('tkGrantN').value) }); b.disabled = false; if (r) { IAP.status(r.credits + ' credits moved to ' + r.toName + '.', 'ok'); loadToolkit(); loadDashboard(); } return; } - if (b.id === 'tkPcGo') { b.disabled = true; const r = await tkPost('/api/my/toolkit/promo', { code: b.dataset.code || ($('tkPcCode') ? $('tkPcCode').value : ''), credits: Number($('tkPcN').value) }); b.disabled = false; if (r) { IAP.status('Code ' + r.code + ' is live: ' + r.credits + ' welcome credits.', 'ok'); loadToolkit(); } return; } - if (b.id === 'tkDraftBc') { if (!tkState || !tkState.unlocked) return; $('tkKind').value = 'broadcast'; $('tkBrief').placeholder = 'What should the team focus on this week?'; $('tkEngine').scrollIntoView({ behavior: 'smooth', block: 'start' }); $('tkBrief').focus(); IAP.status('Pick a focus, hit Write it, then Send to my team.', 'ok'); return; } - }); - $('tkKind') && $('tkKind').addEventListener('change', () => { if ($('tkSendBc')) $('tkSendBc').hidden = $('tkKind').value !== 'broadcast'; }); - async function tkSendBroadcast() { - const txt = $('tkText').value || ''; const m = /^\s*Subject:\s*(.+)\n+([\s\S]+)$/.exec(txt); - const subject = m ? m[1].trim() : 'A note from your sponsor', body = (m ? m[2] : txt).trim(); - if (!(await IAP.confirmBox('Send this to everyone in your three levels? One broadcast a day.', { title: 'Team broadcast', ok: 'Send' }))) return; - const r = await tkPost('/api/my/broadcast', { subject, body: '

' + tkEsc(body).replace(/\n{2,}/g, '

').replace(/\n/g, '
') + '

', scope: 'all' }); - if (r) IAP.status('Sent to ' + (r.sent || r.count || r.recipients || 'your team') + '.', 'ok'); - } - async function tkGenerate() { - const btn = $('tkGo'); if (btn.disabled) return; btn.disabled = true; btn.textContent = 'Writing…'; - try { - const r = await (await fetch('/api/my/toolkit/generate', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ kind: $('tkKind').value, angle: $('tkAngle').value, brief: $('tkBrief').value }) })).json(); - if (r.error) { IAP.status(r.error, 'bad'); return; } - $('tkText').value = r.text; $('tkOut').hidden = false; $('tkSendBc').hidden = $('tkKind').value !== 'broadcast'; - IAP.status(r.charged ? r.charged + ' credits used.' : 'Written. ' + r.freeLeft + ' free left this month.', 'ok'); - loadToolkit(); loadDashboard(); - } catch (e) { IAP.status('The engine did not answer. Try again.', 'bad'); } - finally { btn.disabled = false; btn.textContent = 'Write it'; } - } - if ($('tkGo')) { $('tkGo').addEventListener('click', tkGenerate); $('tkAgain').addEventListener('click', tkGenerate); $('tkCopy').addEventListener('click', async () => { try { await navigator.clipboard.writeText($('tkText').value); IAP.status('Copied.', 'ok'); } catch (e) { $('tkText').select(); } }); $('tkSendBc').addEventListener('click', tkSendBroadcast); } - // promo tools: pill menu switches between posts / swipes / banners / wall / videos - function setPromoSub(name) { - const ids = ['toolkit', 'posts', 'text', 'swipe', 'banners', 'wall', 'objections', 'videos']; - if (name === 'toolkit') loadToolkit(); - if (!ids.includes(name)) name = 'posts'; - ids.forEach(id => { const el = $('promo-' + id); if (el) el.hidden = id !== name; }); - document.querySelectorAll('.promo-pills [data-promo]').forEach(b => { - b.classList.toggle('on', b.dataset.promo === name); - b.setAttribute('aria-selected', b.dataset.promo === name ? 'true' : 'false'); - }); - try { localStorage.setItem('iap.promoSub', name); } catch (e) {} - } - document.querySelectorAll('.promo-pills [data-promo]').forEach(b => - b.addEventListener('click', () => setPromoSub(b.dataset.promo))); - try { setPromoSub(localStorage.getItem('iap.promoSub') || 'posts'); } catch (e) { setPromoSub('posts'); } - async function loadInbox() { - try { - const r = await (await fetch('/api/my/inbox')).json(); - if (r.error) return; - $('ibRewardNote').textContent = '+' + r.readCredits + ' credits per real read (up to ' - + r.readCap + ' rewarded reads a day)'; - const el = $('ibList'); - $('inboxReadCard').hidden = true; - $('inboxListCard').hidden = false; - setInboxBadge(r.unread); - if (!r.items.length) { - el.innerHTML = '

No solo ads yet. When a member sends one, it lands here — and reading it pays.

'; - return; - } - el.innerHTML = ''; - for (const i of r.items) { - const d = document.createElement('div'); - d.className = 'ib-row' + (i.read ? '' : ' unread'); - d.innerHTML = '' - + (i.rewarded ? 'claimed' : i.read ? '' : 'new') - + '' + new Date(i.delivered).toLocaleDateString() + ''; - d.querySelector('.sub').textContent = i.subject || '(no subject)'; - d.querySelector('.from').textContent = 'from ' + (i.fromName || 'a member'); - d.addEventListener('click', () => openInboxItem(i.id)); - el.appendChild(d); - } - } catch (e) {} - } - async function openInboxItem(id) { - try { - const r = await (await fetch('/api/my/inbox/' + id)).json(); - if (r.error) { IAP.status(r.error, 'bad'); return; } - $('inboxListCard').hidden = true; - $('inboxReadCard').hidden = false; - $('ibSubject').textContent = r.subject || '(no subject)'; - $('ibMeta').textContent = 'from ' + (r.fromName || 'a member') + ' · ' + new Date(r.delivered).toLocaleString(); - $('ibBody').innerHTML = r.body || ''; // whitelist-sanitized on the server at submit - const mv = $('ibMedia'); - mv.hidden = !r.mediaUrl; - mv.innerHTML = !r.mediaUrl ? '' - : r.mediaType === 'video' - ? '' - : 'attachment'; - // the read reward needs BOTH the dwell AND an actual click-through to the - // advertiser — the visit is what makes the ad worth the sender's credits - const visit = $('ibVisit'); - visit.href = r.url; - visit.textContent = r.ctaLabel || 'Learn more'; - visit.target = '_blank'; - const btn = $('ibClaimBtn'); - clearInterval(ibTimer); - if (r.rewarded) { - btn.hidden = true; - visit.classList.remove('cta-need'); - $('ibHint').textContent = 'Read reward already claimed for this one.'; - return; - } - let dwellDone = false; - let visited = !!r.visited; - btn.hidden = false; - btn.disabled = true; - visit.classList.toggle('cta-need', !visited); - let left = r.dwell; - const refresh = () => { - if (!dwellDone) { btn.textContent = 'Read it — claim in ' + left + 's'; return; } - if (!visited) { btn.textContent = 'Claim +' + r.reward + ' — visit the ad first'; btn.disabled = true; return; } - btn.textContent = 'Claim +' + r.reward + ' credits'; btn.disabled = false; - }; - $('ibHint').textContent = 'Read the message, click through to the advertiser, then claim your credits.'; - refresh(); - // countdown pauses off-tab; the server separately enforces the dwell on its own clock - ibTimer = setInterval(() => { - if (document.visibilityState !== 'visible' || !document.hasFocus()) return; - left -= 1; - if (left > 0) { refresh(); return; } - clearInterval(ibTimer); - dwellDone = true; - refresh(); - }, 1000); - // clicking the CTA records the visit (and counts the advertiser's click) - visit.onclick = async () => { - visited = true; - visit.classList.remove('cta-need'); - try { await fetch('/api/my/inbox/' + id + '/visit', { method: 'POST' }); } catch (e2) {} - refresh(); - }; - btn.onclick = async () => { - try { - const c = await api('/api/my/inbox/' + id + '/claim'); - IAP.status('+' + c.credited + ' credits for reading. They spend like any earned credits.', 'ok'); - btn.hidden = true; - $('ibHint').textContent = 'Claimed. Head back for the next one.'; - loadDashboard(); - } catch (e2) { IAP.status(e2.message, 'bad'); } - }; - } catch (e) {} - } - $('ibBack').addEventListener('click', ev => { ev.preventDefault(); clearInterval(ibTimer); loadInbox(); }); - - // ── promo tools: content + rendering live in promo.js (IAPPromo.fill) ── - function fillPromo(link, me) { - if (window.IAPPromo) IAPPromo.fill(link, me || {}); - // banner kit - const bwrap = $('promoBanners'); - if (bwrap && !bwrap.dataset.filled) { - bwrap.dataset.filled = '1'; - // one collapsed accordion per size / use, so the kit stays scannable as it grows - // LinkSpin kit (2026-10-08): neutral file names on purpose, ad blockers hide URLs with IAB size tokens - const GROUPS = [ - { title: '1200×630 · social posts, link previews, group covers', items: [ - { file: 'ls-social-a.jpg', size: '1200×630 · one link, every page you promote · Join free' }, - { file: 'ls-social-b.jpg', size: '1200×630 · paid the moment they buy · Join free' } ] }, - { title: '1080×1080 and 1080×1920 · Instagram, Facebook, stories, reels', items: [ - { file: 'ls-square.jpg', size: '1080×1080 · square' }, - { file: 'ls-story.jpg', size: '1080×1920 · story / reel' } ] }, - { title: '1280×720 · Telegram and group posts', items: [ - { file: 'ls-group.jpg', size: '1280×720 · group post' } ] }, - { title: 'Leaderboards · 728×90, 468×60, 320×50', items: [ - { file: 'ls-leader.png', size: '728×90 · leaderboard' }, - { file: 'ls-strip.png', size: '468×60 · banner' }, - { file: 'ls-bar.png', size: '320×50 · mobile leaderboard' } ] }, - { title: 'Rectangles and buttons · 336×280, 300×250, 250×250, 125×125', items: [ - { file: 'ls-panel.png', size: '336×280 · large rectangle' }, - { file: 'ls-box.png', size: '300×250 · medium rectangle' }, - { file: 'ls-square-s.png', size: '250×250 · square' }, - { file: 'ls-tile.png', size: '125×125 · button' } ] }, - { title: 'Skyscrapers · 160×600, 120×600', items: [ - { file: 'ls-tower.png', size: '160×600 · wide skyscraper' }, - { file: 'ls-column.png', size: '120×600 · skyscraper' } ] } - ]; - bwrap.innerHTML = ''; - for (const g of GROUPS) { - const det = document.createElement('details'); - det.className = 'pb-acc'; - det.innerHTML = '' + esc(g.title) + '' + g.items.length + (g.items.length === 1 ? ' banner' : ' banners') + '
'; - const grid = det.querySelector('.pb-grid'); - for (const b of g.items) { - const url = location.origin + '/kit/' + b.file; - const d = document.createElement('div'); - d.className = 'pb-item'; - d.innerHTML = 'LinkSpin banner ' + b.size + '' - + '
' + b.size + '
'; - const dl = document.createElement('a'); - dl.className = 'btn small'; dl.textContent = 'Download'; dl.href = '/kit/' + b.file; dl.setAttribute('download', b.file); - d.querySelector('.pb-row').appendChild(dl); - const btn = document.createElement('button'); - btn.className = 'btn small sec'; - btn.textContent = 'Copy image URL'; - btn.addEventListener('click', async () => { - try { await navigator.clipboard.writeText(url); IAP.status('Banner URL copied.', 'ok'); } - catch (e) { IAP.status('Copy failed.', 'bad'); } - }); - d.querySelector('.pb-row').appendChild(btn); - grid.appendChild(d); - } - bwrap.appendChild(det); - } - } - } - - // ── profile ── (busy2 defers the busy lookup past its TDZ) - $('pfSaveBtn').addEventListener('click', busy2($('pfSaveBtn'), async () => { - const r = await api('/api/my/profile', { username: $('pfUsername').value }); - IAP.status('You are @' + r.account.username + ' now.', 'ok'); - await render(); - })); - - // ── in-dashboard package buying ── - const PKG = { 1: 'Micro', 2: 'Activation', 3: 'Builder', 4: 'Growth', 5: 'Leader' }; - // Card on-ramp: buy POL with a card via MoonPay, delivered to the buyer's own - // wallet. Signed + wallet-prefilled once MoonPay keys are set; generic page - // otherwise. The site never touches funds — MoonPay is merchant of record. - async function openMoonpay(pol) { - try { - let addr = ''; - try { const me = await (await fetch('/api/me')).json(); addr = me.address || ''; } catch (e) {} - const q = '/api/moonpay-url?pol=' + encodeURIComponent(pol || '') + (addr ? '&address=' + encodeURIComponent(addr) : ''); - const r = await (await fetch(q)).json(); - if (r && r.url) { - window.open(r.url, '_blank', 'noopener'); - IAP.status(r.signed - ? 'MoonPay opened in a new tab with your wallet address pre-filled. Choose POL on Polygon, finish the purchase, then come back and buy your package.' - : 'MoonPay opened in a new tab. Choose POL on the Polygon network and paste your own wallet address as the destination, then come back.', 'ok'); - } - } catch (e) { IAP.status('Could not open MoonPay: ' + ((e && e.message) || e), 'bad'); } - } - // ── linked positions (Qualified Start) ── - const short = a => a ? a.slice(0, 6) + '…' + a.slice(-4) : ''; - let noPayoutAddrs = new Set(); // positions the site refuses to buy from (see siteConfig.noPayoutIds) - async function loadPositions(me) { - try { - const r = await (await fetch('/api/my/positions')).json(); - if (r.error) return; - const list = r.positions || []; - const rows = list.map((p, i) => '
Position ' + (i + 2) + ' ' + short(p.address) + '' - + '' + (p.memberId ? '#' + p.memberId : 'not on-chain yet') + '' - + '' + (p.noPayout ? 'linkage only: no purchases from this position (payouts would reach a retired wallet)' : p.counted ? 'counts as a qualifying buyer' : p.memberId ? 'registered, buy $20+ to count' : 'buy a $20+ package to register it') + '' - + '' + (p.credits || 0).toLocaleString() + ' credits' + (p.balanceWei != null ? ' · ' + (Number(BigInt(p.balanceWei) / 10n ** 14n) / 10000).toLocaleString(undefined, { maximumFractionDigits: 2 }) + ' POL' : '') + '' - + (!p.memberId ? '' : '') - + '
').join(''); - const mainRow = r.main && r.main.address ? '
Position 1 · main ' + short(r.main.address) + '' - + '' + (r.main.memberId ? '#' + r.main.memberId : 'payouts not on yet') + '' - + '' + (r.main.buyerCount || 0) + ' qualifying buyer(s)' - + '' + (r.main.credits || 0).toLocaleString() + ' credits' + (r.main.balanceWei != null ? ' · ' + (Number(BigInt(r.main.balanceWei) / 10n ** 14n) / 10000).toLocaleString(undefined, { maximumFractionDigits: 2 }) + ' POL' : '') + '
' : ''; - const html = mainRow + rows + (list.length ? '

Pooled credits: ' + (r.totalCredits || 0).toLocaleString() + '' + (r.credited ? ' plus ' + r.credited.toLocaleString() + ' credited to your account (spends from any position)' : '') + '. A campaign budget spends from one position at a time.

' : ''); - if ($('qsList')) $('qsList').innerHTML = html; - // Wallet tab: live POL balance of the linked wallet, and which package it covers - const wb = $('walletBal'); - if (wb && r.main && r.main.address && r.main.balanceWei != null) { - const polN = Number(BigInt(r.main.balanceWei) / 10n ** 14n) / 10000; - const usd = r.polUsd ? polN * r.polUsd : 0; - const pkgs = [5, 20, 50, 100, 250]; - const covers = r.polUsd ? pkgs.filter(p => usd >= p * 1.06 + 0.05) : []; - wb.hidden = false; - wb.innerHTML = 'Wallet balance: ' + polN.toLocaleString(undefined, { maximumFractionDigits: 2 }) + ' POL' + (usd ? ' (about $' + usd.toLocaleString(undefined, { maximumFractionDigits: 0 }) + ')' : '') - + (r.polUsd ? '
' + (covers.length ? 'Enough for the $' + covers[covers.length - 1] + ' package with gas to spare.' : 'Not enough for the $5 package yet. Buy POL with a card on the Buy packages tab, or send POL to this wallet.') + (covers.length && covers.length < pkgs.length ? ' Top up for the $' + pkgs[covers.length] + ' package.' : '') + '' : ''); - } - if ($('posList')) $('posList').innerHTML = html; - if ($('posCard')) $('posCard').hidden = !list.length; - // "Buy from" picker: main + every position - const sel = $('buyFrom'); - if (sel) { - const keep = sel.value; - sel.innerHTML = '' - + list.map((p, i) => '').join(''); - noPayoutAddrs = new Set(list.filter(p => p.noPayout).map(p => p.address.toLowerCase())); if (r.main && r.main.noPayout && r.main.address) noPayoutAddrs.add(r.main.address.toLowerCase()); - if (keep && [...sel.options].some(o => o.value === keep)) sel.value = keep; - $('buyFromWrap').hidden = !list.length; - } - document.querySelectorAll('[data-unlink]').forEach(b => b.addEventListener('click', async () => { - if (!(await IAP.confirmBox('Unlink ' + short(b.dataset.unlink) + ' from your account?', { title: 'Unlink position', ok: 'Unlink' }))) return; - try { await api('/api/my/positions/remove', { address: b.dataset.unlink }); IAP.status('Position unlinked.', 'ok'); loadPositions(); } - catch (e) { IAP.status(e.message, 'bad'); } - })); - } catch (e) {} - } - if ($('qsAddBtn')) $('qsAddBtn').addEventListener('click', busy2($('qsAddBtn'), async () => { - const me = await (await fetch('/api/me')).json(); - if (!me.address) throw new Error('Link your main wallet first (Wallet tab), then add positions under it.'); - if (!me.memberId) throw new Error('Switch on payouts for your main wallet first (Wallet tab). Positions register under your member number.'); - if (!(await IAP.confirmBox('Your wallet will ask which account to connect. Tick ONLY the new account (not ' + short(me.address) + '), then sign once.\n\nIf you have not created the extra account yet: MetaMask, account menu, Add account. Trust or SafePal: switch wallet.\n\nReady?', { title: 'Add a position', ok: 'Ready' }))) return; - IAP.status('Pick the new account in your wallet, then sign once…'); - const r = await IAPWallet.signIn({ asPosition: true, pick: true }); - $('qsHint').textContent = 'Added ' + short(r.address) + '. Now choose it under "Buy from" and buy a $20 or larger package.'; - IAP.status('Position added: ' + short(r.address) + '. Pick it under "Buy from" above and buy a $20+ package to count it.', 'ok'); - await loadPositions(); - const sel = $('buyFrom'); if (sel) sel.value = r.address.toLowerCase(); - try { $('buyFrom').scrollIntoView({ behavior: 'smooth', block: 'center' }); } catch (e) {} - })); - async function loadBuyTiles() { - try { - const { products } = await (await fetch('/api/catalog')).json(); - const wrap = $('boTiles'); - wrap.innerHTML = ''; - for (const p of products) { - const bonus = p.creditAmount - p.priceCents; - const div = document.createElement('div'); - div.className = 'tile' + (p.priceCents === 5000 ? ' hot' : ''); - div.innerHTML = '
' + (PKG[p.id] || 'Package ' + p.id) + '
' - + '
$' + Math.round(p.priceCents / 100) + '
' - + '
' + p.creditAmount.toLocaleString() + ' credits
' - + '
' + (bonus > 0 ? '+' + bonus.toLocaleString() + ' bonus credits' : ' ') + '
' - + '
' + (p.costWei ? IAP.fmtPol(p.costWei) + ' POL right now' : 'paused') + '
' - + ''; - wrap.appendChild(div); - } - wrap.querySelectorAll('button[data-id]').forEach(b => b.addEventListener('click', async () => { - try { - b.disabled = true; - // the buyer's credits are read by the member id of their LINKED wallet. - // If they only connected a wallet (e.g. for the faucet) but never linked - // it, link it first (one signature) so the purchase's credits show up. - // retry these through transient failures — mobile drops in-flight - // fetches when the page returns from the wallet app-switch - const jretry = async url => { let err; for (let i = 0; i < 4; i++) { try { return await (await fetch(url)).json(); } catch (e) { err = e; await new Promise(s => setTimeout(s, 500 * (i + 1))); } } throw err; }; - const meNow = await jretry('/api/me'); - // which of the member's wallets is buying: the main wallet (default) or a - // linked position (Qualified Start). A position registers under the main - // member id on its first buy, so its sponsor is always this member. - const fromSel = $('buyFrom'); - const fromPos = (fromSel && !$('buyFromWrap').hidden && fromSel.value && fromSel.value !== 'main') ? fromSel.value.toLowerCase() : null; - if (fromPos && !meNow.memberId) { IAP.status('Switch on payouts for your main wallet first (Wallet tab), so this position can register under you.', 'bad'); return; } - if (noPayoutAddrs.has(fromPos || String(meNow.address || '').toLowerCase())) { IAP.status('This position is kept for linkage only. A purchase from it would pay a retired wallet. Buy from your main wallet or another position.', 'bad'); return; } - if (!fromPos && !meNow.address) { - IAP.status('Link your wallet first — one quick signature…'); - await IAPWallet.signIn(); - } - const wantAddr = fromPos || (meNow.address ? meNow.address.toLowerCase() : null); - if (wantAddr) { // never buy from a wallet other than the one selected: a stray wallet would register a brand-new member - await IAPWallet.connect(); - let cur = String(await IAPWallet.activeAddress() || '').toLowerCase(); - if (cur !== wantAddr) { - IAP.status('Pick ' + wantAddr.slice(0, 6) + '…' + wantAddr.slice(-4) + ' in your wallet\'s account picker…'); - cur = String(await IAPWallet.pickAccount() || '').toLowerCase(); - } - if (cur !== wantAddr) throw new Error('Your wallet connected as ' + cur.slice(0, 6) + '…' + cur.slice(-4) + ' but you chose ' + wantAddr.slice(0, 6) + '…' + wantAddr.slice(-4) + '. Switch accounts in your wallet app and try again.'); - } - const spNow = fromPos ? { sponsorId: meNow.memberId } : await jretry('/api/sponsor'); - if (!fromPos && !meNow.memberId && spNow.sponsorBlocked) { IAP.status(sponsorHoldText(spNow), 'bad'); return; } // first activation must not hand a sponsored member to the company - // pre-flight: stop early if the POL is not there. Trust Wallet also hard-blocks any - // transaction that spends most of the balance ("drain your wallet"), so Trust users - // get a heads-up first; other wallets go straight to the confirmation. - try { - const need = BigInt(b.dataset.cost) + BigInt(b.dataset.cost) / 50n; // same 2% pad as buy() - const bal = await IAPWallet.balance(wantAddr || IAPWallet.address() || meNow.address); - if (bal < need) { - IAP.status('That wallet holds ' + IAP.fmtPol(bal.toString()) + ' POL, but this package needs about ' + IAP.fmtPol(need.toString()) + ' POL plus a little for gas. Top it up and try again.', 'bad'); - return; - } - const pct = Number(need * 100n / bal); - const isTrust = /trust/i.test(IAPWallet.walletName() || ''); - if (isTrust && pct > 55 && !(await IAP.confirmBox('Heads up for Trust Wallet users: this purchase uses about ' + pct + '% of the POL in your wallet, and Trust Wallet refuses transactions that spend most of the balance (it shows a "drain your wallet" warning with only Stop and go back).' + '\n\n' + 'Options: pick a smaller package first, add some POL, or connect a different wallet (MetaMask, Phantom, SafePal). Extra POL always stays yours.' + '\n\n' + 'Try it anyway?', { title: 'Trust Wallet check', ok: 'Buy anyway', cancel: 'Pause' }))) { - IAP.status('Purchase paused. Pick a smaller package, add POL, or connect another wallet, then try again.', 'ok'); - return; - } - } catch (e) { /* balance read failed: let the wallet decide */ } - IAP.status('Confirm the purchase in your wallet…'); - const r = await IAPWallet.buy(Number(b.dataset.id), spNow.sponsorId || 0, b.dataset.cost); - if (r.status !== '0x1' && r.receipt && r.receipt.status !== '0x1') throw new Error('Transaction reverted.'); - IAP.status(fromPos ? 'Purchase settled on-chain. That position now counts toward your qualification, and its credits pool with yours.' : 'Purchase settled on-chain. Credits are in your account.', 'ok'); - await render(); - loadBuyTiles(); - } catch (e) { IAP.status('Purchase failed: ' + ((e && e.message) || e), 'bad'); } - finally { b.disabled = false; } - })); - // brand new to crypto? buy POL with a card, sent straight to the wallet - const builder = products.find(p => p.priceCents === 5000) || products[products.length - 1]; - const needPol = (builder && builder.costWei) ? Math.max(30, Math.ceil(Number(builder.costWei) / 1e18) + 3) : 30; - const cta = document.createElement('div'); - cta.style.cssText = 'grid-column:1/-1;margin-top:10px;text-align:center'; - cta.innerHTML = '

New to crypto? Buy POL with a debit or credit card, Apple Pay, or Google Pay. It lands straight in your own wallet, and this site never touches your money.

' - + ' Wallet and MoonPay guide'; - wrap.appendChild(cta); - const mb = $('moonpayBtn'); if (mb) mb.addEventListener('click', () => openMoonpay(needPol)); - } catch (e) {} - } - loadBuyTiles(); - - // ── earn-by-viewing: daily ad set with dwell, then claim ── - const earnState = { types: ['banner', 'text'], i: 0, timer: null }; - async function earnRefresh() { - try { - const st = await (await fetch('/api/my/earn')).json(); - if (st.error) return null; - $('earnProgress').textContent = 'today: ' + st.views + ' / ' + st.target + ' ads viewed'; - $('earnBalance').textContent = (st.earnedAvailable != null ? st.earnedAvailable : st.earned) + ' earned credits available' + (st.reserved ? ' · ' + st.reserved + ' in live campaigns' : ''); - const done = st.views >= st.target; - $('earnClaimBtn').hidden = !(done && !st.claimed); - if (st.claimed) { - $('earnHint').textContent = 'Claimed for today' + (st.streakDay > 1 ? ' (streak day ' + st.streakDay + ')' : '') + '. Tomorrow\'s claim pays ' + st.nextClaim + ' credits if you come back.'; - // after the set (Marty, 2026-09-12): keep going with verified visits, and turn the credits into a campaign - const box = $('earnAdBox'); - if (box) box.innerHTML = '
✓Ads done for todayToday\'s set is viewed and claimed. Fresh ads tomorrow.' - + '
' - + (st.visitsLeft ? '' : '') - + ((st.earnedAvailable != null ? st.earnedAvailable : st.earned) > 0 - ? '' - : '') + '
'; - if (box) box.querySelectorAll('[data-earnnext]').forEach(b => b.addEventListener('click', () => { if (b.dataset.earnnext === 'campaigns') setPane('campaigns'); else setEarnSub('visits'); })); - if ($('earnStartBtn')) $('earnStartBtn').hidden = true; - } else { - if ($('earnStartBtn')) $('earnStartBtn').hidden = done; // set done: the claim button takes over - $('earnHint').textContent = done - ? 'Set complete. Claim your ' + st.claimCredits + ' credits' + (st.streakDay > 1 ? ' (streak day ' + st.streakDay + ')' : '') + '.' - : (st.views ? (st.target - st.views) + ' more to go, then claim ' + st.claimCredits + ' credits' + (st.streakDay > 1 ? ' (streak day ' + st.streakDay + ')' : '') + '.' : 'View ' + st.target + ' ads to unlock the daily claim of ' + st.claimCredits + ' credits' + (st.streakDay > 1 ? ' (streak day ' + st.streakDay + ')' : '') + '.'); - } - return st; - } catch (e) { return null; } - } - async function earnShowAd() { - // each view happens full screen in its own tab: /view/ frames the - // advertiser's site, runs the countdown, then a human check credits it - const type = earnState.types[earnState.i++ % earnState.types.length]; - let r = null; - try { r = await (await fetch('/api/my/earnview?type=' + type)).json(); } catch (e) {} - const box = $('earnAdBox'); - if (!r || !r.ad || !r.viewUrl) { - await earnRefresh(); - box.innerHTML = '' + (r && r.status && r.status.views >= r.status.target - ? 'Set complete for today.' - : 'No member ads are live in rotation right now. Views resume the moment a campaign is running.') + ''; - return; - } - openAdOverlay(r.viewUrl); - box.innerHTML = 'Watch the countdown and pass the quick check. Your view credits itself and this page updates right away.'; - $('earnStartBtn').textContent = 'View next ad'; - } - // In-page ad overlay: no new tab (mobile and in-app wallet browsers handle tabs - // badly), no window.close needed. The /view page runs the dwell + check inside, - // messages back when it credits or when the user is done. - function openAdOverlay(url) { - closeAdOverlay(); - const back = document.createElement('div'); - back.id = 'adOverlay'; - back.style.cssText = 'position:fixed;inset:0;z-index:100000;background:#050b09;display:flex;flex-direction:column'; - const x = document.createElement('button'); - x.type = 'button'; x.setAttribute('aria-label', 'Close ad'); - x.textContent = '✕'; - x.style.cssText = 'position:absolute;top:10px;right:12px;z-index:2;width:40px;height:40px;border-radius:50%;border:1px solid rgba(255,255,255,.25);background:rgba(6,10,16,.85);color:#fff;font-size:20px;font-weight:700;cursor:pointer'; - x.addEventListener('click', closeAdOverlay); - const ifr = document.createElement('iframe'); - ifr.src = url; - ifr.style.cssText = 'flex:1;width:100%;border:0;background:#050b09'; - back.appendChild(ifr); back.appendChild(x); - document.body.appendChild(back); - document.body.style.overflow = 'hidden'; - } - function closeAdOverlay() { - const m = $('adOverlay'); if (m) m.remove(); - document.body.style.overflow = ''; - earnRefresh(); loadDashboard(); - } - window.addEventListener('message', e => { - if (e.origin !== location.origin || !e.data) return; - if (e.data.t === 'iap-view-close') closeAdOverlay(); - else if (e.data.t === 'iap-view-done') { earnRefresh(); loadDashboard(); } - }); - $('earnStartBtn').addEventListener('click', () => earnShowAd()); - // the viewer tab pings localStorage when a view credits; refresh instantly - window.addEventListener('storage', e => { - if (e.key === 'iap-view-done') { earnRefresh(); loadDashboard(); } - }); - document.addEventListener('visibilitychange', () => { - if (document.visibilityState === 'visible' && $('pane-earn') && !$('pane-earn').hidden) earnRefresh(); - }); - $('earnClaimBtn').addEventListener('click', async () => { - try { - const r = await api('/api/my/claim'); - IAP.status('+' + r.credited + ' credits earned' + (r.streakDay > 1 ? ', streak day ' + r.streakDay : '') + '. Tomorrow\'s claim pays ' + r.nextClaim + '. Spend them in Campaigns.', 'ok'); - await earnRefresh(); - loadDashboard(); - } catch (e) { IAP.status(e.message, 'bad'); } - }); - - const busy = (btn, fn) => async () => { - try { btn.disabled = true; await fn(); } - catch (e) { IAP.status((e && e.message) || String(e), 'bad'); } - finally { btn.disabled = false; } - }; - - // passwordless (feature-flagged on config.emailAuth): code replaces passwords - (async () => { - const cfg = await IAP.getConfig(); - if (!cfg.emailAuth) return; - $('passCards').hidden = true; - $('magicCard').hidden = false; - const codeOpts = () => ({ honeypot: $('mcWebsite'), host: $('mcCheck') }); - const start = busy($('mcSendBtn'), async () => { - const r = await IAP.requestCode($('mcEmail').value, codeOpts()); - $('mcCodeRow').hidden = false; - $('mcVerifyBtn').hidden = false; - $('mcSendBtn').hidden = true; - $('mcResend').hidden = false; - if (r.devCode) { $('mcCode').value = r.devCode; IAP.status('Dev mode: code filled in for you.', 'ok'); } - else IAP.status('Code sent. Check your inbox (and spam, the first time).', 'ok'); - $('mcCode').focus(); - }); - $('mcSendBtn').addEventListener('click', start); - $('mcResend').addEventListener('click', busy($('mcResend'), async () => { - const r = await IAP.requestCode($('mcEmail').value, codeOpts()); - if (r.devCode) $('mcCode').value = r.devCode; - IAP.status('Fresh code sent.', 'ok'); - })); - $('mcVerifyBtn').addEventListener('click', busy($('mcVerifyBtn'), async () => { - const r = await api('/api/auth/email/verify', { email: $('mcEmail').value, code: $('mcCode').value, newsletter: !!($('nlOptin') && $('nlOptin').checked) }); - IAP.status('You are in.', 'ok'); - if (r.created && !(r.account && r.account.username)) await showOnboard(); // pick a username first - if (!(await showGauntlet())) await showLoginAd(); // welcome tour outranks the login ad - await render(); - })); - })(); - - // new-member onboarding: choose a username (required), optionally a bio. - // required=true: no skip, no backdrop dismiss, prefilled suggestion, resolves only after a save. - function showOnboard(required) { - return new Promise(resolve => { - const m = $('onboardModal'); if (!m) return resolve(); - m.hidden = false; $('obErr').hidden = true; - $('obSkip').hidden = !!required; - if (required && !$('obUsername').value) { - fetch('/api/my/username-suggest').then(r => r.json()).then(r => { if (r.suggest && !$('obUsername').value) { $('obUsername').value = r.suggest; $('obUsername').select(); } }).catch(() => {}); - } - setTimeout(() => $('obUsername').focus(), 50); - const done = () => { m.hidden = true; resolve(); }; - $('obSkip').onclick = required ? null : done; - $('obUsername').onkeydown = e => { if (e.key === 'Enter') { e.preventDefault(); $('obSave').click(); } }; - $('obSave').onclick = async () => { - const u = $('obUsername').value.trim(); - if (required && !u) { $('obErr').hidden = false; $('obErr').textContent = 'Pick a username to continue.'; return; } - try { - if (u) await api('/api/my/profile', { username: u }); - const bio = $('obBio').value.trim(); - if (bio) await api('/api/my/profile-details', { bio }); - done(); - } catch (e) { $('obErr').hidden = false; $('obErr').textContent = e.message || 'Could not save that. Try a different username.'; } - }; - }); - } - - $('signupBtn').addEventListener('click', busy($('signupBtn'), async () => { - const r = await api('/api/signup', { email: $('suEmail').value, password: $('suPass').value, newsletter: !!($('nlOptin') && $('nlOptin').checked) }); - IAP.status('Welcome aboard. You are in.', 'ok'); - if (!(r.account && r.account.username)) await showOnboard(); - await render(); - })); - $('loginBtn').addEventListener('click', busy($('loginBtn'), async () => { - await api('/api/login', { email: $('liEmail').value, password: $('liPass').value }); - IAP.status('Logged in.', 'ok'); - if (!(await showGauntlet())) await showLoginAd(); // welcome tour outranks the login ad - await render(); - })); - $('linkBtn').addEventListener('click', busy($('linkBtn'), async () => { - IAP.status('Check your wallet for the free link signature…'); - await IAPWallet.signIn(); // server binds the wallet to the signed-in email account - IAP.status('Wallet linked. Earnings pay there from now on.', 'ok'); - await render(); - })); - if ($('faucetBtn')) $('faucetBtn').addEventListener('click', busy($('faucetBtn'), async () => { - IAP.status('Connect your wallet first…'); - const addr = await IAPWallet.connect(); - let copied = false; - try { await navigator.clipboard.writeText(addr); copied = true; } catch (e) {} - window.open('https://faucet.polygon.technology/', '_blank', 'noopener'); - $('faucetInfo').innerHTML = 'Your address ' + addr.slice(0, 8) + '…' + addr.slice(-6) + '' - + (copied ? ' is copied' : '') + '. On the faucet, choose Polygon Amoy, paste your address, and request POL. Then come back and buy.'; - IAP.status('Faucet opened in a new tab. Choose Polygon Amoy, paste your address, and request test POL.', 'ok'); - })); - if ($('wcDisconnect')) $('wcDisconnect').addEventListener('click', busy($('wcDisconnect'), async () => { - // fire-and-forget: don't gate the reload on disconnect resolving (it can - // stall). The reload drops all in-memory wallet state and the picker returns. - IAPWallet.disconnect().catch(() => {}); - $('wcDisconnectInfo').textContent = 'Disconnecting — reloading so you can pick a different wallet…'; - IAP.status('Disconnecting — reloading…', 'ok'); - setTimeout(() => location.reload(), 900); - })); - // a named sponsor that cannot be paid right now: hold the transaction and say why (never credit the company by default) - function sponsorHoldText(sp) { - const who = sp.sponsorName || 'your sponsor'; - if (sp.sponsorBlocked === 'claim' && sp.claim) return (sp.claim.nobody ? 'Nobody above you on LinkSpin has a wallet yet, so there is no one for the contract to pay. ' : who + ' has not linked a wallet on LinkSpin yet. They have until ' + new Date(sp.claim.deadline).toLocaleString() + ' to do it, and we have told them. ') + 'You can use everything else meanwhile; your purchase waits so it pays the right person.'; - if (sp.sponsorBlocked === 'notActivated') return who + ' has not switched on payouts yet, so this purchase would credit the company instead of them. Ask them to switch on payouts (Wallet tab, one free transaction), then try again.'; - if (sp.sponsorBlocked === 'rpc') return 'Could not confirm your sponsor on the chain just now. Try again in a minute; nothing was charged.'; - return 'Your sponsor link could not be matched to a member. Message support before buying so ' + who + ' gets credit.'; - } - $('activateBtn').addEventListener('click', busy($('activateBtn'), async () => { - const me = await (await fetch('/api/me')).json(); - if (me.sponsorBlocked) { IAP.status(sponsorHoldText(me), 'bad'); return; } - IAP.status('Confirm the free activation in your wallet…'); - const r = await IAPWallet.activate(me.sponsorId || 0); - if (r.receipt.status !== '0x1') throw new Error('Transaction reverted. Check the explorer.'); - IAP.status('Payouts are on. Your invite link is live.', 'ok'); - await render(); - })); - $('copyInvite').addEventListener('click', async () => { - try { await navigator.clipboard.writeText($('inviteLine').textContent); IAP.status('Link copied.', 'ok'); } - catch (e) { IAP.status('Copy failed. Select and copy the link text.', 'bad'); } - }); - $('logoutLink').addEventListener('click', async e => { - e.preventDefault(); - await fetch('/api/auth/logout', { method: 'POST' }); - IAP.status('Logged out.', 'ok'); - await render(); - }); - - // ── welcome tour (viral banner gauntlet): a new member meets their 3-level - // upline's sites, 10 focus-paused seconds each, then unlocks welcome credits. - // Same three levels the contract pays — the tour IS the org chart. - async function showGauntlet() { - try { - const g = await (await fetch('/api/my/gauntlet')).json(); - if (!g.pending || !g.slides || !g.slides.length) return false; - const gate = $('gauntGate'); - gate.hidden = false; - for (let i = 0; i < g.slides.length; i++) { - const s = g.slides[i]; - $('ggWho').textContent = 'Position ' + (i + 1) + ': ' + s.name + (i === 0 ? ' — the person who invited you' : ''); - $('ggProgress').textContent = 'Meeting your line: ' + (i + 1) + ' of ' + g.slides.length; - $('ggFrame').hidden = false; - $('ggFrame').src = s.targetUrl; - let left = g.dwell || 10; - $('ggTimer').textContent = left + 's'; - await new Promise(done => { - const t = setInterval(() => { - if (document.visibilityState !== 'visible' || !document.hasFocus()) return; - left -= 1; - $('ggTimer').textContent = Math.max(0, left) + 's'; - if (left <= 0) { clearInterval(t); done(); } - }, 1000); - }); - } - $('ggFrame').src = 'about:blank'; - $('ggFrame').hidden = true; // avoid a white about:blank panel once the tour is done - $('ggTimer').textContent = '✓'; - $('ggWho').textContent = 'That is your line. When you grow, they earn — and yours starts the day you share.'; - $('ggClaim').hidden = false; - await new Promise(done => { - $('ggClaim').onclick = async () => { - try { - const r = await api('/api/my/gauntlet/complete', { token: g.token }); - IAP.status('+' + r.credited + ' welcome credits unlocked. They spend on real campaigns.', 'ok'); - } catch (e) { IAP.status(e.message, 'bad'); } - done(); - }; - }); - gate.hidden = true; - $('ggClaim').hidden = true; - return true; - } catch (e) { return false; } - } - - // ── line banner (profile): the member's slot on welcome tours + their wall ── - function fillLineBanner(a) { - if (!a) return; - if (a.lineTargetUrl) $('lbTarget').value = a.lineTargetUrl; - if (a.lineBannerUrl) { - $('lbBanner').value = a.lineBannerUrl; - $('lbPreview').hidden = false; - $('lbPreview').innerHTML = 'line banner'; - } - $('lbCurrent').textContent = a.lineTargetUrl - ? 'Live: your next three levels meet ' + a.lineTargetUrl + ' on their welcome tour.' - : 'Not set yet. Until you set one, your tour slot is skipped.'; - } - async function loadLineBanner() { - try { - const a = await (await fetch('/api/me')).json(); - fillLineBanner(a); - fillProfileDetails(a); - // buyerCount + wallUnlocked live on the dashboard payload (chain read), not on /api/me - let d = {}; try { d = await (await fetch('/api/my/dashboard')).json(); } catch (e) {} - fillWallOffers(Object.assign({}, a, { buyerCount: d.buyerCount || 0, wallUnlocked: d.wallUnlocked || 1 })); - } catch (e) {} - } - // ── wall positions 2 & 3: the member's own offers, unlocked by qualifying buyers ── - function fillWallOffers(a) { - if (!a || !$('wallOffersCard')) return; - const unlocked = a.wallUnlocked || 1, bc = a.buyerCount || 0; - const offers = Array.isArray(a.wallOffers) ? a.wallOffers : []; - const NEED = [2, 5]; - for (let i = 0; i < 2; i++) { - const o = offers[i] || {}; - const open = unlocked >= i + 2; - $('woTitle' + i).value = o.title || ''; $('woTarget' + i).value = o.targetUrl || ''; $('woBanner' + i).value = o.bannerUrl || ''; - $('woPrev' + i).hidden = !o.bannerUrl; $('woPrev' + i).innerHTML = o.bannerUrl ? '' : ''; - $('woLock' + i).textContent = open ? 'yours' : 'unlocks at ' + NEED[i] + ' qualifying buyers (' + bc + '/' + NEED[i] + ')'; - $('woSlot' + i).classList.toggle('locked', !open); - } - $('woStatus').textContent = unlocked >= 3 ? 'Fully qualified: all three wall positions are yours.' - : unlocked === 2 ? 'Position 2 is yours. ' + (5 - bc) + ' more qualifying buyer' + (5 - bc === 1 ? '' : 's') + ' and position 3 is too.' - : (2 - bc) + ' more qualifying buyer' + (2 - bc === 1 ? '' : 's') + ' ($20 or more) opens position 2. You can set your links now; they go live the moment a slot unlocks.'; - } - document.querySelectorAll('.wo-upload').forEach(b => b.addEventListener('click', () => { const f = document.querySelector('.wo-file[data-slot="' + b.dataset.slot + '"]'); if (f) f.click(); })); - document.querySelectorAll('.wo-file').forEach(inp => inp.addEventListener('change', async () => { - const i = inp.dataset.slot, f = inp.files[0]; if (!f) return; - $('woInfo' + i).textContent = 'Uploading…'; - try { - const r = await (await fetch('/api/my/upload', { method: 'POST', headers: { 'Content-Type': f.type }, body: f })).json(); - if (r.error) { $('woInfo' + i).textContent = r.error; } - else { $('woBanner' + i).value = r.url; $('woInfo' + i).textContent = 'Uploaded'; $('woPrev' + i).hidden = false; $('woPrev' + i).innerHTML = ''; } - } catch (e) { $('woInfo' + i).textContent = 'Upload failed. Try again.'; } - inp.value = ''; - })); - if ($('woSaveBtn')) $('woSaveBtn').addEventListener('click', busy2($('woSaveBtn'), async () => { - const offers = [0, 1].map(i => ({ title: $('woTitle' + i).value, targetUrl: $('woTarget' + i).value, bannerUrl: $('woBanner' + i).value })); - const r = await api('/api/my/wall-offers', { offers }); - IAP.status('Wall positions saved.', 'ok'); - await loadLineBanner(); - })); - const SOCIALS = ['facebook', 'twitter', 'youtube', 'instagram', 'tiktok', 'telegram', 'linkedin', 'website', 'video']; // video = intro video on the wall, not a social link - function fillProfileDetails(a) { - if (!a) return; - if (a.bio) $('pfBio').value = a.bio; - if (a.avatarUrl) { const p = $('pfAvatarPrev'); p.src = a.avatarUrl; p.hidden = false; } - let soc = {}; try { soc = a.socials ? JSON.parse(a.socials) : {}; } catch (e) {} - for (const p of SOCIALS) if ($('soc-' + p)) $('soc-' + p).value = soc[p] || ''; - if (a.username) { - const link = location.origin + '/wall/' + a.username; - $('pfBioLink').textContent = link; - $('pfViewBio').hidden = false; - $('pfViewBio').href = '/wall/' + a.username; - } - } - let pfAvatar; // pending avatar url - $('pfAvatarBtn').addEventListener('click', () => $('pfAvatarFile').click()); - $('pfAvatarFile').addEventListener('change', async () => { - const f = $('pfAvatarFile').files[0]; - if (!f) return; - $('pfAvatarInfo').textContent = 'Uploading…'; - try { - const r = await (await fetch('/api/my/upload', { method: 'POST', headers: { 'Content-Type': f.type }, body: f })).json(); - if (r.error) { $('pfAvatarInfo').textContent = r.error; $('pfAvatarFile').value = ''; return; } - pfAvatar = r.url; - $('pfAvatarInfo').textContent = 'Uploaded — save to apply.'; - const p = $('pfAvatarPrev'); p.src = r.url; p.hidden = false; - } catch (e) { $('pfAvatarInfo').textContent = 'Upload failed.'; } - $('pfAvatarFile').value = ''; - }); - $('pfDetailsSave').addEventListener('click', busy2($('pfDetailsSave'), async () => { - const body = { bio: $('pfBio').value, socials: {} }; - for (const p of SOCIALS) body.socials[p] = ($('soc-' + p) && $('soc-' + p).value.trim()) || ''; - if (pfAvatar) body.avatarUrl = pfAvatar; - const r = await api('/api/my/profile-details', body); - IAP.status('Profile saved.', 'ok'); - if (r.account) fillProfileDetails(r.account); - })); - $('lbUploadBtn').addEventListener('click', () => $('lbFile').click()); - $('lbFile').addEventListener('change', async () => { - const f = $('lbFile').files[0]; - if (!f) return; - $('lbUpInfo').textContent = 'Uploading…'; - try { - const r = await (await fetch('/api/my/upload', { method: 'POST', headers: { 'Content-Type': f.type }, body: f })).json(); - if (r.error) { $('lbUpInfo').textContent = r.error; $('lbFile').value = ''; return; } - $('lbBanner').value = r.url; - $('lbUpInfo').textContent = 'Uploaded.'; - $('lbPreview').hidden = false; - $('lbPreview').innerHTML = 'line banner'; - } catch (e) { $('lbUpInfo').textContent = 'Upload failed. Try again.'; } - $('lbFile').value = ''; - }); - $('lbSaveBtn').addEventListener('click', busy2($('lbSaveBtn'), async () => { - const r = await api('/api/my/linebanner', { bannerUrl: $('lbBanner').value, targetUrl: $('lbTarget').value }); - IAP.status('Line banner saved. Your next three levels will meet it.', 'ok'); - if (r.account) fillLineBanner(r.account); - })); - - // ── login ad interstitial (ClickBaitPays pattern): after a successful - // sign-in the sponsor card appears; "Open Ad" opens the CTA link in a NEW - // tab (a real, counted click) while the timer counts down on THIS page — - // deliberately not paused, the member is expected to be in the ad tab. - // At zero, "Go to dashboard" appears. - async function showLoginAd() { - try { - const { ad } = await (await fetch('/api/ads/slot?type=login')).json(); - if (!ad || !ad.targetUrl) return; - const gate = $('loginGate'); - const openBtn = $('lgOpen'); - const goBtn = $('lgContinue'); - const timer = $('lgTimer'); - $('lgCreative').innerHTML = ad.imageUrl - ? 'sponsor ad' - : '' + (ad.title ? String(ad.title).replace(/[&<>]/g, '') : 'Visit today\'s sponsor') + ''; - $('lgStatus').textContent = 'Login ad sponsor — click "Open Ad" to begin.'; - timer.hidden = true; - goBtn.hidden = true; - openBtn.disabled = false; - gate.hidden = false; - await new Promise(done => { - openBtn.onclick = () => { - window.open(ad.targetUrl, '_blank'); // the click relay counts it - openBtn.disabled = true; - $('lgStatus').textContent = 'Ad open in a new tab. View it and come back — the timer runs here.'; - let left = ad.dwell || 10; - timer.hidden = false; - timer.textContent = 'Time remaining: ' + left + 's'; - const t = setInterval(() => { - left -= 1; - if (left > 0) { timer.textContent = 'Time remaining: ' + left + 's'; return; } - clearInterval(t); - timer.textContent = 'Time is up'; - timer.classList.add('done'); - $('lgStatus').textContent = 'Thanks for the look. Your dashboard is ready.'; - goBtn.hidden = false; - }, 1000); - goBtn.onclick = () => done(); - }; - }); - gate.hidden = true; - $('lgTimer').classList.remove('done'); - } catch (e) {} - } - - // ── SPONSOR CHAT: two-way threads, presence-aware, with a slide-in drawer ── - let CHAT_ME = null, CHAT_OTHER = null, CHAT_LASTID = 0, CHAT_POLL = null, CHAT_CANMUTE = false, CHAT_IMUTE = false, CHAT_SPONSOR = null, CHAT_LAST_UNREAD = 0; - function chatSync(d) { - CHAT_ME = d.email || CHAT_ME; - CHAT_SPONSOR = (d.sponsor && d.sponsor.email) ? d.sponsor : null; - const link = $('chatMenuBtn'); if (link && link.closest('.bo-links')) link.closest('.bo-links').hidden = !d.email; - setChatBadge(d.chatUnread || 0); - CHAT_LAST_UNREAD = d.chatUnread || 0; - const tog = $('chatAvailToggle'); if (tog) tog.checked = d.chatAvailable !== false; - // Overview quick action + My line card: message-your-sponsor entry points - const qs = $('qaMsgSponsor'); - if (qs) { - if (CHAT_SPONSOR) { qs.hidden = false; qs.dataset.email = CHAT_SPONSOR.email; qs.dataset.name = CHAT_SPONSOR.name || 'your sponsor'; } - else qs.hidden = true; - } - const card = $('sponsorMsgCard'); - if (card) { - card.hidden = !CHAT_SPONSOR; - if (CHAT_SPONSOR && $('sponsorMsgName')) $('sponsorMsgName').textContent = CHAT_SPONSOR.name || 'your sponsor'; - } - } - function setChatBadge(n) { const b = $('chatNavBadge'); if (b) { b.hidden = !n; b.textContent = n > 9 ? '9+' : n; } } - function stopPoll() { if (CHAT_POLL) { clearInterval(CHAT_POLL); CHAT_POLL = null; } } - function startPoll() { stopPoll(); CHAT_POLL = setInterval(() => pullThread(false), 4000); } - // the composer grows with the message up to ~45% of the screen, and keeps any height the member dragged it to (Bradley, 2026-09-13) - function autoGrow(el) { - const cap = Math.max(160, Math.floor(window.innerHeight * 0.45)); - const dragged = Number(el.dataset.dragged || 0); - el.style.height = 'auto'; - el.style.height = Math.min(cap, Math.max(dragged, el.scrollHeight)) + 'px'; - } - function closeDrawer() { stopPoll(); if ($('chatDrawer')) $('chatDrawer').hidden = true; CHAT_OTHER = null; loadDashboard(); } - - async function openThreads() { - const dr = $('chatDrawer'); if (!dr) return; - dr.hidden = false; $('chatConvo').hidden = true; $('chatThreads').hidden = false; - $('chatBack').hidden = true; $('chatMute').hidden = true; $('chatDot').hidden = true; - $('chatTitle').textContent = 'Messages'; $('chatStatus').textContent = ''; - stopPoll(); CHAT_OTHER = null; - $('chatThreads').innerHTML = '

Loading…

'; - try { - const r = await (await fetch('/api/my/chat/threads')).json(); - const list = r.threads || []; - // always offer "message your sponsor" up top when they have one and no thread yet - const hasSponsorThread = CHAT_SPONSOR && list.some(t => t.email === CHAT_SPONSOR.email); - const sponsorRow = (CHAT_SPONSOR && !hasSponsorThread) - ? '
' - + '' - + '
' + esc(CHAT_SPONSOR.name) + '
' - + '
Your sponsor · tap to message
' - : ''; - if (!list.length && !sponsorRow) { $('chatThreads').innerHTML = '
No conversations yet. You can message anyone in your line from “My line”.
'; return; } - $('chatThreads').innerHTML = sponsorRow + list.map(t => - '
' - + '' - + '
' + esc(t.name) + '
' - + '
' + (t.last.fromMe ? 'You: ' : '') + esc((t.last.body || '').slice(0, 64)) + '
' - + (t.unread ? '' + t.unread + '' : '') + '
').join(''); - $('chatThreads').querySelectorAll('.chat-thread').forEach(el => - el.addEventListener('click', () => openConvo(el.dataset.email, el.dataset.name))); - } catch (e) { $('chatThreads').innerHTML = '
Could not load messages.
'; } - } - - async function openConvo(email, name) { - if (!email) return; - CHAT_OTHER = email; CHAT_LASTID = 0; - const dr = $('chatDrawer'); if (!dr) return; - dr.hidden = false; $('chatThreads').hidden = true; $('chatConvo').hidden = false; - $('chatBack').hidden = false; $('chatDot').hidden = false; - $('chatTitle').textContent = name || email; $('chatStatus').textContent = '…'; - $('chatMsgs').innerHTML = ''; $('chatBanner').hidden = true; - $('chatInput').disabled = false; $('chatSend').disabled = false; - await pullThread(true); startPoll(); - setTimeout(() => { const i = $('chatInput'); if (i) i.focus(); }, 60); - } - - function renderMsgs(msgs) { - const box = $('chatMsgs'); if (!box) return; - const atBottom = box.scrollTop + box.clientHeight >= box.scrollHeight - 60; - for (const m of msgs) { - if (m.id <= CHAT_LASTID) continue; - CHAT_LASTID = Math.max(CHAT_LASTID, m.id); - const d = document.createElement('div'); - d.className = 'cbub ' + (m.fromMe ? 'me' : 'them'); - d.textContent = m.body; - const t = document.createElement('span'); t.className = 'ct-time'; - t.textContent = new Date(m.sent).toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' }); - d.appendChild(t); box.appendChild(d); - } - if (atBottom) box.scrollTop = box.scrollHeight; - } - - async function pullThread(reset) { - if (!CHAT_OTHER) return; - try { - const r = await (await fetch('/api/my/chat/thread?with=' + encodeURIComponent(CHAT_OTHER) + '&after=' + (reset ? 0 : CHAT_LASTID))).json(); - if (r.error) { $('chatBanner').hidden = false; $('chatBanner').textContent = r.error; return; } - if (reset) { $('chatMsgs').innerHTML = ''; CHAT_LASTID = 0; } - renderMsgs(r.messages || []); - $('chatDot').className = 'pres-dot' + (r.online ? ' on' : ''); - $('chatStatus').textContent = r.online ? 'active now' : (r.available ? 'away · will get your note' : 'not taking live chats · leave a note'); - CHAT_CANMUTE = !!r.canMute; CHAT_IMUTE = !!r.iMute; - const mb = $('chatMute'); mb.hidden = !CHAT_CANMUTE; mb.textContent = CHAT_IMUTE ? 'Unmute' : 'Mute'; - const blocked = !!r.blocked; - $('chatInput').disabled = blocked; $('chatSend').disabled = blocked; - if (blocked) { $('chatBanner').hidden = false; $('chatBanner').textContent = 'They are not accepting messages from you right now.'; } - else if (CHAT_IMUTE) { $('chatBanner').hidden = false; $('chatBanner').textContent = 'You muted this member. Unmute to let them message you again.'; } - else $('chatBanner').hidden = true; - } catch (e) {} - } - - async function chatSend() { - const inp = $('chatInput'); if (!inp) return; - const text = inp.value.trim(); if (!text || !CHAT_OTHER) return; - $('chatSend').disabled = true; - try { - const r = await api('/api/my/chat/send', { to: CHAT_OTHER, body: text }); - inp.value = ''; autoGrow(inp); renderMsgs([r.message]); - const box = $('chatMsgs'); box.scrollTop = box.scrollHeight; - } catch (e) { IAP.status(e.message || 'Could not send.', 'bad'); } - finally { $('chatSend').disabled = false; inp.focus(); } - } - - async function toggleMute() { - if (!CHAT_OTHER) return; - try { const r = await api('/api/my/chat/mute', { email: CHAT_OTHER, muted: !CHAT_IMUTE }); CHAT_IMUTE = r.muted; $('chatMute').textContent = CHAT_IMUTE ? 'Unmute' : 'Mute'; pullThread(false); } - catch (e) { IAP.status(e.message, 'bad'); } - } - - (function chatInit() { - if (!$('chatDrawer')) return; - const on = (id, ev, fn) => { const el = $(id); if (el) el.addEventListener(ev, fn); }; - on('chatMenuBtn', 'click', e => { if (e && e.preventDefault) e.preventDefault(); openThreads(); }); - on('chatClose', 'click', closeDrawer); - on('chatBack', 'click', openThreads); - on('chatMute', 'click', toggleMute); - on('chatSend', 'click', chatSend); - const inp = $('chatInput'); - if (inp) { - inp.addEventListener('input', () => autoGrow(inp)); - inp.addEventListener('mouseup', () => { const h = inp.getBoundingClientRect().height; inp.dataset.dragged = h > 60 ? String(Math.round(h)) : ''; }); - inp.addEventListener('keydown', e => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); chatSend(); } }); - } - on('qaMsgSponsor', 'click', () => { const q = $('qaMsgSponsor'); if (q.dataset.email) openConvo(q.dataset.email, q.dataset.name || 'your sponsor'); }); - on('lineMsgSponsor', 'click', () => { if (CHAT_SPONSOR) openConvo(CHAT_SPONSOR.email, CHAT_SPONSOR.name || 'your sponsor'); }); - on('chatAvailToggle', 'change', async () => { - const t = $('chatAvailToggle'); - try { await api('/api/my/chat/available', { available: t.checked }); IAP.status(t.checked ? 'You are available to chat with your line.' : 'Live chat off. People can still leave you a note.', 'ok'); } - catch (e) { IAP.status(e.message, 'bad'); t.checked = !t.checked; } - }); - // presence heartbeat + new-message notifier: pop + toast when unread rises - setInterval(async () => { - try { - const r = await (await fetch('/api/my/ping')).json(); - const n = r.chatUnread || 0; - if (n > CHAT_LAST_UNREAD) { playSound('pop'); IAP.status('💬 New message from your team.', 'ok'); } - CHAT_LAST_UNREAD = n; setChatBadge(n); - } catch (e) {} - }, 20000); - })(); - - // ad surfaces: a banner greets the sign-in screen; members see live - // banner + text placements inside the back office (they ARE the audience) - IAP.adSlot('banner', 'adSlotLogin'); - IAP.adSlot('banner', 'adSlotOverview'); - IAP.adSlot('banner', 'adSlotSide', { width: 125, height: 125 }); // square button ad in the sidebar - - render(); -})(); - -// ── partner promo codes: typed on the Overview (Marty, 2026-09-12) ── -(function () { - const btn = document.getElementById('promoApply'), inp = document.getElementById('promoCode'), msg = document.getElementById('promoMsg'); - if (!btn || !inp) return; - const say = (t, ok) => { msg.hidden = false; msg.textContent = t; msg.style.color = ok ? 'var(--mint)' : '#ff8a8a'; }; - const go = async () => { - const code = inp.value.trim(); if (!code) { say('Enter a promo code.', false); return; } - btn.disabled = true; - try { - const r = await (await fetch('/api/my/promo/redeem', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ code }) })).json(); - if (r.error) { say(r.error, false); return; } - say('Added ' + Number(r.credits).toLocaleString() + ' credits' + (r.partner ? ' from ' + r.partner : '') + '. They are in your balance now.', true); - inp.value = ''; if (typeof loadDashboard === 'function') loadDashboard(); - } catch (e) { say('Could not apply that code. Try again.', false); } - finally { btn.disabled = false; } - }; - btn.addEventListener('click', go); inp.addEventListener('keydown', e => { if (e.key === 'Enter') go(); }); -})(); +// My account: email-first join/login, wallet link at purchase time, +// free payout activation, invite link, on-chain activity. +(async function () { + // back-office shell: no marketing nav here; rehearsal notice lives in the top bar + const $ = IAP.$; + try { + const c = await IAP.getConfig(); + if (c.rehearsal && $('boRehearsal')) { + $('boRehearsal').hidden = false; + $('boRehearsal').innerHTML = 'Testnet rehearsal · ' + c.chainName; + } + if (c.rehearsal && $('faucetCard')) $('faucetCard').hidden = false; + } catch (e) {} + // if they arrived through a sponsor's link, show who they're joining under + (async () => { + try { + const sp = await (await fetch('/api/sponsor')).json(); + if (sp && sp.invited && sp.name && $('sponsorNote')) { $('sponsorNoteName').textContent = sp.name; $('sponsorNote').hidden = false; } + } catch (e) {} + })(); + + async function api(path, body) { + const r = await (await fetch(path, { method: 'POST', + headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body || {}) })).json(); + if (r.error) throw new Error(r.error); + return r; + } + + function nextMove(d) { + if (!d.address) return 'Grab your link below and start sharing today. Then link your wallet (one free signature) so every payment can lock to you before your people start buying.'; + if (!d.memberId) return 'Your wallet is linked. Switch on payouts above (one free transaction) and every purchase in your line pays you the moment it happens.'; + if (d.buyerCount === 0) return 'Payouts are on and your link is live. Your next milestone: your first buyer of $25 or more. Every direct pays you 50 percent from their very first package.'; + if (d.buyerCount === 1) return 'One qualifying buyer down, one to go. Your next $25+ buyer unlocks level 2: 20 percent of everything your people’s people buy.'; + if (d.buyerCount < 5) return 'Level 2 is open. ' + (5 - d.buyerCount) + ' more qualifying buyer(s) unlock level 3 and the full three-level flow.'; + return 'Fully qualified. Every level pays you, and you catch the pass-ups that under-qualified positions below you let slip. Keep sharing and keep your campaigns running.'; + } + // featured rotation strip on the overview + let featItems = [], featIdx = 0, featTimer = null; + function renderOneFeatured() { + if (!featItems.length) return; + const i = featItems[featIdx % featItems.length]; + $('featStrip').innerHTML = '' + esc(i.title) + '' + + (i.by ? '' + esc(i.by) + '' : '') + ''; + } + async function loadFeatured() { + try { + const r = await (await fetch('/api/featured')).json(); + const card = $('featuredCard'); if (!card) return; + if (!r.items || !r.items.length) { card.hidden = true; return; } + card.hidden = false; + featItems = r.items; featIdx = Math.floor(Math.random() * featItems.length); + $('featSub').textContent = r.items.length + ' link' + (r.items.length === 1 ? '' : 's') + ' in rotation'; + renderOneFeatured(); // show ONE at a time (true rotation), cycle if more than one + clearInterval(featTimer); + if (featItems.length > 1) featTimer = setInterval(() => { featIdx++; renderOneFeatured(); }, 6000); + // self-sell: today's open slots + a CTA to feature your own link + try { + const st = await (await fetch('/api/featured/stats')).json(); + const today = (st.occupancy || []).find(d => d.offset === 0); + const cta = $('featCta'); + if (cta) { + cta.innerHTML = (today ? '' + today.open + ' of ' + today.cap + ' featured slots open today. ' : '') + + 'Feature your link →'; + const fb = $('featBuy'); + if (fb) fb.addEventListener('click', e => { e.preventDefault(); setPane('campaigns'); const ct = $('cType'); if (ct) { ct.value = 'featured'; ct.dispatchEvent(new Event('change')); } }); + } + } catch (e) {} + } catch (e) {} + } + + // achievement badges: the milestone ladder as unlockable medals + share-to-image + const BADGES = [ // ribbonY = vertical center of each badge's name ribbon (art differs per tier) + { key: 'payouts', label: 'Spark', sub: 'payouts on', img: '/badges/badge-spark.jpg', ribbonY: 0.728 }, + { key: 'firstBuyer', label: 'Surge', sub: 'first qualifying buyer', img: '/badges/badge-surge.jpg?v=2', ribbonY: 0.76 }, + { key: 'level2', label: 'Circuit', sub: '2 qualifying buyers', img: '/badges/badge-circuit.jpg?v=2', ribbonY: 0.72 }, + { key: 'level3', label: 'Nexus', sub: 'fully qualified', img: '/badges/badge-nexus.jpg?v=2', ribbonY: 0.73 } + ]; + let lastMilestones = []; + function renderBadges(d) { + const reached = d.milestonesReached || []; + lastMilestones = reached; + const strip = $('badgeStrip'); + if (!strip) return; + $('badgeCard').hidden = false; + strip.innerHTML = BADGES.map(b => { + const got = reached.includes(b.key); + return '
' + + '' + b.label + ' badge' + + '
' + b.label + '
' + b.sub + '
' + + (got ? ' ' : '
🔒 locked
') + '
'; + }).join(''); + strip.querySelectorAll('[data-badge]').forEach(btn => + btn.addEventListener('click', () => shareBadge(btn.dataset.badge, d))); + strip.querySelectorAll('[data-badgepost]').forEach(btn => + btn.addEventListener('click', () => postBadge(btn.dataset.badgepost, d, btn, true))); + fetch('/api/my/badge-posted').then(r => r.json()).then(r => { // the manual button is the admin's only (Marty, 2026-09-13) + if (r.canPost) strip.querySelectorAll('[data-badgepost]').forEach(b => { b.hidden = false; }); + (r.posted || []).forEach(k => { const b = strip.querySelector('[data-badgepost="' + k + '"]'); if (b) { b.textContent = 'Posted ✓'; b.disabled = true; } }); + }).catch(() => {}); + // celebrate anything newly granted this load, and post the branded badge to the team channels (Marty, 2026-09-13) + if (d.milestonesGranted && d.milestonesGranted.length) { + const total = d.milestonesGranted.reduce((s, g) => s + g.credited, 0); + const names = d.milestonesGranted.map(g => (BADGES.find(b => b.key === g.key) || {}).label).filter(Boolean).join(', '); + IAP.status('🏆 Achievement unlocked: ' + names + ' — +' + total + ' bonus credits!', 'ok'); + d.milestonesGranted.forEach((g, i) => setTimeout(() => postBadge(g.key, d, strip.querySelector('[data-badgepost="' + g.key + '"]')), 800 + i * 1500)); + } + } + // draw the badge with the member's name on the ribbon; cb(canvas) or cb(null) + function composeBadge(key, d, cb) { + const b = BADGES.find(x => x.key === key); if (!b) return cb(null); + const who = d.username ? d.username : d.memberId ? 'member #' + d.memberId : ''; + const img = new Image(); + img.onload = () => { + const c = document.createElement('canvas'); c.width = img.width; c.height = img.height; + const x = c.getContext('2d'); + x.drawImage(img, 0, 0); + if (who) { + x.textAlign = 'center'; x.textBaseline = 'middle'; + x.font = 'bold ' + Math.round(c.width * 0.055) + 'px Sora, "Segoe UI", sans-serif'; + const y = c.height * (b.ribbonY || 0.75); + x.lineJoin = 'round'; x.lineWidth = Math.max(3, Math.round(c.width * 0.008)); + x.strokeStyle = 'rgba(4,20,15,.9)'; x.strokeText(who, c.width / 2, y); + x.fillStyle = '#ffd15c'; x.fillText(who, c.width / 2, y); + } + cb(c); + }; + img.onerror = () => cb(null); + img.src = b.img; + } + async function postBadge(key, d, btn, manual) { + if (btn && btn.disabled) return; + if (btn) { btn.disabled = true; btn.textContent = 'Posting…'; } + composeBadge(key, d, c => { + if (!c) { if (btn) { btn.disabled = false; btn.textContent = 'Post to Telegram'; } return; } + c.toBlob(async bl => { + try { + const r = await (await fetch('/api/my/badge-post?key=' + encodeURIComponent(key) + (manual ? '&manual=1' : ''), { method: 'POST', headers: { 'Content-Type': 'image/jpeg' }, body: bl })).json(); + if (r.error) throw new Error(r.error); + if (btn) { btn.textContent = 'Posted ✓'; btn.disabled = true; } + if (!r.already) IAP.status('Your badge is posted in the team channels.', 'ok'); + } catch (e) { if (btn) { btn.disabled = false; btn.textContent = 'Post to Telegram'; } IAP.status(e.message || 'Could not post the badge.', 'bad'); } + }, 'image/jpeg', 0.86); + }); + } + // Share: a picker (Marty, 2026-09-13). The composed badge is stored once so a public page at + // /b// carries it as the preview image; every network gets that link. + function shareBadge(key, d) { + const b = BADGES.find(x => x.key === key); if (!b) return; + if (!d.username) { IAP.status('Pick a username first; your share page carries it.', 'bad'); return; } + IAP.status('Preparing your ' + b.label + ' badge…', 'ok'); + composeBadge(key, d, c => { + if (!c) { IAP.status('Could not load the badge art.', 'bad'); return; } + c.toBlob(async bl => { + let page = null; + try { const r = await (await fetch('/api/my/badge-image?key=' + encodeURIComponent(key), { method: 'POST', headers: { 'Content-Type': 'image/jpeg' }, body: bl })).json(); if (r.error) throw new Error(r.error); page = r.page; } + catch (e) { IAP.status(e.message || 'Could not prepare the share page.', 'bad'); return; } + openShareSheet(b, d, bl, page); + }, 'image/jpeg', 0.9); + }); + } + function openShareSheet(b, d, blob, page) { + const text = 'I just unlocked the ' + b.label + ' badge on LinkSpin (' + b.sub + '). Advertising that pays you back, on-chain, the same second a package sells.'; + const enc = encodeURIComponent; + const links = [ + ['X', 'https://x.com/intent/tweet?text=' + enc(text) + '&url=' + enc(page)], + ['Facebook', 'https://www.facebook.com/sharer/sharer.php?u=' + enc(page)], + ['Telegram', 'https://t.me/share/url?url=' + enc(page) + '&text=' + enc(text)], + ['WhatsApp', 'https://wa.me/?text=' + enc(text + ' ' + page)], + ['LinkedIn', 'https://www.linkedin.com/sharing/share-offsite/?url=' + enc(page)] + ]; + const back = document.createElement('div'); back.className = 'modal-back'; back.style.zIndex = '200'; + back.innerHTML = ''; + document.body.appendChild(back); + const close = () => back.remove(); + back.addEventListener('click', e => { if (e.target === back) close(); }); + back.querySelector('[data-sh="close"]').addEventListener('click', close); + back.querySelector('[data-sh="copy"]').addEventListener('click', async () => { try { await navigator.clipboard.writeText(page); IAP.status('Link copied.', 'ok'); } catch (e) { IAP.status('Copy this: ' + page, 'ok'); } }); + back.querySelector('[data-sh="save"]').addEventListener('click', () => { + const a = document.createElement('a'); a.href = URL.createObjectURL(blob); a.download = 'linkspin-' + b.label.toLowerCase() + '-badge.jpg'; a.click(); setTimeout(() => URL.revokeObjectURL(a.href), 5000); + IAP.status('Your ' + b.label + ' badge is saved.', 'ok'); + }); + // Massifly has no share intent: copy the post text + link, then open the feed composer (Marty, 2026-09-13) + back.querySelector('[data-sh="massifly"]').addEventListener('click', async () => { + try { await navigator.clipboard.writeText(text + ' ' + page); IAP.status('Post copied. Paste it into the Massifly composer; the badge preview appears from the link.', 'ok'); } + catch (e) { IAP.status('Copy this into Massifly: ' + text + ' ' + page, 'ok'); } + window.open('https://massifly.com/account', '_blank', 'noopener'); + }); + const nat = back.querySelector('[data-sh="native"]'); + if (nat) nat.addEventListener('click', async () => { + try { + const file = new File([blob], 'linkspin-' + b.label.toLowerCase() + '-badge.jpg', { type: 'image/jpeg' }); + if (navigator.canShare && navigator.canShare({ files: [file] })) await navigator.share({ files: [file], title: b.label + ' badge', text: text + ' ' + page }); + else await navigator.share({ title: b.label + ' badge', text, url: page }); + } catch (e) {} + }); + } + + // milestone stepper under "Your next move": lit nodes for what's done, + // amber glow on the current target — the same ladder the contract pays + function renderSteps(d) { + const el = $('ncSteps'); + if (!el) return; + const b = d.buyerCount || 0; + const steps = [ + { label: 'Joined', sub: 'free account', hit: true }, + { label: 'Spark', sub: 'payouts on', hit: !!d.memberId }, + { label: 'Surge', sub: 'first buyer · 50%', hit: b >= 1 }, + { label: 'Circuit', sub: '2 buyers · +20%', hit: b >= 2 }, + { label: 'Nexus', sub: '5 buyers · +10%', hit: b >= 5 } + ]; + const cur = steps.findIndex(s => !s.hit); + el.innerHTML = steps.map((s, i) => + '
' + + '' + (s.hit ? '✓' : i + 1) + '' + + '' + s.label + '' + s.sub + '
').join(''); + } + // ── overview v3 charts: hand-rolled SVG/CSS, real data only ── + const esc = s => String(s == null ? '' : s).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c])); + const CH = { mint: '#3b9dff', cyan: '#54ccff', violet: '#9d7dff', amber: '#ffb238', track: 'rgba(139,166,156,.18)' }; + function bars(el, xel, data) { // data: [{v,label,tip,alt}] + if (!el) return; + const max = Math.max(1, ...data.map(d => d.v)); + el.innerHTML = data.length + ? data.map(d => '
').join('') + : '
'.repeat(8); + if (xel) xel.innerHTML = data.map(d => '' + esc(d.label) + '').join(''); + } + function donut(el, segs, center) { // segs sum to the ring; r=15.9155 → circumference 100 + if (!el) return; + const total = segs.reduce((s, x) => s + x.v, 0); + let off = 25, out = ''; + if (total > 0) for (const s of segs) { + const len = s.v / total * 100; + if (len <= 0 || s.color === 'none') { off -= Math.max(0, len); continue; } + out += ''; + off -= len; + } + out += '' + esc(center.big) + '' + + '' + esc(center.small) + ''; + el.innerHTML = out; + } + function legend(el, rows) { + if (el) el.innerHTML = rows.map(r => '
' + + esc(r.label) + ' ' + esc(r.v) + '
').join(''); + } + async function loadCharts(d) { + // credit composition donut + today's viewing ring (live balances) + try { + const st = await (await fetch('/api/my/earn')).json(); + if (!st.error) { + // one rule: a balance is what is NOT committed to a live campaign. Budgets are + // set aside when a campaign starts and spend down inside Campaigns, so these + // numbers only move when a campaign is created, topped up or paused + const purchased = d.credits || 0, earned = d.earnedCredits != null ? d.earnedCredits : (st.earnedAvailable != null ? st.earnedAvailable : (st.earned || 0)), inC = d.inCampaigns || 0; + $('dbCredits').textContent = (purchased + earned).toLocaleString(); + // the Wallet tab card showed on-chain credits only, so promo/earned credits looked like 0 there (Jim, 2026-09-13) + if ($('creditLine')) $('creditLine').innerHTML = (purchased + earned).toLocaleString() + ' ' + purchased.toLocaleString() + ' purchased · ' + earned.toLocaleString() + ' earned'; + $('dbCreditsSub').textContent = purchased.toLocaleString() + ' purchased' + (d.creditedCredits ? ' (' + d.creditedCredits.toLocaleString() + ' credited to you)' : '') + ' · ' + earned.toLocaleString() + ' earned' + (inC ? ' · ' + inC.toLocaleString() + ' in campaigns' : ''); + donut($('chDonut'), + [{ v: purchased, color: CH.mint }, { v: earned, color: CH.cyan }, { v: inC, color: CH.amber }], + { big: (purchased + earned).toLocaleString(), small: 'available' }); + legend($('chDonutLegend'), [ + { color: CH.mint, label: 'Purchased, available', v: purchased.toLocaleString() }, + { color: CH.cyan, label: 'Earned, available', v: earned.toLocaleString() }, + { color: CH.amber, label: 'In live campaigns', v: inC.toLocaleString() }]); + const done = Math.min(st.views || 0, st.target || 5), left = Math.max(0, (st.target || 5) - done); + donut($('chRing'), [{ v: done, color: st.claimed ? CH.mint : CH.cyan }, { v: left, color: 'none' }], + { big: done + '/' + (st.target || 5), small: st.claimed ? 'claimed' : 'ads viewed' }); + legend($('chRingLegend'), [ + { color: st.claimed ? CH.mint : CH.cyan, label: 'Viewed today', v: done }, + { color: CH.track, label: 'To go', v: left }, + { color: CH.amber, label: 'Claim pays', v: '+' + (st.claimCredits || 0) + ' credits' }]); + } + } catch (e) {} + // recent on-chain payouts, sized to scale, oldest→newest + try { + let evs = []; + if (d.memberId) { + const a = await (await fetch('/api/my/activity')).json(); + evs = (a.earnings || []).filter(e => e.amountWei).sort((x, y) => x.block - y.block).slice(-12); + } + bars($('chEarnBars'), $('chEarnX'), evs.map(e => ({ + v: Number(BigInt(e.amountWei) / 1000000000000n) / 1e6, + label: e.type === 'AwardPaid' ? 'award' : 'L' + (e.tier || 1), + tip: IAP.fmtPol(e.amountWei) + ' POL', alt: e.type === 'AwardPaid' }))); + if (!evs.length) $('chEarnSub').textContent = d.memberId + ? 'no payouts yet — share your link' : 'activate a package to start earning'; + } catch (e) {} + // campaign delivery: impressions per campaign + try { + const r = await (await fetch('/api/my/campaigns')).json(); + const cs = (r.campaigns || []).slice(0, 8); + bars($('chCampBars'), $('chCampX'), cs.map(c => ({ + v: c.imps || 0, label: String(c.name || c.type).slice(0, 9), + tip: (c.name || c.type) + ': ' + (c.imps || 0) + ' imps · ' + (c.clicks || 0) + ' clicks', + alt: c.type === 'text' }))); + if (!cs.length) $('chCampSub').textContent = 'no campaigns yet — place your first ad'; + } catch (e) {} + } + // ── live updates: subscribe to the chain event stream so the members area + // reacts to on-chain changes (payouts, qualifications) without a refresh ── + let MYID = 0; + // synthesized sounds (no asset files; CSP-safe). cha-ching on a payment, pop on a message. + function playSound(kind) { + try { + const AC = window.AudioContext || window.webkitAudioContext; if (!AC) return; + const ctx = window.__iapAC || (window.__iapAC = new AC()); + if (ctx.state === 'suspended') ctx.resume(); + const now = ctx.currentTime; + const tone = (freq, at, dur, type, peak) => { + const o = ctx.createOscillator(), g = ctx.createGain(); + o.type = type || 'sine'; o.frequency.value = freq; + g.gain.setValueAtTime(0.0001, now + at); + g.gain.exponentialRampToValueAtTime(peak || 0.22, now + at + 0.02); + g.gain.exponentialRampToValueAtTime(0.0001, now + at + dur); + o.connect(g).connect(ctx.destination); o.start(now + at); o.stop(now + at + dur + 0.02); + }; + if (kind === 'chaching') { tone(1318, 0, 0.34, 'sine', 0.25); tone(1760, 0.09, 0.4, 'sine', 0.25); } + else { tone(680, 0, 0.16, 'triangle', 0.18); tone(1020, 0.05, 0.16, 'triangle', 0.16); } + } catch (e) {} + } + function startLiveFeed() { + if (window.__iapFeed || !window.EventSource) return; + try { + const es = new EventSource('/api/feed/live'); + window.__iapFeed = es; + es.onmessage = m => { let ev; try { ev = JSON.parse(m.data); } catch (e) { return; } handleLiveEvent(ev); }; + // browser auto-reconnects on error; nothing to do + } catch (e) {} + } + let liveRefreshT = null; + function liveRefresh() { // debounce a burst of events into one refresh + clearTimeout(liveRefreshT); + liveRefreshT = setTimeout(() => { loadDashboard(); try { loadLineage(); } catch (e) {} }, 600); + } + // community toasts (Marty, 2026-09-12: keep the dashboard feeling alive): everyone else's joins, + // purchases, payouts, qualifications, tank arrivals and adoptions, in a second, quieter toast so + // they never replace a personal one. At most one every 4 s; a burst shows the latest. + let liveT = 0, liveQ = null; + function communityToast(msg) { + const now = Date.now(); + if (now - liveT < 4000) { liveQ = msg; if (!communityToast._q) communityToast._q = setTimeout(() => { communityToast._q = null; const m = liveQ; liveQ = null; if (m) communityToast(m); }, 4200 - (now - liveT)); return; } + liveT = now; + let el = document.getElementById('liveToast'); + if (!el) { el = document.createElement('div'); el.id = 'liveToast'; el.setAttribute('role', 'status'); el.style.cssText = 'position:fixed;left:16px;bottom:16px;z-index:90;max-width:min(360px,calc(100vw - 32px));background:var(--panel-solid);border:1px solid var(--line-strong);border-left:3px solid var(--mint);border-radius:12px;padding:10px 14px;font-size:14px;box-shadow:0 10px 30px rgba(0,0,0,.4);transition:opacity .3s'; document.body.appendChild(el); } + el.textContent = msg; el.hidden = false; el.style.opacity = '1'; + clearTimeout(communityToast._t); communityToast._t = setTimeout(() => { el.style.opacity = '0'; setTimeout(() => { el.hidden = true; }, 350); }, 6000); + } + function handleLiveEvent(ev) { + if (!ev || !ev.type) return; + const nm = id => (ev.names && ev.names[id]) ? '@' + ev.names[id] : 'member #' + id; + // site-wide activity (not about me): joins, tank, adoptions, purchases, payouts, qualifications + if (ev.type === 'Joined') { communityToast('👋 ' + ev.name + ' just joined' + (ev.tank ? ' and is waiting for a sponsor in the holding tank' : '')); liveRefresh(); return; } + if (ev.type === 'Adopted') { communityToast('🤝 ' + ev.sponsor + ' picked up ' + ev.member + ' from the holding tank'); liveRefresh(); return; } + if (ev.type === 'Contest') { communityToast('🏆 ' + ev.winner + ' won the ' + (ev.kind === 'week' ? 'weekly' : 'monthly') + ' referral contest'); return; } + if (ev.type === 'Badge') { communityToast('🏆 ' + ev.member + ' unlocked ' + ev.label); return; } + if (ev.type === 'Released') { communityToast('🪣 ' + ev.sponsor + ' returned ' + ev.member + ' to the holding tank'); liveRefresh(); return; } + const mine = MYID && (ev.recipientId === MYID || ev.toId === MYID || ev.sponsorId === MYID || ev.skippedId === MYID || ev.buyerId === MYID); + if (!mine) { + if (ev.type === 'Purchase' && ev.buyerId) communityToast('🧾 ' + nm(ev.buyerId) + ' just bought a $' + Math.round((ev.priceCents || 0) / 100) + ' package'); + else if (ev.type === 'TierPaid' && ev.recipientId) communityToast('💸 ' + nm(ev.recipientId) + ' just got paid ' + IAP.fmtPol(ev.amountWei) + ' POL'); + else if (ev.type === 'BuyerCounted' && ev.sponsorId) communityToast('🎯 ' + nm(ev.sponsorId) + ' now has ' + ev.newCount + ' qualifying buyer' + (ev.newCount === 1 ? '' : 's')); + else if (ev.type === 'MemberActivated' && ev.id) communityToast('⚡ ' + nm(ev.id) + ' switched on payouts'); + return; + } + if (!MYID) return; + let toast = null, kind = 'ok'; + let sound = null; + if (ev.type === 'TierPaid' && ev.recipientId === MYID) { toast = '💸 You earned a level-' + ev.tier + ' payout of ' + IAP.fmtPol(ev.amountWei) + ' POL!'; sound = 'chaching'; } + else if (ev.type === 'AwardPaid' && ev.toId === MYID) { toast = '💸 You received ' + IAP.fmtPol(ev.amountWei) + ' POL!'; sound = 'chaching'; } + else if (ev.type === 'BuyerCounted' && ev.sponsorId === MYID) toast = '🎯 A referral just qualified — you now have ' + ev.newCount + ' qualifying buyer' + (ev.newCount === 1 ? '' : 's') + '!'; + else if (ev.type === 'PassedUp' && ev.skippedId === MYID) { toast = '⚠️ A level-' + ev.tier + ' payout passed you by. Get qualified to catch these.'; kind = 'bad'; } + else if (ev.type === 'Purchase' && ev.buyerId === MYID) toast = '✅ Purchase settled on-chain — your credits are updated.'; + else if (ev.type === 'MemberActivated' && ev.sponsorId === MYID) toast = '🤝 A new member just activated in your line!'; + if (toast) { IAP.status(toast, kind); if (sound) playSound(sound); liveRefresh(); } + } + + // training center: videos + materials (admin-curated via data/training.json) + async function loadTraining() { + try { + const r = await (await fetch('/api/training')).json(); + const el = $('trainingList'); if (!el) return; + const items = r.items || []; + if (!items.length) { el.innerHTML = '

Training materials are being added. Check back soon.

'; return; } + // section pills at the top: one per group, plus All; the active pill filters the list + const groups = [...new Set(items.map(it => it.group).filter(Boolean))]; + const pills = $('trainingPills'); + const want = loadTraining.filter || 'all'; + if (pills) { + pills.hidden = groups.length < 2; + pills.innerHTML = ['all', ...groups].map(g => '').join(''); + pills.querySelectorAll('[data-tg]').forEach(b => b.addEventListener('click', () => { loadTraining.filter = b.dataset.tg; loadTraining(); })); + } + const shown = want === 'all' ? items : items.filter(it => it.group === want); + let lastGroup = null; + el.innerHTML = shown.map(it => { + // optional section header: entries carry a `group`; a header renders when it changes + let head = ''; + if (it.group && it.group !== lastGroup) { lastGroup = it.group; head = '

' + esc(it.group) + '

'; } + const isVid = it.videoUrl && /\.(mp4|webm)(\?|$)/i.test(it.videoUrl); + // poster: the admin list can carry one; otherwise assume a .jpg next to the .mp4 (the pipeline uploads both) + const poster = it.posterUrl || (isVid ? it.videoUrl.replace(/\.(mp4|webm)(\?.*)?$/i, '.jpg$2') : ''); + const media = isVid ? '' : ''; + const links = []; + if (it.videoUrl && !isVid) links.push('Watch'); + if (it.docUrl) links.push('Open material'); + return head + '

' + esc(it.title || 'Lesson') + '

' + + (it.desc ? '

' + esc(it.desc) + '

' : '') + + (media ? '

' + media + '

' : '') + + (links.length ? '

' + links.join(' ') + '

' : '') + '
'; + }).join(''); + } catch (e) {} + } + // visual line tree on the Overview: YOU + three levels, qualified directs in gold + async function loadLineTree(buyerCount) { + try { + const r = await (await fetch('/api/my/line')).json(); + const el = $('lineTree'); if (!el) return; + const levels = r.levels || []; + const total = levels.reduce((n, L) => n + L.members.length, 0); + if ($('treeSub')) $('treeSub').textContent = total ? total + ' across 3 levels' : 'share your link to grow'; + const chip = (m, q) => '' + esc(String(m.name || 'M').replace(/^@/, '').slice(0, m.own ? 20 : 14)) + (m.buyers ? '' + m.buyers + '' : '') + ''; + const rowFor = lvl => { + const L = levels.find(x => x.level === lvl); const members = L ? L.members : []; + // gold = the contract counted this member as one of your qualifying buyers (not "the first N chips") + let html = members.map(m => chip(m, !!(m.qualified || m.bought))).join(''); // gold on every level = made their $20+ buy + if (lvl <= 2 && members.length < (lvl === 1 ? 2 : 4)) html += '+ open'; + if (!html) html = '+ open'; + return '
L' + lvl + '
' + html + '
'; + }; + el.innerHTML = '
YOU
' + rowFor(1) + rowFor(2) + rowFor(3); + } catch (e) {} + } + // "What's new" card: latest notes + what is being built; a dot marks notes newer than the member's last look (Marty, 2026-09-14) + let newsLoaded = false; + async function loadNews() { + if (newsLoaded || !$('newsCard')) return; newsLoaded = true; + try { + const r = await (await fetch('/api/releases')).json(); + if (!r.notes.length && !r.roadmap.length) return; + let seen = ''; try { seen = localStorage.getItem('iap.news.seen') || ''; } catch (e) {} + const esc = t => String(t == null ? '' : t).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c])); + const notes = r.notes.slice(0, 3).map(n => '

' + (n.date > seen ? '● ' : '') + '' + esc(n.title) + ' ' + esc(n.date) + '

').join(''); + const rm = r.roadmap.filter(x => x.status === 'building').slice(0, 2).map(x => '

Building: ' + esc(x.title) + (x.eta ? ' (' + esc(x.eta) + ')' : '') + '

').join(''); + $('newsList').innerHTML = notes + rm + '

All release notes and the roadmap →

'; + $('newsCard').hidden = false; + $('newsCard').addEventListener('click', () => { try { localStorage.setItem('iap.news.seen', r.latest || ''); } catch (e) {} $('newsList').querySelectorAll('span[style*="mint"]').forEach(s => { if (s.textContent === '●') s.remove(); }); }, { once: true }); + } catch (e) {} + } + // Leaderboard card: top 5 this week + your own rank + the prize (Marty, 2026-09-14) + async function loadLeaderboard() { + if (!$('lbCard')) return; + try { + const r = await (await fetch('/api/leaderboard?period=week')).json(); + const esc = t => String(t == null ? '' : t).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c])); + let h = r.prize ? '

Prize this week: ' + esc(r.prize) + '

' : ''; + h += r.top.length ? '' + r.top.slice(0, 5).map(x => '').join('') + '
' + x.rank + '' + esc(x.name) + '' + x.sales + ' sold · $' + x.usd + '
' + : '

No packages sold yet this week. First sale takes the top spot.

'; + h += r.me ? '

You: #' + r.me.rank + ' · ' + r.me.sales + ' sold · $' + r.me.usd + '

' : '

You: no sales yet this week. Sales are $20+ packages bought by people you sponsor.

'; + h += '

Full leaderboard: week, month, all time →

'; + $('lbList').innerHTML = h; $('lbCard').hidden = false; + } catch (e) {} + } + // Getting-started stepper: username -> wallet -> payouts -> first package. The current step gets one big + // button that opens the right tab and pulses the control (Jim: "it wasn't obvious", 2026-09-14) + function renderSteps(d) { + const card = $('gsCard'); if (!card) return; + const hasUser = !!d.username, hasWallet = !!d.address, hasPayouts = !!d.memberId, hasPackage = !!(d.memberId && (d.credits || 0) > 0); + const steps = [ + { k: 'user', t: 'Pick a username', done: hasUser }, + { k: 'wallet', t: 'Link your wallet', done: hasWallet }, + { k: 'payouts', t: 'Switch on payouts', done: hasPayouts }, + { k: 'package', t: 'Your first package', done: hasPackage } + ]; + if (steps.every(x => x.done)) { card.hidden = true; return; } + const cur = steps.find(x => !x.done); + let collapsed = false; try { collapsed = localStorage.getItem('iap.gs.collapsed') === '1'; } catch (e) {} + $('gsSub').innerHTML = steps.filter(x => x.done).length + ' of 4 done · ' + (collapsed ? 'show' : 'hide') + ''; + $('gsToggle').addEventListener('click', e => { e.preventDefault(); try { localStorage.setItem('iap.gs.collapsed', collapsed ? '0' : '1'); } catch (er) {} renderSteps(d); }); + $('gsSteps').hidden = collapsed; $('gsNow').hidden = collapsed; + $('gsSteps').innerHTML = steps.map((x, i) => '
' + (x.done ? '✓' : i + 1) + '' + x.t + '
').join(''); + const copy = { + user: ['Pick your username', 'It becomes your invite link and your public page, and it is permanent.', 'Choose a username', () => showOnboard(true)], + wallet: ['Link your wallet', 'Your payouts land in a wallet you control, so the site needs to know which one is yours. One free signature, no purchase. MetaMask recommended; Phantom users switch Polygon on first. Never held crypto? The wallet guide walks you through it.', 'Link my wallet', () => jumpTo('wallet', 'linkBtn')], + payouts: ['Switch on payouts', 'One small transaction registers your wallet with the contract so commissions can reach it. Buying any package does this automatically.', 'Activate payouts', () => jumpTo('wallet', 'activateBtn')], + package: ['Your first package', 'From $5. The $20 Activation package is the one that counts you as a qualifying buyer for your sponsor and unlocks adopting from the holding tank.', 'See packages', () => jumpTo('buy', null)] + }[cur.k]; + $('gsNow').innerHTML = '

Next: ' + copy[0] + '' + copy[1] + (cur.k === 'wallet' ? ' Wallet guide' : '') + '

'; + $('gsGo').addEventListener('click', copy[3]); + card.hidden = false; + } + function jumpTo(pane, id) { + setPane(pane); + setTimeout(() => { const el = id && $(id); if (!el) return; el.scrollIntoView({ behavior: 'smooth', block: 'center' }); el.classList.remove('pulse'); void el.offsetWidth; el.classList.add('pulse'); try { el.focus({ preventScroll: true }); } catch (e) {} }, 250); + } + async function loadDashboard() { + try { + loadNews(); loadLeaderboard(); + const d = await (await fetch('/api/my/dashboard')).json(); + if (d.error) return; + chatSync(d); + try { renderSteps(d); } catch (e) {} + MYID = d.memberId || MYID; + startLiveFeed(); + if (!window.__lbChecked) { // daily login bonus, once per session (server guards once/day) + window.__lbChecked = true; + api('/api/my/login-bonus').then(r => { + if (r && r.granted > 0) { + IAP.status('🎁 Daily login bonus: +' + r.granted + ' credits' + (r.streak > 1 ? ' · ' + r.streak + '-day streak' : '') + '!', 'ok'); + playSound('chaching'); setTimeout(loadDashboard, 900); + } + }).catch(() => {}); + } + const earnedAv = d.earnedCredits || 0, inCamp = d.inCampaigns || 0; + $('dbCredits').textContent = ((d.credits || 0) + earnedAv).toLocaleString(); + $('dbCreditsSub').textContent = (d.credits || 0).toLocaleString() + ' purchased' + (d.creditedCredits ? ' (' + d.creditedCredits.toLocaleString() + ' credited to you)' : '') + ' · ' + earnedAv.toLocaleString() + ' earned' + (inCamp ? ' · ' + inCamp.toLocaleString() + ' in campaigns' : ''); + $('dbEarned').textContent = IAP.fmtPol(d.earnedWei || '0'); + $('dbBuyers').textContent = d.buyerCount || 0; if (d.buyerCountPositions) { const sub = $('dbBuyersSub'); if (sub) sub.textContent = '+' + d.buyerCountPositions + ' on your linked positions (count toward badges; levels pay on your main position)'; } + $('dbTeam').textContent = (d.referrals || []).length; + // trend chips: only real, computable facts + const ec = $('dbEarnedChip'); + if (ec && d.earnCount) { ec.hidden = false; ec.textContent = d.earnCount + ' instant payout' + (d.earnCount > 1 ? 's' : ''); } + const bc = $('dbBuyersChip'); + if (bc && d.memberId) { + bc.hidden = false; + bc.textContent = (d.buyerCount || 0) >= 5 ? 'level 3 open' : (d.buyerCount || 0) >= 2 ? 'level 2 open' : 'level 2 at 2 buyers'; + } + const tc = $('dbTeamChip'), wk = (d.referrals || []).filter(r => Date.now() - new Date(r.joined) < 6048e5).length; + if (tc && wk) { tc.hidden = false; tc.textContent = '+' + wk + ' this week'; } + setInboxBadge(d.inboxUnread || 0); + if (d.sponsorMsg) showSponsorModal(d.sponsorMsg); + renderBadges(d); + loadFeatured(); + loadLineTree(d.buyerCount || 0); + loadCharts(d); + $('nextMove').textContent = nextMove(d); + renderSteps(d); + const wrap = $('rosterWrap'); + if ((d.referrals || []).length) { + $('rosterEmpty').hidden = true; + let t = wrap.querySelector('table'); + if (t) t.remove(); + t = document.createElement('table'); + t.className = 'roster'; + t.innerHTML = d.referrals.map(r => '' + String(r.name || r.email || '').replace(/[&<>]/g, '') + '' + + '' + new Date(r.joined).toLocaleDateString() + '' + + '' + r.status + '').join(''); + wrap.appendChild(t); + } + // overview recent-activity widget: chain events + line joins, newest first + try { + const c = await IAP.getConfig(); + const ov = $('ovFeed'); + const rows = []; + if (d.memberId) { + const a = await (await fetch('/api/my/activity')).json(); + for (const ev of [...(a.earnings || []), ...(a.purchases || [])] + .sort((x, y) => y.block - x.block).slice(0, 5)) rows.push(IAP.feedRow(ev, c)); + } + for (const r of (d.referrals || []).slice(0, 3)) { + const div = document.createElement('div'); + div.className = 'row'; + div.innerHTML = '🤝 ' + esc(r.name || r.email || 'A new member') + ' joined your line' + + new Date(r.joined).toLocaleDateString() + ''; + rows.push(div); + } + if (rows.length) { + ov.innerHTML = ''; + rows.slice(0, 6).forEach(r => ov.appendChild(r)); + } + } catch (e) {} + // ready-to-send share message + promo tools, personalized + const link = location.origin + '/join/' + (d.username || d.refCode || d.memberId || ''); + fillPromo(link, d); + // founding-week readiness: shown until every item is done (or the launch moment is a week past) + try { + const cfg = await IAP.getConfig(); const items = IAP.launchChecks(d); const done = items.filter(i => i.done).length; + const at = cfg.launchAt ? new Date(cfg.launchAt).getTime() : 0; + const show = done < items.length && !(at && Date.now() > at + 7 * 86400000); + const lm = $('launchMark'); + if (lm) { lm.hidden = !show; lm.innerHTML = show ? 'Launch ready: ' + done + ' of ' + items.length + '. ' + (at && Date.now() < at ? 'Doors open ' + new Date(at).toLocaleString([], { weekday: 'short', hour: 'numeric', minute: '2-digit' }) + '. ' : '') + 'Open the founding-week checklist' : ''; } + } catch (e) {} + // people waiting for a sponsor in the holding tank (Marty, 2026-09-12): every Overview sees it + try { + const tw = d.tankWaiting, tn = $('tankNotice'); + if (tn) { + tn.hidden = !(tw && tw.count); + if (tw && tw.count) tn.innerHTML = '' + tw.count + (tw.count === 1 ? ' person is' : ' people are') + ' waiting for a sponsor in the holding tank \u00b7 ' + + tw.names.map(esc).join(', ') + (tw.count > tw.names.length ? ' and more' : '') + '. Adopt them from My line' + + (tw.eligible ? '.' : ' (you need your own $20 package first).'); + } + } catch (e) {} + if (d.username) { // wall link rides the username + const wl = location.origin + '/wall/' + d.username; + $('wallLine').textContent = wl; + if ($('promoWallStrip')) { // the same wall link at the top of Promo tools, next to the invite link + $('promoWallStrip').hidden = false; $('promoWallLink').textContent = wl; $('promoWallOpen').href = '/wall/' + d.username; + $('promoWallCopy').onclick = async () => { try { await navigator.clipboard.writeText(wl); IAP.status('Wall link copied.', 'ok'); } catch (e) { IAP.status('Copy failed. Select the link and copy it.', 'bad'); } }; + } + $('wallCopy').hidden = false; + $('wallOpen').hidden = false; + $('wallOpen').href = '/wall/' + d.username; + $('wallCopy').onclick = async () => { + try { await navigator.clipboard.writeText(wl); IAP.status('Wall link copied.', 'ok'); } + catch (e) { IAP.status('Copy failed. Select the link text instead.', 'bad'); } + }; + } + if (d.refCode || d.memberId) { + const pitch = 'I found an advertising site that pays referrals instantly to your own wallet. ' + + 'No withdrawals, no waiting, and every payment is public on a blockchain ledger you can check yourself. ' + + 'Free to join and look around: ' + link; + $('copyPitch').hidden = false; + $('pitchPreview').hidden = false; + $('pitchPreview').textContent = '"' + pitch + '"'; + $('copyPitch').onclick = async () => { + try { await navigator.clipboard.writeText(pitch); IAP.status('Message copied. Paste it anywhere.', 'ok'); } + catch (e) { IAP.status('Copy failed. Select the preview text instead.', 'bad'); } + }; + } + } catch (e) {} + } + + // ── back-office menu: hash-routed panes ─────────────── + const PANES = ['overview', 'line', 'pipeline', 'rotator', 'buy', 'campaigns', 'earn', 'earnings', 'promo', 'training', 'wallet', 'profile']; + const TITLES = { overview: 'Start', line: 'My line', pipeline: 'Pipeline', rotator: 'Rotator', buy: 'Buy packages', campaigns: 'Campaigns', + earn: 'Earn credits', earnings: 'Earnings', promo: 'Promo tools', training: 'Training', + wallet: 'Wallet & account', profile: 'Profile' }; + const MOVED = { buy: '/credits', rotator: '/links', campaigns: '/ads', earn: '/ads', earnings: '/credits', wallet: '/wallet' }; // control-room screens (2026-10-08) + function setPane(name) { + if (MOVED[name]) { location.replace(MOVED[name]); return; } + if (!PANES.includes(name)) name = 'overview'; + for (const p of PANES) { + const el = $('pane-' + p); + if (el) el.hidden = p !== name; + } + document.querySelectorAll('.bo-menu [data-pane]').forEach(b => + b.classList.toggle('on', b.dataset.pane === name)); + if ($('boTitle')) $('boTitle').textContent = TITLES[name]; + { const h1 = document.querySelector('.topbar h1'); if (h1 && TITLES[name]) h1.textContent = TITLES[name]; } + // member ads: a fresh text ad in the strip under the title, and a banner at the foot of the pane + IAP.adSlot('text', 'adStripTop'); + if ($('adSlotPane-' + name)) IAP.adSlot('banner', 'adSlotPane-' + name); + if (name === 'earn') setEarnSub(earnSub); // refresh whichever sub-tab is active + else if (vidState.token) stopVideo(); + if (name === 'profile') loadLineBanner(); + if (name === 'line') { loadLineage(); loadUplineMessages(); loadCoach(); loadLinkStats(); loadProspects(); } + if (name === 'campaigns') ['cTarget', 'cImage', 'cVideoUrl'].forEach(id => { if ($(id)) $(id).value = ''; }); // no residual URL between visits + if (name === 'training') loadTraining(); + if (name === 'pipeline') loadPipeline(); + if (name === 'rotator') loadRotator(); + document.getElementById('memberArea').classList.remove('side-open'); // close mobile drawer + if (location.hash !== '#' + name) history.replaceState(null, '', '#' + name); + } + document.querySelectorAll('.bo-menu [data-pane]').forEach(b => + b.addEventListener('click', () => setPane(b.dataset.pane))); + document.querySelectorAll('.qa [data-goto]').forEach(b => + b.addEventListener('click', () => setPane(b.dataset.goto))); + const qaCopy = document.getElementById('qaCopyInvite'); + if (qaCopy) qaCopy.addEventListener('click', async () => { + const link = document.getElementById('inviteLine').textContent; + if (!link || !link.startsWith('http')) { setPane('line'); return; } + try { await navigator.clipboard.writeText(link); IAP.status('Invite link copied.', 'ok'); } + catch (e) { setPane('line'); } + }); + window.addEventListener('hashchange', () => setPane(location.hash.slice(1))); + if ($('boBurger')) $('boBurger').addEventListener('click', () => + document.getElementById('memberArea').classList.toggle('side-open')); + + async function render() { + // while /api/me answers, show a spinner instead of flashing the sign-in card at a signed-in member + let me = null; + try { me = await IAP.refreshNavWallet(); } catch (e) { me = null; } + if ($('bootSpin')) $('bootSpin').hidden = true; + // one way in: email. A wallet-only session (no account) is sent back to the + // email card with a finish-setup note; verifying the code links that wallet. + const walletOnly = !!(me && me.signedIn && !me.email); + const signedIn = me && me.signedIn && !walletOnly; + // signed out: the Control Room sign-in dialog (the old email card only serves the wallet-only finish-setup case) + $('authArea').hidden = !!signedIn || !walletOnly; + $('memberArea').hidden = !signedIn; + if ($('mcFinish')) $('mcFinish').hidden = !walletOnly; + if (!signedIn && !walletOnly && window.CR) { // the Control Room shell runs the sign-in dialog; render again once it reports a session + if (window.LS_SESSION_READY && (render.retries = (render.retries || 0) + 1) < 6) { setTimeout(render, 400); } + else if (!render.waiting) { render.waiting = true; window.addEventListener('ls:session', () => { render.waiting = false; render(); }, { once: true }); } + } + if (!signedIn) return; + if ($('adminLink')) $('adminLink').hidden = !me.isAdmin; // admin portal link, only for ADMIN_EMAIL + // REQUIRED first step (Marty, 2026-09-12): no username, nothing else. The modal cannot be + // skipped or dismissed; it resolves only when a username is saved, then the area renders. + if (!me.username) { + if (!render.gating) { render.gating = true; showOnboard(true).then(() => { render.gating = false; render(); }); } + return; + } + // arrived from an invite page: run the welcome tour and login ad once + if (/[?&]welcome=1/.test(location.search) && !render.welcomed) { + render.welcomed = true; + history.replaceState(null, '', '/tools' + (location.hash || '')); + (async () => { + try { if (!(await showGauntlet())) await showLoginAd(); } catch (e) {} + await render(); + })(); + } + setPane(location.hash.slice(1) || 'overview'); + $('campGate').hidden = !!me.memberId; + $('earnGate').hidden = !!me.memberId; + if (me.username && !me.address) { let shown = ''; try { shown = sessionStorage.getItem('iap.gs.walletHint'); sessionStorage.setItem('iap.gs.walletHint', '1'); } catch (e) {} if (shown !== '1') setTimeout(() => IAP.status('Next step when you are ready: link your wallet so your payouts have somewhere to land. The Getting started card at the top shows how.', 'ok'), 1200); } + loadDashboard(); + + const who = []; + if (me.email) who.push(me.email); + // members kept asking whether the wallet was really connected (Marty, 2026-09-12): say it, with a green check + if (me.address) who.push('Wallet connected ' + me.address.slice(0, 8) + '…' + me.address.slice(-6) + ''); + else who.push('No wallet connected yet (link one below)'); + if (me.memberId) who.push('on-chain member #' + me.memberId + '' + + (me.onchainSponsorId ? ', sponsored by #' + me.onchainSponsorId : '')); + else if (me.sponsorId) who.push('invited by member #' + me.sponsorId); + $('posLine').innerHTML = who.join('
'); + + $('creditLine').textContent = (me.credits || 0).toLocaleString(); + loadPositions(me); + $('linkCard').hidden = !!me.address; + $('activateCard').hidden = !(me.address && !me.memberId); + $('activityArea').hidden = !me.memberId; + $('campGate').hidden = true; // earned credits fund campaigns for everyone + $('campaignCard').hidden = false; + loadCampaigns(); + + // profile pane state + $('pfCurrent').textContent = me.username ? '@' + me.username + ' is your permanent username. Your invite link, your public page and any banners you shared carry it, so it cannot be changed.' : 'No username yet. Members see you as a number until you pick one. Choose carefully: it is permanent once saved.'; + if (!$('pfUsername').value) $('pfUsername').value = me.username || ''; + $('pfUsername').disabled = !!me.username; $('pfSaveBtn').hidden = !!me.username; + $('pfDetails').innerHTML = 'Email: ' + (me.email || 'none') + '
Wallet: ' + + (me.address ? '' + me.address.slice(0, 10) + '…' + me.address.slice(-6) + '' : 'not linked yet') + + '
On-chain member: ' + (me.memberId ? '#' + me.memberId : 'not yet'); + // the share link works from day one; usernames make it a vanity link + if (me.username || me.refCode || me.memberId) { + $('inviteLine').textContent = location.origin + '/join/' + (me.username || me.refCode || me.memberId); + $('copyInvite').hidden = false; + } else { + $('inviteLine').textContent = 'Sign in with your email to get your link.'; + $('copyInvite').hidden = true; + } + if (me.memberId) { + const bc = me.buyerCount || 0; + $('qualLine').innerHTML = '' + bc + ' qualifying buyer(s) referred
' + + (bc >= 5 ? 'Level 3 unlocked: full three-level earnings' + : bc >= 2 ? 'Level 2 unlocked · ' + (5 - bc) + ' more for level 3' + : (2 - bc) + ' more buyer(s) of $20+ unlock level 2'); + loadActivity(); + } else { + $('qualLine').innerHTML = 'Share your link now. Then switch on payouts (free, above) ' + + 'before your people start buying: the contract locks each buyer to their sponsor at ' + + 'their first purchase, and payments only route to wallets that are switched on.'; + } + } + + async function loadActivity() { + try { + const c = await IAP.getConfig(); + const a = await (await fetch('/api/my/activity')).json(); + const fill = (id, evs, empty) => { + const el = $(id); + el.innerHTML = ''; + if (!evs || !evs.length) { el.innerHTML = '
' + empty + '
'; return; } + for (const ev of evs) el.appendChild(IAP.feedRow(ev, c)); + }; + fill('earnFeed', a.earnings, 'No payouts yet. They appear here the moment one lands.'); + fill('refFeed', a.referrals, 'No referral activity yet. Share your invite link.'); + fill('buyFeed', a.purchases, 'No purchases from your wallet yet.'); + } catch (e) {} + } + + async function loadCampaigns() { + try { + const r = await (await fetch('/api/my/campaigns')).json(); + if (r.error) return; + lastRates = r.rates; + if ($('cGeoHint') && r.tiers) $('cGeoHint').textContent = 'All three ticked = everyone. Tier 1: ' + r.tiers.t1.join(', ') + '. Tier 2: ' + r.tiers.t2.join(', ') + '. Tier 3: every other country. Geo applies to delivery on this site; a narrowed banner or text ad is kept off the worldwide partner network. ' + (r.geoReady ? '' : 'Country data is still loading, so narrowed campaigns pause until it is ready. ') + 'IP geolocation by DB-IP.'; + // populate the banner-size dropdown once (ids map to NAS width/height) + if (r.bannerSizes && $('cSize') && !$('cSize').options.length) + $('cSize').innerHTML = r.bannerSizes.map(s => '').join(''); + applyType(); // the default type is banner: show its size + image rows now that the sizes exist + soloHint(); + if ($('spendBanner')) { + $('spendBanner').hidden = false; + $('spendBig').textContent = r.availableCredits.toLocaleString(); + $('spendSub').textContent = '= $' + (r.availableCredits / 100).toLocaleString(undefined, { maximumFractionDigits: 2 }) + ' of ad delivery · ' + r.purchasedCredits.toLocaleString() + ' purchased' + (r.creditedCredits ? ' (' + r.creditedCredits.toLocaleString() + ' of it credited to you, spends on anything)' : '') + ' + ' + (r.earnedCredits || 0).toLocaleString() + ' earned' + (r.positionCount > 1 ? ' · pooled across ' + r.positionCount + ' positions (largest single position ' + (r.largestPosition || 0).toLocaleString() + ')' : ''); + if ($('spendNote')) $('spendNote').textContent = r.inCampaigns + ? 'Not counting ' + r.inCampaigns.toLocaleString() + ' credits already set aside for your live campaigns. That budget spends down inside each campaign below. This number only moves when you start, top up or pause a campaign.' + : 'This is what is not committed to a campaign. When you start one, its budget moves out of here and spends down inside the campaign.'; + $('spendRates').innerHTML = [['Banner', r.rates.bannerCreditsPerBatch + ' cr / ' + r.rates.bannerBatch + ' views'], ['Text', r.rates.textCreditsPerBatch + ' cr / ' + r.rates.textBatch + ' views'], ['Login', r.rates.loginCreditsPerDay + ' cr / day'], ['Solo', r.rates.soloCostPerRecipient + ' cr / delivery'], ['Featured', (r.rates.featuredPerDay || 40) + ' cr / day'], ['Visit', (r.rates.visitCostPerVisit || 3) + ' cr / visit']].map(x => '' + x[0] + ' ' + x[1] + '').join(''); + } + $('rateLine').textContent = 'Available to spend: ' + r.availableCredits.toLocaleString() + + (r.earnedCredits ? ' (' + r.purchasedCredits.toLocaleString() + ' purchased + ' + r.earnedCredits + ' earned)' : '') + + (r.inCampaigns ? ' · ' + r.inCampaigns.toLocaleString() + ' set aside in live campaigns' : '') + + ' credits · rates: banner ' + r.rates.bannerCreditsPerBatch + 'cr/' + r.rates.bannerBatch + + ' views, text ' + r.rates.textCreditsPerBatch + 'cr/' + r.rates.textBatch + + ' views, login ' + r.rates.loginCreditsPerDay + 'cr/day, solo ' + + (r.rates.soloCostPerRecipient || 5) + 'cr/delivery'; + const el = $('campList'); + el.innerHTML = ''; + if (!r.campaigns.length) { el.innerHTML = '

No campaigns yet. Launch your first below.

'; return; } + const tbl = document.createElement('div'); + tbl.className = 'tablewrap'; + tbl.innerHTML = '' + + '' + + r.campaigns.map(c => '' + + '' + + '' + + '' + + '' + + '' + + '' + + '').join('') + '
NameTypeViews hereNetwork viewsClicksSpentBudgetStatus
' + c.name + '' + hourBars(r.hours && r.hours[c.id]) + geoLine(r.geo && r.geo[c.id]) + '' + c.type + (c.type === 'banner' && c.width ? ' ' + c.width + '×' + c.height + '' : '') + (c.dailyCap ? ' cap ' + c.dailyCap + '/day' : '') + (c.geo ? ' tier ' + esc(c.geo.replace(/,/g, '+')) + '' : '') + schedChips(c) + '' + c.imps.toLocaleString() + '' + (['banner', 'text'].includes(c.type) ? (c.impsNas || 0).toLocaleString() : 'n/a') + '' + c.clicks + (r.clickSources && r.clickSources[c.id] ? '
' + Object.entries(r.clickSources[c.id]).sort((a, b) => b[1] - a[1]).map(([k, v]) => '' + esc(k) + ' ' + v + '').join('') + (c.impsNas ? ' · network: see Network views' : '') + '
' : '') + '
' + c.spent + '' + c.budget + '' + (c.status === 'out' ? 'budget spent' : c.status === 'done' ? 'ended' : c.scheduled ? 'scheduled' : c.status) + '' + (c.status === 'active' ? '' + : c.status === 'paused' ? '' : '') + + ' ' + + '
'; + el.appendChild(tbl); + el.querySelectorAll('button[data-camp]').forEach(b => b.addEventListener('click', async () => { + try { await api('/api/my/campaigns/' + b.dataset.camp + '/' + b.dataset.act); await loadCampaigns(); } + catch (e) { IAP.status(e.message, 'bad'); } + })); + el.querySelectorAll('button[data-topup]').forEach(b => b.addEventListener('click', async () => { + const n = await IAP.ask({ title: 'Add credits', text: 'How many credits to add to this campaign? More credits buy more views.', type: 'number', placeholder: 'e.g. 100', ok: 'Add credits' }); + if (!n) return; + try { const r = await api('/api/my/campaigns/' + b.dataset.topup + '/topup', { credits: Number(n) }); + IAP.status('Added ' + r.added + ' credits' + (r.reactivated ? ' — campaign is live again.' : '.'), 'ok'); + await loadCampaigns(); loadDashboard(); + } catch (e) { IAP.status(e.message, 'bad'); } + })); + } catch (e) {} + } + let lastRates = null; + function soloHint() { + if (!lastRates || $('cType').value !== 'solo') return; + const cost = lastRates.soloCostPerRecipient || 5; + const n = Math.floor((Number($('cBudget').value) || 0) / cost); + $('cSoloHint').textContent = cost + ' credits per guaranteed inbox delivery' + + (n ? ' — this budget reaches ' + n + ' members' : '') + + '. Readers earn ' + (lastRates.soloReadCredits || 2) + ' credits for a real read, so your message gets opened.'; + } + $('cBudget').addEventListener('input', soloHint); + // rich solo editor: small toolbar over contenteditable (CSP allows no external editor); + // the server whitelist-sanitizes whatever HTML arrives, this is just authoring comfort + document.querySelectorAll('.ed-bar [data-cmd]').forEach(btn => + btn.addEventListener('click', () => { $('cSoloEd').focus(); document.execCommand(btn.dataset.cmd, false, null); })); + document.querySelectorAll('.ed-bar [data-block]').forEach(btn => + btn.addEventListener('click', () => { $('cSoloEd').focus(); document.execCommand('formatBlock', false, btn.dataset.block); })); + $('edLinkBtn').addEventListener('click', async () => { + const sel = window.getSelection(); const range = sel && sel.rangeCount ? sel.getRangeAt(0).cloneRange() : null; // the dialog steals the selection + const url = await IAP.ask({ title: 'Insert link', text: 'Link URL (https://…)', placeholder: 'https://', ok: 'Insert' }); + if (!url) return; + $('cSoloEd').focus(); if (range) { sel.removeAllRanges(); sel.addRange(range); } + document.execCommand('createLink', false, url); + }); + // inline media: upload, then drop the element at the cursor (BV-style) + let mediaMode = 'image'; + function insertHtmlAtCursor(html) { + const ed = $('cSoloEd'); + ed.focus(); + if (!document.execCommand('insertHTML', false, html)) ed.insertAdjacentHTML('beforeend', html); + } + $('edImgBtn').addEventListener('click', () => { mediaMode = 'image'; $('cSoloFile').accept = 'image/png,image/jpeg,image/webp,image/gif'; $('cSoloFile').click(); }); + $('edVidBtn').addEventListener('click', () => { mediaMode = 'video'; $('cSoloFile').accept = 'video/mp4,video/webm'; $('cSoloFile').click(); }); + $('cSoloFile').addEventListener('change', async () => { + const f = $('cSoloFile').files[0]; + if (!f) return; + $('edMediaInfo').textContent = 'Uploading ' + f.name + '…'; + try { + const r = await (await fetch('/api/my/upload', { method: 'POST', headers: { 'Content-Type': f.type }, body: f })).json(); + if (r.error) { $('edMediaInfo').textContent = r.error; $('cSoloFile').value = ''; return; } + insertHtmlAtCursor(r.type === 'video' + ? '


' + : '


'); + $('edMediaInfo').textContent = f.name + ' inserted'; + } catch (e) { $('edMediaInfo').textContent = 'Upload failed. Try again.'; } + $('cSoloFile').value = ''; + }); + // raw-text toggle: swap the WYSIWYG surface for the underlying HTML and back + $('edRawBtn').addEventListener('click', () => { + const ed = $('cSoloEd'), raw = $('cSoloRaw'); + if (raw.hidden) { raw.value = ed.innerHTML; raw.hidden = false; ed.hidden = true; $('edRawBtn').textContent = 'Visual'; } + else { ed.innerHTML = raw.value; ed.hidden = false; raw.hidden = true; $('edRawBtn').textContent = 'Raw text'; } + }); + const WHERE = { banner: 'Runs in the ad viewer, on the home page, the live ledger, every Overview, the sidebar tile, and out in the Network Ad Space rotation across the wider network.', + text: 'Runs in the ad viewer, the live ledger text slot, and out in the Network Ad Space rotation.', + login: 'Full screen for every member who signs in, ten seconds, once a day per member. Opens in a fresh tab, so any working page qualifies. Login ads spend purchased credits only.', + solo: 'Delivered into member inboxes under Earn credits. Each read is timed and rewarded, so it gets opened.', + video: 'Plays in Watch videos and the Shorts feed under Earn credits. You pay only for completed watches.', + featured: 'Your headline and link in the Featured strip on every member Overview for the days you book.', + visits: 'A distinct member opens your site in a new tab, stays eight seconds and passes a check. Nobody counts twice.' }; + const whereHint = () => { const el = $('cWhere'); if (el) el.textContent = WHERE[$('cType').value] || ''; }; + whereHint(); + // runs on every type change AND once at load, so the default type (banner) shows its size + image rows immediately + function applyType() { // hoisted: loadCampaigns may run before this line is reached + whereHint(); + const t = $('cType').value; + $('cImageRow').hidden = t !== 'banner'; // only banners carry a creative; login frames its URL + $('cSizeRow').hidden = t !== 'banner'; + $('cTitleRow').hidden = t !== 'text' && t !== 'solo'; + $('cBodyRow').hidden = t !== 'text'; + $('cSoloRow').hidden = t !== 'solo'; + $('cSoloHint').hidden = t !== 'solo'; + $('cVideoRow').hidden = t !== 'video'; + $('cFeaturedRow').hidden = t !== 'featured'; + $('cVisitsRow').hidden = t !== 'visits'; + if ($('cSchedRow')) { $('cSchedRow').hidden = t === 'featured'; $('cStartLbl').textContent = t === 'solo' ? 'Send from (optional)' : 'Start (optional)'; + $('cSchedHint').textContent = t === 'solo' ? 'Deliveries to member inboxes begin at the time you pick, so you can land when people are reading. Leave empty to start now.' : 'Leave both empty to start now and run until the budget is spent. Times are your local time. Anything left when a campaign ends goes back to Available.'; } + // fixed-cost types derive their spend (featured = day slots, visits = flat pack), + // so hide the free-form Budget field for them to avoid confusion + $('cBudgetRow').hidden = (t === 'featured' || t === 'visits'); + if ($('cCapRow')) $('cCapRow').hidden = !(t === 'banner' || t === 'text'); + // solo ads have a real floor (5cr x 10 deliveries): default to 50 so 10 isn't rejected + if (t === 'solo' && (!$('cBudget').value || Number($('cBudget').value) < 50)) $('cBudget').value = (lastRates && lastRates.soloCostPerRecipient ? lastRates.soloCostPerRecipient : 5) * 10; + if (t === 'visits') visitHint(); + $('cTitle').placeholder = t === 'solo' ? 'Subject line (max 80)' : 'Headline (max 60)'; + soloHint(); + if (t === 'video') videoHint(); + if (t === 'featured') featHint(); + } + $('cType').addEventListener('change', applyType); + let featStartDay = 0; // selected start-day offset (0 = today) + async function featHint() { + if (!lastRates || !lastRates.featuredDurations) return; + if ($('cFeatDays') && !$('cFeatDays').options.length) + $('cFeatDays').innerHTML = lastRates.featuredDurations.map(dys => + '').join(''); + let s = null; + try { s = await (await fetch('/api/featured/stats')).json(); } catch (e) {} + if (s && s.occupancy) { + const grid = $('cFeatDaysGrid'); + grid.innerHTML = s.occupancy.map(d => { + const label = d.offset === 0 ? 'Today' : d.offset === 1 ? 'Tomorrow' : new Date(d.day + 'T00:00:00Z').toLocaleDateString(undefined, { weekday: 'short', month: 'numeric', day: 'numeric' }); + const full = d.open <= 0; + return '
' + + '
' + label + '
' + d.count + '/' + d.cap + (full ? ' full' : ' left ' + d.open) + '
'; + }).join(''); + grid.querySelectorAll('.feat-day:not(.full)').forEach(el => + el.addEventListener('click', () => { featStartDay = Number(el.dataset.off); featHint(); })); + } + const dys = Number($('cFeatDays').value) || (lastRates.featuredDurations[0]); + const dayLabel = featStartDay === 0 ? 'today' : featStartDay === 1 ? 'tomorrow' : 'in ' + featStartDay + ' days'; + $('cFeatHint').textContent = 'Runs ' + dys + ' day' + (dys > 1 ? 's' : '') + ' starting ' + dayLabel + + ' for ' + (dys * lastRates.featuredPerDay) + ' credits. Max ' + (s ? s.slotsPerDay : 10) + ' links share any day.'; + } + document.addEventListener('change', e => { if (e.target && e.target.id === 'cFeatDays') featHint(); }); + function visitHint() { + if (!lastRates) return; + const n = Number($('cVisitCount').value) || 0; + const cost = n * (lastRates.visitCostPerVisit || 3); + $('cVisitHint').textContent = (lastRates.visitCostPerVisit || 3) + ' credits per verified visit' + + (n >= (lastRates.visitMinPack || 20) ? ' — ' + n + ' visits = ' + cost + ' credits' : ' (min ' + (lastRates.visitMinPack || 20) + ')') + + '. Each is a unique member, dwell + human-check verified.'; + } + $('cVisitCount').addEventListener('input', visitHint); + // video composer: tier dropdown + upload + price hint + function videoHint() { + if (!lastRates || !lastRates.videoTiers) return; + if ($('cWatchSecs') && !$('cWatchSecs').options.length) + $('cWatchSecs').innerHTML = lastRates.videoTiers.map(t => + '').join(''); + const tier = lastRates.videoTiers.find(t => t.secs === Number($('cWatchSecs').value)) || lastRates.videoTiers[0]; + const n = tier ? Math.floor((Number($('cBudget').value) || 0) / tier.cost) : 0; + $('cVideoHint').textContent = tier ? (tier.cost + ' credits per completed ' + tier.secs + 's view' + + (n ? ' — this budget buys ' + n + ' views' : '') + '. Viewers earn ' + tier.reward + ' credits each, so they watch.') : ''; + } + document.addEventListener('change', e => { if (e.target && e.target.id === 'cWatchSecs') videoHint(); }); + $('cBudget').addEventListener('input', () => { if ($('cType').value === 'video') videoHint(); }); + $('cVideoUploadBtn').addEventListener('click', () => $('cVideoFile').click()); + $('cVideoUrl').addEventListener('change', async () => { + const url = $('cVideoUrl').value.trim(); + $('cVideoInfo').textContent = url ? 'checking video…' : ''; + cVidDims = url ? await probeVideoDims(url) : null; + if (url && !cVidDims) $('cVideoInfo').textContent = 'could not read that video'; + else { $('cVideoInfo').textContent = ''; showVidOrient(); } + }); + $('cVideoFile').addEventListener('change', async () => { + const f = $('cVideoFile').files[0]; + if (!f) return; + $('cVideoInfo').textContent = 'Uploading ' + f.name + '… (large files take a moment)'; + try { + const r = await (await fetch('/api/my/upload', { method: 'POST', headers: { 'Content-Type': f.type }, body: f })).json(); + if (r.error) { $('cVideoInfo').textContent = r.error; $('cVideoFile').value = ''; return; } + $('cVideoUrl').value = r.url; + $('cVideoInfo').textContent = f.name + ' uploaded'; + $('cVideoPrev').hidden = false; + $('cVideoPrev').innerHTML = ''; + cVidDims = await probeVideoDims(r.url); showVidOrient(); + } catch (e) { $('cVideoInfo').textContent = 'Upload failed. Try again.'; } + $('cVideoFile').value = ''; + }); + $('createCampBtn').addEventListener('click', busy2($('createCampBtn'), async () => { + // in raw mode the source of truth is the textarea; sync it back first + let soloBody = $('cSoloEd').innerHTML; + if ($('cSoloRaw') && !$('cSoloRaw').hidden) soloBody = $('cSoloRaw').value; + const t = $('cType').value; + const isVideo = t === 'video', isFeat = t === 'featured'; + if (isVideo && !cVidDims && $('cVideoUrl').value) cVidDims = await probeVideoDims($('cVideoUrl').value); + await api('/api/my/campaigns', { type: t, name: $('cName').value, + targetUrl: $('cTarget').value, imageUrl: $('cImage').value, size: $('cSize').value, + title: isVideo ? $('cVideoTitle').value : isFeat ? $('cFeatTitle').value : t === 'visits' ? $('cVisitTitle').value : $('cTitle').value, + body: t === 'solo' ? soloBody : $('cBody').value, + videoUrl: $('cVideoUrl').value, watchSecs: Number($('cWatchSecs').value), + videoW: cVidDims ? cVidDims.w : null, videoH: cVidDims ? cVidDims.h : null, + days: Number($('cFeatDays').value), startDay: featStartDay, + count: Number($('cVisitCount').value), + dailyCap: ($('cDailyCap') && (t === 'banner' || t === 'text')) ? Number($('cDailyCap').value) || 0 : 0, + geo: [...document.querySelectorAll('.geoTier:checked')].map(x => x.value).join(','), + startsAt: ($('cStartAt') && $('cStartAt').value && !isFeat) ? new Date($('cStartAt').value).getTime() : 0, + endsAt: ($('cEndAt') && $('cEndAt').value && !isFeat) ? new Date($('cEndAt').value).getTime() : 0, + ctaLabel: isVideo ? $('cVideoCta').value : $('cCtaLabel').value, + budget: isFeat ? (Number($('cFeatDays').value) * (lastRates.featuredPerDay || 40)) : t === 'visits' ? (Number($('cVisitCount').value) * (lastRates.visitCostPerVisit || 3)) : Number($('cBudget').value) }); + const schedStart = ($('cStartAt') && $('cStartAt').value && !isFeat) ? new Date($('cStartAt').value) : null; + IAP.status(schedStart && schedStart.getTime() > Date.now() ? 'Campaign saved. It starts serving ' + schedStart.toLocaleString([], { dateStyle: 'medium', timeStyle: 'short' }) + '.' : 'Campaign is live. It starts serving right away.', 'ok'); + // clear EVERY field so no target/creative carries into the next campaign + ['cName', 'cBudget', 'cTarget', 'cImage', 'cTitle', 'cBody', 'cCtaLabel', + 'cVideoUrl', 'cVideoTitle', 'cVideoCta', 'cVisitTitle', 'cVisitCount', 'cFeatTitle', 'cDailyCap', 'cStartAt', 'cEndAt'] + .forEach(id => { if ($(id)) $(id).value = ''; }); + document.querySelectorAll('.geoTier').forEach(x => { x.checked = true; }); + $('cSoloEd').innerHTML = ''; if ($('cSoloRaw')) $('cSoloRaw').value = ''; + $('cVideoInfo').textContent = ''; $('cVideoPrev').hidden = true; $('cVideoPrev').innerHTML = ''; + if ($('edMediaInfo')) $('edMediaInfo').textContent = ''; + cVidDims = null; + await loadCampaigns(); + })); + // defers the busy() lookup to click time (busy is declared below) + function busy2(btn, fn) { return (...a) => busy(btn, fn)(...a); } + + // ── verified visits: open a member's site (new tab), dwell, human-check, earn ── + const visState = { token: null, id: null, dwell: 8 }; + async function loadVisitStatus() { + try { + const st = await (await fetch('/api/my/visits')).json(); + if (st.error) return; + $('vsProgress').textContent = 'today: ' + (st.status.count || 0) + ' / ' + st.status.cap + ' verified visits'; + $('vsStartBtn').hidden = st.status.count >= st.status.cap; + if (st.status.count >= st.status.cap) $('vsBox').innerHTML = 'That\'s today\'s visits. Come back tomorrow.'; + } catch (e) {} + } + async function loadVisit() { + $('vsCheck').hidden = true; $('vsVisit').hidden = true; $('vsHint').textContent = ''; + let r = null; + try { r = await (await fetch('/api/my/visits')).json(); } catch (e) {} + if (!r || !r.ad) { + $('vsBox').innerHTML = '' + (r && r.status && r.status.count >= r.status.cap + ? 'That\'s today\'s visits. Come back tomorrow.' : 'No verified-visit packs are running right now. Check back soon.') + ''; + return; + } + visState.token = r.token; visState.id = r.ad.id; visState.dwell = r.status.dwell || 8; + $('vsBox').innerHTML = '' + esc(r.ad.title || 'Member site') + '
Open the site and stay ' + visState.dwell + 's.'; + const visit = $('vsVisit'); + visit.href = r.ad.url; visit.hidden = false; + $('vsStartBtn').textContent = 'Loading…'; $('vsStartBtn').disabled = true; + // opening the site starts the dwell; then we ask the human-check + visit.onclick = () => { + let left = visState.dwell; + $('vsHint').textContent = 'Counting your visit: ' + left + 's'; + const t = setInterval(async () => { + left--; + if (left > 0) { $('vsHint').textContent = 'Counting your visit: ' + left + 's'; return; } + clearInterval(t); + $('vsHint').textContent = 'One quick check to count the visit:'; + let c = await (await fetch('/api/my/visitchallenge?token=' + visState.token)).json(); + if (c.early) { await new Promise(r2 => setTimeout(r2, (c.wait || 1) * 1000 + 300)); c = await (await fetch('/api/my/visitchallenge?token=' + visState.token)).json(); } + if (c.error) { $('vsHint').textContent = c.error; return; } + renderVisitCheck(c); + }, 1000); + }; + $('vsStartBtn').textContent = 'Next visit'; $('vsStartBtn').disabled = false; + } + function renderVisitCheck(c) { + $('vsPrompt').textContent = 'Click the ' + c.prompt + ':'; + const w = $('vsOpts'); w.innerHTML = ''; + c.options.forEach((em, i) => { + const b = document.createElement('button'); + b.className = 'btn small sec'; b.style.marginRight = '6px'; b.textContent = em; + b.addEventListener('click', () => answerVisit(i)); + w.appendChild(b); + }); + $('vsCheck').hidden = false; + } + async function answerVisit(i) { + const r = await (await fetch('/api/my/visitdone', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ token: visState.token, answer: i }) })).json(); + if (r.error) { + if (r.retry) { const c = await (await fetch('/api/my/visitchallenge?token=' + visState.token)).json(); if (!c.error) return renderVisitCheck(c); } + $('vsHint').textContent = r.error; $('vsCheck').hidden = true; return; + } + $('vsCheck').hidden = true; + $('vsHint').textContent = '+' + r.credited + ' credits — visit counted. Load the next one.'; + $('vsProgress').textContent = 'today: ' + (r.status.count || 0) + ' / ' + (r.status.cap || 0) + ' verified visits'; + IAP.status('+' + r.credited + ' credits for a verified visit.', 'ok'); + loadDashboard(); + } + $('vsStartBtn').addEventListener('click', () => loadVisit()); + + // ── watch-to-earn videos: escape-proof player, server-clock reward ── + const vidState = { token: null, secs: 0, maxSeen: 0, done: false, credited: false }; + // detected dimensions of the video being created — portrait goes to Shorts, landscape to Watch videos + let cVidDims = null; + function probeVideoDims(url) { + return new Promise(resolve => { + if (!url) return resolve(null); + const v = document.createElement('video'); v.preload = 'metadata'; v.muted = true; + let done = false; const fin = r => { if (!done) { done = true; resolve(r); } }; + v.onloadedmetadata = () => fin(v.videoWidth && v.videoHeight ? { w: v.videoWidth, h: v.videoHeight } : null); + v.onerror = () => fin(null); setTimeout(() => fin(null), 8000); v.src = url; + }); + } + function showVidOrient() { + const el = $('cVideoInfo'); if (!el) return; + if (!cVidDims) return; + const portrait = cVidDims.h > cVidDims.w; + el.textContent = (el.textContent ? el.textContent + ' · ' : '') + + (portrait ? 'portrait — shows in the Shorts reel' : 'landscape — shows in the Watch videos tab'); + } + async function loadVideoStatus() { + try { + const st = await (await fetch('/api/my/videos?orientation=landscape')).json(); + if (st.error) return; + $('vidProgress').textContent = 'today: ' + (st.status.count || 0) + ' / ' + st.status.cap + ' videos watched'; + if (st.status.left <= 0) { + $('vidBox').innerHTML = 'That is today\'s video set. Come back tomorrow.'; + $('vidStartBtn').hidden = true; + return; + } + $('vidStartBtn').hidden = false; + } catch (e) {} + } + // leaving the player (other sub-tab, other pane, page hidden) stops the clip: nothing plays or earns in the background (Marty, 2026-09-13) + function stopVideo() { + const p = $('vidPlayer'); if (!p) return; + const was = !!vidState.token && !vidState.done; + try { p.pause(); p.ontimeupdate = null; p.onseeking = null; p.removeAttribute('src'); p.load(); } catch (e) {} + vidState.token = null; vidState.done = false; vidState.credited = false; vidState.maxSeen = 0; + if ($('vidWrap')) $('vidWrap').hidden = true; + if ($('vidBox')) { $('vidBox').hidden = false; if (was) $('vidBox').innerHTML = 'Video stopped when you left the tab. Tap Load a video to start a fresh one.'; } + if ($('vidStartBtn')) { $('vidStartBtn').disabled = false; $('vidStartBtn').textContent = 'Load a video'; } + } + document.addEventListener('visibilitychange', () => { if (document.hidden && vidState.token && !vidState.done) stopVideo(); }); + async function loadVideoAd() { + let r = null; + try { r = await (await fetch('/api/my/videos?orientation=landscape')).json(); } catch (e) {} + if (!r || !r.ad) { + // same done screen as Watch ads when the day's videos are finished (Marty, 2026-09-13) + const capHit = !!(r && r.status && r.status.left <= 0), allWatched = !!(r && r.allWatched); + $('vidBox').innerHTML = (capHit || allWatched) + ? '
✓Videos done for today' + (capHit ? 'That is today’s video set (' + r.status.count + ' watched). Fresh videos tomorrow.' : 'You have watched every live video for today; each one pays once a day. New ones appear as members launch video campaigns.') + '
' + : 'No member videos are live right now. Check back when a campaign is running.'; + if ($('vidStartBtn')) $('vidStartBtn').hidden = capHit || allWatched; + $('vidBox').hidden = false; + $('vidWrap').hidden = true; + return; + } + const ad = r.ad; + vidState.token = r.token; vidState.secs = ad.watchSecs; vidState.maxSeen = 0; vidState.done = false; vidState.credited = false; + $('vidBox').hidden = true; + $('vidWrap').hidden = false; + $('vidCta').hidden = true; + $('vidHint').textContent = ad.title ? 'Now playing: ' + ad.title : ''; + const p = $('vidPlayer'); + p.src = ad.videoUrl; + p.currentTime = 0; + // escape-proof: no seeking past what's been watched; track max reached + p.onseeking = () => { if (p.currentTime > vidState.maxSeen + 0.5) p.currentTime = vidState.maxSeen; }; + p.ontimeupdate = () => { + if (p.currentTime > vidState.maxSeen) vidState.maxSeen = p.currentTime; + const left = Math.max(0, Math.ceil(vidState.secs - vidState.maxSeen)); + $('vidTimer').textContent = left > 0 ? 'Watch ' + left + 's more to earn' : 'Watch time met — finishing…'; + if (!vidState.done && vidState.maxSeen >= vidState.secs) { vidState.done = true; completeVideo(ad); } + }; + $('vidStartBtn').textContent = 'Playing…'; + $('vidStartBtn').disabled = true; + try { await p.play(); } catch (e) { $('vidStartBtn').disabled = false; $('vidStartBtn').textContent = 'Tap to play'; } + $('vidCta').href = ad.ctaUrl; + $('vidCta').textContent = ad.ctaLabel || 'Learn more'; + $('vidCta').hidden = false; + } + async function completeVideo(ad) { + if (vidState.credited) return; + vidState.credited = true; + try { + const r = await (await fetch('/api/my/videowatch', { method: 'POST', + headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ token: vidState.token }) })).json(); + if (r.error) { IAP.status(r.error, 'bad'); $('vidHint').textContent = r.error + (/no longer open|stale/.test(r.error) ? ' Loading a fresh one.' : ''); if (/no longer open|stale/.test(r.error)) setTimeout(() => loadVideoAd(), 1200); } + else if (r.credited) { IAP.status('+' + r.credited + ' credits earned for watching.', 'ok'); $('vidHint').textContent = '+' + r.credited + ' credits earned. Load the next one.'; loadDashboard(); } + else $('vidHint').textContent = 'That video just ran out of budget — load another.'; + if (r.status) $('vidProgress').textContent = 'today: ' + (r.status.count || 0) + ' / ' + r.status.cap + ' videos watched'; + } catch (e) { IAP.status('Could not confirm that watch. Try the next one.', 'bad'); } + $('vidStartBtn').disabled = false; + $('vidStartBtn').textContent = 'Next video'; + } + $('vidStartBtn').addEventListener('click', () => loadVideoAd()); + // presence enforcement: pause the watch-to-earn video when the tab/window loses focus, + // resume when it comes back — the viewer must stay on the page for the watch to complete + document.addEventListener('visibilitychange', () => { + const p = $('vidPlayer'); if (!p || !p.src) return; + if (document.hidden) p.pause(); else if (!vidState.done) p.play().catch(() => {}); + }); + window.addEventListener('blur', () => { const p = $('vidPlayer'); if (p && p.src) p.pause(); }); + window.addEventListener('focus', () => { const p = $('vidPlayer'); if (p && p.src && !vidState.done) p.play().catch(() => {}); }); + + // ── unmissable sponsor-message modal on sign-in ── + function showSponsorModal(msg) { + if (!$('msgModal')) return; + $('mmFrom').textContent = 'A message from ' + (msg.fromName || 'your sponsor'); + $('mmSubject').textContent = msg.subject || ''; + $('mmBody').innerHTML = msg.body || ''; // server-sanitized + $('msgModal').hidden = false; + $('mmAck').onclick = async () => { + $('msgModal').hidden = true; + try { await fetch('/api/my/messages/' + msg.id + '/read', { method: 'POST' }); } catch (e) {} + }; + } + + // ── coaching: every direct's rung, stalled flag, one-click nudge ── + // ── pay it forward: send POL from the sponsor's own wallet to a downline's linked address ── + async function pif(email, name, address) { + let suggest = 25; + try { const { products } = await (await fetch('/api/catalog')).json(); const p20 = (products || []).find(p => p.priceCents === 2000); if (p20 && p20.costWei) suggest = Math.ceil(Number(p20.costWei) / 1e18) + 3; } catch (e) {} + const amt = await IAP.ask({ title: 'Pay it forward', text: 'Send POL from your wallet to ' + name + ' (' + address.slice(0, 6) + '…' + address.slice(-4) + ') for their first package.\nSuggested: the $20 package plus fees. Amount in POL:', type: 'number', value: String(suggest), ok: 'Send POL' }); + if (amt === null) return; + const pol = Number(amt); if (!(pol > 0)) { IAP.status('Enter an amount in POL.', 'bad'); return; } + try { + IAP.status('Confirm the transfer in your wallet…', 'ok'); + const wei = (BigInt(Math.round(pol * 1e6)) * 10n ** 12n).toString(); + const hash = await IAPWallet.sendPol(address, wei); + await api('/api/my/gift', { email, tx: hash, pol }); + IAP.status('Sent ' + pol + ' POL to ' + name + '. They have been told, with the proof link.', 'ok'); + playSound && playSound('chaching'); + } catch (e) { IAP.status('Transfer not sent: ' + ((e && e.message) || e), 'bad'); } + } + // ── holding tank: waiting members, adopt, my open adoptions ── + const ago = ts => { if (!ts) return 'never'; const d = Math.floor((Date.now() - ts) / 86400000); return d === 0 ? 'today' : d === 1 ? 'yesterday' : d + ' days ago'; }; + async function loadTank() { + const el = $('tankList'); if (!el) return; + try { + const r = await (await fetch('/api/my/tank')).json(); + if (r.error) { el.innerHTML = ''; return; } + $('tankCap').textContent = r.cap; $('tankTtl').textContent = r.ttlDays; + $('tankSub').textContent = r.waiting.length ? r.waiting.length + ' waiting' : 'nobody waiting right now'; + const why = $('tankWhy'); why.hidden = r.eligible; why.innerHTML = r.eligible ? '' : 'not yet ' + esc(r.reason); + $('tankMine').innerHTML = r.mine.length ? '

Your open adoptions

' + r.mine.map(m => '
' + esc(m.name) + '' + + '' + (m.bought ? 'bought' : m.wallet ? 'wallet linked' : 'free, no wallet yet') + ' · last seen ' + ago(m.lastSeen) + '' + + '' + Math.max(0, Math.ceil((m.expires - Date.now()) / 86400000)) + ' days left' + + '' + + (m.address && !m.bought ? ' ' : '') + '
').join('') : ''; + $('tankMine').querySelectorAll('[data-tchat]').forEach(b => b.addEventListener('click', () => openConvo(b.dataset.tchat, b.dataset.tname))); + $('tankMine').querySelectorAll('[data-pif]').forEach(b => b.addEventListener('click', () => pif(b.dataset.pif, b.dataset.pname, b.dataset.paddr))); + if (!r.waiting.length) { el.innerHTML = '

The tank is empty. Anyone who joins from the public site without a sponsor lands here.

'; return; } + el.innerHTML = r.waiting.map(w => '
' + esc(w.name) + '' + + 'joined ' + ago(w.joined) + '' + + 'last sign-in: ' + ago(w.lastSeen) + '' + + (r.eligible ? '' : '') + '
').join(''); + el.querySelectorAll('[data-adopt]').forEach(b => b.addEventListener('click', async () => { + const note = await IAP.ask({ title: 'Adopt ' + b.dataset.aname, text: 'Your first message to ' + b.dataset.aname + ' (sent as a chat and an email):', type: 'textarea', ok: 'Adopt and send', value: 'Hi, I picked you up from the LinkSpin holding tank so you have a sponsor who will actually help. Reply here and I will walk you through the first three steps.' }); + if (note === null) return; + try { const rr = await api('/api/my/tank/adopt', { who: b.dataset.adopt, note }); IAP.status('You are now the sponsor for ' + rr.name + '. Chat and email sent.', 'ok'); loadTank(); loadCoach(); } + catch (e) { IAP.status(e.message, 'bad'); } + })); + } catch (e) {} + } + async function loadCoach() { + loadTank(); + try { + const r = await (await fetch('/api/my/coach')).json(); + const el = $('coachList'); if (!el || r.error) return; + const d = r.directs || []; + $('coachSummary').innerHTML = d.length ? '' + d.length + ' direct' + (d.length === 1 ? '' : 's') + ' · ' + r.stalled + ' quiet for 3+ days' + (r.stalled ? ' · start at the top' : '') : ''; + if (!d.length) { el.innerHTML = '

No directs yet. When someone joins through your link they show up here with their next step.

'; return; } + el.innerHTML = d.map(x => '
' + esc(x.name) + (x.stalled ? ' quiet ' + x.quietDays + 'd' : '') + + (x.rescue && x.rescue.unreached ? ' unreached · tank in ' + x.rescue.rescueInDays + 'd' : '') + (x.bound === false ? ' not bound to you on-chain' : '') + '' + + '' + esc(x.label) + ' → ' + esc(x.next) + '' + + 'rung ' + x.rung + '/6' + + '' + (x.buyerCount ? x.buyerCount + ' buyer' + (x.buyerCount === 1 ? '' : 's') : '') + '' + + '' + + (x.free && x.address ? ' ' : '') + + (x.free && x.rescue ? ' ' : '') + + (x.free ? ' ' : '') + '
').join(''); + el.querySelectorAll('[data-contacted]').forEach(b => b.addEventListener('click', async () => { + try { await api('/api/my/tank/contacted', { email: b.dataset.contacted }); IAP.status('Marked: you have contacted ' + b.dataset.cname + '.', 'ok'); loadCoach(); } + catch (e) { IAP.status(e.message, 'bad'); } + })); + el.querySelectorAll('[data-pif]').forEach(b => b.addEventListener('click', () => pif(b.dataset.pif, b.dataset.pname, b.dataset.paddr))); + el.querySelectorAll('[data-nudge]').forEach(b => b.addEventListener('click', async () => { + await openConvo(b.dataset.nudge, b.dataset.nname); + const inp = $('chatInput'); if (inp) { inp.value = b.dataset.say.replace(/\{\{name\}\}/g, b.dataset.nname.replace(/^@/, '')); inp.focus(); } + })); + el.querySelectorAll('[data-release]').forEach(b => b.addEventListener('click', async () => { + if (!(await IAP.confirmBox('Release ' + b.dataset.rname + ' to the holding tank? You stop being their sponsor and another member can adopt them.', { title: 'Release to the tank', ok: 'Release' }))) return; + try { await api('/api/my/tank/release', { email: b.dataset.release }); IAP.status(b.dataset.rname + ' is in the holding tank.', 'ok'); loadCoach(); } + catch (e) { IAP.status(e.message, 'bad'); } + })); + } catch (e) {} + } + // schedule chips on the campaign table (local time) + by-hour view bars + const fmtWhen = ms => new Date(ms).toLocaleString([], { month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' }); + function schedChips(c) { + const now = Date.now(); let s = ''; + if (c.starts && c.starts > now) s += ' starts ' + fmtWhen(c.starts) + ''; + if (c.expires && c.type !== 'featured') s += ' ' + (c.expires > now ? 'ends ' : 'ended ') + fmtWhen(c.expires) + ''; + return s; + } + function geoLine(rows) { + if (!rows || !rows.length) return ''; + return '
' + rows.map(r => esc(r.cc) + ' ' + r.n).join(' · ') + '
'; + } + function hourBars(utc) { + if (!utc || !utc.some(n => n)) return ''; + // rotate the 24 UTC buckets into the viewer's local hours + const local = new Array(24).fill(0); + for (let h = 0; h < 24; h++) local[new Date(Date.UTC(2000, 0, 1, h)).getHours()] += utc[h]; + const max = Math.max(...local); + const lab = h => (h % 12 || 12) + (h < 12 ? 'am' : 'pm'); + return '
' + local.map((n, h) => + '').join('') + + '
views by hour · last 7 days · your time
'; + } + // ── link stats: views, joins, buyers per angle ── + async function loadLinkStats() { + try { + const r = await (await fetch('/api/my/linkstats')).json(); + const t = $('linkStatsTable'); if (!t || r.error) return; + const rows = (r.angles || []).filter(a => a.views || a.joins || a.buyers); + if (!rows.length) { t.innerHTML = 'No views yet. Share your link and the numbers start here.'; return; } + t.innerHTML = 'HookViews (30d)Views (all)JoinedQualifying buyers' + + rows.map(a => '' + esc(a.angle === 'plain' ? 'plain link' : '?v=' + a.angle) + '' + a.views30 + '' + a.views + '' + a.joins + '' + a.buyers + '').join(''); + const st = $('linkSrcTable'); + if (st) { + const src = (r.sources || []).filter(x => x.views || x.joins); + st.innerHTML = src.length ? 'SourceViews (30d)Views (all)JoinedQualifying buyers' + + src.map(x => '' + esc(x.source) + '' + x.views30 + '' + x.views + '' + x.joins + '' + x.buyers + '').join('') + : 'Sources appear as visits arrive.'; + } + } catch (e) {} + } + // ── prospects: the member's own follow-up list ── + let PP_STATUSES = ['new', 'contacted', 'interested', 'joined', 'bought', 'not now']; + // ── Pipeline: the follow-up board (Marty, 2026-09-15). Stages come from the server; cards never move by hand ── + let PIPE = null, PIPE_KEY = null; + const pipeAgo = ts => { const d = Math.floor((Date.now() - ts) / 86400000); return d <= 0 ? 'today' : d === 1 ? 'yesterday' : d < 30 ? d + 'd ago' : new Date(ts).toLocaleDateString(undefined, { month: 'short', day: 'numeric' }); }; + const pipeInvite = () => { const t = ($('inviteLine') && $('inviteLine').textContent) || ''; return /^https?:\/\//.test(t) ? t : ''; }; + function pipeCardHtml(c, showStage) { + const today = new Date(); today.setHours(23, 59, 59, 999); + const due = c.followUp && c.followUp <= today.getTime(); + const chips = []; + if (c.stalled) chips.push('stalled ' + c.quietDays + 'd'); + if (due) chips.push('follow up'); + else if (c.followUp) chips.push('' + new Date(c.followUp).toLocaleDateString(undefined, { month: 'short', day: 'numeric' }) + ''); + if (c.tag) chips.push('' + esc(c.tag) + ''); + if (c.kind === 'member' && c.buyers) chips.push('' + c.buyers + ' buyer' + (c.buyers === 1 ? '' : 's') + ''); + const stage = showStage ? (PIPE.stages.find(s => s.key === c.stage) || {}).label || '' : ''; + return '
' + + '
' + esc(c.name) + '' + (c.kind === 'prospect' ? 'prospect' : (c.lastSeen ? 'seen ' + pipeAgo(c.lastSeen) : 'never signed in')) + '
' + + '
' + esc(stage ? stage + ' · ' + c.next : c.next) + '
' + + (c.note ? '
' + esc(c.note) + '
' : '') + + (chips.length ? '
' + chips.join('') + '
' : '') + '
'; + } + async function loadPipeline() { + try { + const r = await (await fetch('/api/my/pipeline')).json(); + if (r.error) { IAP.status(r.error, 'bad'); return; } + if (!r.live) { + $('pipeSoon').hidden = false; $('pipeLive').hidden = true; + $('pipeSoonEta').textContent = r.eta ? 'Opens ' + r.eta + '. It is on the roadmap so you can see what is coming and when.' : 'It is on the roadmap so you can see what is coming and when.'; + return; + } + PIPE = r; $('pipeSoon').hidden = true; $('pipeLive').hidden = false; + const badge = $('pipeBadge'); if (badge) { const n = r.counts.due + r.counts.stalled; badge.hidden = !n; badge.textContent = n > 9 ? '9+' : n; } + $('pipeDueCount').hidden = !r.due.length; $('pipeDueCount').textContent = r.due.length; + $('pipeDue').innerHTML = r.due.length ? '
' + r.due.map(c => pipeCardHtml(c, true)).join('') + '
' : '

Nothing due. Set a follow-up date on any card and it shows up here.

'; + $('pipeSummary').textContent = r.counts.total ? r.counts.total + ' people on your board' + (r.counts.stalled ? ', ' + r.counts.stalled + ' stalled' : '') + '. Cards move on their own when something happens on the ledger; open one to add a note, a follow-up date or a tag.' : 'Nobody on your board yet. Add prospects on My line, and everyone who joins through your link appears here on their own.'; + $('pipeBoard').innerHTML = r.columns.map(col => '

' + esc(col.label) + '' + col.cards.length + '

' + esc(col.hint) + '

' + col.cards.map(c => pipeCardHtml(c, false)).join('') + '
').join(''); + $('pipeLive').querySelectorAll('[data-pk]').forEach(el => { + el.addEventListener('click', () => openPipeCard(el.dataset.pk)); + el.addEventListener('keydown', e => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); openPipeCard(el.dataset.pk); } }); + }); + if (PIPE_KEY) { const c = allPipeCards().find(x => x.key === PIPE_KEY); if (c) fillPipeCard(c); else { PIPE_KEY = null; $('pipeCard').hidden = true; } } + } catch (e) { IAP.status('Could not load your pipeline.', 'bad'); } + } + function allPipeCards() { return PIPE ? PIPE.columns.flatMap(c => c.cards) : []; } + function fillPipeCard(c) { + $('pipeCardName').textContent = c.name; + const stage = (PIPE.stages.find(s => s.key === c.stage) || {}).label || ''; + $('pipeCardMeta').textContent = stage + (c.kind === 'member' ? ' · joined ' + new Date(c.since).toLocaleDateString() + (c.lastSeen ? ' · last seen ' + pipeAgo(c.lastSeen) : ' · never signed in') + (c.bought ? ' · your qualifying buyer' : '') + (c.buyersPositions ? ' · ' + c.buyers + ' buyers: ' + c.buyersMain + ' on the main wallet, ' + c.buyersPositions + ' on linked positions' : '') : ' · prospect' + (c.contact ? ' · ' + c.contact : '')); + $('pipeCardNext').innerHTML = 'Next for them: ' + esc(c.next) + (c.stalled ? ' quiet ' + c.quietDays + ' days' : ''); + const say = (c.say || '').replace('{{link}}', pipeInvite()); + $('pipeSayBlock').hidden = !say; $('pipeSay').textContent = say; + $('pipeSend').hidden = c.kind !== 'member' || !c.email; + $('pipeFollow').value = c.followUp ? new Date(c.followUp).toISOString().slice(0, 10) : ''; + const sel = $('pipeTag'); sel.innerHTML = PIPE.tags.map(t => '').join(''); + $('pipeNote').value = c.note || ''; $('pipeSaved').textContent = ''; + $('pipeCard').hidden = false; + } + function openPipeCard(key) { + const c = allPipeCards().find(x => x.key === key); if (!c) return; + PIPE_KEY = key; $('pipeLive').querySelectorAll('[data-pk]').forEach(el => el.classList.toggle('on', el.dataset.pk === key)); + fillPipeCard(c); $('pipeCard').scrollIntoView({ behavior: 'smooth', block: 'nearest' }); + } + if ($('pipeCardClose')) $('pipeCardClose').addEventListener('click', () => { PIPE_KEY = null; $('pipeCard').hidden = true; $('pipeLive').querySelectorAll('[data-pk]').forEach(el => el.classList.remove('on')); }); + if ($('pipeSave')) $('pipeSave').addEventListener('click', async () => { + if (!PIPE_KEY) return; + try { await api('/api/my/pipeline/note', { key: PIPE_KEY, note: $('pipeNote').value, followUp: $('pipeFollow').value || null, tag: $('pipeTag').value }); $('pipeSaved').textContent = 'Saved.'; loadPipeline(); } + catch (e) { IAP.status(e.message, 'bad'); } + }); + if ($('pipeCopy')) $('pipeCopy').addEventListener('click', async () => { try { await navigator.clipboard.writeText($('pipeSay').textContent); $('pipeCopy').textContent = 'Copied'; setTimeout(() => { $('pipeCopy').textContent = 'Copy message'; }, 1500); } catch (e) { IAP.status('Copy failed; select the text by hand.', 'bad'); } }); + if ($('pipeSend')) $('pipeSend').addEventListener('click', () => { + const c = allPipeCards().find(x => x.key === PIPE_KEY); if (!c || !c.email) return; + openConvo(c.email, c.name); + const ta = $('chatInput'); if (ta) { ta.value = $('pipeSay').textContent; ta.dispatchEvent(new Event('input')); ta.focus(); } + }); + // ── the rotator (LinkSpin) ── + let ROT = null, ROT_HOSTS = [], ROT_ID = null; + const rotLink = r => 'https://' + (ROT_HOSTS[0] || location.host) + '/r/' + r.code; + async function loadRotator() { + try { + const r = await (await fetch('/api/my/rotations')).json(); if (r.error) { IAP.status(r.error, 'bad'); return; } + ROT = r.rotations || []; ROT_HOSTS = r.hosts || []; + const el = $('rotList'); + el.innerHTML = ROT.length ? ROT.map(x => '
' + esc(x.name) + (x.paused ? ' paused' : '') + '' + esc(rotLink(x)) + '' + x.destinations.length + ' dest' + x.hits7 + ' hits · 7d' + x.uniques + ' uniques
').join('') : '

No rotations yet. Create one above, add two or more destinations, and share the short link.

'; + el.querySelectorAll('[data-rot]').forEach(row => row.addEventListener('click', () => openRotation(Number(row.dataset.rot)))); + if (ROT_ID) { const cur = ROT.find(x => x.id === ROT_ID); if (cur) fillRotation(cur); else { ROT_ID = null; $('rotCard').hidden = true; } } + } catch (e) { IAP.status('Could not load your rotations.', 'bad'); } + } + function fillRotation(x) { + $('rotCardName').textContent = x.name; $('rotCardLink').textContent = rotLink(x); + $('rotPause').textContent = x.paused ? 'Resume' : 'Pause'; + $('rotCardSum').textContent = x.hits + ' hits all time, ' + x.hits7 + ' in the last 7 days, ' + x.uniques + ' unique visitors, ' + x.bots + ' bot hits filtered' + (x.fallback ? '. Fallback: ' + x.fallback : '. No fallback set: with every destination paused the link shows a not-active page.'); + const t = $('rotDests'); + t.innerHTML = 'DestinationWeightShareHits7dUniques' + (x.destinations.length ? x.destinations.map(d => { const total = x.destinations.filter(q => q.active).reduce((n, q) => n + q.weight, 0) || 1; return '' + esc(d.label || 'Destination ' + d.id) + '
' + esc(d.url) + '' + (d.active ? Math.round(d.weight / total * 100) + '%' : 'paused') + '' + d.hits + '' + d.hits7 + '' + d.uniques + ' '; }).join('') : 'No destinations yet. Add at least one below.'); + t.querySelectorAll('[data-rw]').forEach(i => i.addEventListener('change', async () => { try { await api('/api/my/rotations/' + x.id + '/dest/' + i.dataset.rw, { weight: i.value }); loadRotator(); } catch (e) { IAP.status(e.message, 'bad'); } })); + t.querySelectorAll('[data-rt]').forEach(b => b.addEventListener('click', async () => { const d = x.destinations.find(q => q.id === Number(b.dataset.rt)); try { await api('/api/my/rotations/' + x.id + '/dest/' + b.dataset.rt, { active: !d.active }); loadRotator(); } catch (e) { IAP.status(e.message, 'bad'); } })); + t.querySelectorAll('[data-rx]').forEach(b => b.addEventListener('click', async () => { if (!await IAP.confirmBox('Remove this destination? Its hit history stays in the stats.')) return; try { await api('/api/my/rotations/' + x.id + '/dest/' + b.dataset.rx, { remove: true }); loadRotator(); } catch (e) { IAP.status(e.message, 'bad'); } })); + $('rotCard').hidden = false; + fetch('/api/my/rotations/' + x.id + '/stats').then(r => r.json()).then(st => { + if (!st || st.error) return; + const lst = (arr, label) => arr.length ? '
' + label + '
' + arr.map(a => esc(a.k) + ' ' + a.n).join(' · ') + '
' : ''; + $('rotStats').innerHTML = '
' + lst(st.country, 'By country') + lst(st.source, 'By source') + lst(st.device, 'By device') + '
' + (st.days.length ? '

Last days: ' + st.days.slice(-10).map(d => d.day.slice(5) + ' ' + d.n).join(' · ') + '

' : ''); + }).catch(() => {}); + } + function openRotation(id) { const x = ROT.find(r => r.id === id); if (!x) return; ROT_ID = id; fillRotation(x); $('rotCard').scrollIntoView({ behavior: 'smooth', block: 'nearest' }); } + if ($('rotNew')) $('rotNew').addEventListener('submit', async e => { e.preventDefault(); try { const r = await api('/api/my/rotations', { name: $('rotName').value, fallback: $('rotFallback').value }); $('rotName').value = ''; $('rotFallback').value = ''; ROT_ID = r.rotation.id; await loadRotator(); } catch (err) { IAP.status(err.message, 'bad'); } }); + if ($('rotAdd')) $('rotAdd').addEventListener('submit', async e => { e.preventDefault(); if (!ROT_ID) return; try { await api('/api/my/rotations/' + ROT_ID + '/dest', { url: $('rotUrl').value, label: $('rotLabel').value, weight: $('rotWeight').value }); $('rotUrl').value = ''; $('rotLabel').value = ''; $('rotWeight').value = 1; loadRotator(); } catch (err) { IAP.status(err.message, 'bad'); } }); + if ($('rotCopy')) $('rotCopy').addEventListener('click', async () => { try { await navigator.clipboard.writeText($('rotCardLink').textContent); $('rotCopy').textContent = 'Copied'; setTimeout(() => { $('rotCopy').textContent = 'Copy link'; }, 1500); } catch (e) { IAP.status('Copy failed; select the link by hand.', 'bad'); } }); + if ($('rotPause')) $('rotPause').addEventListener('click', async () => { const x = ROT.find(r => r.id === ROT_ID); if (!x) return; try { await api('/api/my/rotations/' + x.id, { paused: !x.paused }); loadRotator(); } catch (e) { IAP.status(e.message, 'bad'); } }); + if ($('rotDelete')) $('rotDelete').addEventListener('click', async () => { if (!ROT_ID || !await IAP.confirmBox('Delete this rotation? Its short link stops working immediately.')) return; try { await api('/api/my/rotations/' + ROT_ID, { remove: true }); ROT_ID = null; $('rotCard').hidden = true; loadRotator(); } catch (e) { IAP.status(e.message, 'bad'); } }); + if ($('rotClose')) $('rotClose').addEventListener('click', () => { ROT_ID = null; $('rotCard').hidden = true; }); + async function loadProspects() { + try { + const r = await (await fetch('/api/my/prospects')).json(); + if (r.error) return; + PP_STATUSES = r.statuses || PP_STATUSES; + const sel = $('ppStatus'); if (sel && !sel.options.length) sel.innerHTML = PP_STATUSES.map(s => '').join(''); + const list = r.prospects || []; const el = $('prospectList'); if (!el) return; + if (!list.length) { el.innerHTML = '

Nobody on the list yet.

'; return; } + const today = new Date(); today.setHours(0, 0, 0, 0); + el.innerHTML = list.map(p => { const due = p.nextTs && p.nextTs <= today.getTime() + 86399999; return '
' + esc(p.name) + (due ? ' follow up' : '') + '' + + '' + esc(p.contact || '') + (p.note ? ' · ' + esc(p.note) : '') + '' + + '' + + '' + + '
'; }).join(''); + const save = async (id, patch) => { const p = list.find(x => x.id === Number(id)); if (!p) return; try { await api('/api/my/prospects', Object.assign({}, p, patch)); } catch (e) { IAP.status(e.message, 'bad'); } }; + el.querySelectorAll('[data-pstatus]').forEach(s => s.addEventListener('change', () => save(s.dataset.pstatus, { status: s.value }))); + el.querySelectorAll('[data-pnext]').forEach(i => i.addEventListener('change', () => save(i.dataset.pnext, { next: i.value, nextTs: i.value ? Date.parse(i.value + 'T12:00:00') : null }))); + el.querySelectorAll('[data-pdel]').forEach(b => b.addEventListener('click', async () => { try { await api('/api/my/prospects/remove', { id: b.dataset.pdel }); loadProspects(); } catch (e) { IAP.status(e.message, 'bad'); } })); + } catch (e) {} + } + if ($('prospectForm')) $('prospectForm').addEventListener('submit', async e => { + e.preventDefault(); + try { + await api('/api/my/prospects', { name: $('ppName').value, contact: $('ppContact').value, status: $('ppStatus').value, nextTs: $('ppNext').value ? Date.parse($('ppNext').value + 'T12:00:00') : null }); + $('ppName').value = ''; $('ppContact').value = ''; $('ppNext').value = ''; loadProspects(); + } catch (err) { IAP.status(err.message, 'bad'); } + }); + // ── broadcast templates ── + const BC_TEMPLATES = [ + { label: 'Welcome', subject: 'Welcome to my line: your first three moves', html: '

Glad you are in. Three things today, in this order:

  1. Pick your username on the Profile tab (it becomes your link).
  2. Wallet tab: Connect and link wallet, then Switch on payouts. Both are free.
  3. Copy your invite link from My line and send it to one person.

Reply here if you get stuck on any of them. That is what I am here for.

' }, + { label: 'Switch on payouts', subject: 'One free step so nothing passes you by', html: '

Quick reminder: if payouts are not switched on yet, do it now on the Wallet tab. One free transaction.

The contract locks each buyer to their sponsor at their first purchase, and payouts only route to wallets that are switched on. Ready early and you never miss one.

' }, + { label: 'The $5 test', subject: 'See a payout land in real time', html: '

Want to see the whole thing work? Buy the $5 Micro package on Buy packages and watch the live ledger while you do it. You will see your credits mint and the split go out in the same transaction.

When you are ready to count as a qualifying buyer for me, the $20 Activation package is the one.

' }, + { label: 'Qualified Start', subject: 'How to open level 2 today with your own positions', html: '

You can be your own first buyers, openly. On Buy packages, the Qualified Start card lets you link a second wallet you own as a position. When it buys a $20 package, it counts as a qualifying buyer, half comes straight back to your main wallet, and the credits pool with yours.

Two positions open level 2 the same day. The three Qualified Start videos in Training show every click.

' }, + { label: 'Share your link', subject: 'One conversation a day is the whole job', html: '

Promo tools has posts, texts and emails that already carry your link. Pick one and send it to one person today.

Do not wait for the perfect moment. Nobody who waited ever built a line.

' } + ]; + (function () { + const w = $('bcTemplates'); if (!w) return; + w.innerHTML = BC_TEMPLATES.map((t, i) => '').join(''); + w.querySelectorAll('[data-bct]').forEach(b => b.addEventListener('click', () => { const t = BC_TEMPLATES[Number(b.dataset.bct)]; $('bcSubject').value = t.subject; $('bcEd').innerHTML = t.html; $('bcEd').focus(); })); + })(); + // ── Qualified Start calculator ── + (function () { + const n = $('qcN'), pk = $('qcPkg'), out = $('qcOut'); if (!n || !pk || !out) return; + const CR = { 25: 2500, 50: 5000, 100: 10000, 250: 25000, 500: 50000 }; // flat credits = cents (Marty 2026-10-07) + const calc = () => { + const k = Math.max(1, Math.min(10, Number(n.value) || 1)), usd = Number(pk.value) || 25; + const gross = k * usd, back = gross / 2, net = gross - back, credits = k * (CR[usd] || 0); + const level = k >= 5 ? 'Level 3 open (and level 2): the Nexus badge, wall position 3, full 50 / 20 / 10' : k >= 2 ? 'Level 2 open: 20% on your directs\' buyers, wall position 2' : 'Counts as one qualifying buyer. One more opens level 2.'; + out.innerHTML = '
$' + gross + ' out across ' + k + ' position' + (k === 1 ? '' : 's') + '
$' + back + ' back to your main wallet in the same transactions (the 50% direct-sponsor share)
$' + net + ' net, plus a little POL for gas in each wallet
' + + '
' + credits.toLocaleString() + ' credits pooled for your own ads
' + level + '
The 20% and 10% shares go to your upline if they are qualified, otherwise to the platform.
'; + }; + n.addEventListener('input', calc); pk.addEventListener('change', calc); calc(); + })(); + + // ── downline lineage + sponsor broadcast + upline messages ── + async function loadLineage() { + try { + const r = await (await fetch('/api/my/line')).json(); + const el = $('lineageWrap'); + if (r.error || !r.levels || !r.levels.every) return; + if (!r.levels.length || !r.levels.some(L => L.members.length)) { + el.innerHTML = '

No one in your downline yet. Share your link and it fills in here.

'; + return; + } + el.innerHTML = r.levels.map(L => !L.members.length ? '' : + '
Level ' + L.level + ' · ' + L.members.length + (L.level === 1 ? ' direct' : '') + '
' + + L.members.map(m => '
' + esc(m.name) + (m.own ? ' yours' : '') + '' + + '' + (m.email ? esc(m.email) : (m.memberId ? '#' + m.memberId + '' : '')) + (m.sponsor ? 'sponsored by ' + esc(m.sponsor) + '' : '') + (m.own ? '' : '' + (m.bought ? '$20+ buy ✓' : 'no $20+ buy yet') + (m.buyers ? ' · ' + m.buyers + ' qualifying buyer' + (m.buyers === 1 ? '' : 's') + ' of their own' : '') + '') + '' + + '' + + (m.earnedWei && m.earnedWei !== '0' ? '+' + IAP.fmtPol(m.earnedWei) + ' POL' : '0.00 POL') + '' + + '' + new Date(m.joined).toLocaleDateString() + '' + + (m.email ? '' : '') + + (m.ref && !m.own ? '' : '') + + '
' + (m.ref && !m.own ? '' : '')).join('') + + '
').join(''); + el.querySelectorAll('[data-cemail]').forEach(b => + b.addEventListener('click', () => openConvo(b.dataset.cemail, b.dataset.cname))); + el.querySelectorAll('[data-act]').forEach(b => b.addEventListener('click', () => toggleLineActivity(b))); + } catch (e) {} + } + // who is working: per-member activity drop-down under the row (any of the three levels) + const lineActCache = {}; + async function toggleLineActivity(btn) { + const box = document.querySelector('[data-actbox="' + btn.dataset.act + '"]'); if (!box) return; + const open = box.hidden; box.hidden = !open; btn.setAttribute('aria-expanded', String(open)); btn.textContent = open ? 'Activity ▴' : 'Activity ▾'; + if (!open) return; + if (!lineActCache[btn.dataset.act]) { + box.innerHTML = 'Loading…'; + try { lineActCache[btn.dataset.act] = await (await fetch('/api/my/line/activity?ref=' + encodeURIComponent(btn.dataset.act))).json(); } catch (e) { lineActCache[btn.dataset.act] = { error: 'Could not load.' }; } + } + const a = lineActCache[btn.dataset.act]; + if (a.error) { box.innerHTML = '' + esc(a.error) + ''; return; } + const ago = t => { if (!t) return 'never'; const d = Date.now() - t; if (d < 3600e3) return Math.max(1, Math.round(d / 60e3)) + ' min ago'; if (d < 86400e3) return Math.round(d / 3600e3) + 'h ago'; return Math.round(d / 86400e3) + 'd ago'; }; + const chip = (label, val, cls) => '' + esc(label) + '' + esc(val) + ''; + const working = (a.viewsToday || 0) > 0 || (a.campaignsActive || 0) > 0 || (a.linkViews30 || 0) > 0 || (a.lastSeen && Date.now() - a.lastSeen < 2 * 86400e3); + box.innerHTML = chip('Last seen', ago(a.lastSeen), a.lastSeen && Date.now() - a.lastSeen < 2 * 86400e3 ? 'on' : (a.quietDays >= 3 ? 'warn' : '')) + + chip('Joined', new Date(a.joined).toLocaleDateString()) + + chip('Stage', (a.rung || 'Joined') + (a.next ? ' · next: ' + a.next : ''), a.stalled ? 'warn' : '') + + chip('Ads today', (a.viewsToday || 0) + '/' + (a.target || 5) + (a.claimedToday ? ' claimed' : '') + (a.streakDay ? ' · streak day ' + a.streakDay : ''), (a.viewsToday || 0) > 0 ? 'on' : '') + + chip('Campaigns', (a.campaignsActive || 0) + ' active of ' + (a.campaigns || 0) + (a.imps ? ' · ' + a.imps.toLocaleString() + ' views' : ''), (a.campaignsActive || 0) > 0 ? 'on' : '') + + chip('Link', (a.linkViews30 || 0) + ' views (30d) · ' + (a.joins || 0) + ' joined', (a.linkViews30 || 0) > 0 ? 'on' : '') + + chip('Line', (a.directs || 0) + ' direct' + (a.directs === 1 ? '' : 's') + ' · ' + (a.buyerCount || 0) + ' qualifying', (a.buyerCount || 0) > 0 ? 'on' : '') + + chip('Wallet', a.wallet ? (a.badges && a.badges.includes('payouts') ? 'linked · payouts on' : 'linked') : 'not linked', a.wallet ? '' : 'warn') + + (a.badges && a.badges.length ? chip('Badges', a.badges.map(b => ({ payouts: 'Spark', firstBuyer: 'Surge', level2: 'Circuit', level3: 'Nexus' }[b] || b)).join(' · ')) : '') + + '' + (working ? 'Working' : 'Quiet') + ''; + } + async function loadUplineMessages() { + try { + const r = await (await fetch('/api/my/messages')).json(); + if (r.error) return; + const card = $('upMsgCard'), list = $('upList'); + if (!r.items || !r.items.length) { card.hidden = true; return; } + card.hidden = false; + list.innerHTML = r.items.map(i => '
' + + '
' + esc(i.subject) + '' + + '' + esc(i.fromName) + ' · ' + new Date(i.sent).toLocaleDateString() + '
' + + '
' + (i.body || '') + '
').join(''); + // opening the pane marks them read + for (const i of r.items) if (!i.read) fetch('/api/my/messages/' + i.id + '/read', { method: 'POST' }).catch(() => {}); + } catch (e) {} + } + // broadcast composer editor (its own small rich editor, server sanitizes) + document.querySelectorAll('[data-bc]').forEach(b => + b.addEventListener('click', () => { $('bcEd').focus(); document.execCommand(b.dataset.bc, false, null); })); + document.querySelectorAll('[data-bcblock]').forEach(b => + b.addEventListener('click', () => { $('bcEd').focus(); document.execCommand('formatBlock', false, b.dataset.bcblock); })); + if ($('bcLinkBtn')) $('bcLinkBtn').addEventListener('click', async () => { + const sel = window.getSelection(); const range = sel && sel.rangeCount ? sel.getRangeAt(0).cloneRange() : null; + const u = await IAP.ask({ title: 'Insert link', text: 'Link URL (https://…)', placeholder: 'https://', ok: 'Insert' }); + if (u) { $('bcEd').focus(); if (range) { sel.removeAllRanges(); sel.addRange(range); } document.execCommand('createLink', false, u); } + }); + if ($('bcSendBtn')) $('bcSendBtn').addEventListener('click', busy2($('bcSendBtn'), async () => { + const r = await api('/api/my/broadcast', { scope: $('bcScope').value, subject: $('bcSubject').value, body: $('bcEd').innerHTML }); + IAP.status('Broadcast sent to ' + r.sent + ' member' + (r.sent === 1 ? '' : 's') + '.', 'ok'); + $('bcSubject').value = ''; $('bcEd').innerHTML = ''; + $('bcHint').textContent = 'Sent. You can send your next broadcast in 24 hours.'; + })); + + // ── solo-ads inbox: list, read view, dwell-gated read reward ── + let ibTimer = null; + function setInboxBadge(n) { + for (const id of ['inboxBadge', 'inboxBadge2']) { + const b = $(id); + if (b) { b.hidden = !n; b.textContent = n; } + } + } + // Earn credits sub-tabs: Watch ads | Inbox + let earnSub = 'watch'; + function setEarnSub(which) { + earnSub = ['inbox', 'videos', 'visits'].includes(which) ? which : 'watch'; + if (earnSub !== 'videos' && vidState.token) stopVideo(); + const w = $('earn-watch'), i = $('earn-inbox'), v = $('earn-videos'), vs = $('earn-visits'); + if (w) w.hidden = earnSub !== 'watch'; + if (i) i.hidden = earnSub !== 'inbox'; + if (v) v.hidden = earnSub !== 'videos'; + if (vs) vs.hidden = earnSub !== 'visits'; + document.querySelectorAll('.subtabs [data-earn]').forEach(b => + b.classList.toggle('on', b.dataset.earn === earnSub)); + if (earnSub === 'inbox') loadInbox(); + else if (earnSub === 'videos') loadVideoStatus(); + else if (earnSub === 'visits') loadVisitStatus(); + else earnRefresh(); + } + document.querySelectorAll('.subtabs [data-earn]').forEach(b => + b.addEventListener('click', () => setEarnSub(b.dataset.earn))); + // promo toolkit: badge tiers + the AI Copy Engine (Marty, 2026-09-14) + let tkState = null; + async function loadToolkit() { + try { + const r = await (await fetch('/api/my/toolkit')).json(); if (r.error) return; tkState = r; + const esc = t => String(t == null ? '' : t).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c])); + const names = { free: 'Free', spark: 'Spark', surge: 'Surge', circuit: 'Circuit', nexus: 'Nexus' }; + $('tkTierLine').textContent = 'you are at ' + names[r.tier]; + $('tkTiers').innerHTML = r.tiers.map(t => '
' + esc(t.name) + (t.reached ? ' ✓' : '') + '
' + (t.reached ? esc(t.blurb) : 'Unlocks when you ' + esc(t.needText)) + '
    ' + t.items.map(i => '' + esc(i.t) + '').join('') + '
' + (t.reached ? '' : '
locked
') + '
').join(''); + $('tkLocked').hidden = r.unlocked; $('tkForm').hidden = !r.unlocked; + if (!r.unlocked) { $('tkLocked').textContent = 'Unlocks at Surge: your first qualifying buyer of a $20 or larger package. Then it writes posts, DMs, follow-ups, objection replies, emails and story posts in your name, with your link, inside the honesty rules. ' + (r.tier === 'free' ? 'Step one is switching on payouts.' : 'You are one buyer away.'); $('tkUsage').textContent = 'locked'; renderTkTools(r); return; } + $('tkUsage').textContent = r.freeLeft + ' free this month · then ' + r.cost + ' credits each · you have ' + r.available.toLocaleString() + ' credits'; + $('tkCostLine').textContent = r.freeLeft > 0 ? 'This one is free (' + r.freeLeft + ' left this month).' : 'This one costs ' + r.cost + ' credits from your earned pool.'; + if (!$('tkKind').options.length) { $('tkKind').innerHTML = r.kinds.map(k => '').join(''); $('tkAngle').innerHTML = r.angles.map(a => '').join(''); } + renderTkTools(r); + $('tkHistory').innerHTML = r.history.length ? '

Recent

' + r.history.map(h => '
' + esc(h.kind) + ' · ' + new Date(h.ts).toLocaleString() + (h.charged ? ' · ' + h.charged + ' credits' : ' · free') + '
' + esc(h.text).replace(/\n/g, '
') + '
').join('') : ''; + } catch (e) { console.error('toolkit', e); } + } + // the rest of the ladder: Spark templates + handout, Circuit Video Maker + split tester, Nexus Leader Ops + const tkEsc = t => String(t == null ? '' : t).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c])); + const tkRank = { free: 0, spark: 1, surge: 2, circuit: 3, nexus: 4 }; + async function tkPost(url, body) { const r = await (await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body || {}) })).json(); if (r.error) { IAP.status(r.error, 'bad'); return null; } return r; } + function renderTkTools(r) { + const at = tkRank[r.tier] || 0; + // Spark + const spark = at >= 1; $('tkSparkLocked').hidden = spark; $('tkSparkBody').hidden = !spark; + if (!spark) $('tkSparkLocked').textContent = 'Unlocks at Spark: switch on payouts in the Wallet tab. Then one tap builds a banner or text campaign aimed at your link, and you get a printable handout with your QR.'; + else { $('tkHandoutLine').hidden = !r.handoutUrl; if (r.handoutUrl) $('tkHandout').href = r.handoutUrl; } + // Circuit + const circ = at >= 3; $('tkCircuitLocked').hidden = circ; $('tkCircuitBody').hidden = !circ; + if (!circ) $('tkCircuitLocked').textContent = 'Unlocks at Circuit: two qualifying buyers in your line. Then every promo video gets your own end card and QR, and the split tester shows which join angle pulls for you.'; + else { loadTkVideos(r); loadTkSplit(); } + // Nexus + const nex = at >= 4; $('tkNexusLocked').hidden = nex; $('tkNexusBody').hidden = !nex; + if (!nex) $('tkNexusLocked').textContent = 'Unlocks at Nexus: five qualifying buyers. Then you get team triage across three levels with one-click nudges, AI-drafted team broadcasts, credit grants to your people, a co-branded join page and your own partner code.'; + else { loadTkTeam(); renderTkPartner(r); } + } + let tkVidTimer = null; + async function loadTkVideos(r) { + const box = $('tkVideos'); + if (!r.videoMaker) { box.innerHTML = '

The Video Maker is warming up on the server. Check back shortly.

'; return; } + if (!r.username) { box.innerHTML = '

Pick a username first (Profile); it goes on the end card.

'; return; } + try { + const v = await (await fetch('/api/my/toolkit/videos')).json(); if (v.error) return; + box.innerHTML = v.list.map(x => '
' + tkEsc(x.title) + '' + (x.status === 'done' ? 'Download ' : x.status === 'queued' || x.status === 'working' ? '
' + tkEsc(x.stage || 'Starting') + (x.status === 'working' ? ' · ' + (x.pct || 0) + '%' : '') + '' : '') + '
').join(''); + clearTimeout(tkVidTimer); if (v.list.some(x => x.status === 'queued' || x.status === 'working')) tkVidTimer = setTimeout(() => loadTkVideos(r), 2500); + } catch (e) {} + } + async function loadTkSplit() { + try { + const sp = await (await fetch('/api/my/toolkit/split')).json(); if (sp.error) return; + const rows = sp.rows.filter(x => x.views || x.joins); + $('tkSplit').innerHTML = !rows.length ? '

No link views yet. Share two different angle links this week and the winner shows up here.

' + : '
' + rows.map(x => '').join('') + '
AngleViewsLast 30dJoinsBuyersJoin rate
' + tkEsc(x.angle) + (x.angle === sp.best ? ' (winner so far)' : '') + '
' + tkEsc(x.link) + '
' + x.views + '' + x.views30 + '' + x.joins + '' + x.buyers + '' + x.rate + '%

Rate = joins per 100 views. A winner needs at least 10 views. Send more traffic to the winner, keep testing the rest.

'; + } catch (e) {} + } + let tkTeamData = null; + async function loadTkTeam() { + try { + const t = await (await fetch('/api/my/toolkit/team')).json(); if (t.error || !t.unlocked) return; tkTeamData = t; + $('tkTeamSub').textContent = t.total + ' in three levels (' + t.byLevel.join(' / ') + ') · ' + t.recent + ' new this week · ' + t.stalled.length + ' stalled'; + const list = t.stalled.length ? t.stalled : t.members.slice(0, 12); + $('tkTeam').innerHTML = (t.stalled.length ? '

Stalled first: quiet for a while and not yet past the next rung. One click sends them the right message from you.

' : '

Nobody stalled right now. Your newest people:

') + + list.map(m => '
' + tkEsc(m.name) + ' L' + m.level + ' · ' + tkEsc(m.label) + (m.quietDays ? ' · quiet ' + m.quietDays + 'd' : '') + '
Next: ' + tkEsc(m.next) + '
').join(''); + $('tkGrantTo').innerHTML = t.members.map(m => '').join(''); + } catch (e) {} + } + function renderTkPartner(r) { + const pk = r.partner; + $('tkPartner').innerHTML = pk + ? '

Code ' + tkEsc(pk.code) + ' gives ' + pk.credits + ' welcome credits, funded from your earned pool at each redemption. Redeemed ' + pk.uses + ' times.

Invite link with the code: ' + tkEsc(pk.link) + '

Your partner kit page (for list owners and site owners you talk to): ' + tkEsc(pk.kit) + '

' + : '

Give your recruits a welcome bonus under your own code. Each redemption moves the credits from your earned pool to theirs, so it only costs you when it works. Then hand partners the kit page, which sends their deals under you.

'; + } + document.addEventListener('click', async ev => { + const b = ev.target.closest('[data-tpl],[data-mkvid],[data-copyvid],[data-nudge],[data-copy],#tkPcGo,#tkGrantGo,#tkDraftBc,[data-sendnudge]'); if (!b) return; + if (b.dataset.tpl) { b.disabled = true; const r = await tkPost('/api/my/toolkit/template', { kind: b.dataset.tpl, budget: Number($('tkTplBudget').value) }); b.disabled = false; if (r) { IAP.status('Campaign "' + r.name + '" created with ' + r.budget + ' credits. It is under Campaigns.', 'ok'); loadDashboard(); } return; } + if (b.dataset.mkvid) { b.disabled = true; const r = await tkPost('/api/my/toolkit/video', { slug: b.dataset.mkvid }); if (r) { IAP.status(r.status === 'done' ? 'Already made.' : 'Rendering. It appears here in about a minute.', 'ok'); loadTkVideos(tkState); } else b.disabled = false; return; } + if (b.dataset.copyvid || b.dataset.copy) { try { await navigator.clipboard.writeText(b.dataset.copyvid || b.dataset.copy); IAP.status('Copied.', 'ok'); } catch (e) { IAP.status('Copy failed; select it by hand.', 'bad'); } return; } + if (b.dataset.nudge) { const row = b.closest('.tk-team'); const old = row.querySelector('.tk-nudge'); if (old) { old.remove(); return; } const box = document.createElement('div'); box.className = 'tk-nudge'; box.innerHTML = '
Lands in their inbox and their email.
'; box.querySelector('textarea').value = b.dataset.say; row.appendChild(box); return; } + if (b.dataset.sendnudge) { const box = b.closest('.tk-nudge'); b.disabled = true; const r = await tkPost('/api/my/toolkit/nudge', { email: b.dataset.sendnudge, text: box.querySelector('textarea').value }); b.disabled = false; if (r) { IAP.status('Sent.', 'ok'); box.remove(); } return; } + if (b.id === 'tkGrantGo') { b.disabled = true; const r = await tkPost('/api/my/toolkit/grant', { email: $('tkGrantTo').value, credits: Number($('tkGrantN').value) }); b.disabled = false; if (r) { IAP.status(r.credits + ' credits moved to ' + r.toName + '.', 'ok'); loadToolkit(); loadDashboard(); } return; } + if (b.id === 'tkPcGo') { b.disabled = true; const r = await tkPost('/api/my/toolkit/promo', { code: b.dataset.code || ($('tkPcCode') ? $('tkPcCode').value : ''), credits: Number($('tkPcN').value) }); b.disabled = false; if (r) { IAP.status('Code ' + r.code + ' is live: ' + r.credits + ' welcome credits.', 'ok'); loadToolkit(); } return; } + if (b.id === 'tkDraftBc') { if (!tkState || !tkState.unlocked) return; $('tkKind').value = 'broadcast'; $('tkBrief').placeholder = 'What should the team focus on this week?'; $('tkEngine').scrollIntoView({ behavior: 'smooth', block: 'start' }); $('tkBrief').focus(); IAP.status('Pick a focus, hit Write it, then Send to my team.', 'ok'); return; } + }); + $('tkKind') && $('tkKind').addEventListener('change', () => { if ($('tkSendBc')) $('tkSendBc').hidden = $('tkKind').value !== 'broadcast'; }); + async function tkSendBroadcast() { + const txt = $('tkText').value || ''; const m = /^\s*Subject:\s*(.+)\n+([\s\S]+)$/.exec(txt); + const subject = m ? m[1].trim() : 'A note from your sponsor', body = (m ? m[2] : txt).trim(); + if (!(await IAP.confirmBox('Send this to everyone in your three levels? One broadcast a day.', { title: 'Team broadcast', ok: 'Send' }))) return; + const r = await tkPost('/api/my/broadcast', { subject, body: '

' + tkEsc(body).replace(/\n{2,}/g, '

').replace(/\n/g, '
') + '

', scope: 'all' }); + if (r) IAP.status('Sent to ' + (r.sent || r.count || r.recipients || 'your team') + '.', 'ok'); + } + async function tkGenerate() { + const btn = $('tkGo'); if (btn.disabled) return; btn.disabled = true; btn.textContent = 'Writing…'; + try { + const r = await (await fetch('/api/my/toolkit/generate', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ kind: $('tkKind').value, angle: $('tkAngle').value, brief: $('tkBrief').value }) })).json(); + if (r.error) { IAP.status(r.error, 'bad'); return; } + $('tkText').value = r.text; $('tkOut').hidden = false; $('tkSendBc').hidden = $('tkKind').value !== 'broadcast'; + IAP.status(r.charged ? r.charged + ' credits used.' : 'Written. ' + r.freeLeft + ' free left this month.', 'ok'); + loadToolkit(); loadDashboard(); + } catch (e) { IAP.status('The engine did not answer. Try again.', 'bad'); } + finally { btn.disabled = false; btn.textContent = 'Write it'; } + } + if ($('tkGo')) { $('tkGo').addEventListener('click', tkGenerate); $('tkAgain').addEventListener('click', tkGenerate); $('tkCopy').addEventListener('click', async () => { try { await navigator.clipboard.writeText($('tkText').value); IAP.status('Copied.', 'ok'); } catch (e) { $('tkText').select(); } }); $('tkSendBc').addEventListener('click', tkSendBroadcast); } + // promo tools: pill menu switches between posts / swipes / banners / wall / videos + function setPromoSub(name) { + const ids = ['toolkit', 'posts', 'text', 'swipe', 'banners', 'wall', 'objections', 'videos']; + if (name === 'toolkit') loadToolkit(); + if (!ids.includes(name)) name = 'posts'; + ids.forEach(id => { const el = $('promo-' + id); if (el) el.hidden = id !== name; }); + document.querySelectorAll('.promo-pills [data-promo]').forEach(b => { + b.classList.toggle('on', b.dataset.promo === name); + b.setAttribute('aria-selected', b.dataset.promo === name ? 'true' : 'false'); + }); + try { localStorage.setItem('iap.promoSub', name); } catch (e) {} + } + document.querySelectorAll('.promo-pills [data-promo]').forEach(b => + b.addEventListener('click', () => setPromoSub(b.dataset.promo))); + try { setPromoSub(localStorage.getItem('iap.promoSub') || 'posts'); } catch (e) { setPromoSub('posts'); } + async function loadInbox() { + try { + const r = await (await fetch('/api/my/inbox')).json(); + if (r.error) return; + $('ibRewardNote').textContent = '+' + r.readCredits + ' credits per real read (up to ' + + r.readCap + ' rewarded reads a day)'; + const el = $('ibList'); + $('inboxReadCard').hidden = true; + $('inboxListCard').hidden = false; + setInboxBadge(r.unread); + if (!r.items.length) { + el.innerHTML = '

No solo ads yet. When a member sends one, it lands here — and reading it pays.

'; + return; + } + el.innerHTML = ''; + for (const i of r.items) { + const d = document.createElement('div'); + d.className = 'ib-row' + (i.read ? '' : ' unread'); + d.innerHTML = '' + + (i.rewarded ? 'claimed' : i.read ? '' : 'new') + + '' + new Date(i.delivered).toLocaleDateString() + ''; + d.querySelector('.sub').textContent = i.subject || '(no subject)'; + d.querySelector('.from').textContent = 'from ' + (i.fromName || 'a member'); + d.addEventListener('click', () => openInboxItem(i.id)); + el.appendChild(d); + } + } catch (e) {} + } + async function openInboxItem(id) { + try { + const r = await (await fetch('/api/my/inbox/' + id)).json(); + if (r.error) { IAP.status(r.error, 'bad'); return; } + $('inboxListCard').hidden = true; + $('inboxReadCard').hidden = false; + $('ibSubject').textContent = r.subject || '(no subject)'; + $('ibMeta').textContent = 'from ' + (r.fromName || 'a member') + ' · ' + new Date(r.delivered).toLocaleString(); + $('ibBody').innerHTML = r.body || ''; // whitelist-sanitized on the server at submit + const mv = $('ibMedia'); + mv.hidden = !r.mediaUrl; + mv.innerHTML = !r.mediaUrl ? '' + : r.mediaType === 'video' + ? '' + : 'attachment'; + // the read reward needs BOTH the dwell AND an actual click-through to the + // advertiser — the visit is what makes the ad worth the sender's credits + const visit = $('ibVisit'); + visit.href = r.url; + visit.textContent = r.ctaLabel || 'Learn more'; + visit.target = '_blank'; + const btn = $('ibClaimBtn'); + clearInterval(ibTimer); + if (r.rewarded) { + btn.hidden = true; + visit.classList.remove('cta-need'); + $('ibHint').textContent = 'Read reward already claimed for this one.'; + return; + } + let dwellDone = false; + let visited = !!r.visited; + btn.hidden = false; + btn.disabled = true; + visit.classList.toggle('cta-need', !visited); + let left = r.dwell; + const refresh = () => { + if (!dwellDone) { btn.textContent = 'Read it — claim in ' + left + 's'; return; } + if (!visited) { btn.textContent = 'Claim +' + r.reward + ' — visit the ad first'; btn.disabled = true; return; } + btn.textContent = 'Claim +' + r.reward + ' credits'; btn.disabled = false; + }; + $('ibHint').textContent = 'Read the message, click through to the advertiser, then claim your credits.'; + refresh(); + // countdown pauses off-tab; the server separately enforces the dwell on its own clock + ibTimer = setInterval(() => { + if (document.visibilityState !== 'visible' || !document.hasFocus()) return; + left -= 1; + if (left > 0) { refresh(); return; } + clearInterval(ibTimer); + dwellDone = true; + refresh(); + }, 1000); + // clicking the CTA records the visit (and counts the advertiser's click) + visit.onclick = async () => { + visited = true; + visit.classList.remove('cta-need'); + try { await fetch('/api/my/inbox/' + id + '/visit', { method: 'POST' }); } catch (e2) {} + refresh(); + }; + btn.onclick = async () => { + try { + const c = await api('/api/my/inbox/' + id + '/claim'); + IAP.status('+' + c.credited + ' credits for reading. They spend like any earned credits.', 'ok'); + btn.hidden = true; + $('ibHint').textContent = 'Claimed. Head back for the next one.'; + loadDashboard(); + } catch (e2) { IAP.status(e2.message, 'bad'); } + }; + } catch (e) {} + } + $('ibBack').addEventListener('click', ev => { ev.preventDefault(); clearInterval(ibTimer); loadInbox(); }); + + // ── promo tools: content + rendering live in promo.js (IAPPromo.fill) ── + function fillPromo(link, me) { + if (window.IAPPromo) IAPPromo.fill(link, me || {}); + // banner kit + const bwrap = $('promoBanners'); + if (bwrap && !bwrap.dataset.filled) { + bwrap.dataset.filled = '1'; + // one collapsed accordion per size / use, so the kit stays scannable as it grows + // LinkSpin kit (2026-10-08): neutral file names on purpose, ad blockers hide URLs with IAB size tokens + const GROUPS = [ + { title: '1200×630 · social posts, link previews, group covers', items: [ + { file: 'ls-social-a.jpg', size: '1200×630 · one link, every page you promote · Join free' }, + { file: 'ls-social-b.jpg', size: '1200×630 · paid the moment they buy · Join free' } ] }, + { title: '1080×1080 and 1080×1920 · Instagram, Facebook, stories, reels', items: [ + { file: 'ls-square.jpg', size: '1080×1080 · square' }, + { file: 'ls-story.jpg', size: '1080×1920 · story / reel' } ] }, + { title: '1280×720 · Telegram and group posts', items: [ + { file: 'ls-group.jpg', size: '1280×720 · group post' } ] }, + { title: 'Leaderboards · 728×90, 468×60, 320×50', items: [ + { file: 'ls-leader.png', size: '728×90 · leaderboard' }, + { file: 'ls-strip.png', size: '468×60 · banner' }, + { file: 'ls-bar.png', size: '320×50 · mobile leaderboard' } ] }, + { title: 'Rectangles and buttons · 336×280, 300×250, 250×250, 125×125', items: [ + { file: 'ls-panel.png', size: '336×280 · large rectangle' }, + { file: 'ls-box.png', size: '300×250 · medium rectangle' }, + { file: 'ls-square-s.png', size: '250×250 · square' }, + { file: 'ls-tile.png', size: '125×125 · button' } ] }, + { title: 'Skyscrapers · 160×600, 120×600', items: [ + { file: 'ls-tower.png', size: '160×600 · wide skyscraper' }, + { file: 'ls-column.png', size: '120×600 · skyscraper' } ] } + ]; + bwrap.innerHTML = ''; + for (const g of GROUPS) { + const det = document.createElement('details'); + det.className = 'pb-acc'; + det.innerHTML = '' + esc(g.title) + '' + g.items.length + (g.items.length === 1 ? ' banner' : ' banners') + '
'; + const grid = det.querySelector('.pb-grid'); + for (const b of g.items) { + const url = location.origin + '/kit/' + b.file; + const d = document.createElement('div'); + d.className = 'pb-item'; + d.innerHTML = 'LinkSpin banner ' + b.size + '' + + '
' + b.size + '
'; + const dl = document.createElement('a'); + dl.className = 'btn small'; dl.textContent = 'Download'; dl.href = '/kit/' + b.file; dl.setAttribute('download', b.file); + d.querySelector('.pb-row').appendChild(dl); + const btn = document.createElement('button'); + btn.className = 'btn small sec'; + btn.textContent = 'Copy image URL'; + btn.addEventListener('click', async () => { + try { await navigator.clipboard.writeText(url); IAP.status('Banner URL copied.', 'ok'); } + catch (e) { IAP.status('Copy failed.', 'bad'); } + }); + d.querySelector('.pb-row').appendChild(btn); + grid.appendChild(d); + } + bwrap.appendChild(det); + } + } + } + + // ── profile ── (busy2 defers the busy lookup past its TDZ) + $('pfSaveBtn').addEventListener('click', busy2($('pfSaveBtn'), async () => { + const r = await api('/api/my/profile', { username: $('pfUsername').value }); + IAP.status('You are @' + r.account.username + ' now.', 'ok'); + await render(); + })); + + // ── in-dashboard package buying ── + const PKG = { 1: 'Micro', 2: 'Activation', 3: 'Builder', 4: 'Growth', 5: 'Leader' }; + // Card on-ramp: buy POL with a card via MoonPay, delivered to the buyer's own + // wallet. Signed + wallet-prefilled once MoonPay keys are set; generic page + // otherwise. The site never touches funds — MoonPay is merchant of record. + async function openMoonpay(pol) { + try { + let addr = ''; + try { const me = await (await fetch('/api/me')).json(); addr = me.address || ''; } catch (e) {} + const q = '/api/moonpay-url?pol=' + encodeURIComponent(pol || '') + (addr ? '&address=' + encodeURIComponent(addr) : ''); + const r = await (await fetch(q)).json(); + if (r && r.url) { + window.open(r.url, '_blank', 'noopener'); + IAP.status(r.signed + ? 'MoonPay opened in a new tab with your wallet address pre-filled. Choose POL on Polygon, finish the purchase, then come back and buy your package.' + : 'MoonPay opened in a new tab. Choose POL on the Polygon network and paste your own wallet address as the destination, then come back.', 'ok'); + } + } catch (e) { IAP.status('Could not open MoonPay: ' + ((e && e.message) || e), 'bad'); } + } + // ── linked positions (Qualified Start) ── + const short = a => a ? a.slice(0, 6) + '…' + a.slice(-4) : ''; + let noPayoutAddrs = new Set(); // positions the site refuses to buy from (see siteConfig.noPayoutIds) + async function loadPositions(me) { + try { + const r = await (await fetch('/api/my/positions')).json(); + if (r.error) return; + const list = r.positions || []; + const rows = list.map((p, i) => '
Position ' + (i + 2) + ' ' + short(p.address) + '' + + '' + (p.memberId ? '#' + p.memberId : 'not on-chain yet') + '' + + '' + (p.noPayout ? 'linkage only: no purchases from this position (payouts would reach a retired wallet)' : p.counted ? 'counts as a qualifying buyer' : p.memberId ? 'registered, buy $20+ to count' : 'buy a $20+ package to register it') + '' + + '' + (p.credits || 0).toLocaleString() + ' credits' + (p.balanceWei != null ? ' · ' + (Number(BigInt(p.balanceWei) / 10n ** 14n) / 10000).toLocaleString(undefined, { maximumFractionDigits: 2 }) + ' POL' : '') + '' + + (!p.memberId ? '' : '') + + '
').join(''); + const mainRow = r.main && r.main.address ? '
Position 1 · main ' + short(r.main.address) + '' + + '' + (r.main.memberId ? '#' + r.main.memberId : 'payouts not on yet') + '' + + '' + (r.main.buyerCount || 0) + ' qualifying buyer(s)' + + '' + (r.main.credits || 0).toLocaleString() + ' credits' + (r.main.balanceWei != null ? ' · ' + (Number(BigInt(r.main.balanceWei) / 10n ** 14n) / 10000).toLocaleString(undefined, { maximumFractionDigits: 2 }) + ' POL' : '') + '
' : ''; + const html = mainRow + rows + (list.length ? '

Pooled credits: ' + (r.totalCredits || 0).toLocaleString() + '' + (r.credited ? ' plus ' + r.credited.toLocaleString() + ' credited to your account (spends from any position)' : '') + '. A campaign budget spends from one position at a time.

' : ''); + if ($('qsList')) $('qsList').innerHTML = html; + // Wallet tab: live POL balance of the linked wallet, and which package it covers + const wb = $('walletBal'); + if (wb && r.main && r.main.address && r.main.balanceWei != null) { + const polN = Number(BigInt(r.main.balanceWei) / 10n ** 14n) / 10000; + const usd = r.polUsd ? polN * r.polUsd : 0; + const pkgs = [5, 20, 50, 100, 250]; + const covers = r.polUsd ? pkgs.filter(p => usd >= p * 1.06 + 0.05) : []; + wb.hidden = false; + wb.innerHTML = 'Wallet balance: ' + polN.toLocaleString(undefined, { maximumFractionDigits: 2 }) + ' POL' + (usd ? ' (about $' + usd.toLocaleString(undefined, { maximumFractionDigits: 0 }) + ')' : '') + + (r.polUsd ? '
' + (covers.length ? 'Enough for the $' + covers[covers.length - 1] + ' package with gas to spare.' : 'Not enough for the $5 package yet. Buy POL with a card on the Buy packages tab, or send POL to this wallet.') + (covers.length && covers.length < pkgs.length ? ' Top up for the $' + pkgs[covers.length] + ' package.' : '') + '' : ''); + } + if ($('posList')) $('posList').innerHTML = html; + if ($('posCard')) $('posCard').hidden = !list.length; + // "Buy from" picker: main + every position + const sel = $('buyFrom'); + if (sel) { + const keep = sel.value; + sel.innerHTML = '' + + list.map((p, i) => '').join(''); + noPayoutAddrs = new Set(list.filter(p => p.noPayout).map(p => p.address.toLowerCase())); if (r.main && r.main.noPayout && r.main.address) noPayoutAddrs.add(r.main.address.toLowerCase()); + if (keep && [...sel.options].some(o => o.value === keep)) sel.value = keep; + $('buyFromWrap').hidden = !list.length; + } + document.querySelectorAll('[data-unlink]').forEach(b => b.addEventListener('click', async () => { + if (!(await IAP.confirmBox('Unlink ' + short(b.dataset.unlink) + ' from your account?', { title: 'Unlink position', ok: 'Unlink' }))) return; + try { await api('/api/my/positions/remove', { address: b.dataset.unlink }); IAP.status('Position unlinked.', 'ok'); loadPositions(); } + catch (e) { IAP.status(e.message, 'bad'); } + })); + } catch (e) {} + } + if ($('qsAddBtn')) $('qsAddBtn').addEventListener('click', busy2($('qsAddBtn'), async () => { + const me = await (await fetch('/api/me')).json(); + if (!me.address) throw new Error('Link your main wallet first (Wallet tab), then add positions under it.'); + if (!me.memberId) throw new Error('Switch on payouts for your main wallet first (Wallet tab). Positions register under your member number.'); + if (!(await IAP.confirmBox('Your wallet will ask which account to connect. Tick ONLY the new account (not ' + short(me.address) + '), then sign once.\n\nIf you have not created the extra account yet: MetaMask, account menu, Add account. Trust or SafePal: switch wallet.\n\nReady?', { title: 'Add a position', ok: 'Ready' }))) return; + IAP.status('Pick the new account in your wallet, then sign once…'); + const r = await IAPWallet.signIn({ asPosition: true, pick: true }); + $('qsHint').textContent = 'Added ' + short(r.address) + '. Now choose it under "Buy from" and buy a $20 or larger package.'; + IAP.status('Position added: ' + short(r.address) + '. Pick it under "Buy from" above and buy a $20+ package to count it.', 'ok'); + await loadPositions(); + const sel = $('buyFrom'); if (sel) sel.value = r.address.toLowerCase(); + try { $('buyFrom').scrollIntoView({ behavior: 'smooth', block: 'center' }); } catch (e) {} + })); + async function loadBuyTiles() { + try { + const { products } = await (await fetch('/api/catalog')).json(); + const wrap = $('boTiles'); + wrap.innerHTML = ''; + for (const p of products) { + const bonus = p.creditAmount - p.priceCents; + const div = document.createElement('div'); + div.className = 'tile' + (p.priceCents === 5000 ? ' hot' : ''); + div.innerHTML = '
' + (PKG[p.id] || 'Package ' + p.id) + '
' + + '
$' + Math.round(p.priceCents / 100) + '
' + + '
' + p.creditAmount.toLocaleString() + ' credits
' + + '
' + (bonus > 0 ? '+' + bonus.toLocaleString() + ' bonus credits' : ' ') + '
' + + '
' + (p.costWei ? IAP.fmtPol(p.costWei) + ' POL right now' : 'paused') + '
' + + ''; + wrap.appendChild(div); + } + wrap.querySelectorAll('button[data-id]').forEach(b => b.addEventListener('click', async () => { + try { + b.disabled = true; + // the buyer's credits are read by the member id of their LINKED wallet. + // If they only connected a wallet (e.g. for the faucet) but never linked + // it, link it first (one signature) so the purchase's credits show up. + // retry these through transient failures — mobile drops in-flight + // fetches when the page returns from the wallet app-switch + const jretry = async url => { let err; for (let i = 0; i < 4; i++) { try { return await (await fetch(url)).json(); } catch (e) { err = e; await new Promise(s => setTimeout(s, 500 * (i + 1))); } } throw err; }; + const meNow = await jretry('/api/me'); + // which of the member's wallets is buying: the main wallet (default) or a + // linked position (Qualified Start). A position registers under the main + // member id on its first buy, so its sponsor is always this member. + const fromSel = $('buyFrom'); + const fromPos = (fromSel && !$('buyFromWrap').hidden && fromSel.value && fromSel.value !== 'main') ? fromSel.value.toLowerCase() : null; + if (fromPos && !meNow.memberId) { IAP.status('Switch on payouts for your main wallet first (Wallet tab), so this position can register under you.', 'bad'); return; } + if (noPayoutAddrs.has(fromPos || String(meNow.address || '').toLowerCase())) { IAP.status('This position is kept for linkage only. A purchase from it would pay a retired wallet. Buy from your main wallet or another position.', 'bad'); return; } + if (!fromPos && !meNow.address) { + IAP.status('Link your wallet first — one quick signature…'); + await IAPWallet.signIn(); + } + const wantAddr = fromPos || (meNow.address ? meNow.address.toLowerCase() : null); + if (wantAddr) { // never buy from a wallet other than the one selected: a stray wallet would register a brand-new member + await IAPWallet.connect(); + let cur = String(await IAPWallet.activeAddress() || '').toLowerCase(); + if (cur !== wantAddr) { + IAP.status('Pick ' + wantAddr.slice(0, 6) + '…' + wantAddr.slice(-4) + ' in your wallet\'s account picker…'); + cur = String(await IAPWallet.pickAccount() || '').toLowerCase(); + } + if (cur !== wantAddr) throw new Error('Your wallet connected as ' + cur.slice(0, 6) + '…' + cur.slice(-4) + ' but you chose ' + wantAddr.slice(0, 6) + '…' + wantAddr.slice(-4) + '. Switch accounts in your wallet app and try again.'); + } + const spNow = fromPos ? { sponsorId: meNow.memberId } : await jretry('/api/sponsor?intent=buy'); + if (!fromPos && !meNow.memberId && spNow.sponsorBlocked) { IAP.status(sponsorHoldText(spNow), 'bad'); return; } // first activation must not hand a sponsored member to the company + // pre-flight: stop early if the POL is not there. Trust Wallet also hard-blocks any + // transaction that spends most of the balance ("drain your wallet"), so Trust users + // get a heads-up first; other wallets go straight to the confirmation. + try { + const need = BigInt(b.dataset.cost) + BigInt(b.dataset.cost) / 50n; // same 2% pad as buy() + const bal = await IAPWallet.balance(wantAddr || IAPWallet.address() || meNow.address); + if (bal < need) { + IAP.status('That wallet holds ' + IAP.fmtPol(bal.toString()) + ' POL, but this package needs about ' + IAP.fmtPol(need.toString()) + ' POL plus a little for gas. Top it up and try again.', 'bad'); + return; + } + const pct = Number(need * 100n / bal); + const isTrust = /trust/i.test(IAPWallet.walletName() || ''); + if (isTrust && pct > 55 && !(await IAP.confirmBox('Heads up for Trust Wallet users: this purchase uses about ' + pct + '% of the POL in your wallet, and Trust Wallet refuses transactions that spend most of the balance (it shows a "drain your wallet" warning with only Stop and go back).' + '\n\n' + 'Options: pick a smaller package first, add some POL, or connect a different wallet (MetaMask, Phantom, SafePal). Extra POL always stays yours.' + '\n\n' + 'Try it anyway?', { title: 'Trust Wallet check', ok: 'Buy anyway', cancel: 'Pause' }))) { + IAP.status('Purchase paused. Pick a smaller package, add POL, or connect another wallet, then try again.', 'ok'); + return; + } + } catch (e) { /* balance read failed: let the wallet decide */ } + IAP.status('Confirm the purchase in your wallet…'); + const r = await IAPWallet.buy(Number(b.dataset.id), spNow.sponsorId || 0, b.dataset.cost); + if (r.status !== '0x1' && r.receipt && r.receipt.status !== '0x1') throw new Error('Transaction reverted.'); + IAP.status(fromPos ? 'Purchase settled on-chain. That position now counts toward your qualification, and its credits pool with yours.' : 'Purchase settled on-chain. Credits are in your account.', 'ok'); + await render(); + loadBuyTiles(); + } catch (e) { IAP.status('Purchase failed: ' + ((e && e.message) || e), 'bad'); } + finally { b.disabled = false; } + })); + // brand new to crypto? buy POL with a card, sent straight to the wallet + const builder = products.find(p => p.priceCents === 5000) || products[products.length - 1]; + const needPol = (builder && builder.costWei) ? Math.max(30, Math.ceil(Number(builder.costWei) / 1e18) + 3) : 30; + const cta = document.createElement('div'); + cta.style.cssText = 'grid-column:1/-1;margin-top:10px;text-align:center'; + cta.innerHTML = '

New to crypto? Buy POL with a debit or credit card, Apple Pay, or Google Pay. It lands straight in your own wallet, and this site never touches your money.

' + + ' Wallet and MoonPay guide'; + wrap.appendChild(cta); + const mb = $('moonpayBtn'); if (mb) mb.addEventListener('click', () => openMoonpay(needPol)); + } catch (e) {} + } + loadBuyTiles(); + + // ── earn-by-viewing: daily ad set with dwell, then claim ── + const earnState = { types: ['banner', 'text'], i: 0, timer: null }; + async function earnRefresh() { + try { + const st = await (await fetch('/api/my/earn')).json(); + if (st.error) return null; + $('earnProgress').textContent = 'today: ' + st.views + ' / ' + st.target + ' ads viewed'; + $('earnBalance').textContent = (st.earnedAvailable != null ? st.earnedAvailable : st.earned) + ' earned credits available' + (st.reserved ? ' · ' + st.reserved + ' in live campaigns' : ''); + const done = st.views >= st.target; + $('earnClaimBtn').hidden = !(done && !st.claimed); + if (st.claimed) { + $('earnHint').textContent = 'Claimed for today' + (st.streakDay > 1 ? ' (streak day ' + st.streakDay + ')' : '') + '. Tomorrow\'s claim pays ' + st.nextClaim + ' credits if you come back.'; + // after the set (Marty, 2026-09-12): keep going with verified visits, and turn the credits into a campaign + const box = $('earnAdBox'); + if (box) box.innerHTML = '
✓Ads done for todayToday\'s set is viewed and claimed. Fresh ads tomorrow.' + + '
' + + (st.visitsLeft ? '' : '') + + ((st.earnedAvailable != null ? st.earnedAvailable : st.earned) > 0 + ? '' + : '') + '
'; + if (box) box.querySelectorAll('[data-earnnext]').forEach(b => b.addEventListener('click', () => { if (b.dataset.earnnext === 'campaigns') setPane('campaigns'); else setEarnSub('visits'); })); + if ($('earnStartBtn')) $('earnStartBtn').hidden = true; + } else { + if ($('earnStartBtn')) $('earnStartBtn').hidden = done; // set done: the claim button takes over + $('earnHint').textContent = done + ? 'Set complete. Claim your ' + st.claimCredits + ' credits' + (st.streakDay > 1 ? ' (streak day ' + st.streakDay + ')' : '') + '.' + : (st.views ? (st.target - st.views) + ' more to go, then claim ' + st.claimCredits + ' credits' + (st.streakDay > 1 ? ' (streak day ' + st.streakDay + ')' : '') + '.' : 'View ' + st.target + ' ads to unlock the daily claim of ' + st.claimCredits + ' credits' + (st.streakDay > 1 ? ' (streak day ' + st.streakDay + ')' : '') + '.'); + } + return st; + } catch (e) { return null; } + } + async function earnShowAd() { + // each view happens full screen in its own tab: /view/ frames the + // advertiser's site, runs the countdown, then a human check credits it + const type = earnState.types[earnState.i++ % earnState.types.length]; + let r = null; + try { r = await (await fetch('/api/my/earnview?type=' + type)).json(); } catch (e) {} + const box = $('earnAdBox'); + if (!r || !r.ad || !r.viewUrl) { + await earnRefresh(); + box.innerHTML = '' + (r && r.status && r.status.views >= r.status.target + ? 'Set complete for today.' + : 'No member ads are live in rotation right now. Views resume the moment a campaign is running.') + ''; + return; + } + openAdOverlay(r.viewUrl); + box.innerHTML = 'Watch the countdown and pass the quick check. Your view credits itself and this page updates right away.'; + $('earnStartBtn').textContent = 'View next ad'; + } + // In-page ad overlay: no new tab (mobile and in-app wallet browsers handle tabs + // badly), no window.close needed. The /view page runs the dwell + check inside, + // messages back when it credits or when the user is done. + function openAdOverlay(url) { + closeAdOverlay(); + const back = document.createElement('div'); + back.id = 'adOverlay'; + back.style.cssText = 'position:fixed;inset:0;z-index:100000;background:#050b09;display:flex;flex-direction:column'; + const x = document.createElement('button'); + x.type = 'button'; x.setAttribute('aria-label', 'Close ad'); + x.textContent = '✕'; + x.style.cssText = 'position:absolute;top:10px;right:12px;z-index:2;width:40px;height:40px;border-radius:50%;border:1px solid rgba(255,255,255,.25);background:rgba(6,10,16,.85);color:#fff;font-size:20px;font-weight:700;cursor:pointer'; + x.addEventListener('click', closeAdOverlay); + const ifr = document.createElement('iframe'); + ifr.src = url; + ifr.style.cssText = 'flex:1;width:100%;border:0;background:#050b09'; + back.appendChild(ifr); back.appendChild(x); + document.body.appendChild(back); + document.body.style.overflow = 'hidden'; + } + function closeAdOverlay() { + const m = $('adOverlay'); if (m) m.remove(); + document.body.style.overflow = ''; + earnRefresh(); loadDashboard(); + } + window.addEventListener('message', e => { + if (e.origin !== location.origin || !e.data) return; + if (e.data.t === 'iap-view-close') closeAdOverlay(); + else if (e.data.t === 'iap-view-done') { earnRefresh(); loadDashboard(); } + }); + $('earnStartBtn').addEventListener('click', () => earnShowAd()); + // the viewer tab pings localStorage when a view credits; refresh instantly + window.addEventListener('storage', e => { + if (e.key === 'iap-view-done') { earnRefresh(); loadDashboard(); } + }); + document.addEventListener('visibilitychange', () => { + if (document.visibilityState === 'visible' && $('pane-earn') && !$('pane-earn').hidden) earnRefresh(); + }); + $('earnClaimBtn').addEventListener('click', async () => { + try { + const r = await api('/api/my/claim'); + IAP.status('+' + r.credited + ' credits earned' + (r.streakDay > 1 ? ', streak day ' + r.streakDay : '') + '. Tomorrow\'s claim pays ' + r.nextClaim + '. Spend them in Campaigns.', 'ok'); + await earnRefresh(); + loadDashboard(); + } catch (e) { IAP.status(e.message, 'bad'); } + }); + + const busy = (btn, fn) => async () => { + try { btn.disabled = true; await fn(); } + catch (e) { IAP.status((e && e.message) || String(e), 'bad'); } + finally { btn.disabled = false; } + }; + + // passwordless (feature-flagged on config.emailAuth): code replaces passwords + (async () => { + const cfg = await IAP.getConfig(); + if (!cfg.emailAuth) return; + $('passCards').hidden = true; + $('magicCard').hidden = false; + const codeOpts = () => ({ honeypot: $('mcWebsite'), host: $('mcCheck') }); + const start = busy($('mcSendBtn'), async () => { + const r = await IAP.requestCode($('mcEmail').value, codeOpts()); + $('mcCodeRow').hidden = false; + $('mcVerifyBtn').hidden = false; + $('mcSendBtn').hidden = true; + $('mcResend').hidden = false; + if (r.devCode) { $('mcCode').value = r.devCode; IAP.status('Dev mode: code filled in for you.', 'ok'); } + else IAP.status('Code sent. Check your inbox (and spam, the first time).', 'ok'); + $('mcCode').focus(); + }); + $('mcSendBtn').addEventListener('click', start); + $('mcResend').addEventListener('click', busy($('mcResend'), async () => { + const r = await IAP.requestCode($('mcEmail').value, codeOpts()); + if (r.devCode) $('mcCode').value = r.devCode; + IAP.status('Fresh code sent.', 'ok'); + })); + $('mcVerifyBtn').addEventListener('click', busy($('mcVerifyBtn'), async () => { + const r = await api('/api/auth/email/verify', { email: $('mcEmail').value, code: $('mcCode').value, newsletter: !!($('nlOptin') && $('nlOptin').checked) }); + IAP.status('You are in.', 'ok'); + if (r.created && !(r.account && r.account.username)) await showOnboard(); // pick a username first + if (!(await showGauntlet())) await showLoginAd(); // welcome tour outranks the login ad + await render(); + })); + })(); + + // new-member onboarding: choose a username (required), optionally a bio. + // required=true: no skip, no backdrop dismiss, prefilled suggestion, resolves only after a save. + function showOnboard(required) { + return new Promise(resolve => { + const m = $('onboardModal'); if (!m) return resolve(); + m.hidden = false; $('obErr').hidden = true; + $('obSkip').hidden = !!required; + if (required && !$('obUsername').value) { + fetch('/api/my/username-suggest').then(r => r.json()).then(r => { if (r.suggest && !$('obUsername').value) { $('obUsername').value = r.suggest; $('obUsername').select(); } }).catch(() => {}); + } + setTimeout(() => $('obUsername').focus(), 50); + const done = () => { m.hidden = true; resolve(); }; + $('obSkip').onclick = required ? null : done; + $('obUsername').onkeydown = e => { if (e.key === 'Enter') { e.preventDefault(); $('obSave').click(); } }; + $('obSave').onclick = async () => { + const u = $('obUsername').value.trim(); + if (required && !u) { $('obErr').hidden = false; $('obErr').textContent = 'Pick a username to continue.'; return; } + try { + if (u) await api('/api/my/profile', { username: u }); + const bio = $('obBio').value.trim(); + if (bio) await api('/api/my/profile-details', { bio }); + done(); + } catch (e) { $('obErr').hidden = false; $('obErr').textContent = e.message || 'Could not save that. Try a different username.'; } + }; + }); + } + + $('signupBtn').addEventListener('click', busy($('signupBtn'), async () => { + const r = await api('/api/signup', { email: $('suEmail').value, password: $('suPass').value, newsletter: !!($('nlOptin') && $('nlOptin').checked) }); + IAP.status('Welcome aboard. You are in.', 'ok'); + if (!(r.account && r.account.username)) await showOnboard(); + await render(); + })); + $('loginBtn').addEventListener('click', busy($('loginBtn'), async () => { + await api('/api/login', { email: $('liEmail').value, password: $('liPass').value }); + IAP.status('Logged in.', 'ok'); + if (!(await showGauntlet())) await showLoginAd(); // welcome tour outranks the login ad + await render(); + })); + $('linkBtn').addEventListener('click', busy($('linkBtn'), async () => { + IAP.status('Check your wallet for the free link signature…'); + await IAPWallet.signIn(); // server binds the wallet to the signed-in email account + IAP.status('Wallet linked. Earnings pay there from now on.', 'ok'); + await render(); + })); + if ($('faucetBtn')) $('faucetBtn').addEventListener('click', busy($('faucetBtn'), async () => { + IAP.status('Connect your wallet first…'); + const addr = await IAPWallet.connect(); + let copied = false; + try { await navigator.clipboard.writeText(addr); copied = true; } catch (e) {} + window.open('https://faucet.polygon.technology/', '_blank', 'noopener'); + $('faucetInfo').innerHTML = 'Your address ' + addr.slice(0, 8) + '…' + addr.slice(-6) + '' + + (copied ? ' is copied' : '') + '. On the faucet, choose Polygon Amoy, paste your address, and request POL. Then come back and buy.'; + IAP.status('Faucet opened in a new tab. Choose Polygon Amoy, paste your address, and request test POL.', 'ok'); + })); + if ($('wcDisconnect')) $('wcDisconnect').addEventListener('click', busy($('wcDisconnect'), async () => { + // fire-and-forget: don't gate the reload on disconnect resolving (it can + // stall). The reload drops all in-memory wallet state and the picker returns. + IAPWallet.disconnect().catch(() => {}); + $('wcDisconnectInfo').textContent = 'Disconnecting — reloading so you can pick a different wallet…'; + IAP.status('Disconnecting — reloading…', 'ok'); + setTimeout(() => location.reload(), 900); + })); + // a named sponsor that cannot be paid right now: hold the transaction and say why (never credit the company by default) + function sponsorHoldText(sp) { + const who = sp.sponsorName || 'your sponsor'; + if (sp.sponsorBlocked === 'claim' && sp.claim) return (sp.claim.nobody ? 'Nobody above you on LinkSpin has a wallet yet, so there is no one for the contract to pay. ' : who + ' has not linked a wallet on LinkSpin yet. They have until ' + new Date(sp.claim.deadline).toLocaleString() + ' to do it, and we have told them. ') + 'You can use everything else meanwhile; your purchase waits so it pays the right person.'; + if (sp.sponsorBlocked === 'notActivated') return who + ' has not switched on payouts yet, so this purchase would credit the company instead of them. Ask them to switch on payouts (Wallet tab, one free transaction), then try again.'; + if (sp.sponsorBlocked === 'rpc') return 'Could not confirm your sponsor on the chain just now. Try again in a minute; nothing was charged.'; + return 'Your sponsor link could not be matched to a member. Message support before buying so ' + who + ' gets credit.'; + } + $('activateBtn').addEventListener('click', busy($('activateBtn'), async () => { + const me = await (await fetch('/api/sponsor?intent=buy')).json(); + if (me.sponsorBlocked) { IAP.status(sponsorHoldText(me), 'bad'); return; } + IAP.status('Confirm the free activation in your wallet…'); + const r = await IAPWallet.activate(me.sponsorId || 0); + if (r.receipt.status !== '0x1') throw new Error('Transaction reverted. Check the explorer.'); + IAP.status('Payouts are on. Your invite link is live.', 'ok'); + await render(); + })); + $('copyInvite').addEventListener('click', async () => { + try { await navigator.clipboard.writeText($('inviteLine').textContent); IAP.status('Link copied.', 'ok'); } + catch (e) { IAP.status('Copy failed. Select and copy the link text.', 'bad'); } + }); + $('logoutLink').addEventListener('click', async e => { + e.preventDefault(); + await fetch('/api/auth/logout', { method: 'POST' }); + IAP.status('Logged out.', 'ok'); + await render(); + }); + + // ── welcome tour (viral banner gauntlet): a new member meets their 3-level + // upline's sites, 10 focus-paused seconds each, then unlocks welcome credits. + // Same three levels the contract pays — the tour IS the org chart. + async function showGauntlet() { + try { + const g = await (await fetch('/api/my/gauntlet')).json(); + if (!g.pending || !g.slides || !g.slides.length) return false; + const gate = $('gauntGate'); + gate.hidden = false; + for (let i = 0; i < g.slides.length; i++) { + const s = g.slides[i]; + $('ggWho').textContent = 'Position ' + (i + 1) + ': ' + s.name + (i === 0 ? ' — the person who invited you' : ''); + $('ggProgress').textContent = 'Meeting your line: ' + (i + 1) + ' of ' + g.slides.length; + $('ggFrame').hidden = false; + $('ggFrame').src = s.targetUrl; + let left = g.dwell || 10; + $('ggTimer').textContent = left + 's'; + await new Promise(done => { + const t = setInterval(() => { + if (document.visibilityState !== 'visible' || !document.hasFocus()) return; + left -= 1; + $('ggTimer').textContent = Math.max(0, left) + 's'; + if (left <= 0) { clearInterval(t); done(); } + }, 1000); + }); + } + $('ggFrame').src = 'about:blank'; + $('ggFrame').hidden = true; // avoid a white about:blank panel once the tour is done + $('ggTimer').textContent = '✓'; + $('ggWho').textContent = 'That is your line. When you grow, they earn — and yours starts the day you share.'; + $('ggClaim').hidden = false; + await new Promise(done => { + $('ggClaim').onclick = async () => { + try { + const r = await api('/api/my/gauntlet/complete', { token: g.token }); + IAP.status('+' + r.credited + ' welcome credits unlocked. They spend on real campaigns.', 'ok'); + } catch (e) { IAP.status(e.message, 'bad'); } + done(); + }; + }); + gate.hidden = true; + $('ggClaim').hidden = true; + return true; + } catch (e) { return false; } + } + + // ── line banner (profile): the member's slot on welcome tours + their wall ── + function fillLineBanner(a) { + if (!a) return; + if (a.lineTargetUrl) $('lbTarget').value = a.lineTargetUrl; + if (a.lineBannerUrl) { + $('lbBanner').value = a.lineBannerUrl; + $('lbPreview').hidden = false; + $('lbPreview').innerHTML = 'line banner'; + } + $('lbCurrent').textContent = a.lineTargetUrl + ? 'Live: your next three levels meet ' + a.lineTargetUrl + ' on their welcome tour.' + : 'Not set yet. Until you set one, your tour slot is skipped.'; + } + async function loadLineBanner() { + try { + const a = await (await fetch('/api/me')).json(); + fillLineBanner(a); + fillProfileDetails(a); + // buyerCount + wallUnlocked live on the dashboard payload (chain read), not on /api/me + let d = {}; try { d = await (await fetch('/api/my/dashboard')).json(); } catch (e) {} + fillWallOffers(Object.assign({}, a, { buyerCount: d.buyerCount || 0, wallUnlocked: d.wallUnlocked || 1 })); + } catch (e) {} + } + // ── wall positions 2 & 3: the member's own offers, unlocked by qualifying buyers ── + function fillWallOffers(a) { + if (!a || !$('wallOffersCard')) return; + const unlocked = a.wallUnlocked || 1, bc = a.buyerCount || 0; + const offers = Array.isArray(a.wallOffers) ? a.wallOffers : []; + const NEED = [2, 5]; + for (let i = 0; i < 2; i++) { + const o = offers[i] || {}; + const open = unlocked >= i + 2; + $('woTitle' + i).value = o.title || ''; $('woTarget' + i).value = o.targetUrl || ''; $('woBanner' + i).value = o.bannerUrl || ''; + $('woPrev' + i).hidden = !o.bannerUrl; $('woPrev' + i).innerHTML = o.bannerUrl ? '' : ''; + $('woLock' + i).textContent = open ? 'yours' : 'unlocks at ' + NEED[i] + ' qualifying buyers (' + bc + '/' + NEED[i] + ')'; + $('woSlot' + i).classList.toggle('locked', !open); + } + $('woStatus').textContent = unlocked >= 3 ? 'Fully qualified: all three wall positions are yours.' + : unlocked === 2 ? 'Position 2 is yours. ' + (5 - bc) + ' more qualifying buyer' + (5 - bc === 1 ? '' : 's') + ' and position 3 is too.' + : (2 - bc) + ' more qualifying buyer' + (2 - bc === 1 ? '' : 's') + ' ($20 or more) opens position 2. You can set your links now; they go live the moment a slot unlocks.'; + } + document.querySelectorAll('.wo-upload').forEach(b => b.addEventListener('click', () => { const f = document.querySelector('.wo-file[data-slot="' + b.dataset.slot + '"]'); if (f) f.click(); })); + document.querySelectorAll('.wo-file').forEach(inp => inp.addEventListener('change', async () => { + const i = inp.dataset.slot, f = inp.files[0]; if (!f) return; + $('woInfo' + i).textContent = 'Uploading…'; + try { + const r = await (await fetch('/api/my/upload', { method: 'POST', headers: { 'Content-Type': f.type }, body: f })).json(); + if (r.error) { $('woInfo' + i).textContent = r.error; } + else { $('woBanner' + i).value = r.url; $('woInfo' + i).textContent = 'Uploaded'; $('woPrev' + i).hidden = false; $('woPrev' + i).innerHTML = ''; } + } catch (e) { $('woInfo' + i).textContent = 'Upload failed. Try again.'; } + inp.value = ''; + })); + if ($('woSaveBtn')) $('woSaveBtn').addEventListener('click', busy2($('woSaveBtn'), async () => { + const offers = [0, 1].map(i => ({ title: $('woTitle' + i).value, targetUrl: $('woTarget' + i).value, bannerUrl: $('woBanner' + i).value })); + const r = await api('/api/my/wall-offers', { offers }); + IAP.status('Wall positions saved.', 'ok'); + await loadLineBanner(); + })); + const SOCIALS = ['facebook', 'twitter', 'youtube', 'instagram', 'tiktok', 'telegram', 'linkedin', 'website', 'video']; // video = intro video on the wall, not a social link + function fillProfileDetails(a) { + if (!a) return; + if (a.bio) $('pfBio').value = a.bio; + if (a.avatarUrl) { const p = $('pfAvatarPrev'); p.src = a.avatarUrl; p.hidden = false; } + let soc = {}; try { soc = a.socials ? JSON.parse(a.socials) : {}; } catch (e) {} + for (const p of SOCIALS) if ($('soc-' + p)) $('soc-' + p).value = soc[p] || ''; + if (a.username) { + const link = location.origin + '/wall/' + a.username; + $('pfBioLink').textContent = link; + $('pfViewBio').hidden = false; + $('pfViewBio').href = '/wall/' + a.username; + } + } + let pfAvatar; // pending avatar url + $('pfAvatarBtn').addEventListener('click', () => $('pfAvatarFile').click()); + $('pfAvatarFile').addEventListener('change', async () => { + const f = $('pfAvatarFile').files[0]; + if (!f) return; + $('pfAvatarInfo').textContent = 'Uploading…'; + try { + const r = await (await fetch('/api/my/upload', { method: 'POST', headers: { 'Content-Type': f.type }, body: f })).json(); + if (r.error) { $('pfAvatarInfo').textContent = r.error; $('pfAvatarFile').value = ''; return; } + pfAvatar = r.url; + $('pfAvatarInfo').textContent = 'Uploaded — save to apply.'; + const p = $('pfAvatarPrev'); p.src = r.url; p.hidden = false; + } catch (e) { $('pfAvatarInfo').textContent = 'Upload failed.'; } + $('pfAvatarFile').value = ''; + }); + $('pfDetailsSave').addEventListener('click', busy2($('pfDetailsSave'), async () => { + const body = { bio: $('pfBio').value, socials: {} }; + for (const p of SOCIALS) body.socials[p] = ($('soc-' + p) && $('soc-' + p).value.trim()) || ''; + if (pfAvatar) body.avatarUrl = pfAvatar; + const r = await api('/api/my/profile-details', body); + IAP.status('Profile saved.', 'ok'); + if (r.account) fillProfileDetails(r.account); + })); + $('lbUploadBtn').addEventListener('click', () => $('lbFile').click()); + $('lbFile').addEventListener('change', async () => { + const f = $('lbFile').files[0]; + if (!f) return; + $('lbUpInfo').textContent = 'Uploading…'; + try { + const r = await (await fetch('/api/my/upload', { method: 'POST', headers: { 'Content-Type': f.type }, body: f })).json(); + if (r.error) { $('lbUpInfo').textContent = r.error; $('lbFile').value = ''; return; } + $('lbBanner').value = r.url; + $('lbUpInfo').textContent = 'Uploaded.'; + $('lbPreview').hidden = false; + $('lbPreview').innerHTML = 'line banner'; + } catch (e) { $('lbUpInfo').textContent = 'Upload failed. Try again.'; } + $('lbFile').value = ''; + }); + $('lbSaveBtn').addEventListener('click', busy2($('lbSaveBtn'), async () => { + const r = await api('/api/my/linebanner', { bannerUrl: $('lbBanner').value, targetUrl: $('lbTarget').value }); + IAP.status('Line banner saved. Your next three levels will meet it.', 'ok'); + if (r.account) fillLineBanner(r.account); + })); + + // ── login ad interstitial (ClickBaitPays pattern): after a successful + // sign-in the sponsor card appears; "Open Ad" opens the CTA link in a NEW + // tab (a real, counted click) while the timer counts down on THIS page — + // deliberately not paused, the member is expected to be in the ad tab. + // At zero, "Go to dashboard" appears. + async function showLoginAd() { + try { + const { ad } = await (await fetch('/api/ads/slot?type=login')).json(); + if (!ad || !ad.targetUrl) return; + const gate = $('loginGate'); + const openBtn = $('lgOpen'); + const goBtn = $('lgContinue'); + const timer = $('lgTimer'); + $('lgCreative').innerHTML = ad.imageUrl + ? 'sponsor ad' + : '' + (ad.title ? String(ad.title).replace(/[&<>]/g, '') : 'Visit today\'s sponsor') + ''; + $('lgStatus').textContent = 'Login ad sponsor — click "Open Ad" to begin.'; + timer.hidden = true; + goBtn.hidden = true; + openBtn.disabled = false; + gate.hidden = false; + await new Promise(done => { + openBtn.onclick = () => { + window.open(ad.targetUrl, '_blank'); // the click relay counts it + openBtn.disabled = true; + $('lgStatus').textContent = 'Ad open in a new tab. View it and come back — the timer runs here.'; + let left = ad.dwell || 10; + timer.hidden = false; + timer.textContent = 'Time remaining: ' + left + 's'; + const t = setInterval(() => { + left -= 1; + if (left > 0) { timer.textContent = 'Time remaining: ' + left + 's'; return; } + clearInterval(t); + timer.textContent = 'Time is up'; + timer.classList.add('done'); + $('lgStatus').textContent = 'Thanks for the look. Your dashboard is ready.'; + goBtn.hidden = false; + }, 1000); + goBtn.onclick = () => done(); + }; + }); + gate.hidden = true; + $('lgTimer').classList.remove('done'); + } catch (e) {} + } + + // ── SPONSOR CHAT: two-way threads, presence-aware, with a slide-in drawer ── + let CHAT_ME = null, CHAT_OTHER = null, CHAT_LASTID = 0, CHAT_POLL = null, CHAT_CANMUTE = false, CHAT_IMUTE = false, CHAT_SPONSOR = null, CHAT_LAST_UNREAD = 0; + function chatSync(d) { + CHAT_ME = d.email || CHAT_ME; + CHAT_SPONSOR = (d.sponsor && d.sponsor.email) ? d.sponsor : null; + const link = $('chatMenuBtn'); if (link && link.closest('.bo-links')) link.closest('.bo-links').hidden = !d.email; + setChatBadge(d.chatUnread || 0); + CHAT_LAST_UNREAD = d.chatUnread || 0; + const tog = $('chatAvailToggle'); if (tog) tog.checked = d.chatAvailable !== false; + // Overview quick action + My line card: message-your-sponsor entry points + const qs = $('qaMsgSponsor'); + if (qs) { + if (CHAT_SPONSOR) { qs.hidden = false; qs.dataset.email = CHAT_SPONSOR.email; qs.dataset.name = CHAT_SPONSOR.name || 'your sponsor'; } + else qs.hidden = true; + } + const card = $('sponsorMsgCard'); + if (card) { + card.hidden = !CHAT_SPONSOR; + if (CHAT_SPONSOR && $('sponsorMsgName')) $('sponsorMsgName').textContent = CHAT_SPONSOR.name || 'your sponsor'; + } + } + function setChatBadge(n) { const b = $('chatNavBadge'); if (b) { b.hidden = !n; b.textContent = n > 9 ? '9+' : n; } } + function stopPoll() { if (CHAT_POLL) { clearInterval(CHAT_POLL); CHAT_POLL = null; } } + function startPoll() { stopPoll(); CHAT_POLL = setInterval(() => pullThread(false), 4000); } + // the composer grows with the message up to ~45% of the screen, and keeps any height the member dragged it to (Bradley, 2026-09-13) + function autoGrow(el) { + const cap = Math.max(160, Math.floor(window.innerHeight * 0.45)); + const dragged = Number(el.dataset.dragged || 0); + el.style.height = 'auto'; + el.style.height = Math.min(cap, Math.max(dragged, el.scrollHeight)) + 'px'; + } + function closeDrawer() { stopPoll(); if ($('chatDrawer')) $('chatDrawer').hidden = true; CHAT_OTHER = null; loadDashboard(); } + + async function openThreads() { + const dr = $('chatDrawer'); if (!dr) return; + dr.hidden = false; $('chatConvo').hidden = true; $('chatThreads').hidden = false; + $('chatBack').hidden = true; $('chatMute').hidden = true; $('chatDot').hidden = true; + $('chatTitle').textContent = 'Messages'; $('chatStatus').textContent = ''; + stopPoll(); CHAT_OTHER = null; + $('chatThreads').innerHTML = '

Loading…

'; + try { + const r = await (await fetch('/api/my/chat/threads')).json(); + const list = r.threads || []; + // always offer "message your sponsor" up top when they have one and no thread yet + const hasSponsorThread = CHAT_SPONSOR && list.some(t => t.email === CHAT_SPONSOR.email); + const sponsorRow = (CHAT_SPONSOR && !hasSponsorThread) + ? '
' + + '' + + '
' + esc(CHAT_SPONSOR.name) + '
' + + '
Your sponsor · tap to message
' + : ''; + if (!list.length && !sponsorRow) { $('chatThreads').innerHTML = '
No conversations yet. You can message anyone in your line from “My line”.
'; return; } + $('chatThreads').innerHTML = sponsorRow + list.map(t => + '
' + + '' + + '
' + esc(t.name) + '
' + + '
' + (t.last.fromMe ? 'You: ' : '') + esc((t.last.body || '').slice(0, 64)) + '
' + + (t.unread ? '' + t.unread + '' : '') + '
').join(''); + $('chatThreads').querySelectorAll('.chat-thread').forEach(el => + el.addEventListener('click', () => openConvo(el.dataset.email, el.dataset.name))); + } catch (e) { $('chatThreads').innerHTML = '
Could not load messages.
'; } + } + + async function openConvo(email, name) { + if (!email) return; + CHAT_OTHER = email; CHAT_LASTID = 0; + const dr = $('chatDrawer'); if (!dr) return; + dr.hidden = false; $('chatThreads').hidden = true; $('chatConvo').hidden = false; + $('chatBack').hidden = false; $('chatDot').hidden = false; + $('chatTitle').textContent = name || email; $('chatStatus').textContent = '…'; + $('chatMsgs').innerHTML = ''; $('chatBanner').hidden = true; + $('chatInput').disabled = false; $('chatSend').disabled = false; + await pullThread(true); startPoll(); + setTimeout(() => { const i = $('chatInput'); if (i) i.focus(); }, 60); + } + + function renderMsgs(msgs) { + const box = $('chatMsgs'); if (!box) return; + const atBottom = box.scrollTop + box.clientHeight >= box.scrollHeight - 60; + for (const m of msgs) { + if (m.id <= CHAT_LASTID) continue; + CHAT_LASTID = Math.max(CHAT_LASTID, m.id); + const d = document.createElement('div'); + d.className = 'cbub ' + (m.fromMe ? 'me' : 'them'); + d.textContent = m.body; + const t = document.createElement('span'); t.className = 'ct-time'; + t.textContent = new Date(m.sent).toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' }); + d.appendChild(t); box.appendChild(d); + } + if (atBottom) box.scrollTop = box.scrollHeight; + } + + async function pullThread(reset) { + if (!CHAT_OTHER) return; + try { + const r = await (await fetch('/api/my/chat/thread?with=' + encodeURIComponent(CHAT_OTHER) + '&after=' + (reset ? 0 : CHAT_LASTID))).json(); + if (r.error) { $('chatBanner').hidden = false; $('chatBanner').textContent = r.error; return; } + if (reset) { $('chatMsgs').innerHTML = ''; CHAT_LASTID = 0; } + renderMsgs(r.messages || []); + $('chatDot').className = 'pres-dot' + (r.online ? ' on' : ''); + $('chatStatus').textContent = r.online ? 'active now' : (r.available ? 'away · will get your note' : 'not taking live chats · leave a note'); + CHAT_CANMUTE = !!r.canMute; CHAT_IMUTE = !!r.iMute; + const mb = $('chatMute'); mb.hidden = !CHAT_CANMUTE; mb.textContent = CHAT_IMUTE ? 'Unmute' : 'Mute'; + const blocked = !!r.blocked; + $('chatInput').disabled = blocked; $('chatSend').disabled = blocked; + if (blocked) { $('chatBanner').hidden = false; $('chatBanner').textContent = 'They are not accepting messages from you right now.'; } + else if (CHAT_IMUTE) { $('chatBanner').hidden = false; $('chatBanner').textContent = 'You muted this member. Unmute to let them message you again.'; } + else $('chatBanner').hidden = true; + } catch (e) {} + } + + async function chatSend() { + const inp = $('chatInput'); if (!inp) return; + const text = inp.value.trim(); if (!text || !CHAT_OTHER) return; + $('chatSend').disabled = true; + try { + const r = await api('/api/my/chat/send', { to: CHAT_OTHER, body: text }); + inp.value = ''; autoGrow(inp); renderMsgs([r.message]); + const box = $('chatMsgs'); box.scrollTop = box.scrollHeight; + } catch (e) { IAP.status(e.message || 'Could not send.', 'bad'); } + finally { $('chatSend').disabled = false; inp.focus(); } + } + + async function toggleMute() { + if (!CHAT_OTHER) return; + try { const r = await api('/api/my/chat/mute', { email: CHAT_OTHER, muted: !CHAT_IMUTE }); CHAT_IMUTE = r.muted; $('chatMute').textContent = CHAT_IMUTE ? 'Unmute' : 'Mute'; pullThread(false); } + catch (e) { IAP.status(e.message, 'bad'); } + } + + (function chatInit() { + if (!$('chatDrawer')) return; + const on = (id, ev, fn) => { const el = $(id); if (el) el.addEventListener(ev, fn); }; + on('chatMenuBtn', 'click', e => { if (e && e.preventDefault) e.preventDefault(); openThreads(); }); + on('chatClose', 'click', closeDrawer); + on('chatBack', 'click', openThreads); + on('chatMute', 'click', toggleMute); + on('chatSend', 'click', chatSend); + const inp = $('chatInput'); + if (inp) { + inp.addEventListener('input', () => autoGrow(inp)); + inp.addEventListener('mouseup', () => { const h = inp.getBoundingClientRect().height; inp.dataset.dragged = h > 60 ? String(Math.round(h)) : ''; }); + inp.addEventListener('keydown', e => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); chatSend(); } }); + } + on('qaMsgSponsor', 'click', () => { const q = $('qaMsgSponsor'); if (q.dataset.email) openConvo(q.dataset.email, q.dataset.name || 'your sponsor'); }); + on('lineMsgSponsor', 'click', () => { if (CHAT_SPONSOR) openConvo(CHAT_SPONSOR.email, CHAT_SPONSOR.name || 'your sponsor'); }); + on('chatAvailToggle', 'change', async () => { + const t = $('chatAvailToggle'); + try { await api('/api/my/chat/available', { available: t.checked }); IAP.status(t.checked ? 'You are available to chat with your line.' : 'Live chat off. People can still leave you a note.', 'ok'); } + catch (e) { IAP.status(e.message, 'bad'); t.checked = !t.checked; } + }); + // presence heartbeat + new-message notifier: pop + toast when unread rises + setInterval(async () => { + try { + const r = await (await fetch('/api/my/ping')).json(); + const n = r.chatUnread || 0; + if (n > CHAT_LAST_UNREAD) { playSound('pop'); IAP.status('💬 New message from your team.', 'ok'); } + CHAT_LAST_UNREAD = n; setChatBadge(n); + } catch (e) {} + }, 20000); + })(); + + // ad surfaces: a banner greets the sign-in screen; members see live + // banner + text placements inside the back office (they ARE the audience) + IAP.adSlot('banner', 'adSlotLogin'); + IAP.adSlot('banner', 'adSlotOverview'); + IAP.adSlot('banner', 'adSlotSide', { width: 125, height: 125 }); // square button ad in the sidebar + + render(); +})(); + +// ── partner promo codes: typed on the Overview (Marty, 2026-09-12) ── +(function () { + const btn = document.getElementById('promoApply'), inp = document.getElementById('promoCode'), msg = document.getElementById('promoMsg'); + if (!btn || !inp) return; + const say = (t, ok) => { msg.hidden = false; msg.textContent = t; msg.style.color = ok ? 'var(--mint)' : '#ff8a8a'; }; + const go = async () => { + const code = inp.value.trim(); if (!code) { say('Enter a promo code.', false); return; } + btn.disabled = true; + try { + const r = await (await fetch('/api/my/promo/redeem', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ code }) })).json(); + if (r.error) { say(r.error, false); return; } + say('Added ' + Number(r.credits).toLocaleString() + ' credits' + (r.partner ? ' from ' + r.partner : '') + '. They are in your balance now.', true); + inp.value = ''; if (typeof loadDashboard === 'function') loadDashboard(); + } catch (e) { say('Could not apply that code. Try again.', false); } + finally { btn.disabled = false; } + }; + btn.addEventListener('click', go); inp.addEventListener('keydown', e => { if (e.key === 'Enter') go(); }); +})(); diff --git a/public/credits.html b/public/credits.html index 0c2c7bf..b51cb3d 100644 --- a/public/credits.html +++ b/public/credits.html @@ -1,86 +1,86 @@ - - - - - - -Credits · LinkSpin - - - - - -
-
-
-
-
-
-

Buy a package

priced in dollars · settled in POL at the live rate · one transaction
-
-
loading packages…
-
- you pay· - -
-
- - - SafePal recommended. MetaMask, Phantom and WalletConnect wallets also work. -
- -

Loading your sponsor…

-
-
-
-

Your purchases

every row links to the transaction
-
WhenPackagePaidTransaction
-
-
credits appear in Ads the moment the transaction settles · nothing is held by the site
-
-
-
-
-

Where it goes

same transaction
-
-
-
-

Your wallet

-
-
-
-

Earn instead

free credits
-
-
View 5 ads, claim 5 creditsAds →
-
Run a zone on your siteZones →
-
Sign-in ad, once a dayautomatic
-
-
-
-
-
-
- - - - - - + + + + + + +Credits · LinkSpin + + + + + +
+
+
+
+
+
+

Buy a package

priced in dollars · settled in POL at the live rate · one transaction
+
+
loading packages…
+
+ you pay· + +
+
+ + + SafePal recommended. MetaMask, Phantom and WalletConnect wallets also work. +
+ +

Loading your sponsor…

+
+
+
+

Your purchases

every row links to the transaction
+
WhenPackagePaidTransaction
+
+
credits appear in Ads the moment the transaction settles · nothing is held by the site
+
+
+
+
+

Where it goes

same transaction
+
+
+
+

Your wallet

+
+
+
+

Earn instead

free credits
+
+
View 5 ads, claim 5 creditsAds →
+
Run a zone on your siteZones →
+
Sign-in ad, once a dayautomatic
+
+
+
+
+
+
+ + + + + + diff --git a/public/my.html b/public/my.html index 680b2b9..8b3677d 100644 --- a/public/my.html +++ b/public/my.html @@ -1,1018 +1,1018 @@ - - - - - -More · LinkSpin - - - - - - - - - -

Loading your account…

-
- - - - - - - - - - - - - - - - -
- - - - - - - - - - - - - + + + + + +More · LinkSpin + + + + + + + + + +

Loading your account…

+
+ + + + + + + + + + + + + + + + +
+ + + + + + + + + + + + + diff --git a/server.js b/server.js index 5936ea9..f8badb0 100644 --- a/server.js +++ b/server.js @@ -1,3298 +1,3300 @@ -// LinkSpin — membership advertising with immutable on-chain settlement. -// Zero-dependency Node server (RM Circle pattern): static pages + JSON API, -// wallet sign-in (SIWE), live contract ledger, sponsor join links. -// -// Chain selection (Amoy rehearsal vs mainnet) lives in data/config.json — -// see chain.js. Wipe the volume's accounts/sessions + flip config = launch. -const http = require('http'); -const https = require('https'); -const dns = require('dns'); -const fs = require('fs'); -const path = require('path'); -const crypto = require('crypto'); -const sendy = require('./sendy'); -const { URL } = require('url'); -const chain = require('./chain'); -const auth = require('./auth'); -const accounts = require('./accounts'); -const ads = require('./ads'); -const mailer = require('./mailer'); -const messages = require('./messages'); -const reports = require('./reports'); -const drip = require('./drip'); -const spaces = require('./spaces'); // DO Spaces video storage (inert unless DO_SPACES_* set) -let QR = null; try { QR = require('qrcode'); } catch (e) { /* optional */ } -const chatbot = require('./chatbot'); -const coach = require('./coach'); // coaching view, nudges, digest, prospects, link stats -const tank = require('./tank'); // holding tank: unsponsored free members, adoptions, pay-it-forward -const legacy = require('./legacy'); // Faucet Wave / Tier One Ads bridge: welcome-back credits for listed emails -const traffic = require('./traffic'); // public page views by referring domain (admin Traffic tab) -const promos = require('./promos'); // partner promo codes -> free ad credits (link ?promo=CODE or the dashboard box) -const blog = require('./blog'); -const adminMember = require('./adminmember'); -const syndicate = require('./syndicate'); -const releases = require('./releases'); -const updates = require('./updates'); -const audit = require('./audit'); // counter audit: views vs delivery logs, charges vs shows (Marty, 2026-09-15) // member update emails from Admin > Releases (Marty, 2026-09-14) -const leaderboard = require('./leaderboard'); -const toolkit = require('./toolkit'); -const registry = require('./registry'); // network registry: who is who across properties (LinkSpin, 2026-09-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) -const postbacks = require('./postbacks'); // outbound + inbound conversion postbacks on rotator clicks (2026-09-29) -const sources = require('./sources'); // traffic sources: network macros, campaign URLs, per-source postbacks, Reports dimension (2026-10-12) -const pages = require('./pages'); // member pages: bridge / review / squeeze, served at /p/ (2026-09-29) -const domains = require('./domains'); // link-domain pool by channel + six-hourly safety checks; burned domains leave the pool (2026-10-10) -const zonereport = require('./zonereport'); // read-only zone numbers for member Reports (2026-10-10) -const zones = require('./zones'); // ad zones on members' own sites (2026-09-29) -const nas = require('./nas'); -const audiences = require('./audiences'); // first-party retargeting (2026-10-08) // only asked whether syndication is on (the status strip) -const MEMBER_AD_TYPES = ['banner', 'text', 'login']; // the formats LinkSpin members can buy (video, visits, featured, solo stay off) // the rotator: rotations, weighted destinations, /r/ -const snapshot = require('./snapshot'); // daily growth snapshot -> Telegram payments feed (Marty, 2026-09-15) -const pipeline = require('./pipeline'); // sponsor follow-up board (coming soon until site setting pipelineMode = on) (Marty, 2026-09-15) -const videomaker = require('./videomaker'); // Circuit tool: promo videos with the member's own end card (ffmpeg in the image) // badge-gated promo toolkit + AI Copy Engine (Surge and up) (Marty, 2026-09-14) // referral contest: /leaderboard, Overview card, weekly + monthly winners (Marty, 2026-09-14) // release notes + roadmap: /whats-new, Overview card, Admin > Releases (Marty, 2026-09-14) // blog -> Blotato -> X + Instagram on publish (Marty, 2026-09-13) // admin member card: search, drilldown, edits (Marty, 2026-09-13) // admin-written coaching articles, server-rendered public /blog with SEO metadata (Marty, 2026-09-12) -const TRAFFIC_PAGES = new Set(['/', '/ledger', '/contract', '/shorts', '/plays', '/wallets', '/launch', '/partners', '/publishers', '/earning', '/blog', '/whats-new', '/leaderboard']); -let tankWaitCache = null; // dashboard: who is waiting for a sponsor (refreshed every minute) -const geo = require('./geo'); // viewer country -> tier (DB-IP lite), for campaign targeting -const burner = require('./burner'); // automatic on-chain credit burns (inert without ENGINE_KEY) - -const PORT = Number(process.env.PORT || 3000); -const ROOT = __dirname; -const PUBLIC_DIR = path.join(ROOT, 'public'); -const DATA_DIR = process.env.DATA_DIR || path.join(ROOT, 'data'); -const ADMIN_PASSWORD = process.env.ADMIN_PASSWORD || 'changeme'; -const ADMIN_EMAIL = String(process.env.ADMIN_EMAIL || '').trim().toLowerCase(); -const { SITE_HOST, SITE_URL } = require('./host'); -// Admin portal sessions: email-code sign-in allowlisted to ADMIN_EMAIL, kept -// in the volume so a restart doesn't log the admin out. Separate cookie and -// store from member sessions; the Bearer ADMIN_PASSWORD API path still works. -const ADMIN_SESS_FILE = path.join(DATA_DIR, 'admin-sessions.json'); -const ADMIN_TTL = 12 * 60 * 60 * 1000; -let adminSessions = {}; -try { adminSessions = JSON.parse(fs.readFileSync(ADMIN_SESS_FILE, 'utf8')) || {}; } catch (e) { adminSessions = {}; } -function saveAdminSessions() { - const now = Date.now(); - for (const k of Object.keys(adminSessions)) if (!adminSessions[k] || adminSessions[k].expires < now) delete adminSessions[k]; - try { fs.writeFileSync(ADMIN_SESS_FILE, JSON.stringify(adminSessions), { mode: 0o600 }); } catch (e) {} -} -function mintAdminSession(email) { - const t = crypto.randomBytes(32).toString('hex'); - adminSessions[t] = { email, expires: Date.now() + ADMIN_TTL }; - saveAdminSessions(); - return t; -} -function adminTokenOf(req) { const m = /(?:^|;\s*)iap\.adm=([^;]+)/.exec(req.headers.cookie || ''); return m ? decodeURIComponent(m[1]) : null; } -function adminFromRequest(req) { const t = adminTokenOf(req); const s = t && adminSessions[t]; return (s && s.expires > Date.now()) ? s : null; } -function dropAdminSession(req) { const t = adminTokenOf(req); if (t && adminSessions[t]) { delete adminSessions[t]; saveAdminSessions(); } } -function adminCookie(t) { return 'iap.adm=' + encodeURIComponent(t) + '; Path=/; HttpOnly; SameSite=Lax; Max-Age=' + (ADMIN_TTL / 1000) + (IS_PROD ? '; Secure' : ''); } -function clearAdminCookie() { return 'iap.adm=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0'; } -const IS_PROD = process.env.NODE_ENV === 'production'; -// Posture gates. mailer.js is the authority on outbound; this copy only decides whether the -// mailing loops are worth starting. SIGNUPS=closed shuts registration without taking the -// site down — members already here keep their dashboards. -const OUTBOUND_MAIL = process.env.OUTBOUND === 'on'; -const SIGNUPS_OPEN = process.env.SIGNUPS !== 'closed'; -const SHUT = { error: 'LinkSpin is not accepting new accounts right now.' }; -// pre-launch whitelist (Marty 2026-10-08: public pages visible, nobody signs in unless whitelisted): LS_TESTERS = comma list of -// emails or usernames; empty = everyone with an account may sign in -const TESTERS = new Set(String(process.env.LS_TESTERS || '').split(',').map(x => x.trim().toLowerCase()).filter(Boolean)); -const TESTING = { error: 'LinkSpin is in testing. Members get in on launch day.' }; -const isTester = (email, acct) => !TESTERS.size || TESTERS.has(String(email || '').toLowerCase()) || TESTERS.has(String((acct && acct.username) || '').toLowerCase()); -const SITE_FILE = path.join(DATA_DIR, 'site.json'); - -const db = require('./db'); -fs.mkdirSync(DATA_DIR, { recursive: true }); -const UPLOADS_DIR = path.join(DATA_DIR, 'uploads'); // solo-ad media lives on the volume -fs.mkdirSync(UPLOADS_DIR, { recursive: true }); -const uploadCounts = new Map(); // email:day -> uploads today -// open earn tokens (ad view / video / visit / tour) live in memory but mirror to the volume so a -// redeploy mid-watch does not lose them (2026-09-13: a member's video watch died in a restart) -const OPEN_TOKENS_FILE = () => path.join(DATA_DIR, 'open-tokens.json'); -const persistedMaps = {}; -let tokenSaveTimer = null; -function saveOpenTokens() { - tokenSaveTimer = null; - try { - const out = {}; - for (const [name, m] of Object.entries(persistedMaps)) out[name] = Object.fromEntries(m); - fs.writeFileSync(OPEN_TOKENS_FILE(), JSON.stringify(out)); - } catch (e) {} -} -function persistedMap(name) { - const m = new Map(); - const touch = () => { if (!tokenSaveTimer) tokenSaveTimer = setTimeout(saveOpenTokens, 500); }; - const set = m.set.bind(m), del = m.delete.bind(m); - m.set = (k, v) => { set(k, v); touch(); return m; }; - m.delete = k => { const r = del(k); if (r) touch(); return r; }; - persistedMaps[name] = m; - return m; -} -function loadOpenTokens() { - let saved = null; try { saved = JSON.parse(fs.readFileSync(OPEN_TOKENS_FILE(), 'utf8')); } catch (e) { return; } - const cutoff = Date.now() - 2 * 3600 * 1000; let n = 0; - for (const [name, m] of Object.entries(persistedMaps)) { - for (const [k, v] of Object.entries(saved[name] || {})) if (v && Number(v.ts || 0) > cutoff) { Map.prototype.set.call(m, k, v); n++; } - } - if (n) console.log('open earn tokens restored:', n); -} -const gauntletTokens = persistedMap('gauntlet'); // email -> welcome-tour token (server-clock dwell floor) -const videoTokens = persistedMap('video'); // email -> watch-to-earn video token (server-clock watch floor) -const faucetHits = new Map(); // address -> last faucet ts (rehearsal test-POL faucet rate limit) -const visitTokens = persistedMap('visit'); // email -> verified-visit token (dwell + captcha floor) -// walk the referral chain upward via sponsorRef (code/username/member id) -async function uplineSlides(email, depth = 3) { - const out = []; - let cur = await accounts.byEmail(email); - for (let i = 0; i < depth && cur; i++) { - const ref = String(cur.sponsorRef || '').trim().toLowerCase(); - if (!ref) break; - let s = null; - if (/^\d+$/.test(ref)) s = await accounts.byMemberId(Number(ref)); - if (!s) s = await accounts.byCode(ref); - if (!s) s = await accounts.byUsername(ref); - if (!s || s.email === cur.email) break; - out.push(s); - cur = s; - } - return out; -} -// Wall ownership ladder: position 1 is always the member's own line banner; -// positions 2 and 3 become theirs at 2 and 5 qualifying buyers (the same -// thresholds that open payout levels 2 and 3). Until then, or while an unlocked -// slot is empty, the slot shows an upline's banner, then a house ad. -const catalogCache = { at: 0, products: null }; -const wallUnlockedFor = bc => (bc >= 5 ? 3 : bc >= 2 ? 2 : 1); -// every on-chain member id this session controls: the main wallet plus linked -// positions (Qualified Start). Credits pool across them on the dashboard. -const memberInfoCache = new Map(); // id -> { t, v } (60s): line views ask for every member's on-chain row -async function cachedMember(id) { - const c = memberInfoCache.get(id); if (c && Date.now() - c.t < 60000) return c.v; - let v = null; try { v = await chain.member(id); } catch (e) {} - memberInfoCache.set(id, { t: Date.now(), v }); return v; -} -async function myMemberIds(s) { - const main = await auth.refreshMemberId(s); - const ids = main ? [main] : []; - if (s && s.email) for (const p of await accounts.positions(s.email)) if (p.memberId && !ids.includes(p.memberId)) ids.push(p.memberId); - return { main, ids }; -} -function parseWallOffers(a) { - try { const v = JSON.parse((a && a.wallOffers) || '[]'); return Array.isArray(v) ? v.slice(0, 2) : []; } catch (e) { return []; } -} -// admin fallback ads for wall positions 2 & 3 when a member has no upline. -// Configurable by dropping data/admin-wall-ads.json ([{name,targetUrl,bannerUrl}]). -function getAdminWallAds() { - try { const j = JSON.parse(fs.readFileSync(path.join(DATA_DIR, 'admin-wall-ads.json'), 'utf8')); if (Array.isArray(j) && j.length) return j; } catch (e) {} - return [{ name: 'LinkSpin', targetUrl: SITE_URL + '/', bannerUrl: null }]; -} -const chatHits = new Map(); -const demoLimits = new Map(); // ip -> timestamps of home-page demo spins (5 per hour) -function chatLimited(ip) { - const now = Date.now(), rec = chatHits.get(ip); - if (!rec || now > rec.reset) { chatHits.set(ip, { count: 1, reset: now + 60000 }); return false; } - rec.count += 1; - return rec.count > 10; -} -// magic-code sign-in: emailLower -> {code, exp, tries} -const emailCodes = new Map(); -const inviteTokens = new Map(); // admin-minted one-time sign-in links for testers: token -> {email, exp, next} -// ── sign-up code guard (Marty, 2026-09-11): the email box is one field and one -// tap, so nothing visible stands in a human's way. Bots hit four invisible walls: -// a honeypot field, a minimum form age, per-IP + global send limits, and, only -// once an IP trips a limit, the same icon check the ad viewer uses. -const CODE_LIMITS = { per10m: 5, perDay: 20, globalPerMin: 60, passMs: 5 * 60 * 1000, minFormMs: 2000 }; -const codeHits = new Map(); // ip -> { t: [send timestamps, 24h], passUntil, chal: { answer, exp } } -const codeGlobal = { minute: 0, n: 0 }; -const codeAlert = { last: 0, trips: 0, ips: new Set() }; -function clientIp(req) { return String(req.headers['x-forwarded-for'] || req.socket.remoteAddress || '').split(',')[0].trim() || 'unknown'; } -// the viewer's country and tier for ad targeting (null tier = unknown: never matches a restricted campaign) -// CORS for the zone tag: echo the calling origin and allow credentials, so the browser may send the ls.vid cookie -function corsCreds(req) { const o = String(req.headers.origin || ''); return o ? { 'Access-Control-Allow-Origin': o, 'Access-Control-Allow-Credentials': 'true', 'Vary': 'Origin' } : { 'Access-Control-Allow-Origin': '*' }; } -const PIXEL_GIF = Buffer.from('R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7', 'base64'); -function viewerGeo(req) { const cc = geo.countryOf(clientIp(req)); return { cc, tier: geo.tierOf(cc, siteConfig()) }; } -function codeChallenge(rec) { - const pick = CAPTCHA.slice().sort(() => Math.random() - 0.5).slice(0, 5); - const answer = Math.floor(Math.random() * pick.length); - rec.chal = { answer: pick[answer][0], exp: Date.now() + 5 * 60 * 1000 }; - return { prompt: pick[answer][1], options: pick.map(x => x[0]) }; -} -// returns null to allow the send, or { status, body } to answer with instead -const guardLog = (req, why, b) => console.log('signup-guard', why, clientIp(req), String(b.email || '').replace(/^(.).*(@.*)$/, '$1***$2')); -function codeGuard(req, b) { - const now = Date.now(); - // honeypot: bots fill it, humans never see it. Some form-filler extensions fill every field, - // hidden or not (seen 2026-09-11), so a filled honeypot is a CHALLENGE, never a silent drop: - // a person passes the icon check and gets the code, a bot cannot. - const hpRaw = String(b.hp_field_x9 || '').trim(); - const hpIsEmail = !!hpRaw && hpRaw.toLowerCase() === String(b.email || '').trim().toLowerCase(); - const hp = !!hpRaw && !hpIsEmail; // 2026-09-13: phones were autofilling the hidden field; own email = autofill, not a bot - if (hpRaw) console.log('signup-guard honeypot-value', clientIp(req), hpIsEmail ? 'own-email' : (/^https?:/i.test(hpRaw) ? 'url' : /@/.test(hpRaw) ? 'other-email' : /^\+?[\d\s()-]{6,}$/.test(hpRaw) ? 'phone' : 'text'), 'len=' + hpRaw.length, hpIsEmail ? '' : hpRaw.slice(0, 2) + '***'); - const fts = Number(b.fts) || 0; - if (!fts || now - fts < CODE_LIMITS.minFormMs) { guardLog(req, 'form-age', b); return { status: 400, body: { error: 'Give the page a second, then tap again.' } }; } - if (now - fts > 12 * 3600 * 1000) { guardLog(req, 'form-stale', b); return { status: 400, body: { error: 'This page has been open a long time. Refresh it, then tap again.' } }; } - const minute = Math.floor(now / 60000); - if (codeGlobal.minute !== minute) { codeGlobal.minute = minute; codeGlobal.n = 0; } - if (codeGlobal.n >= CODE_LIMITS.globalPerMin) { guardLog(req, 'global-limit', b); codeTrip(req, 'global'); return { status: 429, body: { error: 'Busy right now. Try again in a minute.' } }; } - const ip = clientIp(req); - const rec = codeHits.get(ip) || { t: [], passUntil: 0, chal: null }; - rec.t = rec.t.filter(ts => now - ts < 24 * 3600 * 1000); - const n10 = rec.t.filter(ts => now - ts < 10 * 60 * 1000).length; - const limited = hp || n10 >= CODE_LIMITS.per10m || rec.t.length >= CODE_LIMITS.perDay; - if (limited && now >= rec.passUntil) { - const pick = String(b.pick || ''); - if (pick && rec.chal && rec.chal.exp > now && pick === rec.chal.answer) { rec.passUntil = now + CODE_LIMITS.passMs; rec.chal = null; } - else { - guardLog(req, pick ? 'wrong-pick' : hp ? 'honeypot-challenge' : 'ip-limit', b); if (!hp) codeTrip(req, ip); - const challenge = codeChallenge(rec); codeHits.set(ip, rec); - return { status: 429, body: { error: pick ? 'That was not it. Try once more.' : 'Quick check before we send another code.', challenge } }; - } - } - rec.t.push(now); codeHits.set(ip, rec); codeGlobal.n += 1; - if (codeHits.size > 5000) for (const [k, v] of codeHits) { if (!v.t.length || now - v.t[v.t.length - 1] > 24 * 3600 * 1000) codeHits.delete(k); } - return null; -} -// burst alert: at most one message per 10 minutes, to the admin Telegram chat if set, else the admin email -function codeTrip(req, ip) { - codeAlert.trips += 1; codeAlert.ips.add(ip); - if (Date.now() - codeAlert.last < 10 * 60 * 1000) return; - codeAlert.last = Date.now(); - const text = '\u26A0\uFE0F LinkSpin sign-up guard: ' + codeAlert.trips + ' blocked code request' + (codeAlert.trips === 1 ? '' : 's') + ' from ' + codeAlert.ips.size + ' source' + (codeAlert.ips.size === 1 ? '' : 's') + ' (' + [...codeAlert.ips].slice(0, 5).join(', ') + ') in the last window.'; - codeAlert.trips = 0; codeAlert.ips = new Set(); - const sc = siteConfig(); - if (sc.telegramBotToken && sc.telegramAdminChatId) telegramSend(sc.telegramAdminChatId, text).catch(() => {}); - else if (ADMIN_EMAIL && mailer.hasKey()) mailer.send(ADMIN_EMAIL, 'LinkSpin: sign-up guard tripped', text).catch(() => {}); -} -// earn-view tokens: emailLower -> {token, ts} (one live token per member) -const earnTokens = persistedMap('earn'); -// human-check pairs for the view verifier: [emoji shown, word named in the prompt] -const CAPTCHA = [['🚀', 'rocket'], ['⚡', 'lightning bolt'], ['🔑', 'key'], ['🎯', 'target'], - ['🌊', 'wave'], ['🔥', 'flame'], ['💎', 'diamond'], ['🧲', 'magnet'], ['🔔', 'bell'], ['🌙', 'moon']]; - -// ── frame-breaking check ───────────────────────────────── -// Surf views frame the advertiser's URL full screen, so a target that refuses -// framing (X-Frame-Options / CSP frame-ancestors) would burn members' views on -// a blank frame. Catch it the moment the campaign is submitted. The lookup -// also refuses private/internal addresses so member URLs can't probe our LAN. -const PRIVATE_IP = /^(127\.|10\.|192\.168\.|169\.254\.|0\.|172\.(1[6-9]|2\d|3[01])\.|::1$|::$|f[cd])/i; -function frameFetch(url, depth) { - return new Promise(resolve => { - let u; - try { u = new URL(String(url || '')); } catch (e) { return resolve({ error: 'that is not a valid URL' }); } - if (!/^https?:$/.test(u.protocol)) return resolve({ error: 'only http(s) URLs work' }); - if (u.port && u.port !== '80' && u.port !== '443') return resolve({ error: 'custom ports are not allowed' }); - if (u.hostname === 'localhost' || u.hostname.endsWith('.local')) return resolve({ error: 'that address is not reachable from here' }); - dns.lookup(u.hostname, (de, addr) => { - if (de) return resolve({ error: 'that domain does not resolve' }); - if (PRIVATE_IP.test(addr)) return resolve({ error: 'that address is not reachable from here' }); - const mod = u.protocol === 'https:' ? https : http; - // Our own hosts (the app and the link domains) answer the curtain's 503 to anonymous fetches while the - // app is curtained, which made a test ad aimed at a spin link look dead (2026-10-07). Carry the pass. - const own = [SITE_HOST].concat(String(siteConfig().linkDomains || '').split(',').map(x => x.trim().toLowerCase()).filter(Boolean), pagesHost() ? [pagesHost()] : []); - const hdrs = { 'User-Agent': 'Mozilla/5.0 (compatible; LinkSpin-FrameCheck/1.0)', Accept: 'text/html' }; - if (CURTAIN && own.includes(u.hostname.toLowerCase())) hdrs.Cookie = 'ls.pass=' + encodeURIComponent(CURTAIN); - const rq = mod.get(u.href, { timeout: 8000, headers: hdrs }, r => { - const loc = r.headers.location; - r.resume(); // headers are all we need - if ([301, 302, 303, 307, 308].includes(r.statusCode) && loc && depth < 4) { - rq.destroy(); - let next; try { next = new URL(loc, u.href).href; } catch (e2) { return resolve({ error: 'it redirects somewhere invalid' }); } - return resolve(frameFetch(next, depth + 1)); // every hop re-runs the private-IP guard - } - resolve({ status: r.statusCode, xfo: r.headers['x-frame-options'] || '', csp: r.headers['content-security-policy'] || '' }); - rq.destroy(); - }); - rq.on('timeout', () => { rq.destroy(); resolve({ error: 'it did not answer within 8 seconds' }); }); - rq.on('error', e2 => resolve({ error: 'it did not answer (' + (e2.code || 'connection failed') + ')' })); - }); - }); -} -// shared upload path for member creatives (/api/my/upload) and admin house-ad -// creatives (/api/admin/upload): `who` keys the per-day upload counter -async function handleUpload(req, res, who) { - const ct = String(req.headers['content-type'] || '').split(';')[0].trim().toLowerCase(); - const EXT = { 'image/png': 'png', 'image/jpeg': 'jpg', 'image/webp': 'webp', 'image/gif': 'gif', - 'video/mp4': 'mp4', 'video/webm': 'webm' }; - if (!EXT[ct]) return json(res, 400, { error: 'Use a PNG, JPG, WebP, GIF, MP4 or WebM file.' }); - const isVideo = ct.startsWith('video/'); - const key = who + ':' + new Date().toISOString().slice(0, 10); - if ((uploadCounts.get(key) || 0) >= 10) return json(res, 400, { error: 'Upload limit for today reached (10 files).' }); - let buf; - try { buf = await readRaw(req, isVideo ? 25 * 1024 * 1024 : 3 * 1024 * 1024); } - catch (e) { return json(res, 400, { error: 'File too large. Images up to 3MB, video up to 25MB.' }); } - const magicOk = buf.length > 16 && ( - (ct === 'image/png' && buf[0] === 0x89 && buf[1] === 0x50 && buf[2] === 0x4e && buf[3] === 0x47) || - (ct === 'image/jpeg' && buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff) || - (ct === 'image/webp' && buf.slice(0, 4).toString() === 'RIFF' && buf.slice(8, 12).toString() === 'WEBP') || - (ct === 'image/gif' && buf.slice(0, 4).toString() === 'GIF8') || - (ct === 'video/mp4' && buf.slice(4, 8).toString() === 'ftyp') || - (ct === 'video/webm' && buf[0] === 0x1a && buf[1] === 0x45 && buf[2] === 0xdf && buf[3] === 0xa3)); - if (!magicOk) return json(res, 400, { error: 'That file does not look like a real ' + EXT[ct].toUpperCase() + '.' }); - const name = crypto.randomBytes(12).toString('hex') + '.' + EXT[ct]; - uploadCounts.set(key, (uploadCounts.get(key) || 0) + 1); - // video goes to DO Spaces when configured (keeps big files off the volume); - // images stay local. Falls back to the volume if Spaces isn't set or errors. - if (isVideo && spaces.enabled()) { - try { - const url = await spaces.put('iap-uploads/' + name, buf, ct); - return json(res, 200, { url, type: 'video' }); - } catch (e) { console.error('spaces put', e.message); /* fall through to volume */ } - } - fs.writeFileSync(path.join(UPLOADS_DIR, name), buf); - return json(res, 200, { url: '/uploads/' + name, type: isVideo ? 'video' : 'image' }); -} -// lead-capture page hooks (og tags + copy live in public/assets/join.js too) -const JOIN_ALIASES = { company: 'martbost', top: 'martbost' }; // neutral partner links -> the top position -const JOIN_ANGLES = { - // legacy bridge pages (/from/): former members of Marty's closed EvolutionScript sites - 'fw-adv': { t: 'Your next ad budget pays you back.', d: 'Faucet Wave closed. LinkSpin was built for the people who bought ads there: packages from $10, banner, text and login ads, every package in your line paid out on Polygon in the same transaction. Welcome-back credits waiting.', url: SITE_URL + '/from/faucetwave?seg=advertiser' }, - 'fw-earn': { t: 'Same daily habit. Real payouts on-chain.', d: 'You viewed ads on Faucet Wave. Here you view ads to earn credits, run your own campaign free, and get paid in POL to your own wallet when your line buys ads. Welcome-back credits waiting.', url: SITE_URL + '/from/faucetwave' }, - 't1-adv': { t: 'Your next ad budget pays you back.', d: 'Tier One Ads closed. LinkSpin was built for the people who bought ads there: packages from $10, banner, text and login ads, every package in your line paid out on Polygon in the same transaction. Welcome-back credits waiting.', url: SITE_URL + '/from/tieroneads?seg=advertiser' }, - 't1-earn': { t: 'Same daily habit. Real payouts on-chain.', d: 'You viewed ads on Tier One Ads. Here you view ads to earn credits, run your own campaign free, and get paid in POL to your own wallet when your line buys ads. Welcome-back credits waiting.', url: SITE_URL + '/from/tieroneads' }, - instant: { t: 'Paid before the page reloads.', d: 'A smart contract on Polygon splits every ad package the moment it sells. Same transaction, real wallets, public ledger. Join free by email.' }, - adspend: { t: 'You were buying ads anyway.', d: 'Here the ad spend in your line pays you, in the same transaction, on a public ledger. Banner, text and login ads, packages from $10. Join free.' }, - free: { t: 'Watch first. Spend never.', d: 'Join free, view a few ads, earn credits, run your first campaign for zero dollars. Every payout public on Polygon.' }, - // LinkSpin-only hooks (2026-10-09), each with a video on the join page - links: { t: 'Stop juggling links.', d: 'One short link rotates every page you promote, with weights, hours and a fallback, and a report by source. Free, try a spin with no account.' }, - pages: { t: 'A bridge page in a minute.', d: 'Point LinkSpin at any offer, add one line in your words, and get a bridge, review or squeeze page on a clean domain. Leads are yours. Free.' }, - zones: { t: 'Your site pays you.', d: 'One script tag puts an ad slot on your website. Every viewable view pays you ad credits you spend on your own campaign. Nine sizes, free.' }, - audiences: { t: 'Retarget without renting an audience.', d: 'Everyone who sees your pages or zones is remembered for 30 days in an audience you own. Show a campaign only to them, or never to them.' }, - stack: { t: 'Three tools, zero dollars.', d: 'A link rotator, a bridge-page builder and an ad slot for your own site, free with an email. Buy a package only if you want more.' }, - ledger: { t: 'No back office. No payday.', d: 'Every payout is a public transaction on Polygon you can read yourself. Nothing is ever held. Join free by email.' }, - two: { t: 'Two buyers open level two.', d: 'Every direct buyer pays you 50 percent from their first package. Two qualifying buyers open level two, five open level three. Written in a verified contract.' } -}; -function serveJoinPage(res, tok, angle, ang, setCookies) { - let html; - try { html = fs.readFileSync(path.join(PUBLIC_DIR, 'join.html'), 'utf8'); } catch (e) { res.writeHead(404, baseHeaders({ 'Content-Type': 'text/plain' })); return res.end('Not found'); } - const base = SITE_URL; - const url = (ang && ang.url) || (base + '/join/' + tok + (angle ? '?v=' + angle : '')); - const title = ang ? ang.t : 'Advertise and earn. Paid on-chain, instantly.'; - const desc = ang ? ang.d : 'You are invited to LinkSpin: real ad packages with same-transaction payouts on Polygon, every payment public. Join free by email.'; - const escA = t => String(t).replace(/&/g, '&').replace(/"/g, '"').replace(/' - + '' // keeps ?v= so shares stay on the angle - + '' - + ''; - html = html.replace(/[^<]*<\/title>/, '<title>' + escA(title) + ' | LinkSpin' + og); - if (ang) html = html.replace('', ''); // angle pages: squeeze layout from the first paint - const headers = { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store, must-revalidate' }; - if (setCookies && setCookies.length) headers['Set-Cookie'] = setCookies; - res.writeHead(200, baseHeaders(headers)); - res.end(html); -} -async function frameCheck(url) { - const h = await frameFetch(url, 0); - if (h.error) return { ok: false, reason: 'We checked your URL and ' + h.error + '. Fix the URL and try again.' }; - if (h.status >= 400) return { ok: false, reason: 'Your URL answers with HTTP ' + h.status + '. Point the campaign at a working page.' }; - if (/deny|sameorigin/i.test(String(h.xfo))) - return { ok: false, reason: 'That site blocks framing (X-Frame-Options), so it would show members a blank page in the ad viewer. Use a landing page that allows framing.' }; - const fa = /frame-ancestors\s+([^;]+)/i.exec(String(h.csp)); - if (fa && !fa[1].split(/\s+/).some(x => { - const v = x.replace(/['"]/g, '').toLowerCase(); - return v === '*' || v === 'https:' || v.includes(SITE_HOST); - })) - return { ok: false, reason: 'That site blocks framing (CSP frame-ancestors), so it would show members a blank page in the ad viewer. Use a landing page that allows framing.' }; - return { ok: true }; -} -async function boot() { - await db.init({ dataDir: DATA_DIR }); // no-op without DATABASE_URL (JSON mode) - chain.init({ onEvent: ev => { attachNames([ev]).then(a => pushFeed(a[0])).catch(() => pushFeed(ev)); emailOnEvent(ev).catch(() => {}); telegramOnEvent(ev).catch(() => {}); - if (ev && ev.type === 'Purchase' && ev.buyerId) accounts.byMemberId(Number(ev.buyerId)).then(a => { if (a) return postbacks.convertFor(a.email, 'purchase', { payout: (Number(ev.priceCents) || 0) / 100, currency: 'USD', txid: ev.tx || '' }); }).catch(() => {}); } }); - auth.init({ dataDir: DATA_DIR, chain, isProd: IS_PROD, site: SITE_HOST }); - accounts.init({ dataDir: DATA_DIR }); - ads.init({ dataDir: DATA_DIR, chain }); - mailer.init({ dataDir: DATA_DIR }); - messages.init({ dataDir: DATA_DIR }); - reports.init({ dataDir: DATA_DIR }); - drip.init({ dataDir: DATA_DIR, mailer, accounts, chain, site: SITE_URL }); - chatbot.init({ dataDir: DATA_DIR, chain }); - setTimeout(() => ads.dailySweep().catch(e => console.error('sweep', e.message)), 60 * 1000); - setInterval(() => ads.dailySweep().catch(e => console.error('sweep', e.message)), 60 * 60 * 1000); - setInterval(() => ads.scheduleSweep().catch(e => console.error('schedule sweep', e.message)), 5 * 60 * 1000); // scheduled starts/ends - // follow-up email sequence: send whatever came due (every 10 min, first pass shortly after boot) - coach.init({ dataDir: DATA_DIR, chain, accounts, mailer, ads, tank, lb: () => leaderboard, siteConfig }); - 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 }); - 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) - health.init({ rotator, dataDir: DATA_DIR, notify: (email, subject, html) => messages.deliver(1, ADMIN_EMAIL || 'house@' + SITE_HOST, [email], subject, html) }); - setTimeout(() => health.tick().catch(e => console.error('health', e.message)), 2 * 60 * 1000); - setInterval(() => health.tick().catch(e => console.error('health', e.message)), 30 * 60 * 1000); - setInterval(() => { try { rotator.sweepDemos(); } catch (e) {} }, 60 * 60 * 1000); // unclaimed home-page demo spins expire after 24 h - postbacks.init({ dataDir: DATA_DIR, ownHosts, rotator, sources }); - sources.init({ dataDir: DATA_DIR, postbacks, rotator, catalogFile: path.join(ROOT, 'catalog', 'traffic-sources.json'), linkHost: () => { const hs = String(siteConfig().linkDomains || '').split(',').map(x => x.trim()).filter(Boolean); return hs[0] || SITE_HOST; } }); - zones.init({ dataDir: DATA_DIR, ads, siteHost: SITE_HOST }); - pages.init({ dataDir: DATA_DIR, ownHosts, imageBase: () => (IS_PROD ? 'https' : 'http') + '://' + SITE_HOST, openrouterKey: () => { if (process.env.OPENROUTER_API_KEY) return process.env.OPENROUTER_API_KEY.trim(); try { return fs.readFileSync(path.join(DATA_DIR, 'openrouter.key'), 'utf8').trim(); } catch (e) { return ''; } } }); - audiences.init({ dataDir: DATA_DIR }); - // link-domain pool: channels live in site.json (linkDomainChannels), check state in domains.json; a burn alerts the admin once - domains.init({ dataDir: DATA_DIR, siteConfig, saveSite: patch => fs.writeFileSync(SITE_FILE, JSON.stringify(Object.assign(siteConfig(), patch), null, 2)), - notify: async text => { const sc = siteConfig(); if (sc.telegramBotToken && sc.telegramAdminChatId) await telegramSend(sc.telegramAdminChatId, text); else if (ADMIN_EMAIL && mailer.hasKey()) await mailer.send(ADMIN_EMAIL, 'LinkSpin: link domain burned', text.replace(/<[^>]+>/g, '')); } }); - zonereport.init({ dataDir: DATA_DIR }); - snapshot.init({ dataDir: DATA_DIR, db, chain, siteConfig, send: async (c, t, th) => { await telegramSend(c, t, th); return true; } }); - setInterval(() => snapshot.tick().catch(e => console.error('snapshot', e.message)), 10 * 60 * 1000); - tank.init({ dataDir: DATA_DIR, chain, accounts, messages, mailer, site: SITE_URL }); - legacy.init({ dataDir: DATA_DIR }); - traffic.init({ dataDir: DATA_DIR }); - promos.init({ dataDir: DATA_DIR }); - blog.init({ dataDir: DATA_DIR }); - adminMember.init({ accounts, ads, chain, tank, legacy, promos, messages, dataDir: DATA_DIR }); - loadOpenTokens(); - syndicate.init({ dataDir: DATA_DIR, publicDir: PUBLIC_DIR, uploadsDir: UPLOADS_DIR }); - releases.init({ dataDir: DATA_DIR }); - toolkit.init({ dataDir: DATA_DIR, ads, accounts, siteConfig, coach, messages, promos, videomaker, chain }); - updates.init({ dataDir: DATA_DIR, accounts, releases, mailer, drip, sendy, adminEmail: ADMIN_EMAIL }); - audit.init({ dataDir: DATA_DIR, notify: text => { const sc = siteConfig(); if (sc.telegramBotToken && sc.telegramAdminChatId) telegramSend(sc.telegramAdminChatId, text).catch(() => {}); else if (ADMIN_EMAIL && mailer.hasKey()) mailer.send(ADMIN_EMAIL, 'LinkSpin: counter audit', text).catch(() => {}); } }); - setTimeout(() => audit.dailyTick(), 5 * 60 * 1000); setInterval(() => audit.dailyTick(), 24 * 60 * 60 * 1000); - videomaker.init({ dataDir: DATA_DIR, spaces, accounts }); - leaderboard.init({ chain, accounts, ads, dataDir: DATA_DIR, siteConfig, pushFeed, adminEmail: ADMIN_EMAIL, - notify: async text => { const sc = siteConfig(); if (!sc.telegramBotToken || !sc.telegramEchoChatId) return; await telegramSend(sc.telegramEchoChatId, text, sc.telegramEchoTopicId); if (String(sc.leaderboardAnnounceGeneral || '1') !== '0') await telegramSend(sc.telegramEchoChatId, text, null); } }); - setTimeout(() => leaderboard.rolloverTick().catch(e => console.error('leaderboard rollover', e.message)), 90 * 1000); - setInterval(() => leaderboard.rolloverTick().catch(e => console.error('leaderboard rollover', e.message)), 60 * 60 * 1000); - console.log('blog syndication:', syndicate.enabled() ? 'on (X + Instagram via Blotato)' : 'off (no blotato.key)'); - setInterval(() => tankNotifyTick().catch(e => console.error('tank notify', e.message)), 15 * 60 * 1000); // new tank arrivals -> Telegram - geo.init({ dataDir: DATA_DIR }).catch(e => console.error('geo init', e.message)); - setInterval(() => geo.refresh().catch(e => console.error('geo refresh', e.message)), 24 * 3600 * 1000); // monthly file, checked daily - setInterval(() => tank.sweep().catch(e => console.error('tank sweep', e.message)), 60 * 60 * 1000); // adoptions past their 7-day window - burner.init({ chain, ads, accounts }); - if (OUTBOUND_MAIL) { // the stall nudges are a mailing loop; do not even start it when mail is off - setTimeout(() => coach.nudgeTick().catch(e => console.error('coach', e.message)), 90 * 1000); - setInterval(() => coach.nudgeTick().catch(e => console.error('coach', e.message)), 60 * 60 * 1000); - } - setTimeout(() => burner.tick().catch(e => console.error('burner', e.message)), 45 * 1000); - setInterval(() => burner.tick().catch(e => console.error('burner', e.message)), 5 * 60 * 1000); - if (OUTBOUND_MAIL) { // same for the lead follow-up sequence - setTimeout(() => drip.tick().catch(e => console.error('drip', e.message)), 30 * 1000); - setInterval(() => drip.tick().catch(e => console.error('drip', e.message)), 10 * 60 * 1000); - } - // NAS reconcile: pull syndicated delivery into the unified credit pool - // (inert unless NAS_DB_* is set). Every 5 min after a short warm-up. - if (ads.nasEnabled()) { - console.log('NAS syndication enabled'); - setTimeout(() => ads.reconcileNas().catch(e => console.error('nas reconcile', e.message)), 90 * 1000); - setInterval(() => ads.reconcileNas().catch(e => console.error('nas reconcile', e.message)), 5 * 60 * 1000); - } -} - -function siteConfig() { - let saved = {}; - try { saved = JSON.parse(fs.readFileSync(SITE_FILE, 'utf8')); } catch (e) {} - return Object.assign({ - siteName: 'LinkSpin', - tagline: 'Advertise and earn. Locked in code, not promises.', - rehearsal: true, // shows the testnet banner; flipped off at mainnet launch - // payment-proof Telegram feed (blank = off) and the P&L pane's fixed monthly cost - telegramBotToken: '', telegramChatId: '', telegramTopicId: '', telegramEvents: 'payouts', telegramCtaUrl: SITE_URL + '/', - telegramEchoChatId: '', telegramEchoTopicId: '', telegramEchoEvents: 'payouts', // shared cross-program payments topic - telegramAdminChatId: '', // private chat for admin alerts (sign-up guard bursts); falls back to ADMIN_EMAIL - launchAt: '', // public launch moment, ISO 8601 with offset (e.g. 2026-09-18T19:00:00-05:00): countdown on /launch + dashboard mark - aiCreditsPerGen: 10, aiFreeSurge: 20, aiFreeCircuit: 60, aiFreeNexus: 150, // AI Copy Engine: free generations per month by badge, then credits per generation - carryClaimDays: '3', - carryNotices: '1', // 0 = carry-over notices stay on-site (test area), 1 = email too // sponsor with no wallet: days to link one before a downline seat walks up (LinkSpin) - linkDomains: '', // comma list of short link domains this server answers for (each gets a real mini-site + /r/ redirects) - pagesDomain: '', // the host member pages are published on at the root (https:///); empty = first link domain under /p/ - snapshotEnabled: '1', snapshotHourUtc: '14', snapshotTargets: 'feed,echo', // daily growth snapshot: 14 UTC = 9 AM Central; feed = proof channel, echo = shared payments topic - pipelineMode: 'off', // Pipeline board: off = 'coming soon' card, preview = only the admin account sees the live board, on = everyone (Marty, 2026-09-15) - pipelineEta: 'Sep 28', // what the coming-soon card and the roadmap promise - coachMail: '1', // 0 = stall-nudge emails off (pre-launch: imported shell accounts must not be nudged) - memberWeeklyEmail: '0', // 1 = the weekly 'Your week on LinkSpin' email goes to every active member, not only sponsors with a line - noPayoutIds: '25', // positions kept for linkage only (compromised wallets): no buys signed from them, no new joins routed under them or their upline chain (Marty, 2026-09-14) - leaderboardWeeklyPrize: '', leaderboardMonthlyPrize: '', leaderboardWeeklyCredits: '1000,500,250', leaderboardMonthlyCredits: '5000,2500,1000', leaderboardAnnounceGeneral: '1', // referral contest prizes (text shown on /leaderboard; credits granted to the winner automatically at rollover) - legacyCreditsAdvertiser: 500, legacyCreditsEarner: 150, // welcome-back credits for listed Faucet Wave / Tier One Ads emails arriving via /from/ - geoTier1: '', // comma-separated ISO country codes; empty = built-in default (US, CA, GB, AU, NZ, IE, DE, FR, NL, SE, NO, DK, FI, CH, AT, BE) - geoTier2: '', // empty = built-in default (rest of Western/Central Europe, JP, KR, SG, HK, TW, IL, Gulf, ZA, BR, MX, AR, CL, CO ...); tier 3 = everything else - pnlFixedMonthlyUsd: 0 - }, saved); -} - -// ---- helpers ---- -const MIME = { '.html': 'text/html; charset=utf-8', '.css': 'text/css', '.js': 'text/javascript', - '.png': 'image/png', '.jpg': 'image/jpeg', '.svg': 'image/svg+xml', '.webp': 'image/webp', - '.ico': 'image/x-icon', '.json': 'application/json', '.mp4': 'video/mp4', '.woff2': 'font/woff2', - '.gif': 'image/gif', '.webm': 'video/webm', '.txt': 'text/plain; charset=utf-8', '.xml': 'application/xml; charset=utf-8' }; -const CSP = "default-src 'self'; script-src 'self' https://cdn.jsdelivr.net 'sha256-NzvNrqk5jB9YZATwo5BF4JoRlJ02HsnFikbKXgEPdaQ='; worker-src 'self' blob:; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; img-src 'self' data: blob: https:; media-src 'self' https: blob:; connect-src 'self' https://*.walletconnect.com wss://*.walletconnect.com https://*.walletconnect.org wss://*.walletconnect.org https://*.reown.com wss://*.reown.com https://*.reown.org wss://*.reown.org https://*.web3modal.org https://*.drpc.org https://*.publicnode.com https://*.coinbase.com; font-src 'self' data: https://fonts.gstatic.com https://fonts.reown.com; form-action 'self'; frame-src https: http:"; -function baseHeaders(extra) { - return Object.assign({ 'Content-Security-Policy': CSP, 'X-Content-Type-Options': 'nosniff', - 'Referrer-Policy': 'strict-origin-when-cross-origin' }, extra || {}); -} -function json(res, code, obj, extra) { - const body = JSON.stringify(obj); - res.writeHead(code, baseHeaders(Object.assign({ 'Content-Type': 'application/json', 'Cache-Control': 'no-store' }, extra))); - res.end(body); -} -function sendFile(res, file) { - fs.readFile(file, (err, data) => { - if (err) { res.writeHead(404, baseHeaders({ 'Content-Type': 'text/plain' })); return res.end('Not found'); } - const ext = path.extname(file).toLowerCase(); - // Public pages carry {{SITE_URL}} / {{SITE_HOST}} in canonical, OG and sitemap lines so the same files - // serve every deployment (test host today, linkspin.app at launch); filled here, per request. - if (ext === '.html' || ext === '.txt' || ext === '.xml') data = Buffer.from(data.toString('utf8').split('{{SITE_URL}}').join(SITE_URL).split('{{SITE_HOST}}').join(SITE_HOST)); - res.writeHead(200, baseHeaders({ 'Content-Type': MIME[ext] || 'application/octet-stream', - // HTML is never stored (so a fresh load always gets the current asset - // versions — aggressive in-app wallet browsers were serving stale pages - // that pointed at old, since-fixed JS); versioned assets cache for an hour. - 'Cache-Control': ext === '.html' ? 'no-store, must-revalidate' : 'public, max-age=3600' })); - res.end(data); - }); -} -function readRaw(req, maxBytes) { - return new Promise((resolve, reject) => { - const chunks = []; - let n = 0; - req.on('data', c => { - n += c.length; - if (n > maxBytes) { req.destroy(); reject(new Error('too big')); return; } - chunks.push(c); - }); - req.on('end', () => resolve(Buffer.concat(chunks))); - req.on('error', reject); - }); -} -function readBody(req) { - return new Promise((resolve, reject) => { - let d = ''; let n = 0; - req.on('data', c => { n += c.length; if (n > 64 * 1024) { req.destroy(); reject(new Error('too big')); } d += c; }); - req.on('end', () => { try { resolve(d ? JSON.parse(d) : {}); } catch (e) { reject(e); } }); - req.on('error', reject); - }); -} -function parseCookies(req) { - const out = {}; - for (const p of (req.headers.cookie || '').split(';')) { - const i = p.indexOf('='); if (i > 0) out[p.slice(0, i).trim()] = decodeURIComponent(p.slice(i + 1).trim()); - } - return out; -} -function isAdmin(req) { - const h = req.headers.authorization || ''; - if (h === 'Bearer ' + ADMIN_PASSWORD) return true; - return !!adminFromRequest(req); // /admin portal session -} -// attach a memberId->username map to events so activity shows real people -async function attachNames(evts) { - try { - const ids = []; - for (const ev of evts) - for (const k of ['id', 'buyerId', 'recipientId', 'skippedId', 'sponsorId', 'newBuyerId', 'toId', 'memberId']) - if (ev[k]) ids.push(ev[k]); - const names = await accounts.namesForMembers(ids); - if (!Object.keys(names).length) return evts; - return evts.map(ev => Object.assign({}, ev, { names })); - } catch (e) { return evts; } -} -// A sponsor token is a numeric chain id or a site share code. Codes resolve -// to the referrer's CURRENT chain id, so activation any time before the -// referral's first purchase still locks the line to them. -// No-payout positions (siteConfig.noPayoutIds): a member id whose on-chain wallet must never be paid again. -// A purchase pays the buyer's three uplines, so a buy from `id` is blocked when id itself or any of its three -// uplines is listed; a join under `id` is blocked when id or its two uplines is listed (the new member's buys -// would reach the listed wallet at tier 2 or 3). Returns the listed id that would be hit, else 0. -function noPayoutSet() { return new Set(String(siteConfig().noPayoutIds || '').split(/[,\s]+/).map(Number).filter(n => n > 0)); } -async function payoutChainBlocked(id, hops) { - const bad = noPayoutSet(); if (!bad.size || !id) return 0; - let cur = Number(id); - for (let i = 0; i <= hops && cur; i++) { if (bad.has(cur)) return cur; let m = null; try { m = await chain.member(cur); } catch (e) { break; } cur = m ? Number(m.sponsorId) || 0 : 0; } - return 0; -} -// Why a sponsor token did not resolve matters (vladz79 → #24 locked under the company on 2026-09-13 because a -// lookup came back empty and the code fell back silently): 'ok' | 'none' (no token) | 'unknown' (no such account) -// | 'notActivated' (sponsor has no wallet / payouts off) | 'rpc' (chain lookup failed right now). -async function resolveSponsorDetailed(tok) { - const t = String(tok || '').trim().toLowerCase(); - if (!t) return { id: 0, reason: 'none' }; - if (/^\d+$/.test(t)) return { id: Number(t), reason: 'ok' }; - let acct = await accounts.byCode(t); - if (!acct) acct = await accounts.byUsername(t); // vanity links: /join/ - if (!acct) return { id: 0, reason: 'unknown', name: t }; - if (!acct.address) return { id: 0, reason: 'notActivated', name: acct.username ? '@' + acct.username : t }; - try { const id = await chain.memberIdByAccount(acct.address); return { id, reason: id ? 'ok' : 'notActivated', name: acct.username ? '@' + acct.username : t }; } - catch (e) { return { id: 0, reason: 'rpc', name: acct.username ? '@' + acct.username : t }; } -} -async function resolveSponsorToken(tok) { return (await resolveSponsorDetailed(tok)).id; } -const sponsorAlertLast = new Map(); // email -> ts (one alert per member per hour) -function sponsorBlockedAlert(who, r) { - const k = String(who || '?'); if (Date.now() - (sponsorAlertLast.get(k) || 0) < 3600000) return; sponsorAlertLast.set(k, Date.now()); - const text = '\u26A0\uFE0F LinkSpin: purchase held for ' + k.replace(/^(.{2}).*(@.*)$/, '$1***$2') + '. Their sponsor ' + (r.name || r.tok || '?') + ' could not be resolved (' + r.reason + '), so the buy was blocked instead of crediting the company. ' + (r.reason === 'notActivated' ? 'The sponsor needs to switch on payouts.' : r.reason === 'rpc' ? 'Chain lookup failed; they can retry.' : 'Check the sponsor field in Admin > Members.'); - const sc = siteConfig(); - if (sc.telegramBotToken && sc.telegramAdminChatId) telegramSend(sc.telegramAdminChatId, text).catch(() => {}); - else if (ADMIN_EMAIL && mailer.hasKey()) mailer.send(ADMIN_EMAIL, 'LinkSpin: purchase held, sponsor unresolved', text).catch(() => {}); -} -// The moment someone joins through a code, nudge its owner to activate. -// Email a member's sponsor the moment they get a new referral (free OR paid). -// Resolves the sponsor from the join token by member id, share code, or username, -// and notifies EVERY sponsor — activated or not (an active sponsor still wants to -// know their team grew). A referral is on the line from signup; it only counts -// toward qualification once it makes a $20+ purchase. -async function notifyNewReferral(ref, newAcct) { - try { - if (!mailer.hasKey()) return; - const t = String(ref || '').trim().toLowerCase(); - if (!t) return; - let owner = null; - if (/^\d+$/.test(t)) { try { owner = await accounts.byMemberId(Number(t)); } catch (e) {} } - if (!owner) { try { owner = await accounts.byCode(t); } catch (e) {} } - if (!owner) { try { owner = await accounts.byUsername(t); } catch (e) {} } - if (!owner || !owner.email) return; - const who = newAcct && newAcct.username ? '@' + newAcct.username : 'A new member'; - let body = who + ' just joined LinkSpin through your link — they are on your team from today.\n\n' - + 'They count toward your qualification once they make a $20+ purchase.\n\n'; - if (!owner.address) body += 'Make sure payouts are switched on (one free wallet step) so you never miss a commission — ' - + 'the contract locks each buyer to their sponsor at their first purchase.\n\n'; - body += 'See your team: ' + SITE_URL + '/team\n\nLinkSpin'; - mailer.send(owner.email, 'You have a new referral on LinkSpin', body) - .catch(e => console.error('referral notify failed', e.message)); - } catch (e) {} -} -// welcome email on a new account: onboarding steps + who their sponsor is -// how a member is named in emails/alerts: @username, a linked position named after its owner, else member #id -async function memberLabel(id) { - try { - let a = await accounts.byMemberId(id); - if (!a) { // brand-new buyer: the account learns its member id on its next page load, so read the - // wallet from the chain and match it now (Jim's purchase mailed as "member #25", 2026-09-13) - try { const m = await chain.member(id); if (m && m.account) { a = await accounts.byAddress(String(m.account).toLowerCase()); if (a && !a.memberId) accounts.setMemberId(a.email, id).catch(() => {}); } } catch (e) {} - } - if (a && a.username) return '@' + a.username; - const pos = await accounts.positionByMember(id); - if (pos && pos.email) { const o = await accounts.byEmail(pos.email); if (o && o.username) return '@' + o.username + ' (extra position #' + id + ')'; } - } catch (e) {} - return 'member #' + id; -} -async function sendWelcome(email, ref) { - try { - if (!mailer.hasKey()) return; - const spon = await accounts.sponsorOf(email); - const who = spon ? (spon.username ? '@' + spon.username : 'member #' + (spon.memberId || 0)) : ''; - const sponsorLine = who ? ('You joined through ' + who + ', your sponsor. They are there to help you get started, and you can message them anytime from your dashboard.\n\n') : ''; - mailer.send(email, 'Welcome to LinkSpin', - 'Your free LinkSpin account is ready.\n\n' + sponsorLine - + 'Getting started:\n' - + '1. Pick your username and fill out your profile.\n' - + '2. Grab your invite link and start sharing to build your line.\n' - + '3. Explore the ad packages when you are ready. Every payout settles on-chain, straight to your wallet.\n\n' - + 'Sign in anytime: ' + SITE_URL + '/links\n\nLinkSpin').catch(() => {}); - } catch (e) {} -} -// on-chain event emails: a payout received, or a payout that passed you by -const weiToPol = w => { try { return (Number(BigInt(w) / (10n ** 14n)) / 10000).toString(); } catch (e) { return '?'; } }; -async function emailOnEvent(ev) { - if (!ev) return; - const notify = async (memberId, subject, body) => { - if (!memberId || !mailer.hasKey()) return; - const a = await accounts.byMemberId(memberId); - if (a && a.email) mailer.send(a.email, subject, body + '\n\nSee it on the live ledger: ' + SITE_URL + '/ledger\n\nLinkSpin').catch(() => {}); - }; - // Marty (2026-09-15): payment and missed-payment notices also land in the on-site inbox, so - // they are waiting (login modal + Messages card) whether or not the email was read. Sent as - // the company account (#1), the same sender the credit-return notes used. Plain text in, HTML out. - const inboxNote = async (memberId, subject, text) => { - if (!memberId) return; - try { - const a = await accounts.byMemberId(memberId); - if (!a || !a.email) return; - const html = '

' + String(text).replace(/&/g, '&').replace(//g, '>') - .replace(/(https:\/\/[^\s]+)/g, '$1').split('\n\n').join('

').replace(/\n/g, '
') + '

'; - await messages.deliver(1, ADMIN_EMAIL || 'house@' + SITE_HOST, [a.email], subject, html); - } catch (e) {} - }; - const tell = async (memberId, subject, text) => { await notify(memberId, subject, text); await inboxNote(memberId, subject, text); }; - const PCT = { 1: 50, 2: 20, 3: 10 }; - // the Purchase event of the same tx is already indexed (it precedes every payout log), so the - // dollar side of any share is that purchase's price times the tier percentage - const purchaseOf = tx => { try { return chain.recentEvents(600).find(e => e.tx === tx && e.type === 'Purchase'); } catch (e) { return null; } }; - const usdShare = (pur, pct) => pur ? (' (about ' + ('$' + (pur.priceCents * pct / 10000).toFixed(2)).replace(/\.00$/, '') + ')') : ''; - const txUrlOf = tx => { const cc = chain.getConfig(); return (cc.explorer ? cc.explorer.replace(/\/+$/, '') : 'https://polygonscan.com') + '/tx/' + tx; }; - if (ev.type === 'Purchase') { - const cc = chain.getConfig(); - const txUrl = (cc.explorer ? cc.explorer.replace(/\/+$/, '') : 'https://polygonscan.com') + '/tx/' + ev.tx; - let bal = ev.creditAmount; - try { bal = await chain.creditBalance(ev.buyerId, ev.creditType); } catch (e) {} - await notify(ev.buyerId, 'Your LinkSpin purchase is confirmed', - 'Your purchase is complete and settled on-chain.\n\n' + - 'Ad credits added: ' + ev.creditAmount + '\n' + - 'Your ad-credit balance is now: ' + bal + '\n' + - 'Amount paid: ' + weiToPol(ev.paidWei) + ' POL\n\n' + - 'View your transaction on the blockchain:\n' + txUrl); - // tell the buyer's DIRECT sponsor their referral just bought (upline earners - // are separately notified by the TierPaid payout email when they earn) - try { - const buyer = await chain.member(ev.buyerId); - if (buyer && buyer.sponsorId) { - const sp = await accounts.byMemberId(buyer.sponsorId); - if (sp && sp.email) { - const bn = await memberLabel(ev.buyerId); // @username at a glance (Marty, 2026-09-12) - const usd = ('$' + (ev.priceCents / 100).toFixed(2)).replace(/\.00$/, ''); - const qual = ev.priceCents >= 2000 - ? ' This is a $20+ purchase, so it counts toward your qualification.' - : ' (Purchases under $20 do not count toward qualification.)'; - mailer.send(sp.email, bn + ' just bought a ' + usd + ' ad package', - 'Your referral ' + bn + ' (member #' + ev.buyerId + ') just purchased a package (' + usd + ' — ' + ev.creditAmount + ' credits).' + qual + '\n\n' + - 'See your team and the live ledger: ' + SITE_URL + '/team\n\nLinkSpin').catch(() => {}); - } - } - } catch (e) {} - } - else if (ev.type === 'TierPaid') { - const pct = PCT[ev.tier] || 0; const pur = purchaseOf(ev.tx); - let buyer = 'a member on your level ' + ev.tier; try { buyer = await memberLabel(ev.buyerId); } catch (e) {} - const pol = weiToPol(ev.amountWei); - await tell(ev.recipientId, 'You just got paid ' + pol + ' POL on LinkSpin', - buyer + ' just bought an ad package on your level ' + ev.tier + (pur ? ' ($' + (pur.priceCents / 100).toFixed(2).replace(/\.00$/, '') + ')' : '') + '. Your ' + pct + ' percent share, ' + pol + ' POL' + usdShare(pur, pct) + ', landed in your wallet in the same transaction' + (ev.hops ? ', passed up to you because someone between you was not qualified for this level' : '') + '.\n\n' + - 'Transaction: ' + txUrlOf(ev.tx) + '\n\nYour wallet and payouts: ' + SITE_URL + '/wallet'); - } - else if (ev.type === 'AwardPaid') await tell(ev.toId, 'You just got paid ' + weiToPol(ev.amountWei) + ' POL on LinkSpin', weiToPol(ev.amountWei) + ' POL just landed in your wallet.\n\nTransaction: ' + txUrlOf(ev.tx) + '\n\nYour wallet and payouts: ' + SITE_URL + '/wallet'); - else if (ev.type === 'PassedUp' && ev.reason === 'send-failed') { - // the member WAS qualified but their wallet rejected the POL (usually a smart-contract - // wallet that needs more than the capped gas): tell them and the admin, loudly - await tell(ev.skippedId, 'Your wallet rejected a payout on LinkSpin', 'A level-' + ev.tier + ' payout tried to reach your linked wallet and the wallet refused the transfer, so it passed to the next qualified member. This happens with some smart-contract wallets. Link a regular wallet address (MetaMask, SafePal, Phantom) on the Wallet tab so the next payout lands.\n\nTransaction: ' + txUrlOf(ev.tx)); - if (ADMIN_EMAIL) mailer.send(ADMIN_EMAIL, 'LinkSpin: payout send-failed for member #' + ev.skippedId, 'A level-' + ev.tier + ' payout to member #' + ev.skippedId + ' failed at the wallet (send-failed) and passed up. Tx: ' + ev.tx + '\n\nThe member has been emailed to link a regular wallet.').catch(() => {}); - } - else if (ev.type === 'PassedUp') { - // Marty (2026-09-15): a member who missed a payout because they were not qualified must be told - // exactly what they missed: who bought, the share in POL and dollars, and how to close the gap. - const pct = PCT[ev.tier] || 0; const pur = purchaseOf(ev.tx); - let pol = '', buyer = 'a member on your level ' + ev.tier; - try { if (pur) pol = weiToPol((BigInt(pur.paidWei) * BigInt(pct) / 100n).toString()); buyer = await memberLabel(ev.buyerId); } catch (e) {} - let bc = 0; try { bc = (await chain.member(ev.skippedId)).buyerCount || 0; } catch (e) {} - const need = ev.tier === 3 ? 5 : 2, short = Math.max(0, need - bc); - const what = pol ? pol + ' POL' + usdShare(pur, pct) : 'a level-' + ev.tier + ' payout'; - await tell(ev.skippedId, 'You missed ' + (pol ? pol + ' POL' : 'a payout') + ' on LinkSpin', - buyer + ' just bought an ad package on your level ' + ev.tier + '. Your share was ' + what + ', and it passed you by because level ' + ev.tier + ' is not open on your account yet. The contract paid it to the next qualified person above you.\n\n' + - 'Level ' + ev.tier + ' opens at ' + need + ' qualifying buyers (people you referred who bought a $20 or larger package). You have ' + bc + (short ? ', so you are ' + short + ' buyer' + (short === 1 ? '' : 's') + ' away.' : '.') + '\n\n' + - 'Two ways to close the gap: bring ' + (short || 1) + ' more buyer' + (short === 1 ? '' : 's') + ' from your My line page, or use Qualified Start under Buy packages to be your own buyer today. Every package on level ' + ev.tier + ' pays you ' + pct + ' percent once it is open, and the next one is coming whether you are ready or not.\n\n' + - 'Transaction: ' + txUrlOf(ev.tx) + '\n\nYour wallet and payouts: ' + SITE_URL + '/wallet'); - } -} -// payment-proof Telegram feed (same pattern as the RM Circle proof channel): one compact -// line per event, admin-configured under Settings > Site (telegramBotToken, telegramChatId, -// optional telegramTopicId, telegramEvents = payouts | payouts+purchases | all, telegramCtaUrl) -// A second target, telegramEchoChatId + telegramEchoTopicId (+ telegramEchoEvents), echoes -// the same lines into a shared cross-program payments topic that RM Circle also posts to, -// so every line there carries the program name. -async function telegramOnEvent(ev) { - const sc = siteConfig(); - if (!sc.telegramBotToken || !ev) return; - if (!sc.telegramChatId && !sc.telegramEchoChatId) return; - const names = await accounts.namesForMembers([ev.recipientId, ev.buyerId, ev.sponsorId, ev.newBuyerId, ev.id].filter(Boolean)).catch(() => ({})); - const who = id => '#' + id + (names[id] ? ' @' + names[id] : ''); - const cc = chain.getConfig(); - const tx = (cc.explorer ? cc.explorer.replace(/\/+$/, '') : 'https://polygonscan.com') + '/tx/' + ev.tx; - const build = (mode) => { - let line = null; - if (ev.type === 'TierPaid') line = '\u{1F4B8} Level ' + ev.tier + ' payout: ' + weiToPol(ev.amountWei) + ' POL \u2192 ' + who(ev.recipientId); - else if (ev.type === 'BuyerCounted' && mode !== 'payouts') line = '\u2B50 ' + who(ev.sponsorId) + ' now has ' + ev.newCount + ' qualifying buyer' + (ev.newCount === 1 ? '' : 's') + (ev.newCount === 2 ? ' \u00b7 level 2 open' : ev.newCount === 5 ? ' \u00b7 level 3 open' : ''); - else if (ev.type === 'Purchase' && mode !== 'payouts') line = '\u{1F9FE} ' + who(ev.buyerId) + ' bought a $' + Math.round(ev.priceCents / 100) + ' package'; - else if (ev.type === 'AwardPaid') line = '\u{1F4B8} Award payout: ' + weiToPol(ev.amountWei) + ' POL \u2192 ' + who(ev.toId); - else if (ev.type === 'MemberActivated' && mode === 'all') line = '\u{1F91D} ' + who(ev.id) + ' switched on payouts'; - if (!line) return null; - return line + ' \u00b7 verify' + (sc.telegramCtaUrl ? '\nJoin free' : ''); - }; - if (sc.telegramChatId) { const t = build(String(sc.telegramEvents || 'payouts')); if (t) await telegramSend(sc.telegramChatId, t, sc.telegramTopicId); } - if (sc.telegramEchoChatId) { const t = build(String(sc.telegramEchoEvents || 'payouts')); if (t) await telegramSend(sc.telegramEchoChatId, '\u{1F7E0} LinkSpin \u00b7 ' + t, sc.telegramEchoTopicId); } -} -// holding-tank arrivals -> one digest line in the shared payments topic (Marty, 2026-09-12): who is -// waiting for a sponsor, by username, so builders go adopt them. Runs every 15 min, posts only -// when someone new landed since the last check. -async function tankNotifyTick() { - const sc = siteConfig(); - if (!sc.telegramBotToken || !sc.telegramEchoChatId) return; - const f = path.join(DATA_DIR, 'tank-notify.json'); - let st = { last: 0 }; try { st = JSON.parse(fs.readFileSync(f, 'utf8')); } catch (e) {} - const since = st.last || (Date.now() - 24 * 3600 * 1000); - const fresh = (await tank.waiting()).filter(w => (w.joined || 0) > since); - st.last = Date.now(); fs.writeFileSync(f, JSON.stringify(st)); - if (!fresh.length) return; - const named = fresh.filter(w => w.username).map(w => '@' + w.username); - const who = named.length ? ': ' + named.slice(0, 8).join(', ') + (named.length > 8 ? ' and ' + (named.length - 8) + ' more' : '') : ''; - const text = '\u{1FAA3} LinkSpin \u00b7 ' + fresh.length + ' new member' + (fresh.length === 1 ? '' : 's') + ' waiting for a sponsor in the holding tank' + who - + '\nAdopt from Team \u203a Waiting on a wallet: ' + SITE_HOST + '/team'; - await telegramSend(sc.telegramEchoChatId, text, sc.telegramEchoTopicId); -} -// one sendMessage call; never throws, never logs the token -async function telegramSend(chatId, text, threadId) { - const sc = siteConfig(); - if (!sc.telegramBotToken || !chatId) return; - const body = JSON.stringify(Object.assign({ chat_id: chatId, text, parse_mode: 'HTML', disable_web_page_preview: true }, threadId ? { message_thread_id: Number(threadId) } : {})); - await new Promise((resolve) => { - const rq = https.request({ hostname: 'api.telegram.org', path: '/bot' + sc.telegramBotToken + '/sendMessage', method: 'POST', headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(body) }, timeout: 10000 }, r => { r.resume(); r.on('end', resolve); }); - rq.on('error', () => resolve()); rq.on('timeout', () => { rq.destroy(); resolve(); }); rq.end(body); - }); -} - -// photo post (multipart) for the achievement badges (Marty, 2026-09-13); same bot, sendPhoto only -async function telegramSendPhoto(chatId, jpeg, caption, threadId) { - const sc = siteConfig(); - if (!sc.telegramBotToken || !chatId || !jpeg) return false; - const B = '----iapbadge' + crypto.randomBytes(8).toString('hex'); - const field = (n, v) => Buffer.from('--' + B + '\r\nContent-Disposition: form-data; name="' + n + '"\r\n\r\n' + v + '\r\n'); - const parts = [field('chat_id', String(chatId)), field('caption', caption), field('parse_mode', 'HTML')]; - if (threadId) parts.push(field('message_thread_id', String(Number(threadId)))); - parts.push(Buffer.from('--' + B + '\r\nContent-Disposition: form-data; name="photo"; filename="badge.jpg"\r\nContent-Type: image/jpeg\r\n\r\n'), jpeg, Buffer.from('\r\n--' + B + '--\r\n')); - const body = Buffer.concat(parts); - return new Promise((resolve) => { - const rq = https.request({ hostname: 'api.telegram.org', path: '/bot' + sc.telegramBotToken + '/sendPhoto', method: 'POST', headers: { 'Content-Type': 'multipart/form-data; boundary=' + B, 'Content-Length': body.length }, timeout: 20000 }, res => { - let out = ''; res.on('data', c => out += c); res.on('end', () => resolve(res.statusCode === 200)); - }); - rq.on('error', () => resolve(false)); rq.on('timeout', () => { rq.destroy(); resolve(false); }); rq.end(body); - }); -} -const BADGE_META = { payouts: ['Spark', 'payouts switched on'], firstBuyer: ['Surge', 'first qualifying buyer'], level2: ['Circuit', 'two qualifying buyers, level 2 open'], level3: ['Nexus', 'five qualifying buyers, fully qualified'] }; -const BADGE_LOG = () => path.join(DATA_DIR, 'badge-posts.json'); -function badgeLog() { try { return JSON.parse(fs.readFileSync(BADGE_LOG(), 'utf8')); } catch (e) { return {}; } } - -// ---- live feed (SSE) ---- -const feedClients = new Set(); -function pushFeed(ev) { - const line = 'data: ' + JSON.stringify(ev) + '\n\n'; - for (const res of feedClients) { try { res.write(line); } catch (e) { feedClients.delete(res); } } -} - -// ---- short link domains (LinkSpin): each domain in siteConfig().linkDomains is a small real site ---- -function reqHost(req) { return String(req.headers['x-forwarded-host'] || req.headers.host || '').split(',')[0].trim().toLowerCase().replace(/:\d+$/, '').replace(/^www\./, ''); } -function pagesHost() { return String(siteConfig().pagesDomain || '').trim().toLowerCase().replace(/^www\./, '') || null; } -function isPagesHost(req) { const h = pagesHost(); return !!h && reqHost(req) === h; } -function isLinkHost(req) { const h = reqHost(req); if (!h) return false; return String(siteConfig().linkDomains || '').split(',').map(x => x.trim().toLowerCase()).filter(Boolean).includes(h); } -function linkSitePage(host, page) { - const esc = t => String(t).replace(/&/g, '&').replace(/' + H + '

This domain is a link forwarding service operated by ' + brand + ', a member advertising network. Links on this domain forward visitors in one step to pages published by our members and their partners.

We do not host the pages you land on, and we do not collect payment information here. If a link forwarded you somewhere you did not expect, or to content that looks unsafe, tell us on the report page and we will pull the link.

What we record

When a link is followed we record the day, the country, the referring site, the device type and a one-day anonymous visitor token. We do not store your IP address or any personal data. Details are in the privacy policy.

', - disclosure: '

Affiliate and advertising disclosure

Links forwarded through ' + H + ' may be affiliate links or paid advertisements. The member who published a link may earn a commission or advertising credit if you buy something or sign up on the page you land on. This never changes the price you pay.

' + brand + ' itself is an advertising platform. Members buy ad packages and earn commissions when people they referred buy ad packages. No income is guaranteed to anyone; results depend on effort, and any earnings examples on member pages are illustrations, not promises.

The pages you are forwarded to belong to their publishers. We are not responsible for their claims, and we remove links that are reported and found to violate our terms.

', - terms: '

Terms of use

By following a link on ' + H + ' you agree to these terms.

The service

' + H + ' forwards visitors to destinations chosen by ' + brand + ' members. We provide the forwarding only. We do not endorse, verify or control the destination pages, and we are not a party to any transaction you make there.

Acceptable use

Members may not forward visitors to content that is illegal, deceptive, malicious, adult, or that impersonates another business. Links that violate this are removed and the member\'s account is closed. Automated access to this domain is not permitted except by search engines.

No warranty

The service is provided as is. We do not guarantee that any link will be available, and we are not liable for the content, availability or conduct of destination sites.

Contact

Questions about these terms: linkspin.co.

', - privacy: '

Privacy policy

This policy covers ' + H + ' and the link forwarding service on it.

What we collect

When you follow a link we record the date, your country (derived from your network address and then discarded), the site that referred you, whether you are on a phone or a computer, and an anonymous visitor token that changes every day and cannot be traced back to you. We do not store your IP address, your name, your email address or any account information on this domain.

Cookies

This domain sets no cookies. The page you are forwarded to has its own privacy policy and may set its own.

Why we collect it

So members can see how many people followed their links and from where. Counts are shown to the member who published the link, in aggregate, and to nobody else.

Retention

Link statistics are kept for up to thirteen months and then deleted.

Your rights

Because we hold no personal data on this domain there is nothing to access or delete here. For anything involving a ' + brand + ' member account, contact us through linkspin.co.

', - abuse: '

Report a link

If a link on ' + H + ' forwarded you to a page that is deceptive, unsafe, adult, or impersonates a business, tell us. We review every report and pull the link first, then ask questions.

Send the full link you clicked (it starts with https://' + H + '/r/) and what you saw, to the support contact on linkspin.co. Reports are usually handled the same day.

', - gone: '

That link is not active

The link you followed has been removed or has expired. Nothing was recorded. If you were expecting a specific page, ask the person who shared the link for a fresh one.

' - }; - return '' + H + '
' + nav + (bodies[page] || bodies.gone) + '
'; -} - -// ---- server ---- -// ---- the curtain ---------------------------------------------------------- -// Work in progress is not for passers-by. CURTAIN= puts a contentless holding page -// in front of every request; ?k= sets a cookie that lifts it for that browser. -const CURTAIN = String(process.env.CURTAIN || '').trim(); -const CURTAIN_PAGE = ` - -Coming soon

Coming soon

This site is still being built.

`; - -function curtained(req, res, u) { - if (!CURTAIN) return false; - if (isLinkHost(req) || isPagesHost(req)) return false; // the short link domains and the pages domain stay public: spin links must redirect and the mini-site must answer while the main site is covered (Marty 2026-10-07: test traffic before launch) - if (u.searchParams.get('k') === CURTAIN) { - u.searchParams.delete('k'); - res.writeHead(302, { - 'Set-Cookie': 'ls.pass=' + encodeURIComponent(CURTAIN) + '; Path=/; Max-Age=2592000; HttpOnly; SameSite=Lax; Secure', - Location: u.pathname + (u.searchParams.toString() ? '?' + u.searchParams : ''), - 'Cache-Control': 'no-store' - }); - res.end(); - return true; - } - const pass = /(?:^|;\s*)ls\.pass=([^;]*)/.exec(req.headers.cookie || ''); - if (pass && decodeURIComponent(pass[1]) === CURTAIN) return false; - res.writeHead(503, { - 'Content-Type': 'text/html; charset=utf-8', - 'Cache-Control': 'no-store', - 'X-Robots-Tag': 'noindex, nofollow' - }); - res.end(req.method === 'HEAD' ? '' : CURTAIN_PAGE); - return true; -} - -const server = http.createServer(async (req, res) => { - { const t0 = Date.now(); res.on('finish', () => { const ms = Date.now() - t0; if (ms > 3000) console.warn('slow request', req.method, String(req.url || '').split('?')[0].slice(0, 80), ms + 'ms', res.statusCode); }); } // visibility for member-felt delays (2026-10-12) - try { - const u = new URL(req.url, 'http://x'); - const p = u.pathname; - // zone endpoints run on other people's sites and show only ad creatives, so they pass the curtain - const zonePath = p === '/z.js' || p === '/z/nas' || p === '/p.js' || p === '/p.gif' || p.startsWith('/u/pages/') || p.startsWith('/api/zone/') || p.startsWith('/banners/linkspin-') || p.startsWith('/art/house-'); - if (!zonePath && curtained(req, res, u)) return; // nothing below this line runs for an uninvited visitor - - // -- the rotator redirect: one hop, recorded, on any host (LinkSpin) - let rm = /^\/r\/([a-z0-9]{4,12})$/i.exec(p); - if (rm && (req.method === 'GET' || req.method === 'HEAD')) { - const hit = await rotator.resolve(rm[1], req); - if (hit && hit.url) { res.writeHead(302, { Location: hit.url, 'Cache-Control': 'no-store', 'Referrer-Policy': 'no-referrer-when-downgrade' }); return res.end(); } - res.writeHead(404, { 'Content-Type': 'text/html; charset=utf-8' }); return res.end(linkSitePage(reqHost(req), 'gone')); - } - // -- ad zones on members' sites: the tag, the ad, the viewable beacon, the click. Any origin may call these. - if (p === '/z.js') { const zf = path.join(PUBLIC_DIR, 'z.js'); try { const body = fs.readFileSync(zf); res.writeHead(200, { 'Content-Type': 'application/javascript; charset=utf-8', 'Cache-Control': 'public, max-age=300', 'Access-Control-Allow-Origin': '*' }); return res.end(body); } catch (e) {} } - if (p === '/api/zone/serve' && req.method === 'GET') { - const am = audiences.matcher(req); // ls.vid cookie (when the browser sends it cross-site) + soft key - const ad = await zones.serve(u.searchParams.get('z'), req, Object.assign(viewerGeo(req), am)); - const h = Object.assign({ 'Content-Type': 'application/json', 'Cache-Control': 'no-store' }, corsCreds(req)); - if (!am.vid) h['Set-Cookie'] = audiences.cookieHeader(audiences.newVid(), IS_PROD); - res.writeHead(200, h); return res.end(JSON.stringify({ ad })); - } - // audience pixel: 1x1 gif, sets/refreshes the visitor cookie, records the hit (30-day membership) - if (p === '/p.gif' && req.method === 'GET') { - const a = String(u.searchParams.get('a') || ''); let vid = audiences.cookieVid(req); const h = { 'Content-Type': 'image/gif', 'Cache-Control': 'no-store, private', 'Content-Length': String(PIXEL_GIF.length) }; - if (!vid) { vid = audiences.newVid(); h['Set-Cookie'] = audiences.cookieHeader(vid, IS_PROD); } - if (audiences.isId(a)) audiences.hit(a, vid, audiences.softKey(req)); - res.writeHead(200, h); return res.end(PIXEL_GIF); - } - if (p === '/p.js') { try { const body = fs.readFileSync(path.join(PUBLIC_DIR, 'p.js')); res.writeHead(200, { 'Content-Type': 'application/javascript; charset=utf-8', 'Cache-Control': 'public, max-age=300' }); return res.end(body); } catch (e) { res.writeHead(404); return res.end(); } } - if (p === '/z/nas' && req.method === 'GET') { // the frame a Network Ad Space fallback renders in - const html = zones.nasFrame(String(u.searchParams.get('s') || '')); - if (!html) { res.writeHead(404); return res.end(); } - res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store', 'Content-Security-Policy': "default-src 'none'; script-src https://www.networkadspace.com https://networkadspace.com 'unsafe-inline'; img-src https: http: data:; style-src 'unsafe-inline'; frame-src https: http:; frame-ancestors *; base-uri 'none'", 'Referrer-Policy': 'no-referrer' }); return res.end(html); - } - if (p === '/api/zone/seen' && (req.method === 'GET' || req.method === 'POST')) { await zones.seen(u.searchParams.get('i'), req); res.writeHead(204, corsCreds(req)); return res.end(); } - { const zm = /^\/api\/zone\/click\/([a-f0-9]{12})$/.exec(p); if (zm && req.method === 'GET') { const target = await zones.click(zm[1]); res.writeHead(302, { Location: target || '/', 'Cache-Control': 'no-store', 'Referrer-Policy': 'no-referrer-when-downgrade' }); return res.end(); } } - // -- publisher program (2026-10-10): the public offer for site owners who carry zones, and its live "Network right now" - // strip (7-day totals from zones.js, cached a minute). App host only; the link and pages domains stay single-purpose. - if (p === '/api/public/publishers' && req.method === 'GET') return json(res, 200, zones.publisherPublic(), { 'Cache-Control': 'public, max-age=60' }); - if (p === '/publishers' && (req.method === 'GET' || req.method === 'HEAD') && !isPagesHost(req) && !isLinkHost(req)) return sendFile(res, path.join(PUBLIC_DIR, 'publishers.html')); - { const wm = /^\/welcome\/([a-f0-9]{48})$/.exec(p); if (wm && (req.method === 'GET' || req.method === 'POST')) { // one-time tester sign-in link - const t = inviteTokens.get(wm[1]); - if (!t || t.exp < Date.now()) { inviteTokens.delete(wm[1]); res.writeHead(410, { 'Content-Type': 'text/html; charset=utf-8' }); return res.end('Link used

That sign-in link was already used or has expired. Ask for a fresh one.

'); } - // GET only shows a button: link-preview fetchers and in-app browsers prefetch links, and a prefetch must not spend the token - if (req.method === 'GET') { - res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store', 'X-Robots-Tag': 'noindex' }); - return res.end('Sign in to LinkSpin
LINKSPIN TEST APP

Sign in as

' + String(t.email).replace(/&/g, '&').replace(/

One use. Good for 24 hours from when it was made.

'); - } - inviteTokens.delete(wm[1]); - const acct = await accounts.byEmail(t.email); let memberId = 0; if (acct && acct.address) { try { memberId = await chain.memberIdByAccount(acct.address); } catch (e) {} } - const token = await auth.mintSession({ email: t.email, address: (acct && acct.address) || null, memberId }); - res.writeHead(302, { 'Set-Cookie': auth.sessionCookie(token), Location: t.next || '/ads', 'Cache-Control': 'no-store' }); return res.end(); - } } - // -- member pages: /p/ on the app host and on every link domain; the lead form and the hit beacon live beside it - // -- the pages domain: only pages live here. / -> the app; / and /p/ -> the page; everything else 404 - if (isPagesHost(req)) { - if (p === '/') { res.writeHead(302, { Location: 'https://' + SITE_HOST + '/', 'Cache-Control': 'no-store' }); return res.end(); } - if (p === '/robots.txt') { res.writeHead(200, { 'Content-Type': 'text/plain' }); return res.end('User-agent: *\nAllow: /\n'); } - if (p === '/assets/pt.js') return sendFile(res, path.join(PUBLIC_DIR, 'assets', 'pt.js')); - if (!/^\/p\/[a-z0-9-]{3,60}(\/lead)?$/i.test(p) && !/^\/api\/p\//.test(p) && !/^\/[a-z0-9-]{3,60}$/i.test(p)) { res.writeHead(404, { 'Content-Type': 'text/plain' }); return res.end('Not found'); } - } - let pm = /^\/p\/([a-z0-9-]{3,60})$/i.exec(p) || (isPagesHost(req) ? /^\/([a-z0-9-]{3,60})$/i.exec(p) : null); - if (pm && (req.method === 'GET' || req.method === 'HEAD')) { - const pg = pages.bySlug(pm[1]); - const preview = u.searchParams.get('preview') === '1'; - if (!pg || (pg.status !== 'published' && !preview)) { res.writeHead(404, { 'Content-Type': 'text/html; charset=utf-8' }); return res.end(isLinkHost(req) ? linkSitePage(reqHost(req), 'gone') : 'Not found

That page is not live.

'); } - if (preview) { const sess = await auth.fromRequest(req); if (!sess || !sess.email || String(sess.email).toLowerCase() !== pg.owner) { res.writeHead(404, { 'Content-Type': 'text/plain' }); return res.end('Not found'); } } - else pages.view(pg, req, 'view'); - const lsid = String(u.searchParams.get('lsid') || ''); - const hdr = { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff', 'Referrer-Policy': 'strict-origin-when-cross-origin', - 'Content-Security-Policy': "default-src 'none'; script-src 'self'; style-src 'unsafe-inline'; img-src 'self' https: data:; form-action https: http:; base-uri 'none'; frame-ancestors *; connect-src 'self'" }; - if (/^[a-z0-9]{6,20}$/i.test(lsid)) hdr['Set-Cookie'] = 'ls.click=' + lsid + '; Path=/; SameSite=Lax; Max-Age=2592000' + (IS_PROD ? '; Secure' : ''); - res.writeHead(200, hdr); return res.end(pages.html(pg, { leadUrl: '/p/' + pg.slug + '/lead', trackSrc: '/assets/pt.js', footerLink: 'https://' + SITE_HOST + '/', footerText: 'Made with LinkSpin', pixel: 'https://' + SITE_HOST + '/p.gif?a=' + audiences.defaultFor(pg.owner) + '&e=page' })); - } - pm = /^\/p\/([a-z0-9-]{3,60})\/lead$/i.exec(p); - if (pm && req.method === 'POST') { - const raw = await new Promise(r => { let d = ''; req.on('data', c => { d += c; if (d.length > 20000) req.destroy(); }); req.on('end', () => r(d)); }); - const b = {}; try { const ct = String(req.headers['content-type'] || ''); if (/json/.test(ct)) Object.assign(b, JSON.parse(raw)); else for (const [k, v] of new URLSearchParams(raw)) b[k] = v; } catch (e) {} - const r = await pages.lead(pm[1], b, req); - if (r.error) { res.writeHead(400, { 'Content-Type': 'text/html; charset=utf-8' }); return res.end('Try again

' + r.error + ' Go back

'); } - if (r.owner && r.lsid) { try { postbacks.bindClick(String(b.email || '').toLowerCase(), r.lsid); const hit = await rotator.convert(r.lsid, 'lead', {}); if (hit) postbacks.fire(hit.owner, 'lead', Object.assign({ q: hit.q || {}, source: hit.s, country: hit.c, device: hit.dv, lsid: r.lsid, code: hit.code, sourceId: hit.sourceId || '' })).catch(() => {}); } catch (e) {} } - res.writeHead(302, { Location: r.next || '/', 'Cache-Control': 'no-store' }); return res.end(); - } - if (p.startsWith('/api/p/') && req.method === 'POST' && /\/hit$/.test(p)) { const sl = p.split('/')[3]; const pg = pages.bySlug(sl); if (pg) pages.view(pg, req, 'cta'); res.writeHead(204); return res.end(); } - if (p === '/assets/pt.js' && isLinkHost(req)) return sendFile(res, path.join(PUBLIC_DIR, 'assets', 'pt.js')); - // -- short link domains: a real small site (home, disclosure, terms, privacy, abuse) so the domain never looks parked - if (isLinkHost(req)) { - const page = { '/': 'home', '/disclosure': 'disclosure', '/terms': 'terms', '/privacy': 'privacy', '/abuse': 'abuse', '/robots.txt': 'robots' }[p]; - if (!page) { res.writeHead(404, { 'Content-Type': 'text/html; charset=utf-8' }); return res.end(linkSitePage(reqHost(req), 'gone')); } - if (page === 'robots') { res.writeHead(200, { 'Content-Type': 'text/plain' }); return res.end('User-agent: *\nDisallow: /r/\n'); } - res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'public, max-age=300' }); return res.end(linkSitePage(reqHost(req), page)); - } - - // -- traffic log: public page views by referring domain (admin > Traffic) - if (req.method === 'GET' && (TRAFFIC_PAGES.has(p) || /^\/(join|from|wall|blog)\/[^/]+$/.test(p))) traffic.hit(p.startsWith('/blog/') ? '/blog/*' : p, req.headers.referer, req.headers['user-agent']); - // -- join links: /join/ — LAST-touch cookie (Marty, - // 2026-09-10): the link a visitor opened most recently is the sponsor shown - // and used, and it locks the moment the account is created (accounts.ensure - // never changes an existing account's sponsor; the contract binds the buyer at - // their first purchase). Codes resolve LATE (at buy time) to whatever chain id - // the referrer has by then, so free members refer from day one. - let m = /^\/join\/([A-Za-z0-9_]{1,20})$/.exec(p); - if (m && (req.method === 'GET' || req.method === 'HEAD')) { - // lead-capture page: email first, wallet later. ?v= picks the hook - // copy and is remembered so the account records which angle converted. - // partner placement: /join/company (or /top) places the visitor directly under - // member #1, the company position, with no sponsor in between (Marty, 2026-09-12 partner kit) - const tok = JOIN_ALIASES[m[1].toLowerCase()] || m[1].toLowerCase(); - const cookies = parseCookies(req); - const angle = String(u.searchParams.get('v') || '').toLowerCase(); - const ang = JOIN_ANGLES[angle] || null; - if (req.method === 'GET') coach.recordView(tok, ang ? angle : '', req.headers.referer); // link stats per angle + source - const cookieTail = `; Path=/; SameSite=Lax; Max-Age=${30 * 24 * 3600}${IS_PROD ? '; Secure' : ''}`; // 30 days: whoever brings them back gets the credit - const set = []; - set.push('iap.sponsor=' + tok + cookieTail); // last touch wins - { const lsid = String(u.searchParams.get('lsid') || ''); if (/^[a-z0-9]{6,20}$/i.test(lsid)) set.push('ls.click=' + lsid + cookieTail); } // the rotator click that brought them (postback attribution) - const promo = promos.norm(u.searchParams.get('promo')); if (promo) set.push('iap.promo=' + promo + cookieTail); // partner code, redeemed at signup - if (ang) set.push('iap.angle=' + angle + cookieTail); - if (!cookies['iap.ref']) set.push('iap.ref=' + encodeURIComponent(coach.refHost(req.headers.referer)) + cookieTail); // first-touch source - return serveJoinPage(res, tok, ang ? angle : '', ang, set); - } - // -- legacy bridge: /from/faucetwave | /from/tieroneads [?seg=advertiser]. Same squeeze page - // with brand copy, NO sponsor (the sponsor cookie is cleared so they land in the holding - // tank for adoption), the angle remembered so the welcome-back grant fires at signup, and - // a forced first-touch source so link stats / admin can see the legacy arrivals. - m = /^\/from\/(faucetwave|tieroneads)$/.exec(p); - if (m && (req.method === 'GET' || req.method === 'HEAD')) { - const brand = m[1]; - const key = (brand === 'faucetwave' ? 'fw' : 't1') + (String(u.searchParams.get('seg') || '').toLowerCase().startsWith('adv') ? '-adv' : '-earn'); - const cookieTail = `; Path=/; SameSite=Lax; Max-Age=${30 * 24 * 3600}${IS_PROD ? '; Secure' : ''}`; - const src = String(u.searchParams.get('src') || '').toLowerCase().replace(/[^a-z0-9.\-]/g, '').slice(0, 40); // e.g. the old domain's splash page - const set = ['iap.sponsor=; Path=/; SameSite=Lax; Max-Age=0' + (IS_PROD ? '; Secure' : ''), 'iap.angle=' + key + cookieTail, 'iap.ref=' + encodeURIComponent('legacy:' + brand + (src ? ':' + src : '')) + cookieTail]; - return serveJoinPage(res, '', key, JOIN_ANGLES[key], set); - } - if (p === '/unsubscribe' && req.method === 'GET') { - const r = await drip.unsubscribe(u.searchParams.get('e'), u.searchParams.get('t')); - const msg = r.error ? r.error : 'Done. You will not get any more follow-up emails from LinkSpin. Your account is unchanged.'; - res.writeHead(r.error ? 400 : 200, baseHeaders({ 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store' })); - return res.end('LinkSpin
LinkSpin

' + (r.error ? 'Hmm.' : 'Unsubscribed.') + '

' + msg + '

Member area

'); - } - - // -- public API - if (p === '/api/config' && req.method === 'GET') { - const c = chain.getConfig(); - // public copy of the site settings: never anything that looks like a credential - const pubSite = {}; - for (const [k, v] of Object.entries(siteConfig())) if (!/secret|token|password|private|apikey|api_key/i.test(k)) pubSite[k] = v; - return json(res, 200, Object.assign({ contract: c.contract, chainId: c.chainId, - chainName: c.chainName, explorer: c.explorer, rpc: c.rpcs[0], - emailAuth: (mailer.hasKey() || !IS_PROD) && SIGNUPS_OPEN, - signupsOpen: SIGNUPS_OPEN }, pubSite)); - } - if (p === '/api/moonpay-url' && req.method === 'GET') { - // Card on-ramp deep link. With MoonPay keys set — PUBLIC key via - // MOONPAY_PUBLIC_KEY env or site config, SECRET key via MOONPAY_SECRET_KEY - // env ONLY (never site config, since /api/config exposes siteConfig) — - // returns a SIGNED checkout URL prefilled with the buyer's own wallet and - // a POL amount; otherwise a generic MoonPay buy page. Zero custody either - // way: MoonPay is merchant of record and the crypto goes straight to the - // buyer's wallet — this site never touches or holds anyone's money. - const addr = (u.searchParams.get('address') || '').trim(); - let pol = Math.round(Number(u.searchParams.get('pol')) || 0); - if (!pol || pol < 30) pol = 30; - if (pol > 100000) pol = 100000; - const pk = (process.env.MOONPAY_PUBLIC_KEY || siteConfig().moonpayPublicKey || '').trim(); - const sk = (process.env.MOONPAY_SECRET_KEY || '').trim(); - if (pk && sk && /^0x[0-9a-fA-F]{40}$/.test(addr)) { - const qs = '?apiKey=' + encodeURIComponent(pk) + '¤cyCode=pol_polygon&walletAddress=' + encodeURIComponent(addr) + '"eCurrencyAmount=' + pol; - const sig = crypto.createHmac('sha256', sk).update(qs).digest('base64'); - return json(res, 200, { url: 'https://buy.moonpay.com/' + qs + '&signature=' + encodeURIComponent(sig), signed: true, pol }); - } - return json(res, 200, { url: 'https://www.moonpay.com/buy/matic', signed: false, pol }); // MoonPay's Polygon page still lives at the old slug; /buy/pol renders their 404 (same fix as RM Circle) - } - if (p === '/api/catalog' && req.method === 'GET') { - // five live quotes per call: serve a 20-second cache so pages that load the - // ladder (join, home, buy) are not waiting on the RPC every time - if (!catalogCache.at || Date.now() - catalogCache.at > 20000) { - try { catalogCache.products = await chain.catalog(); catalogCache.at = Date.now(); } - catch (e) { if (!catalogCache.products) throw e; } - } - return json(res, 200, { products: catalogCache.products }); - } - if (p === '/api/feed' && req.method === 'GET') { - return json(res, 200, { events: await attachNames(chain.recentEvents(Number(u.searchParams.get('n')) || 100)) }); - } - if (p === '/api/feed/live' && req.method === 'GET') { - res.writeHead(200, baseHeaders({ 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-store', Connection: 'keep-alive' })); - res.write(': connected\n\n'); - feedClients.add(res); - req.on('close', () => feedClients.delete(res)); - return; - } - m = /^\/api\/tx\/(0x[0-9a-fA-F]{64})$/.exec(p); - if (m && req.method === 'GET') { - // tx relay so the browser never talks to the RPC directly (CSP stays 'self'). - // Serves both the wallet's waitTx poll (found/status) and the built-in - // /tx/ viewer (full details + decoded events). - try { - const r = await chain.rpc('eth_getTransactionReceipt', [m[1]]); - if (!r) return json(res, 200, { found: false }); - const out = { found: true, status: r.status, blockNumber: r.blockNumber, gasUsed: r.gasUsed }; - try { - const t = await chain.rpc('eth_getTransactionByHash', [m[1]]); - if (t) { out.from = t.from; out.to = t.to; out.valueWei = BigInt(t.value || '0x0').toString(); } - } catch (e) {} - try { - const blk = await chain.rpc('eth_getBlockByNumber', [r.blockNumber, false]); - if (blk) out.ts = blk.timestamp; - } catch (e) {} - try { - out.events = await attachNames((r.logs || []).map(chain.decodeLog).filter(Boolean) - .map(ev => Object.assign(ev, { tx: m[1] }))); - } catch (e) { out.events = []; } - return json(res, 200, out); - } catch (e) { return json(res, 200, { found: false, rpcError: true }); } - } - if (p === '/api/sponsor' && req.method === 'GET') { - // The account's stored sponsor is authoritative — it persists across - // devices, cleared cookies, and return visits. Fall back to the first-touch - // cookie only for anonymous visitors with no account sponsor yet. (Reading - // the cookie alone was orphaning buyers to root when the cookie was absent.) - const s = await auth.fromRequest(req); - const acct = s && s.email ? await accounts.byEmail(s.email) : null; - const tok = (acct && acct.sponsorRef) || parseCookies(req)['iap.sponsor'] || ''; - const spd = await resolveSponsorDetailed(tok); let sponsorId = spd.id; - // LinkSpin carry-over: a known sponsor with a wallet is activated on this contract by the engine - // before the member's first transaction; one with no wallet opens the claim window (the buy waits) - let claim = null; - if (acct && !sponsorId) { - try { - const cr = await carry.resolveForChain(acct, spd); - if (cr && cr.sponsorId) { sponsorId = cr.sponsorId; spd.reason = 'ok'; } - else if (cr && cr.hold) { claim = cr.claim; } - } catch (e) {} - } - if (claim) return json(res, 200, { ref: tok, sponsorId: 0, sponsorBlocked: 'claim', claim, sponsorName: spd.name || null, invited: true, name: null, avatarUrl: null, own: false, bio: null, cobrand: false }); - let sponsorBlocked = null; // set when the account itself names a sponsor that cannot be paid right now: the client refuses the transaction - if (acct && acct.sponsorRef && !sponsorId && spd.reason !== 'none') { sponsorBlocked = spd.reason; sponsorBlockedAlert(acct.email, Object.assign({ tok }, spd)); } - if (sponsorId && await payoutChainBlocked(sponsorId, 2)) { console.log('sponsor routed away from no-payout chain', sponsorId); sponsorId = 0; } - // orphan fallback: an unresolvable/absent sponsor (dead link, no link) lands - // the new member under the configured catch position (#1) instead of root - if (!sponsorId && (!acct || acct.memberId !== (Number(siteConfig().defaultSponsorId) || 1))) sponsorId = Number(siteConfig().defaultSponsorId) || 1; - // a brand-new contract has no catch position yet: the first member joins with sponsor 0 and BECOMES #1 (Marty's reverted - // activate(1) on 2026-10-08: 'Unknown sponsor' because memberCount was 0) - if (sponsorId) { try { if (sponsorId > await chain.memberCount()) { console.log('sponsor', sponsorId, 'not on chain yet, using 0'); sponsorId = 0; } } catch (e) {} } - let name = null, avatarUrl = null, own = false; - // the join page names the owner of the LINK it was opened with (?ref=token), not the visitor's own - // sponsor: a member previewing their own invite page was seeing their upline's name (Jim, 2026-09-13) - let showTok = String(u.searchParams.get('ref') || '').trim().toLowerCase(); - if (showTok && JOIN_ALIASES[showTok]) showTok = JOIN_ALIASES[showTok]; - const nameTok = showTok || tok; - if (nameTok) { - const t = nameTok.toLowerCase(); - let a = await accounts.byCode(t); if (!a) a = await accounts.byUsername(t); - if (!a && /^\d+$/.test(nameTok)) a = await accounts.byMemberId(Number(nameTok)); - if (a) { name = a.username ? '@' + a.username : (a.memberId ? 'member #' + a.memberId : null); avatarUrl = a.avatarUrl || null; own = !!(acct && a.email === acct.email); var bio = null, cobrand = false; try { cobrand = (await ads.milestonesOf(a.email)).includes('level3'); if (cobrand) bio = a.bio ? String(a.bio).slice(0, 220) : null; } catch (e) {} } - } - return json(res, 200, { ref: tok, sponsorId, sponsorBlocked, sponsorName: spd.name || null, invited: !!(tok || showTok), name, avatarUrl, own, bio: typeof bio === 'undefined' ? null : bio, cobrand: typeof cobrand === 'undefined' ? false : cobrand }); - } - if (p === '/api/stats' && req.method === 'GET') { - let members = 0; try { members = await chain.memberCount(); } catch (e) {} - return json(res, 200, Object.assign({ onchainMembers: members, siteAccounts: await accounts.count(), servedToday: rotator.servedToday(), rotations: rotator.totals().rotations }, chain.totals())); - } - // -- home-page demo: a working spin link with no account (2026-10-07). One per browser (ls.demo cookie), - // five per IP per hour, 24 h unless the visitor signs in (the email door then claims it). - if (p === '/api/demo/spin' && req.method === 'POST') { - const ip = clientIp(req); const now = Date.now(); - const dl = demoLimits.get(ip) || []; const recent = dl.filter(t => now - t < 3600000); - if (recent.length >= 5) return json(res, 429, { error: 'That is plenty of demo links for one hour. Sign in to make more.' }); - const b = await readBody(req); - const urls = Array.isArray(b.urls) ? b.urls.map(x => String(x || '').trim()).filter(Boolean) : []; - let token = String(parseCookies(req)['ls.demo'] || '').replace(/[^a-f0-9]/g, '').slice(0, 32); - if (token.length < 16) token = crypto.randomBytes(12).toString('hex'); - const r = await rotator.createDemo(token, urls); - if (r.error) return json(res, 400, r); - recent.push(now); demoLimits.set(ip, recent); - const hosts = String(siteConfig().linkDomains || '').split(',').map(x => x.trim()).filter(x => x && !x.startsWith('www.')); - const host = hosts[0] || SITE_HOST; - return json(res, 200, { ok: true, code: r.rotation.code, url: 'https://' + host + '/r/' + r.rotation.code, destinations: r.rotation.destinations.length, expiresIn: 24 * 3600 }, - { 'Set-Cookie': 'ls.demo=' + token + '; Path=/; Max-Age=2592000; HttpOnly; SameSite=Lax' + (IS_PROD ? '; Secure' : '') }); - } - - // -- 24/7 assistant - if (p === '/api/chat' && req.method === 'POST') { - const ip = req.socket.remoteAddress || 'x'; - if (chatLimited(ip)) return json(res, 429, { error: 'Give it a minute, then ask again.' }); - const b = await readBody(req); - const r = await chatbot.answer(b.message, b.history); - return json(res, r.error ? 400 : 200, r); - } - - // -- accounts: email + password is the normal join path (wallet comes - // out only at purchase / payout-activation time and gets linked then) - if (p === '/api/signup' && req.method === 'POST') { - if (!SIGNUPS_OPEN) return json(res, 403, SHUT); - const b = await readBody(req); - const ref = parseCookies(req)['iap.sponsor'] || ''; // last-touch attribution, locked at account creation - const r = await accounts.signup(b.email, b.password, ref); - if (r.error) return json(res, 400, r); - { const lc = parseCookies(req)['ls.click']; if (lc) { postbacks.bindClick(String(b.email || '').trim().toLowerCase(), lc); postbacks.convertFor(String(b.email || '').trim().toLowerCase(), 'join', {}).catch(() => {}); } } - // sponsor is notified once the new member picks a username (onboarding), - // so the email can name them — see /api/my/profile - if (b.newsletter) sendy.subscribe(r.account.email, r.account.username || '').catch(() => {}); // pre-checked opt-in, silent - const token = await auth.mintSession({ email: r.account.email }); - return json(res, 200, { ok: true, account: r.account }, { 'Set-Cookie': auth.sessionCookie(token) }); - } - if (p === '/api/login' && req.method === 'POST') { - const b = await readBody(req); - const r = await accounts.login(b.email, b.password); - if (r.error) return json(res, 400, r); - let memberId = 0; - if (r.account.address) { try { memberId = await chain.memberIdByAccount(r.account.address); } catch (e) {} } - const token = await auth.mintSession({ email: r.account.email, address: r.account.address, memberId }); - return json(res, 200, { ok: true, account: r.account }, { 'Set-Cookie': auth.sessionCookie(token) }); - } - - // -- passwordless: email code sign-in (signup and login are the same act) - if (p === '/api/auth/email/start' && req.method === 'POST') { - const b = await readBody(req); - const e = String(b.email || '').trim().toLowerCase(); - if (!/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(e)) return json(res, 400, { error: 'That email address does not look right.' }); - // closed sign-ups shut the door to NEW accounts only; members already here (incl. imported shells) still get their code - const acct0 = await accounts.byEmail(e); - if (!SIGNUPS_OPEN && !acct0) return json(res, 403, SHUT); - if (!isTester(e, acct0)) return json(res, 403, TESTING); - const prev = emailCodes.get(e); - if (prev && Date.now() < prev.nextAt) { console.log('signup-guard cooldown', clientIp(req), e.replace(/^(.).*(@.*)$/, '$1***$2')); return json(res, 429, { error: 'Code already sent. Give it a minute, then try again.' }); } - const guard = codeGuard(req, b); // honeypot, form age, per-IP + global limits, icon check once limited - if (guard) return json(res, guard.status, guard.body); - const code = String(Math.floor(100000 + Math.random() * 900000)); - emailCodes.set(e, { code, exp: Date.now() + 15 * 60 * 1000, tries: 0, nextAt: Date.now() + 60 * 1000 }); - if (mailer.hasKey()) { - try { await mailer.sendCode(e, code); } catch (err) { - console.error('sendCode failed', err.message); - return json(res, 502, { error: 'Could not send the email. Try again in a minute.' }); - } - return json(res, 200, { ok: true, sent: true }); - } - if (!IS_PROD) return json(res, 200, { ok: true, sent: false, devCode: code }); - return json(res, 503, { error: 'Email sign-in is not configured yet.' }); - } - if (p === '/api/auth/email/verify' && req.method === 'POST') { - const b = await readBody(req); - const e = String(b.email || '').trim().toLowerCase(); - const rec = emailCodes.get(e); - if (!rec || rec.exp < Date.now()) return json(res, 400, { error: 'Code expired. Request a fresh one.' }); - rec.tries += 1; - if (rec.tries > 6) { emailCodes.delete(e); return json(res, 400, { error: 'Too many tries. Request a fresh code.' }); } - if (String(b.code || '').trim() !== rec.code) return json(res, 400, { error: 'That code does not match.' }); - emailCodes.delete(e); - const ref = parseCookies(req)['iap.sponsor'] || ''; - const via = parseCookies(req)['iap.angle'] || ''; - const joinedRef = decodeURIComponent(parseCookies(req)['iap.ref'] || '') || null; - // the code door creates an account on first use, so it is a sign-up door too - if (!SIGNUPS_OPEN && !(await accounts.byEmail(e))) return json(res, 403, SHUT); - if (!isTester(e, await accounts.byEmail(e))) return json(res, 403, TESTING); - 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) carry.onJoin(r.account, !!ref).catch(() => {}); // network sponsor carries over when no link was used (LinkSpin) - if (r.created) { const lc = parseCookies(req)['ls.click']; if (lc) { postbacks.bindClick(e, lc); postbacks.convertFor(e, 'join', {}).catch(() => {}); } } - { const dm = String(parseCookies(req)['ls.demo'] || '').replace(/[^a-f0-9]/g, ''); if (dm.length >= 16) rotator.claim('demo:' + dm, e).catch(() => {}); } // the home-page demo spin becomes theirs - // 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(() => {}); - // a wallet-only session (signed with a wallet, no account) finishing setup: - // adopt that wallet into the email account so member #, purchases and - // payouts stay attached, then retire the wallet-only session - const prior = await auth.fromRequest(req); - if (prior && prior.address && !prior.email) { - const lr = await accounts.linkWallet(e, prior.address); - if (lr.error) return json(res, 400, lr); - r.account = lr.account || await accounts.byEmail(e); - await auth.logout(req); - } - if (r.created) { sendWelcome(e, ref).catch(() => {}); } // sponsor notified at username set (/api/my/profile) - // partner promo code carried on the join link: redeem once per account (ignored if invalid/used) - try { - const pc = parseCookies(req)['iap.promo']; - if (pc) { const g = await promos.redeem(pc, e, 'link'); if (g.ok) { if (g.funder && g.funder !== e) { if (await ads.spendEarned(g.funder, g.credits)) { await ads.addEarned(e, g.credits); console.log('promo redeemed (member-funded)', g.code, g.credits, e, 'by', g.funder); } else console.log('promo funder short', g.code, g.funder); } else { await ads.addEarned(e, g.credits); console.log('promo redeemed', g.code, g.credits, e); } } } - } catch (err) { console.error('promo redeem', err.message); } - // legacy bridge: a listed former Faucet Wave / Tier One Ads member gets welcome-back credits once - if (r.created && /^(fw|t1)-(adv|earn)$/.test(via)) { - try { const g = legacy.grant(e, siteConfig()); if (g) { await ads.addEarned(e, g.credits); console.log('legacy grant', g.brand, g.seg, g.credits, e); } } - catch (err) { console.error('legacy grant', err.message); } - } - if (r.created && b.newsletter) sendy.subscribe(r.account.email, r.account.username || '').catch(() => {}); // pre-checked opt-in, silent, new joins only - let memberId = 0; - if (r.account.address) { try { memberId = await chain.memberIdByAccount(r.account.address); } catch (err) {} } - const token = await auth.mintSession({ email: r.account.email, address: r.account.address, memberId }); - return json(res, 200, { ok: true, account: r.account, created: !!r.created }, { 'Set-Cookie': auth.sessionCookie(token) }); - } - - // -- wallet auth: link-to-account when an email session exists, or - // wallet-first sign-in (no UI door since 2026-09-09; a wallet-only session - // is walked to the email card, which adopts the wallet on verify) - if (p === '/api/auth/challenge' && req.method === 'POST') { - const b = await readBody(req); - const r = auth.makeChallenge(b.address); - return json(res, r.error ? 400 : 200, r); - } - if (p === '/api/auth/verify' && req.method === 'POST') { - const b = await readBody(req); - const r = await auth.verifyChallenge(b.address, b.signature); - if (r.error) return json(res, 400, r); - let memberId = 0; - try { memberId = await chain.memberIdByAccount(r.address); } catch (e) {} - const s = await auth.fromRequest(req); - if (s && s.email && b.asPosition) { - // Qualified Start: a second (third…) wallet on the same account. It becomes - // its own on-chain member under this member's id when it buys; the session - // stays on the main wallet. - // policy (Marty, 2026-09-10): positions exist to qualify, so at most five per account, and a - // wallet that is already registered on-chain under anything other than this account's main - // member is refused (a position-under-position chain would recapture 70% of a self-buy) - const MAX_POS = 5; - const have = await accounts.positions(s.email); - if (!have.find(p => p.address === r.address.toLowerCase()) && have.length >= MAX_POS) - return json(res, 400, { error: 'You can link up to ' + MAX_POS + ' positions, which is everything Qualified Start needs. Once qualified, buy from your main wallet so your sponsor is paid in full.' }); - if (memberId) { - const mainId = await auth.refreshMemberId(s); - let mm = null; try { mm = await chain.member(memberId); } catch (e) {} - if (mm && mainId && mm.sponsorId !== mainId) - return json(res, 400, { error: 'That wallet is already registered on-chain under ' + (mm.sponsorId ? 'member #' + mm.sponsorId : 'no sponsor') + ', not under your main member #' + mainId + '. Only positions registered directly under you can be linked.' }); - } - const pr = await accounts.addPosition(s.email, r.address); - if (pr.error) return json(res, 400, pr); - if (memberId) await accounts.setPositionMember(r.address, memberId); - return json(res, 200, { ok: true, position: true, address: r.address, memberId }); - } - if (s && s.email) { - const lr = await accounts.linkWallet(s.email, r.address); - if (!lr.error) postbacks.convertFor(s.email, 'wallet', {}).catch(() => {}); - if (lr.error) return json(res, 400, lr); - await auth.updateSession(s.token, { address: r.address, memberId }); - return json(res, 200, { ok: true, linked: true, address: r.address, memberId }); - } - const acct = await accounts.byAddress(r.address); - if (!acct && await accounts.positionOwner(r.address)) - return json(res, 400, { error: 'That wallet is a linked position on an account. Sign in with that account\'s email instead.' }); - const token = await auth.mintSession({ email: acct ? acct.email : null, address: r.address, memberId }); - return json(res, 200, { ok: true, address: r.address, memberId }, - { 'Set-Cookie': auth.sessionCookie(token) }); - } - if (p === '/api/auth/logout' && req.method === 'POST') { - await auth.logout(req); - return json(res, 200, { ok: true }, { 'Set-Cookie': auth.clearCookie() }); - } - if (p === '/api/gas' && req.method === 'GET') { - try { - const fees = await chain.suggestedFees(); - const from = u.searchParams.get('from'), to = u.searchParams.get('to'), data = u.searchParams.get('data'), value = u.searchParams.get('value'); - if (/^0x[0-9a-fA-F]{40}$/.test(from || '') && /^0x[0-9a-fA-F]{40}$/.test(to || '') && /^0x[0-9a-fA-F]*$/.test(data || '')) { const call = { from, to, data: data || '0x' }; if (/^0x[0-9a-fA-F]+$/.test(value || '')) call.value = value; fees.gas = await chain.estimateGas(call); } - return json(res, 200, fees); - } - catch (e) { return json(res, 200, {}); } - } - - if (p === '/api/me' && req.method === 'GET') { - const s = await auth.fromRequest(req); - if (!s) return json(res, 200, { signedIn: false }); - const memberId = await auth.refreshMemberId(s); - const acct = (s.email && await accounts.byEmail(s.email)) || (s.address && await accounts.byAddress(s.address)) || null; - const spdMe = await resolveSponsorDetailed((acct && acct.sponsorRef) || parseCookies(req)['iap.sponsor']); let sponsorId = spdMe.id; - const sponsorBlocked = (acct && acct.sponsorRef && !sponsorId && spdMe.reason !== 'none') ? spdMe.reason : null; - if (sponsorId && await payoutChainBlocked(sponsorId, 2)) sponsorId = 0; - const _defSpon = Number(siteConfig().defaultSponsorId) || 1; - if (!sponsorId && memberId !== _defSpon) sponsorId = _defSpon; // orphan fallback → #1 (never self-sponsor) - if (sponsorId) { try { if (sponsorId > await chain.memberCount()) sponsorId = 0; } catch (e) {} } // fresh contract: no catch position exists yet, the first member becomes #1 - if (memberId && acct && acct.memberId !== memberId) accounts.setMemberId(acct.email, memberId).catch(() => {}); - const out = { signedIn: true, sponsorBlocked, sponsorName: spdMe.name || null, email: s.email || (acct && acct.email) || null, - address: s.address || (acct && acct.address) || null, memberId, - username: (acct && acct.username) || null, - refCode: (acct && acct.code) || null, sponsorId, - // profile + line-banner fields so the Profile pane repopulates on reload (were being saved but not returned) - avatarUrl: (acct && acct.avatarUrl) || null, bio: (acct && acct.bio) || null, - socials: (acct && acct.socials) || null, - wallOffers: parseWallOffers(acct), - lineBannerUrl: (acct && acct.lineBannerUrl) || null, lineTargetUrl: (acct && acct.lineTargetUrl) || null }; - if (memberId) { - try { - const mm = await chain.member(memberId); - out.buyerCount = mm.buyerCount; - out.onchainSponsorId = mm.sponsorId; - const bal = await ads.balances((await myMemberIds(s)).ids, s.email); - out.credits = bal.total; out.creditedCredits = bal.credited; out.earnedCredits = bal.earned; out.inCampaigns = bal.inCampaigns; out.availableCredits = bal.available; - } catch (e) { out.chainReadError = true; } - } - return json(res, 200, out); - } - - if (p === '/api/my/dashboard' && req.method === 'GET') { - const s = await auth.fromRequest(req); - if (!s) return json(res, 401, { error: 'Sign in first.' }); - const memberId = await auth.refreshMemberId(s); - const acct = (s.email && await accounts.byEmail(s.email)) || (s.address && await accounts.byAddress(s.address)) || null; - if (memberId && acct && acct.memberId !== memberId) accounts.setMemberId(acct.email, memberId).catch(() => {}); - let tankWaiting = null; // top of every Overview: people waiting for a sponsor (Marty, 2026-09-12) - try { - if (!tankWaitCache || Date.now() - tankWaitCache.ts > 60000) tankWaitCache = { ts: Date.now(), list: await tank.waiting() }; - const tw = tankWaitCache.list; - tankWaiting = { count: tw.length, names: tw.slice(0, 6).map(w => w.name), eligible: !!(await tank.eligibility(s.email)).ok }; - } catch (e) {} - const sc0 = siteConfig(); - const out = { memberId, tankWaiting, email: s.email || (acct && acct.email) || null, - pipeline: { live: pipeline.visible(sc0.pipelineMode, s.email || (acct && acct.email), ADMIN_EMAIL), mode: sc0.pipelineMode || 'off', eta: sc0.pipelineEta || '' }, - address: s.address || (acct && acct.address) || null, - username: (acct && acct.username) || null, - refCode: (acct && acct.code) || null, lineBannerUrl: (acct && acct.lineBannerUrl) || null, /* the launch checklist mark reads it (was 7 of 8 with a banner set, 2026-09-14) */ credits: 0, buyerCount: 0, - earnedWei: '0', earnCount: 0, referrals: [], welcomeCredits: 0 }; - if (out.email) { - // welcome credits unlock via the welcome tour when an upline with a - // line banner exists; members with no tour to walk get them instantly - const welcomed = await ads.welcomeGranted(out.email); - const tour = welcomed ? [] : (await uplineSlides(out.email)).filter(a => a.lineTargetUrl); - if (welcomed || !tour.length) { await ads.grantWelcome(out.email); out.welcomeCredits = ads.rates().welcomeCredits || 0; } // the welcome amount itself; the rest of the earned pool is viewing rewards, milestones and credits we add - else { out.welcomeCredits = 0; out.gauntletPending = true; } - } - if (out.email) out.inboxUnread = await ads.unreadCount(out.email); // delivers pending solos too - if (out.email) { // sponsor chat: presence heartbeat + unread + my availability + direct sponsor - accounts.touchSeen(out.email).catch(() => {}); - out.chatUnread = await messages.chatUnread(out.email); - out.chatAvailable = (acct && acct.chatAvailable !== false); - const spon = await accounts.sponsorOf(out.email); - if (spon && spon.email) out.sponsor = { - email: spon.email, - name: spon.username ? '@' + spon.username : (spon.memberId ? 'member #' + spon.memberId : 'your sponsor'), - online: (Date.now() - (spon.lastSeen || 0)) < 60000, - available: spon.chatAvailable !== false }; - } - if (out.email) { // unmissable login modal when the upline sent a message - const un = await messages.newestUnread(out.email); - if (un) { - const nm = un.fromMember ? await accounts.namesForMembers([un.fromMember]) : {}; - out.sponsorMsg = { id: un.id, subject: un.subject, body: un.body, - fromName: (un.fromMember && nm[un.fromMember]) ? '@' + nm[un.fromMember] : (un.fromMember ? 'member #' + un.fromMember : 'your sponsor') }; - } - } - if (memberId) { - try { - const mm = await chain.member(memberId); - out.buyerCount = mm.buyerCount; - const mine = await myMemberIds(s); - // linked positions are the member's own: their qualifying buyers count toward the account (Jim, 2026-09-14) - out.buyerCountMain = mm.buyerCount; out.buyerCountPositions = 0; - for (const id of mine.ids) if (id && id !== memberId) { try { out.buyerCountPositions += (await chain.member(id)).buyerCount || 0; } catch (e) {} } - out.buyerCountAll = out.buyerCountMain + out.buyerCountPositions; // badges count every position; levels the contract pays #main on depend on buyerCount alone - const bal = await ads.balances(mine.ids, s.email); - out.credits = bal.total; out.creditedCredits = bal.credited; out.earnedCredits = bal.earned; out.inCampaigns = bal.inCampaigns; out.availableCredits = bal.available; - } catch (e) { out.chainReadError = true; } - let earned = 0n, n = 0; - for (const ev of chain.recentEvents(600)) { - if ((ev.type === 'TierPaid' && ev.recipientId === memberId) || (ev.type === 'AwardPaid' && ev.toId === memberId)) { - earned += BigInt(ev.amountWei); n += 1; - } - } - out.earnedWei = earned.toString(); - out.earnCount = n; - } - // achievement milestones (same ladder as the Overview stepper) + one-time credit - // bonuses — computed AFTER buyerCount is read from chain above (else always 0) - { - const bc = out.buyerCountAll != null ? out.buyerCountAll : (out.buyerCount || 0); - const reached = []; - if (out.memberId) reached.push('payouts'); - if (bc >= 1) reached.push('firstBuyer'); - if (bc >= 2) reached.push('level2'); - if (bc >= 5) reached.push('level3'); - try { for (const k of await ads.milestonesOf(out.email)) if (!reached.includes(k)) reached.push(k); } catch (e) {} // a badge once earned stays earned - out.milestonesReached = reached; - if (out.email && reached.length) out.milestonesGranted = await ads.grantMilestones(out.email, reached); - } - // who joined through this member: their invite link uses username when set, - // else code, and the numeric id once on-chain — match all three - const refs = []; - if (acct && acct.code) refs.push(acct.code); - if (acct && acct.username) refs.push(acct.username); - if (memberId) refs.push(String(memberId)); - const joined = await accounts.listByReferrer(refs); - out.referrals = joined.map(r => ({ - name: r.username || r.email.replace(/^(.).*(@.*)$/, '$1***$2'), // username, else privacy mask - joined: r.created, - status: r.address ? 'wallet linked' : 'joined free' - })); - out.isAdmin = !!(ADMIN_EMAIL && out.email && String(out.email).toLowerCase() === ADMIN_EMAIL); // shows the Admin link - out.wallUnlocked = wallUnlockedFor(out.buyerCount || 0); // how many wall positions are the member's own - return json(res, 200, out); - } - // -- linked positions (Qualified Start): list, refresh from chain, unlink - if (p === '/api/my/positions' && req.method === 'GET') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const acct = await accounts.byEmail(s.email); - const mainId = await auth.refreshMemberId(s); - const list = await accounts.positions(s.email); - const out = []; - const posIds = [mainId, ...list.map(p => p.memberId)].filter(Boolean); - let balPer = {}, credited = 0; try { const bb = await ads.balances(posIds, s.email); credited = bb.credited; for (const p of bb.per) balPer[p.memberId] = p.avail; } catch (e) {} - for (const pos of list) { - let id = pos.memberId; - if (!id) { try { id = await chain.memberIdByAccount(pos.address); if (id) await accounts.setPositionMember(pos.address, id); } catch (e) {} } - const row = { address: pos.address, memberId: id || 0, buyerCount: 0, counted: false, credits: 0, created: pos.created }; - if (id) { - try { const mm = await chain.member(id); row.buyerCount = mm.buyerCount; row.counted = mm.countedAsBuyer; row.sponsorId = mm.sponsorId; } catch (e) {} - row.credits = balPer[id] != null ? balPer[id] : 0; - row.noPayout = await payoutChainBlocked(id, 3); // linkage only: a buy from here would pay a listed wallet - } - out.push(row); - } - const main = { address: (acct && acct.address) || null, memberId: mainId, credits: 0, buyerCount: 0 }; - if (mainId) { - main.credits = balPer[mainId] != null ? balPer[mainId] : 0; - try { main.buyerCount = (await chain.member(mainId)).buyerCount; } catch (e) {} - main.noPayout = await payoutChainBlocked(mainId, 3); - } - // live POL balances (the link signature proved the wallet is theirs) + a POL/USD rate from the catalog - const bal = async a => { try { return BigInt(await chain.rpc('eth_getBalance', [a, 'latest'])).toString(); } catch (e) { return null; } }; - if (main.address) main.balanceWei = await bal(main.address); - for (const row of out) row.balanceWei = await bal(row.address); - let polUsd = 0; try { const cat = await chain.catalog(); const pk = cat.find(x => x.costWei); if (pk) polUsd = (pk.priceCents / 100) / (Number(BigInt(pk.costWei)) / 1e18); } catch (e) {} - return json(res, 200, { main, positions: out, polUsd, totalCredits: main.credits + out.reduce((n, r) => n + r.credits, 0), credited }); - } - if (p === '/api/my/positions/remove' && req.method === 'POST') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const b = await readBody(req); - const r = await accounts.removePosition(s.email, b.address); - return json(res, r.error ? 400 : 200, r); - } - // -- coaching: every direct's ladder rung, stalled flag, and what to say - // -- holding tank: waiting members, my adoptions, adopt, release (pay it forward) - // -- promo code typed on the dashboard - if (p === '/api/my/promo/redeem' && req.method === 'POST') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const b = await readBody(req); - const g = await promos.redeem(b.code, s.email, 'dashboard'); - if (g.error) return json(res, 400, g); - await ads.addEarned(s.email, g.credits); - return json(res, 200, { ok: true, credits: g.credits, code: g.code, partner: g.partner }); - } - // -- admin: member card. GET ?q= resolves email / @username / #id / share code / wallet; - // PATCH edits username, sponsor, main wallet or grants credits; DELETE removes a free account (2026-09-13) - if (p === '/api/admin/member' && req.method === 'GET') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - const q = u.searchParams.get('q') || u.searchParams.get('email') || ''; - const a = await adminMember.resolve(q); - if (!a) return json(res, 404, { error: 'No member matches "' + q.slice(0, 60) + '".' }); - return json(res, 200, await adminMember.view(a.email)); - } - if (p === '/api/admin/member' && req.method === 'PATCH') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - const b = await readBody(req); - const e = String(b.email || '').trim().toLowerCase(); const acct = e && await accounts.byEmail(e); - if (!acct) return json(res, 404, { error: 'No such member.' }); - if (b.username !== undefined) { - const un = String(b.username || '').trim().toLowerCase(); - if (!/^[a-z0-9_]{3,20}$/.test(un)) return json(res, 400, { error: 'Username: 3 to 20 letters, numbers or underscore.' }); - const r = await accounts.setUsername(e, un); if (r.error) return json(res, 400, r); - console.log('admin username', e, un); - } - if (b.sponsorRef !== undefined) { const r = await accounts.setSponsorRef(e, String(b.sponsorRef || '').trim()); if (r.error) return json(res, 400, r); console.log('admin sponsor', e, String(b.sponsorRef || '').trim()); } - if (b.address !== undefined) { - const a = String(b.address || '').trim().toLowerCase(); - if (a && !/^0x[0-9a-f]{40}$/.test(a)) return json(res, 400, { error: 'That is not a wallet address.' }); - const r = await accounts.adminSetAddress(e, a || null); if (r.error) return json(res, 400, r); - let mid = 0; if (a) { try { mid = Number(await chain.memberIdByAccount(a)) || 0; } catch (x) {} } - await accounts.setMemberId(e, mid); - if (db.enabled()) await db.q('UPDATE sessions SET address=?, member_id=? WHERE email=?', [a || null, mid || null, e]).catch(() => {}); - console.log('admin wallet swap', e, a || '(none)', 'member', mid); - } - if (b.grantCredits !== undefined) { - const n = Math.round(Number(b.grantCredits)); - if (!(n > 0) || n > 100000) return json(res, 400, { error: 'Credits: a whole number from 1 to 100,000.' }); - await ads.addEarned(e, n); - console.log('admin credits', e, n, String(b.note || '').slice(0, 100)); - } - return json(res, 200, await adminMember.view(e)); - } - if (p === '/api/admin/member' && req.method === 'DELETE') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - const e = String(u.searchParams.get('email') || '').trim().toLowerCase(); const acct = e && await accounts.byEmail(e); - if (!acct) return json(res, 404, { error: 'No such member.' }); - if (acct.memberId) return json(res, 400, { error: 'Member #' + acct.memberId + ' is registered on-chain and cannot be deleted.' }); - const pos = await accounts.positions(e); if (pos.some(x => x.memberId)) return json(res, 400, { error: 'This account owns a registered position and cannot be deleted.' }); - const r = await accounts.removeAccount(e); if (r.error) return json(res, 400, r); - if (db.enabled()) await db.q('DELETE FROM sessions WHERE email=?', [e]).catch(() => {}); - console.log('admin removed account', e); - return json(res, 200, { ok: true }); - } - // -- release notes + roadmap (public read; admin write) (Marty, 2026-09-14) - if (p === '/api/releases' && req.method === 'GET') return json(res, 200, releases.publicView()); - // -- promo toolkit: tiers by badge + the AI Copy Engine (Surge+), credits beyond the free allowance - if (p === '/api/my/toolkit' && req.method === 'GET') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - return json(res, 200, await toolkit.status(s.email)); - } - if (p === '/api/my/toolkit/generate' && req.method === 'POST') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const b = await readBody(req); - const r = await toolkit.generate(s.email, String(b.kind || ''), String(b.brief || ''), String(b.angle || 'plain')); - return json(res, r.error ? 400 : 200, r); - } - if (p === '/api/my/toolkit/template' && req.method === 'POST') { // Spark: one-tap campaign aimed at the member's link - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const b = await readBody(req); const memberId = await auth.refreshMemberId(s); - const r = await toolkit.template(s.email, memberId, (await myMemberIds(s)).ids, String(b.kind || ''), Number(b.budget) || 0); - return json(res, r.error ? 400 : 200, r); - } - if (p === '/api/my/toolkit/split' && req.method === 'GET') { // Circuit: per-angle views/joins/buyers for the member's link - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - return json(res, 200, await toolkit.split(s.email)); - } - if (p === '/api/my/toolkit/videos' && req.method === 'GET') { // Circuit: Video Maker list - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - return json(res, 200, await toolkit.videos(s.email)); - } - if (p === '/api/my/toolkit/video' && req.method === 'POST') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const b = await readBody(req); - const r = await toolkit.makeVideo(s.email, String(b.slug || '')); - return json(res, r.error ? 400 : 200, r); - } - if (p === '/api/my/toolkit/team' && req.method === 'GET') { // Nexus: Leader Ops - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - return json(res, 200, await toolkit.team(s.email)); - } - if (p === '/api/my/toolkit/nudge' && req.method === 'POST') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const b = await readBody(req); const memberId = await auth.refreshMemberId(s); - const r = await toolkit.nudge(s.email, memberId, String(b.email || ''), String(b.text || '')); - return json(res, r.error ? 400 : 200, r); - } - if (p === '/api/my/toolkit/grant' && req.method === 'POST') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const b = await readBody(req); - const r = await toolkit.grant(s.email, String(b.email || ''), Number(b.credits) || 0); - if (r.ok) pushFeed({ type: 'Grant', from: r.fromName, to: r.toName, credits: r.credits, ts: Date.now() }); - return json(res, r.error ? 400 : 200, r); - } - if (p === '/api/my/toolkit/promo' && req.method === 'POST') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const b = await readBody(req); - const r = await toolkit.partnerCode(s.email, String(b.code || ''), Number(b.credits) || 0); - return json(res, r.error ? 400 : 200, r); - } - if (p === '/api/admin/toolkit' && req.method === 'GET') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - return json(res, 200, await toolkit.adminUsage()); - } - if (p === '/api/leaderboard' && req.method === 'GET') { // public standings; signed-in members also get their own row - const s = await auth.fromRequest(req); - const period = ['week', 'month', 'all', 'lastweek', 'lastmonth'].includes(u.searchParams.get('period')) ? u.searchParams.get('period') : 'week'; - return json(res, 200, await leaderboard.view(period, s && s.email ? s.email : null)); - } - if (p === '/api/admin/updates' && req.method === 'GET') { // member update emails: notes, audiences, log - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - const since = updates.lastSentAt(); - return json(res, 200, Object.assign({ notes: releases.notes().map(n => ({ id: n.id, title: n.title, date: n.date, fresh: !since || (n.created || 0) > since || (n.date && new Date(n.date + 'T12:00:00Z').getTime() > since) })), audiences: updates.AUDIENCES, counts: await updates.counts(), mailer: mailer.hasKey(), lastSentAt: since, draft: updates.draft() }, updates.status())); - } - if (p === '/api/admin/updates/draft' && req.method === 'POST') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - return json(res, 200, { ok: true, draft: updates.saveDraft(await readBody(req)) }); - } - if (p === '/api/admin/updates/preview' && req.method === 'POST') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - const b = await readBody(req); - return json(res, 200, updates.compose({ subject: b.subject, intro: b.intro, closing: b.closing, noteIds: (b.noteIds || []).map(String) }, { email: ADMIN_EMAIL, username: 'you' })); - } - if (p === '/api/admin/updates/send' && req.method === 'POST') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - const b = await readBody(req); - const r = await updates.send({ subject: b.subject, intro: b.intro, closing: b.closing, noteIds: (b.noteIds || []).map(String), audience: b.audience, to: Array.isArray(b.to) ? b.to.slice(0, 5000) : null }, { test: !!b.test }); - return json(res, r.error ? 400 : 200, r); - } - if (p === '/api/admin/releases' && req.method === 'GET') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - return json(res, 200, { notes: releases.notes(), roadmap: releases.roadmap(), tags: releases.TAGS, statuses: releases.STATUSES }); - } - if (p === '/api/admin/releases' && req.method === 'POST') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - const b = await readBody(req); - const r = b.kind === 'roadmap' ? releases.saveRoadmap(b) : releases.saveNote(b); - return json(res, r.error ? 400 : 200, r); - } - if (p === '/api/admin/releases' && req.method === 'DELETE') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - return json(res, 200, releases.remove(u.searchParams.get('kind'), String(u.searchParams.get('id') || ''))); - } - // -- admin: blog (list all incl. drafts, save/create, delete) (Marty, 2026-09-12) - if (p === '/api/admin/blog' && req.method === 'GET') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - const slug = u.searchParams.get('slug'); - if (slug) { const post = await blog.get(slug); return post ? json(res, 200, { post }) : json(res, 404, { error: 'No such post.' }); } - return json(res, 200, { syndication: syndicate.enabled(), posts: (await blog.listAll()).map(x => ({ slug: x.slug, title: x.title, status: x.status, tags: x.tags, publishedAt: x.publishedAt, updated: x.updated, views: x.views, excerpt: x.excerpt, cover: x.cover, syndicated: syndicate.statusOf(x.slug) })) }); - } - if (p === '/api/admin/blog' && req.method === 'POST') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - const b = await readBody(req); - const before = b.existingSlug ? await blog.get(b.existingSlug) : null; - const r = await blog.save(b, b.existingSlug || null); - if (r.ok && r.post.status === 'published' && (!before || before.status !== 'published') && !b.noSyndicate) { - // first time this article goes live: push it to X + Instagram (never repeated for the same slug) - syndicate.publish(r.post).catch(e => console.error('syndication', e.message)); - r.syndicating = syndicate.enabled(); - } - r.syndicated = syndicate.statusOf(r.post.slug); - return json(res, r.error ? 400 : 200, r); - } - if (p === '/api/admin/blog/syndicate' && req.method === 'POST') { // manual: post (or retry) a published article - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - const b = await readBody(req); - const post = await blog.get(String(b.slug || '')); - if (!post) return json(res, 404, { error: 'No such post.' }); - if (post.status !== 'published') return json(res, 400, { error: 'Publish the article first.' }); - if (!syndicate.enabled()) return json(res, 400, { error: 'No Blotato key on the server.' }); - const st = await syndicate.publish(post, { force: !!b.force }); - return json(res, 200, { ok: true, syndicated: st }); - } - if (p === '/api/admin/blog' && req.method === 'DELETE') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - const slug = u.searchParams.get('slug'); if (!slug) return json(res, 400, { error: 'slug' }); - return json(res, 200, await blog.remove(slug)); - } - // -- admin: promo codes (create/update, switch on/off, redemptions) - if (p === '/api/admin/promos' && req.method === 'GET') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - return json(res, 200, await promos.adminView()); - } - if (p === '/api/admin/promos' && req.method === 'POST') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - const b = await readBody(req); - const r = await promos.create(b); - return json(res, r.error ? 400 : 200, r); - } - if (p === '/api/admin/promos' && req.method === 'PATCH') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - const b = await readBody(req); - const r = await promos.setActive(b.code, !!b.active); - return json(res, r.error ? 400 : 200, r); - } - // -- username suggestion for the required first step (Marty, 2026-09-12): email prefix, cleaned, unique - if (p === '/api/my/username-suggest' && req.method === 'GET') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - let base = String(s.email).split('@')[0].toLowerCase().replace(/[^a-z0-9_]/g, '').slice(0, 18); - if (!/[a-z]/.test(base)) base = 'member' + base; - if (base.length < 3) base = (base + 'xyz').slice(0, 3); - let pick = base; - for (let i = 2; i < 100 && await accounts.byUsername(pick); i++) pick = base.slice(0, 20 - String(i).length) + i; - return json(res, 200, { suggest: pick }); - } - if (p === '/api/my/tank' && req.method === 'GET') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - return json(res, 200, await tank.view(s.email)); - } - // -- achievement badge -> Telegram (payments topic + the main group), once per badge per member. - // The browser composes the personalised image (canvas, same as Share) and posts it here. - if (p === '/api/my/badge-post' && req.method === 'POST') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const key = String(u.searchParams.get('key') || ''); - if (!BADGE_META[key]) return json(res, 400, { error: 'Unknown badge.' }); - if (!/^image\/jpeg/.test(String(req.headers['content-type'] || ''))) return json(res, 400, { error: 'Send the badge as a JPEG.' }); - let jpeg; try { jpeg = await readRaw(req, 1.5 * 1024 * 1024); } catch (e) { return json(res, 413, { error: 'Image too large.' }); } - if (!jpeg || jpeg.length < 2000 || jpeg[0] !== 0xff || jpeg[1] !== 0xd8) return json(res, 400, { error: 'That is not a JPEG.' }); - const held = await ads.milestonesOf(s.email); - if (!held.includes(key)) return json(res, 400, { error: 'You have not unlocked that badge yet.' }); - const log = badgeLog(); const mine = log[s.email] || {}; - if (mine[key]) return json(res, 200, { ok: true, already: true }); - // manual re-posts (the button) are Marty's only; members' badges go out automatically on unlock - if (u.searchParams.get('manual') === '1' && s.email !== ADMIN_EMAIL) return json(res, 403, { error: 'Badges post automatically when they unlock.' }); - const a = await accounts.byEmail(s.email); - const who = a && a.username ? '@' + a.username : (a && a.memberId ? 'member #' + a.memberId : 'a member'); - const link = a && a.username ? SITE_HOST + '/join/' + a.username : SITE_HOST; - const [label, sub] = BADGE_META[key]; - const caption = '\u{1F3C6} LinkSpin \u00b7 ' + who.replace(/[<>&]/g, '') + ' unlocked ' + label + ': ' + sub + '\n' + link; - const sc = siteConfig(); let sent = 0; - if (sc.telegramBotToken && sc.telegramEchoChatId) { - if (await telegramSendPhoto(sc.telegramEchoChatId, jpeg, caption, sc.telegramEchoTopicId)) sent++; // payments topic - if (String(sc.telegramBadgeGeneral || '1') !== '0' && await telegramSendPhoto(sc.telegramEchoChatId, jpeg, caption, null)) sent++; // the main group (General) - } - mine[key] = { ts: Date.now(), sent }; log[s.email] = mine; try { fs.writeFileSync(BADGE_LOG(), JSON.stringify(log)); } catch (e) {} - pushFeed({ type: 'Badge', member: who, label, ts: Date.now() }); - console.log('badge posted', s.email, key, 'sent', sent); - return json(res, 200, { ok: true, sent }); - } - // -- member's own share: store the composed badge so a public page can carry it as the preview image - if (p === '/api/my/badge-image' && req.method === 'POST') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const key = String(u.searchParams.get('key') || ''); - if (!BADGE_META[key]) return json(res, 400, { error: 'Unknown badge.' }); - let jpeg; try { jpeg = await readRaw(req, 1.5 * 1024 * 1024); } catch (e) { return json(res, 413, { error: 'Image too large.' }); } - if (!jpeg || jpeg.length < 2000 || jpeg[0] !== 0xff || jpeg[1] !== 0xd8) return json(res, 400, { error: 'That is not a JPEG.' }); - if (!(await ads.milestonesOf(s.email)).includes(key)) return json(res, 400, { error: 'You have not unlocked that badge yet.' }); - const a = await accounts.byEmail(s.email); - if (!a || !a.username) return json(res, 400, { error: 'Pick a username first; the share page carries it.' }); - fs.writeFileSync(path.join(UPLOADS_DIR, 'badge-' + a.username + '-' + key + '.jpg'), jpeg); - return json(res, 200, { ok: true, page: SITE_URL + '/b/' + a.username + '/' + key, image: SITE_URL + '/badge-img/' + a.username + '/' + key + '.jpg' }); - } - if (p === '/api/my/badge-posted' && req.method === 'GET') { // which of my badges are already on Telegram - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - return json(res, 200, { posted: Object.keys(badgeLog()[s.email] || {}), canPost: s.email === ADMIN_EMAIL }); - } - if (p === '/api/my/tank/adopt' && req.method === 'POST') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const b = await readBody(req); - const r = await tank.adopt(s.email, b.who, b.note); - if (r.ok) { // tell the payments topic who picked whom up (Marty, 2026-09-12) - pushFeed({ type: 'Adopted', sponsor: r.adopterName, member: r.adopteeName, ts: Date.now() }); - try { - const sc = siteConfig(); - const clean = t => String(t || '').replace(/[<>&]/g, ''); - if (sc.telegramBotToken && sc.telegramEchoChatId) - telegramSend(sc.telegramEchoChatId, '\u{1F91D} LinkSpin \u00b7 ' + clean(r.adopterName) + ' picked up ' + clean(r.adopteeName) + ' from the holding tank and is now their sponsor', sc.telegramEchoTopicId).catch(() => {}); - } catch (e) {} - } - return json(res, r.error ? 400 : 200, r); - } - if (p === '/api/my/tank/release' && req.method === 'POST') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const b = await readBody(req); - const r = await tank.release(s.email, b.email); - if (r.ok) { // the feed shows releases too, so a pickup-and-drop is visible for what it is (Marty, 2026-09-13) - pushFeed({ type: 'Released', sponsor: r.ownerName, member: r.memberName, ts: Date.now() }); - try { - const sc = siteConfig(); - const clean = t => String(t || '').replace(/[<>&]/g, ''); - if (sc.telegramBotToken && sc.telegramEchoChatId) - telegramSend(sc.telegramEchoChatId, '\u{1FAA3} LinkSpin \u00b7 ' + clean(r.ownerName) + ' returned ' + clean(r.memberName) + ' to the holding tank', sc.telegramEchoTopicId); - } catch (e) {} - } - return json(res, r.error ? 400 : 200, r); - } - if (p === '/api/my/tank/contacted' && req.method === 'POST') { // sponsor reached the lead off-site: reset the rescue clock - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const b = await readBody(req); - const r = await tank.markContacted(s.email, b.email); - return json(res, r.error ? 400 : 200, r); - } - if (p === '/api/my/gift' && req.method === 'POST') { // PIF: log a wallet-to-wallet POL gift and tell the recipient - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const b = await readBody(req); - const r = await tank.recordGift(s.email, b.email, b.tx, b.pol); - return json(res, r.error ? 400 : 200, r); - } - if (p === '/api/admin/tank' && req.method === 'GET') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - return json(res, 200, await tank.adminView()); - } - // -- admin Traffic tab: page views + join-page views + signups + $20 buyers, by referring - // domain / first-touch source, by landing page, by angle and by day (Marty, 2026-09-12) - if (p === '/api/admin/traffic' && req.method === 'GET') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - const days = Math.min(365, Math.max(1, Number(u.searchParams.get('days')) || 30)); - const since = Date.now() - days * 86400000, sinceDay = new Date(since).toISOString().slice(0, 10); - const hosts = {}, paths = {}, daily = {}, angles = {}; - const H = k => (hosts[k] = hosts[k] || { source: k, hits: 0, joinViews: 0, signups: 0, registered: 0, buyers: 0 }); - const Dy = k => (daily[k] = daily[k] || { day: k, hits: 0, signups: 0 }); - for (const r of await traffic.rows(sinceDay)) { H(r.host).hits += r.n; paths[r.path] = (paths[r.path] || 0) + r.n; Dy(r.day).hits += r.n; } - for (const v of await coach.viewsSince(since)) { H(v.ref || 'direct').joinViews += 1; const a = angles[v.angle || 'plain'] = angles[v.angle || 'plain'] || { angle: v.angle || 'plain', views: 0, signups: 0 }; a.views += 1; } - const buyerIds = new Set(); for (const ev of chain.recentEvents(1e9)) if (ev.type === 'BuyerCounted' && ev.newBuyerId) buyerIds.add(ev.newBuyerId); - for (const a of await accounts.listAll(5000)) { - if (!a.created || a.created < since) continue; - const h = H(a.joinedRef || 'direct'); h.signups += 1; if (a.memberId) h.registered += 1; if (a.memberId && buyerIds.has(a.memberId)) h.buyers += 1; - Dy(new Date(a.created).toISOString().slice(0, 10)).signups += 1; - const k = a.joinedVia || 'plain'; angles[k] = angles[k] || { angle: k, views: 0, signups: 0 }; angles[k].signups += 1; - } - const sources = Object.values(hosts).sort((x, y) => (y.hits + y.joinViews + y.signups * 10) - (x.hits + x.joinViews + x.signups * 10)); - return json(res, 200, { days, sources, paths: Object.entries(paths).map(([path, hits]) => ({ path, hits })).sort((x, y) => y.hits - x.hits), - angles: Object.values(angles).sort((x, y) => y.views - x.views), daily: Object.values(daily).sort((x, y) => x.day < y.day ? -1 : 1), - totals: { hits: sources.reduce((n, s) => n + s.hits, 0), joinViews: sources.reduce((n, s) => n + s.joinViews, 0), signups: sources.reduce((n, s) => n + s.signups, 0), buyers: sources.reduce((n, s) => n + s.buyers, 0) } }); - } - if (p === '/api/my/coach' && req.method === 'GET') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const cv = await coach.coachView(s.email); - for (const d of cv.directs) if (d.free) { try { d.rescue = await tank.rescueInfo(s.email, await accounts.byEmail(d.email)); } catch (e) {} } // dormant-lead clock - return json(res, 200, cv); - } - // -- link stats: views, joins and buyers per angle link - if (p === '/api/my/linkstats' && req.method === 'GET') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - return json(res, 200, await coach.linkStats(s.email)); - } - // -- prospects: the member's own follow-up list - // -- Pipeline: the follow-up board (stages from the ledger and the site; notes, follow-ups, tags from the sponsor) - if (p === '/api/my/pipeline' && req.method === 'GET') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const sc = siteConfig(); - if (!pipeline.visible(sc.pipelineMode, s.email, ADMIN_EMAIL)) return json(res, 200, { live: false, eta: sc.pipelineEta || '' }); - const b = await pipeline.board(s.email); - return json(res, 200, Object.assign({ live: true }, b), { 'Cache-Control': 'no-store' }); - } - if (p === '/api/my/pipeline/note' && req.method === 'POST') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - if (!pipeline.visible(siteConfig().pipelineMode, s.email, ADMIN_EMAIL)) return json(res, 403, { error: 'The Pipeline is not open yet.' }); - const r = await pipeline.save(s.email, await readBody(req)); - return json(res, r.error ? 400 : 200, r); - } - // -- the rotator (LinkSpin core tool) - if (p === '/api/my/rotations' && req.method === 'GET') { - const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const sc = siteConfig(); const hosts = String(sc.linkDomains || '').split(',').map(x => x.trim()).filter(Boolean); - return json(res, 200, { rotations: await rotator.list(s.email), hosts: hosts.length ? hosts : [SITE_HOST] }, { 'Cache-Control': 'no-store' }); - } - if (p === '/api/my/rotations' && req.method === 'POST') { - const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const r = await rotator.create(s.email, await readBody(req)); return json(res, r.error ? 400 : 200, r); - } - m = /^\/api\/my\/rotations\/(\d+)$/.exec(p); - if (m && req.method === 'POST') { - const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const b = await readBody(req); const r = b.remove ? await rotator.remove(s.email, m[1]) : await rotator.update(s.email, m[1], b); return json(res, r.error ? 400 : 200, r); - } - m = /^\/api\/my\/rotations\/(\d+)\/dest$/.exec(p); - if (m && req.method === 'POST') { - const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const r = await rotator.addDest(s.email, m[1], await readBody(req)); return json(res, r.error ? 400 : 200, r); - } - m = /^\/api\/my\/rotations\/(\d+)\/dest\/(\d+)$/.exec(p); - if (m && req.method === 'POST') { - const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const r = await rotator.updateDest(s.email, m[1], m[2], await readBody(req)); return json(res, r.error ? 400 : 200, r); - } - m = /^\/api\/my\/rotations\/(\d+)\/stats$/.exec(p); - if (m && req.method === 'GET') { - const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const r = await rotator.stats(s.email, m[1]); return r ? json(res, 200, r, { 'Cache-Control': 'no-store' }) : json(res, 404, { error: 'No such rotation.' }); - } - m = /^\/api\/my\/rotations\/(\d+)\/health$/.exec(p); // "Check now": fresh health states for every destination (once a minute per rotation) - if (m && req.method === 'POST') { - const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const r = await health.checkRotation(s.email, m[1]); return json(res, r.error ? (/No such/.test(r.error) ? 404 : 429) : 200, r, { 'Cache-Control': 'no-store' }); - } - if (p === '/api/my/strip' && req.method === 'GET') { // status strip under every Control Room screen - const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - let served = 0; try { served = (await rotator.summary(s.email, 1)).totals.served; } catch (e) {} - let zonesLive = 0; try { zonesLive = (await zones.list(s.email)).filter(z => z.active && z.status !== 'paused').length; } catch (e) {} - return json(res, 200, { ok: true, served, zones: zonesLive, network: nas.enabled() }, { 'Cache-Control': 'no-store' }); - } - if (p === '/api/my/zones' && req.method === 'GET') { - const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - return json(res, 200, { zones: await zones.list(s.email), host: SITE_HOST, sizes: Object.keys(zones.SIZES), networkSizes: Array.from(zones.NAS_SIZES), tiers: zones.TIERS, rates: zones.settings(), warmup: zones.WARMUP, holdRatio: zones.HOLD_RATIO }, { 'Cache-Control': 'no-store' }); - } - if (p === '/api/my/zones' && req.method === 'POST') { - const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const r = await zones.create(s.email, await readBody(req)); return json(res, r.error ? 400 : 200, r); - } - m = /^\/api\/my\/zones\/(ls-[a-f0-9]{6})$/.exec(p); - if (m && req.method === 'POST') { - const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const r = await zones.update(s.email, m[1], await readBody(req)); return json(res, r.error ? 400 : 200, r); - } - // tester invite: an admin-minted one-time sign-in link (24 h). Creates the account if needed, bypasses the sign-up - // gate and needs no email, which is what a curtained test app without outbound mail needs (2026-09-29) - if (p === '/api/admin/invite' && req.method === 'POST') { - if (!isAdmin(req)) return json(res, 401, { error: 'Admin only.' }); - const b = await readBody(req); const e = String(b.email || '').trim().toLowerCase(); - if (!/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(e)) return json(res, 400, { error: 'Which email?' }); - const r = await accounts.ensure(e, '', '', null); if (r.error) return json(res, 400, r); - const token = crypto.randomBytes(24).toString('hex'); - inviteTokens.set(token, { email: e, exp: Date.now() + 24 * 3600 * 1000, next: /^\/[a-z]/.test(String(b.next || '')) ? String(b.next) : '/ads' }); - return json(res, 200, { ok: true, url: 'https://' + SITE_HOST + '/welcome/' + token, created: !!r.created }); - } - if (p === '/api/admin/zones' && req.method === 'GET') { - if (!isAdmin(req)) return json(res, 401, { error: 'Admin only.' }); - return json(res, 200, { zones: await zones.adminList(), totals: zones.totals(), publishers: zones.publisherTotals(7), rates: zones.settings(), tiers: zones.TIERS, warmup: zones.WARMUP, holdRatio: zones.HOLD_RATIO }, { 'Cache-Control': 'no-store' }); - } - // admin: pause/resume, note, and the publisher tier ({ tier: 'standard' | 'verified' }; /tier is an alias for the same update) - m = /^\/api\/admin\/zones\/(ls-[a-f0-9]{6})(\/tier)?$/.exec(p); - if (m && req.method === 'POST') { - if (!isAdmin(req)) return json(res, 401, { error: 'Admin only.' }); - const r = await zones.adminSet(m[1], await readBody(req)); return json(res, r.error ? 400 : 200, r); - } - // -- hosted page images: /u/pages//., only files the pages index knows, a year of cache (2026-10-10) - m = /^\/u\/pages\/([a-f0-9]{16})\/([a-f0-9]{12})\.(png|jpg|webp)$/.exec(p); - if (m && (req.method === 'GET' || req.method === 'HEAD')) { - const f = pages.imageFile(m[1], m[2], m[3]); if (!f) { res.writeHead(404, { 'Content-Type': 'text/plain' }); return res.end('Not found'); } - return fs.readFile(f.file, (err, data) => { if (err) { res.writeHead(404, { 'Content-Type': 'text/plain' }); return res.end('Not found'); } res.writeHead(200, { 'Content-Type': f.mime, 'Content-Length': String(data.length), 'Cache-Control': 'public, max-age=31536000, immutable', 'X-Content-Type-Options': 'nosniff', 'Content-Disposition': 'inline', 'Access-Control-Allow-Origin': '*' }); res.end(req.method === 'HEAD' ? '' : data); }); - } - // -- the link-domain pool for the member Links screen: live (not burned, not reserve) hosts with their channel - if (p === '/api/my/link-hosts' && (req.method === 'GET' || req.method === 'POST')) { // the shell's api() helper posts (2026-10-10) - const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const hs = domains.hosts(); return json(res, 200, { hosts: hs.length ? hs : [{ host: SITE_HOST, channel: 'email', label: 'Email', note: 'The app host (no link domains are live)' }], channels: domains.CHANNELS }, { 'Cache-Control': 'no-store' }); - } - if (p === '/api/my/pages' && req.method === 'GET') { - const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const hosts = domains.live(); // burned or reserve domains are never handed out for new pages - const ph = pagesHost(); const pageBase = ph ? 'https://' + ph + '/' : 'https://' + (hosts[0] || SITE_HOST) + '/p/'; - return json(res, 200, { pages: await pages.list(s.email), hosts: ph ? [ph] : (hosts.length ? hosts : [SITE_HOST]), pageBase, types: pages.TYPES, styles: require('./pagestyle').catalog(), providers: pages.providers(), images: await pages.images(s.email), imageMax: pages.IMG_MAX, imageBytes: pages.IMG_BYTES }, { 'Cache-Control': 'no-store' }); - } - if (p === '/api/my/pages/upload' && req.method === 'POST') { - const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const up = await pages.readUpload(req); if (up.error) return json(res, 400, up); - const r = await pages.uploadImage(s.email, up.buf, up.ct); return json(res, r.error ? 400 : 200, r); - } - m = /^\/api\/my\/pages\/images\/([a-f0-9]{12})$/.exec(p); - if (m && req.method === 'POST') { - const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const b = await readBody(req); if (!b.remove) return json(res, 400, { error: 'Nothing to do.' }); - const r = await pages.removeImage(s.email, m[1]); return json(res, r.error ? 400 : 200, r); - } - // -- admin: the link-domain pool (channel per domain, last safety check, burned flag, check now / clear / pull) - if (p === '/api/admin/domains' && req.method === 'GET') { - if (!isAdmin(req)) return json(res, 401, { error: 'Admin only.' }); - return json(res, 200, { domains: domains.all(), channels: domains.CHANNELS, labels: domains.LABEL, notes: domains.NOTE, gsb: !!String(process.env.GSB_API_KEY || '').trim() }, { 'Cache-Control': 'no-store' }); - } - if (p === '/api/admin/domains' && req.method === 'POST') { - if (!isAdmin(req)) return json(res, 401, { error: 'Admin only.' }); - const b = await readBody(req); let r; - if (b.action === 'check') r = b.domain ? await domains.check(b.domain) : { ok: true, results: await domains.checkAll() }; - else if (b.action === 'channel') r = domains.setChannel(b.domain, b.channel); - else if (b.action === 'clear') r = domains.clear(b.domain); - else if (b.action === 'burn') r = domains.burn(b.domain, b.reason); - else r = { error: 'Unknown action.' }; - return json(res, r.error ? 400 : 200, Object.assign(r, { domains: domains.all() })); - } - if (p === '/api/my/pages' && req.method === 'POST') { - const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const r = await pages.create(s.email, await readBody(req)); return json(res, r.error ? 400 : 200, r); - } - if (p === '/api/my/pages/scan' && req.method === 'POST') { - const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const b = await readBody(req); const r = await pages.scan(b.url); return json(res, r.error ? 400 : 200, r); - } - if (p === '/api/my/pages/leads' && req.method === 'GET') { - const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - return json(res, 200, { leads: await pages.leads(s.email, u.searchParams.get('page') || null) }, { 'Cache-Control': 'no-store' }); - } - if (p === '/api/my/pages/leads.csv' && req.method === 'GET') { - const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const rows = await pages.leads(s.email, u.searchParams.get('page') || null); - res.writeHead(200, { 'Content-Type': 'text/csv; charset=utf-8', 'Content-Disposition': 'attachment; filename="linkspin-leads.csv"', 'Cache-Control': 'no-store' }); return res.end(pages.csv(rows)); - } - m = /^\/api\/my\/pages\/([a-f0-9]{10})(\/write)?$/.exec(p); - if (m && req.method === 'POST') { - const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const b = await readBody(req); const r = m[2] ? await pages.write(s.email, m[1], b) : await pages.update(s.email, m[1], b); return json(res, r.error ? 400 : 200, r); - } - if (p === '/api/my/reports' && req.method === 'GET') { - const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const days = Math.max(1, Math.min(365, Number(u.searchParams.get('days')) || 30)); - // spins (the rotator summary, spread at the top level so older report screens keep working) + pages + zones (2026-10-10) - const [spins, pg, zn] = await Promise.all([rotator.summary(s.email, days), pages.summary(s.email, days), zonereport.summary(s.email, days)]); - return json(res, 200, Object.assign({}, spins, { spins, pages: pg, zones: zn, days: spins.days, range: days }), { 'Cache-Control': 'no-store' }); - } - // -- traffic sources (2026-10-12). Every route takes GET and POST: the shell's api() helper always POSTs. - if (p === '/api/sources/catalog' && (req.method === 'GET' || req.method === 'POST')) return json(res, 200, { catalog: sources.catalog(), keys: sources.KEYS }, { 'Cache-Control': 'public, max-age=300' }); - if (p === '/api/my/sources' && (req.method === 'GET' || req.method === 'POST')) { - const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const b = req.method === 'POST' ? await readBody(req) : {}; - if (req.method === 'GET' || b.list || !Object.keys(b).length) return json(res, 200, await sources.list(s.email), { 'Cache-Control': 'no-store' }); - const r = await sources.create(s.email, b); return json(res, r.error ? 400 : 200, r); - } - m = /^\/api\/my\/sources\/([a-f0-9]{10})(\/url)?$/.exec(p); - if (m && (req.method === 'GET' || req.method === 'POST')) { - const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const b = req.method === 'POST' ? await readBody(req) : {}; for (const [k, v] of u.searchParams) if (b[k] == null) b[k] = v; - if (m[2]) { const r = await sources.urlFor(s.email, m[1], b.rotationId); return json(res, r.error ? 400 : 200, r, { 'Cache-Control': 'no-store' }); } - if (req.method === 'GET' || !Object.keys(b).length) { const r = await sources.get(s.email, m[1]); return r ? json(res, 200, r, { 'Cache-Control': 'no-store' }) : json(res, 404, { error: 'No such source.' }); } - const r = b.test ? await sources.test(s.email, m[1]) : await sources.update(s.email, m[1], b); return json(res, r.error ? 400 : 200, r); - } - if (p === '/api/my/postbacks' && req.method === 'GET') { - const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - return json(res, 200, { postbacks: await postbacks.list(s.email), events: postbacks.EVENTS, key: postbacks.partnerKey(s.email), inboundUrl: 'https://' + SITE_HOST + '/pb/in', log: await postbacks.logFor(s.email, 40) }, { 'Cache-Control': 'no-store' }); - } - if (p === '/api/my/postbacks' && req.method === 'POST') { - const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const b = await readBody(req); if (b.rotateKey) return json(res, 200, { ok: true, key: postbacks.rotateKey(s.email) }); - const r = await postbacks.create(s.email, b); return json(res, r.error ? 400 : 200, r); - } - m = /^\/api\/my\/postbacks\/([a-f0-9]{10})$/.exec(p); - if (m && req.method === 'POST') { - const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const b = await readBody(req); const r = b.test ? await postbacks.test(s.email, m[1]) : await postbacks.update(s.email, m[1], b); return json(res, r.error ? 400 : 200, r); - } - if (p === '/pb/in' && (req.method === 'GET' || req.method === 'POST')) { // partner-reported conversion against our click id - const b = req.method === 'POST' ? await readBody(req).catch(() => ({})) : {}; for (const [k, v] of u.searchParams) if (b[k] == null) b[k] = v; - const r = await postbacks.inbound(b.key, b); return json(res, r.error ? 400 : 200, r, { 'Cache-Control': 'no-store' }); - } - if (p === '/api/my/carry' && req.method === 'GET') { - const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const st = carry.status(); const me = s.email.toLowerCase(); - return json(res, 200, { engine: st.engine, claimDays: st.claimDays, claims: st.claims.filter(c => c.member === me || c.sponsor === me), registry: await registry.get(me) }); - } - if (p === '/api/admin/carry' && req.method === 'GET') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - return json(res, 200, Object.assign(carry.status(), { registryCount: await registry.count(), rotator: rotator.totals() })); - } - if (p === '/api/admin/carry/seed' && req.method === 'POST') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - const b = await readBody(req); return json(res, 200, await carry.seedAll(Number(b.limit) || 0)); - } - // -- live registry sync from InstantAdPay (2026-10-08): signed rows (HMAC LS_SYNC_SECRET over ts + newline + raw body), - // upserted into the registry; new people become shell accounts with their line, existing shells pick up a username, - // wallet or sponsor they did not have. Only the posted rows are touched. - 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) : []; - const n = await registry.importRows(rows, 'instantadpay'); let shells = 0, updated = 0; - for (const r of rows) { - const e = String(r.email || '').trim().toLowerCase(); if (!e) continue; - let a = await accounts.byEmail(e); - if (!a) { const x = await accounts.ensure(e, '', 'carried', 'network'); if (x.created) shells++; a = await accounts.byEmail(e); } - 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; - 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(x => x !== undefined)) { try { await accounts.setProfile(e, upd[0], upd[1], upd[2]); updated++; } catch (err) {} } - } - } - return json(res, 200, { ok: true, rows: rows.length, imported: n, shells, updated, registry: await registry.count() }); - } - 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'); - // every registry row with a sponsor becomes a site account too, so lines exist before anyone signs in - let shells = 0; - if (b.shells) for (const r of await registry.all()) { const a = await accounts.byEmail(r.email); if (!a) { const x = await accounts.ensure(r.email, '', 'carried', 'network'); if (x.created) shells++; if (r.username) { try { await accounts.setUsername(r.email, r.username); } catch (e) {} } if (r.wallet) { try { await accounts.linkWallet(r.email, r.wallet); } catch (e) {} } } } - if (b.shells) for (const r of await registry.all()) { if (!r.sponsorEmail) continue; const a = await accounts.byEmail(r.email); const sp = await accounts.byEmail(r.sponsorEmail); if (a && sp && !a.sponsorRef) await accounts.setSponsorRef(r.email, sp.username || sp.code); } - return json(res, 200, { ok: true, imported: n, shells, registry: await registry.count() }); - } - if (p === '/api/my/prospects' && req.method === 'GET') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - return json(res, 200, { prospects: await coach.prospects(s.email), statuses: coach.STATUSES }); - } - if (p === '/api/my/prospects' && req.method === 'POST') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const r = await coach.saveProspect(s.email, await readBody(req)); - return json(res, r.error ? 400 : 200, r); - } - if (p === '/api/my/prospects/remove' && req.method === 'POST') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const b = await readBody(req); - const r = await coach.removeProspect(s.email, b.id); - return json(res, r.error ? 400 : 200, r); - } - if (p === '/api/my/profile' && req.method === 'POST') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const b = await readBody(req); - const before = await accounts.byEmail(s.email); - // a username is permanent once set: the invite link, the public wall and every - // banner already printed carry it (Marty, 2026-09-10) - if (before && before.username && String(b.username || '').trim().toLowerCase() !== String(before.username).toLowerCase()) - return json(res, 400, { error: 'Your username is locked. Your invite link, your public page and any banners you shared all carry @' + before.username + '. Contact support if it truly has to change.' }); - const r = await accounts.setUsername(s.email, b.username); - // First time a username is set (onboarding): now there's a real name to - // show, so notify the sponsor here rather than at signup (where it'd just - // say "a new member"). Fires once — only on the empty→set transition. - if (!r.error && before && !before.username && b.username) { - const acct = await accounts.byEmail(s.email); - notifyNewReferral(acct && acct.sponsorRef, acct).catch(() => {}); - // everyone's dashboard: "@name just joined" (and whether they are waiting in the tank) - if (acct && acct.username) pushFeed({ type: 'Joined', name: '@' + acct.username, tank: !acct.sponsorRef && !acct.memberId, ts: Date.now() }); - } - return json(res, r.error ? 400 : 200, r); - } - // -- earn credits by viewing ads (attention-gated daily claim) - if (p === '/api/my/earn' && req.method === 'GET') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - return json(res, 200, await ads.viewStatus(s.email)); - } - // fraud-guarded view flow: the server issues a single-use token when it - // serves the ad, and only counts the view if the dwell elapsed on the - // SERVER clock. Client-side focus tracking pauses the countdown; this is - // the floor a script cannot cheat past. - if (p === '/api/my/earnview' && req.method === 'GET') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const status = await ads.viewStatus(s.email); - if (status.views >= status.target || status.claimed) return json(res, 200, { ad: null, status }); - const type = String(u.searchParams.get('type') || 'banner'); - // members never see (or earn from) their own campaigns in the viewer - const ad = await ads.serve(type === 'text' ? 'text' : 'banner', Object.assign({ excludeEmail: s.email }, viewerGeo(req), audiences.matcher(req))); - if (!ad) return json(res, 200, { ad: null, status }); - const token = crypto.randomBytes(16).toString('hex'); - // the viewer tab frames the advertiser's REAL url (no click counted for a paid view) - earnTokens.set(s.email, { token, ts: Date.now(), adId: ad.id, - targetUrl: await ads.targetOf(ad.id), adName: ad.title || ad.name || null }); - return json(res, 200, { ad, token, viewUrl: '/view/' + token, status }); - } - // the viewer tab asks where to point the frame (does not consume the token) - if (p === '/api/my/viewinfo' && req.method === 'GET') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const t = earnTokens.get(s.email); - if (!t || t.token !== String(u.searchParams.get('token') || '')) - return json(res, 400, { error: 'That view is no longer open. Head back to the dashboard and load the next ad.' }); - return json(res, 200, { targetUrl: t.targetUrl, adName: t.adName || null, - dwell: ads.rates().viewDwellSeconds || 10 }); - } - // human check: handed out only once the dwell has elapsed on the SERVER clock - if (p === '/api/my/viewchallenge' && req.method === 'GET') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const t = earnTokens.get(s.email); - if (!t || t.token !== String(u.searchParams.get('token') || '')) - return json(res, 400, { error: 'That view is no longer open.' }); - const dwellMs = (ads.rates().viewDwellSeconds || 10) * 1000; - const age = Date.now() - t.ts; - if (age < dwellMs - 400) return json(res, 200, { early: true, wait: Math.ceil((dwellMs - age) / 1000) }); - if (age > 5 * 60 * 1000) { earnTokens.delete(s.email); return json(res, 400, { error: 'That ad went stale. Load a fresh one.' }); } - const pick = CAPTCHA.slice().sort(() => Math.random() - 0.5).slice(0, 5); - const answer = Math.floor(Math.random() * pick.length); - t.challenge = { answer }; - return json(res, 200, { prompt: pick[answer][1], options: pick.map(x => x[0]) }); - } - if (p === '/api/my/adview' && req.method === 'POST') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const b = await readBody(req); - const t = earnTokens.get(s.email); - const dwellMs = (ads.rates().viewDwellSeconds || 10) * 1000; - if (!t || t.token !== String(b.token || '')) return json(res, 400, { error: 'That view did not check out. Load the next ad and let it finish.' }); - const age = Date.now() - t.ts; - if (age < dwellMs - 400) return json(res, 400, { error: 'Watch the full ad first.' }); - if (age > 5 * 60 * 1000) { earnTokens.delete(s.email); return json(res, 400, { error: 'That ad went stale. Load a fresh one.' }); } - // the human check must be solved on the same token - if (!t.challenge) return json(res, 400, { error: 'Finish the quick check first.', retry: true }); - if (Number(b.answer) !== t.challenge.answer) { - t.attempts = (t.attempts || 0) + 1; - t.challenge = null; // force a fresh challenge for the next try - if (t.attempts >= 3) { earnTokens.delete(s.email); return json(res, 400, { error: 'Three misses — that view is void. Head back and load the next ad.' }); } - return json(res, 400, { error: 'Wrong pick.', retry: true }); - } - earnTokens.delete(s.email); // single use - return json(res, 200, await ads.recordView(s.email)); - } - if (p === '/api/my/claim' && req.method === 'POST') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const r = await ads.claimDaily(s.email); - return json(res, r.error ? 400 : 200, r); - } - // -- downline lineage: 3 levels, usernames+IDs; email only for directs - if (p === '/api/my/line' && req.method === 'GET') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const levels = await accounts.downline(s.email, 3); - // what each person has paid THIS member so far: sum of TierPaid events where - // this member is the recipient and that person is the buyer (all indexed events) - // ...counting payouts to every position this account owns (main id + linked positions) - const myId = await auth.refreshMemberId(s); - const own = (await accounts.positions(s.email)).filter(p => p.memberId); - const myIds = new Set([myId, ...own.map(p => p.memberId)].filter(Boolean)); - const earnedBy = {}; - const qualified = new Set(); // members the contract counted as this account's qualifying buyers ($20+) - if (myIds.size) { - for (const ev of chain.recentEvents(1e9)) { - if (ev.type === 'TierPaid' && myIds.has(ev.recipientId) && ev.buyerId) - earnedBy[ev.buyerId] = (BigInt(earnedBy[ev.buyerId] || '0') + BigInt(ev.amountWei)).toString(); - if (ev.type === 'BuyerCounted' && myIds.has(ev.sponsorId) && ev.newBuyerId) qualified.add(ev.newBuyerId); - } - } - // who sponsored each person (Marty, 2026-09-14): resolve sponsorRef tokens (username, share code or member id) against the line itself - const meAcct = await accounts.byEmail(s.email); const byTok = {}; - const label = a => a.username ? '@' + a.username : (a.memberId ? 'member #' + a.memberId : 'member'); - for (const a of [meAcct, ...levels.flatMap(L => L.members)].filter(Boolean)) { const n = label(a); if (a.username) byTok[String(a.username).toLowerCase()] = n; if (a.code) byTok[String(a.code).toLowerCase()] = n; if (a.memberId) byTok[String(a.memberId)] = n; } - const sponsorOf = m => { const t = String(m.sponsorRef || '').toLowerCase(); if (!t) return null; if (meAcct && (t === String(meAcct.username || '').toLowerCase() || t === String(meAcct.code || '').toLowerCase() || t === String(meAcct.memberId || ''))) return 'you'; return byTok[t] || ('@' + t); }; - // a member's linked positions are theirs too: a qualifying buy from one of them lights their chip - const posIds = {}; for (const m of levels.flatMap(L => L.members)) { try { posIds[m.email] = (await accounts.positions(m.email)).map(p => p.memberId).filter(Boolean); } catch (e) { posIds[m.email] = []; } } - const idsOf = m => [m.memberId, ...(posIds[m.email] || [])].filter(Boolean); - // Clinton's ask (2026-09-14): on levels 2 and 3 show who has made their $20+ buy (counted for their own - // sponsor) and how many qualifying buyers of their own they have, so a leader can see who is one short - const onchain = {}; - for (const m of levels.flatMap(L => L.members)) { let bought = false, buyers = 0; for (const id of idsOf(m)) { const mm = await cachedMember(id); if (mm) { if (mm.countedAsBuyer) bought = true; buyers += mm.buyerCount || 0; } } onchain[m.email] = { bought, buyers }; } - const out = levels.map(L => ({ level: L.level, members: L.members.map(m => ({ - bought: onchain[m.email].bought, buyers: onchain[m.email].buyers, - memberId: m.memberId || 0, - sponsor: sponsorOf(m), - name: m.username ? '@' + m.username : m.memberId ? 'member #' + m.memberId : 'member', - ref: m.code || null, // opens the activity drop-down (Clinton's ask, 2026-09-14): any of the three levels - email: L.level === 1 ? m.email : null, // directs only - joined: m.created, - qualified: idsOf(m).some(id => qualified.has(id)), - earnedWei: idsOf(m).reduce((n, id) => n + BigInt(earnedBy[id] || '0'), 0n).toString() })) })); - // the member's own linked positions sit on level 1 too, labelled as theirs - if (own.length) { - if (!out.find(L => L.level === 1)) out.unshift({ level: 1, members: [] }); - const L1 = out.find(L => L.level === 1); - own.forEach((p, i) => L1.members.push({ memberId: p.memberId, name: 'You · position ' + (i + 2), own: true, - email: null, joined: p.created, earnedWei: earnedBy[p.memberId] || '0' })); - } - return json(res, 200, { levels: out, counts: out.map(L => L.members.length) }); - } - // -- who is working: one downline member's activity, any of the three levels (Clinton, 2026-09-14) - if (p === '/api/my/line/activity' && req.method === 'GET') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const ref = String(u.searchParams.get('ref') || '').trim().toLowerCase().slice(0, 40); - const a = ref ? await accounts.byCode(ref) : null; - if (!a || !(await accounts.isDownlineOf(s.email, a.email, 3))) return json(res, 404, { error: 'Not in your line.' }); - const now = Date.now(); - const out = { name: a.username ? '@' + a.username : (a.memberId ? 'member #' + a.memberId : 'member'), joined: a.created, lastSeen: a.lastSeen || 0, quietDays: Math.floor((now - Math.max(a.created || 0, a.lastSeen || 0)) / 86400000), wallet: !!a.address, memberId: a.memberId || 0 }; - try { const c = await coach.describe(a, now); out.rung = c.label; out.next = c.next; out.stalled = c.stalled; out.buyerCount = c.buyerCount || 0; } catch (e) {} - try { const v = await ads.viewStatus(a.email); out.viewsToday = v.views; out.target = v.target; out.claimedToday = v.claimed; out.streakDay = v.claimed ? v.streakDay : Math.max(0, v.streakDay - 1); } catch (e) {} - try { const cs = await ads.listCampaigns(a.email); out.campaigns = cs.length; out.campaignsActive = cs.filter(c => c.status === 'active').length; out.imps = cs.reduce((n, c) => n + (c.imps || 0) + (c.impsNas || 0), 0); } catch (e) {} - try { const ls = await coach.linkStats(a.email); out.linkViews30 = (ls.angles || []).reduce((n, r) => n + (r.views30 || 0), 0); out.linkViews = ls.totalViews || 0; out.joins = ls.totalJoins || 0; } catch (e) {} - try { out.directs = ((await accounts.downline(a.email, 1))[0] || { members: [] }).members.length; } catch (e) { out.directs = 0; } - try { out.badges = await ads.milestonesOf(a.email); } catch (e) { out.badges = []; } - try { out.positions = (await accounts.positions(a.email)).length; } catch (e) { out.positions = 0; } - return json(res, 200, out); - } - // -- broadcast a message to your downline (1/day), on-site inbox + email - if (p === '/api/my/broadcast' && req.method === 'POST') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const b = await readBody(req); - const subject = String(b.subject || '').trim().slice(0, 160); - const body = ads.sanitizeRich(b.body); - const plain = body.replace(/<[^>]*>/g, ' ').replace(/\s+/g, ' ').trim(); - if (!subject) return json(res, 400, { error: 'Give your message a subject.' }); - if (plain.length < 10) return json(res, 400, { error: 'Write a message first.' }); - const last = await messages.lastBroadcastAt(s.email); - if (Date.now() - last < 24 * 3600 * 1000) - return json(res, 429, { error: 'You can send one broadcast a day. Try again in ' + Math.ceil((24 * 3600 * 1000 - (Date.now() - last)) / 3600000) + 'h.' }); - const depth = b.scope === 'direct' ? 1 : 3; - const levels = await accounts.downline(s.email, depth); - const recipients = [...new Set(levels.flatMap(L => L.members.map(m => m.email)).filter(Boolean))]; - if (!recipients.length) return json(res, 400, { error: 'No one in your line to message yet.' }); - const memberId = s.memberId || await auth.refreshMemberId(s); - await messages.deliver(memberId, s.email, recipients, subject, body); - // email each recipient too (best-effort; never blocks the on-site delivery) - if (mailer.hasKey()) { - const who = (await accounts.byEmail(s.email)); - const from = who && who.username ? '@' + who.username : 'your sponsor'; - for (const to of recipients) { - mailer.send(to, 'Message from ' + from + ': ' + subject, - plain + '\n\n— sent via your LinkSpin upline. Read it in your dashboard: ' + SITE_URL + '/tools#line') - .catch(() => {}); - } - } - return json(res, 200, { ok: true, sent: recipients.length }); - } - // -- sponsor messages: this member's inbox from their upline - if (p === '/api/my/messages' && req.method === 'GET') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const items = await messages.inbox(s.email); - const names = await accounts.namesForMembers([...new Set(items.map(i => i.fromMember).filter(Boolean))]); - for (const i of items) i.fromName = (i.fromMember && names[i.fromMember]) ? '@' + names[i.fromMember] - : i.fromMember ? 'member #' + i.fromMember : 'your upline'; - return json(res, 200, { items, unread: items.filter(i => !i.read).length }); - } - m = /^\/api\/my\/messages\/(\d+)\/read$/.exec(p); - if (m && req.method === 'POST') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - return json(res, 200, await messages.markRead(s.email, m[1])); - } - - // ── SPONSOR CHAT (two-way): presence-aware 1:1 threads up/down the line ── - const chatOnline = ts => (Date.now() - (ts || 0)) < 60000; - const chatName = a => !a ? 'member' : (a.username ? '@' + a.username : (a.memberId ? 'member #' + a.memberId : 'member')); - // lightweight presence heartbeat (called on a timer while the dashboard is open) - if (p === '/api/my/ping' && req.method === 'GET') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 200, { ok: true, chatUnread: 0 }); - accounts.touchSeen(s.email).catch(() => {}); - return json(res, 200, { ok: true, chatUnread: await messages.chatUnread(s.email) }); - } - // training center content (admin-curated via data/training.json) - if (p === '/api/training' && req.method === 'GET') { - const s = await auth.fromRequest(req); - if (!s) return json(res, 401, { error: 'Sign in first.' }); - let items = []; - try { const j = JSON.parse(fs.readFileSync(path.join(DATA_DIR, 'training.json'), 'utf8')); if (Array.isArray(j)) items = j; } catch (e) {} - // a card with feature:'pipeline' waits for the switch, so the video can be ready before the tab opens (Marty, 2026-09-15) - const scT = siteConfig(); items = items.filter(it => !it.feature || (it.feature === 'pipeline' && pipeline.visible(scT.pipelineMode, s.email, ADMIN_EMAIL))); - if (!items.length) items = [{ title: 'Getting started with LinkSpin', - desc: 'How the platform works, how every payout splits on-chain to real wallets, and how to build your line.', - docUrl: SITE_URL + '/' }]; - return json(res, 200, { items }); - } - // daily login bonus (once/day, gentle streak) — granted after the login flow - if (p === '/api/my/login-bonus' && req.method === 'POST') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - return json(res, 200, await ads.grantLoginBonus(s.email)); - } - // -- rehearsal test-POL faucet: top a connected wallet up to 10 test-POL - // (anvil_setBalance, no key needed). Rehearsal-only, rate-limited. - if (p === '/api/my/faucet' && req.method === 'POST') { - const s = await auth.fromRequest(req); - if (!s) return json(res, 401, { error: 'Sign in first.' }); - if (!siteConfig().rehearsal) return json(res, 400, { error: 'The faucet is only open during the rehearsal.' }); - const b = await readBody(req); - const addr = String(b.address || '').trim().toLowerCase(); - if (!/^0x[0-9a-f]{40}$/.test(addr)) return json(res, 400, { error: 'Connect your wallet first.' }); - // Amoy is a public testnet: testers fund their own connected wallet from - // the public Amoy faucet (no server-minted balance). We just echo the - // address + faucet link; the client copies the address and opens it. - let balHex = '0x0'; try { balHex = await chain.rpc('eth_getBalance', [addr, 'latest']); } catch (e) {} - return json(res, 200, { ok: true, faucetUrl: 'https://faucet.polygon.technology/', address: addr, balanceWei: BigInt(balHex || '0x0').toString() }); - } - // -- report an ad (auto-approved ads need a safety valve): store + notify admin - if (p === '/api/report-ad' && req.method === 'POST') { - const b = await readBody(req); - if (!Number(b.campaignId)) return json(res, 400, { error: 'Which ad?' }); - const s = await auth.fromRequest(req); - const who = (s && s.email) || ''; - const rec = await reports.add(b.campaignId, who, b.reason, b.note); - try { - const adminEmail = process.env.ADMIN_EMAIL || ''; // private env only — siteConfig is exposed via /api/config - if (adminEmail && mailer.hasKey()) { - mailer.send(adminEmail, 'Ad reported on LinkSpin (campaign #' + rec.campaignId + ')', - 'A member flagged an ad.\n\nCampaign: #' + rec.campaignId + '\nReason: ' + rec.reason - + '\nReported by: ' + (who || 'anonymous') + '\nNote: ' + (String(b.note || '').slice(0, 500) || '(none)') - + '\n\nPause or review it from the admin.').catch(() => {}); - } - } catch (e) {} - return json(res, 200, { ok: true }); - } - if (p === '/api/my/chat/send' && req.method === 'POST') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const me = s.email.toLowerCase(); - const b = await readBody(req); - const to = String(b.to || '').trim().toLowerCase(); - const text = String(b.body || '').replace(/<[^>]*>/g, '').replace(/\s+$/, '').slice(0, 2000).trim(); - if (!to || to === me) return json(res, 400, { error: 'Pick who to message.' }); - if (!text) return json(res, 400, { error: 'Write a message first.' }); - const target = await accounts.byEmail(to); - if (!target) return json(res, 404, { error: 'No such member.' }); - // authorize: existing thread, my direct sponsor, or someone in my downline - let ok = (await messages.thread(me, to, 0, 1)).length > 0; - if (!ok) { const spon = await accounts.sponsorOf(me); ok = !!(spon && spon.email && spon.email.toLowerCase() === to); } - if (!ok) ok = await accounts.isDownlineOf(me, to); - if (!ok) return json(res, 403, { error: 'You can only message your direct sponsor or someone in your line.' }); - if ((await accounts.getMutes(to)).map(x => String(x).toLowerCase()).includes(me)) - return json(res, 403, { error: 'They are not accepting messages from you right now.' }); - const memberId = s.memberId || await auth.refreshMemberId(s); - const msg = await messages.sendChat(memberId, me, to, text); - // email only when they are offline AND I have not messaged them in ~10 min (no mid-chat spam) - try { - if (mailer.hasKey() && !chatOnline(target.lastSeen)) { - const mine = (await messages.thread(me, to, 0, 400)).filter(x => x.id !== msg.id && String(x.fromEmail).toLowerCase() === me); - const lastMineTs = mine.length ? mine[mine.length - 1].sent : 0; - if (Date.now() - lastMineTs > 10 * 60 * 1000) { - const who = await accounts.byEmail(me); - const from = who && who.username ? '@' + who.username : 'someone in your LinkSpin line'; - mailer.send(to, 'New message from ' + from, - text.slice(0, 400) + '\n\n— reply in your dashboard: ' + SITE_URL + '/tools').catch(() => {}); - } - } - } catch (e) {} - return json(res, 200, { ok: true, message: { id: msg.id, sent: msg.sent, fromMe: true, body: text } }); - } - if (p === '/api/my/chat/thread' && req.method === 'GET') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const me = s.email.toLowerCase(); - const other = String(u.searchParams.get('with') || '').trim().toLowerCase(); - const after = Number(u.searchParams.get('after')) || 0; - if (!other) return json(res, 400, { error: 'Who with?' }); - // may view a thread I'm party to (existing), or one I'm allowed to start - let ok = (await messages.thread(me, other, 0, 1)).length > 0; - if (!ok) { const spon = await accounts.sponsorOf(me); ok = !!(spon && spon.email && spon.email.toLowerCase() === other); } - if (!ok) ok = await accounts.isDownlineOf(me, other); - if (!ok) return json(res, 403, { error: 'Not your conversation.' }); - const msgs = await messages.thread(me, other, after, 300); - await messages.markChatRead(me, other); - accounts.touchSeen(me).catch(() => {}); - const oa = await accounts.byEmail(other); - const iMute = (await accounts.getMutes(me)).map(x => String(x).toLowerCase()).includes(other); - const theyMuteMe = (await accounts.getMutes(other)).map(x => String(x).toLowerCase()).includes(me); - return json(res, 200, { - messages: msgs.map(x => ({ id: x.id, fromMe: String(x.fromEmail).toLowerCase() === me, body: x.body, sent: x.sent })), - otherName: chatName(oa), online: oa ? chatOnline(oa.lastSeen) : false, - available: oa ? oa.chatAvailable !== false : true, iMute, blocked: theyMuteMe, - canMute: await accounts.isDownlineOf(me, other) }); - } - if (p === '/api/my/chat/threads' && req.method === 'GET') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const list = await messages.threadList(s.email.toLowerCase()); - for (const t of list) { - const a = await accounts.byEmail(t.email); - t.name = chatName(a); t.online = a ? chatOnline(a.lastSeen) : false; - } - list.sort((x, y) => (y.last.sent || 0) - (x.last.sent || 0)); - const meAcct = await accounts.byEmail(s.email); - return json(res, 200, { threads: list, available: meAcct ? meAcct.chatAvailable !== false : true }); - } - if (p === '/api/my/chat/available' && req.method === 'POST') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const b = await readBody(req); - return json(res, 200, await accounts.setChatAvailable(s.email, !!b.available)); - } - if (p === '/api/my/chat/mute' && req.method === 'POST') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const b = await readBody(req); - const target = String(b.email || '').trim().toLowerCase(); - if (!target) return json(res, 400, { error: 'Who?' }); - const allowed = (await accounts.isDownlineOf(s.email, target)) || (await messages.thread(s.email.toLowerCase(), target, 0, 1)).length > 0; - if (!allowed) return json(res, 403, { error: 'You can only mute someone in your line.' }); - return json(res, 200, await accounts.setMute(s.email, target, !!b.muted)); - } - // -- featured rotation: the live featured links + dilution stats - if (p === '/api/featured' && req.method === 'GET') { - const items = await ads.serveFeatured(viewerGeo(req)); - try { const sv = await auth.fromRequest(req); ads.noteFeaturedViews(items, (sv && sv.email) || clientIp(req)).catch(() => {}); } catch (e) {} // count the view (per viewer per hour) - const names = await accounts.namesForMembers([...new Set(items.map(i => i.memberId).filter(Boolean))]); - for (const i of items) i.by = (i.memberId && names[i.memberId]) ? '@' + names[i.memberId] : (i.memberId ? 'member #' + i.memberId : null); - return json(res, 200, { items }); - } - if (p === '/api/featured/stats' && req.method === 'GET') { - return json(res, 200, await ads.featuredStats()); - } - // -- QR code (SVG) for any LinkSpin URL — used on bio/wall pages - if (p === '/api/qr' && req.method === 'GET') { - const data = String(u.searchParams.get('d') || '').slice(0, 300); - if (!QR || !data) { res.writeHead(404, baseHeaders()); return res.end(); } - try { - const svg = await QR.toString(data, { type: 'svg', margin: 1, width: 240, - color: { dark: '#0e7d5f', light: '#f2fbf8' } }); // mint-green modules, still high-contrast for reliable scanning - res.writeHead(200, baseHeaders({ 'Content-Type': 'image/svg+xml', 'Cache-Control': 'public, max-age=3600' })); - return res.end(svg); - } catch (e) { res.writeHead(500, baseHeaders()); return res.end(); } - } - // -- profile: avatar + bio - if (p === '/api/my/profile-details' && req.method === 'POST') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const b = await readBody(req); - const avatar = b.avatarUrl === undefined ? undefined : String(b.avatarUrl || '').trim(); - if (avatar && !/^(\/uploads\/[a-z0-9]{24}\.(png|jpg|webp|gif)|https:\/\/[^\s]+)$/i.test(avatar)) - return json(res, 400, { error: 'Avatar must be an uploaded image or an https image URL.' }); - const bio = b.bio === undefined ? undefined : String(b.bio || '').trim().slice(0, 600); - // socials: {platform: url}; keep only known platforms with valid https urls - let socials; - if (b.socials !== undefined) { - const PLAT = ['facebook', 'twitter', 'youtube', 'instagram', 'tiktok', 'telegram', 'linkedin', 'website', 'video']; - const clean = {}; - for (const p of PLAT) { - const v = String((b.socials && b.socials[p]) || '').trim(); - if (v && /^https:\/\/[^\s]+$/i.test(v) && v.length <= 300) clean[p] = v; - } - // intro video on the public wall: a YouTube, Vimeo or direct .mp4/.webm link only - if (clean.video && !/^https:\/\/((www\.|m\.)?youtube\.com\/(watch\?|shorts\/|embed\/)|youtu\.be\/|(www\.)?vimeo\.com\/\d+|player\.vimeo\.com\/video\/\d+|[^\s]+\.(mp4|webm)(\?|$))/i.test(clean.video)) - return json(res, 400, { error: 'The intro video needs to be a YouTube link, a Vimeo link, or a direct .mp4 link.' }); - socials = Object.keys(clean).length ? JSON.stringify(clean) : null; - } - const r = await accounts.setProfile(s.email, avatar, bio, socials); - return json(res, r.error ? 400 : 200, r); - } - // -- wall positions 2 & 3: the member's own offers, unlocked at 2 / 5 qualifying buyers - if (p === '/api/my/wall-offers' && req.method === 'POST') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const b = await readBody(req); - const src = Array.isArray(b.offers) ? b.offers.slice(0, 2) : []; - const out = []; - for (let i = 0; i < 2; i++) { - const o = src[i] || {}; - const targetUrl = String(o.targetUrl || '').trim(); - const bannerUrl = String(o.bannerUrl || '').trim(); - const title = String(o.title || '').trim().slice(0, 60); - if (targetUrl && !/^https:\/\/[^\s]+$/i.test(targetUrl)) return json(res, 400, { error: 'Position ' + (i + 2) + ': the link must start with https://' }); - if (bannerUrl && !/^(\/uploads\/[a-z0-9]{24}\.(png|jpg|webp|gif)|https:\/\/[^\s]+)$/i.test(bannerUrl)) return json(res, 400, { error: 'Position ' + (i + 2) + ': banner must be an uploaded image or an https image URL.' }); - out.push(targetUrl ? { title: title || null, bannerUrl: bannerUrl || null, targetUrl } : null); - } - const r = await accounts.setWallOffers(s.email, out.some(Boolean) ? JSON.stringify(out) : null); - return json(res, r.error ? 400 : 200, r); - } - // -- line banner: the member's viral slot on welcome tours + their wall - if (p === '/api/my/linebanner' && req.method === 'POST') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const b = await readBody(req); - const target = String(b.targetUrl || '').trim(); - if (!/^https?:\/\/[^\s]+$/i.test(target)) return json(res, 400, { error: 'Destination URL must start with http(s)://' }); - const fc = await frameCheck(target); // welcome tours frame it full screen - if (!fc.ok) return json(res, 400, { error: fc.reason }); - const banner = String(b.bannerUrl || '').trim(); - if (banner && !/^(\/uploads\/[a-z0-9]{24}\.(png|jpg|webp|gif)|https:\/\/[^\s]+)$/i.test(banner)) - return json(res, 400, { error: 'Banner must be an uploaded image or an https image URL.' }); - const r = await accounts.setLineBanner(s.email, banner || null, target); - return json(res, r.error ? 400 : 200, r); - } - // -- welcome tour (gauntlet): meet the 3-level upline, then unlock welcome credits - if (p === '/api/my/gauntlet' && req.method === 'GET') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - if (await ads.welcomeGranted(s.email)) return json(res, 200, { pending: false }); - const slides = (await uplineSlides(s.email)).filter(a => a.lineTargetUrl) - .map((a, i) => ({ name: a.username ? '@' + a.username : a.memberId ? 'member #' + a.memberId : 'a member', - bannerUrl: a.lineBannerUrl || null, targetUrl: a.lineTargetUrl })); - if (!slides.length) return json(res, 200, { pending: false }); - const token = crypto.randomBytes(16).toString('hex'); - gauntletTokens.set(s.email, { token, ts: Date.now(), n: slides.length }); - return json(res, 200, { pending: true, slides, dwell: 10, token }); - } - if (p === '/api/my/gauntlet/complete' && req.method === 'POST') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const b = await readBody(req); - const t = gauntletTokens.get(s.email); - if (!t || t.token !== String(b.token || '')) return json(res, 400, { error: 'That tour is no longer open. Reload and try again.' }); - if (Date.now() - t.ts < t.n * 10 * 1000 - 1500) return json(res, 400, { error: 'Give each site its ten seconds first.' }); - gauntletTokens.delete(s.email); - await ads.grantWelcome(s.email); - return json(res, 200, { ok: true, credited: ads.rates().welcomeCredits || 0 }); - } - // -- public banner wall - m = /^\/api\/wall\/([A-Za-z0-9_]{1,20})$/.exec(p); - if (m && req.method === 'GET') { - const tok = m[1].toLowerCase(); - let a = await accounts.byUsername(tok); - if (!a) a = await accounts.byCode(tok); - if (!a) return json(res, 404, { error: 'No wall under that name.' }); - const ownName = a.username ? '@' + a.username : a.memberId ? 'member #' + a.memberId : 'a member'; - let bc = 0; - if (a.memberId) { try { bc = (await chain.member(a.memberId)).buyerCount || 0; } catch (e) {} } - const unlocked = wallUnlockedFor(bc); - const offers = parseWallOffers(a); - // uplines with a live banner, in order (an upline with nothing set is skipped, not shown empty) - const ups = (await uplineSlides(a.email, 2)).filter(x => x.lineTargetUrl) - .map(x => ({ name: x.username ? '@' + x.username : x.memberId ? 'member #' + x.memberId : 'a member', - bannerUrl: x.lineBannerUrl || null, targetUrl: x.lineTargetUrl, upline: true })); - const adAds = getAdminWallAds(); let ai = 0; - const houseAd = () => { if (!adAds.length) return null; const ad = adAds[ai++ % adAds.length]; return { name: ad.name || 'LinkSpin', bannerUrl: ad.bannerUrl || null, targetUrl: ad.targetUrl || SITE_URL + '/', admin: true }; }; - const ladder = [{ name: ownName, bannerUrl: a.lineBannerUrl || null, targetUrl: a.lineTargetUrl || null, own: true }]; - for (let i = 1; i < 3; i++) { - const o = offers[i - 1]; - if (i < unlocked && o && o.targetUrl) { ladder.push({ name: (o.title || ownName), bannerUrl: o.bannerUrl || null, targetUrl: o.targetUrl, own: true }); continue; } - const u = ups.shift(); if (u) { ladder.push(u); continue; } - const h = houseAd(); if (h) ladder.push(h); - } - const finalLadder = ladder.slice(0, 3); - // the wall owner's achievement badge (their highest reached tier) - let badge = null; - if (a.memberId) { - const t = bc >= 5 ? ['nexus', 'Nexus'] : bc >= 2 ? ['circuit', 'Circuit'] : bc >= 1 ? ['surge', 'Surge'] : ['spark', 'Spark']; - badge = { img: '/badges/badge-' + t[0] + '.jpg?v=3', label: t[1] }; - } - const joinPath = '/join/' + (a.username || a.code); - let socials = null; try { socials = a.socials ? JSON.parse(a.socials) : null; } catch (e) {} - return json(res, 200, { name: a.username ? '@' + a.username : 'member #' + (a.memberId || 0), - avatarUrl: a.avatarUrl || null, bio: a.bio || null, socials, badge, - joinUrl: joinPath, qrUrl: '/api/qr?d=' + encodeURIComponent(SITE_URL + joinPath), ladder: finalLadder, unlocked, buyerCount: bc }); - } - // -- watch-to-earn video ads: serve one, then reward a server-clock-verified watch - if (p === '/api/my/videos' && req.method === 'GET') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const status = await ads.videoStatus(s.email); - if (status.left <= 0) return json(res, 200, { ad: null, status }); - const orientation = String(u.searchParams.get('orientation') || ''); // 'portrait' = Shorts reel, 'landscape' = Watch videos tab - const ad = await ads.serveVideo(Object.assign({ excludeEmail: s.email, orientation }, viewerGeo(req))); // never your own video - if (!ad) { // distinguish "you have watched every live video today" from "nothing is live" (Marty, 2026-09-13) - let allWatched = false; try { allWatched = !!(await ads.serveVideo(Object.assign({ excludeEmail: s.email, orientation, ignoreSeen: true }, viewerGeo(req)))); } catch (e) {} - return json(res, 200, { ad: null, status, allWatched }); - } - const token = crypto.randomBytes(16).toString('hex'); - videoTokens.set(s.email, { token, ts: Date.now(), id: ad.id, secs: ad.watchSecs }); - return json(res, 200, { ad, token, status }); - } - if (p === '/api/my/videowatch' && req.method === 'POST') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const b = await readBody(req); - const t = videoTokens.get(s.email); - if (!t || t.token !== String(b.token || '')) return json(res, 400, { error: 'That video is no longer open. Load the next one.' }); - const age = Date.now() - t.ts; - if (age < t.secs * 1000 - 600) return json(res, 400, { error: 'Watch the full video first.' }); - if (age > t.secs * 1000 + 10 * 60 * 1000) { videoTokens.delete(s.email); return json(res, 400, { error: 'That watch went stale. Load a fresh video.' }); } - videoTokens.delete(s.email); // single use - if (await ads.hasWatchedVideoToday(s.email, t.id)) // once-per-day-per-video: no double earning - return json(res, 200, { ok: true, credited: 0, status: await ads.videoStatus(s.email), already: true }); - const tier = await ads.chargeVideoView(t.id); // charge advertiser; null if it ran dry - if (!tier) return json(res, 200, { ok: true, credited: 0, status: await ads.videoStatus(s.email), gone: true }); - await ads.addEarned(s.email, tier.reward); - await ads.markVideoSeen(s.email, t.id); - const status = await ads.recordVideoWatch(s.email); - return json(res, 200, { ok: true, credited: tier.reward, status }); - } - // -- verified visits: view a member's site (new tab) for the dwell, pass a - // human check, and it counts as one guaranteed unique visit for the pack - if (p === '/api/my/visits' && req.method === 'GET') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const status = await ads.visitStatus(s.email); - if (status.count >= status.cap) return json(res, 200, { ad: null, status }); - const ad = await ads.serveVisit(s.email, viewerGeo(req)); - if (!ad) return json(res, 200, { ad: null, status }); - const token = crypto.randomBytes(16).toString('hex'); - visitTokens.set(s.email, { token, ts: Date.now(), id: ad.id }); - return json(res, 200, { ad, token, status }); - } - if (p === '/api/my/visitchallenge' && req.method === 'GET') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const t = visitTokens.get(s.email); - if (!t || t.token !== String(u.searchParams.get('token') || '')) return json(res, 400, { error: 'That visit is no longer open.' }); - const dwellMs = (ads.rates().visitDwellSeconds || 8) * 1000; - const age = Date.now() - t.ts; - if (age < dwellMs - 400) return json(res, 200, { early: true, wait: Math.ceil((dwellMs - age) / 1000) }); - if (age > 5 * 60 * 1000) { visitTokens.delete(s.email); return json(res, 400, { error: 'That visit went stale. Load a fresh one.' }); } - const pick = CAPTCHA.slice().sort(() => Math.random() - 0.5).slice(0, 5); - const answer = Math.floor(Math.random() * pick.length); - t.challenge = { answer }; - return json(res, 200, { prompt: pick[answer][1], options: pick.map(x => x[0]) }); - } - if (p === '/api/my/visitdone' && req.method === 'POST') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const b = await readBody(req); - const t = visitTokens.get(s.email); - if (!t || t.token !== String(b.token || '')) return json(res, 400, { error: 'That visit did not check out. Load the next one.' }); - const dwellMs = (ads.rates().visitDwellSeconds || 8) * 1000; - if (Date.now() - t.ts < dwellMs - 400) return json(res, 400, { error: 'Give the site the full visit first.' }); - if (!t.challenge) return json(res, 400, { error: 'Finish the quick check first.', retry: true }); - if (Number(b.answer) !== t.challenge.answer) { t.challenge = null; return json(res, 400, { error: 'Wrong pick.', retry: true }); } - visitTokens.delete(s.email); - const r = await ads.completeVisit(s.email, t.id); - if (r.error) return json(res, 400, r); - return json(res, 200, Object.assign(r, { status: await ads.visitStatus(s.email) })); - } - // -- onsite solo ads: member inbox with read rewards - if (p === '/api/my/inbox' && req.method === 'GET') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const r = await ads.inboxList(s.email, viewerGeo(req)); - const names = await accounts.namesForMembers([...new Set(r.items.map(i => i.fromMemberId).filter(Boolean))]); - for (const i of r.items) i.fromName = (i.fromMemberId && names[i.fromMemberId]) ? '@' + names[i.fromMemberId] - : i.fromMemberId ? 'member #' + i.fromMemberId : 'a member'; - return json(res, 200, r); - } - m = /^\/api\/my\/inbox\/(\d+)$/.exec(p); - if (m && req.method === 'GET') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const r = await ads.inboxOpen(s.email, m[1]); - if (!r.error) { - const names = r.fromMemberId ? await accounts.namesForMembers([r.fromMemberId]) : {}; - r.fromName = (r.fromMemberId && names[r.fromMemberId]) ? '@' + names[r.fromMemberId] - : r.fromMemberId ? 'member #' + r.fromMemberId : 'a member'; - } - return json(res, r.error ? 404 : 200, r); - } - // media upload for solo ads: raw body, size-capped, magic-byte verified - if (p === '/api/my/upload' && req.method === 'POST') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - return handleUpload(req, res, s.email); - } - m = /^\/api\/my\/inbox\/(\d+)\/visit$/.exec(p); - if (m && req.method === 'POST') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const r = await ads.markSoloVisit(s.email, m[1]); - return json(res, r.error ? 400 : 200, r); - } - m = /^\/api\/my\/inbox\/(\d+)\/claim$/.exec(p); - if (m && req.method === 'POST') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const r = await ads.claimSoloRead(s.email, m[1]); - return json(res, r.error ? 400 : 200, r); - } - if (p === '/api/my/activity' && req.method === 'GET') { - const s = await auth.fromRequest(req); - if (!s) return json(res, 401, { error: 'Sign in first.' }); - const id = s.memberId || await auth.refreshMemberId(s); - if (!id) return json(res, 200, { memberId: 0, earnings: [], purchases: [], referrals: [] }); - const evs = chain.recentEvents(600); - return json(res, 200, { - memberId: id, - earnings: await attachNames(evs.filter(e => (e.type === 'TierPaid' && e.recipientId === id) || (e.type === 'AwardPaid' && e.toId === id))), - purchases: await attachNames(evs.filter(e => e.type === 'Purchase' && e.buyerId === id)), - referrals: await attachNames(evs.filter(e => (e.type === 'MemberActivated' && e.sponsorId === id) || (e.type === 'BuyerCounted' && e.sponsorId === id))) - }); - } - - // -- ad engine (spec §8b v1: banners, text, login ads) - if (p === '/api/ads/slot' && req.method === 'GET') { - const t = String(u.searchParams.get('type') || 'banner'); - const ad = await ads.serve(t, Object.assign({ width: Number(u.searchParams.get('w')) || 0, height: Number(u.searchParams.get('h')) || 0 }, viewerGeo(req), audiences.matcher(req))); - // login ads: the member clicks "Open Ad" (a real, counted click into a - // new tab) while the countdown runs on our interstitial page - if (ad && t === 'login') ad.dwell = ads.rates().loginDwellSeconds || 10; - return json(res, 200, { ad }); - } - m = /^\/api\/ads\/click\/(\d+)$/.exec(p); - if (m && req.method === 'GET') { - const target = await ads.click(m[1]); - if (!target) { res.writeHead(404, baseHeaders()); return res.end(); } - coach.recordClick(m[1], req.headers.referer); // where the click happened - res.writeHead(302, baseHeaders({ Location: target })); - return res.end(); - } - if (p === '/api/my/audiences' && req.method === 'GET') { - const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - return json(res, 200, { audiences: audiences.list(s.email), host: SITE_HOST }); - } - if (p === '/api/my/audiences' && req.method === 'POST') { - const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const b = await readBody(req); - const r = b.remove ? audiences.remove(s.email, b.id) : b.id ? audiences.rename(s.email, b.id, b.name) : audiences.create(s.email, b.name); - return json(res, r.error ? 400 : 200, r); - } - if (p === '/api/my/campaigns' && req.method === 'GET') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const memberId = await auth.refreshMemberId(s); - // welcome credits used to unlock only through the classic dashboard; the Control Room Ads screen grants them the same way (2026-09-29) - let gauntletPending = false; - if (!(await ads.welcomeGranted(s.email))) { const tour = (await uplineSlides(s.email)).filter(a => a.lineTargetUrl); if (!tour.length) await ads.grantWelcome(s.email); else gauntletPending = true; } - const out = { campaigns: await ads.listCampaigns(s.email), rates: ads.rates(), bannerSizes: ads.bannerSizes(), gauntletPending, audiences: audiences.list(s.email) }; - out.clickSources = await coach.clickSources(out.campaigns.map(c => c.id)); - out.hours = await ads.hoursFor(out.campaigns.map(c => c.id)); // on-site views per UTC hour, last 7 days - out.geo = await ads.geoFor(out.campaigns.map(c => c.id)); // on-site serves per viewer country - { const t = geo.tierLists(siteConfig()); out.tiers = { t1: [...t.t1], t2: [...t.t2] }; out.geoReady = geo.status().loaded; } - const pool = await ads.balances((await myMemberIds(s)).ids, s.email); - out.purchasedCredits = pool.total; - out.largestPosition = pool.best.avail; // a single campaign budget has to fit one position - out.positionCount = pool.per.length; - out.creditedCredits = pool.credited; // refunded/credited purchased money, free (counts inside purchasedCredits) - out.earnedCredits = pool.earned; // earned pool minus what live campaigns already hold - out.earnedReserved = pool.earnedReserved; - out.inCampaigns = pool.inCampaigns; // budget still to deliver across live campaigns - out.availableCredits = pool.available; - return json(res, 200, out); - } - if (p === '/api/my/campaigns' && req.method === 'POST') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const memberId = await auth.refreshMemberId(s); // 0 is fine: earned credits fund banner/text - const b = await readBody(req); - if (!MEMBER_AD_TYPES.includes(String(b.type || ''))) return json(res, 400, { error: 'LinkSpin runs banner, text and login ads.' }); - if (b.audience && !audiences.owns(s.email, b.audience)) return json(res, 400, { error: 'That audience is not one of yours.' }); // Marty 2026-09-29: the three formats members buy - if (!['login', 'solo', 'video', 'featured'].includes(String(b.type || ''))) { // banner/text surf views frame the target; login/video/solo/featured open in a new tab or play in our own player - const fc = await frameCheck(b.targetUrl); - if (!fc.ok) return json(res, 400, { error: fc.reason }); - } - // charge the best-funded of the member's positions (main + Qualified Start - // wallets). A campaign burns from one member id, so the budget must fit inside it. - const ids = (await myMemberIds(s)).ids; - const pool = await ads.balances(ids, s.email); - const fundId = pool.best.memberId || memberId; - const earnedNow = String(b.type) !== 'login' ? pool.earned : 0; - const budget = Math.floor(Number(b.budget) || 0); - if (pool.per.length > 1 && budget > pool.best.avail + pool.credited + earnedNow && budget <= pool.total + earnedNow) - return json(res, 400, { error: 'Your credits are spread across ' + pool.per.length + ' positions and one campaign spends from one of them. The largest single position holds ' + pool.best.avail + ' credits: set the budget to that or less, or run two campaigns.' }); - const r = await ads.createCampaign(s.email, fundId, b, ids); - return json(res, r.error ? 400 : 200, r); - } - m = /^\/api\/my\/campaigns\/(\d+)\/topup$/.exec(p); - if (m && req.method === 'POST') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const memberId = await auth.refreshMemberId(s); - const b = await readBody(req); - const r = await ads.topUpCampaign(s.email, memberId, m[1], b.credits); - return json(res, r.error ? 400 : 200, r); - } - m = /^\/api\/my\/campaigns\/(\d+)\/(pause|resume)$/.exec(p); - if (m && req.method === 'POST') { - const s = await auth.fromRequest(req); - if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); - const r = await ads.setStatus(s.email, m[1], m[2] === 'pause' ? 'paused' : 'active'); - return json(res, r.error ? 400 : 200, r); - } - - // -- admin portal: email magic-code sign-in, allowlisted to ADMIN_EMAIL - if (p === '/api/admin/auth/start' && req.method === 'POST') { - const b = await readBody(req); - const e = String(b.email || '').trim().toLowerCase(); - if (!ADMIN_EMAIL) return json(res, 503, { error: 'ADMIN_EMAIL is not set on the server.' }); - if (!e || e !== ADMIN_EMAIL) return json(res, 403, { error: 'That address is not the admin.' }); - const k = 'admin:' + e; - const prev = emailCodes.get(k); - if (prev && Date.now() < prev.nextAt) return json(res, 429, { error: 'Code already sent. Give it a minute, then try again.' }); - const code = String(Math.floor(100000 + Math.random() * 900000)); - emailCodes.set(k, { code, exp: Date.now() + 15 * 60 * 1000, tries: 0, nextAt: Date.now() + 60 * 1000 }); - if (mailer.hasKey()) { - try { await mailer.sendCode(e, code); } catch (err) { - console.error('admin sendCode failed', err.message); - return json(res, 502, { error: 'Could not send the email. Try again in a minute.' }); - } - return json(res, 200, { ok: true, sent: true }); - } - if (!IS_PROD) return json(res, 200, { ok: true, sent: false, devCode: code }); - return json(res, 503, { error: 'Email sign-in is not configured yet.' }); - } - if (p === '/api/admin/auth/verify' && req.method === 'POST') { - const b = await readBody(req); - const e = String(b.email || '').trim().toLowerCase(); - const k = 'admin:' + e; - const rec = emailCodes.get(k); - if (!rec || rec.exp < Date.now()) return json(res, 400, { error: 'Code expired. Request a fresh one.' }); - rec.tries += 1; - if (rec.tries > 6) { emailCodes.delete(k); return json(res, 400, { error: 'Too many tries. Request a fresh code.' }); } - if (String(b.code || '').trim() !== rec.code) return json(res, 400, { error: 'That code does not match.' }); - emailCodes.delete(k); - if (e !== ADMIN_EMAIL) return json(res, 403, { error: 'That address is not the admin.' }); - const token = mintAdminSession(e); - return json(res, 200, { ok: true, email: e }, { 'Set-Cookie': adminCookie(token) }); - } - if (p === '/api/admin/auth/logout' && req.method === 'POST') { - dropAdminSession(req); - return json(res, 200, { ok: true }, { 'Set-Cookie': clearAdminCookie() }); - } - if (p === '/api/admin/me' && req.method === 'GET') { - if (!isAdmin(req)) return json(res, 200, { admin: false }); - return json(res, 200, { admin: true, email: ADMIN_EMAIL }); - } - if (p === '/api/admin/overview' && req.method === 'GET') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - const camps = await ads.adminList(); - const byStatus = {}, byType = {}; - for (const c of camps) { byStatus[c.status] = (byStatus[c.status] || 0) + 1; byType[c.type] = (byType[c.type] || 0) + 1; } - let memberCount = null; try { memberCount = await chain.memberCount(); } catch (e) {} - const cc = chain.getConfig(); - return json(res, 200, { accounts: await accounts.count(), memberCount, campaigns: camps.length, - house: camps.filter(c => c.house).length, byStatus, byType, - openReports: await reports.openCount(), pendingBurns: (await ads.pendingBurns()).length, - followups: await drip.stats(), - chain: { contract: cc.contract, chainId: cc.chainId, chainName: cc.chainName, explorer: cc.explorer }, - site: siteConfig(), rates: ads.rates() }); - } - if (p === '/api/admin/members' && req.method === 'GET') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - const members = await accounts.listAll(500); - // resolve each sponsor token (username, share code or member #) to the sponsor's name - const byTok = {}; - for (const m of members) for (const t of [m.username, m.code, m.memberId ? String(m.memberId) : null]) if (t) byTok[String(t).toLowerCase()] = m; - for (const m of members) { - const t = String(m.sponsorRef || '').toLowerCase(); - const sp = t ? byTok[t] : null; - m.sponsorName = sp ? (sp.username ? '@' + sp.username : (sp.memberId ? 'member #' + sp.memberId : sp.email)) : null; - m.sponsorVia = sp ? (t === String(sp.username || '').toLowerCase() ? 'username' : t === String(sp.code || '').toLowerCase() ? 'code' : 'member #') : (t ? 'unresolved' : ''); - } - for (const m of members) { try { const ps = await accounts.positions(m.email); m.positions = ps.length; m.positionIds = ps.map(p => p.memberId).filter(Boolean); } catch (e) { m.positions = 0; } } - return json(res, 200, { members }); - } - if (p === '/api/admin/members' && req.method === 'PATCH') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - const b = await readBody(req); - if (!b.email) return json(res, 400, { error: 'Which member?' }); - const r = await accounts.setSponsorRef(b.email, b.sponsorRef); - return json(res, r.error ? 400 : 200, r); - } - if (p === '/api/admin/campaigns' && req.method === 'GET') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - return json(res, 200, { campaigns: await ads.adminList(), rates: ads.rates(), bannerSizes: ads.bannerSizes(), houseOwner: ads.HOUSE_OWNER }); - } - if (p === '/api/admin/campaigns' && req.method === 'POST') { // free house ad - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - const b = await readBody(req); - if (!['login', 'solo', 'video', 'featured'].includes(String(b.type || ''))) { - const fc = await frameCheck(b.targetUrl); - if (!fc.ok) return json(res, 400, { error: fc.reason }); - } - const r = await ads.createHouseCampaign(b); - return json(res, r.error ? 400 : 200, r); - } - m = /^\/api\/admin\/campaigns\/(\d+)\/(pause|resume)$/.exec(p); - if (m && req.method === 'POST') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - const r = await ads.adminSetStatus(m[1], m[2] === 'pause' ? 'paused' : 'active'); - return json(res, r.error ? 400 : 200, r); - } - if (p === '/api/admin/audit' && req.method === 'GET') { // counters reconciled against delivery logs - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - return json(res, 200, await audit.run()); - } - if (p === '/api/admin/reports' && req.method === 'GET') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - return json(res, 200, { reports: await reports.list(200) }); - } - m = /^\/api\/admin\/reports\/(\d+)\/resolve$/.exec(p); - if (m && req.method === 'POST') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - return json(res, 200, await reports.resolve(m[1])); - } - if (p === '/api/admin/upload' && req.method === 'POST') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - return handleUpload(req, res, 'admin'); - } - if (p === '/api/admin/rates' && req.method === 'GET') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - return json(res, 200, { rates: ads.rates() }); - } - if (p === '/api/admin/drip' && req.method === 'GET') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - return json(res, 200, { sequence: drip.sequence(), defaults: drip.DEFAULT_SEQUENCE, stats: await drip.stats(), mailReady: mailer.hasKey() }); - } - if (p === '/api/admin/drip' && req.method === 'PATCH') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - const b = await readBody(req); - const r = b.reset ? drip.resetSequence() : drip.setSequence(b.sequence); - return json(res, r.error ? 400 : 200, r); - } - if (p === '/api/admin/drip/test' && req.method === 'POST') { // send one step to the admin inbox - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - const b = await readBody(req); - if (!ADMIN_EMAIL) return json(res, 400, { error: 'ADMIN_EMAIL is not set.' }); - if (!mailer.hasKey()) return json(res, 400, { error: 'No mail key on the server.' }); - try { const r = await drip.sendStep(ADMIN_EMAIL, Number(b.step) || 0, ADMIN_EMAIL); return json(res, r.error ? 400 : 200, r); } - catch (e) { return json(res, 502, { error: 'Send failed: ' + e.message }); } - } - // wall fallback ads: shown in wall positions a member has not earned or filled, when no upline banner exists - if (p === '/api/admin/wall-ads' && req.method === 'GET') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - let saved = null; try { saved = JSON.parse(fs.readFileSync(path.join(DATA_DIR, 'admin-wall-ads.json'), 'utf8')); } catch (e) {} - return json(res, 200, { ads: Array.isArray(saved) ? saved : [], defaults: getAdminWallAds(), usingDefaults: !Array.isArray(saved) || !saved.length }); - } - if (p === '/api/admin/wall-ads' && req.method === 'PATCH') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - const b = await readBody(req); - const src = Array.isArray(b.ads) ? b.ads.slice(0, 20) : []; - const out = []; - for (const o of src) { - const name = String((o && o.name) || '').trim().slice(0, 60); - const targetUrl = String((o && o.targetUrl) || '').trim(); - const bannerUrl = String((o && o.bannerUrl) || '').trim(); - if (!targetUrl) continue; - if (!/^https:\/\/[^\s]+$/i.test(targetUrl)) return json(res, 400, { error: 'Every wall ad needs an https:// link (' + (name || targetUrl) + ').' }); - if (bannerUrl && !/^(\/uploads\/[a-z0-9]{24}\.(png|jpg|webp|gif)|https:\/\/[^\s]+)$/i.test(bannerUrl)) return json(res, 400, { error: 'Banner must be an uploaded image or an https image URL (' + (name || targetUrl) + ').' }); - out.push({ name: name || 'LinkSpin', targetUrl, bannerUrl: bannerUrl || null }); - } - const file = path.join(DATA_DIR, 'admin-wall-ads.json'); - if (out.length) fs.writeFileSync(file, JSON.stringify(out, null, 2)); else { try { fs.unlinkSync(file); } catch (e) {} } - return json(res, 200, { ok: true, ads: out, usingDefaults: !out.length }); - } - // -- growth snapshot: preview the post, or send it now - if (p === '/api/admin/snapshot' && req.method === 'GET') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - return json(res, 200, { text: await snapshot.preview() }); - } - if (p === '/api/admin/snapshot/send' && req.method === 'POST') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - const r = await snapshot.post(); return json(res, r.error ? 400 : 200, r); - } - if (p === '/api/admin/site' && req.method === 'GET') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - return json(res, 200, { site: siteConfig() }); - } - // -- profit and loss from the chain index: volume, platform fees, member payouts, - // pass-ups, per period (by block: ~43,200 Polygon blocks a day), plus the fee - // wallets' live balances and an admin-entered fixed monthly cost - if (p === '/api/admin/pnl' && req.method === 'GET') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - const days = Math.max(0, Number(u.searchParams.get('days') || 30)); - let latest = 0; try { latest = parseInt(await chain.rpc('eth_blockNumber', []), 16); } catch (e) {} - const fromBlock = days ? latest - Math.round(days * 43200) : 0; - const evs = chain.recentEvents(1e9).filter(e => !days || e.block >= fromBlock); - const sum = (list, f) => list.reduce((n, e) => n + BigInt(f(e) || '0'), 0n); - const purchases = evs.filter(e => e.type === 'Purchase'); - const tier = evs.filter(e => e.type === 'TierPaid'); - const admin = evs.filter(e => e.type === 'AdminPaid'); - const passed = evs.filter(e => e.type === 'PassedUp'); - const byTier = {}; - for (const t of [1, 2, 3]) byTier[t] = sum(tier.filter(e => e.tier === t), e => e.amountWei).toString(); - const byPkg = {}; - for (const e of purchases) { const k = '$' + Math.round(e.priceCents / 100); byPkg[k] = (byPkg[k] || 0) + 1; } - let polUsd = 0; try { const cat = await chain.catalog(); const pk = (cat.products || cat).find(x => x.costWei); if (pk) polUsd = (pk.priceCents / 100) / (Number(BigInt(pk.costWei)) / 1e18); } catch (e) {} - const wallets = { feeA: '0x7627fc78876948ac9d95c1c9eb061e7d6d647b70', feeB: '0x8b7d33849a2c4d92c985be31e46dc564ba901ad2', engine: burner.status().address || null }; - const balances = {}; - for (const [k, a] of Object.entries(wallets)) { if (!a) continue; try { balances[k] = BigInt(await chain.rpc('eth_getBalance', [a, 'latest'])).toString(); } catch (e) { balances[k] = null; } } - return json(res, 200, { days, fromBlock, latest, polUsd, - purchases: { count: purchases.length, volumeWei: sum(purchases, e => e.paidWei).toString(), usdCents: purchases.reduce((n, e) => n + (e.priceCents || 0), 0), byPackage: byPkg }, - platformWei: sum(admin, e => e.amountWei).toString(), memberPayoutsWei: sum(tier, e => e.amountWei).toString(), byTier, - passedUp: { count: passed.length, unqualified: passed.filter(e => e.reason === 'unqualified').length, sendFailed: passed.filter(e => e.reason === 'send-failed').length }, - wallets, balances, fixedMonthlyUsd: Number(siteConfig().pnlFixedMonthlyUsd) || 0, burner: burner.status() }); - } - if (p === '/api/admin/burner' && req.method === 'GET') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - return json(res, 200, burner.status()); - } - if (p === '/api/admin/burner/run' && req.method === 'POST') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - return json(res, 200, await burner.tick()); - } - - // -- admin (Bearer ADMIN_PASSWORD, or the /admin portal session) - if (p === '/api/admin/burns' && req.method === 'GET') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - return json(res, 200, { pending: await ads.pendingBurns() }); - } - if (p === '/api/admin/burns/mark' && req.method === 'POST') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - const b = await readBody(req); - const r = await ads.markBurned(b.id, b.tx); - return json(res, r.error ? 400 : 200, r); - } - if (p === '/api/admin/rates' && req.method === 'PATCH') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - const b = await readBody(req); - return json(res, 200, { ok: true, rates: ads.setRates(b) }); - } - - if (p === '/api/admin/site' && req.method === 'PATCH') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - const b = await readBody(req); - const cur = siteConfig(); - fs.writeFileSync(SITE_FILE, JSON.stringify(Object.assign(cur, b), null, 2)); - return json(res, 200, { ok: true, site: siteConfig() }); - } - if (p === '/api/admin/chain' && req.method === 'PATCH') { - if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); - const b = await readBody(req); - const file = path.join(DATA_DIR, 'config.json'); - let cur = {}; try { cur = JSON.parse(fs.readFileSync(file, 'utf8')); } catch (e) {} - fs.writeFileSync(file, JSON.stringify(Object.assign(cur, b), null, 2)); - chain.reloadConfig(); - return json(res, 200, { ok: true, config: chain.getConfig() }); - } - - // -- pages (HEAD answered like GET so link previewers and crawlers see 200; Node drops the body) - if (req.method === 'GET' || req.method === 'HEAD') { - if (p === '/') return sendFile(res, path.join(PUBLIC_DIR, 'index.html')); - if (p === '/ledger') return sendFile(res, path.join(PUBLIC_DIR, 'ledger.html')); - if (p === '/contract') return sendFile(res, path.join(PUBLIC_DIR, 'contract.html')); - if (p === '/terms') return sendFile(res, path.join(PUBLIC_DIR, 'terms.html')); - if (p === '/privacy') return sendFile(res, path.join(PUBLIC_DIR, 'privacy.html')); - if (p === '/disclaimer') return sendFile(res, path.join(PUBLIC_DIR, 'disclaimer.html')); - if (p === '/tools') return sendFile(res, path.join(PUBLIC_DIR, 'my.html')); // classic panes the control room lacks (More) - if (p === '/my') { // retired 2026-10-08: old links/emails/bookmarks land on the right control-room screen by #pane - res.writeHead(200, baseHeaders({ 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store' })); - return res.end('LinkSpin'); - } - if (p === '/links') return sendFile(res, path.join(PUBLIC_DIR, 'links.html')); // Control Room: the links workspace, first screen of the new front end (2026-09-29) - if (p === '/reports') return sendFile(res, path.join(PUBLIC_DIR, 'reports.html')); - if (p === '/pages') return sendFile(res, path.join(PUBLIC_DIR, 'pages.html')); - if (p === '/zones') return sendFile(res, path.join(PUBLIC_DIR, 'zones.html')); - if (p === '/sources') return sendFile(res, path.join(PUBLIC_DIR, 'sources.html')); // Control Room: traffic sources, network macros + postbacks (2026-10-12) - if (p === '/ads') return sendFile(res, path.join(PUBLIC_DIR, 'ads.html')); - if (p === '/team') return sendFile(res, path.join(PUBLIC_DIR, 'team.html')); - if (p === '/wallet') return sendFile(res, path.join(PUBLIC_DIR, 'wallet.html')); - if (p === '/credits') return sendFile(res, path.join(PUBLIC_DIR, 'credits.html')); // Control Room: buy packages, link wallet, payouts on (2026-10-07) - if (p === '/join') return serveJoinPage(res, '', '', null, []); // bare join: sponsor from the cookie if any (home-page CTAs) - if (p === '/admin') return sendFile(res, path.join(PUBLIC_DIR, 'admin.html')); - if (p === '/shorts') return sendFile(res, path.join(PUBLIC_DIR, 'shorts.html')); - if (p === '/plays') return sendFile(res, path.join(PUBLIC_DIR, 'plays.html')); - if (p === '/partners') return sendFile(res, path.join(PUBLIC_DIR, 'partners.html')); // site-owner kit (Marty, 2026-09-12) - if (p === '/earning') return sendFile(res, path.join(PUBLIC_DIR, 'earning.html')); // member guide: how earning works (2026-09-12) - // -- badge share page + image: /b// (OG preview = the member's composed badge) (Marty, 2026-09-13) - m = /^\/badge-img\/([a-z0-9_]{3,20})\/(payouts|firstBuyer|level2|level3)\.jpg$/.exec(p); - if (m) return sendFile(res, path.join(UPLOADS_DIR, 'badge-' + m[1] + '-' + m[2] + '.jpg')); - m = /^\/b\/([a-z0-9_]{3,20})\/(payouts|firstBuyer|level2|level3)$/i.exec(p); - if (m) { - const un = m[1].toLowerCase(), key = m[2]; - const a = await accounts.byUsername(un); - const file = path.join(UPLOADS_DIR, 'badge-' + un + '-' + key + '.jpg'); - if (!a || !fs.existsSync(file) || !(await ads.milestonesOf(a.email)).includes(key)) { res.writeHead(404, baseHeaders({ 'Content-Type': 'text/plain' })); return res.end('Not found'); } - const [label, sub] = BADGE_META[key]; - const esc = t => String(t || '').replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c])); - const url = SITE_URL + '/b/' + un + '/' + key, img = SITE_URL + '/badge-img/' + un + '/' + key + '.jpg'; - const title = '@' + un + ' unlocked ' + label + ' on LinkSpin'; - const desc = label + ': ' + sub + '. LinkSpin pays sponsors in the same transaction, on-chain. Join @' + un + '\u2019s line free.'; - const html = '' + esc(title) + '' - + '' - + '' - + '' - + '' - + '' - + '
' + esc(label) + ' badge for @' + esc(un) + '

@' + esc(un) + ' unlocked ' + label + '

' + esc(sub.charAt(0).toUpperCase() + sub.slice(1)) + '. On LinkSpin every ad package that sells pays the sponsor in the same transaction, straight to their wallet, on-chain.

' - + 'Join @' + esc(un) + '\u2019s line free

Advertising with a performance referral program. Not an investment; no income is guaranteed.

' - + ''; - res.writeHead(200, baseHeaders({ 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'public, max-age=300' })); - return res.end(html); - } - // -- blog: server-rendered so crawlers get real HTML + metadata (Marty, 2026-09-12) - if (p === '/blog' || p === '/blog/' || /^\/blog\/page\/\d+$/.test(p) || /^\/blog\/tag\/[^/]+$/.test(p)) { - const posts = await blog.listPublished(); - const pg = (m = /^\/blog\/page\/(\d+)$/.exec(p)) ? Number(m[1]) : 1; - const tag = (m = /^\/blog\/tag\/([^/]+)$/.exec(p)) ? decodeURIComponent(m[1]).toLowerCase() : null; - res.writeHead(200, baseHeaders({ 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'public, max-age=300' })); - return res.end(blog.renderIndex(posts, pg, tag)); - } - m = /^\/handout\/([a-z0-9_]{3,20})$/i.exec(p); - if (m) { const h = await toolkit.handout(m[1].toLowerCase()); if (!h) { res.writeHead(404, baseHeaders({ 'Content-Type': 'text/plain' })); return res.end('Not found'); } res.writeHead(200, baseHeaders({ 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-cache' })); return res.end(h); } - if (p === '/leaderboard') { res.writeHead(200, baseHeaders({ 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'public, max-age=60' })); return res.end(await leaderboard.renderPage()); } - if (p === '/whats-new') { res.writeHead(200, baseHeaders({ 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'public, max-age=120' })); return res.end(releases.renderPage()); } - if (p === '/blog/feed.xml') { res.writeHead(200, baseHeaders({ 'Content-Type': 'application/rss+xml; charset=utf-8', 'Cache-Control': 'public, max-age=900' })); return res.end(blog.rss(await blog.listPublished())); } - if (p === '/sitemap.xml') { res.writeHead(200, baseHeaders({ 'Content-Type': 'application/xml; charset=utf-8', 'Cache-Control': 'public, max-age=3600' })); return res.end(blog.sitemap(await blog.listPublished())); } - if (p === '/robots.txt') { res.writeHead(200, baseHeaders({ 'Content-Type': 'text/plain; charset=utf-8', 'Cache-Control': 'public, max-age=3600' })); return res.end(blog.robots()); } - m = /^\/blog\/([a-z0-9-]{1,80})$/.exec(p); - if (m) { - const post = await blog.get(m[1]); - const preview = !!(post && post.status !== 'published' && isAdmin(req)); // admins can open a draft at its real URL - if (!post || (post.status !== 'published' && !preview)) { res.writeHead(404, baseHeaders({ 'Content-Type': 'text/html; charset=utf-8' })); return res.end(blog.renderIndex(await blog.listPublished(), 1, null).replace('', '<title>Not found | ')); } - if (!preview && req.method === 'GET') blog.bumpViews(post.slug); - const related = blog.relatedFor(post, await blog.listPublished()); - res.writeHead(200, baseHeaders({ 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': preview ? 'no-store' : 'public, max-age=300' })); - return res.end(blog.renderPost(post, related)); - } - if (p === '/wallets') return sendFile(res, path.join(PUBLIC_DIR, 'wallets.html')); - if (p === '/launch') return sendFile(res, path.join(PUBLIC_DIR, 'launch.html')); - if (/^\/view\/[a-f0-9]{32}$/.test(p)) return sendFile(res, path.join(PUBLIC_DIR, 'view.html')); - m = /^\/uploads\/([a-z0-9]{24}\.(?:png|jpg|webp|gif|mp4|webm))$/.exec(p); - if (m) return sendFile(res, path.join(UPLOADS_DIR, m[1])); - if (/^\/tx\/0x[0-9a-fA-F]{64}$/.test(p)) return sendFile(res, path.join(PUBLIC_DIR, 'tx.html')); - m = /^\/wall\/([A-Za-z0-9_]{1,20})$/.exec(p); - if (m) { // server-inject per-member OG tags so shared bio links preview correctly (crawlers don't run JS) - try { - const tok = m[1].toLowerCase(); - let a = await accounts.byUsername(tok); if (!a) a = await accounts.byCode(tok); - let html = fs.readFileSync(path.join(PUBLIC_DIR, 'wall.html'), 'utf8'); - if (a) { - const nm = a.username ? '@' + a.username : 'member #' + (a.memberId || 0); - const esc = t => String(t || '').replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c])); - const title = nm + ' on LinkSpin'; - const desc = a.bio ? esc(a.bio).slice(0, 200) : 'Join ' + nm + '’s line on LinkSpin — instant on-chain ad payouts, free to join.'; - const img = a.avatarUrl && /^https:/.test(a.avatarUrl) ? a.avatarUrl : SITE_URL + '/banners/linkspin-og-1200x630.png'; - const url = SITE_URL + '/wall/' + (a.username || a.code); - const og = [ - '<meta property="og:type" content="profile">', - '<meta property="og:site_name" content="LinkSpin">', - '<meta property="og:url" content="' + url + '">', - '<meta property="og:title" content="' + esc(title) + '">', - '<meta property="og:description" content="' + desc + '">', - '<meta property="og:image" content="' + esc(img) + '">', - '<meta name="twitter:card" content="summary_large_image">', - '<meta name="twitter:title" content="' + esc(title) + '">', - '<meta name="twitter:description" content="' + desc + '">', - '<meta name="twitter:image" content="' + esc(img) + '">', - '<meta name="description" content="' + desc + '">', - '<link rel="canonical" href="' + url + '">' - ].join('\n'); - html = html.replace('<title>Banner wall | LinkSpin', '' + esc(title) + '').replace('', og); - } - res.writeHead(200, baseHeaders({ 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-cache' })); - return res.end(html); - } catch (e) { return sendFile(res, path.join(PUBLIC_DIR, 'wall.html')); } - } - const safe = path.normalize(p).replace(/^([.\\/])+/, ''); - const file = path.join(PUBLIC_DIR, safe); - if (file.startsWith(PUBLIC_DIR) && fs.existsSync(file) && fs.statSync(file).isFile()) return sendFile(res, file); - } - - res.writeHead(404, baseHeaders({ 'Content-Type': 'text/plain' })); - res.end('Not found'); - } catch (e) { - console.error('request error', req.url, e.message); - try { json(res, 500, { error: 'server error' }); } catch (_) {} - } -}); -boot().then(() => { - server.listen(PORT, () => console.log(`LinkSpin site on :${PORT} — chain: ${chain.getConfig().chainName} — store: ${db.enabled() ? 'MySQL' : 'volume JSON'}` - + ` — outbound mail: ${OUTBOUND_MAIL ? 'ON' : 'OFF'} — sign-ups: ${SIGNUPS_OPEN ? 'open' : 'CLOSED'}`)); -}).catch(e => { console.error('boot failed:', e.message); process.exit(1); }); +// LinkSpin — membership advertising with immutable on-chain settlement. +// Zero-dependency Node server (RM Circle pattern): static pages + JSON API, +// wallet sign-in (SIWE), live contract ledger, sponsor join links. +// +// Chain selection (Amoy rehearsal vs mainnet) lives in data/config.json — +// see chain.js. Wipe the volume's accounts/sessions + flip config = launch. +const http = require('http'); +const https = require('https'); +const dns = require('dns'); +const fs = require('fs'); +const path = require('path'); +const crypto = require('crypto'); +const sendy = require('./sendy'); +const { URL } = require('url'); +const chain = require('./chain'); +const auth = require('./auth'); +const accounts = require('./accounts'); +const ads = require('./ads'); +const mailer = require('./mailer'); +const messages = require('./messages'); +const reports = require('./reports'); +const drip = require('./drip'); +const spaces = require('./spaces'); // DO Spaces video storage (inert unless DO_SPACES_* set) +let QR = null; try { QR = require('qrcode'); } catch (e) { /* optional */ } +const chatbot = require('./chatbot'); +const coach = require('./coach'); // coaching view, nudges, digest, prospects, link stats +const tank = require('./tank'); // holding tank: unsponsored free members, adoptions, pay-it-forward +const legacy = require('./legacy'); // Faucet Wave / Tier One Ads bridge: welcome-back credits for listed emails +const traffic = require('./traffic'); // public page views by referring domain (admin Traffic tab) +const promos = require('./promos'); // partner promo codes -> free ad credits (link ?promo=CODE or the dashboard box) +const blog = require('./blog'); +const adminMember = require('./adminmember'); +const syndicate = require('./syndicate'); +const releases = require('./releases'); +const updates = require('./updates'); +const audit = require('./audit'); // counter audit: views vs delivery logs, charges vs shows (Marty, 2026-09-15) // member update emails from Admin > Releases (Marty, 2026-09-14) +const leaderboard = require('./leaderboard'); +const toolkit = require('./toolkit'); +const registry = require('./registry'); // network registry: who is who across properties (LinkSpin, 2026-09-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) +const postbacks = require('./postbacks'); // outbound + inbound conversion postbacks on rotator clicks (2026-09-29) +const sources = require('./sources'); // traffic sources: network macros, campaign URLs, per-source postbacks, Reports dimension (2026-10-12) +const pages = require('./pages'); // member pages: bridge / review / squeeze, served at /p/ (2026-09-29) +const domains = require('./domains'); // link-domain pool by channel + six-hourly safety checks; burned domains leave the pool (2026-10-10) +const zonereport = require('./zonereport'); // read-only zone numbers for member Reports (2026-10-10) +const zones = require('./zones'); // ad zones on members' own sites (2026-09-29) +const nas = require('./nas'); +const audiences = require('./audiences'); // first-party retargeting (2026-10-08) // only asked whether syndication is on (the status strip) +const MEMBER_AD_TYPES = ['banner', 'text', 'login']; // the formats LinkSpin members can buy (video, visits, featured, solo stay off) // the rotator: rotations, weighted destinations, /r/ +const snapshot = require('./snapshot'); // daily growth snapshot -> Telegram payments feed (Marty, 2026-09-15) +const pipeline = require('./pipeline'); // sponsor follow-up board (coming soon until site setting pipelineMode = on) (Marty, 2026-09-15) +const videomaker = require('./videomaker'); // Circuit tool: promo videos with the member's own end card (ffmpeg in the image) // badge-gated promo toolkit + AI Copy Engine (Surge and up) (Marty, 2026-09-14) // referral contest: /leaderboard, Overview card, weekly + monthly winners (Marty, 2026-09-14) // release notes + roadmap: /whats-new, Overview card, Admin > Releases (Marty, 2026-09-14) // blog -> Blotato -> X + Instagram on publish (Marty, 2026-09-13) // admin member card: search, drilldown, edits (Marty, 2026-09-13) // admin-written coaching articles, server-rendered public /blog with SEO metadata (Marty, 2026-09-12) +const TRAFFIC_PAGES = new Set(['/', '/ledger', '/contract', '/shorts', '/plays', '/wallets', '/launch', '/partners', '/publishers', '/earning', '/blog', '/whats-new', '/leaderboard']); +let tankWaitCache = null; // dashboard: who is waiting for a sponsor (refreshed every minute) +const geo = require('./geo'); // viewer country -> tier (DB-IP lite), for campaign targeting +const burner = require('./burner'); // automatic on-chain credit burns (inert without ENGINE_KEY) + +const PORT = Number(process.env.PORT || 3000); +const ROOT = __dirname; +const PUBLIC_DIR = path.join(ROOT, 'public'); +const DATA_DIR = process.env.DATA_DIR || path.join(ROOT, 'data'); +const ADMIN_PASSWORD = process.env.ADMIN_PASSWORD || 'changeme'; +const ADMIN_EMAIL = String(process.env.ADMIN_EMAIL || '').trim().toLowerCase(); +const { SITE_HOST, SITE_URL } = require('./host'); +// Admin portal sessions: email-code sign-in allowlisted to ADMIN_EMAIL, kept +// in the volume so a restart doesn't log the admin out. Separate cookie and +// store from member sessions; the Bearer ADMIN_PASSWORD API path still works. +const ADMIN_SESS_FILE = path.join(DATA_DIR, 'admin-sessions.json'); +const ADMIN_TTL = 12 * 60 * 60 * 1000; +let adminSessions = {}; +try { adminSessions = JSON.parse(fs.readFileSync(ADMIN_SESS_FILE, 'utf8')) || {}; } catch (e) { adminSessions = {}; } +function saveAdminSessions() { + const now = Date.now(); + for (const k of Object.keys(adminSessions)) if (!adminSessions[k] || adminSessions[k].expires < now) delete adminSessions[k]; + try { fs.writeFileSync(ADMIN_SESS_FILE, JSON.stringify(adminSessions), { mode: 0o600 }); } catch (e) {} +} +function mintAdminSession(email) { + const t = crypto.randomBytes(32).toString('hex'); + adminSessions[t] = { email, expires: Date.now() + ADMIN_TTL }; + saveAdminSessions(); + return t; +} +function adminTokenOf(req) { const m = /(?:^|;\s*)iap\.adm=([^;]+)/.exec(req.headers.cookie || ''); return m ? decodeURIComponent(m[1]) : null; } +function adminFromRequest(req) { const t = adminTokenOf(req); const s = t && adminSessions[t]; return (s && s.expires > Date.now()) ? s : null; } +function dropAdminSession(req) { const t = adminTokenOf(req); if (t && adminSessions[t]) { delete adminSessions[t]; saveAdminSessions(); } } +function adminCookie(t) { return 'iap.adm=' + encodeURIComponent(t) + '; Path=/; HttpOnly; SameSite=Lax; Max-Age=' + (ADMIN_TTL / 1000) + (IS_PROD ? '; Secure' : ''); } +function clearAdminCookie() { return 'iap.adm=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0'; } +const IS_PROD = process.env.NODE_ENV === 'production'; +// Posture gates. mailer.js is the authority on outbound; this copy only decides whether the +// mailing loops are worth starting. SIGNUPS=closed shuts registration without taking the +// site down — members already here keep their dashboards. +const OUTBOUND_MAIL = process.env.OUTBOUND === 'on'; +const SIGNUPS_OPEN = process.env.SIGNUPS !== 'closed'; +const SHUT = { error: 'LinkSpin is not accepting new accounts right now.' }; +// pre-launch whitelist (Marty 2026-10-08: public pages visible, nobody signs in unless whitelisted): LS_TESTERS = comma list of +// emails or usernames; empty = everyone with an account may sign in +const TESTERS = new Set(String(process.env.LS_TESTERS || '').split(',').map(x => x.trim().toLowerCase()).filter(Boolean)); +const TESTING = { error: 'LinkSpin is in testing. Members get in on launch day.' }; +const isTester = (email, acct) => !TESTERS.size || TESTERS.has(String(email || '').toLowerCase()) || TESTERS.has(String((acct && acct.username) || '').toLowerCase()); +const SITE_FILE = path.join(DATA_DIR, 'site.json'); + +const db = require('./db'); +fs.mkdirSync(DATA_DIR, { recursive: true }); +const UPLOADS_DIR = path.join(DATA_DIR, 'uploads'); // solo-ad media lives on the volume +fs.mkdirSync(UPLOADS_DIR, { recursive: true }); +const uploadCounts = new Map(); // email:day -> uploads today +// open earn tokens (ad view / video / visit / tour) live in memory but mirror to the volume so a +// redeploy mid-watch does not lose them (2026-09-13: a member's video watch died in a restart) +const OPEN_TOKENS_FILE = () => path.join(DATA_DIR, 'open-tokens.json'); +const persistedMaps = {}; +let tokenSaveTimer = null; +function saveOpenTokens() { + tokenSaveTimer = null; + try { + const out = {}; + for (const [name, m] of Object.entries(persistedMaps)) out[name] = Object.fromEntries(m); + fs.writeFileSync(OPEN_TOKENS_FILE(), JSON.stringify(out)); + } catch (e) {} +} +function persistedMap(name) { + const m = new Map(); + const touch = () => { if (!tokenSaveTimer) tokenSaveTimer = setTimeout(saveOpenTokens, 500); }; + const set = m.set.bind(m), del = m.delete.bind(m); + m.set = (k, v) => { set(k, v); touch(); return m; }; + m.delete = k => { const r = del(k); if (r) touch(); return r; }; + persistedMaps[name] = m; + return m; +} +function loadOpenTokens() { + let saved = null; try { saved = JSON.parse(fs.readFileSync(OPEN_TOKENS_FILE(), 'utf8')); } catch (e) { return; } + const cutoff = Date.now() - 2 * 3600 * 1000; let n = 0; + for (const [name, m] of Object.entries(persistedMaps)) { + for (const [k, v] of Object.entries(saved[name] || {})) if (v && Number(v.ts || 0) > cutoff) { Map.prototype.set.call(m, k, v); n++; } + } + if (n) console.log('open earn tokens restored:', n); +} +const gauntletTokens = persistedMap('gauntlet'); // email -> welcome-tour token (server-clock dwell floor) +const videoTokens = persistedMap('video'); // email -> watch-to-earn video token (server-clock watch floor) +const faucetHits = new Map(); // address -> last faucet ts (rehearsal test-POL faucet rate limit) +const visitTokens = persistedMap('visit'); // email -> verified-visit token (dwell + captcha floor) +// walk the referral chain upward via sponsorRef (code/username/member id) +async function uplineSlides(email, depth = 3) { + const out = []; + let cur = await accounts.byEmail(email); + for (let i = 0; i < depth && cur; i++) { + const ref = String(cur.sponsorRef || '').trim().toLowerCase(); + if (!ref) break; + let s = null; + if (/^\d+$/.test(ref)) s = await accounts.byMemberId(Number(ref)); + if (!s) s = await accounts.byCode(ref); + if (!s) s = await accounts.byUsername(ref); + if (!s || s.email === cur.email) break; + out.push(s); + cur = s; + } + return out; +} +// Wall ownership ladder: position 1 is always the member's own line banner; +// positions 2 and 3 become theirs at 2 and 5 qualifying buyers (the same +// thresholds that open payout levels 2 and 3). Until then, or while an unlocked +// slot is empty, the slot shows an upline's banner, then a house ad. +const catalogCache = { at: 0, products: null }; +const wallUnlockedFor = bc => (bc >= 5 ? 3 : bc >= 2 ? 2 : 1); +// every on-chain member id this session controls: the main wallet plus linked +// positions (Qualified Start). Credits pool across them on the dashboard. +const memberInfoCache = new Map(); // id -> { t, v } (60s): line views ask for every member's on-chain row +async function cachedMember(id) { + const c = memberInfoCache.get(id); if (c && Date.now() - c.t < 60000) return c.v; + let v = null; try { v = await chain.member(id); } catch (e) {} + memberInfoCache.set(id, { t: Date.now(), v }); return v; +} +async function myMemberIds(s) { + const main = await auth.refreshMemberId(s); + const ids = main ? [main] : []; + if (s && s.email) for (const p of await accounts.positions(s.email)) if (p.memberId && !ids.includes(p.memberId)) ids.push(p.memberId); + return { main, ids }; +} +function parseWallOffers(a) { + try { const v = JSON.parse((a && a.wallOffers) || '[]'); return Array.isArray(v) ? v.slice(0, 2) : []; } catch (e) { return []; } +} +// admin fallback ads for wall positions 2 & 3 when a member has no upline. +// Configurable by dropping data/admin-wall-ads.json ([{name,targetUrl,bannerUrl}]). +function getAdminWallAds() { + try { const j = JSON.parse(fs.readFileSync(path.join(DATA_DIR, 'admin-wall-ads.json'), 'utf8')); if (Array.isArray(j) && j.length) return j; } catch (e) {} + return [{ name: 'LinkSpin', targetUrl: SITE_URL + '/', bannerUrl: null }]; +} +const chatHits = new Map(); +const demoLimits = new Map(); // ip -> timestamps of home-page demo spins (5 per hour) +function chatLimited(ip) { + const now = Date.now(), rec = chatHits.get(ip); + if (!rec || now > rec.reset) { chatHits.set(ip, { count: 1, reset: now + 60000 }); return false; } + rec.count += 1; + return rec.count > 10; +} +// magic-code sign-in: emailLower -> {code, exp, tries} +const emailCodes = new Map(); +const inviteTokens = new Map(); // admin-minted one-time sign-in links for testers: token -> {email, exp, next} +// ── sign-up code guard (Marty, 2026-09-11): the email box is one field and one +// tap, so nothing visible stands in a human's way. Bots hit four invisible walls: +// a honeypot field, a minimum form age, per-IP + global send limits, and, only +// once an IP trips a limit, the same icon check the ad viewer uses. +const CODE_LIMITS = { per10m: 5, perDay: 20, globalPerMin: 60, passMs: 5 * 60 * 1000, minFormMs: 2000 }; +const codeHits = new Map(); // ip -> { t: [send timestamps, 24h], passUntil, chal: { answer, exp } } +const codeGlobal = { minute: 0, n: 0 }; +const codeAlert = { last: 0, trips: 0, ips: new Set() }; +function clientIp(req) { return String(req.headers['x-forwarded-for'] || req.socket.remoteAddress || '').split(',')[0].trim() || 'unknown'; } +// the viewer's country and tier for ad targeting (null tier = unknown: never matches a restricted campaign) +// CORS for the zone tag: echo the calling origin and allow credentials, so the browser may send the ls.vid cookie +function corsCreds(req) { const o = String(req.headers.origin || ''); return o ? { 'Access-Control-Allow-Origin': o, 'Access-Control-Allow-Credentials': 'true', 'Vary': 'Origin' } : { 'Access-Control-Allow-Origin': '*' }; } +const PIXEL_GIF = Buffer.from('R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7', 'base64'); +function viewerGeo(req) { const cc = geo.countryOf(clientIp(req)); return { cc, tier: geo.tierOf(cc, siteConfig()) }; } +function codeChallenge(rec) { + const pick = CAPTCHA.slice().sort(() => Math.random() - 0.5).slice(0, 5); + const answer = Math.floor(Math.random() * pick.length); + rec.chal = { answer: pick[answer][0], exp: Date.now() + 5 * 60 * 1000 }; + return { prompt: pick[answer][1], options: pick.map(x => x[0]) }; +} +// returns null to allow the send, or { status, body } to answer with instead +const guardLog = (req, why, b) => console.log('signup-guard', why, clientIp(req), String(b.email || '').replace(/^(.).*(@.*)$/, '$1***$2')); +function codeGuard(req, b) { + const now = Date.now(); + // honeypot: bots fill it, humans never see it. Some form-filler extensions fill every field, + // hidden or not (seen 2026-09-11), so a filled honeypot is a CHALLENGE, never a silent drop: + // a person passes the icon check and gets the code, a bot cannot. + const hpRaw = String(b.hp_field_x9 || '').trim(); + const hpIsEmail = !!hpRaw && hpRaw.toLowerCase() === String(b.email || '').trim().toLowerCase(); + const hp = !!hpRaw && !hpIsEmail; // 2026-09-13: phones were autofilling the hidden field; own email = autofill, not a bot + if (hpRaw) console.log('signup-guard honeypot-value', clientIp(req), hpIsEmail ? 'own-email' : (/^https?:/i.test(hpRaw) ? 'url' : /@/.test(hpRaw) ? 'other-email' : /^\+?[\d\s()-]{6,}$/.test(hpRaw) ? 'phone' : 'text'), 'len=' + hpRaw.length, hpIsEmail ? '' : hpRaw.slice(0, 2) + '***'); + const fts = Number(b.fts) || 0; + if (!fts || now - fts < CODE_LIMITS.minFormMs) { guardLog(req, 'form-age', b); return { status: 400, body: { error: 'Give the page a second, then tap again.' } }; } + if (now - fts > 12 * 3600 * 1000) { guardLog(req, 'form-stale', b); return { status: 400, body: { error: 'This page has been open a long time. Refresh it, then tap again.' } }; } + const minute = Math.floor(now / 60000); + if (codeGlobal.minute !== minute) { codeGlobal.minute = minute; codeGlobal.n = 0; } + if (codeGlobal.n >= CODE_LIMITS.globalPerMin) { guardLog(req, 'global-limit', b); codeTrip(req, 'global'); return { status: 429, body: { error: 'Busy right now. Try again in a minute.' } }; } + const ip = clientIp(req); + const rec = codeHits.get(ip) || { t: [], passUntil: 0, chal: null }; + rec.t = rec.t.filter(ts => now - ts < 24 * 3600 * 1000); + const n10 = rec.t.filter(ts => now - ts < 10 * 60 * 1000).length; + const limited = hp || n10 >= CODE_LIMITS.per10m || rec.t.length >= CODE_LIMITS.perDay; + if (limited && now >= rec.passUntil) { + const pick = String(b.pick || ''); + if (pick && rec.chal && rec.chal.exp > now && pick === rec.chal.answer) { rec.passUntil = now + CODE_LIMITS.passMs; rec.chal = null; } + else { + guardLog(req, pick ? 'wrong-pick' : hp ? 'honeypot-challenge' : 'ip-limit', b); if (!hp) codeTrip(req, ip); + const challenge = codeChallenge(rec); codeHits.set(ip, rec); + return { status: 429, body: { error: pick ? 'That was not it. Try once more.' : 'Quick check before we send another code.', challenge } }; + } + } + rec.t.push(now); codeHits.set(ip, rec); codeGlobal.n += 1; + if (codeHits.size > 5000) for (const [k, v] of codeHits) { if (!v.t.length || now - v.t[v.t.length - 1] > 24 * 3600 * 1000) codeHits.delete(k); } + return null; +} +// burst alert: at most one message per 10 minutes, to the admin Telegram chat if set, else the admin email +function codeTrip(req, ip) { + codeAlert.trips += 1; codeAlert.ips.add(ip); + if (Date.now() - codeAlert.last < 10 * 60 * 1000) return; + codeAlert.last = Date.now(); + const text = '\u26A0\uFE0F LinkSpin sign-up guard: ' + codeAlert.trips + ' blocked code request' + (codeAlert.trips === 1 ? '' : 's') + ' from ' + codeAlert.ips.size + ' source' + (codeAlert.ips.size === 1 ? '' : 's') + ' (' + [...codeAlert.ips].slice(0, 5).join(', ') + ') in the last window.'; + codeAlert.trips = 0; codeAlert.ips = new Set(); + const sc = siteConfig(); + if (sc.telegramBotToken && sc.telegramAdminChatId) telegramSend(sc.telegramAdminChatId, text).catch(() => {}); + else if (ADMIN_EMAIL && mailer.hasKey()) mailer.send(ADMIN_EMAIL, 'LinkSpin: sign-up guard tripped', text).catch(() => {}); +} +// earn-view tokens: emailLower -> {token, ts} (one live token per member) +const earnTokens = persistedMap('earn'); +// human-check pairs for the view verifier: [emoji shown, word named in the prompt] +const CAPTCHA = [['🚀', 'rocket'], ['⚡', 'lightning bolt'], ['🔑', 'key'], ['🎯', 'target'], + ['🌊', 'wave'], ['🔥', 'flame'], ['💎', 'diamond'], ['🧲', 'magnet'], ['🔔', 'bell'], ['🌙', 'moon']]; + +// ── frame-breaking check ───────────────────────────────── +// Surf views frame the advertiser's URL full screen, so a target that refuses +// framing (X-Frame-Options / CSP frame-ancestors) would burn members' views on +// a blank frame. Catch it the moment the campaign is submitted. The lookup +// also refuses private/internal addresses so member URLs can't probe our LAN. +const PRIVATE_IP = /^(127\.|10\.|192\.168\.|169\.254\.|0\.|172\.(1[6-9]|2\d|3[01])\.|::1$|::$|f[cd])/i; +function frameFetch(url, depth) { + return new Promise(resolve => { + let u; + try { u = new URL(String(url || '')); } catch (e) { return resolve({ error: 'that is not a valid URL' }); } + if (!/^https?:$/.test(u.protocol)) return resolve({ error: 'only http(s) URLs work' }); + if (u.port && u.port !== '80' && u.port !== '443') return resolve({ error: 'custom ports are not allowed' }); + if (u.hostname === 'localhost' || u.hostname.endsWith('.local')) return resolve({ error: 'that address is not reachable from here' }); + dns.lookup(u.hostname, (de, addr) => { + if (de) return resolve({ error: 'that domain does not resolve' }); + if (PRIVATE_IP.test(addr)) return resolve({ error: 'that address is not reachable from here' }); + const mod = u.protocol === 'https:' ? https : http; + // Our own hosts (the app and the link domains) answer the curtain's 503 to anonymous fetches while the + // app is curtained, which made a test ad aimed at a spin link look dead (2026-10-07). Carry the pass. + const own = [SITE_HOST].concat(String(siteConfig().linkDomains || '').split(',').map(x => x.trim().toLowerCase()).filter(Boolean), pagesHost() ? [pagesHost()] : []); + const hdrs = { 'User-Agent': 'Mozilla/5.0 (compatible; LinkSpin-FrameCheck/1.0)', Accept: 'text/html' }; + if (CURTAIN && own.includes(u.hostname.toLowerCase())) hdrs.Cookie = 'ls.pass=' + encodeURIComponent(CURTAIN); + const rq = mod.get(u.href, { timeout: 8000, headers: hdrs }, r => { + const loc = r.headers.location; + r.resume(); // headers are all we need + if ([301, 302, 303, 307, 308].includes(r.statusCode) && loc && depth < 4) { + rq.destroy(); + let next; try { next = new URL(loc, u.href).href; } catch (e2) { return resolve({ error: 'it redirects somewhere invalid' }); } + return resolve(frameFetch(next, depth + 1)); // every hop re-runs the private-IP guard + } + resolve({ status: r.statusCode, xfo: r.headers['x-frame-options'] || '', csp: r.headers['content-security-policy'] || '' }); + rq.destroy(); + }); + rq.on('timeout', () => { rq.destroy(); resolve({ error: 'it did not answer within 8 seconds' }); }); + rq.on('error', e2 => resolve({ error: 'it did not answer (' + (e2.code || 'connection failed') + ')' })); + }); + }); +} +// shared upload path for member creatives (/api/my/upload) and admin house-ad +// creatives (/api/admin/upload): `who` keys the per-day upload counter +async function handleUpload(req, res, who) { + const ct = String(req.headers['content-type'] || '').split(';')[0].trim().toLowerCase(); + const EXT = { 'image/png': 'png', 'image/jpeg': 'jpg', 'image/webp': 'webp', 'image/gif': 'gif', + 'video/mp4': 'mp4', 'video/webm': 'webm' }; + if (!EXT[ct]) return json(res, 400, { error: 'Use a PNG, JPG, WebP, GIF, MP4 or WebM file.' }); + const isVideo = ct.startsWith('video/'); + const key = who + ':' + new Date().toISOString().slice(0, 10); + if ((uploadCounts.get(key) || 0) >= 10) return json(res, 400, { error: 'Upload limit for today reached (10 files).' }); + let buf; + try { buf = await readRaw(req, isVideo ? 25 * 1024 * 1024 : 3 * 1024 * 1024); } + catch (e) { return json(res, 400, { error: 'File too large. Images up to 3MB, video up to 25MB.' }); } + const magicOk = buf.length > 16 && ( + (ct === 'image/png' && buf[0] === 0x89 && buf[1] === 0x50 && buf[2] === 0x4e && buf[3] === 0x47) || + (ct === 'image/jpeg' && buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff) || + (ct === 'image/webp' && buf.slice(0, 4).toString() === 'RIFF' && buf.slice(8, 12).toString() === 'WEBP') || + (ct === 'image/gif' && buf.slice(0, 4).toString() === 'GIF8') || + (ct === 'video/mp4' && buf.slice(4, 8).toString() === 'ftyp') || + (ct === 'video/webm' && buf[0] === 0x1a && buf[1] === 0x45 && buf[2] === 0xdf && buf[3] === 0xa3)); + if (!magicOk) return json(res, 400, { error: 'That file does not look like a real ' + EXT[ct].toUpperCase() + '.' }); + const name = crypto.randomBytes(12).toString('hex') + '.' + EXT[ct]; + uploadCounts.set(key, (uploadCounts.get(key) || 0) + 1); + // video goes to DO Spaces when configured (keeps big files off the volume); + // images stay local. Falls back to the volume if Spaces isn't set or errors. + if (isVideo && spaces.enabled()) { + try { + const url = await spaces.put('iap-uploads/' + name, buf, ct); + return json(res, 200, { url, type: 'video' }); + } catch (e) { console.error('spaces put', e.message); /* fall through to volume */ } + } + fs.writeFileSync(path.join(UPLOADS_DIR, name), buf); + return json(res, 200, { url: '/uploads/' + name, type: isVideo ? 'video' : 'image' }); +} +// lead-capture page hooks (og tags + copy live in public/assets/join.js too) +const JOIN_ALIASES = { company: 'martbost', top: 'martbost' }; // neutral partner links -> the top position +const JOIN_ANGLES = { + // legacy bridge pages (/from/): former members of Marty's closed EvolutionScript sites + 'fw-adv': { t: 'Your next ad budget pays you back.', d: 'Faucet Wave closed. LinkSpin was built for the people who bought ads there: packages from $10, banner, text and login ads, every package in your line paid out on Polygon in the same transaction. Welcome-back credits waiting.', url: SITE_URL + '/from/faucetwave?seg=advertiser' }, + 'fw-earn': { t: 'Same daily habit. Real payouts on-chain.', d: 'You viewed ads on Faucet Wave. Here you view ads to earn credits, run your own campaign free, and get paid in POL to your own wallet when your line buys ads. Welcome-back credits waiting.', url: SITE_URL + '/from/faucetwave' }, + 't1-adv': { t: 'Your next ad budget pays you back.', d: 'Tier One Ads closed. LinkSpin was built for the people who bought ads there: packages from $10, banner, text and login ads, every package in your line paid out on Polygon in the same transaction. Welcome-back credits waiting.', url: SITE_URL + '/from/tieroneads?seg=advertiser' }, + 't1-earn': { t: 'Same daily habit. Real payouts on-chain.', d: 'You viewed ads on Tier One Ads. Here you view ads to earn credits, run your own campaign free, and get paid in POL to your own wallet when your line buys ads. Welcome-back credits waiting.', url: SITE_URL + '/from/tieroneads' }, + instant: { t: 'Paid before the page reloads.', d: 'A smart contract on Polygon splits every ad package the moment it sells. Same transaction, real wallets, public ledger. Join free by email.' }, + adspend: { t: 'You were buying ads anyway.', d: 'Here the ad spend in your line pays you, in the same transaction, on a public ledger. Banner, text and login ads, packages from $10. Join free.' }, + free: { t: 'Watch first. Spend never.', d: 'Join free, view a few ads, earn credits, run your first campaign for zero dollars. Every payout public on Polygon.' }, + // LinkSpin-only hooks (2026-10-09), each with a video on the join page + links: { t: 'Stop juggling links.', d: 'One short link rotates every page you promote, with weights, hours and a fallback, and a report by source. Free, try a spin with no account.' }, + pages: { t: 'A bridge page in a minute.', d: 'Point LinkSpin at any offer, add one line in your words, and get a bridge, review or squeeze page on a clean domain. Leads are yours. Free.' }, + zones: { t: 'Your site pays you.', d: 'One script tag puts an ad slot on your website. Every viewable view pays you ad credits you spend on your own campaign. Nine sizes, free.' }, + audiences: { t: 'Retarget without renting an audience.', d: 'Everyone who sees your pages or zones is remembered for 30 days in an audience you own. Show a campaign only to them, or never to them.' }, + stack: { t: 'Three tools, zero dollars.', d: 'A link rotator, a bridge-page builder and an ad slot for your own site, free with an email. Buy a package only if you want more.' }, + ledger: { t: 'No back office. No payday.', d: 'Every payout is a public transaction on Polygon you can read yourself. Nothing is ever held. Join free by email.' }, + two: { t: 'Two buyers open level two.', d: 'Every direct buyer pays you 50 percent from their first package. Two qualifying buyers open level two, five open level three. Written in a verified contract.' } +}; +function serveJoinPage(res, tok, angle, ang, setCookies) { + let html; + try { html = fs.readFileSync(path.join(PUBLIC_DIR, 'join.html'), 'utf8'); } catch (e) { res.writeHead(404, baseHeaders({ 'Content-Type': 'text/plain' })); return res.end('Not found'); } + const base = SITE_URL; + const url = (ang && ang.url) || (base + '/join/' + tok + (angle ? '?v=' + angle : '')); + const title = ang ? ang.t : 'Advertise and earn. Paid on-chain, instantly.'; + const desc = ang ? ang.d : 'You are invited to LinkSpin: real ad packages with same-transaction payouts on Polygon, every payment public. Join free by email.'; + const escA = t => String(t).replace(/&/g, '&').replace(/"/g, '"').replace(/' + + '' // keeps ?v= so shares stay on the angle + + '' + + ''; + html = html.replace(/[^<]*<\/title>/, '<title>' + escA(title) + ' | LinkSpin' + og); + if (ang) html = html.replace('', ''); // angle pages: squeeze layout from the first paint + const headers = { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store, must-revalidate' }; + if (setCookies && setCookies.length) headers['Set-Cookie'] = setCookies; + res.writeHead(200, baseHeaders(headers)); + res.end(html); +} +async function frameCheck(url) { + const h = await frameFetch(url, 0); + if (h.error) return { ok: false, reason: 'We checked your URL and ' + h.error + '. Fix the URL and try again.' }; + if (h.status >= 400) return { ok: false, reason: 'Your URL answers with HTTP ' + h.status + '. Point the campaign at a working page.' }; + if (/deny|sameorigin/i.test(String(h.xfo))) + return { ok: false, reason: 'That site blocks framing (X-Frame-Options), so it would show members a blank page in the ad viewer. Use a landing page that allows framing.' }; + const fa = /frame-ancestors\s+([^;]+)/i.exec(String(h.csp)); + if (fa && !fa[1].split(/\s+/).some(x => { + const v = x.replace(/['"]/g, '').toLowerCase(); + return v === '*' || v === 'https:' || v.includes(SITE_HOST); + })) + return { ok: false, reason: 'That site blocks framing (CSP frame-ancestors), so it would show members a blank page in the ad viewer. Use a landing page that allows framing.' }; + return { ok: true }; +} +async function boot() { + await db.init({ dataDir: DATA_DIR }); // no-op without DATABASE_URL (JSON mode) + chain.init({ onEvent: ev => { attachNames([ev]).then(a => pushFeed(a[0])).catch(() => pushFeed(ev)); emailOnEvent(ev).catch(() => {}); telegramOnEvent(ev).catch(() => {}); + if (ev && ev.type === 'Purchase' && ev.buyerId) accounts.byMemberId(Number(ev.buyerId)).then(a => { if (a) return postbacks.convertFor(a.email, 'purchase', { payout: (Number(ev.priceCents) || 0) / 100, currency: 'USD', txid: ev.tx || '' }); }).catch(() => {}); } }); + auth.init({ dataDir: DATA_DIR, chain, isProd: IS_PROD, site: SITE_HOST }); + accounts.init({ dataDir: DATA_DIR }); + ads.init({ dataDir: DATA_DIR, chain }); + mailer.init({ dataDir: DATA_DIR }); + messages.init({ dataDir: DATA_DIR }); + reports.init({ dataDir: DATA_DIR }); + drip.init({ dataDir: DATA_DIR, mailer, accounts, chain, site: SITE_URL }); + chatbot.init({ dataDir: DATA_DIR, chain }); + setTimeout(() => ads.dailySweep().catch(e => console.error('sweep', e.message)), 60 * 1000); + setInterval(() => ads.dailySweep().catch(e => console.error('sweep', e.message)), 60 * 60 * 1000); + setInterval(() => ads.scheduleSweep().catch(e => console.error('schedule sweep', e.message)), 5 * 60 * 1000); // scheduled starts/ends + // follow-up email sequence: send whatever came due (every 10 min, first pass shortly after boot) + coach.init({ dataDir: DATA_DIR, chain, accounts, mailer, ads, tank, lb: () => leaderboard, siteConfig }); + 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 }); + 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) + health.init({ rotator, dataDir: DATA_DIR, notify: (email, subject, html) => messages.deliver(1, ADMIN_EMAIL || 'house@' + SITE_HOST, [email], subject, html) }); + setTimeout(() => health.tick().catch(e => console.error('health', e.message)), 2 * 60 * 1000); + setInterval(() => health.tick().catch(e => console.error('health', e.message)), 30 * 60 * 1000); + setInterval(() => { try { rotator.sweepDemos(); } catch (e) {} }, 60 * 60 * 1000); // unclaimed home-page demo spins expire after 24 h + postbacks.init({ dataDir: DATA_DIR, ownHosts, rotator, sources }); + sources.init({ dataDir: DATA_DIR, postbacks, rotator, catalogFile: path.join(ROOT, 'catalog', 'traffic-sources.json'), linkHost: () => { const hs = String(siteConfig().linkDomains || '').split(',').map(x => x.trim()).filter(Boolean); return hs[0] || SITE_HOST; } }); + zones.init({ dataDir: DATA_DIR, ads, siteHost: SITE_HOST }); + pages.init({ dataDir: DATA_DIR, ownHosts, imageBase: () => (IS_PROD ? 'https' : 'http') + '://' + SITE_HOST, openrouterKey: () => { if (process.env.OPENROUTER_API_KEY) return process.env.OPENROUTER_API_KEY.trim(); try { return fs.readFileSync(path.join(DATA_DIR, 'openrouter.key'), 'utf8').trim(); } catch (e) { return ''; } } }); + audiences.init({ dataDir: DATA_DIR }); + // link-domain pool: channels live in site.json (linkDomainChannels), check state in domains.json; a burn alerts the admin once + domains.init({ dataDir: DATA_DIR, siteConfig, saveSite: patch => fs.writeFileSync(SITE_FILE, JSON.stringify(Object.assign(siteConfig(), patch), null, 2)), + notify: async text => { const sc = siteConfig(); if (sc.telegramBotToken && sc.telegramAdminChatId) await telegramSend(sc.telegramAdminChatId, text); else if (ADMIN_EMAIL && mailer.hasKey()) await mailer.send(ADMIN_EMAIL, 'LinkSpin: link domain burned', text.replace(/<[^>]+>/g, '')); } }); + zonereport.init({ dataDir: DATA_DIR }); + snapshot.init({ dataDir: DATA_DIR, db, chain, siteConfig, send: async (c, t, th) => { await telegramSend(c, t, th); return true; } }); + setInterval(() => snapshot.tick().catch(e => console.error('snapshot', e.message)), 10 * 60 * 1000); + tank.init({ dataDir: DATA_DIR, chain, accounts, messages, mailer, site: SITE_URL }); + legacy.init({ dataDir: DATA_DIR }); + traffic.init({ dataDir: DATA_DIR }); + promos.init({ dataDir: DATA_DIR }); + blog.init({ dataDir: DATA_DIR }); + adminMember.init({ accounts, ads, chain, tank, legacy, promos, messages, dataDir: DATA_DIR }); + loadOpenTokens(); + syndicate.init({ dataDir: DATA_DIR, publicDir: PUBLIC_DIR, uploadsDir: UPLOADS_DIR }); + releases.init({ dataDir: DATA_DIR }); + toolkit.init({ dataDir: DATA_DIR, ads, accounts, siteConfig, coach, messages, promos, videomaker, chain }); + updates.init({ dataDir: DATA_DIR, accounts, releases, mailer, drip, sendy, adminEmail: ADMIN_EMAIL }); + audit.init({ dataDir: DATA_DIR, notify: text => { const sc = siteConfig(); if (sc.telegramBotToken && sc.telegramAdminChatId) telegramSend(sc.telegramAdminChatId, text).catch(() => {}); else if (ADMIN_EMAIL && mailer.hasKey()) mailer.send(ADMIN_EMAIL, 'LinkSpin: counter audit', text).catch(() => {}); } }); + setTimeout(() => audit.dailyTick(), 5 * 60 * 1000); setInterval(() => audit.dailyTick(), 24 * 60 * 60 * 1000); + videomaker.init({ dataDir: DATA_DIR, spaces, accounts }); + leaderboard.init({ chain, accounts, ads, dataDir: DATA_DIR, siteConfig, pushFeed, adminEmail: ADMIN_EMAIL, + notify: async text => { const sc = siteConfig(); if (!sc.telegramBotToken || !sc.telegramEchoChatId) return; await telegramSend(sc.telegramEchoChatId, text, sc.telegramEchoTopicId); if (String(sc.leaderboardAnnounceGeneral || '1') !== '0') await telegramSend(sc.telegramEchoChatId, text, null); } }); + setTimeout(() => leaderboard.rolloverTick().catch(e => console.error('leaderboard rollover', e.message)), 90 * 1000); + setInterval(() => leaderboard.rolloverTick().catch(e => console.error('leaderboard rollover', e.message)), 60 * 60 * 1000); + console.log('blog syndication:', syndicate.enabled() ? 'on (X + Instagram via Blotato)' : 'off (no blotato.key)'); + setInterval(() => tankNotifyTick().catch(e => console.error('tank notify', e.message)), 15 * 60 * 1000); // new tank arrivals -> Telegram + geo.init({ dataDir: DATA_DIR }).catch(e => console.error('geo init', e.message)); + setInterval(() => geo.refresh().catch(e => console.error('geo refresh', e.message)), 24 * 3600 * 1000); // monthly file, checked daily + setInterval(() => tank.sweep().catch(e => console.error('tank sweep', e.message)), 60 * 60 * 1000); // adoptions past their 7-day window + burner.init({ chain, ads, accounts }); + if (OUTBOUND_MAIL) { // the stall nudges are a mailing loop; do not even start it when mail is off + setTimeout(() => coach.nudgeTick().catch(e => console.error('coach', e.message)), 90 * 1000); + setInterval(() => coach.nudgeTick().catch(e => console.error('coach', e.message)), 60 * 60 * 1000); + } + setTimeout(() => burner.tick().catch(e => console.error('burner', e.message)), 45 * 1000); + setInterval(() => burner.tick().catch(e => console.error('burner', e.message)), 5 * 60 * 1000); + if (OUTBOUND_MAIL) { // same for the lead follow-up sequence + setTimeout(() => drip.tick().catch(e => console.error('drip', e.message)), 30 * 1000); + setInterval(() => drip.tick().catch(e => console.error('drip', e.message)), 10 * 60 * 1000); + } + // NAS reconcile: pull syndicated delivery into the unified credit pool + // (inert unless NAS_DB_* is set). Every 5 min after a short warm-up. + if (ads.nasEnabled()) { + console.log('NAS syndication enabled'); + setTimeout(() => ads.reconcileNas().catch(e => console.error('nas reconcile', e.message)), 90 * 1000); + setInterval(() => ads.reconcileNas().catch(e => console.error('nas reconcile', e.message)), 5 * 60 * 1000); + } +} + +function siteConfig() { + let saved = {}; + try { saved = JSON.parse(fs.readFileSync(SITE_FILE, 'utf8')); } catch (e) {} + return Object.assign({ + siteName: 'LinkSpin', + tagline: 'Advertise and earn. Locked in code, not promises.', + rehearsal: true, // shows the testnet banner; flipped off at mainnet launch + // payment-proof Telegram feed (blank = off) and the P&L pane's fixed monthly cost + telegramBotToken: '', telegramChatId: '', telegramTopicId: '', telegramEvents: 'payouts', telegramCtaUrl: SITE_URL + '/', + telegramEchoChatId: '', telegramEchoTopicId: '', telegramEchoEvents: 'payouts', // shared cross-program payments topic + telegramAdminChatId: '', // private chat for admin alerts (sign-up guard bursts); falls back to ADMIN_EMAIL + launchAt: '', // public launch moment, ISO 8601 with offset (e.g. 2026-09-18T19:00:00-05:00): countdown on /launch + dashboard mark + aiCreditsPerGen: 10, aiFreeSurge: 20, aiFreeCircuit: 60, aiFreeNexus: 150, // AI Copy Engine: free generations per month by badge, then credits per generation + carryClaimDays: '3', + carryNotices: '1', // 0 = carry-over notices stay on-site (test area), 1 = email too // sponsor with no wallet: days to link one before a downline seat walks up (LinkSpin) + linkDomains: '', // comma list of short link domains this server answers for (each gets a real mini-site + /r/ redirects) + pagesDomain: '', // the host member pages are published on at the root (https:///); empty = first link domain under /p/ + snapshotEnabled: '1', snapshotHourUtc: '14', snapshotTargets: 'feed,echo', // daily growth snapshot: 14 UTC = 9 AM Central; feed = proof channel, echo = shared payments topic + pipelineMode: 'off', // Pipeline board: off = 'coming soon' card, preview = only the admin account sees the live board, on = everyone (Marty, 2026-09-15) + pipelineEta: 'Sep 28', // what the coming-soon card and the roadmap promise + coachMail: '1', // 0 = stall-nudge emails off (pre-launch: imported shell accounts must not be nudged) + memberWeeklyEmail: '0', // 1 = the weekly 'Your week on LinkSpin' email goes to every active member, not only sponsors with a line + noPayoutIds: '25', // positions kept for linkage only (compromised wallets): no buys signed from them, no new joins routed under them or their upline chain (Marty, 2026-09-14) + leaderboardWeeklyPrize: '', leaderboardMonthlyPrize: '', leaderboardWeeklyCredits: '1000,500,250', leaderboardMonthlyCredits: '5000,2500,1000', leaderboardAnnounceGeneral: '1', // referral contest prizes (text shown on /leaderboard; credits granted to the winner automatically at rollover) + legacyCreditsAdvertiser: 500, legacyCreditsEarner: 150, // welcome-back credits for listed Faucet Wave / Tier One Ads emails arriving via /from/ + geoTier1: '', // comma-separated ISO country codes; empty = built-in default (US, CA, GB, AU, NZ, IE, DE, FR, NL, SE, NO, DK, FI, CH, AT, BE) + geoTier2: '', // empty = built-in default (rest of Western/Central Europe, JP, KR, SG, HK, TW, IL, Gulf, ZA, BR, MX, AR, CL, CO ...); tier 3 = everything else + pnlFixedMonthlyUsd: 0 + }, saved); +} + +// ---- helpers ---- +const MIME = { '.html': 'text/html; charset=utf-8', '.css': 'text/css', '.js': 'text/javascript', + '.png': 'image/png', '.jpg': 'image/jpeg', '.svg': 'image/svg+xml', '.webp': 'image/webp', + '.ico': 'image/x-icon', '.json': 'application/json', '.mp4': 'video/mp4', '.woff2': 'font/woff2', + '.gif': 'image/gif', '.webm': 'video/webm', '.txt': 'text/plain; charset=utf-8', '.xml': 'application/xml; charset=utf-8' }; +const CSP = "default-src 'self'; script-src 'self' https://cdn.jsdelivr.net 'sha256-NzvNrqk5jB9YZATwo5BF4JoRlJ02HsnFikbKXgEPdaQ='; worker-src 'self' blob:; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; img-src 'self' data: blob: https:; media-src 'self' https: blob:; connect-src 'self' https://*.walletconnect.com wss://*.walletconnect.com https://*.walletconnect.org wss://*.walletconnect.org https://*.reown.com wss://*.reown.com https://*.reown.org wss://*.reown.org https://*.web3modal.org https://*.drpc.org https://*.publicnode.com https://*.coinbase.com; font-src 'self' data: https://fonts.gstatic.com https://fonts.reown.com; form-action 'self'; frame-src https: http:"; +function baseHeaders(extra) { + return Object.assign({ 'Content-Security-Policy': CSP, 'X-Content-Type-Options': 'nosniff', + 'Referrer-Policy': 'strict-origin-when-cross-origin' }, extra || {}); +} +function json(res, code, obj, extra) { + const body = JSON.stringify(obj); + res.writeHead(code, baseHeaders(Object.assign({ 'Content-Type': 'application/json', 'Cache-Control': 'no-store' }, extra))); + res.end(body); +} +function sendFile(res, file) { + fs.readFile(file, (err, data) => { + if (err) { res.writeHead(404, baseHeaders({ 'Content-Type': 'text/plain' })); return res.end('Not found'); } + const ext = path.extname(file).toLowerCase(); + // Public pages carry {{SITE_URL}} / {{SITE_HOST}} in canonical, OG and sitemap lines so the same files + // serve every deployment (test host today, linkspin.app at launch); filled here, per request. + if (ext === '.html' || ext === '.txt' || ext === '.xml') data = Buffer.from(data.toString('utf8').split('{{SITE_URL}}').join(SITE_URL).split('{{SITE_HOST}}').join(SITE_HOST)); + res.writeHead(200, baseHeaders({ 'Content-Type': MIME[ext] || 'application/octet-stream', + // HTML is never stored (so a fresh load always gets the current asset + // versions — aggressive in-app wallet browsers were serving stale pages + // that pointed at old, since-fixed JS); versioned assets cache for an hour. + 'Cache-Control': ext === '.html' ? 'no-store, must-revalidate' : 'public, max-age=3600' })); + res.end(data); + }); +} +function readRaw(req, maxBytes) { + return new Promise((resolve, reject) => { + const chunks = []; + let n = 0; + req.on('data', c => { + n += c.length; + if (n > maxBytes) { req.destroy(); reject(new Error('too big')); return; } + chunks.push(c); + }); + req.on('end', () => resolve(Buffer.concat(chunks))); + req.on('error', reject); + }); +} +function readBody(req) { + return new Promise((resolve, reject) => { + let d = ''; let n = 0; + req.on('data', c => { n += c.length; if (n > 64 * 1024) { req.destroy(); reject(new Error('too big')); } d += c; }); + req.on('end', () => { try { resolve(d ? JSON.parse(d) : {}); } catch (e) { reject(e); } }); + req.on('error', reject); + }); +} +function parseCookies(req) { + const out = {}; + for (const p of (req.headers.cookie || '').split(';')) { + const i = p.indexOf('='); if (i > 0) out[p.slice(0, i).trim()] = decodeURIComponent(p.slice(i + 1).trim()); + } + return out; +} +function isAdmin(req) { + const h = req.headers.authorization || ''; + if (h === 'Bearer ' + ADMIN_PASSWORD) return true; + return !!adminFromRequest(req); // /admin portal session +} +// attach a memberId->username map to events so activity shows real people +async function attachNames(evts) { + try { + const ids = []; + for (const ev of evts) + for (const k of ['id', 'buyerId', 'recipientId', 'skippedId', 'sponsorId', 'newBuyerId', 'toId', 'memberId']) + if (ev[k]) ids.push(ev[k]); + const names = await accounts.namesForMembers(ids); + if (!Object.keys(names).length) return evts; + return evts.map(ev => Object.assign({}, ev, { names })); + } catch (e) { return evts; } +} +// A sponsor token is a numeric chain id or a site share code. Codes resolve +// to the referrer's CURRENT chain id, so activation any time before the +// referral's first purchase still locks the line to them. +// No-payout positions (siteConfig.noPayoutIds): a member id whose on-chain wallet must never be paid again. +// A purchase pays the buyer's three uplines, so a buy from `id` is blocked when id itself or any of its three +// uplines is listed; a join under `id` is blocked when id or its two uplines is listed (the new member's buys +// would reach the listed wallet at tier 2 or 3). Returns the listed id that would be hit, else 0. +function noPayoutSet() { return new Set(String(siteConfig().noPayoutIds || '').split(/[,\s]+/).map(Number).filter(n => n > 0)); } +async function payoutChainBlocked(id, hops) { + const bad = noPayoutSet(); if (!bad.size || !id) return 0; + let cur = Number(id); + for (let i = 0; i <= hops && cur; i++) { if (bad.has(cur)) return cur; let m = null; try { m = await chain.member(cur); } catch (e) { break; } cur = m ? Number(m.sponsorId) || 0 : 0; } + return 0; +} +// Why a sponsor token did not resolve matters (vladz79 → #24 locked under the company on 2026-09-13 because a +// lookup came back empty and the code fell back silently): 'ok' | 'none' (no token) | 'unknown' (no such account) +// | 'notActivated' (sponsor has no wallet / payouts off) | 'rpc' (chain lookup failed right now). +async function resolveSponsorDetailed(tok) { + const t = String(tok || '').trim().toLowerCase(); + if (!t) return { id: 0, reason: 'none' }; + if (/^\d+$/.test(t)) return { id: Number(t), reason: 'ok' }; + let acct = await accounts.byCode(t); + if (!acct) acct = await accounts.byUsername(t); // vanity links: /join/ + if (!acct) return { id: 0, reason: 'unknown', name: t }; + if (!acct.address) return { id: 0, reason: 'notActivated', name: acct.username ? '@' + acct.username : t }; + try { const id = await chain.memberIdByAccount(acct.address); return { id, reason: id ? 'ok' : 'notActivated', name: acct.username ? '@' + acct.username : t }; } + catch (e) { return { id: 0, reason: 'rpc', name: acct.username ? '@' + acct.username : t }; } +} +async function resolveSponsorToken(tok) { return (await resolveSponsorDetailed(tok)).id; } +const sponsorAlertLast = new Map(); // email -> ts (one alert per member per hour) +function sponsorBlockedAlert(who, r) { + const k = String(who || '?'); if (Date.now() - (sponsorAlertLast.get(k) || 0) < 3600000) return; sponsorAlertLast.set(k, Date.now()); + const text = '\u26A0\uFE0F LinkSpin: sale routed for ' + k.replace(/^(.{2}).*(@.*)$/, '$1***$2') + '. Their sponsor ' + (r.name || r.tok || '?') + ' could not be paid (' + r.reason + '), so the purchase went to ' + (r.routedTo || 'the company') + ' and the member moved with it. Purchases are never held.'; + const sc = siteConfig(); + if (sc.telegramBotToken && sc.telegramAdminChatId) telegramSend(sc.telegramAdminChatId, text).catch(() => {}); + else if (ADMIN_EMAIL && mailer.hasKey()) mailer.send(ADMIN_EMAIL, 'LinkSpin: sale routed, sponsor could not be paid', text).catch(() => {}); +} +// The moment someone joins through a code, nudge its owner to activate. +// Email a member's sponsor the moment they get a new referral (free OR paid). +// Resolves the sponsor from the join token by member id, share code, or username, +// and notifies EVERY sponsor — activated or not (an active sponsor still wants to +// know their team grew). A referral is on the line from signup; it only counts +// toward qualification once it makes a $20+ purchase. +async function notifyNewReferral(ref, newAcct) { + try { + if (!mailer.hasKey()) return; + const t = String(ref || '').trim().toLowerCase(); + if (!t) return; + let owner = null; + if (/^\d+$/.test(t)) { try { owner = await accounts.byMemberId(Number(t)); } catch (e) {} } + if (!owner) { try { owner = await accounts.byCode(t); } catch (e) {} } + if (!owner) { try { owner = await accounts.byUsername(t); } catch (e) {} } + if (!owner || !owner.email) return; + const who = newAcct && newAcct.username ? '@' + newAcct.username : 'A new member'; + let body = who + ' just joined LinkSpin through your link — they are on your team from today.\n\n' + + 'They count toward your qualification once they make a $20+ purchase.\n\n'; + if (!owner.address) body += 'Make sure payouts are switched on (one free wallet step) so you never miss a commission — ' + + 'the contract locks each buyer to their sponsor at their first purchase.\n\n'; + body += 'See your team: ' + SITE_URL + '/team\n\nLinkSpin'; + mailer.send(owner.email, 'You have a new referral on LinkSpin', body) + .catch(e => console.error('referral notify failed', e.message)); + } catch (e) {} +} +// welcome email on a new account: onboarding steps + who their sponsor is +// how a member is named in emails/alerts: @username, a linked position named after its owner, else member #id +async function memberLabel(id) { + try { + let a = await accounts.byMemberId(id); + if (!a) { // brand-new buyer: the account learns its member id on its next page load, so read the + // wallet from the chain and match it now (Jim's purchase mailed as "member #25", 2026-09-13) + try { const m = await chain.member(id); if (m && m.account) { a = await accounts.byAddress(String(m.account).toLowerCase()); if (a && !a.memberId) accounts.setMemberId(a.email, id).catch(() => {}); } } catch (e) {} + } + if (a && a.username) return '@' + a.username; + const pos = await accounts.positionByMember(id); + if (pos && pos.email) { const o = await accounts.byEmail(pos.email); if (o && o.username) return '@' + o.username + ' (extra position #' + id + ')'; } + } catch (e) {} + return 'member #' + id; +} +async function sendWelcome(email, ref) { + try { + if (!mailer.hasKey()) return; + const spon = await accounts.sponsorOf(email); + const who = spon ? (spon.username ? '@' + spon.username : 'member #' + (spon.memberId || 0)) : ''; + const sponsorLine = who ? ('You joined through ' + who + ', your sponsor. They are there to help you get started, and you can message them anytime from your dashboard.\n\n') : ''; + mailer.send(email, 'Welcome to LinkSpin', + 'Your free LinkSpin account is ready.\n\n' + sponsorLine + + 'Getting started:\n' + + '1. Pick your username and fill out your profile.\n' + + '2. Grab your invite link and start sharing to build your line.\n' + + '3. Explore the ad packages when you are ready. Every payout settles on-chain, straight to your wallet.\n\n' + + 'Sign in anytime: ' + SITE_URL + '/links\n\nLinkSpin').catch(() => {}); + } catch (e) {} +} +// on-chain event emails: a payout received, or a payout that passed you by +const weiToPol = w => { try { return (Number(BigInt(w) / (10n ** 14n)) / 10000).toString(); } catch (e) { return '?'; } }; +async function emailOnEvent(ev) { + if (!ev) return; + const notify = async (memberId, subject, body) => { + if (!memberId || !mailer.hasKey()) return; + const a = await accounts.byMemberId(memberId); + if (a && a.email) mailer.send(a.email, subject, body + '\n\nSee it on the live ledger: ' + SITE_URL + '/ledger\n\nLinkSpin').catch(() => {}); + }; + // Marty (2026-09-15): payment and missed-payment notices also land in the on-site inbox, so + // they are waiting (login modal + Messages card) whether or not the email was read. Sent as + // the company account (#1), the same sender the credit-return notes used. Plain text in, HTML out. + const inboxNote = async (memberId, subject, text) => { + if (!memberId) return; + try { + const a = await accounts.byMemberId(memberId); + if (!a || !a.email) return; + const html = '

' + String(text).replace(/&/g, '&').replace(//g, '>') + .replace(/(https:\/\/[^\s]+)/g, '$1').split('\n\n').join('

').replace(/\n/g, '
') + '

'; + await messages.deliver(1, ADMIN_EMAIL || 'house@' + SITE_HOST, [a.email], subject, html); + } catch (e) {} + }; + const tell = async (memberId, subject, text) => { await notify(memberId, subject, text); await inboxNote(memberId, subject, text); }; + const PCT = { 1: 50, 2: 20, 3: 10 }; + // the Purchase event of the same tx is already indexed (it precedes every payout log), so the + // dollar side of any share is that purchase's price times the tier percentage + const purchaseOf = tx => { try { return chain.recentEvents(600).find(e => e.tx === tx && e.type === 'Purchase'); } catch (e) { return null; } }; + const usdShare = (pur, pct) => pur ? (' (about ' + ('$' + (pur.priceCents * pct / 10000).toFixed(2)).replace(/\.00$/, '') + ')') : ''; + const txUrlOf = tx => { const cc = chain.getConfig(); return (cc.explorer ? cc.explorer.replace(/\/+$/, '') : 'https://polygonscan.com') + '/tx/' + tx; }; + if (ev.type === 'Purchase') { + const cc = chain.getConfig(); + const txUrl = (cc.explorer ? cc.explorer.replace(/\/+$/, '') : 'https://polygonscan.com') + '/tx/' + ev.tx; + let bal = ev.creditAmount; + try { bal = await chain.creditBalance(ev.buyerId, ev.creditType); } catch (e) {} + await notify(ev.buyerId, 'Your LinkSpin purchase is confirmed', + 'Your purchase is complete and settled on-chain.\n\n' + + 'Ad credits added: ' + ev.creditAmount + '\n' + + 'Your ad-credit balance is now: ' + bal + '\n' + + 'Amount paid: ' + weiToPol(ev.paidWei) + ' POL\n\n' + + 'View your transaction on the blockchain:\n' + txUrl); + // tell the buyer's DIRECT sponsor their referral just bought (upline earners + // are separately notified by the TierPaid payout email when they earn) + try { + const buyer = await chain.member(ev.buyerId); + if (buyer && buyer.sponsorId) { + const sp = await accounts.byMemberId(buyer.sponsorId); + if (sp && sp.email) { + const bn = await memberLabel(ev.buyerId); // @username at a glance (Marty, 2026-09-12) + const usd = ('$' + (ev.priceCents / 100).toFixed(2)).replace(/\.00$/, ''); + const qual = ev.priceCents >= 2000 + ? ' This is a $20+ purchase, so it counts toward your qualification.' + : ' (Purchases under $20 do not count toward qualification.)'; + mailer.send(sp.email, bn + ' just bought a ' + usd + ' ad package', + 'Your referral ' + bn + ' (member #' + ev.buyerId + ') just purchased a package (' + usd + ' — ' + ev.creditAmount + ' credits).' + qual + '\n\n' + + 'See your team and the live ledger: ' + SITE_URL + '/team\n\nLinkSpin').catch(() => {}); + } + } + } catch (e) {} + } + else if (ev.type === 'TierPaid') { + const pct = PCT[ev.tier] || 0; const pur = purchaseOf(ev.tx); + let buyer = 'a member on your level ' + ev.tier; try { buyer = await memberLabel(ev.buyerId); } catch (e) {} + const pol = weiToPol(ev.amountWei); + await tell(ev.recipientId, 'You just got paid ' + pol + ' POL on LinkSpin', + buyer + ' just bought an ad package on your level ' + ev.tier + (pur ? ' ($' + (pur.priceCents / 100).toFixed(2).replace(/\.00$/, '') + ')' : '') + '. Your ' + pct + ' percent share, ' + pol + ' POL' + usdShare(pur, pct) + ', landed in your wallet in the same transaction' + (ev.hops ? ', passed up to you because someone between you was not qualified for this level' : '') + '.\n\n' + + 'Transaction: ' + txUrlOf(ev.tx) + '\n\nYour wallet and payouts: ' + SITE_URL + '/wallet'); + } + else if (ev.type === 'AwardPaid') await tell(ev.toId, 'You just got paid ' + weiToPol(ev.amountWei) + ' POL on LinkSpin', weiToPol(ev.amountWei) + ' POL just landed in your wallet.\n\nTransaction: ' + txUrlOf(ev.tx) + '\n\nYour wallet and payouts: ' + SITE_URL + '/wallet'); + else if (ev.type === 'PassedUp' && ev.reason === 'send-failed') { + // the member WAS qualified but their wallet rejected the POL (usually a smart-contract + // wallet that needs more than the capped gas): tell them and the admin, loudly + await tell(ev.skippedId, 'Your wallet rejected a payout on LinkSpin', 'A level-' + ev.tier + ' payout tried to reach your linked wallet and the wallet refused the transfer, so it passed to the next qualified member. This happens with some smart-contract wallets. Link a regular wallet address (MetaMask, SafePal, Phantom) on the Wallet tab so the next payout lands.\n\nTransaction: ' + txUrlOf(ev.tx)); + if (ADMIN_EMAIL) mailer.send(ADMIN_EMAIL, 'LinkSpin: payout send-failed for member #' + ev.skippedId, 'A level-' + ev.tier + ' payout to member #' + ev.skippedId + ' failed at the wallet (send-failed) and passed up. Tx: ' + ev.tx + '\n\nThe member has been emailed to link a regular wallet.').catch(() => {}); + } + else if (ev.type === 'PassedUp') { + // Marty (2026-09-15): a member who missed a payout because they were not qualified must be told + // exactly what they missed: who bought, the share in POL and dollars, and how to close the gap. + const pct = PCT[ev.tier] || 0; const pur = purchaseOf(ev.tx); + let pol = '', buyer = 'a member on your level ' + ev.tier; + try { if (pur) pol = weiToPol((BigInt(pur.paidWei) * BigInt(pct) / 100n).toString()); buyer = await memberLabel(ev.buyerId); } catch (e) {} + let bc = 0; try { bc = (await chain.member(ev.skippedId)).buyerCount || 0; } catch (e) {} + const need = ev.tier === 3 ? 5 : 2, short = Math.max(0, need - bc); + const what = pol ? pol + ' POL' + usdShare(pur, pct) : 'a level-' + ev.tier + ' payout'; + await tell(ev.skippedId, 'You missed ' + (pol ? pol + ' POL' : 'a payout') + ' on LinkSpin', + buyer + ' just bought an ad package on your level ' + ev.tier + '. Your share was ' + what + ', and it passed you by because level ' + ev.tier + ' is not open on your account yet. The contract paid it to the next qualified person above you.\n\n' + + 'Level ' + ev.tier + ' opens at ' + need + ' qualifying buyers (people you referred who bought a $20 or larger package). You have ' + bc + (short ? ', so you are ' + short + ' buyer' + (short === 1 ? '' : 's') + ' away.' : '.') + '\n\n' + + 'Two ways to close the gap: bring ' + (short || 1) + ' more buyer' + (short === 1 ? '' : 's') + ' from your My line page, or use Qualified Start under Buy packages to be your own buyer today. Every package on level ' + ev.tier + ' pays you ' + pct + ' percent once it is open, and the next one is coming whether you are ready or not.\n\n' + + 'Transaction: ' + txUrlOf(ev.tx) + '\n\nYour wallet and payouts: ' + SITE_URL + '/wallet'); + } +} +// payment-proof Telegram feed (same pattern as the RM Circle proof channel): one compact +// line per event, admin-configured under Settings > Site (telegramBotToken, telegramChatId, +// optional telegramTopicId, telegramEvents = payouts | payouts+purchases | all, telegramCtaUrl) +// A second target, telegramEchoChatId + telegramEchoTopicId (+ telegramEchoEvents), echoes +// the same lines into a shared cross-program payments topic that RM Circle also posts to, +// so every line there carries the program name. +async function telegramOnEvent(ev) { + const sc = siteConfig(); + if (!sc.telegramBotToken || !ev) return; + if (!sc.telegramChatId && !sc.telegramEchoChatId) return; + const names = await accounts.namesForMembers([ev.recipientId, ev.buyerId, ev.sponsorId, ev.newBuyerId, ev.id].filter(Boolean)).catch(() => ({})); + const who = id => '#' + id + (names[id] ? ' @' + names[id] : ''); + const cc = chain.getConfig(); + const tx = (cc.explorer ? cc.explorer.replace(/\/+$/, '') : 'https://polygonscan.com') + '/tx/' + ev.tx; + const build = (mode) => { + let line = null; + if (ev.type === 'TierPaid') line = '\u{1F4B8} Level ' + ev.tier + ' payout: ' + weiToPol(ev.amountWei) + ' POL \u2192 ' + who(ev.recipientId); + else if (ev.type === 'BuyerCounted' && mode !== 'payouts') line = '\u2B50 ' + who(ev.sponsorId) + ' now has ' + ev.newCount + ' qualifying buyer' + (ev.newCount === 1 ? '' : 's') + (ev.newCount === 2 ? ' \u00b7 level 2 open' : ev.newCount === 5 ? ' \u00b7 level 3 open' : ''); + else if (ev.type === 'Purchase' && mode !== 'payouts') line = '\u{1F9FE} ' + who(ev.buyerId) + ' bought a $' + Math.round(ev.priceCents / 100) + ' package'; + else if (ev.type === 'AwardPaid') line = '\u{1F4B8} Award payout: ' + weiToPol(ev.amountWei) + ' POL \u2192 ' + who(ev.toId); + else if (ev.type === 'MemberActivated' && mode === 'all') line = '\u{1F91D} ' + who(ev.id) + ' switched on payouts'; + if (!line) return null; + return line + ' \u00b7 verify' + (sc.telegramCtaUrl ? '\nJoin free' : ''); + }; + if (sc.telegramChatId) { const t = build(String(sc.telegramEvents || 'payouts')); if (t) await telegramSend(sc.telegramChatId, t, sc.telegramTopicId); } + if (sc.telegramEchoChatId) { const t = build(String(sc.telegramEchoEvents || 'payouts')); if (t) await telegramSend(sc.telegramEchoChatId, '\u{1F7E0} LinkSpin \u00b7 ' + t, sc.telegramEchoTopicId); } +} +// holding-tank arrivals -> one digest line in the shared payments topic (Marty, 2026-09-12): who is +// waiting for a sponsor, by username, so builders go adopt them. Runs every 15 min, posts only +// when someone new landed since the last check. +async function tankNotifyTick() { + const sc = siteConfig(); + if (!sc.telegramBotToken || !sc.telegramEchoChatId) return; + const f = path.join(DATA_DIR, 'tank-notify.json'); + let st = { last: 0 }; try { st = JSON.parse(fs.readFileSync(f, 'utf8')); } catch (e) {} + const since = st.last || (Date.now() - 24 * 3600 * 1000); + const fresh = (await tank.waiting()).filter(w => (w.joined || 0) > since); + st.last = Date.now(); fs.writeFileSync(f, JSON.stringify(st)); + if (!fresh.length) return; + const named = fresh.filter(w => w.username).map(w => '@' + w.username); + const who = named.length ? ': ' + named.slice(0, 8).join(', ') + (named.length > 8 ? ' and ' + (named.length - 8) + ' more' : '') : ''; + const text = '\u{1FAA3} LinkSpin \u00b7 ' + fresh.length + ' new member' + (fresh.length === 1 ? '' : 's') + ' waiting for a sponsor in the holding tank' + who + + '\nAdopt from Team \u203a Waiting on a wallet: ' + SITE_HOST + '/team'; + await telegramSend(sc.telegramEchoChatId, text, sc.telegramEchoTopicId); +} +// one sendMessage call; never throws, never logs the token +async function telegramSend(chatId, text, threadId) { + const sc = siteConfig(); + if (!sc.telegramBotToken || !chatId) return; + const body = JSON.stringify(Object.assign({ chat_id: chatId, text, parse_mode: 'HTML', disable_web_page_preview: true }, threadId ? { message_thread_id: Number(threadId) } : {})); + await new Promise((resolve) => { + const rq = https.request({ hostname: 'api.telegram.org', path: '/bot' + sc.telegramBotToken + '/sendMessage', method: 'POST', headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(body) }, timeout: 10000 }, r => { r.resume(); r.on('end', resolve); }); + rq.on('error', () => resolve()); rq.on('timeout', () => { rq.destroy(); resolve(); }); rq.end(body); + }); +} + +// photo post (multipart) for the achievement badges (Marty, 2026-09-13); same bot, sendPhoto only +async function telegramSendPhoto(chatId, jpeg, caption, threadId) { + const sc = siteConfig(); + if (!sc.telegramBotToken || !chatId || !jpeg) return false; + const B = '----iapbadge' + crypto.randomBytes(8).toString('hex'); + const field = (n, v) => Buffer.from('--' + B + '\r\nContent-Disposition: form-data; name="' + n + '"\r\n\r\n' + v + '\r\n'); + const parts = [field('chat_id', String(chatId)), field('caption', caption), field('parse_mode', 'HTML')]; + if (threadId) parts.push(field('message_thread_id', String(Number(threadId)))); + parts.push(Buffer.from('--' + B + '\r\nContent-Disposition: form-data; name="photo"; filename="badge.jpg"\r\nContent-Type: image/jpeg\r\n\r\n'), jpeg, Buffer.from('\r\n--' + B + '--\r\n')); + const body = Buffer.concat(parts); + return new Promise((resolve) => { + const rq = https.request({ hostname: 'api.telegram.org', path: '/bot' + sc.telegramBotToken + '/sendPhoto', method: 'POST', headers: { 'Content-Type': 'multipart/form-data; boundary=' + B, 'Content-Length': body.length }, timeout: 20000 }, res => { + let out = ''; res.on('data', c => out += c); res.on('end', () => resolve(res.statusCode === 200)); + }); + rq.on('error', () => resolve(false)); rq.on('timeout', () => { rq.destroy(); resolve(false); }); rq.end(body); + }); +} +const BADGE_META = { payouts: ['Spark', 'payouts switched on'], firstBuyer: ['Surge', 'first qualifying buyer'], level2: ['Circuit', 'two qualifying buyers, level 2 open'], level3: ['Nexus', 'five qualifying buyers, fully qualified'] }; +const BADGE_LOG = () => path.join(DATA_DIR, 'badge-posts.json'); +function badgeLog() { try { return JSON.parse(fs.readFileSync(BADGE_LOG(), 'utf8')); } catch (e) { return {}; } } + +// ---- live feed (SSE) ---- +const feedClients = new Set(); +function pushFeed(ev) { + const line = 'data: ' + JSON.stringify(ev) + '\n\n'; + for (const res of feedClients) { try { res.write(line); } catch (e) { feedClients.delete(res); } } +} + +// ---- short link domains (LinkSpin): each domain in siteConfig().linkDomains is a small real site ---- +function reqHost(req) { return String(req.headers['x-forwarded-host'] || req.headers.host || '').split(',')[0].trim().toLowerCase().replace(/:\d+$/, '').replace(/^www\./, ''); } +function pagesHost() { return String(siteConfig().pagesDomain || '').trim().toLowerCase().replace(/^www\./, '') || null; } +function isPagesHost(req) { const h = pagesHost(); return !!h && reqHost(req) === h; } +function isLinkHost(req) { const h = reqHost(req); if (!h) return false; return String(siteConfig().linkDomains || '').split(',').map(x => x.trim().toLowerCase()).filter(Boolean).includes(h); } +function linkSitePage(host, page) { + const esc = t => String(t).replace(/&/g, '&').replace(/' + H + '

This domain is a link forwarding service operated by ' + brand + ', a member advertising network. Links on this domain forward visitors in one step to pages published by our members and their partners.

We do not host the pages you land on, and we do not collect payment information here. If a link forwarded you somewhere you did not expect, or to content that looks unsafe, tell us on the report page and we will pull the link.

What we record

When a link is followed we record the day, the country, the referring site, the device type and a one-day anonymous visitor token. We do not store your IP address or any personal data. Details are in the privacy policy.

', + disclosure: '

Affiliate and advertising disclosure

Links forwarded through ' + H + ' may be affiliate links or paid advertisements. The member who published a link may earn a commission or advertising credit if you buy something or sign up on the page you land on. This never changes the price you pay.

' + brand + ' itself is an advertising platform. Members buy ad packages and earn commissions when people they referred buy ad packages. No income is guaranteed to anyone; results depend on effort, and any earnings examples on member pages are illustrations, not promises.

The pages you are forwarded to belong to their publishers. We are not responsible for their claims, and we remove links that are reported and found to violate our terms.

', + terms: '

Terms of use

By following a link on ' + H + ' you agree to these terms.

The service

' + H + ' forwards visitors to destinations chosen by ' + brand + ' members. We provide the forwarding only. We do not endorse, verify or control the destination pages, and we are not a party to any transaction you make there.

Acceptable use

Members may not forward visitors to content that is illegal, deceptive, malicious, adult, or that impersonates another business. Links that violate this are removed and the member\'s account is closed. Automated access to this domain is not permitted except by search engines.

No warranty

The service is provided as is. We do not guarantee that any link will be available, and we are not liable for the content, availability or conduct of destination sites.

Contact

Questions about these terms: linkspin.co.

', + privacy: '

Privacy policy

This policy covers ' + H + ' and the link forwarding service on it.

What we collect

When you follow a link we record the date, your country (derived from your network address and then discarded), the site that referred you, whether you are on a phone or a computer, and an anonymous visitor token that changes every day and cannot be traced back to you. We do not store your IP address, your name, your email address or any account information on this domain.

Cookies

This domain sets no cookies. The page you are forwarded to has its own privacy policy and may set its own.

Why we collect it

So members can see how many people followed their links and from where. Counts are shown to the member who published the link, in aggregate, and to nobody else.

Retention

Link statistics are kept for up to thirteen months and then deleted.

Your rights

Because we hold no personal data on this domain there is nothing to access or delete here. For anything involving a ' + brand + ' member account, contact us through linkspin.co.

', + abuse: '

Report a link

If a link on ' + H + ' forwarded you to a page that is deceptive, unsafe, adult, or impersonates a business, tell us. We review every report and pull the link first, then ask questions.

Send the full link you clicked (it starts with https://' + H + '/r/) and what you saw, to the support contact on linkspin.co. Reports are usually handled the same day.

', + gone: '

That link is not active

The link you followed has been removed or has expired. Nothing was recorded. If you were expecting a specific page, ask the person who shared the link for a fresh one.

' + }; + return '' + H + '
' + nav + (bodies[page] || bodies.gone) + '
'; +} + +// ---- server ---- +// ---- the curtain ---------------------------------------------------------- +// Work in progress is not for passers-by. CURTAIN= puts a contentless holding page +// in front of every request; ?k= sets a cookie that lifts it for that browser. +const CURTAIN = String(process.env.CURTAIN || '').trim(); +const CURTAIN_PAGE = ` + +Coming soon

Coming soon

This site is still being built.

`; + +function curtained(req, res, u) { + if (!CURTAIN) return false; + if (isLinkHost(req) || isPagesHost(req)) return false; // the short link domains and the pages domain stay public: spin links must redirect and the mini-site must answer while the main site is covered (Marty 2026-10-07: test traffic before launch) + if (u.searchParams.get('k') === CURTAIN) { + u.searchParams.delete('k'); + res.writeHead(302, { + 'Set-Cookie': 'ls.pass=' + encodeURIComponent(CURTAIN) + '; Path=/; Max-Age=2592000; HttpOnly; SameSite=Lax; Secure', + Location: u.pathname + (u.searchParams.toString() ? '?' + u.searchParams : ''), + 'Cache-Control': 'no-store' + }); + res.end(); + return true; + } + const pass = /(?:^|;\s*)ls\.pass=([^;]*)/.exec(req.headers.cookie || ''); + if (pass && decodeURIComponent(pass[1]) === CURTAIN) return false; + res.writeHead(503, { + 'Content-Type': 'text/html; charset=utf-8', + 'Cache-Control': 'no-store', + 'X-Robots-Tag': 'noindex, nofollow' + }); + res.end(req.method === 'HEAD' ? '' : CURTAIN_PAGE); + return true; +} + +const server = http.createServer(async (req, res) => { + { const t0 = Date.now(); res.on('finish', () => { const ms = Date.now() - t0; if (ms > 3000) console.warn('slow request', req.method, String(req.url || '').split('?')[0].slice(0, 80), ms + 'ms', res.statusCode); }); } // visibility for member-felt delays (2026-10-12) + try { + const u = new URL(req.url, 'http://x'); + const p = u.pathname; + // zone endpoints run on other people's sites and show only ad creatives, so they pass the curtain + const zonePath = p === '/z.js' || p === '/z/nas' || p === '/p.js' || p === '/p.gif' || p.startsWith('/u/pages/') || p.startsWith('/api/zone/') || p.startsWith('/banners/linkspin-') || p.startsWith('/art/house-'); + if (!zonePath && curtained(req, res, u)) return; // nothing below this line runs for an uninvited visitor + + // -- the rotator redirect: one hop, recorded, on any host (LinkSpin) + let rm = /^\/r\/([a-z0-9]{4,12})$/i.exec(p); + if (rm && (req.method === 'GET' || req.method === 'HEAD')) { + const hit = await rotator.resolve(rm[1], req); + if (hit && hit.url) { res.writeHead(302, { Location: hit.url, 'Cache-Control': 'no-store', 'Referrer-Policy': 'no-referrer-when-downgrade' }); return res.end(); } + res.writeHead(404, { 'Content-Type': 'text/html; charset=utf-8' }); return res.end(linkSitePage(reqHost(req), 'gone')); + } + // -- ad zones on members' sites: the tag, the ad, the viewable beacon, the click. Any origin may call these. + if (p === '/z.js') { const zf = path.join(PUBLIC_DIR, 'z.js'); try { const body = fs.readFileSync(zf); res.writeHead(200, { 'Content-Type': 'application/javascript; charset=utf-8', 'Cache-Control': 'public, max-age=300', 'Access-Control-Allow-Origin': '*' }); return res.end(body); } catch (e) {} } + if (p === '/api/zone/serve' && req.method === 'GET') { + const am = audiences.matcher(req); // ls.vid cookie (when the browser sends it cross-site) + soft key + const ad = await zones.serve(u.searchParams.get('z'), req, Object.assign(viewerGeo(req), am)); + const h = Object.assign({ 'Content-Type': 'application/json', 'Cache-Control': 'no-store' }, corsCreds(req)); + if (!am.vid) h['Set-Cookie'] = audiences.cookieHeader(audiences.newVid(), IS_PROD); + res.writeHead(200, h); return res.end(JSON.stringify({ ad })); + } + // audience pixel: 1x1 gif, sets/refreshes the visitor cookie, records the hit (30-day membership) + if (p === '/p.gif' && req.method === 'GET') { + const a = String(u.searchParams.get('a') || ''); let vid = audiences.cookieVid(req); const h = { 'Content-Type': 'image/gif', 'Cache-Control': 'no-store, private', 'Content-Length': String(PIXEL_GIF.length) }; + if (!vid) { vid = audiences.newVid(); h['Set-Cookie'] = audiences.cookieHeader(vid, IS_PROD); } + if (audiences.isId(a)) audiences.hit(a, vid, audiences.softKey(req)); + res.writeHead(200, h); return res.end(PIXEL_GIF); + } + if (p === '/p.js') { try { const body = fs.readFileSync(path.join(PUBLIC_DIR, 'p.js')); res.writeHead(200, { 'Content-Type': 'application/javascript; charset=utf-8', 'Cache-Control': 'public, max-age=300' }); return res.end(body); } catch (e) { res.writeHead(404); return res.end(); } } + if (p === '/z/nas' && req.method === 'GET') { // the frame a Network Ad Space fallback renders in + const html = zones.nasFrame(String(u.searchParams.get('s') || '')); + if (!html) { res.writeHead(404); return res.end(); } + res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store', 'Content-Security-Policy': "default-src 'none'; script-src https://www.networkadspace.com https://networkadspace.com 'unsafe-inline'; img-src https: http: data:; style-src 'unsafe-inline'; frame-src https: http:; frame-ancestors *; base-uri 'none'", 'Referrer-Policy': 'no-referrer' }); return res.end(html); + } + if (p === '/api/zone/seen' && (req.method === 'GET' || req.method === 'POST')) { await zones.seen(u.searchParams.get('i'), req); res.writeHead(204, corsCreds(req)); return res.end(); } + { const zm = /^\/api\/zone\/click\/([a-f0-9]{12})$/.exec(p); if (zm && req.method === 'GET') { const target = await zones.click(zm[1]); res.writeHead(302, { Location: target || '/', 'Cache-Control': 'no-store', 'Referrer-Policy': 'no-referrer-when-downgrade' }); return res.end(); } } + // -- publisher program (2026-10-10): the public offer for site owners who carry zones, and its live "Network right now" + // strip (7-day totals from zones.js, cached a minute). App host only; the link and pages domains stay single-purpose. + if (p === '/api/public/publishers' && req.method === 'GET') return json(res, 200, zones.publisherPublic(), { 'Cache-Control': 'public, max-age=60' }); + if (p === '/publishers' && (req.method === 'GET' || req.method === 'HEAD') && !isPagesHost(req) && !isLinkHost(req)) return sendFile(res, path.join(PUBLIC_DIR, 'publishers.html')); + { const wm = /^\/welcome\/([a-f0-9]{48})$/.exec(p); if (wm && (req.method === 'GET' || req.method === 'POST')) { // one-time tester sign-in link + const t = inviteTokens.get(wm[1]); + if (!t || t.exp < Date.now()) { inviteTokens.delete(wm[1]); res.writeHead(410, { 'Content-Type': 'text/html; charset=utf-8' }); return res.end('Link used

That sign-in link was already used or has expired. Ask for a fresh one.

'); } + // GET only shows a button: link-preview fetchers and in-app browsers prefetch links, and a prefetch must not spend the token + if (req.method === 'GET') { + res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store', 'X-Robots-Tag': 'noindex' }); + return res.end('Sign in to LinkSpin
LINKSPIN TEST APP

Sign in as

' + String(t.email).replace(/&/g, '&').replace(/

One use. Good for 24 hours from when it was made.

'); + } + inviteTokens.delete(wm[1]); + const acct = await accounts.byEmail(t.email); let memberId = 0; if (acct && acct.address) { try { memberId = await chain.memberIdByAccount(acct.address); } catch (e) {} } + const token = await auth.mintSession({ email: t.email, address: (acct && acct.address) || null, memberId }); + res.writeHead(302, { 'Set-Cookie': auth.sessionCookie(token), Location: t.next || '/ads', 'Cache-Control': 'no-store' }); return res.end(); + } } + // -- member pages: /p/ on the app host and on every link domain; the lead form and the hit beacon live beside it + // -- the pages domain: only pages live here. / -> the app; / and /p/ -> the page; everything else 404 + if (isPagesHost(req)) { + if (p === '/') { res.writeHead(302, { Location: 'https://' + SITE_HOST + '/', 'Cache-Control': 'no-store' }); return res.end(); } + if (p === '/robots.txt') { res.writeHead(200, { 'Content-Type': 'text/plain' }); return res.end('User-agent: *\nAllow: /\n'); } + if (p === '/assets/pt.js') return sendFile(res, path.join(PUBLIC_DIR, 'assets', 'pt.js')); + if (!/^\/p\/[a-z0-9-]{3,60}(\/lead)?$/i.test(p) && !/^\/api\/p\//.test(p) && !/^\/[a-z0-9-]{3,60}$/i.test(p)) { res.writeHead(404, { 'Content-Type': 'text/plain' }); return res.end('Not found'); } + } + let pm = /^\/p\/([a-z0-9-]{3,60})$/i.exec(p) || (isPagesHost(req) ? /^\/([a-z0-9-]{3,60})$/i.exec(p) : null); + if (pm && (req.method === 'GET' || req.method === 'HEAD')) { + const pg = pages.bySlug(pm[1]); + const preview = u.searchParams.get('preview') === '1'; + if (!pg || (pg.status !== 'published' && !preview)) { res.writeHead(404, { 'Content-Type': 'text/html; charset=utf-8' }); return res.end(isLinkHost(req) ? linkSitePage(reqHost(req), 'gone') : 'Not found

That page is not live.

'); } + if (preview) { const sess = await auth.fromRequest(req); if (!sess || !sess.email || String(sess.email).toLowerCase() !== pg.owner) { res.writeHead(404, { 'Content-Type': 'text/plain' }); return res.end('Not found'); } } + else pages.view(pg, req, 'view'); + const lsid = String(u.searchParams.get('lsid') || ''); + const hdr = { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff', 'Referrer-Policy': 'strict-origin-when-cross-origin', + 'Content-Security-Policy': "default-src 'none'; script-src 'self'; style-src 'unsafe-inline'; img-src 'self' https: data:; form-action https: http:; base-uri 'none'; frame-ancestors *; connect-src 'self'" }; + if (/^[a-z0-9]{6,20}$/i.test(lsid)) hdr['Set-Cookie'] = 'ls.click=' + lsid + '; Path=/; SameSite=Lax; Max-Age=2592000' + (IS_PROD ? '; Secure' : ''); + res.writeHead(200, hdr); return res.end(pages.html(pg, { leadUrl: '/p/' + pg.slug + '/lead', trackSrc: '/assets/pt.js', footerLink: 'https://' + SITE_HOST + '/', footerText: 'Made with LinkSpin', pixel: 'https://' + SITE_HOST + '/p.gif?a=' + audiences.defaultFor(pg.owner) + '&e=page' })); + } + pm = /^\/p\/([a-z0-9-]{3,60})\/lead$/i.exec(p); + if (pm && req.method === 'POST') { + const raw = await new Promise(r => { let d = ''; req.on('data', c => { d += c; if (d.length > 20000) req.destroy(); }); req.on('end', () => r(d)); }); + const b = {}; try { const ct = String(req.headers['content-type'] || ''); if (/json/.test(ct)) Object.assign(b, JSON.parse(raw)); else for (const [k, v] of new URLSearchParams(raw)) b[k] = v; } catch (e) {} + const r = await pages.lead(pm[1], b, req); + if (r.error) { res.writeHead(400, { 'Content-Type': 'text/html; charset=utf-8' }); return res.end('Try again

' + r.error + ' Go back

'); } + if (r.owner && r.lsid) { try { postbacks.bindClick(String(b.email || '').toLowerCase(), r.lsid); const hit = await rotator.convert(r.lsid, 'lead', {}); if (hit) postbacks.fire(hit.owner, 'lead', Object.assign({ q: hit.q || {}, source: hit.s, country: hit.c, device: hit.dv, lsid: r.lsid, code: hit.code, sourceId: hit.sourceId || '' })).catch(() => {}); } catch (e) {} } + res.writeHead(302, { Location: r.next || '/', 'Cache-Control': 'no-store' }); return res.end(); + } + if (p.startsWith('/api/p/') && req.method === 'POST' && /\/hit$/.test(p)) { const sl = p.split('/')[3]; const pg = pages.bySlug(sl); if (pg) pages.view(pg, req, 'cta'); res.writeHead(204); return res.end(); } + if (p === '/assets/pt.js' && isLinkHost(req)) return sendFile(res, path.join(PUBLIC_DIR, 'assets', 'pt.js')); + // -- short link domains: a real small site (home, disclosure, terms, privacy, abuse) so the domain never looks parked + if (isLinkHost(req)) { + const page = { '/': 'home', '/disclosure': 'disclosure', '/terms': 'terms', '/privacy': 'privacy', '/abuse': 'abuse', '/robots.txt': 'robots' }[p]; + if (!page) { res.writeHead(404, { 'Content-Type': 'text/html; charset=utf-8' }); return res.end(linkSitePage(reqHost(req), 'gone')); } + if (page === 'robots') { res.writeHead(200, { 'Content-Type': 'text/plain' }); return res.end('User-agent: *\nDisallow: /r/\n'); } + res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'public, max-age=300' }); return res.end(linkSitePage(reqHost(req), page)); + } + + // -- traffic log: public page views by referring domain (admin > Traffic) + if (req.method === 'GET' && (TRAFFIC_PAGES.has(p) || /^\/(join|from|wall|blog)\/[^/]+$/.test(p))) traffic.hit(p.startsWith('/blog/') ? '/blog/*' : p, req.headers.referer, req.headers['user-agent']); + // -- join links: /join/ — LAST-touch cookie (Marty, + // 2026-09-10): the link a visitor opened most recently is the sponsor shown + // and used, and it locks the moment the account is created (accounts.ensure + // never changes an existing account's sponsor; the contract binds the buyer at + // their first purchase). Codes resolve LATE (at buy time) to whatever chain id + // the referrer has by then, so free members refer from day one. + let m = /^\/join\/([A-Za-z0-9_]{1,20})$/.exec(p); + if (m && (req.method === 'GET' || req.method === 'HEAD')) { + // lead-capture page: email first, wallet later. ?v= picks the hook + // copy and is remembered so the account records which angle converted. + // partner placement: /join/company (or /top) places the visitor directly under + // member #1, the company position, with no sponsor in between (Marty, 2026-09-12 partner kit) + const tok = JOIN_ALIASES[m[1].toLowerCase()] || m[1].toLowerCase(); + const cookies = parseCookies(req); + const angle = String(u.searchParams.get('v') || '').toLowerCase(); + const ang = JOIN_ANGLES[angle] || null; + if (req.method === 'GET') coach.recordView(tok, ang ? angle : '', req.headers.referer); // link stats per angle + source + const cookieTail = `; Path=/; SameSite=Lax; Max-Age=${30 * 24 * 3600}${IS_PROD ? '; Secure' : ''}`; // 30 days: whoever brings them back gets the credit + const set = []; + set.push('iap.sponsor=' + tok + cookieTail); // last touch wins + { const lsid = String(u.searchParams.get('lsid') || ''); if (/^[a-z0-9]{6,20}$/i.test(lsid)) set.push('ls.click=' + lsid + cookieTail); } // the rotator click that brought them (postback attribution) + const promo = promos.norm(u.searchParams.get('promo')); if (promo) set.push('iap.promo=' + promo + cookieTail); // partner code, redeemed at signup + if (ang) set.push('iap.angle=' + angle + cookieTail); + if (!cookies['iap.ref']) set.push('iap.ref=' + encodeURIComponent(coach.refHost(req.headers.referer)) + cookieTail); // first-touch source + return serveJoinPage(res, tok, ang ? angle : '', ang, set); + } + // -- legacy bridge: /from/faucetwave | /from/tieroneads [?seg=advertiser]. Same squeeze page + // with brand copy, NO sponsor (the sponsor cookie is cleared so they land in the holding + // tank for adoption), the angle remembered so the welcome-back grant fires at signup, and + // a forced first-touch source so link stats / admin can see the legacy arrivals. + m = /^\/from\/(faucetwave|tieroneads)$/.exec(p); + if (m && (req.method === 'GET' || req.method === 'HEAD')) { + const brand = m[1]; + const key = (brand === 'faucetwave' ? 'fw' : 't1') + (String(u.searchParams.get('seg') || '').toLowerCase().startsWith('adv') ? '-adv' : '-earn'); + const cookieTail = `; Path=/; SameSite=Lax; Max-Age=${30 * 24 * 3600}${IS_PROD ? '; Secure' : ''}`; + const src = String(u.searchParams.get('src') || '').toLowerCase().replace(/[^a-z0-9.\-]/g, '').slice(0, 40); // e.g. the old domain's splash page + const set = ['iap.sponsor=; Path=/; SameSite=Lax; Max-Age=0' + (IS_PROD ? '; Secure' : ''), 'iap.angle=' + key + cookieTail, 'iap.ref=' + encodeURIComponent('legacy:' + brand + (src ? ':' + src : '')) + cookieTail]; + return serveJoinPage(res, '', key, JOIN_ANGLES[key], set); + } + if (p === '/unsubscribe' && req.method === 'GET') { + const r = await drip.unsubscribe(u.searchParams.get('e'), u.searchParams.get('t')); + const msg = r.error ? r.error : 'Done. You will not get any more follow-up emails from LinkSpin. Your account is unchanged.'; + res.writeHead(r.error ? 400 : 200, baseHeaders({ 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store' })); + return res.end('LinkSpin
LinkSpin

' + (r.error ? 'Hmm.' : 'Unsubscribed.') + '

' + msg + '

Member area

'); + } + + // -- public API + if (p === '/api/config' && req.method === 'GET') { + const c = chain.getConfig(); + // public copy of the site settings: never anything that looks like a credential + const pubSite = {}; + for (const [k, v] of Object.entries(siteConfig())) if (!/secret|token|password|private|apikey|api_key/i.test(k)) pubSite[k] = v; + return json(res, 200, Object.assign({ contract: c.contract, chainId: c.chainId, + chainName: c.chainName, explorer: c.explorer, rpc: c.rpcs[0], + emailAuth: (mailer.hasKey() || !IS_PROD) && SIGNUPS_OPEN, + signupsOpen: SIGNUPS_OPEN }, pubSite)); + } + if (p === '/api/moonpay-url' && req.method === 'GET') { + // Card on-ramp deep link. With MoonPay keys set — PUBLIC key via + // MOONPAY_PUBLIC_KEY env or site config, SECRET key via MOONPAY_SECRET_KEY + // env ONLY (never site config, since /api/config exposes siteConfig) — + // returns a SIGNED checkout URL prefilled with the buyer's own wallet and + // a POL amount; otherwise a generic MoonPay buy page. Zero custody either + // way: MoonPay is merchant of record and the crypto goes straight to the + // buyer's wallet — this site never touches or holds anyone's money. + const addr = (u.searchParams.get('address') || '').trim(); + let pol = Math.round(Number(u.searchParams.get('pol')) || 0); + if (!pol || pol < 30) pol = 30; + if (pol > 100000) pol = 100000; + const pk = (process.env.MOONPAY_PUBLIC_KEY || siteConfig().moonpayPublicKey || '').trim(); + const sk = (process.env.MOONPAY_SECRET_KEY || '').trim(); + if (pk && sk && /^0x[0-9a-fA-F]{40}$/.test(addr)) { + const qs = '?apiKey=' + encodeURIComponent(pk) + '¤cyCode=pol_polygon&walletAddress=' + encodeURIComponent(addr) + '"eCurrencyAmount=' + pol; + const sig = crypto.createHmac('sha256', sk).update(qs).digest('base64'); + return json(res, 200, { url: 'https://buy.moonpay.com/' + qs + '&signature=' + encodeURIComponent(sig), signed: true, pol }); + } + return json(res, 200, { url: 'https://www.moonpay.com/buy/matic', signed: false, pol }); // MoonPay's Polygon page still lives at the old slug; /buy/pol renders their 404 (same fix as RM Circle) + } + if (p === '/api/catalog' && req.method === 'GET') { + // five live quotes per call: serve a 20-second cache so pages that load the + // ladder (join, home, buy) are not waiting on the RPC every time + if (!catalogCache.at || Date.now() - catalogCache.at > 20000) { + try { catalogCache.products = await chain.catalog(); catalogCache.at = Date.now(); } + catch (e) { if (!catalogCache.products) throw e; } + } + return json(res, 200, { products: catalogCache.products }); + } + if (p === '/api/feed' && req.method === 'GET') { + return json(res, 200, { events: await attachNames(chain.recentEvents(Number(u.searchParams.get('n')) || 100)) }); + } + if (p === '/api/feed/live' && req.method === 'GET') { + res.writeHead(200, baseHeaders({ 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-store', Connection: 'keep-alive' })); + res.write(': connected\n\n'); + feedClients.add(res); + req.on('close', () => feedClients.delete(res)); + return; + } + m = /^\/api\/tx\/(0x[0-9a-fA-F]{64})$/.exec(p); + if (m && req.method === 'GET') { + // tx relay so the browser never talks to the RPC directly (CSP stays 'self'). + // Serves both the wallet's waitTx poll (found/status) and the built-in + // /tx/ viewer (full details + decoded events). + try { + const r = await chain.rpc('eth_getTransactionReceipt', [m[1]]); + if (!r) return json(res, 200, { found: false }); + const out = { found: true, status: r.status, blockNumber: r.blockNumber, gasUsed: r.gasUsed }; + try { + const t = await chain.rpc('eth_getTransactionByHash', [m[1]]); + if (t) { out.from = t.from; out.to = t.to; out.valueWei = BigInt(t.value || '0x0').toString(); } + } catch (e) {} + try { + const blk = await chain.rpc('eth_getBlockByNumber', [r.blockNumber, false]); + if (blk) out.ts = blk.timestamp; + } catch (e) {} + try { + out.events = await attachNames((r.logs || []).map(chain.decodeLog).filter(Boolean) + .map(ev => Object.assign(ev, { tx: m[1] }))); + } catch (e) { out.events = []; } + return json(res, 200, out); + } catch (e) { return json(res, 200, { found: false, rpcError: true }); } + } + if (p === '/api/sponsor' && req.method === 'GET') { + // The account's stored sponsor is authoritative — it persists across + // devices, cleared cookies, and return visits. Fall back to the first-touch + // cookie only for anonymous visitors with no account sponsor yet. (Reading + // the cookie alone was orphaning buyers to root when the cookie was absent.) + const s = await auth.fromRequest(req); + const acct = s && s.email ? await accounts.byEmail(s.email) : null; + const tok = (acct && acct.sponsorRef) || parseCookies(req)['iap.sponsor'] || ''; + const spd = await resolveSponsorDetailed(tok); let sponsorId = spd.id; + // LinkSpin carry-over: a sponsor with a wallet is activated on this contract by the engine before the + // member's first transaction. A purchase is NEVER held (Marty, 2026-10-15): no wallet / unknown sponsor + // walks up to the nearest ancestor with a wallet, else the company. intent=buy commits the move + notices. + const intentBuy = u.searchParams.get('intent') === 'buy'; + let sponsorRouted = null; + if (acct && !sponsorId) { + try { + const cr = await carry.resolveForChain(acct, spd, { commit: intentBuy }); + if (cr && cr.sponsorId) { sponsorId = cr.sponsorId; spd.reason = 'ok'; } + if (cr && cr.routed) { sponsorRouted = cr.routed; spd.reason = 'ok'; } + } catch (e) {} + } + let sponsorBlocked = null; // only a momentary chain lookup failure: the client says "try again in a minute", nothing is charged + if (acct && acct.sponsorRef && !sponsorId && spd.reason === 'rpc') sponsorBlocked = 'rpc'; + if (sponsorRouted && intentBuy) sponsorBlockedAlert(acct.email, Object.assign({ tok, routedTo: sponsorRouted.to }, spd)); + if (sponsorId && await payoutChainBlocked(sponsorId, 2)) { console.log('sponsor routed away from no-payout chain', sponsorId); sponsorId = 0; } + // orphan fallback: an unresolvable/absent sponsor (dead link, no link) lands + // the new member under the configured catch position (#1) instead of root + if (!sponsorId && (!acct || acct.memberId !== (Number(siteConfig().defaultSponsorId) || 1))) sponsorId = Number(siteConfig().defaultSponsorId) || 1; + // a brand-new contract has no catch position yet: the first member joins with sponsor 0 and BECOMES #1 (Marty's reverted + // activate(1) on 2026-10-08: 'Unknown sponsor' because memberCount was 0) + if (sponsorId) { try { if (sponsorId > await chain.memberCount()) { console.log('sponsor', sponsorId, 'not on chain yet, using 0'); sponsorId = 0; } } catch (e) {} } + let name = null, avatarUrl = null, own = false; + // the join page names the owner of the LINK it was opened with (?ref=token), not the visitor's own + // sponsor: a member previewing their own invite page was seeing their upline's name (Jim, 2026-09-13) + let showTok = String(u.searchParams.get('ref') || '').trim().toLowerCase(); + if (showTok && JOIN_ALIASES[showTok]) showTok = JOIN_ALIASES[showTok]; + const nameTok = showTok || tok; + if (nameTok) { + const t = nameTok.toLowerCase(); + let a = await accounts.byCode(t); if (!a) a = await accounts.byUsername(t); + if (!a && /^\d+$/.test(nameTok)) a = await accounts.byMemberId(Number(nameTok)); + if (a) { name = a.username ? '@' + a.username : (a.memberId ? 'member #' + a.memberId : null); avatarUrl = a.avatarUrl || null; own = !!(acct && a.email === acct.email); var bio = null, cobrand = false; try { cobrand = (await ads.milestonesOf(a.email)).includes('level3'); if (cobrand) bio = a.bio ? String(a.bio).slice(0, 220) : null; } catch (e) {} } + } + return json(res, 200, { ref: tok, sponsorId, sponsorBlocked, sponsorRouted, sponsorName: spd.name || null, invited: !!(tok || showTok), name, avatarUrl, own, bio: typeof bio === 'undefined' ? null : bio, cobrand: typeof cobrand === 'undefined' ? false : cobrand }); + } + if (p === '/api/stats' && req.method === 'GET') { + let members = 0; try { members = await chain.memberCount(); } catch (e) {} + return json(res, 200, Object.assign({ onchainMembers: members, siteAccounts: await accounts.count(), servedToday: rotator.servedToday(), rotations: rotator.totals().rotations }, chain.totals())); + } + // -- home-page demo: a working spin link with no account (2026-10-07). One per browser (ls.demo cookie), + // five per IP per hour, 24 h unless the visitor signs in (the email door then claims it). + if (p === '/api/demo/spin' && req.method === 'POST') { + const ip = clientIp(req); const now = Date.now(); + const dl = demoLimits.get(ip) || []; const recent = dl.filter(t => now - t < 3600000); + if (recent.length >= 5) return json(res, 429, { error: 'That is plenty of demo links for one hour. Sign in to make more.' }); + const b = await readBody(req); + const urls = Array.isArray(b.urls) ? b.urls.map(x => String(x || '').trim()).filter(Boolean) : []; + let token = String(parseCookies(req)['ls.demo'] || '').replace(/[^a-f0-9]/g, '').slice(0, 32); + if (token.length < 16) token = crypto.randomBytes(12).toString('hex'); + const r = await rotator.createDemo(token, urls); + if (r.error) return json(res, 400, r); + recent.push(now); demoLimits.set(ip, recent); + const hosts = String(siteConfig().linkDomains || '').split(',').map(x => x.trim()).filter(x => x && !x.startsWith('www.')); + const host = hosts[0] || SITE_HOST; + return json(res, 200, { ok: true, code: r.rotation.code, url: 'https://' + host + '/r/' + r.rotation.code, destinations: r.rotation.destinations.length, expiresIn: 24 * 3600 }, + { 'Set-Cookie': 'ls.demo=' + token + '; Path=/; Max-Age=2592000; HttpOnly; SameSite=Lax' + (IS_PROD ? '; Secure' : '') }); + } + + // -- 24/7 assistant + if (p === '/api/chat' && req.method === 'POST') { + const ip = req.socket.remoteAddress || 'x'; + if (chatLimited(ip)) return json(res, 429, { error: 'Give it a minute, then ask again.' }); + const b = await readBody(req); + const r = await chatbot.answer(b.message, b.history); + return json(res, r.error ? 400 : 200, r); + } + + // -- accounts: email + password is the normal join path (wallet comes + // out only at purchase / payout-activation time and gets linked then) + if (p === '/api/signup' && req.method === 'POST') { + if (!SIGNUPS_OPEN) return json(res, 403, SHUT); + const b = await readBody(req); + const ref = parseCookies(req)['iap.sponsor'] || ''; // last-touch attribution, locked at account creation + const r = await accounts.signup(b.email, b.password, ref); + if (r.error) return json(res, 400, r); + { const lc = parseCookies(req)['ls.click']; if (lc) { postbacks.bindClick(String(b.email || '').trim().toLowerCase(), lc); postbacks.convertFor(String(b.email || '').trim().toLowerCase(), 'join', {}).catch(() => {}); } } + // sponsor is notified once the new member picks a username (onboarding), + // so the email can name them — see /api/my/profile + if (b.newsletter) sendy.subscribe(r.account.email, r.account.username || '').catch(() => {}); // pre-checked opt-in, silent + const token = await auth.mintSession({ email: r.account.email }); + return json(res, 200, { ok: true, account: r.account }, { 'Set-Cookie': auth.sessionCookie(token) }); + } + if (p === '/api/login' && req.method === 'POST') { + const b = await readBody(req); + const r = await accounts.login(b.email, b.password); + if (r.error) return json(res, 400, r); + let memberId = 0; + if (r.account.address) { try { memberId = await chain.memberIdByAccount(r.account.address); } catch (e) {} } + const token = await auth.mintSession({ email: r.account.email, address: r.account.address, memberId }); + return json(res, 200, { ok: true, account: r.account }, { 'Set-Cookie': auth.sessionCookie(token) }); + } + + // -- passwordless: email code sign-in (signup and login are the same act) + if (p === '/api/auth/email/start' && req.method === 'POST') { + const b = await readBody(req); + const e = String(b.email || '').trim().toLowerCase(); + if (!/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(e)) return json(res, 400, { error: 'That email address does not look right.' }); + // closed sign-ups shut the door to NEW accounts only; members already here (incl. imported shells) still get their code + const acct0 = await accounts.byEmail(e); + if (!SIGNUPS_OPEN && !acct0) return json(res, 403, SHUT); + if (!isTester(e, acct0)) return json(res, 403, TESTING); + const prev = emailCodes.get(e); + if (prev && Date.now() < prev.nextAt) { console.log('signup-guard cooldown', clientIp(req), e.replace(/^(.).*(@.*)$/, '$1***$2')); return json(res, 429, { error: 'Code already sent. Give it a minute, then try again.' }); } + const guard = codeGuard(req, b); // honeypot, form age, per-IP + global limits, icon check once limited + if (guard) return json(res, guard.status, guard.body); + const code = String(Math.floor(100000 + Math.random() * 900000)); + emailCodes.set(e, { code, exp: Date.now() + 15 * 60 * 1000, tries: 0, nextAt: Date.now() + 60 * 1000 }); + if (mailer.hasKey()) { + try { await mailer.sendCode(e, code); } catch (err) { + console.error('sendCode failed', err.message); + return json(res, 502, { error: 'Could not send the email. Try again in a minute.' }); + } + return json(res, 200, { ok: true, sent: true }); + } + if (!IS_PROD) return json(res, 200, { ok: true, sent: false, devCode: code }); + return json(res, 503, { error: 'Email sign-in is not configured yet.' }); + } + if (p === '/api/auth/email/verify' && req.method === 'POST') { + const b = await readBody(req); + const e = String(b.email || '').trim().toLowerCase(); + const rec = emailCodes.get(e); + if (!rec || rec.exp < Date.now()) return json(res, 400, { error: 'Code expired. Request a fresh one.' }); + rec.tries += 1; + if (rec.tries > 6) { emailCodes.delete(e); return json(res, 400, { error: 'Too many tries. Request a fresh code.' }); } + if (String(b.code || '').trim() !== rec.code) return json(res, 400, { error: 'That code does not match.' }); + emailCodes.delete(e); + const ref = parseCookies(req)['iap.sponsor'] || ''; + const via = parseCookies(req)['iap.angle'] || ''; + const joinedRef = decodeURIComponent(parseCookies(req)['iap.ref'] || '') || null; + // the code door creates an account on first use, so it is a sign-up door too + if (!SIGNUPS_OPEN && !(await accounts.byEmail(e))) return json(res, 403, SHUT); + if (!isTester(e, await accounts.byEmail(e))) return json(res, 403, TESTING); + 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) carry.onJoin(r.account, !!ref).catch(() => {}); // network sponsor carries over when no link was used (LinkSpin) + if (r.created) { const lc = parseCookies(req)['ls.click']; if (lc) { postbacks.bindClick(e, lc); postbacks.convertFor(e, 'join', {}).catch(() => {}); } } + { const dm = String(parseCookies(req)['ls.demo'] || '').replace(/[^a-f0-9]/g, ''); if (dm.length >= 16) rotator.claim('demo:' + dm, e).catch(() => {}); } // the home-page demo spin becomes theirs + // 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(() => {}); + // a wallet-only session (signed with a wallet, no account) finishing setup: + // adopt that wallet into the email account so member #, purchases and + // payouts stay attached, then retire the wallet-only session + const prior = await auth.fromRequest(req); + if (prior && prior.address && !prior.email) { + const lr = await accounts.linkWallet(e, prior.address); + if (lr.error) return json(res, 400, lr); + r.account = lr.account || await accounts.byEmail(e); + await auth.logout(req); + } + if (r.created) { sendWelcome(e, ref).catch(() => {}); } // sponsor notified at username set (/api/my/profile) + // partner promo code carried on the join link: redeem once per account (ignored if invalid/used) + try { + const pc = parseCookies(req)['iap.promo']; + if (pc) { const g = await promos.redeem(pc, e, 'link'); if (g.ok) { if (g.funder && g.funder !== e) { if (await ads.spendEarned(g.funder, g.credits)) { await ads.addEarned(e, g.credits); console.log('promo redeemed (member-funded)', g.code, g.credits, e, 'by', g.funder); } else console.log('promo funder short', g.code, g.funder); } else { await ads.addEarned(e, g.credits); console.log('promo redeemed', g.code, g.credits, e); } } } + } catch (err) { console.error('promo redeem', err.message); } + // legacy bridge: a listed former Faucet Wave / Tier One Ads member gets welcome-back credits once + if (r.created && /^(fw|t1)-(adv|earn)$/.test(via)) { + try { const g = legacy.grant(e, siteConfig()); if (g) { await ads.addEarned(e, g.credits); console.log('legacy grant', g.brand, g.seg, g.credits, e); } } + catch (err) { console.error('legacy grant', err.message); } + } + if (r.created && b.newsletter) sendy.subscribe(r.account.email, r.account.username || '').catch(() => {}); // pre-checked opt-in, silent, new joins only + let memberId = 0; + if (r.account.address) { try { memberId = await chain.memberIdByAccount(r.account.address); } catch (err) {} } + const token = await auth.mintSession({ email: r.account.email, address: r.account.address, memberId }); + return json(res, 200, { ok: true, account: r.account, created: !!r.created }, { 'Set-Cookie': auth.sessionCookie(token) }); + } + + // -- wallet auth: link-to-account when an email session exists, or + // wallet-first sign-in (no UI door since 2026-09-09; a wallet-only session + // is walked to the email card, which adopts the wallet on verify) + if (p === '/api/auth/challenge' && req.method === 'POST') { + const b = await readBody(req); + const r = auth.makeChallenge(b.address); + return json(res, r.error ? 400 : 200, r); + } + if (p === '/api/auth/verify' && req.method === 'POST') { + const b = await readBody(req); + const r = await auth.verifyChallenge(b.address, b.signature); + if (r.error) return json(res, 400, r); + let memberId = 0; + try { memberId = await chain.memberIdByAccount(r.address); } catch (e) {} + const s = await auth.fromRequest(req); + if (s && s.email && b.asPosition) { + // Qualified Start: a second (third…) wallet on the same account. It becomes + // its own on-chain member under this member's id when it buys; the session + // stays on the main wallet. + // policy (Marty, 2026-09-10): positions exist to qualify, so at most five per account, and a + // wallet that is already registered on-chain under anything other than this account's main + // member is refused (a position-under-position chain would recapture 70% of a self-buy) + const MAX_POS = 5; + const have = await accounts.positions(s.email); + if (!have.find(p => p.address === r.address.toLowerCase()) && have.length >= MAX_POS) + return json(res, 400, { error: 'You can link up to ' + MAX_POS + ' positions, which is everything Qualified Start needs. Once qualified, buy from your main wallet so your sponsor is paid in full.' }); + if (memberId) { + const mainId = await auth.refreshMemberId(s); + let mm = null; try { mm = await chain.member(memberId); } catch (e) {} + if (mm && mainId && mm.sponsorId !== mainId) + return json(res, 400, { error: 'That wallet is already registered on-chain under ' + (mm.sponsorId ? 'member #' + mm.sponsorId : 'no sponsor') + ', not under your main member #' + mainId + '. Only positions registered directly under you can be linked.' }); + } + const pr = await accounts.addPosition(s.email, r.address); + if (pr.error) return json(res, 400, pr); + if (memberId) await accounts.setPositionMember(r.address, memberId); + return json(res, 200, { ok: true, position: true, address: r.address, memberId }); + } + if (s && s.email) { + const lr = await accounts.linkWallet(s.email, r.address); + if (!lr.error) postbacks.convertFor(s.email, 'wallet', {}).catch(() => {}); + if (lr.error) return json(res, 400, lr); + await auth.updateSession(s.token, { address: r.address, memberId }); + return json(res, 200, { ok: true, linked: true, address: r.address, memberId }); + } + const acct = await accounts.byAddress(r.address); + if (!acct && await accounts.positionOwner(r.address)) + return json(res, 400, { error: 'That wallet is a linked position on an account. Sign in with that account\'s email instead.' }); + const token = await auth.mintSession({ email: acct ? acct.email : null, address: r.address, memberId }); + return json(res, 200, { ok: true, address: r.address, memberId }, + { 'Set-Cookie': auth.sessionCookie(token) }); + } + if (p === '/api/auth/logout' && req.method === 'POST') { + await auth.logout(req); + return json(res, 200, { ok: true }, { 'Set-Cookie': auth.clearCookie() }); + } + if (p === '/api/gas' && req.method === 'GET') { + try { + const fees = await chain.suggestedFees(); + const from = u.searchParams.get('from'), to = u.searchParams.get('to'), data = u.searchParams.get('data'), value = u.searchParams.get('value'); + if (/^0x[0-9a-fA-F]{40}$/.test(from || '') && /^0x[0-9a-fA-F]{40}$/.test(to || '') && /^0x[0-9a-fA-F]*$/.test(data || '')) { const call = { from, to, data: data || '0x' }; if (/^0x[0-9a-fA-F]+$/.test(value || '')) call.value = value; fees.gas = await chain.estimateGas(call); } + return json(res, 200, fees); + } + catch (e) { return json(res, 200, {}); } + } + + if (p === '/api/me' && req.method === 'GET') { + const s = await auth.fromRequest(req); + if (!s) return json(res, 200, { signedIn: false }); + const memberId = await auth.refreshMemberId(s); + const acct = (s.email && await accounts.byEmail(s.email)) || (s.address && await accounts.byAddress(s.address)) || null; + const spdMe = await resolveSponsorDetailed((acct && acct.sponsorRef) || parseCookies(req)['iap.sponsor']); let sponsorId = spdMe.id; + const sponsorBlocked = (acct && acct.sponsorRef && !sponsorId && spdMe.reason === 'rpc') ? 'rpc' : null; // never hold: the buy/activate paths resolve through /api/sponsor?intent=buy (carry walk-up) + if (sponsorId && await payoutChainBlocked(sponsorId, 2)) sponsorId = 0; + const _defSpon = Number(siteConfig().defaultSponsorId) || 1; + if (!sponsorId && memberId !== _defSpon) sponsorId = _defSpon; // orphan fallback → #1 (never self-sponsor) + if (sponsorId) { try { if (sponsorId > await chain.memberCount()) sponsorId = 0; } catch (e) {} } // fresh contract: no catch position exists yet, the first member becomes #1 + if (memberId && acct && acct.memberId !== memberId) accounts.setMemberId(acct.email, memberId).catch(() => {}); + const out = { signedIn: true, sponsorBlocked, sponsorName: spdMe.name || null, email: s.email || (acct && acct.email) || null, + address: s.address || (acct && acct.address) || null, memberId, + username: (acct && acct.username) || null, + refCode: (acct && acct.code) || null, sponsorId, + // profile + line-banner fields so the Profile pane repopulates on reload (were being saved but not returned) + avatarUrl: (acct && acct.avatarUrl) || null, bio: (acct && acct.bio) || null, + socials: (acct && acct.socials) || null, + wallOffers: parseWallOffers(acct), + lineBannerUrl: (acct && acct.lineBannerUrl) || null, lineTargetUrl: (acct && acct.lineTargetUrl) || null }; + if (memberId) { + try { + const mm = await chain.member(memberId); + out.buyerCount = mm.buyerCount; + out.onchainSponsorId = mm.sponsorId; + const bal = await ads.balances((await myMemberIds(s)).ids, s.email); + out.credits = bal.total; out.creditedCredits = bal.credited; out.earnedCredits = bal.earned; out.inCampaigns = bal.inCampaigns; out.availableCredits = bal.available; + } catch (e) { out.chainReadError = true; } + } + return json(res, 200, out); + } + + if (p === '/api/my/dashboard' && req.method === 'GET') { + const s = await auth.fromRequest(req); + if (!s) return json(res, 401, { error: 'Sign in first.' }); + const memberId = await auth.refreshMemberId(s); + const acct = (s.email && await accounts.byEmail(s.email)) || (s.address && await accounts.byAddress(s.address)) || null; + if (memberId && acct && acct.memberId !== memberId) accounts.setMemberId(acct.email, memberId).catch(() => {}); + let tankWaiting = null; // top of every Overview: people waiting for a sponsor (Marty, 2026-09-12) + try { + if (!tankWaitCache || Date.now() - tankWaitCache.ts > 60000) tankWaitCache = { ts: Date.now(), list: await tank.waiting() }; + const tw = tankWaitCache.list; + tankWaiting = { count: tw.length, names: tw.slice(0, 6).map(w => w.name), eligible: !!(await tank.eligibility(s.email)).ok }; + } catch (e) {} + const sc0 = siteConfig(); + const out = { memberId, tankWaiting, email: s.email || (acct && acct.email) || null, + pipeline: { live: pipeline.visible(sc0.pipelineMode, s.email || (acct && acct.email), ADMIN_EMAIL), mode: sc0.pipelineMode || 'off', eta: sc0.pipelineEta || '' }, + address: s.address || (acct && acct.address) || null, + username: (acct && acct.username) || null, + refCode: (acct && acct.code) || null, lineBannerUrl: (acct && acct.lineBannerUrl) || null, /* the launch checklist mark reads it (was 7 of 8 with a banner set, 2026-09-14) */ credits: 0, buyerCount: 0, + earnedWei: '0', earnCount: 0, referrals: [], welcomeCredits: 0 }; + if (out.email) { + // welcome credits unlock via the welcome tour when an upline with a + // line banner exists; members with no tour to walk get them instantly + const welcomed = await ads.welcomeGranted(out.email); + const tour = welcomed ? [] : (await uplineSlides(out.email)).filter(a => a.lineTargetUrl); + if (welcomed || !tour.length) { await ads.grantWelcome(out.email); out.welcomeCredits = ads.rates().welcomeCredits || 0; } // the welcome amount itself; the rest of the earned pool is viewing rewards, milestones and credits we add + else { out.welcomeCredits = 0; out.gauntletPending = true; } + } + if (out.email) out.inboxUnread = await ads.unreadCount(out.email); // delivers pending solos too + if (out.email) { // sponsor chat: presence heartbeat + unread + my availability + direct sponsor + accounts.touchSeen(out.email).catch(() => {}); + out.chatUnread = await messages.chatUnread(out.email); + out.chatAvailable = (acct && acct.chatAvailable !== false); + const spon = await accounts.sponsorOf(out.email); + if (spon && spon.email) out.sponsor = { + email: spon.email, + name: spon.username ? '@' + spon.username : (spon.memberId ? 'member #' + spon.memberId : 'your sponsor'), + online: (Date.now() - (spon.lastSeen || 0)) < 60000, + available: spon.chatAvailable !== false }; + } + if (out.email) { // unmissable login modal when the upline sent a message + const un = await messages.newestUnread(out.email); + if (un) { + const nm = un.fromMember ? await accounts.namesForMembers([un.fromMember]) : {}; + out.sponsorMsg = { id: un.id, subject: un.subject, body: un.body, + fromName: (un.fromMember && nm[un.fromMember]) ? '@' + nm[un.fromMember] : (un.fromMember ? 'member #' + un.fromMember : 'your sponsor') }; + } + } + if (memberId) { + try { + const mm = await chain.member(memberId); + out.buyerCount = mm.buyerCount; + const mine = await myMemberIds(s); + // linked positions are the member's own: their qualifying buyers count toward the account (Jim, 2026-09-14) + out.buyerCountMain = mm.buyerCount; out.buyerCountPositions = 0; + for (const id of mine.ids) if (id && id !== memberId) { try { out.buyerCountPositions += (await chain.member(id)).buyerCount || 0; } catch (e) {} } + out.buyerCountAll = out.buyerCountMain + out.buyerCountPositions; // badges count every position; levels the contract pays #main on depend on buyerCount alone + const bal = await ads.balances(mine.ids, s.email); + out.credits = bal.total; out.creditedCredits = bal.credited; out.earnedCredits = bal.earned; out.inCampaigns = bal.inCampaigns; out.availableCredits = bal.available; + } catch (e) { out.chainReadError = true; } + let earned = 0n, n = 0; + for (const ev of chain.recentEvents(600)) { + if ((ev.type === 'TierPaid' && ev.recipientId === memberId) || (ev.type === 'AwardPaid' && ev.toId === memberId)) { + earned += BigInt(ev.amountWei); n += 1; + } + } + out.earnedWei = earned.toString(); + out.earnCount = n; + } + // achievement milestones (same ladder as the Overview stepper) + one-time credit + // bonuses — computed AFTER buyerCount is read from chain above (else always 0) + { + const bc = out.buyerCountAll != null ? out.buyerCountAll : (out.buyerCount || 0); + const reached = []; + if (out.memberId) reached.push('payouts'); + if (bc >= 1) reached.push('firstBuyer'); + if (bc >= 2) reached.push('level2'); + if (bc >= 5) reached.push('level3'); + try { for (const k of await ads.milestonesOf(out.email)) if (!reached.includes(k)) reached.push(k); } catch (e) {} // a badge once earned stays earned + out.milestonesReached = reached; + if (out.email && reached.length) out.milestonesGranted = await ads.grantMilestones(out.email, reached); + } + // who joined through this member: their invite link uses username when set, + // else code, and the numeric id once on-chain — match all three + const refs = []; + if (acct && acct.code) refs.push(acct.code); + if (acct && acct.username) refs.push(acct.username); + if (memberId) refs.push(String(memberId)); + const joined = await accounts.listByReferrer(refs); + out.referrals = joined.map(r => ({ + name: r.username || r.email.replace(/^(.).*(@.*)$/, '$1***$2'), // username, else privacy mask + joined: r.created, + status: r.address ? 'wallet linked' : 'joined free' + })); + out.isAdmin = !!(ADMIN_EMAIL && out.email && String(out.email).toLowerCase() === ADMIN_EMAIL); // shows the Admin link + out.wallUnlocked = wallUnlockedFor(out.buyerCount || 0); // how many wall positions are the member's own + return json(res, 200, out); + } + // -- linked positions (Qualified Start): list, refresh from chain, unlink + if (p === '/api/my/positions' && req.method === 'GET') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const acct = await accounts.byEmail(s.email); + const mainId = await auth.refreshMemberId(s); + const list = await accounts.positions(s.email); + const out = []; + const posIds = [mainId, ...list.map(p => p.memberId)].filter(Boolean); + let balPer = {}, credited = 0; try { const bb = await ads.balances(posIds, s.email); credited = bb.credited; for (const p of bb.per) balPer[p.memberId] = p.avail; } catch (e) {} + for (const pos of list) { + let id = pos.memberId; + if (!id) { try { id = await chain.memberIdByAccount(pos.address); if (id) await accounts.setPositionMember(pos.address, id); } catch (e) {} } + const row = { address: pos.address, memberId: id || 0, buyerCount: 0, counted: false, credits: 0, created: pos.created }; + if (id) { + try { const mm = await chain.member(id); row.buyerCount = mm.buyerCount; row.counted = mm.countedAsBuyer; row.sponsorId = mm.sponsorId; } catch (e) {} + row.credits = balPer[id] != null ? balPer[id] : 0; + row.noPayout = await payoutChainBlocked(id, 3); // linkage only: a buy from here would pay a listed wallet + } + out.push(row); + } + const main = { address: (acct && acct.address) || null, memberId: mainId, credits: 0, buyerCount: 0 }; + if (mainId) { + main.credits = balPer[mainId] != null ? balPer[mainId] : 0; + try { main.buyerCount = (await chain.member(mainId)).buyerCount; } catch (e) {} + main.noPayout = await payoutChainBlocked(mainId, 3); + } + // live POL balances (the link signature proved the wallet is theirs) + a POL/USD rate from the catalog + const bal = async a => { try { return BigInt(await chain.rpc('eth_getBalance', [a, 'latest'])).toString(); } catch (e) { return null; } }; + if (main.address) main.balanceWei = await bal(main.address); + for (const row of out) row.balanceWei = await bal(row.address); + let polUsd = 0; try { const cat = await chain.catalog(); const pk = cat.find(x => x.costWei); if (pk) polUsd = (pk.priceCents / 100) / (Number(BigInt(pk.costWei)) / 1e18); } catch (e) {} + return json(res, 200, { main, positions: out, polUsd, totalCredits: main.credits + out.reduce((n, r) => n + r.credits, 0), credited }); + } + if (p === '/api/my/positions/remove' && req.method === 'POST') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const b = await readBody(req); + const r = await accounts.removePosition(s.email, b.address); + return json(res, r.error ? 400 : 200, r); + } + // -- coaching: every direct's ladder rung, stalled flag, and what to say + // -- holding tank: waiting members, my adoptions, adopt, release (pay it forward) + // -- promo code typed on the dashboard + if (p === '/api/my/promo/redeem' && req.method === 'POST') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const b = await readBody(req); + const g = await promos.redeem(b.code, s.email, 'dashboard'); + if (g.error) return json(res, 400, g); + await ads.addEarned(s.email, g.credits); + return json(res, 200, { ok: true, credits: g.credits, code: g.code, partner: g.partner }); + } + // -- admin: member card. GET ?q= resolves email / @username / #id / share code / wallet; + // PATCH edits username, sponsor, main wallet or grants credits; DELETE removes a free account (2026-09-13) + if (p === '/api/admin/member' && req.method === 'GET') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + const q = u.searchParams.get('q') || u.searchParams.get('email') || ''; + const a = await adminMember.resolve(q); + if (!a) return json(res, 404, { error: 'No member matches "' + q.slice(0, 60) + '".' }); + return json(res, 200, await adminMember.view(a.email)); + } + if (p === '/api/admin/member' && req.method === 'PATCH') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + const b = await readBody(req); + const e = String(b.email || '').trim().toLowerCase(); const acct = e && await accounts.byEmail(e); + if (!acct) return json(res, 404, { error: 'No such member.' }); + if (b.username !== undefined) { + const un = String(b.username || '').trim().toLowerCase(); + if (!/^[a-z0-9_]{3,20}$/.test(un)) return json(res, 400, { error: 'Username: 3 to 20 letters, numbers or underscore.' }); + const r = await accounts.setUsername(e, un); if (r.error) return json(res, 400, r); + console.log('admin username', e, un); + } + if (b.sponsorRef !== undefined) { const r = await accounts.setSponsorRef(e, String(b.sponsorRef || '').trim()); if (r.error) return json(res, 400, r); console.log('admin sponsor', e, String(b.sponsorRef || '').trim()); } + if (b.address !== undefined) { + const a = String(b.address || '').trim().toLowerCase(); + if (a && !/^0x[0-9a-f]{40}$/.test(a)) return json(res, 400, { error: 'That is not a wallet address.' }); + const r = await accounts.adminSetAddress(e, a || null); if (r.error) return json(res, 400, r); + let mid = 0; if (a) { try { mid = Number(await chain.memberIdByAccount(a)) || 0; } catch (x) {} } + await accounts.setMemberId(e, mid); + if (db.enabled()) await db.q('UPDATE sessions SET address=?, member_id=? WHERE email=?', [a || null, mid || null, e]).catch(() => {}); + console.log('admin wallet swap', e, a || '(none)', 'member', mid); + } + if (b.grantCredits !== undefined) { + const n = Math.round(Number(b.grantCredits)); + if (!(n > 0) || n > 100000) return json(res, 400, { error: 'Credits: a whole number from 1 to 100,000.' }); + await ads.addEarned(e, n); + console.log('admin credits', e, n, String(b.note || '').slice(0, 100)); + } + return json(res, 200, await adminMember.view(e)); + } + if (p === '/api/admin/member' && req.method === 'DELETE') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + const e = String(u.searchParams.get('email') || '').trim().toLowerCase(); const acct = e && await accounts.byEmail(e); + if (!acct) return json(res, 404, { error: 'No such member.' }); + if (acct.memberId) return json(res, 400, { error: 'Member #' + acct.memberId + ' is registered on-chain and cannot be deleted.' }); + const pos = await accounts.positions(e); if (pos.some(x => x.memberId)) return json(res, 400, { error: 'This account owns a registered position and cannot be deleted.' }); + const r = await accounts.removeAccount(e); if (r.error) return json(res, 400, r); + if (db.enabled()) await db.q('DELETE FROM sessions WHERE email=?', [e]).catch(() => {}); + console.log('admin removed account', e); + return json(res, 200, { ok: true }); + } + // -- release notes + roadmap (public read; admin write) (Marty, 2026-09-14) + if (p === '/api/releases' && req.method === 'GET') return json(res, 200, releases.publicView()); + // -- promo toolkit: tiers by badge + the AI Copy Engine (Surge+), credits beyond the free allowance + if (p === '/api/my/toolkit' && req.method === 'GET') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + return json(res, 200, await toolkit.status(s.email)); + } + if (p === '/api/my/toolkit/generate' && req.method === 'POST') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const b = await readBody(req); + const r = await toolkit.generate(s.email, String(b.kind || ''), String(b.brief || ''), String(b.angle || 'plain')); + return json(res, r.error ? 400 : 200, r); + } + if (p === '/api/my/toolkit/template' && req.method === 'POST') { // Spark: one-tap campaign aimed at the member's link + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const b = await readBody(req); const memberId = await auth.refreshMemberId(s); + const r = await toolkit.template(s.email, memberId, (await myMemberIds(s)).ids, String(b.kind || ''), Number(b.budget) || 0); + return json(res, r.error ? 400 : 200, r); + } + if (p === '/api/my/toolkit/split' && req.method === 'GET') { // Circuit: per-angle views/joins/buyers for the member's link + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + return json(res, 200, await toolkit.split(s.email)); + } + if (p === '/api/my/toolkit/videos' && req.method === 'GET') { // Circuit: Video Maker list + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + return json(res, 200, await toolkit.videos(s.email)); + } + if (p === '/api/my/toolkit/video' && req.method === 'POST') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const b = await readBody(req); + const r = await toolkit.makeVideo(s.email, String(b.slug || '')); + return json(res, r.error ? 400 : 200, r); + } + if (p === '/api/my/toolkit/team' && req.method === 'GET') { // Nexus: Leader Ops + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + return json(res, 200, await toolkit.team(s.email)); + } + if (p === '/api/my/toolkit/nudge' && req.method === 'POST') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const b = await readBody(req); const memberId = await auth.refreshMemberId(s); + const r = await toolkit.nudge(s.email, memberId, String(b.email || ''), String(b.text || '')); + return json(res, r.error ? 400 : 200, r); + } + if (p === '/api/my/toolkit/grant' && req.method === 'POST') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const b = await readBody(req); + const r = await toolkit.grant(s.email, String(b.email || ''), Number(b.credits) || 0); + if (r.ok) pushFeed({ type: 'Grant', from: r.fromName, to: r.toName, credits: r.credits, ts: Date.now() }); + return json(res, r.error ? 400 : 200, r); + } + if (p === '/api/my/toolkit/promo' && req.method === 'POST') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const b = await readBody(req); + const r = await toolkit.partnerCode(s.email, String(b.code || ''), Number(b.credits) || 0); + return json(res, r.error ? 400 : 200, r); + } + if (p === '/api/admin/toolkit' && req.method === 'GET') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + return json(res, 200, await toolkit.adminUsage()); + } + if (p === '/api/leaderboard' && req.method === 'GET') { // public standings; signed-in members also get their own row + const s = await auth.fromRequest(req); + const period = ['week', 'month', 'all', 'lastweek', 'lastmonth'].includes(u.searchParams.get('period')) ? u.searchParams.get('period') : 'week'; + return json(res, 200, await leaderboard.view(period, s && s.email ? s.email : null)); + } + if (p === '/api/admin/updates' && req.method === 'GET') { // member update emails: notes, audiences, log + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + const since = updates.lastSentAt(); + return json(res, 200, Object.assign({ notes: releases.notes().map(n => ({ id: n.id, title: n.title, date: n.date, fresh: !since || (n.created || 0) > since || (n.date && new Date(n.date + 'T12:00:00Z').getTime() > since) })), audiences: updates.AUDIENCES, counts: await updates.counts(), mailer: mailer.hasKey(), lastSentAt: since, draft: updates.draft() }, updates.status())); + } + if (p === '/api/admin/updates/draft' && req.method === 'POST') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + return json(res, 200, { ok: true, draft: updates.saveDraft(await readBody(req)) }); + } + if (p === '/api/admin/updates/preview' && req.method === 'POST') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + const b = await readBody(req); + return json(res, 200, updates.compose({ subject: b.subject, intro: b.intro, closing: b.closing, noteIds: (b.noteIds || []).map(String) }, { email: ADMIN_EMAIL, username: 'you' })); + } + if (p === '/api/admin/updates/send' && req.method === 'POST') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + const b = await readBody(req); + const r = await updates.send({ subject: b.subject, intro: b.intro, closing: b.closing, noteIds: (b.noteIds || []).map(String), audience: b.audience, to: Array.isArray(b.to) ? b.to.slice(0, 5000) : null }, { test: !!b.test }); + return json(res, r.error ? 400 : 200, r); + } + if (p === '/api/admin/releases' && req.method === 'GET') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + return json(res, 200, { notes: releases.notes(), roadmap: releases.roadmap(), tags: releases.TAGS, statuses: releases.STATUSES }); + } + if (p === '/api/admin/releases' && req.method === 'POST') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + const b = await readBody(req); + const r = b.kind === 'roadmap' ? releases.saveRoadmap(b) : releases.saveNote(b); + return json(res, r.error ? 400 : 200, r); + } + if (p === '/api/admin/releases' && req.method === 'DELETE') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + return json(res, 200, releases.remove(u.searchParams.get('kind'), String(u.searchParams.get('id') || ''))); + } + // -- admin: blog (list all incl. drafts, save/create, delete) (Marty, 2026-09-12) + if (p === '/api/admin/blog' && req.method === 'GET') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + const slug = u.searchParams.get('slug'); + if (slug) { const post = await blog.get(slug); return post ? json(res, 200, { post }) : json(res, 404, { error: 'No such post.' }); } + return json(res, 200, { syndication: syndicate.enabled(), posts: (await blog.listAll()).map(x => ({ slug: x.slug, title: x.title, status: x.status, tags: x.tags, publishedAt: x.publishedAt, updated: x.updated, views: x.views, excerpt: x.excerpt, cover: x.cover, syndicated: syndicate.statusOf(x.slug) })) }); + } + if (p === '/api/admin/blog' && req.method === 'POST') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + const b = await readBody(req); + const before = b.existingSlug ? await blog.get(b.existingSlug) : null; + const r = await blog.save(b, b.existingSlug || null); + if (r.ok && r.post.status === 'published' && (!before || before.status !== 'published') && !b.noSyndicate) { + // first time this article goes live: push it to X + Instagram (never repeated for the same slug) + syndicate.publish(r.post).catch(e => console.error('syndication', e.message)); + r.syndicating = syndicate.enabled(); + } + r.syndicated = syndicate.statusOf(r.post.slug); + return json(res, r.error ? 400 : 200, r); + } + if (p === '/api/admin/blog/syndicate' && req.method === 'POST') { // manual: post (or retry) a published article + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + const b = await readBody(req); + const post = await blog.get(String(b.slug || '')); + if (!post) return json(res, 404, { error: 'No such post.' }); + if (post.status !== 'published') return json(res, 400, { error: 'Publish the article first.' }); + if (!syndicate.enabled()) return json(res, 400, { error: 'No Blotato key on the server.' }); + const st = await syndicate.publish(post, { force: !!b.force }); + return json(res, 200, { ok: true, syndicated: st }); + } + if (p === '/api/admin/blog' && req.method === 'DELETE') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + const slug = u.searchParams.get('slug'); if (!slug) return json(res, 400, { error: 'slug' }); + return json(res, 200, await blog.remove(slug)); + } + // -- admin: promo codes (create/update, switch on/off, redemptions) + if (p === '/api/admin/promos' && req.method === 'GET') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + return json(res, 200, await promos.adminView()); + } + if (p === '/api/admin/promos' && req.method === 'POST') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + const b = await readBody(req); + const r = await promos.create(b); + return json(res, r.error ? 400 : 200, r); + } + if (p === '/api/admin/promos' && req.method === 'PATCH') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + const b = await readBody(req); + const r = await promos.setActive(b.code, !!b.active); + return json(res, r.error ? 400 : 200, r); + } + // -- username suggestion for the required first step (Marty, 2026-09-12): email prefix, cleaned, unique + if (p === '/api/my/username-suggest' && req.method === 'GET') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + let base = String(s.email).split('@')[0].toLowerCase().replace(/[^a-z0-9_]/g, '').slice(0, 18); + if (!/[a-z]/.test(base)) base = 'member' + base; + if (base.length < 3) base = (base + 'xyz').slice(0, 3); + let pick = base; + for (let i = 2; i < 100 && await accounts.byUsername(pick); i++) pick = base.slice(0, 20 - String(i).length) + i; + return json(res, 200, { suggest: pick }); + } + if (p === '/api/my/tank' && req.method === 'GET') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + return json(res, 200, await tank.view(s.email)); + } + // -- achievement badge -> Telegram (payments topic + the main group), once per badge per member. + // The browser composes the personalised image (canvas, same as Share) and posts it here. + if (p === '/api/my/badge-post' && req.method === 'POST') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const key = String(u.searchParams.get('key') || ''); + if (!BADGE_META[key]) return json(res, 400, { error: 'Unknown badge.' }); + if (!/^image\/jpeg/.test(String(req.headers['content-type'] || ''))) return json(res, 400, { error: 'Send the badge as a JPEG.' }); + let jpeg; try { jpeg = await readRaw(req, 1.5 * 1024 * 1024); } catch (e) { return json(res, 413, { error: 'Image too large.' }); } + if (!jpeg || jpeg.length < 2000 || jpeg[0] !== 0xff || jpeg[1] !== 0xd8) return json(res, 400, { error: 'That is not a JPEG.' }); + const held = await ads.milestonesOf(s.email); + if (!held.includes(key)) return json(res, 400, { error: 'You have not unlocked that badge yet.' }); + const log = badgeLog(); const mine = log[s.email] || {}; + if (mine[key]) return json(res, 200, { ok: true, already: true }); + // manual re-posts (the button) are Marty's only; members' badges go out automatically on unlock + if (u.searchParams.get('manual') === '1' && s.email !== ADMIN_EMAIL) return json(res, 403, { error: 'Badges post automatically when they unlock.' }); + const a = await accounts.byEmail(s.email); + const who = a && a.username ? '@' + a.username : (a && a.memberId ? 'member #' + a.memberId : 'a member'); + const link = a && a.username ? SITE_HOST + '/join/' + a.username : SITE_HOST; + const [label, sub] = BADGE_META[key]; + const caption = '\u{1F3C6} LinkSpin \u00b7 ' + who.replace(/[<>&]/g, '') + ' unlocked ' + label + ': ' + sub + '\n' + link; + const sc = siteConfig(); let sent = 0; + if (sc.telegramBotToken && sc.telegramEchoChatId) { + if (await telegramSendPhoto(sc.telegramEchoChatId, jpeg, caption, sc.telegramEchoTopicId)) sent++; // payments topic + if (String(sc.telegramBadgeGeneral || '1') !== '0' && await telegramSendPhoto(sc.telegramEchoChatId, jpeg, caption, null)) sent++; // the main group (General) + } + mine[key] = { ts: Date.now(), sent }; log[s.email] = mine; try { fs.writeFileSync(BADGE_LOG(), JSON.stringify(log)); } catch (e) {} + pushFeed({ type: 'Badge', member: who, label, ts: Date.now() }); + console.log('badge posted', s.email, key, 'sent', sent); + return json(res, 200, { ok: true, sent }); + } + // -- member's own share: store the composed badge so a public page can carry it as the preview image + if (p === '/api/my/badge-image' && req.method === 'POST') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const key = String(u.searchParams.get('key') || ''); + if (!BADGE_META[key]) return json(res, 400, { error: 'Unknown badge.' }); + let jpeg; try { jpeg = await readRaw(req, 1.5 * 1024 * 1024); } catch (e) { return json(res, 413, { error: 'Image too large.' }); } + if (!jpeg || jpeg.length < 2000 || jpeg[0] !== 0xff || jpeg[1] !== 0xd8) return json(res, 400, { error: 'That is not a JPEG.' }); + if (!(await ads.milestonesOf(s.email)).includes(key)) return json(res, 400, { error: 'You have not unlocked that badge yet.' }); + const a = await accounts.byEmail(s.email); + if (!a || !a.username) return json(res, 400, { error: 'Pick a username first; the share page carries it.' }); + fs.writeFileSync(path.join(UPLOADS_DIR, 'badge-' + a.username + '-' + key + '.jpg'), jpeg); + return json(res, 200, { ok: true, page: SITE_URL + '/b/' + a.username + '/' + key, image: SITE_URL + '/badge-img/' + a.username + '/' + key + '.jpg' }); + } + if (p === '/api/my/badge-posted' && req.method === 'GET') { // which of my badges are already on Telegram + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + return json(res, 200, { posted: Object.keys(badgeLog()[s.email] || {}), canPost: s.email === ADMIN_EMAIL }); + } + if (p === '/api/my/tank/adopt' && req.method === 'POST') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const b = await readBody(req); + const r = await tank.adopt(s.email, b.who, b.note); + if (r.ok) { // tell the payments topic who picked whom up (Marty, 2026-09-12) + pushFeed({ type: 'Adopted', sponsor: r.adopterName, member: r.adopteeName, ts: Date.now() }); + try { + const sc = siteConfig(); + const clean = t => String(t || '').replace(/[<>&]/g, ''); + if (sc.telegramBotToken && sc.telegramEchoChatId) + telegramSend(sc.telegramEchoChatId, '\u{1F91D} LinkSpin \u00b7 ' + clean(r.adopterName) + ' picked up ' + clean(r.adopteeName) + ' from the holding tank and is now their sponsor', sc.telegramEchoTopicId).catch(() => {}); + } catch (e) {} + } + return json(res, r.error ? 400 : 200, r); + } + if (p === '/api/my/tank/release' && req.method === 'POST') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const b = await readBody(req); + const r = await tank.release(s.email, b.email); + if (r.ok) { // the feed shows releases too, so a pickup-and-drop is visible for what it is (Marty, 2026-09-13) + pushFeed({ type: 'Released', sponsor: r.ownerName, member: r.memberName, ts: Date.now() }); + try { + const sc = siteConfig(); + const clean = t => String(t || '').replace(/[<>&]/g, ''); + if (sc.telegramBotToken && sc.telegramEchoChatId) + telegramSend(sc.telegramEchoChatId, '\u{1FAA3} LinkSpin \u00b7 ' + clean(r.ownerName) + ' returned ' + clean(r.memberName) + ' to the holding tank', sc.telegramEchoTopicId); + } catch (e) {} + } + return json(res, r.error ? 400 : 200, r); + } + if (p === '/api/my/tank/contacted' && req.method === 'POST') { // sponsor reached the lead off-site: reset the rescue clock + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const b = await readBody(req); + const r = await tank.markContacted(s.email, b.email); + return json(res, r.error ? 400 : 200, r); + } + if (p === '/api/my/gift' && req.method === 'POST') { // PIF: log a wallet-to-wallet POL gift and tell the recipient + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const b = await readBody(req); + const r = await tank.recordGift(s.email, b.email, b.tx, b.pol); + return json(res, r.error ? 400 : 200, r); + } + if (p === '/api/admin/tank' && req.method === 'GET') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + return json(res, 200, await tank.adminView()); + } + // -- admin Traffic tab: page views + join-page views + signups + $20 buyers, by referring + // domain / first-touch source, by landing page, by angle and by day (Marty, 2026-09-12) + if (p === '/api/admin/traffic' && req.method === 'GET') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + const days = Math.min(365, Math.max(1, Number(u.searchParams.get('days')) || 30)); + const since = Date.now() - days * 86400000, sinceDay = new Date(since).toISOString().slice(0, 10); + const hosts = {}, paths = {}, daily = {}, angles = {}; + const H = k => (hosts[k] = hosts[k] || { source: k, hits: 0, joinViews: 0, signups: 0, registered: 0, buyers: 0 }); + const Dy = k => (daily[k] = daily[k] || { day: k, hits: 0, signups: 0 }); + for (const r of await traffic.rows(sinceDay)) { H(r.host).hits += r.n; paths[r.path] = (paths[r.path] || 0) + r.n; Dy(r.day).hits += r.n; } + for (const v of await coach.viewsSince(since)) { H(v.ref || 'direct').joinViews += 1; const a = angles[v.angle || 'plain'] = angles[v.angle || 'plain'] || { angle: v.angle || 'plain', views: 0, signups: 0 }; a.views += 1; } + const buyerIds = new Set(); for (const ev of chain.recentEvents(1e9)) if (ev.type === 'BuyerCounted' && ev.newBuyerId) buyerIds.add(ev.newBuyerId); + for (const a of await accounts.listAll(5000)) { + if (!a.created || a.created < since) continue; + const h = H(a.joinedRef || 'direct'); h.signups += 1; if (a.memberId) h.registered += 1; if (a.memberId && buyerIds.has(a.memberId)) h.buyers += 1; + Dy(new Date(a.created).toISOString().slice(0, 10)).signups += 1; + const k = a.joinedVia || 'plain'; angles[k] = angles[k] || { angle: k, views: 0, signups: 0 }; angles[k].signups += 1; + } + const sources = Object.values(hosts).sort((x, y) => (y.hits + y.joinViews + y.signups * 10) - (x.hits + x.joinViews + x.signups * 10)); + return json(res, 200, { days, sources, paths: Object.entries(paths).map(([path, hits]) => ({ path, hits })).sort((x, y) => y.hits - x.hits), + angles: Object.values(angles).sort((x, y) => y.views - x.views), daily: Object.values(daily).sort((x, y) => x.day < y.day ? -1 : 1), + totals: { hits: sources.reduce((n, s) => n + s.hits, 0), joinViews: sources.reduce((n, s) => n + s.joinViews, 0), signups: sources.reduce((n, s) => n + s.signups, 0), buyers: sources.reduce((n, s) => n + s.buyers, 0) } }); + } + if (p === '/api/my/coach' && req.method === 'GET') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const cv = await coach.coachView(s.email); + for (const d of cv.directs) if (d.free) { try { d.rescue = await tank.rescueInfo(s.email, await accounts.byEmail(d.email)); } catch (e) {} } // dormant-lead clock + return json(res, 200, cv); + } + // -- link stats: views, joins and buyers per angle link + if (p === '/api/my/linkstats' && req.method === 'GET') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + return json(res, 200, await coach.linkStats(s.email)); + } + // -- prospects: the member's own follow-up list + // -- Pipeline: the follow-up board (stages from the ledger and the site; notes, follow-ups, tags from the sponsor) + if (p === '/api/my/pipeline' && req.method === 'GET') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const sc = siteConfig(); + if (!pipeline.visible(sc.pipelineMode, s.email, ADMIN_EMAIL)) return json(res, 200, { live: false, eta: sc.pipelineEta || '' }); + const b = await pipeline.board(s.email); + return json(res, 200, Object.assign({ live: true }, b), { 'Cache-Control': 'no-store' }); + } + if (p === '/api/my/pipeline/note' && req.method === 'POST') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + if (!pipeline.visible(siteConfig().pipelineMode, s.email, ADMIN_EMAIL)) return json(res, 403, { error: 'The Pipeline is not open yet.' }); + const r = await pipeline.save(s.email, await readBody(req)); + return json(res, r.error ? 400 : 200, r); + } + // -- the rotator (LinkSpin core tool) + if (p === '/api/my/rotations' && req.method === 'GET') { + const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const sc = siteConfig(); const hosts = String(sc.linkDomains || '').split(',').map(x => x.trim()).filter(Boolean); + return json(res, 200, { rotations: await rotator.list(s.email), hosts: hosts.length ? hosts : [SITE_HOST] }, { 'Cache-Control': 'no-store' }); + } + if (p === '/api/my/rotations' && req.method === 'POST') { + const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const r = await rotator.create(s.email, await readBody(req)); return json(res, r.error ? 400 : 200, r); + } + m = /^\/api\/my\/rotations\/(\d+)$/.exec(p); + if (m && req.method === 'POST') { + const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const b = await readBody(req); const r = b.remove ? await rotator.remove(s.email, m[1]) : await rotator.update(s.email, m[1], b); return json(res, r.error ? 400 : 200, r); + } + m = /^\/api\/my\/rotations\/(\d+)\/dest$/.exec(p); + if (m && req.method === 'POST') { + const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const r = await rotator.addDest(s.email, m[1], await readBody(req)); return json(res, r.error ? 400 : 200, r); + } + m = /^\/api\/my\/rotations\/(\d+)\/dest\/(\d+)$/.exec(p); + if (m && req.method === 'POST') { + const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const r = await rotator.updateDest(s.email, m[1], m[2], await readBody(req)); return json(res, r.error ? 400 : 200, r); + } + m = /^\/api\/my\/rotations\/(\d+)\/stats$/.exec(p); + if (m && req.method === 'GET') { + const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const r = await rotator.stats(s.email, m[1]); return r ? json(res, 200, r, { 'Cache-Control': 'no-store' }) : json(res, 404, { error: 'No such rotation.' }); + } + m = /^\/api\/my\/rotations\/(\d+)\/health$/.exec(p); // "Check now": fresh health states for every destination (once a minute per rotation) + if (m && req.method === 'POST') { + const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const r = await health.checkRotation(s.email, m[1]); return json(res, r.error ? (/No such/.test(r.error) ? 404 : 429) : 200, r, { 'Cache-Control': 'no-store' }); + } + if (p === '/api/my/strip' && req.method === 'GET') { // status strip under every Control Room screen + const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + let served = 0; try { served = (await rotator.summary(s.email, 1)).totals.served; } catch (e) {} + let zonesLive = 0; try { zonesLive = (await zones.list(s.email)).filter(z => z.active && z.status !== 'paused').length; } catch (e) {} + return json(res, 200, { ok: true, served, zones: zonesLive, network: nas.enabled() }, { 'Cache-Control': 'no-store' }); + } + if (p === '/api/my/zones' && req.method === 'GET') { + const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + return json(res, 200, { zones: await zones.list(s.email), host: SITE_HOST, sizes: Object.keys(zones.SIZES), networkSizes: Array.from(zones.NAS_SIZES), tiers: zones.TIERS, rates: zones.settings(), warmup: zones.WARMUP, holdRatio: zones.HOLD_RATIO }, { 'Cache-Control': 'no-store' }); + } + if (p === '/api/my/zones' && req.method === 'POST') { + const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const r = await zones.create(s.email, await readBody(req)); return json(res, r.error ? 400 : 200, r); + } + m = /^\/api\/my\/zones\/(ls-[a-f0-9]{6})$/.exec(p); + if (m && req.method === 'POST') { + const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const r = await zones.update(s.email, m[1], await readBody(req)); return json(res, r.error ? 400 : 200, r); + } + // tester invite: an admin-minted one-time sign-in link (24 h). Creates the account if needed, bypasses the sign-up + // gate and needs no email, which is what a curtained test app without outbound mail needs (2026-09-29) + if (p === '/api/admin/invite' && req.method === 'POST') { + if (!isAdmin(req)) return json(res, 401, { error: 'Admin only.' }); + const b = await readBody(req); const e = String(b.email || '').trim().toLowerCase(); + if (!/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(e)) return json(res, 400, { error: 'Which email?' }); + const r = await accounts.ensure(e, '', '', null); if (r.error) return json(res, 400, r); + const token = crypto.randomBytes(24).toString('hex'); + inviteTokens.set(token, { email: e, exp: Date.now() + 24 * 3600 * 1000, next: /^\/[a-z]/.test(String(b.next || '')) ? String(b.next) : '/ads' }); + return json(res, 200, { ok: true, url: 'https://' + SITE_HOST + '/welcome/' + token, created: !!r.created }); + } + if (p === '/api/admin/zones' && req.method === 'GET') { + if (!isAdmin(req)) return json(res, 401, { error: 'Admin only.' }); + return json(res, 200, { zones: await zones.adminList(), totals: zones.totals(), publishers: zones.publisherTotals(7), rates: zones.settings(), tiers: zones.TIERS, warmup: zones.WARMUP, holdRatio: zones.HOLD_RATIO }, { 'Cache-Control': 'no-store' }); + } + // admin: pause/resume, note, and the publisher tier ({ tier: 'standard' | 'verified' }; /tier is an alias for the same update) + m = /^\/api\/admin\/zones\/(ls-[a-f0-9]{6})(\/tier)?$/.exec(p); + if (m && req.method === 'POST') { + if (!isAdmin(req)) return json(res, 401, { error: 'Admin only.' }); + const r = await zones.adminSet(m[1], await readBody(req)); return json(res, r.error ? 400 : 200, r); + } + // -- hosted page images: /u/pages//., only files the pages index knows, a year of cache (2026-10-10) + m = /^\/u\/pages\/([a-f0-9]{16})\/([a-f0-9]{12})\.(png|jpg|webp)$/.exec(p); + if (m && (req.method === 'GET' || req.method === 'HEAD')) { + const f = pages.imageFile(m[1], m[2], m[3]); if (!f) { res.writeHead(404, { 'Content-Type': 'text/plain' }); return res.end('Not found'); } + return fs.readFile(f.file, (err, data) => { if (err) { res.writeHead(404, { 'Content-Type': 'text/plain' }); return res.end('Not found'); } res.writeHead(200, { 'Content-Type': f.mime, 'Content-Length': String(data.length), 'Cache-Control': 'public, max-age=31536000, immutable', 'X-Content-Type-Options': 'nosniff', 'Content-Disposition': 'inline', 'Access-Control-Allow-Origin': '*' }); res.end(req.method === 'HEAD' ? '' : data); }); + } + // -- the link-domain pool for the member Links screen: live (not burned, not reserve) hosts with their channel + if (p === '/api/my/link-hosts' && (req.method === 'GET' || req.method === 'POST')) { // the shell's api() helper posts (2026-10-10) + const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const hs = domains.hosts(); return json(res, 200, { hosts: hs.length ? hs : [{ host: SITE_HOST, channel: 'email', label: 'Email', note: 'The app host (no link domains are live)' }], channels: domains.CHANNELS }, { 'Cache-Control': 'no-store' }); + } + if (p === '/api/my/pages' && req.method === 'GET') { + const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const hosts = domains.live(); // burned or reserve domains are never handed out for new pages + const ph = pagesHost(); const pageBase = ph ? 'https://' + ph + '/' : 'https://' + (hosts[0] || SITE_HOST) + '/p/'; + return json(res, 200, { pages: await pages.list(s.email), hosts: ph ? [ph] : (hosts.length ? hosts : [SITE_HOST]), pageBase, types: pages.TYPES, styles: require('./pagestyle').catalog(), providers: pages.providers(), images: await pages.images(s.email), imageMax: pages.IMG_MAX, imageBytes: pages.IMG_BYTES }, { 'Cache-Control': 'no-store' }); + } + if (p === '/api/my/pages/upload' && req.method === 'POST') { + const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const up = await pages.readUpload(req); if (up.error) return json(res, 400, up); + const r = await pages.uploadImage(s.email, up.buf, up.ct); return json(res, r.error ? 400 : 200, r); + } + m = /^\/api\/my\/pages\/images\/([a-f0-9]{12})$/.exec(p); + if (m && req.method === 'POST') { + const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const b = await readBody(req); if (!b.remove) return json(res, 400, { error: 'Nothing to do.' }); + const r = await pages.removeImage(s.email, m[1]); return json(res, r.error ? 400 : 200, r); + } + // -- admin: the link-domain pool (channel per domain, last safety check, burned flag, check now / clear / pull) + if (p === '/api/admin/domains' && req.method === 'GET') { + if (!isAdmin(req)) return json(res, 401, { error: 'Admin only.' }); + return json(res, 200, { domains: domains.all(), channels: domains.CHANNELS, labels: domains.LABEL, notes: domains.NOTE, gsb: !!String(process.env.GSB_API_KEY || '').trim() }, { 'Cache-Control': 'no-store' }); + } + if (p === '/api/admin/domains' && req.method === 'POST') { + if (!isAdmin(req)) return json(res, 401, { error: 'Admin only.' }); + const b = await readBody(req); let r; + if (b.action === 'check') r = b.domain ? await domains.check(b.domain) : { ok: true, results: await domains.checkAll() }; + else if (b.action === 'channel') r = domains.setChannel(b.domain, b.channel); + else if (b.action === 'clear') r = domains.clear(b.domain); + else if (b.action === 'burn') r = domains.burn(b.domain, b.reason); + else r = { error: 'Unknown action.' }; + return json(res, r.error ? 400 : 200, Object.assign(r, { domains: domains.all() })); + } + if (p === '/api/my/pages' && req.method === 'POST') { + const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const r = await pages.create(s.email, await readBody(req)); return json(res, r.error ? 400 : 200, r); + } + if (p === '/api/my/pages/scan' && req.method === 'POST') { + const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const b = await readBody(req); const r = await pages.scan(b.url); return json(res, r.error ? 400 : 200, r); + } + if (p === '/api/my/pages/leads' && req.method === 'GET') { + const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + return json(res, 200, { leads: await pages.leads(s.email, u.searchParams.get('page') || null) }, { 'Cache-Control': 'no-store' }); + } + if (p === '/api/my/pages/leads.csv' && req.method === 'GET') { + const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const rows = await pages.leads(s.email, u.searchParams.get('page') || null); + res.writeHead(200, { 'Content-Type': 'text/csv; charset=utf-8', 'Content-Disposition': 'attachment; filename="linkspin-leads.csv"', 'Cache-Control': 'no-store' }); return res.end(pages.csv(rows)); + } + m = /^\/api\/my\/pages\/([a-f0-9]{10})(\/write)?$/.exec(p); + if (m && req.method === 'POST') { + const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const b = await readBody(req); const r = m[2] ? await pages.write(s.email, m[1], b) : await pages.update(s.email, m[1], b); return json(res, r.error ? 400 : 200, r); + } + if (p === '/api/my/reports' && req.method === 'GET') { + const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const days = Math.max(1, Math.min(365, Number(u.searchParams.get('days')) || 30)); + // spins (the rotator summary, spread at the top level so older report screens keep working) + pages + zones (2026-10-10) + const [spins, pg, zn] = await Promise.all([rotator.summary(s.email, days), pages.summary(s.email, days), zonereport.summary(s.email, days)]); + return json(res, 200, Object.assign({}, spins, { spins, pages: pg, zones: zn, days: spins.days, range: days }), { 'Cache-Control': 'no-store' }); + } + // -- traffic sources (2026-10-12). Every route takes GET and POST: the shell's api() helper always POSTs. + if (p === '/api/sources/catalog' && (req.method === 'GET' || req.method === 'POST')) return json(res, 200, { catalog: sources.catalog(), keys: sources.KEYS }, { 'Cache-Control': 'public, max-age=300' }); + if (p === '/api/my/sources' && (req.method === 'GET' || req.method === 'POST')) { + const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const b = req.method === 'POST' ? await readBody(req) : {}; + if (req.method === 'GET' || b.list || !Object.keys(b).length) return json(res, 200, await sources.list(s.email), { 'Cache-Control': 'no-store' }); + const r = await sources.create(s.email, b); return json(res, r.error ? 400 : 200, r); + } + m = /^\/api\/my\/sources\/([a-f0-9]{10})(\/url)?$/.exec(p); + if (m && (req.method === 'GET' || req.method === 'POST')) { + const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const b = req.method === 'POST' ? await readBody(req) : {}; for (const [k, v] of u.searchParams) if (b[k] == null) b[k] = v; + if (m[2]) { const r = await sources.urlFor(s.email, m[1], b.rotationId); return json(res, r.error ? 400 : 200, r, { 'Cache-Control': 'no-store' }); } + if (req.method === 'GET' || !Object.keys(b).length) { const r = await sources.get(s.email, m[1]); return r ? json(res, 200, r, { 'Cache-Control': 'no-store' }) : json(res, 404, { error: 'No such source.' }); } + const r = b.test ? await sources.test(s.email, m[1]) : await sources.update(s.email, m[1], b); return json(res, r.error ? 400 : 200, r); + } + if (p === '/api/my/postbacks' && req.method === 'GET') { + const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + return json(res, 200, { postbacks: await postbacks.list(s.email), events: postbacks.EVENTS, key: postbacks.partnerKey(s.email), inboundUrl: 'https://' + SITE_HOST + '/pb/in', log: await postbacks.logFor(s.email, 40) }, { 'Cache-Control': 'no-store' }); + } + if (p === '/api/my/postbacks' && req.method === 'POST') { + const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const b = await readBody(req); if (b.rotateKey) return json(res, 200, { ok: true, key: postbacks.rotateKey(s.email) }); + const r = await postbacks.create(s.email, b); return json(res, r.error ? 400 : 200, r); + } + m = /^\/api\/my\/postbacks\/([a-f0-9]{10})$/.exec(p); + if (m && req.method === 'POST') { + const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const b = await readBody(req); const r = b.test ? await postbacks.test(s.email, m[1]) : await postbacks.update(s.email, m[1], b); return json(res, r.error ? 400 : 200, r); + } + if (p === '/pb/in' && (req.method === 'GET' || req.method === 'POST')) { // partner-reported conversion against our click id + const b = req.method === 'POST' ? await readBody(req).catch(() => ({})) : {}; for (const [k, v] of u.searchParams) if (b[k] == null) b[k] = v; + const r = await postbacks.inbound(b.key, b); return json(res, r.error ? 400 : 200, r, { 'Cache-Control': 'no-store' }); + } + if (p === '/api/my/carry' && req.method === 'GET') { + const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const st = carry.status(); const me = s.email.toLowerCase(); + return json(res, 200, { engine: st.engine, claimDays: st.claimDays, claims: st.claims.filter(c => c.member === me || c.sponsor === me), registry: await registry.get(me) }); + } + if (p === '/api/admin/carry' && req.method === 'GET') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + return json(res, 200, Object.assign(carry.status(), { registryCount: await registry.count(), rotator: rotator.totals() })); + } + if (p === '/api/admin/carry/seed' && req.method === 'POST') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + const b = await readBody(req); return json(res, 200, await carry.seedAll(Number(b.limit) || 0)); + } + // -- live registry sync from InstantAdPay (2026-10-08): signed rows (HMAC LS_SYNC_SECRET over ts + newline + raw body), + // upserted into the registry; new people become shell accounts with their line, existing shells pick up a username, + // wallet or sponsor they did not have. Only the posted rows are touched. + 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) : []; + const n = await registry.importRows(rows, 'instantadpay'); let shells = 0, updated = 0; + for (const r of rows) { + const e = String(r.email || '').trim().toLowerCase(); if (!e) continue; + let a = await accounts.byEmail(e); + if (!a) { const x = await accounts.ensure(e, '', 'carried', 'network'); if (x.created) shells++; a = await accounts.byEmail(e); } + 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; + 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(x => x !== undefined)) { try { await accounts.setProfile(e, upd[0], upd[1], upd[2]); updated++; } catch (err) {} } + } + } + return json(res, 200, { ok: true, rows: rows.length, imported: n, shells, updated, registry: await registry.count() }); + } + 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'); + // every registry row with a sponsor becomes a site account too, so lines exist before anyone signs in + let shells = 0; + if (b.shells) for (const r of await registry.all()) { const a = await accounts.byEmail(r.email); if (!a) { const x = await accounts.ensure(r.email, '', 'carried', 'network'); if (x.created) shells++; if (r.username) { try { await accounts.setUsername(r.email, r.username); } catch (e) {} } if (r.wallet) { try { await accounts.linkWallet(r.email, r.wallet); } catch (e) {} } } } + if (b.shells) for (const r of await registry.all()) { if (!r.sponsorEmail) continue; const a = await accounts.byEmail(r.email); const sp = await accounts.byEmail(r.sponsorEmail); if (a && sp && !a.sponsorRef) await accounts.setSponsorRef(r.email, sp.username || sp.code); } + return json(res, 200, { ok: true, imported: n, shells, registry: await registry.count() }); + } + if (p === '/api/my/prospects' && req.method === 'GET') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + return json(res, 200, { prospects: await coach.prospects(s.email), statuses: coach.STATUSES }); + } + if (p === '/api/my/prospects' && req.method === 'POST') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const r = await coach.saveProspect(s.email, await readBody(req)); + return json(res, r.error ? 400 : 200, r); + } + if (p === '/api/my/prospects/remove' && req.method === 'POST') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const b = await readBody(req); + const r = await coach.removeProspect(s.email, b.id); + return json(res, r.error ? 400 : 200, r); + } + if (p === '/api/my/profile' && req.method === 'POST') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const b = await readBody(req); + const before = await accounts.byEmail(s.email); + // a username is permanent once set: the invite link, the public wall and every + // banner already printed carry it (Marty, 2026-09-10) + if (before && before.username && String(b.username || '').trim().toLowerCase() !== String(before.username).toLowerCase()) + return json(res, 400, { error: 'Your username is locked. Your invite link, your public page and any banners you shared all carry @' + before.username + '. Contact support if it truly has to change.' }); + const r = await accounts.setUsername(s.email, b.username); + // First time a username is set (onboarding): now there's a real name to + // show, so notify the sponsor here rather than at signup (where it'd just + // say "a new member"). Fires once — only on the empty→set transition. + if (!r.error && before && !before.username && b.username) { + const acct = await accounts.byEmail(s.email); + notifyNewReferral(acct && acct.sponsorRef, acct).catch(() => {}); + // everyone's dashboard: "@name just joined" (and whether they are waiting in the tank) + if (acct && acct.username) pushFeed({ type: 'Joined', name: '@' + acct.username, tank: !acct.sponsorRef && !acct.memberId, ts: Date.now() }); + } + return json(res, r.error ? 400 : 200, r); + } + // -- earn credits by viewing ads (attention-gated daily claim) + if (p === '/api/my/earn' && req.method === 'GET') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + return json(res, 200, await ads.viewStatus(s.email)); + } + // fraud-guarded view flow: the server issues a single-use token when it + // serves the ad, and only counts the view if the dwell elapsed on the + // SERVER clock. Client-side focus tracking pauses the countdown; this is + // the floor a script cannot cheat past. + if (p === '/api/my/earnview' && req.method === 'GET') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const status = await ads.viewStatus(s.email); + if (status.views >= status.target || status.claimed) return json(res, 200, { ad: null, status }); + const type = String(u.searchParams.get('type') || 'banner'); + // members never see (or earn from) their own campaigns in the viewer + const ad = await ads.serve(type === 'text' ? 'text' : 'banner', Object.assign({ excludeEmail: s.email }, viewerGeo(req), audiences.matcher(req))); + if (!ad) return json(res, 200, { ad: null, status }); + const token = crypto.randomBytes(16).toString('hex'); + // the viewer tab frames the advertiser's REAL url (no click counted for a paid view) + earnTokens.set(s.email, { token, ts: Date.now(), adId: ad.id, + targetUrl: await ads.targetOf(ad.id), adName: ad.title || ad.name || null }); + return json(res, 200, { ad, token, viewUrl: '/view/' + token, status }); + } + // the viewer tab asks where to point the frame (does not consume the token) + if (p === '/api/my/viewinfo' && req.method === 'GET') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const t = earnTokens.get(s.email); + if (!t || t.token !== String(u.searchParams.get('token') || '')) + return json(res, 400, { error: 'That view is no longer open. Head back to the dashboard and load the next ad.' }); + return json(res, 200, { targetUrl: t.targetUrl, adName: t.adName || null, + dwell: ads.rates().viewDwellSeconds || 10 }); + } + // human check: handed out only once the dwell has elapsed on the SERVER clock + if (p === '/api/my/viewchallenge' && req.method === 'GET') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const t = earnTokens.get(s.email); + if (!t || t.token !== String(u.searchParams.get('token') || '')) + return json(res, 400, { error: 'That view is no longer open.' }); + const dwellMs = (ads.rates().viewDwellSeconds || 10) * 1000; + const age = Date.now() - t.ts; + if (age < dwellMs - 400) return json(res, 200, { early: true, wait: Math.ceil((dwellMs - age) / 1000) }); + if (age > 5 * 60 * 1000) { earnTokens.delete(s.email); return json(res, 400, { error: 'That ad went stale. Load a fresh one.' }); } + const pick = CAPTCHA.slice().sort(() => Math.random() - 0.5).slice(0, 5); + const answer = Math.floor(Math.random() * pick.length); + t.challenge = { answer }; + return json(res, 200, { prompt: pick[answer][1], options: pick.map(x => x[0]) }); + } + if (p === '/api/my/adview' && req.method === 'POST') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const b = await readBody(req); + const t = earnTokens.get(s.email); + const dwellMs = (ads.rates().viewDwellSeconds || 10) * 1000; + if (!t || t.token !== String(b.token || '')) return json(res, 400, { error: 'That view did not check out. Load the next ad and let it finish.' }); + const age = Date.now() - t.ts; + if (age < dwellMs - 400) return json(res, 400, { error: 'Watch the full ad first.' }); + if (age > 5 * 60 * 1000) { earnTokens.delete(s.email); return json(res, 400, { error: 'That ad went stale. Load a fresh one.' }); } + // the human check must be solved on the same token + if (!t.challenge) return json(res, 400, { error: 'Finish the quick check first.', retry: true }); + if (Number(b.answer) !== t.challenge.answer) { + t.attempts = (t.attempts || 0) + 1; + t.challenge = null; // force a fresh challenge for the next try + if (t.attempts >= 3) { earnTokens.delete(s.email); return json(res, 400, { error: 'Three misses — that view is void. Head back and load the next ad.' }); } + return json(res, 400, { error: 'Wrong pick.', retry: true }); + } + earnTokens.delete(s.email); // single use + return json(res, 200, await ads.recordView(s.email)); + } + if (p === '/api/my/claim' && req.method === 'POST') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const r = await ads.claimDaily(s.email); + return json(res, r.error ? 400 : 200, r); + } + // -- downline lineage: 3 levels, usernames+IDs; email only for directs + if (p === '/api/my/line' && req.method === 'GET') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const levels = await accounts.downline(s.email, 3); + // what each person has paid THIS member so far: sum of TierPaid events where + // this member is the recipient and that person is the buyer (all indexed events) + // ...counting payouts to every position this account owns (main id + linked positions) + const myId = await auth.refreshMemberId(s); + const own = (await accounts.positions(s.email)).filter(p => p.memberId); + const myIds = new Set([myId, ...own.map(p => p.memberId)].filter(Boolean)); + const earnedBy = {}; + const qualified = new Set(); // members the contract counted as this account's qualifying buyers ($20+) + if (myIds.size) { + for (const ev of chain.recentEvents(1e9)) { + if (ev.type === 'TierPaid' && myIds.has(ev.recipientId) && ev.buyerId) + earnedBy[ev.buyerId] = (BigInt(earnedBy[ev.buyerId] || '0') + BigInt(ev.amountWei)).toString(); + if (ev.type === 'BuyerCounted' && myIds.has(ev.sponsorId) && ev.newBuyerId) qualified.add(ev.newBuyerId); + } + } + // who sponsored each person (Marty, 2026-09-14): resolve sponsorRef tokens (username, share code or member id) against the line itself + const meAcct = await accounts.byEmail(s.email); const byTok = {}; + const label = a => a.username ? '@' + a.username : (a.memberId ? 'member #' + a.memberId : 'member'); + for (const a of [meAcct, ...levels.flatMap(L => L.members)].filter(Boolean)) { const n = label(a); if (a.username) byTok[String(a.username).toLowerCase()] = n; if (a.code) byTok[String(a.code).toLowerCase()] = n; if (a.memberId) byTok[String(a.memberId)] = n; } + const sponsorOf = m => { const t = String(m.sponsorRef || '').toLowerCase(); if (!t) return null; if (meAcct && (t === String(meAcct.username || '').toLowerCase() || t === String(meAcct.code || '').toLowerCase() || t === String(meAcct.memberId || ''))) return 'you'; return byTok[t] || ('@' + t); }; + // a member's linked positions are theirs too: a qualifying buy from one of them lights their chip + const posIds = {}; for (const m of levels.flatMap(L => L.members)) { try { posIds[m.email] = (await accounts.positions(m.email)).map(p => p.memberId).filter(Boolean); } catch (e) { posIds[m.email] = []; } } + const idsOf = m => [m.memberId, ...(posIds[m.email] || [])].filter(Boolean); + // Clinton's ask (2026-09-14): on levels 2 and 3 show who has made their $20+ buy (counted for their own + // sponsor) and how many qualifying buyers of their own they have, so a leader can see who is one short + const onchain = {}; + for (const m of levels.flatMap(L => L.members)) { let bought = false, buyers = 0; for (const id of idsOf(m)) { const mm = await cachedMember(id); if (mm) { if (mm.countedAsBuyer) bought = true; buyers += mm.buyerCount || 0; } } onchain[m.email] = { bought, buyers }; } + const out = levels.map(L => ({ level: L.level, members: L.members.map(m => ({ + bought: onchain[m.email].bought, buyers: onchain[m.email].buyers, + memberId: m.memberId || 0, + sponsor: sponsorOf(m), + name: m.username ? '@' + m.username : m.memberId ? 'member #' + m.memberId : 'member', + ref: m.code || null, // opens the activity drop-down (Clinton's ask, 2026-09-14): any of the three levels + email: L.level === 1 ? m.email : null, // directs only + joined: m.created, + qualified: idsOf(m).some(id => qualified.has(id)), + earnedWei: idsOf(m).reduce((n, id) => n + BigInt(earnedBy[id] || '0'), 0n).toString() })) })); + // the member's own linked positions sit on level 1 too, labelled as theirs + if (own.length) { + if (!out.find(L => L.level === 1)) out.unshift({ level: 1, members: [] }); + const L1 = out.find(L => L.level === 1); + own.forEach((p, i) => L1.members.push({ memberId: p.memberId, name: 'You · position ' + (i + 2), own: true, + email: null, joined: p.created, earnedWei: earnedBy[p.memberId] || '0' })); + } + return json(res, 200, { levels: out, counts: out.map(L => L.members.length) }); + } + // -- who is working: one downline member's activity, any of the three levels (Clinton, 2026-09-14) + if (p === '/api/my/line/activity' && req.method === 'GET') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const ref = String(u.searchParams.get('ref') || '').trim().toLowerCase().slice(0, 40); + const a = ref ? await accounts.byCode(ref) : null; + if (!a || !(await accounts.isDownlineOf(s.email, a.email, 3))) return json(res, 404, { error: 'Not in your line.' }); + const now = Date.now(); + const out = { name: a.username ? '@' + a.username : (a.memberId ? 'member #' + a.memberId : 'member'), joined: a.created, lastSeen: a.lastSeen || 0, quietDays: Math.floor((now - Math.max(a.created || 0, a.lastSeen || 0)) / 86400000), wallet: !!a.address, memberId: a.memberId || 0 }; + try { const c = await coach.describe(a, now); out.rung = c.label; out.next = c.next; out.stalled = c.stalled; out.buyerCount = c.buyerCount || 0; } catch (e) {} + try { const v = await ads.viewStatus(a.email); out.viewsToday = v.views; out.target = v.target; out.claimedToday = v.claimed; out.streakDay = v.claimed ? v.streakDay : Math.max(0, v.streakDay - 1); } catch (e) {} + try { const cs = await ads.listCampaigns(a.email); out.campaigns = cs.length; out.campaignsActive = cs.filter(c => c.status === 'active').length; out.imps = cs.reduce((n, c) => n + (c.imps || 0) + (c.impsNas || 0), 0); } catch (e) {} + try { const ls = await coach.linkStats(a.email); out.linkViews30 = (ls.angles || []).reduce((n, r) => n + (r.views30 || 0), 0); out.linkViews = ls.totalViews || 0; out.joins = ls.totalJoins || 0; } catch (e) {} + try { out.directs = ((await accounts.downline(a.email, 1))[0] || { members: [] }).members.length; } catch (e) { out.directs = 0; } + try { out.badges = await ads.milestonesOf(a.email); } catch (e) { out.badges = []; } + try { out.positions = (await accounts.positions(a.email)).length; } catch (e) { out.positions = 0; } + return json(res, 200, out); + } + // -- broadcast a message to your downline (1/day), on-site inbox + email + if (p === '/api/my/broadcast' && req.method === 'POST') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const b = await readBody(req); + const subject = String(b.subject || '').trim().slice(0, 160); + const body = ads.sanitizeRich(b.body); + const plain = body.replace(/<[^>]*>/g, ' ').replace(/\s+/g, ' ').trim(); + if (!subject) return json(res, 400, { error: 'Give your message a subject.' }); + if (plain.length < 10) return json(res, 400, { error: 'Write a message first.' }); + const last = await messages.lastBroadcastAt(s.email); + if (Date.now() - last < 24 * 3600 * 1000) + return json(res, 429, { error: 'You can send one broadcast a day. Try again in ' + Math.ceil((24 * 3600 * 1000 - (Date.now() - last)) / 3600000) + 'h.' }); + const depth = b.scope === 'direct' ? 1 : 3; + const levels = await accounts.downline(s.email, depth); + const recipients = [...new Set(levels.flatMap(L => L.members.map(m => m.email)).filter(Boolean))]; + if (!recipients.length) return json(res, 400, { error: 'No one in your line to message yet.' }); + const memberId = s.memberId || await auth.refreshMemberId(s); + await messages.deliver(memberId, s.email, recipients, subject, body); + // email each recipient too (best-effort; never blocks the on-site delivery) + if (mailer.hasKey()) { + const who = (await accounts.byEmail(s.email)); + const from = who && who.username ? '@' + who.username : 'your sponsor'; + for (const to of recipients) { + mailer.send(to, 'Message from ' + from + ': ' + subject, + plain + '\n\n— sent via your LinkSpin upline. Read it in your dashboard: ' + SITE_URL + '/tools#line') + .catch(() => {}); + } + } + return json(res, 200, { ok: true, sent: recipients.length }); + } + // -- sponsor messages: this member's inbox from their upline + if (p === '/api/my/messages' && req.method === 'GET') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const items = await messages.inbox(s.email); + const names = await accounts.namesForMembers([...new Set(items.map(i => i.fromMember).filter(Boolean))]); + for (const i of items) i.fromName = (i.fromMember && names[i.fromMember]) ? '@' + names[i.fromMember] + : i.fromMember ? 'member #' + i.fromMember : 'your upline'; + return json(res, 200, { items, unread: items.filter(i => !i.read).length }); + } + m = /^\/api\/my\/messages\/(\d+)\/read$/.exec(p); + if (m && req.method === 'POST') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + return json(res, 200, await messages.markRead(s.email, m[1])); + } + + // ── SPONSOR CHAT (two-way): presence-aware 1:1 threads up/down the line ── + const chatOnline = ts => (Date.now() - (ts || 0)) < 60000; + const chatName = a => !a ? 'member' : (a.username ? '@' + a.username : (a.memberId ? 'member #' + a.memberId : 'member')); + // lightweight presence heartbeat (called on a timer while the dashboard is open) + if (p === '/api/my/ping' && req.method === 'GET') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 200, { ok: true, chatUnread: 0 }); + accounts.touchSeen(s.email).catch(() => {}); + return json(res, 200, { ok: true, chatUnread: await messages.chatUnread(s.email) }); + } + // training center content (admin-curated via data/training.json) + if (p === '/api/training' && req.method === 'GET') { + const s = await auth.fromRequest(req); + if (!s) return json(res, 401, { error: 'Sign in first.' }); + let items = []; + try { const j = JSON.parse(fs.readFileSync(path.join(DATA_DIR, 'training.json'), 'utf8')); if (Array.isArray(j)) items = j; } catch (e) {} + // a card with feature:'pipeline' waits for the switch, so the video can be ready before the tab opens (Marty, 2026-09-15) + const scT = siteConfig(); items = items.filter(it => !it.feature || (it.feature === 'pipeline' && pipeline.visible(scT.pipelineMode, s.email, ADMIN_EMAIL))); + if (!items.length) items = [{ title: 'Getting started with LinkSpin', + desc: 'How the platform works, how every payout splits on-chain to real wallets, and how to build your line.', + docUrl: SITE_URL + '/' }]; + return json(res, 200, { items }); + } + // daily login bonus (once/day, gentle streak) — granted after the login flow + if (p === '/api/my/login-bonus' && req.method === 'POST') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + return json(res, 200, await ads.grantLoginBonus(s.email)); + } + // -- rehearsal test-POL faucet: top a connected wallet up to 10 test-POL + // (anvil_setBalance, no key needed). Rehearsal-only, rate-limited. + if (p === '/api/my/faucet' && req.method === 'POST') { + const s = await auth.fromRequest(req); + if (!s) return json(res, 401, { error: 'Sign in first.' }); + if (!siteConfig().rehearsal) return json(res, 400, { error: 'The faucet is only open during the rehearsal.' }); + const b = await readBody(req); + const addr = String(b.address || '').trim().toLowerCase(); + if (!/^0x[0-9a-f]{40}$/.test(addr)) return json(res, 400, { error: 'Connect your wallet first.' }); + // Amoy is a public testnet: testers fund their own connected wallet from + // the public Amoy faucet (no server-minted balance). We just echo the + // address + faucet link; the client copies the address and opens it. + let balHex = '0x0'; try { balHex = await chain.rpc('eth_getBalance', [addr, 'latest']); } catch (e) {} + return json(res, 200, { ok: true, faucetUrl: 'https://faucet.polygon.technology/', address: addr, balanceWei: BigInt(balHex || '0x0').toString() }); + } + // -- report an ad (auto-approved ads need a safety valve): store + notify admin + if (p === '/api/report-ad' && req.method === 'POST') { + const b = await readBody(req); + if (!Number(b.campaignId)) return json(res, 400, { error: 'Which ad?' }); + const s = await auth.fromRequest(req); + const who = (s && s.email) || ''; + const rec = await reports.add(b.campaignId, who, b.reason, b.note); + try { + const adminEmail = process.env.ADMIN_EMAIL || ''; // private env only — siteConfig is exposed via /api/config + if (adminEmail && mailer.hasKey()) { + mailer.send(adminEmail, 'Ad reported on LinkSpin (campaign #' + rec.campaignId + ')', + 'A member flagged an ad.\n\nCampaign: #' + rec.campaignId + '\nReason: ' + rec.reason + + '\nReported by: ' + (who || 'anonymous') + '\nNote: ' + (String(b.note || '').slice(0, 500) || '(none)') + + '\n\nPause or review it from the admin.').catch(() => {}); + } + } catch (e) {} + return json(res, 200, { ok: true }); + } + if (p === '/api/my/chat/send' && req.method === 'POST') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const me = s.email.toLowerCase(); + const b = await readBody(req); + const to = String(b.to || '').trim().toLowerCase(); + const text = String(b.body || '').replace(/<[^>]*>/g, '').replace(/\s+$/, '').slice(0, 2000).trim(); + if (!to || to === me) return json(res, 400, { error: 'Pick who to message.' }); + if (!text) return json(res, 400, { error: 'Write a message first.' }); + const target = await accounts.byEmail(to); + if (!target) return json(res, 404, { error: 'No such member.' }); + // authorize: existing thread, my direct sponsor, or someone in my downline + let ok = (await messages.thread(me, to, 0, 1)).length > 0; + if (!ok) { const spon = await accounts.sponsorOf(me); ok = !!(spon && spon.email && spon.email.toLowerCase() === to); } + if (!ok) ok = await accounts.isDownlineOf(me, to); + if (!ok) return json(res, 403, { error: 'You can only message your direct sponsor or someone in your line.' }); + if ((await accounts.getMutes(to)).map(x => String(x).toLowerCase()).includes(me)) + return json(res, 403, { error: 'They are not accepting messages from you right now.' }); + const memberId = s.memberId || await auth.refreshMemberId(s); + const msg = await messages.sendChat(memberId, me, to, text); + // email only when they are offline AND I have not messaged them in ~10 min (no mid-chat spam) + try { + if (mailer.hasKey() && !chatOnline(target.lastSeen)) { + const mine = (await messages.thread(me, to, 0, 400)).filter(x => x.id !== msg.id && String(x.fromEmail).toLowerCase() === me); + const lastMineTs = mine.length ? mine[mine.length - 1].sent : 0; + if (Date.now() - lastMineTs > 10 * 60 * 1000) { + const who = await accounts.byEmail(me); + const from = who && who.username ? '@' + who.username : 'someone in your LinkSpin line'; + mailer.send(to, 'New message from ' + from, + text.slice(0, 400) + '\n\n— reply in your dashboard: ' + SITE_URL + '/tools').catch(() => {}); + } + } + } catch (e) {} + return json(res, 200, { ok: true, message: { id: msg.id, sent: msg.sent, fromMe: true, body: text } }); + } + if (p === '/api/my/chat/thread' && req.method === 'GET') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const me = s.email.toLowerCase(); + const other = String(u.searchParams.get('with') || '').trim().toLowerCase(); + const after = Number(u.searchParams.get('after')) || 0; + if (!other) return json(res, 400, { error: 'Who with?' }); + // may view a thread I'm party to (existing), or one I'm allowed to start + let ok = (await messages.thread(me, other, 0, 1)).length > 0; + if (!ok) { const spon = await accounts.sponsorOf(me); ok = !!(spon && spon.email && spon.email.toLowerCase() === other); } + if (!ok) ok = await accounts.isDownlineOf(me, other); + if (!ok) return json(res, 403, { error: 'Not your conversation.' }); + const msgs = await messages.thread(me, other, after, 300); + await messages.markChatRead(me, other); + accounts.touchSeen(me).catch(() => {}); + const oa = await accounts.byEmail(other); + const iMute = (await accounts.getMutes(me)).map(x => String(x).toLowerCase()).includes(other); + const theyMuteMe = (await accounts.getMutes(other)).map(x => String(x).toLowerCase()).includes(me); + return json(res, 200, { + messages: msgs.map(x => ({ id: x.id, fromMe: String(x.fromEmail).toLowerCase() === me, body: x.body, sent: x.sent })), + otherName: chatName(oa), online: oa ? chatOnline(oa.lastSeen) : false, + available: oa ? oa.chatAvailable !== false : true, iMute, blocked: theyMuteMe, + canMute: await accounts.isDownlineOf(me, other) }); + } + if (p === '/api/my/chat/threads' && req.method === 'GET') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const list = await messages.threadList(s.email.toLowerCase()); + for (const t of list) { + const a = await accounts.byEmail(t.email); + t.name = chatName(a); t.online = a ? chatOnline(a.lastSeen) : false; + } + list.sort((x, y) => (y.last.sent || 0) - (x.last.sent || 0)); + const meAcct = await accounts.byEmail(s.email); + return json(res, 200, { threads: list, available: meAcct ? meAcct.chatAvailable !== false : true }); + } + if (p === '/api/my/chat/available' && req.method === 'POST') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const b = await readBody(req); + return json(res, 200, await accounts.setChatAvailable(s.email, !!b.available)); + } + if (p === '/api/my/chat/mute' && req.method === 'POST') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const b = await readBody(req); + const target = String(b.email || '').trim().toLowerCase(); + if (!target) return json(res, 400, { error: 'Who?' }); + const allowed = (await accounts.isDownlineOf(s.email, target)) || (await messages.thread(s.email.toLowerCase(), target, 0, 1)).length > 0; + if (!allowed) return json(res, 403, { error: 'You can only mute someone in your line.' }); + return json(res, 200, await accounts.setMute(s.email, target, !!b.muted)); + } + // -- featured rotation: the live featured links + dilution stats + if (p === '/api/featured' && req.method === 'GET') { + const items = await ads.serveFeatured(viewerGeo(req)); + try { const sv = await auth.fromRequest(req); ads.noteFeaturedViews(items, (sv && sv.email) || clientIp(req)).catch(() => {}); } catch (e) {} // count the view (per viewer per hour) + const names = await accounts.namesForMembers([...new Set(items.map(i => i.memberId).filter(Boolean))]); + for (const i of items) i.by = (i.memberId && names[i.memberId]) ? '@' + names[i.memberId] : (i.memberId ? 'member #' + i.memberId : null); + return json(res, 200, { items }); + } + if (p === '/api/featured/stats' && req.method === 'GET') { + return json(res, 200, await ads.featuredStats()); + } + // -- QR code (SVG) for any LinkSpin URL — used on bio/wall pages + if (p === '/api/qr' && req.method === 'GET') { + const data = String(u.searchParams.get('d') || '').slice(0, 300); + if (!QR || !data) { res.writeHead(404, baseHeaders()); return res.end(); } + try { + const svg = await QR.toString(data, { type: 'svg', margin: 1, width: 240, + color: { dark: '#0e7d5f', light: '#f2fbf8' } }); // mint-green modules, still high-contrast for reliable scanning + res.writeHead(200, baseHeaders({ 'Content-Type': 'image/svg+xml', 'Cache-Control': 'public, max-age=3600' })); + return res.end(svg); + } catch (e) { res.writeHead(500, baseHeaders()); return res.end(); } + } + // -- profile: avatar + bio + if (p === '/api/my/profile-details' && req.method === 'POST') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const b = await readBody(req); + const avatar = b.avatarUrl === undefined ? undefined : String(b.avatarUrl || '').trim(); + if (avatar && !/^(\/uploads\/[a-z0-9]{24}\.(png|jpg|webp|gif)|https:\/\/[^\s]+)$/i.test(avatar)) + return json(res, 400, { error: 'Avatar must be an uploaded image or an https image URL.' }); + const bio = b.bio === undefined ? undefined : String(b.bio || '').trim().slice(0, 600); + // socials: {platform: url}; keep only known platforms with valid https urls + let socials; + if (b.socials !== undefined) { + const PLAT = ['facebook', 'twitter', 'youtube', 'instagram', 'tiktok', 'telegram', 'linkedin', 'website', 'video']; + const clean = {}; + for (const p of PLAT) { + const v = String((b.socials && b.socials[p]) || '').trim(); + if (v && /^https:\/\/[^\s]+$/i.test(v) && v.length <= 300) clean[p] = v; + } + // intro video on the public wall: a YouTube, Vimeo or direct .mp4/.webm link only + if (clean.video && !/^https:\/\/((www\.|m\.)?youtube\.com\/(watch\?|shorts\/|embed\/)|youtu\.be\/|(www\.)?vimeo\.com\/\d+|player\.vimeo\.com\/video\/\d+|[^\s]+\.(mp4|webm)(\?|$))/i.test(clean.video)) + return json(res, 400, { error: 'The intro video needs to be a YouTube link, a Vimeo link, or a direct .mp4 link.' }); + socials = Object.keys(clean).length ? JSON.stringify(clean) : null; + } + const r = await accounts.setProfile(s.email, avatar, bio, socials); + return json(res, r.error ? 400 : 200, r); + } + // -- wall positions 2 & 3: the member's own offers, unlocked at 2 / 5 qualifying buyers + if (p === '/api/my/wall-offers' && req.method === 'POST') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const b = await readBody(req); + const src = Array.isArray(b.offers) ? b.offers.slice(0, 2) : []; + const out = []; + for (let i = 0; i < 2; i++) { + const o = src[i] || {}; + const targetUrl = String(o.targetUrl || '').trim(); + const bannerUrl = String(o.bannerUrl || '').trim(); + const title = String(o.title || '').trim().slice(0, 60); + if (targetUrl && !/^https:\/\/[^\s]+$/i.test(targetUrl)) return json(res, 400, { error: 'Position ' + (i + 2) + ': the link must start with https://' }); + if (bannerUrl && !/^(\/uploads\/[a-z0-9]{24}\.(png|jpg|webp|gif)|https:\/\/[^\s]+)$/i.test(bannerUrl)) return json(res, 400, { error: 'Position ' + (i + 2) + ': banner must be an uploaded image or an https image URL.' }); + out.push(targetUrl ? { title: title || null, bannerUrl: bannerUrl || null, targetUrl } : null); + } + const r = await accounts.setWallOffers(s.email, out.some(Boolean) ? JSON.stringify(out) : null); + return json(res, r.error ? 400 : 200, r); + } + // -- line banner: the member's viral slot on welcome tours + their wall + if (p === '/api/my/linebanner' && req.method === 'POST') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const b = await readBody(req); + const target = String(b.targetUrl || '').trim(); + if (!/^https?:\/\/[^\s]+$/i.test(target)) return json(res, 400, { error: 'Destination URL must start with http(s)://' }); + const fc = await frameCheck(target); // welcome tours frame it full screen + if (!fc.ok) return json(res, 400, { error: fc.reason }); + const banner = String(b.bannerUrl || '').trim(); + if (banner && !/^(\/uploads\/[a-z0-9]{24}\.(png|jpg|webp|gif)|https:\/\/[^\s]+)$/i.test(banner)) + return json(res, 400, { error: 'Banner must be an uploaded image or an https image URL.' }); + const r = await accounts.setLineBanner(s.email, banner || null, target); + return json(res, r.error ? 400 : 200, r); + } + // -- welcome tour (gauntlet): meet the 3-level upline, then unlock welcome credits + if (p === '/api/my/gauntlet' && req.method === 'GET') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + if (await ads.welcomeGranted(s.email)) return json(res, 200, { pending: false }); + const slides = (await uplineSlides(s.email)).filter(a => a.lineTargetUrl) + .map((a, i) => ({ name: a.username ? '@' + a.username : a.memberId ? 'member #' + a.memberId : 'a member', + bannerUrl: a.lineBannerUrl || null, targetUrl: a.lineTargetUrl })); + if (!slides.length) return json(res, 200, { pending: false }); + const token = crypto.randomBytes(16).toString('hex'); + gauntletTokens.set(s.email, { token, ts: Date.now(), n: slides.length }); + return json(res, 200, { pending: true, slides, dwell: 10, token }); + } + if (p === '/api/my/gauntlet/complete' && req.method === 'POST') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const b = await readBody(req); + const t = gauntletTokens.get(s.email); + if (!t || t.token !== String(b.token || '')) return json(res, 400, { error: 'That tour is no longer open. Reload and try again.' }); + if (Date.now() - t.ts < t.n * 10 * 1000 - 1500) return json(res, 400, { error: 'Give each site its ten seconds first.' }); + gauntletTokens.delete(s.email); + await ads.grantWelcome(s.email); + return json(res, 200, { ok: true, credited: ads.rates().welcomeCredits || 0 }); + } + // -- public banner wall + m = /^\/api\/wall\/([A-Za-z0-9_]{1,20})$/.exec(p); + if (m && req.method === 'GET') { + const tok = m[1].toLowerCase(); + let a = await accounts.byUsername(tok); + if (!a) a = await accounts.byCode(tok); + if (!a) return json(res, 404, { error: 'No wall under that name.' }); + const ownName = a.username ? '@' + a.username : a.memberId ? 'member #' + a.memberId : 'a member'; + let bc = 0; + if (a.memberId) { try { bc = (await chain.member(a.memberId)).buyerCount || 0; } catch (e) {} } + const unlocked = wallUnlockedFor(bc); + const offers = parseWallOffers(a); + // uplines with a live banner, in order (an upline with nothing set is skipped, not shown empty) + const ups = (await uplineSlides(a.email, 2)).filter(x => x.lineTargetUrl) + .map(x => ({ name: x.username ? '@' + x.username : x.memberId ? 'member #' + x.memberId : 'a member', + bannerUrl: x.lineBannerUrl || null, targetUrl: x.lineTargetUrl, upline: true })); + const adAds = getAdminWallAds(); let ai = 0; + const houseAd = () => { if (!adAds.length) return null; const ad = adAds[ai++ % adAds.length]; return { name: ad.name || 'LinkSpin', bannerUrl: ad.bannerUrl || null, targetUrl: ad.targetUrl || SITE_URL + '/', admin: true }; }; + const ladder = [{ name: ownName, bannerUrl: a.lineBannerUrl || null, targetUrl: a.lineTargetUrl || null, own: true }]; + for (let i = 1; i < 3; i++) { + const o = offers[i - 1]; + if (i < unlocked && o && o.targetUrl) { ladder.push({ name: (o.title || ownName), bannerUrl: o.bannerUrl || null, targetUrl: o.targetUrl, own: true }); continue; } + const u = ups.shift(); if (u) { ladder.push(u); continue; } + const h = houseAd(); if (h) ladder.push(h); + } + const finalLadder = ladder.slice(0, 3); + // the wall owner's achievement badge (their highest reached tier) + let badge = null; + if (a.memberId) { + const t = bc >= 5 ? ['nexus', 'Nexus'] : bc >= 2 ? ['circuit', 'Circuit'] : bc >= 1 ? ['surge', 'Surge'] : ['spark', 'Spark']; + badge = { img: '/badges/badge-' + t[0] + '.jpg?v=3', label: t[1] }; + } + const joinPath = '/join/' + (a.username || a.code); + let socials = null; try { socials = a.socials ? JSON.parse(a.socials) : null; } catch (e) {} + return json(res, 200, { name: a.username ? '@' + a.username : 'member #' + (a.memberId || 0), + avatarUrl: a.avatarUrl || null, bio: a.bio || null, socials, badge, + joinUrl: joinPath, qrUrl: '/api/qr?d=' + encodeURIComponent(SITE_URL + joinPath), ladder: finalLadder, unlocked, buyerCount: bc }); + } + // -- watch-to-earn video ads: serve one, then reward a server-clock-verified watch + if (p === '/api/my/videos' && req.method === 'GET') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const status = await ads.videoStatus(s.email); + if (status.left <= 0) return json(res, 200, { ad: null, status }); + const orientation = String(u.searchParams.get('orientation') || ''); // 'portrait' = Shorts reel, 'landscape' = Watch videos tab + const ad = await ads.serveVideo(Object.assign({ excludeEmail: s.email, orientation }, viewerGeo(req))); // never your own video + if (!ad) { // distinguish "you have watched every live video today" from "nothing is live" (Marty, 2026-09-13) + let allWatched = false; try { allWatched = !!(await ads.serveVideo(Object.assign({ excludeEmail: s.email, orientation, ignoreSeen: true }, viewerGeo(req)))); } catch (e) {} + return json(res, 200, { ad: null, status, allWatched }); + } + const token = crypto.randomBytes(16).toString('hex'); + videoTokens.set(s.email, { token, ts: Date.now(), id: ad.id, secs: ad.watchSecs }); + return json(res, 200, { ad, token, status }); + } + if (p === '/api/my/videowatch' && req.method === 'POST') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const b = await readBody(req); + const t = videoTokens.get(s.email); + if (!t || t.token !== String(b.token || '')) return json(res, 400, { error: 'That video is no longer open. Load the next one.' }); + const age = Date.now() - t.ts; + if (age < t.secs * 1000 - 600) return json(res, 400, { error: 'Watch the full video first.' }); + if (age > t.secs * 1000 + 10 * 60 * 1000) { videoTokens.delete(s.email); return json(res, 400, { error: 'That watch went stale. Load a fresh video.' }); } + videoTokens.delete(s.email); // single use + if (await ads.hasWatchedVideoToday(s.email, t.id)) // once-per-day-per-video: no double earning + return json(res, 200, { ok: true, credited: 0, status: await ads.videoStatus(s.email), already: true }); + const tier = await ads.chargeVideoView(t.id); // charge advertiser; null if it ran dry + if (!tier) return json(res, 200, { ok: true, credited: 0, status: await ads.videoStatus(s.email), gone: true }); + await ads.addEarned(s.email, tier.reward); + await ads.markVideoSeen(s.email, t.id); + const status = await ads.recordVideoWatch(s.email); + return json(res, 200, { ok: true, credited: tier.reward, status }); + } + // -- verified visits: view a member's site (new tab) for the dwell, pass a + // human check, and it counts as one guaranteed unique visit for the pack + if (p === '/api/my/visits' && req.method === 'GET') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const status = await ads.visitStatus(s.email); + if (status.count >= status.cap) return json(res, 200, { ad: null, status }); + const ad = await ads.serveVisit(s.email, viewerGeo(req)); + if (!ad) return json(res, 200, { ad: null, status }); + const token = crypto.randomBytes(16).toString('hex'); + visitTokens.set(s.email, { token, ts: Date.now(), id: ad.id }); + return json(res, 200, { ad, token, status }); + } + if (p === '/api/my/visitchallenge' && req.method === 'GET') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const t = visitTokens.get(s.email); + if (!t || t.token !== String(u.searchParams.get('token') || '')) return json(res, 400, { error: 'That visit is no longer open.' }); + const dwellMs = (ads.rates().visitDwellSeconds || 8) * 1000; + const age = Date.now() - t.ts; + if (age < dwellMs - 400) return json(res, 200, { early: true, wait: Math.ceil((dwellMs - age) / 1000) }); + if (age > 5 * 60 * 1000) { visitTokens.delete(s.email); return json(res, 400, { error: 'That visit went stale. Load a fresh one.' }); } + const pick = CAPTCHA.slice().sort(() => Math.random() - 0.5).slice(0, 5); + const answer = Math.floor(Math.random() * pick.length); + t.challenge = { answer }; + return json(res, 200, { prompt: pick[answer][1], options: pick.map(x => x[0]) }); + } + if (p === '/api/my/visitdone' && req.method === 'POST') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const b = await readBody(req); + const t = visitTokens.get(s.email); + if (!t || t.token !== String(b.token || '')) return json(res, 400, { error: 'That visit did not check out. Load the next one.' }); + const dwellMs = (ads.rates().visitDwellSeconds || 8) * 1000; + if (Date.now() - t.ts < dwellMs - 400) return json(res, 400, { error: 'Give the site the full visit first.' }); + if (!t.challenge) return json(res, 400, { error: 'Finish the quick check first.', retry: true }); + if (Number(b.answer) !== t.challenge.answer) { t.challenge = null; return json(res, 400, { error: 'Wrong pick.', retry: true }); } + visitTokens.delete(s.email); + const r = await ads.completeVisit(s.email, t.id); + if (r.error) return json(res, 400, r); + return json(res, 200, Object.assign(r, { status: await ads.visitStatus(s.email) })); + } + // -- onsite solo ads: member inbox with read rewards + if (p === '/api/my/inbox' && req.method === 'GET') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const r = await ads.inboxList(s.email, viewerGeo(req)); + const names = await accounts.namesForMembers([...new Set(r.items.map(i => i.fromMemberId).filter(Boolean))]); + for (const i of r.items) i.fromName = (i.fromMemberId && names[i.fromMemberId]) ? '@' + names[i.fromMemberId] + : i.fromMemberId ? 'member #' + i.fromMemberId : 'a member'; + return json(res, 200, r); + } + m = /^\/api\/my\/inbox\/(\d+)$/.exec(p); + if (m && req.method === 'GET') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const r = await ads.inboxOpen(s.email, m[1]); + if (!r.error) { + const names = r.fromMemberId ? await accounts.namesForMembers([r.fromMemberId]) : {}; + r.fromName = (r.fromMemberId && names[r.fromMemberId]) ? '@' + names[r.fromMemberId] + : r.fromMemberId ? 'member #' + r.fromMemberId : 'a member'; + } + return json(res, r.error ? 404 : 200, r); + } + // media upload for solo ads: raw body, size-capped, magic-byte verified + if (p === '/api/my/upload' && req.method === 'POST') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + return handleUpload(req, res, s.email); + } + m = /^\/api\/my\/inbox\/(\d+)\/visit$/.exec(p); + if (m && req.method === 'POST') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const r = await ads.markSoloVisit(s.email, m[1]); + return json(res, r.error ? 400 : 200, r); + } + m = /^\/api\/my\/inbox\/(\d+)\/claim$/.exec(p); + if (m && req.method === 'POST') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const r = await ads.claimSoloRead(s.email, m[1]); + return json(res, r.error ? 400 : 200, r); + } + if (p === '/api/my/activity' && req.method === 'GET') { + const s = await auth.fromRequest(req); + if (!s) return json(res, 401, { error: 'Sign in first.' }); + const id = s.memberId || await auth.refreshMemberId(s); + if (!id) return json(res, 200, { memberId: 0, earnings: [], purchases: [], referrals: [] }); + const evs = chain.recentEvents(600); + return json(res, 200, { + memberId: id, + earnings: await attachNames(evs.filter(e => (e.type === 'TierPaid' && e.recipientId === id) || (e.type === 'AwardPaid' && e.toId === id))), + purchases: await attachNames(evs.filter(e => e.type === 'Purchase' && e.buyerId === id)), + referrals: await attachNames(evs.filter(e => (e.type === 'MemberActivated' && e.sponsorId === id) || (e.type === 'BuyerCounted' && e.sponsorId === id))) + }); + } + + // -- ad engine (spec §8b v1: banners, text, login ads) + if (p === '/api/ads/slot' && req.method === 'GET') { + const t = String(u.searchParams.get('type') || 'banner'); + const ad = await ads.serve(t, Object.assign({ width: Number(u.searchParams.get('w')) || 0, height: Number(u.searchParams.get('h')) || 0 }, viewerGeo(req), audiences.matcher(req))); + // login ads: the member clicks "Open Ad" (a real, counted click into a + // new tab) while the countdown runs on our interstitial page + if (ad && t === 'login') ad.dwell = ads.rates().loginDwellSeconds || 10; + return json(res, 200, { ad }); + } + m = /^\/api\/ads\/click\/(\d+)$/.exec(p); + if (m && req.method === 'GET') { + const target = await ads.click(m[1]); + if (!target) { res.writeHead(404, baseHeaders()); return res.end(); } + coach.recordClick(m[1], req.headers.referer); // where the click happened + res.writeHead(302, baseHeaders({ Location: target })); + return res.end(); + } + if (p === '/api/my/audiences' && req.method === 'GET') { + const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + return json(res, 200, { audiences: audiences.list(s.email), host: SITE_HOST }); + } + if (p === '/api/my/audiences' && req.method === 'POST') { + const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const b = await readBody(req); + const r = b.remove ? audiences.remove(s.email, b.id) : b.id ? audiences.rename(s.email, b.id, b.name) : audiences.create(s.email, b.name); + return json(res, r.error ? 400 : 200, r); + } + if (p === '/api/my/campaigns' && req.method === 'GET') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const memberId = await auth.refreshMemberId(s); + // welcome credits used to unlock only through the classic dashboard; the Control Room Ads screen grants them the same way (2026-09-29) + let gauntletPending = false; + if (!(await ads.welcomeGranted(s.email))) { const tour = (await uplineSlides(s.email)).filter(a => a.lineTargetUrl); if (!tour.length) await ads.grantWelcome(s.email); else gauntletPending = true; } + const out = { campaigns: await ads.listCampaigns(s.email), rates: ads.rates(), bannerSizes: ads.bannerSizes(), gauntletPending, audiences: audiences.list(s.email) }; + out.clickSources = await coach.clickSources(out.campaigns.map(c => c.id)); + out.hours = await ads.hoursFor(out.campaigns.map(c => c.id)); // on-site views per UTC hour, last 7 days + out.geo = await ads.geoFor(out.campaigns.map(c => c.id)); // on-site serves per viewer country + { const t = geo.tierLists(siteConfig()); out.tiers = { t1: [...t.t1], t2: [...t.t2] }; out.geoReady = geo.status().loaded; } + const pool = await ads.balances((await myMemberIds(s)).ids, s.email); + out.purchasedCredits = pool.total; + out.largestPosition = pool.best.avail; // a single campaign budget has to fit one position + out.positionCount = pool.per.length; + out.creditedCredits = pool.credited; // refunded/credited purchased money, free (counts inside purchasedCredits) + out.earnedCredits = pool.earned; // earned pool minus what live campaigns already hold + out.earnedReserved = pool.earnedReserved; + out.inCampaigns = pool.inCampaigns; // budget still to deliver across live campaigns + out.availableCredits = pool.available; + return json(res, 200, out); + } + if (p === '/api/my/campaigns' && req.method === 'POST') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const memberId = await auth.refreshMemberId(s); // 0 is fine: earned credits fund banner/text + const b = await readBody(req); + if (!MEMBER_AD_TYPES.includes(String(b.type || ''))) return json(res, 400, { error: 'LinkSpin runs banner, text and login ads.' }); + if (b.audience && !audiences.owns(s.email, b.audience)) return json(res, 400, { error: 'That audience is not one of yours.' }); // Marty 2026-09-29: the three formats members buy + if (!['login', 'solo', 'video', 'featured'].includes(String(b.type || ''))) { // banner/text surf views frame the target; login/video/solo/featured open in a new tab or play in our own player + const fc = await frameCheck(b.targetUrl); + if (!fc.ok) return json(res, 400, { error: fc.reason }); + } + // charge the best-funded of the member's positions (main + Qualified Start + // wallets). A campaign burns from one member id, so the budget must fit inside it. + const ids = (await myMemberIds(s)).ids; + const pool = await ads.balances(ids, s.email); + const fundId = pool.best.memberId || memberId; + const earnedNow = String(b.type) !== 'login' ? pool.earned : 0; + const budget = Math.floor(Number(b.budget) || 0); + if (pool.per.length > 1 && budget > pool.best.avail + pool.credited + earnedNow && budget <= pool.total + earnedNow) + return json(res, 400, { error: 'Your credits are spread across ' + pool.per.length + ' positions and one campaign spends from one of them. The largest single position holds ' + pool.best.avail + ' credits: set the budget to that or less, or run two campaigns.' }); + const r = await ads.createCampaign(s.email, fundId, b, ids); + return json(res, r.error ? 400 : 200, r); + } + m = /^\/api\/my\/campaigns\/(\d+)\/topup$/.exec(p); + if (m && req.method === 'POST') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const memberId = await auth.refreshMemberId(s); + const b = await readBody(req); + const r = await ads.topUpCampaign(s.email, memberId, m[1], b.credits); + return json(res, r.error ? 400 : 200, r); + } + m = /^\/api\/my\/campaigns\/(\d+)\/(pause|resume)$/.exec(p); + if (m && req.method === 'POST') { + const s = await auth.fromRequest(req); + if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); + const r = await ads.setStatus(s.email, m[1], m[2] === 'pause' ? 'paused' : 'active'); + return json(res, r.error ? 400 : 200, r); + } + + // -- admin portal: email magic-code sign-in, allowlisted to ADMIN_EMAIL + if (p === '/api/admin/auth/start' && req.method === 'POST') { + const b = await readBody(req); + const e = String(b.email || '').trim().toLowerCase(); + if (!ADMIN_EMAIL) return json(res, 503, { error: 'ADMIN_EMAIL is not set on the server.' }); + if (!e || e !== ADMIN_EMAIL) return json(res, 403, { error: 'That address is not the admin.' }); + const k = 'admin:' + e; + const prev = emailCodes.get(k); + if (prev && Date.now() < prev.nextAt) return json(res, 429, { error: 'Code already sent. Give it a minute, then try again.' }); + const code = String(Math.floor(100000 + Math.random() * 900000)); + emailCodes.set(k, { code, exp: Date.now() + 15 * 60 * 1000, tries: 0, nextAt: Date.now() + 60 * 1000 }); + if (mailer.hasKey()) { + try { await mailer.sendCode(e, code); } catch (err) { + console.error('admin sendCode failed', err.message); + return json(res, 502, { error: 'Could not send the email. Try again in a minute.' }); + } + return json(res, 200, { ok: true, sent: true }); + } + if (!IS_PROD) return json(res, 200, { ok: true, sent: false, devCode: code }); + return json(res, 503, { error: 'Email sign-in is not configured yet.' }); + } + if (p === '/api/admin/auth/verify' && req.method === 'POST') { + const b = await readBody(req); + const e = String(b.email || '').trim().toLowerCase(); + const k = 'admin:' + e; + const rec = emailCodes.get(k); + if (!rec || rec.exp < Date.now()) return json(res, 400, { error: 'Code expired. Request a fresh one.' }); + rec.tries += 1; + if (rec.tries > 6) { emailCodes.delete(k); return json(res, 400, { error: 'Too many tries. Request a fresh code.' }); } + if (String(b.code || '').trim() !== rec.code) return json(res, 400, { error: 'That code does not match.' }); + emailCodes.delete(k); + if (e !== ADMIN_EMAIL) return json(res, 403, { error: 'That address is not the admin.' }); + const token = mintAdminSession(e); + return json(res, 200, { ok: true, email: e }, { 'Set-Cookie': adminCookie(token) }); + } + if (p === '/api/admin/auth/logout' && req.method === 'POST') { + dropAdminSession(req); + return json(res, 200, { ok: true }, { 'Set-Cookie': clearAdminCookie() }); + } + if (p === '/api/admin/me' && req.method === 'GET') { + if (!isAdmin(req)) return json(res, 200, { admin: false }); + return json(res, 200, { admin: true, email: ADMIN_EMAIL }); + } + if (p === '/api/admin/overview' && req.method === 'GET') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + const camps = await ads.adminList(); + const byStatus = {}, byType = {}; + for (const c of camps) { byStatus[c.status] = (byStatus[c.status] || 0) + 1; byType[c.type] = (byType[c.type] || 0) + 1; } + let memberCount = null; try { memberCount = await chain.memberCount(); } catch (e) {} + const cc = chain.getConfig(); + return json(res, 200, { accounts: await accounts.count(), memberCount, campaigns: camps.length, + house: camps.filter(c => c.house).length, byStatus, byType, + openReports: await reports.openCount(), pendingBurns: (await ads.pendingBurns()).length, + followups: await drip.stats(), + chain: { contract: cc.contract, chainId: cc.chainId, chainName: cc.chainName, explorer: cc.explorer }, + site: siteConfig(), rates: ads.rates() }); + } + if (p === '/api/admin/members' && req.method === 'GET') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + const members = await accounts.listAll(500); + // resolve each sponsor token (username, share code or member #) to the sponsor's name + const byTok = {}; + for (const m of members) for (const t of [m.username, m.code, m.memberId ? String(m.memberId) : null]) if (t) byTok[String(t).toLowerCase()] = m; + for (const m of members) { + const t = String(m.sponsorRef || '').toLowerCase(); + const sp = t ? byTok[t] : null; + m.sponsorName = sp ? (sp.username ? '@' + sp.username : (sp.memberId ? 'member #' + sp.memberId : sp.email)) : null; + m.sponsorVia = sp ? (t === String(sp.username || '').toLowerCase() ? 'username' : t === String(sp.code || '').toLowerCase() ? 'code' : 'member #') : (t ? 'unresolved' : ''); + } + for (const m of members) { try { const ps = await accounts.positions(m.email); m.positions = ps.length; m.positionIds = ps.map(p => p.memberId).filter(Boolean); } catch (e) { m.positions = 0; } } + return json(res, 200, { members }); + } + if (p === '/api/admin/members' && req.method === 'PATCH') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + const b = await readBody(req); + if (!b.email) return json(res, 400, { error: 'Which member?' }); + const r = await accounts.setSponsorRef(b.email, b.sponsorRef); + return json(res, r.error ? 400 : 200, r); + } + if (p === '/api/admin/campaigns' && req.method === 'GET') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + return json(res, 200, { campaigns: await ads.adminList(), rates: ads.rates(), bannerSizes: ads.bannerSizes(), houseOwner: ads.HOUSE_OWNER }); + } + if (p === '/api/admin/campaigns' && req.method === 'POST') { // free house ad + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + const b = await readBody(req); + if (!['login', 'solo', 'video', 'featured'].includes(String(b.type || ''))) { + const fc = await frameCheck(b.targetUrl); + if (!fc.ok) return json(res, 400, { error: fc.reason }); + } + const r = await ads.createHouseCampaign(b); + return json(res, r.error ? 400 : 200, r); + } + m = /^\/api\/admin\/campaigns\/(\d+)\/(pause|resume)$/.exec(p); + if (m && req.method === 'POST') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + const r = await ads.adminSetStatus(m[1], m[2] === 'pause' ? 'paused' : 'active'); + return json(res, r.error ? 400 : 200, r); + } + if (p === '/api/admin/audit' && req.method === 'GET') { // counters reconciled against delivery logs + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + return json(res, 200, await audit.run()); + } + if (p === '/api/admin/reports' && req.method === 'GET') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + return json(res, 200, { reports: await reports.list(200) }); + } + m = /^\/api\/admin\/reports\/(\d+)\/resolve$/.exec(p); + if (m && req.method === 'POST') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + return json(res, 200, await reports.resolve(m[1])); + } + if (p === '/api/admin/upload' && req.method === 'POST') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + return handleUpload(req, res, 'admin'); + } + if (p === '/api/admin/rates' && req.method === 'GET') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + return json(res, 200, { rates: ads.rates() }); + } + if (p === '/api/admin/drip' && req.method === 'GET') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + return json(res, 200, { sequence: drip.sequence(), defaults: drip.DEFAULT_SEQUENCE, stats: await drip.stats(), mailReady: mailer.hasKey() }); + } + if (p === '/api/admin/drip' && req.method === 'PATCH') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + const b = await readBody(req); + const r = b.reset ? drip.resetSequence() : drip.setSequence(b.sequence); + return json(res, r.error ? 400 : 200, r); + } + if (p === '/api/admin/drip/test' && req.method === 'POST') { // send one step to the admin inbox + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + const b = await readBody(req); + if (!ADMIN_EMAIL) return json(res, 400, { error: 'ADMIN_EMAIL is not set.' }); + if (!mailer.hasKey()) return json(res, 400, { error: 'No mail key on the server.' }); + try { const r = await drip.sendStep(ADMIN_EMAIL, Number(b.step) || 0, ADMIN_EMAIL); return json(res, r.error ? 400 : 200, r); } + catch (e) { return json(res, 502, { error: 'Send failed: ' + e.message }); } + } + // wall fallback ads: shown in wall positions a member has not earned or filled, when no upline banner exists + if (p === '/api/admin/wall-ads' && req.method === 'GET') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + let saved = null; try { saved = JSON.parse(fs.readFileSync(path.join(DATA_DIR, 'admin-wall-ads.json'), 'utf8')); } catch (e) {} + return json(res, 200, { ads: Array.isArray(saved) ? saved : [], defaults: getAdminWallAds(), usingDefaults: !Array.isArray(saved) || !saved.length }); + } + if (p === '/api/admin/wall-ads' && req.method === 'PATCH') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + const b = await readBody(req); + const src = Array.isArray(b.ads) ? b.ads.slice(0, 20) : []; + const out = []; + for (const o of src) { + const name = String((o && o.name) || '').trim().slice(0, 60); + const targetUrl = String((o && o.targetUrl) || '').trim(); + const bannerUrl = String((o && o.bannerUrl) || '').trim(); + if (!targetUrl) continue; + if (!/^https:\/\/[^\s]+$/i.test(targetUrl)) return json(res, 400, { error: 'Every wall ad needs an https:// link (' + (name || targetUrl) + ').' }); + if (bannerUrl && !/^(\/uploads\/[a-z0-9]{24}\.(png|jpg|webp|gif)|https:\/\/[^\s]+)$/i.test(bannerUrl)) return json(res, 400, { error: 'Banner must be an uploaded image or an https image URL (' + (name || targetUrl) + ').' }); + out.push({ name: name || 'LinkSpin', targetUrl, bannerUrl: bannerUrl || null }); + } + const file = path.join(DATA_DIR, 'admin-wall-ads.json'); + if (out.length) fs.writeFileSync(file, JSON.stringify(out, null, 2)); else { try { fs.unlinkSync(file); } catch (e) {} } + return json(res, 200, { ok: true, ads: out, usingDefaults: !out.length }); + } + // -- growth snapshot: preview the post, or send it now + if (p === '/api/admin/snapshot' && req.method === 'GET') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + return json(res, 200, { text: await snapshot.preview() }); + } + if (p === '/api/admin/snapshot/send' && req.method === 'POST') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + const r = await snapshot.post(); return json(res, r.error ? 400 : 200, r); + } + if (p === '/api/admin/site' && req.method === 'GET') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + return json(res, 200, { site: siteConfig() }); + } + // -- profit and loss from the chain index: volume, platform fees, member payouts, + // pass-ups, per period (by block: ~43,200 Polygon blocks a day), plus the fee + // wallets' live balances and an admin-entered fixed monthly cost + if (p === '/api/admin/pnl' && req.method === 'GET') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + const days = Math.max(0, Number(u.searchParams.get('days') || 30)); + let latest = 0; try { latest = parseInt(await chain.rpc('eth_blockNumber', []), 16); } catch (e) {} + const fromBlock = days ? latest - Math.round(days * 43200) : 0; + const evs = chain.recentEvents(1e9).filter(e => !days || e.block >= fromBlock); + const sum = (list, f) => list.reduce((n, e) => n + BigInt(f(e) || '0'), 0n); + const purchases = evs.filter(e => e.type === 'Purchase'); + const tier = evs.filter(e => e.type === 'TierPaid'); + const admin = evs.filter(e => e.type === 'AdminPaid'); + const passed = evs.filter(e => e.type === 'PassedUp'); + const byTier = {}; + for (const t of [1, 2, 3]) byTier[t] = sum(tier.filter(e => e.tier === t), e => e.amountWei).toString(); + const byPkg = {}; + for (const e of purchases) { const k = '$' + Math.round(e.priceCents / 100); byPkg[k] = (byPkg[k] || 0) + 1; } + let polUsd = 0; try { const cat = await chain.catalog(); const pk = (cat.products || cat).find(x => x.costWei); if (pk) polUsd = (pk.priceCents / 100) / (Number(BigInt(pk.costWei)) / 1e18); } catch (e) {} + const wallets = { feeA: '0x7627fc78876948ac9d95c1c9eb061e7d6d647b70', feeB: '0x8b7d33849a2c4d92c985be31e46dc564ba901ad2', engine: burner.status().address || null }; + const balances = {}; + for (const [k, a] of Object.entries(wallets)) { if (!a) continue; try { balances[k] = BigInt(await chain.rpc('eth_getBalance', [a, 'latest'])).toString(); } catch (e) { balances[k] = null; } } + return json(res, 200, { days, fromBlock, latest, polUsd, + purchases: { count: purchases.length, volumeWei: sum(purchases, e => e.paidWei).toString(), usdCents: purchases.reduce((n, e) => n + (e.priceCents || 0), 0), byPackage: byPkg }, + platformWei: sum(admin, e => e.amountWei).toString(), memberPayoutsWei: sum(tier, e => e.amountWei).toString(), byTier, + passedUp: { count: passed.length, unqualified: passed.filter(e => e.reason === 'unqualified').length, sendFailed: passed.filter(e => e.reason === 'send-failed').length }, + wallets, balances, fixedMonthlyUsd: Number(siteConfig().pnlFixedMonthlyUsd) || 0, burner: burner.status() }); + } + if (p === '/api/admin/burner' && req.method === 'GET') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + return json(res, 200, burner.status()); + } + if (p === '/api/admin/burner/run' && req.method === 'POST') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + return json(res, 200, await burner.tick()); + } + + // -- admin (Bearer ADMIN_PASSWORD, or the /admin portal session) + if (p === '/api/admin/burns' && req.method === 'GET') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + return json(res, 200, { pending: await ads.pendingBurns() }); + } + if (p === '/api/admin/burns/mark' && req.method === 'POST') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + const b = await readBody(req); + const r = await ads.markBurned(b.id, b.tx); + return json(res, r.error ? 400 : 200, r); + } + if (p === '/api/admin/rates' && req.method === 'PATCH') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + const b = await readBody(req); + return json(res, 200, { ok: true, rates: ads.setRates(b) }); + } + + if (p === '/api/admin/site' && req.method === 'PATCH') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + const b = await readBody(req); + const cur = siteConfig(); + fs.writeFileSync(SITE_FILE, JSON.stringify(Object.assign(cur, b), null, 2)); + return json(res, 200, { ok: true, site: siteConfig() }); + } + if (p === '/api/admin/chain' && req.method === 'PATCH') { + if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); + const b = await readBody(req); + const file = path.join(DATA_DIR, 'config.json'); + let cur = {}; try { cur = JSON.parse(fs.readFileSync(file, 'utf8')); } catch (e) {} + fs.writeFileSync(file, JSON.stringify(Object.assign(cur, b), null, 2)); + chain.reloadConfig(); + return json(res, 200, { ok: true, config: chain.getConfig() }); + } + + // -- pages (HEAD answered like GET so link previewers and crawlers see 200; Node drops the body) + if (req.method === 'GET' || req.method === 'HEAD') { + if (p === '/') return sendFile(res, path.join(PUBLIC_DIR, 'index.html')); + if (p === '/ledger') return sendFile(res, path.join(PUBLIC_DIR, 'ledger.html')); + if (p === '/contract') return sendFile(res, path.join(PUBLIC_DIR, 'contract.html')); + if (p === '/terms') return sendFile(res, path.join(PUBLIC_DIR, 'terms.html')); + if (p === '/privacy') return sendFile(res, path.join(PUBLIC_DIR, 'privacy.html')); + if (p === '/disclaimer') return sendFile(res, path.join(PUBLIC_DIR, 'disclaimer.html')); + if (p === '/tools') return sendFile(res, path.join(PUBLIC_DIR, 'my.html')); // classic panes the control room lacks (More) + if (p === '/my') { // retired 2026-10-08: old links/emails/bookmarks land on the right control-room screen by #pane + res.writeHead(200, baseHeaders({ 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store' })); + return res.end('LinkSpin'); + } + if (p === '/links') return sendFile(res, path.join(PUBLIC_DIR, 'links.html')); // Control Room: the links workspace, first screen of the new front end (2026-09-29) + if (p === '/reports') return sendFile(res, path.join(PUBLIC_DIR, 'reports.html')); + if (p === '/pages') return sendFile(res, path.join(PUBLIC_DIR, 'pages.html')); + if (p === '/zones') return sendFile(res, path.join(PUBLIC_DIR, 'zones.html')); + if (p === '/sources') return sendFile(res, path.join(PUBLIC_DIR, 'sources.html')); // Control Room: traffic sources, network macros + postbacks (2026-10-12) + if (p === '/ads') return sendFile(res, path.join(PUBLIC_DIR, 'ads.html')); + if (p === '/team') return sendFile(res, path.join(PUBLIC_DIR, 'team.html')); + if (p === '/wallet') return sendFile(res, path.join(PUBLIC_DIR, 'wallet.html')); + if (p === '/credits') return sendFile(res, path.join(PUBLIC_DIR, 'credits.html')); // Control Room: buy packages, link wallet, payouts on (2026-10-07) + if (p === '/join') return serveJoinPage(res, '', '', null, []); // bare join: sponsor from the cookie if any (home-page CTAs) + if (p === '/admin') return sendFile(res, path.join(PUBLIC_DIR, 'admin.html')); + if (p === '/shorts') return sendFile(res, path.join(PUBLIC_DIR, 'shorts.html')); + if (p === '/plays') return sendFile(res, path.join(PUBLIC_DIR, 'plays.html')); + if (p === '/partners') return sendFile(res, path.join(PUBLIC_DIR, 'partners.html')); // site-owner kit (Marty, 2026-09-12) + if (p === '/earning') return sendFile(res, path.join(PUBLIC_DIR, 'earning.html')); // member guide: how earning works (2026-09-12) + // -- badge share page + image: /b// (OG preview = the member's composed badge) (Marty, 2026-09-13) + m = /^\/badge-img\/([a-z0-9_]{3,20})\/(payouts|firstBuyer|level2|level3)\.jpg$/.exec(p); + if (m) return sendFile(res, path.join(UPLOADS_DIR, 'badge-' + m[1] + '-' + m[2] + '.jpg')); + m = /^\/b\/([a-z0-9_]{3,20})\/(payouts|firstBuyer|level2|level3)$/i.exec(p); + if (m) { + const un = m[1].toLowerCase(), key = m[2]; + const a = await accounts.byUsername(un); + const file = path.join(UPLOADS_DIR, 'badge-' + un + '-' + key + '.jpg'); + if (!a || !fs.existsSync(file) || !(await ads.milestonesOf(a.email)).includes(key)) { res.writeHead(404, baseHeaders({ 'Content-Type': 'text/plain' })); return res.end('Not found'); } + const [label, sub] = BADGE_META[key]; + const esc = t => String(t || '').replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c])); + const url = SITE_URL + '/b/' + un + '/' + key, img = SITE_URL + '/badge-img/' + un + '/' + key + '.jpg'; + const title = '@' + un + ' unlocked ' + label + ' on LinkSpin'; + const desc = label + ': ' + sub + '. LinkSpin pays sponsors in the same transaction, on-chain. Join @' + un + '\u2019s line free.'; + const html = '' + esc(title) + '' + + '' + + '' + + '' + + '' + + '' + + '
' + esc(label) + ' badge for @' + esc(un) + '

@' + esc(un) + ' unlocked ' + label + '

' + esc(sub.charAt(0).toUpperCase() + sub.slice(1)) + '. On LinkSpin every ad package that sells pays the sponsor in the same transaction, straight to their wallet, on-chain.

' + + 'Join @' + esc(un) + '\u2019s line free

Advertising with a performance referral program. Not an investment; no income is guaranteed.

' + + ''; + res.writeHead(200, baseHeaders({ 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'public, max-age=300' })); + return res.end(html); + } + // -- blog: server-rendered so crawlers get real HTML + metadata (Marty, 2026-09-12) + if (p === '/blog' || p === '/blog/' || /^\/blog\/page\/\d+$/.test(p) || /^\/blog\/tag\/[^/]+$/.test(p)) { + const posts = await blog.listPublished(); + const pg = (m = /^\/blog\/page\/(\d+)$/.exec(p)) ? Number(m[1]) : 1; + const tag = (m = /^\/blog\/tag\/([^/]+)$/.exec(p)) ? decodeURIComponent(m[1]).toLowerCase() : null; + res.writeHead(200, baseHeaders({ 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'public, max-age=300' })); + return res.end(blog.renderIndex(posts, pg, tag)); + } + m = /^\/handout\/([a-z0-9_]{3,20})$/i.exec(p); + if (m) { const h = await toolkit.handout(m[1].toLowerCase()); if (!h) { res.writeHead(404, baseHeaders({ 'Content-Type': 'text/plain' })); return res.end('Not found'); } res.writeHead(200, baseHeaders({ 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-cache' })); return res.end(h); } + if (p === '/leaderboard') { res.writeHead(200, baseHeaders({ 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'public, max-age=60' })); return res.end(await leaderboard.renderPage()); } + if (p === '/whats-new') { res.writeHead(200, baseHeaders({ 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'public, max-age=120' })); return res.end(releases.renderPage()); } + if (p === '/blog/feed.xml') { res.writeHead(200, baseHeaders({ 'Content-Type': 'application/rss+xml; charset=utf-8', 'Cache-Control': 'public, max-age=900' })); return res.end(blog.rss(await blog.listPublished())); } + if (p === '/sitemap.xml') { res.writeHead(200, baseHeaders({ 'Content-Type': 'application/xml; charset=utf-8', 'Cache-Control': 'public, max-age=3600' })); return res.end(blog.sitemap(await blog.listPublished())); } + if (p === '/robots.txt') { res.writeHead(200, baseHeaders({ 'Content-Type': 'text/plain; charset=utf-8', 'Cache-Control': 'public, max-age=3600' })); return res.end(blog.robots()); } + m = /^\/blog\/([a-z0-9-]{1,80})$/.exec(p); + if (m) { + const post = await blog.get(m[1]); + const preview = !!(post && post.status !== 'published' && isAdmin(req)); // admins can open a draft at its real URL + if (!post || (post.status !== 'published' && !preview)) { res.writeHead(404, baseHeaders({ 'Content-Type': 'text/html; charset=utf-8' })); return res.end(blog.renderIndex(await blog.listPublished(), 1, null).replace('', '<title>Not found | ')); } + if (!preview && req.method === 'GET') blog.bumpViews(post.slug); + const related = blog.relatedFor(post, await blog.listPublished()); + res.writeHead(200, baseHeaders({ 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': preview ? 'no-store' : 'public, max-age=300' })); + return res.end(blog.renderPost(post, related)); + } + if (p === '/wallets') return sendFile(res, path.join(PUBLIC_DIR, 'wallets.html')); + if (p === '/launch') return sendFile(res, path.join(PUBLIC_DIR, 'launch.html')); + if (/^\/view\/[a-f0-9]{32}$/.test(p)) return sendFile(res, path.join(PUBLIC_DIR, 'view.html')); + m = /^\/uploads\/([a-z0-9]{24}\.(?:png|jpg|webp|gif|mp4|webm))$/.exec(p); + if (m) return sendFile(res, path.join(UPLOADS_DIR, m[1])); + if (/^\/tx\/0x[0-9a-fA-F]{64}$/.test(p)) return sendFile(res, path.join(PUBLIC_DIR, 'tx.html')); + m = /^\/wall\/([A-Za-z0-9_]{1,20})$/.exec(p); + if (m) { // server-inject per-member OG tags so shared bio links preview correctly (crawlers don't run JS) + try { + const tok = m[1].toLowerCase(); + let a = await accounts.byUsername(tok); if (!a) a = await accounts.byCode(tok); + let html = fs.readFileSync(path.join(PUBLIC_DIR, 'wall.html'), 'utf8'); + if (a) { + const nm = a.username ? '@' + a.username : 'member #' + (a.memberId || 0); + const esc = t => String(t || '').replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c])); + const title = nm + ' on LinkSpin'; + const desc = a.bio ? esc(a.bio).slice(0, 200) : 'Join ' + nm + '’s line on LinkSpin — instant on-chain ad payouts, free to join.'; + const img = a.avatarUrl && /^https:/.test(a.avatarUrl) ? a.avatarUrl : SITE_URL + '/banners/linkspin-og-1200x630.png'; + const url = SITE_URL + '/wall/' + (a.username || a.code); + const og = [ + '<meta property="og:type" content="profile">', + '<meta property="og:site_name" content="LinkSpin">', + '<meta property="og:url" content="' + url + '">', + '<meta property="og:title" content="' + esc(title) + '">', + '<meta property="og:description" content="' + desc + '">', + '<meta property="og:image" content="' + esc(img) + '">', + '<meta name="twitter:card" content="summary_large_image">', + '<meta name="twitter:title" content="' + esc(title) + '">', + '<meta name="twitter:description" content="' + desc + '">', + '<meta name="twitter:image" content="' + esc(img) + '">', + '<meta name="description" content="' + desc + '">', + '<link rel="canonical" href="' + url + '">' + ].join('\n'); + html = html.replace('<title>Banner wall | LinkSpin', '' + esc(title) + '').replace('', og); + } + res.writeHead(200, baseHeaders({ 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-cache' })); + return res.end(html); + } catch (e) { return sendFile(res, path.join(PUBLIC_DIR, 'wall.html')); } + } + const safe = path.normalize(p).replace(/^([.\\/])+/, ''); + const file = path.join(PUBLIC_DIR, safe); + if (file.startsWith(PUBLIC_DIR) && fs.existsSync(file) && fs.statSync(file).isFile()) return sendFile(res, file); + } + + res.writeHead(404, baseHeaders({ 'Content-Type': 'text/plain' })); + res.end('Not found'); + } catch (e) { + console.error('request error', req.url, e.message); + try { json(res, 500, { error: 'server error' }); } catch (_) {} + } +}); +boot().then(() => { + server.listen(PORT, () => console.log(`LinkSpin site on :${PORT} — chain: ${chain.getConfig().chainName} — store: ${db.enabled() ? 'MySQL' : 'volume JSON'}` + + ` — outbound mail: ${OUTBOUND_MAIL ? 'ON' : 'OFF'} — sign-ups: ${SIGNUPS_OPEN ? 'open' : 'CLOSED'}`)); +}).catch(e => { console.error('boot failed:', e.message); process.exit(1); });