Files
banner-line/server.js
T

566 lines
45 KiB
JavaScript

// 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 dlbnas = require('./dlbnas'); // Network Ad Space: standing house banner + finishing spots still owed views after 30 days (2026-11-13)
const refuelspots = require('./refuelspots'); // refuel spots: $50+ Monthly Refuels earn a spot, engine wallet pays (2026-11-13)
const tgproof = require('./tgproof'); // payment proof in the Telegram payments topic, one message per spot sale (2026-11-13)
const hubreport = require('./hubreport'); // network hub, shadow mode: members reported by wallet (2026-11-13), off unless HUB_ENABLED
const promokit = require('./promokit'); // promo kit feed /api/promo-kit, the /promote page, /art/kit/* creatives (2026-11-14)
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 https://linkspin.app; 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://*.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' : ''); }
// Client IP. Behind Coolify's proxy the RIGHTMOST X-Forwarded-For entry is the one the proxy added; earlier entries and cf-connecting-ip
// are whatever the client sent (this domain is not on Cloudflare) and could fake many unique visitors. CF_PROXIED=1 only if Cloudflare proxies it.
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 => 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. The network hub answers first (Marty 2026-11-14: "want everything looped through the hub to
// verify membership"; hubpeople.js, cached 5 minutes); InstantAdPay's GET /api/network/member ?u= / ?a= only when the hub is
// unreachable (cached an hour, misses too; a failed call is not cached). A person the hub does not know is unknown here too.
const hubpeople = require('./hubpeople');
const netCache = new Map();
const fromHub = p => { const a = hubpeople.wallet(p); return a ? { address: a, username: p.username ? String(p.username) : null, hubId: p.id || null, via: 'hub' } : null; };
async function netMember(q) {
const h = q.u ? await hubpeople.byRef(q.u) : await hubpeople.byWallet(q.a);
if (h.ok) return fromHub(h.person);
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; } // 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;
}
// extra wallets a member bought with (Marty 2026-11-14: bizventures bought spot #3 from a second wallet the network does not know):
// wallet -> network username, set by the admin; wallet-aliases.json is a MySQL document (docstore)
const ALIAS_F = () => path.join(C.dataDir, 'wallet-aliases.json');
function aliases() { try { return JSON.parse(fs.readFileSync(ALIAS_F(), 'utf8')); } catch (e) { return {}; } }
const nameOf = async addr => { const al = aliases()[String(addr || '').toLowerCase()]; if (al) return al.username; const m = await netMember({ a: addr }); return m && m.address === String(addr).toLowerCase() ? m.username || null : 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); }
}
// ---- live ledger: chain events grouped into one row per spot sale ----
async function ledgerData(n) {
const evs = chain.recent(5000); const byTx = new Map();
for (const e of evs.slice().reverse()) { if (!['SpotBought', 'Paid', 'PaymentFailed', 'FundBuy'].includes(e.type)) continue; if (!byTx.has(e.tx)) byTx.set(e.tx, []); byTx.get(e.tx).push(e); }
const fee = new Set(['0x7627fc78876948ac9d95c1c9eb061e7d6d647b70', '0x8b7d33849a2c4d92c985be31e46dc564ba901ad2', String(C.contract).toLowerCase()]);
const items = [];
for (const [tx, list] of [...byTx].reverse()) {
const sb = list.find(e => e.type === 'SpotBought'); if (!sb) continue;
let level = 0, house = 0n; const pays = [];
for (const e of list) {
if (e.type !== 'Paid' && e.type !== 'PaymentFailed') continue;
if (e.role === 1) level++;
if (e.type === 'Paid' && (fee.has(e.to) || e.role >= 2)) { house += BigInt(e.amount); continue; }
pays.push({ role: e.role === 0 ? 'sponsor' : 'line', level: e.role === 1 ? level : null, to: e.to, name: await nameOf(e.to).catch(() => null), wei: e.amount, failed: e.type === 'PaymentFailed' });
}
items.push({ tx, at: sb.ts || null, spotId: sb.id, kind: sb.kind, owner: sb.owner, ownerName: await nameOf(sb.owner).catch(() => null), valueWei: sb.valueWei, usd: Number(sb.usdPrice) / 1e8, pays, houseWei: house.toString() });
if (items.length >= n) break;
}
let fund = null; try { const f = await chain.tryRead('fundBalance'); fund = f == null ? null : f.toString(); } catch (e) {}
return { items, totals: Object.assign(chain.totals(), { fundWei: fund }), explorer: C.explorer, contract: C.contract };
}
// ---- sponsor ref (?ref=<address or network username>) ----
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; };
// Returning Downline Banners members (Marty 2026-11-13). welcome.json (a MySQL document) maps each personal code to that member's
// sponsor line, nearest first: their network sponsor, then their old Downline Banners upline, as network usernames. /w/<code>
// keeps the code in a cookie; when the member opens the buy page, the first person in that line who has a wallet linked AND owns
// a spot here at that moment becomes the sponsor (the contract only binds a sponsor who is already a member). Nobody qualifies:
// no sponsor, never the company. A plain ?ref= link is used only when there is no personal code.
const WELCOME = () => { try { return JSON.parse(fs.readFileSync(path.join(C.dataDir, 'welcome.json'), 'utf8')); } catch (e) { return {}; } };
async function lineSponsor(req) {
const code = cookies(req)['bl.wl']; const w = code && /^[a-z0-9]{8,16}$/.test(code) ? WELCOME()[code] : null;
if (!w || !Array.isArray(w.line)) return null;
for (const un of w.line.slice(0, 25)) {
const m = await netMember({ u: un }).catch(() => null);
if (m && m.address && chain.isMember(m.address)) return { address: m.address, username: m.username, via: 'line' };
}
return { address: null, via: 'line' };
}
// The network sponsor from the hub (Marty 2026-11-14), for a buyer whose wallet the hub knows: their network sponsor, resolved to
// a wallet through the hub by hub id, if that wallet owns a spot here (the contract only binds a sponsor who is already a member);
// else that sponsor's own network sponsor, and so on up the network line (the same nearest-first rule as the /w/ welcome line, at
// most 12 up). Nobody up the line qualifies: no sponsor, never the company, and no ?ref= or welcome code overrides the network.
// undefined = the hub does not decide (unreachable, the wallet or its sponsor unknown, or the buyer is already a member here):
// the welcome line and the ?ref= cookie decide as before.
async function hubSponsor(wallet) {
const a = String(wallet || '').toLowerCase(); if (!ADDR_RE.test(a) || chain.isMember(a)) return undefined;
const me = await hubpeople.byWallet(a); if (!me.ok || !me.person || !me.person.sponsor) return undefined;
let cur = me.person; const seen = new Set([cur.id]);
for (let i = 0; i < 12 && cur.sponsor && cur.sponsor.id && !seen.has(cur.sponsor.id); i++) {
seen.add(cur.sponsor.id);
const s = await hubpeople.sponsorOf(cur); if (!s.ok) return undefined; if (!s.person) break;
const sw = hubpeople.wallet(s.person);
if (sw && sw !== a && chain.isMember(sw)) return { address: sw, username: s.person.username || null, via: 'hub', network: i === 0 };
cur = s.person;
}
return { address: null, via: 'hub' };
}
// the sponsor this buyer gets: forWallet = the wallet that will own the spot (the buy page asks just before the buy), else the
// signed-in wallet. Hub network sponsor first, then the personal welcome line, then the ?ref= cookie.
async function sponsorPick(req, forWallet) {
const s = session(req); const w = ADDR_RE.test(forWallet || '') ? forWallet.toLowerCase() : s ? s.address : null;
const h = w ? await hubSponsor(w).catch(() => undefined) : undefined; if (h) return h;
const l = await lineSponsor(req); if (l) return l;
const c = sponsorOf(req); return { address: c, via: c ? 'ref' : null };
}
async function sponsorFor(req, forWallet) { return (await sponsorPick(req, forWallet)).address; }
// ---- 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 v0 = store.views(s.id); const nasV = dlbnas.spotServed(s.id); const v = Object.assign({}, v0, { total: v0.total + nasV, nas: nasV }); 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;
if ((p === '/api/promo-kit' || p === '/promote' || p.startsWith('/art/kit/')) && promokit.handle(req, res, u, sendFile)) return;
// -- pages
if (req.method === 'GET' || req.method === 'HEAD') {
// old site links (2026-11-13): referral links were /?<old username> (bare query) and pages were *.php. An old username maps to
// the same person's network username (oldrefs.json, matched by email); a page address goes home.
if (/\.php$/i.test(p) || (p === '/' && /^[A-Za-z0-9_.-]{2,40}$/.test(u.search.slice(1).split('&')[0]))) { // "&fbclid=..." may follow
const old = /\.php$/i.test(p) && p !== '/index.php' ? '' : u.search.slice(1).split('&')[0].toLowerCase();
let OR = {}; try { OR = JSON.parse(fs.readFileSync(path.join(C.dataDir, 'oldrefs.json'), 'utf8')); } catch (e) {}
const net = old && OR[old]; res.writeHead(301, { Location: net ? '/?ref=' + encodeURIComponent(net) : '/', 'Cache-Control': 'no-store' }); return res.end();
}
const PAGES = { '/': 'index.html', '/board': 'board.html', '/join': 'join.html', '/my': 'my.html', '/how': 'how.html', '/ledger': 'ledger.html', '/contract': 'contract.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(); }
// sitemap (2026-11-13, SEO): the public pages only
if (p === '/sitemap.xml') {
const day = new Date().toISOString().slice(0, 10);
const urls = ['/', '/board', '/how', '/ledger', '/contract', '/join', '/promote'].map(u => '<url><loc>https://' + C.site + u + '</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.startsWith('/assets/') || p.startsWith('/art/house-') || p === '/art/mark.svg' || p === '/art/og-share.png' || 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' });
}
const wm = /^\/w\/([a-z0-9]{8,16})$/.exec(p);
if (wm) {
const ok = !!WELCOME()[wm[1]];
if (ok && !isBot(req)) { // returning-member link opens (2026-11-13): how many come back from the email, per code, first + last time
const VF = path.join(C.dataDir, 'welcome-visits.json'); let v = {}; try { v = JSON.parse(fs.readFileSync(VF, 'utf8')); } catch (e) {}
const r = v[wm[1]] || { n: 0, first: Date.now() }; r.n++; r.last = Date.now(); v[wm[1]] = r; try { fs.writeFileSync(VF, JSON.stringify(v)); } catch (e) {}
}
res.writeHead(302, { Location: '/', 'Cache-Control': 'no-store', 'Set-Cookie': ok ? cookie('bl.wl', wm[1], 120 * 86400, false) : cookie('bl.wl', '', 0, false) });
return res.end();
}
// click relay: /go/<spotId | h-key>[?g=<gid>&i=<step>] (gate visits counted apart from organic clicks)
if (/^\/go\/[\w-]+$/.test(p)) {
const ref = p.slice(4); const t = board.target(ref);
if (!t) { res.writeHead(302, { Location: '/' }); return res.end(); }
let kind = 'organic';
if (t.spotId && !isBot(req)) {
const g = gates.get(u.searchParams.get('g') || ''); const gi = Number(u.searchParams.get('i'));
const isGate = g && g.vk === visitorKey(req) && g.steps[gi] && g.steps[gi].ref === ref;
kind = isGate ? 'gate' : 'organic';
store.addClick(t.spotId, visitorKey(req), kind);
}
// tracking macros in a member's link (2026-11-13, LinkSpin's "Downline Banners" source): {clickid} a fresh id per click,
// {spot} the spot number, {type} gate or organic
const loc = !t.spotId || t.link.indexOf('{') < 0 ? t.link : t.link
.replace(/\{clickid\}/g, crypto.randomBytes(8).toString('hex')).replace(/\{spot\}/g, String(t.spotId)).replace(/\{type\}/g, kind);
res.writeHead(302, { Location: loc, 'Cache-Control': 'no-store', 'Referrer-Policy': 'origin' }); return res.end();
}
}
// -- public API
if (p === '/api/config' && req.method === 'GET') {
return json(res, 200, { site: C.site, chainId: C.chainId, chainName: C.chainName, contract: C.contract, rpc: C.publicRpc, explorer: C.explorer,
walletConnectProjectId: C.walletConnectProjectId, viewsOwed: C.viewsOwed, spotDays: C.spotDays, priceUsd: 5, ready: !!C.contract, sel: SEL }, extra);
}
// live ledger (Marty 2026-11-13): every spot sale as one row with its payouts, straight from the chain index; the toasts read it too
if (p === '/api/ledger' && req.method === 'GET') {
const n = Math.min(200, Math.max(1, Number(u.searchParams.get('n')) || 50));
return json(res, 200, await ledgerData(n), { 'Cache-Control': 'public, max-age=10' });
}
// contract proof: the live contract's own answers, so anyone can compare them with Polygonscan
if (p === '/api/contract' && req.method === 'GET') {
const r = async f => { const v = await chain.tryRead(f); return v == null ? null : (typeof v === 'bigint' ? v.toString() : String(v).toLowerCase()); };
const [owner, keeper, feeA, feeB, priceFeed, paused, spotCount, fundBalance, quoteWei] = await Promise.all(['owner', 'keeper', 'feeA', 'feeB', 'priceFeed', 'paused', 'spotCount', 'fundBalance', 'quoteWei'].map(r));
return json(res, 200, { address: C.contract, chain: C.chainName, chainId: C.chainId, explorer: C.explorer, verified: true,
deployTx: '0xbe0c76a0999af2b81cd73b69afbe168f08003afdb27dd4ed7be026943e23046d', deployBlock: Number(process.env.START_BLOCK) || null,
owner, keeper, feeA, feeB, priceFeed, paused, spotCount, fundBalance, quoteWei,
split: [{ share: '30%', to: "the buyer's sponsor (none: the momentum fund)" }, { share: '55%', to: '5.5% to each of the 10 spots bought just before (a missing spot: company A)' },
{ share: '5%', to: 'company A' }, { share: '5%', to: 'company B' }, { share: '5%', to: 'the momentum fund (can only buy spots)' }] }, { 'Cache-Control': 'public, max-age=30' });
}
if (p === '/api/quote' && req.method === 'GET') {
try { return json(res, 200, await chain.quote()); } catch (e) { return json(res, 503, { error: e.message }); }
}
if (p === '/api/gas' && req.method === 'GET') { try { return json(res, 200, await chain.suggestedFees()); } catch (e) { return json(res, 200, {}); } }
if (/^\/api\/tx\/0x[0-9a-fA-F]{64}$/.test(p)) { try { return json(res, 200, await chain.receipt(p.slice(8))); } catch (e) { return json(res, 200, { found: false }); } }
if (p === '/api/stats' && req.method === 'GET') {
const t = chain.totals(); const recent = chain.spots().slice(0, 10).map(s => ({ id: s.id, owner: s.owner, kind: s.kind, boughtAt: s.boughtAt, tx: s.tx }));
return json(res, 200, { totals: t, index: chain.status(), recent, daily: store.daily() });
}
if (p === '/api/sponsor' && req.method === 'GET') {
const raw = u.searchParams.get('ref'); const fw = u.searchParams.get('for');
if (fw && limited(req, 'sponsor-for', 120, 3600000)) return json(res, 429, { error: 'Too many requests this hour.' });
const pick = raw ? { address: await resolveRef(raw), via: 'ref' } : await sponsorPick(req, ADDR_RE.test(fw || '') ? fw : null);
const a = pick.address || null;
return json(res, 200, { address: a, member: a ? chain.isMember(a) : false, via: pick.via || null });
}
// board: organic view counting with a one-time token, after 5 s on screen
if (p === '/api/board' && req.method === 'GET') {
const tiles = board.pick(); const token = crypto.randomBytes(12).toString('hex');
if (!isBot(req)) boardTokens.set(token, { at: Date.now(), vk: visitorKey(req), ids: tiles.filter(t => t.t === 'spot').map(t => t.id) });
if (boardTokens.size > 50000) { const cut = Date.now() - 600000; for (const [k, v] of boardTokens) if (v.at < cut) boardTokens.delete(k); }
return json(res, 200, { tiles, token }, extra);
}
if (p === '/api/board/seen' && req.method === 'POST') {
const b = await readBody(req); const t = boardTokens.get(String(b.token || ''));
if (!t || t.vk !== visitorKey(req) || Date.now() - t.at < 4500 || Date.now() - t.at > 600000) return json(res, 200, { counted: 0 });
boardTokens.delete(b.token);
if (limited(req, 'views', 400, 3600000)) return json(res, 200, { counted: 0 });
let n = 0; for (const id of t.ids) if (store.addView(id, t.vk, 'organic')) n++;
return json(res, 200, { counted: n });
}
// gate
if (p === '/api/gate' && req.method === 'GET') {
const s = session(req);
if (isBot(req)) return json(res, 200, { passed: true, bot: true });
if (passed(req) || (s && chain.isMember(s.address))) return json(res, 200, { passed: true });
if (limited(req, 'gate', 60, 3600000)) return json(res, 429, { error: 'Too many gate starts from this connection. Try again in a while.' });
const g = await makeGate(req);
return json(res, 200, { passed: false, gid: g.gid, steps: g.steps.map(st => Object.assign({}, st)) }, extra);
}
if (p === '/api/gate/begin' && req.method === 'POST') {
const b = await readBody(req); const g = gates.get(String(b.gid || ''));
if (!g || g.vk !== visitorKey(req)) return json(res, 400, { error: 'Gate expired. Reload the page.' });
if (Number(b.i) !== g.idx) return json(res, 400, { error: 'Out of order.', idx: g.idx });
g.stepStart = Date.now(); return json(res, 200, { ok: true });
}
if (p === '/api/gate/done' && req.method === 'POST') {
const b = await readBody(req); const g = gates.get(String(b.gid || ''));
if (!g || g.vk !== visitorKey(req)) return json(res, 400, { error: 'Gate expired. Reload the page.' });
const st = g.steps[g.idx];
if (Number(b.i) !== g.idx || !st || !g.stepStart) return json(res, 400, { error: 'Out of order.', idx: g.idx });
if (Date.now() - g.stepStart < (st.seconds - 1.5) * 1000) return json(res, 400, { error: 'Keep the page open until the timer ends.' });
if (st.type === 'board' && !limited(req, 'views', 400, 3600000)) for (const t of st.tiles) if (t.t === 'spot') store.addView(t.id, g.vk, 'gate');
g.idx += 1; g.stepStart = 0;
if (g.idx >= g.steps.length) { gates.delete(g.gid); passedKeys.set(g.vk, Date.now() + 86400000); if (passedKeys.size > 100000) passedKeys.clear(); return json(res, 200, { ok: true, passed: true }, { 'Set-Cookie': cookie('bl.pass', passToken(g.vk), 86400, true) }); }
return json(res, 200, { ok: true, idx: g.idx });
}
// 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\nDownline Banners 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);
const token = store.mintSession(a);
return json(res, 200, { ok: true, address: a }, { 'Set-Cookie': cookie('bl.sid', token, 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('bl.sid', '', 0, true), networksso.offCookie()] }); // signed out stays signed out here for 12 hours
}
if (p === '/api/me' && req.method === 'GET') {
const s = session(req); if (!s) return json(res, 200, { signedIn: false, sponsor: await sponsorFor(req) });
store.touch(s.address);
return json(res, 200, { signedIn: true, address: s.address, member: chain.isMember(s.address), sponsor: await sponsorFor(req) });
}
// -- member API (signed in)
if (p.startsWith('/api/my')) {
const s = session(req); if (!s) return json(res, 401, { error: 'Sign in with your wallet first.' });
const me = s.address;
if (p === '/api/my' && req.method === 'GET') return json(res, 200, await myData(me));
if (p === '/api/my/lsspins' && req.method === 'GET') { const r = await lsSpins({ wallet: me }); return json(res, r.error ? 502 : 200, r); }
if (p === '/api/my/lsspins/use' && req.method === 'POST') { const b = await readBody(req); const r = await lsSpins({ wallet: me, spinId: Number(b.spinId) || 0 }); return json(res, r.error ? 400 : 200, r); }
let m = /^\/api\/my\/spot\/(\d+)$/.exec(p);
if (m && req.method === 'POST') {
const sp = chain.spot(m[1]); if (!sp || sp.owner !== me) return json(res, 403, { error: 'That spot is not yours.' });
const b = await readBody(req); const out = {};
if (b.link !== undefined) { if (b.link === '') out.link = ''; else { const r = safety.checkLink(b.link, 'Target link'); if (r.error) return json(res, 400, r); out.link = r.url; } }
if (b.img !== undefined && !String(b.img).startsWith('/art/u/')) { if (b.img === '') out.img = ''; else { const r = safety.checkLink(b.img, 'Image URL'); if (r.error) return json(res, 400, r); out.img = r.url; } }
return json(res, 200, { ok: true, meta: store.setSpotMeta(sp.id, out) });
}
if (p === '/api/my/default' && req.method === 'POST') {
const b = await readBody(req); const out = {};
if (b.link !== undefined) { if (b.link === '') out.link = ''; else { const r = safety.checkLink(b.link, 'Default link'); if (r.error) return json(res, 400, r); out.link = r.url; } }
if (b.img !== undefined && !String(b.img).startsWith('/art/u/')) { if (b.img === '') out.img = ''; else { const r = safety.checkLink(b.img, 'Image URL'); if (r.error) return json(res, 400, r); out.img = r.url; } }
return json(res, 200, { ok: true, defaults: store.setMemberDefault(me, out) });
}
if (p === '/api/my/upload' && req.method === 'POST') {
if (limited(req, 'upload', 40, 3600000)) return json(res, 429, { error: 'Too many uploads this hour.' });
const target = u.searchParams.get('for') || '';
let sp = null;
if (target !== 'default') { sp = chain.spot(target); if (!sp || sp.owner !== me) return json(res, 403, { error: 'That spot is not yours.' }); }
let buf; try { buf = await readRaw(req, safety.MAX_UPLOAD + 1); } catch (e) { return json(res, 400, { error: 'The file is over 150 KB.' }); }
const r = safety.checkImage(buf); if (r.error) return json(res, 400, r);
const name = (sp ? 's' + sp.id : 'd' + me.slice(2, 10)) + '-' + crypto.randomBytes(5).toString('hex') + r.info.ext;
fs.writeFileSync(path.join(C.dataDir, 'art', name), buf);
const img = '/art/u/' + name;
if (sp) store.setSpotMeta(sp.id, { img }); else store.setMemberDefault(me, { img });
return json(res, 200, { ok: true, img });
}
return json(res, 404, { error: 'Not found' });
}
// -- InstantAdPay -> refuel spot (signed with NETWORK_SSO_SECRET, see refuelspots.js)
if (p === '/api/partner/refuel-spot' && req.method === 'POST') {
const raw = (await readRaw(req, 4096)).toString('utf8');
const sec = String(process.env.NETWORK_SSO_SECRET || '').trim(); const ts = String(req.headers['x-net-ts'] || ''); const sig = String(req.headers['x-net-sig'] || '');
if (sec.length < 32 || !/^\d{13}$/.test(ts) || Math.abs(Date.now() - Number(ts)) > 300000) return json(res, 401, { error: 'unauthorized' });
const want = crypto.createHmac('sha256', sec).update('net.v1.' + ts + '\n' + raw).digest('hex');
if (sig.length !== want.length || !crypto.timingSafeEqual(Buffer.from(sig), Buffer.from(want))) return json(res, 401, { error: 'unauthorized' });
let b; try { b = JSON.parse(raw || '{}'); } catch (e) { return json(res, 400, { error: 'bad json' }); }
const r = refuelspots.enqueue(b); return json(res, r.error ? 400 : 200, r);
}
if (p === '/api/admin/welcome' && req.method === 'POST') {
const tok = process.env.ADMIN_TOKEN; if (!tok || req.headers['x-admin-token'] !== tok) return json(res, 401, { error: 'no' });
const raw = (await readRaw(req, 4 * 1024 * 1024)).toString('utf8'); let b; try { b = JSON.parse(raw); } catch (e) { return json(res, 400, { error: 'bad json' }); }
const cur = WELCOME(); let n = 0;
if (b.oldrefs && typeof b.oldrefs === 'object') { const o = {}; for (const [k, v] of Object.entries(b.oldrefs)) if (/^[a-z0-9_.-]{2,40}$/.test(k) && /^[a-z0-9_]{1,20}$/.test(String(v))) o[k] = String(v); fs.writeFileSync(path.join(C.dataDir, 'oldrefs.json'), JSON.stringify(o)); }
for (const [code, v] of Object.entries(b.codes || {})) { if (!/^[a-z0-9]{8,16}$/.test(code) || !v || !Array.isArray(v.line)) continue; cur[code] = { line: v.line.map(x => String(x).toLowerCase()).slice(0, 25), at: Date.now() }; n++; }
fs.writeFileSync(path.join(C.dataDir, 'welcome.json'), JSON.stringify(cur));
return json(res, 200, { ok: true, added: n, total: Object.keys(cur).length });
}
// returning-member results: personal links opened, and how many of those visitors went on to buy (matched by the wallet that
// signed in on the same browser is not tracked; this counts link opens and new members since the first open)
if (p === '/api/admin/wallet-alias' && req.method === 'POST') { // {wallet, username} adds; {wallet, remove: true} drops
const tok = process.env.ADMIN_TOKEN; if (!tok || req.headers['x-admin-token'] !== tok) return json(res, 401, { error: 'no' });
const b = await readBody(req); const w = String(b.wallet || '').toLowerCase(); if (!/^0x[0-9a-f]{40}$/.test(w)) return json(res, 400, { error: 'wallet' });
const al = aliases(); if (b.remove) delete al[w]; else { const un = String(b.username || '').trim(); if (!/^[A-Za-z0-9_.-]{2,40}$/.test(un)) return json(res, 400, { error: 'username' }); al[w] = { username: un, at: Date.now(), note: String(b.note || '').slice(0, 200) }; }
fs.writeFileSync(ALIAS_F(), JSON.stringify(al)); return json(res, 200, { ok: true, aliases: al });
}
if (p === '/api/admin/welcome-stats' && req.method === 'GET') {
const tok = process.env.ADMIN_TOKEN; if (!tok || req.headers['x-admin-token'] !== tok) return json(res, 401, { error: 'no' });
let v = {}; try { v = JSON.parse(fs.readFileSync(path.join(C.dataDir, 'welcome-visits.json'), 'utf8')); } catch (e) {}
const codes = Object.keys(v); const opens = codes.reduce((t, k) => t + v[k].n, 0); const since = codes.length ? Math.min(...codes.map(k => v[k].first)) : Date.now();
const newMembers = chain.allMembers().filter(m => m.joinedAt >= since);
return json(res, 200, { codesOpened: codes.length, opens, firstOpen: codes.length ? since : null, newMembersSince: newMembers.length,
newMembers: newMembers.map(m => ({ address: m.address, sponsor: m.sponsor, joinedAt: m.joinedAt })) });
}
// -- admin (ADMIN_TOKEN header): keeper preview + index status. No key material is ever returned.
if (p === '/api/admin/status' && req.method === 'GET') {
const tok = process.env.ADMIN_TOKEN; if (!tok || req.headers['x-admin-token'] !== tok) return json(res, 401, { error: 'no' });
return json(res, 200, { index: chain.status(), totals: chain.totals(), keeper: keeper.statusInfo(), hub: hubreport.view(), hubLookup: hubpeople.view(), refuelSpots: refuelspots.view(), nas: dlbnas.view() });
}
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><title>Not found</title><body style="background:#09080f;color:#f3f1fa;font-family:sans-serif;text-align:center;padding:40px 16px"><p>Not found. <a style="color:#c6f432" href="/">Downline Banners home</a></p>'
+ '<p style="color:#a29cbc;font-size:11px;margin:24px 0 4px">Network</p><script async src="https://linkspin.app/z.js" data-zone="ls-00c064"></script></body>');
} 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();
tgproof.init({ nameOf, contract: C.contract, explorer: C.explorer || 'https://polygonscan.com', site: C.site,
feeWallets: ['0x7627fc78876948ac9d95c1c9eb061e7d6d647b70', '0x8b7d33849a2c4d92c985be31e46dc564ba901ad2'] }); // contract feeA / feeB
chain.init({ onEvent: tgproof.onEvent }); // every spot sale -> one payment-proof message in the payments topic
hubreport.init({ dataDir: C.dataDir, members: () => chain.allMembers() });
refuelspots.init({ lock: () => keeper.busy() }); keeper.setOtherBusy(() => refuelspots.busy());
keeper.init();
dlbnas.init({ spots: () => chain.spots(), views: id => store.views(id).total, creative: board.creative });
// members' LinkSpin Banner Spins for empty board slots: one active 468x60 spin per member, refreshed every 10 minutes
const refreshSpins = async () => {
const out = [];
for (const m of chain.allMembers()) {
const r = await lsSpins({ wallet: m.address }).catch(() => null);
const sp = r && r.account && (r.spins || []).find(x => !x.paused && x.banners > 0);
if (sp) out.push({ owner: m.address, img: 'https://rubav.com/i/' + sp.code + '.gif', link: 'https://rubav.com/c/' + sp.code + '?placement=board&s1=fill', title: (r.username ? '@' + r.username + ': ' : '') + sp.name });
}
board.setMemberSpins(out);
};
setTimeout(() => refreshSpins().catch(() => {}), 20000); setInterval(() => refreshSpins().catch(() => {}), 10 * 60000).unref();
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); });