// 5xYourTeam "The Draft" partner routes (draftpartner.js + the tank.adopt partner path, 2026-11-15). // node qa/draft-partner.test.mjs (also part of `bash qa/run.sh member`; `bash qa/run.sh draft` alone) // Part A, no server: the REAL tank.js + draftpartner.js with in-memory accounts, a fake chain, a fake hub and a MOCKED CLOCK. // signature, the pool rules (locked / sponsored / spam / throwaway / adopted twice / grace shown with opensAt / no contact data), // adopt (the 5x claim replaces the $20 rule only here, wallet + contract line, 10 open, fresh lock check, hub off, rid repeat, // the normal adoption email is the only mail), the auto-assign conflict rule (a drafted person is out of the tank; tank.sweep // leaves a pick's adoption alone), release (48 h hold, back with the original join time, two adoptions = kept, started = done, // locked = kept, hub silent = wait), the hourly sweep (wallet alone is not started), reconcile, status, the log. // Part B, LOCAL copy (throwaway DATA_DIR, JSON store, DRAFT_ALLOW_NO_HUB=1): the HTTP routes answer signed calls only. // Never production. Exit code 1 on any failure. import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; import crypto from 'node:crypto'; import { spawn } from 'node:child_process'; import { createRequire } from 'node:module'; const SITE = path.resolve(path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1')), '..'); const require = createRequire(path.join(SITE, 'package.json')); delete process.env.DATABASE_URL; // JSON stores only const SECRET = 'draft-test-secret-' + 'x'.repeat(40); let fails = 0, passes = 0; const ok = (cond, label, extra) => { console.log((cond ? 'PASS ' : 'FAIL ') + label + (cond || extra === undefined ? '' : ' ' + (typeof extra === 'string' ? extra : JSON.stringify(extra)))); if (!cond) fails++; else passes++; }; const H = 3600000, D = 86400000; const addr = () => '0x' + crypto.randomBytes(20).toString('hex'); function fakeAccounts() { const by = new Map(); let nextId = 100; const pub = a => a ? Object.assign({}, a) : null; const find = f => { for (const a of by.values()) if (f(a)) return pub(a); return null; }; return { _by: by, add(email, o) { const a = Object.assign({ email, username: email.split('@')[0].replace(/[^a-z0-9_]/g, ''), code: 'c' + (nextId++), sponsorRef: '', memberId: 0, address: null, created: Date.now() - 30 * D, lastSeen: Date.now() - H, joinedVia: null }, o || {}); by.set(email, a); return pub(a); }, async byEmail(e) { return pub(by.get(String(e || '').toLowerCase())); }, async byUsername(u) { const x = String(u || '').toLowerCase(); return find(a => a.username === x); }, async byCode(c) { const x = String(c || '').toLowerCase(); return find(a => a.code === x); }, async byMemberId(id) { return find(a => Number(a.memberId) === Number(id) && id > 0); }, async byAddress(w) { const x = String(w || '').toLowerCase(); return find(a => a.address && a.address.toLowerCase() === x); }, async positionOwner() { return null; }, async setSponsorRef(e, ref) { const a = by.get(e); if (!a) return { error: 'No such account.' }; a.sponsorRef = String(ref || '').toLowerCase(); return { ok: true }; }, async listAll() { return [...by.values()].map(pub); }, isUnclaimedShell: () => false, async sponsorOf(e) { const a = by.get(e); if (!a || !a.sponsorRef) return null; return (await this.byUsername(a.sponsorRef)) || (await this.byCode(a.sponsorRef)); } }; } function bench(o) { o = o || {}; for (const m of ['tank.js', 'draftpartner.js']) delete require.cache[require.resolve(path.join(SITE, m))]; const tank = require(path.join(SITE, 'tank.js')); const dp = require(path.join(SITE, 'draftpartner.js')); const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'iap-draft-')); const accounts = fakeAccounts(); const events = []; const chats = []; const mails = []; const notices = []; const assigned = []; const deliberate = []; const hub = { locked: new Set(), sponsored: new Set(), down: false, on: true, ids: new Map() }; const flagged = new Set(); const spamList = []; const env = { now: Date.now() }; const follow = { setDeliberate: async (email, token, by, note) => { deliberate.push({ email, token, by, note }); return accounts.setSponsorRef(email, token); } }; const why = e => hub.down ? 'unknown' : hub.locked.has(e) ? 'locked' : hub.sponsored.has(e) ? 'sponsored' : null; tank.init({ dataDir: dir, accounts, chain: { recentEvents: () => events.slice().reverse(), getConfig: () => ({}) }, follow, messages: { sendChat: async (id, from, to, text) => { chats.push({ from, to, text }); }, lastFrom: async () => 0 }, mailer: { hasKey: () => true, send: async (to, subject, body) => { mails.push({ to, subject, body }); } }, site: 'https://iap.test', hooks: { network: () => null, isSuspended: () => false, excluded: e => flagged.has(e), payoutBlocked: async () => false, companyId: () => 1, networkHeld: async accts => new Map(accts.map(a => [a.email, why(a.email)]).filter(x => x[1])), networkLocked: async e => { const w = why(e); return w === 'locked' || w === 'unknown' ? w : null; }, isDraftPick: id => dp.isDraftPick(id), assigned: r => { assigned.push(r); }, adminAlert: () => {}, claim: () => true, activated: () => false, notify: async (to, subject, text) => { notices.push({ to, subject, text }); } } }); tank.setClock(() => env.now); process.env.DRAFT_PARTNER_SECRET = SECRET; const ready = dp.init({ dataDir: dir, accounts, chain: { recentEvents: () => events.slice().reverse() }, tank, ads: { earnedTotals: async em => Object.fromEntries(em.map(e => [e, { earned: e.startsWith('surf') ? 420 : 0, balance: 0 }])) }, requireHub: true, clock: () => env.now, hooks: { hubInfo: e => hub.ids.has(e) ? { id: hub.ids.get(e), door: 'linkspin' } : null, networkOn: () => hub.on, excluded: e => flagged.has(e), spamEmails: () => spamList, suggestDomain: d => require(path.join(SITE, 'emailcheck.js')).suggestDomain(d) } }); let block = 1000; // a coach: a wallet linked here and payouts on (member id), but NO $20 purchase (their vesting is the 5x position) const coach = (email, memberId, extra) => accounts.add(email, Object.assign({ memberId, address: addr() }, extra || {})); const buy = (memberId, cents) => events.push({ type: 'Purchase', buyerId: memberId, priceCents: cents || 2000, block: block++ }); return { tank, dp, ready, accounts, events, chats, mails, notices, assigned, deliberate, hub, flagged, spamList, env, coach, buy, dir }; } const claimOf = (a, positions) => ({ wallet: a.address, username: a.username, positions: positions === undefined ? 1 : positions }); let ridN = 0; const rid = () => 'rid-test-' + (++ridN) + '-' + crypto.randomBytes(3).toString('hex'); async function partA() { console.log('-- Part A: draftpartner.js + tank.js, mocked clock, fake hub'); // ---- signature ---- { const B = bench(); await B.ready; const raw = JSON.stringify({}); const ts = String(Date.now()); const good = B.dp.verify({ 'x-draft-ts': ts, 'x-draft-sig': B.dp.sign(ts, raw) }, raw); ok(good.body && typeof good.body === 'object', 'signature: a good signature passes'); ok(B.dp.verify({ 'x-draft-ts': ts, 'x-draft-sig': B.dp.sign(ts, raw, 'other-secret-' + 'y'.repeat(30)) }, raw).status === 401, 'signature: another secret is refused'); ok(B.dp.verify({ 'x-draft-ts': ts, 'x-draft-sig': B.dp.sign(ts, raw) }, raw + ' ').status === 401, 'signature: a changed body is refused'); const old = String(Date.now() - 6 * 60000); ok(B.dp.verify({ 'x-draft-ts': old, 'x-draft-sig': B.dp.sign(old, raw) }, raw).status === 401, 'signature: older than 5 minutes is refused'); const keep = process.env.DRAFT_PARTNER_SECRET; process.env.DRAFT_PARTNER_SECRET = 'short'; ok(B.dp.verify({ 'x-draft-ts': ts, 'x-draft-sig': 'x' }, raw).status === 503, 'signature: no (or a short) secret = 503, nothing answers'); process.env.DRAFT_PARTNER_SECRET = keep; } // ---- the pool ---- const B = bench(); await B.ready; const { tank, dp, accounts, env, hub } = B; accounts.add('live@x.co', { address: addr(), lastSeen: env.now - 2 * H }); accounts.add('plain@x.co'); accounts.add('surfer@x.co'); accounts.add('locked@x.co'); hub.locked.add('locked@x.co'); accounts.add('sponsoredhub@x.co'); hub.sponsored.add('sponsoredhub@x.co'); accounts.add('flagged@x.co'); B.flagged.add('flagged@x.co'); accounts.add('farm@x.co'); B.spamList.push('farm@x.co'); accounts.add('temp@mailinator.com'); accounts.add('typo@gmial.com'); accounts.add('fresh@x.co', { created: env.now - 2 * H }); accounts.add('kid@x.co', { sponsorRef: 'someone' }); accounts.add('twice@x.co'); hub.ids.set('live@x.co', 'h_0123456789abcdef'); const C1 = B.coach('coach1@x.co', 41); const C2 = B.coach('coach2@x.co', 42); // twice@ has had two adoptions already (an old IAP one and a dropped one) B.buy(43); B.coach('iapadopter@x.co', 43); await tank.adopt('iapadopter@x.co', 'twice@x.co'); await accounts.setSponsorRef('twice@x.co', ''); // back in the tank by hand: 1 counted await tank.adopt('iapadopter@x.co', 'twice@x.co'); await accounts.setSponsorRef('twice@x.co', ''); // 2 counted for (const ad of await tank.openOf('twice@x.co')) await tank.closeAdoption(ad.id, 'dropped'); B.mails.length = 0; B.chats.length = 0; const P = await dp.pool(); const names = P.pool.map(c => c.username).sort(); ok(P.ok && names.join(',') === ['fresh', 'live', 'plain', 'surfer'].join(','), 'pool: only people who pass every rule', names.join(',')); ok(P.excluded.spam === 2 && P.excluded.throwaway === 2 && P.excluded.adoptedTwice === 1, 'pool: spam/flagged, throwaway + mistyped domains and adopted-twice counted out', P.excluded); ok(!names.includes('locked') && !names.includes('sponsoredhub') && !names.includes('kid'), 'pool: nobody locked on a contract, sponsored on the hub or sponsored here'); const live = P.pool.find(c => c.username === 'live'); const fresh = P.pool.find(c => c.username === 'fresh'); const plain = P.pool.find(c => c.username === 'plain'); ok(live.id === 'h_0123456789abcdef' && live.door === 'LinkSpin' && live.wallet === true && live.joinedAt > 0, 'card: hub id + door from the hub cache, wallet linked yes/no, joined', live); ok(/^i_[0-9a-f]{16}$/.test(plain.id) && plain.door === 'InstantAdPay', 'card: someone the hub does not know gets an opaque i_ id'); ok(fresh.opensAt > env.now, 'card: a sign-up inside the 24-hour grace is shown with opensAt'); ok(live.games === null && live.surfWei === null && typeof live.surfCredits === 'number', 'card: games null (not tracked here), surfing as credits, never invented'); const keys = new Set(P.pool.flatMap(c => Object.keys(c))); ok(!JSON.stringify(P).includes('@') && !keys.has('email') && !keys.has('address'), 'pool: no contact data (no email, no wallet address) in the answer'); ok(P.rules.returnHours === 72 && P.rules.holdHours === 48 && P.rules.maxOpen === 10 && P.rules.maxAdoptions === 2 && P.rules.graceHours === 24, 'pool: the rules travel with it', P.rules); // ---- adopt ---- const a0 = await dp.adopt({ rid: rid(), coach: claimOf(C1, 0), person: plain.id, kind: 'draft' }); ok(a0.code === 'not_vested', 'adopt: no 5x position = refused (free members cannot adopt)', a0); const a1 = await dp.adopt({ rid: rid(), coach: { wallet: addr(), positions: 1 }, person: plain.id }); ok(a1.code === 'coach_unknown', 'adopt: a wallet with no account here is refused', a1); const nw = accounts.add('nowallet@x.co', { memberId: 0 }); accounts._by.get('nowallet@x.co').address = null; const nwc = B.coach('freecoach@x.co', 0); const a2 = await dp.adopt({ rid: rid(), coach: claimOf(nwc), person: plain.id }); ok(a2.code === 'no_contract_line', 'adopt: a coach with nobody on this contract in their line is refused (a pick would land under the company)', a2); void nw; hub.on = false; const a3 = await dp.adopt({ rid: rid(), coach: claimOf(C1), person: plain.id }); ok(a3.code === 'hub_off', 'adopt: hub off = nobody can be drafted', a3); ok((await dp.pool()).pool.length === 0, 'pool: hub off = empty pool'); hub.on = true; ok(!(await tank.eligibility('coach1@x.co')).ok, "the coach is NOT eligible for InstantAdPay's own tank button (keeps its $20 rule)"); const r1 = rid(); const g = await dp.adopt({ rid: rid(), coach: claimOf(C1), person: fresh.id }); ok(g.code === 'grace', 'adopt: a sign-up inside the 24-hour grace is refused', g); const ok1 = await dp.adopt({ rid: r1, coach: claimOf(C1), person: live.id, kind: 'draft', week: '2026-11-16', slot: '1.1' }); ok(ok1.ok && /^iap:\d+$/.test(ok1.ref) && ok1.person === live.id && ok1.expires === env.now + 3 * D && ok1.holdUntil === env.now + 48 * H, 'adopt: a 5x coach with payouts on and no $20 buy adopts; 3-day window, 48 h hold', ok1); const la = await accounts.byEmail('live@x.co'); ok(la.sponsorRef === 'coach1', 'adopt: the sponsor is now the coach (InstantAdPay record)', la.sponsorRef); ok(B.deliberate.some(d => d.email === 'live@x.co' && d.by === 'adopt'), "adopt: the move went through the deliberate path (sponsorfollow + the hub's sponsor-change, by 'adopt')"); const open = await tank.openOf('live@x.co'); ok(open.length === 1 && open[0].expires - open[0].ts === 3 * D && /5xYourTeam draft pick/.test(open[0].note), "adopt: the tank adoption's own window is 3 days, noted as a draft pick", open[0]); ok(B.mails.length === 1 && B.mails[0].to === 'live@x.co' && /is now your sponsor on InstantAdPay/.test(B.mails[0].subject), 'mail: exactly one, the normal "X is now your sponsor" adoption email', B.mails.map(m => m.subject)); ok(B.chats.some(c => c.to === 'live@x.co' && /your coach from 5xYourTeam/.test(c.text)), 'adopt: a site chat from the coach (site messages only)'); ok(!tank.payView().some(x => x.email === 'live@x.co'), 'adopt: no switch-on-payouts reminder mails are queued for a pick'); ok(B.assigned.length === 0, 'adopt: no payments-topic pickup post'); const rep = await dp.adopt({ rid: r1, coach: claimOf(C1), person: live.id }); ok(rep.ok && rep.repeat && rep.ref === ok1.ref && B.mails.length === 1, 'adopt: the same rid again answers the first result and sends nothing'); const tw = await dp.adopt({ rid: rid(), coach: claimOf(C2), person: live.id }); ok(tw.code === 'gone', 'adopt: someone already picked is no longer in the pool', tw); // fresh lock check at adopt (the pool cache is 30 s old at most; the adopt asks the hub again) accounts.add('late@x.co'); const lp = (await dp.pool()).pool; dp._poolReset(); const late = (await dp.pool()).pool.find(c => c.username === 'late'); hub.locked.add('late@x.co'); const al = await dp.adopt({ rid: rid(), coach: claimOf(C2), person: late.id }); ok(al.code === 'gone' || al.code === 'locked', 'adopt: locked a moment ago = refused', al); hub.locked.delete('late@x.co'); void lp; hub.down = true; dp._poolReset(); const ad = await dp.adopt({ rid: rid(), coach: claimOf(C2), person: late.id }); ok(ad.error && (ad.code === 'gone' || ad.code === 'hub_unknown'), 'adopt: a hub that does not answer refuses (the conservative side)', ad); hub.down = false; dp._poolReset(); // 10 open picks at most for (let i = 0; i < 10; i++) accounts.add('fill' + i + '@x.co'); const pl = (await dp.pool()).pool; let made = 0; for (const c of pl.filter(c => /^fill/.test(c.username))) { const r = await dp.adopt({ rid: rid(), coach: claimOf(C2), person: c.id }); if (r.ok) made++; } const over = await dp.adopt({ rid: rid(), coach: claimOf(C2), person: plain.id }); ok(made === 10 && over.code === 'full', 'adopt: 10 open picks a coach, the 11th is refused', { made, over }); // ---- auto-assign vs the pick window ---- env.now += 30 * H; // past any 24-hour activation hold const tick = await tank.readyTick(); ok(!tick.assigned.some(x => x.adoptee === 'live@x.co') && (await accounts.byEmail('live@x.co')).sponsorRef === 'coach1', 'conflict rule: a drafted person (wallet linked) is out of the tank, never auto-assigned while the pick runs'); ok(!(await tank.waiting()).some(w => w.email === 'live@x.co'), 'conflict rule: not on the waiting list while picked'); // ---- release ---- const early = await dp.release({ rid: rid(), coach: claimOf(C1), ref: ok1.ref, why: 'coach' }); ok(early.code === 'hold', 'release: not inside the 48-hour hold', early); const notMine = await dp.release({ rid: rid(), coach: claimOf(C2), ref: ok1.ref, why: 'coach' }); ok(notMine.code === 'not_yours', 'release: another coach cannot release it', notMine); const tooEarly = await dp.release({ rid: rid(), coach: claimOf(C1), ref: ok1.ref, why: 'return' }); ok(tooEarly.code === 'too_early', 'return: not before the 3 days', tooEarly); env.now += 20 * H; // 50 h after the pick const rel = await dp.release({ rid: rid(), coach: claimOf(C1), ref: ok1.ref, why: 'coach' }); const back = await accounts.byEmail('live@x.co'); ok(rel.ok && rel.outcome === 'returned' && back.sponsorRef === '', 'release: after 48 h the pick goes back to the tank', rel); ok(B.deliberate.some(d => d.email === 'live@x.co' && d.by === 'release' && /released by the coach/.test(d.note)), "release: the move went through the deliberate path (by 'release')"); dp._poolReset(); const again = (await dp.pool()).pool.find(c => c.id === live.id); ok(again && again.joinedAt === live.joinedAt && !again.opensAt, 'release: back in the pool with the ORIGINAL join time, no new sign-up grace', again); ok(again.adoptionsTotal === 1 && again.adoptions === 0, 'release: the dropped pick still counts toward their two (total 1; 0 outside 5xYourTeam, which counts its own picks)', again); const relAgain = await dp.release({ rid: rid(), coach: claimOf(C1), ref: ok1.ref, why: 'coach' }); ok(relAgain.ok && relAgain.already && relAgain.outcome === 'returned', 'release: a repeat answers "already" and changes nothing'); ok(B.mails.length === 11, 'mail: still only the adoption emails (1 + 10), nothing on release', B.mails.length); // second adoption: C3 picks them again; at 3 days unstarted they stay with C3 (adopted twice) const C3 = B.coach('coach3@x.co', 44); const p2 = await dp.adopt({ rid: rid(), coach: claimOf(C3), person: live.id, kind: 'instant' }); ok(p2.ok, 'second pick of the same person (their 2nd adoption)', p2); env.now += 3 * D + H; const sw = await dp.sweep(); ok(sw.kept === 1 && (await accounts.byEmail('live@x.co')).sponsorRef === 'coach3', 'sweep: at 3 days, a person on their 2nd adoption stays with the coach (kept)', sw); dp._poolReset(); ok(!(await dp.pool()).pool.some(c => c.id === live.id), 'pool: someone adopted twice is never offered again'); // ---- the hourly sweep: wallet alone is not started; started = done; locked = kept; hub silent = wait ---- const C4 = B.coach('coach4@x.co', 45); accounts.add('w1@x.co'); accounts.add('s1@x.co'); accounts.add('k1@x.co'); accounts.add('u1@x.co'); dp._poolReset(); const pool4 = (await dp.pool()).pool; const idOf = u => pool4.find(c => c.username === u).id; const pw = await dp.adopt({ rid: rid(), coach: claimOf(C4), person: idOf('w1') }); const ps = await dp.adopt({ rid: rid(), coach: claimOf(C4), person: idOf('s1') }); const pk = await dp.adopt({ rid: rid(), coach: claimOf(C4), person: idOf('k1') }); const pu = await dp.adopt({ rid: rid(), coach: claimOf(C4), person: idOf('u1') }); ok(pw.ok && ps.ok && pk.ok && pu.ok, 'four more picks for the sweep checks'); accounts._by.get('w1@x.co').address = addr(); // linked a wallet only accounts._by.get('s1@x.co').address = addr(); accounts._by.get('s1@x.co').memberId = 77; B.buy(77, 1000); // switched on payouts + bought // tank.sweep (the IAP 7-day sweep) leaves a pick's expired adoption alone env.now += 3 * D + H; hub.locked.add('k1@x.co'); const st0 = await dp.status({ ids: [idOf('s1'), idOf('w1'), 'h_ffffffffffffffff'] }); ok(st0.people['h_ffffffffffffffff'] === null, 'status: someone 5xYourTeam holds no pick for answers null'); ok(st0.people[idOf('s1')].payouts > 0 && st0.people[idOf('s1')].purchase > 0 && st0.people[idOf('w1')].wallet > 0 && !st0.people[idOf('w1')].payouts, 'status: milestones (wallet / payouts / purchase as first-seen times)', st0.people[idOf('w1')]); ok(!JSON.stringify(st0).includes('@'), 'status: no contact data'); hub.down = true; const swU = await dp.sweep(); ok(swU.waiting >= 1 && swU.done === 1 && (await accounts.byEmail('u1@x.co')).sponsorRef === 'coach4', 'sweep: hub not answering = the return waits, nobody moved', swU); hub.down = false; const sw2 = await dp.sweep(); ok(sw2.returned === 2 && sw2.kept === 1, 'sweep: started = done (even with the hub silent), wallet-only + plain = returned, locked = kept', sw2); ok((await accounts.byEmail('w1@x.co')).sponsorRef === '' && (await accounts.byEmail('s1@x.co')).sponsorRef === 'coach4' && (await accounts.byEmail('k1@x.co')).sponsorRef === 'coach4', 'sweep: sponsors after the 3 days (wallet-only back to the tank; started and locked stay)'); const tsw = await tank.sweep(); ok(tsw.back === 0, 'tank.sweep: never touches a pick (the pick rule decides, not the 7-day wallet rule)', tsw); // a pick whose tank adoption was closed some other way (released on InstantAdPay itself, a LinkSpin follow) reconciles accounts.add('m1@x.co'); dp._poolReset(); const pm = (await dp.pool()).pool.find(c => c.username === 'm1'); const pmk = await dp.adopt({ rid: rid(), coach: claimOf(C4), person: pm.id }); for (const a of await tank.openOf('m1@x.co')) await tank.closeAdoption(a.id, 'moved'); const stm = await dp.status({ ids: [pm.id] }); ok(pmk.ok && stm.people[pm.id].pick.status === 'moved', 'reconcile: a pick closed on InstantAdPay shows as moved', stm.people[pm.id].pick); // the log: every call with a reason const av = await dp.adminView(); ok(av.log.length > 20 && av.log.every(l => l.op && l.ts && (l.ok || l.code)) && av.log.some(l => l.op === 'adopt' && !l.ok && l.code === 'not_vested') && av.log.some(l => l.op === 'sweep' && l.code === 'kept'), 'log: every call is logged with an outcome code / reason', av.log.slice(0, 3)); ok(!JSON.stringify(av.picks).includes('@'), 'admin view: picks carry no emails'); } // ---------------- Part B: the routes on a local copy ---------------- async function partB() { console.log('-- Part B: HTTP routes on a local copy'); const port = Number(process.env.DRAFT_E2E_PORT || 8825); const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'iap-draft-b-')); const env = Object.assign({}, process.env, { PORT: String(port), DATA_DIR: dir, ADMIN_EMAIL: 'admin@iap.test', ADMIN_PASSWORD: 'localtest', DRAFT_PARTNER_SECRET: SECRET, DRAFT_ALLOW_NO_HUB: '1', LS_URL: 'http://127.0.0.1:9', HUB_ENABLED: '' }); delete env.DATABASE_URL; delete env.NODE_ENV; const child = spawn(process.execPath, ['server.js'], { cwd: SITE, env, stdio: ['ignore', 'pipe', 'pipe'] }); let log = ''; child.stdout.on('data', d => { log += d; }); child.stderr.on('data', d => { log += d; }); const base = 'http://127.0.0.1:' + port; try { let up = false; for (let i = 0; i < 40 && !up; i++) { try { up = (await fetch(base + '/api/config')).ok; } catch (e) {} if (!up) await new Promise(r => setTimeout(r, 500)); } ok(up, 'local copy up on :' + port, up ? undefined : log.slice(-600)); if (!up) return; const call = async (op, body, opts) => { const raw = JSON.stringify(body || {}); const ts = String(Date.now()); const sig = (opts && opts.sig) || crypto.createHmac('sha256', SECRET).update('draft.v1.' + ts + '\n' + raw).digest('hex'); const r = await fetch(base + '/api/partner/draft/' + op, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Draft-Ts': ts, 'X-Draft-Sig': sig }, body: raw }); return { status: r.status, body: await r.json().catch(() => null) }; }; const p = await call('pool', {}); ok(p.status === 200 && p.body.ok && Array.isArray(p.body.pool) && p.body.rules.maxOpen === 10, 'POST /api/partner/draft/pool signed: 200 with rules + pool', p); ok((await call('pool', {}, { sig: 'f'.repeat(64) })).status === 401, 'unsigned / wrong signature: 401'); ok((await call('nope', {})).status === 404, 'unknown op: 404'); const a = await call('adopt', { rid: 'rid-route-0001', coach: { wallet: addr(), positions: 1 }, person: 'h_0000000000000000' }); ok(a.status === 400 && a.body.code === 'coach_unknown', 'adopt for an unknown coach: 400 with a code', a.body); const s = await call('status', { ids: ['h_0000000000000000'] }); ok(s.status === 200 && s.body.people['h_0000000000000000'] === null, 'status: 200, unknown person null'); ok((await fetch(base + '/api/admin/draft')).status === 401, 'GET /api/admin/draft needs the admin'); } finally { child.kill(); } } await partA(); if (!process.env.DRAFT_SKIP_B) await partB(); console.log(fails ? 'FAILED ' + fails + ' (passed ' + passes + ')' : 'ALL PASSED (' + passes + ')'); process.exit(fails ? 1 : 0);