// Network hub events for a wallet site (Marty 2026-11-16, "Yes do 1 and 2"). Byte-identical in Viral Banner Blitz, Downline Banners, // ViralAdBlitz, DownlineHydra and 5xYourTeam (like networksso.js): copy it whole, never edit one copy alone. // // The hub tells every hooked site what changed (POST /api/hub/events, the same hook InstantAdPay and LinkSpin take): X-Hub-Ts + // X-Hub-Sig = hex HMAC-SHA256(HUB_SECRET, ts + newline + raw body), 5-minute window. The hub only moves its cursor after a 2xx and // may send an event twice. This site acts on three events and ignores every other one: // member.signedout "Sign out everywhere" on any network site // member.blocked the hub blocked the person // member.erased the hub erased the person ({emailHash, walletHashes}: the person is gone from the hub, so no lookup) // Each one ends that person's sessions here. A wallet site keys sessions by wallet, so the person is mapped through the hub: // POST /v1/resolve {id} (signed as HUB_SITE) gives their main wallet and every contract wallet (contractWallets). An erased // person cannot be looked up any more: the event carries the SHA-256 of each of their wallets (and of their email) instead. // Only sessions made BEFORE the event end (a fresh sign-in after it stays), so a replay can never sign anyone out twice. // A failed lookup answers 503 so the hub sends the batch again; after 5 tries an event is set aside in the log. // Nothing here sends mail, posts or touches a banner, a payout or the chain: it only ends sign-in sessions. // // init({ dataDir, site, end }) where end({ type, personId, at, wallets, walletHashes, emailHash, match }) ends the sessions and // answers how many; match(session-like {address?, email?, wallet?, hubId?}) is the shared test (wallet, wallet hash, email // hash, hub id). Off when HUB_HOOK=0, or without HUB_URL and a 32+ character HUB_SECRET (then the route answers 404). 'use strict'; const crypto = require('crypto'); const fs = require('fs'); const path = require('path'); const WALLET_RE = /^0x[0-9a-f]{40}$/, HASH_RE = /^[0-9a-f]{64}$/; const TRIES = 5, KEEP = 3000, SKEW = 2000; const ACTS = new Set(['member.signedout', 'member.blocked', 'member.erased']); let R = null, st = null, chain_ = Promise.resolve(); const SECRET = () => String(process.env.HUB_SECRET || '').trim(); const BASE = () => String(process.env.HUB_URL || '').trim().replace(/\/+$/, ''); const SITE = () => String(process.env.HUB_SITE || (R && R.site) || '').trim().toLowerCase(); const on = () => !/^(0|false|no|off)$/i.test(String(process.env.HUB_HOOK || '').trim()) && /^https?:\/\/[a-z0-9.:-]+$/i.test(BASE()) && SECRET().length >= 32; const lc = v => String(v == null ? '' : v).trim().toLowerCase(); const sha = v => crypto.createHash('sha256').update(lc(v)).digest('hex'); const FILE = () => path.join(R.dataDir, 'hubevents.json'); function load() { if (st) return st; try { st = JSON.parse(fs.readFileSync(FILE(), 'utf8')); } catch (e) { st = null; } if (!st || typeof st !== 'object') st = {}; st.done = st.done || {}; st.tries = st.tries || {}; st.log = st.log || []; st.stats = Object.assign({ batches: 0, events: 0, ended: 0, ignored: 0, skipped: 0, gaveUp: 0, refused: 0 }, st.stats || {}); return st; } function save() { if (!R || !R.dataDir) return; try { const t = FILE() + '.tmp'; fs.writeFileSync(t, JSON.stringify(load())); fs.renameSync(t, FILE()); } catch (e) { console.error('hubevents 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); } function init(deps) { R = deps || {}; load(); } const sign = (ts, raw) => crypto.createHmac('sha256', SECRET()).update(String(ts) + '\n' + raw).digest('hex'); function verify(headers, raw) { if (SECRET().length < 32) return false; const ts = String(headers['x-hub-ts'] || ''), sig = String(headers['x-hub-sig'] || ''); if (!/^\d{10,16}$/.test(ts) || Math.abs(Date.now() - Number(ts)) > 5 * 60000 || !/^[0-9a-f]{64}$/.test(sig)) return false; const want = sign(ts, raw); return crypto.timingSafeEqual(Buffer.from(want), Buffer.from(sig)); } // the hub person by hub id (null = the hub does not know them); throws when the hub does not answer async function resolveId(id) { const raw = JSON.stringify({ id }); const ts = String(Date.now()); const r = await fetch(BASE() + '/v1/resolve', { method: 'POST', body: raw, signal: AbortSignal.timeout(10000), headers: { 'Content-Type': 'application/json', 'X-Hub-Site': SITE(), 'X-Hub-Ts': ts, 'X-Hub-Sig': sign(ts, raw) } }); if (r.status !== 200) throw new Error('hub resolve ' + r.status); const j = await r.json(); return j && j.person && typeof j.person === 'object' ? j.person : null; } // every wallet the hub holds for a person: the main wallet and each contract's wallet function walletsOf(p) { const out = new Set(); if (!p) return []; if (WALLET_RE.test(lc(p.wallet))) out.add(lc(p.wallet)); for (const w of Object.values(p.contractWallets || {})) if (WALLET_RE.test(lc(w))) out.add(lc(w)); return [...out]; } // the shared test: does this session / member belong to the person? function matcher(who) { const ws = new Set(who.wallets || []), hs = new Set(who.walletHashes || []), eh = who.emailHash || null, id = who.personId || null; return x => { if (!x) return false; for (const w of [x.address, x.wallet, x.hubWallet]) { const v = lc(w); if (WALLET_RE.test(v) && (ws.has(v) || hs.has(sha(v)))) return true; } if (eh && x.email && sha(x.email) === eh) return true; if (id && (x.hubId === id || x.key === id)) return true; return false; }; } async function apply(ev) { if (!ACTS.has(ev.type) || !ev.personId) return 'ignored'; const who = { type: ev.type, personId: String(ev.personId), at: Number(ev.at) || Date.now(), wallets: [], walletHashes: [], emailHash: null }; if (ev.type === 'member.erased') { const d = ev.data || {}; who.walletHashes = (Array.isArray(d.walletHashes) ? d.walletHashes : []).map(lc).filter(h => HASH_RE.test(h)).slice(0, 50); who.emailHash = HASH_RE.test(lc(d.emailHash)) ? lc(d.emailHash) : null; } else { const p = await resolveId(who.personId); // throws: the hub sends it again if (!p) return 'ignored'; who.wallets = walletsOf(p); } who.before = who.at + SKEW; // sessions made after the event are fresh sign-ins and stay who.match = matcher(who); const n = Number(await R.end(who)) || 0; note({ type: ev.type, seq: ev.seq, sessions: n }); if (n) { load().stats.ended += n; return 'applied'; } return 'none'; } function prune() { const s = load(); const seqs = Object.keys(s.done).map(Number).sort((a, b) => a - b); for (const q of seqs.slice(0, Math.max(0, seqs.length - KEEP))) delete s.done[q]; } async function handle(events) { const s = load(); s.stats.batches++; let failed = null; for (const ev of Array.isArray(events) ? events : []) { const seq = Number(ev && ev.seq); if (!seq) continue; if (s.done[seq]) { s.stats.skipped++; continue; } s.stats.events++; try { const r = await apply(ev); s.done[seq] = Date.now(); delete s.tries[seq]; if (r === 'ignored') s.stats.ignored++; } catch (e) { s.tries[seq] = (s.tries[seq] || 0) + 1; console.error('hubevents', seq, ev.type, e.message); if (s.tries[seq] >= TRIES) { s.done[seq] = Date.now(); delete s.tries[seq]; s.stats.gaveUp++; note({ type: 'gave-up', seq, event: ev.type, error: String(e.message).slice(0, 160) }); continue; } failed = e; break; } } prune(); save(); return failed ? { status: 503, body: { error: 'retry' } } : { status: 200, body: { ok: true } }; } // the POST /api/hub/events handler -> { status, body }. Batches run one at a time. function receive(headers, raw) { if (!R || !on()) return Promise.resolve({ status: 404, body: { error: 'not found' } }); if (!verify(headers || {}, String(raw || ''))) { load().stats.refused++; return Promise.resolve({ status: 401, body: { error: 'unauthorized' } }); } let b; try { b = JSON.parse(raw || '{}'); } catch (e) { return Promise.resolve({ status: 400, body: { error: 'bad json' } }); } const run = chain_.then(() => handle(b && b.events)); chain_ = run.catch(() => {}); return run; } function view() { const s = load(); return { on: on(), stats: s.stats, waiting: Object.keys(s.tries).length, log: s.log.slice(-20) }; } module.exports = { init, receive, view, on, verify, walletsOf, matcher, sha, _reset: () => { st = null; chain_ = Promise.resolve(); } };