Files
instantadpay/qa/gamepass.mjs
T

248 lines
26 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Game Pass + account-wide POL caps, end to end against a LOCAL copy (2026-10-16, docs/GAME-PASS.md).
// node qa/gamepass.mjs (or: bash qa/run.sh gamepass)
// Boots server.js on its own port with a throwaway DATA_DIR (JSON store, no DB, no mail key, devCode sign-in) and throwaway game
// secrets. Nothing touches production. Covers: settings on/off; buy without purchased credits -> waiting order -> a $5 package
// fulfils it; buy -> active, buy again -> extended (the charge is stubbed with devPaid, the real ads.gamePurchase(purchasedOnly)
// path needs a position with on-chain credits and is the live PolyWarriors mint path); partner auth (bad sig / stale / unknown game);
// /api/partner/player pass + caps; polgrant before capsStartDate (allowed, recorded); daily within/over the cap; progress deferral
// and carry-forward on the next day (the Central day is faked with devDay); caps account-wide across games; idempotent ref; void;
// pass expiry back to free caps; the tournament settle + pending + paid seam; admin stats. Exit code 1 on any failure.
import crypto from 'node:crypto';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { spawn } from 'node:child_process';
const SITE = path.resolve(path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1')), '..');
const PORT = Number(process.env.GP_PORT || 8799);
const B = 'http://127.0.0.1:' + PORT;
const GK = crypto.randomBytes(24).toString('hex'), HUNT = crypto.randomBytes(24).toString('hex'); // throwaway, never printed
const ADMIN = 'localtest', ADMIN_EMAIL = 'qa-admin@example.com';
const DATA = fs.mkdtempSync(path.join(os.tmpdir(), 'iap-gamepass-')); fs.mkdirSync(path.join(DATA, 'uploads'));
let fails = 0; const ok = (cond, label, extra) => { console.log((cond ? 'PASS ' : 'FAIL ') + label + (extra ? ' ' + extra : '')); if (!cond) 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 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, GK_SSO_SECRET: GK, 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) {} try { fs.rmSync(DATA, { 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 };
// a game's signed POST (3a): X-Game-Ts + X-Game-Sig = HMAC(secret, ts + '\n' + rawBody)
async function gamePost(p, body, secret, tsOverride) {
const raw = JSON.stringify(body); const ts = tsOverride || String(Date.now());
const sig = crypto.createHmac('sha256', secret).update(ts + '\n' + raw).digest('hex');
const r = await fetch(B + p, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Game-Ts': ts, 'X-Game-Sig': sig }, body: raw });
let j = null; try { j = await r.json(); } catch (e) {} return { status: r.status, j };
}
// a game's signed GET (3a): sig = HMAC(secret, 'player:' + who + ':' + ts)
async function gameGet(p, q, who, secret) {
const ts = String(Date.now()); const sig = crypto.createHmac('sha256', secret).update('player:' + who + ':' + ts).digest('hex');
const r = await fetch(B + p + '?' + new URLSearchParams(Object.assign({}, q, { ts, sig })).toString()); let j = null; try { j = await r.json(); } catch (e) {} return { status: r.status, j };
}
const grant = (o, secret, tsOverride) => gamePost('/api/partner/polgrant', o, secret || GK, tsOverride);
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 } }, adminH);
const A = 'qa-gp-a@example.com', Bm = 'qa-gp-b@example.com', C = 'qa-gp-c@example.com';
const hA = await signIn(A, 'qagpa'), hB = await signIn(Bm, 'qagpb'), hC = await signIn(C, 'qagpc');
// 1. settings: off by default, member GET says so, buy refused
let g = (await api('/api/my/gamepass', null, hA)).j;
ok(g && g.enabled === false && g.active === false && g.price === 500 && g.days === 7, 'GET /api/my/gamepass with the pass OFF: enabled false, price 500, days 7', JSON.stringify(g));
let r = await api('/api/my/gamepass/buy', { data: {} }, hA);
ok(r.status === 400 && /not open/.test(r.j && r.j.error || ''), 'buy refused while the pass is off', JSON.stringify(r.j));
await api('/api/admin/site', { method: 'PATCH', data: { gamePassEnabled: '1', capsStartDate: '' } }, adminH);
g = (await api('/api/my/gamepass', null, hA)).j;
ok(g && g.enabled === true && g.caps && g.caps.enforced === false && g.caps.daily === 0.3 && g.caps.total === 2, 'pass ON: GET shows free caps 0.30 / 2 and enforced false (no capsStartDate)', JSON.stringify(g.caps));
// 2. buy (2026-10-22: no pass is ever bought with credits) -> waiting order; only a FRESH package by the member's own position fulfils it.
// A's purchases are stamped Sun Oct 18 (week of Oct 12) and B's Tue Oct 20 (week of Oct 19), so the tournament below sees one sale.
const SUN = Date.parse('2026-10-18T17:00:00Z'), TUE = Date.parse('2026-10-20T17:00:00Z');
r = await api('/api/my/gamepass/buy', { data: {} }, hA);
ok(r.status === 200 && r.j && r.j.needPay === true && r.j.payUrl === '/my?from=gamepass#buy' && r.j.order && r.j.package === 5 && /package/.test(r.j.message || ''), 'buy -> needPay + payUrl + waiting order (never a credit charge)', JSON.stringify(r.j && { needPay: r.j.needPay, payUrl: r.j.payUrl, pkg: r.j.package }));
const order1 = r.j && r.j.order, order1Ts = r.j && r.j.orderTs;
r = await api('/api/my/gamepass/buy', { data: { devPaid: true } }, hA);
ok(r.j && r.j.order === order1 && r.j.needPay === true && !r.j.ok, 'a second buy (even with the retired devPaid flag) reuses the same waiting order, no pass', r.j && r.j.order);
g = (await api('/api/my/gamepass', null, hA)).j; ok(g.waiting === true && g.active === false, 'GET shows waiting: true', '');
r = await api('/api/dev/gamepass-purchase', { data: { email: A, cents: 500, minedAt: order1Ts - 10 * 60000 } });
ok(r.j && r.j.order === null, 'a package mined BEFORE the order was opened does not fulfil it', JSON.stringify(r.j));
r = await api('/api/dev/gamepass-purchase', { data: { email: A, cents: 200 } });
ok(r.j && r.j.order === null, 'a $2 package does not fulfil a $5 pass order', JSON.stringify(r.j));
r = await api('/api/dev/gamepass-purchase', { data: { email: Bm, cents: 500 } });
ok(r.j && r.j.order === null, 'another member’s package does not fulfil A’s order', JSON.stringify(r.j));
const tx1 = '0x' + crypto.randomBytes(32).toString('hex');
r = await api('/api/dev/gamepass-purchase', { data: { email: A, cents: 500, tx: tx1, now: SUN } });
ok(r.j && r.j.order && r.j.order.order === order1, 'a fresh $5 package by A fulfils the waiting order', JSON.stringify(r.j));
g = (await api('/api/my/gamepass', null, hA)).j; const until1 = g.until;
ok(g.active === true && g.waiting === false && g.until === SUN + 7 * 86400000 && g.bought === 1, 'pass active for 7 days from the purchase, waiting cleared', new Date(g.until).toISOString());
r = await api('/api/dev/gamepass-purchase', { data: { email: A, cents: 500 } });
ok(r.j && r.j.order === null, 'another package with no waiting order does nothing', JSON.stringify(r.j));
// 3. buy while active -> a new order; the same tx again is refused, a new package extends from the current until
r = await api('/api/my/gamepass/buy', { data: {} }, hA);
ok(r.j && r.j.needPay && r.j.order && r.j.order !== order1, 'buy while active opens a new waiting order', r.j && r.j.order);
r = await api('/api/dev/gamepass-purchase', { data: { email: A, cents: 500, tx: tx1, now: SUN } });
ok(r.j && r.j.order === null, 'replaying a purchase tx that already paid a pass does nothing (each tx once)', JSON.stringify(r.j));
r = await api('/api/dev/gamepass-purchase', { data: { email: A, cents: 500, now: SUN } });
ok(r.j && r.j.order && near(r.j.order.until, until1 + 7 * 86400000, 1000), 'a fresh package while active extends by 7 days from the current until', r.j && r.j.order && new Date(r.j.order.until).toISOString());
r = await api('/api/my/gamepass/buy', { data: {} }, hB);
r = await api('/api/dev/gamepass-purchase', { data: { email: Bm, cents: 1000, now: TUE } });
g = (await api('/api/my/gamepass', null, hB)).j;
ok(r.j && r.j.order && g.active === true, 'member B: order + a $10 package -> active (sale stamped in the week of Oct 19 for the tournament)', JSON.stringify(r.j));
// 4. partner auth + /api/partner/player
let pl = await gameGet('/api/partner/player', { game: 'gemkingdom', m: 0, e: A }, A, GK);
ok(pl.status === 200 && pl.j.pass && pl.j.pass.active === true && pl.j.pass.until === until1 + 7 * 86400000 && pl.j.caps.daily === 1.5 && pl.j.caps.total === 5 && pl.j.caps.used.total === 0 && /^\d{4}-\d{2}-\d{2}$/.test(pl.j.caps.day), 'player (pass holder): pass.active, pass caps 1.50 / 5, used 0, Central day', JSON.stringify(pl.j.pass) + ' ' + JSON.stringify(pl.j.caps));
pl = await gameGet('/api/partner/player', { game: 'gemkingdom', m: 0, e: C }, C, GK);
ok(pl.status === 200 && pl.j.pass.active === false && pl.j.pass.until === null && pl.j.caps.daily === 0.3 && pl.j.caps.total === 2, 'player (free): pass false, free caps 0.30 / 2', JSON.stringify(pl.j.caps));
pl = await gameGet('/api/partner/player', { game: 'gemkingdom', m: 0, e: C }, C, HUNT);
ok(pl.status === 401, 'player signed with another game’s secret -> 401', String(pl.status));
pl = await gameGet('/api/partner/player', { game: 'nosuchgame', m: 0, e: C }, C, GK);
ok(pl.status === 400, 'unknown game -> 400', String(pl.status));
pl = await gameGet('/api/partner/player', { game: 'spellwheel', m: 0, e: C }, C, GK);
ok(pl.status === 503, 'a game with no secret configured -> 503', String(pl.status));
let gr = await grant({ memberId: 0, email: C, game: 'gemkingdom', kind: 'daily', pol: 0.1, ref: 'auth-stale' }, GK, String(Date.now() - 20 * 60000));
ok(gr.status === 401 && /stale/.test(gr.j.error), 'polgrant with a 20-minute-old timestamp -> 401 stale', JSON.stringify(gr.j));
gr = await grant({ memberId: 0, email: C, game: 'gemkingdom', kind: 'daily', pol: 0.1, ref: 'auth-bad' }, HUNT);
ok(gr.status === 401, 'polgrant signed with the wrong secret -> 401', String(gr.status));
gr = await grant({ memberId: 0, email: 'nobody-here@example.com', game: 'gemkingdom', kind: 'daily', pol: 0.1, ref: 'x' });
ok(gr.status === 404, 'polgrant for an unknown member -> 404', String(gr.status));
// 5. before capsStartDate: everything allowed, nothing deferred, usage recorded
gr = await grant({ memberId: 0, email: C, game: 'gemkingdom', kind: 'daily', pol: 1.0, ref: 'pre:1', devDay: '2026-10-19' });
ok(gr.status === 200 && gr.j.allowed === 1 && gr.j.deferred === 0 && gr.j.pass === false && gr.j.enforced === false && gr.j.day === '2026-10-19', 'before capsStartDate: daily 1.0 -> allowed 1.0 (over the 0.30 free cap), enforced false', JSON.stringify(gr.j));
gr = await grant({ memberId: 0, email: C, game: 'gemkingdom', kind: 'progress', pol: 5, ref: 'pre:boss', devDay: '2026-10-19' });
ok(gr.j.allowed === 5 && gr.j.deferred === 0, 'before capsStartDate: progress 5 -> allowed 5, nothing deferred', JSON.stringify(gr.j));
let st = (await api('/api/admin/gamepass/stats', null, adminH)).j;
ok(st && st.enabled === true && st.settings.enforced === false, 'admin stats: enabled, caps not enforced', JSON.stringify(st.settings));
// 6. enforced: daily within / over the cap, idempotent ref, progress deferral
// capFreeLifetime is parked high here so the daily/total cap checks below read as they always did; it gets its own block at the end
await api('/api/admin/site', { method: 'PATCH', data: { capsStartDate: '2026-10-20', capFreeLifetime: 1000 } }, adminH);
const D1 = '2026-10-20', D2 = '2026-10-21', D3 = '2026-10-22';
gr = await grant({ memberId: 0, email: C, game: 'gemkingdom', kind: 'daily', pol: 0.2, ref: 'f1', devDay: D1 });
ok(gr.j.allowed === 0.2 && gr.j.deferred === 0 && gr.j.enforced === true && gr.j.capHit === null, 'D1 daily 0.2 -> allowed 0.2', JSON.stringify(gr.j));
gr = await grant({ memberId: 0, email: C, game: 'gemkingdom', kind: 'daily', pol: 0.2, ref: 'f2', devDay: D1 });
ok(gr.j.allowed === 0.1 && gr.j.deferred === 0 && gr.j.capHit === 'daily', 'D1 daily 0.2 -> allowed 0.1 (daily cap 0.30), the rest dropped, capHit daily', JSON.stringify(gr.j));
gr = await grant({ memberId: 0, email: C, game: 'gemkingdom', kind: 'daily', pol: 0.1, ref: 'f3', devDay: D1 });
ok(gr.j.allowed === 0 && gr.j.deferred === 0 && gr.j.capHit === 'daily', 'D1 daily 0.1 at the cap -> allowed 0, nothing deferred', JSON.stringify(gr.j));
gr = await grant({ memberId: 0, email: C, game: 'gemkingdom', kind: 'daily', pol: 0.2, ref: 'f2', devDay: D2 });
ok(gr.j.allowed === 0.1 && gr.j.repeat === true && gr.j.day === D1, 'same ref f2 again (even on another day) -> the same answer, nothing re-applied', JSON.stringify(gr.j));
gr = await grant({ memberId: 0, email: C, game: 'gemkingdom', kind: 'progress', pol: 5, ref: 'boss:1', devDay: D1 });
ok(gr.j.allowed === 1.7 && gr.j.deferred === 3.3 && gr.j.capHit === 'total', 'D1 progress 5 -> allowed 1.7 (total cap 2 minus 0.3 daily), 3.3 deferred', JSON.stringify(gr.j));
gr = await grant({ memberId: 0, email: C, game: 'gemkingdom', kind: 'progress', pol: 0.5, ref: 'stage:2', devDay: D1 });
ok(gr.j.allowed === 0 && gr.j.deferred === 0.5, 'D1 progress 0.5 with the total cap used -> all 0.5 deferred', JSON.stringify(gr.j));
pl = await gameGet('/api/partner/player', { game: 'gemkingdom', m: 0, e: C, devDay: D1 }, C, GK);
ok(pl.j.caps.used.daily === 0.3 && pl.j.caps.used.total === 2 && pl.j.caps.pending === 3.8 && pl.j.caps.enforced === true, 'player caps on D1: used 0.30 / 2.0, 3.8 POL pending for Gem Kingdom', JSON.stringify(pl.j.caps));
// 7. carry-forward on the next day, inside the total cap, before the new grant
gr = await grant({ memberId: 0, email: C, game: 'gemkingdom', kind: 'daily', pol: 0.1, ref: 'f4', devDay: D2 });
ok(gr.j.allowed === 2 && gr.j.carried === 2 && gr.j.deferred === 0 && gr.j.capHit === 'total' && gr.j.day === D2, 'D2 daily 0.1 -> allowed 2.0 (2.0 carried from the boss fills the day), the 0.1 dropped', JSON.stringify(gr.j));
pl = await gameGet('/api/partner/player', { game: 'gemkingdom', m: 0, e: C, devDay: D2 }, C, GK);
ok(pl.j.caps.used.total === 2 && pl.j.caps.used.daily === 0 && pl.j.caps.pending === 1.8, 'D2 caps: total 2.0 used (all carried), 1.8 still pending', JSON.stringify(pl.j.caps));
gr = await grant({ memberId: 0, email: C, game: 'gemkingdom', kind: 'progress', pol: 0.3, ref: 'stage:3', devDay: D3 });
ok(gr.j.allowed === 2 && gr.j.carried === 1.8 && gr.j.deferred === 0.1, 'D3 progress 0.3 -> 1.8 carried + 0.2 own = 2.0 allowed, 0.1 deferred', JSON.stringify(gr.j));
// account-wide: another game on the same day sees the cap used
gr = await grant({ memberId: 0, email: C, game: 'polhunter', kind: 'daily', pol: 0.3, ref: 'find:1', devDay: D3 }, HUNT);
ok(gr.j.allowed === 0 && gr.j.capHit === 'total', 'D3 PolHunter daily 0.3 -> allowed 0: the cap is account-wide across games', JSON.stringify(gr.j));
// 8. void: this ref's own share is reversed, the carry it triggered stays; a replay stays voided
let vd = await gamePost('/api/partner/polgrant/void', { memberId: 0, email: C, game: 'gemkingdom', ref: 'stage:3' }, GK);
ok(vd.status === 200 && vd.j.voided === true && vd.j.reversed.allowed === 0.2 && vd.j.reversed.deferred === 0.1, 'void stage:3 -> reversed 0.2 allowed + 0.1 deferred', JSON.stringify(vd.j));
pl = await gameGet('/api/partner/player', { game: 'gemkingdom', m: 0, e: C, devDay: D3 }, C, GK);
ok(pl.j.caps.used.total === 1.8 && pl.j.caps.pending === 0, 'D3 caps after the void: 1.8 used (the carry stays), nothing pending', JSON.stringify(pl.j.caps));
gr = await grant({ memberId: 0, email: C, game: 'gemkingdom', kind: 'progress', pol: 0.3, ref: 'stage:3', devDay: D3 });
ok(gr.j.allowed === 0 && gr.j.repeat === true && gr.j.voided === true, 'replaying a voided ref -> allowed 0, voided', JSON.stringify(gr.j));
vd = await gamePost('/api/partner/polgrant/void', { memberId: 0, email: C, game: 'gemkingdom', ref: 'never-granted' }, GK);
ok(vd.j.ok === true && vd.j.unknown === true, 'voiding an unknown ref is harmless', JSON.stringify(vd.j));
// the Overview nudge source: the free player's last cap hit
g = (await api('/api/my/gamepass', null, hC)).j;
ok(g.lastCapHit && g.lastCapHit.game === 'polhunter' && g.lastCapHit.kind === 'total' && g.lastCapHit.pass === false, 'member GET carries lastCapHit for the Overview nudge', JSON.stringify(g.lastCapHit));
// 9. a pass holder gets the pass caps; after expiry the free caps are back
gr = await grant({ memberId: 0, email: A, game: 'gemkingdom', kind: 'daily', pol: 1.0, ref: 'a:f1', devDay: D1 });
ok(gr.j.allowed === 1 && gr.j.pass === true && gr.j.capHit === null, 'pass holder: daily 1.0 -> allowed 1.0 (pass daily cap 1.50)', JSON.stringify(gr.j));
gr = await grant({ memberId: 0, email: A, game: 'gemkingdom', kind: 'daily', pol: 1.0, ref: 'a:f2', devDay: D1 });
ok(gr.j.allowed === 0.5 && gr.j.capHit === 'daily', 'pass holder: second daily 1.0 -> allowed 0.5 (1.50 reached)', JSON.stringify(gr.j));
g = (await api('/api/my/gamepass?devDay=2026-12-01', null, hA)).j;
ok(g.active === false && g.caps.daily === 0.3, 'after expiry (faked Dec 1): active false, free caps', JSON.stringify(g.caps));
gr = await grant({ memberId: 0, email: A, game: 'gemkingdom', kind: 'daily', pol: 1.0, ref: 'a:dec', devDay: '2026-12-01' });
ok(gr.j.allowed === 0.3 && gr.j.pass === false, 'after expiry: daily 1.0 -> allowed 0.30, pass false', JSON.stringify(gr.j));
// 10. tournament: the week of Oct 19 (A played, B bought); 5% of $5 = $0.25 at $0.10/POL = 2.5 POL pool, 50% to #1
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.sales === 1 && near(t.j.poolPol, 2.5) && t.j.winners.length === 1 && t.j.winners[0].email === A && near(t.j.winners[0].pol, 1.25) && t.j.winners[0].score === 2, 'tournament week of Oct 19: 1 sale, pool 2.5 POL, A wins #1 with 2 plays -> 1.25 POL pending', JSON.stringify(t.j && { week: t.j.week, sales: t.j.sales, poolPol: t.j.poolPol, winners: t.j.winners.map(w => [w.email, w.score, w.pol, w.status]) }));
t = await api('/api/admin/gamepass/tournament/run', { data: { week: '2026-10-21' } }, adminH);
ok(t.j.winners && t.j.winners.length === 1 && t.j.ranAt, 'running the same week again returns the recorded row (no double prizes)', '');
let pend = await api('/api/partner/tournament/pending', null, adminH);
ok(pend.j.ok && pend.j.pending.length === 1 && pend.j.pending[0].place === 1 && near(pend.j.pending[0].pol, 1.25), 'GET /api/partner/tournament/pending (admin) lists the unpaid prize', JSON.stringify(pend.j.pending));
pend = await gameGet('/api/partner/tournament/pending', { game: 'gemkingdom' }, 'tournament', GK);
ok(pend.status === 200 && pend.j.pending.length === 1 && pend.j.pending[0].email === A && Array.isArray(pend.j.rows) && pend.j.rows.length === 1, 'a game can read the pending prizes with its signature (answer carries `rows`, the field the games\' polgrant.js reads)', '');
let paid = await gamePost('/api/partner/tournament/paid', { game: 'gemkingdom', week: '2026-10-19', place: 1, tx: '0xabc123' }, GK);
ok(paid.j.ok === true, 'a game marks the prize paid', JSON.stringify(paid.j));
pend = await api('/api/partner/tournament/pending', null, adminH);
ok(pend.j.pending.length === 0, 'pending is empty after the payout', '');
const inbox = (await api('/api/my/messages', null, hA)).j;
const stored = (() => { try { return JSON.parse(fs.readFileSync(path.join(DATA, 'sponsor-messages.json'), 'utf8')).items || []; } catch (e) { return []; } })().find(i => /Game Pass Tournament/.test(i.subject || ''));
ok(inbox && JSON.stringify(inbox).includes('Game Pass Tournament') && stored && stored.kind === 'notice', 'the winner got an inbox message of kind notice (never a broadcast pop-up)', stored ? 'kind=' + stored.kind : 'not stored');
// 11. admin stats + comp
st = (await api('/api/admin/gamepass/stats', null, adminH)).j;
ok(st.passes.soldTotal === 3 && st.passes.active >= 2 && st.deferredQueue.entries === 0 && st.tournament.last && st.tournament.last.week === '2026-10-19' && typeof st.capHits.week.free.daily === 'number', 'admin stats: 3 passes sold, active >= 2, tournament recorded', JSON.stringify({ passes: st.passes, q: st.deferredQueue, hits: st.capHits.week }));
r = await api('/api/admin/gamepass/comp', { data: { email: C, why: 'qa' } }, adminH);
g = (await api('/api/my/gamepass', null, hC)).j;
ok(r.j.ok && g.active === true && g.caps.daily === 1.5, 'admin comp gives C a pass week: caps now 1.50 / 5', JSON.stringify(g.caps));
st = (await api('/api/admin/gamepass/stats', null, adminH)).j;
ok(st.passes.soldTotal === 3 && st.passes.usdTotal === 15 && st.passes.comped === 1 && st.passes.active === 3, 'a comp is not a sale (soldTotal 3, $15, comped 1, active 3)', JSON.stringify(st.passes));
// 12. the hand-off token carries the flag
const gkO = { Origin: 'https://gemkingdom.app' }; // the game's own origin, as its sign-in page sends it
const hv = await api('/api/game/auth/start', { data: { email: A, game: 'gemkingdom', fts: Date.now() - 5000 } }, gkO);
const vv = await api('/api/game/auth/verify', { data: { email: A, game: 'gemkingdom', code: hv.j && hv.j.devCode } }, gkO);
if (!(vv.j && vv.j.token)) console.log(' game auth answer:', JSON.stringify(hv.j), JSON.stringify(vv.j));
const tokenClaims = vv.j && vv.j.token ? JSON.parse(Buffer.from(String(vv.j.token).split('.')[0].replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8')) : null;
ok(tokenClaims && tokenClaims.gamePass && tokenClaims.gamePass.active === true && tokenClaims.gamePass.until === until1 + 7 * 86400000, 'in-game sign-in token carries gamePass { active, until }', JSON.stringify(tokenClaims && tokenClaims.gamePass));
// the ledger file on the volume (saves are debounced 500 ms)
// 9. the free allowance (2026-11-02): an account with no pass receives at most capFreeLifetime POL of game rewards, ever
await api('/api/admin/site', { method: 'PATCH', data: { capFreeLifetime: 2 } }, adminH);
const LF = 'qa-gp-lifetime@example.com'; await signIn(LF, 'qagplife');
gr = await grant({ memberId: 0, email: LF, game: 'gemkingdom', kind: 'progress', pol: 1.5, ref: 'lf:boss:1', devDay: D1 });
ok(gr.j.allowed === 1.5 && gr.j.deferred === 0 && gr.j.lifetimeHit === false && gr.j.freeUsed === 1.5, 'allowance: progress 1.5 -> allowed 1.5, 1.5 of 2 used', JSON.stringify(gr.j));
gr = await grant({ memberId: 0, email: LF, game: 'gemkingdom', kind: 'daily', pol: 0.3, ref: 'lf:d1', devDay: D1 });
ok(gr.j.allowed === 0.3 && gr.j.freeUsed === 1.8, 'allowance: daily 0.3 -> allowed 0.3, 1.8 used', JSON.stringify(gr.j));
gr = await grant({ memberId: 0, email: LF, game: 'gemkingdom', kind: 'progress', pol: 1, ref: 'lf:boss:2', devDay: D1 });
ok(gr.j.allowed === 0.2 && gr.j.deferred === 0.8 && gr.j.lifetimeHit === true && gr.j.freeUsed === 2, 'allowance: progress 1 -> 0.2 allowed, 0.8 deferred, the allowance is used up', JSON.stringify(gr.j));
pl = await gameGet('/api/partner/player', { game: 'gemkingdom', m: 0, e: LF, devDay: D1 }, LF, GK);
ok(pl.j.caps.lifetime && pl.j.caps.lifetime.cap === 2 && pl.j.caps.lifetime.used === 2 && pl.j.caps.pending === 0.8, 'player caps carry the allowance: 2 of 2 used, 0.8 pending', JSON.stringify(pl.j.caps));
gr = await grant({ memberId: 0, email: LF, game: 'gemkingdom', kind: 'daily', pol: 0.2, ref: 'lf:d2', devDay: D2 });
ok(gr.j.allowed === 0 && gr.j.deferred === 0 && gr.j.lifetimeHit === true, 'allowance used: next day daily 0.2 -> nothing, dropped', JSON.stringify(gr.j));
gr = await grant({ memberId: 0, email: LF, game: 'gemkingdom', kind: 'progress', pol: 0.1, ref: 'lf:stage:9', devDay: D2 });
ok(gr.j.allowed === 0 && gr.j.deferred === 0.1 && gr.j.carried === 0, 'allowance used: next day progress 0.1 -> deferred, no carry paid either', JSON.stringify(gr.j));
await api('/api/admin/site', { method: 'PATCH', data: { capFreeLifetime: 1000 } }, adminH);
await sleep(1200);
ok(fs.existsSync(path.join(DATA, 'gamepass-ledger.json')), 'cap ledger persisted to DATA_DIR/gamepass-ledger.json', fs.readdirSync(DATA).join(','));
const ot = JSON.parse(fs.readFileSync(path.join(DATA, 'open-tokens.json'), 'utf8'));
ok(ot.gamepass && ot.gamepass[A] && ot.gporders && ot.gpprizes && ot.gpprizes['2026-10-19'], 'pass store, orders and prizes persisted in the durable open-tokens store', Object.keys(ot).join(','));
} catch (e) {
console.error('FAIL harness error', e && e.stack || e); fails++;
} finally {
cleanup();
}
if (fails && /gamepass/i.test(srvLog)) 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);