// Game Pass checks for PolHunter (docs/GAME-PASS.md 3a), all local: a stub InstantAdPay on 127.0.0.1 answers polgrant and the // tournament endpoints; a mocked faucet records sends. Covers the grant client (fail closed, the retry queue, the 48 h alert), // finds and Ad Detective cases as 'daily' rewards (dropped at the cap, paid missions not gated, 'gp-wait' rows settled by the // queue), the perks (5 missions a day, a second case) and the Pass Tournament payer (pending -> paid, duplicate ignored, restart // re-report, send failure leaves the row pending and alerts, dry run, low balance). Production is never contacted. // Run: node test/gamepass.js 'use strict'; const http = require('http'), crypto = require('crypto'), fs = require('fs'), os = require('os'), path = require('path'); process.env.GAMEPASS = 'on'; process.env.HUNT_SSO_SECRET = 'x'.repeat(48); delete process.env.HUNT_DRY_RUN; const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'ph-gp-')); const store = require('../lib/store'); store.init(dir); const gp = require('../lib/polgrant'), rewards = require('../lib/rewards'), detective = require('../lib/detective'), tournament = require('../lib/tournament'), missions = require('../lib/missions'); const SECRET = 'test-secret-'.padEnd(40, 'x'), GAME = 'polhunter'; let pass = 0, fail = 0; const ok = (name, cond, info) => { if (cond) { pass++; console.log(' ok ', name); } else { fail++; console.log(' FAIL', name, info === undefined ? '' : JSON.stringify(info)); } }; (async () => { // ---- the stub IAP: polgrant (scripted by ref), tournament pending (a list we control) and paid (records the acks) const seen = [], acks = []; let mode = 'ok', pendingRows = []; const script = {}; 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'); if (req.method === 'GET') { // the signed GET forms: player and tournament/pending const who = u.pathname.endsWith('/tournament/pending') ? 'tournament' : (Number(u.searchParams.get('m')) > 0 ? u.searchParams.get('m') : u.searchParams.get('e')); const want = crypto.createHmac('sha256', SECRET).update('player:' + who + ':' + u.searchParams.get('ts')).digest('hex'); if (want !== u.searchParams.get('sig') || u.searchParams.get('game') !== GAME) { res.writeHead(401); return res.end('{"error":"bad sig"}'); } if (mode === '500') { res.writeHead(500); return res.end('boom'); } res.writeHead(200, { 'Content-Type': 'application/json' }); if (u.pathname.endsWith('/tournament/pending')) return res.end(JSON.stringify({ rows: pendingRows.filter(r => !acks.some(a => a.id === r.id)) })); return res.end(JSON.stringify({ pass: { active: true, until: Date.now() + 86400000 }, memberId: 7 })); } const sig = crypto.createHmac('sha256', SECRET).update(req.headers['x-game-ts'] + '\n' + raw).digest('hex'); if (sig !== req.headers['x-game-sig']) { res.writeHead(401, { 'Content-Type': 'application/json' }); return res.end('{"error":"bad signature"}'); } if (mode === '500') { res.writeHead(500); return res.end('boom'); } const b = JSON.parse(raw); if (b.game !== GAME) { res.writeHead(400); return res.end('{"error":"wrong game"}'); } if (u.pathname.endsWith('/tournament/paid')) { if (mode === 'ackfail') { res.writeHead(500); return res.end('x'); } acks.push(b); res.writeHead(200, { 'Content-Type': 'application/json' }); return res.end('{"ok":true}'); } seen.push(b); const s = script[b.ref] || { allowed: b.pol, deferred: 0 }; res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ allowed: s.allowed, deferred: s.deferred || 0, carried: 0, pass: !!s.pass, capHit: s.capHit || null, day: '2026-10-16' })); }); }); await new Promise(r => stub.listen(0, '127.0.0.1', r)); const port = stub.address().port; const alerts = []; const notify = async (k, p) => { alerts.push([k, p]); }; gp.use({ game: GAME, secret: SECRET, iap: 'http://127.0.0.1:' + port, store, notify }); // ---- the client let r = await gp.grant({ memberId: 7, kind: 'daily', pol: 0.3, ref: 'd:1' }); ok('daily inside the cap: allowed = pol', r.allowed === 0.3 && r.retry === false); script['d:2'] = { allowed: 0.1, capHit: 'daily' }; r = await gp.grant({ memberId: 7, kind: 'daily', pol: 0.3, ref: 'd:2' }); ok('daily over the cap: dropped, capHit carried, the nudge names the Pass', r.allowed === 0.1 && r.capHit === 'daily' && /Get the Pass/.test(gp.note(r, 'daily', 0.3))); r = await gp.grant({ memberId: 0, email: 'nowallet@example.com', kind: 'daily', pol: 0.1, ref: 'd:e' }); ok('a wallet-less member is sent by email, memberId 0', r.allowed === 0.1 && seen.at(-1).email === 'nowallet@example.com'); mode = '500'; r = await gp.grant({ memberId: 7, kind: 'daily', pol: 0.3, ref: 'd:5' }); ok('a 5xx fails closed', r.allowed === 0 && r.retry === true); mode = 'ok'; gp.use({ iap: 'http://127.0.0.1:9' }); r = await gp.grant({ memberId: 7, kind: 'daily', pol: 0.3, ref: 'd:8' }); ok('an unreachable IAP fails closed', r.allowed === 0 && r.retry === true); gp.use({ iap: 'http://127.0.0.1:' + port }); gp.use({ secret: 'wrong-secret-'.padEnd(40, 'y') }); r = await gp.grant({ memberId: 7, kind: 'daily', pol: 0.3, ref: 'd:7' }); ok('a rejected signature fails closed', r.allowed === 0 && r.retry === true); gp.use({ secret: SECRET }); ok('a fresh cached flag is not refetched (10-minute TTL)', (await gp.fetchPass(7, 'hugh@example.com')).active === false); store.write('gamepass', {}); const p0 = await gp.fetchPass(7, 'hugh@example.com'); ok('with no cached flag the signed player GET fetches it', p0.active === true && gp.passOf(7, '').active); mode = '500'; gp.enqueue({ memberId: 7, ref: 'q:old', kind: 'daily', pol: 0.2, at: Date.now() - gp.GIVE_UP_MS - 1000 }); const rr = await gp.retry(async () => {}, Date.now() + gp.RETRY_MS + 1); ok('48 h without an answer: stuck, the admin chat told once', rr.stuck === 1 && alerts.some(a => a[0] === 'gpstuck')); gp.dequeue(7, '', 'q:old'); mode = 'ok'; alerts.length = 0; // ---- finds: 'daily'; the account-wide cap decides; a 0 is recorded as a capped find (still today's find); paid missions are not gated rewards.setSettings({ minPol: 0.05, maxPol: 1, dailyCapPol: 20, missionsPerDay: 3 }); const me = { memberId: 7, email: 'hugh@example.com', username: 'hugh', wallet: '0x' + 'a'.repeat(40) }, day = missions.ctDay(); const m1 = { id: 'm1', site: 'example.com' }, m2 = { id: 'm2', site: 'two.com' }, mpaid = { id: 'adv', site: 'adv.com', paid: true, hunterPol: 0.2 }; const q1 = rewards.quote(m1, true); ok('the quote is the draw inside the range', q1 >= 0.05 && q1 <= 1); const q0 = rewards.quote(m1, false); ok('the free tier draws on the small range (2026-11-02)', q0 >= 0.02 && q0 <= 0.1); let g = rewards.grant(me, m1, { pol: 0.03, nominal: q1, gp: { ref: 'find:m1:' + day, kind: 'daily' } }); ok('a find pays what IAP allowed, due for the faucet', g.ok && g.rec.pol === 0.03 && g.rec.status === 'due' && g.rec.nominal === q1 && g.rec.gp.ref === 'find:m1:' + day); g = rewards.grant(me, m2, { pol: 0, nominal: 0.2, gp: { ref: 'find:m2:' + day, kind: 'daily', capHit: 'daily' } }); ok('a find at the cap: recorded as capped, pays nothing, never reaches the faucet', g.capped && g.rec.status === 'capped' && g.rec.pol === 0 && !rewards.payable().some(p => p.id === g.rec.id)); ok('a capped find still counts as today\'s find and completes the mission', rewards.findsToday(7) === 2 && rewards.completed(7, 'm2', me.wallet) && rewards.daily(7, new Set(), 0, 0, true).left === 1); const gw = rewards.grant(me, { id: 'm3', site: 'three.com' }, { pol: 0.4, status: 'gp-wait', nominal: 0.4, gp: { ref: 'find:m3:' + day, kind: 'daily', pending: true } }); ok('IAP unreachable: the find is recorded as gp-wait, not payable yet', gw.waiting && gw.rec.status === 'gp-wait' && !rewards.payable().some(p => p.id === gw.rec.id)); rewards.settleQueued(gw.rec.id, 0.25, { pass: false }); const settled = store.read('payouts', []).find(p => p.id === gw.rec.id); ok('the queue answer settles it: pays the allowed part, due', settled.pol === 0.25 && settled.status === 'due' && settled.gp.pending === false); rewards.settleQueued(gw.rec.id, 0.9, {}); ok('a settled row is not settled twice', store.read('payouts', []).find(p => p.id === gw.rec.id).pol === 0.25); const gpaid = rewards.grant(me, mpaid); ok('an advertiser-funded mission pays the advertiser\'s amount, ungated (no gp on the row)', gpaid.rec.pol === 0.2 && !gpaid.rec.gp && gpaid.rec.paid === true); ok('the perk: +2 missions a day with the pass', rewards.daily(7, new Set(), 0, 2, true).limit === 5 && rewards.daily(7, new Set(), 0, 0, true).limit === 3); ok('the free tier: one hunt a day without the pass (2026-11-02)', rewards.daily(7, new Set(), 0, 0, false).limit === 1 && rewards.daily(7, new Set(), 0, 0).limit === 1); // ---- Ad Detective: the case is scored first, then IAP decides; a second case a day with the pass rewards.setSettings({ detectiveOn: 1, detectivePol: 0.15 }); const gate = { ask: async (pol, ref) => { const a = await gp.grant({ memberId: 7, email: me.email, kind: 'daily', pol, ref }); a.note = gp.note(a, 'daily', pol); return a; }, wait: (rowId, pol, ref) => gp.enqueue({ memberId: 7, email: me.email, ref, kind: 'daily', pol, rowId }) }; const mkBox = (id, status) => store.update('boxes', {}, all => { all[id] = { id, memberId: 7, day, missionId: 'm1', qid: 'q1', pol: 0.15, status, openedAt: Date.now(), shownAt: Date.now() }; return all; }); store.update('detective-bank', [], all => { all.push({ id: 'q1', missionId: 'm1', q: 'What color?', options: ['Blue', 'Red', 'Green'], active: true }); return all; }); mkBox('7:' + day, 'visited'); const b1 = detective.getBox(7, day); const bank = store.read('detective-bank', [])[0]; // find the choice index that maps to the right answer (option 0) under the box's shuffled order const orderOf = (box) => bank.options.map((o, i) => ({ i, k: crypto.createHmac('sha256', String(process.env.HUNT_CODE_SECRET || process.env.HUNT_SSO_SECRET || 'dev').trim()).update('det:' + box.id + ':' + bank.id + ':' + i).digest().readUInt32BE(0) })).sort((a, b) => a.k - b.k).map(x => x.i); script['detective:' + b1.id] = { allowed: 0.05, capHit: 'daily' }; let a = await detective.answer(me, orderOf(b1).indexOf(0), gate); ok('a solved case pays what IAP allowed and tells the truth', a.ok && a.correct && a.pol === 0.05 && a.nominal === 0.15 && /Daily cap reached/.test(a.note) && seen.at(-1).ref === 'detective:' + b1.id && seen.at(-1).kind === 'daily', a); ok('no pass: the day\'s case is closed, no second box', detective.open(me, false).ok === true && detective.getBox(7, day).id === '7:' + day); // the perk: a second case once the first is closed (needs a live mission with an active question; fake the one check open() makes) store.update('missions', [], all => { all.push({ id: 'm1', site: 'example.com', name: 'Example', active: true, dwell: 30 }); return all; }); store.update('payouts', [], all => { for (let i = 0; i < 3; i++) all.push({ id: 'f' + i, memberId: 7, day, missionId: 'x' + i, pol: 0.05, status: 'paid', at: Date.now() }); return all; }); // 3 finds today -> the box is earned const o2 = detective.open(me, true); ok('pass active: a second case opens with its own id', o2.ok && o2.box && o2.box.id === '7:' + day + ':2' && o2.box.second === true, o2); ok('the second box is now the current one, and a third is refused', detective.getBox(7, day).id === '7:' + day + ':2' && detective.open(me, true).box.id === '7:' + day + ':2'); mode = '500'; store.update('boxes', {}, all => { all['7:' + day + ':2'].status = 'visited'; all['7:' + day + ':2'].shownAt = Date.now(); return all; }); a = await detective.answer(me, orderOf(detective.getBox(7, day)).indexOf(0), gate); ok('IAP down while a case is solved: recorded as gp-wait, queued, the hunter told', a.ok && a.correct && a.waiting && a.pol === 0 && /recorded/.test(a.note) && gp.queued(7, me.email, 'detective:7:' + day + ':2')); mode = 'ok'; script['detective:7:' + day + ':2'] = { allowed: 0.15 }; await gp.retry(async (item, resp) => { rewards.settleQueued(item.rowId, resp.allowed, {}); }, Date.now() + gp.RETRY_MS + 1); ok('the queued case pays on retry', !gp.queued(7, me.email, 'detective:7:' + day + ':2') && store.read('payouts', []).some(p => p.id === a.rec.id && p.pol === 0.15 && p.status === 'due')); process.env.GAMEPASS = 'off'; ok('GAMEPASS=off: a plain answer path still works', (await detective.answer(me, 0, null)).error === 'You already answered today’s case.'); process.env.GAMEPASS = 'on'; // ---- the Pass Tournament payer: PolHunter's faucet pays IAP's pending rows, never twice const sends = []; let sendMode = 'ok', bal = 10; const faucet = { address: () => '0x' + 'f'.repeat(40), balance: async () => bal, send: async (to, pol, onHash) => { if (sendMode === 'fail') throw new Error('nonce too low'); if (sendMode === 'hashThenCrash') { await onHash('0xhash-crash'); throw new Error('receipt lost'); } const tx = '0xtx' + sends.length; sends.push({ to, pol }); await onHash(tx); return { tx, ok: true }; } }; let dry = false; tournament.init({ faucet, notify, dry: () => dry }); pendingRows = [{ id: 'p1', week: '2026-W42', place: 1, email: 'a@example.com', memberId: 11, wallet: '0x' + '1'.repeat(40), pol: 0.5 }, { id: 'p2', week: '2026-W42', place: 2, email: 'b@example.com', memberId: 12, wallet: '0x' + '2'.repeat(40), pol: 0.3 }, { id: 'p3', week: '2026-W42', place: 3, email: 'c@example.com', memberId: 13, wallet: null, pol: 0.2 }]; let st = await tournament.run(); ok('pending rows are paid from the faucet and reported to IAP; the row without a wallet is a failure, not a payment', st.paid === 2 && st.acked === 2 && sends.length === 2 && sends[0].pol === 0.5 && sends[1].to === '0x' + '2'.repeat(40) && acks.length === 2 && acks[0].id === 'p1' && acks[0].tx === '0xtx0' && st.failures.length === 1 && /no wallet/.test(st.failures[0].error), st); ok('the claims file holds the hash per row', store.read('tourney-claims', {})['id:p1'].tx === '0xtx0' && store.read('tourney-claims', {})['id:p1'].acked > 0); ok('the admin chat heard about each prize', alerts.filter(a => a[0] === 'tourneypaid').length === 2); st = await tournament.run(); ok('a second run pays nothing new (IAP no longer lists them)', st.paid === 0 && sends.length === 2); // IAP still lists a row that was paid (its ack was lost): re-report the hash, never re-send acks.length = 0; st = await tournament.run(); ok('a paid row IAP still lists is re-reported, not re-sent', sends.length === 2 && st.acked === 2 && st.paid === 0 && acks.length === 2); // a fresh row while the send fails: the row stays pending, the claim is released, the admin chat alerted pendingRows.push({ id: 'p4', week: '2026-W43', place: 1, email: 'd@example.com', memberId: 14, wallet: '0x' + '4'.repeat(40), pol: 0.4 }); sendMode = 'fail'; alerts.length = 0; st = await tournament.run(); ok('a send failure leaves the row pending and alerts', st.paid === 0 && st.failures.some(f => /nonce too low/.test(f.error)) && alerts.some(a => a[0] === 'tourneyfail') && !acks.some(a => a.id === 'p4') && !store.read('tourney-claims', {})['id:p4'].tx); sendMode = 'ok'; st = await tournament.run(); ok('the next run pays it (the claim was released)', st.paid === 1 && acks.some(a => a.id === 'p4')); // a fresh claim by "another app copy" within the TTL is respected (deploy overlap) pendingRows.push({ id: 'p5', week: '2026-W43', place: 2, email: 'e@example.com', memberId: 15, wallet: '0x' + '5'.repeat(40), pol: 0.1 }); store.update('tourney-claims', {}, all => { all['id:p5'] = { claimedAt: Date.now(), week: '2026-W43', place: 2, wallet: '0x' + '5'.repeat(40), pol: 0.1 }; return all; }); st = await tournament.run(); ok('a row another copy claimed moments ago is skipped, not paid twice', st.skipped >= 1 && !sends.some(s => s.to === '0x' + '5'.repeat(40))); store.update('tourney-claims', {}, all => { all['id:p5'].claimedAt = Date.now() - tournament.CLAIM_TTL - 1; return all; }); st = await tournament.run(); ok('after the claim TTL with no hash, the row is paid', sends.some(s => s.to === '0x' + '5'.repeat(40)) && acks.some(a => a.id === 'p5')); // the chain has the hash but the receipt was lost: never re-sent, reported next run pendingRows.push({ id: 'p6', week: '2026-W43', place: 3, email: 'f@example.com', memberId: 16, wallet: '0x' + '6'.repeat(40), pol: 0.1 }); sendMode = 'hashThenCrash'; st = await tournament.run(); ok('a hash recorded before the crash is kept', store.read('tourney-claims', {})['id:p6'].tx === '0xhash-crash' && st.failures.some(f => /receipt unknown/.test(f.error))); sendMode = 'ok'; const n0 = sends.length; st = await tournament.run(); ok('the next run only reports that hash', sends.length === n0 && acks.some(a => a.id === 'p6' && a.tx === '0xhash-crash')); // dry run and low balance dry = true; pendingRows.push({ id: 'p7', week: '2026-W44', place: 1, email: 'g@example.com', memberId: 17, wallet: '0x' + '7'.repeat(40), pol: 0.9 }); st = await tournament.run(); ok('HUNT_DRY_RUN: records what it would pay, sends nothing', st.wouldPay === 0.9 && st.paid === 0 && !sends.some(s => s.to === '0x' + '7'.repeat(40)) && store.read('tourney-claims', {})['id:p7'].dry === true); st = await tournament.run(); ok('a dry-run row is not re-claimed', st.skipped >= 1 && st.wouldPay === 0.9); dry = false; store.update('tourney-claims', {}, all => { delete all['id:p7']; return all; }); bal = 0.5; alerts.length = 0; st = await tournament.run(); ok('a low balance leaves the row pending and alerts once', st.paid === 0 && st.failures.some(f => /low balance/.test(f.error)) && alerts.some(a => a[0] === 'low' && a[1].tournament) && !store.read('tourney-claims', {})['id:p7'].tx); bal = 10; st = await tournament.run(); ok('topped up: paid', acks.some(a => a.id === 'p7')); process.env.GAMEPASS = 'off'; st = await tournament.run(); ok('GAMEPASS=off: the payer is inert', st.on === false && st.pending === 0); process.env.GAMEPASS = 'on'; const view = tournament.state(); ok('the admin sees last run, totals and claims', view.last && view.paidTotal >= 5 && view.claims.length >= 6 && view.recent.length >= 1); stub.close(); console.log(`\n${pass} passed, ${fail} failed`); process.exit(fail ? 1 : 0); })().catch(e => { console.error(e); process.exit(1); });