Files
instantadpay/qa/gamepass.mjs
T
martbost 4d6a0f2f83 Game Pass (IAP side): $5 weekly pass across all nine games + account-wide POL cap service
- gamepass.js: durable pass store, waiting orders fulfilled by the next $5 package, cap ledger
  (daily/total per Central day, progress deferral + next-day carry-forward, idempotent refs kept 90 days,
  void), weekly Pass Tournament (Monday 9 AM Central, marks.claim, prizes recorded for the game faucets),
  admin stats. Settings in site config, caps enforced only from capsStartDate (recorded before).
- server.js: /api/partner/player, /api/partner/polgrant(+/void), /api/partner/tournament/pending|paid,
  /api/my/gamepass(+/buy), /api/admin/gamepass/stats|comp|tournament/run; gamePass claim on every
  sign-in hand-off token; purchase-event fulfilment inside the marks.claim block.
- Members > Games: Game Pass card (Buy via IAP.confirmBox, deep link /my#games?pass=1), Overview nudge
  after a free-cap hit. Admin > Game Pass pane. Chatbot canned answer + FACTS, KNOWLEDGE_DATE 10-16.
- qa/gamepass.mjs scripted test (bash qa/run.sh gamepass), Games tab card in qa/walk.mjs.
- docs/GAME-PASS.md: 3a clarifications + Built section; docs/GAME-PASS-RELEASE.md draft (not sent).

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

216 lines
22 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 without purchased credits -> waiting order; a $5 package fulfils it
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, 'buy with no purchased credits -> needPay + payUrl + waiting order', JSON.stringify(r.j && { needPay: r.j.needPay, payUrl: r.j.payUrl, need: r.j.need }));
const order1 = r.j && r.j.order;
r = await api('/api/my/gamepass/buy', { data: {} }, hA);
ok(r.j && r.j.order === order1, 'a second buy attempt reuses the same waiting order', 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 } });
ok(r.j && r.j.order && r.j.order.order === order1, 'a $5 package purchase event 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 && near(g.until, Date.now() + 7 * 86400000, 60000) && g.bought === 1, 'pass active for 7 days, 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 -> extends from the current until (charge stubbed: devPaid, local only)
r = await api('/api/my/gamepass/buy', { data: { devPaid: true } }, hA);
ok(r.status === 200 && r.j.ok && near(r.j.until, until1 + 7 * 86400000, 1000) && r.j.paid === 'credits', 'buy while active extends by 7 days from the current until', new Date(r.j.until).toISOString());
r = await api('/api/my/gamepass/buy', { data: { devPaid: true, devDay: '2026-10-20' } }, hB);
ok(r.status === 200 && r.j.ok && r.j.active === true, 'member B: buy -> active (sale stamped in the week of Oct 19 for the tournament)', '');
// 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
await api('/api/admin/site', { method: 'PATCH', data: { capsStartDate: '2026-10-20' } }, 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, 'a game can read the pending prizes with its signature', '');
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)
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);