// Banner Line web app (downlinebanners.com). Plain Node http server, no framework (InstantAdPay pattern). // Pages: / (gate, then board + join), /board, /join (buy), /my (My Spots + dashboard), /how. // Chain index: chain.js. Board/rotation: board.js. Creative + link checks: safety.js. Keeper: keeper.js. 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 chain = require('./chain'); const store = require('./store'); const board = require('./board'); const safety = require('./safety'); const keeper = require('./keeper'); const { iface } = require('./abi'); const SEL = { buy: iface.getFunction('buy').selector, buyFor: iface.getFunction('buyFor').selector }; // the browser builds calldata from these (ABI stays in abi.js) const C = cfgMod.get(); fs.mkdirSync(path.join(C.dataDir, 'art'), { recursive: true }); store.load(); chain.init(); keeper.init(); const PUB = path.join(__dirname, 'public'); const ADDR_RE = /^0x[0-9a-fA-F]{40}$/; const BOT_UA = /bot|crawl|spider|slurp|facebookexternalhit|preview|monitor|wget|curl|python-requests|httpclient|scrapy|semrush|ahrefs/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 hmac = s => crypto.createHmac('sha256', SECRET).update(s).digest('hex').slice(0, 32); // ---- 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' }; 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; // over the limit: keep draining (so the 400 reaches the client) but store nothing; cut the socket only far past it 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' : ''); } function ip(req) { return String(req.headers['cf-connecting-ip'] || (req.headers['x-forwarded-for'] || '').split(',')[0] || req.socket.remoteAddress || '').trim(); } const isBot = req => BOT_UA.test(req.headers['user-agent'] || '') || !req.headers['user-agent']; // visitor = IP + user agent (not a cookie: traffic-exchange frames drop cookies, and the gate must work there) function visitorKey(req) { return crypto.createHash('sha256').update(ip(req) + '|' + (req.headers['user-agent'] || '')).digest('hex').slice(0, 20); } // 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; } // ---- sponsor ref (?ref=
) ---- const refCache = new Map(); async function resolveRef(raw) { const r = String(raw || '').trim(); if (ADDR_RE.test(r)) return r.toLowerCase(); if (!/^[a-zA-Z0-9_.-]{2,32}$/.test(r) || !C.iapResolveUrl) return null; const hit = refCache.get(r.toLowerCase()); if (hit && Date.now() - hit.at < 3600000) return hit.a; let a = null; try { const ac = new AbortController(); setTimeout(() => ac.abort(), 4000).unref(); const j = await (await fetch(C.iapResolveUrl + encodeURIComponent(r), { signal: ac.signal })).json(); if (j && ADDR_RE.test(j.address || '')) a = j.address.toLowerCase(); } catch (e) {} refCache.set(r.toLowerCase(), { at: Date.now(), a }); return a; } const sponsorOf = req => { const v = cookies(req)['bl.ref']; return ADDR_RE.test(v || '') ? v.toLowerCase() : null; }; // ---- sessions (wallet signature sign-in) ---- const challenges = new Map(); function session(req) { const s = store.session(cookies(req)['bl.sid']); return s; } // ---- gate ---- const gates = new Map(); // gid -> plan const GATE_TTL = 2 * 3600000; function passToken(vk) { const exp = Date.now() + 24 * 3600000; return exp + '.' + hmac('pass:' + vk + ':' + exp); } const passedKeys = new Map(); // vk -> expiry, for visitors whose browser dropped the pass cookie (framed) function passed(req) { const vk = visitorKey(req); if ((passedKeys.get(vk) || 0) > Date.now()) return true; const t = cookies(req)['bl.pass'] || ''; const [exp, sig] = t.split('.'); return Number(exp) > Date.now() && sig === hmac('pass:' + vk + ':' + exp); } async function visitStep(role, ref, img, link, title) { return { type: 'visit', role, ref: String(ref), img, title: title || '', seconds: C.gateVisitSeconds, frame: await board.frameable(link), open: '/go/' + ref }; } async function makeGate(req) { const vk = visitorKey(req); const steps = []; const sp = sponsorOf(req); const sSpot = sp && board.newestOf(sp); if (sSpot) { const cr = board.creative(sSpot); steps.push(await visitStep('sponsor', sSpot.id, cr.img, cr.link, 'Your sponsor\'s newest spot')); } steps.push({ type: 'board', tiles: board.pick(), seconds: C.gateBoardSeconds }); const nw = board.newest(3, sSpot ? [sSpot.id] : []); for (const s of nw) { const cr = board.creative(s); steps.push(await visitStep('newest', s.id, cr.img, cr.link, 'Spot #' + s.id)); } const house = cfgMod.house().filter(h => h.link.startsWith('https://')); let hi = 0; while (steps.filter(x => x.role === 'newest' || x.role === 'house').length < 3 && house.length) { const h = house[hi++ % house.length]; steps.push(await visitStep('house', 'h-' + h.key, h.img, h.link, h.title)); if (hi > 6) break; } const gid = crypto.randomBytes(12).toString('hex'); const g = { gid, vk, created: Date.now(), steps, idx: 0, stepStart: 0 }; gates.set(gid, g); if (gates.size > 20000) { const cut = Date.now() - GATE_TTL; for (const [k, v] of gates) if (v.created < cut) gates.delete(k); } return g; } // one-time board tokens for organic views const boardTokens = new Map(); // ---- dashboard data ---- function spotView(s) { const v = store.views(s.id); const m = store.spotMeta(s.id) || {}; const cr = board.creative(s); const now = Date.now(); const left = Math.max(0, C.spotDays - Math.floor((now - s.boughtAt) / 86400000)); return { id: s.id, kind: s.kind, boughtAt: s.boughtAt, tx: s.tx, valueWei: s.valueWei, views: v.total, gateViews: v.gate, owed: C.viewsOwed, clicks: store.clicks(s.id), daysLeft: left, delivering: s.kind !== 3 && left > 0 && v.total < C.viewsOwed, img: m.img || '', link: m.link || '', showing: cr }; } function myData(addr) { const a = addr.toLowerCase(); const mine = chain.spotsOf(a).map(spotView); const w = chain.walletTotals(a); const dir = chain.directs(a).map(m => { const ss = chain.spotsOf(m.address); return { address: m.address, joinedAt: m.joinedAt, spots: ss.length, paidSpots: ss.filter(x => x.kind === 0).length, paidInWei: ss.filter(x => x.kind === 0 || x.kind === 1).reduce((t, x) => t + BigInt(x.valueWei), 0n).toString() }; }); const me = chain.member(a); return { address: a, member: chain.isMember(a), sponsor: me ? me.sponsor : null, spots: mine, paidInWei: w.inWei, paidOutWei: w.outWei, byRole: w.byRole, payouts: chain.paidOf(a).slice(0, 50), directs: dir, defaults: store.memberDefault(a) || {}, share: 'https://' + C.site + '/?ref=' + a }; } // ---- server ---- const server = http.createServer(async (req, res) => { const u = new URL(req.url, 'http://x'); const p = u.pathname; try { // visitor cookie (used for rate limits only) const ck = cookies(req); const setVid = !ck['bl.vid'] && !isBot(req) ? cookie('bl.vid', crypto.randomBytes(9).toString('hex'), 365 * 86400, true) : null; const extra = setVid ? { 'Set-Cookie': setVid } : {}; // -- pages if (req.method === 'GET' || req.method === 'HEAD') { const PAGES = { '/': 'index.html', '/board': 'board.html', '/join': 'join.html', '/my': 'my.html', '/how': 'how.html' }; if (PAGES[p]) { const set = []; if (setVid) set.push(setVid); if (u.searchParams.get('ref')) { const a = await resolveRef(u.searchParams.get('ref')); if (a) set.push(cookie('bl.ref', a, 90 * 86400, false)); } const ex = set.length ? { 'Set-Cookie': set } : {}; if (p === '/my') ex['X-Frame-Options'] = 'DENY'; // member board: never framed (public pages stay frameable for traffic exchanges) 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.startsWith('/assets/') || p.startsWith('/art/house-') || p === '/logo-icon.png' || p === '/robots.txt') { const f = path.normalize(path.join(PUB, p)); if (!f.startsWith(PUB)) { res.writeHead(400); return res.end(); } return sendFile(res, f); } if (p.startsWith('/art/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(C.dataDir, 'art', name), { 'Cache-Control': 'public, max-age=86400' }); } // click relay: /go/Not found. Banner Line home
'); } catch (e) { console.error('request', p, e.message); if (!res.headersSent) json(res, 500, { error: 'Server error' }); } }); server.listen(C.port, () => console.log('Banner Line on :' + C.port + ' chain ' + C.chainName + ' (' + C.chainId + ') contract ' + (C.contract || '(not set)'))); process.on('SIGTERM', () => { store.flush(); process.exit(0); }); process.on('SIGINT', () => { store.flush(); process.exit(0); });