// polgrant.js: the Game Pass bridge to InstantAdPay (GAME-PASS.md section 3a + its "Built" clarifications). The SAME file lives // in every network game; change it in one place and copy it to the others. // // IAP is the single source of truth for the pass and for the account-wide daily caps. Before any POL grant to a signed-in // player the game asks `grant({ memberId, email, kind, pol, ref })` and pays only what comes back as `allowed`. // - kind 'daily' = a repeatable reward (a find, a patrol, a gem): what the cap does not allow is DROPPED, never deferred // - kind 'progress' = a one-time reward (a boss, a sector, a chapter): what the cap does not allow is DEFERRED on IAP and // paid on a later day inside `allowed` (the answer says `carried`), so nothing is ever lost // - the same ref twice gets the same answer (IAP is idempotent on ref, `repeat: true`), so a retry can never double-pay // - FAIL CLOSED: when IAP cannot be reached (network, 5xx, bad JSON, bad auth) the answer is { allowed: 0, retry: true } // and the game queues the ref: retried every 5 minutes for up to 48 hours, then the admin chat is told once // - a player who has not linked a wallet has memberId 0 in every hand-off token: send the email too, IAP resolves the account // (the pass and the caps are per ACCOUNT); `who` below is the member id when > 0, else the lowercased email // // Feature switch: GAMEPASS=on|off (default off: every game keeps its current behaviour, so deploying before launch is safe). // Env: IAP_URL (default https://instantadpay.com). Auth = the game's own shared sign-in secret (its *_SSO_SECRET): // POST: JSON body with `game: `, headers X-Game-Ts (ms) and X-Game-Sig = hex HMAC-SHA256(secret, ts + "\n" + rawBody) // GET /api/partner/player?game=&m=&e=&ts=&sig= with sig = hex HMAC-SHA256(secret, 'player:' + who + ':' + ts) // GET /api/partner/tournament/pending?game=&ts=&sig= with who = 'tournament' // The hand-off token carries the flag as claims.gamePass = { active, until }; grant and player answers refresh it. 'use strict'; const crypto = require('crypto'); const PASS_URL = 'https://instantadpay.com/my#games?pass=1'; const RETRY_MS = 5 * 60000, GIVE_UP_MS = 48 * 3600000, PASS_TTL = 10 * 60000; let cfg = { game: '', secret: '', iap: 'https://instantadpay.com', store: null, notify: null, fetch: null, log: console, queueKey: 'polgrantq', passKey: 'gamepass' }; // use({ game, secret, iap, store: { read, write, update }, notify(kind, payload), fetch? }) function use(o) { cfg = Object.assign(cfg, o || {}); cfg.iap = String(cfg.iap || process.env.IAP_URL || 'https://instantadpay.com').replace(/\/+$/, ''); return cfg; } const on = () => String(process.env.GAMEPASS || 'off').trim().toLowerCase() === 'on'; const ctDay = t => new Date(t || Date.now()).toLocaleDateString('en-CA', { timeZone: 'America/Chicago' }); const r4 = n => Math.round(Number(n) * 10000) / 10000; const doFetch = (u, o) => (cfg.fetch || globalThis.fetch)(u, o); const ready = () => !!(cfg.store && cfg.secret && String(cfg.secret).length >= 32); // the account key IAP and this module agree on: the member id when linked, else the email ('' = nobody signed in) const whoOf = (memberId, email) => Number(memberId) > 0 ? String(Number(memberId)) : String(email || '').trim().toLowerCase(); const hmac = s => crypto.createHmac('sha256', String(cfg.secret)).update(s).digest('hex'); async function post(path, body) { const raw = JSON.stringify(Object.assign({ game: cfg.game }, body)), ts = String(Date.now()); const r = await doFetch(cfg.iap + path, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Game': cfg.game, 'X-Game-Ts': ts, 'X-Game-Sig': hmac(ts + '\n' + raw) }, body: raw, signal: AbortSignal.timeout(6000) }); const text = await r.text(); let json = null; try { json = JSON.parse(text); } catch (e) {} return { status: r.status, json }; } async function get(path, who, params) { const ts = String(Date.now()); const q = new URLSearchParams(Object.assign({ game: cfg.game }, params || {}, { ts, sig: hmac('player:' + who + ':' + ts) })); const r = await doFetch(cfg.iap + path + '?' + q.toString(), { signal: AbortSignal.timeout(6000) }); const text = await r.text(); let json = null; try { json = JSON.parse(text); } catch (e) {} return { status: r.status, json }; } // the one call that matters -> { allowed, deferred, carried, pass, day, capHit, enforced, repeat, lifetimeHit, freeLifetime, waiting, retry: false } // or { allowed: 0, retry: true, error }. Never throws. async function grant({ memberId, email, game, kind, pol, ref }) { const body = { memberId: Number(memberId) || 0, email: String(email || '').trim().toLowerCase() || undefined, game: game || cfg.game, kind: kind === 'daily' ? 'daily' : 'progress', pol: r4(Math.max(0, Number(pol) || 0)), ref: String(ref || '') }; if (!whoOf(body.memberId, body.email) || !body.ref) return { allowed: 0, deferred: 0, carried: 0, pass: false, retry: false, error: 'bad request' }; if (!ready()) return { allowed: 0, deferred: 0, carried: 0, pass: false, retry: true, error: 'polgrant not configured' }; try { const { status, json } = await post('/api/partner/polgrant', body); if (status !== 200 || !json || typeof json.allowed !== 'number') return { allowed: 0, deferred: 0, carried: 0, pass: false, retry: true, error: 'http ' + status + (json && json.error ? ': ' + json.error : '') }; const out = { allowed: r4(Math.max(0, json.allowed)), deferred: r4(Math.max(0, Number(json.deferred) || 0)), carried: r4(Math.max(0, Number(json.carried) || 0)), pass: !!(json.pass && (json.pass === true || json.pass.active)), day: json.day || ctDay(), capHit: json.capHit || null, enforced: json.enforced !== false, repeat: !!json.repeat, suspended: !!json.suspended, lifetimeHit: !!json.lifetimeHit, freeLifetime: Number(json.freeLifetime) || 0, waiting: r4(Math.max(0, Number(json.waiting) || 0)), retry: false }; rememberPass(body.memberId, body.email, json.pass, json.passUntil || (json.pass && json.pass.until)); return out; } catch (e) { return { allowed: 0, deferred: 0, carried: 0, pass: false, retry: true, error: String(e && e.message || e).slice(0, 120) }; } } // the game decided not to pay after all (rare): tell IAP so that ref's own share comes back. Best effort. async function voidGrant({ memberId, email, game, ref }) { if (!ready() || !whoOf(memberId, email) || !ref) return { ok: false }; try { const { status } = await post('/api/partner/polgrant/void', { memberId: Number(memberId) || 0, email: String(email || '').toLowerCase() || undefined, game: game || cfg.game, ref: String(ref) }); return { ok: status === 200 }; } catch (e) { return { ok: false, error: String(e && e.message || e) }; } } // ---- the pass flag: from the sign-in hand-off (claims.gamePass), every grant answer, or a signed GET to IAP ---------------- function passOf(memberId, email) { const who = whoOf(memberId, email), all = cfg.store && who ? cfg.store.read(cfg.passKey, {}) : {}, p = all[who] || null; if (!p) return { active: false, until: null, at: 0 }; const active = !!p.active && (!p.until || p.until > Date.now()); return { active, until: p.until || null, at: p.at || 0 }; } // pass = true/false or { active, until }; until = ms when known function rememberPass(memberId, email, pass, until) { const who = whoOf(memberId, email); if (!cfg.store || !who || pass == null) return; const active = pass === true || !!(pass && pass.active); const u = Number(until || (pass && pass.until)) || null; cfg.store.update(cfg.passKey, {}, all => { const cur = all[who] || {}; all[who] = { active, until: active ? (u || cur.until || null) : null, at: Date.now() }; return all; }); } // refresh from IAP when the cached answer is stale; fail-soft (display only, the grant answers are the truth for money) async function fetchPass(memberId, email) { const who = whoOf(memberId, email), cur = passOf(memberId, email); if (!ready() || !who) return cur; if (Date.now() - cur.at < PASS_TTL) return cur; try { const { status, json } = await get('/api/partner/player', who, { m: Number(memberId) || 0, e: String(email || '').toLowerCase() }); if (status !== 200 || !json) throw new Error('http ' + status); if (json.pass != null) rememberPass(memberId, email, json.pass, json.pass && json.pass.until); return passOf(memberId, email); } catch (e) { return cur; } } // what the lobby shows: { on, active, until, untilText, url } function view(memberId, email) { const p = whoOf(memberId, email) ? passOf(memberId, email) : { active: false, until: null }; return { on: on(), active: p.active, until: p.until, untilText: p.until ? new Date(p.until).toLocaleDateString('en-US', { timeZone: 'America/Chicago', month: 'short', day: 'numeric' }) : null, url: PASS_URL }; } // ---- the player-facing truth for a grant answer ------------------------------------------------------------------------ function note(resp, kind, nominal) { nominal = r4(nominal); if (!resp) return null; if (resp.retry) return 'Your reward is recorded and pays as soon as InstantAdPay confirms it.'; // the free allowance is used up (Marty 2026-11-03): only the Game Pass pays from here, so say so, and what is waiting for them if (resp.lifetimeHit && !resp.pass) { const cap = resp.freeLifetime ? r4(resp.freeLifetime) + ' POL' : 'POL'; const wait = kind === 'progress' && resp.waiting > 0 ? ' Your ' + r4(resp.waiting) + ' POL earned since is saved and pays out with the Pass.' : ''; return 'You have used your free ' + cap + ' in the games. Get the Game Pass to keep earning.' + wait; } if (kind === 'progress' && resp.deferred > 0) return resp.deferred + ' POL is yours; it pays out over the next days (daily cap).'; if (kind === 'daily' && resp.allowed + 1e-9 < nominal) return resp.pass ? 'Daily cap reached for today.' : 'Daily cap reached for today. Get the Pass for a higher cap.'; return null; } // ---- the retry queue (fail closed, never lost): persisted, every 5 minutes, 48 hours, then the admin chat ---------------- function enqueue(item) { if (!cfg.store) return null; const row = Object.assign({}, item, { memberId: Number(item.memberId) || 0, email: String(item.email || '').toLowerCase(), ref: String(item.ref), at: item.at || Date.now(), tries: 0, nextAt: Date.now() + RETRY_MS, stuck: false }); row.who = whoOf(row.memberId, row.email); cfg.store.update(cfg.queueKey, [], q => { if (!q.some(x => (x.who || whoOf(x.memberId, x.email)) === row.who && x.ref === row.ref)) q.push(row); return q; }); return row; } const queue = () => cfg.store ? cfg.store.read(cfg.queueKey, []) : []; const same = (x, memberId, email, ref) => (x.who || whoOf(x.memberId, x.email)) === whoOf(memberId, email) && x.ref === String(ref); const queued = (memberId, email, ref) => queue().some(x => same(x, memberId, email, ref)); // waiting on IAP: do not ask again const dequeue = (memberId, email, ref) => cfg.store && cfg.store.update(cfg.queueKey, [], q => q.filter(x => !same(x, memberId, email, ref))); // pay(item, resp) settles the answer in the game's own ledger. Returns { tried, paid, stuck }. async function retry(pay, now) { now = now || Date.now(); const out = { tried: 0, paid: 0, stuck: 0 }; if (!cfg.store || !on()) return out; for (const item of queue()) { if (item.stuck || item.nextAt > now) continue; out.tried++; const r = await grant({ memberId: item.memberId, email: item.email, kind: item.kind, pol: item.pol, ref: item.ref }); if (r.retry) { const stuck = now - item.at >= GIVE_UP_MS; cfg.store.update(cfg.queueKey, [], q => { const x = q.find(y => same(y, item.memberId, item.email, item.ref)); if (x) { x.tries = (x.tries || 0) + 1; x.nextAt = now + RETRY_MS; x.lastError = r.error || null; if (stuck) x.stuck = true; } return q; }); if (stuck) { out.stuck++; if (cfg.notify) { try { await cfg.notify('gpstuck', { memberId: item.memberId, email: item.email, ref: item.ref, pol: item.pol, kind: item.kind, since: item.at, error: r.error || null }); } catch (e) {} } } continue; } dequeue(item.memberId, item.email, item.ref); try { await pay(item, r); out.paid++; } catch (e) { if (cfg.log) cfg.log.error('polgrant pay', item.ref, e && e.message); } } return out; } let timer = null; function startRetry(pay, everyMs) { if (timer) return timer; timer = setInterval(() => { retry(pay).catch(e => cfg.log && cfg.log.error('polgrant retry', e && e.message)); }, everyMs || RETRY_MS); if (timer.unref) timer.unref(); return timer; } function stopRetry() { if (timer) clearInterval(timer); timer = null; } // ---- the weekly Pass Tournament prize seam (3a item 8): IAP records the winners, a game's faucet pays them ------------------ // -> { ok, rows: [{ id?, week, place, email, memberId, wallet, pol }] } or { ok: false, retry: true, error } async function tournamentPending() { if (!ready()) return { ok: false, retry: true, error: 'polgrant not configured', rows: [] }; try { const { status, json } = await get('/api/partner/tournament/pending', 'tournament', {}); if (status !== 200 || !json) return { ok: false, retry: true, error: 'http ' + status, rows: [] }; return { ok: true, rows: Array.isArray(json.rows) ? json.rows : Array.isArray(json) ? json : [] }; } catch (e) { return { ok: false, retry: true, error: String(e && e.message || e).slice(0, 120), rows: [] }; } } // the row leaves IAP's unpaid list once the game reports the tx (sends id when the row has one, and week + place always) async function tournamentPaid(row, tx) { if (!ready()) return { ok: false, error: 'polgrant not configured' }; try { const { status, json } = await post('/api/partner/tournament/paid', { id: row.id, week: row.week, place: row.place, memberId: row.memberId, email: row.email, tx }); return { ok: status === 200 && !(json && json.error), status, error: json && json.error }; } catch (e) { return { ok: false, error: String(e && e.message || e).slice(0, 120) }; } } module.exports = { use, on, whoOf, grant, voidGrant, passOf, rememberPass, fetchPass, view, note, enqueue, queue, queued, dequeue, retry, startRetry, stopRetry, tournamentPending, tournamentPaid, PASS_URL, RETRY_MS, GIVE_UP_MS, ctDay, r4, _cfg: () => cfg };