Files

160 lines
14 KiB
JavaScript

// The holding tank behind The Draft. ONE interface, two implementations:
//
// candidates(now) -> [{ id, username, joinedAt, lastSeen, door, wallet, locked, sponsored, spam, throwaway, adoptions,
// games: { plays, title, earnedWei } | null, surfWei | null }] people waiting for a sponsor
// status(ids, now) -> { id: { lastSeen, username, wallet, payouts, purchase, games, surfWei, adoptions } | null }
// milestones are timestamps (0 = not yet); null = the network cannot say right now
// adopt({ coach, person, kind, note }) -> { ok, ref } | { error } the pick becomes this coach's adoption
// release({ coach, person, why }) -> { ok } | { error } back to the tank (return window ended, or released)
//
// Contact data never crosses this interface: no emails, no phone numbers. Coaches get the RIGHT TO SPONSOR AND HELP; the only
// mail a pick gets is the tank's normal "X is now your sponsor" adoption email, which the tank (InstantAdPay / LinkSpin) sends.
//
// 'stub' (phase 1, TANK_MODE unset): a local fixture (STUB_POOL_FILE, else qa/fixtures/pool.json) with relative times, adoption
// state in the document stub-tank.json. It adopts nobody for real and sends no mail. Admin test routes can move a person's
// milestones (POST /api/admin/stub/status) so the coaching tools, cards and boards can be exercised.
// 'iap' (phase 2, TANK_MODE=iap; 'hub' is read the same): the REAL network holding tank on InstantAdPay, through its signed partner
// routes (InstantAdPay site/draftpartner.js, 2026-11-15). One secret both sides, DRAFT_PARTNER_SECRET (32+ characters), sent as
// X-Draft-Ts (ms) + X-Draft-Sig = hex HMAC-SHA256('draft.v1.' + ts + newline + raw body); IAP_URL is the base.
// POST /api/partner/draft/pool {} -> { ok, rules, pool: [card] }
// POST /api/partner/draft/adopt { rid, coach: { wallet, hubId, username, positions }, person, kind, week, slot } -> { ok, ref } | { error, code }
// POST /api/partner/draft/release { rid, coach: { wallet }, ref, person, why: 'coach' | 'return' } -> { ok, outcome } | { error, code }
// POST /api/partner/draft/status { ids } -> { ok, people: { id: milestones + pick | null } }
// InstantAdPay runs tank.adopt() for every pick (the 2-adoption count, the 24 h grace, rule 3, the normal adoption email, the hub's
// sponsor change) and checks "holds a 5x position" from the coach claim this app signs (positions = store.positionsOf). It owns the
// 3-day window too (its hourly sweep returns unstarted picks); this app's own sweep calls release(why 'return') and takes
// InstantAdPay's outcome (returned / kept / done). A call that fails answers { error } / [] / null: nothing is drafted or moved.
'use strict';
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const H = 3600000, D = 86400000;
let C = null, mode = 'stub', fixture = null, nowFn = () => Date.now();
const FILE = () => path.join(C.dataDir, 'stub-tank.json');
function st() { let s = {}; try { s = JSON.parse(fs.readFileSync(FILE(), 'utf8')); } catch (e) {} s.adopted = s.adopted || {}; s.over = s.over || {}; s.log = s.log || []; s.mails = s.mails || 0; return s; }
function put(s) { s.log = s.log.slice(-300); fs.writeFileSync(FILE() + '.tmp', JSON.stringify(s)); fs.renameSync(FILE() + '.tmp', FILE()); }
function init(cfg, opts) {
C = cfg; mode = cfg.tankMode; if (opts && opts.now) nowFn = opts.now;
if (mode === 'stub') {
const f = cfg.stubPool || path.join(__dirname, 'qa', 'fixtures', 'pool.json');
try { fixture = JSON.parse(fs.readFileSync(f, 'utf8')); } catch (e) { fixture = { people: [] }; console.error('tankpool: no stub pool at', f); }
fixture.base = nowFn(); // relative times are measured from boot
console.log('tankpool: STUB mode (' + fixture.people.length + ' fixture people, nobody is adopted for real, no mail)');
} else console.log('tankpool: InstantAdPay mode (' + C.iapBase + '/api/partner/draft/*' + (secret() ? '' : ', DRAFT_PARTNER_SECRET MISSING: every call refuses') + ')' + (live() ? ' LIVE: picks are real adoptions' : ' TEST MODE (DRAFT_LIVE not 1): pool read-only, picks are previews, nobody is adopted, no mail'));
}
const isStub = () => mode === 'stub';
// ---- staging test mode (Marty 2026-11-15, "test apps never touch real people"): with TANK_MODE=iap and DRAFT_LIVE not '1', the pool
// and pick status are READ from InstantAdPay, but every pick (instant picks on a purchase and the weekly draft) and every release is a
// PREVIEW kept here only: no tank.adopt() on InstantAdPay, no sponsor change, no "X is now your sponsor" email. DRAFT_LIVE=1 at go-live.
const live = () => !isStub() && String(process.env.DRAFT_LIVE || '').trim() === '1';
const preview = () => !isStub() && !live();
const PFILE = () => path.join(C.dataDir, 'preview-picks.json');
function pst() { let s = {}; try { s = JSON.parse(fs.readFileSync(PFILE(), 'utf8')); } catch (e) {} s.picked = s.picked || {}; s.log = s.log || []; s.wouldMail = s.wouldMail || 0; return s; }
function pput(s) { s.log = s.log.slice(-300); fs.writeFileSync(PFILE() + '.tmp', JSON.stringify(s)); fs.renameSync(PFILE() + '.tmp', PFILE()); }
// ---- the InstantAdPay client ----
const secret = () => { const s = String(process.env.DRAFT_PARTNER_SECRET || '').trim(); return s.length >= 32 ? s : ''; };
const remote = { calls: 0, failed: 0, lastError: null, lastPool: 0 };
async function call(op, body, timeoutMs) {
const sec = secret(); if (!sec) return { error: 'The holding tank is not connected (no DRAFT_PARTNER_SECRET).', code: 'no_secret' };
const raw = JSON.stringify(body || {}); const ts = String(Date.now());
const sig = crypto.createHmac('sha256', sec).update('draft.v1.' + ts + '\n' + raw).digest('hex');
remote.calls++;
try {
const r = await fetch(C.iapBase + '/api/partner/draft/' + op, { method: 'POST', body: raw, signal: AbortSignal.timeout(timeoutMs || 15000), headers: { 'Content-Type': 'application/json', 'X-Draft-Ts': ts, 'X-Draft-Sig': sig } });
const j = await r.json().catch(() => null);
if (!j || typeof j !== 'object') throw new Error('InstantAdPay answered ' + r.status + ' with no JSON');
if (r.status >= 500 || r.status === 401 || r.status === 404) throw new Error('InstantAdPay answered ' + r.status + (j.error ? ': ' + j.error : ''));
return j; // 200 { ok ... } or 400 { error, code }
} catch (e) {
remote.failed++; remote.lastError = { at: Date.now(), op, error: String(e.name === 'TimeoutError' ? 'timeout' : e.message).slice(0, 160) };
console.error('tankpool:', op, 'failed:', remote.lastError.error);
return { error: 'The holding tank did not answer.', code: 'unreachable', transient: true };
}
}
const rid = () => 'fx-' + Date.now().toString(36) + '-' + crypto.randomBytes(6).toString('hex');
// a card from InstantAdPay -> the candidate shape draft.js reads (InstantAdPay already left out locked / sponsored / spam / twice)
const candOf = c => ({ id: String(c.id), username: c.username || null, joinedAt: Number(c.joinedAt) || 0, lastSeen: Number(c.lastSeen) || 0, door: c.door || null, wallet: !!c.wallet,
locked: false, sponsored: false, spam: false, throwaway: false, adoptions: Number(c.adoptions) || 0, games: c.games || null, surfWei: c.surfWei || null,
surfCredits: c.surfCredits == null ? null : Number(c.surfCredits) || 0, opensAt: Number(c.opensAt) || 0, ready: !!c.ready, holdUntil: Number(c.holdUntil) || 0 });
const ago = (h, base) => (h == null ? 0 : base - h * H);
// a fixture person at time `now` (relative hours), with any admin override applied
function person(p, s, now) {
const o = s.over[p.id] || {}; const base = fixture.base;
const ts = k => (o[k] !== undefined ? o[k] : p[k + 'HoursAgo'] != null ? ago(p[k + 'HoursAgo'], base) : 0);
return { id: p.id, username: p.username || null, door: p.door || null, joinedAt: ago(p.joinedHoursAgo, base), lastSeen: ts('seen'),
wallet: ts('wallet'), payouts: ts('payouts'), purchase: ts('purchase'), locked: !!p.locked, sponsored: !!p.sponsored || !!(s.adopted[p.id] && s.adopted[p.id].sticky),
spam: !!p.spam, throwaway: !!p.throwaway, adoptions: Number(p.adoptionsElsewhere) || 0,
games: p.games ? { plays: Number(p.games.plays) || 0, title: p.games.title || null, earnedWei: p.games.earnedWei || null } : null, surfWei: p.surfWei || null };
}
async function candidates(now) {
if (!isStub()) { const r = await call('pool', {}); if (!r.ok || !Array.isArray(r.pool)) return []; remote.lastPool = r.pool.length; const taken = preview() ? pst().picked : {}; return r.pool.filter(c => c && c.id && !taken[String(c.id)]).map(candOf); }
const s = st(); now = now || nowFn();
return fixture.people.filter(p => !s.adopted[p.id]).map(p => { const x = person(p, s, now); return Object.assign(x, { wallet: !!x.wallet }); })
.filter(x => !x.payouts && !x.purchase); // payouts on = out of the tank (the IAP rule)
}
async function status(ids, now) {
const out = {};
if (!isStub()) {
for (const id of ids) out[id] = null;
for (let i = 0; i < ids.length; i += 500) {
const r = await call('status', { ids: ids.slice(i, i + 500) }); if (!r.ok || !r.people) continue; // the network cannot say: nothing changes
for (const [id, s] of Object.entries(r.people)) if (s) out[id] = { lastSeen: Number(s.lastSeen) || 0, username: s.username || null, wallet: Number(s.wallet) || 0, payouts: Number(s.payouts) || 0,
purchase: Number(s.purchase) || 0, games: s.games || null, surfWei: s.surfWei || null, surfCredits: s.surfCredits == null ? null : Number(s.surfCredits) || 0, adoptions: Number(s.adoptions) || 0, door: s.door || null, pick: s.pick || null };
}
return out;
}
const s = st(); now = now || nowFn();
for (const id of ids) { const p = fixture.people.find(x => x.id === id); if (!p) { out[id] = null; continue; } const x = person(p, s, now);
out[id] = { lastSeen: x.lastSeen, username: x.username, wallet: x.wallet, payouts: x.payouts, purchase: x.purchase, games: x.games, surfWei: x.surfWei, adoptions: x.adoptions, door: x.door }; }
return out;
}
async function adopt(o) {
if (preview()) {
const s = pst(); const id = String(o.person || ''); if (!id) return { error: 'Not in the holding tank.' };
if (s.picked[id]) return { error: 'Already picked (test mode).' };
const c = o.coach || {}; s.picked[id] = { coach: c.address || null, at: nowFn(), kind: o.kind || 'draft', week: o.week || null };
s.wouldMail++; s.log.push({ at: nowFn(), preview: 'adopt', person: id, coach: c.address || null, kind: o.kind || 'draft' }); pput(s);
return { ok: true, ref: 'preview:' + id, preview: true };
}
if (!isStub()) {
const c = o.coach || {}; const body = { rid: rid(), coach: { wallet: c.address, hubId: c.hubId || null, username: c.username || null, positions: Number(c.positions) || 0 },
person: o.person, kind: o.kind || 'draft', week: o.week || null, slot: o.slot || null, note: o.note || '' };
let r = await call('adopt', body);
if (r.transient) r = await call('adopt', body); // one retry with the SAME rid: InstantAdPay answers the first result, never two adoptions
return r.ok ? { ok: true, ref: r.ref || null, expires: r.expires || null } : { error: r.error || 'The holding tank refused.', code: r.code || null };
}
const s = st(); const p = fixture.people.find(x => x.id === o.person);
if (!p) return { error: 'Not in the holding tank.' };
if (p.locked) return { error: 'Locked on a network contract.' };
if (p.sponsored) return { error: 'Already has a sponsor.' };
if (s.adopted[p.id]) return { error: 'Already adopted.' };
s.adopted[p.id] = { coach: o.coach, at: nowFn(), kind: o.kind || 'draft' }; s.mails++; // phase 2: the tank sends the normal adoption email here
s.log.push({ at: nowFn(), adopt: p.id, coach: o.coach, kind: o.kind }); put(s);
return { ok: true, ref: 'stub:' + p.id };
}
async function release(o) {
if (preview() || String(o.ref || '').startsWith('preview:')) { // a preview pick never touches InstantAdPay, even after DRAFT_LIVE flips to 1
const s = pst(); const id = String(o.person || ''); delete s.picked[id];
s.log.push({ at: nowFn(), preview: 'release', person: id, why: o.why || '' }); pput(s); return { ok: true, outcome: 'returned', preview: true };
}
if (!isStub()) {
const body = { rid: rid(), coach: { wallet: o.coach }, ref: o.ref || null, person: o.person, why: o.kind === 'return' || /window/.test(o.why || '') ? 'return' : 'coach' };
let r = await call('release', body); if (r.transient) r = await call('release', body);
return r.ok ? { ok: true, outcome: r.outcome || 'returned', already: !!r.already } : { error: r.error || 'The holding tank refused.', code: r.code || null };
}
const s = st(); if (!s.adopted[o.person]) return { ok: true };
delete s.adopted[o.person]; s.log.push({ at: nowFn(), release: o.person, why: o.why || '' }); put(s); return { ok: true };
}
// admin test hook (stub only): move a person's milestones, e.g. { id, wallet: true, payouts: true, seen: true }
function setStatus(id, patch) {
if (!isStub()) return { error: 'stub only' };
const s = st(); const o = s.over[id] || (s.over[id] = {}); const t = nowFn();
for (const k of ['wallet', 'payouts', 'purchase', 'seen']) if (patch[k] !== undefined) o[k] = patch[k] ? (typeof patch[k] === 'number' ? patch[k] : t) : 0;
put(s); return { ok: true, over: o };
}
function view() { if (!C) return {}; const s = isStub() ? st() : null; const ps = preview() ? pst() : null; return { mode, live: live(), testMode: preview(), previewPicks: ps ? Object.keys(ps.picked).length : 0, adoptionMailsSkipped: ps ? ps.wouldMail : 0, remote: isStub() ? null : Object.assign({ url: C.iapBase, secret: !!secret() }, remote), fixture: fixture ? fixture.people.length : 0, adopted: s ? Object.keys(s.adopted).length : 0, adoptionMailsThatWouldSend: s ? s.mails : 0, log: s ? s.log.slice(-20) : [] }; }
module.exports = { init, candidates, status, adopt, release, setStatus, view, isStub, live, preview, H, D };