Network hub hook (Marty 2026-11-16): sign out everywhere, hub blocks and erases end sessions here; "Sign out everywhere" button

hubevents.js (new, byte-identical in VBB, DLB, ViralAdBlitz, DownlineHydra, 5xYourTeam): POST /api/hub/events, signed by the hub
with HUB_SECRET (same hook InstantAdPay and LinkSpin take). member.signedout and member.blocked: the person is looked up by hub id
(/v1/resolve, signed as vbb) and their sessions here end (by the main wallet or any contract wallet). member.erased: matched by the wallet SHA-256s
(and email SHA-256) the hub now sends with the event. Only sessions made before the event end (a replay never signs anyone out
twice); a failed hub lookup answers 503 so the hub resends. Off with HUB_HOOK=0. Admin status: hubEvents (counts only).
My Banners: "Sign out everywhere" next to Sign out (POST /api/auth/logout-everywhere -> networksso.signOutEverywhere, then every
session of this member here ends).
Smoke: section 16 (refused signatures, signedout in two browsers, replay, older event, blocked, erased by wallet hash, other events, hub down -> 503 -> resent, Sign out everywhere, admin view): 322/322 with UI. my.js?v=5.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
martbost
2026-11-16 05:05:34 -06:00
parent 43e8dac257
commit fb45fcddca
6 changed files with 192 additions and 4 deletions
+135
View File
@@ -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(); } };
+1
View File
@@ -16,6 +16,7 @@
return;
}
$('outBtn').onclick = async () => { await VBB.post('/api/auth/logout'); location.reload(); };
$('outAllBtn').onclick = async () => { $('outAllBtn').disabled = true; await VBB.post('/api/auth/logout-everywhere'); location.reload(); };
let uploaded = '';
function preview(src) { const p = $('preview'); p.innerHTML = src ? '<img alt="Preview" width="125" height="125">' : '125 x 125<br>preview'; if (src) p.querySelector('img').src = src; }
+2 -2
View File
@@ -41,7 +41,7 @@
<div id="dash" hidden>
<div class="card">
<div class="row" style="justify-content:space-between"><div><span class="muted small">Signed in as</span> <span class="mono" id="me"></span></div><button class="btn quiet small" id="outBtn">Sign out</button></div>
<div class="row" style="justify-content:space-between"><div><span class="muted small">Signed in as</span> <span class="mono" id="me"></span></div><span class="row" style="gap:8px"><button class="btn quiet small" id="outBtn">Sign out</button><button class="btn quiet small" id="outAllBtn" title="Ends your network sign-in on every network site">Sign out everywhere</button></span></div>
<div class="stats" id="stats"></div>
<p class="muted small" id="creditNote"></p>
</div>
@@ -81,7 +81,7 @@
<script src="/assets/common.js?v=9"></script>
<script src="/assets/wallet.js?v=2"></script>
<script src="/assets/buy.js?v=1"></script>
<script src="/assets/my.js?v=4"></script>
<script src="/assets/my.js?v=5"></script>
<script src="/assets/chat.js?v=2" defer></script>
</body>
</html>
+36
View File
@@ -780,6 +780,42 @@ async function main() {
}
}
console.log('16. network hub events (sign out everywhere, block, erase end sessions here)');
{ const admin = (p, body) => client().json(p, body, { 'x-admin-token': ADMIN }); let hseq = 900000;
const signAs = async w => { const c = client(); NET.add(w.address.toLowerCase()); const ch = await c.json('/api/auth/challenge', { address: w.address });
const v = await c.json('/api/auth/verify', { address: w.address, signature: await w.signMessage(ch.message) });
c.address = w.address.toLowerCase(); c.wallet = w; c.hubId = hubId(c.address); c.ok = v.ok === true && !!c.jar['vbb.sid']; return c; };
const walletMember = o => signAs((o && o.wallet) || ethers.Wallet.createRandom()); 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'); NET.delete(H3.address);
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="outAllBtn"[^>]*>Sign out everywhere</.test(await (await client().req('/my')).text()), '/my has a Sign out everywhere button next to Sign out');
const st2 = await admin('/api/admin/status');
ok(st2.hubEvents && st2.hubEvents.on && st2.hubEvents.stats.ended >= 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');
+15 -1
View File
@@ -93,6 +93,7 @@ const isAdmin = req => { const t = String(process.env.ADMIN_TOKEN || ''); const
// The network hub answers first (hubpeople.js, signed as vbb, cached 5 minutes); InstantAdPay's /api/network/member only when
// the hub is unreachable. A person the hub does not know is unknown here too (never "verified" on InstantAdPay's word alone).
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();
async function netMember(q) {
const h = q.u ? await hubpeople.byRef(q.u) : await hubpeople.byWallet(q.a);
@@ -200,6 +201,8 @@ networksso.init({ self: 'vbb', peer: 'iap', peerBase: () => C.iapBase, from: { i
return cookie('vbb.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: 'vbb', end: who => store.endSessions(x => who.match(x) || who.match(store.member(x.address)), who.before) });
// 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
@@ -365,6 +368,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('vbb.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('vbb.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);
@@ -515,7 +529,7 @@ 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(), prize: prize.view(), proof: proof.view(), hub: hubreport.view(), hubLookup: hubpeople.view(), lsSpins: lsspins.view(), docstore: docstore.view(), oldrefs: Object.keys(oldRefMap()).length });
members: store.members().length, banners: S.banners.length, visitsKept: store.visits().length, shop: shop.view(), prize: prize.view(), proof: proof.view(), hub: hubreport.view(), hubLookup: hubpeople.view(), hubEvents: hubevents.view(), lsSpins: lsspins.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') {
+3 -1
View File
@@ -106,6 +106,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, banner, addBanner, saveBanner, bannersOf, addLedger, ledger,
addVisit, visits, pruneVisits, member, upsertMember, memberByName, members, mintSession, session, dropSession, SESSION_TTL };
addVisit, visits, pruneVisits, member, upsertMember, memberByName, members, mintSession, session, dropSession, endSessions, SESSION_TTL };