// Downline Banners 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 refuelspots = require('./refuelspots'); // refuel spots: $50+ Monthly Refuels earn a spot, engine wallet pays (2026-11-13) const hubreport = require('./hubreport'); // network hub, shadow mode: members reported by wallet (2026-11-13), off unless HUB_ENABLED const networksso = require('./networksso'); // network sign-in: arrive signed in from InstantAdPay or LinkSpin (2026-11-13), see networksso.js 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 }); const docstore = require('./docstore'); docstore.install(C.dataDir); // data documents live in MySQL when DOCSTORE_URL is set (Marty 2026-11-13: database is the standard) 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; } // ---- network usernames (Marty 2026-11-13: share links use the member's network username, not the wallet) ---- // One lookup for both directions. Today the usernames live in InstantAdPay (GET /api/network/member ?u= / ?a=); when the // network hub goes live this is the one place to point at it. Cached an hour, misses too. const netCache = new Map(); async function netMember(q) { 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) }; } catch (e) { return null; } // a failed call is not cached netCache.set(k, { at: Date.now(), m }); if (netCache.size > 20000) netCache.clear(); if (m) netCache.set('a:' + m.address, { at: Date.now(), m }); return m; } const nameOf = async addr => { const m = await netMember({ a: addr }); return m && m.address === addr.toLowerCase() ? m.username : null; }; // ---- LinkSpin Banner Spins for My Spots (Marty 2026-11-13: pull a Banner Spin in with a couple of clicks) ---- // Signed with NETWORK_SSO_SECRET: X-Net-Ts + X-Net-Sig = hex HMAC-SHA256('net.v1.' + ts + newline + raw body). LinkSpin answers // for the account holding the signed-in wallet only. async function lsSpins(body) { const sec = String(process.env.NETWORK_SSO_SECRET || '').trim(); if (sec.length < 32) return { error: 'LinkSpin link is not set up.' }; const raw = JSON.stringify(body); const ts = String(Date.now()); const sig = crypto.createHmac('sha256', sec).update('net.v1.' + ts + '\n' + raw).digest('hex'); const ac = new AbortController(); const t = setTimeout(() => ac.abort(), 8000); try { const r = await fetch(C.lsBase + '/api/partner/bl/spins', { method: 'POST', body: raw, signal: ac.signal, headers: { 'Content-Type': 'application/json', 'X-Net-Ts': ts, 'X-Net-Sig': sig } }); const j = await r.json().catch(() => ({})); return r.ok ? j : { error: j.error || 'LinkSpin did not answer.' }; } catch (e) { return { error: 'LinkSpin did not answer. Try again in a minute.' }; } finally { clearTimeout(t); } } // ---- sponsor ref (?ref=
) ---- async function resolveRef(raw) { const r = String(raw || '').trim(); if (ADDR_RE.test(r)) return r.toLowerCase(); if (!/^[a-zA-Z0-9_]{1,20}$/.test(r) || !C.networkLookupUrl) return null; const m = await netMember({ u: r }); return m ? m.address : null; } 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 }; } async 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); const [username, sponsorName] = await Promise.all([nameOf(a), me && me.sponsor ? nameOf(me.sponsor) : null]); await Promise.all(dir.map(async d => { d.username = await nameOf(d.address); })); return { address: a, username, sponsorName, 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=' + (username || a) }; } // ---- server ---- // Downline Banners only RECEIVES network sign-ins: a member signed in on InstantAdPay (or LinkSpin) arrives signed in as the wallet that // site vouches for (the one they signed in with there, else the main wallet their account linked by signature). No email here. networksso.init({ self: 'bannerline', 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) => { if (v.name) netCache.set('a:' + v.wallet, { at: Date.now(), m: { address: v.wallet, username: v.name } }); return cookie('bl.sid', store.mintSession(v.wallet), store.SESSION_TTL / 1000, true); }, landing: to => to, signinPath: to => to }); const server = http.createServer(async (req, res) => { const u = new URL(req.url, 'http://x'); const p = u.pathname; // one address (Marty 2026-11-13: downlinebanners.com, not a subdomain): www. and new. move to the main domain, path and query kept { const host = String(req.headers.host || '').toLowerCase().split(':')[0]; if (C.isProd && host !== C.site && /(^|\.)downlinebanners\.com$/.test(host)) { res.writeHead(301, { Location: 'https://' + C.site + req.url, 'Cache-Control': 'no-store' }); return res.end(); } } 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 } : {}; // -- network sign-in (2026-11-13): /sso/start, /sso/in, /api/sso/status if (req.method === 'GET' && (p.startsWith('/sso/') || p === '/api/sso/status') && await networksso.handle(req, res, u)) return; // -- 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 === '/art/mark.svg' || 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. Downline Banners home
'); } catch (e) { console.error('request', p, e.message); if (!res.headersSent) json(res, 500, { error: 'Server error' }); } }); (async () => { await docstore.init({}); // before anything reads its data process.on('SIGTERM', () => { docstore.drain(8000).finally(() => process.exit(0)); }); store.load(); chain.init(); hubreport.init({ dataDir: C.dataDir, members: () => chain.allMembers() }); refuelspots.init({ lock: () => keeper.busy() }); keeper.setOtherBusy(() => refuelspots.busy()); keeper.init(); server.listen(C.port, () => console.log('Downline Banners on :' + C.port + ' chain ' + C.chainName + ' (' + C.chainId + ') contract ' + (C.contract || '(not set)') + ' store: ' + (docstore.isOn() ? 'MySQL documents' : 'volume JSON'))); })().catch(e => { console.error('start failed:', e.message); process.exit(1); }); process.on('SIGTERM', () => { store.flush(); process.exit(0); }); process.on('SIGINT', () => { store.flush(); process.exit(0); });