Files
vbb/server.js
T
martbost fb45fcddca Network hub hook (Marty 2026-11-16): sign out everywhere, hub blocks and erases end sessions here; "Sign out everywhere" button
hubevents.js (new, byte-identical in VBB, DLB, ViralAdBlitz, DownlineHydra, 5xYourTeam): POST /api/hub/events, signed by the hub
with HUB_SECRET (same hook InstantAdPay and LinkSpin take). member.signedout and member.blocked: the person is looked up by hub id
(/v1/resolve, signed as vbb) and their sessions here end (by the main wallet or any contract wallet). member.erased: matched by the wallet SHA-256s
(and email SHA-256) the hub now sends with the event. Only sessions made before the event end (a replay never signs anyone out
twice); a failed hub lookup answers 503 so the hub resends. Off with HUB_HOOK=0. Admin status: hubEvents (counts only).
My Banners: "Sign out everywhere" next to Sign out (POST /api/auth/logout-everywhere -> networksso.signOutEverywhere, then every
session of this member here ends).
Smoke: section 16 (refused signatures, signedout in two browsers, replay, older event, blocked, erased by wallet hash, other events, hub down -> 503 -> resent, Sign out everywhere, admin view): 322/322 with UI. my.js?v=5.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 05:05:35 -06:00

693 lines
59 KiB
JavaScript

