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>
This commit is contained in:
martbost
2026-10-16 09:27:46 -05:00
parent 4d6a0f2f83
commit 084d1ea3d6
5 changed files with 272 additions and 6 deletions
+78 -4
View File
@@ -90,9 +90,10 @@ that anyway." The paced total cap spreads a big boss payout over a few days; the
> 7. **Hand-off tokens carry the flag** as `gamePass: { active, until }` (not `pass`, which the in-game sign-in flow already uses for > 7. **Hand-off tokens carry the flag** as `gamePass: { active, until }` (not `pass`, which the in-game sign-in flow already uses for
> its session token). Apply perks from it at sign-in; refresh from `player`/`polgrant` answers. > its session token). Apply perks from it at sign-in; refresh from `player`/`polgrant` answers.
> 8. **Tournament prize payout seam.** IAP records the winners and POL amounts; a game faucet (Road Agent pattern) pays them: > 8. **Tournament prize payout seam.** IAP records the winners and POL amounts; a game faucet (Road Agent pattern) pays them:
> `GET /api/partner/tournament/pending` lists `{ week, place, email, memberId, wallet, pol }` rows still unpaid, and the paying > `GET /api/partner/tournament/pending` answers `{ ok, rows: [{ week, place, email, memberId, wallet, pol, ... }] }` (the same
> game calls `POST /api/partner/tournament/paid { game, week, place, tx }` so the row leaves the list. Which faucet pays is a > list is also under `pending`, the admin pane's name) for the rows still unpaid, and the paying game calls
> settings/ops decision, not yet wired: until it is, Admin > Game Pass shows the unpaid rows. > `POST /api/partner/tournament/paid { game, week, place, tx }` so the row leaves the list. PolHunter's faucet pays them
> (`polhunter/lib/tournament.js`, see "Games: as built"); Admin > Game Pass shows the unpaid rows meanwhile.
> 9. **Not deviations, just dev conveniences (non-production only):** `devDay: 'YYYY-MM-DD'` on `polgrant`/`player`/`buy` fakes the > 9. **Not deviations, just dev conveniences (non-production only):** `devDay: 'YYYY-MM-DD'` on `polgrant`/`player`/`buy` fakes the
> Central day; `POST /api/dev/gamepass-purchase` fakes a package event; `devPaid: true` on `buy` skips the credit charge. > Central day; `POST /api/dev/gamepass-purchase` fakes a package event; `devPaid: true` on `buy` skips the credit charge.
@@ -209,6 +210,79 @@ sales. If the POL rate is unavailable the tick retries next hour.
- `qa/gamepass.mjs` stubs the credit charge (`devPaid`) for the "buy -> active" step: `ads.gamePurchase(purchasedOnly)` needs a - `qa/gamepass.mjs` stubs the credit charge (`devPaid`) for the "buy -> active" step: `ads.gamePurchase(purchasedOnly)` needs a
position with on-chain package credits, which a local copy without RPC cannot have. The "short -> waiting order -> package fulfils position with on-chain package credits, which a local copy without RPC cannot have. The "short -> waiting order -> package fulfils
it" step runs the real path. The purchasedOnly charge itself is the live PolyWarriors mint path. it" step runs the real path. The purchasedOnly charge itself is the live PolyWarriors mint path.
- Prize POL is not sent by IAP (see 3a item 8); the Games pane lists unpaid rows until a faucet is wired. - Prize POL is not sent by IAP (see 3a item 8): PolHunter's faucet pays the pending rows every 10 minutes behind `GAMEPASS=on`;
the Games pane lists whatever is still unpaid.
- Settings pass through `/api/admin/site` like every other site setting (that endpoint accepts any key; the defaults above make the - Settings pass through `/api/admin/site` like every other site setting (that endpoint accepts any key; the defaults above make the
Game Pass keys show in the Site settings form). Game Pass keys show in the Site settings form).
## Games: as built (2026-10-16, local commits only, nothing deployed)
Everything is behind `GAMEPASS=on` (env, default off = today's behaviour, so the games can be deployed before launch). `IAP_URL` is
read where it already existed (default `https://instantadpay.com`). No reward amount changed anywhere; every game's local
`dailyCapPol` / pool / hidden ceiling still stands in FRONT of the IAP call as a backstop and none was raised.
**The shared client `polgrant.js`** (byte-identical copy in every repo, md5 `f3c00b90…116a`; change one, copy to the rest):
`spooky-doors/server/`, `road-agent/server/`, `match3-game/server/`, `seek-game/`, `spellwheel/`, `polybreak/`, `cyber-battle/game/`,
`polhunter/lib/`, `drip-runner/lib/`.
- `grant({ memberId, email, kind, pol, ref })` -> `POST /api/partner/polgrant` `{ game, memberId, email, kind, pol, ref }`, headers
`X-Game-Ts` + `X-Game-Sig` (plus an informational `X-Game`), 6 s timeout. Returns `{ allowed, deferred, carried, pass, day, capHit,
enforced, repeat, suspended, retry: false }` or `{ allowed: 0, retry: true, error }` on ANY non-200 / non-JSON / network error
(fail closed; a 404 "no such member" is also a retry, so the games only call it for signed-in IAP members).
- `email` always rides along (wallet-less members have `memberId: 0`; Drip Runner maps its negative `emailId` to 0). `whoOf()` = the
member id when > 0, else the lowercased email; the pass cache and the retry queue key on it.
- `voidGrant`, `fetchPass` (`GET /api/partner/player`, cached 10 min, fail-soft), `passOf` / `rememberPass` (hand-off claim
`gamePass: { active, until }` + every answer), `view()` for the lobby, `note(resp, kind, nominal)` = the player-facing line.
- Retry queue `polgrantq` in each game's store: `enqueue` dedupes per (who, ref); `retry(pay)` every 5 min, 48 h then `stuck` +
`notify('gpstuck')` once (each game routes it to its faucet alert path); `queued()` keeps a waiting ref from being re-asked.
- Carry-forward collection (SD-pattern games): `carrySweep()` on the existing tick, once a Central day per account with `gpOwed > 0`,
a zero-POL `progress` call with ref `carry:<YYYY-MM-DD>`; IAP folds the carry into `allowed` (`carried`). `gpOwed` is bookkeeping
(`+= deferred`, `-= carried`); the money truth is IAP's. **IAP accepts `pol: 0`** (verified by the integration test below).
- `tournamentPending()` reads `rows` from `GET /api/partner/tournament/pending`; `tournamentPaid(row, tx)` posts
`{ game, id?, week, place, memberId, email, tx }` (PolHunter only).
**Per game**
| Game | Files | Refs (kind) | Pass perk | Tests |
|---|---|---|---|---|
| Spooky Doors (`spooky-doors`) | server/pol.js (quote/settleGrant/grantGated/payQueued/carrySweep), server/game.js, server/server.js, server/social.js, src/main.js, test/gamepass.mjs | `rung:<n>` (progress) | +1 door/day while the season runs | sim 63/63, gamepass 37/37, e2e 200 pass / 3 pre-existing timing fails |
| Road Agent (`road-agent`) | server/pol.js, server/game.js, server/server.js, server/social.js, src/main.js, test/gamepass.mjs | `sector:<n>` (progress); `patrol:<day>`, `patrol:<day>:2` (daily) | 2 patrols/day, +25% scrap | sim pass, gamepass 22/22, e2e pass |
| Gem Kingdom (`match3-game`) | server/pol.js, server/server.js (`/api/continue/free`), src/world.js, src/battle.js, src/game.js, test/gamepass.cjs | `stage:<n>` (progress, bosses included) | one free continue/day, no sponsor visit | kingdom.test pass, gamepass 26/26, vite build ok |
| ClutterHunt (`seek-game`) | pol.js, server.js, public/game.js, public/index.html (`game.js?v=20261016gp`), test/gamepass.js | `<season>:<room>:<clear or stars or xclear or xstars>` (progress) | 2 bonus hints banked once per Central day | gamepass 23/23 |
| SpellWheel (`spellwheel`) | pol.js (`streakPassPol: 0.30`), server.js, public/play.js, public/play.html (`play.js?v=7`), test/gamepass.js | `level:<ch>:<n>`, `chapter:<ch>` (progress); `daily:<day>`, `streak:<day>` (daily) | streak 0.15 -> 0.30, 1 free hint/day | gamepass 25/25 |
| PolyBreak (`polybreak`) | pol.js (`gemDailyPassPol: 1.5`), server.js, public/play.js, public/play.html (`play.js?v=6`), test/gamepass.js | `round:<n>` (progress); `gem:<run>:<id>` (daily) | gem ceiling 0.5 -> 1.5/day; +1 paddle per round | gamepass 27/27, run.js 70/70 |
| PolyWarriors (`cyber-battle/game`) | pol.js, server.js (DEF_PAY_PASS 25), missions.js (3 + pass), public/game.js, public/game.html (`game.js?v=30`), test/gamepass.js | `rival:<id>`, `ladder`, `elite` (progress) | +1 daily mission (4), held defense 15 -> 25 Circuits, Pass row on the profile (card.js untouched) | gamepass 26/26 |
| Drip Runner (`drip-runner`) | lib/ledger.js (chapterDripGated), lib/game.js, server.js, public/play.js, public/play.html (`play.js?v=20261016gp`), test/gamepass.js | `chapter:<n>` (progress; the only POL it pays) | a shield at every run start | gamepass 28/28, run.js pass |
| PolHunter (`polhunter`) | lib/rewards.js (status `capped` / `gp-wait`), lib/detective.js, lib/faucet.js (`HUNT_DRY_RUN`), lib/tournament.js (new), server.js, public/app.js, public/app.html (`app.js?v=22`), test/gamepass.js | `find:<missionId>:<day>`, `detective:<boxId>` (daily) | 5 missions/day (+2), 2 Ad Detective cases/day | gamepass 42/42, run.js pass |
Game commits (local, not pushed): spooky-doors f54ef0c, road-agent d345bbf, match3-game 972dd71, seek-game 9751329, spellwheel b582b72,
polybreak e9c3a54, cyber-battle/game fa76d30, drip-runner a7b1fd9, polhunter 7391fd7 + 08486e1. Spooky Doors, Road Agent and Gem
Kingdom are Vite builds (hashed assets, no `?v=` bump).
**Decisions taken on the games side (flip if wanted)**
1. Advertiser-funded PolHunter missions (`mission.paid`) are NOT gated: the advertiser paid for that completion. Gate them in
polhunter/server.js (`gp.on() && !m.paid`) if the cap should cover them too.
2. A 0-allowed daily reward is still "done": a capped find counts as today's find (status `capped`, never reaches the faucet); a capped
gem/patrol/daily puzzle is recorded as handled with `pol: 0`. The player sees the cap line with the Pass link.
3. Fail closed, visibly: IAP unreachable = the reward is recorded (SD pattern: nothing written until IAP answers, ref queued; PolHunter:
a `gp-wait` row settled by the queue), the player sees "Your reward is recorded and pays as soon as InstantAdPay confirms it."
4. Perks read the cached flag (hand-off claim -> every grant answer -> `fetchPass` every 10 min); a pass bought mid-session shows
within 10 minutes or on the next grant.
5. Deferred progress rewards: the ledger row is written with `pol: allowed` (0 included) so the achievement is marked done; carry comes
back through `carry:<day>` or any later grant.
6. Not built: a per-game admin view of the queue (PolHunter's admin state shows queue + stuck counts and the tournament payer).
**Pass Tournament payer (PolHunter `lib/tournament.js`)**: every 10 min behind `GAMEPASS=on`, only with the faucet wallet configured.
Per pending row: a durable claim in `tourney-claims` BEFORE sending (`id:<id>` or `wk:<week>:<place>`), the tx hash written the
moment the chain has it, then `POST /api/partner/tournament/paid`. A claimed row with a hash is only re-reported, never re-sent; a
claim without a hash is retried after 10 min; a send failure releases the claim, leaves the row pending on IAP and alerts
(`tourneyfail`); low balance alerts once a day. `HUNT_DRY_RUN=on` records `wouldPay` and sends nothing. **Trap:** a claim written
during a dry run is permanent (`c.dry` rows are skipped forever), so a prize row seen while `HUNT_DRY_RUN=on` is never paid after the
flag is turned off unless `tourney-claims.json` on the PolHunter volume is cleared. Prizes bypass the per-find daily cap and the
payout threshold. Admin: `/api/admin/state` -> `tournament` and `gamepass` blocks.
**Integration test (both sides, local)**: `bash qa/run.sh gamepass-games` (qa/gamepass-games.cjs) boots IAP like qa/gamepass.mjs and
drives the REAL `spooky-doors/server/polgrant.js` and `polhunter/lib/tournament.js` against it (needs the sibling game repos under
`../..`): fetchPass free/pass, daily within/over cap, progress deferral, the `carry:<day>` zero-POL call on the next Central day
(`carried` > 0, idempotent repeat), void, bad secret and IAP-down -> `{ allowed: 0, retry: true }`, the retry queue, and the
tournament payer in dry run and live (mocked faucet.send) until IAP's pending list is empty. 2026-10-16: 44/44 after the `rows`
fix on the pending endpoint (the games read `rows`; IAP answered only `pending`).
+188
View File
@@ -0,0 +1,188 @@
// 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);
})();
+1 -1
View File
@@ -174,7 +174,7 @@ try {
let pend = await api('/api/partner/tournament/pending', null, adminH); 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)); 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); 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', ''); 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); 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)); ok(paid.j.ok === true, 'a game marks the prize paid', JSON.stringify(paid.j));
pend = await api('/api/partner/tournament/pending', null, adminH); pend = await api('/api/partner/tournament/pending', null, adminH);
+3
View File
@@ -6,6 +6,7 @@
# bash qa/run.sh all # public + member + earn # bash qa/run.sh all # public + member + earn
# bash qa/run.sh door # Spooky Doors door + costume shop flows on their own local copy (qa/door.mjs boots it) # bash qa/run.sh door # Spooky Doors door + costume shop flows on their own local copy (qa/door.mjs boots it)
# bash qa/run.sh gamepass # Game Pass buy flow + account-wide POL caps (polgrant) on their own local copy (qa/gamepass.mjs boots it) # bash qa/run.sh gamepass # Game Pass buy flow + account-wide POL caps (polgrant) on their own local copy (qa/gamepass.mjs boots it)
# bash qa/run.sh gamepass-games # the REAL games' polgrant.js + PolHunter's tournament payer against a local copy (needs the sibling game repos)
# Each local run boots server.js on its own port with a throwaway data dir (JSON store, no DB, no # Each local run boots server.js on its own port with a throwaway data dir (JSON store, no DB, no
# mail key, devCode sign-in), so nothing touches production data. Reports land in qa/out/. # mail key, devCode sign-in), so nothing touches production data. Reports land in qa/out/.
set -u set -u
@@ -36,6 +37,8 @@ elif [ "$MODE" = "door" ]; then
node qa/door.mjs || status=1 node qa/door.mjs || status=1
elif [ "$MODE" = "gamepass" ]; then elif [ "$MODE" = "gamepass" ]; then
node qa/gamepass.mjs || status=1 node qa/gamepass.mjs || status=1
elif [ "$MODE" = "gamepass-games" ]; then
node qa/gamepass-games.cjs || status=1
elif [ "$MODE" = "earn" ]; then elif [ "$MODE" = "earn" ]; then
start_local 8797 && { LOCAL=http://127.0.0.1:8797 node qa/earn.mjs || status=1; }; stop_local 8797 start_local 8797 && { LOCAL=http://127.0.0.1:8797 node qa/earn.mjs || status=1; }; stop_local 8797
else else
+2 -1
View File
@@ -3629,7 +3629,8 @@ const server = http.createServer(async (req, res) => {
if (!/^\d{13}$/.test(ts) || Math.abs(Date.now() - Number(ts)) > 600000) return json(res, 401, { error: 'stale' }); if (!/^\d{13}$/.test(ts) || Math.abs(Date.now() - Number(ts)) > 600000) return json(res, 401, { error: 'stale' });
if (!gpSigOk(crypto.createHmac('sha256', chk.secret).update('player:tournament:' + ts).digest('hex'), sig)) return json(res, 401, { error: 'bad signature' }); if (!gpSigOk(crypto.createHmac('sha256', chk.secret).update('player:tournament:' + ts).digest('hex'), sig)) return json(res, 401, { error: 'bad signature' });
} }
return json(res, 200, { ok: true, pending: gamepass.pending() }); const rows = gamepass.pending();
return json(res, 200, { ok: true, rows, pending: rows }); // `rows` is what the games' polgrant.js tournamentPending() reads; `pending` is the admin pane's name
} }
if (p === '/api/my/gamepass' && req.method === 'GET') { if (p === '/api/my/gamepass' && req.method === 'GET') {
const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); const s = await auth.fromRequest(req); if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });