Files
viraladblitz/server.js
T
martbost 4d0ddbe881 Network hub sign-in, step 3 (Marty 2026-11-15): networksso.js hub mode + every GET passes networksso.page()
networksso.js (the same file on every network site): with HUB_SSO=on (and HUB_URL, HUB_SECRET, HUB_SITE) /sso/start asks the network hub instead of one other site, /sso/in takes the hub's h1. token (this site's HUB_SECRET, iss hub, aud this site, 60 s, single use, state cookie) and falls back once to the old pairwise provider when the hub has nobody. page(): a signed-in member's real page load tells the hub once (nsso.hp, through hub /sso/set and straight back) and pings POST /v1/activity once a day (fire and forget; HUB_ACTIVITY=0 turns it off), only when the hub answered /health lately, so a hub that is down never takes a page with it. HUB_SSO stays off until switched on per site.
qa smoke passes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 15:20:08 -06:00

495 lines
43 KiB
JavaScript

// ViralAdBlitz web app (viraladblitz.com rebuild, Marty approved 2026-11-14). Plain Node http server, no framework (the
// InstantAdPay / Downline Banners / VBB pattern).
// Product: the network's text-ad home. A network member (signed in through InstantAdPay / LinkSpin, membership checked with the
// hub) posts one free text ad: a headline, two lines and an https link. Their page viraladblitz.com/<username> shows their ad plus
// the ads of the 5 people above them in their hub sponsor line, so recruiting spreads an ad 5 levels down. The front page: a live
// royal ticker (Boosted ads starred), "Top ads this week" by verified clicks, 3 steps, the live ledger, contract proof.
// Boost: $5 one-time, 500 guaranteed network views (wire.js delivers and counts them), paid in POL through VABShop and split on
// chain 10% to each of 5 sponsor levels (pass-up to the next person who has boosted) + 50% company.
// Pages: / (front), /<username> (member page), /how, /my, /boost, /ledger, /contract, /promote, /terms, /disclaimer, /privacy, /admin.
'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(C.dataDir, { recursive: true });
const docstore = require('./docstore'); docstore.install(C.dataDir); // before any module reads data
const store = require('./store');
const wire = require('./wire');
const safety = require('./safety');
const networksso = require('./networksso');
const shop = require('./shop');
const promokit = require('./promokit');
const hubreport = require('./hubreport');
const hubpeople = require('./hubpeople');
const hubline = require('./hubline');
const proof = require('./proof');
const netsites = require('./netsites');
const vabnas = require('./vabnas');
const lstrack = require('./lstrack');
const chatbot = require('./chatbot'); // the site assistant (2026-11-15): chatcore.js + kb.js + the network knowledge base (netkb.js)
const PUB = path.join(__dirname, 'public');
const ADDR_RE = /^0x[0-9a-fA-F]{40}$/;
const NAME_RE = /^[A-Za-z0-9_.-]{1,40}$/;
const PAGE_RE = /^\/([A-Za-z0-9_.-]{2,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);
wire.setSecret(SECRET);
// ---- 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, code) {
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(code || 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: the RIGHTMOST X-Forwarded-For entry is the one Coolify's proxy added (earlier ones can be forged). CF_PROXIED=1: 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']);
const visitorKey = req => hash('vk|' + ip(req) + '|' + (req.headers['user-agent'] || '')); // not a cookie: traffic-exchange frames drop cookies
const ipKey = req => hash('ip|' + ip(req));
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 membership through the hub (InstantAdPay's lookup only while the hub is unreachable) ----
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;
}
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 });
}
// network-verified = the hub knows this wallet, or the network member who signed in through InstantAdPay / LinkSpin (their token's
// email, never stored). While the hub is unreachable: InstantAdPay's lookup by wallet, or a network sign-in. Rechecked each visit.
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(() => {}); }
}
const session = req => store.session(cookies(req)['vab.sid']);
networksso.init({ self: C.siteId, 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; }
store.upsertMember(v.wallet, patch);
await verifyNet(v.wallet, email).catch(() => {});
return cookie('vab.sid', store.mintSession(v.wallet), store.SESSION_TTL / 1000, true);
},
landing: to => to, signinPath: to => to });
// ---- old site links (the VBB pattern): /?<old username>, /splashpg.php?pid=N&r=<old>, /lcp.php?pid=N&r=<old> -> the same person's
// page here (oldrefs.json, a MySQL document loaded by POST /api/admin/oldrefs, matched by email); any other *.php -> / ----
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 : '/'; }
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 ? '/' + encodeURIComponent(net) : '/';
}
const ZONE_404 = 'ls-c6c515'; // LinkSpin zone "ViralAdBlitz not found" (300x250) on Marty's LinkSpin account (2026-11-15); '' = off
const PAGES = { '/': 'index.html', '/how': 'how.html', '/my': 'my.html', '/boost': 'boost.html', '/ledger': 'ledger.html', '/contract': 'contract.html', '/admin': 'admin.html',
'/terms': 'terms.html', '/disclaimer': 'disclaimer.html', '/privacy': 'privacy.html' };
const RESERVED = new Set(['api', 'assets', 'art', 'go', 'r', 'sso', 'health', 'promote', 'sitemap.xml', 'robots.txt', 'favicon.ico', 'index.php', 'how', 'my', 'boost', 'ledger', 'contract', 'admin', 'terms', 'disclaimer', 'privacy']);
const challenges = new Map();
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 ''; } };
// ---- a member page: their ad, the first 5 people above them in the hub line who have a live ad here, and Boosted places ----
async function memberPage(name) {
const local = store.memberByName(name);
const lo = await hubline.lineOf({ ref: name.toLowerCase() }, C.lineSearch);
const person = lo.person;
const ownerAddr = local ? local.address : person ? hubpeople.wallet(person) : null;
const ownerName = (person && person.username) || (local && local.username) || name;
const own = ownerAddr ? store.adOf(ownerAddr) : null;
const ownAd = own && own.status === 'live' ? own : null;
const line = []; const used = new Set(ownAd ? [ownAd.id] : []);
for (const p of lo.line) {
if (line.length >= C.levels) break;
let a = p.wallet ? store.adOf(p.wallet) : null;
if (!a && p.username) { const lm = store.memberByName(p.username); if (lm) a = store.adOf(lm.address); }
if (a && a.status === 'live' && a.owner !== ownerAddr && !used.has(a.id)) { used.add(a.id); line.push({ level: line.length + 1, depth: p.depth, ad: a }); } // LEVEL n = the nth row shown (Marty 2026-11-14); depth = real place
}
const boosted = wire.pickBoosted(C.boostSlots, used);
return { known: !!(local || person), hubOk: lo.ok, stale: !!lo.stale, ownerAddr, ownerName, ownAd, line, boosted };
}
// ---- a page load's ads + its visit ticket (the ads it showed, decided here, never by the browser) ----
function issueTicket(req, page, shownIds, ref, src) {
if (isBot(req) || req.headers['sec-fetch-site'] === 'cross-site' || limited(req, 'ticket', 240, 3600000)) return null;
const s = session(req); const t = crypto.randomBytes(12).toString('hex');
tickets.set(t, { vk: visitorKey(req), iph: ipKey(req), at: Date.now(), page, shown: [...new Set(shownIds)], ref: ref || null, src: srcHost(src), viewer: s ? s.address : null });
if (tickets.size > 50000) { const cut = Date.now() - 1800000; for (const [k, v] of tickets) if (v.at < cut) tickets.delete(k); }
return t;
}
const todayStats = () => { const t = store.today(); return { views: t.views || 0, vclicks: t.vclicks || 0, boosts: t.boosts || 0, ads: store.liveAds().length }; };
// with no ref, the join page without a sponsor: /join/{ref} becomes the site root, ?ref={ref} is dropped
const joinUrl = ref => ref ? C.joinUrl.split('{ref}').join(encodeURIComponent(ref)) : C.joinUrl.replace(/\/join\/\{ref\}.*$/, '/').replace(/[?&]ref=\{ref\}/, '').split('{ref}').join('');
// tracking macros in an ad link, filled on every click: {clickid} a fresh id, {placement} where it was clicked
const MACRO = /\{(clickid|placement)\}|%7B(clickid|placement)%7D/gi;
function clickLink(a, placement) {
const l = String(a.link || ''); if (!l.match(MACRO)) return l;
const v = { clickid: crypto.randomBytes(8).toString('hex'), placement: String(placement || 'site').replace(/[^a-z0-9-]/gi, '').slice(0, 20) || 'site' };
return l.replace(MACRO, (x, p1, p2) => v[(p1 || p2).toLowerCase()]);
}
function cleanText(s, max) { return String(s == null ? '' : s).replace(/[\u0000-\u001f\u007f<>]/g, ' ').replace(/[\u2013\u2014]/g, '-').replace(/\s+/g, ' ').trim().slice(0, max + 1); }
function myEarned(me) {
let wei = 0n; const list = [];
for (const x of wire.purchases()) for (const p of x.pays || []) if (p.level > 0 && p.to === me) { try { wei += BigInt(p.wei); } catch (e) {} list.push({ tx: String(x.key).split(':')[0], at: (x.blockAt ? x.blockAt * 1000 : x.at), level: p.level, depth: p.depth, wei: p.wei, failed: !!p.failed, buyerName: (store.member(x.buyer) || {}).username || null }); }
return { wei: wei.toString(), items: list.sort((a, b) => (b.at || 0) - (a.at || 0)).slice(0, 50) };
}
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(); } }
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('vab.ref', ref, 30 * 86400, false);
if (p === '/my' || p === '/admin') ex['X-Frame-Options'] = 'DENY';
return sendFile(res, path.join(PUB, PAGES[p]), ex);
}
if (/^\/r\/[^/]+$/.test(p)) { res.writeHead(302, { Location: '/' + encodeURIComponent(decodeURIComponent(p.slice(3))) }); return res.end(); }
if (p === '/sitemap.xml') {
const day = new Date().toISOString().slice(0, 10);
const urls = ['/', '/how', '/boost', '/ledger', '/contract', '/promote', '/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);
}
// click relay: /go/<ad id>?v=<verified token>&p=<placement> -> the ad's link. Verified clicks rank the weekly board.
const gm = /^\/go\/(\d{1,9})$/.exec(p);
if (gm) {
const a = store.ad(gm[1]); if (!a || a.status === 'removed') { res.writeHead(302, { Location: '/' }); return res.end(); }
const pl = String(u.searchParams.get('p') || '').slice(0, 20);
if (!isBot(req) && !limited(req, 'click', 600, 3600000)) { const vk = visitorKey(req); const s = session(req); wire.click(a, vk, wire.vtokenOk(vk, u.searchParams.get('v')), s ? s.address : null, pl); }
res.writeHead(302, { Location: lstrack.dest(a) || clickLink(a, pl), 'Cache-Control': 'no-store', 'Referrer-Policy': 'origin' }); return res.end(); // the member's LinkSpin tracked link when it is current (lstrack.js), else their own link
}
// a member page: viraladblitz.com/<network username>
const pm = PAGE_RE.exec(p);
if (pm && !RESERVED.has(pm[1].toLowerCase()) && !/\.php$/i.test(pm[1])) {
const name = pm[1];
const known = store.memberByName(name) || (await hubpeople.byRef(name.toLowerCase()).then(h => (h.ok ? h.person : 'down')).catch(() => 'down'));
if (known) return sendFile(res, path.join(PUB, 'member.html'), { 'Set-Cookie': cookie('vab.ref', name, 30 * 86400, false) });
}
}
// -- 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,
boost: C.boost, split: C.split, deliverDays: C.deliverDays, levels: C.levels, visitSeconds: C.visitSeconds, ad: C.ad, sso: networksso.enabled(),
shop: { live: shop.watching(), contract: shop.watching() ? C.contractAddress : null }, explorer: C.explorer, joinUrl: joinUrl('') });
}
// everything a page shows, with its visit ticket. page=front|member|other, u=<username> for member pages
if (p === '/api/wire' && req.method === 'GET') {
const kind = ['front', 'member'].includes(u.searchParams.get('page')) ? u.searchParams.get('page') : 'other';
const tick = wire.ticker(); const shown = tick.map(x => x.id); const out = { ticker: tick, today: todayStats(), week: wire.weekStats() };
let ref = null;
if (kind === 'front') { out.board = wire.board(); out.board.items.forEach(x => shown.push(x.id)); out.joinUrl = joinUrl(''); }
if (kind === 'member') {
const name = String(u.searchParams.get('u') || ''); if (!NAME_RE.test(name)) return json(res, 404, { error: 'Not found' });
const mp = await memberPage(name);
if (!mp.known && mp.hubOk) return json(res, 404, { error: 'No network member by that name.' });
const boostedIds = new Set(wire.activeBoosts().map(b => b.adId));
out.page = { username: mp.ownerName, known: mp.known, hubOk: mp.hubOk, ad: mp.ownAd ? wire.adCard(mp.ownAd, boostedIds.has(mp.ownAd.id)) : null,
line: mp.line.map(x => Object.assign({ level: x.level, depth: x.depth }, wire.adCard(x.ad, boostedIds.has(x.ad.id)))), boosted: mp.boosted.map(a => wire.adCard(a, true)),
joinUrl: joinUrl(mp.ownerName) };
if (mp.ownAd) shown.push(mp.ownAd.id); mp.line.forEach(x => shown.push(x.ad.id)); mp.boosted.forEach(a => shown.push(a.id));
ref = mp.ownerAddr;
}
// PolHunter hunters (mission on the front page's How it works, 2026-11-15) are paid to be here: their visit is never a verified
// view or click (no ticket: no ad views, no Boost delivery, no verified-click token). The page says so with hunt=1 (a ?ph= / #ph=
// token or PolHunter's tab token), or the visit comes from polhunter.com.
const hunt = u.searchParams.get('hunt') === '1' || srcHost(u.searchParams.get('src')) === 'polhunter.com';
out.ticket = hunt ? null : issueTicket(req, kind === 'member' ? 'member:' + String(u.searchParams.get('u')).toLowerCase() : kind, shown, ref, u.searchParams.get('src'));
if (hunt) { out.hunt = true; store.bump('huntVisits'); }
out.seconds = C.visitSeconds;
return json(res, 200, out);
}
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, { verified: 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, { verified: false, why: 'early' });
tickets.delete(String(b.ticket));
if (age > 1800000) return json(res, 200, { verified: false, why: 'ticket' });
const r = wire.verify(t);
return json(res, 200, Object.assign(r, r.verified ? { vt: wire.vtoken(t.vk) } : {}));
}
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);
// toasts: real events of the last 30 minutes (new ads, Boosts with the levels they paid)
if (p === '/api/recent' && req.method === 'GET') {
const cut = Date.now() - 30 * 60000;
const ads = store.liveAds().filter(a => a.createdAt > cut).slice(-6).map(a => ({ kind: 'ad', key: 'a' + a.id, at: a.createdAt, name: (store.member(a.owner) || {}).username || null, headline: a.headline }));
const boosts = proof.ledger(10).items.filter(x => x.at && x.at > cut).map(x => ({ kind: 'boost', key: 'b' + x.tx + x.orderId, at: x.at, name: x.buyerName, levels: x.pays.filter(q => q.level > 0 && !q.failed).length }));
return json(res, 200, { items: ads.concat(boosts).sort((a, b) => b.at - a.at) }, { 'Cache-Control': 'public, max-age=10' });
}
if (p === '/api/quote' && req.method === 'GET') {
if (!shop.watching()) return json(res, 503, { error: 'Boosts are not open yet.' });
if (limited(req, 'quote', 600, 3600000)) return json(res, 429, { error: 'Too many requests this hour.' });
const qty = Number(u.searchParams.get('qty') || 1);
if (!Number.isInteger(qty) || qty < 1 || qty > C.boost.maxQty) return json(res, 400, { error: 'Pick 1 to ' + C.boost.maxQty + ' Boosts.' });
try { return json(res, 200, Object.assign({ usd: C.boost.usd * qty, views: C.boost.views * qty }, await shop.quote(C.boost.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 }); }
}
// 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\nViralAdBlitz 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);
store.upsertMember(a, store.member(a) ? {} : { via: 'wallet' });
await verifyNet(a).catch(() => {});
return json(res, 200, { ok: true, address: a }, { 'Set-Cookie': cookie('vab.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('vab.sid', '', 0, true), networksso.offCookie()] });
}
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, netVerified: netVerified(m) });
}
// -- 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)) store.upsertMember(me, { via: 'wallet' });
if (p === '/api/my' && req.method === 'GET') {
await verifyNet(me).catch(() => {}); const m = store.member(me); m.lastSeen = Date.now();
const a = store.adOf(me); const lo = netVerified(m) ? await hubline.lineOf({ wallet: me }, C.lineSearch) : { ok: true, line: [] };
const line = []; for (const x of lo.line) { if (line.length >= C.levels) break; const la = x.wallet ? store.adOf(x.wallet) : null; line.push({ depth: x.depth, username: x.username, hasWallet: !!x.wallet, hasAd: !!(la && la.status === 'live') }); }
const page = m.username ? 'https://' + C.site + '/' + encodeURIComponent(m.username) : null;
let ls = null; // LinkSpin tracking of the ad (lstrack.js): state, the tracked link, its clicks as LinkSpin counts them
if (a) { const stt = lstrack.state(a); ls = { on: lstrack.on(), track: a.track !== false, state: stt, link: stt === 'tracked' ? a.ls.link : null, clicks: null };
if (stt === 'tracked' && m.username) { const cs = await lstrack.clicks(m.username).catch(() => null); if (cs && cs[String(a.id)]) { const c0 = cs[String(a.id)]; ls.clicks = { hits: c0.hits || 0, hits30: c0.hits30 || 0, unique30: c0.unique30 || 0 }; } } }
return json(res, 200, { address: me, username: m.username, netVerified: netVerified(m), ad: a ? { id: a.id, headline: a.headline, line1: a.line1, line2: a.line2, link: a.link, status: a.status, views: a.views || 0, clicks: a.clicks || 0, vclicks: a.vclicks || 0, createdAt: a.createdAt, track: a.track !== false, spin: !!a.spin } : null, linkspin: ls,
boosts: wire.purchases().filter(b => b.buyer === me).sort((x, y) => (y.at || 0) - (x.at || 0)).map(wire.boostView), earned: myEarned(me), line: line.slice(0, 8), lineOk: lo.ok,
page, joinUrl: joinUrl(''), boost: C.boost });
}
// "Use one of my spin links" (Marty 2026-11-15): the member's own LinkSpin spin links, read from LinkSpin (lstrack.spins)
if (p === '/api/my/spins' && req.method === 'GET') {
if (limited(req, 'spins', 120, 3600000)) return json(res, 429, { error: 'Too many requests this hour.' });
const m = store.member(me); if (!netVerified(m)) return json(res, 403, { error: 'Sign in through InstantAdPay or LinkSpin to use your spin links.' });
const r = await lstrack.spins(m.username); if (r.error) return json(res, 502, { error: r.error });
return json(res, 200, { account: r.account !== false, spins: r.spins || [] });
}
// the member's one text ad: create, or edit (a Boost follows the ad, so editing keeps it)
if (p === '/api/my/ad' && req.method === 'POST') {
if (limited(req, 'ad', 30, 3600000)) return json(res, 429, { error: 'Too many changes this hour.' });
const m = store.member(me); await verifyNet(me).catch(() => {});
if (!netVerified(m)) return json(res, 403, { error: 'Text ads are free for network members. Join InstantAdPay or LinkSpin free, then sign in here through them.', join: joinUrl('') });
const b = await readBody(req);
const headline = cleanText(b.headline, C.ad.headline), line1 = cleanText(b.line1, C.ad.line), line2 = cleanText(b.line2, C.ad.line);
if (headline.length < 3 || headline.length > C.ad.headline) return json(res, 400, { error: 'Write a headline of 3 to ' + C.ad.headline + ' characters.' });
if (line1.length < 3 || line1.length > C.ad.line) return json(res, 400, { error: 'Write the first line in 3 to ' + C.ad.line + ' characters.' });
if (line2.length > C.ad.line) return json(res, 400, { error: 'Keep the second line to ' + C.ad.line + ' characters.' });
const lk = safety.checkLink(b.link, 'Your link'); if (lk.error) return json(res, 400, lk);
// a LinkSpin spin link (/r/<code> on a LinkSpin host) is accepted ONLY when LinkSpin confirms it is this member's own
// (lstrack.checkSpin, Marty 2026-11-15). It is already tracked on LinkSpin, so it never gets the tracked-link wrapper.
const sp = await lstrack.checkSpin(lk.url, m.username); if (sp.error) return json(res, 400, { error: sp.error });
const spin = sp.spin ? sp.code : null;
const cur = store.adOf(me);
if (C.linkProbe && (!cur || cur.link !== lk.url)) { const pr = await safety.probeLink(lk.url, { frames: false }); if (pr.error) return json(res, 400, pr); }
// "Track with LinkSpin" (default on): the ad's public link goes through the member's own LinkSpin tracked link (lstrack.js).
// LinkSpin is asked right away (at most 4 s); if it does not answer, the ad goes live with its own link and the sweep retries.
const track = b.track === undefined ? (cur ? cur.track !== false : true) : b.track !== false && b.track !== 'off' && b.track !== 0;
const lsNow = async x => { if (!lstrack.on() || x.track === false) return lstrack.state(x); await Promise.race([lstrack.ensureAd(x).catch(() => {}), new Promise(r => setTimeout(r, 4000).unref())]); return lstrack.state(x); };
if (cur) { Object.assign(cur, { headline, line1, line2, link: lk.url, track, spin, status: cur.status === 'paused' ? 'paused' : 'live' }); if (cur.link !== (cur.ls && cur.ls.url)) delete cur.lsTry; store.saveAd(cur); return json(res, 200, { ok: true, ad: { id: cur.id }, created: false, linkspin: await lsNow(cur) }); }
const a = store.addAd({ owner: me, headline, line1, line2, link: lk.url, track, spin, status: 'live', views: 0, clicks: 0, vclicks: 0 }); store.bump('adsPosted');
wire.attachPending(me, a.id);
return json(res, 200, { ok: true, ad: { id: a.id }, created: true, linkspin: await lsNow(a) });
}
// a Boost: the buy() call for the member's own wallet, with a fresh line voucher when the line is not bound on chain yet
if (p === '/api/my/order' && req.method === 'POST') {
if (!shop.watching()) return json(res, 503, { error: 'Boosts 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 qty = Number(b.qty || 1);
if (!Number.isInteger(qty) || qty < 1 || qty > C.boost.maxQty) return json(res, 400, { error: 'Pick 1 to ' + C.boost.maxQty + ' Boosts.' });
const a = store.adOf(me); if (!a || a.status !== 'live') return json(res, 400, { error: 'Post your text ad first. A Boost is for your ad.' });
let v = null, why = null; const bound = await shop.boundSponsor(me);
if (bound) why = 'bound';
else if (bound === undefined) return json(res, 503, { error: 'The chain did not answer just now. Try again in a minute.' });
else if (!shop.voucherOn()) why = 'off';
else {
const lo = await hubline.lineOf({ wallet: me }, shop.MAX_LINE);
if (!lo.ok) return json(res, 503, { error: 'Your sponsor line could not be checked with the network just now. Try again in a minute, so your team gets paid.' });
const wallets = lo.line.filter(x => x.wallet && x.wallet !== me).map(x => x.wallet);
if (!wallets.length) why = 'no-line'; else v = await shop.voucher(me, wallets);
}
try { return json(res, 200, Object.assign({ buyer: me, usd: C.boost.usd * qty, views: C.boost.views * qty, qty, adId: a.id, why }, await shop.order(me, C.boost.sku, qty, a.id, v))); }
catch (e) { return json(res, 503, { error: 'Price unavailable right now. Try again in a minute.' }); }
}
if (p === '/api/my/paid' && req.method === 'POST') { shop.nudge(); return json(res, 200, { ok: true, confirmations: C.shopConfirmations }); }
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 B = wire.purchases().map(wire.boostView);
return json(res, 200, { day: store.ctDay(), week: store.ctWeek(), config: { boost: C.boost, split: C.split, deliverDays: C.deliverDays, visitSeconds: C.visitSeconds, perIpDay: C.perIpDay, boostSlots: C.boostSlots, tickerBoosts: C.tickerBoosts, lineSearch: C.lineSearch },
today: store.today(), totals: S.totals, members: store.members().length, ads: { live: store.liveAds().length, all: store.ads().length },
boosts: { orders: B.length, views: B.reduce((t, b) => t + b.views, 0), delivered: B.reduce((t, b) => t + b.delivered, 0), active: B.filter(b => b.remaining > 0).length, late: B.filter(b => b.status === 'finishing-in-network').length, waitingForAd: B.filter(b => b.status === 'waiting-for-ad').length },
rows: { visits: store.visits().length, clicks: store.clicks().length, boostViews: store.bviews().length },
shop: shop.view(), proof: proof.view(), hub: hubreport.view(), hubLookup: hubpeople.view(), nas: vabnas.view(), linkspin: lstrack.view(), docstore: docstore.view(), oldrefs: Object.keys(oldRefMap()).length });
}
if (p === '/api/admin/boosts' && req.method === 'GET') return json(res, 200, { boosts: wire.purchases().map(x => Object.assign(wire.boostView(x), { buyer: x.buyer, usdCents: x.usdCents, weiPaid: x.weiPaid, pays: x.pays || null, over: x.over || null })).sort((a, b) => (b.at || 0) - (a.at || 0)) });
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 });
}
if (p === '/api/admin/nas/tick' && req.method === 'POST') return json(res, 200, await vabnas.tick());
// remove an ad that breaks the rules (spam, a dead or harmful link); its Boosts stop delivering until the owner posts again
if (p === '/api/admin/ad' && req.method === 'POST') {
const b = await readBody(req); const a = store.ad(b.id); if (!a) return json(res, 404, { error: 'not found' });
if (!['live', 'paused', 'removed'].includes(b.status)) return json(res, 400, { error: 'status live | paused | removed' });
a.status = b.status; a.note = cleanText(b.note, 200); store.saveAd(a); return json(res, 200, { ok: true, ad: a });
}
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 ad = store.ad(Number(q.replace('#', ''))); a = ad ? ad.owner : null; via = 'ad'; }
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 = wire.purchases();
return json(res, 200, { via, address: a, record: store.member(a), ad: store.adOf(a), boosts: P.filter(x => x.buyer === a).map(wire.boostView), earned: myEarned(a),
paidBy: P.filter(x => (x.pays || []).some(q2 => q2.to === a && q2.level > 0)).map(x => ({ tx: String(x.key).split(':')[0], buyer: x.buyer })), 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 | ViralAdBlitz</title><body style="background:#EAF0FF;color:#0A1F6B;font-family:Inter,system-ui,sans-serif;text-align:center;padding:40px 16px"><p style="font-size:22px;font-weight:700">Not found.</p><p><a style="color:#C4111A;font-weight:700" href="/">Back to the wire</a></p>'
+ (ZONE_404 ? '<p style="color:#3E4C7A;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' });
}
});
(async () => {
await docstore.init({ splits: store.SPLITS });
process.on('SIGTERM', () => { store.flush(); docstore.drain(8000).finally(() => process.exit(0)); });
store.load();
wire.init({ nasServed: key => vabnas.boostServed(key) });
store.prune(); wire.rebuild();
hubreport.init({ dataDir: C.dataDir, purchases: () => wire.purchases().map(x => ({ key: x.key, buyer: x.buyer, sponsor: x.sponsor || null, usdCents: x.usdCents, block: x.block, at: x.at })) });
proof.init(C, { shop, wire, nameOf: async a => { const m = await netMember({ a }).catch(() => null); return m && m.address === a ? m.username : null; } });
shop.setAttach(rec => { wire.attach(rec); store.bump('boosts', Number(rec.qty) || 1); });
shop.setHook(proof.onPurchase);
shop.init(C);
vabnas.init({ boosts: () => wire.purchases(), remaining: b => wire.remaining(b), ad: id => store.ad(id) });
setInterval(() => { if (store.prune()) wire.rebuild(); }, 3600000).unref();
chatbot.init(); // after docstore.init: kb.json is a MySQL document
lstrack.init(C, store); // LinkSpin tracked links for text ads: retry sweep (fails soft while LinkSpin is down or does not know the endpoint)
{ let busy = false; const tick = () => { if (busy) return; busy = true; lstrack.sweep(25).catch(() => {}).finally(() => { busy = false; }); };
setTimeout(tick, Number(process.env.LS_SWEEP_FIRST_MS || 20000)).unref(); setInterval(tick, Number(process.env.LS_SWEEP_MS || 120000)).unref(); }
server.listen(C.port, () => console.log('ViralAdBlitz on :' + C.port + ', Boost $' + C.boost.usd + ' = ' + C.boost.views + ' views, 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); });