Files
5xyourteam/server.js
T
martbost 8645b471ae The Draft on the real holding tank (2026-11-15, LOCAL ONLY): tankpool.js 'iap' mode = signed client for InstantAdPay's draft partner routes
TANK_MODE=iap (or hub) + IAP_URL + DRAFT_PARTNER_SECRET: pool / adopt / release / status as HMAC-signed POSTs ('draft.v1.' + ts +
newline + body, X-Draft-Ts / X-Draft-Sig). The stub stays the default and keeps every existing test. adopt carries the coach claim
(wallet, hubId, username, positions = store.positionsOf) and a request id; one retry with the same rid on a network failure, so a
retry never makes two adoptions. release sends why 'coach' | 'return' + the pick's iap ref and takes InstantAdPay's outcome
(returned / kept / done). league.sweep follows a pick InstantAdPay closed first (its own 3-day sweep, a release there, a LinkSpin
follow). Surfing arrives as ad credits (surfCredits, shown "N ad credits" to coaches, +10 scouting like surf POL); games stay
"not tracked yet" (InstantAdPay has no per-member game record).

Fix found by the cross test: a tank refusal about the COACH (no InstantAdPay account, full, not vested, hub off) used to mark the
person unavailable and let the same coach choose again, which would burn the whole pool; now the slot passes (skip 'tank: <code>')
and a silent tank pauses the draft (nothing recorded, the next tick retries the same slot). Manual picks record nothing on either.

