Files

735 lines
61 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 netsites = require('./netsites'); // footer network list from the hub (trust pack 2026-11-14)
const netdeals = require('./netdeals'); // Network Weekend ribbon feed from the hub (2026-11-17)
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 chatbot = require('./chatbot'); // the site assistant (2026-11-15): chatcore.js + kb.js + the network knowledge base (netkb.js)
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', '.mp4': 'video/mp4', '.webm': 'video/webm' };
const CSP = "default-src 'self'; script-src 'self' https://cdn.jsdelivr.net https://linkspin.app https://polhunter.com; worker-src 'self' blob:; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; "
+ "img-src 'self' data: blob: https:; connect-src 'self' https://linkspin.app https://polhunter.com https://*.walletconnect.com wss://*.walletconnect.com https://*.walletconnect.org wss://*.walletconnect.org "
+ "https://*.reown.com wss://*.reown.com https://*.reown.org wss://*.reown.org https://*.web3modal.org https://*.drpc.org https://*.publicnode.com https://*.coinbase.com; "
+ "font-src 'self' data: https://fonts.gstatic.com https://fonts.reown.com; form-action 'self'; frame-src https: 'self'";
function headers(extra) { return Object.assign({ 'Content-Security-Policy': CSP, 'X-Content-Type-Options': 'nosniff', 'Referrer-Policy': 'strict-origin-when-cross-origin' }, extra || {}); }
function json(res, code, obj, extra) { res.writeHead(code, headers(Object.assign({ 'Content-Type': 'application/json', 'Cache-Control': 'no-store' }, extra))); res.end(JSON.stringify(obj)); }
function sendFile(res, file, extra) {
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);
});
}
// video needs byte ranges (Safari will not play it without them); tutorial videos 2026-11-18
function sendMedia(req, res, file) {
fs.stat(file, (err, st) => {
if (err || !st.isFile()) { res.writeHead(404, headers({ 'Content-Type': 'text/plain' })); return res.end('Not found'); }
const base = { 'Content-Type': MIME[path.extname(file).toLowerCase()], 'Accept-Ranges': 'bytes', 'Cache-Control': 'public, max-age=86400' };
const m = /^bytes=(\d*)-(\d*)$/.exec(req.headers.range || '');
if (!m || (!m[1] && !m[2])) { res.writeHead(200, headers(Object.assign(base, { 'Content-Length': st.size }))); return fs.createReadStream(file).pipe(res); }
let a = m[1] ? +m[1] : Math.max(0, st.size - +m[2]), b = m[1] && m[2] ? Math.min(+m[2], st.size - 1) : st.size - 1;
if (a > b || a >= st.size) { res.writeHead(416, headers({ 'Content-Range': 'bytes */' + st.size })); return res.end(); }
res.writeHead(206, headers(Object.assign(base, { 'Content-Range': 'bytes ' + a + '-' + b + '/' + st.size, 'Content-Length': b - a + 1 })));
fs.createReadStream(file, { start: a, end: b }).pipe(res);
});
}
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); });
}
// the chat knowledge-base admin routes: the same ADMIN_TOKEN header as the other admin routes, compared in constant time
const chatAdmin = req => { const t = String(process.env.ADMIN_TOKEN || ''); const g = String(req.headers['x-admin-token'] || '');
return t.length >= 8 && g.length === t.length && require('crypto').timingSafeEqual(Buffer.from(g), Buffer.from(t)); };
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 hubevents = require('./hubevents'); // network hub hook (2026-11-16): sign-out-everywhere, block and erase end sessions here
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);
// a spot the admin took down (2026-11-16) keeps its step, but the step shows a house site (never the spot's own banner or link)
const stepOf = async (role, s, title) => { const cr = board.creative(s); return cr.from === 'down' ? visitStep(role, 'h-' + cr.key, cr.img, cr.link, cr.title) : visitStep(role, s.id, cr.img, cr.link, title); };
if (sSpot) steps.push(await stepOf('sponsor', sSpot, '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) steps.push(await stepOf('newest', s, '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,
down: (dn => dn ? { at: dn.at, reason: dn.reason } : null)(store.spotDown(s.id)), // taken down by the admin: the owner sees the reason
edits: store.spotEdits(s.id).slice(-10).reverse() };
}
// ---- spot edits (Marty 2026-11-16): unlimited, every one gets the full check and is logged on the spot ----
// checkLink first; then (LINK_PROBE on) the link must answer (safety.probeLink, up to 3 checked redirects) and an image address
// must download as a real 468x60 image (safety.probeImage). The one exception: the Banner Spin image + click link LinkSpin's signed
// answer just handed this member (/api/my/lsspins/use) are not fetched (fetching the click link would count a click on LinkSpin).
const lsVouched = new Map(); // wallet -> { link, img, at }
async function checkEdit(me, b, linkLabel) {
const out = {};
if (b.link !== undefined) { if (b.link === '') out.link = ''; else { const r = safety.checkLink(b.link, linkLabel); if (r.error) return 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 r; out.img = r.url; } }
if (C.linkProbe) {
const v = lsVouched.get(me); const vouched = x => !!v && Date.now() - v.at < 30 * 60000 && (x === v.link || x === v.img);
if (out.link && !vouched(out.link)) { const pr = await safety.probeLink(out.link.replace(/\{(clickid|spot|type)\}/g, 'x')); if (pr.error) return pr; }
if (out.img && !vouched(out.img)) { const pr = await safety.probeImage(out.img); if (pr.error) return pr; }
}
return { ok: true, out };
}
// one log row per real change: old and new link and image, when, how (edit, upload)
function logChange(kind, key, before, patch, via) {
const o = { img: (before && before.img) || '', link: (before && before.link) || '' }; const n = Object.assign({}, o, patch);
const what = ['link', 'img'].filter(k => o[k] !== n[k]); if (!what.length) return null;
const row = { what: what.length === 2 ? 'both' : what[0], old: o, new: { img: n.img, link: n.link }, via };
return kind === 'spot' ? store.logSpotEdit(key, row) : store.logDefaultEdit(key, row);
}
const DOWN_EDIT = 'This spot was taken down, so it cannot be changed. The reason is shown on the spot.';
// "credit back" has no meaning on Downline Banners yet (2026-11-16): a spot is a $5 on-chain purchase (POL cannot be refunded) and
// the site has no free replacement spot or post credit. Marty decides; until then a takedown is "no credit" only.
const CREDIT_BACK_PENDING = 'Credit back is not available on Downline Banners yet: a spot is a $5 on-chain purchase and this site has no free replacement spot or post credit. Marty decides what credit back means; until then choose credit: "none".';
// the admin view of a spot: what it shows, its views, every edit, and its takedown history
async function adminSpot(s) {
const m = store.spotMeta(s.id) || {}; const v0 = store.views(s.id);
return { id: s.id, owner: s.owner, username: await nameOf(s.owner).catch(() => null), kind: s.kind, boughtAt: s.boughtAt, tx: s.tx,
img: m.img || '', link: m.link || '', showing: board.creative(s), views: v0.total + dlbnas.spotServed(s.id), owed: C.viewsOwed, clicks: store.clicks(s.id),
down: store.spotDown(s.id), downs: store.spotDowns(s.id), edits: store.spotEdits(s.id).slice(-50).reverse(), defaultEdits: store.defaultEdits(s.owner).slice(-10).reverse() };
}
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 });
// the hub's member.signedout / member.blocked / member.erased: that person's sessions here end (by any of their wallets)
hubevents.init({ dataDir: C.dataDir, site: 'bannerline', end: who => store.endSessions(x => who.match(x), who.before) });
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' && await networksso.page(req, res, u)) return; // network hub: daily activity ping + the hub sign-in push (2026-11-15)
if (req.method === 'GET' && (p.startsWith('/sso/') || p === '/api/sso/status') && await networksso.handle(req, res, u)) return;
if ((p === '/api/promo-kit' || p === '/promote' || p.startsWith('/art/kit/')) && promokit.handle(req, res, u, sendFile)) return;
if ((p.startsWith('/api/chat') || p.startsWith('/api/admin/kb')) && await chatbot.handle(req, res, p, u, { json, readBody, isAdmin: chatAdmin })) 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
// old splash/landing pages carried the referral as ?r=<old username> (2026-11-17: /splashpg.php?r= kept the ref like VAS)
const lp = p.toLowerCase(); const rq = String(u.searchParams.get('r') || '');
const old = (lp === '/splashpg.php' || lp === '/lcp.php') ? (/^[A-Za-z0-9_.-]{2,40}$/.test(rq) ? rq.toLowerCase() : '')
: /\.php$/i.test(p) && lp !== '/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',
'/terms': 'terms.html', '/disclaimer': 'disclaimer.html', '/privacy': 'privacy.html', '/admin': 'admin.html',
'/guides': 'guides.html', '/guides/is-it-legit': 'guides-legit.html', '/guides/free-account': 'guides-free.html', '/guides/faq': 'guides-faq.html' }; // legal pages: trust pack 2026-11-14; /admin 2026-11-16; Guides 2026-11-17
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' || p === '/admin') ex['X-Frame-Options'] = 'DENY'; // member board + admin: 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', '/guides', '/guides/is-it-legit', '/guides/free-account', '/guides/faq', '/terms', '/disclaimer', '/privacy'].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-') || /^\/art\/how-it-works\.(mp4|jpg)$/.test(p) || 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(); }
if (/\.(mp4|webm)$/i.test(f)) return sendMedia(req, res, f);
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/network-sites' && req.method === 'GET') return netsites.handle(req, res);
if (p === '/api/network-deals' && req.method === 'GET') return netdeals.handle(req, res, 'dlb'); // Network Weekend ribbon (2026-11-17)
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
}
// "Sign out everywhere" (2026-11-16): the hub ends every network sign-in of this member and tells every hooked site; every
// session of this wallet here ends now. Same-origin POST only (SameSite=Lax session cookie).
if (p === '/api/auth/logout-everywhere' && req.method === 'POST') {
const s = session(req); let hub = { ok: false };
if (s) { hub = await networksso.signOutEverywhere(s); store.endSessions(x => x.address === s.address, Date.now() + 1000); }
return json(res, 200, { ok: true, everywhere: !!hub.ok }, { 'Set-Cookie': [cookie('bl.sid', '', 0, true), networksso.offCookie()] });
}
if (p === '/api/hub/events' && req.method === 'POST') {
let raw = ''; try { raw = (await readRaw(req, 256 * 1024)).toString('utf8'); } catch (e) { return json(res, 413, { error: 'too big' }); }
const r = await hubevents.receive(req.headers, raw); return json(res, r.status, r.body);
}
if (p === '/api/me' && req.method === 'GET') {
// username / refName (Marty 2026-11-15): the footer's network links carry a referral username, the member's own network
// username when signed in, else the sponsor's (usernames only, never the wallet)
const nm = async a => (a ? await nameOf(a).catch(() => null) : null);
const s = session(req); if (!s) { const sp = await sponsorFor(req); return json(res, 200, { signedIn: false, sponsor: sp, refName: await nm(sp) }); }
store.touch(s.address);
const sp = await sponsorFor(req); const [username, refName] = await Promise.all([nm(s.address), nm(sp)]);
return json(res, 200, { signedIn: true, address: s.address, member: chain.isMember(s.address), sponsor: sp, username, refName });
}
// -- 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 });
if (!r.error && r.use) { const lk = safety.checkLink(r.use.link, 'link'), im = safety.checkLink(r.use.img, 'img'); if (lk.ok && im.ok) lsVouched.set(me, { link: lk.url, img: im.url, at: Date.now() }); if (lsVouched.size > 20000) lsVouched.clear(); }
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.' });
if (store.spotDown(sp.id)) return json(res, 400, { error: DOWN_EDIT });
if (limited(req, 'edit', 120, 3600000)) return json(res, 429, { error: 'Too many changes this hour. Try again in a while.' }); // each change fetches the link
const b = await readBody(req); const ck = await checkEdit(me, b, 'Target link'); if (ck.error) return json(res, 400, ck);
if (store.spotDown(sp.id)) return json(res, 400, { error: DOWN_EDIT }); // re-checked after the fetches
const before = Object.assign({}, store.spotMeta(sp.id) || {});
const meta = store.setSpotMeta(sp.id, ck.out); const edit = logChange('spot', sp.id, before, ck.out, 'edit');
return json(res, 200, { ok: true, meta, edit });
}
if (p === '/api/my/default' && req.method === 'POST') {
if (limited(req, 'edit', 120, 3600000)) return json(res, 429, { error: 'Too many changes this hour. Try again in a while.' });
const b = await readBody(req); const ck = await checkEdit(me, b, 'Default link'); if (ck.error) return json(res, 400, ck);
const before = Object.assign({}, store.memberDefault(me) || {});
const defaults = store.setMemberDefault(me, ck.out); const edit = logChange('default', me, before, ck.out, 'edit');
return json(res, 200, { ok: true, defaults, edit });
}
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.' }); if (store.spotDown(sp.id)) return json(res, 400, { error: DOWN_EDIT }); }
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;
const before = Object.assign({}, (sp ? store.spotMeta(sp.id) : store.memberDefault(me)) || {});
if (sp) store.setSpotMeta(sp.id, { img }); else store.setMemberDefault(me, { img });
logChange(sp ? 'spot' : 'default', sp ? sp.id : me, before, { img }, 'upload');
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(), hubEvents: hubevents.view(), refuelSpots: refuelspots.view(), nas: dlbnas.view() });
}
// -- admin: the network hub's member lookup (Marty 2026-11-14, read-only). GET ?q=<wallet> | <spot id>. No email lives here.
if (p === '/api/admin/member-lookup' && req.method === 'GET') {
const tok = process.env.ADMIN_TOKEN; if (!tok || req.headers['x-admin-token'] !== tok) return json(res, 401, { error: 'no' });
const q = String(u.searchParams.get('q') || '').trim(); let a = null, via = null;
if (ADDR_RE.test(q)) { a = q.toLowerCase(); via = 'wallet'; }
else if (/^#?\d{1,9}$/.test(q)) { const sp = chain.spot(Number(q.replace('#', ''))); a = sp ? sp.owner : null; via = 'spot'; }
if (!a) return json(res, 404, { error: 'not found' });
const al = aliases(); const d = await myData(a);
const un = d.username ? String(d.username).toLowerCase() : null;
const aliasWallets = Object.entries(al).filter(([w, v]) => w === a || (un && v && String(v.username || '').toLowerCase() === un)).map(([w, v]) => Object.assign({ wallet: w }, v));
return json(res, 200, Object.assign(d, { via, known: d.member || d.spots.length > 0, chainMember: chain.member(a) || null, aliasWallets,
paidFor: chain.spots().filter(x => x.payer === a && x.owner !== a).map(x => ({ id: x.id, owner: x.owner, tx: x.tx, kind: x.kind })),
gifted: chain.fundBuys().filter(f => f.giftee === a), contract: C.contract, explorer: C.explorer }));
}
// -- admin: spot takedown and restore (Marty 2026-11-16, the Viral Banner Blitz way). The spot is a $5 on-chain purchase: the
// contract is never touched; only what this site shows and counts changes. Taken down = hidden everywhere at once (board, gate,
// /go, Network Ad Space), its place held by a house tile so nobody else moves, no views or clicks counted while down; the owner
// sees "Taken down" with the reason; one admin ledger row per takedown and restore.
if (p === '/api/admin/spots' || p === '/api/admin/actions' || /^\/api\/admin\/spots\/\d{1,9}\/(takedown|restore)$/.test(p)) {
const tok = process.env.ADMIN_TOKEN; if (!tok || req.headers['x-admin-token'] !== tok) return json(res, 401, { error: 'no' });
if (p === '/api/admin/actions' && req.method === 'GET') return json(res, 200, { actions: store.adminLogs(Math.min(500, Math.max(1, Number(u.searchParams.get('n')) || 100))) });
// GET ?q=#<id> | <id> | <wallet> | <username>
if (p === '/api/admin/spots' && req.method === 'GET') {
const q = String(u.searchParams.get('q') || '').trim(); let list = [];
if (/^#?\d{1,9}$/.test(q)) { const sp = chain.spot(Number(q.replace('#', ''))); if (sp) list = [sp]; }
else if (ADDR_RE.test(q)) list = chain.spotsOf(q.toLowerCase());
else if (/^@?[a-zA-Z0-9_]{1,20}$/.test(q)) {
const name = q.replace(/^@/, '').toLowerCase(); const al = Object.entries(aliases()).find(([, v]) => v && String(v.username || '').toLowerCase() === name);
const a = al ? al[0] : await resolveRef(name).catch(() => null); if (a) list = chain.spotsOf(a);
}
if (!list.length) return json(res, 404, { error: 'No spot found for that.' });
return json(res, 200, { spots: await Promise.all(list.slice(0, 100).map(adminSpot)) });
}
const tk = /^\/api\/admin\/spots\/(\d{1,9})\/(takedown|restore)$/.exec(p);
if (tk && req.method === 'POST') {
const sp = chain.spot(Number(tk[1])); if (!sp) return json(res, 404, { error: 'No such spot.' });
const b = await readBody(req); const by = String(b.by || 'admin').replace(/[^\w .@-]/g, '').slice(0, 40) || 'admin';
const reason = String(b.reason || '').replace(/[\u0000-\u001f\u007f<>]/g, '').replace(/\s+/g, ' ').trim();
const username = await nameOf(sp.owner).catch(() => null);
if (tk[2] === 'takedown') {
if (store.spotDown(sp.id)) return json(res, 400, { error: 'That spot is already taken down.' });
if (sp.kind === 3) return json(res, 400, { error: 'A fund-kept spot never shows, so there is nothing to take down.' });
if (reason.length < 3 || reason.length > 300) return json(res, 400, { error: 'A reason is required (3 to 300 characters). The owner sees it.' });
if (b.credit === 'back') return json(res, 400, { error: CREDIT_BACK_PENDING });
if (b.credit !== 'none') return json(res, 400, { error: 'Choose credit: "none". (Credit back is not available on Downline Banners yet.)' });
const rec = store.setSpotDown(sp.id, { at: Date.now(), by, reason, credit: 'none', views: store.views(sp.id).total });
const nas = await dlbnas.pause(sp.id).catch(e => 'error: ' + String(e.message).slice(0, 80));
const e = store.adminLog({ action: 'takedown', spotId: sp.id, owner: sp.owner, username, by, reason, credit: 'none', nas });
return json(res, 200, { ok: true, spot: await adminSpot(sp), down: rec, log: e });
}
const was = store.spotDown(sp.id); if (!was) return json(res, 400, { error: 'That spot is not taken down.' });
store.clearSpotDown(sp.id, { restoredAt: Date.now(), restoredBy: by, restoreReason: reason || null });
const nas = await dlbnas.resume(sp.id).catch(e => 'error: ' + String(e.message).slice(0, 80));
const e = store.adminLog({ action: 'restore', spotId: sp.id, owner: sp.owner, username, by, reason: reason || null, credit: 'none given', nas });
return json(res, 200, { ok: true, spot: await adminSpot(sp), log: e });
}
return json(res, 404, { error: 'Not found' });
}
if (p.startsWith('/api/')) return json(res, 404, { error: 'Not found' });
res.writeHead(404, headers({ 'Content-Type': 'text/html; charset=utf-8' }));
return res.end('<!doctype html><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' });
}
});
// this Central-time week (from Monday 12:00 AM CT): spots taken, bought vs gifted by the momentum fund, plus the all-time count
function ctWeekStart(now) {
const p = Object.fromEntries(new Intl.DateTimeFormat('en-US', { timeZone: 'America/Chicago', weekday: 'short', hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false })
.formatToParts(new Date(now)).map(x => [x.type, x.value]));
const back = { Mon: 0, Tue: 1, Wed: 2, Thu: 3, Fri: 4, Sat: 5, Sun: 6 }[p.weekday] || 0;
return now - back * 86400000 - ((Number(p.hour) % 24) * 3600 + Number(p.minute) * 60 + Number(p.second)) * 1000;
}
function weekLine() {
const from = ctWeekStart(Date.now()); const all = chain.spots(); const wk = all.filter(s => s.boughtAt >= from);
const gifted = wk.filter(s => s.kind === 2).length;
return '\u{1F4CA} This week: ' + wk.length + ' spot' + (wk.length === 1 ? '' : 's') + (gifted ? ' (' + (wk.length - gifted) + ' bought, ' + gifted + ' gifted by the momentum fund)' : '') + ' · ' + all.length + ' spots in the line';
}
(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
weekLine }); // this week's spot numbers on every sale message (trust pack 2026-11-14)
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, isDown: id => !!store.spotDown(id) });
// 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();
chatbot.init(); // after docstore.init: kb.json is a MySQL document
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); });