Files
instantadpay/qa/gamepass-games.cjs
T
martbost 084d1ea3d6 Game Pass: tournament/pending answers rows (the field the games' polgrant.js reads), games-side integration test, docs "Games: as built"
- /api/partner/tournament/pending returned only `pending`; every game's polgrant.js tournamentPending() reads `rows`, so
  PolHunter's prize payer would never have seen a row. Answer now carries both (`pending` stays for the admin pane + qa).
- qa/gamepass-games.cjs (bash qa/run.sh gamepass-games): boots a local copy like qa/gamepass.mjs and drives the REAL
  spooky-doors/server/polgrant.js and polhunter/lib/tournament.js against it (fetchPass, daily/progress caps, carry:<day>
  zero-POL call on the next Central day, void, bad secret / IAP down -> retry, retry queue, tournament dry run + live). 44/44.
- qa/gamepass.mjs pins the `rows` field.
- docs/GAME-PASS.md: 3a item 8 updated, "Games: as built" section merged from the games' notes (per game files/refs/perk/tests,
  decisions, the tournament payer and its dry-run claim trap, the integration test).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-16 09:27:46 -05:00

189 lines
19 KiB
JavaScript

// Game Pass integration test (2026-10-16): the REAL games' shared client (spooky-doors/server/polgrant.js) and PolHunter's tournament
// payer (polhunter/lib/tournament.js) against a LOCAL copy of this server, booted the way qa/gamepass.mjs boots it (JSON store,
// throwaway DATA_DIR, devCode sign-in, throwaway game secrets). Nothing touches production.
// node qa/gamepass-games.cjs (or: bash qa/run.sh gamepass-games)
// Needs the sibling game repos (GAMES_ROOT, default ../.. = D:/Projects/HighRisk): spooky-doors/server/{polgrant,store}.js and
// polhunter/lib/{polgrant,store,tournament,faucet}.js. The games' client has no devDay field, so for the "next Central day" calls a
// fetch wrapper adds devDay to the already-built body and re-signs it with the same secret; every "today" call goes through untouched.
'use strict';
const crypto = require('crypto');
const fs = require('fs');
const os = require('os');
const path = require('path');
const { spawn } = require('child_process');
const SITE = path.resolve(__dirname, '..');
const GAMES = (process.env.GAMES_ROOT || path.resolve(SITE, '..', '..')).replace(/\\/g, '/');
const SD = GAMES + '/spooky-doors/server';
const PH = GAMES + '/polhunter/lib';
const PORT = Number(process.env.GP_PORT || 8798);
const B = 'http://127.0.0.1:' + PORT;
const SDS = crypto.randomBytes(24).toString('hex'), HUNT = crypto.randomBytes(24).toString('hex');
const ADMIN = 'localtest', ADMIN_EMAIL = 'qa-admin@example.com';
const DATA = fs.mkdtempSync(path.join(os.tmpdir(), 'iap-gpint-')); fs.mkdirSync(path.join(DATA, 'uploads'));
const SDDATA = fs.mkdtempSync(path.join(os.tmpdir(), 'sd-gpint-'));
const PHDATA = fs.mkdtempSync(path.join(os.tmpdir(), 'ph-gpint-'));
let fails = 0; const ok = (c, label, extra) => { console.log((c ? 'PASS ' : 'FAIL ') + label + (extra ? ' ' + extra : '')); if (!c) fails++; };
const near = (a, b, tol) => Math.abs(Number(a) - Number(b)) <= (tol || 1e-6);
const sleep = ms => new Promise(r => setTimeout(r, ms));
const ctDay = t => new Date(t).toLocaleDateString('en-CA', { timeZone: 'America/Chicago' });
const srv = spawn(process.execPath, ['server.js'], { cwd: SITE, stdio: ['ignore', 'pipe', 'pipe'],
env: Object.assign({}, process.env, { PORT: String(PORT), DATA_DIR: DATA, NODE_ENV: 'development', ADMIN_EMAIL, ADMIN_PASSWORD: ADMIN, SD_SSO_SECRET: SDS, HUNT_SSO_SECRET: HUNT, DEV_POL_USD: '0.10' }) });
let srvLog = ''; srv.stdout.on('data', d => srvLog += d); srv.stderr.on('data', d => srvLog += d);
const cleanup = () => { try { srv.kill(); } catch (e) {} for (const d of [DATA, SDDATA, PHDATA]) { try { fs.rmSync(d, { recursive: true, force: true }); } catch (e) {} } };
async function api(p, o, headers) {
const opts = { method: (o && o.method) || (o && 'data' in o ? 'POST' : 'GET'), headers: Object.assign({ 'Content-Type': 'application/json' }, headers || {}) };
if (o && 'data' in o) opts.body = JSON.stringify(o.data);
const r = await fetch(B + p, opts); let j = null; try { j = await r.json(); } catch (e) {}
return { status: r.status, j, headers: r.headers };
}
const adminH = { Authorization: 'Bearer ' + ADMIN };
// harness-side signed GET of the player card (to READ caps; the client's fetchPass caches 10 min and only returns the pass)
async function rawPlayer(secret, game, email, devDay) {
const ts = String(Date.now()); const sig = crypto.createHmac('sha256', secret).update('player:' + email + ':' + ts).digest('hex');
const q = Object.assign({ game, m: 0, e: email, ts, sig }, devDay ? { devDay } : {});
const r = await fetch(B + '/api/partner/player?' + new URLSearchParams(q)); let j = null; try { j = await r.json(); } catch (e) {} return { status: r.status, j };
}
(async () => {
try {
for (let i = 0; i < 40; i++) { try { if ((await fetch(B + '/api/config')).ok) break; } catch (e) {} await sleep(500); }
async function signIn(email, username) {
const s = await api('/api/auth/email/start', { data: { email, fts: Date.now() - 5000 } });
const v = await fetch(B + '/api/auth/email/verify', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email, code: s.j && s.j.devCode }) });
const cookie = (v.headers.getSetCookie ? v.headers.getSetCookie() : [v.headers.get('set-cookie')]).map(c => String(c).split(';')[0]).join('; ');
if (username) await api('/api/my/profile', { data: { username } }, { Cookie: cookie });
return { Cookie: cookie };
}
await api('/api/admin/site', { method: 'PATCH', data: { fraudMaxSignupsPerIpDay: 10, gamePassEnabled: '1', capsStartDate: '2026-01-01' } }, adminH);
const F = 'qa-int-free@example.com', P = 'qa-int-pass@example.com';
const hF = await signIn(F, 'qaintfree'), hP = await signIn(P, 'qaintpass');
// the pass holder: buy (charge stubbed, local only) -> active 7 days
let r = await api('/api/my/gamepass/buy', { data: { devPaid: true } }, hP);
ok(r.status === 200 && r.j.ok && r.j.active === true, 'setup: P buys the pass (devPaid) -> active', new Date(r.j.until).toISOString());
const untilP = r.j.until;
// the pass holder links a wallet through the real challenge/verify flow (signed locally with ethers) so tournament.js has somewhere to pay
const { ethers } = require(SITE + '/node_modules/ethers');
const w = ethers.Wallet.createRandom();
const ch = await api('/api/auth/challenge', { data: { address: w.address } });
const sigm = await w.signMessage(ch.j.message);
const lv = await api('/api/auth/verify', { data: { address: w.address, signature: sigm } }, hP);
ok(lv.status === 200 && lv.j.linked === true && lv.j.address === w.address.toLowerCase(), 'setup: P links a wallet via /api/auth/challenge + /verify', JSON.stringify(lv.j));
const walletP = w.address.toLowerCase();
// ---- the REAL games' client, configured the way spooky-doors/server/server.js does (line 17-28) ----
process.env.GAMEPASS = 'on'; process.env.IAP_URL = B; process.env.SD_SSO_SECRET = SDS;
const sdStore = require(SD + '/store.js'); sdStore.init(SDDATA);
const gp = require(SD + '/polgrant.js');
const SECRET = String(process.env.SD_SSO_SECRET || '').trim(); const IAP = String(process.env.IAP_URL || 'https://instantadpay.com').replace(/\/+$/, '');
const notes = []; gp.use({ game: 'spookydoors', secret: SECRET, iap: IAP, store: sdStore, notify: (k, p) => notes.push([k, p]) });
ok(gp.on() && gp._cfg().iap === B && gp._cfg().game === 'spookydoors', 'client: GAMEPASS=on, IAP_URL honoured, slug spookydoors', gp._cfg().iap);
// next-Central-day plumbing: the client has no devDay field, so (only while fakeDay is set) the already-built POST body gets
// devDay added and is re-signed with the same secret; every "today" call goes through the client untouched
let fakeDay = null; const realFetch = globalThis.fetch;
gp.use({ fetch: (u, o) => { if (fakeDay && o && o.method === 'POST' && o.body) { const b = JSON.parse(o.body); b.devDay = fakeDay; const raw = JSON.stringify(b); const ts = o.headers['X-Game-Ts']; o = Object.assign({}, o, { body: raw, headers: Object.assign({}, o.headers, { 'X-Game-Sig': crypto.createHmac('sha256', SECRET).update(ts + '\n' + raw).digest('hex') }) }); } return realFetch(u, o); } });
// 1. fetchPass: free member vs pass holder
let pf = await gp.fetchPass(0, F); ok(pf.active === false && pf.until === null, 'fetchPass(free) -> active false', JSON.stringify(pf));
let pp = await gp.fetchPass(0, P); ok(pp.active === true && pp.until === untilP, 'fetchPass(pass holder) -> active true, until = IAP until', JSON.stringify(pp));
let vw = gp.view(0, P); ok(vw.on === true && vw.active === true && vw.untilText && vw.url === 'https://instantadpay.com/my#games?pass=1', 'view(P) for the lobby', JSON.stringify(vw));
// 2. daily within / over the cap (free caps 0.30 / 2.0, enforced since capsStartDate 2026-01-01)
const today = ctDay(Date.now());
let g = await gp.grant({ memberId: 0, email: F, kind: 'daily', pol: 0.2, ref: 'it:d1' });
ok(g.retry === false && g.allowed === 0.2 && g.deferred === 0 && g.carried === 0 && g.pass === false && g.enforced === true && g.capHit === null && g.day === today, 'daily 0.2 within cap -> allowed 0.2, enforced, day = Central today', JSON.stringify(g));
g = await gp.grant({ memberId: 0, email: F, kind: 'daily', pol: 0.2, ref: 'it:d2' });
ok(g.retry === false && g.allowed === 0.1 && g.capHit === 'daily' && g.deferred === 0, 'daily 0.2 over cap -> allowed 0.1, capHit daily, nothing deferred', JSON.stringify(g));
ok(gp.note(g, 'daily', 0.2) === 'Daily cap reached for today. Get the Pass for a higher cap.', 'note() for the capped free daily', gp.note(g, 'daily', 0.2));
// 3. progress over the total cap -> deferred
g = await gp.grant({ memberId: 0, email: F, kind: 'progress', pol: 5, ref: 'rung:7' });
ok(g.retry === false && g.allowed === 1.7 && g.deferred === 3.3 && g.capHit === 'total', 'progress 5 -> allowed 1.7 (2.0 total minus 0.3 daily), 3.3 deferred', JSON.stringify(g));
ok(gp.note(g, 'progress', 5) === '3.3 POL is yours; it pays out over the next days (daily cap).', 'note() for the deferred progress', gp.note(g, 'progress', 5));
let pl = await rawPlayer(SDS, 'spookydoors', F); ok(pl.j.caps.used.daily === 0.3 && pl.j.caps.used.total === 2 && pl.j.caps.pending === 3.3, 'IAP caps today: used 0.30 / 2.0, 3.3 pending for spookydoors', JSON.stringify(pl.j.caps));
// 4. the carrySweep-style zero-POL call on the NEXT Central day (pol.js carrySweep: kind progress, pol 0, ref carry:<day>)
const day2 = ctDay(Date.now() + 86400000), day3 = ctDay(Date.now() + 2 * 86400000);
fakeDay = day2;
g = await gp.grant({ memberId: 0, email: F, kind: 'progress', pol: 0, ref: 'carry:' + day2 });
ok(g.retry === false && g.allowed === 2 && g.carried === 2 && g.deferred === 0 && g.day === day2, 'NEXT day carry (pol 0) -> accepted, allowed 2.0, carried 2.0 (not rejected)', JSON.stringify(g));
const g2 = await gp.grant({ memberId: 0, email: F, kind: 'progress', pol: 0, ref: 'carry:' + day2 });
ok(g2.retry === false && g2.repeat === true && g2.allowed === 2 && g2.carried === 2, 'the same carry ref again -> repeat true, same answer (idempotent)', JSON.stringify(g2));
pl = await rawPlayer(SDS, 'spookydoors', F, day2); ok(pl.j.caps.used.total === 2 && pl.j.caps.pending === 1.3, 'IAP caps on day 2: total 2.0 used (all carried), 1.3 still pending', JSON.stringify(pl.j.caps));
fakeDay = day3;
g = await gp.grant({ memberId: 0, email: F, kind: 'progress', pol: 0, ref: 'carry:' + day3 });
ok(g.retry === false && g.allowed === 1.3 && g.carried === 1.3 && g.day === day3, 'day 3 carry -> the last 1.3', JSON.stringify(g));
g = await gp.grant({ memberId: 0, email: F, kind: 'progress', pol: 0, ref: 'carry:x:' + day3 });
ok(g.retry === false && g.allowed === 0 && g.carried === 0 && g.deferred === 0, 'a carry call with nothing owed -> allowed 0, no error, not retry', JSON.stringify(g));
fakeDay = null;
// 5. void: the ref's own share comes back (today's daily 0.2), so a new daily grant fits again
let vd = await gp.voidGrant({ memberId: 0, email: F, ref: 'it:d1' }); ok(vd.ok === true, 'voidGrant(it:d1) -> ok', JSON.stringify(vd));
pl = await rawPlayer(SDS, 'spookydoors', F); ok(pl.j.caps.used.daily === 0.1 && pl.j.caps.used.total === 1.8, 'IAP caps today after the void: daily 0.1, total 1.8', JSON.stringify(pl.j.caps));
g = await gp.grant({ memberId: 0, email: F, kind: 'daily', pol: 0.2, ref: 'it:d3' });
ok(g.allowed === 0.2 && g.capHit === null, 'daily 0.2 after the void -> allowed 0.2', JSON.stringify(g));
g = await gp.grant({ memberId: 0, email: F, kind: 'daily', pol: 0.2, ref: 'it:d1' });
ok(g.repeat === true && g.allowed === 0, 'replaying the voided ref -> repeat, allowed 0', JSON.stringify(g));
// pass holder: pass caps apply
g = await gp.grant({ memberId: 0, email: P, kind: 'daily', pol: 1.0, ref: 'p:d1' });
ok(g.allowed === 1 && g.pass === true && g.capHit === null, 'pass holder daily 1.0 -> allowed 1.0, pass true', JSON.stringify(g));
ok(gp.passOf(0, P).active === true, 'the grant answer refreshed the cached pass flag', JSON.stringify(gp.passOf(0, P)));
// 6. failure modes: bad secret / IAP down / unknown member -> the client answers { allowed: 0, retry: true }
gp.use({ secret: crypto.randomBytes(24).toString('hex') });
g = await gp.grant({ memberId: 0, email: F, kind: 'daily', pol: 0.1, ref: 'bad:1' });
ok(g.allowed === 0 && g.retry === true && /401/.test(g.error), 'bad secret -> { allowed: 0, retry: true } (IAP 401)', JSON.stringify(g));
gp.use({ secret: SECRET, iap: 'http://127.0.0.1:1' });
g = await gp.grant({ memberId: 0, email: F, kind: 'daily', pol: 0.1, ref: 'down:1' });
ok(g.allowed === 0 && g.retry === true, 'IAP down -> { allowed: 0, retry: true }', JSON.stringify(g));
// the retry queue pays once IAP is back
gp.enqueue({ memberId: 0, email: F, kind: 'daily', pol: 0.1, ref: 'down:1' });
ok(gp.queued(0, F, 'down:1') === true, 'enqueue -> queued() guards the ref', '');
let rt = await gp.retry(() => {}, Date.now() + gp.RETRY_MS + 1); ok(rt.tried === 1 && rt.paid === 0 && gp.queued(0, F, 'down:1'), 'retry while IAP is down -> still queued', JSON.stringify(rt));
gp.use({ iap: B });
let paidItems = []; rt = await gp.retry((item, resp) => paidItems.push([item.ref, resp.allowed, resp.capHit]), Date.now() + 2 * gp.RETRY_MS + 2);
ok(rt.tried === 1 && rt.paid === 1 && paidItems.length === 1 && paidItems[0][1] === 0 && paidItems[0][2] === 'daily' && !gp.queued(0, F, 'down:1'), 'retry once IAP is back -> settled (allowed 0: F already used today\'s 0.30 daily cap), dequeued', JSON.stringify(rt) + ' ' + JSON.stringify(paidItems));
g = await gp.grant({ memberId: 0, email: 'nobody-here@example.com', kind: 'daily', pol: 0.1, ref: 'nb:1' });
ok(g.allowed === 0 && g.retry === true && /404/.test(g.error), 'unknown member -> retry: true (IAP 404; the game would queue it 48 h) [observation]', JSON.stringify(g));
// 7. the tournament: P plays in the week of Oct 19 and buys again that week (a sale), then admin settles the week
fakeDay = '2026-10-20';
g = await gp.grant({ memberId: 0, email: P, kind: 'daily', pol: 0.1, ref: 'wk:1' }); ok(g.allowed === 0.1, 'P plays (Oct 20) #1', JSON.stringify(g));
g = await gp.grant({ memberId: 0, email: P, kind: 'progress', pol: 0.1, ref: 'wk:2' }); ok(g.allowed === 0.1, 'P plays (Oct 20) #2', JSON.stringify(g));
fakeDay = null;
r = await api('/api/my/gamepass/buy', { data: { devPaid: true, devDay: '2026-10-20' } }, hP); ok(r.j.ok, 'P buys again stamped Oct 20 (a sale in the week of Oct 19)', '');
let t = await api('/api/admin/gamepass/tournament/run', { data: { week: '2026-10-21' } }, adminH);
ok(t.status === 200 && t.j.week === '2026-10-19' && t.j.winners.length === 1 && t.j.winners[0].email === P && near(t.j.winners[0].pol, 1.25) && t.j.winners[0].wallet === walletP, 'tournament settled: P #1, 1.25 POL, wallet set', JSON.stringify(t.j.winners));
// ---- PolHunter's payer: lib/tournament.js with its own store + polgrant copy, configured like polhunter/server.js line 50-61 ----
process.env.HUNT_SSO_SECRET = HUNT;
const phStore = require(PH + '/store.js'); phStore.init(PHDATA);
const gph = require(PH + '/polgrant.js');
const phNotes = []; gph.use({ game: 'polhunter', secret: String(process.env.HUNT_SSO_SECRET || '').trim(), iap: String(process.env.IAP_URL || '').replace(/\/+$/, ''), store: phStore, notify: (k, p) => phNotes.push([k, p]) });
let dryFn; try { dryFn = require(PH + '/faucet.js').dry; } catch (e) { console.log(' (faucet.js not requirable here: ' + e.message.slice(0, 80) + '; using the same HUNT_DRY_RUN rule)'); dryFn = () => String(process.env.HUNT_DRY_RUN || 'off').trim().toLowerCase() !== 'off'; }
const tournament = require(PH + '/tournament.js');
const sends = []; const TX = '0x' + crypto.randomBytes(32).toString('hex');
const faucet = { address: () => '0x' + '1'.repeat(40), balance: async () => 50, send: async (to, pol, onHash) => { sends.push({ to, pol }); if (onHash) await onHash(TX); return { tx: TX, ok: true }; } };
tournament.init({ faucet, notify: (k, p) => phNotes.push([k, p]), dry: dryFn });
const tp = await gph.tournamentPending();
ok(tp.ok === true && tp.rows.length === 1 && tp.rows[0].email === P && tp.rows[0].week === '2026-10-19' && tp.rows[0].place === 1 && tp.rows[0].wallet === walletP && near(tp.rows[0].pol, 1.25), 'client tournamentPending() sees the 1 unpaid row', JSON.stringify(tp));
process.env.HUNT_DRY_RUN = 'on';
let st = await tournament.run();
ok(st.on === true && st.dry === true && st.pending === 1 && near(st.wouldPay, 1.25) && st.paid === 0 && sends.length === 0, 'HUNT_DRY_RUN=on: run() lists the row as wouldPay 1.25, sends nothing', JSON.stringify(st));
let cl = phStore.read('tourney-claims', {}); ok(cl['wk:2026-10-19:1'] && cl['wk:2026-10-19:1'].dry === true, 'dry claim recorded in tourney-claims', JSON.stringify(cl));
process.env.HUNT_DRY_RUN = 'off';
st = await tournament.run();
ok(st.dry === false && st.paid === 0 && st.skipped === 1 && sends.length === 0, 'dry OFF with the dry claim still there: the row is SKIPPED, never paid (games-side trap: a dry-run claim is permanent)', JSON.stringify(st));
phStore.write('tourney-claims', {}); // a fresh volume (what a real deploy without a dry run looks like)
st = await tournament.run();
ok(st.paid === 1 && st.acked === 1 && st.failures.length === 0 && sends.length === 1 && sends[0].to === walletP && near(sends[0].pol, 1.25), 'dry OFF, fresh claims: faucet.send(wallet, 1.25) + POST /paid acked', JSON.stringify(st) + ' ' + JSON.stringify(sends));
cl = phStore.read('tourney-claims', {}); ok(cl['wk:2026-10-19:1'] && cl['wk:2026-10-19:1'].tx === TX && cl['wk:2026-10-19:1'].acked, 'claim carries the tx + acked', JSON.stringify(cl['wk:2026-10-19:1']));
ok(phNotes.some(n => n[0] === 'tourneypaid'), 'notify(tourneypaid) fired', phNotes.map(n => n[0]).join(','));
let pend = await api('/api/partner/tournament/pending', null, adminH); ok(pend.j.pending.length === 0, 'IAP pending is empty after the payout', JSON.stringify(pend.j));
st = await tournament.run(); ok(st.pending === 0 && st.paid === 0 && sends.length === 1, 'next run: nothing pending, nothing re-sent', JSON.stringify(st));
const tstate = tournament.state(); ok(tstate.paidTotal === 1 && tstate.recent.length >= 3, 'tournament.state() for the admin: paidTotal 1', JSON.stringify({ paidTotal: tstate.paidTotal, runs: tstate.recent.length }));
ok(/gamepass prize paid 2026-10-19 #1 by polhunter/.test(srvLog), 'IAP logged the prize as paid by polhunter', '');
} catch (e) { console.error('FAIL harness error', e && e.stack || e); fails++; }
finally { cleanup(); }
if (fails) console.log('--- server log (gamepass lines) ---\n' + srvLog.split('\n').filter(l => /gamepass|Error|error/.test(l)).slice(-30).join('\n'));
console.log(fails ? fails + ' FAILURE(S)' : 'ALL PASS');
process.exit(fails ? 1 : 0);
})();