Tests: unit 62/62 (2 new: skip + wait), smoke 156/156 (ports 3561-3564), qa/iap-tank.test.cjs 23/23 (this client + league against
InstantAdPay's REAL draftpartner.js + tank.js from the sibling checkout behind a signed server on 3565, then a dead port 3566).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 07:18:00 -06:00

465 lines
40 KiB
JavaScript

// 5xYourTeam web app (5xyourteam.com rebuild, "The Draft", Marty approved 2026-11-14). Plain Node http server, no framework (the
// InstantAdPay / Downline Banners / VBB / ViralAdBlitz pattern). Phase 1 = local build: nothing here deploys, posts or adopts for real.
// Product: a $10 one-time position = 5 picks right away + a draft spot every week. Every Monday the coaches draft people waiting in
// the network holding tank, in rounds; the draft order is earned (last week's picks started). Picks are adoptions (tankpool.js):
// coaches get the right to sponsor and help, never contact data. Coaching tools: pick cards with scouting stats, a message composer
// that goes through the site, a "who to help" list, the coach's builder links (the CryptoTeamBuild downline builder, wild.js).
// Pages: / (draft board), /team, /cards, /join, /<username> (coach page), /ledger, /contract, /promote, /terms, /disclaimer,
// /privacy, /admin.
'use strict';
const http = require('http');
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const { verifyMessage, getAddress } = require('ethers');
const cfgMod = require('./config');
const C = cfgMod.get();
fs.mkdirSync(C.dataDir, { recursive: true });
const docstore = require('./docstore'); docstore.install(C.dataDir); // before any module reads data
const store = require('./store');
const draft = require('./draft');
const league = require('./league');
const tank = require('./tankpool');
const networksso = require('./networksso');
const shop = require('./shop');
const promokit = require('./promokit');
const hubreport = require('./hubreport');
const hubpeople = require('./hubpeople');
const hubline = require('./hubline');
const proof = require('./proof');
const netsites = require('./netsites');
const wild = require('./wild');
const PUB = path.join(__dirname, 'public');
const ADDR_RE = /^0x[0-9a-fA-F]{40}$/;
const NAME_RE = /^[A-Za-z0-9_.-]{1,40}$/;
const PAGE_RE = /^\/([A-Za-z0-9_.-]{2,40})\/?$/;
const HUBID_RE = /^h_[0-9a-z]{16}$/;
const BOT_UA = /bot|crawl|spider|slurp|facebookexternalhit|preview|monitor|wget|curl|python|httpclient|scrapy|semrush|ahrefs|headless|lighthouse|pingdom|go-http|java\/|okhttp|axios|node-fetch|phantom|selenium|puppeteer/i;
const now = () => league.clock.now();
const DAY = 86400000;
// ---- http helpers ----
const MIME = { '.html': 'text/html; charset=utf-8', '.css': 'text/css', '.js': 'text/javascript', '.png': 'image/png', '.jpg': 'image/jpeg',
'.gif': 'image/gif', '.svg': 'image/svg+xml', '.ico': 'image/x-icon', '.json': 'application/json', '.txt': 'text/plain; charset=utf-8', '.xml': 'application/xml' };
const CSP = "default-src 'self'; script-src 'self' https://cdn.jsdelivr.net https://linkspin.app; worker-src 'self' blob:; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; "
+ "img-src 'self' data: blob: https:; connect-src 'self' https://linkspin.app https://*.walletconnect.com wss://*.walletconnect.com https://*.walletconnect.org wss://*.walletconnect.org "
+ "https://*.reown.com wss://*.reown.com https://*.reown.org wss://*.reown.org https://*.web3modal.org https://*.drpc.org https://*.publicnode.com https://*.coinbase.com; "
+ "font-src 'self' data: https://fonts.gstatic.com https://fonts.reown.com; form-action 'self'; frame-src https: 'self'";
function headers(extra) { return Object.assign({ 'Content-Security-Policy': CSP, 'X-Content-Type-Options': 'nosniff', 'Referrer-Policy': 'strict-origin-when-cross-origin' }, extra || {}); }
function json(res, code, obj, extra) { res.writeHead(code, headers(Object.assign({ 'Content-Type': 'application/json', 'Cache-Control': 'no-store' }, extra))); res.end(JSON.stringify(obj)); }
function sendFile(res, file, extra, code) {
fs.readFile(file, (err, data) => {
if (err) { res.writeHead(404, headers({ 'Content-Type': 'text/plain' })); return res.end('Not found'); }
const ext = path.extname(file).toLowerCase();
res.writeHead(code || 200, headers(Object.assign({ 'Content-Type': MIME[ext] || 'application/octet-stream', 'Cache-Control': ext === '.html' ? 'no-store, must-revalidate' : 'public, max-age=3600' }, extra)));
res.end(data);
});
}
function readRaw(req, max) {
return new Promise((resolve, reject) => { const ch = []; let n = 0;
req.on('data', c => { n += c.length; if (n > max * 8) { req.destroy(); return; } if (n <= max) ch.push(c); });
req.on('end', () => n > max ? reject(new Error('too big')) : resolve(Buffer.concat(ch))); req.on('error', reject); });
}
async function readBody(req) { const b = await readRaw(req, 32 * 1024); try { return b.length ? JSON.parse(b.toString('utf8')) : {}; } catch (e) { return {}; } }
function cookies(req) { const o = {}; for (const p of (req.headers.cookie || '').split(';')) { const i = p.indexOf('='); if (i > 0) { try { o[p.slice(0, i).trim()] = decodeURIComponent(p.slice(i + 1).trim()); } catch (e) {} } } return o; }
function cookie(name, val, maxAgeSec, httpOnly) { return name + '=' + encodeURIComponent(val) + '; Path=/; SameSite=Lax; Max-Age=' + maxAgeSec + (httpOnly ? '; HttpOnly' : '') + (C.isProd ? '; Secure' : ''); }
function ip(req) {
if (process.env.CF_PROXIED === '1' && req.headers['cf-connecting-ip']) return String(req.headers['cf-connecting-ip']).trim();
const xff = String(req.headers['x-forwarded-for'] || '').split(',').map(s => s.trim()).filter(Boolean);
return (xff.length ? xff[xff.length - 1] : String(req.socket.remoteAddress || '')).replace(/^::ffff:/, '');
}
const isBot = req => !req.headers['user-agent'] || BOT_UA.test(req.headers['user-agent']);
const buckets = new Map();
function limited(req, name, max, windowMs) {
const k = name + ':' + ip(req); const t = Date.now(); let b = buckets.get(k);
if (!b || t - b.t > windowMs) { b = { t, n: 0 }; buckets.set(k, b); }
if (buckets.size > 100000) buckets.clear();
return ++b.n > max;
}
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)); };
function cleanText(s, max) { return String(s == null ? '' : s).replace(/<[^>]{0,200}>/g, '').replace(/[\u0000-\u0008\u000b-\u001f\u007f<>]/g, ' ').replace(/[\u2013\u2014]/g, '-').replace(/[ \t]+/g, ' ').trim().slice(0, max); }
// ---- who is signed in: a wallet; the hub says who they are on the network ----
async function linkHub(addr, email) {
const m = store.member(addr); if (!m) return;
if (m.hubId && m.netAt && Date.now() - m.netAt < 3600000) return;
let h = await hubpeople.byWallet(addr);
if (h.ok && !h.person && email) h = await hubpeople.resolve({ email: String(email).trim().toLowerCase() }).then(r => (r.ok ? { ok: true, person: r.person && !r.person.blocked ? r.person : null } : r));
if (!h.ok) return;
const patch = { netAt: Date.now(), netOk: !!h.person };
if (h.person) { patch.hubId = h.person.id || null; if (h.person.username && NAME_RE.test(h.person.username)) { const o = store.memberByName(h.person.username); if (!o || o.address === m.address) patch.username = String(h.person.username); } }
store.upsertMember(addr, patch);
}
const session = req => store.session(cookies(req)['fx.sid']);
networksso.init({ self: C.siteId, peer: 'iap', peerBase: () => C.iapBase, from: { iap: () => C.iapBase, linkspin: () => C.lsBase },
isProd: C.isProd, dataDir: C.dataDir, defaultPath: '/team',
member: async req => { const s = session(req); return s ? { address: s.address } : null; },
accept: async (email, req, v) => (v && v.wallet ? { ok: true } : { fallback: 'no wallet in the token' }),
signIn: async (email, req, v) => {
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; }
store.upsertMember(v.wallet, patch);
await linkHub(v.wallet, email).catch(() => {}); // the email is used for this one hub lookup and never stored
return cookie('fx.sid', store.mintSession(v.wallet), store.SESSION_TTL / 1000, true);
},
landing: to => to, signinPath: to => to });
// ---- old site links (the YFW downline builder: /?<old>, /splashpg.php?r=, /lcp.php?r=, /index.php?r=) -> the coach page ----
let oldRefs = { at: 0, map: {} };
function oldRefMap() {
if (Date.now() - oldRefs.at < 60000) return oldRefs.map;
let m = {}; try { m = JSON.parse(fs.readFileSync(path.join(C.dataDir, 'oldrefs.json'), 'utf8')) || {}; } catch (e) {}
oldRefs = { at: Date.now(), map: m }; return m;
}
function oldLink(u) {
const p = u.pathname; const bare = u.search.slice(1).split('&')[0];
if (/^\/members(\/|$)/i.test(p)) return '/team';
if (p === '/' || p === '/index.php') { if (!/^[A-Za-z0-9_.-]{2,40}$/.test(bare) && !u.searchParams.get('r')) return p === '/' ? null : '/'; }
else if (!/\.php$/i.test(p)) return null;
const lp = p.toLowerCase();
const old = (lp === '/splashpg.php' || lp === '/lcp.php' || u.searchParams.get('r')) ? String(u.searchParams.get('r') || '') : bare;
const net = /^[A-Za-z0-9_.-]{2,40}$/.test(old) ? oldRefMap()[old.toLowerCase()] : null;
return net ? '/' + encodeURIComponent(net) : '/';
}
const PAGES = { '/': 'index.html', '/team': 'team.html', '/cards': 'cards.html', '/join': 'join.html', '/ledger': 'ledger.html', '/contract': 'contract.html', '/admin': 'admin.html',
'/terms': 'terms.html', '/disclaimer': 'disclaimer.html', '/privacy': 'privacy.html', '/builder': 'builder.html' };
const RESERVED = new Set(['api', 'assets', 'art', 'go', 'r', 'sso', 'health', 'promote', 'sitemap.xml', 'robots.txt', 'favicon.ico', 'index.php', 'team', 'cards', 'join', 'ledger', 'contract', 'admin', 'terms', 'disclaimer', 'privacy', 'builder', 'members', 'draft', 'board']);
const challenges = new Map();
const joinUrl = ref => ref ? C.joinUrl.split('{ref}').join(encodeURIComponent(ref)) : C.joinUrl.replace(/\/join\/\{ref\}.*$/, '/').replace(/[?&]ref=\{ref\}/, '').split('{ref}').join('');
const short = a => a ? a.slice(0, 6) + '...' + a.slice(-4) : '';
const display = a => { const m = store.member(a); return m && m.username ? m.username : short(a); };
const isCoach = a => store.positionsOf(a) > 0;
// ---- payload builders ----
// a scouting card for a person in the pool. Earnings (game POL, surf POL) only for coaches; anyone sees the public facts.
function scoutCard(c, full) {
const out = { id: c.id, username: c.username || null, door: c.door || null, lastSeen: c.lastSeen || 0, joinedAt: c.joinedAt || 0, wallet: !!c.wallet, score: c.score || 0,
hot: (c.score || 0) >= 60, plays: c.games ? Number(c.games.plays) || 0 : null, game: c.games ? c.games.title || null : null };
if (full) { out.gameWei = c.games ? c.games.earnedWei || null : null; out.surfWei = c.surfWei || null; out.surfCredits = c.surfCredits == null ? null : c.surfCredits; }
return out;
}
function pickView(p, t) {
const m = p.m || {};
return { id: p.id, person: p.person, username: p.personName || m.username || null, week: p.week, kind: p.kind, slot: p.slot || null, round: p.round || null, status: p.status,
at: p.at, expires: p.expires, daysLeft: p.status === 'open' ? Math.max(0, Math.ceil((p.expires - t) / DAY)) : null, tier: p.tier || draft.tierOf(m), tierName: draft.TIER_NAME[p.tier || draft.tierOf(m)],
door: p.door || m.door || null, lastSeen: m.lastSeen || 0, steps: draft.steps(m), plays: m.games ? Number(m.games.plays) || 0 : null, game: m.games ? m.games.title || null : null,
gameWei: m.games ? m.games.earnedWei || null : null, surfWei: m.surfWei || null, surfCredits: m.surfCredits == null ? null : m.surfCredits, unread: store.msgsOfPick(p.id).filter(x => x.dir === 'in' && !x.read).length };
}
// a trading card: milestones only, never earnings (public)
function cardView(p) {
const m = p.m || {}; const t = p.tier || draft.tierOf(m);
const line = { rookie: 'Drafted', starter: 'Wallet linked', pro: 'Payouts switched on', allstar: 'First purchase', hof: 'Built a team of their own' }[t];
return { id: p.id, username: p.personName || m.username || null, coach: p.coachName || display(p.coach), round: p.round || null, kind: p.kind, week: p.week, tier: t, tierName: draft.TIER_NAME[t], milestone: line,
plays: m.games ? Number(m.games.plays) || 0 : null, status: p.status };
}
function weekStats(t) {
const w = league.weekInfo(t != null ? t : now());
const P = store.purchases().filter(x => { const at = (x.blockAt ? x.blockAt * 1000 : x.at) || 0; return at >= w.from && at < w.to; });
return { positions: P.reduce((n, x) => n + (Number(x.qty) || 1), 0), coaches: store.coaches().length, started: draft.bestCoach(store.picks(), w.from, w.to).reduce((n, x) => n + x.started, 0), potWei: proof.potOf(w.from, w.to) };
}
async function board(me) {
const t = now(); const w = league.weekInfo(t); const d = store.draft(w.week);
const coach = me && isCoach(me);
const pl = await league.pool(t);
const cur = d ? draft.current(d) : null;
const room = d && d.status === 'live' ? d.slots.slice(d.made.length, d.made.length + 6).map(s => ({ slot: draft.slotLabel(s), coach: display(s.coach), me: s.coach === me })) : [];
const made = d ? d.made.slice(-30).reverse().map(x => { const p = x.pickId ? store.pick(x.pickId) : null; return { slot: x.slot, coach: display(x.coach), person: p ? p.personName : null, tier: p ? p.tier : null, tierName: p ? draft.TIER_NAME[p.tier] : null, auto: !!x.auto, skipped: x.skipped || null, me: x.coach === me }; }) : [];
const best = draft.bestCoach(store.picks(), w.from, w.to, display).slice(0, 10);
const pot = proof.potOf(w.from, w.to);
const rk = draft.rookie(store.picks(), w.week);
const prev = league.weekInfo(t - 7 * DAY);
const lastBest = draft.bestCoach(store.picks(), prev.from, prev.to, display).slice(0, 3);
const out = { week: w.week, now: t, draftAt: w.draftAt, nextDraftAt: w.nextDraftAt, draftDay: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'][C.draft.dow], draftHour: C.draft.hour, rounds: C.draft.rounds,
draft: d ? { status: d.status, coaches: d.order.length, poolSize: d.poolSize, made: d.made.filter(x => x.person).length, slots: d.slots.length,
onClock: cur ? { slot: draft.slotLabel(cur), round: cur.round, n: cur.n, coach: display(cur.coach), me: cur.coach === me, until: d.clockAt + C.draft.pickSeconds * 1000 } : null, room, rows: made, doneAt: d.doneAt || null } : null,
pool: pl.slice(0, 24).map(c => scoutCard(c, coach)), poolSize: pl.length, pot: { wei: pot, week: w.week, split: C.pot.split },
best: best.map(x => ({ rank: x.rank, coach: x.username, started: x.started, me: x.coach === me })), lastWeekBest: lastBest.map(x => ({ rank: x.rank, coach: x.username, started: x.started })),
rookie: rk ? cardView(rk.pick) : null, coaches: store.coaches().length, seconds: C.draft.pickSeconds };
if (me) {
const m = store.member(me);
out.me = { coach, credits: store.credits(me), open: league.openCount(me), maxOpen: C.picks.maxOpen, queue: (m && m.queue) || [], username: m ? m.username : null };
if (coach) { const st = draft.standings(store.coaches().map(x => ({ address: x.address, username: x.username, since: store.firstPositionAt(x.address) })), store.picks(), w.nextWeek, w.week);
out.me.nextSpot = st.findIndex(x => x.address === me) + 1; out.me.startedThisWeek = (best.find(x => x.coach === m.username) || {}).started || 0; }
}
return out;
}
// the person signed in may be someone's pick (their hub id): their coach and the thread
function myCoach(m) {
if (!m || !m.hubId) return null;
const p = store.picksOfPerson(m.hubId).filter(x => ['open', 'done', 'kept'].includes(x.status)).sort((a, b) => b.at - a.at)[0]; if (!p) return null;
return { pickId: p.id, coach: display(p.coach), since: p.at, tier: p.tier, tierName: draft.TIER_NAME[p.tier], steps: draft.steps(p.m),
messages: store.msgsOfPick(p.id).map(x => ({ id: x.id, dir: x.dir === 'out' ? 'in' : 'out', text: x.text, at: x.at })), builder: builderFor(p.coach) };
}
// the CryptoTeamBuild builder: the coach's links (else the owner's, else the program default, else its home page)
const programs = () => (store.state().programs || []);
function builderFor(addr) {
const owner = store.memberByName(C.owner);
const idOf = (person, pid) => store.refidOf(person.address, pid);
const chain = addr ? [{ address: addr, username: display(addr), depth: 1 }] : [];
return wild.visible(programs()).map(p => { const l = wild.sponsorLink(p, chain, idOf, owner ? { address: owner.address, username: owner.username } : null);
return { id: p.id, name: p.name, cat: p.cat, url: l.url, by: l.by, fallback: l.fallback }; });
}
const server = http.createServer(async (req, res) => {
const u = new URL(req.url, 'http://x'); const p = u.pathname;
{ const host = String(req.headers.host || '').toLowerCase().split(':')[0];
if (C.isProd && host !== C.site && host.endsWith('.' + C.site)) { res.writeHead(301, { Location: 'https://' + C.site + req.url, 'Cache-Control': 'no-store' }); return res.end(); } }
try {
if (req.method === 'GET' && (p.startsWith('/sso/') || p === '/api/sso/status') && await networksso.handle(req, res, u)) return;
if ((p === '/api/promo-kit' || p === '/promote') && promokit.handle(req, res, u, sendFile)) return;
if (req.method === 'GET' || req.method === 'HEAD') {
if (p === '/health') return json(res, 200, { ok: true, store: docstore.isOn() ? 'mysql' : 'files', tank: C.tankMode });
{ const to = oldLink(u); if (to) { res.writeHead(301, { Location: to, 'Cache-Control': 'no-store' }); return res.end(); } }
if (PAGES[p]) {
const ex = {}; const ref = u.searchParams.get('ref');
if (ref && (NAME_RE.test(ref) || ADDR_RE.test(ref))) ex['Set-Cookie'] = cookie('fx.ref', ref, 30 * 86400, false);
if (p === '/team' || p === '/admin') ex['X-Frame-Options'] = 'DENY';
return sendFile(res, path.join(PUB, PAGES[p]), ex);
}
if (/^\/r\/[^/]+$/.test(p)) { res.writeHead(302, { Location: '/' + encodeURIComponent(decodeURIComponent(p.slice(3))) }); return res.end(); }
if (p === '/sitemap.xml') {
const day = new Date().toISOString().slice(0, 10);
const urls = ['/', '/join', '/cards', '/ledger', '/contract', '/promote', '/terms', '/disclaimer', '/privacy'].map(x => '<url><loc>https://' + C.site + x + '</loc><lastmod>' + day + '</lastmod></url>').join('');
res.writeHead(200, headers({ 'Content-Type': 'application/xml; charset=utf-8', 'Cache-Control': 'public, max-age=3600' }));
return res.end('<?xml version="1.0" encoding="UTF-8"?><urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' + urls + '</urlset>');
}
if (p === '/robots.txt') { res.writeHead(200, headers({ 'Content-Type': 'text/plain; charset=utf-8' })); return res.end('User-agent: *\nAllow: /\nDisallow: /team\nDisallow: /admin\nDisallow: /api/\nDisallow: /sso/\n\nSitemap: https://' + C.site + '/sitemap.xml\n'); }
if (p.startsWith('/assets/') || p.startsWith('/art/') || p === '/favicon.ico') {
const f = path.normalize(path.join(PUB, p === '/favicon.ico' ? '/art/icon-192.png' : p)); if (!f.startsWith(PUB + path.sep)) { res.writeHead(400); return res.end(); }
return sendFile(res, f);
}
// the Draft Day results card (1080 x 1080, rendered to PNG by tools/art.mjs for Telegram)
const dd = /^\/draftday\/(\d{4}-\d{2}-\d{2})$/.exec(p);
if (dd) return sendFile(res, path.join(PUB, 'draftday.html'));
// a coach page: 5xyourteam.com/<network username>
const pm = PAGE_RE.exec(p);
if (pm && !RESERVED.has(pm[1].toLowerCase()) && !/\.php$/i.test(pm[1])) {
const m = store.memberByName(pm[1]);
if (m) return sendFile(res, path.join(PUB, 'coach.html'), { 'Set-Cookie': cookie('fx.ref', m.username, 30 * 86400, false) });
}
}
// -- public API
if (p === '/api/config' && req.method === 'GET') {
return json(res, 200, { site: C.site, siteName: C.siteName, chainId: C.chainId, chainName: C.chainName, rpc: C.publicRpc, walletConnectProjectId: C.walletConnectProjectId,
position: C.position, split: C.split, draft: { dow: C.draft.dow, hour: C.draft.hour, rounds: C.draft.rounds, pickSeconds: C.draft.pickSeconds }, picks: { returnDays: C.picks.returnDays, maxOpen: C.picks.maxOpen, holdHours: C.picks.holdHours },
pot: C.pot, sso: networksso.enabled(), shop: { live: shop.watching(), contract: shop.watching() ? C.contractAddress : null }, explorer: C.explorer, tank: C.tankMode, joinUrl: joinUrl('') });
}
if (p === '/api/board' && req.method === 'GET') { const s = session(req); return json(res, 200, await board(s ? s.address : null)); }
if (p === '/api/draftday' && req.method === 'GET') {
const wk = String(u.searchParams.get('week') || ''); const d = store.draft(wk); if (!d) return json(res, 404, { error: 'No draft that week.' });
const rows = d.made.filter(x => x.person).map(x => ({ slot: x.slot, coach: display(x.coach), person: (store.pick(x.pickId) || {}).personName || null }));
const w = league.weekInfo(store.ctToMs(wk, 12));
return json(res, 200, { week: wk, rows, players: rows.length, coaches: d.order.length, potWei: proof.potOf(w.from, w.to) });
}
if (p === '/api/coach' && req.method === 'GET') {
const m = store.memberByName(String(u.searchParams.get('u') || '')); if (!m || !isCoach(m.address)) return json(res, 404, { error: 'No coach by that name.' });
const mine = store.picksOf(m.address).filter(x => x.status !== 'void' && x.status !== 'returned');
return json(res, 200, { username: m.username, since: store.firstPositionAt(m.address), positions: store.positionsOf(m.address), team: mine.map(cardView),
started: mine.filter(x => draft.started(x.m)).length, joinUrl: joinUrl(m.username) });
}
if (p === '/api/ledger' && req.method === 'GET') return json(res, 200, proof.ledger(u.searchParams.get('n')), { 'Cache-Control': 'public, max-age=10' });
if (p === '/api/contract' && req.method === 'GET') { if (limited(req, 'contract', 600, 3600000)) return json(res, 429, { error: 'Too many requests' }); return json(res, 200, await proof.contract(), { 'Cache-Control': 'public, max-age=60' }); }
if (p === '/api/network-sites' && req.method === 'GET') return netsites.handle(req, res);
// toasts: real events of the last 30 minutes (new coaches, picks, picks that levelled up)
if (p === '/api/recent' && req.method === 'GET') {
const t = now(); const cut = t - 30 * 60000;
const buys = proof.ledger(10).items.filter(x => x.at && x.at > cut).map(x => ({ kind: 'position', key: 'b' + x.tx + x.orderId, at: x.at, name: x.buyerName }));
const picks = store.picks().filter(x => x.at > cut).slice(-6).map(x => ({ kind: 'pick', key: 'p' + x.id, at: x.at, name: x.coachName, person: x.personName, slot: x.slot || null }));
const ups = store.picks().filter(x => x.levelAt > cut && x.tier && x.tier !== 'rookie').slice(-6).map(x => ({ kind: 'level', key: 'l' + x.id + x.tier, at: x.levelAt, name: x.coachName, person: x.personName, tierName: draft.TIER_NAME[x.tier] }));
return json(res, 200, { items: buys.concat(picks, ups).sort((a, b) => b.at - a.at) }, { 'Cache-Control': 'public, max-age=10' });
}
if (p === '/api/quote' && req.method === 'GET') {
if (!shop.watching()) return json(res, 503, { error: 'Positions are not open yet.' });
if (limited(req, 'quote', 600, 3600000)) return json(res, 429, { error: 'Too many requests this hour.' });
const qty = Number(u.searchParams.get('qty') || 1);
if (!Number.isInteger(qty) || qty < 1 || qty > C.position.maxQty) return json(res, 400, { error: 'Pick 1 to ' + C.position.maxQty + ' positions.' });
try { return json(res, 200, Object.assign({ usd: C.position.usd * qty, picks: C.position.picksOnBuy * qty }, await shop.quote(qty))); } catch (e) { return json(res, 503, { error: 'Price unavailable right now. Try again in a minute.' }); }
}
if (p === '/api/gas' && req.method === 'GET') { try { return json(res, 200, shop.watching() ? await shop.fees() : {}); } catch (e) { return json(res, 200, {}); } }
if (/^\/api\/tx\/0x[0-9a-fA-F]{64}$/.test(p) && req.method === 'GET') {
if (!shop.watching() || limited(req, 'tx', 1200, 3600000)) return json(res, 200, { found: false });
try { return json(res, 200, await shop.receipt(p.slice(8))); } catch (e) { return json(res, 200, { found: false }); }
}
// wallet sign-in
if (p === '/api/auth/challenge' && req.method === 'POST') {
if (limited(req, 'auth', 30, 600000)) return json(res, 429, { error: 'Too many sign-in attempts. Wait a few minutes.' });
const b = await readBody(req); if (!ADDR_RE.test(b.address || '')) return json(res, 400, { error: 'Bad address' });
const a = b.address.toLowerCase(); const nonce = crypto.randomBytes(16).toString('hex');
const message = C.site + ' wants you to sign in with your wallet:\n' + getAddress(a) + '\n\n5xYourTeam sign-in. This signature is free and cannot move funds or approve anything.\n\nChain ID: ' + C.chainId + '\nNonce: ' + nonce + '\nIssued At: ' + new Date().toISOString();
challenges.set(a, { message, exp: Date.now() + 600000 }); if (challenges.size > 20000) challenges.clear();
return json(res, 200, { message });
}
if (p === '/api/auth/verify' && req.method === 'POST') {
const b = await readBody(req); const a = String(b.address || '').toLowerCase(); const ch = challenges.get(a);
if (!ch || ch.exp < Date.now()) return json(res, 400, { error: 'Sign-in request expired. Tap sign in again.' });
let rec; try { rec = verifyMessage(ch.message, String(b.signature || '')).toLowerCase(); } catch (e) { return json(res, 400, { error: 'Invalid signature.' }); }
if (rec !== a) return json(res, 400, { error: 'Your wallet signed with a different account (' + rec.slice(0, 6) + '...' + rec.slice(-4) + '). Switch accounts and try again.' });
challenges.delete(a);
store.upsertMember(a, store.member(a) ? {} : { via: 'wallet' });
await linkHub(a).catch(() => {});
return json(res, 200, { ok: true, address: a }, { 'Set-Cookie': cookie('fx.sid', store.mintSession(a), store.SESSION_TTL / 1000, true) });
}
if (p === '/api/auth/logout' && req.method === 'POST') {
const s = session(req); if (s) store.dropSession(s.token);
return json(res, 200, { ok: true }, { 'Set-Cookie': [cookie('fx.sid', '', 0, true), networksso.offCookie()] });
}
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);
return json(res, 200, { signedIn: true, address: s.address, username: m ? m.username : null, coach: isCoach(s.address), onNetwork: !!(m && m.hubId) });
}
// -- member API
if (p.startsWith('/api/my') || p === '/api/presence' || p === '/api/draft/pick') {
const s = session(req); if (!s) return json(res, 401, { error: 'Sign in first.' });
const me = s.address; if (!store.member(me)) store.upsertMember(me, { via: 'wallet' });
const m = store.member(me);
if (p === '/api/presence' && req.method === 'POST') { m.presenceAt = now(); store.save(); return json(res, 200, { ok: true }); }
if (p === '/api/draft/pick' && req.method === 'POST') {
const b = await readBody(req); if (!HUBID_RE.test(String(b.person || ''))) return json(res, 400, { error: 'Pick a player.' });
m.presenceAt = now(); return json(res, 200, await league.manualPick(me, String(b.person)));
}
if (p === '/api/my' && req.method === 'GET') {
await linkHub(me).catch(() => {});
const t = now(); const mine = store.picksOf(me).filter(x => x.status !== 'void');
const open = mine.filter(x => x.status === 'open');
const w = league.weekInfo(t);
const bd = await board(me);
return json(res, 200, { address: me, username: m.username, onNetwork: !!m.hubId, coach: isCoach(me), positions: store.positionsOf(me), credits: store.credits(me),
stats: { onTeam: mine.filter(x => ['open', 'done', 'kept'].includes(x.status)).length, startedThisWeek: mine.filter(x => { const a = draft.startedAt(x.m); return a >= w.from && a < w.to; }).length,
nextSpot: bd.me && bd.me.nextSpot ? bd.me.nextSpot : null, backSoon: open.filter(x => x.expires - t < DAY).length, open: open.length, maxOpen: C.picks.maxOpen },
picks: mine.sort((a, b) => (a.status === 'open' ? 0 : 1) - (b.status === 'open' ? 0 : 1) || b.at - a.at).map(x => pickView(x, t)), help: draft.helpList(mine, t),
queue: m.queue || [], myCoach: myCoach(m), page: m.username && isCoach(me) ? 'https://' + C.site + '/' + encodeURIComponent(m.username) : null, joinUrl: joinUrl('') });
}
if (p === '/api/my/instant' && req.method === 'POST') {
const b = await readBody(req); if (!HUBID_RE.test(String(b.person || ''))) return json(res, 400, { error: 'Pick a player.' });
if (!isCoach(me)) return json(res, 403, { error: 'Get a position first: it comes with ' + C.position.picksOnBuy + ' picks right away.' });
return json(res, 200, await league.instantPick(me, String(b.person)));
}
if (p === '/api/my/queue' && req.method === 'POST') {
const b = await readBody(req); const ids = (Array.isArray(b.ids) ? b.ids : []).map(String).filter(x => HUBID_RE.test(x)).slice(0, 30);
m.queue = [...new Set(ids)]; store.save(); return json(res, 200, { ok: true, queue: m.queue });
}
if (p === '/api/my/release' && req.method === 'POST') { const b = await readBody(req); return json(res, 200, await league.release(me, Number(b.pick))); }
// messages: a coach writes to their own pick; a pick replies to their coach. Through the site only, no contact data.
if (p === '/api/my/messages' && req.method === 'GET') {
const pk = store.pick(Number(u.searchParams.get('pick'))); if (!pk) return json(res, 404, { error: 'Not found' });
const asCoach = pk.coach === me, asPick = m.hubId && pk.person === m.hubId; if (!asCoach && !asPick) return json(res, 403, { error: 'Not your thread.' });
const list = store.msgsOfPick(pk.id); let changed = false;
for (const x of list) if (!x.read && ((asCoach && x.dir === 'in') || (asPick && x.dir === 'out'))) { x.read = now(); store.saveMsg(x); changed = true; }
return json(res, 200, { pick: pk.id, with: asCoach ? pk.personName : display(pk.coach), items: list.map(x => ({ id: x.id, mine: asCoach ? x.dir === 'out' : x.dir === 'in', text: x.text, at: x.at })), changed });
}
if (p === '/api/my/message' && req.method === 'POST') {
if (limited(req, 'msg', 60, 3600000)) return json(res, 429, { error: 'That is a lot of messages this hour. Give them a little time to answer.' });
const b = await readBody(req); const pk = store.pick(Number(b.pick)); if (!pk) return json(res, 404, { error: 'Not found' });
const asCoach = pk.coach === me, asPick = m.hubId && pk.person === m.hubId; if (!asCoach && !asPick) return json(res, 403, { error: 'You can message your own picks and your own coach.' });
if (!['open', 'done', 'kept'].includes(pk.status)) return json(res, 400, { error: 'They are back in the pool, so this thread is closed.' });
const text = cleanText(b.text, 600); if (text.length < 2) return json(res, 400, { error: 'Write a message first.' });
const x = store.addMsg({ pick: pk.id, dir: asCoach ? 'out' : 'in', from: me, text, at: now(), read: 0, deliveredVia: 'site' });
return json(res, 200, { ok: true, id: x.id });
}
// builder: my referral ID for one CryptoTeamBuild program
if (p === '/api/my/builder' && req.method === 'GET') return json(res, 200, { programs: wild.visible(programs()).map(pr => ({ id: pr.id, name: pr.name, cat: pr.cat, myId: store.refidOf(me, pr.id), example: wild.fillUrl(pr, 'YOURID') })) });
if (p === '/api/my/builder' && req.method === 'POST') {
const b = await readBody(req); const pr = programs().find(x => x.id === String(b.program || ''));
if (!pr || pr.hidden || pr.network) return json(res, 404, { error: 'That program is not in the builder.' });
const id = wild.cleanId(pr, b.refId); if (id === null) return json(res, 400, { error: 'That does not look like a referral ID for ' + pr.name + '.' });
store.setRefid(me, pr.id, id); return json(res, 200, { ok: true, refId: id, link: id ? wild.fillUrl(pr, id) : null });
}
// a position: the buy() call for the member's own wallet, with a fresh line voucher when the line is not bound on chain yet
if (p === '/api/my/order' && req.method === 'POST') {
if (!shop.watching()) return json(res, 503, { error: 'Positions are not open yet.' });
if (limited(req, 'order', 60, 3600000)) return json(res, 429, { error: 'Too many requests this hour.' });
const b = await readBody(req); const qty = Number(b.qty || 1);
if (!Number.isInteger(qty) || qty < 1 || qty > C.position.maxQty) return json(res, 400, { error: 'Pick 1 to ' + C.position.maxQty + ' positions.' });
let v = null, why = null; const bound = await shop.boundSponsor(me);
if (bound) why = 'bound';
else if (bound === undefined) return json(res, 503, { error: 'The chain did not answer just now. Try again in a minute.' });
else if (!shop.voucherOn()) why = 'off';
else {
const lo = await hubline.lineOf({ wallet: me }, shop.MAX_LINE);
if (!lo.ok) return json(res, 503, { error: 'Your sponsor line could not be checked with the network just now. Try again in a minute, so your team gets paid.' });
const wallets = lo.line.filter(x => x.wallet && x.wallet !== me).map(x => x.wallet);
if (!wallets.length) why = 'no-line'; else v = await shop.voucher(me, wallets);
}
const hubRef = m.hubId ? BigInt('0x' + crypto.createHash('sha256').update(m.hubId).digest('hex').slice(0, 15)) : 0n; // ref = a short hash of the hub id (free data)
try { return json(res, 200, Object.assign({ buyer: me, usd: C.position.usd * qty, picks: C.position.picksOnBuy * qty, qty, why }, await shop.order(me, qty, hubRef, v))); }
catch (e) { return json(res, 503, { error: 'Price unavailable right now. Try again in a minute.' }); }
}
if (p === '/api/my/paid' && req.method === 'POST') { shop.nudge(); return json(res, 200, { ok: true, confirmations: C.shopConfirmations }); }
return json(res, 404, { error: 'Not found' });
}
// -- admin (x-admin-token: ADMIN_TOKEN)
if (p.startsWith('/api/admin/')) {
if (!isAdmin(req)) return json(res, 401, { error: 'no' });
if (p === '/api/admin/status' && req.method === 'GET') {
const t = now(); const w = league.weekInfo(t); const d = store.draft(w.week);
return json(res, 200, { day: store.ctDay(t), week: w.week, now: t, draftAt: w.draftAt, config: { position: C.position, split: C.split, draft: C.draft, picks: C.picks, pot: C.pot, tankMode: C.tankMode },
members: store.members().length, coaches: store.coaches().length, picks: { all: store.picks().length, open: store.picks().filter(x => x.status === 'open').length, done: store.picks().filter(x => x.status === 'done').length, returned: store.picks().filter(x => x.status === 'returned').length, kept: store.picks().filter(x => x.status === 'kept').length },
draft: d ? { status: d.status, made: d.made.length, slots: d.slots.length, why: d.why || null } : null, pot: { weekWei: proof.potOf(w.from, w.to), best: draft.bestCoach(store.picks(), w.from, w.to, display).slice(0, 5) },
shop: shop.view(), proof: proof.view(), hub: hubreport.view(), hubLookup: hubpeople.view(), tank: tank.view(), docstore: docstore.view(), oldrefs: Object.keys(oldRefMap()).length, testClock: C.testClock });
}
if (p === '/api/admin/tick' && req.method === 'POST') return json(res, 200, await league.tick());
if (p === '/api/admin/clock' && req.method === 'POST') {
if (!C.testClock) return json(res, 403, { error: 'test clock off' });
const b = await readBody(req); if (!Number.isFinite(Number(b.now))) return json(res, 400, { error: 'now (ms) required' });
league.clock.set(Number(b.now)); return json(res, 200, { ok: true, now: now() });
}
if (p === '/api/admin/stub/status' && req.method === 'POST') { const b = await readBody(req); return json(res, 200, tank.setStatus(String(b.id || ''), b)); }
// the week's Best Coach shares (the pot wallet's holder pays them; Marty decides the rule) and recording a payout tx
if (p === '/api/admin/pot' && req.method === 'GET') {
const wk = String(u.searchParams.get('week') || league.weekInfo(now() - 7 * DAY).week); const w = league.weekInfo(store.ctToMs(wk, 12));
const bd = draft.bestCoach(store.picks(), w.from, w.to, display); const pot = proof.potOf(w.from, w.to);
return json(res, 200, { week: wk, potWei: pot, split: C.pot.split, shares: draft.potShares(pot, C.pot.split, bd), paid: (store.state().payouts || {})[wk] || [] });
}
if (p === '/api/admin/pot/paid' && req.method === 'POST') {
const b = await readBody(req); if (!/^\d{4}-\d{2}-\d{2}$/.test(String(b.week || '')) || !/^0x[0-9a-fA-F]{64}$/.test(String(b.tx || '')) || !ADDR_RE.test(String(b.coach || ''))) return json(res, 400, { error: 'week, coach, tx required' });
const S = store.state(); const l = S.payouts[b.week] || (S.payouts[b.week] = []);
const row = { rank: Number(b.rank) || l.length + 1, coach: String(b.coach).toLowerCase(), username: display(String(b.coach).toLowerCase()), wei: String(BigInt(b.wei || 0)), tx: String(b.tx).toLowerCase(), at: Date.now() };
l.push(row); store.save(); proof.payoutLine(b.week, row).catch(() => {}); return json(res, 200, { ok: true, row });
}
if (p === '/api/admin/oldrefs' && req.method === 'POST') {
let b; try { b = JSON.parse((await readRaw(req, 4 * 1024 * 1024)).toString('utf8')); } catch (e) { return json(res, 400, { error: 'bad json' }); }
if (!b || !b.oldrefs || typeof b.oldrefs !== 'object') return json(res, 400, { error: 'oldrefs object required' });
const o = {}; for (const [k, v] of Object.entries(b.oldrefs)) if (/^[a-z0-9_.-]{2,40}$/.test(k) && NAME_RE.test(String(v))) o[k] = String(v);
fs.writeFileSync(path.join(C.dataDir, 'oldrefs.json'), JSON.stringify(o)); oldRefs = { at: 0, map: {} };
return json(res, 200, { ok: true, total: Object.keys(o).length, skipped: Object.keys(b.oldrefs).length - Object.keys(o).length });
}
return json(res, 404, { error: 'Not found' });
}
if (p.startsWith('/api/')) return json(res, 404, { error: 'Not found' });
res.writeHead(404, headers({ 'Content-Type': 'text/html; charset=utf-8' }));
return res.end('<!doctype html><meta name="viewport" content="width=device-width,initial-scale=1"><title>Not found | 5xYourTeam</title><body style="background:#0b1530;color:#eef2fb;font-family:Inter,system-ui,sans-serif;text-align:center;padding:40px 16px"><p style="font-size:22px;font-weight:700">Not found.</p><p><a style="color:#ffc93c;font-weight:700" href="/">Back to the draft board</a></p></body>');
} catch (e) {
console.error('request', p, e.message);
if (!res.headersSent) json(res, 500, { error: 'Server error' });
}
});
(async () => {
await docstore.init({ splits: store.SPLITS });
process.on('SIGTERM', () => { store.flush(); docstore.drain(8000).finally(() => process.exit(0)); });
store.load();
if (!store.state().programs) { try { store.state().programs = JSON.parse(fs.readFileSync(path.join(__dirname, 'data-seed', 'programs.seed.json'), 'utf8')).programs; store.save(); } catch (e) { store.state().programs = []; } }
tank.init(C, { now });
proof.init(C, { shop, weekStats, nameOf: async a => { const h = await hubpeople.byWallet(a).catch(() => ({ ok: false })); return h.ok && h.person && h.person.username ? h.person.username : null; } });
league.init(C, { proof });
hubreport.init({ dataDir: C.dataDir, purchases: () => store.purchases().map(x => ({ key: x.key, buyer: x.buyer, sponsor: x.sponsor || null, usdCents: x.usdCents, block: x.block, at: x.at })) });
shop.setAttach(rec => { store.addCredits(rec.buyer, C.position.picksOnBuy * (Number(rec.qty) || 1)); store.bump('positions', Number(rec.qty) || 1); });
shop.setHook(proof.onPurchase);
shop.init(C);
const loop = () => league.tick().catch(e => console.error('league tick', e.message)).finally(() => setTimeout(loop, C.draft.tickMs).unref());
setTimeout(loop, 300).unref();
server.listen(C.port, () => console.log('5xYourTeam on :' + C.port + ', position $' + C.position.usd + ', tank ' + C.tankMode + ', store: ' + (docstore.isOn() ? 'MySQL documents' : 'files (prototype mode)')));
})().catch(e => { console.error('start failed:', e.message); process.exit(1); });
process.on('SIGINT', () => { store.flush(); process.exit(0); });