// The Network Tour (Marty 2026-11-17): mission rotation per hunter and the free tier's tour stops, end to end on a local // boot with GAMEPASS=on against a stub InstantAdPay (player, polgrant, credits). Production is never contacted. // Covers: round progression and reset, a mission added mid-round, a paused mission, never-visited first then least // recently found, the start gate, the Full Network Tour badge once per round, discovery pays POL for a free member, // a repeat after the full tour is a tour stop (credits, no POL), a new mission pays POL once, Game Pass holders // unchanged, tour-stop credits capped per day and idempotent on ref, daily limits unchanged. // Run: node test/rotation.js 'use strict'; const { spawn } = require('child_process'); const http = require('http'), crypto = require('crypto'), path = require('path'), fs = require('fs'); const PORT = 8897, DIR = path.join(__dirname, '..', 'data-test-rot'), SECRET = 'r'.repeat(48); fs.rmSync(DIR, { recursive: true, force: true }); let fails = 0; const eq = (a, b, m) => { const ok = JSON.stringify(a) === JSON.stringify(b); console.log((ok ? ' ok ' : ' FAIL ') + m + (ok ? '' : ' -> got ' + JSON.stringify(a) + ' want ' + JSON.stringify(b))); if (!ok) fails++; }; const sleep = ms => new Promise(r => setTimeout(r, ms)); const B = 'http://127.0.0.1:' + PORT, ORG = { Origin: 'http://127.0.0.1:' + PORT }; const DAY = 86400000, ctDay = t => new Date(t).toLocaleDateString('en-CA', { timeZone: 'America/Chicago' }); // ---- the stub InstantAdPay: pass flags per member, polgrant answers allowed = pol, credits once per ref const PASS = { 102: true }; const creditCalls = []; const granted = new Map(); const stub = http.createServer((req, res) => { let raw = ''; req.on('data', c => raw += c); req.on('end', () => { const u = new URL(req.url, 'http://x'); const send = (c, o) => { res.writeHead(c, { 'Content-Type': 'application/json' }); res.end(JSON.stringify(o)); }; if (req.method === 'GET') { const m = Number(u.searchParams.get('m')); return send(200, { ok: true, memberId: m, pass: { active: !!PASS[m], until: PASS[m] ? Date.now() + 7 * DAY : null } }); } const sig = crypto.createHmac('sha256', SECRET).update(req.headers['x-game-ts'] + '\n' + raw).digest('hex'); if (sig !== req.headers['x-game-sig']) return send(401, { error: 'bad signature' }); const b = JSON.parse(raw); if (u.pathname === '/api/partner/credits') { creditCalls.push(b); if (granted.has(b.ref)) return send(200, { ok: true, repeat: true, credits: granted.get(b.ref) }); granted.set(b.ref, b.credits); return send(200, { ok: true, credits: b.credits }); } if (u.pathname === '/api/partner/polgrant') return send(200, { allowed: b.pol, deferred: 0, carried: 0, pass: !!PASS[b.memberId], day: ctDay(Date.now()) }); send(404, { error: 'no' }); }); }); let child; const jars = {}; const call = async (who, p, opt = {}) => { const res = await fetch(B + p, Object.assign({ redirect: 'manual' }, opt, { headers: Object.assign({ Cookie: jars[who] || '', 'Content-Type': 'application/json' }, opt.headers || {}) })); const sc = res.headers.get('set-cookie'); if (sc && /ph\.sid=/.test(sc)) jars[who] = sc.split(';')[0]; let body = null; try { body = await res.json(); } catch (e) {} return { status: res.status, body }; }; const admin = (p, body) => call('admin', p, { method: body ? 'POST' : 'GET', body: body ? JSON.stringify(body) : undefined, headers: { 'X-Admin-Key': 'adminkey123' } }); const mission = (id, extra) => admin('/api/admin/mission', Object.assign({ id, site: 'Site ' + id.toUpperCase(), name: 'Find ' + id, brief: 'x', url: B + '/index.html', dwell: 5, slots: 1 }, extra || {})); const PF = path.join(DIR, 'payouts.json'); const readP = () => { try { return JSON.parse(fs.readFileSync(PF, 'utf8')); } catch (e) { return []; } }; const writeP = all => fs.writeFileSync(PF, JSON.stringify(all)); // a past find, written straight onto the ledger (history the hunter already has) const past = (memberId, missionId, daysAgo, wallet) => { const all = readP(); const at = Date.now() - daysAgo * DAY; all.push({ id: 'h' + memberId + missionId + daysAgo, memberId, wallet, missionId, site: 'Site ' + missionId.toUpperCase(), pol: 0.05, day: ctDay(at), at, status: 'paid' }); writeP(all); }; // move a member's finds of a mission to yesterday (so the once-a-day rule does not hide what the rotation does) const toYesterday = (memberId, missionId) => { const all = readP(); for (const p of all) if (p.memberId === memberId && p.missionId === missionId) p.day = ctDay(Date.now() - DAY); writeP(all); }; // a real find: start, wait the dwell, read the code from the embed, submit async function find(who, missionId) { const st = await call(who, '/api/my/start', { method: 'POST', body: JSON.stringify({ missionId }) }); if (st.status !== 200) return st; await sleep(5300); const code = await (await fetch(B + '/api/embed/code?t=' + st.body.token, { headers: ORG })).json(); return call(who, '/api/my/submit', { method: 'POST', body: JSON.stringify({ token: st.body.token, code: code.code }) }); } const signIn = (who, memberId, pass) => call(who, '/auth?t=' + sso.mint({ memberId, email: 'h' + memberId + '@example.com', wallet: '0x' + String(memberId).padStart(40, '0'), username: 'hunter' + memberId, gamePass: { active: !!pass, until: pass ? Date.now() + 7 * DAY : null } })); let sso; (async () => { await new Promise(r => stub.listen(0, '127.0.0.1', r)); const env = Object.assign({}, process.env, { PORT: String(PORT), DATA_DIR: DIR, HUNT_SSO_SECRET: SECRET, ADMIN_KEY: 'adminkey123', SIGNUPS: 'open', SITE_URL: B, GAMEPASS: 'on', IAP_URL: 'http://127.0.0.1:' + stub.address().port }); delete env.CURTAIN; delete env.OUTBOUND; delete env.HUNT_WALLET_KEY; delete env.HUNT_RPC; child = spawn(process.execPath, [path.join(__dirname, '..', 'server.js')], { env, stdio: ['ignore', 'pipe', 'pipe'] }); child.stderr.on('data', d => process.stderr.write(d)); for (let i = 0; i < 120; i++) { try { await fetch(B + '/health'); break; } catch (e) { await sleep(500); } } process.env.HUNT_SSO_SECRET = SECRET; sso = require('../lib/sso'); for (const id of ['a', 'b', 'c']) await mission(id); await signIn('free', 101, false); await signIn('pass', 102, true); // ---- limits unchanged: the free tier is 1 a day, the Game Pass 3 + 2 = 5, rotation on by default let bf = await call('free', '/api/my/board'), bp = await call('pass', '/api/my/board'); eq([bf.body.daily.limit, bp.body.daily.limit, bf.body.tour.on, bf.body.tour.total, bf.body.tour.done, bf.body.tour.round], [1, 5, true, 3, 0, 1], 'limits unchanged (free 1, Pass 5); rotation on; tour 0 of 3, round 1'); eq(bf.body.tour.left.slice().sort(), ['Site A', 'Site B', 'Site C'], 'the board lists the sites left this round by name'); await admin('/api/admin/settings', { freeMissionsPerDay: 10 }); // room for several finds in one test day (restored below) // ---- discovery pays POL for a free member let r = await find('free', 'a'); eq([r.status, r.body.pol >= 0.02 && r.body.pol <= 0.1, !!r.body.tourStop], [200, true, false], 'free member, first find of a mission: POL on the free draw, not a tour stop'); bf = await call('free', '/api/my/board'); eq([bf.body.tour.done, bf.body.tour.left.includes('Site A'), bf.body.missions.find(m => m.id === 'a').done], [1, false, true], 'round progress: 1 of 3, Site A off the list, shown as done today'); // ---- the start gate: found earlier in this round = refused, even on a new day toYesterday(101, 'a'); r = await call('free', '/api/my/start', { method: 'POST', body: JSON.stringify({ missionId: 'a' }) }); eq([r.status, r.body.tour], [400, true], 'a mission found earlier this round cannot be started again (rotation)'); bf = await call('free', '/api/my/board'); eq(bf.body.missions.map(m => m.id).includes('a'), false, 'and the board does not offer it'); // ---- a paused mission is skipped and never blocks the round; finishing the rest closes it const ms = (await admin('/api/admin/state')).body.missions; const mc = ms.find(m => m.id === 'c'); await mission('c', { active: false, dwell: mc.dwell, slots: mc.slots }); bf = await call('free', '/api/my/board'); eq([bf.body.tour.total, bf.body.tour.left], [2, ['Site B']], 'paused mission c is out of the round: 1 of 2, only Site B left'); r = await find('free', 'b'); eq([r.status, r.body.round, r.body.unlocked.includes('sweep')], [200, 1, true], 'finishing the round: round 1 closed, Full Network Tour celebrated'); bf = await call('free', '/api/my/board'); eq([bf.body.tour.round, bf.body.tour.rounds, bf.body.tour.done, bf.body.badges.some(b => b.id === 'sweep' && b.name === 'Full Network Tour')], [2, 1, 0, true], 'reset: round 2 starts at 0, the badge reads Full Network Tour'); // ---- a mission added (or back) mid-round joins as not done, never-visited first await mission('c', { active: true }); bf = await call('free', '/api/my/board'); eq([bf.body.tour.total, bf.body.missions[0].id, bf.body.missions[0].fresh], [3, 'c', true], 'mission c back mid-round: part of round 2, offered first as never visited'); eq(bf.body.tour.toured, false, 'not toured yet: c was never found'); r = await find('free', 'c'); eq([r.status, r.body.pol > 0, !!r.body.tourStop], [200, true, false], 'a mission new to this free member pays POL on the first find'); bf = await call('free', '/api/my/board'); eq([bf.body.tour.toured, bf.body.tour.free, bf.body.missions.filter(m => !m.done).every(m => m.tourStop && m.tourStop.credits === 10)], [true, true, true], 'every active mission found once: toured; the open cards read as tour stops worth 10 credits'); // ---- after the full tour a free member's repeat is a tour stop: credits, not POL; capped at the daily max toYesterday(101, 'b'); const before = creditCalls.length; r = await find('free', 'a'); eq([r.status, r.body.pol, r.body.tourStop && r.body.tourStop.credits, /Tour stop/.test(r.body.message)], [200, 0, 10, true], 'repeat after the full tour: a tour stop, 0 POL, +10 ad credits'); await sleep(400); const stopRow = readP().find(p => p.memberId === 101 && p.tourStop); eq([creditCalls.length - before, creditCalls.at(-1) && creditCalls.at(-1).credits, creditCalls.at(-1) && creditCalls.at(-1).ref, stopRow.status, stopRow.pol, stopRow.tourStop.state], [1, 10, 'tour:' + stopRow.id, 'tour', 0, 'sent'], 'one signed credits call, ref tour:, row is a 0 POL tour stop marked sent'); eq(readP().filter(p => p.memberId === 101 && p.missionId === 'a').map(p => p.status), ['due', 'tour'], 'mission a: the discovery drip (due) and the tour stop, no second POL drip'); r = await find('free', 'b'); eq([r.status, r.body.pol, r.body.tourStop.credits, r.body.round], [200, 0, 0, 2], 'second tour stop the same day: credits capped at the daily max (0 more), and it closes round 2'); await sleep(300); eq(creditCalls.length - before, 1, 'no credits call for a capped stop'); // idempotent on ref: a stop sent again (a retry) is answered as a repeat and never granted twice { process.env.GAMEPASS = 'on'; const store = require('../lib/store'); store.init(DIR); const gp = require('../lib/polgrant'); const rot = require('../lib/rotation'); gp.use({ game: 'polhunter', secret: SECRET, iap: 'http://127.0.0.1:' + stub.address().port, store }); rot.markStop(stopRow.id, { state: 'due' }); const again = await rot.deliver(readP().find(p => p.id === stopRow.id), gp); eq([again.tourStop.state, granted.get('tour:' + stopRow.id), [...granted.values()].reduce((a, b) => a + b, 0)], ['sent', 10, 10], 'a retried stop reuses its ref: 10 credits granted once in total'); const capped = rot.tourStop({ memberId: 101, email: 'h101@example.com', wallet: '0x' + '101'.padStart(40, '0') }, { id: 'zz', site: 'Z' }); eq([capped.tourStop.credits, capped.tourStop.state], [0, 'none'], 'the daily max holds at the library too (10 already granted today)'); } // ---- a newly added mission pays POL again to a toured free member, once await mission('d'); bf = await call('free', '/api/my/board'); eq([bf.body.tour.toured, bf.body.missions[0].id], [false, 'd'], 'new mission d: no longer toured, d offered first'); r = await find('free', 'd'); eq([r.status, r.body.pol > 0, !!r.body.tourStop], [200, true, false], 'the new mission pays POL on the first find'); // ---- never visited first, then least recently found (member 103, history only) past(103, 'a', 4, '0x' + '103'.padStart(40, '0')); past(103, 'b', 3, '0x' + '103'.padStart(40, '0')); past(103, 'c', 2, '0x' + '103'.padStart(40, '0')); past(103, 'd', 5, '0x' + '103'.padStart(40, '0')); await signIn('h103', 103, true); await call('h103', '/api/my/board'); await mission('e'); const b3 = await call('h103', '/api/my/board'); eq([b3.body.tour.rounds, b3.body.missions.map(m => m.id)], [1, ['e', 'd', 'a', 'b', 'c']], 'a whole history closes round 1; round 2 order: never visited (e), then least recently found (d, a, b, c)'); // ---- Game Pass holders unchanged: a repeat pays POL on the full draw past(102, 'a', 3, '0x' + '102'.padStart(40, '0')); past(102, 'b', 3, '0x' + '102'.padStart(40, '0')); past(102, 'c', 3, '0x' + '102'.padStart(40, '0')); past(102, 'd', 3, '0x' + '102'.padStart(40, '0')); past(102, 'e', 3, '0x' + '102'.padStart(40, '0')); r = await find('pass', 'a'); eq([r.status, r.body.pol >= 0.05 && r.body.pol <= 1, !!r.body.tourStop], [200, true, false], 'Game Pass holder repeat: POL on the full draw, never a tour stop'); // ---- rotation off: everything is offered again (the old board), the badge stays toYesterday(101, 'd'); const on1 = await call('free', '/api/my/board'); await admin('/api/admin/settings', { rotationOn: 0 }); bf = await call('free', '/api/my/board'); eq([on1.body.missions.some(m => m.id === 'd'), bf.body.tour.on, bf.body.missions.some(m => m.id === 'd' && !m.done)], [false, true && false, true], 'rotationOn 0: no progress panel, a mission found this round is offered again'); await admin('/api/admin/settings', { rotationOn: 1, freeMissionsPerDay: 1 }); bf = await call('free', '/api/my/board'); eq(bf.body.daily.limit, 1, 'free tier back to 1 a day'); // ---- admin: round stats per hunter const av = await admin('/api/admin/rotation'); const h101 = av.body.hunters.find(h => h.memberId === 101); eq([av.status, h101.rounds, av.body.settings.credits, av.body.settings.dailyMax, av.body.tourStops.creditsSent], [200, 2, 10, 10, 10], 'admin: rounds per hunter, settings 10 / 10, 10 credits sent'); console.log(fails ? '\nFAILURES: ' + fails : '\nALL ROTATION CHECKS PASS'); child.kill(); stub.close(); fs.rmSync(DIR, { recursive: true, force: true }); process.exit(fails ? 1 : 0); })().catch(e => { console.error('CRASH', e); if (child) child.kill(); process.exit(1); });