Launch prep: /health + Dockerfile HEALTHCHECK; old site links (/?<old username>, /splashpg.php?pid=N&r=, /lcp.php?pid=N&r= -> /?ref=<network username> from the oldrefs.json MySQL document, loaded by POST /api/admin/oldrefs; any other *.php -> /), checked before any page; hubreport.js (DLB pattern): each VBBShop purchase reported to the network hub by wallet, first as contract-bind with the sponsor, later as contract-spend, signed as vbb, off unless HUB_ENABLED; compose passes HUB_* + RPC_URLS + CHAIN_ID. Smoke 134/134

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
martbost
2026-11-14 08:03:26 -06:00
parent 07cc1944e6
commit be9de262db
6 changed files with 159 additions and 3 deletions
+6
View File
@@ -31,3 +31,9 @@ SHOP_CONFIRMATIONS=10 # credit only this many blocks behind the head
SHOP_POLL_MS=30000
KEEPER_KEY= # private key of the contract's keeper (signs sponsor vouchers). Coolify secret only, never in git
VOUCHER_SECONDS=1800 # a voucher is good for 30 minutes
# Network hub report (hubreport.js): every VBBShop purchase reported by wallet (bind, then spend). Off unless HUB_ENABLED=1.
HUB_URL= # https://hub.saasy.top
HUB_SECRET= # this site's secret in the hub's HUB_SITES (32+ chars)
HUB_SITE=vbb
HUB_ENABLED=0
RPC_URLS= # kept for parity with Downline Banners; the watcher reads CHAIN_RPC
+2
View File
@@ -7,4 +7,6 @@ RUN mkdir -p /app/data
ENV NODE_ENV=production
ENV PORT=3000
EXPOSE 3000
# a container that cannot boot is never swapped in (2026-10-08 rule)
HEALTHCHECK --interval=15s --timeout=5s --start-period=20s --retries=4 CMD wget -qO- http://127.0.0.1:3000/health >/dev/null || exit 1
CMD ["node","server.js"]
+7 -1
View File
@@ -16,9 +16,15 @@ services:
CHAIN_RPC: ${CHAIN_RPC:-}
SHOP_START_BLOCK: ${SHOP_START_BLOCK:-}
KEEPER_KEY: ${KEEPER_KEY:-}
CHAIN_ID: ${CHAIN_ID:-137}
RPC_URLS: ${RPC_URLS:-}
HUB_URL: ${HUB_URL:-}
HUB_SECRET: ${HUB_SECRET:-}
HUB_SITE: ${HUB_SITE:-vbb}
HUB_ENABLED: ${HUB_ENABLED:-0}
volumes:
- vbb-data:/app/data # uploads only once DOCSTORE_URL is set
expose:
- "3000"
- "3000" # Coolify's proxy routes the domain here; no host port
volumes:
vbb-data:
+75
View File
@@ -0,0 +1,75 @@
// Network hub report (the Downline Banners hubreport.js pattern, 2026-11-14). VBB has no email accounts, so every VBBShop purchase
// goes to the hub by wallet:
// the buyer's first purchase: POST /v1/contract-bind { contract: 'viralbannerblitz', wallet, sponsorRef: <sponsor wallet>, spentCents, tx, at }
// every later purchase: POST /v1/contract-spend { contract: 'viralbannerblitz', wallet, cents, tx, at }
// signed as HUB_SITE (default vbb) with HUB_SECRET (X-Hub-Site, X-Hub-Ts, X-Hub-Sig = hex HMAC-SHA256(ts + newline + raw body)).
// One way only: nothing the hub answers changes anything here. A wallet the hub does not know (404) is kept in `unknown` and asked
// again every 6 hours (the member may link it on InstantAdPay later). Off unless HUB_ENABLED=1 with HUB_URL and a 32+ char HUB_SECRET.
// State lives in hubreport.json (a MySQL document through docstore when DOCSTORE_URL is set).
'use strict';
const crypto = require('crypto');
const fs = require('fs');
const path = require('path');
const CONTRACT = 'viralbannerblitz';
const ZERO = '0x0000000000000000000000000000000000000000';
const enabled = () => /^(1|true|yes|on)$/i.test(String(process.env.HUB_ENABLED || '').trim())
&& !!String(process.env.HUB_URL || '').trim() && String(process.env.HUB_SECRET || '').trim().length >= 32;
const RECHECK = 6 * 3600000;
let R = null, st = null, busy = false;
const FILE = () => path.join(R.dataDir, 'hubreport.json');
function load() {
if (st) return st;
try { st = JSON.parse(fs.readFileSync(FILE(), 'utf8')); } catch (e) { st = {}; }
st.sent = st.sent || {}; st.bound = st.bound || {}; st.unknown = st.unknown || {}; st.errors = st.errors || {}; st.log = st.log || [];
return st;
}
function save() { try { fs.writeFileSync(FILE() + '.tmp', JSON.stringify(load())); fs.renameSync(FILE() + '.tmp', FILE()); } catch (e) { console.error('hubreport save', e.message); } }
function note(x) { const s = load(); s.log.push(Object.assign({ ts: Date.now() }, x)); if (s.log.length > 200) s.log = s.log.slice(-200); }
async function post(route, body) {
const raw = JSON.stringify(body); const ts = String(Date.now());
const sig = crypto.createHmac('sha256', String(process.env.HUB_SECRET).trim()).update(ts + '\n' + raw).digest('hex');
const ac = new AbortController(); const t = setTimeout(() => ac.abort(), 15000);
try {
const r = await fetch(String(process.env.HUB_URL).trim().replace(/\/+$/, '') + route, { method: 'POST', body: raw, signal: ac.signal,
headers: { 'Content-Type': 'application/json', 'X-Hub-Site': String(process.env.HUB_SITE || 'vbb').trim(), 'X-Hub-Ts': ts, 'X-Hub-Sig': sig } });
let j = null; try { j = await r.json(); } catch (e) {}
return { status: r.status, body: j };
} finally { clearTimeout(t); }
}
async function tick() {
if (!enabled() || busy) return; busy = true;
try {
const s = load(); const now = Date.now();
const list = R.purchases().slice().sort((a, b) => (a.block || 0) - (b.block || 0) || (a.at || 0) - (b.at || 0));
for (const p of list) {
if (s.sent[p.key]) continue;
const a = p.buyer;
if (s.unknown[a] && now - s.unknown[a].at < RECHECK) continue;
const tx = String(p.key).split(':')[0];
const bind = !s.bound[a];
const body = bind
? { contract: CONTRACT, wallet: a, sponsorRef: p.sponsor && p.sponsor !== ZERO ? p.sponsor : '', spentCents: p.usdCents || 0, tx, at: p.at || now }
: { contract: CONTRACT, wallet: a, cents: p.usdCents || 0, tx, at: p.at || now };
let r; try { r = await post(bind ? '/v1/contract-bind' : '/v1/contract-spend', body); }
catch (e) { s.errors[p.key] = { at: now, error: e.message }; break; } // hub unreachable: try again next tick
if (r.status === 200) { s.sent[p.key] = { at: now, route: bind ? 'bind' : 'spend' }; if (bind) s.bound[a] = now; delete s.unknown[a]; delete s.errors[p.key]; note({ sent: p.key, bind }); }
else if (r.status === 404) { s.unknown[a] = { at: now, sponsor: p.sponsor || null }; note({ unknown: a }); }
else { s.errors[p.key] = { at: now, status: r.status, error: r.body && (r.body.error || r.body.message) }; note({ error: p.key, status: r.status }); if (r.status >= 500) break; }
}
save();
} finally { busy = false; }
}
// deps: { dataDir, purchases: () => [{ key, buyer, sponsor, usdCents, block, at }] }
function init(deps) {
R = deps; if (!enabled()) return; load(); save();
const every = Math.max(200, Number(process.env.HUB_TICK_MS) || 60000);
setTimeout(() => tick().catch(e => console.error('hubreport', e.message)), Math.min(20000, every)).unref();
setInterval(() => tick().catch(e => console.error('hubreport', e.message)), every).unref();
}
function view() { if (!R) return { enabled: false }; const s = load(); return { enabled: enabled(), site: String(process.env.HUB_SITE || 'vbb').trim(), sent: Object.keys(s.sent).length, bound: Object.keys(s.bound).length, unknown: s.unknown, errors: s.errors, log: s.log.slice(-30) }; }
module.exports = { init, tick, view, enabled, CONTRACT };
+36 -1
View File
@@ -36,10 +36,17 @@ require('node:http').createServer(async (q, r) => { let b = ''; for await (const
if (j.method === 'eth_blockNumber') result = '0x' + CHAIN.head.toString(16);
if (j.method === 'eth_getLogs') { const f = j.params[0], lo = parseInt(f.fromBlock, 16), hi = parseInt(f.toBlock, 16); result = CHAIN.logs.filter(l => CHAIN.replayAll || (parseInt(l.blockNumber, 16) >= lo && parseInt(l.blockNumber, 16) <= hi)); }
r.setHeader('Content-Type', 'application/json'); r.end(JSON.stringify({ jsonrpc: '2.0', id: j.id, result })); }).listen(CHAIN_PORT, '127.0.0.1').unref();
// stand-in network hub: records the signed reports (contract-bind / contract-spend) and checks each signature
const HUB = { got: [], badSig: 0 }; const HUB_PORT = PORT + 3, HUB_SECRET = 'h'.repeat(40);
require('node:http').createServer(async (q, r) => { let b = ''; for await (const c of q) b += c;
const want = crypto.createHmac('sha256', HUB_SECRET).update(q.headers['x-hub-ts'] + '\n' + b).digest('hex');
if (q.headers['x-hub-sig'] !== want || q.headers['x-hub-site'] !== 'vbb') { HUB.badSig++; r.statusCode = 401; return r.end('{}'); }
HUB.got.push({ route: q.url, body: JSON.parse(b) }); r.setHeader('Content-Type', 'application/json'); r.end(JSON.stringify({ id: 'p' + HUB.got.length })); }).listen(HUB_PORT, '127.0.0.1').unref();
const ENV = Object.assign({}, process.env, { PORT: String(PORT), DATA_DIR: DATA, ADMIN_TOKEN: ADMIN, NODE_ENV: 'development', DOCSTORE_URL: '',
LOOP_SIZE: '5', VISITORS_PER_SHIFT: '3', VIEWS_PER_CYCLE: '150', VISIT_SECONDS: '2', VISITS_PER_IP_DAY: '2', LINK_PROBE: '0', NETWORK_LOOKUP_URL: 'http://127.0.0.1:' + (PORT + 1) + '/api/network/member',
NETWORK_SSO_SECRET: SSO_SECRET, IAP_URL: 'https://iap.invalid', LS_URL: 'https://ls.invalid',
CONTRACT_ADDRESS: SHOP, CHAIN_RPC: 'http://127.0.0.1:' + CHAIN_PORT, KEEPER_KEY: KEEPER_PK, SHOP_START_BLOCK: '1', SHOP_CONFIRMATIONS: '0', SHOP_POLL_MS: '200' });
CONTRACT_ADDRESS: SHOP, CHAIN_RPC: 'http://127.0.0.1:' + CHAIN_PORT, KEEPER_KEY: KEEPER_PK, SHOP_START_BLOCK: '1', SHOP_CONFIRMATIONS: '0', SHOP_POLL_MS: '200',
HUB_ENABLED: '1', HUB_URL: 'http://127.0.0.1:' + HUB_PORT, HUB_SECRET, HUB_SITE: 'vbb', HUB_TICK_MS: '300' });
const sleep = ms => new Promise(r => setTimeout(r, ms));
let pass = 0, fail = 0; let srv = null;
const ok = (cond, what, extra) => { if (cond) { pass++; console.log(' ok ' + what); } else { fail++; console.log(' FAIL ' + what + (extra !== undefined ? ' -> ' + JSON.stringify(extra).slice(0, 400) : '')); } };
@@ -300,6 +307,34 @@ async function main() {
my = await V.json('/api/my'); ok(my.credits === credits0 + 60, 'after a restart the replayed logs still credit nothing', my.credits);
const cfgNow = await (await fetch(BASE + '/api/config')).json(); ok(!JSON.stringify(cfgNow).toLowerCase().includes(SHOP.slice(2).toLowerCase()), 'public config does not offer the contract yet (packages stay coming soon)');
// ---- 12b. hub report: each purchase reported once, signed as vbb (first = bind with the sponsor, later = spend) ----
console.log('12b. hub report');
await sleep(1200);
const binds = HUB.got.filter(x => x.route === '/v1/contract-bind'), spends = HUB.got.filter(x => x.route === '/v1/contract-spend');
ok(HUB.badSig === 0 && binds.length === 1 && binds[0].body.contract === 'viralbannerblitz' && binds[0].body.wallet === V.address && binds[0].body.sponsorRef === spW && binds[0].body.spentCents === 600 && binds[0].body.tx === tx1, 'hub: the first purchase is a signed contract-bind with the sponsor wallet and 600 cents', HUB);
ok(spends.length === 1 && spends[0].body.wallet === V.address && spends[0].body.cents === 1000, 'hub: the second purchase is a contract-spend of 1000 cents', spends);
const adh = await anon.json('/api/admin/status', undefined, { 'x-admin-token': ADMIN });
ok(adh.hub && adh.hub.enabled && adh.hub.sent === 2 && adh.hub.site === 'vbb' && !JSON.stringify(adh).includes(HUB_SECRET), 'admin status shows the hub report (2 sent), never the secret', adh.hub);
// ---- 12c. old site links + health ----
console.log('12c. old site links + health');
r = await anon.req('/health'); let hj = await r.json(); ok(r.status === 200 && hj.ok === true && hj.store === 'files', '/health answers ok (files in the smoke test)', hj);
r = await anon.json('/api/admin/oldrefs', { oldrefs: { oldguy: 'netguy', 'bad key!': 'x', other: 'bad value!' } }); ok(r._status === 401, 'loading old refs needs the admin token');
r = await anon.json('/api/admin/oldrefs', { oldrefs: { oldguy: 'netguy', '224411': 'berninisonia80', 'bad key!': 'x', other: 'bad value!' } }, { 'x-admin-token': ADMIN });
ok(r.ok && r.total === 2 && r.skipped === 2, 'admin loads the old username map, bad rows skipped', r);
const oloc = async q => { const x = await anon.req(q); return x.status + ' ' + x.headers.get('location'); };
ok(await oloc('/?oldguy') === '301 /?ref=netguy', '/?<old username> -> /?ref=<network username>');
ok(await oloc('/?OldGuy&fbclid=abc') === '301 /?ref=netguy', 'old username is case-insensitive and fbclid may follow');
ok(await oloc('/?224411') === '301 /?ref=berninisonia80', 'a numeric old username maps too');
ok(await oloc('/splashpg.php?pid=3&r=oldguy') === '301 /?ref=netguy', '/splashpg.php?pid=N&r=<old> -> /?ref=<network>');
ok(await oloc('/lcp.php?pid=12&r=oldguy') === '301 /?ref=netguy', '/lcp.php?pid=N&r=<old> -> /?ref=<network>');
ok(await oloc('/?nobodyhere') === '301 /', 'an unknown old username goes home');
ok(await oloc('/splashpg.php?pid=3&r=nobodyhere') === '301 /', 'an unknown old splash ref goes home');
ok(await oloc('/members.php') === '301 /' && await oloc('/login.php?x=1') === '301 /', 'any other old *.php page goes home');
r = await anon.req('/?ref=netguy'); ok(r.status === 200, 'the new ?ref= link is served, not redirected');
r = await anon.req('/'); ok(r.status === 200, 'the plain home page is served');
const adr = await anon.json('/api/admin/status', undefined, { 'x-admin-token': ADMIN }); ok(adr.oldrefs === 2, 'admin status counts the old refs', adr.oldrefs);
// ---- 13. page renders (Playwright, if installed) ----
if (!process.env.SKIP_UI && fs.existsSync(PW)) {
console.log('13. page renders (Playwright)');
+33 -1
View File
@@ -19,6 +19,7 @@ const loop = require('./loop');
const safety = require('./safety');
const networksso = require('./networksso');
const shop = require('./shop');
const hubreport = require('./hubreport'); // network hub report by wallet (off unless HUB_ENABLED)
const PUB = path.join(__dirname, 'public');
const UPL = path.join(C.dataDir, 'uploads');
@@ -163,6 +164,26 @@ networksso.init({ self: 'vbb', peer: 'iap', peerBase: () => C.iapBase, from: { i
},
landing: to => to, signinPath: to => to });
// old site links (2026-11-14, the Downline Banners pattern): the old YFW site's referral links were /?<old username>,
// /splashpg.php?pid=N&r=<old username> and /lcp.php?pid=N&r=<old username>. An old username maps to the same person's network
// username (oldrefs.json, a MySQL document loaded by POST /api/admin/oldrefs, matched by email); any other *.php page goes home.
let oldRefs = { at: 0, map: {} };
function oldRefMap() {
if (Date.now() - oldRefs.at < 60000) return oldRefs.map;
let m = {}; try { m = JSON.parse(fs.readFileSync(path.join(C.dataDir, 'oldrefs.json'), 'utf8')) || {}; } catch (e) {}
oldRefs = { at: Date.now(), map: m }; return m;
}
function oldLink(u) {
const p = u.pathname;
const bare = u.search.slice(1).split('&')[0];
if (p === '/' || p === '/index.php') { if (!/^[A-Za-z0-9_.-]{2,40}$/.test(bare)) return p === '/' ? null : '/'; } // "&fbclid=..." may follow
else if (!/\.php$/i.test(p)) return null;
const lp = p.toLowerCase();
const old = (lp === '/splashpg.php' || lp === '/lcp.php') ? String(u.searchParams.get('r') || '') : (lp === '/' || lp === '/index.php') ? bare : '';
const net = /^[A-Za-z0-9_.-]{2,40}$/.test(old) ? oldRefMap()[old.toLowerCase()] : null;
return net ? '/?ref=' + encodeURIComponent(net) : '/';
}
const PAGES = { '/': 'index.html', '/my': 'my.html', '/leaders': 'leaders.html', '/how': 'how.html', '/packages': 'packages.html', '/admin': 'admin.html' };
const challenges = new Map();
const clickSeen = new Map();
@@ -175,6 +196,8 @@ const server = http.createServer(async (req, res) => {
if (req.method === 'GET' && (p.startsWith('/sso/') || p === '/api/sso/status') && await networksso.handle(req, res, u)) return;
if (req.method === 'GET' || req.method === 'HEAD') {
if (p === '/health') return json(res, 200, { ok: true, store: docstore.isOn() ? 'mysql' : 'files' });
{ const to = oldLink(u); if (to) { res.writeHead(301, { Location: to, 'Cache-Control': 'no-store' }); return res.end(); } } // before any page
if (PAGES[p]) {
const ex = {};
const ref = u.searchParams.get('ref');
@@ -343,7 +366,15 @@ const server = http.createServer(async (req, res) => {
queue: { length: S.queue.length, next: S.queue.slice(0, 20) }, progress: S.progress, held: S.progress >= C.perShift && !S.queue.length,
today: { visits: t.visits || 0, shifts: t.shifts || 0, cycles: t.cycles || 0, posts: t.posts || 0, clicks: t.clicks || 0 },
totals: S.totals, ledger: { entries: L.length, views: L.reduce((x, e) => x + e.views, 0), viewsByStatus: byStatus, credited: 0 },
members: store.members().length, banners: S.banners.length, visitsKept: store.visits().length, shop: shop.view(), docstore: docstore.view() });
members: store.members().length, banners: S.banners.length, visitsKept: store.visits().length, shop: shop.view(), hub: hubreport.view(), docstore: docstore.view(), oldrefs: Object.keys(oldRefMap()).length });
}
// old username -> network username map for the old-link redirects: { oldrefs: { old: network } } replaces the whole map
if (p === '/api/admin/oldrefs' && req.method === 'POST') {
let b; try { b = JSON.parse((await readRaw(req, 4 * 1024 * 1024)).toString('utf8')); } catch (e) { return json(res, 400, { error: 'bad json' }); }
if (!b || !b.oldrefs || typeof b.oldrefs !== 'object') return json(res, 400, { error: 'oldrefs object required' });
const o = {}; for (const [k, v] of Object.entries(b.oldrefs)) if (/^[a-z0-9_.-]{2,40}$/.test(k) && NAME_RE.test(String(v))) o[k] = String(v);
fs.writeFileSync(path.join(C.dataDir, 'oldrefs.json'), JSON.stringify(o)); oldRefs = { at: 0, map: {} };
return json(res, 200, { ok: true, total: Object.keys(o).length, skipped: Object.keys(b.oldrefs).length - Object.keys(o).length });
}
if (p === '/api/admin/ledger' && req.method === 'GET') {
const n = Math.min(2000, Math.max(1, Number(u.searchParams.get('n')) || 200)); const L = store.ledger();
@@ -373,6 +404,7 @@ function saveUpload(owner, buf, ext) {
store.load();
loop.init({ onCycle: (b, e) => console.log('cycle', 'banner #' + b.id, e.views + ' network views recorded') });
store.pruneVisits(); loop.rebuildIndex();
hubreport.init({ dataDir: C.dataDir, purchases: () => Object.entries((store.state() || {}).purchases || {}).map(([key, x]) => Object.assign({ key }, x)) });
shop.init(C); // inert without CONTRACT_ADDRESS + CHAIN_RPC (watcher) / KEEPER_KEY (vouchers)
setInterval(() => { if (store.pruneVisits()) loop.rebuildIndex(); }, 3600000).unref();
server.listen(C.port, () => console.log('Viral Banner Blitz on :' + C.port + ' loop ' + C.loopSize + ', ' + C.perShift + ' visitors per shift, store: ' + (docstore.isOn() ? 'MySQL documents' : 'files (prototype mode)')));