// Viral Banner Blitz web app (viralbannerblitz.com rebuild, "VBB"). Plain Node http server, no framework (the InstantAdPay and // Downline Banners pattern). v1 is off-chain: no contract, no prices, no money. // VBBShop hooks (shop.js): GET /api/my/voucher signs a sponsor voucher; the purchase watcher credits packs. Both inert until configured. // 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 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; worker-src 'self' blob:; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; " + "img-src 'self' data: blob: https:; connect-src 'self' https://*.walletconnect.com wss://*.walletconnect.com https://*.walletconnect.org wss://*.walletconnect.org " + "https://*.reown.com wss://*.reown.com https://*.reown.org wss://*.reown.org https://*.web3modal.org https://*.drpc.org https://*.publicnode.com https://*.coinbase.com; " + "font-src 'self' data: https://fonts.gstatic.com https://fonts.reown.com; form-action 'self'; frame-src https: '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 (InstantAdPay today, the network hub later: this is the one place to point at it) ---- const netCache = new Map(); async function netMember(q) { 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), sponsor: ADDR_RE.test(j.sponsor || '') ? j.sponsor.toLowerCase() : null }; } catch (e) { return null; } netCache.set(k, { at: Date.now(), m }); if (netCache.size > 20000) netCache.clear(); return m; } // ?ref= -> 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): signed in through InstantAdPay or // LinkSpin, or a wallet the network knows. A plain wallet is rechecked on each visit, so joining InstantAdPay later unlocks it. const netVerified = m => !!m && (m.via === 'iap' || m.via === 'linkspin' || m.netOk === true); async function verifyNet(addr) { const m = store.member(addr); if (!m || netVerified(m)) return; const n = await netMember({ a: addr }).catch(() => null); if (n && n.address === m.address) { store.upsertMember(addr, { netOk: true }); 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 }, loop.placeOf(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) }; } // ---- 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); return cookie('vbb.sid', store.mintSession(v.wallet), store.SESSION_TTL / 1000, true); }, landing: to => to, signinPath: to => to }); const PAGES = { '/': 'index.html', '/my': 'my.html', '/leaders': 'leaders.html', '/how': 'how.html', '/packages': 'packages.html', '/admin': 'admin.html' }; 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' && (p.startsWith('/sso/') || p === '/api/sso/status') && await networksso.handle(req, res, u)) return; if (req.method === 'GET' || req.method === 'HEAD') { 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'].map(x => 'https://' + C.site + x + '' + day + '').join(''); res.writeHead(200, headers({ 'Content-Type': 'application/xml; charset=utf-8', 'Cache-Control': 'public, max-age=3600' })); return res.end('' + urls + ''); } 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/ 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) { res.writeHead(302, { Location: '/' }); return res.end(); } 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: b.link, 'Cache-Control': 'no-store', 'Referrer-Policy': 'origin' }); return res.end(); } } // this week's prize pot. v1 takes no payments, so week sales are 0 and the pot sits at the floor until the contract step. function prizes(weekSalesUsd = 0) { const z = C.prizePot; const pot = Math.min(z.capUsd, Math.max(z.floorUsd, weekSalesUsd * z.pct / 100)); const board = pot / 2, r2 = x => Math.round(x * 100) / 100, per = z.places.map(x => r2(board * x / 100)); return { pot: r2(pot), atFloor: pot <= z.floorUsd, visitors: per, sources: per }; } // -- 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, prizes: prizes(), sso: networksso.enabled() }); } if (p === '/api/splash' && req.method === 'GET') return json(res, 200, loop.view(24), { '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()] }); } 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 n = await netMember({ a: me }).catch(() => null); const sp = n && n.address === me ? n.sponsor : null; if (!sp || sp === me) return json(res, 200, { voucher: null, why: 'no-sponsor' }); return json(res, 200, { voucher: await shop.voucher(me, sp) }); } 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').length; if (waiting >= C.maxQueuedPerMember) return json(res, 400, { error: 'You already have ' + waiting + ' banners waiting. Post again when one enters the loop.' }); const lk = safety.checkLink(b.link, 'Target link'); if (lk.error) return json(res, 400, lk); let img = String(b.img || '').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 json(res, 400, { error: 'Upload the image again.' }); } else { const ic = safety.checkLink(img, 'Image address'); if (ic.error) return json(res, 400, ic); const f = await safety.fetchImage(ic.url); if (f.error) return json(res, 400, f); img = saveUpload(me, f.buf, f.info.ext); } 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(), docstore: docstore.view() }); } 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.' }); } 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('Not found

Not found. Back to the loop

'); } catch (e) { console.error('request', p, e.message); if (!res.headersSent) json(res, 500, { error: 'Server error' }); } }); 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(); shop.init(C); // inert without CONTRACT_ADDRESS + CHAIN_RPC (watcher) / KEEPER_KEY (vouchers) setInterval(() => { if (store.pruneVisits()) loop.rebuildIndex(); }, 3600000).unref(); 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); });