// Viral Banner Blitz web app (viralbannerblitz.com rebuild, "VBB"). Plain Node http server, no framework (the InstantAdPay and
// Downline Banners pattern). Purchases are live through VBBShop (2026-11-14): POST /api/my/order builds the member's buy() call
// (with a fresh sponsor voucher when the hub knows their sponsor), the member's wallet sends it, the purchase watcher (shop.js)
// credits packs and banner looks. Weekly prize payouts: prize.js (prepared automatically, paid only on an admin's approval).
// Pages: / (splash: the loop, the next-shift bar, the queue), /my (My Banners), /leaders, /how, /packages, /admin.
// Engine: loop.js. Data: store.js on docstore.js (MySQL when DOCSTORE_URL is set). Checks: safety.js. Network sign-in: networksso.js.
'use strict';
const http = require('http');
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const { verifyMessage, getAddress } = require('ethers');
const cfgMod = require('./config');
const C = cfgMod.get();
fs.mkdirSync(path.join(C.dataDir, 'uploads'), { recursive: true });
const docstore = require('./docstore'); docstore.install(C.dataDir); // before any module reads data
const store = require('./store');
const loop = require('./loop');
const safety = require('./safety');
const networksso = require('./networksso');
const shop = require('./shop');
const promokit = require('./promokit'); // promo kit feed /api/promo-kit + the /promote page (2026-11-14)
const chatbot = require('./chatbot'); // the site assistant (2026-11-15): chatcore.js + kb.js + the network knowledge base (netkb.js)
const hubreport = require('./hubreport'); // network hub report by wallet (off unless HUB_ENABLED)
const prize = require('./prize');
const proof = require('./proof'); // trust pack: /ledger, /contract, Telegram card per purchase + line per prize payout (2026-11-14)
const netsites = require('./netsites'); // footer network list from the hub (2026-11-14)
const lsspins = require('./lsspins'); // LinkSpin Banner Spins: post one as a banner, and fill the splash's open places (2026-11-14)
const PUB = path.join(__dirname, 'public');
const UPL = path.join(C.dataDir, 'uploads');
const ADDR_RE = /^0x[0-9a-fA-F]{40}$/;
const NAME_RE = /^[A-Za-z0-9_.-]{1,40}$/;
const BOT_UA = /bot|crawl|spider|slurp|facebookexternalhit|preview|monitor|wget|curl|python|httpclient|scrapy|semrush|ahrefs|headless|lighthouse|pingdom|go-http|java\/|okhttp|axios|node-fetch|phantom|selenium|puppeteer|playwright/i;
const SECRET = (() => {
if (process.env.SESSION_SECRET) return process.env.SESSION_SECRET;
const f = path.join(C.dataDir, '.secret');
try { return fs.readFileSync(f, 'utf8').trim(); } catch (e) {}
const s = crypto.randomBytes(32).toString('hex'); try { fs.writeFileSync(f, s, { mode: 0o600 }); } catch (e) {} return s;
})();
const hash = s => crypto.createHmac('sha256', SECRET).update(s).digest('hex').slice(0, 24);
// ---- http helpers ----
const MIME = { '.html': 'text/html; charset=utf-8', '.css': 'text/css', '.js': 'text/javascript', '.png': 'image/png', '.jpg': 'image/jpeg',
'.gif': 'image/gif', '.svg': 'image/svg+xml', '.ico': 'image/x-icon', '.json': 'application/json', '.txt': 'text/plain; charset=utf-8', '.xml': 'application/xml' };
const CSP = "default-src 'self'; script-src 'self' https://cdn.jsdelivr.net https://linkspin.app https://polhunter.com; worker-src 'self' blob:; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; "
+ "img-src 'self' data: blob: https:; connect-src 'self' https://linkspin.app https://polhunter.com 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: 'self'";
function headers(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) { res.writeHead(code, headers(Object.assign({ 'Content-Type': 'application/json', 'Cache-Control': 'no-store' }, extra))); res.end(JSON.stringify(obj)); }
function sendFile(res, file, extra) {
fs.readFile(file, (err, data) => {
if (err) { res.writeHead(404, headers({ 'Content-Type': 'text/plain' })); return res.end('Not found'); }
const ext = path.extname(file).toLowerCase();
res.writeHead(200, headers(Object.assign({ 'Content-Type': MIME[ext] || 'application/octet-stream', 'Cache-Control': ext === '.html' ? 'no-store, must-revalidate' : 'public, max-age=3600' }, extra)));
res.end(data);
});
}
function readRaw(req, max) {
return new Promise((resolve, reject) => { const ch = []; let n = 0;
req.on('data', c => { n += c.length; if (n > max * 8) { req.destroy(); return; } if (n <= max) ch.push(c); });
req.on('end', () => n > max ? reject(new Error('too big')) : resolve(Buffer.concat(ch))); req.on('error', reject); });
}
async function readBody(req) { const b = await readRaw(req, 32 * 1024); try { return b.length ? JSON.parse(b.toString('utf8')) : {}; } catch (e) { return {}; } }
function cookies(req) { const o = {}; for (const p of (req.headers.cookie || '').split(';')) { const i = p.indexOf('='); if (i > 0) { try { o[p.slice(0, i).trim()] = decodeURIComponent(p.slice(i + 1).trim()); } catch (e) {} } } return o; }
function cookie(name, val, maxAgeSec, httpOnly) { return name + '=' + encodeURIComponent(val) + '; Path=/; SameSite=Lax; Max-Age=' + maxAgeSec + (httpOnly ? '; HttpOnly' : '') + (C.isProd ? '; Secure' : ''); }
// Client IP. Behind Coolify's proxy the RIGHTMOST X-Forwarded-For entry is the one the proxy added; earlier entries are whatever
// the client sent and can be forged, so they are never used. CF_PROXIED=1 (only when Cloudflare proxies the domain): cf-connecting-ip.
function ip(req) {
if (process.env.CF_PROXIED === '1' && req.headers['cf-connecting-ip']) return String(req.headers['cf-connecting-ip']).trim();
const xff = String(req.headers['x-forwarded-for'] || '').split(',').map(s => s.trim()).filter(Boolean);
return (xff.length ? xff[xff.length - 1] : String(req.socket.remoteAddress || '')).replace(/^::ffff:/, '');
}
const isBot = req => !req.headers['user-agent'] || BOT_UA.test(req.headers['user-agent']);
// visitor = IP + user agent (not a cookie: traffic-exchange frames drop cookies)
const visitorKey = req => hash('vk|' + ip(req) + '|' + (req.headers['user-agent'] || ''));
const ipKey = req => hash('ip|' + ip(req));
// per-IP fixed-window limiter
const buckets = new Map();
function limited(req, name, max, windowMs) {
const k = name + ':' + ip(req); const now = Date.now(); let b = buckets.get(k);
if (!b || now - b.t > windowMs) { b = { t: now, n: 0 }; buckets.set(k, b); }
if (buckets.size > 100000) buckets.clear();
return ++b.n > max;
}
const isAdmin = req => { const t = String(process.env.ADMIN_TOKEN || ''); const g = String(req.headers['x-admin-token'] || '');
return t.length >= 8 && g.length === t.length && crypto.timingSafeEqual(Buffer.from(g), Buffer.from(t)); };
// ---- network usernames + membership (Marty 2026-11-14: "want everything looped through the hub to verify membership") ----
// The network hub answers first (hubpeople.js, signed as vbb, cached 5 minutes); InstantAdPay's /api/network/member only when
// the hub is unreachable. A person the hub does not know is unknown here too (never "verified" on InstantAdPay's word alone).
const hubpeople = require('./hubpeople');
const hubevents = require('./hubevents'); // network hub hook (2026-11-16): sign-out-everywhere, block and erase end sessions here
const netCache = new Map();
async function netMember(q) {
const h = q.u ? await hubpeople.byRef(q.u) : await hubpeople.byWallet(q.a);
if (h.ok) { const a = hubpeople.wallet(h.person); return a ? { address: a, username: h.person.username ? String(h.person.username) : null, hubId: h.person.id || null, via: 'hub' } : null; }
if (!C.networkLookupUrl) return null;
const k = q.u ? 'u:' + q.u.toLowerCase() : 'a:' + q.a.toLowerCase();
const hit = netCache.get(k); if (hit && Date.now() - hit.at < 3600000) return hit.m;
let m = null;
try { const ac = new AbortController(); setTimeout(() => ac.abort(), 4000).unref();
const qs = q.u ? 'u=' + encodeURIComponent(q.u) : 'a=' + encodeURIComponent(q.a);
const j = await (await fetch(C.networkLookupUrl + '?' + qs, { signal: ac.signal })).json();
if (j && ADDR_RE.test(j.address || '') && j.username) m = { address: j.address.toLowerCase(), username: String(j.username), via: 'iap' }; } catch (e) { return null; }
netCache.set(k, { at: Date.now(), m }); if (netCache.size > 20000) netCache.clear();
return m;
}
// the member's network sponsor as a wallet, through the hub only (a sponsor voucher binds on chain): the hub's sponsor for this
// wallet, resolved to that sponsor's wallet by hub id. {ok: false} = the hub is unreachable; sponsor null = none known.
async function hubSponsorWallet(addr) {
const me = await hubpeople.byWallet(addr); if (!me.ok) return { ok: false };
if (!me.person || !me.person.sponsor) return { ok: true, sponsor: null };
const sp = await hubpeople.sponsorOf(me.person); if (!sp.ok) return { ok: false };
return { ok: true, sponsor: hubpeople.wallet(sp.person) };
}
// ?ref=<network username or wallet> -> a VBB member's address (only members who have signed in here can be credited)
async function resolveRef(raw) {
const r = String(raw || '').trim().slice(0, 60); if (!r) return null;
if (ADDR_RE.test(r)) return store.member(r) ? r.toLowerCase() : null;
if (!NAME_RE.test(r)) return null;
const local = store.memberByName(r); if (local) return local.address;
const m = await netMember({ u: r }).catch(() => null);
return m && store.member(m.address) ? m.address : null;
}
// a member's username: the one the network sign-in carried, else the network lookup by wallet (filled in once)
async function fillUsername(addr) {
const m = store.member(addr); if (!m || m.username) return;
const n = await netMember({ a: addr }).catch(() => null);
if (n && n.address === m.address && NAME_RE.test(n.username) && !store.memberByName(n.username)) store.upsertMember(addr, { username: n.username });
}
const refCookie = req => { const v = cookies(req)['vbb.ref']; return v && (NAME_RE.test(v) || ADDR_RE.test(v)) ? v : null; };
// ---- members ----
const session = req => store.session(cookies(req)['vbb.sid']);
function signedIn(addr, patch) {
const m = store.upsertMember(addr, patch);
grantDaily(m); return m;
}
// free daily credits go to network-verified members only (Marty 2026-11-13, stops wallet farming). Verified (Marty 2026-11-14) =
// the network hub knows this wallet, or knows the network member who signed in here through InstantAdPay or LinkSpin (looked up
// by the email in their sign-in token, never stored). Only while the hub is unreachable: InstantAdPay's lookup by wallet, or a
// network sign-in, as before. A plain wallet is rechecked on each visit, so joining the network later unlocks it.
const netVerified = m => !!m && m.netOk === true;
async function verifyNet(addr, email) {
const m = store.member(addr); if (!m || netVerified(m)) return;
const h = await hubpeople.byWallet(addr);
let known = h.ok && !!h.person, down = !h.ok;
if (!known && !down && email) { const e = await hubpeople.resolve({ email: String(email).trim().toLowerCase() }); if (e.ok) known = !!(e.person && !e.person.blocked); else down = true; }
if (!known && down) {
const n = await netMember({ a: addr }).catch(() => null);
known = (n && n.address === m.address) || m.via === 'iap' || m.via === 'linkspin';
}
if (known) { store.upsertMember(addr, { netOk: true, netAt: Date.now(), netBy: down ? 'fallback' : 'hub' }); await fillUsername(addr).catch(() => {}); }
}
// one free post credit a day (Central time), banked up to freeCreditCap
function grantDaily(m) {
if (!netVerified(m)) return false;
const day = store.ctDay(); if (m.freeDay === day) return false;
m.freeDay = day; let granted = false;
const add = Math.min(C.freeCreditsPerDay, Math.max(0, C.freeCreditCap - m.credits));
if (add > 0) { m.credits += add; granted = true; }
store.save(); return granted;
}
function myData(addr) {
const m = store.member(addr);
const banners = store.bannersOf(addr).slice().reverse().map(b => Object.assign({ id: b.id, img: b.img, link: b.link, createdAt: b.createdAt, cycledAt: b.cycledAt || null, clicks: b.clicks || 0,
look: !!b.look, teaser: b.look ? (b.teaser || '') : '', teaserDefault: b.spin ? b.spin.name : loop.hostOf(b.link), spin: b.spin ? { name: b.spin.name, size: b.spin.size } : null,
swapUsed: swapUsed(b), swappedAt: swapUsed(b) ? b.swaps[b.swaps.length - 1].at : null, canSwap: canSwap(b) }, loop.memberPlace(b)));
const rewards = store.ledger().filter(e => e.owner === m.address);
const shareName = m.username || m.address;
return { address: m.address, username: m.username, credits: m.credits, freeCreditCap: C.freeCreditCap, freeToday: m.freeDay === store.ctDay(), netVerified: netVerified(m),
maxQueued: C.maxQueuedPerMember, banners, rewards: rewards.slice(-50).reverse(), rewardViews: rewards.reduce((t, e) => t + e.views, 0),
week: loop.memberWeek(m.address), share: 'https://' + C.site + '/?ref=' + encodeURIComponent(shareName) };
}
// one swap per banner (Marty 2026-11-15: "allow the member to swap it only, and they can only do it one time"): image and/or link,
// while the banner is waiting or in the loop and not taken down. No withdraw, no removal, no refund for members.
const swapUsed = b => Array.isArray(b.swaps) && b.swaps.length > 0;
const canSwap = b => !swapUsed(b) && !b.down && (b.state === 'queued' || b.state === 'loop');
// ---- visit tickets: issued on page load, redeemed after the page has been visible for visitSeconds ----
const tickets = new Map();
const srcHost = raw => { try { const u = new URL(String(raw || '')); if (!/^https?:$/.test(u.protocol)) return ''; const h = u.hostname.toLowerCase().replace(/^www\./, ''); return h === C.site || h.endsWith('.' + C.site) || !h.includes('.') ? '' : h.slice(0, 80); } catch (e) { return ''; } };
// Viral Banner Blitz only RECEIVES network sign-ins (like Downline Banners): InstantAdPay or LinkSpin vouch for the member's wallet
// and username. Those sites must list `vbb` under `wallets` before this works live.
networksso.init({ self: 'vbb', peer: 'iap', peerBase: () => C.iapBase, from: { iap: () => C.iapBase, linkspin: () => C.lsBase },
isProd: C.isProd, dataDir: C.dataDir, defaultPath: '/my',
member: async req => { const s = session(req); return s ? { address: s.address } : null; },
accept: async (email, req, v) => (v && v.wallet ? { ok: true } : { fallback: 'no wallet in the token' }),
signIn: async (email, req, v) => {
const patch = { via: v.iss };
if (v.name && NAME_RE.test(v.name)) { const other = store.memberByName(v.name); if (!other || other.address === v.wallet) patch.username = v.name; }
signedIn(v.wallet, patch);
await verifyNet(v.wallet, email).catch(() => {}); // the hub knows this network member (by wallet, else by their email)
grantDaily(store.member(v.wallet));
return cookie('vbb.sid', store.mintSession(v.wallet), store.SESSION_TTL / 1000, true);
},
landing: to => to, signinPath: to => to });
// the hub's member.signedout / member.blocked / member.erased: that person's sessions here end (by any of their wallets)
hubevents.init({ dataDir: C.dataDir, site: 'vbb', end: who => store.endSessions(x => who.match(x) || who.match(store.member(x.address)), who.before) });
// old site links (2026-11-14, the Downline Banners pattern): the old YFW site's referral links were /?<old username>,
// /splashpg.php?pid=N&r=<old username> and /lcp.php?pid=N&r=<old username>. An old username maps to the same person's network
// username (oldrefs.json, a MySQL document loaded by POST /api/admin/oldrefs, matched by email); any other *.php page goes home.
let oldRefs = { at: 0, map: {} };
function oldRefMap() {
if (Date.now() - oldRefs.at < 60000) return oldRefs.map;
let m = {}; try { m = JSON.parse(fs.readFileSync(path.join(C.dataDir, 'oldrefs.json'), 'utf8')) || {}; } catch (e) {}
oldRefs = { at: Date.now(), map: m }; return m;
}
function oldLink(u) {
const p = u.pathname;
const bare = u.search.slice(1).split('&')[0];
if (p === '/' || p === '/index.php') { if (!/^[A-Za-z0-9_.-]{2,40}$/.test(bare)) return p === '/' ? null : '/'; } // "&fbclid=..." may follow
else if (!/\.php$/i.test(p)) return null;
const lp = p.toLowerCase();
const old = (lp === '/splashpg.php' || lp === '/lcp.php') ? String(u.searchParams.get('r') || '') : (lp === '/' || lp === '/index.php') ? bare : '';
const net = /^[A-Za-z0-9_.-]{2,40}$/.test(old) ? oldRefMap()[old.toLowerCase()] : null;
return net ? '/?ref=' + encodeURIComponent(net) : '/';
}
// network ad zone on the 404 page (LinkSpin zone on Marty's account, 300x250; the page zones live in public/assets/common.js ZONES). '' = none
const ZONE_404 = 'ls-d83484'; // LinkSpin zone "VBB not found" (2026-11-14)
const PAGES = { '/': 'index.html', '/my': 'my.html', '/leaders': 'leaders.html', '/how': 'how.html', '/packages': 'packages.html', '/admin': 'admin.html',
'/contract': 'contract.html', '/ledger': 'ledger.html', '/terms': 'terms.html', '/disclaimer': 'disclaimer.html', '/privacy': 'privacy.html' }; // trust pack 2026-11-14
const challenges = new Map();
const clickSeen = new Map();
const server = http.createServer(async (req, res) => {
const u = new URL(req.url, 'http://x'); const p = u.pathname;
{ const host = String(req.headers.host || '').toLowerCase().split(':')[0];
if (C.isProd && host !== C.site && host.endsWith('.' + C.site)) { res.writeHead(301, { Location: 'https://' + C.site + req.url, 'Cache-Control': 'no-store' }); return res.end(); } }
try {
if (req.method === 'GET' && await networksso.page(req, res, u)) return; // network hub: daily activity ping + the hub sign-in push (2026-11-15)
if (req.method === 'GET' && (p.startsWith('/sso/') || p === '/api/sso/status') && await networksso.handle(req, res, u)) return;
if ((p === '/api/promo-kit' || p === '/promote') && promokit.handle(req, res, u, sendFile)) return;
if ((p.startsWith('/api/chat') || p.startsWith('/api/admin/kb')) && await chatbot.handle(req, res, p, u, { json, readBody, isAdmin })) return;
if (req.method === 'GET' || req.method === 'HEAD') {
if (p === '/health') return json(res, 200, { ok: true, store: docstore.isOn() ? 'mysql' : 'files' });
{ const to = oldLink(u); if (to) { res.writeHead(301, { Location: to, 'Cache-Control': 'no-store' }); return res.end(); } } // before any page
if (PAGES[p]) {
const ex = {};
const ref = u.searchParams.get('ref');
if (ref && (NAME_RE.test(ref) || ADDR_RE.test(ref))) ex['Set-Cookie'] = cookie('vbb.ref', ref, 30 * 86400, false);
if (p === '/my' || p === '/admin') ex['X-Frame-Options'] = 'DENY'; // member + admin pages never framed; the splash stays frameable
return sendFile(res, path.join(PUB, PAGES[p]), ex);
}
if (/^\/r\/[^/]+$/.test(p)) { res.writeHead(302, { Location: '/?ref=' + encodeURIComponent(decodeURIComponent(p.slice(3))) }); return res.end(); }
if (p === '/sitemap.xml') {
const day = new Date().toISOString().slice(0, 10);
const urls = ['/', '/leaders', '/how', '/packages', '/promote', '/contract', '/ledger', '/terms', '/disclaimer', '/privacy'].map(x => '<url><loc>https://' + C.site + x + '</loc><lastmod>' + day + '</lastmod></url>').join('');
res.writeHead(200, headers({ 'Content-Type': 'application/xml; charset=utf-8', 'Cache-Control': 'public, max-age=3600' }));
return res.end('<?xml version="1.0" encoding="UTF-8"?><urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' + urls + '</urlset>');
}
if (p === '/robots.txt') { res.writeHead(200, headers({ 'Content-Type': 'text/plain; charset=utf-8' })); return res.end('User-agent: *\nAllow: /\nDisallow: /my\nDisallow: /admin\nDisallow: /api/\nDisallow: /go/\nDisallow: /sso/\n\nSitemap: https://' + C.site + '/sitemap.xml\n'); }
if (p.startsWith('/assets/') || p.startsWith('/art/') || p === '/favicon.ico') {
const f = path.normalize(path.join(PUB, p === '/favicon.ico' ? '/art/icon-192.png' : p)); if (!f.startsWith(PUB + path.sep)) { res.writeHead(400); return res.end(); }
return sendFile(res, f);
}
if (p.startsWith('/u/')) {
const name = path.basename(p); if (!/^[a-z0-9-]+\.(png|jpg|gif)$/.test(name)) { res.writeHead(404); return res.end(); }
return sendFile(res, path.join(UPL, name), { 'Cache-Control': 'public, max-age=604800, immutable' });
}
// click relay: /go/<bannerId> counts one click per visitor per banner per hour, then sends the visitor to the banner's link
const gm = /^\/go\/(\d{1,9})$/.exec(p);
if (gm) {
const b = store.banner(gm[1]); if (!b || b.down) { res.writeHead(302, { Location: '/' }); return res.end(); } // taken down: never sends anyone to it
if (!isBot(req)) {
const k = visitorKey(req) + ':' + b.id; const t = clickSeen.get(k);
if (!t || Date.now() - t > 3600000) { clickSeen.set(k, Date.now()); if (clickSeen.size > 100000) clickSeen.clear(); b.clicks = (b.clicks || 0) + 1; store.saveBanner(b); store.bump('clicks'); }
}
res.writeHead(302, { Location: clickLink(b), 'Cache-Control': 'no-store', 'Referrer-Policy': 'origin' }); return res.end();
}
}
// this week's prize pot from this week's VBBShop sales (prize.js); the cap is never shown
function prizes() { const z = prize.pot(store.ctWeek()); return { pot: z.potUsd, atFloor: z.atFloor, visitors: z.places, sources: z.places }; }
// -- public API
if (p === '/api/config' && req.method === 'GET') {
return json(res, 200, { site: C.site, siteName: C.siteName, chainId: C.chainId, chainName: C.chainName, rpc: C.publicRpc, walletConnectProjectId: C.walletConnectProjectId,
loopSize: C.loopSize, perShift: C.perShift, viewsPerCycle: C.viewsPerCycle, visitSeconds: C.visitSeconds, freeCreditCap: C.freeCreditCap, maxQueued: C.maxQueuedPerMember,
freeCreditsPerDay: C.freeCreditsPerDay, packs: C.packs, lookUsd: C.lookUsd, lookSku: C.lookSku, prizes: prizes(), sso: networksso.enabled(),
shop: { live: shop.watching(), contract: shop.watching() ? C.contractAddress : null }, explorer: C.explorer });
}
// buying: the live price, gas fees for the wallet, and the confirmation wait (the Downline Banners endpoints)
if (p === '/api/quote' && req.method === 'GET') {
if (!shop.watching()) return json(res, 503, { error: 'Purchases are not open.' });
if (limited(req, 'quote', 600, 3600000)) return json(res, 429, { error: 'Too many requests this hour.' });
const sku = Number(u.searchParams.get('sku')), qty = Number(u.searchParams.get('qty') || 1);
if (!validSku(sku) || !Number.isInteger(qty) || qty < 1 || qty > (sku === C.lookSku ? 1 : 10)) return json(res, 400, { error: 'Unknown package.' });
try { return json(res, 200, Object.assign({ usd: skuUsd(sku) * qty }, await shop.quote(sku, qty))); } catch (e) { return json(res, 503, { error: 'Price unavailable right now. Try again in a minute.' }); }
}
if (p === '/api/gas' && req.method === 'GET') { try { return json(res, 200, shop.watching() ? await shop.fees() : {}); } catch (e) { return json(res, 200, {}); } }
if (/^\/api\/tx\/0x[0-9a-fA-F]{64}$/.test(p) && req.method === 'GET') {
if (!shop.watching() || limited(req, 'tx', 1200, 3600000)) return json(res, 200, { found: false });
try { return json(res, 200, await shop.receipt(p.slice(8))); } catch (e) { return json(res, 200, { found: false }); }
}
// past weeks' prize winners with their transactions (paid weeks only)
// trust pack (2026-11-14): the public ledger (purchases with their split, prize payouts), the live contract facts, the network list
if (p === '/api/ledger' && req.method === 'GET') return json(res, 200, proof.ledger(u.searchParams.get('n')), { 'Cache-Control': 'public, max-age=10' });
if (p === '/api/contract' && req.method === 'GET') { if (limited(req, 'contract', 600, 3600000)) return json(res, 429, { error: 'Too many requests' }); return json(res, 200, await proof.contract(), { 'Cache-Control': 'public, max-age=60' }); }
if (p === '/api/network-sites' && req.method === 'GET') return netsites.handle(req, res);
if (p === '/api/prizes' && req.method === 'GET') return json(res, 200, { current: prizes(), week: store.ctWeek(), past: prize.history(12), explorer: C.explorer }, { 'Cache-Control': 'public, max-age=30' });
if (p === '/api/splash' && req.method === 'GET') { const v = loop.view(24); v.fill = splashFill(); return json(res, 200, v, { 'Cache-Control': 'no-store' }); }
if (p === '/api/leaders' && req.method === 'GET') {
const out = loop.leaders(null, 10);
const fmt = r => ({ name: r.username ? '@' + r.username : r.address.slice(0, 6) + '...' + r.address.slice(-4), visitors: r.visitors, sources: r.sources });
return json(res, 200, { week: out.week, visitors: out.visitors.map(fmt), sources: out.sources.map(fmt) }, { 'Cache-Control': 'public, max-age=15' });
}
if (p === '/api/recent' && req.method === 'GET') {
const list = store.ledger().slice(-8).reverse().filter(e => Date.now() - e.at < 30 * 60000)
.map(e => ({ id: e.id, at: e.at, bannerId: e.bannerId, name: e.username ? '@' + e.username : null, views: e.views }));
return json(res, 200, { cycles: list }, { 'Cache-Control': 'public, max-age=10' });
}
// verified visitors: start (page load) -> seen (after visitSeconds of the page being visible)
if (p === '/api/visit/start' && req.method === 'POST') {
const b = await readBody(req);
if (isBot(req) || req.headers['sec-fetch-site'] === 'cross-site') return json(res, 200, { ticket: null });
if (limited(req, 'ticket', 120, 3600000)) return json(res, 200, { ticket: null });
const refRaw = String(b.ref || '').trim() || refCookie(req);
const ref = refRaw ? await resolveRef(refRaw) : null;
const s = session(req);
const t = crypto.randomBytes(12).toString('hex');
tickets.set(t, { vk: visitorKey(req), iph: ipKey(req), at: Date.now(), ref: ref && (!s || s.address !== ref) ? ref : null, src: srcHost(b.src) });
if (tickets.size > 50000) { const cut = Date.now() - 1800000; for (const [k, v] of tickets) if (v.at < cut) tickets.delete(k); }
return json(res, 200, { ticket: t, seconds: C.visitSeconds, already: !loop.canCount(visitorKey(req), ipKey(req)).ok });
}
if (p === '/api/visit/seen' && req.method === 'POST') {
const b = await readBody(req); const t = tickets.get(String(b.ticket || ''));
if (!t || isBot(req) || t.vk !== visitorKey(req)) return json(res, 200, { counted: false, why: 'ticket' });
const age = Date.now() - t.at;
if (age < C.visitSeconds * 1000 - 300 || Number(b.visibleMs) < C.visitSeconds * 1000 - 300) return json(res, 200, { counted: false, why: 'early' });
tickets.delete(String(b.ticket));
if (age > 1800000) return json(res, 200, { counted: false, why: 'ticket' });
const r = loop.verifiedVisit({ vk: t.vk, iph: t.iph, ref: t.ref, src: t.src });
return json(res, 200, { counted: r.counted, why: r.why || null, shifted: !!r.shifted, cycled: r.cycled ? r.cycled.bannerId : null, progress: store.state().progress, perShift: C.perShift });
}
// wallet sign-in
if (p === '/api/auth/challenge' && req.method === 'POST') {
if (limited(req, 'auth', 30, 600000)) return json(res, 429, { error: 'Too many sign-in attempts. Wait a few minutes.' });
const b = await readBody(req); if (!ADDR_RE.test(b.address || '')) return json(res, 400, { error: 'Bad address' });
const a = b.address.toLowerCase(); const nonce = crypto.randomBytes(16).toString('hex');
const message = C.site + ' wants you to sign in with your wallet:\n' + getAddress(a) + '\n\nViral Banner Blitz sign-in. This signature is free and cannot move funds or approve anything.\n\nChain ID: ' + C.chainId + '\nNonce: ' + nonce + '\nIssued At: ' + new Date().toISOString();
challenges.set(a, { message, exp: Date.now() + 600000 });
if (challenges.size > 20000) challenges.clear();
return json(res, 200, { message });
}
if (p === '/api/auth/verify' && req.method === 'POST') {
const b = await readBody(req); const a = String(b.address || '').toLowerCase(); const ch = challenges.get(a);
if (!ch || ch.exp < Date.now()) return json(res, 400, { error: 'Sign-in request expired. Tap sign in again.' });
let rec; try { rec = verifyMessage(ch.message, String(b.signature || '')).toLowerCase(); } catch (e) { return json(res, 400, { error: 'Invalid signature.' }); }
if (rec !== a) return json(res, 400, { error: 'Your wallet signed with a different account (' + rec.slice(0, 6) + '...' + rec.slice(-4) + '). Switch accounts and try again.' });
challenges.delete(a);
signedIn(a, store.member(a) ? {} : { via: 'wallet' });
fillUsername(a).catch(() => {});
return json(res, 200, { ok: true, address: a }, { 'Set-Cookie': cookie('vbb.sid', store.mintSession(a), store.SESSION_TTL / 1000, true) });
}
if (p === '/api/auth/logout' && req.method === 'POST') {
const s = session(req); if (s) store.dropSession(s.token);
return json(res, 200, { ok: true }, { 'Set-Cookie': [cookie('vbb.sid', '', 0, true), networksso.offCookie()] });
}
// "Sign out everywhere" (2026-11-16): the hub ends every network sign-in of this member and tells every hooked site; every
// session of this wallet here ends now. Same-origin POST only (SameSite=Lax session cookie).
if (p === '/api/auth/logout-everywhere' && req.method === 'POST') {
const s = session(req); let hub = { ok: false };
if (s) { hub = await networksso.signOutEverywhere(s); store.endSessions(x => x.address === s.address, Date.now() + 1000); }
return json(res, 200, { ok: true, everywhere: !!hub.ok }, { 'Set-Cookie': [cookie('vbb.sid', '', 0, true), networksso.offCookie()] });
}
if (p === '/api/hub/events' && req.method === 'POST') {
let raw = ''; try { raw = (await readRaw(req, 256 * 1024)).toString('utf8'); } catch (e) { return json(res, 413, { error: 'too big' }); }
const r = await hubevents.receive(req.headers, raw); return json(res, r.status, r.body);
}
if (p === '/api/me' && req.method === 'GET') {
const s = session(req); if (!s) return json(res, 200, { signedIn: false });
const m = store.member(s.address);
return json(res, 200, { signedIn: true, address: s.address, username: m ? m.username : null });
}
// -- member API
if (p.startsWith('/api/my')) {
const s = session(req); if (!s) return json(res, 401, { error: 'Sign in first.' });
const me = s.address;
if (!store.member(me)) signedIn(me, { via: 'wallet' });
if (p === '/api/my' && req.method === 'GET') { await verifyNet(me); const m = store.member(me); const granted = grantDaily(m); m.lastSeen = Date.now(); return json(res, 200, Object.assign(myData(me), { grantedNow: granted })); }
// sponsor voucher for VBBShop.buy: only when the hub knows this member's network sponsor (a wallet that is not their own)
if (p === '/api/my/voucher' && req.method === 'GET') {
if (limited(req, 'voucher', 60, 3600000)) return json(res, 429, { error: 'Too many requests this hour.' });
if (!shop.voucherOn()) return json(res, 200, { voucher: null, why: 'off' });
const h = await hubSponsorWallet(me).catch(() => ({ ok: false }));
if (!h.ok) return json(res, 200, { voucher: null, why: 'hub-unavailable' }); // no voucher now; the contract binds on a later purchase
const sp = h.sponsor;
if (!sp || sp === me) return json(res, 200, { voucher: null, why: 'no-sponsor' });
return json(res, 200, { voucher: await shop.voucher(me, sp) });
}
// a purchase: the buy() call for the member's own wallet. Packs: SKUs from config. Banner look: one of their own banners that
// is waiting or in the loop and has no look yet (ref = the banner id). A fresh sponsor voucher when the hub knows the sponsor.
if (p === '/api/my/order' && req.method === 'POST') {
if (!shop.watching()) return json(res, 503, { error: 'Purchases are not open yet.' });
if (limited(req, 'order', 60, 3600000)) return json(res, 429, { error: 'Too many requests this hour.' });
const b = await readBody(req); const sku = Number(b.sku); const qty = Number(b.qty || 1); let ref = 0;
if (!validSku(sku)) return json(res, 400, { error: 'Unknown package.' });
if (sku === C.lookSku) {
const bn = store.banner(b.ref);
if (!bn || bn.owner !== me) return json(res, 400, { error: 'That banner is not yours.' });
if (bn.down) return json(res, 400, { error: 'That banner was taken down.' });
if (bn.look) return json(res, 400, { error: 'That banner already has the look.' });
if (bn.state === 'cycled') return json(res, 400, { error: 'That banner has already cycled. Add the look to a banner that is waiting or in the loop.' });
if (qty !== 1) return json(res, 400, { error: 'One look per banner.' });
ref = bn.id;
} else if (!Number.isInteger(qty) || qty < 1 || qty > 10) return json(res, 400, { error: 'Pick 1 to 10 packs.' });
let v = null, why = null;
if (shop.voucherOn()) {
const h = await hubSponsorWallet(me).catch(() => ({ ok: false }));
if (!h.ok) why = 'hub-unavailable'; else if (!h.sponsor || h.sponsor === me) why = 'no-sponsor'; else v = await shop.voucher(me, h.sponsor);
} else why = 'off';
try { return json(res, 200, Object.assign({ buyer: me, usd: skuUsd(sku) * qty, sku, qty, ref, why }, await shop.order(me, sku, qty, ref, v))); }
catch (e) { return json(res, 503, { error: 'Price unavailable right now. Try again in a minute.' }); }
}
// the member's transaction confirmed: scan the chain now (credits still wait for the confirmations)
if (p === '/api/my/paid' && req.method === 'POST') { shop.nudge(); return json(res, 200, { ok: true, confirmations: C.shopConfirmations }); }
// the hover teaser of a banner with the look: up to 40 characters of plain text ('' = the link's site)
const tm = /^\/api\/my\/banners\/(\d{1,9})\/teaser$/.exec(p);
if (tm && req.method === 'POST') {
const bn = store.banner(tm[1]); if (!bn || bn.owner !== me) return json(res, 404, { error: 'Not found' });
if (bn.down) return json(res, 400, { error: 'That banner was taken down.' });
if (!bn.look) return json(res, 400, { error: 'Add the banner look first.' });
const t = String((await readBody(req)).teaser || '').replace(/[\u0000-\u001f\u007f<>]/g, '').replace(/\s+/g, ' ').trim();
if (t.length > 40) return json(res, 400, { error: 'Keep the teaser to 40 characters.' });
bn.teaser = t; store.saveBanner(bn); return json(res, 200, { ok: true, teaser: t || loop.hostOf(bn.link) });
}
// the member's LinkSpin Banner Spins in a size the loop shows (125x125, or 250x250 for sharp screens)
if (p === '/api/my/lsspins' && req.method === 'GET') {
if (limited(req, 'lsspins', 120, 3600000)) return json(res, 429, { error: 'Too many requests this hour.' });
const r = await lsspins.list(me, lsName(me)); if (r.error) return json(res, 502, r);
return json(res, 200, { account: !!r.account, username: r.username || null, spins: (r.spins || []).filter(x => ['125x125', '250x250'].includes(x.size)).map(x => ({ id: x.id, name: x.name, size: x.size || null, paused: !!x.paused, banners: x.banners || 0 })) });
}
// swap the image and/or link of a banner that is waiting or in the loop, once per banner. The banner keeps its id, place, clicks
// and cycle progress. The new image and link get exactly the checks a new post gets. A Banner Spin swap ({ spinId }) takes the
// image + link from LinkSpin's signed answer for another of the member's own 125x125/250x250 spins. Logged on the banner.
const sw = /^\/api\/my\/banners\/(\d{1,9})\/swap$/.exec(p);
if (sw && req.method === 'POST') {
if (limited(req, 'swap', 20, 3600000)) return json(res, 429, { error: 'Too many tries this hour.' });
const bn = store.banner(sw[1]); if (!bn || bn.owner !== me) return json(res, 404, { error: 'Not found' });
if (swapUsed(bn)) return json(res, 400, { error: 'This banner already used its one swap.' });
if (bn.down) return json(res, 400, { error: 'That banner was taken down.' });
if (bn.state !== 'queued' && bn.state !== 'loop') return json(res, 400, { error: 'Only a banner that is waiting or in the loop can be swapped.' });
const b = await readBody(req); let next;
if (b.spinId != null) {
const r = await lsspins.use(me, lsName(me), b.spinId);
if (r.error || !r.use) return json(res, 400, { error: r.error || (r.account === false ? 'No LinkSpin account holds this wallet yet.' : 'Could not use that Banner Spin.') });
if (!['125x125', '250x250'].includes(r.use.size)) return json(res, 400, { error: 'Use a 125x125 (or 250x250) Banner Spin.' });
const ic = safety.checkLink(r.use.img, 'Banner Spin image'); const sl = safety.checkLink(r.use.link, 'Banner Spin link');
if (ic.error || sl.error || new URL(ic.url).hostname !== new URL(sl.url).hostname) return json(res, 400, { error: 'LinkSpin sent a link we cannot use. Try again in a minute.' });
next = { img: ic.url, link: sl.url, spin: { id: Number(r.use.spinId), name: String(r.use.name || '').slice(0, 60), size: r.use.size } };
if (bn.spin && bn.spin.id === next.spin.id) return json(res, 400, { error: 'That is the Banner Spin this banner already shows. Pick another one.' });
} else {
const hasImg = String(b.img || '').trim() !== '', hasLink = String(b.link || '').trim() !== '';
if (!hasImg && !hasLink) return json(res, 400, { error: 'Add a new image, a new link, or both.' });
if (bn.spin && !(hasImg && hasLink)) return json(res, 400, { error: 'A Banner Spin swaps to another Banner Spin, or to your own image and link together.' });
let link = bn.link, img = bn.img;
if (hasLink) { const lk = safety.checkLink(b.link, 'Target link'); if (lk.error) return json(res, 400, lk); link = lk.url; }
if (hasImg) { const im = await checkedImage(me, b.img); if (im.error) return json(res, 400, im); img = im.img; }
if (hasLink && C.linkProbe) { const pr = await safety.probeLink(link); if (pr.error) return json(res, 400, pr); }
if (link === bn.link && img === bn.img) return json(res, 400, { error: 'That is the image and link the banner already has.' });
next = { img, link, spin: null };
}
const cur = store.banner(sw[1]); // re-checked after the awaits (another tab, or the admin, may have acted meanwhile)
if (swapUsed(cur) || !canSwap(cur)) return json(res, 400, { error: swapUsed(cur) ? 'This banner already used its one swap.' : 'This banner can no longer be swapped.' });
cur.swaps = [{ at: Date.now(), old: { img: cur.img, link: cur.link, spin: cur.spin || null }, new: { img: next.img, link: next.link, spin: next.spin } }];
cur.img = next.img; cur.link = next.link; if (next.spin) cur.spin = next.spin; else delete cur.spin;
store.saveBanner(cur);
return json(res, 200, { ok: true, banner: Object.assign({ id: cur.id, img: cur.img, link: cur.link, spin: cur.spin ? { name: cur.spin.name, size: cur.spin.size } : null, swapUsed: true }, loop.placeOf(cur)) });
}
if (p === '/api/my/upload' && req.method === 'POST') {
if (limited(req, 'upload', 40, 3600000)) return json(res, 429, { error: 'Too many uploads this hour.' });
let buf; try { buf = await readRaw(req, safety.MAX_UPLOAD + 1); } catch (e) { return json(res, 400, { error: 'The file is over 100 KB.' }); }
const r = safety.checkImage(buf); if (r.error) return json(res, 400, r);
return json(res, 200, { ok: true, img: saveUpload(me, buf, r.info.ext) });
}
if (p === '/api/my/banners' && req.method === 'POST') {
if (limited(req, 'post', 30, 3600000)) return json(res, 429, { error: 'Too many posts this hour.' });
const b = await readBody(req); const m = store.member(me);
if (m.credits < 1) return json(res, 400, { error: 'You have no post credits. A free credit arrives each day you sign in.' });
const waiting = store.bannersOf(me).filter(x => x.state === 'queued' && !x.down).length;
if (waiting >= C.maxQueuedPerMember) return json(res, 400, { error: 'You already have ' + waiting + ' banners waiting. Post again when one enters the loop.' });
// a LinkSpin Banner Spin (2026-11-14): image + link come from LinkSpin's signed answer, never from the browser. The image is the
// spin's rotating image on LinkSpin (not copied: it changes on every view) and the link its click link (clicks count in
// LinkSpin Reports); LinkSpin checked the spin's images and links, so the frame probe (it would count a click) is skipped.
if (b.spinId != null) {
const r = await lsspins.use(me, lsName(me), b.spinId);
if (r.error || !r.use) return json(res, 400, { error: r.error || (r.account === false ? 'No LinkSpin account holds this wallet yet.' : 'Could not use that Banner Spin.') });
if (!['125x125', '250x250'].includes(r.use.size)) return json(res, 400, { error: 'Use a 125x125 (or 250x250) Banner Spin.' });
const ic = safety.checkLink(r.use.img, 'Banner Spin image'); const sl = safety.checkLink(r.use.link, 'Banner Spin link');
if (ic.error || sl.error || new URL(ic.url).hostname !== new URL(sl.url).hostname) return json(res, 400, { error: 'LinkSpin sent a link we cannot use. Try again in a minute.' });
if (store.member(me).credits < 1) return json(res, 400, { error: 'You have no post credits.' });
m.credits -= 1;
const nb = loop.post(me, ic.url, sl.url, 'credit', { id: Number(r.use.spinId), name: String(r.use.name || '').slice(0, 60), size: r.use.size });
return json(res, 200, { ok: true, banner: Object.assign({ id: nb.id }, loop.placeOf(nb)), credits: m.credits, otherSource: !!r.use.otherSource });
}
const lk = safety.checkLink(b.link, 'Target link'); if (lk.error) return json(res, 400, lk);
const im = await checkedImage(me, b.img); if (im.error) return json(res, 400, im);
const img = im.img;
if (C.linkProbe) { const pr = await safety.probeLink(lk.url); if (pr.error) return json(res, 400, pr); }
if (store.member(me).credits < 1) return json(res, 400, { error: 'You have no post credits.' }); // spent meanwhile by another tab
m.credits -= 1;
const nb = loop.post(me, img, lk.url, 'credit');
return json(res, 200, { ok: true, banner: Object.assign({ id: nb.id }, loop.placeOf(nb)), credits: m.credits });
}
return json(res, 404, { error: 'Not found' });
}
// -- admin (x-admin-token: ADMIN_TOKEN)
if (p.startsWith('/api/admin/')) {
if (!isAdmin(req)) return json(res, 401, { error: 'no' });
if (p === '/api/admin/status' && req.method === 'GET') {
const S = store.state(); const L = store.ledger(); const t = store.today();
const byStatus = {}; for (const e of L) byStatus[e.status] = (byStatus[e.status] || 0) + e.views;
return json(res, 200, { day: store.ctDay(), week: store.ctWeek(), config: { split: C.split, packs: C.packs, lookUsd: C.lookUsd, prizePot: C.prizePot, prizes: prizes(), freeCreditsPerDay: C.freeCreditsPerDay, loopSize: C.loopSize, perShift: C.perShift, viewsPerCycle: C.viewsPerCycle, visitSeconds: C.visitSeconds, perIpDay: C.perIpDay, freeCreditCap: C.freeCreditCap, maxQueued: C.maxQueuedPerMember },
loop: { filled: S.loop.length, size: C.loopSize, ids: S.loop, nextOut: S.loop.length ? S.loop[S.loop.length - 1] : null },
queue: { length: S.queue.length, next: S.queue.slice(0, 20) }, progress: S.progress, held: S.progress >= C.perShift && !S.queue.length,
today: { visits: t.visits || 0, shifts: t.shifts || 0, cycles: t.cycles || 0, posts: t.posts || 0, clicks: t.clicks || 0 },
totals: S.totals, ledger: { entries: L.length, views: L.reduce((x, e) => x + e.views, 0), viewsByStatus: byStatus, credited: 0 },
members: store.members().length, banners: S.banners.length, visitsKept: store.visits().length, shop: shop.view(), prize: prize.view(), proof: proof.view(), hub: hubreport.view(), hubLookup: hubpeople.view(), hubEvents: hubevents.view(), lsSpins: lsspins.view(), docstore: docstore.view(), oldrefs: Object.keys(oldRefMap()).length });
}
// old username -> network username map for the old-link redirects: { oldrefs: { old: network } } replaces the whole map
if (p === '/api/admin/oldrefs' && req.method === 'POST') {
let b; try { b = JSON.parse((await readRaw(req, 4 * 1024 * 1024)).toString('utf8')); } catch (e) { return json(res, 400, { error: 'bad json' }); }
if (!b || !b.oldrefs || typeof b.oldrefs !== 'object') return json(res, 400, { error: 'oldrefs object required' });
const o = {}; for (const [k, v] of Object.entries(b.oldrefs)) if (/^[a-z0-9_.-]{2,40}$/.test(k) && NAME_RE.test(String(v))) o[k] = String(v);
fs.writeFileSync(path.join(C.dataDir, 'oldrefs.json'), JSON.stringify(o)); oldRefs = { at: 0, map: {} };
return json(res, 200, { ok: true, total: Object.keys(o).length, skipped: Object.keys(b.oldrefs).length - Object.keys(o).length });
}
// weekly prize payouts: plans (newest first) with a live quote for the ones waiting, prepare, approve and pay
if (p === '/api/admin/prizes' && req.method === 'GET') {
const list = prize.plans().slice(0, 20); const out = [];
for (const pl of list) out.push(Object.assign({}, pl, pl.status === 'prepared' ? { quote: await prize.quotePlan(pl) } : {}));
return json(res, 200, { week: store.ctWeek(), lastWeek: prize.prevWeek(store.ctWeek()), current: prize.pot(store.ctWeek()), weeks: out, prize: prize.view(), explorer: C.explorer });
}
if (p === '/api/admin/prizes/prepare' && req.method === 'POST') { const b = await readBody(req); const r = prize.prepare(String(b.week || prize.prevWeek(store.ctWeek())), true); return json(res, r.error ? 400 : 200, r); }
if (p === '/api/admin/prizes/pay' && req.method === 'POST') {
const b = await readBody(req); const wk = String(b.week || '');
if (!wk || b.confirm !== wk) return json(res, 400, { error: 'Send {week, confirm: week} to approve.' });
const r = await prize.pay(wk); return json(res, r.error ? 400 : 200, r);
}
if (p === '/api/admin/ledger' && req.method === 'GET') {
const n = Math.min(2000, Math.max(1, Number(u.searchParams.get('n')) || 200)); const L = store.ledger();
const per = {}; for (const e of L) { const k = e.owner; const r = per[k] || (per[k] = { address: k, username: e.username, cycles: 0, views: 0 }); r.cycles++; r.views += e.views; if (e.username) r.username = e.username; }
return json(res, 200, { entries: L.slice(-n).reverse(), members: Object.values(per).sort((a, b) => b.views - a.views), note: 'v1 records rewards only; nothing has been credited to InstantAdPay or LinkSpin.' });
}
// ---- banner takedown (Marty 2026-11-15: "Admin takes down the option to credit back or none") ----
// GET ?q=#<id> | <id> | <wallet> | <username>: the banners with their swap + takedown history
if (p === '/api/admin/banners' && req.method === 'GET') {
const q = String(u.searchParams.get('q') || '').trim(); let list = [];
if (/^#?\d{1,9}$/.test(q)) { const b = store.banner(Number(q.replace('#', ''))); if (b) list = [b]; }
else if (ADDR_RE.test(q)) list = store.bannersOf(q);
else if (NAME_RE.test(q.replace(/^@/, ''))) { const m = store.memberByName(q.replace(/^@/, '')); if (m) list = store.bannersOf(m.address); }
if (!list.length) return json(res, 404, { error: 'No banner found for that.' });
return json(res, 200, { banners: list.slice().reverse().slice(0, 100).map(adminBanner) });
}
const tk = /^\/api\/admin\/banners\/(\d{1,9})\/(takedown|restore)$/.exec(p);
if (tk && req.method === 'POST') {
const bn = store.banner(tk[1]); if (!bn) return json(res, 404, { error: 'No such banner.' });
const b = await readBody(req); const by = String(b.by || 'admin').replace(/[^\w .@-]/g, '').slice(0, 40) || 'admin';
const reason = String(b.reason || '').replace(/[\u0000-\u001f\u007f<>]/g, '').replace(/\s+/g, ' ').trim();
const m = store.member(bn.owner);
if (tk[2] === 'takedown') {
if (bn.down) return json(res, 400, { error: 'That banner is already taken down.' });
if (bn.state !== 'queued' && bn.state !== 'loop') return json(res, 400, { error: 'Only a banner that is waiting or in the loop can be taken down (this one is ' + bn.state + ').' });
if (reason.length < 3 || reason.length > 300) return json(res, 400, { error: 'A reason is required (3 to 300 characters). The owner sees it.' });
if (b.credit !== 'back' && b.credit !== 'none') return json(res, 400, { error: 'Choose credit: "back" (the owner gets the post credit back) or "none".' });
const back = b.credit === 'back' && !!m;
bn.down = { at: Date.now(), by, reason, creditBack: back, slot: bn.state };
if (back) { m.credits += 1; store.save(); }
store.saveBanner(bn);
const e = adminLog({ action: 'takedown', bannerId: bn.id, owner: bn.owner, username: (m && m.username) || null, by, reason, credit: back ? 'back' : 'none', slot: bn.state });
return json(res, 200, { ok: true, banner: adminBanner(bn), log: e, ownerCredits: m ? m.credits : null });
}
// restore a mistaken takedown: the banner shows again; a credit that was given back is taken back
if (!bn.down) return json(res, 400, { error: 'That banner is not taken down.' });
const was = bn.down; let reversed = false, short = false, cycle = null;
if (was.creditBack && m) { if (m.credits >= 1) { m.credits -= 1; reversed = true; store.save(); } else short = true; }
(bn.downs || (bn.downs = [])).push(Object.assign({}, was, { restoredAt: Date.now(), restoredBy: by, restoreReason: reason || null, creditReversed: reversed }));
delete bn.down;
// its place rode out while it was down: it gets the cycle it would have had
if (bn.state === 'ended') { bn.state = 'cycled'; bn.cycledAt = Date.now(); delete bn.endedAt; cycle = loop.recordCycle(bn, { note: 'restored' }); }
store.saveBanner(bn);
const e = adminLog({ action: 'restore', bannerId: bn.id, owner: bn.owner, username: (m && m.username) || null, by, reason: reason || null,
credit: was.creditBack ? (reversed ? 'taken back' : 'already used, not taken back') : 'none given', cycleRecorded: !!cycle });
return json(res, 200, { ok: true, banner: adminBanner(bn), log: e, creditReversed: reversed, creditAlreadyUsed: short, cycle, ownerCredits: m ? m.credits : null });
}
if (p === '/api/admin/actions' && req.method === 'GET') {
const n = Math.min(500, Math.max(1, Number(u.searchParams.get('n')) || 100));
return json(res, 200, { actions: (store.state().adminLog || []).slice(-n).reverse() });
}
// the network hub's member lookup (Marty 2026-11-14, read-only). GET ?q=<wallet> | #<banner id> | <username>. No email lives here.
if (p === '/api/admin/member-lookup' && req.method === 'GET') {
const q = String(u.searchParams.get('q') || '').trim(); let a = null, via = null;
if (ADDR_RE.test(q)) { a = q.toLowerCase(); via = 'wallet'; }
else if (/^#?\d{1,9}$/.test(q)) { const b = store.banner(Number(q.replace('#', ''))); a = b ? b.owner : null; via = 'banner'; }
else if (NAME_RE.test(q)) { const m = store.memberByName(q); a = m ? m.address : null; via = 'username'; }
if (!a) return json(res, 404, { error: 'not found' });
const P = Object.entries(store.state().purchases || {}).map(([k, x]) => Object.assign({ tx: k.split(':')[0], logIndex: Number(k.split(':')[1]) }, x));
const purchases = P.filter(x => x.buyer === a).sort((x, y) => (y.at || 0) - (x.at || 0)); const sponsored = P.filter(x => x.sponsor === a).sort((x, y) => (y.at || 0) - (x.at || 0));
const m = store.member(a);
return json(res, 200, Object.assign(m ? myData(a) : { address: a, banners: [], credits: 0 }, { via, known: !!m || purchases.length > 0 || sponsored.length > 0, record: m || null,
purchases: purchases.slice(0, 100), sponsored: sponsored.slice(0, 100), contract: C.contractAddress, explorer: C.explorer }));
}
return json(res, 404, { error: 'Not found' });
}
if (p.startsWith('/api/')) return json(res, 404, { error: 'Not found' });
res.writeHead(404, headers({ 'Content-Type': 'text/html; charset=utf-8' }));
return res.end('<!doctype html><meta name="viewport" content="width=device-width,initial-scale=1"><title>Not found</title><body style="background:#fff4dc;color:#14121f;font-family:sans-serif;text-align:center;padding:40px 16px"><p>Not found. <a style="color:#ff2d87;font-weight:700" href="/">Back to the loop</a></p>'
+ (ZONE_404 ? '<p style="color:#4d4862;font-size:11px;margin:24px 0 4px">Network</p><script async src="https://linkspin.app/z.js" data-zone="' + ZONE_404 + '"></script>' : '') + '</body>');
} catch (e) {
console.error('request', p, e.message);
if (!res.headersSent) json(res, 500, { error: 'Server error' });
}
});
// the network username LinkSpin may look the member up by when no LinkSpin account holds this wallet: network-verified members only
const lsName = addr => { const m = store.member(addr); return m && netVerified(m) && m.username ? m.username : null; };
// admin views of a banner + the admin action ledger (takedowns and restores: who, when, reason, credit decision)
function adminBanner(b) { const m = store.member(b.owner);
return Object.assign({ id: b.id, owner: b.owner, username: (m && m.username) || null, img: b.img, link: b.link, spin: b.spin || null, createdAt: b.createdAt, clicks: b.clicks || 0, look: !!b.look,
swaps: b.swaps || [], down: b.down || null, downs: b.downs || [], cycledAt: b.cycledAt || null, endedAt: b.endedAt || null }, loop.placeOf(b)); }
function adminLog(e) { const S = store.state(); const L = S.adminLog || (S.adminLog = []);
e.id = 'a' + (S.seq.admin = (S.seq.admin || 0) + 1); e.at = Date.now(); L.push(e); if (L.length > 5000) L.splice(0, L.length - 5000); store.save(); return e; }
// a banner image from the browser: one of this member's uploads (/u/...), or an https image address fetched once and checked like an upload
async function checkedImage(me, raw) {
const img = String(raw || '').trim();
if (/^\/u\/[a-z0-9-]+\.(png|jpg|gif)$/.test(img)) {
if (!img.slice(3).startsWith(me.slice(2, 10) + '-') || !fs.existsSync(path.join(UPL, img.slice(3)))) return { error: 'Upload the image again.' };
return { img };
}
const ic = safety.checkLink(img, 'Image address'); if (ic.error) return ic;
const f = await safety.fetchImage(ic.url); if (f.error) return f;
return { img: saveUpload(me, f.buf, f.info.ext) };
}
// tracking macros in a banner link, filled on every click: {clickid} a fresh id, {spot} the banner number, {type} loop or waiting
const MACRO = /\{(clickid|spot|type)\}|%7B(clickid|spot|type)%7D/gi;
function clickLink(b) {
const l = String(b.link || ''); if (!l.match(MACRO)) return l;
const v = { clickid: crypto.randomBytes(8).toString('hex'), spot: String(b.id), type: b.state === 'queued' ? 'waiting' : 'loop' };
return l.replace(MACRO, (x, a, c) => v[(a || c).toLowerCase()]);
}
// members' Banner Spins on the splash: the loop's open places (one place always stays "post yours") and, while nobody waits, the
// waiting line. Never in the loop list: no shift, no cycle, no reward. Same picks for 2 minutes, so the page does not reshuffle.
let fillCache = { key: '', at: 0, out: { loop: [], queue: [] } };
function splashFill() {
const S = store.state(); const ids = S.loop.concat(S.queue.slice(0, 24)); const bs = ids.map(id => store.banner(id)).filter(b => b && !b.down);
const open = Math.max(0, C.loopSize - S.loop.length - 1), queueSlots = S.queue.length ? 0 : 8;
const key = ids.join(',') + '|' + open + '|' + queueSlots + '|' + lsspins.view().fill + '|' + lsspins.view().at;
if (fillCache.key === key && Date.now() - fillCache.at < 120000) return fillCache.out;
const out = lsspins.fill({ openPlaces: open, queueSlots, pageOwners: bs.map(b => b.owner), pageImgs: bs.map(b => b.img) });
fillCache = { key, at: Date.now(), out }; return out;
}
const validSku = sku => sku === C.lookSku || C.packs.some(x => x.sku === sku);
const skuUsd = sku => sku === C.lookSku ? C.lookUsd : (C.packs.find(x => x.sku === sku) || {}).usd || 0;
function saveUpload(owner, buf, ext) {
const name = owner.slice(2, 10) + '-' + crypto.randomBytes(6).toString('hex') + ext;
fs.writeFileSync(path.join(UPL, name), buf); // uploads stay files on the volume (docstore keeps the uploads folder on disk)
return '/u/' + name;
}
(async () => {
await docstore.init({ splits: store.SPLITS }); // before anything reads its data
process.on('SIGTERM', () => { store.flush(); docstore.drain(8000).finally(() => process.exit(0)); });
store.load();
loop.init({ onCycle: (b, e) => console.log('cycle', 'banner #' + b.id, e.views + ' network views recorded') });
store.pruneVisits(); loop.rebuildIndex();
hubreport.init({ dataDir: C.dataDir, purchases: () => Object.entries((store.state() || {}).purchases || {}).map(([key, x]) => Object.assign({ key }, x)) });
proof.init(C, { shop, prize, nameOf: async a => { const m = await netMember({ a }).catch(() => null); return m && m.address === a ? m.username : null; } });
shop.setHook(proof.onPurchase); prize.setHook(proof.onPrize); // before the watcher's first scan
shop.init(C); // inert without CONTRACT_ADDRESS + CHAIN_RPC (watcher) / KEEPER_KEY (vouchers)
prize.init(C); // prepares last week's payout plan; pays only on an admin's approval (PRIZE_KEY)
// fill spins: members seen in the last 60 days (most recent 400), one LinkSpin call each every 10 minutes
lsspins.init({ base: () => C.lsPartnerBase, members: () => store.members().filter(m => Date.now() - (m.lastSeen || m.joinedAt || 0) < 60 * 86400000)
.sort((a, b) => (b.lastSeen || 0) - (a.lastSeen || 0)).slice(0, 400) });
setInterval(() => { if (store.pruneVisits()) loop.rebuildIndex(); }, 3600000).unref();
chatbot.init(); // after docstore.init: kb.json is a MySQL document
server.listen(C.port, () => console.log('Viral Banner Blitz on :' + C.port + ' loop ' + C.loopSize + ', ' + C.perShift + ' visitors per shift, store: ' + (docstore.isOn() ? 'MySQL documents' : 'files (prototype mode)')));
})().catch(e => { console.error('start failed:', e.message); process.exit(1); });
process.on('SIGINT', () => { store.flush(); process.exit(0); });