diff --git a/hubevents.js b/hubevents.js new file mode 100644 index 0000000..866c8a4 --- /dev/null +++ b/hubevents.js @@ -0,0 +1,135 @@ +// 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(); } }; diff --git a/public/assets/my.js b/public/assets/my.js index ac71014..97b5045 100644 --- a/public/assets/my.js +++ b/public/assets/my.js @@ -18,6 +18,7 @@ return; } $('signout').onclick = async () => { await VAB.post('/api/auth/logout'); location.reload(); }; + $('signoutAll').onclick = async () => { $('signoutAll').disabled = true; await VAB.post('/api/auth/logout-everywhere'); location.reload(); }; const counter = (inp, out, max) => { const f = () => { out.textContent = inp.value.length + ' / ' + max; }; inp.addEventListener('input', f); f(); }; const copyText = (t, b) => { const o = b.textContent; try { navigator.clipboard.writeText(t); b.textContent = 'Copied'; setTimeout(() => { b.textContent = o; }, 1400); } catch (e) {} }; const ex = c.explorer || 'https://polygonscan.com'; diff --git a/public/my.html b/public/my.html index c7f507b..a5c302f 100644 --- a/public/my.html +++ b/public/my.html @@ -47,7 +47,7 @@ Payouts Promote -
Signed in
+
Signed in
@@ -88,6 +88,6 @@ - + diff --git a/qa/smoke.mjs b/qa/smoke.mjs index 3d2c4e8..ea102c9 100644 --- a/qa/smoke.mjs +++ b/qa/smoke.mjs @@ -476,7 +476,7 @@ const mtop = await anon.json('/api/wire?page=member&u=topdog'); pa = await M1.json('/api/my/ad', adBody(1, { link: 'https://member-1.example-shop.com/third', track: true })); my = await M1.json('/api/my'); ok(pa.ok && pa.linkspin === 'tracked' && my.ad.spin === false && my.linkspin.state === 'tracked', 'back to an ordinary link: tracked with LinkSpin again', [pa, my.linkspin]); const h = await (await anon.req('/my')).text(); const js = await (await anon.req('/assets/my.js?v=7')).text(); - ok(/id="spinBtn"[^>]*>Use one of my spin links]*>Use one of my spin links client().json(p, body, { 'x-admin-token': ADMIN }); let hseq = 900000; const signedIn = async c => (await c.json('/api/me')).signedIn === true; + const hook = async (events, o = {}) => { const raw = JSON.stringify({ events }); const ts = String(o.ts || Date.now()); + const sig = o.sig || crypto.createHmac('sha256', o.secret || HUB_SECRET).update(ts + '\n' + raw).digest('hex'); + const r = await fetch(BASE + '/api/hub/events', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Hub-Ts': ts, 'X-Hub-Sig': sig }, body: raw }); return r.status; }; + const ev = (type, personId, data, at) => ({ seq: ++hseq, at: at || Date.now(), type, personId, data: data || {} }); + const H1 = await walletMember({ hub: { username: 'hookone' } }); const H1b = await walletMember({ wallet: H1.wallet }); const H2 = await walletMember({ hub: { username: 'hooktwo' } }); + const H3 = await walletMember({ hub: { username: 'hookthree' } }); const H4 = await walletMember({ hub: { username: 'hookfour' } }); + ok(H1.ok && H1b.ok && H2.ok && H3.ok && H4.ok && await signedIn(H1) && await signedIn(H1b), 'setup: hub members signed in here (one of them in two browsers)'); + ok(await hook([ev('member.signedout', H1.hubId)], { secret: 'x'.repeat(40) }) === 401 && await hook([ev('member.signedout', H1.hubId)], { ts: Date.now() - 600000 }) === 401, 'a hook signed with another key, or 10 minutes old, is refused (401)'); + ok(await signedIn(H1), 'a refused hook ends nothing'); + const so = ev('member.signedout', H1.hubId); + ok(await hook([so]) === 200 && !(await signedIn(H1)) && !(await signedIn(H1b)) && await signedIn(H2), 'member.signedout: every session of that wallet ends (both browsers), nobody else\'s'); + const H1c = await walletMember({ wallet: H1.wallet }); + ok(await hook([so]) === 200 && await signedIn(H1c), 'the same event sent twice: applied once, a fresh sign-in stays'); + ok(await hook([ev('member.signedout', H1.hubId, {}, Date.now() - 60000)]) === 200 && await signedIn(H1c), 'an event older than a session never ends it (only sessions made before the event)'); + ok(await hook([ev('member.blocked', H2.hubId)]) === 200 && !(await signedIn(H2)) && await signedIn(H3), 'member.blocked: that member is signed out here'); + const wh = crypto.createHash('sha256').update(H3.address).digest('hex'); HUB.people.delete(H3.hubId); + ok(await hook([ev('member.erased', H3.hubId, { emailHash: 'a'.repeat(64), walletHashes: [wh] })]) === 200 && !(await signedIn(H3)) && await signedIn(H4), 'member.erased: found by the wallet hash in the event (the hub no longer knows them), signed out'); + ok(await hook([ev('member.joined', H4.hubId), ev('member.signedout', 'h_' + 'f'.repeat(16))]) === 200 && await signedIn(H4), 'other events and unknown people are ignored'); + HUB.down = true; const late = ev('member.signedout', H4.hubId); + ok(await hook([late]) === 503 && await signedIn(H4), 'the hub lookup failing answers 503 (the hub sends it again), nothing ended'); + HUB.down = false; ok(await hook([late]) === 200 && !(await signedIn(H4)), 'resent once the hub answers: signed out'); + const E1 = await walletMember({ hub: { username: 'hookfive' } }); const E2 = await walletMember({ wallet: E1.wallet }); const g0 = HUB.got.length; + const eo = await E1.json('/api/auth/logout-everywhere', {}); + const call = HUB.got.slice(g0).find(x => x.route === '/v1/sso/signout'); + ok(eo.ok && eo.everywhere === true && !(await signedIn(E1)) && !(await signedIn(E2)) && call && call.body.wallet === E1.address, 'Sign out everywhere: the hub is told (signed, by wallet) and every session of that wallet here ends', { eo, call }); + ok(/id="signoutAll"[^>]*>Sign out everywhere= 5 && st2.hubEvents.stats.refused >= 2 && !JSON.stringify(st2.hubEvents).includes(HUB_SECRET), 'admin status shows the hub events (counts only, no secret)', st2.hubEvents); + } + await stop(); console.log('\n' + pass + ' passed, ' + fail + ' failed'); fs.writeFileSync(path.join(OUT, 'smoke.txt'), new Date().toISOString() + ' ' + pass + ' passed, ' + fail + ' failed\n'); diff --git a/server.js b/server.js index d59bedc..b7e18c8 100644 --- a/server.js +++ b/server.js @@ -26,6 +26,7 @@ const shop = require('./shop'); const promokit = require('./promokit'); const hubreport = require('./hubreport'); const hubpeople = require('./hubpeople'); +const hubevents = require('./hubevents'); // network hub hook (2026-11-16): sign-out-everywhere, block and erase end sessions here const hubline = require('./hubline'); const proof = require('./proof'); const netsites = require('./netsites'); @@ -137,6 +138,8 @@ networksso.init({ self: C.siteId, peer: 'iap', peerBase: () => C.iapBase, from: return cookie('vab.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: 'viraladblitz', end: who => store.endSessions(x => who.match(x) || who.match(store.member(x.address)), who.before) }); // ---- old site links (the VBB pattern): /?, /splashpg.php?pid=N&r=, /lcp.php?pid=N&r= -> the same person's // page here (oldrefs.json, a MySQL document loaded by POST /api/admin/oldrefs, matched by email); any other *.php -> / ---- @@ -344,6 +347,17 @@ const server = http.createServer(async (req, res) => { const s = session(req); if (s) store.dropSession(s.token); return json(res, 200, { ok: true }, { 'Set-Cookie': [cookie('vab.sid', '', 0, true), networksso.offCookie()] }); } + // "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('vab.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') { const s = session(req); if (!s) return json(res, 200, { signedIn: false }); const m = store.member(s.address); @@ -432,7 +446,7 @@ const server = http.createServer(async (req, res) => { today: store.today(), totals: S.totals, members: store.members().length, ads: { live: store.liveAds().length, all: store.ads().length }, boosts: { orders: B.length, views: B.reduce((t, b) => t + b.views, 0), delivered: B.reduce((t, b) => t + b.delivered, 0), active: B.filter(b => b.remaining > 0).length, late: B.filter(b => b.status === 'finishing-in-network').length, waitingForAd: B.filter(b => b.status === 'waiting-for-ad').length }, rows: { visits: store.visits().length, clicks: store.clicks().length, boostViews: store.bviews().length }, - shop: shop.view(), proof: proof.view(), hub: hubreport.view(), hubLookup: hubpeople.view(), nas: vabnas.view(), linkspin: lstrack.view(), docstore: docstore.view(), oldrefs: Object.keys(oldRefMap()).length }); + shop: shop.view(), proof: proof.view(), hub: hubreport.view(), hubLookup: hubpeople.view(), hubEvents: hubevents.view(), nas: vabnas.view(), linkspin: lstrack.view(), docstore: docstore.view(), oldrefs: Object.keys(oldRefMap()).length }); } if (p === '/api/admin/boosts' && req.method === 'GET') return json(res, 200, { boosts: wire.purchases().map(x => Object.assign(wire.boostView(x), { buyer: x.buyer, usdCents: x.usdCents, weiPaid: x.weiPaid, pays: x.pays || null, over: x.over || null })).sort((a, b) => (b.at || 0) - (a.at || 0)) }); if (p === '/api/admin/oldrefs' && req.method === 'POST') { diff --git a/store.js b/store.js index ae62a61..2723c7e 100644 --- a/store.js +++ b/store.js @@ -109,6 +109,8 @@ const SESSION_TTL = 7 * 24 * 3600000; function mintSession(address) { const token = crypto.randomBytes(32).toString('hex'); S.sessions[token] = { address: address.toLowerCase(), expires: Date.now() + SESSION_TTL }; save(); return token; } function session(token) { const s = token && S.sessions[token]; return s && s.expires > Date.now() ? Object.assign({ token }, s) : null; } function dropSession(token) { delete S.sessions[token]; save(); } +// network hub events (hubevents.js, 2026-11-16): end every session `match` names that was made before `before` -> how many +function endSessions(match, before) { let n = 0; for (const [k, x] of Object.entries(S.sessions)) if (x.expires - SESSION_TTL <= before && match(x)) { delete S.sessions[k]; n++; } if (n) save(); return n; } module.exports = { SPLITS, load, flush, save, state, ctDay, ctWeek, bump, today, ad, adOf, addAd, saveAd, ads, liveAds, - addVisit, addClick, addBview, visits, clicks, bviews, prune, member, upsertMember, memberByName, members, mintSession, session, dropSession, SESSION_TTL }; + addVisit, addClick, addBview, visits, clicks, bviews, prune, member, upsertMember, memberByName, members, mintSession, session, dropSession, endSessions, SESSION_TTL };