From 57e733b55d180c998ba2322e1dc0356001e11b90 Mon Sep 17 00:00:00 2001 From: martbost Date: Sat, 14 Nov 2026 09:25:46 -0600 Subject: [PATCH] Member lookups through the network hub (Marty 2026-11-14: "want everything looped through the hub to verify membership"): hubpeople.js asks POST /v1/resolve (ref / wallet / hub id, signed as bannerline, cached 5 minutes, 2.5 s timeout, hub skipped 30 s after a failure); netMember / nameOf ask the hub first and InstantAdPay's /api/network/member only when the hub is unreachable (wallet-aliases.json still first). Sponsor pick: the hub network sponsor for the wallet that will own the spot (the buy page asks /api/sponsor?for= just before the buy; else the signed-in wallet), resolved to a wallet by hub id, nearest up the network line who owns a spot here, none = no sponsor; then the /w/ welcome line (usernames resolved through the hub), then the ?ref= cookie. Admin status shows hubLookup. join.js?v=20261114h. Smoke 91/91 (stand-in hub + stand-in InstantAdPay) Co-Authored-By: Claude Opus 5.5 --- hubpeople.js | 62 +++++++++++++++++++++++++++++++++++++++++++ public/assets/join.js | 5 ++++ public/join.html | 2 +- qa/smoke.mjs | 57 +++++++++++++++++++++++++++++++++++++-- server.js | 52 ++++++++++++++++++++++++++++++------ 5 files changed, 167 insertions(+), 11 deletions(-) create mode 100644 hubpeople.js diff --git a/hubpeople.js b/hubpeople.js new file mode 100644 index 0000000..182a3e4 --- /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 = 'bannerline'; +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/public/assets/join.js b/public/assets/join.js index 3491132..b62083e 100644 --- a/public/assets/join.js +++ b/public/assets/join.js @@ -25,6 +25,11 @@ BL.status(''); try { await loadQuote(); if (!q || q.error) throw new Error('No price right now. Try again in a minute.'); + // the network hub knows many buyers' sponsors (Marty 2026-11-14): ask for the wallet that will own the spot, right before the buy + try { + const owner = forAddr || await BLWallet.activeAddress(await BLWallet.connect()); + if (owner) { const s2 = await BL.getJSON('/api/sponsor?for=' + encodeURIComponent(owner)); if (s2 && !s2.error) { sponsor = s2.address && s2.member ? s2.address : null; $('sponsor').textContent = sponsor ? BL.short(sponsor) : 'none'; } } + } catch (e) { /* keep the sponsor shown on the page */ } BL.status('Confirm the payment in your wallet. The contract refunds anything above the price in the same transaction.'); const r = forAddr ? await BLWallet.buyFor(forAddr, sponsor, q.sendWei) : await BLWallet.buy(sponsor, q.sendWei); if (r.receipt.status !== '0x1') throw new Error('The transaction reverted. Nothing was charged except gas.'); diff --git a/public/join.html b/public/join.html index 23af0f0..8d20f24 100644 --- a/public/join.html +++ b/public/join.html @@ -50,6 +50,6 @@ - + diff --git a/qa/smoke.mjs b/qa/smoke.mjs index a239dd5..d0a4720 100644 --- a/qa/smoke.mjs +++ b/qa/smoke.mjs @@ -25,6 +25,26 @@ const ADMIN = 'smoke-admin'; const sleep = ms => new Promise(r => setTimeout(r, ms)); let pass = 0, fail = 0; const procs = []; 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, 300) : '')); } }; +// stand-in network hub (POST /v1/resolve, signed as bannerline) and stand-in InstantAdPay member lookup (the fallback when the +// hub is unreachable). HUB.people: {id, username, wallet, sponsorId}; HUB.down makes every hub call fail with 503. +const HUB = { people: [], down: false, calls: 0, badSig: 0 }; const HUB_PORT = APP_PORT + 7, HUB_SECRET = 'b'.repeat(40); +const IAPNET = new Map(); const IAP_PORT = APP_PORT + 8; +const hubView = p => p ? { id: p.id, username: p.username, wallet: p.wallet, sponsor: (x => x ? { id: x.id, username: x.username } : null)(HUB.people.find(y => y.id === p.sponsorId)), blocked: false, locked: false } : null; +function startStandIns() { + const http = require('node:http'); const crypto = require('node:crypto'); + http.createServer(async (q, r) => { let b = ''; for await (const c of q) b += c; HUB.calls++; + 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'] !== 'bannerline') { HUB.badSig++; r.statusCode = 401; return r.end('{"error":"unauthorized"}'); } + if (q.url !== '/v1/resolve') { r.statusCode = 404; return r.end('{"error":"not_found"}'); } + const j = JSON.parse(b || '{}'); const ref = String(j.ref || '').toLowerCase(); + const p = j.id ? HUB.people.find(x => x.id === j.id) : j.wallet ? HUB.people.find(x => x.wallet === String(j.wallet).toLowerCase()) : ref ? HUB.people.find(x => x.username === ref || x.wallet === ref) : null; + r.end(JSON.stringify({ person: hubView(p) })); }).listen(HUB_PORT, '127.0.0.1').unref(); + http.createServer((q, r) => { const u = new URL(q.url, 'http://x'); const un = (u.searchParams.get('u') || '').toLowerCase(), a = (u.searchParams.get('a') || '').toLowerCase(); + const hit = [...IAPNET].find(([n, w]) => n === un || w === a); r.setHeader('Content-Type', 'application/json'); + r.end(JSON.stringify(hit ? { address: hit[1], username: hit[0] } : {})); }).listen(IAP_PORT, '127.0.0.1').unref(); +} function cleanup() { for (const p of procs) { try { p.kill(); } catch (e) {} } } process.on('exit', cleanup); @@ -86,7 +106,14 @@ async function main() { // house list for tests: reserved example domains only, so no real site sees test traffic fs.writeFileSync(path.join(DATA, 'house.json'), JSON.stringify([{ key: 'one', title: 'Test house 1', img: '/art/house-iap.svg', link: 'https://example.com/' }, { key: 'two', title: 'Test house 2', img: '/art/house-linkspin.svg', link: 'https://example.net/' }])); const env = Object.assign({}, process.env, { PORT: String(APP_PORT), DATA_DIR: DATA, CHAIN_ID: '31337', RPC_URLS: 'http://127.0.0.1:' + RPC_PORT, CONTRACT_ADDRESS: CA, - DEPLOY_BLOCK: String(deployBlock), POLL_MS: '1000', ADMIN_TOKEN: ADMIN, KEEPER_ENABLED: '1', KEEPER_KEY: W[7].signer.privateKey, KEEPER_STALL_HOURS: '0.01', KEEPER_EVERY_MIN: '0.25', NODE_ENV: 'development' }); + DEPLOY_BLOCK: String(deployBlock), POLL_MS: '1000', ADMIN_TOKEN: ADMIN, KEEPER_ENABLED: '1', KEEPER_KEY: W[7].signer.privateKey, KEEPER_STALL_HOURS: '0.01', KEEPER_EVERY_MIN: '0.25', NODE_ENV: 'development', + HUB_URL: 'http://127.0.0.1:' + HUB_PORT, HUB_SECRET, HUB_SITE: 'bannerline', HUB_ENABLED: '0', HUB_DOWN_MS: '400', NETWORK_LOOKUP_URL: 'http://127.0.0.1:' + IAP_PORT + '/api/network/member' }); + startStandIns(); + const hid = n => 'h_' + String(n).padStart(16, '0'); + const ZW = ethers.Wallet.createRandom().address.toLowerCase(); // a network member with no spot here + HUB.people.push({ id: hid(1), username: 'alpha', wallet: addr[A].toLowerCase(), sponsorId: null }, { id: hid(2), username: 'beta', wallet: addr[B].toLowerCase(), sponsorId: hid(1) }, + { id: hid(3), username: 'zed', wallet: ZW, sponsorId: hid(2) }, { id: hid(4), username: 'zeta', wallet: null, sponsorId: null }); + IAPNET.set('iaponly', addr[Cc].toLowerCase()); IAPNET.set('iapfallback', addr[D].toLowerCase()); const srv = spawn(process.execPath, ['server.js'], { cwd: APP, env, stdio: ['ignore', 'pipe', 'pipe'] }); procs.push(srv); const log = fs.createWriteStream(path.join(OUT, 'server.log')); srv.stdout.pipe(log); srv.stderr.pipe(log); const u = client(); @@ -151,7 +178,7 @@ async function main() { ok(BigInt(my2.paidOutWei) === onChain && onChain > 0n, 'A paid out matches Paid events on chain (' + ethers.formatEther(onChain) + ' POL)', my2.paidOutWei); ok(BigInt(my.paidInWei) === 2n * q, 'A paid in = 2 spots', my.paidInWei); ok(my.directs && my.directs.length === 2 && my.directs.some(x => x.address === addr[B].toLowerCase()), 'A directs = B and E (buyFor sponsor)', my.directs); - ok(my.share.endsWith('?ref=' + addr[A].toLowerCase()), 'share link'); + ok(my.share.endsWith('?ref=alpha'), 'share link uses the network username the hub has for the wallet', my.share); const sid = my.spots[my.spots.length - 1].id; ok((await m.json('/api/my/spot/' + sid, { link: 'http://example.org/' }))._status === 400, 'http link refused'); ok((await m.json('/api/my/spot/' + sid, { link: 'https://192.168.1.1/' }))._status === 400, 'IP link refused'); @@ -172,6 +199,32 @@ async function main() { ok(t && t.img === up.img, 'board shows the uploaded image for that spot'); const go = await v.req('/go/' + sid); ok(go.headers.get('location') === 'https://example.org/landing', 'click relay goes to the member link'); + // ---- 5b. network hub lookups (Marty 2026-11-14: everything through the hub; InstantAdPay only when the hub is unreachable) ---- + console.log('5b. network hub lookups'); + const nb = [1, 2, 3].map(() => ethers.Wallet.createRandom().address.toLowerCase()); + HUB.people.push({ id: hid(11), username: 'newone', wallet: nb[0], sponsorId: hid(1) }, { id: hid(12), username: 'newtwo', wallet: nb[1], sponsorId: hid(3) }, { id: hid(13), username: 'newthree', wallet: nb[2], sponsorId: hid(4) }); + ok((await m.json('/api/my')).username === 'alpha', 'My Spots shows the network username the hub has for the wallet'); + let sp = await u.json('/api/sponsor?ref=alpha'); ok(sp.address === addr[A].toLowerCase() && sp.member, '?ref= resolves through the hub', sp); + sp = await u.json('/api/sponsor?ref=iaponly'); ok(sp.address === null, 'a username only InstantAdPay knows: unknown while the hub answers', sp); + const rv = client(); await rv.req('/?ref=' + addr[Cc]); + sp = await rv.json('/api/sponsor?for=' + nb[0]); ok(sp.address === addr[A].toLowerCase() && sp.via === 'hub', 'buyer the hub knows: the hub network sponsor (resolved to a wallet by hub id) beats the ?ref= cookie', sp); + sp = await rv.json('/api/sponsor?for=' + nb[1]); ok(sp.address === addr[B].toLowerCase() && sp.via === 'hub', 'network sponsor without a spot here: the next one up the network line who has one', sp); + sp = await rv.json('/api/sponsor?for=' + nb[2]); ok(sp.address === null && sp.via === 'hub', 'network sponsor with no wallet and nobody above: no sponsor (never the ?ref= cookie, never the company)', sp); + sp = await rv.json('/api/sponsor?for=' + ethers.Wallet.createRandom().address); ok(sp.address === addr[Cc].toLowerCase() && sp.via === 'ref', 'a wallet the hub does not know: the ?ref= cookie as before', sp); + sp = await rv.json('/api/sponsor?for=' + addr[E]); ok(sp.via === 'ref', 'already a member here: the hub does not pick (the contract keeps the bound sponsor)', sp); + const wc = 'smokewl0001'; ok((await u.json('/api/admin/welcome', { codes: { [wc]: { line: ['nobodyhere', 'zed', 'beta'] } } }, { 'x-admin-token': ADMIN })).ok, 'welcome code saved'); + const wv = client(); await wv.req('/w/' + wc); sp = await wv.json('/api/sponsor'); + ok(sp.address === addr[B].toLowerCase() && sp.via === 'line', '/w/ welcome line: usernames resolved through the hub, first one with a spot here', sp); + ok(HUB.badSig === 0 && HUB.calls > 0, 'every hub call is signed as bannerline with HUB_SECRET', HUB); + HUB.down = true; + sp = await u.json('/api/sponsor?ref=iapfallback'); ok(sp.address === addr[D].toLowerCase(), 'hub unreachable: InstantAdPay answers the username lookup', sp); + const t0 = Date.now(); sp = await rv.json('/api/sponsor?for=' + ethers.Wallet.createRandom().address); ok(sp.via === 'ref' && Date.now() - t0 < 2000, 'hub unreachable: the sponsor pick falls back at once (no wait on the hub)', [sp, Date.now() - t0]); + const ah = await u.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); + HUB.people.push({ id: hid(21), username: 'later', wallet: addr[Cc].toLowerCase(), sponsorId: null }); + sp = await u.json('/api/sponsor?ref=later'); ok(sp.address === addr[Cc].toLowerCase(), 'the hub answers again after it comes back', sp); + // ---- 6. keeper ---- console.log('6. keeper (stall set to 36 s for the test)'); const adm = await u.json('/api/admin/status', undefined, { 'x-admin-token': ADMIN }); diff --git a/server.js b/server.js index d1120ba..4f1e919 100644 --- a/server.js +++ b/server.js @@ -82,17 +82,23 @@ function limited(req, name, max, windowMs) { } // ---- network usernames (Marty 2026-11-13: share links use the member's network username, not the wallet) ---- -// One lookup for both directions. Today the usernames live in InstantAdPay (GET /api/network/member ?u= / ?a=); when the -// network hub goes live this is the one place to point at it. Cached an hour, misses too. +// One lookup for both directions. The network hub answers first (Marty 2026-11-14: "want everything looped through the hub to +// verify membership"; hubpeople.js, cached 5 minutes); InstantAdPay's GET /api/network/member ?u= / ?a= only when the hub is +// unreachable (cached an hour, misses too; a failed call is not cached). A person the hub does not know is unknown here too. +const hubpeople = require('./hubpeople'); const netCache = new Map(); +const fromHub = p => { const a = hubpeople.wallet(p); return a ? { address: a, username: p.username ? String(p.username) : null, hubId: p.id || null, via: 'hub' } : null; }; async function netMember(q) { + const h = q.u ? await hubpeople.byRef(q.u) : await hubpeople.byWallet(q.a); + if (h.ok) return fromHub(h.person); + 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; let m = null; 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) }; } catch (e) { return null; } // a failed call is not cached + if (j && ADDR_RE.test(j.address || '') && j.username) m = { address: j.address.toLowerCase(), username: String(j.username), via: 'iap' }; } catch (e) { return null; } // a failed call is not cached netCache.set(k, { at: Date.now(), m }); if (netCache.size > 20000) netCache.clear(); if (m) netCache.set('a:' + m.address, { at: Date.now(), m }); return m; @@ -101,7 +107,7 @@ async function netMember(q) { // wallet -> network username, set by the admin; wallet-aliases.json is a MySQL document (docstore) const ALIAS_F = () => path.join(C.dataDir, 'wallet-aliases.json'); function aliases() { try { return JSON.parse(fs.readFileSync(ALIAS_F(), 'utf8')); } catch (e) { return {}; } } -const nameOf = async addr => { const al = aliases()[String(addr || '').toLowerCase()]; if (al) return al.username; const m = await netMember({ a: addr }); return m && m.address === addr.toLowerCase() ? m.username : null; }; +const nameOf = async addr => { const al = aliases()[String(addr || '').toLowerCase()]; if (al) return al.username; const m = await netMember({ a: addr }); return m && m.address === String(addr).toLowerCase() ? m.username || null : null; }; // ---- LinkSpin Banner Spins for My Spots (Marty 2026-11-13: pull a Banner Spin in with a couple of clicks) ---- // Signed with NETWORK_SSO_SECRET: X-Net-Ts + X-Net-Sig = hex HMAC-SHA256('net.v1.' + ts + newline + raw body). LinkSpin answers // for the account holding the signed-in wallet only. @@ -159,7 +165,34 @@ async function lineSponsor(req) { } return { address: null, via: 'line' }; } -async function sponsorFor(req) { const l = await lineSponsor(req); if (l) return l.address; return sponsorOf(req); } +// The network sponsor from the hub (Marty 2026-11-14), for a buyer whose wallet the hub knows: their network sponsor, resolved to +// a wallet through the hub by hub id, if that wallet owns a spot here (the contract only binds a sponsor who is already a member); +// else that sponsor's own network sponsor, and so on up the network line (the same nearest-first rule as the /w/ welcome line, at +// most 12 up). Nobody up the line qualifies: no sponsor, never the company, and no ?ref= or welcome code overrides the network. +// undefined = the hub does not decide (unreachable, the wallet or its sponsor unknown, or the buyer is already a member here): +// the welcome line and the ?ref= cookie decide as before. +async function hubSponsor(wallet) { + const a = String(wallet || '').toLowerCase(); if (!ADDR_RE.test(a) || chain.isMember(a)) return undefined; + const me = await hubpeople.byWallet(a); if (!me.ok || !me.person || !me.person.sponsor) return undefined; + let cur = me.person; const seen = new Set([cur.id]); + for (let i = 0; i < 12 && cur.sponsor && cur.sponsor.id && !seen.has(cur.sponsor.id); i++) { + seen.add(cur.sponsor.id); + const s = await hubpeople.sponsorOf(cur); if (!s.ok) return undefined; if (!s.person) break; + const sw = hubpeople.wallet(s.person); + if (sw && sw !== a && chain.isMember(sw)) return { address: sw, username: s.person.username || null, via: 'hub', network: i === 0 }; + cur = s.person; + } + return { address: null, via: 'hub' }; +} +// the sponsor this buyer gets: forWallet = the wallet that will own the spot (the buy page asks just before the buy), else the +// signed-in wallet. Hub network sponsor first, then the personal welcome line, then the ?ref= cookie. +async function sponsorPick(req, forWallet) { + const s = session(req); const w = ADDR_RE.test(forWallet || '') ? forWallet.toLowerCase() : s ? s.address : null; + const h = w ? await hubSponsor(w).catch(() => undefined) : undefined; if (h) return h; + const l = await lineSponsor(req); if (l) return l; + const c = sponsorOf(req); return { address: c, via: c ? 'ref' : null }; +} +async function sponsorFor(req, forWallet) { return (await sponsorPick(req, forWallet)).address; } // ---- sessions (wallet signature sign-in) ---- const challenges = new Map(); @@ -335,8 +368,11 @@ const server = http.createServer(async (req, res) => { return json(res, 200, { totals: t, index: chain.status(), recent, daily: store.daily() }); } if (p === '/api/sponsor' && req.method === 'GET') { - const raw = u.searchParams.get('ref'); const a = raw ? await resolveRef(raw) : await sponsorFor(req); - return json(res, 200, { address: a || null, member: a ? chain.isMember(a) : false }); + const raw = u.searchParams.get('ref'); const fw = u.searchParams.get('for'); + if (fw && limited(req, 'sponsor-for', 120, 3600000)) return json(res, 429, { error: 'Too many requests this hour.' }); + const pick = raw ? { address: await resolveRef(raw), via: 'ref' } : await sponsorPick(req, ADDR_RE.test(fw || '') ? fw : null); + const a = pick.address || null; + return json(res, 200, { address: a, member: a ? chain.isMember(a) : false, via: pick.via || null }); } // board: organic view counting with a one-time token, after 5 s on screen @@ -486,7 +522,7 @@ const server = http.createServer(async (req, res) => { // -- admin (ADMIN_TOKEN header): keeper preview + index status. No key material is ever returned. if (p === '/api/admin/status' && req.method === 'GET') { const tok = process.env.ADMIN_TOKEN; if (!tok || req.headers['x-admin-token'] !== tok) return json(res, 401, { error: 'no' }); - return json(res, 200, { index: chain.status(), totals: chain.totals(), keeper: keeper.statusInfo(), hub: hubreport.view(), refuelSpots: refuelspots.view(), nas: dlbnas.view() }); + return json(res, 200, { index: chain.status(), totals: chain.totals(), keeper: keeper.statusInfo(), hub: hubreport.view(), hubLookup: hubpeople.view(), refuelSpots: refuelspots.view(), nas: dlbnas.view() }); } if (p.startsWith('/api/')) return json(res, 404, { error: 'Not found' });