Files
stackpol/server.js
T

258 lines
33 KiB
JavaScript

// Stack POL (stackpol.com), 2026-11-09. Marty: build it out before LinkSpin's Nov 15 launch, its own blog on the same engine,
// full SEO footprint. Every POL payout across the network, stacked: a network home with live totals, one page per program,
// the public ledger (every row links to Polygonscan), opt-in member stacks at /<username>, and the blog.
// Data: tools/indexer.py on core reads every program's payout records and IAP/LinkSpin's chain index every 5 minutes and POSTs
// one JSON snapshot to /api/ingest (Bearer STACK_INGEST_KEY). Pages read that snapshot, never the chain.
// Storage (Marty 2026-11-16: "Stack POL wipes its payout totals on every deploy; they should live in the database"): the last
// snapshot and the chatbot's knowledge base are MySQL documents through docstore.js (DOCSTORE_URL, Coolify stackpol-mysql), loaded
// at boot before the server listens, so a restart or deploy serves the last totals at once. The snapshot is two documents:
// stack-index.json (everything but `at`) and stack-index-at.json ({at}), so a push with no new payouts rewrites only the tiny one
// (docstore skips unchanged bodies; binlog stays small). Without DOCSTORE_URL (local only) they are files in DATA_DIR.
'use strict';
const http = require('http');
const fs = require('fs');
const path = require('path');
const DATA_DIR = process.env.DATA_DIR || path.join(__dirname, 'data');
const docstore = require('./docstore'); docstore.install(DATA_DIR); // before any module reads data
const zlib = require('zlib');
const { SITE, esc, head, tail, ZONES, spot, personalize, memberLinks, proCta } = require('./layout');
let QR = null; try { QR = require('qrcode'); } catch (e) { console.error('[stackpol] qrcode module missing: no QR on Pro pages'); }
const { PROGRAMS, BY_KEY, BY_SLUG } = require('./programs');
const blog = require('./blog');
const PORT = Number(process.env.PORT) || 80;
const KEY = String(process.env.STACK_INGEST_KEY || '').trim();
const OWNER = 'martbost'; // the network pages' join links (the site owner's referral)
const SNAP = path.join(DATA_DIR, 'stack-index.json'), SNAP_AT = path.join(DATA_DIR, 'stack-index-at.json');
const PUB = path.join(__dirname, 'public');
let IDX = null;
function loadSnap() {
try { const j = JSON.parse(fs.readFileSync(SNAP, 'utf8')); let at = 0; try { at = Number(JSON.parse(fs.readFileSync(SNAP_AT, 'utf8')).at) || 0; } catch (e) {} j.at = at || j.at || null; IDX = j; } catch (e) { IDX = null; }
}
function saveSnap(j) {
const body = Object.assign({}, j); delete body.at;
fs.writeFileSync(SNAP, JSON.stringify(body)); fs.writeFileSync(SNAP_AT, JSON.stringify({ at: j.at }));
}
blog.load();
const fmt = n => Number(n || 0).toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
const fmtInt = n => Number(n || 0).toLocaleString('en-US');
const ago = ts => { const s = Math.max(0, (Date.now() - ts) / 1000); return s < 90 ? 'just now' : s < 5400 ? Math.round(s / 60) + ' min ago' : s < 129600 ? Math.round(s / 3600) + ' h ago' : Math.round(s / 86400) + ' days ago'; };
const when = ts => new Date(ts).toLocaleString('en-US', { month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit', timeZone: 'America/Chicago' }) + ' CT';
const shortTx = tx => tx ? tx.slice(0, 10) + '…' + tx.slice(-4) : '';
const RESERVED = new Set(['blog', 'ledger', 'programs', 'earn', 'api', 'img', 'sitemap', 'robots', 'favicon', 'about', 'admin', 'login', 'join', 'feed', 'www', 'static', 'assets', 'terms', 'privacy', 'disclaimer']);
const net = () => (IDX && IDX.network) || { pol: 0, payments: 0, wallets: 0 };
const prog = k => (IDX && IDX.programs && IDX.programs[k]) || { pol: 0, payments: 0, wallets: 0 };
const live = () => IDX ? '<div class="live"><span class="dot"></span>Ledger refreshed ' + ago(IDX.at) + '</div>' : '<div class="live"><span class="dot" style="background:var(--gold)"></span>Ledger warming up</div>';
const seasonOn = p => !p.season || Date.parse(p.season.ends + 'T23:59:59-06:00') >= Date.now();
function card(p, amt, pays, ref, opts) {
opts = opts || {};
return '<article class="card" style="--c:' + p.c + '"><a class="img" href="/earn/' + p.slug + '"><img src="/img/' + p.k + '.jpg" alt="' + esc(p.n) + ': ' + esc(p.kind) + '" loading="lazy" width="800" height="420"></a><div class="body"><div class="head"><div><div class="nm"><i></i><a href="/earn/' + p.slug + '">' + esc(p.n) + '</a></div><div class="kind">' + esc(p.kind) + '</div></div>'
+ '<div class="earned"><b>' + fmt(amt) + '<small>POL</small></b><span>' + fmtInt(pays) + ' ' + (opts.label || 'payments') + '</span></div></div><p>' + esc(p.d) + '</p>'
+ '<a class="join" href="' + esc(p.join(ref)) + '" rel="nofollow noopener" target="_blank"><span>' + (p.verb || (p.k === 'iap' || p.k === 'ls' ? 'Join' : 'Play')) + ' ' + esc(p.n) + ' free' + '</span></a></div></article>';
}
function feature(p, ref) {
return '<article class="feature"><img src="/img/' + p.k + '.jpg" alt="' + esc(p.n) + '" width="800" height="420"><div class="fb"><span class="ftag">This season</span><h3>' + esc(p.n) + '</h3><p>' + esc(p.d) + '</p><span class="ends">' + esc(p.season.label) + '</span><a class="go" href="' + esc(p.join(ref)) + '" rel="nofollow noopener" target="_blank">Play ' + esc(p.n) + ' free</a></div></article>';
}
function ledgerRows(rows, showWho) {
if (!rows || !rows.length) return '<tr><td colspan="5" style="color:var(--muted)">The ledger fills in on the next refresh.</td></tr>';
return rows.map(r => { const p = BY_KEY[r.k] || { n: r.k, c: '#888' };
return '<tr><td class="pg" style="--c:' + p.c + '"><i></i>' + esc(p.n) + '</td>' + (showWho ? '<td class="who">' + (r.u ? (r.pub ? '<a href="/' + esc(r.u) + '">@' + esc(r.u) + '</a>' : '@' + esc(r.u)) : 'a member') + '</td>' : '') + '<td class="amt">' + fmt(r.pol) + ' POL</td><td class="when">' + when(r.ts) + '</td><td class="tx">' + (r.tx ? '<a href="https://polygonscan.com/tx/' + esc(r.tx) + '" target="_blank" rel="noopener">' + shortTx(r.tx) + ' ↗</a>' : '') + '</td></tr>'; }).join('');
}
const tableHead = showWho => '<div class="tbl"><table><thead><tr><th>Program</th>' + (showWho ? '<th>Member</th>' : '') + '<th class="r">Amount</th><th>When</th><th>Polygon transaction</th></tr></thead><tbody>';
const heroVideo = '<aside class="vid"><div class="frame"><video id="hero" src="/stackpol-hero.mp4" poster="/stackpol-hero-poster.jpg" autoplay muted loop playsinline preload="metadata" aria-label="Coins stacking up as POL payouts arrive"></video><button class="snd" id="snd" type="button">Tap for sound</button></div>'
+ '<div class="trust"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#4ade80" stroke-width="2.5" aria-hidden="true"><path d="M12 2l8 4v6c0 5-3.5 8.5-8 10-4.5-1.5-8-5-8-10V6z"/><path d="M8.5 12l2.5 2.5 4.5-5"/></svg><div><b>Nothing typed in by hand.</b> Every amount on this site is a real Polygon transaction. Check any of them in the ledger.</div></div></aside>';
const videoJs = '<script>(function(){var v=document.getElementById("hero"),b=document.getElementById("snd");if(!v||!b)return;b.onclick=function(){v.muted=!v.muted;b.textContent=v.muted?"Tap for sound":"Sound on";if(!v.muted){v.currentTime=0;v.play();}};})();</script>';
const sortedProgs = () => PROGRAMS.slice().sort((a, b) => prog(b.k).pol - prog(a.k).pol);
const FAQ = [
['What is Stack POL?', 'Stack POL adds up every POL payout from the programs in the Crypto Team Build Network: InstantAdPay, LinkSpin and the games that pay POL. The network page shows everyone combined; a member who switches it on gets their own page with their own stack.'],
['Where do the numbers come from?', 'From each program\'s own payout records and from the InstantAdPay and LinkSpin smart contracts on Polygon. Every row in the ledger links to its Polygon transaction, so anyone can check it on Polygonscan.'],
['Is this income? Will I earn this much?', 'No promise of income is made. The totals are what the whole network has paid out so far. What one member stacks depends on what they do, and many members earn little or nothing.'],
['What is POL?', 'POL is the native token of the Polygon network, formerly MATIC. Fees are a fraction of a cent and transfers confirm in seconds, which is why small payouts work on it.'],
['How do I get my own Stack POL page?', 'Join InstantAdPay free, link a wallet, and switch on "Show my Stack POL page" in Promo tools. Your page lives at stackpol.com/your-username and updates every 5 minutes.'],
['Does Stack POL hold my money?', 'No. Stack POL only shows payouts. Every payment goes straight from the program to your own wallet on Polygon.']
];
function home() {
const n = net(), ps = sortedProgs(), feat = ps.filter(p => p.season && seasonOn(p)), rest = ps.filter(p => !(p.season && seasonOn(p))), live7 = IDX && IDX.last7 ? IDX.last7 : null;
const ld = [{ '@context': 'https://schema.org', '@type': 'WebSite', name: 'Stack POL', url: SITE + '/', description: 'Every POL payout across the network, stacked in one place.' },
{ '@context': 'https://schema.org', '@type': 'Organization', name: 'Stack POL', url: SITE + '/', logo: SITE + '/apple-touch-icon.png', sameAs: ['https://instantadpay.com', 'https://linkspin.app'] },
{ '@context': 'https://schema.org', '@type': 'FAQPage', mainEntity: FAQ.map(([q, a]) => ({ '@type': 'Question', name: q, acceptedAnswer: { '@type': 'Answer', text: a } })) }];
let h = head({ title: 'Stack POL: Every POL Payout Across the Network, in One Place', desc: 'See every POL payout from InstantAdPay, LinkSpin and ' + (PROGRAMS.length - 2) + ' more programs that pay on Polygon, games included. ' + fmt(n.pol) + ' POL paid in ' + fmtInt(n.payments) + ' payments so far, each one checkable on Polygonscan.', path: '/', nav: '/', jsonld: ld });
h += live();
h += '<section class="hero"><div><p class="kick">Paid straight to members\' wallets</p><h1>Every POL the network pays, <span style="color:var(--gold)">stacked in one place</span></h1>';
h += '<div class="total"><span class="n" id="tot">' + fmt(n.pol) + '</span><span class="u">POL</span></div><div class="verify"><svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" aria-hidden="true"><path d="M5 12l5 5 9-10"/></svg>Paid by ' + PROGRAMS.length + ' programs, every payment on Polygon</div>';
h += '<div class="stats"><div><b>' + fmtInt(n.payments) + '</b><span>payments</span></div><div><b>' + fmtInt(n.wallets) + '</b><span>wallets paid</span></div>' + (live7 ? '<div><b>' + fmt(live7.pol) + '</b><span>POL in the last 7 days</span></div>' : '') + '</div>';
h += '<div class="stackbar" aria-label="How the network total splits across programs">' + ps.filter(p => prog(p.k).pol > 0).map(p => '<i style="--c:' + p.c + ';flex:' + prog(p.k).pol + '" title="' + esc(p.n) + ': ' + fmt(prog(p.k).pol) + ' POL"></i>').join('') + '</div>';
h += '<div class="keys">' + ps.filter(p => prog(p.k).pol > 0).map(p => '<span style="--c:' + p.c + '"><i></i>' + esc(p.n) + ' <b>' + fmt(prog(p.k).pol) + '</b></span>').join('') + '</div>';
h += '<div class="cta"><a class="btn" href="https://instantadpay.com/join/' + OWNER + '?src=stackpol" rel="noopener">Start your own stack, free</a><span class="fine">Free to join. Network totals, not a promise. What you stack depends on what you do.</span></div></div>' + heroVideo + '</section>';
h += '<div class="sec-head" id="programs"><h2>Where the POL comes from</h2><p>Each program pays straight to your own wallet. <a href="/programs">See all programs</a></p></div>';
h += feat.map(p => feature(p, OWNER)).join('') + '<div class="cards">' + rest.map(p => card(p, prog(p.k).pol, prog(p.k).payments, OWNER)).join('') + '</div>';
h += '<div class="sec-head"><h2>Latest payouts on the ledger</h2><p>Refreshed every 5 minutes. <a href="/ledger">Open the full ledger</a></p></div>' + tableHead(true) + ledgerRows(((IDX && IDX.recent) || []).slice(0, 15), true) + '</tbody></table></div>';
const posts = blog.listPublished().slice(0, 3);
if (posts.length) h += '<div class="sec-head"><h2>From the blog</h2><p><a href="/blog">All posts</a></p></div><div class="posts">' + posts.map(blog.cardHtml).join('') + '</div>';
h += '<div class="sec-head"><h2>Questions</h2></div><div class="faq">' + FAQ.map(([q, a]) => '<details><summary>' + esc(q) + '</summary><p>' + esc(a) + '</p></details>').join('') + '</div>';
return h + tail(videoJs);
}
function programsPage() {
const ps = sortedProgs();
const ld = [{ '@context': 'https://schema.org', '@type': 'ItemList', name: 'Programs that pay POL in the network', itemListElement: ps.map((p, i) => ({ '@type': 'ListItem', position: i + 1, name: p.n, url: SITE + '/earn/' + p.slug })) }];
let h = head({ title: 'Programs That Pay POL: Games, Ads and Link Tools | Stack POL', desc: 'Every program in the network that pays POL on Polygon, with what each has paid so far: InstantAdPay, LinkSpin, PolHunter, Gem Kingdom, SpellWheel, ClutterHunt and more.', path: '/programs', nav: '/programs', jsonld: ld });
h += '<section style="padding:30px 0 6px"><p class="kick">' + PROGRAMS.length + ' programs</p><h1>Programs that pay POL</h1><p class="lead">Ad platforms, link tools and games. Each one pays straight to your own wallet on Polygon, and every payout shows up on the ledger.</p></section>';
h += '<div class="cards" style="margin-top:22px">' + ps.map(p => card(p, prog(p.k).pol, prog(p.k).payments, OWNER)).join('') + '</div>';
return h + tail();
}
function programPage(p, who) { const ref = who || OWNER; // a Pro member's ref (2026-11-09) or the site owner
const s = prog(p.k), rows = ((IDX && IDX.progRecent && IDX.progRecent[p.k]) || ((IDX && IDX.recent) || []).filter(r => r.k === p.k)).slice(0, 20);
const desc = p.n + ' pays POL on Polygon. ' + fmt(s.pol) + ' POL paid in ' + fmtInt(s.payments) + ' payments to ' + fmtInt(s.wallets) + ' wallets so far. ' + p.d.slice(0, 90);
const ld = [{ '@context': 'https://schema.org', '@type': 'BreadcrumbList', itemListElement: [{ '@type': 'ListItem', position: 1, name: 'Stack POL', item: SITE + '/' }, { '@type': 'ListItem', position: 2, name: 'Programs', item: SITE + '/programs' }, { '@type': 'ListItem', position: 3, name: p.n, item: SITE + '/earn/' + p.slug }] },
p.k === 'iap' || p.k === 'ls' || p.app ? { '@context': 'https://schema.org', '@type': 'WebApplication', name: p.n, url: p.site, applicationCategory: 'BusinessApplication', operatingSystem: 'Web', offers: { '@type': 'Offer', price: '0', priceCurrency: 'USD' } }
: { '@context': 'https://schema.org', '@type': 'VideoGame', name: p.n, url: p.site, genre: p.kind, gamePlatform: 'Web browser', playMode: 'SinglePlayer', offers: { '@type': 'Offer', price: '0', priceCurrency: 'USD' } }];
let h = head({ title: p.n + ': How It Pays POL, and What It Has Paid So Far | Stack POL', desc, path: '/earn/' + p.slug, image: '/img/' + p.k + '.jpg', imageAlt: p.n, nav: '/programs', jsonld: ld });
h += '<p class="crumb"><a href="/">Stack POL</a> / <a href="/programs">Programs</a> / ' + esc(p.n) + '</p>';
h += '<section class="hero" style="padding-top:10px"><div><p class="kick">' + esc(p.kind) + '</p><h1>' + esc(p.n) + '</h1><p class="lead">' + esc(p.d) + '</p>';
h += '<div class="total"><span class="n">' + fmt(s.pol) + '</span><span class="u">POL</span></div><div class="stats"><div><b>' + fmtInt(s.payments) + '</b><span>payments</span></div><div><b>' + fmtInt(s.wallets) + '</b><span>wallets paid</span></div>' + (s.last ? '<div><b>' + ago(s.last) + '</b><span>last payout</span></div>' : '') + '</div>';
if (p.season) h += '<p style="color:#fb923c;font-weight:700">' + esc(p.season.label) + '</p>';
h += '<div class="cta"><a class="btn" href="' + esc(p.join(ref)) + '" rel="nofollow noopener" target="_blank">' + (p.verb || (p.k === 'iap' || p.k === 'ls' ? 'Join' : 'Play')) + ' ' + esc(p.n) + ' free</a><a class="btn sec" href="/ledger?p=' + p.k + '">Its payouts on the ledger</a></div></div>';
h += '<aside><img src="/img/' + p.k + '.jpg" alt="' + esc(p.n) + '" width="800" height="420" style="border-radius:18px;border:1px solid var(--line)"></aside></section>';
h += '<div class="sec-head"><h2>How ' + esc(p.n) + ' pays</h2></div><p class="lead" style="max-width:72ch">' + esc(p.how || ('Rewards are sent in POL from ' + p.n + '\'s own payout wallet straight to the wallet on your account, on the Polygon network. Every payment is a public transaction you can open on Polygonscan.')) + '</p>';
if (p.guides) h += '<p class="lead" style="max-width:72ch"><a href="' + esc(p.guides) + '" target="_blank" rel="noopener">Read the ' + esc(p.n) + ' guides</a> on its own site: how it works, whether it is legit (the contract, the ledger and the split) and the FAQ.</p>'; // 2026-11-17
h += '<div class="sec-head"><h2>Latest ' + esc(p.n) + ' payouts</h2><p><a href="/ledger?p=' + p.k + '">All of them</a></p></div>' + tableHead(true) + ledgerRows(rows, true) + '</tbody></table></div>';
const posts = blog.listPublished().filter(b => b.tags.includes(p.slug) || b.tags.includes(p.n.toLowerCase())).slice(0, 3);
if (posts.length) h += '<div class="sec-head"><h2>Guides</h2></div><div class="posts">' + posts.map(blog.cardHtml).join('') + '</div>';
h += '<div class="sec-head"><h2>More programs that pay POL</h2></div><div class="cards">' + sortedProgs().filter(x => x.k !== p.k).slice(0, 3).map(x => card(x, prog(x.k).pol, prog(x.k).payments, ref)).join('') + '</div>';
return h + tail();
}
function ledgerPage(k) {
const p = k && BY_KEY[k]; const rows = ((IDX && IDX.recent) || []).filter(r => !p || r.k === p.k);
let h = head({ title: (p ? p.n + ' Payout Ledger' : 'The POL Payout Ledger') + ': Every Payment on Polygon | Stack POL', desc: 'The latest POL payouts across the network' + (p ? ' from ' + p.n : '') + ', each linked to its Polygon transaction. Refreshed every 5 minutes.', path: p ? '/ledger?p=' + p.k : '/ledger', nav: '/ledger', noindex: !!p });
h += live() + '<section style="padding:20px 0 6px"><p class="kick">Public and checkable</p><h1>The payout ledger</h1><p class="lead">The latest ' + rows.length + ' payouts' + (p ? ' from ' + esc(p.n) : ' across the network') + '. Each row shows the member it was paid to; members with a Stack POL page link to it. Every row links to its transaction on Polygonscan.</p></section>';
h += '<div class="ltools"><a class="chip" href="/ledger"' + (!p ? ' aria-current="page"' : '') + '>All</a>' + sortedProgs().map(x => '<a class="chip" href="/ledger?p=' + x.k + '"' + (p && p.k === x.k ? ' aria-current="page"' : '') + '>' + esc(x.n) + '</a>').join('') + '</div>';
h += spot(ZONES.banner, ZONES.strip) + tableHead(true) + ledgerRows(rows, true) + '</tbody></table></div>' + spot(ZONES.ledgerBox, ZONES.ledgerBox);
return h + tail();
}
function stackPage(u, st) {
const ps = PROGRAMS.filter(p => st.byProg[p.k]).sort((a, b) => st.byProg[b.k].pol - st.byProg[a.k].pol);
const since = st.since ? new Date(st.since).toLocaleDateString('en-US', { month: 'long', year: 'numeric', timeZone: 'America/Chicago' }) : '';
const ld = [{ '@context': 'https://schema.org', '@type': 'ProfilePage', name: '@' + u + ' on Stack POL', url: SITE + '/' + u, mainEntity: { '@type': 'Person', alternateName: u } }];
let h = head({ title: '@' + u + '\'s POL Stack: ' + fmt(st.total) + ' POL From ' + ps.length + ' Programs | Stack POL', desc: '@' + u + ' has stacked ' + fmt(st.total) + ' POL from ' + ps.length + ' programs in the network, every payment on Polygon. Start your own stack free.', path: '/' + u, type: 'profile', jsonld: ld });
h += live() + '<section class="hero"><div><div class="who"><span class="av">' + esc(u[0].toUpperCase()) + '</span><div><b>@' + esc(u) + '</b><span>' + (since ? 'Stacking POL since ' + since : 'Stacking POL') + '</span></div></div><p class="kick">Paid straight to one wallet</p>';
h += '<div class="total"><span class="n">' + fmt(st.total) + '</span><span class="u">POL</span></div><div class="verify"><svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" aria-hidden="true"><path d="M5 12l5 5 9-10"/></svg>From ' + ps.length + ' programs, ' + fmtInt(st.payments) + ' payments on Polygon</div>';
h += '<div class="stackbar">' + ps.map(p => '<i style="--c:' + p.c + ';flex:' + st.byProg[p.k].pol + '" title="' + esc(p.n) + '"></i>').join('') + '</div><div class="keys">' + ps.map(p => '<span style="--c:' + p.c + '"><i></i>' + esc(p.n) + ' <b>' + fmt(st.byProg[p.k].pol) + '</b></span>').join('') + '</div>';
h += '<div class="cta"><a class="btn" href="https://instantadpay.com/join/' + esc(u) + '?src=stackpol" rel="noopener">Start your own stack, free</a><span class="fine">Free to join. One member\'s results, not a promise. What you stack depends on what you do.</span></div></div>' + heroVideo + '</section>';
const feat = PROGRAMS.filter(p => p.season && seasonOn(p)), rest = PROGRAMS.filter(p => !(p.season && seasonOn(p))).sort((a, b) => ((st.byProg[b.k] || {}).pol || 0) - ((st.byProg[a.k] || {}).pol || 0));
h += '<div class="sec-head"><h2>Where @' + esc(u) + '\'s POL comes from</h2><p>Tap any program to start. Each pays to your own wallet.</p></div>' + feat.map(p => feature(p, u)).join('') + '<div class="cards">' + rest.map(p => card(p, (st.byProg[p.k] || {}).pol || 0, (st.byProg[p.k] || {}).payments || 0, u)).join('') + '</div>';
if (st.pro) { // Stack POL Pro (2026-11-09): the member's own links and a purple Polygon QR that opens this page
h += '<div class="prorow"><div style="min-width:0">' + (memberLinks(u, st) || '<p class="kick">@' + esc(u) + '\'s page</p>') + '<p class="lead" style="margin:6px 0 0">Scan the code to open @' + esc(u) + '\'s stack on your phone, or share it anywhere people can see it.</p></div>'
+ (QR ? '<div class="qr"><img src="/qr/' + esc(u) + '.svg" alt="QR code for stackpol.com/' + esc(u) + '" width="150" height="150"><span>stackpol.com/' + esc(u) + '</span></div>' : '') + '</div>';
}
h += spot(ZONES.banner, ZONES.strip);
h += '<div class="sec-head"><h2>@' + esc(u) + '\'s latest payouts</h2></div>' + tableHead(false) + ledgerRows(st.recent || [], false) + '</tbody></table></div>';
const posts = blog.listPublished().slice(0, 3);
if (posts.length) h += '<div class="sec-head"><h2>From the blog</h2><p><a href="/blog">All posts</a></p></div><div class="posts">' + posts.map(blog.cardHtml).join('') + '</div>';
if (st.pro) h += proCta(u);
return h + tail(videoJs);
}
const QRC = new Map(); // username -> svg (the page URL never changes)
async function qrSvg(un) {
if (QRC.has(un)) return QRC.get(un);
const svg = await QR.toString(SITE + '/' + un, { type: 'svg', margin: 1, width: 300, errorCorrectionLevel: 'M', color: { dark: '#6a2fd6', light: '#ffffff' } }); // Polygon purple, dark enough to scan
QRC.set(un, svg); return svg;
}
function notFound(msg) { return head({ title: 'Not found | Stack POL', desc: 'This page is not on Stack POL.', path: '/404', noindex: true }) + '<section style="padding:60px 0"><h1>Nothing stacked here</h1><p class="lead">' + esc(msg || 'That page does not exist.') + '</p><p><a class="btn" href="/">Go to Stack POL</a></p></section>' + tail(); }
function sitemap() {
const d = new Date().toISOString().slice(0, 10);
const u = [['/', 'daily', '1.0'], ['/programs', 'daily', '0.9'], ['/ledger', 'hourly', '0.8'], ['/blog', 'daily', '0.9'], ['/terms', 'yearly', '0.2'], ['/privacy', 'yearly', '0.2'], ['/disclaimer', 'yearly', '0.2']].map(([p, f, pr]) => '<url><loc>' + SITE + p + '</loc><lastmod>' + d + '</lastmod><changefreq>' + f + '</changefreq><priority>' + pr + '</priority></url>').join('')
+ PROGRAMS.map(p => '<url><loc>' + SITE + '/earn/' + p.slug + '</loc><lastmod>' + d + '</lastmod><changefreq>daily</changefreq><priority>0.8</priority></url>').join('')
+ blog.listPublished().map(p => '<url><loc>' + SITE + '/blog/' + p.slug + '</loc><lastmod>' + new Date(p.updated).toISOString().slice(0, 10) + '</lastmod><changefreq>monthly</changefreq><priority>0.7</priority></url>').join('')
+ Object.keys((IDX && IDX.stacks) || {}).map(x => '<url><loc>' + SITE + '/' + x + '</loc><changefreq>daily</changefreq><priority>0.5</priority></url>').join('');
return '<?xml version="1.0" encoding="UTF-8"?><urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' + u + '</urlset>';
}
const robots = () => 'User-agent: *\nAllow: /\nDisallow: /api/\n\nSitemap: ' + SITE + '/sitemap.xml\n';
const TYPES = { '.js': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8', '.jpg': 'image/jpeg', '.png': 'image/png', '.svg': 'image/svg+xml', '.mp4': 'video/mp4', '.webmanifest': 'application/manifest+json', '.ico': 'image/x-icon', '.txt': 'text/plain; charset=utf-8', '.xml': 'application/xml' };
function send(req, res, code, type, body, cache) {
const h = { 'Content-Type': type, 'Cache-Control': cache || 'public, max-age=60', 'X-Content-Type-Options': 'nosniff', 'Referrer-Policy': 'strict-origin-when-cross-origin' };
if (/gzip/.test(req.headers['accept-encoding'] || '') && /text|xml|json|javascript/.test(type) && body.length > 1024) { h['Content-Encoding'] = 'gzip'; h.Vary = 'Accept-Encoding'; body = zlib.gzipSync(body); }
res.writeHead(code, h); res.end(req.method === 'HEAD' ? undefined : body);
}
const html = (req, res, code, body, cache) => send(req, res, code, 'text/html; charset=utf-8', body, cache);
function staticFile(req, res, p) {
const f = path.normalize(path.join(PUB, p)); if (!f.startsWith(PUB)) return false;
let st; try { st = fs.statSync(f); } catch (e) { return false; } if (!st.isFile()) return false;
const type = TYPES[path.extname(f).toLowerCase()] || 'application/octet-stream';
if (type === 'video/mp4' && req.headers.range) { // seeking support for the hero video
const m = /bytes=(\d*)-(\d*)/.exec(req.headers.range); const s = m && m[1] ? Number(m[1]) : 0, e = m && m[2] ? Number(m[2]) : st.size - 1;
res.writeHead(206, { 'Content-Type': type, 'Content-Range': 'bytes ' + s + '-' + e + '/' + st.size, 'Accept-Ranges': 'bytes', 'Content-Length': e - s + 1, 'Cache-Control': 'public, max-age=604800' });
return fs.createReadStream(f, { start: s, end: e }).pipe(res), true;
}
res.writeHead(200, { 'Content-Type': type, 'Content-Length': st.size, 'Cache-Control': 'public, max-age=604800', 'Accept-Ranges': 'bytes' });
if (req.method === 'HEAD') res.end(); else fs.createReadStream(f).pipe(res);
return true;
}
// the site assistant (2026-11-15): chatcore.js + kb.js + the network knowledge base (netkb.js); no admin editing on Stack POL
const chatbot = require('./chatbot');
const legal = require('./legal');
const chatJson = (res, code, obj, extra) => { res.writeHead(code, Object.assign({ 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' }, extra || {})); res.end(JSON.stringify(obj)); };
const chatBody = req => new Promise(resolve => { const ch = []; let n = 0; req.on('data', c => { n += c.length; if (n <= 32768) ch.push(c); }); req.on('end', () => { try { resolve(n && n <= 32768 ? JSON.parse(Buffer.concat(ch).toString('utf8')) : {}); } catch (e) { resolve({}); } }); req.on('error', () => resolve({})); });
const server = http.createServer((req, res) => {
let u; try { u = new URL(req.url, SITE); } catch (e) { res.writeHead(400); return res.end(); }
const p = decodeURIComponent(u.pathname);
if ((req.headers.host || '').startsWith('www.')) { res.writeHead(301, { Location: SITE + req.url }); return res.end(); }
try {
if (p === '/api/ingest' && req.method === 'POST') {
if (!KEY || req.headers.authorization !== 'Bearer ' + KEY) { res.writeHead(401); return res.end(); }
const chunks = []; let n = 0;
req.on('data', c => { n += c.length; if (n > 8e6) req.destroy(); else chunks.push(c); });
req.on('end', () => { try { const j = JSON.parse(Buffer.concat(chunks).toString('utf8')); if (!j || !j.network || !j.programs) throw new Error('shape'); j.at = j.at || Date.now(); IDX = j; saveSnap(j); send(req, res, 200, 'application/json', JSON.stringify({ ok: true, at: j.at }), 'no-store'); } catch (e) { send(req, res, 400, 'application/json', JSON.stringify({ error: e.message }), 'no-store'); } });
return;
}
if (p.startsWith('/api/chat') || p.startsWith('/api/admin/kb')) { chatbot.handle(req, res, p, u, { json: chatJson, readBody: chatBody, isAdmin: () => false })
.then(done => { if (!done) chatJson(res, 404, { error: 'Not found' }); }).catch(e => { console.error('[stackpol] chat', e.message); if (!res.headersSent) chatJson(res, 500, { error: 'Server error' }); }); return; }
if (req.method !== 'GET' && req.method !== 'HEAD') { res.writeHead(405); return res.end(); }
if (p === '/api/network-deals' && req.method === 'GET') return require('./netdeals').handle(req, res, 'stackpol'); // Network Weekend ribbon (2026-11-17)
if (p === '/api/totals') return send(req, res, 200, 'application/json', JSON.stringify({ at: IDX ? IDX.at : null, network: net(), programs: (IDX && IDX.programs) || {} }), 'public, max-age=120');
if (p === '/health') return send(req, res, 200, 'text/plain', 'ok', 'no-store');
// ?ref=<username> of a Pro member (Marty 2026-11-09): every call to action credits them (join links, game links, program
// pages) and their banners fill the ad spots. Anyone else, or no ref: the standard network pages and zones.
const refName = String(u.searchParams.get('ref') || '').toLowerCase(), refSt = /^[a-z0-9_]{3,30}$/.test(refName) && IDX && IDX.stacks && IDX.stacks[refName];
const pc = refSt && refSt.pro ? { who: refName, st: refSt } : null;
const page = body => pc ? personalize(body, pc.who, pc.st) : body;
const q = /^\/qr\/([a-z0-9_]{3,30})\.svg$/.exec(p);
if (q) { const st = IDX && IDX.stacks && IDX.stacks[q[1]]; if (!QR || !st || !st.pro) return html(req, res, 404, notFound()); return qrSvg(q[1]).then(svg => send(req, res, 200, 'image/svg+xml', svg, 'public, max-age=86400')).catch(() => html(req, res, 500, notFound())); }
if (p === '/') return html(req, res, 200, page(home()), 'public, max-age=120');
if (legal.PATHS.includes(p)) return html(req, res, 200, page(legal.render(p)), 'public, max-age=3600'); // Terms / Privacy / Disclaimer (2026-11-17)
if (p === '/programs') return html(req, res, 200, page(programsPage()), 'public, max-age=300');
if (p === '/ledger') return html(req, res, 200, page(ledgerPage(u.searchParams.get('p'))), 'public, max-age=120');
let m = /^\/earn\/([a-z0-9-]+)\/?$/.exec(p); if (m) return BY_SLUG[m[1]] ? html(req, res, 200, page(programPage(BY_SLUG[m[1]], pc && pc.who)), 'public, max-age=300') : html(req, res, 404, notFound());
if (p === '/blog' || p === '/blog/') return html(req, res, 200, page(blog.renderIndex(1)));
m = /^\/blog\/page\/(\d+)$/.exec(p); if (m) return html(req, res, 200, page(blog.renderIndex(Number(m[1]))));
m = /^\/blog\/tag\/([^/]+)$/.exec(p); if (m) return html(req, res, 200, page(blog.renderIndex(1, m[1].toLowerCase())));
if (p === '/blog/feed.xml') return send(req, res, 200, 'application/rss+xml; charset=utf-8', blog.rss(), 'public, max-age=600');
m = /^\/blog\/([a-z0-9-]+)\/?$/.exec(p); if (m) { const post = blog.get(m[1]); return post ? html(req, res, 200, page(blog.renderPost(post, pc)), 'public, max-age=600') : html(req, res, 404, notFound('That post is not here.')); }
if (p === '/sitemap.xml') return send(req, res, 200, 'application/xml; charset=utf-8', sitemap(), 'public, max-age=3600');
if (p === '/robots.txt') return send(req, res, 200, 'text/plain; charset=utf-8', robots(), 'public, max-age=86400');
if (staticFile(req, res, p)) return;
m = /^\/@?([a-z0-9_]{3,30})\/?$/i.exec(p);
if (m && !RESERVED.has(m[1].toLowerCase())) {
const name = m[1].toLowerCase(), st = IDX && IDX.stacks && IDX.stacks[name];
if (st) return html(req, res, 200, st.pro ? personalize(stackPage(name, st), name, st) : stackPage(name, st), 'public, max-age=120');
return html(req, res, 404, notFound('@' + name + ' has not switched on a Stack POL page yet. Members turn it on in InstantAdPay Promo tools.'));
}
return html(req, res, 404, notFound());
} catch (e) { console.error('[stackpol]', p, e); html(req, res, 500, notFound('Something went wrong on our side. Try again in a minute.'), 'no-store'); }
});
(async () => {
// MySQL first: never serve (or take a push into) an empty copy. A few tries for a database that is still starting.
for (let i = 1; ; i++) {
try { await docstore.init(); break; } catch (e) { console.error('docstore init try ' + i + ':', e.message); if (i >= 6) throw e; await new Promise(r => setTimeout(r, 5000)); }
}
process.on('SIGTERM', () => { docstore.drain(8000).finally(() => process.exit(0)); });
if (!docstore.isOn()) { try { fs.mkdirSync(DATA_DIR, { recursive: true }); } catch (e) {} }
loadSnap();
chatbot.init(); // after docstore.init: kb.json and netkb-cache.json are MySQL documents
server.listen(PORT, () => console.log('Stack POL on :' + PORT + ' | snapshot ' + (IDX && IDX.at ? new Date(IDX.at).toISOString() : 'none yet') + ' | store ' + (docstore.isOn() ? 'MySQL' : 'files in ' + DATA_DIR) + ' | posts ' + blog.listPublished().length + ' | ingest ' + (KEY ? 'on' : 'OFF (no STACK_INGEST_KEY)')));
})().catch(e => { console.error('start failed:', e.message); process.exit(1); });