diff --git a/hubpeople.js b/hubpeople.js new file mode 100644 index 0000000..ef849cf --- /dev/null +++ b/hubpeople.js @@ -0,0 +1,62 @@ +// Network hub lookups (Marty 2026-11-14: "want everything looped through the hub to verify membership"). The hub is the one +// record per person across the network; this asks it who a username, wallet or hub id is: +// POST /v1/resolve {ref: } | {wallet} | {id: 'h_...'} -> {person: view or null} +// signed as HUB_SITE with HUB_SECRET (X-Hub-Site, X-Hub-Ts, X-Hub-Sig = hex HMAC-SHA256(ts + newline + raw body)), the same +// scheme as hubreport.js. This site cannot see emails (seeEmails false): a person is {id, username, wallet, sponsor: {id, username}, blocked, ...}. +// Answers (people and misses) are cached HUB_CACHE_MS (5 minutes). A failed call (timeout, refused, any non-200) is never +// cached: it returns {ok: false} so the caller can fall back, and the hub is skipped for 30 seconds so pages never wait on it. +// On unless HUB_LOOKUP=0; needs HUB_URL and a 32+ character HUB_SECRET (HUB_ENABLED only switches the shadow report). +'use strict'; +const crypto = require('crypto'); + +const DEFAULT_SITE = 'vbb'; +const ADDR_RE = /^0x[0-9a-f]{40}$/; +const TTL = () => Number(process.env.HUB_CACHE_MS || 5 * 60000); +const TIMEOUT = () => Number(process.env.HUB_LOOKUP_TIMEOUT_MS || 2500); +const on = () => !/^(0|false|no|off)$/i.test(String(process.env.HUB_LOOKUP || '').trim()) + && !!String(process.env.HUB_URL || '').trim() && String(process.env.HUB_SECRET || '').trim().length >= 32; +const cache = new Map(); let downUntil = 0; let lastError = null; const stats = { asked: 0, cached: 0, failed: 0 }; + +async function call(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(), TIMEOUT()); + try { + const r = await fetch(String(process.env.HUB_URL).trim().replace(/\/+$/, '') + '/v1/resolve', { method: 'POST', body: raw, signal: ac.signal, + headers: { 'Content-Type': 'application/json', 'X-Hub-Site': String(process.env.HUB_SITE || DEFAULT_SITE).trim(), 'X-Hub-Ts': ts, 'X-Hub-Sig': sig } }); + if (r.status !== 200) throw new Error('hub answered ' + r.status); + const j = await r.json(); + if (!j || typeof j !== 'object' || !('person' in j)) throw new Error('hub answer has no person field'); + return j.person && typeof j.person === 'object' ? j.person : null; + } finally { clearTimeout(t); } +} + +// {ok: true, person: view | null} when the hub answered; {ok: false} when it is off or unreachable (the caller falls back) +async function resolve(body) { + if (!on() || Date.now() < downUntil) return { ok: false }; + const k = JSON.stringify(body); const hit = cache.get(k); + if (hit && Date.now() - hit.at < TTL()) { stats.cached++; return { ok: true, person: hit.person }; } + stats.asked++; + let person; + try { person = await call(body); } catch (e) { + stats.failed++; downUntil = Date.now() + Number(process.env.HUB_DOWN_MS || 30000); + if (!lastError || Date.now() - lastError.at > 600000) console.error('hub lookup failed, falling back:', e.name === 'AbortError' ? 'timeout' : e.message); + lastError = { at: Date.now(), error: e.name === 'AbortError' ? 'timeout' : String(e.message).slice(0, 120) }; + return { ok: false }; + } + if (cache.size > 20000) cache.clear(); + cache.set(k, { at: Date.now(), person }); + if (person && person.id) cache.set(JSON.stringify({ id: person.id }), { at: Date.now(), person }); + return { ok: true, person }; +} + +const wallet = p => (p && ADDR_RE.test(String(p.wallet || '').toLowerCase()) ? String(p.wallet).toLowerCase() : null); +// a username or wallet -> person (a blocked person counts as unknown) +async function byRef(ref) { const r = await resolve({ ref: String(ref || '').trim().toLowerCase() }); return r.ok ? { ok: true, person: r.person && !r.person.blocked ? r.person : null } : r; } +async function byWallet(w) { const r = await resolve({ wallet: String(w || '').trim().toLowerCase() }); return r.ok ? { ok: true, person: r.person && !r.person.blocked ? r.person : null } : r; } +async function byId(id) { if (!/^h_[0-9a-f]{16}$/.test(String(id || ''))) return { ok: true, person: null }; const r = await resolve({ id: String(id) }); return r.ok ? { ok: true, person: r.person && !r.person.blocked ? r.person : null } : r; } +// the person's network sponsor as a full person (with wallet), resolved through the hub by hub id. {ok, person: sponsor or null} +async function sponsorOf(p) { if (!p || !p.sponsor || !p.sponsor.id) return { ok: true, person: null }; return byId(p.sponsor.id); } + +function view() { return { on: on(), down: Date.now() < downUntil, cached: cache.size, stats, lastError }; } +module.exports = { resolve, byRef, byWallet, byId, sponsorOf, wallet, view, on, _reset: () => { cache.clear(); downUntil = 0; } }; diff --git a/qa/smoke.mjs b/qa/smoke.mjs index 99bcb19..a6f88f2 100644 --- a/qa/smoke.mjs +++ b/qa/smoke.mjs @@ -36,17 +36,32 @@ 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); +// stand-in network hub: records the signed reports (contract-bind / contract-spend), checks each signature, and answers +// POST /v1/resolve {wallet | ref | id | email} the way the real hub does for a site without emails. The hub knows every NET wallet +// (minus HUBSKIP: wallets only InstantAdPay knows), every sponsor wallet in NETSP, HUBONLY wallets, and HUBMAIL emails. +// HUB.down = every hub call fails with 503 (unreachable). +const HUB = { got: [], badSig: 0, resolves: 0, down: false }; const HUB_PORT = PORT + 3, HUB_SECRET = 'h'.repeat(40); +const HUBSKIP = new Set(), HUBONLY = new Set(), HUBMAIL = new Map(); +const hubKnows = w => !!w && ((NET.has(w) && !HUBSKIP.has(w)) || HUBONLY.has(w) || [...NETSP.values()].includes(w)); +const hubId = w => 'h_' + w.slice(2, 18); +const hubPerson = w => hubKnows(w) ? { id: hubId(w), username: 'net' + w.slice(2, 10), wallet: w, blocked: false, + sponsor: NETSP.get(w) && hubKnows(NETSP.get(w)) ? { id: hubId(NETSP.get(w)), username: 'net' + NETSP.get(w).slice(2, 10) } : null } : null; +const hubAll = () => [...new Set([...NET, ...HUBONLY, ...NETSP.values()])].filter(hubKnows); require('node:http').createServer(async (q, r) => { let b = ''; for await (const c of q) b += c; + r.setHeader('Content-Type', 'application/json'); + if (HUB.down) { r.statusCode = 503; return r.end('{"error":"superseded"}'); } 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(); + if (q.url === '/v1/resolve') { HUB.resolves++; const j = JSON.parse(b || '{}'); const ref = String(j.ref || '').toLowerCase(); let w = null; + if (j.wallet) w = String(j.wallet).toLowerCase(); else if (j.id) w = hubAll().find(x => hubId(x) === j.id); else if (ref) w = hubAll().find(x => x === ref || 'net' + x.slice(2, 10) === ref); + else if (j.email && HUBMAIL.has(j.email)) return r.end(JSON.stringify({ person: { id: 'h_' + '9'.repeat(16), username: HUBMAIL.get(j.email), wallet: null, sponsor: null, blocked: false } })); + return r.end(JSON.stringify({ person: hubPerson(w) })); } + HUB.got.push({ route: q.url, body: JSON.parse(b) }); 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', - HUB_ENABLED: '1', HUB_URL: 'http://127.0.0.1:' + HUB_PORT, HUB_SECRET, HUB_SITE: 'vbb', HUB_TICK_MS: '300' }); + HUB_ENABLED: '1', HUB_URL: 'http://127.0.0.1:' + HUB_PORT, HUB_SECRET, HUB_SITE: 'vbb', HUB_TICK_MS: '300', HUB_DOWN_MS: '400' }); 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) : '')); } }; @@ -86,7 +101,8 @@ async function stop() { const p = srv; srv = null; if (!p) return; const done = // a signed-in member by wallet signature async function walletMember(o = {}) { - const w = ethers.Wallet.createRandom(); const c = client(); if (!o.stranger) NET.add(w.address.toLowerCase()); + const w = ethers.Wallet.createRandom(); const c = client(); if (!o.stranger && !o.hubOnly) NET.add(w.address.toLowerCase()); + if (o.hubOnly) HUBONLY.add(w.address.toLowerCase()); if (o.iapOnly) HUBSKIP.add(w.address.toLowerCase()); if (o.sponsor) NETSP.set(w.address.toLowerCase(), o.sponsor === 'self' ? w.address.toLowerCase() : o.sponsor.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) }); @@ -162,6 +178,7 @@ async function main() { const st = new URL(loc).searchParams.get('st'); const nsso = require(path.join(APP, 'networksso.js')); process.env.NETWORK_SSO_SECRET = SSO_SECRET; + HUBMAIL.set('leader@example.org', 'smokeleader'); // the hub knows this network member by email (wallet not linked there yet) const tok = nsso.mint({ iss: 'iap', aud: 'vbb', email: 'leader@example.org', wallet: lw, name: 'smokeleader', st, to: '/my' }); r = await L.req('/sso/in?t=' + encodeURIComponent(tok)); ok(r.status === 302 && r.headers.get('location') === '/my' && !!L.jar['vbb.sid'], 'network token signs the member in', { s: r.status, l: r.headers.get('location') }); @@ -169,6 +186,25 @@ async function main() { const me = await L.json('/api/me'); ok(me.signedIn && me.username === 'smokeleader' && me.address === lw, 'network member keeps the network username', me); my = await L.json('/api/my'); ok(my.credits === 1 && my.share === 'https://viralbannerblitz.com/?ref=smokeleader', 'referral link is ?ref=', my.share); + console.log('4b. network hub: membership + sponsors (InstantAdPay only when the hub is unreachable)'); + const HO = await walletMember({ hubOnly: true }); let mh = await HO.json('/api/my'); + ok(mh.netVerified === true && mh.credits === 1, 'a wallet only the hub knows is network-verified: one free credit', mh); + const IO = await walletMember({ iapOnly: true }); mh = await IO.json('/api/my'); + ok(mh.netVerified === false && mh.credits === 0, 'a wallet only InstantAdPay knows is not verified while the hub answers', mh); + const L2 = client(); r = await L2.req('/sso/start?mode=go&via=linkspin&to=%2Fmy'); const st2 = new URL(r.headers.get('location') || 'https://x/').searchParams.get('st'); + r = await L2.req('/sso/in?t=' + encodeURIComponent(nsso.mint({ iss: 'linkspin', aud: 'vbb', email: 'nobody@example.org', wallet: ethers.Wallet.createRandom().address.toLowerCase(), name: 'smokenobody', st: st2, to: '/my' }))); + mh = await L2.json('/api/my'); ok(L2.jar['vbb.sid'] && mh.netVerified === false && mh.credits === 0, 'a network sign-in the hub does not know (wallet or email): signed in, no free credit', mh); + ok(HUB.resolves > 0 && HUB.badSig === 0, 'hub lookups are signed as vbb with HUB_SECRET', HUB); + HUB.down = true; + const FB = await walletMember(); mh = await FB.json('/api/my'); + ok(mh.netVerified === true && mh.credits === 1, 'hub unreachable: InstantAdPay verifies the wallet (fallback)', mh); + const fbSp = ethers.Wallet.createRandom().address.toLowerCase(); const FBV = await walletMember({ sponsor: fbSp }); let vh = await FBV.json('/api/my/voucher'); + ok(vh._status === 200 && vh.voucher === null && vh.why === 'hub-unavailable', 'hub unreachable: no sponsor voucher (never a sponsor the hub did not give)', vh); + const ah = await anon.json('/api/admin/status', undefined, { 'x-admin-token': ADMIN }); + ok(ah.hubLookup && ah.hubLookup.on && ah.hubLookup.stats.failed >= 1 && !JSON.stringify(ah).includes(HUB_SECRET), 'admin status shows the hub lookup (failures counted, no secret)', ah.hubLookup); + HUB.down = false; await sleep(500); + vh = await FBV.json('/api/my/voucher'); ok(vh.voucher && vh.voucher.sponsor.toLowerCase() === fbSp, 'hub back: the voucher names the hub network sponsor, its wallet resolved by hub id', vh); + console.log('5. posting banners (checks + credits)'); let u = await upload(A, png(468, 60)); ok(u._status === 400 && /125x125/.test(u.error), 'a 468x60 upload is refused', u); u = await upload(A, Buffer.concat([png(125, 125), Buffer.alloc(101 * 1024)])); ok(u._status === 400 && /100 KB/.test(u.error), 'an upload over 100 KB is refused', u); diff --git a/server.js b/server.js index 01cb93a..8ccd29d 100644 --- a/server.js +++ b/server.js @@ -82,9 +82,14 @@ function limited(req, name, max, windowMs) { const isAdmin = req => { const t = String(process.env.ADMIN_TOKEN || ''); const g = String(req.headers['x-admin-token'] || ''); return t.length >= 8 && g.length === t.length && crypto.timingSafeEqual(Buffer.from(g), Buffer.from(t)); }; -// ---- network usernames (InstantAdPay today, the network hub later: this is the one place to point at it) ---- +// ---- network usernames + membership (Marty 2026-11-14: "want everything looped through the hub to verify membership") ---- +// 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 netCache = new Map(); async function netMember(q) { + const h = q.u ? await hubpeople.byRef(q.u) : await hubpeople.byWallet(q.a); + if (h.ok) { const a = hubpeople.wallet(h.person); return a ? { address: a, username: h.person.username ? String(h.person.username) : null, hubId: h.person.id || null, via: 'hub' } : null; } if (!C.networkLookupUrl) return null; const k = q.u ? 'u:' + q.u.toLowerCase() : 'a:' + q.a.toLowerCase(); const hit = netCache.get(k); if (hit && Date.now() - hit.at < 3600000) return hit.m; @@ -92,10 +97,18 @@ async function netMember(q) { try { const ac = new AbortController(); setTimeout(() => ac.abort(), 4000).unref(); const qs = q.u ? 'u=' + encodeURIComponent(q.u) : 'a=' + encodeURIComponent(q.a); const j = await (await fetch(C.networkLookupUrl + '?' + qs, { signal: ac.signal })).json(); - if (j && ADDR_RE.test(j.address || '') && j.username) m = { address: j.address.toLowerCase(), username: String(j.username), sponsor: ADDR_RE.test(j.sponsor || '') ? j.sponsor.toLowerCase() : null }; } catch (e) { return null; } + if (j && ADDR_RE.test(j.address || '') && j.username) m = { address: j.address.toLowerCase(), username: String(j.username), via: 'iap' }; } catch (e) { return null; } netCache.set(k, { at: Date.now(), m }); if (netCache.size > 20000) netCache.clear(); return m; } +// the member's network sponsor as a wallet, through the hub only (a sponsor voucher binds on chain): the hub's sponsor for this +// wallet, resolved to that sponsor's wallet by hub id. {ok: false} = the hub is unreachable; sponsor null = none known. +async function hubSponsorWallet(addr) { + const me = await hubpeople.byWallet(addr); if (!me.ok) return { ok: false }; + if (!me.person || !me.person.sponsor) return { ok: true, sponsor: null }; + const sp = await hubpeople.sponsorOf(me.person); if (!sp.ok) return { ok: false }; + return { ok: true, sponsor: hubpeople.wallet(sp.person) }; +} // ?ref= -> a VBB member's address (only members who have signed in here can be credited) async function resolveRef(raw) { const r = String(raw || '').trim().slice(0, 60); if (!r) return null; @@ -119,13 +132,21 @@ function signedIn(addr, patch) { const m = store.upsertMember(addr, patch); grantDaily(m); return m; } -// free daily credits go to network-verified members only (Marty 2026-11-13, stops wallet farming): signed in through InstantAdPay or -// LinkSpin, or a wallet the network knows. A plain wallet is rechecked on each visit, so joining InstantAdPay later unlocks it. -const netVerified = m => !!m && (m.via === 'iap' || m.via === 'linkspin' || m.netOk === true); -async function verifyNet(addr) { +// free daily credits go to network-verified members only (Marty 2026-11-13, stops wallet farming). Verified (Marty 2026-11-14) = +// the network hub knows this wallet, or knows the network member who signed in here through InstantAdPay or LinkSpin (looked up +// by the email in their sign-in token, never stored). Only while the hub is unreachable: InstantAdPay's lookup by wallet, or a +// network sign-in, as before. A plain wallet is rechecked on each visit, so joining the network later unlocks it. +const netVerified = m => !!m && m.netOk === true; +async function verifyNet(addr, email) { const m = store.member(addr); if (!m || netVerified(m)) return; - const n = await netMember({ a: addr }).catch(() => null); - if (n && n.address === m.address) { store.upsertMember(addr, { netOk: true }); await fillUsername(addr).catch(() => {}); } + const h = await hubpeople.byWallet(addr); + let known = h.ok && !!h.person, down = !h.ok; + if (!known && !down && email) { const e = await hubpeople.resolve({ email: String(email).trim().toLowerCase() }); if (e.ok) known = !!(e.person && !e.person.blocked); else down = true; } + if (!known && down) { + const n = await netMember({ a: addr }).catch(() => null); + known = (n && n.address === m.address) || m.via === 'iap' || m.via === 'linkspin'; + } + if (known) { store.upsertMember(addr, { netOk: true, netAt: Date.now(), netBy: down ? 'fallback' : 'hub' }); await fillUsername(addr).catch(() => {}); } } // one free post credit a day (Central time), banked up to freeCreditCap function grantDaily(m) { @@ -160,6 +181,8 @@ networksso.init({ self: 'vbb', peer: 'iap', peerBase: () => C.iapBase, from: { i const patch = { via: v.iss }; if (v.name && NAME_RE.test(v.name)) { const other = store.memberByName(v.name); if (!other || other.address === v.wallet) patch.username = v.name; } signedIn(v.wallet, patch); + await verifyNet(v.wallet, email).catch(() => {}); // the hub knows this network member (by wallet, else by their email) + grantDaily(store.member(v.wallet)); return cookie('vbb.sid', store.mintSession(v.wallet), store.SESSION_TTL / 1000, true); }, landing: to => to, signinPath: to => to }); @@ -321,7 +344,9 @@ const server = http.createServer(async (req, res) => { if (p === '/api/my/voucher' && req.method === 'GET') { if (limited(req, 'voucher', 60, 3600000)) return json(res, 429, { error: 'Too many requests this hour.' }); if (!shop.voucherOn()) return json(res, 200, { voucher: null, why: 'off' }); - const n = await netMember({ a: me }).catch(() => null); const sp = n && n.address === me ? n.sponsor : null; + const h = await hubSponsorWallet(me).catch(() => ({ ok: false })); + if (!h.ok) return json(res, 200, { voucher: null, why: 'hub-unavailable' }); // no voucher now; the contract binds on a later purchase + const sp = h.sponsor; if (!sp || sp === me) return json(res, 200, { voucher: null, why: 'no-sponsor' }); return json(res, 200, { voucher: await shop.voucher(me, sp) }); } @@ -366,7 +391,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(), hub: hubreport.view(), docstore: docstore.view(), oldrefs: Object.keys(oldRefMap()).length }); + members: store.members().length, banners: S.banners.length, visitsKept: store.visits().length, shop: shop.view(), hub: hubreport.view(), hubLookup: hubpeople.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') {